diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d5451bdb..4f75f444c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,7 +64,7 @@ jobs: DISPLAY: ${{ runner.os == 'Linux' && ':99.0' || '' }} QT_QPA_PLATFORM: offscreen - - name: Validate graphics diagnostic with real OpenGL (Linux) + - name: Validate graphics diagnostic and native shortcuts with real OpenGL (Linux) if: runner.os == 'Linux' run: | # Keep native child-window geometry stable. The tiling manager on :99 @@ -77,6 +77,9 @@ jobs: ldd "$qt_plugin_path" uv run --no-sync pytest -o addopts= scripts/tests/test_diagnose_graphics.py \ -k 'real_gl_controlled_faults or scene_ or xcb_glx_requires_matching' + uv run --no-sync pytest -o addopts= \ + phy/apps/large_recording/tests/test_ccg_exclusion_view.py \ + -k 'shortcuts or full_bounded_gui' env: DISPLAY: ':98.0' QT_QPA_PLATFORM: xcb diff --git a/.gitignore b/.gitignore index 0330682f1..63af2a3c5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ local_tests +.context/ +.venv/ contrib data doc diff --git a/design/README.md b/design/README.md index 90565b927..e52897a7a 100644 --- a/design/README.md +++ b/design/README.md @@ -57,3 +57,19 @@ and section 11 for integration and manual acceptance. The implementation and user documentation are complete on the unreleased phy 2.2 branch. Final large-dataset smoke testing and save/reopen validation remain. + +## Long-recording curation (proposed) + +The [long-recording curation Phy-side design contract](large-recording-curation.md) +describes bounded local datasets for ~1000-hour sorting datasets, the three spike-index +spaces, optional upstream waveform evidence, full-duration metrics, replay safety, +and the implementation stages. The accompanying synthetic 1000-hour +fixture and reference tests are in `phy/apps/tests/large_recording_fixtures.py` +and `phy/apps/tests/test_large_recording_contract.py`. + +This is a proposal and a reference test contract, **not yet** a `prepare-large` +implementation or an upstream export-format agreement. + +The [integration audit and plan](large-recording-integration-plan.md) refines +the contract with correctness findings, module boundaries, ordered commits in one PR and +acceptance gates. Follow its gates before enabling editable bounded sessions. diff --git a/design/aind-export-handoff.md b/design/aind-export-handoff.md new file mode 100644 index 000000000..924c823f4 --- /dev/null +++ b/design/aind-export-handoff.md @@ -0,0 +1,90 @@ +# AIND export handoff for elapsed-time coordinates + +This note describes the producer work needed before an AIND export can use +Phy's explicit elapsed-tick contract. It is a handoff, not evidence that an +exporter change has been implemented or that a real export has passed +acceptance. The exporter source repository was not available in this worktree; +the steps below are proposed commit-sized changes, with no repository or branch +assumed. + +## Proposed exporter changes + +1. **Establish authoritative acquisition truth.** Obtain acquisition logs or + equivalent source records for clock origin, piece boundaries, dropped or + invalid spans, filler, and the physical recording extent. Resolve the + reported interruptions and the 35 sorting spikes reported inside filler. + Do not infer validity solely from spike times or endpoint interpolation. +2. **Emit a canonical event time axis.** For each sorting spike, emit a + nonnegative integer elapsed tick from the source time origin. Declare + `time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': ...}`. Set + `num_samples` to the exclusive bound that includes the last representable + event tick; retain a physical frame count separately (for example as + `recording.num_frames`). Do not call a tick bound a frame count. +3. **Emit authoritative exposure.** Emit ordered, disjoint integer + `valid_intervals` in the same elapsed-tick coordinates, excluding missing + acquisition time and unusable filler. Ensure every emitted sorting spike + belongs to a valid interval. If any sorting rows fall outside exposure, + resolve them using acquisition truth upstream; never silently drop, move, or + relabel rows. +4. **Emit aligned waveform and window evidence.** Store + `_phy_spikes_subset.sample_index.npy` in canonical elapsed ticks, with each + value equal to `spike_times[subset_spikes[w]]`. Emit producer windows in + elapsed ticks, with boundaries that do not bridge unsupported intervals. + If the windows overlap, retain their original boundaries and ensure their + union accurately represents potential evidence. Add + `recording.sample_index_coordinates: "elapsed_ticks"` and + `recording.window_bounds_coordinates: "elapsed_ticks"` to the manifest when + those sidecars are present. Add `recording.time_base` and authoritative + `valid_intervals`; if `params.py` also declares them, keep the declarations + identical. +5. **Keep raw voltage semantics explicit.** Do not put elapsed ticks into raw + frame-index fields or claim ordinary raw-trace loading works. An export with + a real raw-data path is outside this contract until an explicit validated + event-to-frame mapping is supported. Stored waveform data can be exported + without a raw path. + +## Report evidence separately from verification + +The supplied export report describes 420 frame/clock endpoints for 210 pieces, +with strictly increasing frame endpoints, nondecreasing clock endpoints, and +15 equal adjacent clock pairs. It also reports backward timestamp steps that +are not represented by those endpoints. These are reported properties of the +export metadata, not independent verification of the corresponding acquisition +events. + +The reported `total_dropped_within_pieces_s` was not independently confirmed +against acquisition truth. Endpoint interpolation does not establish the exact +valid-time mask, a sample-accurate raw clock, or reversibility: equal clock +endpoints make the endpoint map non-invertible. The reported 35 spikes inside +filler likewise require independent confirmation and resolution. A 30 kHz +label, monotonic spike times, or a plausible endpoint-derived extent cannot +replace those checks. + +Changing Phy's sampling seed (including setting it to `42`) does not make an +export interoperable. The seed only selects among windows already defined in +Phy's coordinate system; it cannot recover producer acquisition boundaries, +map clock coordinates to frames, or determine which spans contain valid data. +Use compatible producer windows and an explicit coordinate and exposure +contract. + +## Acceptance evidence to return with an export + +Provide the exporter commit or reviewable diff, a short provenance note naming +the authoritative source for boundaries and filler, and machine-checkable +checks showing: + +- every exported spike's elapsed tick and valid-interval membership; +- the exclusive event-axis bound and separately named physical frame count; +- waveform-row alignment of sample indices to `spike_times[subset_spikes]`; +- producer windows' coordinate kind, valid exposure, and source waveform + coverage; +- exact source, retained, and omitted waveform counts under Phy's unchanged + 512 MiB package and 2,000,000-spike budgets. + +If the exporter removes spike rows, it must apply the identical row selection to +every spike-aligned array and rewrite any row-reference arrays such as +`subset_spikes` consistently. Silent removal leaves waveform and metadata rows +misaligned and is not acceptable. Phy can validate the explicit contract and +the exported arrays; only the exporter and acquisition evidence can establish +that the chosen exposure is scientifically authoritative. A local older +recording is not acceptance evidence for a new export. diff --git a/design/aind-native-export-acceptance.md b/design/aind-native-export-acceptance.md new file mode 100644 index 000000000..b7082c825 --- /dev/null +++ b/design/aind-native-export-acceptance.md @@ -0,0 +1,63 @@ +# Native AIND export acceptance + +This checklist accepts an export for Phy software integration only. Passing +checks do not prove scientific validity. The exporter owner must provide +authoritative acquisition evidence for the clock origin, physical extent, +valid exposure, dropped spans, and filler policy. A Phy run cannot supply that +evidence by inferring or converting timestamps or exposure. + +## Before validation + +- [ ] Record the exact Phy revision and native exporter revision in the report. +- [ ] Attach the reviewable exporter change and provenance for acquisition + boundaries and filler classification. +- [ ] Confirm the exporter declares one explicit time base and emits + `num_samples`, `valid_intervals`, waveform sample indices, and producer + windows in that same coordinate system. +- [ ] Confirm every sorting spike is inside authoritative valid exposure and + every waveform sample index equals `spike_times[subset_spikes]`. +- [ ] Resolve spikes inside filler from acquisition evidence upstream. Any + intentional row removal must use the same row mask for every spike-aligned + array and update row references consistently. +- [ ] Keep elapsed ticks separate from physical frame counts. Do not route + elapsed ticks to raw frame-index fields or claim raw-trace loading is + supported by this contract. + +## Phy engineering validation + +1. Run the native export through `tools/validate_aind_export.py` with the two + revisions above, without an output directory. Retain its JSON report, + including input file hashes, time contract, exposure, array counts, and + timings. Resolve every source validation failure at the exporter. +2. Run optional preparation first with Phy's default budgets: 2,000,000 spikes + and 512 MiB. Use a new destination outside the source directory. Record + retained spike and waveform counts, omitted evidence, output size, and + timings. Confirm the original source file hashes are unchanged. +3. If the complete producer evidence exceeds either default cap, run larger + spike and byte caps as distinct, explicitly labeled runs, each to a fresh + destination. Report each cap and its result independently; never treat a + larger-cap success as a pass under the defaults. +4. Open the default bounded output in the Phy GUI. Exercise navigation at the + beginning, middle, and end of retained windows, select units with and + without retained stored waveforms, and verify displayed waveform/channel + mapping and feature behavior. +5. Exercise the three-round SLAY carryforward workflow on the bounded output: + save each round, carry assignments and labels forward, reopen the result, + and compare final assignments and metadata with an independent expected + result. Preserve the round-by-round artifacts and logs. +6. Recheck the native source hashes after GUI and carryforward work. All curation + products must be separate from the source export. + +## Decision record + +- [ ] Phy contract validation passes with no timestamp or exposure inference. +- [ ] Default-budget preparation and output counts are recorded. +- [ ] Larger-cap runs, if needed, are separately reported. +- [ ] GUI and three-round SLAY carryforward evidence is attached. +- [ ] Acquisition authority has approved the clock, exposure, and filler + policy independently of the software checks. + +Record the outcome as **software integration accepted** only when the Phy +checks pass. Record **acquisition truth accepted** separately and only when the +authoritative producer evidence has been reviewed. The first outcome alone is +not scientific acceptance of the export. diff --git a/design/aind-real-data-validation.md b/design/aind-real-data-validation.md new file mode 100644 index 000000000..2edf9d868 --- /dev/null +++ b/design/aind-real-data-validation.md @@ -0,0 +1,137 @@ +# Real AIND software diagnostic + +## Conclusion + +The downloaded export does **not** work unchanged with PR #1428: its time +coordinates and exposure declarations still need upstream correction. A +separately labeled diagnostic derivative exercised the complete Phy workflow +over 469,725,534 rows and exposed one additional Phy defect. That defect is +fixed, with portable regression coverage. Preparation, GUI curation, +save/reopen, full replay, independent verification, and repreparation now pass +on the derivative. + +This is software integration evidence, not scientific acceptance of the +original export. The derivative's exposure is inferred from the JSON endpoint +map, and 33 filler-region spikes were explicitly quarantined. Those choices +require acquisition evidence and producer review before use for curation. + +## Source and unchanged-export checks + +The supplied download script selected computation +`b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`, rather than the earlier reported +`85640506-601d-4826-aa61-d3b822e53c84`. Its recording is +`experiment1_AmplifierData_recording1_group0` from session +`854393_2026-06-09_19-34-26`. + +All 67 downloaded files matched the server's listed sizes, totaling +15,381,599,263 bytes. NumPy headers and payload sizes were checked. The export +contains 469,725,567 spikes, 705 declared units, 140,240 stored waveforms and +177 producer windows. Spike times are monotonic across the complete array. + +The unchanged source fails `prepare-large` with the intended early +`timestamps.json requires an explicit time_base` diagnostic. It declares +10,800,000,000 pipeline frames, while its last spike is elapsed tick +12,188,787,421. Exactly 54,808,765 spikes are beyond the declared extent. +`params.py` and the waveform manifest lack an explicit elapsed-time contract +and valid acquisition intervals. + +All 140,240 waveform centers match the JSON's frame-to-clock conversion within +0.5 tick, while their stored sample indices remain pipeline frames. This +reproduces producer interpolation; it does not establish sample-accurate +acquisition timestamps or exposure. Under that same map, filler regions contain +23, 4 and 6 spikes. These 33 rows differ from the 35 reported for the other +computation. Neither explicit large gap contains spikes. + +## Diagnostic derivative and limits + +The original export was retained unchanged. A separate source was constructed +solely to isolate software behavior: + +- Declare the elapsed-tick contract at 30 kHz, an exclusive extent of + 12,188,787,510 ticks, and canonical sidecar coordinates. +- Copy exact `spike_times[waveform_ids]` into the waveform sample-index sidecar. + Convert each producer `[a, b)` window to + `[round(map(a)), round(map(b - 1)) + 1)` on the elapsed axis. +- Infer diagnostic exposure by excluding only the mapped explicit large gaps + and filler regions. This does not locate unknown dropped frames within + pieces or establish acquisition truth. +- Confirm that coordinate normalization alone still rejects the 33 filler + spikes through the strict exposure-membership check. +- Quarantine those source rows explicitly, apply the identical row selection + to every spike-aligned array, and remap waveform row references. No stored + waveform references a quarantined row. Keep a provenance file listing every + excluded source row and spike tick. + +No conversion or filtering behavior was added to the production importer. +The diagnostic source, outputs, SHA-256 inventory, assumptions and one-off +reproduction scripts are retained beneath the downloaded computation's +`diagnostic-validation/` directory on the validation workstation. + +## Observed Phy defect and fix + +With the actual bounded data, merge, undo/redo, amplitude split and undo/redo +left NumPy integer child IDs as keys in split-event metadata. Projected session +metadata had been normalized, but the retained event had not. Saving failed +while serializing `journal.json` with `TypeError: keys must be str, int, float, +bool or None, not numpy.int64`. + +Both split-event construction paths now normalize metadata before retaining +the event. This preserves IDs and the remainder/selected child order. Two +session API regressions reproduced the failure before the fix; a GUI regression +also exercises merge undo/redo, split, save and reopen. The focused +curation/lifecycle run passed 43 tests. Independent Sol-high review confirmed +the root cause and semantics of the fix. + +## Full workflow results + +Default preparation retained 1,486,361 spikes in 36 windows and 27,865 of +140,240 waveforms. Every unit has spike evidence; 702 of 705 have stored +waveform evidence. The package occupies 532,625,401 bytes, within the +536,870,912-byte cap. The complete producer-window plan is estimated at +2,554,394,546 bytes and 7,298,318 spikes, exceeding both default budgets. + +All default bounded views opened, including waveform-derived features without +exported PCs. Selection included units 574, 578 and 579, which have no retained +stored waveforms. Navigation covered the beginning, middle and final retained +windows. Artificial merge and amplitude-split actions passed undo/redo, an +independent bounded assignment comparison, save and reopen, without logged +application errors. These actions are test operations, not biological curation. + +Full replay wrote a separate output. An independent streamed oracle compared +**all 469,725,534 assignments**, using explicit merge masks and amplitude +comparisons rather than the production replay functions. Edge searches and +weighted/unweighted histograms independently checked the original per-bin +counts, finite amplitude counts and amplitude sums. Exposure arithmetic was +checked against the declared diagnostic intervals, without claiming their +scientific validity. + +Every bounded spike row was checked against its source row. All 27,865 bounded +waveform rows, channel lists and center indices matched their mapped source +rows exactly. Replay preserved immutable array bytes and timestamp provenance. +Repreparation's complete unit counts matched the replay oracle. SHA-256 checks +confirmed that every file in the original download remained unchanged. + +## Measurements and acceptance limits + +Single workstation runs used Linux, Python 3.12.3, phylib 2.7.1, 100,000-row +batches, Xvfb/software OpenGL and Qt's offscreen platform. The workstation has +125 GiB RAM; source files were warm in the filesystem cache. Some later phases +ran concurrently with tests or another verification phase. These are observed +integration costs, not controlled throughput benchmarks or laptop predictions. + +| Phase | Wall time | Peak process RSS | +| --- | ---: | ---: | +| Preparation | 50.1 s | 14.2 GiB | +| GUI actions and reopen | 9.1 s | 0.68 GiB | +| Full replay | 37.0 s | 25.0 GiB | +| Repreparation | 51.0 s | 14.1 GiB | + +Offline RSS includes resident memory-mapped source/output pages. It is not +limited by the bounded package's byte budget. These measurements do not prove a +small process-RSS bound on a much longer source. + +The original export remains blocked until its producer supplies consistent +time coordinates, authoritative exposure and a justified filler-spike policy. +See the [exporter handoff](aind-export-handoff.md). No acquisition logs or +verified exporter source repository were available, and this diagnostic does +not resolve timestamp precision within pieces or chronic unit identity. diff --git a/design/amplitude-index-gui-result.json b/design/amplitude-index-gui-result.json new file mode 100644 index 000000000..fbc4a481f --- /dev/null +++ b/design/amplitude-index-gui-result.json @@ -0,0 +1,36 @@ +{ + "revision": "7ad3454178174b3ab97f96d07b6ab2591f52fdb5", + "source_spikes": 469725567, + "label": "Earlier converted 112.859h engineering dataset; not native1000h acceptance", + "build_attach_and_child_summary_seconds": 84.87282061809674, + "heartbeat": { + "target_interval_ms": 10, + "samples": 8054, + "p50_ms": 9.663892909884453, + "p95_ms": 10.70371069945395, + "max_ms": 322.84208107739687, + "screenshot_intervals_excluded": true + }, + "children": [ + 709, + 710 + ], + "child_counts": [ + 292990, + 346764 + ], + "curation_remained_unsaved": true, + "stages": [ + "Validating source", + "Building summary store", + "Finalizing", + "Sorting amplitude ranges", + "Authenticating range index" + ], + "screenshots": [ + "prompt.png", + "building.png", + "indexing.png", + "ready.png" + ] +} diff --git a/design/benchmarks/bounded_parallel.py b/design/benchmarks/bounded_parallel.py new file mode 100644 index 000000000..8f4c0732e --- /dev/null +++ b/design/benchmarks/bounded_parallel.py @@ -0,0 +1,91 @@ +"""Synthetic cached-file comparison; run from a synced development checkout.""" + +import json +import platform +import tempfile +import time +import tracemalloc +from pathlib import Path + +import numpy as np + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.range_build import build_amplitude_index +from phy.apps.large_recording.source import Source, hash_file, hash_files +from phy.apps.large_recording.summaries import build_summaries +from phy.apps.large_recording.summary_store import build_summary_store + + +def measured(label, fn): + tracemalloc.start() + start = time.perf_counter() + result = fn() + elapsed = time.perf_counter() - start + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + print(label, 'seconds', round(elapsed, 4), 'traced_peak_bytes', peak, flush=True) + return result + + +print(platform.platform(), platform.processor(), 'numpy', np.__version__, flush=True) +with tempfile.TemporaryDirectory(prefix='phy-bench-') as temporary: + root = Path(temporary) + path = root / 'source' + path.mkdir() + n = 8_000_000 + rng = np.random.default_rng(0) + arrays = { + 'spike_times.npy': np.arange(n, dtype=np.int64) * 80000 // n, + 'spike_clusters.npy': rng.integers(0, 16, n, dtype=np.int32), + 'spike_templates.npy': np.zeros(n, np.int32), + 'amplitudes.npy': rng.standard_normal(n).astype(np.float32), + 'spike_depths.npy': rng.standard_normal(n).astype(np.float32), + } + for name, values in arrays.items(): + np.save(path / name, values) + np.save(path / 'templates.npy', np.zeros((1, 3, 1), np.float32)) + np.save(path / 'channel_map.npy', np.array([0], np.int32)) + np.save(path / 'channel_positions.npy', np.array([[0.0, 0.0]])) + (path / 'params.py').write_text('sample_rate=1000\nnum_samples=80000\ndat_path=None\n') + paths = {name: path / name for name in arrays} + hs = [] + for w in (1, 4): + hs.append(measured('hash ' + str(w), lambda w=w: hash_files(paths, workers=w))) + assert hs[0] == hs[1] + bounded = prepare_large( + path / 'params.py', + root / 'bounded', + max_spikes=100000, + max_bytes=128 * 1024 * 1024, + window_seconds=0.01, + stratum_seconds=80, + bin_seconds=40, + ) + stores = [] + for w in (1, 4): + stores.append( + measured( + 'rows ' + str(w), + lambda w=w: build_summary_store( + bounded, root / ('rows' + str(w)), workers=w, buffer_bytes=256 * 1024 * 1024 + ), + ) + ) + assert hash_file(stores[0] / 'data.bin') == hash_file(stores[1] / 'data.bin') + indices = [] + for w in (1, 4): + indices.append( + measured( + 'index ' + str(w), + lambda w=w: build_amplitude_index( + bounded, + root / ('index' + str(w)), + workers=w, + attach=False, + memory_bytes=256 * 1024 * 1024, + ), + ) + ) + for name in ('values.bin', 'nodes.bin', 'segments.bin'): + assert hash_file(indices[0] / name) == hash_file(indices[1] / name) + print('ALL OUTPUTS EXACT', flush=True) diff --git a/design/benchmarks/carl-nov19-results.json b/design/benchmarks/carl-nov19-results.json new file mode 100644 index 000000000..2e03454ab --- /dev/null +++ b/design/benchmarks/carl-nov19-results.json @@ -0,0 +1,1122 @@ +{ + "date": "2026-11-19", + "scope": "Linux engineering fixtures; not Carl\u2019s current 6.75-billion-spike recording", + "core": { + "before": { + "revision": "0af0dae76bf19b1626a199ca6ab876d70b50f606", + "source_spikes": 20216806, + "units": 859, + "fixed_merges": 100, + "cache_conditions": "uncontrolled OS caches; warm synthetic arrays", + "peak_rss_bytes": 3998273536, + "measurements": [ + { + "initial_events": 100, + "samples": [ + { + "wall_seconds": 29.927571862004697, + "cpu_seconds": 29.918934891, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 10.166222169995308 + }, + { + "rows": 20216806, + "seconds": 9.794655934907496 + }, + { + "rows": 20216806, + "seconds": 9.891136494930834 + } + ] + }, + { + "wall_seconds": 29.745199905708432, + "cpu_seconds": 29.736926768000004, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.88471123483032 + }, + { + "rows": 20216806, + "seconds": 9.864308328833431 + }, + { + "rows": 20216806, + "seconds": 9.921595983672887 + } + ] + }, + { + "wall_seconds": 29.62064553005621, + "cpu_seconds": 29.608358956000004, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.784110115841031 + }, + { + "rows": 20216806, + "seconds": 9.829973532818258 + }, + { + "rows": 20216806, + "seconds": 9.931843464262784 + } + ] + } + ], + "p50_seconds": 29.745199905708432, + "p95_seconds": 29.90933466637507 + }, + { + "initial_events": 213, + "samples": [ + { + "wall_seconds": 30.18541553290561, + "cpu_seconds": 30.179331163, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 10.246864053886384 + }, + { + "rows": 20216806, + "seconds": 9.91836383100599 + }, + { + "rows": 20216806, + "seconds": 9.942775877658278 + } + ] + }, + { + "wall_seconds": 29.634047148749232, + "cpu_seconds": 29.61571909, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.866531400941312 + }, + { + "rows": 20216806, + "seconds": 9.892742965370417 + }, + { + "rows": 20216806, + "seconds": 9.797230020165443 + } + ] + }, + { + "wall_seconds": 29.71732787694782, + "cpu_seconds": 29.707683283000023, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.804183029104024 + }, + { + "rows": 20216806, + "seconds": 9.913529362995178 + }, + { + "rows": 20216806, + "seconds": 9.922629232052714 + } + ] + } + ], + "p50_seconds": 29.71732787694782, + "p95_seconds": 30.13860676730983 + }, + { + "initial_events": 1000, + "samples": [ + { + "wall_seconds": 29.829374212771654, + "cpu_seconds": 29.817043223999974, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 10.043684529606253 + }, + { + "rows": 20216806, + "seconds": 9.767458693124354 + }, + { + "rows": 20216806, + "seconds": 9.92158277798444 + } + ] + }, + { + "wall_seconds": 29.358332351781428, + "cpu_seconds": 29.349157273000003, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.774672088213265 + }, + { + "rows": 20216806, + "seconds": 9.748869351111352 + }, + { + "rows": 20216806, + "seconds": 9.739135244861245 + } + ] + }, + { + "wall_seconds": 29.49965327885002, + "cpu_seconds": 29.492624766000006, + "projector_calls": [ + { + "rows": 20216806, + "seconds": 9.810444934759289 + }, + { + "rows": 20216806, + "seconds": 9.765173946041614 + }, + { + "rows": 20216806, + "seconds": 9.829106920864433 + } + ] + } + ], + "p50_seconds": 29.49965327885002, + "p95_seconds": 29.79640211937949 + } + ] + }, + "after": { + "revision": "1888bf1d71586527167d0450070255d5b39cc970", + "source_spikes": 20216806, + "units": 859, + "fixed_merges": 100, + "cache_conditions": "uncontrolled OS caches; warm synthetic arrays", + "peak_rss_bytes": 3961827328, + "measurements": [ + { + "initial_events": 100, + "samples": [ + { + "wall_seconds": 0.0014749621041119099, + "cpu_seconds": 0.001473643000000635, + "projector_calls": [] + }, + { + "wall_seconds": 0.0008020158857107162, + "cpu_seconds": 0.0008023679999986655, + "projector_calls": [] + }, + { + "wall_seconds": 0.0007235710509121418, + "cpu_seconds": 0.0007236950000013564, + "projector_calls": [] + } + ], + "p50_seconds": 0.0008020158857107162, + "p95_seconds": 0.0014076674822717905 + }, + { + "initial_events": 213, + "samples": [ + { + "wall_seconds": 0.0014765160158276558, + "cpu_seconds": 0.0014758149999991588, + "projector_calls": [] + }, + { + "wall_seconds": 0.0008090999908745289, + "cpu_seconds": 0.0008092899999994074, + "projector_calls": [] + }, + { + "wall_seconds": 0.0007412307895720005, + "cpu_seconds": 0.0007414299999979335, + "projector_calls": [] + } + ], + "p50_seconds": 0.0008090999908745289, + "p95_seconds": 0.001409774413332343 + }, + { + "initial_events": 1000, + "samples": [ + { + "wall_seconds": 0.0016497690230607986, + "cpu_seconds": 0.0016486919999891825, + "projector_calls": [] + }, + { + "wall_seconds": 0.0008547753095626831, + "cpu_seconds": 0.000854935999996087, + "projector_calls": [] + }, + { + "wall_seconds": 0.0007868488319218159, + "cpu_seconds": 0.000787019000000555, + "projector_calls": [] + } + ], + "p50_seconds": 0.0008547753095626831, + "p95_seconds": 0.001570269651710987 + } + ] + } + }, + "gui": { + "before": { + "revision": "43cdc7bc2dbc16bb3f7d87071a85577233a06479", + "status": "ok", + "configuration": { + "repeats": 2, + "events": 213, + "merges": 100, + "merge_undo": true, + "profile": false, + "max_copy_bytes": 4294967296, + "worker_timeout_seconds": 900.0 + }, + "source_unchanged": true, + "worker_exit_code": 0, + "rendering_environment": { + "QT_QPA_PLATFORM": "xcb", + "LIBGL_ALWAYS_SOFTWARE": "1", + "PYOPENGL_PLATFORM": "glx", + "LP_NUM_THREADS": "4" + }, + "worker": { + "measurements": [ + { + "action": "move_best_to_good-0", + "profiled": false, + "initial_events": 214, + "selected_before": [ + 804 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 16.30898629501462, + "supervisor_wait_seconds": 0.06186949834227562, + "additional_ready_seconds": 0.0009453347884118557, + "wall_seconds": 16.371801128145307, + "cpu_seconds": 16.388386488000002, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 16.327713459264487, + "heartbeat_max_delay_seconds": 16.317713459264485 + }, + { + "action": "label-0", + "profiled": false, + "initial_events": 215, + "selected_before": [ + 550 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 15.775807308964431, + "supervisor_wait_seconds": 0.05095731792971492, + "additional_ready_seconds": 7.849326357245445e-05, + "wall_seconds": 15.826843120157719, + "cpu_seconds": 15.806094694999999, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 4, + "heartbeat_max_gap_seconds": 15.793606107123196, + "heartbeat_max_delay_seconds": 15.783606107123196 + }, + { + "action": "merge-0", + "profiled": false, + "initial_events": 216, + "selected_before": [ + 804, + 550 + ], + "selected_after": [ + 805 + ], + "action_return_seconds": 7.001773044001311, + "supervisor_wait_seconds": 0.8797019179910421, + "additional_ready_seconds": 0.016769326757639647, + "wall_seconds": 7.898244288749993, + "cpu_seconds": 7.908885870999995, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 7.022254269104451, + "heartbeat_max_delay_seconds": 7.012254269104451 + }, + { + "action": "undo-0", + "profiled": false, + "initial_events": 217, + "selected_before": [ + 805 + ], + "selected_after": [ + 804, + 550 + ], + "action_return_seconds": 7.053042684681714, + "supervisor_wait_seconds": 0.8667833283543587, + "additional_ready_seconds": 0.016959969885647297, + "wall_seconds": 7.9367859829217196, + "cpu_seconds": 7.955239789000004, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 7.075571252033114, + "heartbeat_max_delay_seconds": 7.065571252033115 + }, + { + "action": "move_best_to_good-1", + "profiled": false, + "initial_events": 217, + "selected_before": [ + 804 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 16.623395862989128, + "supervisor_wait_seconds": 0.05108706373721361, + "additional_ready_seconds": 0.0005689812824130058, + "wall_seconds": 16.675051908008754, + "cpu_seconds": 16.684939623999995, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 16.64111898979172, + "heartbeat_max_delay_seconds": 16.63111898979172 + }, + { + "action": "label-1", + "profiled": false, + "initial_events": 218, + "selected_before": [ + 550 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 15.811389989219606, + "supervisor_wait_seconds": 0.050696097780019045, + "additional_ready_seconds": 6.888294592499733e-05, + "wall_seconds": 15.86215496994555, + "cpu_seconds": 15.841664982999987, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 4, + "heartbeat_max_gap_seconds": 15.829505287110806, + "heartbeat_max_delay_seconds": 15.819505287110806 + }, + { + "action": "merge-1", + "profiled": false, + "initial_events": 219, + "selected_before": [ + 804, + 550 + ], + "selected_after": [ + 806 + ], + "action_return_seconds": 7.128287340980023, + "supervisor_wait_seconds": 0.78158586518839, + "additional_ready_seconds": 0.016668240074068308, + "wall_seconds": 7.9265414462424815, + "cpu_seconds": 7.938548279999992, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 7.148839966394007, + "heartbeat_max_delay_seconds": 7.138839966394007 + }, + { + "action": "undo-1", + "profiled": false, + "initial_events": 220, + "selected_before": [ + 806 + ], + "selected_after": [ + 804, + 550 + ], + "action_return_seconds": 7.182583073154092, + "supervisor_wait_seconds": 0.796483906917274, + "additional_ready_seconds": 0.016933593899011612, + "wall_seconds": 7.9960005739703774, + "cpu_seconds": 8.012919914000008, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 7.204622955061495, + "heartbeat_max_delay_seconds": 7.1946229550614955 + } + ], + "status": "ok", + "original_events": 0, + "initial_events": 213, + "synthetic_events_added": 213, + "synthetic_merges_added": 100, + "gui_setup_seconds": 13.649033174850047, + "views": [ + "EvidenceAmplitudeView", + "UnitStabilityView" + ], + "threading": false, + "requested_threading": true, + "ready_definition": "supervisor.block + processEvents + zero-delay Qt timer", + "versions": { + "phy": "2.2.0.dev0", + "phylib": "2.7.1", + "numpy": "2.4.3", + "PyQt5": "5.15.11", + "PyOpenGL": "3.1.10" + }, + "opengl": { + "vendor": "b'Mesa'", + "renderer": "b'llvmpipe (LLVM 20.1.2, 256 bits)'", + "version": "b'4.5 (Compatibility Profile) Mesa 25.2.8-0ubuntu0.24.04.4'" + }, + "python": "3.12.13 (main, Jul 23 2026, 14:43:28) [Clang 22.1.3 ]", + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "worker_wall_seconds": 157.87383385421708, + "worker_cpu_seconds": 157.6228037, + "peak_rss_bytes": 1947037696, + "rss_method": "resource.ru_maxrss" + } + }, + "after_final": { + "revision": "c2d541f0e57e68f2259876e3a0b10c345e6eca23", + "status": "ok", + "configuration": { + "repeats": 2, + "events": 213, + "merges": 100, + "merge_undo": true, + "profile": true, + "max_copy_bytes": 4294967296, + "worker_timeout_seconds": 900.0 + }, + "source_unchanged": true, + "worker_exit_code": 0, + "rendering_environment": { + "QT_QPA_PLATFORM": "xcb", + "LIBGL_ALWAYS_SOFTWARE": "1", + "PYOPENGL_PLATFORM": "glx", + "LP_NUM_THREADS": "4" + }, + "worker": { + "measurements": [ + { + "action": "move_best_to_good-0", + "profiled": false, + "initial_events": 214, + "selected_before": [ + 804 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 0.706919482909143, + "supervisor_wait_seconds": 0.05111942999064922, + "additional_ready_seconds": 7.194932550191879e-05, + "wall_seconds": 0.7581108622252941, + "cpu_seconds": 0.7592442730000002, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 4, + "heartbeat_max_gap_seconds": 0.7257922571152449, + "heartbeat_max_delay_seconds": 0.7157922571152449 + }, + { + "action": "label-0", + "profiled": false, + "initial_events": 215, + "selected_before": [ + 550 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 0.14307844499126077, + "supervisor_wait_seconds": 0.05062761763110757, + "additional_ready_seconds": 8.582742884755135e-05, + "wall_seconds": 0.1937918900512159, + "cpu_seconds": 0.15415445700000419, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 5, + "heartbeat_max_gap_seconds": 0.1537492098286748, + "heartbeat_max_delay_seconds": 0.14374920982867478 + }, + { + "action": "merge-0", + "profiled": false, + "initial_events": 216, + "selected_before": [ + 804, + 550 + ], + "selected_after": [ + 805 + ], + "action_return_seconds": 1.7540130941197276, + "supervisor_wait_seconds": 0.8196123717352748, + "additional_ready_seconds": 0.01652061427012086, + "wall_seconds": 2.5901460801251233, + "cpu_seconds": 2.604096161000001, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 1.7741776751354337, + "heartbeat_max_delay_seconds": 1.7641776751354337 + }, + { + "action": "undo-0", + "profiled": false, + "initial_events": 217, + "selected_before": [ + 805 + ], + "selected_after": [ + 804, + 550 + ], + "action_return_seconds": 1.9810601798817515, + "supervisor_wait_seconds": 0.8843560758978128, + "additional_ready_seconds": 0.017091649118810892, + "wall_seconds": 2.8825079048983753, + "cpu_seconds": 2.9029404409999984, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 2.0021299268119037, + "heartbeat_max_delay_seconds": 1.9921299268119037 + }, + { + "action": "move_best_to_good-1", + "profiled": false, + "initial_events": 217, + "selected_before": [ + 804 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 0.7075264868326485, + "supervisor_wait_seconds": 0.12148346472531557, + "additional_ready_seconds": 0.0005580051802098751, + "wall_seconds": 0.829567956738174, + "cpu_seconds": 0.8437553719999968, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 0.8134420388378203, + "heartbeat_max_delay_seconds": 0.8034420388378203 + }, + { + "action": "label-1", + "profiled": false, + "initial_events": 218, + "selected_before": [ + 550 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 0.1430545155890286, + "supervisor_wait_seconds": 0.05036998400464654, + "additional_ready_seconds": 6.970716640353203e-05, + "wall_seconds": 0.19349420676007867, + "cpu_seconds": 0.1540899170000003, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 4, + "heartbeat_max_gap_seconds": 0.15387950092554092, + "heartbeat_max_delay_seconds": 0.14387950092554092 + }, + { + "action": "merge-1", + "profiled": false, + "initial_events": 219, + "selected_before": [ + 804, + 550 + ], + "selected_after": [ + 806 + ], + "action_return_seconds": 1.8603575541637838, + "supervisor_wait_seconds": 0.9067575177177787, + "additional_ready_seconds": 0.017287258058786392, + "wall_seconds": 2.784402329940349, + "cpu_seconds": 2.7980890949999946, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 1.8811276592314243, + "heartbeat_max_delay_seconds": 1.8711276592314243 + }, + { + "action": "undo-1", + "profiled": false, + "initial_events": 220, + "selected_before": [ + 806 + ], + "selected_after": [ + 804, + 550 + ], + "action_return_seconds": 1.8973542782478034, + "supervisor_wait_seconds": 0.917965404689312, + "additional_ready_seconds": 0.01711077895015478, + "wall_seconds": 2.83243046188727, + "cpu_seconds": 2.856617567999997, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 1.9192384709604084, + "heartbeat_max_delay_seconds": 1.9092384709604084 + }, + { + "action": "move_best_to_good-profile", + "profiled": true, + "initial_events": 220, + "selected_before": [ + 804 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 1.533061029855162, + "supervisor_wait_seconds": 0.0513141630217433, + "additional_ready_seconds": 4.7130975872278214e-05, + "wall_seconds": 1.5844223238527775, + "cpu_seconds": 1.6058459159999998, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 1.5629122839309275, + "heartbeat_max_delay_seconds": 1.5529122839309275 + }, + { + "action": "label-profile", + "profiled": true, + "initial_events": 221, + "selected_before": [ + 550 + ], + "selected_after": [ + 550 + ], + "action_return_seconds": 0.4784826170653105, + "supervisor_wait_seconds": 0.051018691156059504, + "additional_ready_seconds": 0.00010555470362305641, + "wall_seconds": 0.529606862924993, + "cpu_seconds": 0.49857399700000826, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 4, + "heartbeat_max_gap_seconds": 0.4963857620023191, + "heartbeat_max_delay_seconds": 0.4863857620023191 + }, + { + "action": "merge-profile", + "profiled": true, + "initial_events": 222, + "selected_before": [ + 804, + 550 + ], + "selected_after": [ + 807 + ], + "action_return_seconds": 3.8639148687943816, + "supervisor_wait_seconds": 1.430221898946911, + "additional_ready_seconds": 0.027201506309211254, + "wall_seconds": 5.321338274050504, + "cpu_seconds": 5.341184016999989, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 3.8962029879912734, + "heartbeat_max_delay_seconds": 3.8862029879912736 + }, + { + "action": "undo-profile", + "profiled": true, + "initial_events": 223, + "selected_before": [ + 807 + ], + "selected_after": [ + 804, + 550 + ], + "action_return_seconds": 3.2259246869944036, + "supervisor_wait_seconds": 1.557266023941338, + "additional_ready_seconds": 0.027752608060836792, + "wall_seconds": 4.8109433189965785, + "cpu_seconds": 4.837099711999997, + "heartbeat_interval_seconds": 0.01, + "heartbeat_ticks": 2, + "heartbeat_max_gap_seconds": 3.2586072338745, + "heartbeat_max_delay_seconds": 3.2486072338745 + } + ], + "status": "ok", + "original_events": 0, + "initial_events": 213, + "synthetic_events_added": 213, + "synthetic_merges_added": 100, + "gui_setup_seconds": 21.46330912411213, + "views": [ + "EvidenceAmplitudeView", + "UnitStabilityView" + ], + "threading": false, + "requested_threading": true, + "ready_definition": "supervisor.block + processEvents + zero-delay Qt timer", + "versions": { + "phy": "2.2.0.dev0", + "phylib": "2.7.1", + "numpy": "2.4.3", + "PyQt5": "5.15.11", + "PyOpenGL": "3.1.10" + }, + "opengl": { + "vendor": "b'Mesa'", + "renderer": "b'llvmpipe (LLVM 20.1.2, 256 bits)'", + "version": "b'4.5 (Compatibility Profile) Mesa 25.2.8-0ubuntu0.24.04.4'" + }, + "python": "3.12.13 (main, Jul 23 2026, 14:43:28) [Clang 22.1.3 ]", + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "worker_wall_seconds": 74.02844266686589, + "worker_cpu_seconds": 73.735140181, + "peak_rss_bytes": 1948729344, + "rss_method": "resource.ru_maxrss" + } + } + }, + "full_source_validation": { + "head": "22eed44faab1aed60da8cb498556ea43bde3c907", + "status": "passed", + "comparison": { + "active_units": 700, + "independent_original_membership_oracle_exact": true, + "references": { + "1": { + "assignments_rows_exact": 469725567, + "assignments_sha256": "c74ad993e42e5d70de058c221ddd5338ae0128753a9074d2bef48de1cb25ff05", + "lineage_exact": true, + "params_byte_exact": true, + "metadata_files_byte_exact_count": 52 + }, + "4": { + "assignments_rows_exact": 469725567, + "assignments_sha256": "c74ad993e42e5d70de058c221ddd5338ae0128753a9074d2bef48de1cb25ff05", + "lineage_exact": true, + "params_byte_exact": true, + "metadata_files_byte_exact_count": 52 + } + }, + "split_counts": [ + 1691273, + 1597610 + ] + }, + "immutable_inputs_unchanged": true, + "runtime_code_unchanged": true, + "phases": { + "apply-curation": { + "cpu_seconds": 51.995750085000005, + "peak_rss_bytes": 28650700800, + "success": true, + "wall_seconds": 52.98781754029915 + }, + "compare-reference-and-independent-oracle": { + "cpu_seconds": 16.139086387000006, + "peak_rss_bytes": 9587712000, + "success": true, + "wall_seconds": 17.204725943971425 + }, + "inventory-after": { + "cpu_seconds": 13.516467300000002, + "peak_rss_bytes": 258002944, + "success": true, + "wall_seconds": 13.507640429306775 + }, + "inventory-before": { + "cpu_seconds": 13.973860735, + "peak_rss_bytes": 232550400, + "success": true, + "wall_seconds": 14.886226363945752 + } + }, + "total_wall_seconds": 98.61504838196561, + "total_cpu_seconds": 95.651780955, + "peak_rss_bytes": 28648398848 + }, + "local_gates": { + "runtime_revision": "c2d541f0", + "shared_master_revision": "306667e4", + "pr1428": { + "test_full_exit_code": 0, + "common_passed": 739, + "apps_passed": 893, + "skipped": 19, + "doc_check_exit_code": 0, + "build_exit_code": 0 + }, + "master": { + "test_full_exit_code": 0, + "common_passed": 673, + "apps_passed": 168, + "skipped": 19, + "doc_check_exit_code": 0 + } + }, + "sampled_pair_exclusion": { + "kernel_sha256": "69933b4fb76be0b2b942f7c55c3e95a3f639a9d1996723eb617257f9717ae3d4", + "numpy_version": "2.4.3", + "sample_rows": 7298318, + "windows": 175, + "sample_clock_dtype": "int64", + "sample_rate": 30000.0, + "bin_ms": 0.5, + "window_ms": 50.0, + "selected_ids": [ + 40, + 44, + 48 + ], + "selected_retained_counts": { + "40": 9642, + "44": 3400, + "48": 5563 + }, + "fixed_readonly_mmap_arrays_for_all_calls": true, + "repeats": 3, + "profiling_enabled": false, + "inputs_unchanged": true, + "memory": { + "rss_before_calls_bytes": 280952832, + "rss_after_calls_bytes": 340586496, + "process_peak_rss_bytes": 353185792, + "mapped_fixture_array_bytes": 116775888, + "rss_note": "Process RSS includes shared read-only mmap pages and imports. Peak is a process high-water mark, not an allocation profile or a per-case peak." + }, + "cases": [ + { + "exclusion_ms": 0.3, + "exclude_auto": false, + "exclude_cross": false, + "seconds": [ + 0.0377472504042089, + 0.036931389942765236, + 0.03846447775140405 + ], + "median_seconds": 0.0377472504042089, + "histogram_total": 20605, + "histogram_sha256": "849f9139bc1e6789f69a5f90ab1570224910b339a4a8f269571c93eac1ccb778", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340426752, + 340549632, + 340561920 + ], + "median_ratio_to_both_disabled": 1.0 + }, + { + "exclusion_ms": 0.3, + "exclude_auto": false, + "exclude_cross": true, + "seconds": [ + 0.03517023427411914, + 0.03351428406313062, + 0.03464335668832064 + ], + "median_seconds": 0.03464335668832064, + "histogram_total": 20589, + "histogram_sha256": "14b58701c310f3ead61a34aee2460950f7ef2ed3796f441f7de1bd66f1b1582c", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340553728, + 340561920, + 340549632 + ], + "median_ratio_to_both_disabled": 0.91777166064678 + }, + { + "exclusion_ms": 0.3, + "exclude_auto": true, + "exclude_cross": false, + "seconds": [ + 0.03363155713304877, + 0.032709193881601095, + 0.0340843559242785 + ], + "median_seconds": 0.03363155713304877, + "histogram_total": 20604, + "histogram_sha256": "86be5836d3d3d7e73e1b3a6f0d09123c441a9651cd00a114156a9825242a80fa", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340557824, + 340566016, + 340557824 + ], + "median_ratio_to_both_disabled": 0.8909670710558241 + }, + { + "exclusion_ms": 0.3, + "exclude_auto": true, + "exclude_cross": true, + "seconds": [ + 0.03261388512328267, + 0.03150375233963132, + 0.032571813091635704 + ], + "median_seconds": 0.032571813091635704, + "histogram_total": 20588, + "histogram_sha256": "599f828c4342ab4ab92c845bf26bdfa8641ee377bebcdc6c8ccd00edbebf33e2", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340566016, + 340553728, + 340566016 + ], + "median_ratio_to_both_disabled": 0.8628923363383277 + }, + { + "exclusion_ms": 2.0, + "exclude_auto": false, + "exclude_cross": false, + "seconds": [ + 0.03660568408668041, + 0.036235762760043144, + 0.03585618082433939 + ], + "median_seconds": 0.036235762760043144, + "histogram_total": 20605, + "histogram_sha256": "849f9139bc1e6789f69a5f90ab1570224910b339a4a8f269571c93eac1ccb778", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340553728, + 340570112, + 340561920 + ], + "median_ratio_to_both_disabled": 1.0 + }, + { + "exclusion_ms": 2.0, + "exclude_auto": false, + "exclude_cross": true, + "seconds": [ + 0.035132244694978, + 0.03413944412022829, + 0.033686691895127296 + ], + "median_seconds": 0.03413944412022829, + "histogram_total": 20557, + "histogram_sha256": "1d2c4afa8218b528c48b38244e19830e155602227de3e4bf4b1ba11725feb5d0", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340570112, + 340574208, + 340582400 + ], + "median_ratio_to_both_disabled": 0.9421477987452096 + }, + { + "exclusion_ms": 2.0, + "exclude_auto": true, + "exclude_cross": false, + "seconds": [ + 0.033492091577500105, + 0.03398209111765027, + 0.03417128883302212 + ], + "median_seconds": 0.03398209111765027, + "histogram_total": 20572, + "histogram_sha256": "a962da4241f6a4ec7cb2dc4e36f28307040c57f777618673a45591ad82423604", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340570112, + 340574208, + 340570112 + ], + "median_ratio_to_both_disabled": 0.9378053207457805 + }, + { + "exclusion_ms": 2.0, + "exclude_auto": true, + "exclude_cross": true, + "seconds": [ + 0.03198580024763942, + 0.030888855922967196, + 0.03169637219980359 + ], + "median_seconds": 0.03169637219980359, + "histogram_total": 20524, + "histogram_sha256": "56cf74c31f80878feeb08addd496c96d0d4c4f394e84cd733229b6743587418b", + "histogram_shape": [ + 3, + 3, + 101 + ], + "histogram_dtype": "int64", + "rss_after_each_repeat_bytes": [ + 340574208, + 340570112, + 340574208 + ], + "median_ratio_to_both_disabled": 0.8747262313670654 + } + ], + "runtime_commit": "d1018a63", + "validation": { + "runtime_commit": "d1018a63", + "test_full_exit_code": 0, + "common_passed": 739, + "apps_passed": 972, + "skipped": 19, + "doc_check_exit_code": 0, + "build_exit_code": 0, + "real_xcb_ui_tests_passed": 8, + "master_unchanged": "306667e4" + } + } +} diff --git a/design/benchmarks/summary_histograms.py b/design/benchmarks/summary_histograms.py new file mode 100644 index 000000000..2b053e8db --- /dev/null +++ b/design/benchmarks/summary_histograms.py @@ -0,0 +1,74 @@ +"""Synthetic lookup/histogram microbenchmark; not end-to-end preparation.""" + +import time +import tracemalloc + +import numpy as np + +from phy.apps.large_recording.streaming import UnitRows + +rng = np.random.default_rng(0) +n = 10_000_000 +units = np.arange(1173, dtype=np.int64) +bins = 2050 +batch = 100000 +ids = rng.integers(0, len(units), n, dtype=np.int32) +cols = np.arange(n, dtype=np.int64) * bins // n +values = rng.standard_normal(n).astype(np.float32) +lookup = UnitRows(units) + + +def run(new): + counts = np.zeros((len(units), bins), np.int64) + sums = np.zeros_like(counts, dtype=float) + finite_counts = np.zeros_like(counts) + tracemalloc.start() + start = time.perf_counter() + for first in range(0, n, batch): + v = values[first : first + batch] + c = cols[first : first + batch] + r = ( + lookup(ids[first : first + batch]) + if new + else np.searchsorted(units, ids[first : first + batch]) + ) + if new: + lo, hi = int(c[0]), int(c[-1]) + 1 + width = hi - lo + flat = r.astype(np.int64) * width + c - lo + for out, weights in ((counts, None), (sums, v), (finite_counts, None)): + out[:, lo:hi] += np.bincount( + flat, weights=weights, minlength=len(units) * width + ).reshape(-1, width) + else: + np.add.at(counts, (r, c), 1) + np.add.at(sums, (r, c), v) + np.add.at(finite_counts, (r, c), 1) + seconds = time.perf_counter() - start + peak = tracemalloc.get_traced_memory()[1] + tracemalloc.stop() + return (counts, sums, finite_counts), seconds, peak + + +old, t0, m0 = run(False) +new, t1, m1 = run(True) +print('spikes', n, 'units', len(units), 'bins', bins, 'batch', batch) +print( + 'baseline seconds', + t0, + 'scratch peak bytes', + m0, + 'new seconds', + t1, + 'scratch peak bytes', + m1, + 'speedup', + t0 / t1, +) +print('counts exact', np.array_equal(old[0], new[0]), 'sums exact', np.array_equal(old[1], new[1])) +for dtype in (np.int32, np.int64): + keys = ids[:batch].astype(dtype) + start = time.perf_counter() + for _ in range(100): + np.argsort(keys, kind='stable') + print('stable grouping', dtype, 'seconds/100', time.perf_counter() - start) diff --git a/design/carl-feedback-captures/README.md b/design/carl-feedback-captures/README.md new file mode 100644 index 000000000..d90e3b7c5 --- /dev/null +++ b/design/carl-feedback-captures/README.md @@ -0,0 +1,416 @@ +# Carl feedback: rendered real-data validation + +## Recursive restoration and SLAY reassembly — current review + +[Play the narrated 58-second video on PR #1428](https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782). +The new walkthrough demonstrates Carl's nested-merge request on a copied real dataset: + +1. Merge source units **25 + 27 → 705**, then **705 + 22 → 706**. +2. Make a later unrelated **0 + 1 → 707** merge and label **707 MUA**. +3. Restore **706** once. All three original components appear together as live + units **708, 709, 710**, with **was 25, was 27, was 22** in the Parent column. + The intermediate **705** is not a staged component. +4. Undo/redo reverses the entire restoration, preserving **707/MUA**. Leaving + Merge Mode keeps all three restored clusters live. +5. Exclude **710**, then merge the original pair again into **711**. The SLAY + suggestion returns to green. Undo/redo returns it to white/green respectively. +6. Save/reopen: **711**, separate **710**, later **707/MUA**, the historical review + and the green suggestion all remain correct. + +Restoration follows recorded merge topology and stops at genuine split boundaries. +It validates the complete plan before mutation, including every retained evidence +component in bounded mode. Corrupt known ancestry rejects the entire operation; +unknown earlier ancestry remains opaque. Fresh IDs preserve unambiguous history; +the Parent column carries historical identity, including legacy alias chains. +The normal scrollable Merge workspace supports more than 16 restored components. +The separate read-only comparison retains its existing immediate-parent behavior. + +New bounded restore events use **version 4**, with ordered historical leaf +references authenticated to the journal prefix and source revision. Existing +version-3 immediate-parent events keep their original meaning. SLAY reassembly +uses exact ordinary memberships or conservative bounded membership-expression +proof, without scanning full-source spikes during interactive refresh. Partial +reassembly remains historical; extra membership is accepted-modified. Historical +modified acceptance retains its recorded scope. + +Both [ordinary](recursive-ordinary-capture.json) and +[bounded](recursive-bounded-capture.json) runs at `03377575` passed all **12 +checkpoints**, scientific membership assertions, one-action history checks, +actual SLAY foreground-color checks, Undo/Redo, Save/reopen and unchanged-source +hashes. The later split-scope SLAY proof (`857dc3ea`) and legacy ordinary identity +alias handling (`c57abdaf`) have separate focused regressions; these scenarios +are not claimed as additional actions in the recording. + +| Checkpoint | Ordinary | Bounded | +| --- | --- | --- | +| First result merged with a third source unit | [Open](recursive-ordinary-03-nested-merge.png) | [Open](recursive-bounded-03-nested-merge.png) | +| All three original components restored once | [Open](recursive-ordinary-05-restored-parents.png) | [Open](recursive-bounded-05-restored-parents.png) | +| Exact pair remerged, SLAY green again | [Open](recursive-ordinary-09-exact-remerge.png) | [Open](recursive-bounded-09-exact-remerge.png) | +| Reopened result and green suggestion | [Open](recursive-ordinary-12-reopened.png) | [Open](recursive-bounded-12-reopened.png) | + +The [new full-source report](recursive-pipeline-report.md) independently checks +**469,725,567 rows in each of two replays** (one/four workers), including an +amplitude split followed by two nested merges, one recursive restore, exclusion, +addition and remerge. All **45 metadata fields / 31,545 cells**, reviews, lineage, +counts and cumulative provenance survive replay/reprepare. All 140 input files +retain their hashes and stats. Reprepare remains below 2M rows / 512 MiB. +[Exact scenario](recursive-pipeline-scenario.json) · +[Final checks](recursive-pipeline-final-checks.json) · +[Artifact provenance](recursive-pipeline-artifact-provenance.json). +The scientific run is attributed to `03377575`; subsequent UI-only proof changes +are explicitly hashed and AST-checked in its report. The converted fixture's +clock/exposure assumptions remain unverified; this is engineering validation, +not a claim about biological merge quality or acquisition timing. + +### Narrated media and reproduction + +The H.264/AAC recording remains 1920×1200 at 30 fps, with 1,738 video frames, +a visible pointer, click rings, in-window keyboard cues and burned-in English +subtitles. The keyboard cues sit above the subtitles. Labeled **REVIEW NOTE** +panels are video annotations, not application UI. Original-speed source clips +are retained; idle dwell and the reload wait are omitted with an explicit card. +The [edit timeline](recursive-review.timeline.json) retains every checkpoint. +This is settled X11 rendering evidence, not a latency or spontaneous-redraw test. + +Narration uses the previously reviewed Kyutai voice and sentence-by-sentence +process. Eleven complete sentences retain their exact PCM samples before volume +normalization: **no internal speech cuts or tempo changes**, with at least +**0.51 seconds** of silence between sentences. The audio peak is **−2.0 dB**; +black detection found no full-frame interval of at least 0.2 seconds at the +specified threshold. Native context clicks use XTest; other inputs use Qt events. +No capture window reaches the user's desktop. + +[Subtitles](recursive-narration.srt) · +[Audio placement](recursive-narration-alignment.json) · +[Generation parameters and input hashes](recursive-narration-generation.json) · +[Published video verification](recursive-review.json). + +Synthetic speech uses [Kyutai TTS](https://huggingface.co/kyutai/tts-1.6b-en_fr) +(model weights CC BY 4.0, developed by Kyutai) and its published +[voice preset](https://huggingface.co/kyutai/tts-voices/tree/main/unmute-prod-website) +(CC0 for this voice, per the voice repository). Dependencies remain in a separate +environment, without changing Phy's dependencies. + +To recreate the current postproduction from the archived capture and sentence WAVs: + +```bash +uv run --no-sync python tools/caption_capture_video.py CAPTURE_DIRECTORY \ + --review-cut --review-seconds 58 --output-name recursive-review.mp4 +python design/carl-feedback-captures/render-narrated-review.py \ + --capture CAPTURE_DIRECTORY \ + --approved-audio SENTENCE_AUDIO_DIRECTORY \ + --output NEW_OUTPUT_DIRECTORY +``` + +The renderer needs FFmpeg, NumPy and soundfile. The capture directory contains +`walkthrough.mp4`, `recursive-review.ass` and its `.timeline.json`. The audio +directory contains `generation.json`, `01-with-bonjour.wav`, and +`02-sentence.wav` through `11-sentence.wav`. Original media and logs remain in the +local validation archive; generation metadata records the input hashes. Speech +regeneration is a separate step and does not guarantee identical waveforms. +The renderer requires a fresh output directory and accepts only complete sentences. + +### Local checks + +The core target passed **706 tests, 13 skipped**; the final application target +passed **833 tests, 6 skipped**, both with normal exits. After the legacy alias +followup, **147 ordinary GUI/lineage tests** passed. The final rollback-cache +followup passed all **122 Supervisor tests**, including its new failure-path +regression. Lint, +formatting and published documentation checks pass. +Validation uses **PyQt5-sip 12.20.1**, proposed separately in +[PR #1442](https://github.com/cortex-lab/phy/pull/1442); this feature branch's +lockfile is unchanged. The Qt event-class guard covers the reported missing +mouse-method exception, including generic/mismatched wrappers and repeated +context-menu sequences. It does not establish the cause of every reported +instability. CI is excluded. + +The sections below preserve superseded immediate-parent workflow evidence. + +## Historical immediate-parent restoration review + +[Earlier narrated immediate-parent video](https://github.com/user-attachments/assets/92be1237-6174-4269-bd6b-3bb27f6c0511). +This section preserves the previous workflow; recursive restoration is documented above. +This review demonstrates the workflow that global Undo and the former read-only +parent view could not provide: + +1. Merge the combined SLAY suggestions into unit **705**. +2. Perform two later edits: merge unrelated units into **706**, then mark it **MUA**. +3. Revisit **705** and choose **Restore parents in Merge Mode**. Its exact immediate + parents become real editable units **707–713**, with original IDs in the **Parent** + column and preserved colors. The unrelated **706/MUA** edit remains intact. +4. Undo/redo only the restoration. Leave Merge Mode with **V** to show that these + parents remain live, then stage them again. +5. **Exclude current row** removes **713** from the pending merge; Ctrl-click adds + candidate **34**. Press **G** to merge the chosen combination into **714**. +6. Save/reopen: **714** remains merged, **713** remains independent, and **706** is + still MUA. Original SLAY acceptance stays historical, with restored status. + +This is a new undoable curation action, not a traversal of earlier Undo entries. +Fresh IDs prevent reuse of retired IDs. New memberships start unclassified rather +than inheriting the former merged unit's quality. **Inspect parents (read-only)** +remains available as the secondary comparison action. + +The current recording is 1920×1200, 30 fps, about 58 seconds, with English +narration and burned-in English subtitles. The visible pointer, gold click rings +and translucent keycaps remain; keyboard cues sit above the subtitles. Labeled +**REVIEW NOTE** overlays explain the stages; they are video annotations, not UI. +Interactions retain original speed; idle dwell and the reload wait are omitted, +with a labeled reload card and a [complete edit timeline](restore-review.timeline.json). +It is settled X11 rendering evidence, not a latency or spontaneous-redraw test. +The context menu uses a native XTest right-click; other inputs use Qt events. +No window reaches the user's desktop. The uncut recording and logs stay locally. + +Both fresh real-data walkthroughs at `6cf2a4db` passed all **12 checkpoints**, exact +assignment/lineage/color checks, restore Undo/Redo, independent-parent and later-edit +preservation, save/reopen and unchanged source hashes: +[ordinary](restore-ordinary-capture.json) · [bounded](restore-bounded-capture.json). + +| Checkpoint | Ordinary | Bounded | +| --- | --- | --- | +| Later unrelated merge and MUA label | [Open](restore-ordinary-06-later-edits.png) | [Open](restore-bounded-06-later-edits.png) | +| Real parents in editable Merge Mode | [Open](restore-ordinary-07-restored-parents.png) | [Open](restore-bounded-07-restored-parents.png) | +| Excluded parent and added candidate | [Open](restore-ordinary-10-new-combination.png) | [Open](restore-bounded-10-new-combination.png) | +| Revised curation reopened | [Open](restore-ordinary-12-reopened.png) | [Open](restore-bounded-12-reopened.png) | + +[Full-source restoration report](restore-pipeline-report.md) at `e13906ac` verifies +**all 469,725,567 rows in each of two replays** (one/four workers) against an +independent original-label/raw-amplitude oracle. It exercises a nested merge +following an amplitude split, later unrelated merge/label, restore Undo/Redo, +exclusion/addition/remerge, save/reopen and reprepare. All **45 metadata fields** +(**31,590 cells**) match exactly; original inputs retain their hashes and stats. +[Exact scenario](restore-pipeline-scenario.json) · +[Final checks](restore-pipeline-final-checks.json) · +[Artifact provenance](restore-pipeline-artifact-provenance.json). +The later `2ff1b010` runtime change only refreshes bounded review UI immediately; +the new GUI captures and application regression cover it. + +Restoration persists across Save/reopen in the same dataset/package. It requires +recorded lineage and refuses a bounded restore if any parent has no retained +evidence. Historical merge restoration after a fresh preparation is unavailable; +already restored live children replay/reprepare normally. Arbitrary bounded +lasso/feature splitting remains outside this change. The converted fixture's +clock/exposure assumptions remain unverified; this is engineering evidence, +not a biological merge-quality or acquisition-timing claim. + +Local validation uses the separately proposed **PyQt5-sip 12.20.1** shutdown fix +([PR #1442](https://github.com/cortex-lab/phy/pull/1442)); this feature branch's +lockfile remains unchanged. The core suite passed **692 tests, 13 skipped**, and +the final application suite passed **813 tests, 6 skipped**, both with normal +exit. The application rerun covers the immediate review-status refresh. Lint, format checks, +published documentation checks and source/wheel builds pass. CI is excluded. + +Recreate the review cut from a fresh recording with: + +```bash +uv run --no-sync python tools/caption_capture_video.py NEW_BOUNDED_OUTPUT \ + --review-cut --review-seconds 58 +``` + +### Narration and reproduction + +The synthetic narration was generated locally using [Kyutai TTS](https://huggingface.co/kyutai/tts-1.6b-en_fr) +(CC BY 4.0 model weights, developed by Kyutai) and its published +[voice preset](https://huggingface.co/kyutai/tts-voices/tree/main/unmute-prod-website) +(CC0 for this voice, per the voice repository). Speech dependencies live in a +separate environment and do not change Phy's dependencies. + +The reviewed recording uses 11 complete approved sentences, with no internal +speech cuts or tempo changes and at least 0.48 seconds of silence between +sentences. Each placed sentence was verified sample-for-sample against its +approved WAV before whole-track loudness normalization. The AAC audio peaks at +-2.0 dB; the MP4 retains 1,737 video frames at 30 fps and has no full-frame black +interval of at least 0.2 seconds at the documented detection threshold. + +[Subtitles](restore-narration.srt) · [Audio placement](restore-narration-alignment.json) · +[Generation parameters and input hashes](restore-narration-generation.json) · +[Published artifact verification](restore-review.json). + +The earlier immediate-parent renderer and recipe are preserved at +[commit 1aab04a9](https://github.com/cortex-lab/phy/blob/1aab04a9dea015be28f86254ffa78641f8f40881/design/carl-feedback-captures/render-narrated-review.py). +The current renderer above follows the new recursive workflow instead. + +The remaining sections preserve earlier evidence and superseded workflows. + +## Historical read-only review (superseded) + +[Play the updated 30 fps video inline on PR #1428](https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782). +The 42.87-second, 1920×1200 recording uses H.264 at 30 fps (about 3.3 MB). +The review cut shows the integrated dark parent workspace, white IDs/counts beside +color swatches, and Back/Esc navigation. New merges preserve their pre-merge colors; +older merges without optional display hints use a deterministic fallback palette. +The recording uses a visible pointer, gold click rings, translucent keycaps over +the lower part of the window, and a nearby Ctrl badge for modified clicks. + +The review cut removes idle settling intervals and replaces the blank reload wait +with a labeled **Reload wait omitted** card. Retained interactions play at their +original speed. Its [timeline](integrated-review.timeline.json) records the edits +and maps all ten checkpoints; it is not a latency benchmark. The original uncut +recording and complete logs remain in the separate local validation workspace. +The native GitHub attachment avoids storing another video binary in Git. + +Both fresh real-data runs at `3d8b492e` passed assignment, metadata, dirty-state, +undo-history, exact dock-state/action restoration, color preservation, save/reopen +and unchanged-source checks. The ordinary union `[9,15,10,13]` deliberately tests +color continuity across a parent order that differs from numeric ID order. +[Ordinary report](ordinary-integrated-capture.json) · +[Bounded report](bounded-integrated-capture.json). + +| Current parent workspace | Screenshot | +| --- | --- | +| Ordinary, four parents | [Open](ordinary-integrated-parents.png) | +| Bounded, seven parents | [Open](bounded-integrated-parents.png) | + +The recorder defaults to 30 fps and uses an isolated Xvfb display. After recording +as described below, create the review cut with: + +```bash +uv run --no-sync python tools/caption_capture_video.py NEW_BOUNDED_OUTPUT \ + --review-cut --review-seconds 43 +``` + +The older recordings and screenshots below are preserved as historical evidence; +their detached parent window and footer treatment have been superseded. + +The artifacts use actual Qt/OpenGL screenshots and virtual-display recordings, +not generated UI mockups. The earlier videos below are uncut; the current PR +review video is explicitly edited as described above. The ordinary run used Carl's earlier Sway sorting +(4,143,311 spikes, 614 original units, 181,947 stored waveforms). The bounded run +used a fresh package from the converted AIND engineering fixture (469,725,567 +source spikes, 705 original units, 93 suggestions), retaining 1,486,361 evidence +spikes and 27,865 stored waveforms under the default 2M-spike / 512MiB caps. +The source fixtures were copied before curation; input-file hashes were +unchanged after each complete run. No windows or recordings reached the desktop. + +The converted AIND clock/exposure assumptions remain engineering assumptions; +these captures do not validate acquisition timing, rates or merge quality. +See [the source investigation](../aind-real-data-validation.md). + +## Recordings and checkpoints + +Scaled 4fps preview; the complete recordings below retain the original frames: + +![Bounded workflow preview](bounded-preview.gif) + +- [Ordinary recording, 51 seconds](ordinary-walkthrough.mp4) · [captions](ordinary-walkthrough.srt) +- [Bounded recording, 54 seconds](bounded-walkthrough.mp4) · [captions](bounded-walkthrough.srt) + +The MP4s contain optional English soft subtitles. Video packets are identical to +the original captures; only a subtitle track was added. The display was +1920×1200 at 12fps, Xvfb with software Mesa OpenGL. Renderer inventories and +[packet/dimension checks](artifact-validation.json) accompany the videos. +The recorder limits BLAS and software-renderer threads within its own process. +These videos are visual/state evidence, not interactive latency benchmarks. + +Each run exercised ten checkpoints: initial comparison, actual correlogram +right-click transfer, one suggestion, Ctrl-click addition/removal, explicit G +merge, context-menu Show parents, visible one-click return, undo, redo/save, +and reopen. Qt mouse/key events drive native widgets; this does not establish +physical input routing. Screenshot settlement pumps events and resizes the GUI, +so this does not prove spontaneous repaint correctness. + +The bounded run explicitly chooses evidence window 7 to show the selected units' +stored waveforms/features. Reopening initially selects window 0; the final +recording explicitly uses the **Inspect evidence window** dialog to select 7 +again. This is a user action, not automatic persistence of the inspected window. +The final amplitude plot consequently shows that window rather than the initial +all-windows overview. + +| Checkpoint | Ordinary | Bounded | +| --- | --- | --- | +| Ctrl-click combined suggestions | [Screenshot](ordinary-04-control-click-union.png) | [Screenshot](bounded-04-control-click-union.png) | +| Exact immediate parents | [Screenshot](ordinary-06-show-parents.png) | [Screenshot](bounded-06-show-parents.png) | +| Saved state reopened | [Screenshot](ordinary-10-reopened.png) | [Screenshot](bounded-10-reopened.png) | +| Correlogram row transferred | In video | [Screenshot](bounded-02-right-click-transfer.png) | +| Undo restores both suggestions | In video | [Screenshot](bounded-08-undo.png) | + +The ordinary union was `[9,15,10,13] → 614`; the bounded union was +`[40,44,48,49,50,51,53] → 705`. Selection alone changed neither assignments nor +reviews. Both selected reviews were accepted-modified by the explicit combined +merge. Parent inspection changed no assignments, metadata, dirty state or history. +Undo restored assignments, review records and the exact proposition workspace; +redo and save/reopen preserved the complete expected assignment vector and both +review records. All returned parent groups were exact after reopening. + +The images revealed two real UI defects that state-only tests missed: the generic +GUI toolbar started hidden, and a wrapped label could consume excessive header +height. Commits `f2102295` and `4a2345b2` fix visible/reachable return controls, +a compact untruncated legend, and a 2×2 scientific layout with correlogram priority. +Regression coverage checks visibility, actual click geometry and wrapping for +2, 7 and 16 parents at two window widths. + +The ordinary capture is at `40c5d2bd`; the final bounded capture is at +`ce019119`. Only the recorder's explicit reopen-window step differs between +those revisions; production runtime files are identical. Sanitized checkpoint +reports: [ordinary](ordinary-capture.json), [bounded](bounded-capture.json). +All twenty original PNGs and complete local logs remain in the separate validation +workspace; selected checkpoints are published here with both complete recordings. + +## Full-source replay and performance + +[The pipeline report](pipeline-report.md) covers independently verified assignments +for every one of the 469,725,567 source rows in **both** serial and four-worker +replays, following a combined SLAY merge and source-amplitude split. It also +covers byte-identical prepared/store/index payloads, all 140,240 waveform rows, +save/reopen, repreparation, exact counts, finite-amplitude counts and sums, labels, +review records, independent source inventories and output inode separation. + +[The matched baseline comparison](baseline-comparison.md) uses identical dependencies, +parameters and checkpoint with unmodified `3ee67e5` versus `40c5d2bd`: + +| Serial operation | Old PR head | Current | Observed result | +| --- | ---: | ---: | --- | +| Preparation | 88.42 s | 33.49 s | 2.64× faster | +| Full replay | 54.93 s | 54.99 s | Essentially unchanged | + +The separate one-versus-four-worker run found preparation 31.75 → 26.92s, +row snapshots 61.97 → 59.18s, indexes 67.46 → 102.65s, and replay 53.86 → 52.51s. +These are single warm-cache workstation observations with possible concurrent +validation work, not controlled causal estimates or predictions for Carl's newer +5.24-billion-spike recording. The default stays at one worker; more workers can +slow index construction on this layout. + +## Reproduction + +From a synced checkout, using the existing real fixture paths on your machine: + +```bash +uv run --no-sync python tools/capture_carl_feedback.py \ + --mode ordinary --dataset SWAY_SOURCE --output NEW_ORDINARY_OUTPUT +uv run --no-sync python tools/capture_carl_feedback.py \ + --mode bounded --dataset FRESH_BOUNDED_PACKAGE --output NEW_BOUNDED_OUTPUT +``` + +The recorder creates its own Xvfb server, configuration and copied dataset. +It needs Xvfb, GLX/Mesa, glxinfo and FFmpeg. Its bounded example expects the +specific AIND proposition groups named above. New output directories are required. +It mutates only its newly created working copy and checks source hashes afterward. + +A standalone verifier independently rechecked both full replay assignment arrays +without importing Phy's projection or journal implementation: + +```bash +uv run --no-sync python tools/verify_feedback_replay.py \ + --source CONVERTED_SOURCE --outputs REPLAY_ONE REPLAY_FOUR \ + --parents 40 44 48 49 50 51 53 --children 706 707 \ + --threshold -378.4182434082031 +``` + +It verified all rows, 700 active units, and child counts 1,691,273 / 1,597,610. + +## Historical local checks and test-process limitation + +The final application target passed **795 tests, 6 skipped**, with exit status zero. +Both final real GUI recording processes exited normally. All **15 focused parent +regressions** pass, including a canceled dirty-close prompt, blocked editing keys, +Back/Esc, exact layout/action/focus restoration, failure cleanup, saved color hints, +and historical fallback. Lint, formatting, documentation generation/checks and +source/wheel builds pass; the wheel includes the new workspace module. + +The core partition passed **682 tests, 13 skipped**, then the previously documented +intermittent native interpreter-shutdown fault recurred (exit 139, no Python frame). +Thus `make test-full` did **not** complete cleanly; the application target was run +separately. CI is excluded at the maintainer's request. Prior standard and debugger +core runs have exited normally; the cause remains unlocalized. This supports +further beta testing, not a claim that native shutdown is fixed or release +readiness is established. diff --git a/design/carl-feedback-captures/SHA256SUMS b/design/carl-feedback-captures/SHA256SUMS new file mode 100644 index 000000000..b68bc4a9b --- /dev/null +++ b/design/carl-feedback-captures/SHA256SUMS @@ -0,0 +1,13 @@ +1559d37c4474c3ed4b5f74392d32a825c1e8d6204d037657b0f6a0e12db57999 bounded-02-right-click-transfer.png +ef8b6e71f5da0a4c08e7d2449326cc7bf81daece8568599cf64f1fc4e7e10b70 bounded-04-control-click-union.png +c9d48f5a709620d288732cd94b1090c04192ba1cf854d1b24aa68caf38152cb1 bounded-06-show-parents.png +70c299d1e28c08b5311d68d5f238c38199314ac8a49f8187bfb8b64f9ba70156 bounded-08-undo.png +4d29c1b1ab3d86ab67e7b8c9a0d8bbc44455ef479cc95357b819aabc6ca8db6e bounded-10-reopened.png +20102d01ecdbdc305acab2384127222e49cb45ba78375f9c766f5fcb974bbf0b bounded-preview.gif +ff54bdc9c7177f8b59b9b8f8ebfa2269bc626f35afaea4ecda2fd1e77edaabc6 bounded-walkthrough.mp4 +885d6539d213ba12d6cdb42dc26d0c7b499f2971c5f3ffc428ef1d6ab9175b67 bounded-walkthrough.srt +2d7388fe4f6c5a388f72359b112b9ee5f0e7283847aeed838bd39d5d9895ed94 ordinary-04-control-click-union.png +66f69c1876e9049e810e086e457996b2a00e1acdb15c09dd5e0bb0298fd4919a ordinary-06-show-parents.png +0479c253f584b85f719ef9bbb26bbeacd1c98f84e31b6f82f323ae92f00a7f18 ordinary-10-reopened.png +fb03ec0bfd15ab60ce272d63784f1d30b75f78216a8eaf7e20f7f68f799a5064 ordinary-walkthrough.mp4 +b0dabcc3b19cb10ee2833c8b2bcac25be39e40f46351dc48ec1892f959992a04 ordinary-walkthrough.srt diff --git a/design/carl-feedback-captures/artifact-validation.json b/design/carl-feedback-captures/artifact-validation.json new file mode 100644 index 000000000..75d0694c7 --- /dev/null +++ b/design/carl-feedback-captures/artifact-validation.json @@ -0,0 +1,22 @@ +{ + "ordinary": { + "video_packets_unchanged": true, + "packet_digest": "MD5=02d6c216e2593fbc425833e1db82bd79", + "width": 1920, + "height": 1200, + "frames": 613, + "fps": "12/1", + "duration_seconds": 51.083333, + "soft_subtitles": true + }, + "bounded": { + "video_packets_unchanged": true, + "packet_digest": "MD5=b2a9ca06d5df80be702c712badc94bf6", + "width": 1920, + "height": 1200, + "frames": 647, + "fps": "12/1", + "duration_seconds": 53.917, + "soft_subtitles": true + } +} diff --git a/design/carl-feedback-captures/baseline-comparison.md b/design/carl-feedback-captures/baseline-comparison.md new file mode 100644 index 000000000..c2aa20b3c --- /dev/null +++ b/design/carl-feedback-captures/baseline-comparison.md @@ -0,0 +1,26 @@ +# Matched real-data baseline/current comparison + +Single-worker passes on the same converted Carl AIND overlay: 469,725,567 source +spikes, 8,000,000-spike / 3,000,000,000-byte evidence caps, 1,800-second bins, +100,000-row batches. Replay uses the identical committed combined-SLAY-merge and +threshold-split checkpoint. This is engineering validation; acquisition exposure +truth remains unestablished. + +| Operation | Baseline seconds | Current seconds | Observed ratio | Baseline RSS GiB | Current RSS GiB | +| --- | ---: | ---: | ---: | ---: | ---: | +| prepare | 88.42 | 33.49 | 2.64x | 15.16 | 15.16 | +| replay | 54.93 | 54.99 | 1.00x | 26.62 | 26.62 | + +The baseline is unmodified revision 3ee67e5 in a new isolated detached checkout. +Both processes assert their imported phy path and git revision and use the same +Python executable, NumPy and phylib versions. Exact revisions, dependency versions, +host load and individual logs are retained in comparison.json and case JSON files. +No GUI was launched by this comparison. Root GUI/media/application validation may +have run concurrently. These are single warm-cache observed ratios, not controlled +causal estimates; RSS includes mapped source/output pages. + +All prepared NumPy files and both replay assignment files matched the previously +independently verified current outputs byte for byte. An independent SHA-256 and +file-stat recheck confirmed all 134 original/overlay entries unchanged. The old +checkout and runtime code were not patched. The earlier pipeline report is retained +unchanged; this is a separate comparison. diff --git a/design/carl-feedback-captures/bounded-02-right-click-transfer.png b/design/carl-feedback-captures/bounded-02-right-click-transfer.png new file mode 100644 index 000000000..60bd61a4f Binary files /dev/null and b/design/carl-feedback-captures/bounded-02-right-click-transfer.png differ diff --git a/design/carl-feedback-captures/bounded-04-control-click-union.png b/design/carl-feedback-captures/bounded-04-control-click-union.png new file mode 100644 index 000000000..ab5b9bf7b Binary files /dev/null and b/design/carl-feedback-captures/bounded-04-control-click-union.png differ diff --git a/design/carl-feedback-captures/bounded-06-show-parents.png b/design/carl-feedback-captures/bounded-06-show-parents.png new file mode 100644 index 000000000..c3df982dd Binary files /dev/null and b/design/carl-feedback-captures/bounded-06-show-parents.png differ diff --git a/design/carl-feedback-captures/bounded-08-undo.png b/design/carl-feedback-captures/bounded-08-undo.png new file mode 100644 index 000000000..14f6aa213 Binary files /dev/null and b/design/carl-feedback-captures/bounded-08-undo.png differ diff --git a/design/carl-feedback-captures/bounded-10-reopened.png b/design/carl-feedback-captures/bounded-10-reopened.png new file mode 100644 index 000000000..3809c365e Binary files /dev/null and b/design/carl-feedback-captures/bounded-10-reopened.png differ diff --git a/design/carl-feedback-captures/bounded-capture.json b/design/carl-feedback-captures/bounded-capture.json new file mode 100644 index 000000000..032f8c120 --- /dev/null +++ b/design/carl-feedback-captures/bounded-capture.json @@ -0,0 +1,184 @@ +{ + "mode": "bounded", + "dataset": "Carl converted AIND bounded engineering fixture", + "capture_scope": "Settled real X11 pixels; Qt input events; not a spontaneous-redraw test", + "private_display": ":1", + "revision": "ce01911985a7360b105e444380a875dcd4d0d014", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 6.772, + "selected": [ + 40, + 48, + 44 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 9.846, + "selected": [ + 40, + 44, + 48 + ], + "transferred": 48 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 12.938, + "selected": [ + 40, + 44, + 48 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 16.455, + "selected": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "selected_keys": [ + "merge:f27398ae0f9960b6", + "merge:3097c4197d91ff70" + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 24.383, + "selected": [ + 705 + ], + "merged": 705 + }, + { + "name": "06-show-parents", + "title": "Exact immediate merge parents \u2014 read only", + "seconds": 30.666, + "selected": [ + 705 + ], + "parents": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "07-return", + "title": "One click returns to the merged unit without editing", + "seconds": 33.494, + "selected": [ + 705 + ] + }, + { + "name": "08-undo", + "title": "Undo restores assignments, both decisions and the comparison workspace", + "seconds": 37.655, + "selected": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "09-redo-save", + "title": "Redo and Save retain the combined merge", + "seconds": 42.776, + "selected": [ + 705 + ] + }, + { + "name": "10-reopened", + "title": "Reopened: saved curation verified; evidence window explicitly reselected", + "seconds": 53.36, + "selected": [ + 705 + ] + } + ], + "label": "Real earlier Carl dataset; engineering validation", + "propositions": [ + { + "key": "merge:f27398ae0f9960b6", + "unit_ids": [ + 40, + 44, + 48 + ] + }, + { + "key": "merge:3097c4197d91ff70", + "unit_ids": [ + 49, + 50, + 51, + 53 + ] + } + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "evidence_window": 7, + "window_waveforms_by_unit": { + "40": 1, + "44": 2, + "48": 2, + "49": 2, + "50": 2, + "51": 1, + "53": 2 + }, + "merged": 705, + "assigned_spikes": 10681, + "reopened_initial_evidence_window": 0, + "reopened_selected_evidence_window": 7, + "reopen_window_action": "Explicit Inspect evidence window dialog; not automatic restoration", + "source_unchanged": true, + "success": true, + "published_screenshots": [ + "bounded-02-right-click-transfer.png", + "bounded-04-control-click-union.png", + "bounded-06-show-parents.png", + "bounded-08-undo.png", + "bounded-10-reopened.png" + ] +} diff --git a/design/carl-feedback-captures/bounded-integrated-capture.json b/design/carl-feedback-captures/bounded-integrated-capture.json new file mode 100644 index 000000000..7e8adc36a --- /dev/null +++ b/design/carl-feedback-captures/bounded-integrated-capture.json @@ -0,0 +1,328 @@ +{ + "mode": "bounded", + "dataset": "Carl converted AIND bounded engineering fixture", + "capture_scope": "Settled real X11 pixels; Qt input events; not a spontaneous-redraw test", + "revision": "3d8b492e3e88417d40347916cdf65a1ab8a53229", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 7.429, + "selected": [ + 40, + 48, + 44 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 10.41, + "selected": [ + 40, + 44, + 48 + ], + "transferred": 48 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 13.184, + "selected": [ + 40, + 44, + 48 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 16.519, + "selected": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "selected_keys": [ + "merge:f27398ae0f9960b6", + "merge:3097c4197d91ff70" + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 24.41, + "selected": [ + 705 + ], + "merged": 705 + }, + { + "name": "06-show-parents", + "title": "Exact immediate merge parents \u2014 read only", + "seconds": 29.853, + "selected": [ + 705 + ], + "parents": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "07-return", + "title": "One click returns to the merged unit without editing", + "seconds": 32.523, + "selected": [ + 705 + ] + }, + { + "name": "08-undo", + "title": "Undo restores assignments, both decisions and the comparison workspace", + "seconds": 35.877, + "selected": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "09-redo-save", + "title": "Redo and Save retain the combined merge", + "seconds": 40.185, + "selected": [ + 705 + ] + }, + { + "name": "10-reopened", + "title": "Reopened: saved curation verified; evidence window explicitly reselected", + "seconds": 50.804, + "selected": [ + 705 + ] + } + ], + "input_events": [ + { + "seconds": 0.215, + "label": "Left click: Cluster 40", + "point": [ + 28, + 314 + ], + "click_seconds": 0.847 + }, + { + "seconds": 2.516, + "label": "Ctrl + Left click: Cluster 44", + "point": [ + 28, + 314 + ], + "click_seconds": 3.145 + }, + { + "seconds": 4.566, + "label": "Ctrl + Left click: Cluster 48", + "point": [ + 28, + 178 + ], + "click_seconds": 5.2 + }, + { + "seconds": 7.429, + "label": "Right click: Transfer correlogram row", + "point": [ + 550, + 206 + ], + "click_seconds": 8.068 + }, + { + "seconds": 10.612, + "label": "Left click: P5 \u00b7 40, 44, 48", + "point": [ + 95, + 971 + ], + "click_seconds": 11.247 + }, + { + "seconds": 13.386, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 14.02 + }, + { + "seconds": 16.72, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 17.354 + }, + { + "seconds": 18.845, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 19.475 + }, + { + "seconds": 21.233, + "label": "G: merge the combined suggestions", + "key_seconds": 21.484, + "key_released_seconds": 22.462 + }, + { + "seconds": 24.623, + "label": "Right click: merged unit context menu" + }, + { + "seconds": 25.81, + "label": "Left click: Show parents", + "point": [ + 103, + 191 + ], + "click_seconds": 26.444 + }, + { + "seconds": 29.853, + "label": "Left click: Back to merged unit", + "point": [ + 313, + 103 + ], + "click_seconds": 30.488 + }, + { + "seconds": 32.523, + "label": "Ctrl + Z: undo", + "key_seconds": 32.773, + "key_released_seconds": 33.886 + }, + { + "seconds": 35.877, + "label": "Ctrl + Shift + Z: redo", + "key_seconds": 36.128, + "key_released_seconds": 36.935 + }, + { + "seconds": 37.91, + "label": "Ctrl + S: save", + "key_seconds": 38.161, + "key_released_seconds": 38.439 + }, + { + "seconds": 40.187, + "label": "Reopen the saved working copy" + }, + { + "seconds": 47.035, + "label": "View menu: Inspect evidence window" + }, + { + "seconds": 47.837, + "label": "Type evidence window index, then Enter" + }, + { + "seconds": 48.607, + "label": "Enter: inspect evidence window 7", + "key_seconds": 48.858, + "key_released_seconds": 48.859 + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "propositions": [ + { + "key": "merge:f27398ae0f9960b6", + "unit_ids": [ + 40, + 44, + 48 + ] + }, + { + "key": "merge:3097c4197d91ff70", + "unit_ids": [ + 49, + 50, + 51, + 53 + ] + } + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "evidence_window": 7, + "window_waveforms_by_unit": { + "40": 1, + "44": 2, + "48": 2, + "49": 2, + "50": 2, + "51": 1, + "53": 2 + }, + "premerge_colors": { + "40": 0, + "44": 1, + "48": 2, + "49": 3, + "50": 4, + "51": 5, + "53": 6 + }, + "parent_colors_preserved": true, + "parent_workspace_restored": true, + "merged": 705, + "assigned_spikes": 10681, + "reopened_initial_evidence_window": 0, + "reopened_selected_evidence_window": 7, + "reopen_window_action": "Explicit Inspect evidence window dialog; not automatic restoration", + "reopened_parent_colors_preserved": true, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/bounded-integrated-parents.png b/design/carl-feedback-captures/bounded-integrated-parents.png new file mode 100644 index 000000000..957f04f1b Binary files /dev/null and b/design/carl-feedback-captures/bounded-integrated-parents.png differ diff --git a/design/carl-feedback-captures/bounded-preview.gif b/design/carl-feedback-captures/bounded-preview.gif new file mode 100644 index 000000000..1fb5b0965 Binary files /dev/null and b/design/carl-feedback-captures/bounded-preview.gif differ diff --git a/design/carl-feedback-captures/bounded-renderer.txt b/design/carl-feedback-captures/bounded-renderer.txt new file mode 100644 index 000000000..0d5050bff --- /dev/null +++ b/design/carl-feedback-captures/bounded-renderer.txt @@ -0,0 +1,40 @@ +name of display: :1 +display: :1 screen: 0 +direct rendering: Yes +Extended renderer info (GLX_MESA_query_renderer): + Vendor: Mesa (0xffffffff) + Device: llvmpipe (LLVM 20.1.2, 256 bits) (0xffffffff) + Version: 25.2.8 + Accelerated: no + Video memory: 128458MB + Unified memory: yes + Preferred profile: core (0x1) + Max core profile version: 4.5 + Max compat profile version: 4.5 + Max GLES1 profile version: 1.1 + Max GLES[23] profile version: 3.2 +Memory info (GL_ATI_meminfo): + VBO free memory - total: 577418 MB, largest block: 577418 MB + VBO free aux. memory - total: 109153 MB, largest block: 109153 MB + Texture free memory - total: 577418 MB, largest block: 577418 MB + Texture free aux. memory - total: 109153 MB, largest block: 109153 MB + Renderbuffer free memory - total: 577418 MB, largest block: 577418 MB + Renderbuffer free aux. memory - total: 109153 MB, largest block: 109153 MB +Memory info (GL_NVX_gpu_memory_info): + Dedicated video memory: 559428 MB + Total available memory: 687887 MB + Currently available dedicated video memory: 577418 MB +OpenGL vendor string: Mesa +OpenGL renderer string: llvmpipe (LLVM 20.1.2, 256 bits) +OpenGL core profile version string: 4.5 (Core Profile) Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL core profile shading language version string: 4.50 +OpenGL core profile context flags: (none) +OpenGL core profile profile mask: core profile + +OpenGL version string: 4.5 (Compatibility Profile) Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL shading language version string: 4.50 +OpenGL context flags: (none) +OpenGL profile mask: compatibility profile + +OpenGL ES profile version string: OpenGL ES 3.2 Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20 diff --git a/design/carl-feedback-captures/bounded-walkthrough.mp4 b/design/carl-feedback-captures/bounded-walkthrough.mp4 new file mode 100644 index 000000000..f9d60f15a Binary files /dev/null and b/design/carl-feedback-captures/bounded-walkthrough.mp4 differ diff --git a/design/carl-feedback-captures/bounded-walkthrough.srt b/design/carl-feedback-captures/bounded-walkthrough.srt new file mode 100644 index 000000000..231d0e591 --- /dev/null +++ b/design/carl-feedback-captures/bounded-walkthrough.srt @@ -0,0 +1,39 @@ +1 +00:00:00,000 --> 00:00:06,772 +Bounded real-data walkthrough: Real-data cluster comparison before the new workflow + +2 +00:00:06,772 --> 00:00:09,846 +Bounded real-data walkthrough: Right-click transfers the correlogram row to Similarity + +3 +00:00:09,846 --> 00:00:12,938 +Bounded real-data walkthrough: One SLAY suggestion in the Merge workspace + +4 +00:00:12,938 --> 00:00:16,455 +Bounded real-data walkthrough: Ctrl-click combines two suggestions; assignments unchanged + +5 +00:00:16,455 --> 00:00:24,383 +Bounded real-data walkthrough: G commits one merge and both suggestion decisions + +6 +00:00:24,383 --> 00:00:30,666 +Bounded real-data walkthrough: Exact immediate merge parents — read only + +7 +00:00:30,666 --> 00:00:33,494 +Bounded real-data walkthrough: One click returns to the merged unit without editing + +8 +00:00:33,494 --> 00:00:37,655 +Bounded real-data walkthrough: Undo restores assignments, both decisions and the comparison workspace + +9 +00:00:37,655 --> 00:00:42,776 +Bounded real-data walkthrough: Redo and Save retain the combined merge + +10 +00:00:42,776 --> 00:00:53,917 +Bounded real-data walkthrough: Reopened: saved curation verified; evidence window explicitly reselected diff --git a/design/carl-feedback-captures/independent-replay.json b/design/carl-feedback-captures/independent-replay.json new file mode 100644 index 000000000..daea8d945 --- /dev/null +++ b/design/carl-feedback-captures/independent-replay.json @@ -0,0 +1,10 @@ +{ + "rows_checked_per_output": 469725567, + "outputs": 2, + "assignments_exact": true, + "active_units": 700, + "children": { + "706": 1691273, + "707": 1597610 + } +} diff --git a/design/carl-feedback-captures/integrated-review.timeline.json b/design/carl-feedback-captures/integrated-review.timeline.json new file mode 100644 index 000000000..5f24a76da --- /dev/null +++ b/design/carl-feedback-captures/integrated-review.timeline.json @@ -0,0 +1,348 @@ +{ + "source": "walkthrough.mp4 (uncut validation recording retained locally)", + "output": "native GitHub attachment; see review-integrated.json", + "source_fps": "30/1", + "source_duration_seconds": 51.233333, + "output_duration_seconds": 42.86666666666666, + "review_cut": true, + "timeline_note": "Original-speed source frames concatenated; idle dwell and reopen wait omitted. Not a latency benchmark.", + "settle_tail_seconds": 1.558999999999998, + "items": [ + { + "kind": "source", + "source_start_frame": 0, + "source_end_frame": 210, + "source_start": 0.0, + "source_end": 7.0, + "event_indices": [ + 0, + 1, + 2 + ], + "output_start": 0.0, + "output_end": 7.0 + }, + { + "kind": "source", + "source_start_frame": 214, + "source_end_frame": 296, + "source_start": 7.133333333333334, + "source_end": 9.866666666666667, + "event_indices": [ + 3 + ], + "output_start": 7.0, + "output_end": 9.733333333333334 + }, + { + "kind": "source", + "source_start_frame": 303, + "source_end_frame": 475, + "source_start": 10.1, + "source_end": 15.833333333333334, + "event_indices": [ + 4, + 5 + ], + "output_start": 9.733333333333334, + "output_end": 15.466666666666669 + }, + { + "kind": "source", + "source_start_frame": 487, + "source_end_frame": 848, + "source_start": 16.233333333333334, + "source_end": 28.266666666666666, + "event_indices": [ + 6, + 7, + 8, + 9, + 10 + ], + "output_start": 15.466666666666669, + "output_end": 27.5 + }, + { + "kind": "source", + "source_start_frame": 887, + "source_end_frame": 1063, + "source_start": 29.566666666666666, + "source_end": 35.43333333333333, + "event_indices": [ + 11, + 12 + ], + "output_start": 27.5, + "output_end": 33.36666666666667 + }, + { + "kind": "source", + "source_start_frame": 1067, + "source_end_frame": 1200, + "source_start": 35.56666666666667, + "source_end": 40.0, + "event_indices": [ + 13, + 14 + ], + "output_start": 33.36666666666667, + "output_end": 37.8 + }, + { + "kind": "reload_card", + "source_frame": 1205, + "source_time": 40.166666666666664, + "duration_frames": 24, + "duration": 0.8, + "event_indices": [ + 15 + ], + "label": "REOPENING SAVED SESSION \u2014 reload wait omitted", + "output_start": 37.8, + "output_end": 38.599999999999994 + }, + { + "kind": "source", + "source_start_frame": 1405, + "source_end_frame": 1533, + "source_start": 46.833333333333336, + "source_end": 51.1, + "event_indices": [ + 16, + 17, + 18 + ], + "output_start": 38.599999999999994, + "output_end": 42.86666666666666 + } + ], + "omitted_source_ranges": [ + { + "source_start": 7.0, + "source_end": 7.133333333333334, + "duration_seconds": 0.13333333333333375, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 9.866666666666667, + "source_end": 10.1, + "duration_seconds": 0.2333333333333325, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 15.833333333333334, + "source_end": 16.233333333333334, + "duration_seconds": 0.40000000000000036, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 28.266666666666666, + "source_end": 29.566666666666666, + "duration_seconds": 1.3000000000000007, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 35.43333333333333, + "source_end": 35.56666666666667, + "duration_seconds": 0.13333333333333997, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 40.0, + "source_end": 40.166666666666664, + "duration_seconds": 0.1666666666666643, + "reason": "reopen wait replaced by reload card" + }, + { + "source_start": 40.96666666666666, + "source_end": 46.833333333333336, + "duration_seconds": 5.866666666666674, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 51.1, + "source_end": 51.233333, + "duration_seconds": 0.13333300000000037, + "reason": "trailing settled dwell trimmed" + } + ], + "events": [ + { + "index": 0, + "label": "Left click: Cluster 40", + "source_seconds": 0.215, + "output_seconds": 0.215 + }, + { + "index": 1, + "label": "Ctrl + Left click: Cluster 44", + "source_seconds": 2.516, + "output_seconds": 2.516 + }, + { + "index": 2, + "label": "Ctrl + Left click: Cluster 48", + "source_seconds": 4.566, + "output_seconds": 4.566 + }, + { + "index": 3, + "label": "Right click: Transfer correlogram row", + "source_seconds": 7.429, + "output_seconds": 7.2956666666666665 + }, + { + "index": 4, + "label": "Left click: P5 \u00b7 40, 44, 48", + "source_seconds": 10.612, + "output_seconds": 10.245333333333335 + }, + { + "index": 5, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 13.386, + "output_seconds": 13.019333333333334 + }, + { + "index": 6, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 16.72, + "output_seconds": 15.953333333333333 + }, + { + "index": 7, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 18.845, + "output_seconds": 18.078333333333333 + }, + { + "index": 8, + "label": "G: merge the combined suggestions", + "source_seconds": 21.233, + "output_seconds": 20.466333333333335 + }, + { + "index": 9, + "label": "Right click: merged unit context menu", + "source_seconds": 24.623, + "output_seconds": 23.856333333333335 + }, + { + "index": 10, + "label": "Left click: Show parents", + "source_seconds": 25.81, + "output_seconds": 25.043333333333333 + }, + { + "index": 11, + "label": "Left click: Back to merged unit", + "source_seconds": 29.853, + "output_seconds": 27.786333333333335 + }, + { + "index": 12, + "label": "Ctrl + Z: undo", + "source_seconds": 32.523, + "output_seconds": 30.456333333333337 + }, + { + "index": 13, + "label": "Ctrl + Shift + Z: redo", + "source_seconds": 35.877, + "output_seconds": 33.677 + }, + { + "index": 14, + "label": "Ctrl + S: save", + "source_seconds": 37.91, + "output_seconds": 35.709999999999994 + }, + { + "index": 15, + "label": "Reopen the saved working copy", + "source_seconds": 40.187, + "output_seconds": 37.8 + }, + { + "index": 16, + "label": "View menu: Inspect evidence window", + "source_seconds": 47.035, + "output_seconds": 38.801666666666655 + }, + { + "index": 17, + "label": "Type evidence window index, then Enter", + "source_seconds": 47.837, + "output_seconds": 39.60366666666666 + }, + { + "index": 18, + "label": "Enter: inspect evidence window 7", + "source_seconds": 48.607, + "output_seconds": 40.37366666666666 + } + ], + "checkpoints": [ + { + "name": "01-initial", + "source_seconds": 7.429, + "output_seconds": 7.2956666666666665, + "captured": true + }, + { + "name": "02-right-click-transfer", + "source_seconds": 10.41, + "output_seconds": 10.043333333333335, + "captured": true + }, + { + "name": "03-single-suggestion", + "source_seconds": 13.184, + "output_seconds": 12.817333333333334, + "captured": true + }, + { + "name": "04-control-click-union", + "source_seconds": 16.519, + "output_seconds": 15.752333333333333, + "captured": true + }, + { + "name": "05-merged", + "source_seconds": 24.41, + "output_seconds": 23.643333333333334, + "captured": true + }, + { + "name": "06-show-parents", + "source_seconds": 29.853, + "output_seconds": 27.786333333333335, + "captured": true + }, + { + "name": "07-return", + "source_seconds": 32.523, + "output_seconds": 30.456333333333337, + "captured": true + }, + { + "name": "08-undo", + "source_seconds": 35.877, + "output_seconds": 33.677, + "captured": true + }, + { + "name": "09-redo-save", + "source_seconds": 40.185, + "output_seconds": 37.8, + "captured": true + }, + { + "name": "10-reopened", + "source_seconds": 50.804, + "output_seconds": 42.57066666666666, + "captured": true + } + ] +} diff --git a/design/carl-feedback-captures/ordinary-04-control-click-union.png b/design/carl-feedback-captures/ordinary-04-control-click-union.png new file mode 100644 index 000000000..0b88726f5 Binary files /dev/null and b/design/carl-feedback-captures/ordinary-04-control-click-union.png differ diff --git a/design/carl-feedback-captures/ordinary-06-show-parents.png b/design/carl-feedback-captures/ordinary-06-show-parents.png new file mode 100644 index 000000000..fcd522998 Binary files /dev/null and b/design/carl-feedback-captures/ordinary-06-show-parents.png differ diff --git a/design/carl-feedback-captures/ordinary-10-reopened.png b/design/carl-feedback-captures/ordinary-10-reopened.png new file mode 100644 index 000000000..b3e5eb839 Binary files /dev/null and b/design/carl-feedback-captures/ordinary-10-reopened.png differ diff --git a/design/carl-feedback-captures/ordinary-capture.json b/design/carl-feedback-captures/ordinary-capture.json new file mode 100644 index 000000000..e326a4896 --- /dev/null +++ b/design/carl-feedback-captures/ordinary-capture.json @@ -0,0 +1,148 @@ +{ + "mode": "ordinary", + "dataset": "Carl Sway real sorting", + "capture_scope": "Settled real X11 pixels; Qt input events; not a spontaneous-redraw test", + "private_display": ":2", + "revision": "40c5d2bd3202b0cc8807a5f01e53a5d437dffeef", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 5.596, + "selected": [ + 9, + 15 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 8.237, + "selected": [ + 9, + 15 + ], + "transferred": 15 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 11.101, + "selected": [ + 9, + 15 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 15.178, + "selected": [ + 9, + 15, + 10, + 13 + ], + "selected_keys": [ + "merge:f79990b25de62781", + "merge:58e6ea5a4536166f" + ], + "union": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 22.491, + "selected": [ + 614 + ], + "merged": 614 + }, + { + "name": "06-show-parents", + "title": "Exact immediate merge parents \u2014 read only", + "seconds": 28.997, + "selected": [ + 614 + ], + "parents": [ + 9, + 10, + 13, + 15 + ] + }, + { + "name": "07-return", + "title": "One click returns to the merged unit without editing", + "seconds": 31.821, + "selected": [ + 614 + ] + }, + { + "name": "08-undo", + "title": "Undo restores assignments, both decisions and the comparison workspace", + "seconds": 35.291, + "selected": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "09-redo-save", + "title": "Redo and Save retain the combined merge", + "seconds": 39.802, + "selected": [ + 614 + ] + }, + { + "name": "10-reopened", + "title": "Reopened: saved assignments, review decisions and parent history verified", + "seconds": 46.918, + "selected": [ + 614 + ] + } + ], + "label": "Real earlier Carl dataset; engineering validation", + "propositions": [ + { + "key": "merge:f79990b25de62781", + "unit_ids": [ + 9, + 15 + ] + }, + { + "key": "merge:58e6ea5a4536166f", + "unit_ids": [ + 10, + 13 + ] + } + ], + "union": [ + 9, + 15, + 10, + 13 + ], + "merged": 614, + "assigned_spikes": 31905, + "source_unchanged": true, + "success": true, + "published_screenshots": [ + "ordinary-04-control-click-union.png", + "ordinary-06-show-parents.png", + "ordinary-10-reopened.png" + ] +} diff --git a/design/carl-feedback-captures/ordinary-integrated-capture.json b/design/carl-feedback-captures/ordinary-integrated-capture.json new file mode 100644 index 000000000..f7add7a40 --- /dev/null +++ b/design/carl-feedback-captures/ordinary-integrated-capture.json @@ -0,0 +1,268 @@ +{ + "mode": "ordinary", + "dataset": "Carl Sway ordinary sorting", + "capture_scope": "Settled real X11 pixels; Qt input events; not a spontaneous-redraw test", + "revision": "3d8b492e3e88417d40347916cdf65a1ab8a53229", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 5.748, + "selected": [ + 9, + 15 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 8.253, + "selected": [ + 9, + 15 + ], + "transferred": 15 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 10.968, + "selected": [ + 9, + 15 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 14.634, + "selected": [ + 9, + 15, + 10, + 13 + ], + "selected_keys": [ + "merge:f79990b25de62781", + "merge:58e6ea5a4536166f" + ], + "union": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 21.91, + "selected": [ + 614 + ], + "merged": 614 + }, + { + "name": "06-show-parents", + "title": "Exact immediate merge parents \u2014 read only", + "seconds": 27.661, + "selected": [ + 614 + ], + "parents": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "07-return", + "title": "One click returns to the merged unit without editing", + "seconds": 30.353, + "selected": [ + 614 + ] + }, + { + "name": "08-undo", + "title": "Undo restores assignments, both decisions and the comparison workspace", + "seconds": 33.11, + "selected": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "09-redo-save", + "title": "Redo and Save retain the combined merge", + "seconds": 37.023, + "selected": [ + 614 + ] + }, + { + "name": "10-reopened", + "title": "Reopened: saved assignments, review decisions and parent history verified", + "seconds": 42.879, + "selected": [ + 614 + ] + } + ], + "input_events": [ + { + "seconds": 0.221, + "label": "Left click: Cluster 9", + "point": [ + 229, + 416 + ], + "click_seconds": 0.866 + }, + { + "seconds": 2.62, + "label": "Ctrl + Left click: Cluster 15", + "point": [ + 229, + 416 + ], + "click_seconds": 3.25 + }, + { + "seconds": 5.748, + "label": "Right click: Transfer correlogram row", + "point": [ + 1020, + 448 + ], + "click_seconds": 6.388 + }, + { + "seconds": 8.455, + "label": "Left click: P1 \u00b7 9, 15", + "point": [ + 95, + 925 + ], + "click_seconds": 9.103 + }, + { + "seconds": 11.169, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 11.804 + }, + { + "seconds": 14.836, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 15.467 + }, + { + "seconds": 16.911, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 17.542 + }, + { + "seconds": 19.301, + "label": "G: merge the combined suggestions", + "key_seconds": 19.552, + "key_released_seconds": 20.111 + }, + { + "seconds": 22.123, + "label": "Right click: merged unit context menu" + }, + { + "seconds": 23.308, + "label": "Left click: Show parents", + "point": [ + 103, + 191 + ], + "click_seconds": 23.943 + }, + { + "seconds": 27.662, + "label": "Left click: Back to merged unit", + "point": [ + 313, + 103 + ], + "click_seconds": 28.298 + }, + { + "seconds": 30.354, + "label": "Ctrl + Z: undo", + "key_seconds": 30.604, + "key_released_seconds": 31.342 + }, + { + "seconds": 33.11, + "label": "Ctrl + Shift + Z: redo", + "key_seconds": 33.361, + "key_released_seconds": 33.658 + }, + { + "seconds": 34.492, + "label": "Ctrl + S: save", + "key_seconds": 34.743, + "key_released_seconds": 35.278 + }, + { + "seconds": 37.026, + "label": "Reopen the saved working copy" + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "propositions": [ + { + "key": "merge:f79990b25de62781", + "unit_ids": [ + 9, + 15 + ] + }, + { + "key": "merge:58e6ea5a4536166f", + "unit_ids": [ + 10, + 13 + ] + } + ], + "union": [ + 9, + 15, + 10, + 13 + ], + "premerge_colors": { + "9": 0, + "15": 1, + "10": 2, + "13": 3 + }, + "parent_colors_preserved": true, + "parent_workspace_restored": true, + "merged": 614, + "assigned_spikes": 31905, + "reopened_parent_colors_preserved": true, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/ordinary-integrated-parents.png b/design/carl-feedback-captures/ordinary-integrated-parents.png new file mode 100644 index 000000000..574abea73 Binary files /dev/null and b/design/carl-feedback-captures/ordinary-integrated-parents.png differ diff --git a/design/carl-feedback-captures/ordinary-renderer.txt b/design/carl-feedback-captures/ordinary-renderer.txt new file mode 100644 index 000000000..c749d1280 --- /dev/null +++ b/design/carl-feedback-captures/ordinary-renderer.txt @@ -0,0 +1,40 @@ +name of display: :2 +display: :2 screen: 0 +direct rendering: Yes +Extended renderer info (GLX_MESA_query_renderer): + Vendor: Mesa (0xffffffff) + Device: llvmpipe (LLVM 20.1.2, 256 bits) (0xffffffff) + Version: 25.2.8 + Accelerated: no + Video memory: 128458MB + Unified memory: yes + Preferred profile: core (0x1) + Max core profile version: 4.5 + Max compat profile version: 4.5 + Max GLES1 profile version: 1.1 + Max GLES[23] profile version: 3.2 +Memory info (GL_ATI_meminfo): + VBO free memory - total: 0 MB, largest block: 0 MB + VBO free aux. memory - total: 108689 MB, largest block: 108689 MB + Texture free memory - total: 0 MB, largest block: 0 MB + Texture free aux. memory - total: 108689 MB, largest block: 108689 MB + Renderbuffer free memory - total: 0 MB, largest block: 0 MB + Renderbuffer free aux. memory - total: 108690 MB, largest block: 108690 MB +Memory info (GL_NVX_gpu_memory_info): + Dedicated video memory: 0 MB + Total available memory: 128458 MB + Currently available dedicated video memory: 0 MB +OpenGL vendor string: Mesa +OpenGL renderer string: llvmpipe (LLVM 20.1.2, 256 bits) +OpenGL core profile version string: 4.5 (Core Profile) Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL core profile shading language version string: 4.50 +OpenGL core profile context flags: (none) +OpenGL core profile profile mask: core profile + +OpenGL version string: 4.5 (Compatibility Profile) Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL shading language version string: 4.50 +OpenGL context flags: (none) +OpenGL profile mask: compatibility profile + +OpenGL ES profile version string: OpenGL ES 3.2 Mesa 25.2.8-0ubuntu0.24.04.4 +OpenGL ES profile shading language version string: OpenGL ES GLSL ES 3.20 diff --git a/design/carl-feedback-captures/ordinary-walkthrough.mp4 b/design/carl-feedback-captures/ordinary-walkthrough.mp4 new file mode 100644 index 000000000..b3b64acb8 Binary files /dev/null and b/design/carl-feedback-captures/ordinary-walkthrough.mp4 differ diff --git a/design/carl-feedback-captures/ordinary-walkthrough.srt b/design/carl-feedback-captures/ordinary-walkthrough.srt new file mode 100644 index 000000000..20f905ec1 --- /dev/null +++ b/design/carl-feedback-captures/ordinary-walkthrough.srt @@ -0,0 +1,39 @@ +1 +00:00:00,000 --> 00:00:05,596 +Ordinary real-data walkthrough: Real-data cluster comparison before the new workflow + +2 +00:00:05,596 --> 00:00:08,237 +Ordinary real-data walkthrough: Right-click transfers the correlogram row to Similarity + +3 +00:00:08,237 --> 00:00:11,101 +Ordinary real-data walkthrough: One SLAY suggestion in the Merge workspace + +4 +00:00:11,101 --> 00:00:15,178 +Ordinary real-data walkthrough: Ctrl-click combines two suggestions; assignments unchanged + +5 +00:00:15,178 --> 00:00:22,491 +Ordinary real-data walkthrough: G commits one merge and both suggestion decisions + +6 +00:00:22,491 --> 00:00:28,997 +Ordinary real-data walkthrough: Exact immediate merge parents — read only + +7 +00:00:28,997 --> 00:00:31,821 +Ordinary real-data walkthrough: One click returns to the merged unit without editing + +8 +00:00:31,821 --> 00:00:35,291 +Ordinary real-data walkthrough: Undo restores assignments, both decisions and the comparison workspace + +9 +00:00:35,291 --> 00:00:39,802 +Ordinary real-data walkthrough: Redo and Save retain the combined merge + +10 +00:00:39,802 --> 00:00:51,083 +Ordinary real-data walkthrough: Reopened: saved assignments, review decisions and parent history verified diff --git a/design/carl-feedback-captures/pipeline-report.md b/design/carl-feedback-captures/pipeline-report.md new file mode 100644 index 000000000..e242952f9 --- /dev/null +++ b/design/carl-feedback-captures/pipeline-report.md @@ -0,0 +1,75 @@ +# Real Carl feedback pipeline validation — 17 November 2026 + +PASS on code `9e7607059fdd4271e733acfc0d42bcc957728958`. This is an engineering validation of Carl's +converted AIND overlay, not acceptance of the original exporter or acquisition +exposure policy. The unmodified export's clock/exposure problem remains outside +this result. + +The source has 469,725,567 spikes, 705 original units, 140,240 waveform rows and +93 SLAY suggestions. Both runs used 8,000,000 evidence-spike / 3,000,000,000-byte +caps, 1,800-second bins, 100,000 requested source rows per batch, 32 MiB total +row-packing/write allowance and 64 MiB total index memory allowance. Both retained +7,298,318 evidence rows and all 140,240 waveform rows. + +| Operation | 1 worker seconds | 4 workers seconds | 1 worker peak RSS GiB | 4 workers peak RSS GiB | +| --- | ---: | ---: | ---: | ---: | +| Preparation | 31.75 | 26.92 | 15.16 | 15.18 | +| Summary rows | 61.97 | 59.17 | 0.23 | 0.26 | +| Amplitude index | 67.46 | 102.65 | 0.24 | 0.27 | +| Full replay | 53.86 | 52.51 | 26.67 | 26.59 | + +These are single warm-cache sequential worker comparisons while independent GUI +validation ran concurrently. A 10.5-second independent evidence/exposure check +also overlapped the four-worker index. They are observed integration costs, not +controlled throughput benchmarks. RSS includes resident mapped source/output +pages and is not a scratch-budget measurement. Detailed callback-stage timings +and stage RSS are in `result.json`; the final callback stage can also include +publication and cleanup work. Four workers were slower for this real index +layout; keeping one worker as the default is supported by this run. + +The prepared packages' 23 NumPy files, unit/count catalogs and producer document +matched exactly between worker counts. Row-store payloads and all three index +payloads plus their packed Merkle hash files were byte-identical. Independent +source-row comparison checked every bounded spike field, all waveform values, +channels and mapped center coordinates in both packages. Bin edges matched an +independent construction; exposure agreed within 1e-10 seconds against the +**declared test intervals only**. + +A copied package exercised the ordinary controller's new multi-suggestion path: +`_activate_merge_propositions(view, (keyA, keyB))`, then the ordinary merge action. +The groups `[40,44,48]` and `[49,50,51,53]` formed one ordered seven-unit union and +merged to 705. Both accepted decisions retain all seven applied units and result +705; their displayed status is `accepted_modified`, as each applied union differs +from its individual suggestion. Selecting the rows alone changed neither +assignments nor reviews. A source-amplitude split at +`-378.4182434082031` created selected child 706 and remainder 707, both +labeled good. Save/reopen preserved assignments, events, labels and both review +records. There are two accepted-modified and 91 pending suggestions. This ran in +a private Xvfb display, without desktop windows, and the child exited cleanly. +Its peak process RSS was 1.41 GiB. + +The independent oracle used only original seven-unit membership and raw amplitude +`< threshold` comparisons with nonfinite values retained on the remainder. It +checked all **469,725,567 assignments in each of the two full replays**, without +calling production projection helpers. It found 1,691,273 +selected and 1,597,610 remainder spikes and 700 active +units. Independent dense histograms verified exact per-unit/bin counts and exact +finite amplitude counts; amplitude sums agreed at rtol 1e-9, atol 1e-6. Both outputs +preserved every unchanged canonical NumPy file's bytes and producer/review +records. Repreparation took 28.43 seconds +and preserved full counts, labels and reviews. + +Independent SHA-256 inventories before and after matched all 134 named source +entries: 67 original files and 67 overlay entries, resolving to 71 unique files. +The inventory also binds resolved paths, symlink targets, inode/device, lengths, +mtime and ctime. All 18 replayed canonical arrays per output have distinct source +inodes and link count one. The mutable working assignment file is independent of +the pristine prepared package. Original source files were unchanged. + +Artifacts are all local to this directory: `validate_pipeline.py` (resumable +harness), `curate_offscreen.py`, `check_evidence_exposure.py`, +`check_output_inodes.py`, `summarize.py`, `result.json`, `progress.jsonl`, +`stdout.log`, `curation-offscreen.log`, both source inventories and supplemental +result JSON files. Preparation, row/index stores, isolated curation, both full +replays and repreparation are retained in separate new subdirectories. No runtime +repository edits, commits or GitHub writes were made by this validation task. diff --git a/design/carl-feedback-captures/recursive-bounded-03-nested-merge.png b/design/carl-feedback-captures/recursive-bounded-03-nested-merge.png new file mode 100644 index 000000000..60ade445a Binary files /dev/null and b/design/carl-feedback-captures/recursive-bounded-03-nested-merge.png differ diff --git a/design/carl-feedback-captures/recursive-bounded-05-restored-parents.png b/design/carl-feedback-captures/recursive-bounded-05-restored-parents.png new file mode 100644 index 000000000..de8ad6f54 Binary files /dev/null and b/design/carl-feedback-captures/recursive-bounded-05-restored-parents.png differ diff --git a/design/carl-feedback-captures/recursive-bounded-09-exact-remerge.png b/design/carl-feedback-captures/recursive-bounded-09-exact-remerge.png new file mode 100644 index 000000000..4b1c3fcf8 Binary files /dev/null and b/design/carl-feedback-captures/recursive-bounded-09-exact-remerge.png differ diff --git a/design/carl-feedback-captures/recursive-bounded-12-reopened.png b/design/carl-feedback-captures/recursive-bounded-12-reopened.png new file mode 100644 index 000000000..31f9b3bb8 Binary files /dev/null and b/design/carl-feedback-captures/recursive-bounded-12-reopened.png differ diff --git a/design/carl-feedback-captures/recursive-bounded-capture.json b/design/carl-feedback-captures/recursive-bounded-capture.json new file mode 100644 index 000000000..e0f2896f1 --- /dev/null +++ b/design/carl-feedback-captures/recursive-bounded-capture.json @@ -0,0 +1,428 @@ +{ + "mode": "bounded", + "dataset": "FRESH_BOUNDED_ENGINEERING_PACKAGE", + "working_copy": "DISPOSABLE_ISOLATED_COPY", + "capture_scope": "Settled X11 pixels; native XTest context click and Qt input events; not a spontaneous-redraw test", + "revision": "03377575cadc4cfd010d1977b869375e5078d515", + "steps": [ + { + "name": "01-initial", + "title": "Compare the two source clusters before the first merge", + "seconds": 5.206, + "selected": [ + 25, + 27 + ] + }, + { + "name": "02-first-merge", + "title": "First merge accepted: the SLAY suggestion is green", + "seconds": 10.539, + "selected": [ + 705 + ] + }, + { + "name": "03-nested-merge", + "title": "Second merge contains the first merge plus a third source cluster", + "seconds": 18.235, + "selected": [ + 706 + ], + "immediate_parents": [ + 705, + 22 + ], + "original_components": [ + 25, + 27, + 22 + ] + }, + { + "name": "04-later-edits", + "title": "A later unrelated merge and MUA label must remain intact", + "seconds": 30.099, + "selected": [ + 707 + ] + }, + { + "name": "05-restored-parents", + "title": "One restoration returns all three original components, not the intermediate merge", + "seconds": 38.295, + "selected": [ + 708, + 709, + 710 + ], + "restored": { + "25": 708, + "27": 709, + "22": 710 + }, + "slay_status": "accepted_restored" + }, + { + "name": "06-restore-history", + "title": "One Undo/Redo reverses the entire recursive restoration", + "seconds": 44.074, + "selected": [ + 708, + 709, + 710 + ] + }, + { + "name": "07-parents-remain-live", + "title": "The restored source components remain real live clusters", + "seconds": 46.173, + "selected": [ + 708, + 709, + 710 + ] + }, + { + "name": "08-excluded-parent", + "title": "Exclude the third component and keep the original suggested pair", + "seconds": 51.86, + "selected": [ + 708, + 709 + ] + }, + { + "name": "09-exact-remerge", + "title": "The exact SLAY pair is merged again: its suggestion is green", + "seconds": 55.349, + "selected": [ + 711 + ] + }, + { + "name": "10-remerge-history", + "title": "Undo/Redo keeps the SLAY color synchronized with actual membership", + "seconds": 61.183, + "selected": [ + 711 + ] + }, + { + "name": "11-revised-save", + "title": "Saved: remerged pair, independent third component and later MUA edit", + "seconds": 63.514, + "selected": [ + 711 + ] + }, + { + "name": "12-reopened", + "title": "Reopened: green SLAY pair, independent third component and later edits", + "seconds": 71.167, + "selected": [ + 711 + ] + } + ], + "input_events": [ + { + "seconds": 0.21, + "label": "Left click: Cluster 25", + "point": [ + 28, + 314 + ], + "click_seconds": 0.847 + }, + { + "seconds": 2.308, + "label": "Ctrl + Left click: Cluster 27", + "point": [ + 28, + 178 + ], + "click_seconds": 2.945 + }, + { + "seconds": 5.408, + "label": "Left click: P3 \u00b7 25, 27", + "point": [ + 95, + 903 + ], + "click_seconds": 6.044 + }, + { + "seconds": 7.034, + "label": "G: merge the first two source clusters", + "key_seconds": 7.285, + "key_released_seconds": 8.591 + }, + { + "seconds": 10.742, + "label": "Left click: Cluster 705", + "point": [ + 28, + 178 + ], + "click_seconds": 11.375 + }, + { + "seconds": 12.913, + "label": "Ctrl + Left click: Cluster 22", + "point": [ + 28, + 348 + ], + "click_seconds": 13.546 + }, + { + "seconds": 14.826, + "label": "G: merge the first result with one more source cluster", + "key_seconds": 15.077, + "key_released_seconds": 16.287 + }, + { + "seconds": 18.438, + "label": "Left click: Cluster 0", + "point": [ + 28, + 348 + ], + "click_seconds": 19.067 + }, + { + "seconds": 20.439, + "label": "Ctrl + Left click: Cluster 1", + "point": [ + 28, + 178 + ], + "click_seconds": 21.074 + }, + { + "seconds": 22.264, + "label": "G: make an unrelated later merge", + "key_seconds": 22.515, + "key_released_seconds": 23.69 + }, + { + "seconds": 24.662, + "label": "Alt + M: label the unrelated unit MUA", + "key_seconds": 24.913, + "key_released_seconds": 26.303 + }, + { + "seconds": 27.315, + "label": "Left click: Cluster 707", + "point": [ + 28, + 178 + ], + "click_seconds": 27.945 + }, + { + "seconds": 30.304, + "label": "Left click: Cluster 706", + "point": [ + 28, + 178 + ], + "click_seconds": 30.935 + }, + { + "seconds": 32.327, + "label": "Right click: older nested merge context menu" + }, + { + "seconds": 33.508, + "label": "Left click: Restore all merge components in Merge Mode", + "point": [ + 162, + 191 + ], + "click_seconds": 34.146 + }, + { + "seconds": 38.297, + "label": "Ctrl + Z: undo the whole recursive restoration", + "key_seconds": 38.547, + "key_released_seconds": 39.655 + }, + { + "seconds": 40.655, + "label": "Ctrl + Shift + Z: redo the whole recursive restoration", + "key_seconds": 40.906, + "key_released_seconds": 42.112 + }, + { + "seconds": 44.075, + "label": "V: leave Merge Mode; all three restored clusters stay live", + "key_seconds": 44.325, + "key_released_seconds": 44.409 + }, + { + "seconds": 46.173, + "label": "V: stage the restored components again", + "key_seconds": 46.423, + "key_released_seconds": 46.512 + }, + { + "seconds": 47.515, + "label": "Left click: Cluster 710", + "point": [ + 28, + 451 + ], + "click_seconds": 48.151 + }, + { + "seconds": 49.004, + "label": "Left click: Exclude the third source component", + "point": [ + 347, + 318 + ], + "click_seconds": 49.641 + }, + { + "seconds": 51.861, + "label": "G: remerge the exact original SLAY pair", + "key_seconds": 52.111, + "key_released_seconds": 53.378 + }, + { + "seconds": 55.35, + "label": "Ctrl + Z: undo the remerge; SLAY becomes white", + "key_seconds": 55.6, + "key_released_seconds": 56.769 + }, + { + "seconds": 57.836, + "label": "Ctrl + Shift + Z: redo the remerge; SLAY becomes green", + "key_seconds": 58.087, + "key_released_seconds": 59.224 + }, + { + "seconds": 61.184, + "label": "Ctrl + S: save the revised curation", + "key_seconds": 61.435, + "key_released_seconds": 61.764 + }, + { + "seconds": 63.514, + "label": "Reopen the saved working copy" + }, + { + "seconds": 67.317, + "label": "View menu: Inspect evidence window" + }, + { + "seconds": 68.119, + "label": "Type evidence window index, then Enter" + }, + { + "seconds": 68.896, + "label": "Enter: inspect evidence window 1", + "key_seconds": 69.147, + "key_released_seconds": 69.149 + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "display_columns": [ + "group", + "full_count", + "n_spikes", + "ch" + ], + "workflow": "recursive-restore-and-exact-slay-reassembly", + "propositions": [ + { + "key": "merge:bc141c6e345f8137", + "unit_ids": [ + 25, + 27 + ] + } + ], + "first_parents": [ + 25, + 27 + ], + "evidence_window": 1, + "window_waveforms_by_unit": { + "25": 2, + "27": 2 + }, + "first_merged": 705, + "nested_merge": { + "immediate_inputs": [ + 705, + 22 + ], + "original_components": [ + 25, + 27, + 22 + ], + "result": 706 + }, + "merged": 706, + "union": [ + 25, + 27, + 22 + ], + "nested_merge_slay_status": "accepted", + "unrelated": { + "inputs": [ + 0, + 1 + ], + "result": 707, + "group": "mua" + }, + "restored": { + "25": 708, + "27": 709, + "22": 710 + }, + "restored_live_units": true, + "recursive_restore_exact": true, + "one_restore_history_entry": true, + "restored_historical_ids_visible": true, + "restored_color_indices": { + "25": 0, + "27": 1, + "22": 2 + }, + "excluded_parent": { + "original": 22, + "live": 710 + }, + "chosen": [ + 708, + 709 + ], + "final_merged": 711, + "exact_remerge_slay_green": true, + "historical_review_preserved": true, + "later_edits_preserved": true, + "excluded_parent_stays_independent": true, + "remerge_undo_redo_status_correct": true, + "assigned_spikes": 20220, + "reopened_initial_evidence_window": 0, + "reopened_selected_evidence_window": 1, + "reopen_window_action": "Explicit Inspect evidence window dialog; not automatic restoration", + "reopened_parent_colors_preserved": true, + "reopened_lineage_correct": true, + "reopened_slay_green": true, + "historical_review_statuses": { + "merge:bc141c6e345f8137": "accepted" + }, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/recursive-narration-alignment.json b/design/carl-feedback-captures/recursive-narration-alignment.json new file mode 100644 index 000000000..73ad0ceeb --- /dev/null +++ b/design/carl-feedback-captures/recursive-narration-alignment.json @@ -0,0 +1,127 @@ +{ + "phrases": [ + { + "sentence": 1, + "text": "Bonjour. We begin by merging two clusters.", + "source_file": "01-with-bonjour.wav", + "source_sha256": "271b48d1d659364149206872622b43521de9dd8bd4a0dac3bc3aec7d48d91372", + "source_start": 0, + "source_end": 3.12, + "output_start": 0.35, + "output_end": 3.47, + "tempo_factor": 1.0 + }, + { + "sentence": 2, + "text": "Next, merge that result with a third cluster.", + "source_file": "02-sentence.wav", + "source_sha256": "5a4fa2495cec77f5981c507e5530009d7d3bd01e81d5290305a2a304f71e8d9c", + "source_start": 0, + "source_end": 3.33, + "output_start": 10.0, + "output_end": 13.33, + "tempo_factor": 1.0 + }, + { + "sentence": 3, + "text": "Then make an unrelated merge, and mark it as multi-unit activity.", + "source_file": "03-sentence.wav", + "source_sha256": "f391ffcfc4678c0e510e2356ccc14dc28d34f087cda0681822d87c7e7dee662b", + "source_start": 0, + "source_end": 4.69, + "output_start": 18.1, + "output_end": 22.790000000000003, + "tempo_factor": 1.0 + }, + { + "sentence": 4, + "text": "Return to the older, nested merge.", + "source_file": "04-sentence.wav", + "source_sha256": "423cfe93e6df5af58135c42c1601f59d51de5540c98f844e106aa91765a6e187", + "source_start": 0, + "source_end": 2.69, + "output_start": 26.1, + "output_end": 28.790000000000003, + "tempo_factor": 1.0 + }, + { + "sentence": 5, + "text": "One restore brings back all three original clusters.", + "source_file": "05-sentence.wav", + "source_sha256": "a15b3739cb3defd8d66ea79c9465e404e55027c6a2dc0ab76f78bef67d6445da", + "source_start": 0, + "source_end": 3.73, + "output_start": 29.3, + "output_end": 33.03, + "tempo_factor": 1.0 + }, + { + "sentence": 6, + "text": "Undo and redo affect the whole restoration.", + "source_file": "06-sentence.wav", + "source_sha256": "b19c52957501b4a9def7083429ba82b40af12c029d58a2ee6a243ee4ac63f7e4", + "source_start": 0, + "source_end": 2.61, + "output_start": 33.6, + "output_end": 36.21, + "tempo_factor": 1.0 + }, + { + "sentence": 7, + "text": "Leaving Merge Mode keeps them separate.", + "source_file": "07-sentence.wav", + "source_sha256": "8d63f41785a69c137aa9a03d879f32c95796db966a2d0c3030b6ffa71de4e231", + "source_start": 0, + "source_end": 2.61, + "output_start": 37.0, + "output_end": 39.61, + "tempo_factor": 1.0 + }, + { + "sentence": 8, + "text": "Exclude the third cluster.", + "source_file": "08-sentence.wav", + "source_sha256": "d8ffed185ea5704b974a40da5530062ae0845e4fa93ce28456ef8a9b1f9c0bcd", + "source_start": 0, + "source_end": 1.81, + "output_start": 40.2, + "output_end": 42.010000000000005, + "tempo_factor": 1.0 + }, + { + "sentence": 9, + "text": "Remerge the pair: SLAY turns green again.", + "source_file": "09-sentence.wav", + "source_sha256": "7be136f7b2c896f4152aca8fe04c41e5526f4f53348ac84e209623eeeba044cf", + "source_start": 0, + "source_end": 2.69, + "output_start": 43.6, + "output_end": 46.29, + "tempo_factor": 1.0 + }, + { + "sentence": 10, + "text": "Undo and redo update the status.", + "source_file": "10-sentence.wav", + "source_sha256": "a59e891d7275017c62ccce15278c5e3984e1b701981341b41e615475f78c69f3", + "source_start": 0, + "source_end": 2.29, + "output_start": 47.5, + "output_end": 49.79, + "tempo_factor": 1.0 + }, + { + "sentence": 11, + "text": "Save and reopen: the result and later edits are preserved.", + "source_file": "11-sentence.wav", + "source_sha256": "6ecedefa3243b84ab334667ce97ed337b81b03b0cc546b29f41dbba50c70805f", + "source_start": 0, + "source_end": 3.01, + "output_start": 54.1, + "output_end": 57.11, + "tempo_factor": 1.0 + } + ], + "timing": "Full approved sentences only; no internal edits, no tempo changes; minimum0.4s silence between sentences", + "publication": "Published video verification and native attachment are recorded in recursive-review.json" +} diff --git a/design/carl-feedback-captures/recursive-narration-generation.json b/design/carl-feedback-captures/recursive-narration-generation.json new file mode 100644 index 000000000..f5ccc5cdb --- /dev/null +++ b/design/carl-feedback-captures/recursive-narration-generation.json @@ -0,0 +1,544 @@ +{ + "model": "kyutai/tts-1.6b-en_fr", + "voice": "unmute-prod-website/fabieng-enhanced-v2.wav", + "batch_size": 4, + "seed": "42+batch_start", + "primer": "Bonjour.", + "primer_extra_padding_frames": 4, + "sample_rate": 24000, + "frame_rate": 12.5, + "elapsed_seconds": 10.725781819783151, + "sentences": [ + { + "number": 1, + "text": "We begin by merging two clusters.", + "file": "01-sentence.wav", + "with_bonjour": "01-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.45, + "raw_duration_seconds": 3.12, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "We", + 11 + ], + [ + "begin", + 15 + ], + [ + "by", + 18 + ], + [ + "merging", + 21 + ], + [ + "two", + 25 + ], + [ + "clusters.", + 30 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 2, + "text": "Next, merge that result with a third cluster.", + "file": "02-sentence.wav", + "with_bonjour": "02-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.33, + "raw_duration_seconds": 4.0, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Next,", + 11 + ], + [ + "merge", + 18 + ], + [ + "that", + 22 + ], + [ + "result", + 27 + ], + [ + "with", + 32 + ], + [ + "a", + 36 + ], + [ + "third", + 39 + ], + [ + "cluster.", + 42 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 3, + "text": "Then make an unrelated merge, and mark it as multi-unit activity.", + "file": "03-sentence.wav", + "with_bonjour": "03-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 4.69, + "raw_duration_seconds": 5.36, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Then", + 11 + ], + [ + "make", + 16 + ], + [ + "an", + 21 + ], + [ + "unrelated", + 24 + ], + [ + "merge,", + 30 + ], + [ + "and", + 39 + ], + [ + "mark", + 41 + ], + [ + "it", + 44 + ], + [ + "as", + 46 + ], + [ + "multi-unit", + 49 + ], + [ + "activity.", + 58 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 4, + "text": "Return to the older, nested merge.", + "file": "04-sentence.wav", + "with_bonjour": "04-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.69, + "raw_duration_seconds": 3.36, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Return", + 11 + ], + [ + "to", + 18 + ], + [ + "the", + 21 + ], + [ + "older,", + 23 + ], + [ + "nested", + 30 + ], + [ + "merge.", + 36 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 5, + "text": "One restore brings back all three original clusters.", + "file": "05-sentence.wav", + "with_bonjour": "05-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.73, + "raw_duration_seconds": 4.4, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "One", + 11 + ], + [ + "restore", + 14 + ], + [ + "brings", + 20 + ], + [ + "back", + 25 + ], + [ + "all", + 30 + ], + [ + "three", + 35 + ], + [ + "original", + 38 + ], + [ + "clusters.", + 46 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 6, + "text": "Undo and redo affect the whole restoration.", + "file": "06-sentence.wav", + "with_bonjour": "06-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.61, + "raw_duration_seconds": 3.28, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Undo", + 11 + ], + [ + "and", + 16 + ], + [ + "redo", + 18 + ], + [ + "affect", + 21 + ], + [ + "the", + 27 + ], + [ + "whole", + 30 + ], + [ + "restoration.", + 32 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 7, + "text": "Leaving Merge Mode keeps them separate.", + "file": "07-sentence.wav", + "with_bonjour": "07-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.61, + "raw_duration_seconds": 3.28, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Leaving", + 11 + ], + [ + "Merge", + 16 + ], + [ + "Mode", + 21 + ], + [ + "keeps", + 24 + ], + [ + "them", + 27 + ], + [ + "separate.", + 32 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 8, + "text": "Exclude the third cluster.", + "file": "08-sentence.wav", + "with_bonjour": "08-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 1.81, + "raw_duration_seconds": 2.48, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Exclude", + 11 + ], + [ + "the", + 18 + ], + [ + "third", + 20 + ], + [ + "cluster.", + 23 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 9, + "text": "Remerge the pair: SLAY turns green again.", + "file": "09-sentence.wav", + "with_bonjour": "09-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.69, + "raw_duration_seconds": 3.36, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Remerge", + 11 + ], + [ + "the", + 16 + ], + [ + "pair", + 19 + ], + [ + "SLAY", + 21 + ], + [ + "turns", + 28 + ], + [ + "green", + 31 + ], + [ + "again.", + 35 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + }, + { + "number": 10, + "text": "Undo and redo update the status.", + "file": "10-sentence.wav", + "with_bonjour": "10-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.29, + "raw_duration_seconds": 2.96, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Undo", + 11 + ], + [ + "and", + 16 + ], + [ + "redo", + 18 + ], + [ + "update", + 22 + ], + [ + "the", + 27 + ], + [ + "status.", + 30 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + }, + { + "number": 11, + "text": "Save and reopen: the result and later edits are preserved.", + "file": "11-sentence.wav", + "with_bonjour": "11-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.01, + "raw_duration_seconds": 3.68, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Save", + 11 + ], + [ + "and", + 14 + ], + [ + "reopen", + 17 + ], + [ + "the", + 21 + ], + [ + "result", + 23 + ], + [ + "and", + 26 + ], + [ + "later", + 29 + ], + [ + "edits", + 32 + ], + [ + "are", + 35 + ], + [ + "preserved.", + 38 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + } + ], + "model_revision": "f65439609986c392cb12df63938abcc550c3fb15", + "voice_revision": "323332d33f997de8394f24a193e1a76df720e01a", + "model_license": "CC-BY-4.0", + "voice_license": "CC0", + "sentence_audio_sha256": { + "01-sentence.wav": "ea91938ac2464bca1590d2303374e025d501e8bd96201ee7572da7f31983af7d", + "01-with-bonjour.wav": "271b48d1d659364149206872622b43521de9dd8bd4a0dac3bc3aec7d48d91372", + "02-sentence.wav": "5a4fa2495cec77f5981c507e5530009d7d3bd01e81d5290305a2a304f71e8d9c", + "02-with-bonjour.wav": "84c1d12148d87a3cca572a3a8f390297dc8a3d20800928f0476156b0a37298b5", + "03-sentence.wav": "f391ffcfc4678c0e510e2356ccc14dc28d34f087cda0681822d87c7e7dee662b", + "03-with-bonjour.wav": "7e73929a503e046894d1d31f5ca4916a98e7e73a70d112524578bc0803003255", + "04-sentence.wav": "423cfe93e6df5af58135c42c1601f59d51de5540c98f844e106aa91765a6e187", + "04-with-bonjour.wav": "5906d2ced07737c24cf1c638500df9387b8b4b04804ccd3374811f1fe532025d", + "05-sentence.wav": "a15b3739cb3defd8d66ea79c9465e404e55027c6a2dc0ab76f78bef67d6445da", + "05-with-bonjour.wav": "8c30a34de824410f3b71f58411f904186619fad3db349f27614a0f569aee7420", + "06-sentence.wav": "b19c52957501b4a9def7083429ba82b40af12c029d58a2ee6a243ee4ac63f7e4", + "06-with-bonjour.wav": "b9422d4513395ff4fda9c132db4555542d625157e019b61b8484302509277eeb", + "07-sentence.wav": "8d63f41785a69c137aa9a03d879f32c95796db966a2d0c3030b6ffa71de4e231", + "07-with-bonjour.wav": "424a694f75cb447ed8dd4105ff70b33de74c57f94775e477a95d90d113054c7c", + "08-sentence.wav": "d8ffed185ea5704b974a40da5530062ae0845e4fa93ce28456ef8a9b1f9c0bcd", + "08-with-bonjour.wav": "a3fdf5b2f8db5d058b9ea975970e870a33ff15f1fee84fc9c0ac98526a883173", + "09-sentence.wav": "7be136f7b2c896f4152aca8fe04c41e5526f4f53348ac84e209623eeeba044cf", + "09-with-bonjour.wav": "83cc17f53fabe8359a73c3ae932ec3100b5bbe3e7d1182158e9e7024bb6ba4dc", + "10-sentence.wav": "a59e891d7275017c62ccce15278c5e3984e1b701981341b41e615475f78c69f3", + "10-with-bonjour.wav": "5dea6ec5256ab31b41afcf04268482b87ba1e99658955fed3dbb7913ddb2edd6", + "11-sentence.wav": "6ecedefa3243b84ab334667ce97ed337b81b03b0cc546b29f41dbba50c70805f", + "11-with-bonjour.wav": "75ef3e113084d2bc3db8bebf1c44188b80ab4f974b39bba8c7fd7e7b354d5038" + } +} diff --git a/design/carl-feedback-captures/recursive-narration.srt b/design/carl-feedback-captures/recursive-narration.srt new file mode 100644 index 000000000..162bc3ff6 --- /dev/null +++ b/design/carl-feedback-captures/recursive-narration.srt @@ -0,0 +1,44 @@ +1 +00:00:00,370 --> 00:00:03,470 +Bonjour. We begin by merging two clusters. + +2 +00:00:10,020 --> 00:00:13,330 +Next, merge that result with a third cluster. + +3 +00:00:18,120 --> 00:00:22,790 +Then make an unrelated merge, and mark it as multi-unit +activity. + +4 +00:00:26,120 --> 00:00:28,790 +Return to the older, nested merge. + +5 +00:00:29,320 --> 00:00:33,030 +One restore brings back all three original clusters. + +6 +00:00:33,620 --> 00:00:36,210 +Undo and redo affect the whole restoration. + +7 +00:00:37,020 --> 00:00:39,610 +Leaving Merge Mode keeps them separate. + +8 +00:00:40,220 --> 00:00:42,010 +Exclude the third cluster. + +9 +00:00:43,620 --> 00:00:46,290 +Remerge the pair: SLAY turns green again. + +10 +00:00:47,520 --> 00:00:49,790 +Undo and redo update the status. + +11 +00:00:54,120 --> 00:00:57,110 +Save and reopen: the result and later edits are preserved. diff --git a/design/carl-feedback-captures/recursive-ordinary-03-nested-merge.png b/design/carl-feedback-captures/recursive-ordinary-03-nested-merge.png new file mode 100644 index 000000000..0e57bcea4 Binary files /dev/null and b/design/carl-feedback-captures/recursive-ordinary-03-nested-merge.png differ diff --git a/design/carl-feedback-captures/recursive-ordinary-05-restored-parents.png b/design/carl-feedback-captures/recursive-ordinary-05-restored-parents.png new file mode 100644 index 000000000..a1d1ba9cb Binary files /dev/null and b/design/carl-feedback-captures/recursive-ordinary-05-restored-parents.png differ diff --git a/design/carl-feedback-captures/recursive-ordinary-09-exact-remerge.png b/design/carl-feedback-captures/recursive-ordinary-09-exact-remerge.png new file mode 100644 index 000000000..5c4bccdf8 Binary files /dev/null and b/design/carl-feedback-captures/recursive-ordinary-09-exact-remerge.png differ diff --git a/design/carl-feedback-captures/recursive-ordinary-12-reopened.png b/design/carl-feedback-captures/recursive-ordinary-12-reopened.png new file mode 100644 index 000000000..cdf365f80 Binary files /dev/null and b/design/carl-feedback-captures/recursive-ordinary-12-reopened.png differ diff --git a/design/carl-feedback-captures/recursive-ordinary-capture.json b/design/carl-feedback-captures/recursive-ordinary-capture.json new file mode 100644 index 000000000..75e093997 --- /dev/null +++ b/design/carl-feedback-captures/recursive-ordinary-capture.json @@ -0,0 +1,405 @@ +{ + "mode": "ordinary", + "dataset": "CARL_SWAY_SOURCE", + "working_copy": "DISPOSABLE_ISOLATED_COPY", + "capture_scope": "Settled X11 pixels; native XTest context click and Qt input events; not a spontaneous-redraw test", + "revision": "03377575cadc4cfd010d1977b869375e5078d515", + "steps": [ + { + "name": "01-initial", + "title": "Compare the two source clusters before the first merge", + "seconds": 5.839, + "selected": [ + 9, + 15 + ] + }, + { + "name": "02-first-merge", + "title": "First merge accepted: the SLAY suggestion is green", + "seconds": 10.012, + "selected": [ + 614 + ] + }, + { + "name": "03-nested-merge", + "title": "Second merge contains the first merge plus a third source cluster", + "seconds": 16.878, + "selected": [ + 615 + ], + "immediate_parents": [ + 614, + 23 + ], + "original_components": [ + 9, + 15, + 23 + ] + }, + { + "name": "04-later-edits", + "title": "A later unrelated merge and MUA label must remain intact", + "seconds": 27.312, + "selected": [ + 616 + ] + }, + { + "name": "05-restored-parents", + "title": "One restoration returns all three original components, not the intermediate merge", + "seconds": 34.501, + "selected": [ + 617, + 618, + 619 + ], + "restored": { + "9": 618, + "15": 619, + "23": 617 + }, + "slay_status": "accepted_restored" + }, + { + "name": "06-restore-history", + "title": "One Undo/Redo reverses the entire recursive restoration", + "seconds": 38.594, + "selected": [ + 617, + 618, + 619 + ] + }, + { + "name": "07-parents-remain-live", + "title": "The restored source components remain real live clusters", + "seconds": 40.661, + "selected": [ + 617, + 618, + 619 + ] + }, + { + "name": "08-excluded-parent", + "title": "Exclude the third component and keep the original suggested pair", + "seconds": 46.302, + "selected": [ + 618, + 619 + ] + }, + { + "name": "09-exact-remerge", + "title": "The exact SLAY pair is merged again: its suggestion is green", + "seconds": 48.776, + "selected": [ + 620 + ] + }, + { + "name": "10-remerge-history", + "title": "Undo/Redo keeps the SLAY color synchronized with actual membership", + "seconds": 52.727, + "selected": [ + 620 + ] + }, + { + "name": "11-revised-save", + "title": "Saved: remerged pair, independent third component and later MUA edit", + "seconds": 55.246, + "selected": [ + 620 + ] + }, + { + "name": "12-reopened", + "title": "Reopened: green SLAY pair, independent third component and later edits", + "seconds": 58.958, + "selected": [ + 620 + ] + } + ], + "input_events": [ + { + "seconds": 0.226, + "label": "Left click: Cluster 9", + "point": [ + 229, + 416 + ], + "click_seconds": 0.863 + }, + { + "seconds": 2.518, + "label": "Ctrl + Left click: Cluster 15", + "point": [ + 229, + 416 + ], + "click_seconds": 3.146 + }, + { + "seconds": 6.041, + "label": "Left click: P1 \u00b7 9, 15", + "point": [ + 95, + 925 + ], + "click_seconds": 6.673 + }, + { + "seconds": 7.556, + "label": "G: merge the first two source clusters", + "key_seconds": 7.807, + "key_released_seconds": 8.216 + }, + { + "seconds": 10.213, + "label": "Left click: Cluster 614", + "point": [ + 28, + 178 + ], + "click_seconds": 10.846 + }, + { + "seconds": 12.188, + "label": "Ctrl + Left click: Cluster 23", + "point": [ + 28, + 382 + ], + "click_seconds": 12.826 + }, + { + "seconds": 14.292, + "label": "G: merge the first result with one more source cluster", + "key_seconds": 14.542, + "key_released_seconds": 15.049 + }, + { + "seconds": 17.08, + "label": "Left click: Cluster 0", + "point": [ + 28, + 382 + ], + "click_seconds": 17.709 + }, + { + "seconds": 19.207, + "label": "Ctrl + Left click: Cluster 1", + "point": [ + 28, + 178 + ], + "click_seconds": 19.846 + }, + { + "seconds": 21.254, + "label": "G: make an unrelated later merge", + "key_seconds": 21.505, + "key_released_seconds": 22.11 + }, + { + "seconds": 22.911, + "label": "Alt + M: label the unrelated unit MUA", + "key_seconds": 23.162, + "key_released_seconds": 23.646 + }, + { + "seconds": 24.655, + "label": "Left click: Cluster 616", + "point": [ + 28, + 178 + ], + "click_seconds": 25.285 + }, + { + "seconds": 27.518, + "label": "Left click: Cluster 615", + "point": [ + 28, + 178 + ], + "click_seconds": 28.146 + }, + { + "seconds": 29.452, + "label": "Right click: older nested merge context menu" + }, + { + "seconds": 30.631, + "label": "Left click: Restore all merge components in Merge Mode", + "point": [ + 162, + 191 + ], + "click_seconds": 31.267 + }, + { + "seconds": 34.504, + "label": "Ctrl + Z: undo the whole recursive restoration", + "key_seconds": 34.755, + "key_released_seconds": 35.08 + }, + { + "seconds": 35.936, + "label": "Ctrl + Shift + Z: redo the whole recursive restoration", + "key_seconds": 36.187, + "key_released_seconds": 36.802 + }, + { + "seconds": 38.594, + "label": "V: leave Merge Mode; all three restored clusters stay live", + "key_seconds": 38.846, + "key_released_seconds": 38.872 + }, + { + "seconds": 40.662, + "label": "V: stage the restored components again", + "key_seconds": 40.912, + "key_released_seconds": 40.928 + }, + { + "seconds": 41.931, + "label": "Left click: Cluster 617", + "point": [ + 28, + 404 + ], + "click_seconds": 42.57 + }, + { + "seconds": 43.423, + "label": "Left click: Exclude the third source component", + "point": [ + 611, + 339 + ], + "click_seconds": 44.062 + }, + { + "seconds": 46.302, + "label": "G: remerge the exact original SLAY pair", + "key_seconds": 46.553, + "key_released_seconds": 46.987 + }, + { + "seconds": 48.776, + "label": "Ctrl + Z: undo the remerge; SLAY becomes white", + "key_seconds": 49.027, + "key_released_seconds": 49.613 + }, + { + "seconds": 50.444, + "label": "Ctrl + Shift + Z: redo the remerge; SLAY becomes green", + "key_seconds": 50.695, + "key_released_seconds": 50.965 + }, + { + "seconds": 52.728, + "label": "Ctrl + S: save the revised curation", + "key_seconds": 52.979, + "key_released_seconds": 53.492 + }, + { + "seconds": 55.247, + "label": "Reopen the saved working copy" + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "display_columns": [ + "group", + "n_spikes", + "ch" + ], + "workflow": "recursive-restore-and-exact-slay-reassembly", + "propositions": [ + { + "key": "merge:f79990b25de62781", + "unit_ids": [ + 9, + 15 + ] + } + ], + "first_parents": [ + 9, + 15 + ], + "first_merged": 614, + "nested_merge": { + "immediate_inputs": [ + 614, + 23 + ], + "original_components": [ + 9, + 15, + 23 + ], + "result": 615 + }, + "merged": 615, + "union": [ + 9, + 15, + 23 + ], + "nested_merge_slay_status": "accepted", + "unrelated": { + "inputs": [ + 0, + 1 + ], + "result": 616, + "group": "mua" + }, + "restored": { + "9": 618, + "15": 619, + "23": 617 + }, + "restored_live_units": true, + "recursive_restore_exact": true, + "one_restore_history_entry": true, + "restored_historical_ids_visible": true, + "restored_color_indices": { + "9": 1, + "15": 2, + "23": 0 + }, + "excluded_parent": { + "original": 23, + "live": 617 + }, + "chosen": [ + 618, + 619 + ], + "final_merged": 620, + "exact_remerge_slay_green": true, + "historical_review_preserved": true, + "later_edits_preserved": true, + "excluded_parent_stays_independent": true, + "remerge_undo_redo_status_correct": true, + "assigned_spikes": 31482, + "reopened_parent_colors_preserved": true, + "reopened_lineage_correct": true, + "reopened_slay_green": true, + "historical_review_statuses": { + "merge:f79990b25de62781": "accepted" + }, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/recursive-pipeline-artifact-provenance.json b/design/carl-feedback-captures/recursive-pipeline-artifact-provenance.json new file mode 100644 index 000000000..0386b9592 --- /dev/null +++ b/design/carl-feedback-captures/recursive-pipeline-artifact-provenance.json @@ -0,0 +1,54 @@ +{ + "REPORT.md": { + "bytes": 1960, + "sha256": "c8107f8c6aaefae6baba148d22b8152092be5912517c51a29f675c714f2bb08f" + }, + "curation-result.json": { + "bytes": 938, + "sha256": "4691371cf07b0bc564230610b268dcc54f2b412a461c8874ae0d67eb5195e7fb" + }, + "curation-state.json": { + "bytes": 906568, + "sha256": "4f2d219a61f6e2e085500f7989583ebf5772f6816c592dcfd94ef94bca8b49f0" + }, + "execution-provenance.json": { + "bytes": 10946, + "sha256": "de1812d4ce22a0aa736d62e11263cb00eb77fd6e83962b13bd433d57b7ddf9fb" + }, + "final-checks.json": { + "bytes": 2020, + "sha256": "20379d6940db74c01f57a68ae0406a9ba53a7cf95a60c660f2c5c4894c65bc56" + }, + "final_checks.py": { + "bytes": 7098, + "sha256": "547757d8dd413a81ce6e8aeaeac8da401030fe00f2d02e8847045292f5154777" + }, + "independent-oracle.json": { + "bytes": 13525, + "sha256": "db2f7752dd40abe2272cbb983ca92631c21588c76de2d2e9451f2a0c11fb6817" + }, + "inventory-after.json": { + "bytes": 77280, + "sha256": "6b2cd3875e52cc83940da740e4e08a61dd688d8c76b00e76b73b58bd93b4b529" + }, + "inventory-before.json": { + "bytes": 77280, + "sha256": "6b2cd3875e52cc83940da740e4e08a61dd688d8c76b00e76b73b58bd93b4b529" + }, + "result.json": { + "bytes": 112773, + "sha256": "346e2090d235bffaf6d7fb909417d7ab74813775b47d95fae9530f1be885bc27" + }, + "scenario.json": { + "bytes": 538, + "sha256": "49777a04bf7cc9972403426fdba82e83a6be8737dbf7b3ec60f8c3428f6254c4" + }, + "validate_pipeline.py": { + "bytes": 18803, + "sha256": "0263b75a8be46fc9b08b5b3d28c64876b39f8264032689782dd5d40170b9d3b1" + }, + "verify_parent_restore_replay.py": { + "bytes": 3469, + "sha256": "edb3ec3f5c2c58fee8260d00b34049367a5644358cde1bda5543cfeadb6333a8" + } +} diff --git a/design/carl-feedback-captures/recursive-pipeline-final-checks.json b/design/carl-feedback-captures/recursive-pipeline-final-checks.json new file mode 100644 index 000000000..71b25aaf5 --- /dev/null +++ b/design/carl-feedback-captures/recursive-pipeline-final-checks.json @@ -0,0 +1,34 @@ +{ + "all_metadata_field_names_unit_keys_values_and_json_types_exact": true, + "assignment_journal_replay_runtime_sha256_unchanged_since_launch": true, + "assignment_outputs_are_not_source_hardlinks": true, + "code_head_at_launch": "03377575cadc4cfd010d1977b869375e5078d515", + "frozen_oracle_sha256_unchanged_since_launch": true, + "independent_oracle_script_mtime_precedes_run": true, + "independent_oracle_script_sha256": "edb3ec3f5c2c58fee8260d00b34049367a5644358cde1bda5543cfeadb6333a8", + "metadata_cells_per_output": 31545, + "metadata_fields": 45, + "replay_assignment_payload_sha256_identical": { + "replayed-1": "9096b13b5ec2d7c02d7be9d3edbfae29f12cf599ad8c66564c1065745287f8f1", + "replayed-4": "9096b13b5ec2d7c02d7be9d3edbfae29f12cf599ad8c66564c1065745287f8f1" + }, + "reprepared_byte_budget": 536870912, + "reprepared_bytes": 534551613, + "reprepared_cumulative_metadata_provenance_exact": true, + "reprepared_spike_budget": 2000000, + "seconds": 5.5383116328157485, + "source_timestamps_subset_manifest_and_propositions_bytes_preserved": true, + "ui_difference_scope": "Bounded SLAY review membership-containment helper and its UI caller only; existing assignment/journal/replay and membership_expressions code unchanged; later narrow UI regressions cover this followup separately", + "ui_only_differences_ast_verified_against_launch_commit": true, + "ui_only_runtime_differences_after_launch": { + "phy/apps/large_recording/live_summaries.py": { + "sha256_after_validation": "68f612c0aef9a14d2ea55f07b424f752951e26b37502acd905f09a5da00eeb0a", + "sha256_at_launch": "d61c8b15ee8d3511a59ba8ffdedb1345c2e64eda650b2eefe71a14aae7e33e98" + }, + "phy/apps/large_recording/supervisor.py": { + "sha256_after_validation": "36f219ccffb70871d78e90970a7db7caae6cb6902440dcb11655c905e370d82b", + "sha256_at_launch": "7ff505998b3a34117090a8b420b59088dc8b160ad9d1f6541087d8137d32be51" + } + }, + "validation_harness_sha256": "0263b75a8be46fc9b08b5b3d28c64876b39f8264032689782dd5d40170b9d3b1" +} diff --git a/design/carl-feedback-captures/recursive-pipeline-report.md b/design/carl-feedback-captures/recursive-pipeline-report.md new file mode 100644 index 000000000..dcb651619 --- /dev/null +++ b/design/carl-feedback-captures/recursive-pipeline-report.md @@ -0,0 +1,27 @@ +# Full source recursive restoration validation + +Engineering validation of a converted fixture only: original acquisition clock, exposure and producer export have not been verified. Timings are observations, not benchmarks; other GUI and test workloads run concurrently. + +Code: `03377575cadc4cfd010d1977b869375e5078d515`. Complete: **True**. Input SHA-256/stat inventories unchanged: **True**. + +The independent oracle checked **469,725,567 rows in each of 2 outputs**, using original labels and raw finite amplitude comparisons. + +| Phase | Seconds | +|---|---:| +| immutable-inventory-before | 20.42 | +| copy-prepared-input | 0.15 | +| public-gui-supervisor-curation-save-reopen | 46.97 | +| full-source-replay-1 | 93.92 | +| full-source-replay-4 | 80.54 | +| independent-original-row-oracle | 14.51 | +| replay-canonical-bytes-counts-labels-reviews-lineage | 84.68 | +| reprepare-one-replayed-full-source | 25.90 | +| reprepared-contract-verification | 0.56 | + +See `result.json`, `scenario.json`, `curation-state.json`, `independent-oracle.json`, and input inventories for exact provenance and checks. + +All **45 metadata fields (31,545 unit cells)** match exactly in both full outputs and the reprepared package, including JSON types. Cumulative metadata provenance also matches. Both assignment payload SHA-256 hashes match; timestamps, subset manifest and producer propositions retain their bytes. See `final-checks.json`. + +The scientific pipeline is attributed to the launch commit above. During validation, a subsequent UI-only SLAY containment proof was added in `live_summaries.py` and its caller in `large_recording/supervisor.py`. AST comparison confirms the existing membership-expression, assignment, journal and replay code stayed unchanged. Before/after file hashes are recorded in `final-checks.json`; the followup has separate focused UI regressions. + +Copy method: 73 conservative full-copy fallbacks, 0 explicit reflinks; all copies use distinct inodes. diff --git a/design/carl-feedback-captures/recursive-pipeline-scenario.json b/design/carl-feedback-captures/recursive-pipeline-scenario.json new file mode 100644 index 000000000..bdc817520 --- /dev/null +++ b/design/carl-feedback-captures/recursive-pipeline-scenario.json @@ -0,0 +1,29 @@ +{ + "excluded_live": 713, + "excluded_original": 50, + "final_merged": 714, + "included_originals": [ + 49 + ], + "included_restored_live": 712, + "initial_merge": 705, + "initial_parents": [ + 40, + 44, + 48 + ], + "intermediate_merge": 708, + "new_candidate": 51, + "nonfinite": "keep", + "operator": "<", + "restored_merge_target": 709, + "selected_restored_live": 711, + "split_remainder": 707, + "split_selected": 706, + "threshold": -424.19464111328125, + "unrelated_inputs": [ + 0, + 1 + ], + "unrelated_result": 710 +} diff --git a/design/carl-feedback-captures/recursive-review.json b/design/carl-feedback-captures/recursive-review.json new file mode 100644 index 000000000..fbd0233a1 --- /dev/null +++ b/design/carl-feedback-captures/recursive-review.json @@ -0,0 +1,76 @@ +{ + "comment": "https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782", + "capture_revision": "03377575cadc4cfd010d1977b869375e5078d515", + "workflow": "recursive-restore-and-exact-slay-reassembly", + "width": 1920, + "height": 1200, + "recording_fps": 30, + "duration_seconds": 57.933333, + "frames": 1738, + "bytes": 4461850, + "sha256": "41a53e5eb948d465414ab0307bd87da9c507cf413b8bd9c626cdc9f92a06b403", + "visible_pointer": true, + "click_cues": true, + "in_window_translucent_keycaps": true, + "stage_annotations": "Labeled REVIEW NOTE overlays, not application UI", + "reload_wait_omitted": true, + "retained_interactions_original_speed": true, + "checkpoints": 12, + "both_real_data_state_checks_passed": true, + "source_unchanged": true, + "native_XTest_context_click": true, + "other_input": "Qt events; settled rendering, not spontaneous repaint or physical routing proof", + "english_subtitles_burned_in": true, + "keyboard_cues_above_subtitles": true, + "narration": { + "language": "English", + "synthetic": true, + "complete_sentences": 11, + "internal_speech_cuts": 0, + "sentence_tempo_changes": 0, + "minimum_silence_between_sentences_seconds": 0.51, + "sentence_pcm_verified_before_normalization": true, + "codec": "AAC", + "peak_db": -2.0, + "model": "kyutai/tts-1.6b-en_fr", + "voice": "unmute-prod-website/fabieng-enhanced-v2.wav" + }, + "reproduction_matches_video_bytes": true, + "blackdetect": { + "minimum_duration_seconds": 0.2, + "pixel_threshold": 0.02, + "picture_threshold": 0.99, + "intervals_detected": 0 + }, + "local_dependency_override": "PyQt5-sip 12.20.1, separate PR1442", + "scientific_pipeline_revision": "03377575cadc4cfd010d1977b869375e5078d515", + "bounded_ui_proof_revision": "857dc3ea100f05973974e2215b111c9e3bc5ea67", + "ordinary_legacy_alias_revision": "c57abdaf5755faf9cb09610659adcd74605998f7", + "core_tests": { + "passed": 706, + "skipped": 13, + "exit_code": 0 + }, + "final_ordinary_integration_tests": { + "passed": 147, + "exit_code": 0 + }, + "independent_full_source_rows_per_output": 469725567, + "independent_full_source_outputs": 2, + "all_metadata_fields": 45, + "metadata_cells_per_output": 31545, + "app_tests": { + "passed": 833, + "skipped": 6, + "exit_code": 0 + }, + "final_supervisor_tests": { + "passed": 122, + "exit_code": 0 + }, + "rollback_display_cache_revision": "fece6a32df3aa274d81539c3be73dd51531e0464", + "asset": "https://github.com/user-attachments/assets/238920fb-2bda-4189-97aa-816c43c4b8be", + "inline_player_verified": true, + "uploaded_bytes_verified": true, + "uploaded_audio_stream_verified": true +} diff --git a/design/carl-feedback-captures/recursive-review.timeline.json b/design/carl-feedback-captures/recursive-review.timeline.json new file mode 100644 index 000000000..3cb6f9cbe --- /dev/null +++ b/design/carl-feedback-captures/recursive-review.timeline.json @@ -0,0 +1,668 @@ +{ + "source": "LOCAL_UNCUT_RECURSIVE_WALKTHROUGH.mp4", + "output": "GITHUB_NATIVE_VIDEO_ATTACHMENT", + "source_fps": "30/1", + "source_duration_seconds": 71.566667, + "output_duration_seconds": 57.93333333333333, + "review_cut": true, + "timeline_note": "Original-speed source frames concatenated; idle dwell and reopen wait omitted. Not a latency benchmark.", + "settle_tail_seconds": 0.5046666666665908, + "items": [ + { + "kind": "source", + "source_start_frame": 0, + "source_end_frame": 48, + "source_start": 0.0, + "source_end": 1.6, + "event_indices": [ + 0 + ], + "output_start": 0.0, + "output_end": 1.6 + }, + { + "kind": "source", + "source_start_frame": 63, + "source_end_frame": 111, + "source_start": 2.1, + "source_end": 3.7, + "event_indices": [ + 1 + ], + "output_start": 1.6, + "output_end": 3.2 + }, + { + "kind": "source", + "source_start_frame": 147, + "source_end_frame": 364, + "source_start": 4.9, + "source_end": 12.133333333333333, + "event_indices": [ + 2, + 3, + 4 + ], + "output_start": 3.2, + "output_end": 10.433333333333334 + }, + { + "kind": "source", + "source_start_frame": 381, + "source_end_frame": 429, + "source_start": 12.7, + "source_end": 14.3, + "event_indices": [ + 5 + ], + "output_start": 10.433333333333334, + "output_end": 12.033333333333333 + }, + { + "kind": "source", + "source_start_frame": 439, + "source_end_frame": 595, + "source_start": 14.633333333333333, + "source_end": 19.833333333333332, + "event_indices": [ + 6, + 7 + ], + "output_start": 12.033333333333333, + "output_end": 17.233333333333334 + }, + { + "kind": "source", + "source_start_frame": 607, + "source_end_frame": 655, + "source_start": 20.233333333333334, + "source_end": 21.833333333333332, + "event_indices": [ + 8 + ], + "output_start": 17.233333333333334, + "output_end": 18.833333333333336 + }, + { + "kind": "source", + "source_start_frame": 662, + "source_end_frame": 726, + "source_start": 22.066666666666666, + "source_end": 24.2, + "event_indices": [ + 9 + ], + "output_start": 18.833333333333336, + "output_end": 20.96666666666667 + }, + { + "kind": "source", + "source_start_frame": 734, + "source_end_frame": 804, + "source_start": 24.466666666666665, + "source_end": 26.8, + "event_indices": [ + 10 + ], + "output_start": 20.96666666666667, + "output_end": 23.3 + }, + { + "kind": "source", + "source_start_frame": 813, + "source_end_frame": 951, + "source_start": 27.1, + "source_end": 31.7, + "event_indices": [ + 11, + 12 + ], + "output_start": 23.3, + "output_end": 27.9 + }, + { + "kind": "source", + "source_start_frame": 964, + "source_end_frame": 1047, + "source_start": 32.13333333333333, + "source_end": 34.9, + "event_indices": [ + 13, + 14 + ], + "output_start": 27.9, + "output_end": 30.666666666666664 + }, + { + "kind": "source", + "source_start_frame": 1077, + "source_end_frame": 1205, + "source_start": 35.9, + "source_end": 40.166666666666664, + "event_indices": [ + 15 + ], + "output_start": 30.666666666666664, + "output_end": 34.93333333333333 + }, + { + "kind": "source", + "source_start_frame": 1214, + "source_end_frame": 1278, + "source_start": 40.46666666666667, + "source_end": 42.6, + "event_indices": [ + 16 + ], + "output_start": 34.93333333333333, + "output_end": 37.06666666666666 + }, + { + "kind": "source", + "source_start_frame": 1313, + "source_end_frame": 1347, + "source_start": 43.766666666666666, + "source_end": 44.9, + "event_indices": [ + 17 + ], + "output_start": 37.06666666666666, + "output_end": 38.199999999999996 + }, + { + "kind": "source", + "source_start_frame": 1376, + "source_end_frame": 1410, + "source_start": 45.86666666666667, + "source_end": 47.0, + "event_indices": [ + 18 + ], + "output_start": 38.199999999999996, + "output_end": 39.33333333333333 + }, + { + "kind": "source", + "source_start_frame": 1419, + "source_end_frame": 1718, + "source_start": 47.3, + "source_end": 57.266666666666666, + "event_indices": [ + 19, + 20, + 21, + 22 + ], + "output_start": 39.33333333333333, + "output_end": 49.3 + }, + { + "kind": "source", + "source_start_frame": 1729, + "source_end_frame": 1792, + "source_start": 57.63333333333333, + "source_end": 59.733333333333334, + "event_indices": [ + 23 + ], + "output_start": 49.3, + "output_end": 51.4 + }, + { + "kind": "source", + "source_start_frame": 1826, + "source_end_frame": 1868, + "source_start": 60.86666666666667, + "source_end": 62.266666666666666, + "event_indices": [ + 24 + ], + "output_start": 51.4, + "output_end": 52.8 + }, + { + "kind": "reload_card", + "source_frame": 1905, + "source_time": 63.5, + "duration_frames": 24, + "duration": 0.8, + "event_indices": [ + 25 + ], + "label": "REOPENING SAVED SESSION \u2014 reload wait omitted", + "output_start": 52.8, + "output_end": 53.599999999999994 + }, + { + "kind": "source", + "source_start_frame": 2014, + "source_end_frame": 2144, + "source_start": 67.13333333333334, + "source_end": 71.46666666666667, + "event_indices": [ + 26, + 27, + 28 + ], + "output_start": 53.599999999999994, + "output_end": 57.93333333333333 + } + ], + "omitted_source_ranges": [ + { + "source_start": 1.6, + "source_end": 2.1, + "duration_seconds": 0.5, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 3.7, + "source_end": 4.9, + "duration_seconds": 1.2000000000000002, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 12.133333333333333, + "source_end": 12.7, + "duration_seconds": 0.5666666666666664, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 14.3, + "source_end": 14.633333333333333, + "duration_seconds": 0.33333333333333215, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 19.833333333333332, + "source_end": 20.233333333333334, + "duration_seconds": 0.40000000000000213, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 21.833333333333332, + "source_end": 22.066666666666666, + "duration_seconds": 0.23333333333333428, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 24.2, + "source_end": 24.466666666666665, + "duration_seconds": 0.2666666666666657, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 26.8, + "source_end": 27.1, + "duration_seconds": 0.3000000000000007, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 31.7, + "source_end": 32.13333333333333, + "duration_seconds": 0.43333333333333357, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 34.9, + "source_end": 35.9, + "duration_seconds": 1.0, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 40.166666666666664, + "source_end": 40.46666666666667, + "duration_seconds": 0.30000000000000426, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 42.6, + "source_end": 43.766666666666666, + "duration_seconds": 1.1666666666666643, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 44.9, + "source_end": 45.86666666666667, + "duration_seconds": 0.9666666666666686, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 47.0, + "source_end": 47.3, + "duration_seconds": 0.29999999999999716, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 57.266666666666666, + "source_end": 57.63333333333333, + "duration_seconds": 0.36666666666666714, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 59.733333333333334, + "source_end": 60.86666666666667, + "duration_seconds": 1.1333333333333329, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 62.266666666666666, + "source_end": 63.5, + "duration_seconds": 1.2333333333333343, + "reason": "reopen wait replaced by reload card" + }, + { + "source_start": 64.3, + "source_end": 67.13333333333334, + "duration_seconds": 2.833333333333343, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 71.46666666666667, + "source_end": 71.566667, + "duration_seconds": 0.10000033333332681, + "reason": "trailing settled dwell trimmed" + } + ], + "events": [ + { + "index": 0, + "label": "Left click: Cluster 25", + "source_seconds": 0.21, + "output_seconds": 0.21 + }, + { + "index": 1, + "label": "Ctrl + Left click: Cluster 27", + "source_seconds": 2.308, + "output_seconds": 1.8079999999999998 + }, + { + "index": 2, + "label": "Left click: P3 \u00b7 25, 27", + "source_seconds": 5.408, + "output_seconds": 3.708 + }, + { + "index": 3, + "label": "G: merge the first two source clusters", + "source_seconds": 7.034, + "output_seconds": 5.334 + }, + { + "index": 4, + "label": "Left click: Cluster 705", + "source_seconds": 10.742, + "output_seconds": 9.042000000000002 + }, + { + "index": 5, + "label": "Ctrl + Left click: Cluster 22", + "source_seconds": 12.913, + "output_seconds": 10.646333333333335 + }, + { + "index": 6, + "label": "G: merge the first result with one more source cluster", + "source_seconds": 14.826, + "output_seconds": 12.226 + }, + { + "index": 7, + "label": "Left click: Cluster 0", + "source_seconds": 18.438, + "output_seconds": 15.838 + }, + { + "index": 8, + "label": "Ctrl + Left click: Cluster 1", + "source_seconds": 20.439, + "output_seconds": 17.439 + }, + { + "index": 9, + "label": "G: make an unrelated later merge", + "source_seconds": 22.264, + "output_seconds": 19.03066666666667 + }, + { + "index": 10, + "label": "Alt + M: label the unrelated unit MUA", + "source_seconds": 24.662, + "output_seconds": 21.162000000000003 + }, + { + "index": 11, + "label": "Left click: Cluster 707", + "source_seconds": 27.315, + "output_seconds": 23.515 + }, + { + "index": 12, + "label": "Left click: Cluster 706", + "source_seconds": 30.304, + "output_seconds": 26.503999999999998 + }, + { + "index": 13, + "label": "Right click: older nested merge context menu", + "source_seconds": 32.327, + "output_seconds": 28.093666666666664 + }, + { + "index": 14, + "label": "Left click: Restore all merge components in Merge Mode", + "source_seconds": 33.508, + "output_seconds": 29.27466666666667 + }, + { + "index": 15, + "label": "Ctrl + Z: undo the whole recursive restoration", + "source_seconds": 38.297, + "output_seconds": 33.06366666666666 + }, + { + "index": 16, + "label": "Ctrl + Shift + Z: redo the whole recursive restoration", + "source_seconds": 40.655, + "output_seconds": 35.12166666666666 + }, + { + "index": 17, + "label": "V: leave Merge Mode; all three restored clusters stay live", + "source_seconds": 44.075, + "output_seconds": 37.375 + }, + { + "index": 18, + "label": "V: stage the restored components again", + "source_seconds": 46.173, + "output_seconds": 38.50633333333333 + }, + { + "index": 19, + "label": "Left click: Cluster 710", + "source_seconds": 47.515, + "output_seconds": 39.54833333333333 + }, + { + "index": 20, + "label": "Left click: Exclude the third source component", + "source_seconds": 49.004, + "output_seconds": 41.03733333333333 + }, + { + "index": 21, + "label": "G: remerge the exact original SLAY pair", + "source_seconds": 51.861, + "output_seconds": 43.89433333333333 + }, + { + "index": 22, + "label": "Ctrl + Z: undo the remerge; SLAY becomes white", + "source_seconds": 55.35, + "output_seconds": 47.38333333333333 + }, + { + "index": 23, + "label": "Ctrl + Shift + Z: redo the remerge; SLAY becomes green", + "source_seconds": 57.836, + "output_seconds": 49.50266666666666 + }, + { + "index": 24, + "label": "Ctrl + S: save the revised curation", + "source_seconds": 61.184, + "output_seconds": 51.71733333333333 + }, + { + "index": 25, + "label": "Reopen the saved working copy", + "source_seconds": 63.514, + "output_seconds": 52.8 + }, + { + "index": 26, + "label": "View menu: Inspect evidence window", + "source_seconds": 67.317, + "output_seconds": 53.78366666666665 + }, + { + "index": 27, + "label": "Type evidence window index, then Enter", + "source_seconds": 68.119, + "output_seconds": 54.585666666666654 + }, + { + "index": 28, + "label": "Enter: inspect evidence window 1", + "source_seconds": 68.896, + "output_seconds": 55.362666666666655 + } + ], + "checkpoints": [ + { + "name": "01-initial", + "source_seconds": 5.206, + "output_seconds": 3.5060000000000002, + "captured": true + }, + { + "name": "02-first-merge", + "source_seconds": 10.539, + "output_seconds": 8.838999999999999, + "captured": true + }, + { + "name": "03-nested-merge", + "source_seconds": 18.235, + "output_seconds": 15.635, + "captured": true + }, + { + "name": "04-later-edits", + "source_seconds": 30.099, + "output_seconds": 26.299, + "captured": true + }, + { + "name": "05-restored-parents", + "source_seconds": 38.295, + "output_seconds": 33.06166666666667, + "captured": true + }, + { + "name": "06-restore-history", + "source_seconds": 44.074, + "output_seconds": 37.373999999999995, + "captured": true + }, + { + "name": "07-parents-remain-live", + "source_seconds": 46.173, + "output_seconds": 38.50633333333333, + "captured": true + }, + { + "name": "08-excluded-parent", + "source_seconds": 51.86, + "output_seconds": 43.89333333333333, + "captured": true + }, + { + "name": "09-exact-remerge", + "source_seconds": 55.349, + "output_seconds": 47.38233333333333, + "captured": true + }, + { + "name": "10-remerge-history", + "source_seconds": 61.183, + "output_seconds": 51.71633333333333, + "captured": true + }, + { + "name": "11-revised-save", + "source_seconds": 63.514, + "output_seconds": 52.8, + "captured": true + }, + { + "name": "12-reopened", + "source_seconds": 71.167, + "output_seconds": 57.633666666666656, + "captured": true + } + ], + "review_annotations": [ + { + "checkpoint": "02-first-merge", + "text": "First merge: 25, 27 becomes 705", + "output_start_seconds": 6.438999999999998, + "output_end_seconds": 9.139, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "03-nested-merge", + "text": "Second merge: 705 plus 22 becomes 706", + "output_start_seconds": 13.235, + "output_end_seconds": 15.934999999999999, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "04-later-edits", + "text": "Later: merge 707, then mark MUA", + "output_start_seconds": 23.899, + "output_end_seconds": 26.599, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "05-restored-parents", + "text": "One restore: all three original clusters", + "output_start_seconds": 30.66166666666667, + "output_end_seconds": 33.36166666666667, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "08-excluded-parent", + "text": "Exclude restored 710; keep the original pair", + "output_start_seconds": 41.493333333333325, + "output_end_seconds": 44.19333333333333, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "09-exact-remerge", + "text": "Exact pair remerged: SLAY is green again", + "output_start_seconds": 44.98233333333332, + "output_end_seconds": 47.682333333333325, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "12-reopened", + "text": "Reopened: merge 711, separate 710, MUA 707", + "output_start_seconds": 55.23366666666665, + "output_end_seconds": 57.93333333333333, + "label": "review overlay; not part of application UI" + } + ] +} diff --git a/design/carl-feedback-captures/render-narrated-review.py b/design/carl-feedback-captures/render-narrated-review.py new file mode 100644 index 000000000..dba20ea11 --- /dev/null +++ b/design/carl-feedback-captures/render-narrated-review.py @@ -0,0 +1,240 @@ +"""Reassemble the reviewed narration from the archived capture and approved WAV files. + +Requires FFmpeg, NumPy and soundfile; does not generate speech or alter Phy. +""" + +import argparse +import hashlib +import json +import subprocess +import textwrap +from pathlib import Path + +import numpy as np +import soundfile as sf + +parser = argparse.ArgumentParser(description=__doc__) +parser.add_argument('--capture', type=Path, required=True) +parser.add_argument('--approved-audio', type=Path, required=True) +parser.add_argument('--output', type=Path, required=True) +args = parser.parse_args() +source = args.capture.resolve() +approved = args.approved_audio.resolve() +out = args.output.resolve() +# Require a fresh directory to preserve existing review artifacts. +out.mkdir(parents=True, exist_ok=False) +meta = json.loads((approved / 'generation.json').read_text()) +sr = meta['sample_rate'] +# (sentence, first word, end word, video start, video limit); word zero is Bonjour. +plan = [ + (1, 0, None, 0.35, 8.9), + (2, 1, None, 10.0, 15.7), + (3, 1, None, 18.1, 25.9), + (4, 1, None, 26.1, 29.1), + (5, 1, None, 29.3, 33.4), + (6, 1, None, 33.6, 36.8), + (7, 1, None, 37.0, 40.0), + (8, 1, None, 40.2, 43.3), + (9, 1, None, 43.6, 47.2), + (10, 1, None, 47.5, 51.7), + (11, 1, None, 54.1, 57.8), +] +timeline_path = source / 'recursive-review.timeline.json' +caption_path = source / 'recursive-review.ass' +timeline = json.loads(timeline_path.read_text()) +video_duration = timeline['output_duration_seconds'] + +output = np.zeros(round(video_duration * sr), dtype=np.float32) +cues = [] +alignment = [] +last_end = 0 +for number, first, last, start, limit in plan: + info = meta['sentences'][number - 1] + assert first in (0, 1) and last is None, 'Only complete approved sentences are allowed.' + keep_intro = number == 1 + path = approved / (info['with_bonjour'] if keep_intro else info['file']) + clip, rate = sf.read(path) + assert rate == sr and clip.ndim == 1 + a, b = 0, len(clip) / sr + duration = b + assert duration <= limit - start + 1 / sr, (number, duration, limit - start) + assert start >= last_end, (number, start, last_end) + pos = round(start * sr) + output[pos : pos + len(clip)] = clip + last_end = start + duration + text = ('Bonjour. ' if keep_intro else '') + info['text'] + cues.append({'start': start + 0.02, 'end': start + duration, 'text': text}) + alignment.append( + { + 'sentence': number, + 'text': text, + 'source_file': path.name, + 'source_sha256': hashlib.sha256(path.read_bytes()).hexdigest(), + 'source_start': a, + 'source_end': b, + 'output_start': start, + 'output_end': last_end, + 'tempo_factor': 1.0, + } + ) +assert len(cues) == 11 +assert all(x['source_start'] == 0 for x in alignment) +assert ( + min( + alignment[i + 1]['output_start'] - alignment[i]['output_end'] + for i in range(len(alignment) - 1) + ) + >= 0.4 +) +assert ' '.join(c['text'] for c in cues) == ( + 'Bonjour. ' + ' '.join(s['text'] for s in meta['sentences']) +) +sf.write(out / 'narration-timed.wav', output, sr) +subprocess.run( + [ + 'ffmpeg', + '-nostdin', + '-v', + 'error', + '-y', + '-i', + str(out / 'narration-timed.wav'), + '-af', + 'loudnorm=I=-18:TP=-2:LRA=7', + '-ar', + str(sr), + str(out / 'narration-timed-normalized.wav'), + ], + check=True, +) +subprocess.run( + [ + 'ffmpeg', + '-nostdin', + '-v', + 'error', + '-y', + '-i', + str(out / 'narration-timed-normalized.wav'), + '-c:a', + 'libmp3lame', + '-b:a', + '128k', + str(out / 'narration-timed.mp3'), + ], + check=True, +) +(out / 'alignment.json').write_text( + json.dumps( + { + 'phrases': alignment, + 'timing': 'Full approved sentences only; no internal edits, no tempo changes; minimum0.4s silence between sentences', + 'publication': 'Local preview only; not published', + }, + indent=2, + ) + + '\n' +) + + +def ass_time(t): + n = round(t * 100) + h, n = divmod(n, 360000) + m, n = divmod(n, 6000) + s, c = divmod(n, 100) + return f'{h}:{m:02}:{s:02}.{c:02}' + + +def srt_time(t): + n = round(t * 1000) + h, n = divmod(n, 3600000) + m, n = divmod(n, 60000) + s, c = divmod(n, 1000) + return f'{h:02}:{m:02}:{s:02},{c:03}' + + +ass = caption_path.read_text() +# Only move the bottom-centred keycaps; nearby pointer Ctrl badges stay put. +ass = ass.replace(',1060)', ',990)').replace(',1084)', ',1014)') +style = 'Style: Narration,DejaVu Sans,32,&H00FFFFFF,&H00FFFFFF,&H00101010,&H60101010,0,0,0,0,100,100,0,0,3,2,0,2,80,80,30,1\n' +ass = ass.replace('[Events]', style + '\n[Events]') +srt = [] +for n, cue in enumerate(cues, 1): + text = '\\N'.join(textwrap.wrap(cue['text'], width=58)) + ass += f'Dialogue: 8,{ass_time(cue["start"])},{ass_time(cue["end"])},Narration,,0,0,0,,{{\\fad(60,90)}}{text}\n' + srt.append( + f'{n}\n{srt_time(cue["start"])} --> {srt_time(cue["end"])}\n' + + '\n'.join(textwrap.wrap(cue['text'], width=58)) + + '\n' + ) +(out / 'preview.ass').write_text(ass) +(out / 'narration.srt').write_text('\n'.join(srt)) +items = timeline['items'] +filters = [] +labels = [] +for i, item in enumerate(items): + label = f'v{i}' + labels.append(f'[{label}]') + if item['kind'] == 'source': + filters.append( + f'[0:v]trim=start_frame={item["source_start_frame"]}:end_frame={item["source_end_frame"]},setpts=PTS-STARTPTS[{label}]' + ) + else: + frame = item['source_frame'] + pad = max(0, item['duration'] - 1 / 30) + filters.append( + f'[0:v]trim=start_frame={frame}:end_frame={frame + 1},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration={pad:.6f}[{label}]' + ) +ass_path = ( + str(out / 'preview.ass') + .replace('\\', '\\\\') + .replace(':', '\\:') + .replace("'", "\\'") + .replace(',', '\\,') +) +filters.append(''.join(labels) + f'concat=n={len(labels)}:v=1:a=0,ass={ass_path}[outv]') +subprocess.run( + [ + 'ffmpeg', + '-nostdin', + '-y', + '-v', + 'warning', + '-i', + str(source / 'walkthrough.mp4'), + '-i', + str(out / 'narration-timed-normalized.wav'), + '-filter_complex', + ';'.join(filters), + '-map', + '[outv]', + '-map', + '1:a:0', + '-c:v', + 'libx264', + '-preset', + 'veryfast', + '-crf', + '22', + '-threads', + '4', + '-pix_fmt', + 'yuv420p', + '-r', + '30', + '-fps_mode', + 'cfr', + '-c:a', + 'aac', + '-b:a', + '160k', + '-t', + str(video_duration), + '-movflags', + '+faststart', + str(out / 'narrated-preview.mp4'), + ], + check=True, +) +print('Preview complete', flush=True) +print(json.dumps(alignment, indent=2), flush=True) diff --git a/design/carl-feedback-captures/restore-bounded-06-later-edits.png b/design/carl-feedback-captures/restore-bounded-06-later-edits.png new file mode 100644 index 000000000..f992249e9 Binary files /dev/null and b/design/carl-feedback-captures/restore-bounded-06-later-edits.png differ diff --git a/design/carl-feedback-captures/restore-bounded-07-restored-parents.png b/design/carl-feedback-captures/restore-bounded-07-restored-parents.png new file mode 100644 index 000000000..0def333f4 Binary files /dev/null and b/design/carl-feedback-captures/restore-bounded-07-restored-parents.png differ diff --git a/design/carl-feedback-captures/restore-bounded-10-new-combination.png b/design/carl-feedback-captures/restore-bounded-10-new-combination.png new file mode 100644 index 000000000..1909ad895 Binary files /dev/null and b/design/carl-feedback-captures/restore-bounded-10-new-combination.png differ diff --git a/design/carl-feedback-captures/restore-bounded-12-reopened.png b/design/carl-feedback-captures/restore-bounded-12-reopened.png new file mode 100644 index 000000000..44ea1d8ee Binary files /dev/null and b/design/carl-feedback-captures/restore-bounded-12-reopened.png differ diff --git a/design/carl-feedback-captures/restore-bounded-capture.json b/design/carl-feedback-captures/restore-bounded-capture.json new file mode 100644 index 000000000..82c16268d --- /dev/null +++ b/design/carl-feedback-captures/restore-bounded-capture.json @@ -0,0 +1,507 @@ +{ + "mode": "bounded", + "dataset": "FRESH_BOUNDED_ENGINEERING_PACKAGE", + "working_copy": "DISPOSABLE_ISOLATED_COPY", + "capture_scope": "Settled X11 pixels; native XTest context click and Qt input events; not a spontaneous-redraw test", + "revision": "6cf2a4dbc2ec38fdab1ee4a39fe189e1341a1716", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 7.108, + "selected": [ + 40, + 48, + 44 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 10.01, + "selected": [ + 40, + 44, + 48 + ], + "transferred": 48 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 12.743, + "selected": [ + 40, + 44, + 48 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 16.142, + "selected": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "selected_keys": [ + "merge:f27398ae0f9960b6", + "merge:3097c4197d91ff70" + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 24.087, + "selected": [ + 705 + ], + "merged": 705 + }, + { + "name": "06-later-edits", + "title": "A later merge and its MUA label must survive parent restoration", + "seconds": 35.397, + "selected": [ + 706 + ] + }, + { + "name": "07-restored-parents", + "title": "Restore the older merge: real parent clusters in editable Merge Mode", + "seconds": 43.514, + "selected": [ + 707, + 708, + 709, + 710, + 711, + 712, + 713 + ], + "restored": { + "40": 707, + "44": 708, + "48": 709, + "49": 710, + "50": 711, + "51": 712, + "53": 713 + }, + "later_edits_preserved": true + }, + { + "name": "08-restore-history", + "title": "Undo/redo restoration preserves the later merge and label", + "seconds": 49.098, + "selected": [ + 707, + 708, + 709, + 710, + 711, + 712, + 713 + ] + }, + { + "name": "09-parents-remain-live", + "title": "Leaving Merge Mode keeps the restored units available for normal curation", + "seconds": 51.187, + "selected": [ + 707, + 708, + 709, + 710, + 711, + 712, + 713 + ] + }, + { + "name": "10-new-combination", + "title": "Exclude one restored parent and add a new candidate before merging", + "seconds": 59.377, + "selected": [ + 707, + 708, + 709, + 710, + 711, + 712, + 34 + ], + "excluded": 713, + "candidate": 34, + "chosen": [ + 707, + 708, + 709, + 710, + 711, + 712, + 34 + ] + }, + { + "name": "11-revised-save", + "title": "Saved: new merge, excluded parent and unrelated MUA unit are all retained", + "seconds": 64.09, + "selected": [ + 714 + ], + "final_merged": 714, + "excluded": 713, + "unrelated": 706 + }, + { + "name": "12-reopened", + "title": "Reopened: revised merge, excluded parent, unrelated edits and lineage verified", + "seconds": 71.626, + "selected": [ + 714 + ] + } + ], + "input_events": [ + { + "seconds": 0.212, + "label": "Left click: Cluster 40", + "point": [ + 28, + 314 + ], + "click_seconds": 0.85 + }, + { + "seconds": 2.211, + "label": "Ctrl + Left click: Cluster 44", + "point": [ + 28, + 314 + ], + "click_seconds": 2.839 + }, + { + "seconds": 4.244, + "label": "Ctrl + Left click: Cluster 48", + "point": [ + 28, + 178 + ], + "click_seconds": 4.878 + }, + { + "seconds": 7.108, + "label": "Right click: Transfer correlogram row", + "point": [ + 550, + 206 + ], + "click_seconds": 7.743 + }, + { + "seconds": 10.213, + "label": "Left click: P5 \u00b7 40, 44, 48", + "point": [ + 95, + 971 + ], + "click_seconds": 10.844 + }, + { + "seconds": 12.945, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 13.584 + }, + { + "seconds": 16.344, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 16.974 + }, + { + "seconds": 18.472, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "point": [ + 95, + 1103 + ], + "click_seconds": 19.101 + }, + { + "seconds": 20.814, + "label": "G: merge the combined suggestions", + "key_seconds": 21.064, + "key_released_seconds": 22.103 + }, + { + "seconds": 24.29, + "label": "Left click: Cluster 0", + "point": [ + 28, + 348 + ], + "click_seconds": 24.926 + }, + { + "seconds": 26.261, + "label": "Ctrl + Left click: Cluster 1", + "point": [ + 28, + 178 + ], + "click_seconds": 26.902 + }, + { + "seconds": 28.123, + "label": "G: make an unrelated later merge", + "key_seconds": 28.373, + "key_released_seconds": 29.357 + }, + { + "seconds": 30.31, + "label": "Alt + M: label the unrelated unit MUA", + "key_seconds": 30.561, + "key_released_seconds": 31.666 + }, + { + "seconds": 32.678, + "label": "Left click: Cluster 706", + "point": [ + 28, + 178 + ], + "click_seconds": 33.312 + }, + { + "seconds": 35.64, + "label": "Left click: Cluster 705", + "point": [ + 28, + 178 + ], + "click_seconds": 36.268 + }, + { + "seconds": 37.61, + "label": "Right click: older merged unit context menu" + }, + { + "seconds": 38.791, + "label": "Left click: Restore parents in Merge Mode", + "point": [ + 162, + 191 + ], + "click_seconds": 39.425 + }, + { + "seconds": 43.518, + "label": "Ctrl + Z: undo only the parent restoration", + "key_seconds": 43.768, + "key_released_seconds": 44.675 + }, + { + "seconds": 45.645, + "label": "Ctrl + Shift + Z: redo the parent restoration", + "key_seconds": 45.895, + "key_released_seconds": 47.113 + }, + { + "seconds": 49.099, + "label": "V: leave Merge Mode; restored parents stay live", + "key_seconds": 49.349, + "key_released_seconds": 49.427 + }, + { + "seconds": 51.188, + "label": "V: stage the real parents again", + "key_seconds": 51.439, + "key_released_seconds": 51.522 + }, + { + "seconds": 52.526, + "label": "Left click: Cluster 713", + "point": [ + 28, + 579 + ], + "click_seconds": 53.161 + }, + { + "seconds": 54.014, + "label": "Left click: Exclude current parent from the pending merge", + "point": [ + 347, + 318 + ], + "click_seconds": 54.652 + }, + { + "seconds": 56.327, + "label": "Ctrl + Left click: Cluster 34", + "point": [ + 28, + 745 + ], + "click_seconds": 56.963 + }, + { + "seconds": 59.38, + "label": "G: merge the chosen parents and new candidate", + "key_seconds": 59.63, + "key_released_seconds": 60.768 + }, + { + "seconds": 61.765, + "label": "Ctrl + S: save the revised curation", + "key_seconds": 62.015, + "key_released_seconds": 62.347 + }, + { + "seconds": 64.092, + "label": "Reopen the saved working copy" + }, + { + "seconds": 67.772, + "label": "View menu: Inspect evidence window" + }, + { + "seconds": 68.573, + "label": "Type evidence window index, then Enter" + }, + { + "seconds": 69.349, + "label": "Enter: inspect evidence window 7", + "key_seconds": 69.6, + "key_released_seconds": 69.601 + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "display_columns": [ + "group", + "full_count", + "n_spikes", + "ch" + ], + "propositions": [ + { + "key": "merge:f27398ae0f9960b6", + "unit_ids": [ + 40, + 44, + 48 + ] + }, + { + "key": "merge:3097c4197d91ff70", + "unit_ids": [ + 49, + 50, + 51, + 53 + ] + } + ], + "union": [ + 40, + 44, + 48, + 49, + 50, + 51, + 53 + ], + "evidence_window": 7, + "window_waveforms_by_unit": { + "40": 1, + "44": 2, + "48": 2, + "49": 2, + "50": 2, + "51": 1, + "53": 2 + }, + "premerge_colors": { + "40": 0, + "44": 1, + "48": 2, + "49": 3, + "50": 4, + "51": 5, + "53": 6 + }, + "unrelated": { + "inputs": [ + 0, + 1 + ], + "result": 706, + "group": "mua" + }, + "restored": { + "40": 707, + "44": 708, + "48": 709, + "49": 710, + "50": 711, + "51": 712, + "53": 713 + }, + "restored_live_units": true, + "parent_colors_preserved": true, + "excluded_parent": { + "original": 53, + "live": 713 + }, + "new_candidate": 34, + "final_merged": 714, + "chosen": [ + 707, + 708, + 709, + 710, + 711, + 712, + 34 + ], + "later_edits_preserved": true, + "excluded_parent_stays_independent": true, + "historical_review_statuses": { + "merge:f27398ae0f9960b6": "accepted_restored", + "merge:3097c4197d91ff70": "accepted_restored" + }, + "merged": 705, + "assigned_spikes": 17467, + "reopened_initial_evidence_window": 0, + "reopened_selected_evidence_window": 7, + "reopen_window_action": "Explicit Inspect evidence window dialog; not automatic restoration", + "reopened_parent_colors_preserved": true, + "reopened_lineage_correct": true, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/restore-narration-alignment.json b/design/carl-feedback-captures/restore-narration-alignment.json new file mode 100644 index 000000000..9893cc55b --- /dev/null +++ b/design/carl-feedback-captures/restore-narration-alignment.json @@ -0,0 +1,127 @@ +{ + "phrases": [ + { + "sentence": 1, + "text": "Bonjour. Here is the revised merge workflow.", + "source_file": "01-with-bonjour.wav", + "source_sha256": "3a85993e444ac279df46da11dbd204e6bd86c025f7ae77d893f168a35daa948b", + "source_start": 0, + "source_end": 3.6, + "output_start": 0.35, + "output_end": 3.95, + "tempo_factor": 1.0 + }, + { + "sentence": 2, + "text": "First, compare the clusters.", + "source_file": "02-sentence.wav", + "source_sha256": "d95aaeaf50cae81f96972e9b36ecc18beaf4b98119c9e3371e2a07eb90960a14", + "source_start": 0, + "source_end": 2.13, + "output_start": 5.45, + "output_end": 7.58, + "tempo_factor": 1.0 + }, + { + "sentence": 3, + "text": "Hold Control to combine two suggestions, then press G to merge.", + "source_file": "03-sentence.wav", + "source_sha256": "39dbf558fba30f312d8f507d500219b306e6a12d135d934bdfaf13b4a577a625", + "source_start": 0, + "source_end": 4.61, + "output_start": 11.15, + "output_end": 15.760000000000002, + "tempo_factor": 1.0 + }, + { + "sentence": 4, + "text": "Now make an unrelated merge, and mark it as multi-unit activity.", + "source_file": "04-sentence.wav", + "source_sha256": "62feacd70fc45493c22b7d518426eefaa261a96fda2776643bc3873a5e455ff2", + "source_start": 0, + "source_end": 4.21, + "output_start": 20.6, + "output_end": 24.810000000000002, + "tempo_factor": 1.0 + }, + { + "sentence": 5, + "text": "Return to the older merge.", + "source_file": "05-sentence.wav", + "source_sha256": "46f12fecc66a7461fb8c017e7a934993e5e370ecffa9846a2ed4a57f3d3c3463", + "source_start": 0, + "source_end": 2.37, + "output_start": 28.2, + "output_end": 30.57, + "tempo_factor": 1.0 + }, + { + "sentence": 6, + "text": "Restore its parents in Merge Mode.", + "source_file": "06-sentence.wav", + "source_sha256": "12c5d4e9d98334a4513ac9f23ef24ef76342d2c1fded81b96e013959cc52c752", + "source_start": 0, + "source_end": 2.45, + "output_start": 31.3, + "output_end": 33.75, + "tempo_factor": 1.0 + }, + { + "sentence": 7, + "text": "Undo and redo affect only this restoration.", + "source_file": "07-sentence.wav", + "source_sha256": "108838f9419e634cd39f86e69f256fe0a5ee69099bbf67f218f4d99cded7449a", + "source_start": 0, + "source_end": 3.33, + "output_start": 35.4, + "output_end": 38.73, + "tempo_factor": 1.0 + }, + { + "sentence": 8, + "text": "Leaving Merge Mode keeps these parents alive.", + "source_file": "08-sentence.wav", + "source_sha256": "b4dcafd1a8a6e31d5d8a8a8b1f991cc30b2d5560781fb66bcce1653e8d816b54", + "source_start": 0, + "source_end": 2.77, + "output_start": 39.7, + "output_end": 42.470000000000006, + "tempo_factor": 1.0 + }, + { + "sentence": 9, + "text": "Exclude one parent, and add a new candidate with Control-click.", + "source_file": "09-sentence.wav", + "source_sha256": "01cd4c4bf6533915f6d2d5347e4c239d1b69e823a2e94c0a2cee40bb424343a2", + "source_start": 0, + "source_end": 3.73, + "output_start": 43.6, + "output_end": 47.33, + "tempo_factor": 1.0 + }, + { + "sentence": 10, + "text": "Merge the new combination and save.", + "source_file": "10-sentence.wav", + "source_sha256": "3c245c90d99cfb1f8276b2f7425f8c9d303078e0c49c84d3d4537dd49695b8c9", + "source_start": 0, + "source_end": 3.17, + "output_start": 49.45, + "output_end": 52.620000000000005, + "tempo_factor": 1.0 + }, + { + "sentence": 11, + "text": "Reopening preserves the result, the excluded parent, and the later edits.", + "source_file": "11-sentence.wav", + "source_sha256": "12cd08208364b8a0c5ace66dd2526697a85ab6bd1264d64cbb93de6a196bd36f", + "source_start": 0, + "source_end": 4.53, + "output_start": 53.1, + "output_end": 57.63, + "tempo_factor": 1.0 + } + ], + "timing": "Full approved sentences only; no internal edits, no tempo changes; minimum0.4s silence between sentences", + "publication": "Local preview only; not published" +} diff --git a/design/carl-feedback-captures/restore-narration-generation.json b/design/carl-feedback-captures/restore-narration-generation.json new file mode 100644 index 000000000..8561f41cb --- /dev/null +++ b/design/carl-feedback-captures/restore-narration-generation.json @@ -0,0 +1,569 @@ +{ + "model": "kyutai/tts-1.6b-en_fr", + "voice": "unmute-prod-website/fabieng-enhanced-v2.wav", + "batch_size": 4, + "seed": "42+batch_start", + "primer": "Bonjour.", + "primer_extra_padding_frames": 4, + "sample_rate": 24000, + "frame_rate": 12.5, + "elapsed_seconds": 18.546877312939614, + "sentences": [ + { + "number": 1, + "text": "Here is the revised merge workflow.", + "file": "01-sentence.wav", + "with_bonjour": "01-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.93, + "raw_duration_seconds": 3.6, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Here", + 11 + ], + [ + "is", + 16 + ], + [ + "the", + 18 + ], + [ + "revised", + 20 + ], + [ + "merge", + 27 + ], + [ + "workflow.", + 36 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 2, + "text": "First, compare the clusters.", + "file": "02-sentence.wav", + "with_bonjour": "02-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.13, + "raw_duration_seconds": 2.8, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "First,", + 11 + ], + [ + "compare", + 19 + ], + [ + "the", + 23 + ], + [ + "clusters.", + 27 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 3, + "text": "Hold Control to combine two suggestions, then press G to merge.", + "file": "03-sentence.wav", + "with_bonjour": "03-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 4.61, + "raw_duration_seconds": 5.28, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Hold", + 11 + ], + [ + "Control", + 15 + ], + [ + "to", + 20 + ], + [ + "combine", + 24 + ], + [ + "two", + 30 + ], + [ + "suggestions,", + 35 + ], + [ + "then", + 44 + ], + [ + "press", + 47 + ], + [ + "G", + 52 + ], + [ + "to", + 56 + ], + [ + "merge.", + 59 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 4, + "text": "Now make an unrelated merge, and mark it as multi-unit activity.", + "file": "04-sentence.wav", + "with_bonjour": "04-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 4.21, + "raw_duration_seconds": 4.88, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Now", + 11 + ], + [ + "make", + 15 + ], + [ + "an", + 18 + ], + [ + "unrelated", + 20 + ], + [ + "merge,", + 25 + ], + [ + "and", + 33 + ], + [ + "mark", + 35 + ], + [ + "it", + 38 + ], + [ + "as", + 40 + ], + [ + "multi-unit", + 44 + ], + [ + "activity.", + 53 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 0 + }, + { + "number": 5, + "text": "Return to the older merge.", + "file": "05-sentence.wav", + "with_bonjour": "05-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.37, + "raw_duration_seconds": 3.04, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Return", + 11 + ], + [ + "to", + 18 + ], + [ + "the", + 22 + ], + [ + "older", + 25 + ], + [ + "merge.", + 30 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 6, + "text": "Restore its parents in Merge Mode.", + "file": "06-sentence.wav", + "with_bonjour": "06-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.45, + "raw_duration_seconds": 3.12, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Restore", + 11 + ], + [ + "its", + 18 + ], + [ + "parents", + 21 + ], + [ + "in", + 25 + ], + [ + "Merge", + 28 + ], + [ + "Mode.", + 33 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 7, + "text": "Undo and redo affect only this restoration.", + "file": "07-sentence.wav", + "with_bonjour": "07-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.33, + "raw_duration_seconds": 4.0, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Undo", + 11 + ], + [ + "and", + 16 + ], + [ + "redo", + 19 + ], + [ + "affect", + 24 + ], + [ + "only", + 31 + ], + [ + "this", + 36 + ], + [ + "restoration.", + 41 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 8, + "text": "Leaving Merge Mode keeps these parents alive.", + "file": "08-sentence.wav", + "with_bonjour": "08-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 2.77, + "raw_duration_seconds": 3.44, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Leaving", + 11 + ], + [ + "Merge", + 17 + ], + [ + "Mode", + 22 + ], + [ + "keeps", + 25 + ], + [ + "these", + 28 + ], + [ + "parents", + 31 + ], + [ + "alive.", + 35 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 4 + }, + { + "number": 9, + "text": "Exclude one parent, and add a new candidate with Control-click.", + "file": "09-sentence.wav", + "with_bonjour": "09-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.73, + "raw_duration_seconds": 4.4, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Exclude", + 11 + ], + [ + "one", + 16 + ], + [ + "parent,", + 18 + ], + [ + "and", + 27 + ], + [ + "add", + 29 + ], + [ + "a", + 32 + ], + [ + "new", + 34 + ], + [ + "candidate", + 36 + ], + [ + "with", + 42 + ], + [ + "Control-click.", + 46 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + }, + { + "number": 10, + "text": "Merge the new combination and save.", + "file": "10-sentence.wav", + "with_bonjour": "10-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 3.17, + "raw_duration_seconds": 3.84, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Merge", + 11 + ], + [ + "the", + 18 + ], + [ + "new", + 20 + ], + [ + "combination", + 23 + ], + [ + "and", + 31 + ], + [ + "save.", + 39 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + }, + { + "number": 11, + "text": "Reopening preserves the result, the excluded parent, and the later edits.", + "file": "11-sentence.wav", + "with_bonjour": "11-with-bonjour.wav", + "primer_cut_seconds": 0.6699999999999999, + "duration_seconds": 4.53, + "raw_duration_seconds": 5.2, + "transcript": [ + [ + "Bonjour.", + 2 + ], + [ + "Reopening", + 11 + ], + [ + "preserves", + 18 + ], + [ + "the", + 23 + ], + [ + "result,", + 27 + ], + [ + "the", + 36 + ], + [ + "excluded", + 39 + ], + [ + "parent,", + 43 + ], + [ + "and", + 50 + ], + [ + "the", + 52 + ], + [ + "later", + 54 + ], + [ + "edits.", + 58 + ] + ], + "decoder_timestamp_shift_seconds": 0.16, + "batch_start": 8 + } + ], + "approved_audio_sha256": { + "01-sentence.wav": "7c6b28408b8c515bf46cb99571b2c81503398830cb53560cfde16cb3c3616d1a", + "01-with-bonjour.wav": "3a85993e444ac279df46da11dbd204e6bd86c025f7ae77d893f168a35daa948b", + "02-sentence.wav": "d95aaeaf50cae81f96972e9b36ecc18beaf4b98119c9e3371e2a07eb90960a14", + "02-with-bonjour.wav": "054fb208af06eb3ca68c093212c53c465206493594d3947d6808139ff42edabb", + "03-sentence.wav": "39dbf558fba30f312d8f507d500219b306e6a12d135d934bdfaf13b4a577a625", + "03-with-bonjour.wav": "0541633436ea8d220b780c736660c9fca8717ed5b7445d9c3a9eea3f968a807c", + "04-sentence.wav": "62feacd70fc45493c22b7d518426eefaa261a96fda2776643bc3873a5e455ff2", + "04-with-bonjour.wav": "d42b922124406817ce8fa0044cea43a4888d041428cd9e0bbedfc9a8e179f6bd", + "05-sentence.wav": "46f12fecc66a7461fb8c017e7a934993e5e370ecffa9846a2ed4a57f3d3c3463", + "05-with-bonjour.wav": "e88fb65c09dbbb7aec19392b227ea376f491bfeb4115447d9ee4b80ceec77c9a", + "06-sentence.wav": "12c5d4e9d98334a4513ac9f23ef24ef76342d2c1fded81b96e013959cc52c752", + "06-with-bonjour.wav": "5dbec477ebad8ef6d341754a6528eefaa92e36f60fec41dacca075a614679a94", + "07-sentence.wav": "108838f9419e634cd39f86e69f256fe0a5ee69099bbf67f218f4d99cded7449a", + "07-with-bonjour.wav": "ec2805327c7e7359395c4fd1aebf98cc7ad4604b88e34543ca5648bc42af46f8", + "08-sentence.wav": "b4dcafd1a8a6e31d5d8a8a8b1f991cc30b2d5560781fb66bcce1653e8d816b54", + "08-with-bonjour.wav": "ef5bfc09a93f48224f77085d841baef8e6f89db85c5980986d3030baf44dcd5c", + "09-sentence.wav": "01cd4c4bf6533915f6d2d5347e4c239d1b69e823a2e94c0a2cee40bb424343a2", + "09-with-bonjour.wav": "0d4b334254255268626bdcea4c1f16be1a4b288e70184eb33cbdbf9fbdec21a6", + "10-sentence.wav": "3c245c90d99cfb1f8276b2f7425f8c9d303078e0c49c84d3d4537dd49695b8c9", + "10-with-bonjour.wav": "80fa0da1a29f2c41013254329f3d3b84243cc194cd5813b6bf833c5ed6eb7563", + "11-sentence.wav": "12cd08208364b8a0c5ace66dd2526697a85ab6bd1264d64cbb93de6a196bd36f", + "11-with-bonjour.wav": "3771568b5f71b639ed3d3ed7be94504c200b28586aa566b4b1dcf43ae48ed2b5" + }, + "model_revision": "f65439609986c392cb12df63938abcc550c3fb15", + "voice_revision": "323332d33f997de8394f24a193e1a76df720e01a", + "model_license": "CC-BY-4.0", + "voice_license": "CC0", + "generation_environment": { + "python": "3.12", + "torch": "2.9.1+cu128", + "moshi": "0.2.13" + } +} diff --git a/design/carl-feedback-captures/restore-narration.srt b/design/carl-feedback-captures/restore-narration.srt new file mode 100644 index 000000000..28790670b --- /dev/null +++ b/design/carl-feedback-captures/restore-narration.srt @@ -0,0 +1,47 @@ +1 +00:00:00,370 --> 00:00:03,950 +Bonjour. Here is the revised merge workflow. + +2 +00:00:05,470 --> 00:00:07,580 +First, compare the clusters. + +3 +00:00:11,170 --> 00:00:15,760 +Hold Control to combine two suggestions, then press G to +merge. + +4 +00:00:20,620 --> 00:00:24,810 +Now make an unrelated merge, and mark it as multi-unit +activity. + +5 +00:00:28,220 --> 00:00:30,570 +Return to the older merge. + +6 +00:00:31,320 --> 00:00:33,750 +Restore its parents in Merge Mode. + +7 +00:00:35,420 --> 00:00:38,730 +Undo and redo affect only this restoration. + +8 +00:00:39,720 --> 00:00:42,470 +Leaving Merge Mode keeps these parents alive. + +9 +00:00:43,620 --> 00:00:47,330 +Exclude one parent, and add a new candidate with Control- +click. + +10 +00:00:49,470 --> 00:00:52,620 +Merge the new combination and save. + +11 +00:00:53,120 --> 00:00:57,630 +Reopening preserves the result, the excluded parent, and +the later edits. diff --git a/design/carl-feedback-captures/restore-ordinary-06-later-edits.png b/design/carl-feedback-captures/restore-ordinary-06-later-edits.png new file mode 100644 index 000000000..a44eee853 Binary files /dev/null and b/design/carl-feedback-captures/restore-ordinary-06-later-edits.png differ diff --git a/design/carl-feedback-captures/restore-ordinary-07-restored-parents.png b/design/carl-feedback-captures/restore-ordinary-07-restored-parents.png new file mode 100644 index 000000000..d2eabfb44 Binary files /dev/null and b/design/carl-feedback-captures/restore-ordinary-07-restored-parents.png differ diff --git a/design/carl-feedback-captures/restore-ordinary-10-new-combination.png b/design/carl-feedback-captures/restore-ordinary-10-new-combination.png new file mode 100644 index 000000000..2482ac87b Binary files /dev/null and b/design/carl-feedback-captures/restore-ordinary-10-new-combination.png differ diff --git a/design/carl-feedback-captures/restore-ordinary-12-reopened.png b/design/carl-feedback-captures/restore-ordinary-12-reopened.png new file mode 100644 index 000000000..32f82e63a Binary files /dev/null and b/design/carl-feedback-captures/restore-ordinary-12-reopened.png differ diff --git a/design/carl-feedback-captures/restore-ordinary-capture.json b/design/carl-feedback-captures/restore-ordinary-capture.json new file mode 100644 index 000000000..96300e4ee --- /dev/null +++ b/design/carl-feedback-captures/restore-ordinary-capture.json @@ -0,0 +1,428 @@ +{ + "mode": "ordinary", + "dataset": "CARL_SWAY_SOURCE", + "working_copy": "DISPOSABLE_ISOLATED_COPY", + "capture_scope": "Settled X11 pixels; native XTest context click and Qt input events; not a spontaneous-redraw test", + "revision": "6cf2a4dbc2ec38fdab1ee4a39fe189e1341a1716", + "steps": [ + { + "name": "01-initial", + "title": "Real-data cluster comparison before the new workflow", + "seconds": 5.498, + "selected": [ + 9, + 15 + ] + }, + { + "name": "02-right-click-transfer", + "title": "Right-click transfers the correlogram row to Similarity", + "seconds": 7.982, + "selected": [ + 9, + 15 + ], + "transferred": 15 + }, + { + "name": "03-single-suggestion", + "title": "One SLAY suggestion in the Merge workspace", + "seconds": 10.646, + "selected": [ + 9, + 15 + ] + }, + { + "name": "04-control-click-union", + "title": "Ctrl-click combines two suggestions; assignments unchanged", + "seconds": 14.325, + "selected": [ + 9, + 15, + 10, + 13 + ], + "selected_keys": [ + "merge:f79990b25de62781", + "merge:58e6ea5a4536166f" + ], + "union": [ + 9, + 15, + 10, + 13 + ] + }, + { + "name": "05-merged", + "title": "G commits one merge and both suggestion decisions", + "seconds": 21.548, + "selected": [ + 614 + ], + "merged": 614 + }, + { + "name": "06-later-edits", + "title": "A later merge and its MUA label must survive parent restoration", + "seconds": 31.73, + "selected": [ + 615 + ] + }, + { + "name": "07-restored-parents", + "title": "Restore the older merge: real parent clusters in editable Merge Mode", + "seconds": 39.165, + "selected": [ + 616, + 617, + 618, + 619 + ], + "restored": { + "9": 616, + "15": 617, + "10": 618, + "13": 619 + }, + "later_edits_preserved": true + }, + { + "name": "08-restore-history", + "title": "Undo/redo restoration preserves the later merge and label", + "seconds": 43.341, + "selected": [ + 616, + 617, + 618, + 619 + ] + }, + { + "name": "09-parents-remain-live", + "title": "Leaving Merge Mode keeps the restored units available for normal curation", + "seconds": 45.378, + "selected": [ + 616, + 617, + 618, + 619 + ] + }, + { + "name": "10-new-combination", + "title": "Exclude one restored parent and add a new candidate before merging", + "seconds": 53.698, + "selected": [ + 616, + 617, + 618, + 3 + ], + "excluded": 619, + "candidate": 3, + "chosen": [ + 616, + 617, + 618, + 3 + ] + }, + { + "name": "11-revised-save", + "title": "Saved: new merge, excluded parent and unrelated MUA unit are all retained", + "seconds": 57.924, + "selected": [ + 620 + ], + "final_merged": 620, + "excluded": 619, + "unrelated": 615 + }, + { + "name": "12-reopened", + "title": "Reopened: revised merge, excluded parent, unrelated edits and lineage verified", + "seconds": 61.665, + "selected": [ + 620 + ] + } + ], + "input_events": [ + { + "seconds": 0.219, + "label": "Left click: Cluster 9", + "point": [ + 229, + 416 + ], + "click_seconds": 0.85 + }, + { + "seconds": 2.39, + "label": "Ctrl + Left click: Cluster 15", + "point": [ + 229, + 416 + ], + "click_seconds": 3.018 + }, + { + "seconds": 5.498, + "label": "Right click: Transfer correlogram row", + "point": [ + 1020, + 448 + ], + "click_seconds": 6.135 + }, + { + "seconds": 8.184, + "label": "Left click: P1 \u00b7 9, 15", + "point": [ + 95, + 925 + ], + "click_seconds": 8.814 + }, + { + "seconds": 10.848, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 11.483 + }, + { + "seconds": 14.527, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 15.156 + }, + { + "seconds": 16.596, + "label": "Ctrl + Left click: P2 \u00b7 10, 13", + "point": [ + 95, + 1067 + ], + "click_seconds": 17.227 + }, + { + "seconds": 18.975, + "label": "G: merge the combined suggestions", + "key_seconds": 19.226, + "key_released_seconds": 19.759 + }, + { + "seconds": 21.749, + "label": "Left click: Cluster 0", + "point": [ + 28, + 382 + ], + "click_seconds": 22.387 + }, + { + "seconds": 23.826, + "label": "Ctrl + Left click: Cluster 1", + "point": [ + 28, + 178 + ], + "click_seconds": 24.464 + }, + { + "seconds": 25.885, + "label": "G: make an unrelated later merge", + "key_seconds": 26.136, + "key_released_seconds": 26.534 + }, + { + "seconds": 27.336, + "label": "Alt + M: label the unrelated unit MUA", + "key_seconds": 27.586, + "key_released_seconds": 28.037 + }, + { + "seconds": 29.05, + "label": "Left click: Cluster 615", + "point": [ + 28, + 178 + ], + "click_seconds": 29.679 + }, + { + "seconds": 31.938, + "label": "Left click: Cluster 614", + "point": [ + 28, + 178 + ], + "click_seconds": 32.569 + }, + { + "seconds": 33.891, + "label": "Right click: older merged unit context menu" + }, + { + "seconds": 35.07, + "label": "Left click: Restore parents in Merge Mode", + "point": [ + 162, + 191 + ], + "click_seconds": 35.71 + }, + { + "seconds": 39.167, + "label": "Ctrl + Z: undo only the parent restoration", + "key_seconds": 39.418, + "key_released_seconds": 39.722 + }, + { + "seconds": 40.555, + "label": "Ctrl + Shift + Z: redo the parent restoration", + "key_seconds": 40.806, + "key_released_seconds": 41.552 + }, + { + "seconds": 43.342, + "label": "V: leave Merge Mode; restored parents stay live", + "key_seconds": 43.592, + "key_released_seconds": 43.615 + }, + { + "seconds": 45.379, + "label": "V: stage the real parents again", + "key_seconds": 45.629, + "key_released_seconds": 45.654 + }, + { + "seconds": 46.658, + "label": "Left click: Cluster 619", + "point": [ + 28, + 506 + ], + "click_seconds": 47.292 + }, + { + "seconds": 48.146, + "label": "Left click: Exclude current parent from the pending merge", + "point": [ + 611, + 339 + ], + "click_seconds": 48.785 + }, + { + "seconds": 50.401, + "label": "Ctrl + Left click: Cluster 3", + "point": [ + 28, + 767 + ], + "click_seconds": 51.036 + }, + { + "seconds": 53.701, + "label": "G: merge the chosen parents and new candidate", + "key_seconds": 53.952, + "key_released_seconds": 54.447 + }, + { + "seconds": 55.283, + "label": "Ctrl + S: save the revised curation", + "key_seconds": 55.533, + "key_released_seconds": 56.173 + }, + { + "seconds": 57.926, + "label": "Reopen the saved working copy" + } + ], + "recording_fps": 30, + "pointer": "Visible native X11 cursor, eased motion and click ring", + "label": "Real earlier Carl dataset; engineering validation", + "display_columns": [ + "group", + "n_spikes", + "ch" + ], + "propositions": [ + { + "key": "merge:f79990b25de62781", + "unit_ids": [ + 9, + 15 + ] + }, + { + "key": "merge:58e6ea5a4536166f", + "unit_ids": [ + 10, + 13 + ] + } + ], + "union": [ + 9, + 15, + 10, + 13 + ], + "premerge_colors": { + "9": 0, + "15": 1, + "10": 2, + "13": 3 + }, + "unrelated": { + "inputs": [ + 0, + 1 + ], + "result": 615, + "group": "mua" + }, + "restored": { + "9": 616, + "15": 617, + "10": 618, + "13": 619 + }, + "restored_live_units": true, + "parent_colors_preserved": true, + "excluded_parent": { + "original": 13, + "live": 619 + }, + "new_candidate": 3, + "final_merged": 620, + "chosen": [ + 616, + 617, + 618, + 3 + ], + "later_edits_preserved": true, + "excluded_parent_stays_independent": true, + "historical_review_statuses": { + "merge:f79990b25de62781": "accepted_restored", + "merge:58e6ea5a4536166f": "accepted_restored" + }, + "merged": 614, + "assigned_spikes": 48937, + "reopened_parent_colors_preserved": true, + "reopened_lineage_correct": true, + "source_unchanged": true, + "success": true +} diff --git a/design/carl-feedback-captures/restore-pipeline-artifact-provenance.json b/design/carl-feedback-captures/restore-pipeline-artifact-provenance.json new file mode 100644 index 000000000..35d207690 --- /dev/null +++ b/design/carl-feedback-captures/restore-pipeline-artifact-provenance.json @@ -0,0 +1,50 @@ +{ + "REPORT.md": { + "bytes": 1508, + "sha256": "cdffe3f6dc8e91f1755bbcc6633c26b8bb6f719278fecafde3783907555d2708" + }, + "curation-result.json": { + "bytes": 828, + "sha256": "d404ff77cd9f79976acebe3ff2e65a65f6fc3f8f5a7f1a65f0582ebcb5426c91" + }, + "curation-state.json": { + "bytes": 904524, + "sha256": "ed722106dee60ae753bba5337aa299ac0af53198a652cf1b72f26f2d488ba01f" + }, + "final-checks.json": { + "bytes": 961, + "sha256": "0f93b1f3aa2cee28cc3a54dbb0d2af125dfd4219ef2a00022f7a9bdef2c80478" + }, + "final_checks.py": { + "bytes": 4767, + "sha256": "d1d7cc12e96003d33b2364a85c12d6f4d20488af12b259527012583f41c87eeb" + }, + "independent-oracle.json": { + "bytes": 13543, + "sha256": "1ac9d489d9c5141fe630b35e910c9fb5e0de9ba368d8d8a9591f3849de331f10" + }, + "inventory-after.json": { + "bytes": 77280, + "sha256": "6b2cd3875e52cc83940da740e4e08a61dd688d8c76b00e76b73b58bd93b4b529" + }, + "inventory-before.json": { + "bytes": 77280, + "sha256": "6b2cd3875e52cc83940da740e4e08a61dd688d8c76b00e76b73b58bd93b4b529" + }, + "result.json": { + "bytes": 111560, + "sha256": "53984e9c54f00ea3f3ebf963b7e537a971242d668bf967a1abb5e35bb772c6df" + }, + "scenario.json": { + "bytes": 438, + "sha256": "7dd9059fd753b7d36c6cf2bb5c801ec77d03dc91d31a6318519e91838d1ee837" + }, + "validate_pipeline.py": { + "bytes": 18346, + "sha256": "8242e6210810e81ac55a14b6d07ae55c57c06316c8d05a7d5bf21e1e1b33a019" + }, + "verify_parent_restore_replay.py": { + "bytes": 3143, + "sha256": "2745c6d1f03141463c002b36fe8c9e19b9b7533b6a124a56e5518195ce6d99cb" + } +} diff --git a/design/carl-feedback-captures/restore-pipeline-final-checks.json b/design/carl-feedback-captures/restore-pipeline-final-checks.json new file mode 100644 index 000000000..34d57df02 --- /dev/null +++ b/design/carl-feedback-captures/restore-pipeline-final-checks.json @@ -0,0 +1,19 @@ +{ + "all_metadata_field_names_unit_keys_values_and_json_types_exact": true, + "assignment_outputs_are_not_source_hardlinks": true, + "independent_oracle_script_mtime_precedes_run": true, + "independent_oracle_script_sha256": "2745c6d1f03141463c002b36fe8c9e19b9b7533b6a124a56e5518195ce6d99cb", + "metadata_cells_per_output": 31590, + "metadata_fields": 45, + "replay_assignment_payload_sha256_identical": { + "replayed-1": "78879ca3b65a5402035830e5e551a5f360744993af69307dead454d7b3de476d", + "replayed-4": "78879ca3b65a5402035830e5e551a5f360744993af69307dead454d7b3de476d" + }, + "reprepared_byte_budget": 536870912, + "reprepared_bytes": 534554605, + "reprepared_cumulative_metadata_provenance_exact": true, + "reprepared_spike_budget": 2000000, + "seconds": 5.523916601203382, + "source_timestamps_subset_manifest_and_propositions_bytes_preserved": true, + "validation_harness_sha256": "8242e6210810e81ac55a14b6d07ae55c57c06316c8d05a7d5bf21e1e1b33a019" +} diff --git a/design/carl-feedback-captures/restore-pipeline-report.md b/design/carl-feedback-captures/restore-pipeline-report.md new file mode 100644 index 000000000..19ad3aab2 --- /dev/null +++ b/design/carl-feedback-captures/restore-pipeline-report.md @@ -0,0 +1,25 @@ +# Full source restoration validation + +Engineering validation of a converted fixture only: original acquisition clock, exposure and producer export have not been verified. Timings are observations, not benchmarks; other GUI and test workloads run concurrently. + +Code: `e13906ac68510d24df71205d96ca6d5994724c56`. Complete: **True**. Input SHA-256/stat inventories unchanged: **True**. + +The independent oracle checked **469,725,567 rows in each of 2 outputs**, using original labels and raw finite amplitude comparisons. + +| Phase | Seconds | +|---|---:| +| immutable-inventory-before | 11.97 | +| copy-prepared-input | 0.12 | +| public-gui-supervisor-curation-save-reopen | 37.97 | +| full-source-replay-1 | 86.76 | +| full-source-replay-4 | 85.29 | +| independent-original-row-oracle | 12.81 | +| replay-canonical-bytes-counts-labels-reviews-lineage | 89.46 | +| reprepare-one-replayed-full-source | 25.42 | +| reprepared-contract-verification | 0.56 | + +See `result.json`, `scenario.json`, `curation-state.json`, `independent-oracle.json`, and input inventories for exact provenance and checks. + +All **45 metadata fields (31,590 unit cells)** match exactly in both full outputs and the reprepared package, including JSON types. Cumulative metadata provenance also matches. Both assignment payload SHA-256 hashes match; timestamps, subset manifest and producer propositions retain their bytes. See `final-checks.json`. + +Copy method:73 conservative full-copy fallbacks,0 explicit reflinks; all copies use distinct inodes. diff --git a/design/carl-feedback-captures/restore-pipeline-scenario.json b/design/carl-feedback-captures/restore-pipeline-scenario.json new file mode 100644 index 000000000..e954b90bb --- /dev/null +++ b/design/carl-feedback-captures/restore-pipeline-scenario.json @@ -0,0 +1,24 @@ +{ + "excluded_live": 711, + "excluded_original": 49, + "final_merged": 712, + "initial_merge": 705, + "initial_parents": [ + 40, + 44, + 48 + ], + "new_candidate": 50, + "nonfinite": "keep", + "operator": "<", + "restored_merge_target": 708, + "selected_restored_live": 710, + "split_remainder": 707, + "split_selected": 706, + "threshold": -424.19464111328125, + "unrelated_inputs": [ + 0, + 1 + ], + "unrelated_result": 709 +} diff --git a/design/carl-feedback-captures/restore-review.json b/design/carl-feedback-captures/restore-review.json new file mode 100644 index 000000000..e121e600c --- /dev/null +++ b/design/carl-feedback-captures/restore-review.json @@ -0,0 +1,61 @@ +{ + "comment": "https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782", + "asset": "https://github.com/user-attachments/assets/92be1237-6174-4269-bd6b-3bb27f6c0511", + "capture_revision": "6cf2a4dbc2ec38fdab1ee4a39fe189e1341a1716", + "width": 1920, + "height": 1200, + "recording_fps": 30, + "duration_seconds": 57.9, + "frames": 1737, + "bytes": 5088051, + "sha256": "03ce05465181cfdbbaa791a269973c5177fa58e541d30c0ed0e354c3898f388b", + "visible_pointer": true, + "click_cues": true, + "in_window_translucent_keycaps": true, + "stage_annotations": "Labeled REVIEW NOTE overlays, not application UI", + "reload_wait_omitted": true, + "retained_interactions_original_speed": true, + "checkpoints": 12, + "state_checks_passed": true, + "source_unchanged": true, + "native_XTest_context_click": true, + "other_input": "Qt events; settled rendering, not spontaneous repaint or physical routing proof", + "blackdetect": { + "minimum_duration_seconds": 0.2, + "pixel_threshold": 0.02, + "picture_threshold": 0.99, + "intervals_detected": 0 + }, + "inline_player_verified": true, + "uploaded_bytes_verified": true, + "local_dependency_override": "PyQt5-sip12.20.1, separate PR1442", + "core_tests": { + "passed": 692, + "skipped": 13, + "exit_code": 0 + }, + "app_tests": { + "passed": 813, + "skipped": 6, + "exit_code": 0 + }, + "supersedes_asset": "https://github.com/user-attachments/assets/66e293b8-3e2f-4928-9249-a8ad867f16e1", + "narration": { + "language": "English", + "approved_complete_sentences": 11, + "internal_speech_cuts": 0, + "sentence_tempo_changes": 0, + "minimum_silence_between_sentences_seconds": 0.48, + "approved_audio_verified_before_normalization": true, + "codec": "AAC", + "peak_db": -2.0, + "model": "kyutai/tts-1.6b-en_fr", + "voice": "unmute-prod-website/fabieng-enhanced-v2.wav", + "synthetic": true + }, + "english_subtitles_burned_in": true, + "subtitle_cues": 11, + "keyboard_cues_above_subtitles": true, + "reproduction_matches_approved_video_bytes": true, + "media_only_update": true +} diff --git a/design/carl-feedback-captures/restore-review.timeline.json b/design/carl-feedback-captures/restore-review.timeline.json new file mode 100644 index 000000000..09e445e00 --- /dev/null +++ b/design/carl-feedback-captures/restore-review.timeline.json @@ -0,0 +1,712 @@ +{ + "source": "LOCAL_UNCUT_WALKTHROUGH.mp4", + "output": "GITHUB_NATIVE_VIDEO_ATTACHMENT", + "source_fps": "30/1", + "source_duration_seconds": 72.033333, + "output_duration_seconds": 57.9, + "review_cut": true, + "timeline_note": "Original-speed source frames concatenated; idle dwell and reopen wait omitted. Not a latency benchmark.", + "settle_tail_seconds": 0.6499999999999777, + "items": [ + { + "kind": "source", + "source_start_frame": 0, + "source_end_frame": 52, + "source_start": 0.0, + "source_end": 1.7333333333333334, + "event_indices": [ + 0 + ], + "output_start": 0.0, + "output_end": 1.7333333333333334 + }, + { + "kind": "source", + "source_start_frame": 60, + "source_end_frame": 112, + "source_start": 2.0, + "source_end": 3.7333333333333334, + "event_indices": [ + 1 + ], + "output_start": 1.7333333333333334, + "output_end": 3.466666666666667 + }, + { + "kind": "source", + "source_start_frame": 121, + "source_end_frame": 173, + "source_start": 4.033333333333333, + "source_end": 5.766666666666667, + "event_indices": [ + 2 + ], + "output_start": 3.466666666666667, + "output_end": 5.2 + }, + { + "kind": "source", + "source_start_frame": 204, + "source_end_frame": 259, + "source_start": 6.8, + "source_end": 8.633333333333333, + "event_indices": [ + 3 + ], + "output_start": 5.2, + "output_end": 7.033333333333333 + }, + { + "kind": "source", + "source_start_frame": 291, + "source_end_frame": 352, + "source_start": 9.7, + "source_end": 11.733333333333333, + "event_indices": [ + 4 + ], + "output_start": 7.033333333333333, + "output_end": 9.066666666666666 + }, + { + "kind": "source", + "source_start_frame": 373, + "source_end_frame": 435, + "source_start": 12.433333333333334, + "source_end": 14.5, + "event_indices": [ + 5 + ], + "output_start": 9.066666666666666, + "output_end": 11.133333333333333 + }, + { + "kind": "source", + "source_start_frame": 475, + "source_end_frame": 536, + "source_start": 15.833333333333334, + "source_end": 17.866666666666667, + "event_indices": [ + 6 + ], + "output_start": 11.133333333333333, + "output_end": 13.166666666666666 + }, + { + "kind": "source", + "source_start_frame": 548, + "source_end_frame": 600, + "source_start": 18.266666666666666, + "source_end": 20.0, + "event_indices": [ + 7 + ], + "output_start": 13.166666666666666, + "output_end": 14.899999999999999 + }, + { + "kind": "source", + "source_start_frame": 618, + "source_end_frame": 683, + "source_start": 20.6, + "source_end": 22.766666666666666, + "event_indices": [ + 8 + ], + "output_start": 14.899999999999999, + "output_end": 17.066666666666666 + }, + { + "kind": "source", + "source_start_frame": 714, + "source_end_frame": 775, + "source_start": 23.8, + "source_end": 25.833333333333332, + "event_indices": [ + 9 + ], + "output_start": 17.066666666666666, + "output_end": 19.1 + }, + { + "kind": "source", + "source_start_frame": 782, + "source_end_frame": 834, + "source_start": 26.066666666666666, + "source_end": 27.8, + "event_indices": [ + 10 + ], + "output_start": 19.1, + "output_end": 20.833333333333336 + }, + { + "kind": "source", + "source_start_frame": 838, + "source_end_frame": 969, + "source_start": 27.933333333333334, + "source_end": 32.3, + "event_indices": [ + 11, + 12 + ], + "output_start": 20.833333333333336, + "output_end": 25.200000000000003 + }, + { + "kind": "source", + "source_start_frame": 974, + "source_end_frame": 1115, + "source_start": 32.46666666666667, + "source_end": 37.166666666666664, + "event_indices": [ + 13, + 14 + ], + "output_start": 25.200000000000003, + "output_end": 29.900000000000002 + }, + { + "kind": "source", + "source_start_frame": 1122, + "source_end_frame": 1210, + "source_start": 37.4, + "source_end": 40.333333333333336, + "event_indices": [ + 15, + 16 + ], + "output_start": 29.900000000000002, + "output_end": 32.833333333333336 + }, + { + "kind": "source", + "source_start_frame": 1233, + "source_end_frame": 1360, + "source_start": 41.1, + "source_end": 45.333333333333336, + "event_indices": [ + 17 + ], + "output_start": 32.833333333333336, + "output_end": 37.06666666666667 + }, + { + "kind": "source", + "source_start_frame": 1363, + "source_end_frame": 1433, + "source_start": 45.43333333333333, + "source_end": 47.766666666666666, + "event_indices": [ + 18 + ], + "output_start": 37.06666666666667, + "output_end": 39.400000000000006 + }, + { + "kind": "source", + "source_start_frame": 1464, + "source_end_frame": 1565, + "source_start": 48.8, + "source_end": 52.166666666666664, + "event_indices": [ + 19, + 20 + ], + "output_start": 39.400000000000006, + "output_end": 42.76666666666667 + }, + { + "kind": "source", + "source_start_frame": 1570, + "source_end_frame": 1667, + "source_start": 52.333333333333336, + "source_end": 55.56666666666667, + "event_indices": [ + 21, + 22 + ], + "output_start": 42.76666666666667, + "output_end": 46.00000000000001 + }, + { + "kind": "source", + "source_start_frame": 1684, + "source_end_frame": 1843, + "source_start": 56.13333333333333, + "source_end": 61.43333333333333, + "event_indices": [ + 23, + 24 + ], + "output_start": 46.00000000000001, + "output_end": 51.300000000000004 + }, + { + "kind": "source", + "source_start_frame": 1847, + "source_end_frame": 1890, + "source_start": 61.56666666666667, + "source_end": 63.0, + "event_indices": [ + 25 + ], + "output_start": 51.300000000000004, + "output_end": 52.733333333333334 + }, + { + "kind": "reload_card", + "source_frame": 1922, + "source_time": 64.06666666666666, + "duration_frames": 24, + "duration": 0.8, + "event_indices": [ + 26 + ], + "label": "REOPENING SAVED SESSION \u2014 reload wait omitted", + "output_start": 52.733333333333334, + "output_end": 53.53333333333333 + }, + { + "kind": "source", + "source_start_frame": 2027, + "source_end_frame": 2158, + "source_start": 67.56666666666666, + "source_end": 71.93333333333334, + "event_indices": [ + 27, + 28, + 29 + ], + "output_start": 53.53333333333333, + "output_end": 57.9 + } + ], + "omitted_source_ranges": [ + { + "source_start": 1.7333333333333334, + "source_end": 2.0, + "duration_seconds": 0.2666666666666666, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 3.7333333333333334, + "source_end": 4.033333333333333, + "duration_seconds": 0.2999999999999998, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 5.766666666666667, + "source_end": 6.8, + "duration_seconds": 1.0333333333333332, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 8.633333333333333, + "source_end": 9.7, + "duration_seconds": 1.0666666666666664, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 11.733333333333333, + "source_end": 12.433333333333334, + "duration_seconds": 0.7000000000000011, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 14.5, + "source_end": 15.833333333333334, + "duration_seconds": 1.333333333333334, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 17.866666666666667, + "source_end": 18.266666666666666, + "duration_seconds": 0.3999999999999986, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 20.0, + "source_end": 20.6, + "duration_seconds": 0.6000000000000014, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 22.766666666666666, + "source_end": 23.8, + "duration_seconds": 1.033333333333335, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 25.833333333333332, + "source_end": 26.066666666666666, + "duration_seconds": 0.23333333333333428, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 27.8, + "source_end": 27.933333333333334, + "duration_seconds": 0.13333333333333286, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 32.3, + "source_end": 32.46666666666667, + "duration_seconds": 0.1666666666666714, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 37.166666666666664, + "source_end": 37.4, + "duration_seconds": 0.23333333333333428, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 40.333333333333336, + "source_end": 41.1, + "duration_seconds": 0.7666666666666657, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 45.333333333333336, + "source_end": 45.43333333333333, + "duration_seconds": 0.09999999999999432, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 47.766666666666666, + "source_end": 48.8, + "duration_seconds": 1.0333333333333314, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 52.166666666666664, + "source_end": 52.333333333333336, + "duration_seconds": 0.1666666666666714, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 55.56666666666667, + "source_end": 56.13333333333333, + "duration_seconds": 0.5666666666666629, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 61.43333333333333, + "source_end": 61.56666666666667, + "duration_seconds": 0.13333333333333997, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 63.0, + "source_end": 64.06666666666666, + "duration_seconds": 1.0666666666666629, + "reason": "reopen wait replaced by reload card" + }, + { + "source_start": 64.86666666666666, + "source_end": 67.56666666666666, + "duration_seconds": 2.700000000000003, + "reason": "idle or settled dwell trimmed" + }, + { + "source_start": 71.93333333333334, + "source_end": 72.033333, + "duration_seconds": 0.09999966666666182, + "reason": "trailing settled dwell trimmed" + } + ], + "events": [ + { + "index": 0, + "label": "Left click: Cluster 40", + "source_seconds": 0.212, + "output_seconds": 0.212 + }, + { + "index": 1, + "label": "Ctrl + Left click: Cluster 44", + "source_seconds": 2.211, + "output_seconds": 1.9443333333333332 + }, + { + "index": 2, + "label": "Ctrl + Left click: Cluster 48", + "source_seconds": 4.244, + "output_seconds": 3.6773333333333333 + }, + { + "index": 3, + "label": "Right click: Transfer correlogram row", + "source_seconds": 7.108, + "output_seconds": 5.508 + }, + { + "index": 4, + "label": "Left click: P5 \u00b7 40, 44, 48", + "source_seconds": 10.213, + "output_seconds": 7.546333333333333 + }, + { + "index": 5, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 12.945, + "output_seconds": 9.578333333333333 + }, + { + "index": 6, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 16.344, + "output_seconds": 11.644 + }, + { + "index": 7, + "label": "Ctrl + Left click: P7 \u00b7 49, 50, 51, 53", + "source_seconds": 18.472, + "output_seconds": 13.372000000000002 + }, + { + "index": 8, + "label": "G: merge the combined suggestions", + "source_seconds": 20.814, + "output_seconds": 15.113999999999997 + }, + { + "index": 9, + "label": "Left click: Cluster 0", + "source_seconds": 24.29, + "output_seconds": 17.556666666666665 + }, + { + "index": 10, + "label": "Ctrl + Left click: Cluster 1", + "source_seconds": 26.261, + "output_seconds": 19.294333333333334 + }, + { + "index": 11, + "label": "G: make an unrelated later merge", + "source_seconds": 28.123, + "output_seconds": 21.023000000000003 + }, + { + "index": 12, + "label": "Alt + M: label the unrelated unit MUA", + "source_seconds": 30.31, + "output_seconds": 23.21 + }, + { + "index": 13, + "label": "Left click: Cluster 706", + "source_seconds": 32.678, + "output_seconds": 25.41133333333333 + }, + { + "index": 14, + "label": "Left click: Cluster 705", + "source_seconds": 35.64, + "output_seconds": 28.373333333333335 + }, + { + "index": 15, + "label": "Right click: older merged unit context menu", + "source_seconds": 37.61, + "output_seconds": 30.110000000000003 + }, + { + "index": 16, + "label": "Left click: Restore parents in Merge Mode", + "source_seconds": 38.791, + "output_seconds": 31.291 + }, + { + "index": 17, + "label": "Ctrl + Z: undo only the parent restoration", + "source_seconds": 43.518, + "output_seconds": 35.251333333333335 + }, + { + "index": 18, + "label": "Ctrl + Shift + Z: redo the parent restoration", + "source_seconds": 45.645, + "output_seconds": 37.27833333333334 + }, + { + "index": 19, + "label": "V: leave Merge Mode; restored parents stay live", + "source_seconds": 49.099, + "output_seconds": 39.699000000000005 + }, + { + "index": 20, + "label": "V: stage the real parents again", + "source_seconds": 51.188, + "output_seconds": 41.78800000000001 + }, + { + "index": 21, + "label": "Left click: Cluster 713", + "source_seconds": 52.526, + "output_seconds": 42.95933333333334 + }, + { + "index": 22, + "label": "Left click: Exclude current parent from the pending merge", + "source_seconds": 54.014, + "output_seconds": 44.44733333333334 + }, + { + "index": 23, + "label": "Ctrl + Left click: Cluster 34", + "source_seconds": 56.327, + "output_seconds": 46.19366666666667 + }, + { + "index": 24, + "label": "G: merge the chosen parents and new candidate", + "source_seconds": 59.38, + "output_seconds": 49.24666666666668 + }, + { + "index": 25, + "label": "Ctrl + S: save the revised curation", + "source_seconds": 61.765, + "output_seconds": 51.498333333333335 + }, + { + "index": 26, + "label": "Reopen the saved working copy", + "source_seconds": 64.092, + "output_seconds": 52.733333333333334 + }, + { + "index": 27, + "label": "View menu: Inspect evidence window", + "source_seconds": 67.772, + "output_seconds": 53.738666666666674 + }, + { + "index": 28, + "label": "Type evidence window index, then Enter", + "source_seconds": 68.573, + "output_seconds": 54.53966666666666 + }, + { + "index": 29, + "label": "Enter: inspect evidence window 7", + "source_seconds": 69.349, + "output_seconds": 55.31566666666667 + } + ], + "checkpoints": [ + { + "name": "01-initial", + "source_seconds": 7.108, + "output_seconds": 5.508, + "captured": true + }, + { + "name": "02-right-click-transfer", + "source_seconds": 10.01, + "output_seconds": 7.343333333333334, + "captured": true + }, + { + "name": "03-single-suggestion", + "source_seconds": 12.743, + "output_seconds": 9.376333333333333, + "captured": true + }, + { + "name": "04-control-click-union", + "source_seconds": 16.142, + "output_seconds": 11.441999999999998, + "captured": true + }, + { + "name": "05-merged", + "source_seconds": 24.087, + "output_seconds": 17.353666666666665, + "captured": true + }, + { + "name": "06-later-edits", + "source_seconds": 35.397, + "output_seconds": 28.130333333333333, + "captured": true + }, + { + "name": "07-restored-parents", + "source_seconds": 43.514, + "output_seconds": 35.24733333333334, + "captured": true + }, + { + "name": "08-restore-history", + "source_seconds": 49.098, + "output_seconds": 39.69800000000001, + "captured": true + }, + { + "name": "09-parents-remain-live", + "source_seconds": 51.187, + "output_seconds": 41.787000000000006, + "captured": true + }, + { + "name": "10-new-combination", + "source_seconds": 59.377, + "output_seconds": 49.24366666666668, + "captured": true + }, + { + "name": "11-revised-save", + "source_seconds": 64.09, + "output_seconds": 52.733333333333334, + "captured": true + }, + { + "name": "12-reopened", + "source_seconds": 71.626, + "output_seconds": 57.59266666666667, + "captured": true + } + ], + "review_annotations": [ + { + "checkpoint": "06-later-edits", + "text": "Later: merge 706, then mark MUA", + "output_start_seconds": 25.730333333333334, + "output_end_seconds": 28.430333333333333, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "07-restored-parents", + "text": "Restore older 705: editable parents", + "output_start_seconds": 32.84733333333333, + "output_end_seconds": 35.547333333333334, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "09-parents-remain-live", + "text": "Leave Merge Mode; real parents stay live", + "output_start_seconds": 39.387, + "output_end_seconds": 42.087, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "10-new-combination", + "text": "Exclude 713; add candidate 34", + "output_start_seconds": 46.84366666666667, + "output_end_seconds": 49.543666666666674, + "label": "review overlay; not part of application UI" + }, + { + "checkpoint": "12-reopened", + "text": "Reopened: merge 714, separate 713, MUA 706", + "output_start_seconds": 55.19266666666667, + "output_end_seconds": 57.89266666666667, + "label": "review overlay; not part of application UI" + } + ] +} diff --git a/design/carl-feedback-captures/review-30fps.json b/design/carl-feedback-captures/review-30fps.json new file mode 100644 index 000000000..7376ee2a1 --- /dev/null +++ b/design/carl-feedback-captures/review-30fps.json @@ -0,0 +1,19 @@ +{ + "comment": "https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782", + "asset": "https://github.com/user-attachments/assets/c7df489b-6cee-46cb-a841-6dfe23641bc9", + "capture_revision": "b17a3c291d5cefbc10e3096b2bd2e2e0c143cdfb", + "recording_fps": 30, + "width": 1920, + "height": 1272, + "frames": 2261, + "duration_seconds": 75.366667, + "bytes": 4293315, + "sha256": "f60b2cf8f3bb3c1087ddaf26a25115eea0c0a15043a90bb82db222a906424ddb", + "visible_pointer": true, + "click_cues": true, + "input_event_footer": true, + "checkpoints": 10, + "state_checks_passed": true, + "source_unchanged": true, + "gh_version": "2.104.0" +} diff --git a/design/carl-feedback-captures/review-integrated.json b/design/carl-feedback-captures/review-integrated.json new file mode 100644 index 000000000..437a487ab --- /dev/null +++ b/design/carl-feedback-captures/review-integrated.json @@ -0,0 +1,28 @@ +{ + "comment": "https://github.com/cortex-lab/phy/pull/1428#issuecomment-6946254782", + "capture_revision": "3d8b492e3e88417d40347916cdf65a1ab8a53229", + "width": 1920, + "height": 1200, + "recording_fps": 30, + "duration_seconds": 42.866667, + "frames": 1286, + "bytes": 3298072, + "sha256": "4695414e3baa436426d192a2595641f1079fa0434634c7104691ffd16343501f", + "visible_pointer": true, + "click_cues": true, + "in_window_translucent_keycaps": true, + "reload_wait_omitted": true, + "retained_interactions_original_speed": true, + "checkpoints": 10, + "state_checks_passed": true, + "source_unchanged": true, + "blackdetect": { + "minimum_duration_seconds": 0.2, + "pixel_threshold": 0.02, + "picture_threshold": 0.99, + "intervals_detected": 0 + }, + "asset": "https://github.com/user-attachments/assets/9e840a5e-c2e8-433f-a040-93b3394f75b9", + "inline_player_verified": true, + "uploaded_bytes_verified": true +} diff --git a/design/carl-feedback-validation.md b/design/carl-feedback-validation.md new file mode 100644 index 000000000..0295bcecc --- /dev/null +++ b/design/carl-feedback-validation.md @@ -0,0 +1,363 @@ +# Carl's curation requests: validation and limits + +Implementation branch: `feature/carl-curation-feedback`, based on the long-recording +curation branch with current master merged before implementation. The original +request attachments were copied from MBA to local storage before implementation. +No request attachments or user data are committed here. + +## Behavioral checks + +- Bounded correlogram row transfer uses the same Supervisor operation as ordinary + correlograms. Tests cover reference promotion, protecting the final staged unit, + and close/reopen without duplicate callbacks. +- Ctrl-clicking SLAY suggestions changes only the comparison selection. The unit + union is stable and deduplicated. Explicit G records all selected acceptances + in one undoable operation; unrelated suggestions are never autoaccepted. + Tests cover invalid/stale suggestions, failing preflight, cancel, assignment + and review undo/redo, bounded save/reload, unchanged producer JSON, and replay + against every source row. +- Parent inspection uses exact immediate parent membership. Its views have no + curation actions and do not publish channel/time/transfer click events. Tests + cover nested merges, splits, undo/redo, persistence, stale history, bounded + predicate history, exact partition checks, and callback cleanup. See + [the parent implementation note](parent-review-implementation.md) for limits. +- Performance tests compare serial/parallel arrays, row bytes, index bytes and + Merkle data; sparse large IDs, NaNs, threshold ties, split/merge metadata, + cancellation, hash mutation and deliberately corrupted clones have dedicated + cases. Cloning never uses hardlinks and preserves existing destinations. + +## Synthetic measurements + +Measurements are single synthetic runs on this Linux machine (Intel i9-14900K, +CPython 3.12.13, NumPy 2.4.3), with cached files and `tracemalloc` active. They do +not measure Carl's 185 GB dataset, his machine, or cold-storage behavior. Traced +scratch is not whole-process RSS. Times are illustrative, not acceptance limits. + +The lookup/histogram microbenchmark uses 10 million spikes, 1173 units, 2050 +bins, and batches of 100,000. Replacing per-batch search and scatter with a +capped unit lookup and tiled histogram took approximately 0.115 s versus 1.344 s +(11.7×), with exact counts and sums. This isolates a kernel, not preparation as +an end-to-end command. + +The dense pipeline fixture uses 8 million spikes, 16 units, two bins and 192 MB +of source arrays. The row/index configured global scratch budget is 256 MiB. + +| Pass | One worker | Four workers | Ratio | +| --- | ---: | ---: | ---: | +| Source-file hashes | 0.1437 s | 0.0746 s | 1.93× | +| Row snapshot | 0.8706 s | 0.4717 s | 1.85× | +| Amplitude index | 1.5101 s | 0.7256 s | 2.08× | + +Corresponding traced peak scratch bytes (one → four workers): hash 2,105,230 → +7,391,690; row snapshot 94,201,452 → 99,773,006; index 16,848,615 → 52,436,623. +Every compared output and Merkle byte was equal. In an earlier smaller fixture +(2 million spikes, 128 units, eight bins), four-worker row/index construction +was slower than serial. Consequently the default remains one worker. + +Reproduce from a synced development checkout: + +```bash +uv run --no-sync python design/benchmarks/summary_histograms.py +uv run --no-sync python design/benchmarks/bounded_parallel.py +``` + +Native stable integer grouping is retained. No claim about NumPy's internal +indirect sorting algorithm is required for correctness or performance. + +## Remaining empirical limits + +Headless tests establish view providers and curation state, not physical display +presentation. Ordinary merges made before lineage recording remain unavailable; +no template-based guess is substituted. Parent comparison is limited to 16 +immediate parents, and plots obey existing evidence budgets. Bounded parent +views describe retained windows; full split-parent counts can be unavailable. + +The follow-up [rendered real-data validation](carl-feedback-captures/README.md) +now covers Carl's earlier 469.7-million-spike fixture, including full replay and +matched baseline timings. His newer 5.24-billion-spike recording remains +unavailable locally, so its end-to-end improvement and worker choice still need +measurement there. + +## Final integrated checks + +On the combined implementation (including the cancellation and output-contract +follow-ups), the standard component targets completed with exit status zero: + +- `make test UV_RUN='uv run --no-sync'`: 682 passed, 13 skipped. +- `make test-apps UV_RUN='uv run --no-sync'`: 788 passed, 6 skipped. +- Together these cover the `make test-full` test partitions: 1470 passed, + 19 skipped. Both targets include their required lint/format checks. +- `make doc-check UV_RUN='uv run --no-sync'` and `uv build` passed. +- Both checked-in benchmark scripts ran successfully and compared equal + serial/parallel outputs. The wheel contains every new runtime module. + +Two earlier coverage-enabled core runs completed all assertions and then exited +with signal 11 during interpreter shutdown. Fault tracing reported no Python +frame; the kernel log confirmed a native fault. The final standard core run +exited normally, as did debugger runs with and without coverage and with normal +address randomization. No native stack identified the cause, so no speculative +renderer or ownership change was made. A similar unresolved shutdown limitation +was already recorded in `slay-roundtrip-validation.md` before these changes. +This remains an intermittent harness/runtime limitation, not a claim that native +shutdown has been fixed or that the cause is established as harmless. + + +## Follow-up on real data + +See [screenshots, complete recordings, replay and timing reports](carl-feedback-captures/README.md). +The rendered walkthrough found and fixed hidden parent controls and excessive +legend height. Application checks now pass 791 tests (6 skipped); the core +partition passes 682 assertions (13 skipped), but the native shutdown fault +recurred after that summary in the latest full-target attempt. We do not report +that invocation as a clean full-suite pass. Both real GUI processes and both +469,725,567-row replay pipelines exited normally, with unchanged source hashes. + + +## November 19: growing-journal curation follow-up + +Carl and Andrew's logs contained two recoverable Python exceptions: an absent +optional parent-color configuration directory, and stale Similarity selection +after the final primary reference disappeared. Focused regressions cover both, +plus backward batch selection and reordering the blue reference independently +of its identity and color. + +The performance PDF described 20,216,806 evidence spikes and 213 journal events +on a newer 6.75-billion-spike source. That exact checkpoint/source was unavailable. +The following engineering measurements use disposable fixtures on this Linux +machine, Python 3.12.13, NumPy 2.4.3 and phylib 2.7.1. OS caches were uncontrolled. +Raw profiles and user attachments remain outside Git; compact measurements and +revision attribution are in [the result JSON](benchmarks/carl-nov19-results.json). + +### Isolated metadata actions + +The synthetic fixture retains 20,216,806 rows across 859 source units. A fixed +100-merge prefix holds the live catalogue constant; labels extend the journal +to 100, 213 and 1,000 events. Three unprofiled label actions per case give: + +| Initial events | Before median | After median | Full projections per label | +| --- | ---: | ---: | --- | +| 100 | 29.745 s | 0.802 ms | 3 → 0 | +| 213 | 29.717 s | 0.809 ms | 3 → 0 | +| 1,000 | 29.500 s | 0.855 ms | 3 → 0 | + +These timings isolate supervisor actions without GUI tables/views. They show +that repeated assignment projection caused the dominant cost; they do not prove +all work is independent of journal/catalogue size. Event-reference and metadata +bookkeeping still scale with their respective small collections. Each measured +case also compares final assignments against the sequential reference projector. +Whole-process peak RSS, including fixture construction, was 4.00 GB before and +3.96 GB after; this is not an action-specific memory measurement. + +### GUI actions + +A guarded copy of the existing real-source bounded fixture retains 7,298,318 +rows from 469,725,567 source spikes. Both runs seed 213 events including the +same 100 merges, use Evidence Amplitude and Unit Stability views, and measure +two unprofiled samples under private Xvfb/software Mesa. Both controller +threading settings are recorded. Readiness means the supervisor/view queues +plus one Qt timer turn, rather than physical frame presentation. + +| Action | Before median | Final optimized median | +| --- | ---: | ---: | +| Move to good and next selection | 16.523 s | 0.794 s | +| Label | 15.844 s | 0.194 s | +| Merge | 7.912 s | 2.687 s | +| Undo | 7.966 s | 2.857 s | + +Every GUI worker exited normally and all input package hashes were unchanged. +The final follow-up refreshes affected metadata rows and preserves unchanged +stability artists. Its focused tests retain filters, sorting, selection, custom +metrics and plugin events; membership edits and asynchronous summaries redraw. +Unknown or replaced metric providers refresh across all live units because their +values can depend on other clusters. Only unchanged built-in provider identities +use the narrower metadata refresh. Array-valued metrics retain table support. +Merge/undo still include metric refresh and selected-unit plot reconstruction. + +Reproduce on a synced checkout with new output directories: + +```bash +uv run --no-sync python tools/profile_bounded_actions.py --help +uv run --no-sync python tools/profile_bounded_gui.py --help +``` + +### Full-source correctness + +Replay of the previously validated saved checkpoint on runtime code at +`22eed44f` completed in 52.99 seconds with one worker; complete validation took +98.62 seconds. This is a single warm-cache run, not a baseline speed comparison. +All **469,725,567 assignments** matched both earlier one-/four-worker outputs; +all 52 compared metadata/JSON files, lineage and rewritten parameters matched. +A separate original-label/raw-amplitude oracle also passed, including split +counts 1,691,273 and 1,597,610, with 700 final active units. All 156 named input +files retained their hashes and identity statistics. Runtime module hashes were +unchanged during the run. Peak process RSS was 26.68 GiB including mapped pages. + +Incremental native edits, bounded inverse-history retention and compiled export +writing retain full validation on Save/load and an independent sequential +interpreter for export verification. Cache misses replay validated history; +the new fast path does not remove those fallback and integrity checks. + + +### Final local gates + +On the integrated runtime (`c2d541f0`, followed by documentation/results only), +`make test-full UV_RUN='uv run --no-sync'` exited normally with **739 common and +893 application tests passed**, 19 skipped in total. It includes lint and +formatting checks. `make doc-check` and `uv build` passed, and the wheel contains +all new runtime modules. The locked environment uses PyQt5-sip 12.17.0. + +The independently scoped shared `master` changes at `306667e4` passed their own +full suite (**673 common + 168 application tests**, 19 skipped), documentation, +lint and formatting checks with normal exits. The PR1428 branch incorporates +those shared changes without merging PR1428 into master. + +The previous remote CI run at `8c232422` failed after successful pytest summaries +on four matrix jobs (Unix exit 139; Windows exit 1). These are recorded separately +from assertion failures. Local normal exits do not establish that this existing +remote runtime problem is fixed; the separate dependency-fix PR is unchanged. + + +### Sampled near-zero pair exclusion (PR1428 only) + +The follow-up implements pair exclusion in Sampled Correlogram View only. It +filters raw integer-sample delays before histogram binning, independently for +auto and cross pairs, with inclusive boundaries and a default half-width of +0.3 ms. Both switches start off. No spike is removed from the retained trains; +all longer-lag pair contributions remain eligible. Window boundaries and the +existing central-bin conventions are preserved. The conditional-uniform chance +line uses the same pair-specific exclusion when evaluating off-center exposure. + +Independent all-pairs and exhaustive discrete-clock oracles cover all four +switch combinations, partial bins, sample boundaries, ties, sparse/reversed IDs, +late clocks and observation gaps. View regressions cover legacy providers, +keyboard scope/customization, unchanged input arrays and curation history, +GUI-state restoration, and live merge/split/undo membership changes. Actual +canvas-click keyboard tests also pass under Xvfb/xcb with software OpenGL. The +visible status prefix retains active flags/width when the dock truncates text. + +On the same 7,298,318-row fixture (175 windows), fixed selected units 40/44/48 +contain 18,605 retained spikes. Three unprofiled repeats with 0.5 ms bins and a +50 ms correlogram window produced the following medians on this machine: + +| Half-width | Disabled | Cross only | Auto only | Both | +| --- | ---: | ---: | ---: | ---: | +| 0.3 ms | 37.75 ms | 34.64 ms | 33.63 ms | 32.57 ms | +| 2 ms | 36.24 ms | 34.14 ms | 33.98 ms | 31.70 ms | + +These are warm-mapping provider timings, not complete GUI/presentation timings +or a general speedup claim. All calls reuse the same read-only integer arrays; +input hashes are unchanged. Peak process RSS was 337 MiB, including mapped +pages and imports, rather than a per-case allocation measurement. The compact +benchmark JSON records the exact statistics module SHA256 and case results; +that module is committed in `d1018a63`. Existing ordinary Correlogram View, +source assignments, replay and master remain unchanged by this feature. + + +The integrated exclusion runtime at `d1018a63` passed `make test-full` with a +normal process exit: **739 common + 972 application tests passed**, 19 skipped. +The target includes lint and formatting checks. Strict `make doc-check` and +`uv build` passed. The eight UI/provider tests present during the real +Xvfb/xcb run passed; the additional live-membership oracle test also passes in +the full suite. Master remains at `306667e4`; this follow-up is PR1428 only. + + +### November 22 requests: recovery, annotations and RP investigation + +The three PDFs downloaded on MBA were fetched read-only and retained with +SHA256 provenance under `phy-data/carl/feedback-2026-11-22`. The deduplication +request matches the existing sampled pair-exclusion feature. SLAY's requested +axis-label grouping is implemented separately from trace color semantics. + +The RP investigation is an external prototype, not a shipped estimator. Its +12 tests establish aligned uint32 sample-offset encoding, authenticated paired +chunks, independent iterator cursors, 64-bit absolute clocks, and rejection of +inconsistent metadata. A five-million-row synthetic warm-cache trial added +20 MB of offsets to 30 MB of base records. It built in 0.153 seconds and read, +authenticated, decoded and oracle-compared in 0.088 seconds. These timings do +not measure deduplication, RP estimation, cold storage, or Carl's 6.75-billion- +spike recording. The real fixture's base record is five bytes rather than the +synthetic fixture's six; neither existing store was rewritten. + +Two small counterexamples demonstrate unresolved producer conventions. With +spikes at samples 995 and 1005 and window [0,1000), attributing a pair to its +earlier bin counts a violation that a both-endpoints-inside rule excludes. +With spikes at 996 and 1004, amplitudes 1 and 2, and exclusion radius 9, +global amplitude-greedy deduplication leaves no spike inside that window, +whereas window-local deduplication retains one. Merged-parent violation counts +are also nonadditive. A display-only pair mask cannot implement this metric. + +The next RP gate is the exact `phytastic` repository and commit used for the +figures, or its `export.py` and `rp_windows.py`, together with SpikeInterface +and DARTsort versions. Scoped local/MBA and connected-source searches did not +locate these files; no request was sent. The proposed next step is an independent +small-data oracle against that producer before implementing an optional exact- +time sidecar, full-train deduplication and a background RP panel. Existing raw +rate/count summaries must retain their definitions. + +Draft protection captures immutable active-journal/catalog references only after +the outer curation transaction settles. A single worker writes coalesced +snapshots; two independently verified heads rotate by successful writes rather +than revision parity. Private files/directories, durable ancestor creation, +live-owner locks, checksum fallback, canonical-pointer conflicts, allocator +high-water marks, and explicit discard/retirement have focused regressions. +Checkpoint publication remains separate. Recovered work starts a new undo +baseline and stays dirty; saving retires the recovered source draft without +deleting a newer foreign head. Failed or uncertain Save outcomes do not invent +a successful protection acknowledgement. + +The close-path review found that existing callbacks disconnected the workspace +before a later save prompt could veto closure. GUI state capture now runs in +`close_accepted`, after every veto and before geometry persistence; resource +cleanup runs in `closed`. Regression tests preserve Merge mode, staged selection, +parent inspection, controller selection hooks and logging after cancellation. + +Native Xvfb/xcb screenshots on a new 12-spike synthetic fixture cover neutral +and amber states at 1100×700 and 1600×900. Actual checkpoint/draft acknowledgements +were used; only the reminder widget's clock advanced by 902 seconds. The fixed +status area was 520×26 pixels and its Save button 171×26 in all four captures. +The indicator remained outside the plots and the colored SLAY axes were visible. +Artifacts and exact code hashes are in +`phy-data/carl/recovery-visual-review-2026-11-22/final-002`. + +An external 5 ms Qt heartbeat probe measured two consecutive worker writes per +case, including previous-head verification. At 10,000 valid label events, writes +took 28.4/41.0 ms with maximum observed UI gaps of 15.4 ms. At 100,000 events, +writes took 173.5/318.7 ms with maximum gaps of 76.5/75.8 ms; none exceeded +100 ms. This is a small warm-cache experiment, not a latency guarantee. Python +JSON encoding can briefly hold the GIL even on a worker; protection avoids +spike-array scans/copies on the GUI thread but is not strictly pause-free for +arbitrarily large journals. The probe script, raw gaps and code hashes are in +`phy-data/carl/recovery-validation-2026-11-22/heartbeat_probe.json`. No original +Carl data was read or modified by either recovery experiment. + +The integrated changes passed `make test-full UV_RUN='uv run --no-sync'` with +the CI-matching Qt offscreen backend under Xvfb: **744 common + 1,016 application +tests passed**, 19 skipped, with normal process exits. This includes lint and +formatting. Two earlier full-native probes without a window manager encountered +shortcut/focus assumptions; they are not recorded as successful full-native +runs. The proposition text-focus assertion now explicitly waits for focus. +Native recovery, close-cancellation and screenshot checks passed separately. + +A final indicator-only refinement distinguishes retained startup warnings from +actual protection failures: a warning shows “Draft needs attention” while a +genuine error shows “Protection failed.” All nine reminder/status tests were +rerun under native xcb after that refinement and passed; lint, formatting and +the package build passed again. Strict `make doc-check` passed for the published +documentation. The wheel includes all recovery and proposition-annotation +modules. Master remains `306667e4`; these changes target the existing PR1428. + +The first remote run on `3ea319eb` reproduced the known native shutdown failure: +Ubuntu 3.11/3.12 passed all 1,760 tests and then exited 139; Windows 3.11 passed +all 1,750 platform-eligible tests and then exited 1. No assertion failures were +observed. Codespell, documentation, integration and the other six matrix jobs +passed. This run is explicitly not a clean CI result. + +A feature-free QtCore subprocess experiment with SIP 12.17.0 crashed at all +three wrapper counts (256, 1,024 and 4,096), with no Phy imports or curation +data. The already-prepared dependency fix from `a8cf001d` was therefore carried +onto PR1428 as a separate follow-up: require `PyQt5-sip>=12.20.1,<13` and update +only that locked runtime. This does not merge PR1442 or change master. All three +shutdown regression cases pass on 12.20.1; lint, formatting, strict docs and +package build pass again. The final gate uses the exact combined CI pytest +command and requires a normal process exit, rather than suppressing shutdown or +splitting the test process to avoid the native failure. diff --git a/design/carl-oct29-stability.md b/design/carl-oct29-stability.md new file mode 100644 index 000000000..f5ad7a7a6 --- /dev/null +++ b/design/carl-oct29-stability.md @@ -0,0 +1,65 @@ +# Carl's 29 October stability report + +The console records checkout `6855aae4`, successful row-store and amplitude-index +preparation, rapid Similarity navigation errors, then a shutdown abort. The +accompanying 28 October PDF describes the older full-source scan cost. Preparation +success alone does not establish the path or latency of later GUI summary jobs. + +## Selection and curation targets + +Table selection changes immediately, while its events are debounced. Keeping +only the last incremental mutation lost transitions required by the canonical +selection reducer. Its strict `before_ids` guard correctly detected divergence. +Repeated Next actions could keep failing until the primary selection reset. + +An isolated 12-spike bounded fixture also reproduced a target-safety issue: +a pending Next displayed primary/candidate `[0, 2]` while canonical state still +held `[0, 1]`. Immediate merge recorded parents `[0, 1]`; label and Move Similar +likewise affected the old candidate. This reproduction does not establish that +Carl's saved dataset was affected. + +The fix retains a bounded ordered mutation batch on its own debounce key. A +scratch controller validates and reduces all intents before applying the result +atomically; expensive presentation is published once. Projections and resets +invalidate superseded generations. Overflow drains operations rather than +dropping them. Curation boundaries settle both tables before target resolution, +semantic preflight, transaction snapshots and action history capture. Reentrant +or nonsettling selection observers fail before a curation mutation. + +Permanent regressions include rapid actual Next actions, mixed intent/color +semantics, hidden selections, reference resets, unrelated debounced events, +atomic failure, bounded draining and role transfers. Bounded direct/shortcut +merge, label and move tests check exact native targets, journal entries, history, +saved metadata and full-source replay. Graphical splitting rejects a preview +made obsolete by a pending reference change. + +## Generic task shutdown + +`TaskWidget.dispose()` evaluated a deleted manager's Qt signals before its +exception guard. Owner cleanup could then stop before cancellation. Independently, +a worker finishing after manager deletion could release its task key but strand +manager ownership because terminal delivery required the deleted receiver. + +Generic workers now retain only a plain Python record/context. A GUI timer polls +bounded progress and terminal mailboxes. Detached managers continue terminal +polling without owner callbacks; QObject destruction cancels work and releases +manager ownership on the GUI thread. Worker completion never accesses Qt. Short +commit-aware publication and synchronous task chaining are preserved. + +Widget and owner cleanup tolerate destruction order, including prompt preflight +tasks. Subprocess regressions cover deleted managers before active/committed +workers finish and full GUI destruction after idle/completed manager deletion. +The live-summary reader has a separate existing delivery mechanism; this change +does not replace every worker lifecycle in Phy. + +## Runtime evidence and validation + +The GUI integration regression covers source, row-store and amplitude-index +paths separately. The amplitude case spies successful range resolution for new +split expressions and rejects both row-store and source fallback. Existing +count/trend checks, save/reopen and full-source replay remain in that test. The +GUI preparation/handover test also asserts actual range queries after attachment. + +One debug line per live-summary job reports path, unit count and elapsed time. +It distinguishes `amplitude-index`, `row-store`, `source` and `prepared/cache`; +there is no per-spike logging or new index algorithm in this fix. diff --git a/design/ccg-shortcut-regression-2026-11-25.json b/design/ccg-shortcut-regression-2026-11-25.json new file mode 100644 index 000000000..50e3c22a8 --- /dev/null +++ b/design/ccg-shortcut-regression-2026-11-25.json @@ -0,0 +1,43 @@ +{ + "report": "Carl reported D / Shift+D no longer working; email reported by user as 2026-11-24 19:53. Exact affected version and focus context unknown.", + "base_commit": "acd944d754ba210430ad9c85f2db356aa430054a", + "reproduction": { + "headless_existing_tests": "79 passed; did not reproduce native focus problem", + "native_existing_shortcut_tests": "2 passed with minimal GUI", + "native_full_bounded_gui_before_fix": "D fails to enable auto exclusion despite focused native canvas; waitUntil times out. Reproduced again with explicit native requestActivate and verified QApplication.focusWindow() == canvas.", + "focus_observation": "QApplication widget focus can remain on another dock button or be None while the native canvas receives keys. Dock WidgetWithChildrenShortcut cannot activate.", + "logs": [ + "/tmp/phy-ccg-native-full.log", + "/tmp/phy-ccg-activated.log" + ] + }, + "fix": "Fallback only for unconsumed key events delivered to the focused native sampled-correlogram canvas. Trigger the existing enabled QAction matching its current shortcut. Preserve shortcut remapping, first-instance shortcut policy and table/editor isolation.", + "validation": { + "native_command": "QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 xvfb-run -a uv run --no-sync pytest --no-cov -q phy/apps/large_recording/tests/test_ccg_exclusion_view.py phy/apps/large_recording/tests/test_ccg_exclusion.py", + "native_results": "81 passed in 6.76s", + "new_test": "Full bounded GUI, D and remapped X, Shift+D; auto/cross histogram contributions independent; toggling restores original histogram; no curation events or assignment changes.", + "full_suite": { + "command": "make test-full UV_RUN='uv run --no-sync'", + "results": [ + "747 passed, 13 skipped in 147.94s (0:02:27)", + "1081 passed, 6 skipped, 136 warnings in 463.31s (0:07:43)" + ], + "log": "/tmp/phy-ccg-fixed-full.log", + "lint": "passed", + "format_check": "passed" + }, + "native_log": "/tmp/phy-ccg-native-exact.log", + "ci_regression": "Added shortcut and full bounded GUI tests to the existing Linux xcb/software-OpenGL CI step; exact pytest command passes 4 tests, 7 deselected.", + "docs": "make doc-check UV_RUN=\"uv run --no-sync\" passed", + "ci_yaml": "Parsed successfully; native test command verified" + }, + "limits": [ + "Native validation uses Xvfb and software OpenGL, not Carl's machine.", + "This reproduces a matching symptom; cannot establish Carl's exact version or rule out a second cause." + ], + "publication": "on hold at user request; no push, GitHub comment or email", + "source_sha256": { + "phy/apps/large_recording/views.py": "dcf313497d6a4821e99864dcb47a9a9ec189a20e23661eed98fc5614bc5ada20", + "phy/apps/large_recording/tests/test_ccg_exclusion_view.py": "65e7dc243dd2bc887664b103d224ba40216e50cb672322790918e2f9c48d8ef8" + } +} diff --git a/design/curation-main-gui-result.json b/design/curation-main-gui-result.json new file mode 100644 index 000000000..74117f2e2 --- /dev/null +++ b/design/curation-main-gui-result.json @@ -0,0 +1,76 @@ +{ + "ok": true, + "method": "exact all-row two-way ID mapping", + "revision": "c79666c672ab045e356b31f0764efc2cd0e4bdb4", + "rows": 469725567, + "assignment_dtypes": [ + "int32", + "int64" + ], + "partition_mismatch_rows": 0, + "examples": [], + "input_hashes": { + "left": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "3cbef5e08dc915ddd57aac9c214370a34282d264695f53959c184d6f8f2b7148" + }, + "right": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "b0223191c2cd29d2167b975175d22428bfe444175e19dc68e67aa9a82aea5168" + } + }, + "unmapped_label_ids": { + "left": { + "group": [], + "notes": [] + }, + "right": { + "group": [], + "notes": [] + } + }, + "manual_label_mismatches": [], + "compared_fields": [ + "group", + "notes" + ], + "scope": "complete curation assignments and requested manual labels; baseline GUI rendering errors retained", + "main_revision": "ad64e9138a6556f4785a359c3ee1258864d60f1d", + "bounded_runtime_revision": "06637b24aeca9b0984d7928d459187df46406444", + "reviewed_pr_head": "c79666c672ab045e356b31f0764efc2cd0e4bdb4", + "mapped_units": 703, + "gui_rendering_error_free": false, + "baseline_feature_errors": { + "acceptance": 7, + "reopen": 5 + }, + "actual_restored_view_count": { + "AmplitudeView": 1, + "ClusterScatterView": 1, + "ClusterView": 1, + "CorrelogramView": 1, + "FeatureView": 1, + "FiringRateView": 1, + "ISIView": 1, + "MergePropositionsView": 1, + "ProbeView": 1, + "SimilarityView": 1, + "WaveformView": 1 + }, + "raw_source_parent_scan": { + "units": [ + 40, + 44, + 48 + ], + "rows": 1156852, + "nonfinite": 0, + "equal_to_threshold": 0, + "independently_verified": true + }, + "source_integrity": { + "ok": true, + "raw_files_verified": 67, + "immutable_main_working_files": 19 + } +} diff --git a/design/curation-main-gui-validation.md b/design/curation-main-gui-validation.md new file mode 100644 index 000000000..869a7c3ab --- /dev/null +++ b/design/curation-main-gui-validation.md @@ -0,0 +1,139 @@ +# Main GUI versus bounded PR curation: real-data comparison + +On 26 October 2026, the actual ordinary GUI on current `master` +(`ad64e9138a6556f4785a359c3ee1258864d60f1d`, verified against GitHub) completed +the same action ledger as the bounded PR GUI. Its complete saved output matches +bounded full-source replay on **all 469,725,567 spikes** and requested manual +labels. This extends the earlier ordinary-engine-only reference with an actual +main-branch TemplateModel, controller, graphical split and GUI save/reopen. + +The result is **curation completed with baseline Feature View errors**. It is +not an error-free all-view GUI acceptance claim. The renderer failure and other +limits are retained below. + +## Inputs and isolation + +- Source: Carl's earlier converted engineering export, computation + `b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`, 705 original units, 112.859 elapsed + clock hours. This is not Carl's newer 500-hour dataset, and its inferred + exposure remains unverified. +- Main code: a clean detached worktree at `ad64e913`; the script asserts the + imported `phy` module comes from that worktree. No main code was changed. +- PR runtime: `06637b24`, unchanged by the subsequent tool/documentation commits + through reviewed head `c79666c6`. The previously completed native bounded GUI + run and full replay were reused, with their pinned inputs and ledger. +- Main working data: a separate 15,381,601,942-byte deep copy with symlinks + dereferenced, never hard-linked. Its `params.py` has one final `dat_path = None` + override so ordinary phylib treats the exporter's string sentinel as absent raw + data. No event times, source rows, amplitudes or exposure declarations were + converted for this run. Both parameter-file hashes are recorded locally. +- Environment: Python 3.12.3, phylib 2.7.1, native X11 Qt under Xvfb and software + OpenGL. Each full ordinary GUI process ran under a 96 GiB virtual-memory limit. + +The [shared ledger](curation-mode-acceptance-ledger.json) specifies merge +40/44/48, undo/redo, source-amplitude split, undo/redo, merge the low child with +24, explicit GOOD/MUA and notes, a label-history branch, save/reopen and a no-edit +save. The ordinary GUI used **template** amplitudes, matching `amplitudes.npy`. + +## Native graphical split and save/reopen + +The script ran the real ordinary controller and Supervisor. A real Qt +Alt-right-drag placed the preview; a real `K` key event triggered the standard +split action and its all-spike provider. The resulting two children were checked +against the full parent membership and source predicate, rather than inferred +from child counts alone. + +The viewport was panned so the shared threshold landed on an integer pixel. +Requested and actual thresholds were exactly **-424.0037077454673**. An +independent chunked scan of raw source arrays confirmed all **1,156,852 parent +spikes** have finite amplitudes, with none equal to the threshold. Thus ordinary +display sanitization of nonfinite values does not affect this comparison. + +After the ledger's final save, the process closed the GUI/controller and exited +zero. A fresh process loaded the saved full sorting through the main GUI, +verified the final groups/notes for all three reviewed units, selected them, +saved without edits and exited zero. Using a separate process establishes real +reload and avoids retaining an earlier model through global callbacks. + +Observed single warm-cache runs: + +| Run | Wall time in harness | Peak RSS | +| --- | --- | --- | +| Main GUI ledger and saves | 116.1 s | 33.5 GiB | +| Fresh-process GUI reopen and no-edit save | 44.5 s | 26.5 GiB | + +These are integration observations, not controlled performance benchmarks. + +The caller requested Amplitude and Waveform views, but ordinary saved/default +state restored **11 view types**, including Feature View, Firing Rate, ISI, +Correlogram, Probe, Cluster Scatter and the tables. The original run JSON's +`views` field lists requested views only. The committed summary records the +actual restored inventory and the rendering errors instead of treating that +field as the observed layout. + +## Exact complete-output comparison and integrity + +`tools/compare_curation_modes.py compare` compared the saved main full sorting +after reopen against the existing complete bounded replay. It passed: + +- **469,725,567** rows, with exact row-aligned integer spike times. +- **Zero partition mismatches**, using a two-way raw unit-ID mapping over every + row, spanning 703 final units. +- **Zero group/notes differences** and no unmapped manual-label IDs. + +Ordinary main saved int32 assignments; bounded replay retained int64. Assignment +dtype and numeric IDs need not agree for partition equality. The comparison +checks exact integer memberships, with input hashes recorded in the +[report summary](curation-main-gui-result.json). + +An independent verifier checked all **67 original download files** against the +archived SHA-256 inventory. All **19 immutable working-copy files** (every NPY +except assignments, plus timestamps and suggestions) match the converted source. +The source parameters still match the original hash recorded during preparation. + +An optional working-copy hash helper was started concurrently with the first +GUI run and lost a race with the intentional GUI save of `spike_clusters.npy`. +Its failed log is retained; it is not claimed as a successful input preflight. +The source copy operation, unchanged original hashes, final immutable-file check +and complete-output comparison provide the stated evidence. When reproducing, +run the copy hash helper before launching the GUI. + +## Baseline Feature View failure + +Main emitted **7 Feature View errors during curation and 5 during reopen**: +background feature sampling sometimes requests no IDs in the stored waveform +reservoir. Unmodified phylib 2.7.1 `TemplateModel.get_features()` then invokes PCA +on zero waveforms, causing `ZeroDivisionError` in `_compute_pcs()`. + +A minimal independent reproduction calls the installed `get_features()` with +requested row 2 and stored row 1; their empty intersection raises the same +exception. This is a baseline feature-rendering failure, not an assignment +mutation. No exception was discarded when classifying this acceptance result. + +Bounded `_get_feature_view_spike_ids()` intersects selected and background IDs +with stored waveform rows before projection when dense features are unavailable. +Its inherited feature getter returns an empty bunch for an empty request, so +this particular phylib empty-PCA path differs from ordinary main. No PR #1428 +change is needed to establish the curation equivalence above. An upstream phylib +guard and focused regression would be a separate follow-up; changing the +ordinary baseline during this comparison would hide the observed behavior. + +## Artifacts and remaining acceptance + +Actual main captures are in `docs/images/amplitude-main-gui/`: the native +threshold preview and the reopened full sorting. Empty feature panels in these +captures reflect the recorded baseline issue. They are not a controlled layout +comparison with the separately captured bounded views. + +Reports, exact scripts, screenshots and logs are archived under +`/home/cyrille/GIT/IBL/phy-data/carl/aind-b1b0782a-b3ea-4f34-81d7-b3c6e36452b3/main-versus-pr-gui-acceptance/`. +The separate high-effort audit independently confirmed raw parent finiteness, +the exact comparator result, both process exits, restored inventory and the +rendering-error scope. No additional product-code regression was identified. + +This closes the automated main-GUI versus bounded-GUI comparison for this pinned +dataset and ledger. Carl's manual usability and scientific assessment remain +valuable, particularly on his 500-hour recording. The practical variants in +`curation-user-acceptance.md` remain proposed user tests, not claims that every +variant was executed. Acceptance of Brandon's native exporter still needs that +export and authoritative acquisition exposure. diff --git a/design/curation-mode-acceptance-ledger.json b/design/curation-mode-acceptance-ledger.json new file mode 100644 index 000000000..a64e7b957 --- /dev/null +++ b/design/curation-mode-acceptance-ledger.json @@ -0,0 +1,149 @@ +{ + "aliases": { + "a": 40, + "b": 44, + "c": 48, + "d": 49, + "extra": 24 + }, + "fields": [ + "group", + "notes" + ], + "actions": [ + { + "op": "merge", + "parents": [ + "a", + "b", + "c" + ], + "as": "merged" + }, + { + "op": "undo" + }, + { + "op": "redo" + }, + { + "op": "split", + "parent": "merged", + "threshold": -424.0037077454673, + "selected": "low", + "remainder": "rest" + }, + { + "op": "undo" + }, + { + "op": "redo" + }, + { + "op": "merge", + "parents": [ + "low", + "extra" + ], + "as": "final" + }, + { + "op": "label", + "ids": [ + "final" + ], + "field": "group", + "value": "good" + }, + { + "op": "label", + "ids": [ + "final" + ], + "field": "notes", + "value": "reviewed merged low side" + }, + { + "op": "label", + "ids": [ + "rest" + ], + "field": "group", + "value": "mua" + }, + { + "op": "label", + "ids": [ + "rest" + ], + "field": "notes", + "value": "reviewed threshold remainder" + }, + { + "op": "label", + "ids": [ + "d" + ], + "field": "group", + "value": "mua" + }, + { + "op": "label", + "ids": [ + "d" + ], + "field": "notes", + "value": "reviewed unchanged source unit" + }, + { + "op": "label", + "ids": [ + "rest" + ], + "field": "group", + "value": "noise" + }, + { + "op": "undo" + }, + { + "op": "label", + "ids": [ + "rest" + ], + "field": "group", + "value": "good" + }, + { + "op": "label", + "ids": [ + "rest" + ], + "field": "group", + "value": "mua" + }, + { + "op": "save" + }, + { + "op": "reopen" + }, + { + "op": "save" + } + ], + "expected_labels": { + "final": { + "group": "good", + "notes": "reviewed merged low side" + }, + "rest": { + "group": "mua", + "notes": "reviewed threshold remainder" + }, + "d": { + "group": "mua", + "notes": "reviewed unchanged source unit" + } + } +} diff --git a/design/curation-mode-acceptance-result.json b/design/curation-mode-acceptance-result.json new file mode 100644 index 000000000..a01ef6ef1 --- /dev/null +++ b/design/curation-mode-acceptance-result.json @@ -0,0 +1,51 @@ +{ + "ok": true, + "method": "exact all-row two-way ID mapping", + "revision": "06637b24aeca9b0984d7928d459187df46406444", + "rows": 469725567, + "assignment_dtypes": [ + "int64", + "int64" + ], + "partition_mismatch_rows": 0, + "examples": [], + "input_hashes": { + "left": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "2b9c3d4f8163bd29a0d5eb2b15205b38380d87149535f3e5820442eb05bcd936" + }, + "right": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "b0223191c2cd29d2167b975175d22428bfe444175e19dc68e67aa9a82aea5168" + } + }, + "unmapped_label_ids": { + "left": { + "group": [], + "notes": [] + }, + "right": { + "group": [], + "notes": [] + } + }, + "manual_label_mismatches": [], + "compared_fields": [ + "group", + "notes" + ], + "mapped_units": 703, + "numeric_ids_also_identical": true, + "evidence": "native bounded Qt graphical drag/K and full ordinary Supervisor without GUI views, same PR code revision", + "noop-comparison": { + "ok": true, + "method": "exact matching SHA-256 of complete NPY files and explicit manual-label tables", + "arrays": 18 + }, + "immutable-check": { + "ok": true, + "raw_files_verified": 67, + "immutable_replay_files_per_round": 19, + "rounds": 2 + } +} diff --git a/design/curation-output-contract-result.json b/design/curation-output-contract-result.json new file mode 100644 index 000000000..000098fd6 --- /dev/null +++ b/design/curation-output-contract-result.json @@ -0,0 +1,146 @@ +{ + "ok": true, + "method": "exact all-row two-way ID mapping", + "revision": "eb7983f0cd435c8acd5ef3722e19df00356b3ef8", + "rows": 469725567, + "assignment_dtypes": [ + "int32", + "int64" + ], + "partition_mismatch_rows": 0, + "manual_label_mismatches": [], + "input_hashes": { + "left": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "3cbef5e08dc915ddd57aac9c214370a34282d264695f53959c184d6f8f2b7148" + }, + "right": { + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c", + "spike_clusters.npy": "b0223191c2cd29d2167b975175d22428bfe444175e19dc68e67aa9a82aea5168" + } + }, + "file_contract": { + "ok": true, + "assignment_oracle": { + "verified": true, + "source_rows": 469725567, + "membership_events": 3, + "threshold_splits": 1 + }, + "immutable_files": [ + "_phy_spikes_subset.channels.npy", + "_phy_spikes_subset.manifest.json", + "_phy_spikes_subset.sample_index.npy", + "_phy_spikes_subset.spikes.npy", + "_phy_spikes_subset.waveforms.npy", + "_phy_spikes_subset.window_bounds.npy", + "_phy_spikes_subset.window_strata.npy", + "_phy_spikes_subset.window_types.npy", + "amplitudes.npy", + "channel_groups.npy", + "channel_map.npy", + "channel_map_si.npy", + "channel_positions.npy", + "curation.json", + "similar_templates.npy", + "spike_templates.npy", + "spike_times.npy", + "template_ind.npy", + "templates.npy", + "timestamps.json" + ], + "native_derived_static_files": [ + "whitening_mat_inv.npy" + ], + "all_metadata_fields": [ + "amplitude_cutoff", + "amplitude_cv_median", + "amplitude_cv_range", + "amplitude_median", + "bombcell_label", + "channel_group", + "default_qc", + "exp_decay", + "firing_range", + "group", + "isi_violations_count", + "isi_violations_ratio", + "main_peak_to_trough_ratio", + "main_to_next_extremum_duration", + "noise_cutoff", + "noise_ratio", + "notes", + "num_negative_peaks", + "num_positive_peaks", + "peak_after_to_trough_ratio", + "peak_after_width", + "peak_before_to_peak_after_ratio", + "peak_before_to_trough_ratio", + "peak_before_width", + "peak_half_width", + "peak_to_trough_duration", + "presence_ratio", + "recovery_slope", + "repolarization_slope", + "rp_contamination", + "rp_violations", + "sd_ratio", + "si_unit_id", + "sliding_rp_violation", + "snr", + "spread", + "sync_spike_2", + "sync_spike_4", + "sync_spike_8", + "trough_half_width", + "trough_width", + "unitrefine_label", + "unitrefine_probability", + "velocity_above", + "velocity_below", + "waveform_baseline_flatness" + ], + "permitted_metadata_differences": [], + "ordinary_aliases": [ + { + "filename": "cluster_si_unit_ids.tsv", + "field": "si_unit_id", + "policy": "unchanged source alias" + }, + { + "filename": "cluster_sync_spike_2.tsv", + "field": "sync_spike_2", + "policy": "byte-pinned blank source column" + }, + { + "filename": "cluster_sync_spike_4.tsv", + "field": "sync_spike_4", + "policy": "byte-pinned blank source column" + }, + { + "filename": "cluster_sync_spike_8.tsv", + "field": "sync_spike_8", + "policy": "byte-pinned blank source column" + } + ], + "preparation_verified": true, + "saved_generation_verified": "96fce3cd8e02474f8a175ddbb89c571c", + "historical_parents": "recorded cumulative ancestry; current parent bound to supplied manifest" + }, + "file_inventory_counts": { + "ordinary": { + "required": 70, + "optional_artifacts": [ + ".phy", + "cluster_info.tsv", + "curation_review.json", + "phy.log" + ] + }, + "replay": { + "required": 73, + "optional_artifacts": [] + } + }, + "scope": "Full source logical output contract with independent cumulative predicate execution over every source row; explicit optional artifacts have their own checks, only GUI caches/logs excluded from byte identity." +} diff --git a/design/curation-output-equivalence.md b/design/curation-output-equivalence.md new file mode 100644 index 000000000..070687a36 --- /dev/null +++ b/design/curation-output-equivalence.md @@ -0,0 +1,529 @@ +# Executable curation equivalence contract + +Carl's acceptance requirement is that applying supported decisions to retained +evidence and replaying them over the full source produces the same complete +curation as applying those decisions to the full recording directly. A useful +regression must exercise actual controllers and saved files, including spikes +that were neither retained nor drawn. + +This follow-up stays on PR #1428's `feature/long-recording-curation` branch. +The separate empty-waveform feature projection fix belongs to +[phylib PR #70](https://github.com/cortex-lab/phylib/pull/70); bounded mode does +not require a dependency bump for that guard. + +## Permanent controller test + +`phy/apps/large_recording/tests/test_controller_equivalence.py` creates a finite +660-spike, six-unit sorting with an explicit acquisition gap, imported producer +metadata and sparse stored waveforms. Three window/budget/seed configurations +retain genuine subsets; every active unit has unseen source spikes. + +One shared action runner drives ordinary TemplateController/Supervisor and the +manifest-selected bounded controller/Supervisor. It never substitutes manual +`BoundedSession.record_*()` calls for controller actions. The amplitude panel +receives real Qt Alt-right-drag events and the normal split QAction. Only five +points may be drawn while the parent contains more spikes. The source includes +amplitudes exactly equal to the requested threshold; they stay in the remainder. +Viewport calibration accommodates floating pixel transforms without changing +the spike values or bypassing the split action. + +The same ledger exercises: + +1. Merge, undo/redo, amplitude split, undo/redo, and merge one child with another + source unit; explicit GOOD/MUA, noise, cleared classification and custom notes; + undo/redo of reviewed labels, a new edit discarding the redo branch, save, + close, reopen and save again. +2. Prepare the full replay for another round, merge and split again, review both + new memberships, edit/undo/redo an explicitly seeded note, save and reopen. +3. Prepare/save/reopen/apply without edits. Complete NPY files and manual group + and notes tables must be byte-identical to the preceding replay. +4. Prepare again and leave a separate merge unreviewed. The checker verifies + bounded clearing and explicitly admits only supported native ancestor + inheritance, rather than pretending these imported values must agree. + +Expected reviewed labels are written independently in `EXPECTED_ONE/TWO`. +Each round compares full saved ordinary data with full bounded replay using the +original source and the actual final bounded package. Original inputs are hashed +before and after; GUI callbacks and mapped resources are explicitly cleaned up. +The GUI layout is scoped to amplitude and tables, not an all-view rendering test. + +An early extra snapshot assertion exposed ordinary inherited-note undo behavior: +editing an inherited parent note on a derived unit and undoing it restores an +empty value, rather than the displayed inherited note. The ledger seeds an +explicit reviewed note before testing its edit/undo, matching the explicit-label +contract. That initial diagnostic is retained locally; it is not claimed as a +successful inherited-note undo check or fixed by this PR. + +## File-by-file contract + +The opt-in checker is `tools/curation_output_contract.py`, called by +`tools/compare_curation_modes.py compare --source ...`. The existing basic +comparison remains available for complete partition/selected-label comparisons. + +| Output class | Required check | +| --- | --- | +| `spike_clusters.npy` | Every source row belongs to the same final partition through a two-way ID bijection. An independent chunked oracle also executes cumulative merges/split predicates on original source rows and checks exact replay IDs. Assignment dtype/vector-column representation and native allocated IDs may differ. | +| Immutable NPY arrays and producer sidecars | Every full array/file matches the original bytes, including times, amplitudes, features, templates, channels, waveform rows/channels/samples, producer window plans, timestamps and suggestion bytes when present. | +| Imported and curator metadata | All fields are checked. Untouched units retain source values. New identities clear bounded producer fields unless explicitly reviewed. Every surviving label event requires an independent final expectation, including clear/null. Native differences must be supported ancestor values or empty values and are reported individually. | +| Metadata files/schema | Replay preserves producer basenames, delimiters and columns. Native canonical field tables may supersede byte-identical source aliases. Entirely blank native source columns may retain retired rows only when their original file is byte-identical. Missing blank tables still fail. Typed sidecars and tables must agree. | +| Parameters | Original Python structure outside managed extent/exposure/raw-path overrides is preserved; evaluated parameter values and effective recording clock/exposure/raw reference are checked. This is not a general proof of executable Python equivalence. | +| Journal/lineage | Exact operation/version/clearing-payload/predicate schemas, journal hash, current parent/preparation binding, final identity/revision, cumulative allocated ancestry, retired identities, metadata snapshots and explicit label intent are checked. | +| Saved generation | Pointer, descriptor and all checkpoint file hashes bind the export's journal, metadata, schema, allocator, provenance and reviews to the saved session. Every retained row's full output assignment must equal its saved assignment. | +| Suggestions/reviews | Suggestion bytes and source-hash bindings survive; inherited decisions match semantically. This action ledger makes no new proposition decisions. Their separate acceptance procedure remains in force. | +| Native derived whitening inverse | When absent from source but materialized by ordinary Phy, it must equal the inverse of the source whitening matrix, or the channel-count identity when no matrix exists. It is not an arbitrary extra-file exemption. | +| GUI state/derived summaries | `.phy` caches, logs and GUI `phy_curation_history.jsonl` save records may differ. Optional generated cluster summaries must have the complete active catalog and agree with their manual labels. Other optional source snapshots are byte-checked. Unknown or missing assets fail. | + +The checker does not call the bounded assignment projector or event metadata +interpreter. It uses the source format reader for admission and independently +executes cumulative membership intent and tracks clearing and label intent. +The assignment oracle reads original scalar attributes for every source spike, +including spikes omitted from every bounded package. It applies earlier-round +actions before later actions, skips history already incorporated in the supplied +original source, and compares the resulting IDs exactly with the replay. Split +child order, comparator equality and parent-local nonfinite policy are checked. +Memory use is bounded by the requested chunk size and action history. +Native producer inheritance +is constrained to supported ancestor values/empty values; it does not reconstruct +every intermediate largest-parent inheritance choice. Historical parent revisions +are recorded ancestry, not fetched historical files. The current parent and +saved generation are verified against the supplied final package. + +`--source` without a package supports first-round checks but explicitly reports +unverified preparation/saved-generation bindings. The full acceptance command is: + +```bash +uv run --no-sync python tools/compare_curation_modes.py compare \ + /data/ordinary-final /data/bounded-full-output \ + --source /data/original-source --bounded-dir /data/final-bounded \ + --expectations /data/expected-labels.json --chunk-size 1000000 \ + --output /data/full-output-comparison.json +``` + +The report path must be fresh and outside every input folder. Expectations map +replay unit IDs to actual planned final decisions, not values copied from the +export under test. Use the original source across repeated rounds. Immutable +input preservation is checked by the test's pinned before/after inventory; a +post-hoc CLI source path alone cannot establish that its caller never edited it. + +## Corruption regressions and scope + +`test_output_contract.py` includes positive canonical/native-alias/blank-column +and implicit-group cases, and deliberate corruptions of arrays, memberships, +manual labels, new/untouched producer values, source aliases, metadata layout, +parameters, missing/extra files, malformed provenance, journal payloads, +predicates, parent bindings, allocator state, retired identities, review binding +and generated catalog coverage. Corrupt metadata tests repair table/JSON/revision +consistency so policy checks must catch them. Journal tests repair the correct +canonical JSON hash including its trailing newline, including source-only checks. +A standalone CLI regression catches import/path problems outside pytest. + +A two-merge case swaps derived unit IDs while preserving the same partitions +and identical labels. The basic comparison accepts that rename; the strict +assignment oracle rejects its now-incorrect recorded source-parent relationships. + +A subsequent independent audit exposed a checker false acceptance: a split +threshold could be changed in both journal and provenance, with repaired +checkpoint hashes, while leaving the old assignments in place. Schema, ancestry +and saved-row agreement did not establish predicate semantics. The independent +all-source oracle closes that gap; the corruption is now a regression, including +source-only and cumulative-round checks. This was a validation gap, not evidence +that the normal curation producer generated an incorrect split. + +These tests guard the supported workflows and declared exceptions. They do not +prove equivalence for every possible action sequence or arbitrary lasso/feature +cuts, which cannot assign unseen spikes in bounded mode. Controller tests use +finite source amplitudes; ordinary display sanitization of nonfinite values can +differ from raw bounded predicates. Existing raw predicate regressions test +nonfinite/equality policy separately. + +## Real-data validation + +The existing main-GUI versus PR comparison uses Carl's converted engineering +dataset: **469,725,567 spikes**, a 112.859-hour elapsed clock, and unverified +inferred exposure. It is not the newer 500-hour recording or native-export +acceptance. The stronger file stage passed against the hash-pinned all-row +mapping, checking **46 metadata fields**, **20 immutable files**, the actual +saved generation and full file inventory. It recognized the unchanged plural +SI-ID alias, three byte-identical blank source columns, and a valid native +derived whitening inverse. These are explicit file-format artifacts. + +The initial strict run correctly surfaced a checker admission gap: ordinary +loading skips entirely blank imported columns, leaving their original files +unchanged after source IDs retire. A narrow byte-pinned rule and a forged-value +regression were added. The first standalone run also found a tool import-path +error, now covered by an actual subprocess CLI regression. Both diagnostic logs +are retained; neither is described as a product curation mismatch. + +The final standalone CLI run passed over all **469,725,567 rows**, including +all 46 metadata fields, 20 immutable files, the exact saved generation and full +file inventories. It reported zero unexpected partition or manual-label +mismatches and zero producer-value differences for this particular saved pair. +The subsequent predicate-oracle run independently checked all 469,725,567 +original rows through two merges and one threshold split, with no assignment +contradictions. The runtime checker is commit `eb7983f0`; the complete local +report is `contract-comparison-predicate-oracle-committed.json` in the acceptance +directory below. +The [committed report summary](curation-output-contract-result.json) records the +runtime revision, input hashes, checked fields/files and admitted native artifacts. + +After the predicate-oracle fix, `make test-full` passed **1,041 tests** (499 core +and 542 application) with one existing benchmark skip, including lint and +formatting. The complete **52-case file-contract target** includes coherent +current/inherited threshold forgeries, an unseen-row-only contradiction, and +an already-curated source whose incorporated history must be skipped. +The **26 literal oracle cases** cover all four operators, equality, child +ordering, scalar vector/column attributes, wide allocated IDs, nonfinite policy +and mixed cumulative actions across chunk boundaries. Independent targeted +verification also passed all three controller plans and 18 comparison cases. +The Sol 6.1 high auditor independently reran the original forged-checkpoint +reproduction: it is now rejected at source spike 4, and the implementation review +found no further issue. +Documentation and cross-platform CI links are recorded at handoff. Local +reports and reproducibility scripts remain in the dataset's +`main-versus-pr-gui-acceptance/` directory; no source or prior baseline output was +modified by the checker. + +The independent high-effort audit found and regression-tested missing blank +table coverage, journal/history agreement, new-unit ancestry, malformed history +and invalid event payloads. Its final read found no remaining must-fix issue. + +## Live post-split summaries + +Commits through `6a5c9824` add automatic background computation of exact counts and +available finite amplitude/depth summaries for split descendants. The service +uses native preparation bins and acquisition exposure. Immutable membership +expressions identify cached results independently of labels and allocated IDs; +merges add counts and scalar sums/counts. Source readers are validated once and +reused while their file and metadata fingerprints remain unchanged. A separate +bounded derived cache cannot change or prevent curation saves. + +The controller schedules work after transaction completion, delivers results on +the GUI thread and maps results to current memberships. Undo/redo, rollback, +branching, hidden views, source relocation, accepted GUI closure and reopening +have regressions. Scalar full counts remain available if plot arrays are evicted. +Unavailable source/cache capacity produces an explicit status rather than a +sampled rate. Finite-sum comparisons allow floating-point reduction tolerance; +spike and finite-value counts must match exactly. + +The actual GUI trial ran on a copy of Carl's earlier converted 112.859-hour +engineering dataset, with **469,725,567 spikes**, **113 native bins** and +unverified exposure. It split unit 49 at source amplitude **-341.797119140625**, +producing units 709 and 710 with **292,990** and **346,764** full spikes. +Unrelated control unit 50 retained **541,925** spikes and its rate curve during +the computation. Three earlier saved membership actions were present in the +copied package; this run added the new split and resolved the missing summaries. + +First-job source validation, computation and GUI delivery took **8.331 seconds**; +the checked source arrays totaled **9,394,511,724 bytes**. A completed summary +lookup took **0.000603 seconds**. Hash preflight warmed the filesystem cache: +these timings are not cold-storage measurements or a latency guarantee for the +newer 500-hour recording. No responsiveness timing threshold is claimed. + +An independent chunked replay checked every original source row and compared +the two children and control against the displayed counts and finite scalar +summaries. Counts matched exactly; float64 sums and means matched at the +declared tolerance. All required source-array hashes and all **99 original +package-file hashes** were unchanged. The [committed result](live-summary-result.json) +records revision, source bindings, thresholds, timings and comparisons. Full +local artifacts remain in `live-summary-acceptance-2026-10-27-final/` under the dataset. + +These are actual application screenshots of that trial: + +- [Before splitting](../docs/images/live-summaries/before-split.png): parent 49 + and control 50 have their original full-recording rate curves. +- [Recomputing](../docs/images/live-summaries/recomputing.png): both children + explicitly show pending computation while the control curve remains. +- [After computation](../docs/images/live-summaries/after-split.png): both child + curves and the unchanged control are available together. + +Reproduce on a fresh output directory using: + +```bash +xvfb-run -a -s '-screen 0 2400x1500x24' \ + env QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 \ + uv run --no-sync python tools/capture_live_summaries.py \ + --bounded /data/existing-bounded --output /data/fresh-live-summary-trial \ + --unit 49 --control 50 --rate-only +``` + +The tool copies the package, makes the split only in that copy, captures the +three stages and verifies full-source summaries. Existing valid cache entries +are reusable offline; new computations need matching original source files. +The high Sol 6.1 review found and regression-tested unsafe cache payload +allocation, redundant source hashing, hidden-view refresh and cache-eviction +rescan hazards. Its final read found no remaining correctness blocker, and an +independent run of the 40 engine/service cases passed. + +The full local suite passed **1,086 tests** (500 core and 586 application) with +one existing benchmark skip, including lint and format checks. After the final +cache-key performance change, all **40 engine/service cases** and **four live +GUI integration cases** passed again. Strict documentation checks and final CI +results are recorded at handoff. + +Windows 3.12 CI exposed differing `stat()` and `fstat()` timestamp semantics, +consistent with [CPython issue 157671](https://github.com/python/cpython/issues/157671). +The source reader now captures path and descriptor fingerprints separately, +compares each against its own later samples, and retains common identity/size/ +modification-time binding plus the original file hashes. Three regressions cover +different timestamps, changes reported by either provider and replacement +between sampling the path and opening it. All **44 engine/service cases** and +the **four live GUI cases** passed after this fix. Source-edit fault injection +also writes the mapped payload in place, since Windows prevents truncation of +an open mapping. Summary arithmetic and the recorded real-data results are +unchanged. + +## Parallel phylib follow-up + +[phylib PR #70](https://github.com/cortex-lab/phylib/pull/70) returns the existing +zero-filled feature tensor when a request has no stored waveform overlap or +no channels, instead of attempting PCA on an empty array. Five real on-disk +regressions cover empty requests, no coverage, empty channels, partial coverage +and complete coverage. Three fail before the guard; **308 full-suite tests** and +cross-platform/minimum-SpikeInterface CI pass afterward. + +A separate copied real sorting was reopened in unmodified main Phy with only +the isolated patched phylib on `PYTHONPATH`. It exited zero with **zero +tracebacks**, versus five Feature View errors in the original equivalent reopen. +Complete assignments and group/notes files remained byte-identical. Original +validation data and installed environments were preserved. This addresses the +recorded baseline renderer failure and does not change PR #1428's dependency pin. + + +## Unit-indexed summary acceleration + +The 1,000-hour feedback exposed full-source scan and first-session hashing costs. +The optional summary store groups exact source scalars and native bin IDs by +original unit. It is independently budgeted, atomically published outside the +bounded package, and attached through a small `.phy` reference. Existing package +manifests and saved curation generations are unchanged. Payload checksums are +verified only for consumed units before any result is published. This certifies +the prepared source snapshot, not the present contents of original files; +full-source replay and the unindexed fallback retain source validation. + +At revision `9e4ac004`, the earlier converted 112.859-hour engineering dataset +contained **469,725,567 spikes** and 113 native bins. The reusable store occupied +**2,348,718,604 bytes**, took **47.389 seconds** to build (including required +source validation), and peaked at **335,151,104 bytes RSS** in a separate process. +The input arrays were read in bounded batches, without touching every page of a +recording-sized memory mapping or allocating a full permutation. + +Splitting unit 49 at **-341.797119140625** read only its **639,754 original spikes** +(approximately 3.2 MB). The first indexed request took **0.01795 seconds**, and a +repeated uncached request **0.01683 seconds**. The updated source fallback took +**6.470 seconds** including required-source hashing, and **2.176 seconds** with +validated readers reused. Result-cache lookups and publication were disabled for +both paths, so these are computation timings rather than result-cache hits. +These measurements exclude GUI delivery and use uncontrolled OS cache state; +they are not cold-storage or 1,000-hour acceptance measurements. + +Counts were **346,764** and **292,990**. Integer counts and finite counts matched +exactly. Float64 sums matched at `rtol=1e-9, atol=1e-6`. Besides comparing indexed +and full-scan engines, independent cumulative assignment replay traversed **all +469,725,567 original rows** and used histogram accumulation to verify the indexed +outputs. Top-level bounded-package file hashes were unchanged. The +[committed result](summary-store-result.json) records the measurements; full +artifacts remain under `summary-store-acceptance-2026-10-28/` in the dataset. + +Regressions cover native-bin boundaries and acquisition gaps, every comparator, +nonfinite rejection and remainder membership, nested split/merge ancestry, +source-offline computation, template-predicate fallback, corrupt stores, +cancellation, interrupted and racing publication, disk failure, lost references, +Fortran-order depth coordinates, wide scalar dtypes, and actual sparse-file +seeks past `2**32` rows. The real GUI split/merge/undo/redo/save/replay/reopen test +runs with and without an index; its indexed variant forbids source access. +Progress ignores cancelled or undone memberships. The high-effort Sol audit's +identified issues were corrected and regression-tested; its final read found no +remaining must-fix issue. + +Reproduce on a fresh copy of the bounded package: + +```bash +uv run --no-sync python tools/benchmark_summary_store.py \ + --bounded /data/bounded-copy --store /data/new-summary-store \ + --output /data/summary-store-result.json --unit 49 \ + --threshold -341.797119140625 --dataset-label 'engineering dataset' +``` + +Cost scales with original ancestry, not surviving child size: a split of a merge +of every original unit can read the entire store. The compact 1,000-bin, +float32-amplitude layout requires roughly 29.2 GB for 4.87 billion spikes, before +optional depth. Carl's actual 1,000-hour dataset still needs owner-run cold/warm +split and build measurements. No universal one-second bound is claimed. + + +## Large-dataset scaling and GUI background preparation + +The fixed implementation at `f2c53f69` was benchmarked serially on the local +Linux host (134,698,618,880 bytes physical RAM). The real 100-hour sorting has +418,167,522 spikes. The 200-hour and 1,000-hour engineering datasets repeat its +arrays two and ten times, offsetting time by 100 hours per segment. They test +scale, not independent biology or Carl's native 4.873-billion-spike export. +The assumed continuous exposure on the real legacy 100-hour input is also an +engineering declaration, not a new validation of acquisition timing. + +Each case resolves both children together. Result-cache lookup and publication +are disabled, and each scenario gets a fresh engine. These are first-request +computation timings, excluding GUI delivery. OS page caches are uncontrolled; +repeated requests are recorded in the linked JSON. They are not cold-storage +measurements or latency guarantees on a laptop with less RAM. + +| Dataset | Source spikes | Median unit | Largest unit | Nested median split | Merge two largest, then split | Merge ten typical, then split | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| Real 100 h | 418,167,522 | 0.020 s | 0.215 s | 0.019 s | 0.447 s | 0.113 s | +| Synthetic 200 h | 836,335,044 | 0.038 s | 0.429 s | 0.038 s | 0.880 s | 0.248 s | +| Synthetic 1,000 h | 4,181,675,220 | 0.170 s | 2.137 s | 0.174 s | 4.738 s | 1.224 s | + +The 1,000-hour median unit contains 4,481,760 spikes; the largest contains +77,538,160. The two largest ancestors together contain 154,940,400 spikes. +Merging ten typical ancestors produces 44,726,720 spikes. Query time still +scales with this original ancestry, including nested descendants. + +One-time store creation took approximately **41 s / 2.09 GB** for 100 hours, +**83 s / 4.18 GB** for 200 hours, and **420 s / 25.09 GB** for 1,000 hours. +Peak builder RSS stayed between **347 and 353 MB**. Build measurements came +from separate earlier child processes; the frozen runtime rerun reused their +completed compatible stores. The 1,000-hour format uses two bytes per native +bin ID instead of one, explaining its larger bytes-per-spike footprint. + +All cases matched a combined fully validated source scan and a separate +cumulative assignment replay using independent histogram accumulation. Every +original source row was traversed in each dataset: **5,436,177,786 rows** across +the three runs. Integer spike and finite-value counts matched exactly; trend +sums matched at `rtol=1e-9, atol=1e-6`. The combined source scan computes all five +scenario expressions in one pass; its duration must not be compared as though +it measured a single split. Top-level bounded input hashes were unchanged. +Reports record runtime source-component hashes, recipes, byte counts, and timings: +[100 h](summary-scaling/100h.json), [200 h](summary-scaling/200h.json), +[1,000 h](summary-scaling/1000h.json). + +Reproduce on a fresh bounded benchmark package with: + +```bash +uv run --no-sync python tools/benchmark_summary_scenarios.py \ + --bounded /data/bounded-copy --store /data/summary-store \ + --output /data/result.json --label 'identified dataset and provenance' +``` + +The GUI trial at `0da082b1` used a fresh copy of the earlier converted +469,725,567-spike package. Building, attaching and restoring the two split-child +summaries took **49.61 seconds** while curation remained unsaved. A 10 ms Qt +heartbeat had **9.62 ms median**, **10.64 ms p95**, and **333.68 ms maximum** across +4,659 intervals, excluding screenshot capture intervals. This supports normal +responsiveness; it does not establish a hard maximum event-loop latency. The +children contained **292,990** and **346,764** spikes. The store was adopted +without reopening. [GUI report](summary-store-gui-result.json) and actual +[prompt](../docs/images/summary-store-task/prompt.png), +[progress/ETA](../docs/images/summary-store-task/building.png), and +[completion](../docs/images/summary-store-task/ready.png) captures are committed. + +The task runner has bounded latest-only progress, staged ETA, shared recording +I/O exclusion, cooperative cancellation and a short publication boundary. +Regressions cover cancellation/publication races, failed thread startup, +worker exits, detached QObject ownership, GUI deletion before controller close, +vetoed close, slow destination checks, newer attachment references, persisted +budgets, and automatic prompts retaining keyboard-shortcut ownership. The +ordinary/bounded controller equivalence and graphical K-split tests pass with +the new prompt behavior. + +### Next interactive-latency improvement + +One-time preparation cost is secondary to interactive split latency. The current +row store greatly reduces source I/O, but the 2.1-second largest-unit and +4.7-second largest-parent-merge cases remain targets for further improvement. +The high-effort Sol architecture audit recommends an optional amplitude range +accelerator, not merely more batching or a faster builder: + +- Sort exact finite amplitudes within each original-unit/native-bin segment. + Keep aligned raw depth when needed; track nonfinite membership separately. +- Compile supported merge/split expressions into disjoint amplitude intervals + per original unit. Preserve inherited parent rejection obligations. +- Use small endpoint blocks and balanced aggregate range trees, avoiding + cancellation-prone subtraction of large floating prefixes. Benchmark block + sizes 64, 128 and 256 before selecting a default. +- Authenticate only consumed metadata pages, aggregate nodes and data blocks. + Retaining a whole-unit hash scan would erase the latency improvement. +- Reproduce canonical evaluator comparison semantics. Raw `searchsorted` can + disagree with float32 weak-scalar comparisons near a threshold. Counts must + remain exact; document and test trend arithmetic tolerances. +- Keep the existing verified row store as fallback. Preflight extra final and + scratch disk space; perform bounded-memory sorting and atomic publication in + another adapter for the same GUI task runner. + +This is an audited proposal, not an implemented accelerator or an asserted speed +result. Initial prototype targets are below 50 ms for typical warm queries and +below 200 ms for the largest-parent cases, including selective integrity work. +Cold-query behavior needs separate device measurements. The key acceptance +criterion is that query work no longer grows linearly with source spike count +when bins, ancestry and predicates are fixed. + + +## Authenticated amplitude-range acceleration (28 October 2026) + +Implemented on the same PR1428 branch. Preparation now optionally sorts finite +raw amplitudes per original unit/native bin and builds bounded-block aggregate +trees. Queries compile split/merge membership into rank intervals and verify only +consumed pages against pinned SHA-256 roots. Original dtype comparisons, nonfinite +policies and rejection obligations remain unchanged. Counts/finite counts are +exact; conservative error bounds require existing float64 sum tolerance (1e-9 +relative, 1e-6 absolute), otherwise verified rows are used. Replay/assignments are +unchanged. No recording-sized index array is built in memory. + +The GUI reuses the generic background task manager: inspect → rows if missing → +attach rows → amplitude index → attach index. Existing rows can be upgraded while +the original source is offline. Late cancellation stops subsequent long stages; +completed rows remain usable. Each automatic attachment is fenced against newer +choices. Independent indexes can be reattached from File or CLI. Combined disk +budgets and temporary sorting space are checked before expensive preparation. + +### Reproducible measurements + +`tools/benchmark_summary_scenarios.py --amplitude-index PATH` uses the same five +scenarios as the earlier row-store benchmark. Every scenario uses a fresh engine; +a second query reuses authenticated pages but no completed summary result. OS page +cache is uncontrolled. These timings include summary computation and selective +integrity checks, and exclude GUI delivery/rendering. The 1000h source is ten +repetitions of Carl's real 100h source, **not** an independently acquired 1000h +recording; legacy 100h acquisition/exposure construction is not certified here. + +| Scenario | Real 100h: first / repeat | Synthetic 1000h: first / repeat | Earlier 1000h row-only first | +| --- | ---: | ---: | ---: | +| median unit | 6.5 / 4.4 ms | 55.1 / 40.2 ms | 169.9 ms | +| largest unit | 11.4 / 5.9 ms | 115.5 / 57.2 ms | 2137.3 ms | +| nested split median | 8.1 / 5.7 ms | 73.6 / 54.2 ms | 174.4 ms | +| merge two largest then split | 24.3 / 12.3 ms | 244.2 / 120.1 ms | 4737.7 ms | +| merge ten typical then split | 53.7 / 38.8 ms | 524.2 / 540.1 ms | 1223.5 ms | + +Both runs compared every native-bin count, finite-value count and scalar sum with +one validated full-source scan and a separate independent sequential semantic +curation replay over all source spikes. All comparisons passed; bounded-package +files were unchanged. The earlier row-only results are historical measurements, +not an interleaved controlled A/B trial. Machine details, runtime component hashes, +cache conditions and complete recipes are in +[100h results](summary-scaling/amplitude-index-100h.json) and +[1000h results](summary-scaling/amplitude-index-1000h.json). Runtime hashes identify +the tested implementation even where the recorded HEAD predates its commit. + +The 4.18-billion-spike index added 20.27 GB to the existing 25.09 GB row store; +construction took 264.3 seconds at 314 MB peak RSS. The real 418-million-spike +index added 2.04 GB, built in 26.0 seconds at 235 MB peak RSS. Construction is an +offline cost; these figures are not interactive latency guarantees. A ten-unit +query exceeds the 64 MiB page cache in the 1000h run and takes about half a second +on repeats; broad merged ancestry still increases work. + +The refreshed real converted 469,725,567-spike GUI trial completed row build, +index build, attachment and current child summaries in 84.9 seconds. Curation +remained unsaved. Its 10 ms heartbeat measured p95 10.70 ms and maximum 322.84 ms +excluding screenshot intervals: responsive overall, with occasional larger pauses. +See [GUI results](amplitude-index-gui-result.json) and the actual +[prompt](../docs/images/amplitude-index-task/prompt.png), +[row preparation](../docs/images/amplitude-index-task/building.png), +[indexing with ETA](../docs/images/amplitude-index-task/indexing.png), and +[restored child rates](../docs/images/amplitude-index-task/ready.png). + +Focused regressions cover all comparators, weak float32 boundaries, int64/uint64 +extremes, nested/merged memberships, nonfinite-only bins, depth, stable external +merge sorting, real ill-conditioned arithmetic fallback, selective corruption, +reattachment invalidation, cancellation, injected sort/hash/publication failures, +newer-choice conflicts, offline upgrade and GUI lifecycle/adoption. High-sol +read-only audits checked reader correctness, resource bounds and task publication +boundaries; their concrete findings were fixed and regression-tested. diff --git a/design/curation-user-acceptance.md b/design/curation-user-acceptance.md new file mode 100644 index 000000000..3101d3409 --- /dev/null +++ b/design/curation-user-acceptance.md @@ -0,0 +1,277 @@ +# Curation-mode user acceptance protocol + +Status: protocol for the graphical bounded curation workflow; run both GUI +branches against the same full-source data before accepting the feature. + +Permanent controller-to-controller tests and the stronger whole-output checker +are now described in [the executable equivalence contract](curation-output-equivalence.md). +They supplement the manual protocol and the pinned main-branch GUI trial below. + +## Purpose and evidence boundary + +This is an end-to-end acceptance check for ordinary and bounded curation. It +compares their complete final spike assignments and explicitly reviewed manual +labels after applying the same user action ledger. It does not compare bounded +evidence arrays with full-source arrays, nor does it treat a streamed reference +as ordinary GUI evidence. +The harness comparison tests live in +`phy/apps/large_recording/tests/test_curation_comparison.py`. + +The ordinary GUI run exercises the usual complete-data workflow. The bounded +GUI run exercises retained evidence, semantic action journaling, and full-source +replay. Separately, `tools/compare_curation_modes.py reference --engine +ordinary` executes full Supervisor commands without GUI views attached; it is +an ordinary engine reference, not evidence from the ordinary GUI. The +`--engine streamed` reference is a further independent streamed baseline, also +not GUI evidence. + +## Freeze inputs and outputs + +1. Pin the exact ordinary and bounded code revisions under review. Record both + revisions and the comparison tool revision. +2. Preserve an immutable, complete snapshot of the source sorting. Create a + separate writable working copy for the ordinary GUI, which saves in place. + Record hashes for `spike_times.npy`, `spike_clusters.npy`, and + `amplitudes.npy`. Do not use the bounded evidence package as the ordinary + input. +3. Prepare the bounded package from the immutable source and retain its manifest, + window plan, journal, and preparation report. Use fresh output directories + outside the immutable source copies. +4. Use the same selected source units, threshold, action order, and explicit + final manual labels in both GUI runs. Save each result and preserve its + final full output. Keep screenshots or a short screen recording of the + relevant preview and actions alongside the ledger. + +For real data, record the dataset's actual extent and time axis from metadata. +Do not use a generated 500-hour example as evidence about a different real +recording. In particular, Carl's currently available converted dataset is +469 million spikes and 112.9 hours on its declared clock, with a frame value +near 100 hours; it is not a 500-hour dataset. Treat any newer source revision +as a separate input and recapture its metadata. + +## Graphical action ledger + +Record one shared `ledger.json`. The following schema illustrates the order and +the required alias mapping; replace example aliases, IDs, threshold, and labels +with those actually used. The actions describe user intent, including history +and save boundaries. + +```json +{ + "aliases": {"unit_a": 40, "unit_b": 44, "unit_c": 48}, + "actions": [ + {"op": "merge", "parents": ["unit_a", "unit_b"], "as": "merged"}, + { + "op": "split", + "parent": "merged", + "threshold": 1.5, + "selected": "low", + "remainder": "rest" + }, + {"op": "undo"}, + {"op": "redo"}, + {"op": "label", "ids": ["low"], "field": "group", "value": "good"}, + {"op": "label", "ids": ["low"], "field": "notes", "value": "reviewed low side"}, + {"op": "label", "ids": ["rest"], "field": "group", "value": "mua"}, + {"op": "label", "ids": ["rest"], "field": "notes", "value": "reviewed remainder"}, + {"op": "label", "ids": ["unit_c"], "field": "group", "value": "mua"}, + {"op": "label", "ids": ["unit_c"], "field": "notes", "value": "reviewed unchanged unit"}, + {"op": "save"}, + {"op": "reopen"}, + {"op": "save"} + ], + "expected_labels": { + "low": {"group": "good"}, + "rest": {"group": "mua"}, + "unit_c": {"group": "mua"} + }, + "fields": ["group", "notes"] +} +``` + +Use the actual final unit identities returned by each run to fill the aliases. +In ordinary Amplitude View, select the **template** amplitude type, which reads +`amplitudes.npy`; feature and template-feature amplitudes define different +quantities. Run ordinary GUI acceptance with the graphical threshold interaction +(Alt plus right-drag, then `K`) and bounded GUI acceptance with the same threshold. Use +source units whose amplitudes are all finite for this graphical equivalence +check. Bounded splitting assigns finite values strictly below the threshold to +the selected side; equal and nonfinite values stay in the remainder. Require +evidence on both sides before committing. Test nonfinite values separately +through the raw source predicate engine: ordinary TemplateModel displays +nonfinite amplitudes as zero, so its graphical selection need not match that +raw predicate. The ordinary comparison engine deliberately uses raw source +`amplitudes.npy` values rather than displayed values. + +Record intentional no-ops and state boundaries in the acceptance log alongside +the shared action ledger when relevant: for example an invalid threshold +rejected before mutation, an undo with nothing available, a no-change label, a +save/reopen/save cycle without edits, or a second save without edits. The +reference harness ledger currently supports merge, split, label, undo, redo, +save, and reopen; do not put unsupported no-op operations into its `actions` +array. Record the expected result (no mutation, rejection, or unchanged output) +so both GUI branches are checked consistently. + +After the final redo and before concluding, assign explicit final `group` and +`notes` values to every transformed or deliberately reviewed final unit, plus +an unchanged control. Other untouched units retain and compare their source +labels. This keeps the comparison about reviewed manual labels, not +legacy producer-label inheritance. The protocol compares only the requested +manual fields. Producer metrics such as SNR may intentionally be cleared on +transformed memberships in bounded mode. Membership-scoped quality automation +may also give transformed units different automatic status; record and review +that behavior separately instead of treating it as a manual-label mismatch. + +## Complete-output comparison + +Export the ordinary GUI result and run `phy apply-curation` on the bounded +session to produce its complete full-source result. The bounded GUI assignment +at `K` covers retained evidence rows; replay applies its recorded predicate to +the unseen source spikes. Save both results to separate complete output +directories. +Put the JSON report in a fresh path outside both compared directories and both +immutable source copies. Compare the complete output directories (not the +bounded package or its retained rows): + +```bash +uv run python tools/compare_curation_modes.py compare \ + /data/ordinary-final /data/bounded-replay-final \ + --fields group notes --output /data/curation-comparison.json +``` + +The report checks equal source row counts and exact row-aligned `spike_times`, +then proves partition equivalence using a two-way raw cluster-ID mapping over +all assignment rows in chunks. It checks the requested manual labels through +that mapping. A label attached to an ID with no assigned spikes is reported as +unmapped and fails acceptance; empty or unmapped label tables are not silently +ignored. `--fields` is an explicit allowlist: include the manual fields reviewed +in the ledger and do not add producer metrics or automatic quality fields whose +bounded membership policy intentionally differs. Review the full report, +including input hashes, ID mapping, examples, and label diagnostics. A zero exit +status and `ok: true` are required. + +This check establishes final partition and chosen manual-label equivalence for +the pinned inputs and ledger. It does not prove identical intermediate UI +behavior, producer metadata, automatic quality calculations, or scientific +validity of the reviewed labels. Preserve GUI evidence and compare reports with +the pinned revisions and immutable source hashes. + +## Practical user-test matrix + +Start with one shared ledger, then add small variants rather than attempting +every combination in one session. These are proposed user checks; the observed +automated run is recorded separately below. + +| Check | What to verify | +| --- | --- | +| Merge and review | Merge three units, split the result, then merge one child with another original unit. Explicitly assign GOOD, MUA, noise, a cleared/unsorted group and custom notes on final units. Try reversing merge-candidate order in a separate run. | +| History | Undo and redo a merge, split and label. Undo, make a different edit and confirm redo is discarded. Track the actual new IDs rather than assuming allocation reuse. | +| Thresholds | Compare graphical `K` with the exact recorded numeric threshold. Test equality, a rejected one-sided threshold, and selection/context changes that clear a preview. Test raw nonfinite values separately from ordinary graphical equivalence. | +| Persistence | Save, close, reopen and save without edits. Apply, prepare again, save without edits and apply again. Compare complete assignments and explicit manual labels after both rounds. | +| Sampling and gaps | Repeat a small ledger with a different seed, window plan or budget while both children retain evidence. Keep the same authoritative gap/exposure declaration and source predicate. The complete result should be independent of the displayed sample. | +| SLAY decisions | Separately accept and reject suggestions, transform an overlapping unit and check stale reasons. Preserve decisions through further rounds using the existing `design/slay-roundtrip-validation.md` procedure. The comparison reference ledger does not implement proposition operations. | + +## Observed engineering acceptance, 26 October 2026 + +Runtime code and comparison tool were pinned at +`06637b24aeca9b0984d7928d459187df46406444` on PR #1428's existing +`feature/long-recording-curation` branch. The source was Carl's converted test +overlay for computation `b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`: **469,725,567 +spikes**, 705 original units and a 112.859-hour elapsed clock. Its inferred +exposure remains unverified acquisition truth; this is engineering integration +evidence, not native-export acceptance or a run on Carl's newer 500-hour data. + +The bounded package contained 1,486,361 evidence spikes. A native X11 Qt GUI +performed the real `Alt`-right drag and `K` action, then saved and reopened. +The shared [recorded ledger](curation-mode-acceptance-ledger.json) includes: + +1. Merge 40, 44 and 48; undo and redo. +2. Graphically split the merged unit using the exact preview threshold + **-424.0037077454673** in raw source amplitude units; undo and redo. +3. Merge the low-amplitude child with original unit 24. +4. Explicitly label that new unit GOOD, the remainder MUA and unchanged + control 49 MUA, with custom notes. Change a label to noise, undo it, then + branch with a different label and restore the intended final MUA value. +5. Save, reopen and save again without edits; apply to the full source. + +The independent reference ran the same ledger through the complete ordinary +Supervisor/Clustering and ClusterMeta implementations without attaching GUI +views. It used raw source amplitudes for the predicate. Both paths used the +same PR revision: this was **not a main-branch versus PR ordinary GUI trial**. +The ordinary run finished in 3:31 with 29.8 GiB peak RSS and no swap, under a +96 GiB virtual-memory ceiling. The bounded GUI plus first replay took 53.3 s. +These are single warm-cache observations, not controlled benchmarks. + +The independent complete-output comparison passed over **all 469,725,567 rows**: +exact row-aligned sample times, **zero partition mismatches**, a bijection over +703 final units, and **zero group/notes mismatches or unmapped label IDs**. +The numerical unit IDs also happened to agree; that is not required by the +partition test. Complete NPY file hashes for assignments differ because the +ordinary reference writes a vector and replay retains the source column shape; +the comparator normalizes both shapes and checks every assignment exactly. +The [committed report summary](curation-mode-acceptance-result.json) retains +the comparison method, revision, counts, diagnostics and input hashes. + +A further preparation from that full output, direct session save, reopen, +no-edit save and replay completed in 121.8 s. All **18 complete NPY files**, +including assignments and spike times, and both explicit group/notes tables +matched the preceding replay byte-for-byte by SHA-256. This second cycle tests +persistence without edits; it is separate from the native GUI save/reopen test. +An independent hash verifier also confirmed that all **67 original download +files** remained unchanged, and that **19 immutable source files in each full +output** matched the converted input. + +### Screenshots and reproduction + +The three images in `docs/images/amplitude-threshold-workflow/` show a separate +disposable demonstration on the newly prepared real output, selecting unit 708. +They show its sampled overview before the drag, the orange threshold preview +with matching waveform highlights, and the two children after actual `K`. +The exact threshold is **-180.09097605065006**, with retained children of 3721 +and 3643 spikes and 34 highlighted waveform traces. This is a separate split +from the shared comparison ledger. All 88 files in the input bounded package +retained their hashes; the capture operates on a temporary copy. + +```bash +QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 \ + xvfb-run -a -s '-screen 0 2600x1600x24 +extension GLX' \ + uv run --no-sync python tools/capture_long_recording_views.py \ + --amplitude-split --bounded-dir /data/fresh-bounded \ + --cluster-ids 708 --output-dir /data/amplitude-screenshots + +QT_QPA_PLATFORM=offscreen uv run --no-sync python \ + tools/compare_curation_modes.py reference /data/full-source \ + design/curation-mode-acceptance-ledger.json /data/ordinary-reference \ + --engine ordinary --chunk-size 1000000 + +uv run --no-sync python tools/compare_curation_modes.py compare \ + /data/ordinary-reference /data/bounded-full-output --fields group notes \ + --chunk-size 1000000 --output /data/comparison.json +``` + +The reference command uses full ordinary in-memory curation and needs memory +appropriate for the source. Its comparison artifact is assignments, times, +manual-label tables and provenance, not a complete sorting export. Choose the +actual active unit in a fresh bounded package when reproducing the screenshots. +Pixel quantization can move the requested threshold slightly; `capture.json` +records the exact committed value. + +Local reports, scripts and logs are archived in +`/home/cyrille/GIT/IBL/phy-data/carl/aind-b1b0782a-b3ea-4f34-81d7-b3c6e36452b3/curation-mode-acceptance/`. +The initial one-off native GUI script needed a harness correction from QWidget +focus handling to QWindow activation; the corrected GUI and reference processes +both exited zero. The final capture tool also exits zero. + +`make test-full` passed **960 tests** (499 core and 461 application), with one +existing benchmark skip, including lint and formatting. The 24 added tests cover +six graphical workflows and eighteen independent comparisons, including raw +nonfinite semantics, ID renumbering, metadata differences, callback cleanup, +history and output protection. The independent Sol 6.1-high audit found no +remaining concrete blocker. Documentation checks and CI are recorded at handoff. + +The later [main-GUI comparison](curation-main-gui-validation.md) completed this +same ledger on unmodified main and matched every assignment and manual label. +It retains baseline Feature View rendering errors as an explicit limitation. +Carl's manual usability and scientific review remain useful, together with the +small practical variants in the matrix. Neither automated run establishes the +scientific validity of splits or of the acquisition exposure declaration. diff --git a/design/large-recording-curation.md b/design/large-recording-curation.md new file mode 100644 index 000000000..26f6d482e --- /dev/null +++ b/design/large-recording-curation.md @@ -0,0 +1,348 @@ +# Long-recording curation in Phy 2.x: Phy-side design contract + +**Status:** implementation present; acceptance validation is ongoing. This +specification is for Phy-side behavior; it does not authorize changes to the +AIND/Code Ocean export pipeline. The current branch implements the bounded +workflow behind an explicit manifest while retaining standard behavior for +ordinary datasets. See the [integration plan](large-recording-integration-plan.md) +and [validation record](large-recording-validation.md) for implementation scope, +checks, and remaining acceptance work. + +The [integration audit and plan](large-recording-integration-plan.md) refines +this proposal with assignment revisions, transactional persistence, capability +gates and ordered commit acceptance criteria for one implementation PR. Its enablement gates take precedence +over the original implementation sequence in Section 9. + +## 1. Objective and boundaries + +Curate chronic Neuropixels sorting datasets of roughly 1000 hours without opening hundreds +of millions or billions of spikes in the existing in-memory Phy clustering model. +The workstation downloads the **complete sorter output once**; downloading the +complete raw voltage recording is **not required**. All preparation, interactive +curation, full-data replay, and regeneration run locally: + +```text +complete, immutable sorting (local disk) + | prepare-large: streamed/batch + v +bounded, temporally distributed Phy dataset + full-duration summaries + | existing Template GUI + Unit Stability + v +semantic curation actions (not only sampled row assignments) + | apply-curation: streamed/batch against complete sorting + v +new complete curated sorting (original untouched) + | prepare-large again, potentially different evidence windows + +-----------------------> new bounded GUI dataset +``` + +The **complete spike-level sorting stays outside the interactive GUI**. +The bounded dataset must reproduce useful current Phy workflows rather than +pretend to be a statistically representative replacement for every spike. +Full-duration plots and rates come from separate complete-sorting summaries. + +Out of scope: cloud services, rewriting phylib for out-of-core clustering, +longitudinal unit-identity graphs (phy3), automatic change-point detection, and +implementing upstream waveform extraction in this repository. + +## 2. The three index spaces (essential contract) + +All index values below are **zero-based row positions**, not timestamps, sample +numbers, SpikeInterface unit IDs, or stable IDs assigned by a sorter. + +| Symbol | Meaning | Where it lives | +| --- | --- | --- | +| `g` | Full-sorting spike row index, in immutable source order | Original `spike_times.npy` / `spike_clusters.npy` | +| `b` | Bounded spike row index used by the GUI | Bounded `spike_times.npy` / `spike_clusters.npy` | +| `w` | Row in the stored waveform/channel tensors | `_phy_spikes_subset.waveforms.npy` / `.channels.npy` | + +**Canonical mapping:** the bounded package writes +`_phy_spike_global_ids.npy`, a one-dimensional strictly increasing `int64` +array of length `N_bounded`. It is `G[b] = g`. The underscore prefix is +intentional: phylib treats ordinary `spike_*.npy` files as per-spike +attributes, so `spike_global_ids.npy` would be needlessly interpreted as one. + +**Dataset-local waveform IDs:** `_phy_spikes_subset.spikes.npy[w] = b` in the +bounded package. In the *upstream full export*, the same filename instead +contains `g` because that file accompanies the full sorting. The file **never** +means an intrinsic immutable/global ID; it indexes whichever Phy dataset is in +its directory. + +Example: + +```text +full indices selected by prepare-large, G: + [14, 19, 27, 117, 203, 839] +bounded rows b: + [ 0, 1, 2, 3, 4, 5] +upstream waveform full indices: + [14, 117, 839, 1902] +intersection with G: + [14, 117, 839] +bounded _phy_spikes_subset.spikes.npy: + [ 0, 3, 5] +``` + +Recover full source row numbers for waveforms by composition: + +```python +G = np.load('_phy_spike_global_ids.npy', mmap_mode='r') +B = np.load('_phy_spikes_subset.spikes.npy', mmap_mode='r') +full_waveform_rows = G[B] # [14, 117, 839] +``` + +`prepare-large` must preserve source row order, subset all per-spike arrays +consistently, retain absolute spike sample times, and remap matching waveform +rows **along with the corresponding channel/waveform data**. A sorted +intersection / `np.searchsorted` implementation needs no billion-element +inverse lookup array. Sorting by sample time is not a substitute for preserving +row identity; use the source export's exact row order (including ties). + +## 3. Source and optional upstream waveform inputs + +The source is a locally accessible standard Phy/SpikeInterface export (or an +adapter yielding equivalent arrays). The original spike index `g` refers to +**the exact exported row ordering**, not an assumed row in an unrelated +SpikeInterface spike vector. Source arrays and their provenance must be +validated before processing; never infer a row mapping from spike timestamps. + +The existing, unmodified Phy waveform files are: + +| Filename | Meaning | +| --- | --- | +| `_phy_spikes_subset.spikes.npy` | `int64[N_waveforms]`: source full spike row indices, sorted/unique | +| `_phy_spikes_subset.channels.npy` | `int32[N_waveforms, C_sparse]`: model channel indices, with `-1` padding; `channel_map.npy` maps these to raw-file columns | +| `_phy_spikes_subset.waveforms.npy` | numeric `[N_waveforms, N_samples, C_sparse]`: aligned waveform data, zero on padded channels | + +The upstream AIND pipeline **may later** supply the following proposed files; +these names/schema are *not yet finalized with its developers*: + +| Optional file | Initial proposal | +| --- | --- | +| `_phy_spikes_subset.window_bounds.npy` | `int64[W, 2]` recording sample intervals, `[start, end)` | +| `_phy_spikes_subset.window_types.npy` | `uint8[W]`: `0` survey, `1` rescue | +| `_phy_spikes_subset.window_strata.npy` | `int32[W]`: survey stratum index, `-1` for rescue | +| `_phy_spikes_subset.manifest.json` | Small versioned scalar metadata: source identity, time base, extractor geometry, parameters, seed, array semantics | + +There are deliberately **no structured NumPy dtypes**, mixed-purpose `N x 5` +matrices, or massive JSON window arrays. The upstream manifest is useful for +planning downstream windows but is not required for fixture-based development. +The presence of a window denotes *potential* waveform coverage, not one stored +waveform for every spike within that interval: per-unit waveform caps still +apply. The three established waveform files remain authoritative for which +individual spikes actually have stored waveforms. + +In the absence of the proposed window sidecars, `prepare-large` may use the +existing three files and their spike-index/time distribution as available +evidence, with reduced guarantees about raw-I/O locality and survey windows. +A dataset with neither raw traces nor pre-extracted waveforms must not claim +that Waveform/Feature View evidence is available. + +The full export's identifier/fingerprint should combine an immutable sorting +asset ID when available, full spike count, and a digest of a canonical +row-ordered immutable spike array (`spike_times.npy` is one candidate). The +upstream reservoir must be verified against that *exact* source. A mutable +`spike_clusters.npy` hash must not be the sole identity used across curation +iterations. Byte-level hashes in examples are illustrative; the definitive +AIND provenance method is a pending joint decision. + +Coordinate identity and assignment revision are separate: the latter binds the +initial full cluster assignments and metadata for replay. Each curated output +records its parent revision and journal digest. Validate relevant immutable +feature, acquisition and time-base provenance as well as spike rows; equal +timestamp arrays alone do not establish source identity. Production hashing +must stream file contents rather than read a complete array into memory. + +## 4. Bounded-package Phy-side output + +`prepare-large` creates a **new directory**, not an in-place rewrite of the +original. At minimum it contains ordinary, internally consistent Phy files +(`params.py`, `spike_times.npy`, `spike_templates.npy`, `spike_clusters.npy`, +channel/template arrays, and present per-spike attributes), plus: + +| File | Role | +| --- | --- | +| `_phy_spike_global_ids.npy` | Required `int64[N_bounded]` sorted mapping `b -> g`, no duplicates | +| `_phy_curation_manifest.json` | Versioned local contract; immutable source ID/fingerprint, complete/bounded counts, durations, preparation algorithm/parameters/seed, evidence limitations and file names | +| `_phy_spikes_subset.{spikes,channels,waveforms}.npy` | Existing Phy-format stored waveforms, *remapped to bounded row indices* (if available) | +| Full-duration metrics | Separate time-binned evidence, described in Section 6; do not pretend proxy metrics are full metrics | + +Unselected spike rows are absent from the GUI arrays, **not deleted from the +complete sorting**. Absolute `spike_times.npy` values remain in acquisition +sample coordinates and require a dtype capable of representing 1000 h at the +source sample rate (typically `int64`, not `int32`). For 30 kHz, 1000 h is +108 billion samples. Keep recording start/end, session/block boundaries, valid +acquisition exposure, and gaps distinct from periods of zero firing. + +Do not rely on phylib's fallback of estimating `model.duration` from the last +spike when raw traces are absent. The future GUI metrics/time-axis integration +must take the authoritative duration/coverage metadata instead. Standard +`params.py` still identifies the bounded Phy dataset; the manifest augments it. + +## 5. Preparation algorithm: scientific and memory constraints + +A first version should: + +1. Scan the **full** local sorting in a bounded-memory batch pass; calculate + full-duration per-unit time bins and coverage/exposure. +2. Partition *valid acquisition time* into coarse strata. Select short shared + contiguous survey windows at deterministic seeded offsets across sessions/ + blocks (illustrative defaults: one 30 s window per 1 h stratum). +3. Include **all units and all spikes within each chosen window** as initial + bounded candidates; preserve source indices and absolute times. +4. Enforce configurable **total spike / RAM budgets**. Add shared rescue windows + for underrepresented units, prioritizing benefit to several units and + temporally separated evidence; retain bounded deterministic selection. +5. Where a waveform reservoir exists, favor windows with usable waveform + coverage and report per-unit counts and uncovered regions. Selecting a + window does not guarantee all its spikes have stored waveforms. +6. Write an atomic, versioned bounded package. Verify array-length alignment, + sorted global IDs, waveform/feature alignment, provenance, coverage and + source immutability before marking it usable. + +These choices are **heuristics**, not a claim of unbiased sampling, complete +physiological representativeness, or equivalent CCG/ISI statistics. Never label +metrics from the bounded subset as full-data measurements. Windows identified +manually in a future Unit Stability View may motivate a regenerated package; +automated anomaly detection is out of scope. + +The upstream `20_000` waveform cap per unit is **not** a mandatory local budget: +for 1000 units x 20k waveforms x 90 samples x 32 channels x 4 bytes it would +approach **230 GB** uncompressed. Extraction, transfer, storage and bounded +GUI consumption require independently configurable *total* byte/spike budgets. + +## 6. Unit Stability evidence from the full recording + +A Unit Stability View should work on ordinary 1-10 h recordings too. For a +selected cluster it plots time-binned **full-sorting** spike count / firing rate, +amplitude median/quantiles, depth/position and presence/coverage when those +quantities exist in the source. Use an explicit time axis, valid acquisition +exposure per bin, data-availability flags, and recording gaps. Counts divided +by wall-clock bin width are wrong for acquisition gaps. No missing metric should +be silently synthesized. + +Initial storage may use regular homogeneous `.npy` arrays plus a small manifest, +with explicit row-to-cluster-ID mapping and bin edges; exact metric schema and +plot integration belong to the Unit Stability PR. At each full-data curation +iteration, merged/split clusters must receive **correctly recomputed or +incrementally updated** summaries, not merely the stale parent-unit curves. + +Current `BaseController.get_mean_firing_rate()` divides the loaded cluster's +`n_spikes` by `model.duration`; this would severely undercount a bounded unit. +When a bounded package is detected, its full-count/exposure-aware value must +replace that calculation wherever presented. The same provenance distinction +applies to the Cluster View, correlograms, ISI and other proxy-based statistics. + +Window statistics need explicit observation intervals. Do not connect ISIs or +CCG pairs across independent segments or unsupported gaps. CCG normalization +must use a declared lag-exposure estimator for those intervals; initially hide +unsupported normalized diagnostics. Whole-window sampling, rescue selection +and incomplete waveform coverage do not establish unbiased full-data quality +metrics or chronic biological unit identity. + +## 7. Semantic curation and full-data replay + +The current `Clustering` operates on arrays of loaded spike rows, creates new +cluster IDs during `assign/split`, and saves those local assignments. They +cannot by themselves define the fate of billions of unobserved spikes. + +Before mutations in a bounded GUI session, record **versioned semantic events** +with preconditions, affected source clusters, deterministic operation parameters, +resolved cluster IDs and provenance. Track edits through existing undo/redo and +save. Apply them in order against the *complete* local sorting to write a new +curated output (never overwrite the original). + +| Operation | Initial replay policy | +| --- | --- | +| Merge complete units | Reapply to every source spike in the units; replayable | +| Cluster quality/metadata labels | Replay per resulting cluster identity; replayable | +| Threshold split | Replay only if the predicate/feature definition is serialized and an equivalent full-data per-spike attribute exists; otherwise disallow | +| Lasso or arbitrary selected spike-ID split | Not replayable for unseen spikes by default; **block in bounded mode** unless a valid full-data rule is supplied | +| Undo/redo | Journal must represent the committed final event sequence and allow exact save/reopen, not duplicate reverted edits | + +Unbounded/ordinary Phy behavior must remain unchanged. It is not acceptable to +silently treat a selection of bounded spike IDs as a valid full-unit split. +Existing `curation.json` merge proposals and `curation_review.json` are separate +producer/review artifacts; the new semantic event journal must not overwrite +either file. Re-running `prepare-large` after `apply-curation` may reuse the same +source spike/waveform bytes because curation changes assignments, not spike +identity. + +For the first editable release, support merges and labels only. Keep all splits +blocked until their specific replay rules pass end-to-end tests. Allocate IDs +from the complete unit catalog, including units absent from the subset. Record +resolved inherited metadata, rather than recomputing it from full parent counts. +Commit journal, assignments and metadata as one validated save generation; +reopen must recover a coherent generation and allocator state. Validate operation +intent before mutation, including plugin and console entry points. + +## 8. Test/reference fixture and future acceptance + +`phy/apps/tests/large_recording_fixtures.py` deterministically writes a minimal +32-spike, **1000 h** full Phy-format sorting and a bounded eight-spike package, +including upstream waveforms for eight different source rows and remapped +bounded waveforms for five. The fixture intentionally omits the raw binary. +`phy/apps/tests/test_large_recording_contract.py` asserts: + +- exact `int64` sample indexing well past the 32-bit limit, source-order and + time preservation; +- full -> bounded -> waveform mapping, including copied waveform/channel rows; +- existing Phy waveform filenames, row/dtype/shape and `-1` padding invariants; +- simple window array dtypes, sample-coordinate bounds and shared row alignment; +- source fingerprint agreement, separate source-vs-bounded identity; +- empty/disjoint intersections and existing phylib load compatibility. + +**These are reference contract tests only:** they do not claim that +`prepare-large`, Unit Stability or semantic replay already exists. Subsequent +PRs should reuse the fixture but replace the reference remapping with tests of +the production command. Add mismatched-source, reordered-row, excessive-memory, +partially covered units, gap, sparse feature and replay/undo corruption tests +before enabling bounded curation on real datasets. + +## 9. Ownership and implementation order + +1. **This PR:** Phy-side design, source-coordinate/format reference fixture and + tests only. No GUI changes, no new CLI, no upstream exporter changes. +2. **Unit Stability:** full-data summaries and selected-unit GUI view, initially + usable on normal recordings. Keep user-visible full/partial provenance clear. +3. **Semantic curation journal:** integration with `Supervisor`, event semantics, + undo/save/reopen and blocking unsafe splits in bounded mode. +4. **`prepare-large`:** separate streaming batch CLI, input validation, window + selection, output/remapped waveform files and bounded-manifest generation. +5. **`apply-curation`:** validate/replay semantic actions against full local + sorting, write a new curated full sorting, verify, then regenerate a bounded + package. Test deterministic repeatability and failures atomically. + +The integration plan now organizes these stages as commits within a single PR, +rather than separate PRs. **Do not ship an editable bounded GUI without replay safety**. + +Agent starting points: `AGENTS.md`, `design/README.md`, +`phy/apps/__init__.py` (Click CLI), `phy/apps/template/gui.py` (controller), +`phy/apps/base.py` (views/rates/save), `phy/cluster/{clustering,supervisor}.py` +(actions/history), `phy/apps/template/tests/test_gui.py`, and +`phy/apps/tests/test_large_recording_contract.py`. The existing waveform +reader is in the separate `phylib/io/model.py` dependency. + +## 10. Decisions not frozen by this Phy-side PR + +The upstream team should review the exact optional window-sidecar names, AIND +sorting asset identity/fingerprinting, segment/time/recording-block semantics, +waveform extraction alignment, total storage budget, and whether windows or a +more general sampling-plan format fits its pipeline best. Phy should accept the +existing three-file waveform format regardless. Values such as `1 h`, `30 s`, +`2,000` and `20,000` are preliminary, not schema requirements. + +Code Ocean handles **creation of a reusable evidence reservoir**; Phy handles +**bounded selection, GUI coordinate remapping, full-duration summaries, +semantic curation and replay**. Neither side should infer an absent waveform +or silently redefine source spike IDs. + +## Implementation references + +- [Phy `Clustering.assign`](../phy/cluster/clustering.py) and + [Supervisor](../phy/cluster/supervisor.py) for current row-based edits. +- [Template GUI](../phy/apps/template/gui.py) and + [Waveform/Feature mixins](../phy/apps/base.py) for standard stored-waveform + support and full/proxy metric safeguards. +- [Existing stored-waveform GUI test](../phy/apps/template/tests/test_gui.py). +- [SpikeInterface `export_to_phy` source (AIND inspected commit)](https://github.com/SpikeInterface/spikeinterface/blob/896ea840da72b4a5f06dcf8870ad820d20fe7031/src/spikeinterface/exporters/to_phy.py). diff --git a/design/large-recording-integration-plan.md b/design/large-recording-integration-plan.md new file mode 100644 index 000000000..de9e7043d --- /dev/null +++ b/design/large-recording-integration-plan.md @@ -0,0 +1,283 @@ +# Long recording audit and integration plan + +## Assessment + +The downloaded contract bundle is a useful foundation. Keep the bounded GUI, +immutable full sorting, explicit source-row mapping, and full-data replay model. +Do not enable editing until replay and persistence agree with the GUI. A 1000-hour +timestamp fixture validates coordinate range; it does not validate capacity or +scientific representativeness. + +This review targets phy `7e439491` and the downloaded +`phy_large_recording_contract_bundle.zip`. The accompanying contract remains a +proposal. This plan refines its implementation order and supplies additional +requirements; the phases below govern enablement. + +## Findings that affect correctness + +1. **Identity needs two layers.** A spike-coordinate fingerprint identifies + immutable rows and their time/channel/feature provenance. An assignment + revision identifies the starting full cluster assignments and metadata. + Replay must validate both. A times-only hash cannot distinguish recordings + with identical timestamps or changes to feature values. Include the acquisition + identity, time base, relevant immutable array digests and schema in coordinate + identity; hash assignments and metadata separately for each revision. Record + parent revision, journal digest, output revision and preparation identity. + Compute hashes incrementally, without `read_bytes()` on production arrays. + +2. **Cluster IDs must come from the full namespace.** + [Clustering](../phy/cluster/clustering.py) initializes its allocator from the + maximum loaded cluster ID. A subset can omit the highest full ID. Seed the + allocator from a full unit catalog and persist its high-water mark. Record + explicit output IDs in events and reject collisions during replay. Units with + no bounded evidence remain in the catalog and output, with missing evidence + visible to the user. + +3. **Save is a transaction.** + [BaseController](../phy/apps/base.py) currently saves assignments and metadata + separately; [Supervisor.save](../phy/cluster/supervisor.py) emits further save + events and clears dirty state. Adding another journal file to that chain does + not make it crash consistent. Bounded mode needs immutable save generations + containing assignments, metadata, journal and identity, published by a single + commit pointer. Reopen only complete validated generations. Preserve the last + valid generation after interruption; keep dirty state after a failed commit. + Define whether undo survives reopen. Recommended v1: reopen establishes a new + undo baseline while retaining the committed semantic history for replay. + +4. **Record resolved metadata.** `Clustering._do_merge` selects the largest + parent using loaded counts, and Supervisor inherits its metadata. Full and + sampled counts can choose different parents. Serialize the resolved group and + custom labels in merge events, including an explicit policy for conflicting + labels. Replay must not infer this choice from full counts. + +5. **Capture intent before mutation.** + [AmplitudeView.on_request_split](../phy/cluster/views/amplitude.py) returns + selected row IDs and clears the threshold. A listener after clustering cannot + recover the predicate. Route bounded edits through a command service before + any mutation. Gate direct assign/split, plugins, console operations, shortcuts, + merge proposals and threshold providers at the mutation boundary. V1 supports + whole-unit merges and labels; block every split until its full-data semantics + are implemented and tested. + +6. **Statistics require observation intervals.** Preserve shared contiguous + windows and segment boundaries. ISIs must not connect windows or acquisition + gaps. CCGs must exclude pairs crossing unsupported boundaries, and their + normalization must match observed lag exposure; the existing full-duration + baseline in `BaseController._get_correlograms_rate` is not valid for a window + subset. Initially suppress unsupported normalization and diagnostic claims. + Label window statistics as sampled evidence. Rescue selection and waveform + availability introduce bias; they do not justify extrapolating quality, + contamination, refractory violations or chronic unit identity to the full run. + +7. **Define time and channel coordinates.** V1 accepts one validated monotonic + sample axis with a fixed sampling rate and explicit valid acquisition + intervals. Reject unsupported segment layouts rather than concatenate silently. + Preserve tied timestamps and source row order. Sparse waveform channel IDs + index model channels; `channel_map.npy` maps these to raw-file columns. They + are not interchangeable with hardware or SpikeInterface channel IDs. Test a + nonidentity map, sparse padding, whitening/scaling and waveform alignment. + Keep sample coordinates as integers and CPU times as float64; subtract the + viewport origin before converting fine-scale plotting positions to float32. + +8. **All preparation products need budgets.** A dense units-by-time-bin summary, + exact quantile calculation, waveform gather, or full index inversion can + exceed RAM despite streamed input. Specify batch, output, summary, cache and + GUI memory limits, plus temporary disk estimates. Distinguish peak working + memory from file-backed pages. Whole shared windows exceeding the spike budget + must be shortened, rejected or replaced with documented deterministic rules; + do not silently thin spikes within a window and retain its statistical claims. + +9. **Persist the final window plan.** Store retained intervals, segment/block + identity, survey/rescue classification and valid exposure in the bounded + package. A seed and parameters do not identify trimmed or replaced windows. + Count acquisition exposure once when composing merged-unit summaries. + +## Module boundaries + +Use a small `phy/apps/large_recording/` package, with pure services callable +without Qt and thin Click/controller adapters. Refine filenames while coding; +keep these responsibilities separate: + +| Responsibility | Contract | +| --- | --- | +| Source adapter and validation | Stream canonical arrays; classify per-spike, template, channel and cluster data explicitly; reject ambiguous unsupported arrays | +| Manifest and identity | Validate versions, paths, coordinate identity, assignment revisions, exposure and capabilities | +| Preparation | Deterministic window plan, bounded output, streamed waveform remapping, budget report | +| Summaries | Full counts/exposure, availability, declared exact or approximate estimators and multiresolution queries | +| Semantic commands and journal | Operation validation, explicit IDs/metadata, history cursor and transactional commit | +| Replay | Pure event interpretation, chunked output assignments, invariants and lineage | +| GUI adapter | Capability gating, evidence labels, bounded model/controller integration | + +Do not load the complete source through TemplateModel or Clustering in batch +commands. Do not hide full-data scans in a selected-unit GUI callback. Limit +changes to phylib to demonstrated loader/coordinate fixes, with separate tests +and dependency requirements. Preserve existing ordinary-dataset behavior. + +## One implementation PR with ordered commits and acceptance gates + +Implement the complete workflow on `feature/long-recording-curation` in the +main phy checkout. Use the stages below as reviewable commit groups within one +PR. Intermediate capability gates support development; merge the PR only after +the complete prepare, curate, save, replay and regenerate workflow passes its +acceptance checks. Predicate splits require their own full-data equivalence +checks within the same PR if included in its supported functionality. + +### 1. Contract and reference fixtures + +Start with the revised contract, this plan and format fixtures. +Fix the bundle's missing `dtype` in `params.py`, allow equal sample times, and +reject malformed reference row IDs. Run the real released-phylib loader test +without accepting a skip. Its success proves this small file layout loads, +not that all GUI workflows or long-recording statistics are supported. + +### 2. Source validation and summary engine + +Implement identities, assignment revisions, array inventory, exposure and +capability validation independently of Qt. Start with full counts and rates; +add amplitude/depth only with defined units and available source attributes. +Do not add per-bin quantiles until their exact/approximate algorithm, merge +behavior and memory costs are specified. Medians cannot be merged by averaging +parent medians; invalidate or recompute unavailable derived summaries. + +Gate: exact tiny-oracle counts; missing exposure; gaps; source/feature mismatch; +reordered rows; column-vector input arrays; unknown versions; unsupported +segments; bounded peak memory as source size grows; actionable disk estimates. + +### 3. Read-only preparation and inspection + +Implement `prepare-large` with deterministic shared windows, rescue policies, +per-unit evidence reports and explicit budgets. Write into a temporary sibling +directory and publish only after complete validation. Rebuild paths in params, +subset every registered per-spike array, retain template-indexed structures, and +avoid copying stale `.phy` caches and derived cluster metrics. Unknown attributes +must be explicitly included, excluded with a report, or rejected. + +Add a bounded-manifest GUI adapter with authoritative duration, full/proxy +counts and unsupported-view safeguards. Until phase 6, require read-only bounded +sessions, including save and plugin mutation entry points. + +Gate: production command vs independently specified expected arrays; shuffled +channel mapping; actual `get_waveforms()` values; sparse PC feature alignment; +missing/partial waveform coverage; tied samples; zero evidence units; empty +selection policy; deterministic budgets; interrupted publication; no source +writes; GUI open/close and time-axis precision tests. + +### 4. Semantic commands and durable saves + +Implement merge/label command validation, full-catalog ID allocation, resolved +metadata, undo/redo active history and transactional generations. Keep the +feature disabled for editable bounded sessions while replay is incomplete. +Existing `curation.json` and `curation_review.json` retain their separate roles. + +Gate: merge chains; conflicting labels; undo then branch; redo; reopen baseline; +omitted high-ID units; proposal-driven merges; rejected direct split/assign; +failed-save dirty state; fault injection at every commit boundary; assignments +equal the journal's projection onto bounded rows. + +### 5. Full-data replay + +Implement `apply-curation` against an exact source assignment revision. For v1 +merges, resolve the final source-unit mapping once, then stream assignments into +a new full dataset. Preserve row count/order, times and immutable arrays; write +metadata and lineage coherently. Reject repeated application to the wrong parent +revision. Publish only a verified complete output. Reprepare from that revision +with the same coordinate identity and fresh revision-dependent summaries. + +Gate: compare every assignment with an independent tiny oracle; preserve all +unseen spikes; replay chains and labels exactly; reject mismatched parent or +corrupted journal; interruption never exposes a complete-looking partial output; +same source/events produce the same semantic result; source bytes unchanged. + +### 6. Enable bounded merges and labels with Unit Stability + +Expose editable bounded mode only when phases 3–5 pass together. Integrate a +Unit Stability view that distinguishes acquisition exposure, evidence windows, +available measurements and unresolved identity. Add bounded status and operation +capabilities to the existing workflow. Count/exposure summaries can update for +merges; quantiles and other nonadditive metrics require recomputation or explicit +unavailability. Keep all splits blocked. + +Gate: prepare → inspect → merge/label → undo/redo → save/reopen → replay → +reprepare → verify. Include ordinary 1–10 h datasets to prevent regressions. +Run `make test-full`, `make doc-check`, and `uv build` when CLI/package changes +are included. Complete manual smoke testing with an actual chronic dataset. + +### 7. Optional predicate splits + +Add one operation at a time after the initial workflow is accepted. Store feature +identity/units, predicate operator, threshold, missing-value policy, parent +revision and explicit child IDs. The same predicate must evaluate identically +on GUI evidence and all source spikes. Stored waveform-derived or local PCA +amplitudes do not automatically define a full-data predicate. Lasso splits +remain unavailable without a separately validated full-data rule. + +## Standard recording compatibility gate + +Recording length must never select a new behavior implicitly. Activate bounded +curation only through an explicit validated bounded manifest. Without that +manifest, retain the standard loader, selector, metrics, mutation capabilities, +save format and history behavior. A malformed bounded manifest must produce an +actionable error rather than silently enter standard editable mode. Optional +Unit Stability on ordinary recordings must not replace their existing views, +change their default layout or introduce full-source scans at GUI startup. + +Keep the semantic command, replay and transactional save implementation behind +the bounded adapter wherever possible. Any necessary shared-code change requires +focused standard-mode regression coverage in addition to bounded-mode tests. +Do not impose bounded split restrictions or journal files on ordinary datasets. + +Before merging the single PR, run `make test-full` and verify ordinary datasets +with raw traces, stored waveforms only, and sparse features. Cover standard +merge and label inheritance, lasso/threshold/template splits, undo/redo and +branching, save/reopen assignments and metadata, merge proposals, plugin-driven +edits, channel mapping, sampled views and existing rate/ISI/CCG behavior. Assert +that ordinary saves do not create bounded journals or manifests. Compare startup +memory and selection latency on the same ordinary datasets before and after the +change; any meaningful regression must be explained and resolved before merge. +Existing tests and these checks establish compatibility evidence; the plan +itself does not guarantee compatibility before implementation. + +## Capacity and scientific acceptance + +Use three kinds of evidence: tiny exact-oracle datasets for correctness; +generated high-density on-disk datasets for resource behavior; real chronic +recordings for usability and scientific acceptance. Duration, spike count, +number of units, array widths and available waveform coverage are separate axes. +Measure preparation/replay throughput, peak process memory, temporary disk, +GUI startup and selected-unit update latency on documented hardware. Establish +acceptance budgets from those measurements before advertising capacity. + +Have a domain curator review known drift, rare/bursting units, transient +artifacts, gaps and intentionally incorrect merges. Compare selected evidence +with withheld contiguous windows and full-data diagnostics where available. +Record what the curator can and cannot infer; finite selected evidence cannot +guarantee biological identity throughout 1000 hours. Software integrity and +scientific evidence sufficiency are separate release criteria. + +## Producer decisions + +Agree with the producer team on source asset identity, full unit IDs, authoritative +duration/exposure, segment mapping, waveform time/channel/amplitude semantics, +reservoir coverage and total storage costs. Existing three-file waveforms remain +supported; proposed window sidecars must remain optional until jointly agreed. +The inspected [SpikeInterface exporter revision](https://github.com/SpikeInterface/spikeinterface/blob/896ea840da72b4a5f06dcf8870ad820d20fe7031/src/spikeinterface/exporters/to_phy.py) +supports one segment and distinguishes Phy channel indices from exported original +channel IDs. Do not assume that arbitrary multi-session inputs already satisfy +this contract or that a deployed exporter matches this inspected revision. + +## Implementation and validation status + +The branch now includes batched source validation and preparation, full-source +summaries, bounded GUI curation and checkpoints, semantic replay, Unit Stability, +and dedicated long-recording tests. The feature is implemented, but its +acceptance remains incomplete: this test and synthetic benchmark evidence does +not replace real chronic-recording review by domain curators. + +On 2026-10-13, `make test-full` completed with 745 passed and 1 skipped. Three +additional bounded GUI lifecycle regressions pass in +`phy/apps/large_recording/tests/test_gui_lifecycle.py`. +[`design/large-recording-validation.md`](large-recording-validation.md) records +the synthetic capacity runs and their limits. The separate 32-spike, 1000-hour +fixture verifies sample-coordinate handling and file mapping; it is not a +billion-spike capacity test or evidence of chronic biological identity. Curator +acceptance on real chronic recordings remains outstanding. diff --git a/design/large-recording-time-coordinates.md b/design/large-recording-time-coordinates.md new file mode 100644 index 000000000..3c04bc9bf --- /dev/null +++ b/design/large-recording-time-coordinates.md @@ -0,0 +1,244 @@ +# Event coordinates and acquisition exposure + +This document defines the narrow time-coordinate extension for the AIND export +reported against PR #1428. It supplements the +[large-recording contract](large-recording-curation.md) and its +[integration plan](large-recording-integration-plan.md). It does not authorize +changes to an upstream export or establish that this particular chronic +recording is ready for curation. + +## Supported coordinates + +Phy-facing event times are nonnegative integer coordinates on one monotonic +axis. Two explicitly distinguished meanings are supported: + +- `acquisition_samples`: sample indices on the acquisition axis supported by the + original contract. +- `elapsed_ticks`: elapsed seconds from the source recording's time origin, + multiplied by a declared tick frequency and quantized to integers. Gaps remain + visible on this axis. A tick is a time coordinate, not a recorded voltage + sample. + +The optional producer declaration is a Python dictionary in `params.py`: + +```python +sample_rate = 30000.0 +waveform_sample_rate = 30000.0 +time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': 30000.0} +num_samples = 12188787510 +# Illustrative values only; the producer must supply authoritative exposure. +valid_intervals = [[0, 100000], [200000, 12188787510]] +``` + +The same declaration can occur as `recording.time_base` in +`_phy_spikes_subset.manifest.json`. If both locations declare it, they must +agree. `kind` is one of the two strings above; `ticks_per_second` is positive +and finite. Unknown kinds and conflicting declarations are errors. + +For this implementation, `ticks_per_second`, `params.py`'s `sample_rate`, +`waveform_sample_rate` when declared, and the waveform manifest's +`recording.sampling_frequency_hz` when declared must be equal. This keeps the +existing loader and waveform time axes correct for the reported 30 kHz export. +Supporting unequal event tick and physical waveform sample frequencies requires +separate waveform-axis plumbing and is outside this extension. + +The physical and event frequencies nevertheless have different meanings. In +elapsed mode, `sample_rate` converts event ticks to seconds; the waveform +frequency describes the spacing between samples inside each stored waveform. +Clock drift or a piecewise clock map must not stretch the waveform's local +sample axis. + +Without an explicit declaration, retain the original acquisition-sample +behavior and identity representation for existing sources. A source containing +`timestamps.json` must provide an explicit time-base declaration before this +bounded workflow accepts it. This is an intentional conservative admission +rule: the file's presence signals acquisition metadata whose exposure semantics +have not been established by the legacy defaults. It is not proof that every +such source actually has mixed coordinates. The error must explain how to +declare authoritative coordinates and exposure; it must not parse the JSON and +guess a conversion. + +## Bounds and exposure + +For both kinds, the legacy names `num_samples` and `valid_intervals` describe +the canonical event axis: + +- `num_samples` is its exclusive positive integer upper bound. In elapsed mode + it is a tick extent, not the number of acquired frames. +- `valid_intervals` contains ordered, disjoint, nonempty integer `[start, end)` + intervals inside that extent. They declare valid acquisition exposure on the + same event axis. +- Every spike belongs to a valid interval. Time ties and original source row + order remain allowed and preserved. +- Exposure in seconds is the sum of interval lengths divided by the tick + frequency, counted once across units. Gaps and filler are not zero firing. + +An explicit elapsed-time source needs authoritative exposure rather than a +silent `[0, num_samples)` default. The producer must exclude missing acquisition +time and filler that does not contain usable recording data. If sorting spikes +remain in excluded intervals, reject the source with an actionable error. Do +not silently drop, move or relabel them: these actions change source row +identity or scientific interpretation. A future flagged-spike policy needs its +own full-data counting, selection and replay contract. + +The upper bound must include the producer's final representable event tick. +An endpoint mapping may describe the last sample rather than an exclusive end; +do not blindly substitute its rounded clock span for `num_samples`. A physical +pipeline frame count can be retained as separately named producer provenance, +for example `recording.num_frames`, but cannot also define the elapsed extent. +`--duration` remains a consistency check and does not override conflicting +producer metadata. + +Reject a first or last source spike outside the declared extent before a full +validation/hash scan. Still perform the complete batched validation for internal +reversals, out-of-range rows and invalid exposure membership. The early check +is a diagnostic improvement, not a replacement for validation. + +## Waveform and window sidecars + +In explicit elapsed mode, the waveform manifest must declare the coordinates of +each present time-bearing sidecar: + +```json +{ + "format": "phy_spikes_subset", + "format_version": 1, + "recording": { + "sampling_frequency_hz": 30000.0, + "num_samples": 12188787510, + "time_base": {"kind": "elapsed_ticks", "ticks_per_second": 30000.0}, + "window_bounds_coordinates": "elapsed_ticks", + "sample_index_coordinates": "elapsed_ticks" + } +} +``` + +The example omits `valid_intervals`; a real elapsed export must declare the +authoritative intervals in `params.py` or `recording`, with agreement when both +declare them. `window_bounds_coordinates` is required when window bounds are +present; `sample_index_coordinates` is required when sample indices are +present. Their values equal `time_base.kind`. A contradictory +`recording.frame_coordinates` declaration is an error, not an invitation to +reinterpret an array. Existing producer prose describing frames before +clock conversion must be corrected explicitly for an elapsed export. + +The sidecars have these meanings and validation obligations: + +- `_phy_spikes_subset.window_bounds.npy`: `int64[W, 2]` event-coordinate + `[start, end)` intervals, ordered by start, within the declared extent and + valid exposure. Overlapping windows are unioned without double counting; + acquisition block boundaries remain distinct. A window cannot bridge an + unsupported interruption. +- Optional `_phy_spikes_subset.window_types.npy`: integer `[W]`, conventionally + `uint8`, with `0` survey and `1` rescue; absent types default to survey. +- Optional `_phy_spikes_subset.window_strata.npy`: integer `[W]`, conventionally + `int32`, nonnegative survey stratum IDs and `-1` for rescue. Supplied arrays + align with the window bounds; absent strata receive deterministic defaults. +- Optional `_phy_spikes_subset.sample_index.npy`: integer `[N_waveforms]`, aligned + with waveform rows, containing canonical event-center coordinates. For every + waveform row `w`, it equals + `spike_times[subset_spikes[w]]`. It is not a source spike row ID or a raw-file + sample offset. + +The established waveform triplet remains authoritative for actual waveform +availability. A window denotes potential evidence, not a waveform for every +spike in it. When sidecars are supplied as producer evidence, waveform centers +must lie in the declared window union. Reject malformed sidecars rather than +falling back to an independently generated plan that hides the error. + +The existing row spaces remain unchanged: full spike row `g`, bounded spike row +`b`, waveform row `w`. Remap waveform row IDs through the selected full-to-bounded +mapping, and gather sample-index, waveform and channel rows together. Replay +preserves the original full arrays byte for byte. Supporting a sample-index +sidecar that intentionally remains in pipeline-frame coordinates is a separate +future provenance extension; this implementation does not infer its mapping. + +Preparation should prefer validated producer evidence windows while keeping +whole windows, the configured spike/byte budgets, and deterministic omission +reporting. Do not enlarge memory or disk budgets merely because many waveforms +were exported. Report the source, retained and omitted waveform counts so a +small bounded package cannot appear to preserve the complete reservoir. + +## Raw voltage access + +Elapsed event ticks must never flow into raw voltage indexing. This first +extension rejects an elapsed source with a real raw-data path until a separate +explicit event-to-raw-frame mapping and its validation exist. Absent raw paths, +including an export's literal `None` sentinel, must be recognized consistently. +The bounded package continues to use stored waveforms without raw data. + +Do not replace raw indices with elapsed ticks in an exporter and then claim +ordinary raw-trace loading works. Converting waveform centers for this contract +does not convert the physical voltage stream or establish a reversible map. + +## Identity, replay and metadata preservation + +Explicit time-base metadata participates in coordinate identity alongside the +canonical extent, exposure, immutable arrays, channel geometry and existing +acquisition provenance. Changing the coordinate kind, tick frequency or +exposure must invalidate a bounded package prepared against different metadata. +Keep the legacy identity shape unchanged for sources without a declaration. + +Carry explicit metadata into bounded `params.py` and the bounded manifest. +Validate it when reopening and replaying, rather than trusting a free-form field +that is never consumed. Preserve it in complete replay outputs and their +lineage. Repreparing a replay output must produce the same coordinate identity. +Assignment revisions remain distinct from that identity. Coordinate changes +cannot be repaired by retaining a journal against an obsolete source identity. + +Optional upstream sampling-policy windows do not by themselves change immutable +spike identity, but their validation and package hashes must bind the exact +evidence that the GUI uses. A waveform-aligned sample-index array does carry +immutable row provenance and must be included in the corresponding hashes and +copy/gather paths. + +## Why Phy does not convert the supplied timestamps JSON + +The supplied file contains 420 frame/clock endpoints for 210 pieces. Frame +endpoints increase strictly; clock endpoints are nondecreasing with 15 equal +adjacent pairs. Its metadata additionally reports underlying backward timestamp +steps that are not represented by those endpoint pairs. Consequently, the +endpoint map does not establish an invertible or sample-accurate raw clock. + +Interpolation can reproduce the reported exported spike ticks without proving +the exposure between endpoints. Piecewise dropped samples, filler and true +gaps need producer knowledge. Mapping just the endpoints of a window that +crosses a gap would incorrectly declare the gap observed. The reported +`total_dropped_within_pieces_s` also does not locate every unsupported interval. +Neither the apparent 30 kHz unit nor monotonic exported spikes makes elapsed +ticks equivalent to physical acquisition samples. + +The producer owns clock conversion and the final validity mask. Phy validates +the resulting explicit contract. Acquisition logs remain necessary to resolve +the reported interruptions and the 35 sorting spikes inside filler before +declaring this export suitable for exposure-aware statistics. + +## Regression and acceptance gates + +Before considering the extension complete, require concrete checks for: + +1. Unchanged legacy preparation, identity, summaries, GUI behavior and replay; + explicit acquisition-sample sources also round-trip. +2. Explicit elapsed data with tied spikes, long `int64` coordinates, gaps and + endpoint boundaries; exact independently calculated full counts and exposure. +3. Missing/conflicting time declarations, unsupported rates, raw paths, + contradictory frame metadata, and first/last out-of-bounds spikes; errors + identify the conflicting coordinate meanings before the expensive scan. +4. Spikes in filler/excluded exposure, internal reversals and invalid interval + boundaries; none are silently dropped or accepted as valid exposure. +5. Malformed producer sidecars, policy labels without bounds, invalid + dtypes/lengths, overlapping-window union without double counting, windows + crossing gaps, waveform centers outside windows, and sample-index values + inconsistent with their source spike rows. +6. Budget-constrained producer-window selection with exact retained/omitted + waveform reporting and deterministic complete-window selection. +7. Prepare, merge/label, save/reopen, replay and reprepare preserving explicit + metadata, immutable rows and waveform alignment. Mutating time metadata or + sample-index provenance must invalidate the appropriate identity/checksum. +8. Window-local ISI/CCG calculations excluding unsupported cross-boundary pairs, + physical waveform sample spacing, and no elapsed-coordinate raw indexing. + +These establish software behavior. They do not establish that endpoint-derived +exposure is scientifically precise or that the finite waveform evidence is +sufficient for chronic unit identity. Domain-curator acceptance remains required +by the existing validation plan. diff --git a/design/large-recording-validation.md b/design/large-recording-validation.md new file mode 100644 index 000000000..afcee5825 --- /dev/null +++ b/design/large-recording-validation.md @@ -0,0 +1,114 @@ +# Long-recording implementation validation + +This record summarizes the current implementation checks and their limits. The +results validate the measured code paths and fixtures described here. They do +not establish capacity for every source layout or scientific suitability for +chronic curation. + +## Automated checks + +After the real-data split-journal fix described in the +[AIND diagnostic record](aind-real-data-validation.md), `make test-full` passed +**821 tests with 1 existing benchmark skip** (496 core and 325 application +tests). Lint, formatting, documentation checks, and package build passed. + +On 2026-10-24, the AIND time-coordinate follow-up passed `make test-full`: +**818 passed, 1 existing benchmark skip** (496 core tests and 322 application +tests). The environment used Python 3.12.3, released phylib 2.7.1, Linux, +Xvfb, software OpenGL, and Qt's offscreen platform. The target included lint +and formatting checks. The strict documentation check and `uv build` also +passed; the wheel contains all 12 long-recording runtime modules. + +The follow-up has a 96-test focused source/preparation/replay run and an +additional GUI regression for explicit elapsed clocks. Its independent +discontinuous-clock oracle verifies per-bin exposure and unit counts, exact +waveform sample-index alignment, merge assignments, save/reopen, replay, +repreparation, timestamp provenance, and unchanged source bytes. The GUI test +opens all default bounded views, checks exposure-based firing rate and window +navigation, and confirms that elapsed ticks do not enable raw traces. All of +these tests are included in the full-suite result above. + +Separate architecture, correctness, and final audit reviews used Sol at high +reasoning effort. The correctness review found a legacy coordinate-name +mismatch and a generated-policy bypass of producer waveform-window membership +validation; both received regression coverage and were corrected. The final +independent audit found no remaining blocking defect in the reviewed changes. + +These results validate the [explicit coordinate contract](large-recording-time-coordinates.md), +not the supplied export's acquisition truth. During that initial follow-up the +complete export and its acquisition logs were unavailable; its spike-array and +filler-spike claims were attributed to Carl's report. A different computation +was subsequently downloaded and tested as an explicitly modified engineering +derivative, as recorded in the AIND diagnostic above. No exporter repository +was identified or modified. The +[exporter handoff](aind-export-handoff.md) records the upstream work and real-data +acceptance evidence still needed. + +On 2026-10-13, `make test-full` completed with **756 passed and 1 +skipped** (496 non-application tests and 260 application tests). Final channel +geometry and nonidentity waveform-mapping additions passed a further focused +source/preparation run of **33 tests**. Lint, format checking, package build, +and the strict documentation build also passed. The dedicated bounded GUI lifecycle file passed all three +regressions: reentrant observer rollback with the GUI attached, merge-proposal +review through undo/redo/save/reopen, and pending full metrics for threshold +children in the default bounded views. + +The reference long-recording fixture is deliberately sparse: 32 spikes spread +over a 1000-hour sample clock. It checks long `int64` coordinates, tied times, +source-row mapping, waveform remapping, and loader compatibility. It is not a +billion-spike capacity test, a realistic chronic recording, or evidence of +biological identity across a recording. + +## Synthetic preparation and replay runs + +The reproducible benchmark is `uv run python +tools/benchmark_long_recording.py`. It writes synthetic source arrays in +batches, with no raw voltage data, and runs preparation and replay in separate +processes. Both runs below used Python 3.13.3, NumPy 2.4.3, Linux +`x86_64`/glibc 2.39, 30 kHz sampling, 1000 units, a 1000-hour sample axis, +100,000-row batches, 30-second windows, 3600-second strata, a 100,000-spike +budget, a 512 MiB output budget, seed 0, and 3600-second summary bins. The +oracle independently streamed every source and output assignment row and +matched the expected merge in both cases. + +| Synthetic source spikes | Source files | Bounded package | Bounded spikes | Curated output | Prepare time / peak RSS | Replay time / peak RSS | Oracle rows | +| ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| 250,000 | 4,032,892 B | 8,625,460 B | 2,389 | 5,038,086 B | 1.902 s / 215,773,184 B | 0.114 s / 214,847,488 B | 250,000 | +| 2,000,000 | 32,032,892 B | 9,157,120 B | 16,676 | 40,038,086 B | 1.227 s / 214,433,792 B | 0.292 s / 215,285,760 B | 2,000,000 | + +Each measurement is a single run, not a throughput curve. Preparation and +replay durations exclude child-process startup; peak RSS is the process high +water mark. The source is a regular synthetic distribution with tiny templates +and no stored waveforms, raw data, irregular acquisition gaps, or real feature +loads. These figures therefore do not predict every preparation cost or GUI +interaction on a chronic dataset. The full JSON reports are retained at +`/tmp/phy-long-recording-benchmark-250k.json` and +`/tmp/phy-long-recording-benchmark-2m.json` on the validation workstation. + +## Ordinary-dataset smoke comparison + +A separate three-run comparison used fresh subprocesses, configs, and caches in +the same Python environment. It compared baseline `a30d5c65` with current +`f212f069e5b5b19469cfa73781dac08de093d9a1` on a 12,000-spike, two-cluster +dataset with 1,024 stored waveform rows of shape `[40, 4]` and dense template +features. Counts and output dimensions matched exactly. + +| Measure (median of 3) | Baseline | Current | +| --- | ---: | ---: | +| Controller startup | 0.03879 s | 0.02822 s | +| Waveform provider | 0.00353 s | 0.00293 s | +| Feature provider | 0.00372 s | 0.00302 s | + +This small case showed no regression; the apparent gains are within the range +where run-to-run noise matters. The comparison did not measure Qt rendering, +raw-voltage I/O, or large-dataset selection churn. Its report is retained at +`/tmp/phy-standard-recording-comparison.json` on the validation workstation. + +## Remaining acceptance work + +Real chronic-recording review by domain curators remains outstanding. It must +cover drift, rare and bursting units, artifacts, gaps, waveform coverage, +intentionally incorrect merges, withheld contiguous windows, and full-data +diagnostics where available. Software integrity checks and synthetic throughput +do not establish that the evidence is scientifically sufficient or that a +cluster represents one biological unit throughout 1000 hours. diff --git a/design/live-summary-result.json b/design/live-summary-result.json new file mode 100644 index 000000000..588c5176f --- /dev/null +++ b/design/live-summary-result.json @@ -0,0 +1,313 @@ +{ + "format": "phy_live_summary_capture", + "format_version": 1, + "capture_revision": "6a5c982404409488c7a18aaf90f6ccf94829a963", + "capture_tool_sha256": "5d421168d4a89035472be3919baf4609edb93934fcd05f2f8d36da6b711ddcf7", + "provenance": "Converted engineering validation; acquisition exposure unverified", + "dataset_label": "Carl earlier 112.859h converted engineering dataset; not 500h/native-export acceptance", + "acceptance_scope": "Existing converted engineering package; not new dataset acceptance", + "parent_unit": 49, + "control_units": [ + 50 + ], + "children": [ + 709, + 710 + ], + "threshold": -341.797119140625, + "split_event": { + "version": 2, + "operation": "threshold_split", + "parent": 49, + "children": [ + 710, + 709 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -341.797119140625, + "nonfinite": "keep" + }, + "metadata": { + "amplitude_cutoff": { + "710": null, + "709": null + }, + "si_unit_id": { + "710": null, + "709": null + }, + "sync_spike_2": { + "710": null, + "709": null + }, + "trough_half_width": { + "710": null, + "709": null + }, + "unitrefine_probability": { + "710": null, + "709": null + }, + "sliding_rp_violation": { + "710": null, + "709": null + }, + "isi_violations_count": { + "710": null, + "709": null + }, + "num_positive_peaks": { + "710": null, + "709": null + }, + "spread": { + "710": null, + "709": null + }, + "velocity_below": { + "710": null, + "709": null + }, + "peak_before_width": { + "710": null, + "709": null + }, + "num_negative_peaks": { + "710": null, + "709": null + }, + "trough_width": { + "710": null, + "709": null + }, + "peak_before_to_trough_ratio": { + "710": null, + "709": null + }, + "firing_range": { + "710": null, + "709": null + }, + "noise_cutoff": { + "710": null, + "709": null + }, + "peak_before_to_peak_after_ratio": { + "710": null, + "709": null + }, + "group": { + "710": null, + "709": null + }, + "presence_ratio": { + "710": null, + "709": null + }, + "sync_spike_8": { + "710": null, + "709": null + }, + "main_to_next_extremum_duration": { + "710": null, + "709": null + }, + "channel_group": { + "710": null, + "709": null + }, + "velocity_above": { + "710": null, + "709": null + }, + "amplitude_cv_median": { + "710": null, + "709": null + }, + "peak_after_to_trough_ratio": { + "710": null, + "709": null + }, + "waveform_baseline_flatness": { + "710": null, + "709": null + }, + "peak_to_trough_duration": { + "710": null, + "709": null + }, + "notes": { + "710": null, + "709": null + }, + "repolarization_slope": { + "710": null, + "709": null + }, + "recovery_slope": { + "710": null, + "709": null + }, + "snr": { + "710": null, + "709": null + }, + "isi_violations_ratio": { + "710": null, + "709": null + }, + "main_peak_to_trough_ratio": { + "710": null, + "709": null + }, + "peak_half_width": { + "710": null, + "709": null + }, + "unitrefine_label": { + "710": null, + "709": null + }, + "peak_after_width": { + "710": null, + "709": null + }, + "default_qc": { + "710": null, + "709": null + }, + "bombcell_label": { + "710": null, + "709": null + }, + "rp_violations": { + "710": null, + "709": null + }, + "exp_decay": { + "710": null, + "709": null + }, + "amplitude_cv_range": { + "710": null, + "709": null + }, + "rp_contamination": { + "710": null, + "709": null + }, + "amplitude_median": { + "710": null, + "709": null + }, + "sd_ratio": { + "710": null, + "709": null + }, + "sync_spike_4": { + "710": null, + "709": null + }, + "noise_ratio": { + "710": null, + "709": null + } + } + }, + "events_sha256": "02cd4722ed1c340f39f237ef32935e0016394fad6fcf880cfe47b0f52b7d901a", + "initial_event_count": 11, + "final_event_count": 12, + "native_bins": 113, + "source_spikes": 469725567, + "retained_spikes": 1486361, + "full_counts": { + "709": 292990, + "710": 346764, + "50": 541925 + }, + "timing_seconds": { + "bounded_split": 0.5794001140166074, + "resume_to_worker_launch_notification": 0.4424441419541836, + "first_job_validation_scan_and_gui_delivery": 8.331006723921746, + "worker_notification_to_exact_results": 7.888562581967562, + "resume_to_exact_results": 8.331006723921746, + "completed_cached_summary_lookup": 0.0006028888747096062 + }, + "timing_context": "Preflight SHA256 warms filesystem cache; not cold-storage latency", + "source_required_bytes": 9394511724, + "source_array_inventory": { + "amplitudes.npy": { + "bytes": 1878902268, + "dtype": "float32", + "role": "per_spike", + "shape": [ + 469725567, + 1 + ] + }, + "spike_clusters.npy": { + "bytes": 3757804536, + "dtype": "int64", + "role": "per_spike", + "shape": [ + 469725567, + 1 + ] + }, + "spike_times.npy": { + "bytes": 3757804536, + "dtype": "int64", + "role": "per_spike", + "shape": [ + 469725567, + 1 + ] + } + }, + "source_sha256_before": { + "amplitudes.npy": "086bf254d385b72c23fa3ecb8918d078741a1cec1d3685be12ca04b7286a77b0", + "spike_clusters.npy": "28c21c56f9e36bf97ae1faa279af439fa49874f34361dd43da345bf0cf8b08fb", + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c" + }, + "source_sha256_after": { + "amplitudes.npy": "086bf254d385b72c23fa3ecb8918d078741a1cec1d3685be12ca04b7286a77b0", + "spike_clusters.npy": "28c21c56f9e36bf97ae1faa279af439fa49874f34361dd43da345bf0cf8b08fb", + "spike_times.npy": "fedfe8732bebf59a7446a14a3979fbacd322707b66a3506b07bbe0b3837b042c" + }, + "inputs_unchanged": true, + "oracle": { + "all_source_rows_checked": 469725567, + "batch_size": 100000, + "verified_unit_ids": [ + 709, + 710, + 50 + ], + "counts_comparison": "exact int64", + "finite_counts_comparison": "exact int64", + "finite_sums_comparison": { + "dtype": "float64", + "rtol": 1e-09, + "atol": 1e-06 + }, + "seconds": 4.137655219994485 + }, + "rate_only": true, + "recomputing_capture_pending_at_entry": true, + "recomputing_capture_pending_at_exit": true, + "screenshots": [ + "before-split.png", + "recomputing.png", + "after-split.png" + ], + "gui_size": [ + 2200, + 1250 + ], + "source_identity_sha256": "103621da4c00da1cdbbeb4234717800fa7f43294148aeeebd2b6561456dc5f8b", + "source_revision": "ff45d8502cc2cbb916a8754885ba4c9158490191f1a097bc02b0deaf354549ea", + "input_package_file_count": 99, + "input_package_files_unchanged": true +} diff --git a/design/merge-propositions.md b/design/merge-propositions.md index 68b63d0e4..f4466861c 100644 --- a/design/merge-propositions.md +++ b/design/merge-propositions.md @@ -218,7 +218,7 @@ support is deferred. duplicate entries, missing IDs, and mixed valid/invalid merges. - Stable proposition keys and source-file change detection. - Exact Normal-state cancellation after starting a review. -- Ordered staging with the first ID fixed as blue reference. +- Ordered staging with the initial first ID retained as blue reference after row reordering. - Invalid and stale propositions cannot enter Merge mode. - Failed merge preserves review state and the complete workspace. - Successful and modified acceptance record exact applied and result IDs. diff --git a/design/merge-view-architecture.md b/design/merge-view-architecture.md index 80ce216cf..454166a8e 100644 --- a/design/merge-view-architecture.md +++ b/design/merge-view-architecture.md @@ -216,10 +216,11 @@ class MergeSession: proposition_id: str | None = None ``` -`ordered_ids[0]` is always `reference_id`. The reference cannot be reordered -within Merge View, but transferring it to Similarity promotes the next staged -ID. Reordering later candidates changes `ordered_ids` but not -`presentation_order`. +`reference_id` belongs to `ordered_ids` but need not occupy its first position. +All staged rows can be reordered; Merge presentation follows that row order, +while reference identity and palette bindings remain stable. Transferring the +reference to Similarity promotes the first remaining staged ID. Removing another +row retains the existing reference. The entry snapshot contains the user state required by the workflow contract, not arbitrary application state. It includes selections, reference, diff --git a/design/merge-view-workflow.md b/design/merge-view-workflow.md index 0f9475bb4..10d81bcde 100644 --- a/design/merge-view-workflow.md +++ b/design/merge-view-workflow.md @@ -26,7 +26,9 @@ The GUI has two mutually exclusive modes: followed by the other selected Cluster View rows and selected Similarity View rows in their visible table order. - **Merge mode:** the effective selection is the union of every cluster in Merge - View and the Similarity View selection. Cluster View is disabled. + View and the Similarity View selection. Presentation follows staged row order, + then selected Similarity rows. The blue reference can occupy any staged row. + Cluster View is disabled. The effective selection is what graphical and scientific views display. It is also what `G` merges. Transferring a cluster between Similarity View and Merge @@ -73,9 +75,9 @@ remain in Merge View. Merge View is tied to one blue reference cluster: -- it is always the first row; +- it initially occupies the first row and may be dragged to any staged row; - it remains the reference used to calculate Similarity; -- it cannot be reordered within Merge View; +- changing its row position preserves its identity and blue palette slot; - it can be transferred to Similarity when another staged cluster remains; and - the current reference always owns the blue palette slot. @@ -100,8 +102,8 @@ removing that cluster from Merge View. - Right-click on a Similarity row transfers that cluster to Merge View. - Drag-and-drop between Similarity View and Merge View provides the equivalent transfer operation. -- Dragging within Merge View reorders candidates, except for the fixed blue - reference. +- Dragging within Merge View reorders any staged row, including the blue + reference, without changing reference identity. - New candidates are appended after the candidates already in Merge View unless they are dropped at an explicit insertion point. - Duplicate membership is not possible; adding an existing member is a no-op. @@ -144,6 +146,8 @@ Similarity View remains the live candidate area during Merge mode: - Ctrl+Space keeps its existing behavior and selects the next configured number of eligible Similarity candidates. +- Ctrl+Shift+Space selects up to N eligible rows before the first selected eligible + row, in current visible order, or from the end with no eligible selection. - Ctrl+click manages its multi-row selection. - Backspace clears only the Similarity View selection; it does not alter Merge View. diff --git a/design/parent-review-implementation.md b/design/parent-review-implementation.md new file mode 100644 index 000000000..3aac46142 --- /dev/null +++ b/design/parent-review-implementation.md @@ -0,0 +1,114 @@ +# Exact parent restoration and inspection + +The curation workflow offers **Restore parents in Merge Mode** for a live unit +with exact recorded immediate ancestry. **Inspect parents (read-only)** remains +a separate operation. Restoration changes real assignments; inspection creates +isolated providers and changes no curation state. + +## Restoration and workspace history + +`Clustering.restore_partition()` validates a complete, disjoint, nonempty +partition of the live target and allocates fresh cluster IDs. It uses cached +target rows and native assignment/history events, avoiding a recording-wide +search for affected spikes. Historical IDs are provenance, never resurrected +live identities. Merge rows show a **Parent** column beside the current ID. + +`Supervisor.restore_parents()` appends one new global-history action, with a +rollback snapshot limited to affected assignment rows plus metadata/history and +workflow state. It does not remove an earlier history entry or rewind later +work. New memberships clear metadata rather than inherit the merged unit's +quality. Native undo-state metadata snapshots also preserve exact parent values +when a later remerge is undone. + +The post-restoration Merge session contains actual live units. Its entry snapshot +is a Normal selection of the fresh parents; the history before-snapshot describes +the old merged target. Consequently V/cancel leaves the restored units intact, +Undo restores the merged unit without reversing earlier unrelated edits, and +Redo restores the parent workspace. Existing Merge operations remain available; +Normal-mode split/quality/label tools remain accessed through V. + +**Exclude current row** acts on the native Merge table's current row and removes +that ID from the effective merge selection. It is intentionally distinct from +right-click transfer: transferred Similarity units remain selected and are still +included by G. Tests exercise actual row/button clicks and unchanged transfer +semantics. + +## Ordinary ancestry and durability + +`ParentLineage` retains exact immutable per-parent spike memberships captured at +merge time. `_phy_merge_parents.npz` is atomic, non-pickle and bound to saved +assignments, spike times and templates. Save retains ancestry reachable from live +units and origin aliases, including retired intermediate composite parents. +Fresh restored children can therefore refer back to their historical merge and +restore another level after save/reopen. Unreachable ancestry can be discarded. + +Optional color records preserve pre-merge palette slots; unavailable historical +colors use a deterministic fallback. The origin map and restoration retirement +projection survive reopen. SLAY acceptance decisions retain their historical +result IDs; an accepted result subsequently restored is shown as such instead +of appearing to be a current accepted merge or becoming pending automatically. + +Legacy merges without recorded exact membership are unavailable. Split +descendants are not silently treated as their former merged ancestor. Every +partition is checked against the current unit before mutation; original +sorting templates are never used to guess a missing partition. + +## Bounded journal and full-source replay + +Bounded restoration appends a source- and prefix-bound version-3 +`restore_parents` event. It references an earlier merge in the same preparation, +its currently active equivalent target, ordered fresh child IDs, and explicit +metadata clearing. Referenced membership is reconstructed immediately before +that merge, including any earlier source-amplitude predicate expressions. +Nested restored composite children retain equivalent-membership origin links. + +The native change, semantic event, metadata, review projection, selection and +history participate in one rollback transaction. A source parent with no retained +evidence cannot currently be represented as an editable native unit, so GUI +restoration rejects it before mutation rather than silently omit it. Legacy +merge-capable packages can use the command; explicit capability denial is +honored. Older bounded consumers reject the new event version/capability. + +Replay uses explicit event dispatch instead of sending restoration journals down +the merge-only mapping shortcut. Existing source/union/split expression trees +represent restored memberships and continue to drive live summaries, indexes +and source-unit resolution. Historical predicate projection uses adaptive +sub-batches with a bounded mask allowance, not parent-count times the complete +recording. The independent output contract reconstructs pre-merge masks in +bounded chunks and verifies metadata clearing separately from the runtime. + +Save/reopen in the same package preserves ancestry. Replay exports restored live +units, metadata, reviews and retirement provenance for further preparation. +A fresh preparation starts from its new source assignments and does not retain +recoverable membership anchors for pre-preparation historical merges; those +merges remain unavailable. No claim of arbitrary cross-round historical +restoration or arbitrary sampled lasso replay is made. + +## Read-only inspection + +Inspection uses an embedded dark Qt workspace containing a QTableWidget parent +catalog and separate native correlogram, waveform, amplitude and feature views. +Providers operate only on the exact requested parent memberships, respecting +per-view sample budgets. Bounded correlograms describe retained contiguous +windows and have no full-recording rate baseline. Missing stored/raw waveforms +can use explicitly labelled, capped template traces without changing membership. + +The workspace snapshots and restores dock layout, visibility, actions and focus; +Back/Esc and a new selection dispose it without pumping queued curation events. +Main-window close restores the original layout before geometry saving. Inspection +supports at most 16 immediate parents; that display limit never truncates actual +restoration. Curation actions and inherited editing shortcuts are blocked during +inspection, and its view handlers do not publish global editing/transfer events. + +## Validation + +Focused regressions cover later unrelated edits, exact fresh-ID assignments, +metadata clearing and undo preservation, nested ancestry, invalid partitions, +rollback failures, real exclusion gestures, save/reopen, immediate review status, +bounded earlier predicate parents, zero-evidence rejection, replay dispatch, +summary expression equivalence, scratch limits and unsupported old consumers. + +Rendered copied-data walkthroughs and independent full-source replay evidence +are recorded in `carl-feedback-captures/README.md`. These are engineering checks +of the supplied converted fixture, not validation of its acquisition clock, +exposure assumptions or biological merge quality. diff --git a/design/rp-acceleration-benchmark-2026-11-24.json b/design/rp-acceleration-benchmark-2026-11-24.json new file mode 100644 index 000000000..8f99fb2e8 --- /dev/null +++ b/design/rp-acceleration-benchmark-2026-11-24.json @@ -0,0 +1,496 @@ +{ + "platform": "Linux-7.0.0-43-generic-x86_64-with-glibc2.39", + "python": "3.12.3", + "branch_base": "02c8b6f79a1142e96d1c72730caf06e229bf8a4a", + "files_sha256": { + "phy/apps/__init__.py": "d3f400172ef22670b4d5c29268e766985e22ef897cdafeb883cf44efad916be0", + "phy/apps/large_recording/prepare.py": "c4ceca4472a2f242877ea419183f44cab3f9896c9fe5ff12d93e898c0971b5e0", + "phy/apps/large_recording/range_build.py": "d705ad8ae286e03bd1b72e25a992c8120ecf33511da57bb6539ed9aaca32b3af", + "phy/apps/large_recording/refractory_engine.py": "8ff3e4e7abdb9c065ea7b948c3e9badb90a79a03c9741ed6b8ea6b7fd2d8d27d", + "phy/apps/large_recording/refractory_store.py": "05f639748dc7cdd9a8fa6421576cd55d77f966f4dd7fb3dcf7745462ab96f3d6", + "phy/apps/large_recording/summary_store.py": "c037167c6717c4165ce2b95ec37e2424bf6aedc9dc18a9936d5f718c5793bf1d", + "phy/apps/large_recording/tests/test_refractory_store.py": "49dee93847b201504370e75a65cb9762b1bd80a7befe7935189098f78d50397a", + "tools/benchmark_refractory.py": "7b1adeb8ea9c1ee06c778f00892366c889e21fa0087d7a2b223d1b2f8db00937" + }, + "workload": { + "spikes": 80000000, + "hours": 1000, + "sample_rate": 30000, + "units": { + "0": 60000000, + "1": 16000000, + "2": 2000000, + "99": 2000000 + }, + "time_step_samples": 1350, + "amplitudes": "float32, (row % 17 - 8) / 8", + "native_bin_seconds": 3600, + "scientific_bin_seconds": 1800, + "note": "Regular sparse synthetic data; no refractory violations or duplicates. Scientific edge cases are covered by independent small-oracle tests. OS caches uncontrolled; fresh-process does not mean cold disk." + }, + "scratch_path": "/tmp/phy-rp-benchmark-3kw_eht_", + "equality": "All result fingerprints equal authenticated source results. Prepared requests assert no source access.", + "runs": { + "source": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 6.430178848007927, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.00027263200900051743, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 6.603425208988483, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0002733810106292367, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 3.5590111460041953, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.0002777219924610108, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + } + ], + "seconds": 16.601740051002707, + "peak_rss_bytes": 1534197760, + "source_hash_bytes": 1280000384 + }, + "build-counters": { + "mode": "build-counters", + "os_cache": "uncontrolled", + "queries": [], + "seconds": 7.768697706007515, + "peak_rss_bytes": 1500672000, + "source_hash_bytes": 1280000384, + "artifact_bytes": 131807 + }, + "counters": { + "mode": "counters", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 0.0022168299910845235, + "path": "prepared RP counters", + "timestamp_bytes": 0, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.0016935289895627648, + "path": "prepared RP counters", + "timestamp_bytes": 0, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + } + ], + "seconds": 0.005239876001724042, + "peak_rss_bytes": 213725184, + "source_hash_bytes": 0 + }, + "build-timestamps": { + "mode": "build-timestamps", + "os_cache": "uncontrolled", + "queries": [], + "seconds": 5.788922972002183, + "peak_rss_bytes": 238858240, + "source_hash_bytes": 1280000384, + "artifact_bytes": 800015653 + }, + "timestamps": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 5.79833563399734, + "path": "prepared timestamp rows", + "timestamp_bytes": 600000000, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.0010057710023829713, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "b010c075289a9ac5eea98f71f08bd4457e2205e465651c27f752f1fd4474289b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 6.973513268996612, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009801179985515773, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 4.3267333219992, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.0010096619953401387, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + } + ], + "cancel_seconds": 2.61410023085773e-05, + "cancelled_request_seconds": 0.014258233000873588, + "seconds": 17.117750134988455, + "peak_rss_bytes": 240033792, + "source_hash_bytes": 0 + }, + "source-subset": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 1.2411384690058185, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "8253fdc62498a0eb8d45e0aee6367e9903758e00a97203df1ee2707ad6e0ef52", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.00026186199102085084, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "8253fdc62498a0eb8d45e0aee6367e9903758e00a97203df1ee2707ad6e0ef52", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 0.4229724479955621, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "b23bca6ccba1ce91f3afc347ff5cf1264861b5d2713b0d683d0a225ccb9804a0", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.00025977499899454415, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "b23bca6ccba1ce91f3afc347ff5cf1264861b5d2713b0d683d0a225ccb9804a0", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 0.3819475509953918, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "2741cc575b00142071cf853b8a3261aa8c9d46ed8bb9b654b2b8b0d9321410f3", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.00027419699472375214, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "2741cc575b00142071cf853b8a3261aa8c9d46ed8bb9b654b2b8b0d9321410f3", + "status": "ready" + } + ], + "seconds": 2.055210004997207, + "peak_rss_bytes": 1500348416, + "source_hash_bytes": 1280000384 + }, + "timestamps-subset": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 0.2166328150051413, + "path": "prepared timestamp rows", + "timestamp_bytes": 20000000, + "fingerprint": "8253fdc62498a0eb8d45e0aee6367e9903758e00a97203df1ee2707ad6e0ef52", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.0010211139888269827, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "8253fdc62498a0eb8d45e0aee6367e9903758e00a97203df1ee2707ad6e0ef52", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 0.5103752789873397, + "path": "prepared timestamp rows", + "timestamp_bytes": 40000000, + "fingerprint": "b23bca6ccba1ce91f3afc347ff5cf1264861b5d2713b0d683d0a225ccb9804a0", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009634180023567751, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "b23bca6ccba1ce91f3afc347ff5cf1264861b5d2713b0d683d0a225ccb9804a0", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 0.31758163300401065, + "path": "prepared timestamp rows", + "timestamp_bytes": 40000000, + "fingerprint": "2741cc575b00142071cf853b8a3261aa8c9d46ed8bb9b654b2b8b0d9321410f3", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.0009965880017261952, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "2741cc575b00142071cf853b8a3261aa8c9d46ed8bb9b654b2b8b0d9321410f3", + "status": "ready" + } + ], + "cancel_seconds": 3.5061006201431155e-05, + "cancelled_request_seconds": 0.01858464500401169, + "seconds": 1.0679998959967634, + "peak_rss_bytes": 237936640, + "source_hash_bytes": 0 + }, + "source-fresh-merge": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 7.70867867799825, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.00027633800345938653, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + } + ], + "seconds": 7.717049372004112, + "peak_rss_bytes": 1526644736, + "source_hash_bytes": 1280000384 + }, + "timestamps-fresh-merge": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 7.219127032003598, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009931209933711216, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + } + ], + "cancel_seconds": 2.7115005650557578e-05, + "cancelled_request_seconds": 0.015303506996133365, + "seconds": 7.237172989989631, + "peak_rss_bytes": 232169472, + "source_hash_bytes": 0 + }, + "source-fresh-amplitude-child": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 4.657482080991031, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.00027188099920749664, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + } + ], + "seconds": 4.665822479000781, + "peak_rss_bytes": 1514872832, + "source_hash_bytes": 1280000384 + }, + "timestamps-fresh-amplitude-child": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 4.340520915997331, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.0010021670022979379, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "8852d570bc73a6dc3cbef5b456c5d2368939fcf28f8e7850a7cd16059e5a8ef7", + "status": "ready" + } + ], + "cancel_seconds": 2.3069995222613215e-05, + "cancelled_request_seconds": 0.01461819298856426, + "seconds": 4.357806073006941, + "peak_rss_bytes": 230412288, + "source_hash_bytes": 0 + } + }, + "additional_validated_files_sha256": { + "phy/apps/large_recording/summary_tasks.py": "433e0cf07edb01603c2ca842a7e8eab48a81215fcee8a7e314868155c8433ecd", + "phy/apps/large_recording/tests/test_summary_tasks.py": "34d6e48ad79522cad4084bd191bb2642fde63c0de3d693ecc7d9a73a7e7ac83c" + }, + "validation": { + "full_suite": { + "passed": 1826, + "skipped": 19, + "command": "xvfb-run -a -s '-screen 0 1400x900x24 -ac +extension GLX +render' env QT_QPA_PLATFORM=offscreen make test-full UV_RUN='uv run --no-sync'", + "log": "/tmp/phy-rp-full-final.log", + "includes": [ + "lint", + "format-check", + "non-application tests", + "application tests" + ] + }, + "focused": { + "passed": 28, + "log": "/tmp/phy-rp-final-focused.log" + }, + "docs": { + "command": "make doc-check UV_RUN='uv run --no-sync'", + "result": "passed", + "log": "/tmp/phy-rp-doc.log", + "comparison": "Temporary Git index held intended documentation edits; generation left them unchanged. Real index untouched." + }, + "build": { + "command": "uv build", + "result": "passed", + "log": "/tmp/phy-rp-build.log" + }, + "reference": "Verified against existing exact source path and independent small pairwise-oracle tests. No local phytastic checkout was available; no direct external-reference parity claim.", + "gui_regression": "Attached timestamp stores include exact row width in amplitude-index budget estimates. Regression reproduced before fix and passes in the final full suite." + }, + "dependency_versions": { + "numpy": "2.4.3", + "phylib": "2.7.1", + "PyQt5": "5.15.11", + "PyQt5-sip": "12.20.1", + "pytest": "9.1.1" + }, + "interpretation": [ + "Fresh-process source merge and amplitude-child runs include authentication. Default all-membership source runs authenticate once, then reuse that reader.", + "Timestamp query bytes equal selected ancestor rows: 600 MB for 60 million rows, 760 MB for 76 million rows, 20/40 MB for the small subset. Prepared paths assert no original-source access.", + "Peak RSS includes interpreter/import baseline and mapped source pages; it is not a measurement of heap scratch alone.", + "Timings are local synthetic measurements with uncontrolled OS caches. Sparse regular spikes exercise scale; scientific duplicate, pair, gap and history edge cases are tested separately." + ] +} diff --git a/design/rp-carl-requirements-validation-2026-11-25.json b/design/rp-carl-requirements-validation-2026-11-25.json new file mode 100644 index 000000000..8fd9bbdc4 --- /dev/null +++ b/design/rp-carl-requirements-validation-2026-11-25.json @@ -0,0 +1,332 @@ +{ + "ground_truth": { + "path": "/home/cyrille/T\u00e9l\u00e9chargements/Speeding_up_the_RP_panel_on_long_recordings.pdf", + "sha256": "494f10008867355bdf78830b98d42f5dfddcfbef095d5415a52942a03008b234", + "title": "Speeding up the RP panel on long recordings", + "author": "Carl", + "date": "2026-11-24" + }, + "requirements": [ + { + "page": 2, + "request": "Optional prepare-large original-unit deduplicated counts and violations on 30-minute scientific bins", + "implementation": [ + "phy/apps/large_recording/refractory_store.py:build_refractory_summaries", + "phy/apps/large_recording/prepare.py:prepare_large", + "phy/apps/__init__.py:--rp-summaries" + ], + "assessment": "Implemented; authenticated per-original grids, complete duplicate components across batches, recorded exposure retained." + }, + { + "page": 2, + "request": "Exact timestamps alongside amplitudes; read only parents for merges and amplitude splits", + "implementation": [ + "phy/apps/large_recording/summary_store.py:_layout", + "phy/apps/large_recording/refractory_store.py:_chronological", + "phy/apps/large_recording/refractory_store.py:resolve_prepared" + ], + "assessment": "Implemented; offsets relative to native store bins reconstruct exact integer ticks; dtype adapts to bin width and preserves amplitude precision. Storage differs from illustrative +4-byte layout when a narrower exact offset suffices." + }, + { + "page": 2, + "request": "Optional features, source fallback for old packages, bounded folder plus store usable without phy/", + "implementation": [ + "phy/apps/large_recording/refractory_engine.py:resolve", + "phy/apps/large_recording/tests/test_refractory_store.py" + ], + "assessment": "Implemented for originals, unions and supported amplitude predicates; unsupported histories retain source fallback. Offline evidence is explicitly tied to prepared snapshot." + } + ], + "acceptance_limits": [ + "This document asks to avoid whole-source scans; it does not specify a 10x speed target. The user separately requested at least 10x.", + "Real export is 469725567 spikes across 705 roots and 99.436744 recorded hours / 112.859144 elapsed hours, not Carl's 1000-hour shanks.", + "No general 10x novel-merge speedup has been established. Compare source steady-state scans separately from first-use source authentication.", + "OS page-cache state uncontrolled; tests and artifact construction may run concurrently with measurements, so timings are indicative rather than isolated hardware benchmarks.", + "No custom binary extension or new project dependency introduced; no publication." + ], + "real_export": { + "source": "/home/cyrille/GIT/IBL/phy-data/carl/aind-b1b0782a-b3ea-4f34-81d7-b3c6e36452b3/phy/experiment1_AmplifierData_recording1_group0", + "original_preparation": "/home/cyrille/GIT/IBL/phy-data/carl/feedback-validation-2026-11-17/pipeline/prepared-1", + "spikes": 469725567, + "units": 705, + "selected_units": [ + 550, + 575 + ], + "selected_counts": [ + 6049498, + 5464447 + ], + "elapsed_hours": 112.85914361111112, + "recorded_hours": 99.43674400925926, + "store_build_seconds": 73.53931737299717, + "store_bytes": 4227624543 + }, + "measurements": { + "source": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 14.725798075000057, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.0012057490093866363, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 2.16931946000841, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0012005879980279133, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 2.021045839996077, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "4f9d6ed178cfa3be4a1adcca49efee7cd4570e1f89d5ead6d075370203f3cba4", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.0012057290005031973, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "4f9d6ed178cfa3be4a1adcca49efee7cd4570e1f89d5ead6d075370203f3cba4", + "status": "ready" + } + ], + "seconds": 18.97732564699254, + "peak_rss_bytes": 9623576576, + "source_hash_bytes": 9394511724 + }, + "timestamps": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 0.26277301499794703, + "path": "prepared timestamp rows", + "timestamp_bytes": 54445482, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.0037837540003238246, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 0, + "seconds": 0.7879041740088724, + "path": "prepared timestamp rows", + "timestamp_bytes": 103625505, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0036645429936470464, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 0, + "seconds": 0.3684799030015711, + "path": "prepared timestamp rows", + "timestamp_bytes": 103625505, + "fingerprint": "4f9d6ed178cfa3be4a1adcca49efee7cd4570e1f89d5ead6d075370203f3cba4", + "status": "ready" + }, + { + "membership": "amplitude-child", + "repeat": 1, + "seconds": 0.003778084006626159, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "4f9d6ed178cfa3be4a1adcca49efee7cd4570e1f89d5ead6d075370203f3cba4", + "status": "ready" + } + ], + "cancel_seconds": 2.1450003259815276e-05, + "cancelled_request_seconds": 0.013284906002809294, + "seconds": 1.4565428919886472, + "peak_rss_bytes": 245682176, + "source_hash_bytes": 0 + }, + "source-first-merge": { + "mode": "source", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 9.13593974300602, + "path": "source scan", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0012156870070612058, + "path": "result cache", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + } + ], + "seconds": 9.194043210998643, + "peak_rss_bytes": 9622986752, + "source_hash_bytes": 9394511724 + }, + "timestamps-first-merge": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 0.8239759889984271, + "path": "prepared timestamp rows", + "timestamp_bytes": 103625505, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.004266465999535285, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "32039d613fcbae29fb76e29b6f24d5238835be70a3d24d1f91d72ed04f1f6729", + "status": "ready" + } + ], + "cancel_seconds": 2.370499714743346e-05, + "cancelled_request_seconds": 0.014001378003740683, + "seconds": 0.8548901670001214, + "peak_rss_bytes": 243359744, + "source_hash_bytes": 0 + }, + "build-counters": { + "mode": "build-counters", + "os_cache": "uncontrolled", + "queries": [], + "seconds": 166.29372705299465, + "peak_rss_bytes": 9583378432, + "source_hash_bytes": 9394511724, + "artifact_bytes": 3039426 + }, + "counters": { + "mode": "counters", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "original", + "repeat": 0, + "seconds": 0.0038765110075473785, + "path": "prepared RP counters", + "timestamp_bytes": 0, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + }, + { + "membership": "original", + "repeat": 1, + "seconds": 0.003068461999646388, + "path": "prepared RP counters", + "timestamp_bytes": 0, + "fingerprint": "8b9357fd0d36f7f0c7a7e8c3b12467830d4af5ae802c69110a873f963b28da8e", + "status": "ready" + } + ], + "seconds": 0.019501380011206493, + "peak_rss_bytes": 220299264, + "source_hash_bytes": 0 + } + }, + "agreement": { + "original": { + "fingerprints_equal": true, + "source_seconds": 14.725798075000057, + "prepared_seconds": 0.26277301499794703, + "speedup": 56.03999358577632, + "comparison_note": "Source timing includes first-use authentication; timestamp original is not the precomputed-counter path." + }, + "merge": { + "fingerprints_equal": true, + "source_seconds": 2.16931946000841, + "prepared_seconds": 0.7879041740088724, + "speedup": 2.753278293946418, + "comparison_note": "Source reader authenticated by preceding original query; root cache disabled in both paths." + }, + "amplitude-child": { + "fingerprints_equal": true, + "source_seconds": 2.021045839996077, + "prepared_seconds": 0.3684799030015711, + "speedup": 5.484819724313323, + "comparison_note": "Threshold is raw amplitude >= 0; source reader already authenticated; root cache disabled." + } + }, + "benchmark_tool_change": "Added --source-dir to query and builder modes because the saved preparation points to a removed temporary overlay. Explicit source override authenticates the original export; original preparation and source files are not modified.", + "validation": { + "command": "make test-full UV_RUN='uv run --no-sync'", + "results": [ + "747 passed, 13 skipped in 144.80s (0:02:24)", + "1079 passed, 6 skipped, 84 warnings in 446.11s (0:07:26)" + ], + "lint": "passed (included in test-full)", + "format_check": "passed (included in test-full)", + "benchmark_tool_lint_and_format": "passed", + "git_diff_check": "passed", + "log": "/tmp/phy-rp-resumed-full.log", + "source_changes_this_resume": [ + "tools/benchmark_refractory.py: explicit source directory override for queries and builders" + ], + "publication": "none" + }, + "counter_agreement": { + "source_fingerprint_equal": true, + "first_query_seconds": 0.0038765110075473785, + "source_access_blocked": true + } +} diff --git a/design/rp-performance-audit-2026-11-25.json b/design/rp-performance-audit-2026-11-25.json new file mode 100644 index 000000000..35a70ed34 --- /dev/null +++ b/design/rp-performance-audit-2026-11-25.json @@ -0,0 +1,272 @@ +{ + "audit": { + "model": "GPT-6.1 Sol", + "reasoning": "high", + "scope": "read-only audit of RP performance, exact precomputation, Numba, multicore, GPU/HPC; root supplemented local measurements", + "custom_binary_extensions": "excluded by user", + "publication": "none" + }, + "hardware": { + "cpu": "Intel Core i9-14900K", + "logical_cpus": 32, + "physical_cores": 24, + "gpu": "NVIDIA GeForce RTX 5090", + "gpu_memory_MiB": 32607 + }, + "prototype_environment": { + "launch": "uv run --no-sync --with numba", + "numba": "0.68.1", + "numpy": "2.4.3", + "project_dependencies_changed": false + }, + "measurements": { + "optimized_regular": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 2.9991373009979725, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009898540010908619, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "status": "ready" + } + ], + "cancel_seconds": 1.7272992408834398e-05, + "cancelled_request_seconds": 0.006781752992537804, + "seconds": 3.0081933209876297, + "peak_rss_bytes": 231133184, + "source_hash_bytes": 0 + }, + "baseline_poisson": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 7.083105063997209, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009878570126602426, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "status": "ready" + } + ], + "cancel_seconds": 2.364299143664539e-05, + "cancelled_request_seconds": 0.011994404994766228, + "seconds": 7.097299722998287, + "peak_rss_bytes": 235032576, + "source_hash_bytes": 0 + }, + "optimized_poisson": { + "mode": "timestamps", + "os_cache": "uncontrolled", + "queries": [ + { + "membership": "merge", + "repeat": 0, + "seconds": 4.538168281011167, + "path": "prepared timestamp rows", + "timestamp_bytes": 760000000, + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "status": "ready" + }, + { + "membership": "merge", + "repeat": 1, + "seconds": 0.0009927419887389988, + "path": "prepared timestamp rows", + "timestamp_bytes": 0, + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "status": "ready" + } + ], + "cancel_seconds": 2.3590007913298905e-05, + "cancelled_request_seconds": 0.009144266005023383, + "seconds": 4.549644910992356, + "peak_rss_bytes": 235073536, + "source_hash_bytes": 0 + }, + "numba_initial_regular": { + "prototype": "two roots, whole read-only mmap; bounded-state but RSS/mapping and cancellation NOT production-ready", + "verification_seconds": 0.5816308339999523, + "kernel_seconds_first_and_repeat": [ + 11.018256787996506, + 9.80866855799104 + ], + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "spikes_after_dedup": 76000000, + "violations": 0, + "duplicates_removed": 0, + "peak_rss_bytes": 1111277568 + }, + "numba_initial_poisson": { + "prototype": "two roots, whole read-only mmap; bounded-state but RSS/mapping and cancellation NOT production-ready", + "verification_seconds": 0.589644859006512, + "kernel_seconds_first_and_repeat": [ + 10.228227327010245, + 9.94403443999181 + ], + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "spikes_after_dedup": 75468024, + "violations": 1107760, + "duplicates_removed": 531976, + "peak_rss_bytes": 1089409024 + }, + "numba_inlined_regular": { + "prototype": "two roots, whole read-only mmap; bounded-state but RSS/mapping and cancellation NOT production-ready", + "verification_seconds": 0.5692608760000439, + "kernel_seconds_first_and_repeat": [ + 13.593661984996288, + 8.882050542000798 + ], + "fingerprint": "175e58864b9f8b716e515feca4ee1948bce80c213a129c66d89d9ba1c6aa301b", + "spikes_after_dedup": 76000000, + "violations": 0, + "duplicates_removed": 0, + "peak_rss_bytes": 1138823168 + }, + "numba_inlined_poisson": { + "prototype": "two roots, whole read-only mmap; bounded-state but RSS/mapping and cancellation NOT production-ready", + "verification_seconds": 0.5670164360053604, + "kernel_seconds_first_and_repeat": [ + 8.981380551005714, + 9.3991468000022 + ], + "fingerprint": "c7301ac6e7e006adf9092caba8cd4e9d8fa3d48a254d45bcdba5232c65a1f447", + "spikes_after_dedup": 75468024, + "violations": 1107760, + "duplicates_removed": 531976, + "peak_rss_bytes": 1090273280 + } + }, + "raw_report_paths": { + "optimized_regular": "/tmp/phy-rp-optimized-merge.json", + "baseline_poisson": "/tmp/phy-rp-baseline-poisson.json", + "optimized_poisson": "/tmp/phy-rp-numpy-poisson.json", + "numba_initial_regular": "/tmp/phy-rp-numba-regular.json", + "numba_initial_poisson": "/tmp/phy-rp-numba-poisson.json", + "numba_inlined_regular": "/tmp/phy-rp-numba-inline-regular.json", + "numba_inlined_poisson": "/tmp/phy-rp-numba-inline-poisson.json" + }, + "poisson_workload": { + "spikes": 80000000, + "duration_samples": 107938507064, + "seed": 25062026, + "ticks": "floor exponential interarrival with mean1350 ticks; integer ties allowed", + "labels": "exact counts60M,16M,2M,2M shuffled independently per1M rows", + "amplitudes": "float32 normal(0,1)" + }, + "optimized_profile": { + "path": "/tmp/phy-rp-optimized-poisson.prof", + "total_seconds_including_imports": 7.381233393999985, + "stages": [ + { + "file": "/home/cyrille/GIT/IBL/phy/phy/apps/large_recording/refractory_store.py", + "line": 250, + "function": "_unit_batches", + "calls": 1166, + "self_seconds": 0.390173168, + "inclusive_seconds": 1.1241697290000001 + }, + { + "file": "/home/cyrille/GIT/IBL/phy/phy/apps/large_recording/refractory_store.py", + "line": 271, + "function": "_chronological", + "calls": 1164, + "self_seconds": 0.38339335300000005, + "inclusive_seconds": 1.84160823 + }, + { + "file": "/home/cyrille/GIT/IBL/phy/phy/apps/large_recording/refractory.py", + "line": 111, + "function": "feed", + "calls": 1163, + "self_seconds": 0.892395577, + "inclusive_seconds": 2.637280001 + }, + { + "file": "/home/cyrille/GIT/IBL/phy/phy/apps/large_recording/summary_store.py", + "line": 394, + "function": "batches", + "calls": 1166, + "self_seconds": 0.005295818000000001, + "inclusive_seconds": 0.573734594 + }, + { + "file": "/home/cyrille/GIT/IBL/phy/phy/apps/large_recording/refractory.py", + "line": 19, + "function": "deduplicate", + "calls": 1156, + "self_seconds": 0.41736861900000005, + "inclusive_seconds": 0.871929646 + }, + { + "file": "~", + "line": 0, + "function": "", + "calls": 1206, + "self_seconds": 0.49538740700000006, + "inclusive_seconds": 0.49538740700000006 + } + ], + "note": "Inclusive stage times overlap and must not be added. Profile instrumentation affects timings." + }, + "source": { + "baseline_refractory_sha256": "0751d63f83c8185139dec61060e3119304b49df3212b2df8bff765885cd7512b", + "pending_refractory_sha256": "5ca9a4677ec984b321d1b735ae320c9f1d1c1cab4df6c772a70f8329b8d5a55c", + "numba_initial_path": "/tmp/phy-rp-numba-prototype-first.py", + "numba_inlined_path": "/tmp/phy-rp-numba-prototype.py", + "numba_inlined_sha256": "63e44714f21bd6d02a156378c534b680c32b4708ecf4196b585a5557d144164c" + }, + "validation": { + "numpy_focused_tests": 51, + "numpy_full_suite_since_optimization": false, + "numba_dense_small_oracle_cases": 30, + "large_fingerprints": "all equal for corresponding workload", + "numba_limitations": [ + "two-original-root pure merges only", + "whole-file read-only mmap; peak RSS about1.1GB", + "separate pre-verification pass warms data", + "bounded cancellation and production publication rechecks not implemented", + "compiled-cache state not controlled for every first call" + ] + }, + "findings": [ + "Prepared rows still replay all selected raw spikes; this is the structural latency cost.", + "Sparse NumPy counting improves the regular fixture from7.2s to3.0s and Poisson-like fixture from7.08s to4.54s.", + "Naive scalar Numba fusion and forced helper inlining do not accelerate these cases; no10x claim is established.", + "Prepared exact likely-pair results can eliminate query replay for those exact memberships. Arbitrary multiway merges and threshold descendants require additional evidence or exact fallback.", + "Global interaction sparsity must not be assumed from selected-root sparsity.", + "Selective page authentication/time directories and certified independent partitions enable sparse access and bounded parallel processing.", + "Numba/hybrid, multicore and GPU options require measured end-to-end wins including authentication, startup/JIT and memory." + ], + "primary_sources": [ + "https://numba.readthedocs.io/en/stable/user/performance-tips.html", + "https://numba.readthedocs.io/en/stable/developer/caching.html", + "https://numba.readthedocs.io/en/stable/user/threading-layer.html", + "https://numba.readthedocs.io/en/stable/developer/inlining.html", + "https://docs.cupy.dev/en/stable/user_guide/performance.html", + "https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#data-transfer-between-host-and-device" + ] +} diff --git a/design/rp-resource-budgets-2026-11-26.json b/design/rp-resource-budgets-2026-11-26.json new file mode 100644 index 000000000..97c29d695 --- /dev/null +++ b/design/rp-resource-budgets-2026-11-26.json @@ -0,0 +1,88 @@ +{ + "platform": "Linux-7.0.0-43-generic-x86_64-with-glibc2.39", + "python": "3.12.3", + "numpy": "2.4.3", + "spikes": 2000000, + "units": 962, + "bins": 2052, + "elapsed_seconds": 20.88217046900536, + "spikes_per_second": 95775.48478346763, + "plan": { + "units": 962, + "bins": 2052, + "disk_bytes": 33621069, + "fixed_bytes": 45883548, + "component_bytes": 10589696, + "max_component": 43, + "batch_size": 41545, + "row_bytes": 256 + }, + "planned_memory_bytes": 67108764, + "traced_peak_bytes": 34954400, + "peak_rss_bytes": 292712448, + "baseline_peak_rss_bytes": 221876224, + "artifact_bytes": 32250922, + "note": "Synthetic 962-unit,1026h geometry; 2M regular spikes, no duplicate chains. tracemalloc enabled during build; RSS includes interpreter and mapped source pages. Not a real-data throughput comparison.", + "source_sha256": { + "phy/apps/large_recording/refractory.py": "d258760e41161b0256f1438781b58d56f7865e55e93c026ea1c21bbd19c5495b", + "phy/apps/large_recording/refractory_store.py": "227e28285a6fd71e422b550182879f578e1ca71429a2f5c4ac1e1c9102b3e11f", + "phy/apps/large_recording/refractory_resources.py": "3293329b3c9837cecd1447085b74dd0f01bd6615142abdb8d92c48d4c1dde9bc" + }, + "implementation_commit": "083bedc9", + "workload": { + "duration_hours": 1026, + "sample_rate": 30000, + "spike_times": "arange(2000000, dtype=int64) * (2052 * 1800 * 30000 // 2000000)", + "spike_clusters": "(arange(2000000) % 962).astype(int32)", + "amplitudes": "ones(2000000, dtype=float32)", + "exposure": "continuous acquisition for the full declared duration", + "construction": "make_sorting fixture with replaced spike arrays and clock; remove feature/position/depth and waveform-subset sidecars" + }, + "uninstrumented_timings": [ + { + "mode": "defaults", + "seconds": 8.39139715701458, + "spikes_per_second": 238339.33284019926, + "kwargs": { + "batch_size": 10000000 + }, + "artifact_bytes": 32250922, + "note": "Uninstrumented synthetic timing, warm/uncontrolled OS caches; not a real-data benchmark." + }, + { + "mode": "large-budget", + "seconds": 6.601254294975661, + "spikes_per_second": 302972.72467177, + "kwargs": { + "batch_size": 10000000, + "memory_bytes": 17179869184, + "max_bytes": 4294967296 + }, + "artifact_bytes": 32250922, + "note": "Uninstrumented synthetic timing, warm/uncontrolled OS caches; not a real-data benchmark." + } + ], + "validation": { + "environment": "uv sync --frozen --dev (94 packages checked; no dependency changes)", + "full_suite": { + "command": "make test-full UV_RUN='uv run --no-sync'", + "results": [ + "747 passed, 13 skipped in 147.10s", + "1089 passed, 6 skipped in 477.16s" + ], + "lint": "passed (included in test-full)", + "format_check": "passed (included in test-full)", + "log": "/tmp/phy-rp-full.log" + }, + "documentation": { + "command": "make doc-check UV_RUN='uv run --no-sync'", + "result": "passed; generated documentation current", + "log": "/tmp/phy-rp-doc-check.log" + }, + "diff_check": "passed", + "review": "GPT-6.1 Sol high read-only review found fragmented exposure metadata accounting gap; fixed with interval/catalog allowances and a focused regression. No other blockers reported.", + "scope": "Synthetic geometry and scientific/integrity regression coverage; Carl actual 4.92B-spike dataset not reproduced." + }, + "uninstrumented_artifacts_byte_identical": true, + "uninstrumented_artifact_files_compared": 963 +} diff --git a/design/selection-order-color-refactor.md b/design/selection-order-color-refactor.md index e0a729e8f..118d9fe65 100644 --- a/design/selection-order-color-refactor.md +++ b/design/selection-order-color-refactor.md @@ -63,11 +63,12 @@ projection and never infer colors from presentation order. color-slot bindings are unique. 2. `set(presentation_order) == set(effective_ids)`. 3. Every effective ID has exactly one color-slot binding. -4. If a reference exists, it belongs to the active primary role and occupies - index zero in both `presentation_order` and `color_slots`. +4. If a reference exists, it belongs to the active primary role and owns color + slot zero. In Normal mode it also occupies presentation index zero; in Merge + mode its row position is independent. 5. Normal mode has no Merge session and its reference belongs to `cluster_ids`. -6. Merge mode has no Cluster role selection, and the reference is the first - Merge member. +6. Merge mode has no Cluster role selection, and the reference is a staged Merge + member whose identity is independent of row position. 7. In Merge mode, `presentation_order` begins with the exact Merge View order; its tail contains exactly the selected Similarity IDs. 8. A non-empty Similarity selection requires a reference. diff --git a/design/slay-roundtrip-validation.md b/design/slay-roundtrip-validation.md new file mode 100644 index 000000000..7af25b863 --- /dev/null +++ b/design/slay-roundtrip-validation.md @@ -0,0 +1,84 @@ +# SLAY persistence validation + +The follow-up to PR #1428 preserves producer `curation.json` bytes and the +complete source-bound review ledger through bounded preparation, committed +save, full replay, and re-preparation. Suggestions retain original IDs; pending +suggestions affected by merges or threshold splits become stale. Historical +accept/reject decisions take precedence over that derived status. + +## Integrity and regression coverage + +Preparation hashes the producer document and an immutable inherited review +snapshot. Session loading uses committed checkpoint reviews before loose review +copies. Direct saves and saves with the proposition feature disabled preserve +the ledger; suggestions without decisions receive an empty bound ledger. +Generation extra documents must belong to the checkpoint hash inventory. +Replay stages both documents, checks copied bytes, and publishes hashes and +cumulative merge/split retirement records in lineage. + +Focused regressions cover three no-op rounds in direct, enabled and disabled +modes; accepted, rejected and orphan history; cumulative merge/split retirement; +malformed, conflicting or absent loose copies; mutated bound documents; missing +or null checkpoint ledgers; and mutations during copying. Old bounded packages +with unbound proposition artifacts fail explicitly instead of dropping history. +Ordinary unbounded loading keeps its existing compatibility behavior. + +A separate Sol-high read-only audit identified copy-time mutation, legacy +silent-drop and null-ledger bypasses. Each received a fix and regression; the +final audit reported no remaining blocking findings. + +## Real-data fixture and limits + +The fixture is Carl's converted overlay of computation +`b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`, with 469,725,567 spikes, +705 original units, 140,240 waveform rows and 93 suggestions. It preserves the +33 filler-edge spikes using Carl's test-only exposure intervals. These intervals +have not been established as acquisition truth; this is an engineering test, +not acceptance of Brandon's native exporter. See +`aind-real-data-validation.md` for the original coordinate mismatch and exposure +limitations. + +The roundtrip uses Carl's explicit 8,000,000-spike / 3,000,000,000-byte caps to +retain all waveform rows. Through the ordinary proposition-review and merge +path, it accepts `[40,44,48] -> 705` and `[49,50,51,53] -> 706` and marks both +results good. Subsequent rounds perform no additional curation. + +The acceptance oracle requires two accepted and 91 pending suggestions in each +round, identical suggestion bytes and review records, save/reopen consistency, +and an independent streamed comparison of every full-source assignment against +the two original merge groups. Small regression fixtures provide overlapping +stale-suggestion coverage, because Carl's remaining 91 suggestions are disjoint +from these groups. + +The separate validator run on this same test overlay passed with default +2,000,000-spike / 536,870,912-byte caps: 1,486,361 evidence spikes, 27,865 of +140,240 waveform rows retained, and 532,625,749 output bytes. It records that +the exporter revision is Carl's test conversion and that acquisition truth is +unestablished. A real native export and authoritative gap/filler policy are +still required; see `aind-native-export-acceptance.md`. + +Local reports and reproduction scripts are retained under +`/home/cyrille/GIT/IBL/phy-data/carl/aind-b1b0782a-b3ea-4f34-81d7-b3c6e36452b3/slay-validation`. +Large arrays and access credentials are not repository artifacts. + +## Results + +- All three rounds retained exactly two accepted and 91 pending suggestions, + identical producer bytes and review records, and matching assignments for + all 469,725,567 source rows. Each bounded package retained all 140,240 + waveform rows and 7,298,318 evidence spikes at Carl's larger caps. +- The independent hash oracle verified all 67 original files were unchanged + and 12 immutable files per full replay matched the converted source. Both + good labels and the seven retired parent records survived every round. +- A separate final-code controller with proposition loading disabled saved and + reopened the real third-round checkpoint with both accepted reviews intact. +- `make test-full` passed: 854 tests (499 core, 355 applications), with one + existing benchmark skip. Lint and formatting passed. The corrected disabled + controller tests subsequently passed all 22 persistence cases. `make doc-check` + passed; packaging was unchanged. +- The combined three-round script completed every functional assertion and + wrote its success report, then exited with signal 11 during process shutdown. + A separate repeated six-controller/three-GUI lifecycle run with event + processing and reference cleanup exited successfully. The combined harness's + shutdown fault is retained as a limitation; its cause is not established as + a product defect or a data-integrity failure. diff --git a/design/summary-scaling/1000h.json b/design/summary-scaling/1000h.json new file mode 100644 index 000000000..d19300728 --- /dev/null +++ b/design/summary-scaling/1000h.json @@ -0,0 +1,231 @@ +{ + "revision": "f2c53f693ba817bdd5cf6191e0dbf8474f6eb242", + "component_sha256": { + "curation.py": "bb7c9ece0b18b8beb3ce1c9a2b2e30fac3d037b3a6b92291c0d141470b1ec097", + "live_summaries.py": "d65d563fb93ebd666c108831bac7412985f9b7e442f4d16c346c5c5abf67a681", + "source.py": "1de34e489eee0f416408030d5e1f19458f86018c81b2439fff34a6a9ee9ce856", + "summary_store.py": "12946ba1816baa3e6bd31c708e7f6fb822127af784f260642b04d810559ccdb9" + }, + "label": "Synthetic 1000h: 10 repetitions of carl-100; scaling only", + "source_spikes": 4181675220, + "duration_hours": 1000.0, + "native_bins": 1000, + "source_units": 635, + "source_dir": "/home/cyrille/GIT/IBL/phy-data/carl/carl-1000-synthetic", + "cache_conditions": "Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.", + "hardware": { + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "ram_bytes": 134698618880 + }, + "build": { + "seconds": 419.6801867969334, + "peak_rss_bytes": 352661504, + "store_bytes": 25090145902 + }, + "build_note": "Build cost may be from an earlier invocation; runtime component hashes identify this verification run.", + "scenarios": [ + { + "scenario": "median_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 734, + 735 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 4481760, + "payload_bytes_read": 26890560, + "first_seconds": 0.16988634690642357, + "repeat_seconds": 0.16561484895646572, + "counts": { + "734": 2064950, + "735": 2416810 + } + }, + { + "scenario": "largest_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 393, + "children": [ + 834, + 835 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 393 + ], + "source_rows_read": 77538160, + "payload_bytes_read": 465228960, + "first_seconds": 2.1372598209418356, + "repeat_seconds": 2.165173081913963, + "counts": { + "834": 22682900, + "835": 54855260 + } + }, + { + "scenario": "nested_split_median", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 934, + 935 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + }, + { + "operation": "threshold_split", + "parent": 935, + "children": [ + 936, + 937 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -183.10560607910156, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 4481760, + "payload_bytes_read": 26890560, + "first_seconds": 0.17443224298767745, + "repeat_seconds": 0.1753861429169774, + "counts": { + "936": 1241070, + "937": 1175740 + } + }, + { + "scenario": "merge_two_largest_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 320, + 393 + ], + "target": 1034 + }, + { + "operation": "threshold_split", + "parent": 1034, + "children": [ + 1035, + 1036 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 320, + 393 + ], + "source_rows_read": 154940400, + "payload_bytes_read": 929642400, + "first_seconds": 4.737723988015205, + "repeat_seconds": 4.628034166991711, + "counts": { + "1035": 79365690, + "1036": 75574710 + } + }, + { + "scenario": "merge_ten_typical_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 86, + 341, + 370, + 595, + 620, + 259, + 108, + 263, + 541, + 337 + ], + "target": 1134 + }, + { + "operation": "threshold_split", + "parent": 1134, + "children": [ + 1135, + 1136 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 86, + 108, + 259, + 263, + 337, + 341, + 370, + 541, + 595, + 620 + ], + "source_rows_read": 44726720, + "payload_bytes_read": 268360320, + "first_seconds": 1.2235043731052428, + "repeat_seconds": 1.09882698697038, + "counts": { + "1135": 15885470, + "1136": 28841250 + } + } + ], + "combined_full_source_scan_seconds": 173.7228150719311, + "independent_replay_seconds": 145.9861634899862, + "independent_replay_rows": 4181675220, + "indexed_equals_full_scan_and_independent_replay": true, + "bounded_files_unchanged": true +} diff --git a/design/summary-scaling/100h.json b/design/summary-scaling/100h.json new file mode 100644 index 000000000..6785f9f99 --- /dev/null +++ b/design/summary-scaling/100h.json @@ -0,0 +1,231 @@ +{ + "revision": "f2c53f693ba817bdd5cf6191e0dbf8474f6eb242", + "component_sha256": { + "curation.py": "bb7c9ece0b18b8beb3ce1c9a2b2e30fac3d037b3a6b92291c0d141470b1ec097", + "live_summaries.py": "d65d563fb93ebd666c108831bac7412985f9b7e442f4d16c346c5c5abf67a681", + "source.py": "1de34e489eee0f416408030d5e1f19458f86018c81b2439fff34a6a9ee9ce856", + "summary_store.py": "12946ba1816baa3e6bd31c708e7f6fb822127af784f260642b04d810559ccdb9" + }, + "label": "Real carl-100 source; declared 100h engineering exposure", + "source_spikes": 418167522, + "duration_hours": 100.0, + "native_bins": 100, + "source_units": 635, + "source_dir": "/home/cyrille/GIT/IBL/phy-data/carl/carl-100", + "cache_conditions": "Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.", + "hardware": { + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "ram_bytes": 134698618880 + }, + "build": { + "seconds": 41.09955540113151, + "peak_rss_bytes": 347717632, + "store_bytes": 2090919145 + }, + "build_note": "Build cost may be from an earlier invocation; runtime component hashes identify this verification run.", + "scenarios": [ + { + "scenario": "median_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 734, + 735 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 448176, + "payload_bytes_read": 2240880, + "first_seconds": 0.020023497054353356, + "repeat_seconds": 0.018924148054793477, + "counts": { + "734": 206495, + "735": 241681 + } + }, + { + "scenario": "largest_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 393, + "children": [ + 834, + 835 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 393 + ], + "source_rows_read": 7753816, + "payload_bytes_read": 38769080, + "first_seconds": 0.21475644991733134, + "repeat_seconds": 0.21050908719189465, + "counts": { + "834": 2268290, + "835": 5485526 + } + }, + { + "scenario": "nested_split_median", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 934, + 935 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + }, + { + "operation": "threshold_split", + "parent": 935, + "children": [ + 936, + 937 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -183.10560607910156, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 448176, + "payload_bytes_read": 2240880, + "first_seconds": 0.01868885802105069, + "repeat_seconds": 0.01911260699853301, + "counts": { + "936": 124107, + "937": 117574 + } + }, + { + "scenario": "merge_two_largest_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 320, + 393 + ], + "target": 1034 + }, + { + "operation": "threshold_split", + "parent": 1034, + "children": [ + 1035, + 1036 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 320, + 393 + ], + "source_rows_read": 15494040, + "payload_bytes_read": 77470200, + "first_seconds": 0.44719005189836025, + "repeat_seconds": 0.4269037509802729, + "counts": { + "1035": 7936569, + "1036": 7557471 + } + }, + { + "scenario": "merge_ten_typical_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 86, + 341, + 370, + 595, + 620, + 259, + 108, + 263, + 541, + 337 + ], + "target": 1134 + }, + { + "operation": "threshold_split", + "parent": 1134, + "children": [ + 1135, + 1136 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 86, + 108, + 259, + 263, + 337, + 341, + 370, + 541, + 595, + 620 + ], + "source_rows_read": 4472672, + "payload_bytes_read": 22363360, + "first_seconds": 0.11264334712177515, + "repeat_seconds": 0.10721563105471432, + "counts": { + "1135": 1588547, + "1136": 2884125 + } + } + ], + "combined_full_source_scan_seconds": 16.826590470038354, + "independent_replay_seconds": 15.20495374687016, + "independent_replay_rows": 418167522, + "indexed_equals_full_scan_and_independent_replay": true, + "bounded_files_unchanged": true +} diff --git a/design/summary-scaling/200h.json b/design/summary-scaling/200h.json new file mode 100644 index 000000000..9336ced95 --- /dev/null +++ b/design/summary-scaling/200h.json @@ -0,0 +1,231 @@ +{ + "revision": "f2c53f693ba817bdd5cf6191e0dbf8474f6eb242", + "component_sha256": { + "curation.py": "bb7c9ece0b18b8beb3ce1c9a2b2e30fac3d037b3a6b92291c0d141470b1ec097", + "live_summaries.py": "d65d563fb93ebd666c108831bac7412985f9b7e442f4d16c346c5c5abf67a681", + "source.py": "1de34e489eee0f416408030d5e1f19458f86018c81b2439fff34a6a9ee9ce856", + "summary_store.py": "12946ba1816baa3e6bd31c708e7f6fb822127af784f260642b04d810559ccdb9" + }, + "label": "Synthetic 200h: two repetitions of carl-100; scaling only", + "source_spikes": 836335044, + "duration_hours": 200.0, + "native_bins": 200, + "source_units": 635, + "source_dir": "/home/cyrille/GIT/IBL/phy-data/carl/carl-200-synthetic", + "cache_conditions": "Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.", + "hardware": { + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "ram_bytes": 134698618880 + }, + "build": { + "seconds": 82.86803907901049, + "peak_rss_bytes": 347410432, + "store_bytes": 4181758334 + }, + "build_note": "Build cost may be from an earlier invocation; runtime component hashes identify this verification run.", + "scenarios": [ + { + "scenario": "median_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 734, + 735 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 896352, + "payload_bytes_read": 4481760, + "first_seconds": 0.037769469898194075, + "repeat_seconds": 0.03765337495133281, + "counts": { + "734": 412990, + "735": 483362 + } + }, + { + "scenario": "largest_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 393, + "children": [ + 834, + 835 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 393 + ], + "source_rows_read": 15507632, + "payload_bytes_read": 77538160, + "first_seconds": 0.42889548116363585, + "repeat_seconds": 0.4220040859654546, + "counts": { + "834": 4536580, + "835": 10971052 + } + }, + { + "scenario": "nested_split_median", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 934, + 935 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + }, + { + "operation": "threshold_split", + "parent": 935, + "children": [ + 936, + 937 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -183.10560607910156, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 896352, + "payload_bytes_read": 4481760, + "first_seconds": 0.038135949056595564, + "repeat_seconds": 0.03697570809163153, + "counts": { + "936": 248214, + "937": 235148 + } + }, + { + "scenario": "merge_two_largest_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 320, + 393 + ], + "target": 1034 + }, + { + "operation": "threshold_split", + "parent": 1034, + "children": [ + 1035, + 1036 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 320, + 393 + ], + "source_rows_read": 30988080, + "payload_bytes_read": 154940400, + "first_seconds": 0.8800507651176304, + "repeat_seconds": 0.8461028258316219, + "counts": { + "1035": 15873138, + "1036": 15114942 + } + }, + { + "scenario": "merge_ten_typical_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 86, + 341, + 370, + 595, + 620, + 259, + 108, + 263, + 541, + 337 + ], + "target": 1134 + }, + { + "operation": "threshold_split", + "parent": 1134, + "children": [ + 1135, + 1136 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 86, + 108, + 259, + 263, + 337, + 341, + 370, + 541, + 595, + 620 + ], + "source_rows_read": 8945344, + "payload_bytes_read": 44726720, + "first_seconds": 0.2478583010379225, + "repeat_seconds": 0.2253292128443718, + "counts": { + "1135": 3177094, + "1136": 5768250 + } + } + ], + "combined_full_source_scan_seconds": 23.002842705929652, + "independent_replay_seconds": 27.71198688284494, + "independent_replay_rows": 836335044, + "indexed_equals_full_scan_and_independent_replay": true, + "bounded_files_unchanged": true +} diff --git a/design/summary-scaling/amplitude-index-1000h.json b/design/summary-scaling/amplitude-index-1000h.json new file mode 100644 index 000000000..aaf3eaf45 --- /dev/null +++ b/design/summary-scaling/amplitude-index-1000h.json @@ -0,0 +1,302 @@ +{ + "revision": "3419700463849757f91efc90b5b83f6856f725b2", + "component_sha256": { + "curation.py": "bb7c9ece0b18b8beb3ce1c9a2b2e30fac3d037b3a6b92291c0d141470b1ec097", + "live_summaries.py": "8b0877d31467262cc50694742167ab0f09492ec38a4ef32a4c51f476bacc9f83", + "source.py": "1de34e489eee0f416408030d5e1f19458f86018c81b2439fff34a6a9ee9ce856", + "summary_store.py": "8f75cb61816999148de9c4d83feeb8dd7d8b81d1f324179e5b8e9dd202753223", + "range_build.py": "ca3fc31a2d820e4f03a49e142cc75dc962ea8b3a0566cc32f26d0b6f766db968", + "range_files.py": "f7c553fd1849055961a0a2a711df6377ff477ef50a44d33a4ad3b83e6660993d", + "range_index.py": "f8a05926778c8a7875582a1746bc4211f35415a9d81f015eee8c876349acb85f", + "range_intervals.py": "4a9a52022c5df86efc6b5cb2bab118d204b41b5adf3ea1357e9964a38d39cc65", + "range_math.py": "c48c2c85127e29a3f9421fa2d01ef79cd8cc7a70a910686190e5378e509819a8" + }, + "label": "1000h synthetic from Carl 100h source, 10 repetitions", + "source_spikes": 4181675220, + "duration_hours": 1000.0, + "native_bins": 1000, + "source_units": 635, + "source_dir": "/home/cyrille/GIT/IBL/phy-data/carl/carl-1000-synthetic", + "cache_conditions": "Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.", + "hardware": { + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "ram_bytes": 134698618880 + }, + "build": null, + "range_build": { + "seconds": 264.32920015999116, + "peak_rss_bytes": 314470400, + "index_bytes": 20274424930 + }, + "build_note": "Build cost may be from an earlier invocation; runtime component hashes identify this verification run.", + "scenarios": [ + { + "scenario": "median_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 734, + 735 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 0, + "original_rows_represented": 4481760, + "payload_bytes_read": 7798784, + "first_range_metrics": { + "payload_bytes_read": 7798784, + "authentication_bytes_read": 120864, + "pages_verified": 1904, + "resident_page_bytes": 7798784 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 7798784 + }, + "first_seconds": 0.05507006193511188, + "repeat_seconds": 0.04022911796346307, + "counts": { + "734": 2064950, + "735": 2416810 + } + }, + { + "scenario": "largest_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 393, + "children": [ + 834, + 835 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 393 + ], + "source_rows_read": 0, + "original_rows_represented": 77538160, + "payload_bytes_read": 27078656, + "first_range_metrics": { + "payload_bytes_read": 27078656, + "authentication_bytes_read": 542080, + "pages_verified": 6611, + "resident_page_bytes": 27078656 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 27078656 + }, + "first_seconds": 0.1154752301517874, + "repeat_seconds": 0.05717089888639748, + "counts": { + "834": 22682900, + "835": 54855260 + } + }, + { + "scenario": "nested_split_median", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 934, + 935 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + }, + { + "operation": "threshold_split", + "parent": 935, + "children": [ + 936, + 937 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -183.10560607910156, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 0, + "original_rows_represented": 4481760, + "payload_bytes_read": 11509760, + "first_range_metrics": { + "payload_bytes_read": 11509760, + "authentication_bytes_read": 144416, + "pages_verified": 2810, + "resident_page_bytes": 11509760 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 11509760 + }, + "first_seconds": 0.07356515293940902, + "repeat_seconds": 0.054177568992599845, + "counts": { + "936": 1241070, + "937": 1175740 + } + }, + { + "scenario": "merge_two_largest_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 320, + 393 + ], + "target": 1034 + }, + { + "operation": "threshold_split", + "parent": 1034, + "children": [ + 1035, + 1036 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 320, + 393 + ], + "source_rows_read": 0, + "original_rows_represented": 154940400, + "payload_bytes_read": 59379712, + "first_range_metrics": { + "payload_bytes_read": 59379712, + "authentication_bytes_read": 1159200, + "pages_verified": 14497, + "resident_page_bytes": 59379712 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 59379712 + }, + "first_seconds": 0.24421490007080138, + "repeat_seconds": 0.12011308292858303, + "counts": { + "1035": 79365690, + "1036": 75574710 + } + }, + { + "scenario": "merge_ten_typical_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 86, + 341, + 370, + 595, + 620, + 259, + 108, + 263, + 541, + 337 + ], + "target": 1134 + }, + { + "operation": "threshold_split", + "parent": 1134, + "children": [ + 1135, + 1136 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 86, + 108, + 259, + 263, + 337, + 341, + 370, + 541, + 595, + 620 + ], + "source_rows_read": 0, + "original_rows_represented": 44726720, + "payload_bytes_read": 77725696, + "first_range_metrics": { + "payload_bytes_read": 77725696, + "authentication_bytes_read": 1219328, + "pages_verified": 18976, + "resident_page_bytes": 67108864 + }, + "repeat_range_metrics": { + "payload_bytes_read": 77725696, + "authentication_bytes_read": 1211520, + "pages_verified": 18976, + "resident_page_bytes": 67108864 + }, + "first_seconds": 0.5241659739986062, + "repeat_seconds": 0.5401255849283189, + "counts": { + "1135": 15885470, + "1136": 28841250 + } + } + ], + "combined_full_source_scan_seconds": 138.23595696105622, + "independent_replay_seconds": 142.96548272110522, + "independent_replay_rows": 4181675220, + "indexed_equals_full_scan_and_independent_replay": true, + "bounded_files_unchanged": true +} diff --git a/design/summary-scaling/amplitude-index-100h.json b/design/summary-scaling/amplitude-index-100h.json new file mode 100644 index 000000000..2f104ccfb --- /dev/null +++ b/design/summary-scaling/amplitude-index-100h.json @@ -0,0 +1,302 @@ +{ + "revision": "5d3a429cbe42f4861d55fa2a26f1e437b2535d64", + "component_sha256": { + "curation.py": "bb7c9ece0b18b8beb3ce1c9a2b2e30fac3d037b3a6b92291c0d141470b1ec097", + "live_summaries.py": "dcc5df42de4401ec4068818672777c8fceee206b39be1202416d192cb25298b9", + "source.py": "1de34e489eee0f416408030d5e1f19458f86018c81b2439fff34a6a9ee9ce856", + "summary_store.py": "45b8cbac0d2a6c5e80cf716fb4c2e7e3c0b074b5865a1ff65354dd0185c638f7", + "range_build.py": "840f3041c028dbc7ab0d1c1ee68248d2222e9e0ba83891e22a2f60aae35d4e4e", + "range_files.py": "146f01f0fb1f999673ca61256f4ea23209b0804d268c6e129fc31fe9cabb61c6", + "range_index.py": "f8a05926778c8a7875582a1746bc4211f35415a9d81f015eee8c876349acb85f", + "range_intervals.py": "4a9a52022c5df86efc6b5cb2bab118d204b41b5adf3ea1357e9964a38d39cc65", + "range_math.py": "c48c2c85127e29a3f9421fa2d01ef79cd8cc7a70a910686190e5378e509819a8" + }, + "label": "Carl 100h real source, legacy construction/exposure not independently certified", + "source_spikes": 418167522, + "duration_hours": 100.0, + "native_bins": 100, + "source_units": 635, + "source_dir": "/home/cyrille/GIT/IBL/phy-data/carl/carl-100", + "cache_conditions": "Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.", + "hardware": { + "platform": "Linux-7.0.0-38-generic-x86_64-with-glibc2.39", + "ram_bytes": 134698618880 + }, + "build": null, + "range_build": { + "seconds": 26.027659064158797, + "peak_rss_bytes": 234627072, + "index_bytes": 2035795190 + }, + "build_note": "Build cost may be from an earlier invocation; runtime component hashes identify this verification run.", + "scenarios": [ + { + "scenario": "median_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 734, + 735 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 0, + "original_rows_represented": 448176, + "payload_bytes_read": 806912, + "first_range_metrics": { + "payload_bytes_read": 806912, + "authentication_bytes_read": 13504, + "pages_verified": 197, + "resident_page_bytes": 806912 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 806912 + }, + "first_seconds": 0.006470035994425416, + "repeat_seconds": 0.0043745560105890036, + "counts": { + "734": 206495, + "735": 241681 + } + }, + { + "scenario": "largest_unit", + "events": [ + { + "operation": "threshold_split", + "parent": 393, + "children": [ + 834, + 835 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 393 + ], + "source_rows_read": 0, + "original_rows_represented": 7753816, + "payload_bytes_read": 2695168, + "first_range_metrics": { + "payload_bytes_read": 2695168, + "authentication_bytes_read": 55168, + "pages_verified": 658, + "resident_page_bytes": 2695168 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 2695168 + }, + "first_seconds": 0.011418625013902783, + "repeat_seconds": 0.00589829683303833, + "counts": { + "834": 2268290, + "835": 5485526 + } + }, + { + "scenario": "nested_split_median", + "events": [ + { + "operation": "threshold_split", + "parent": 259, + "children": [ + 934, + 935 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + }, + { + "operation": "threshold_split", + "parent": 935, + "children": [ + 936, + 937 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -183.10560607910156, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 259 + ], + "source_rows_read": 0, + "original_rows_represented": 448176, + "payload_bytes_read": 1155072, + "first_range_metrics": { + "payload_bytes_read": 1155072, + "authentication_bytes_read": 15776, + "pages_verified": 282, + "resident_page_bytes": 1155072 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 1155072 + }, + "first_seconds": 0.00808028900064528, + "repeat_seconds": 0.0057254391722381115, + "counts": { + "936": 124107, + "937": 117574 + } + }, + { + "scenario": "merge_two_largest_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 320, + 393 + ], + "target": 1034 + }, + { + "operation": "threshold_split", + "parent": 1034, + "children": [ + 1035, + 1036 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -241.0890350341797, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 320, + 393 + ], + "source_rows_read": 0, + "original_rows_represented": 15494040, + "payload_bytes_read": 5926912, + "first_range_metrics": { + "payload_bytes_read": 5926912, + "authentication_bytes_read": 118272, + "pages_verified": 1447, + "resident_page_bytes": 5926912 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 5926912 + }, + "first_seconds": 0.024271545000374317, + "repeat_seconds": 0.012288301950320601, + "counts": { + "1035": 7936569, + "1036": 7557471 + } + }, + { + "scenario": "merge_ten_typical_then_split", + "events": [ + { + "operation": "merge", + "parents": [ + 86, + 341, + 370, + 595, + 620, + 259, + 108, + 263, + 541, + 337 + ], + "target": 1134 + }, + { + "operation": "threshold_split", + "parent": 1134, + "children": [ + 1135, + 1136 + ], + "predicate": { + "attribute": "amplitudes.npy", + "operator": "<", + "threshold": -155.63975524902344, + "nonfinite": "keep" + } + } + ], + "original_units": [ + 86, + 108, + 259, + 263, + 337, + 341, + 370, + 541, + 595, + 620 + ], + "source_rows_read": 0, + "original_rows_represented": 4472672, + "payload_bytes_read": 7835648, + "first_range_metrics": { + "payload_bytes_read": 7835648, + "authentication_bytes_read": 130880, + "pages_verified": 1913, + "resident_page_bytes": 7835648 + }, + "repeat_range_metrics": { + "payload_bytes_read": 0, + "authentication_bytes_read": 0, + "pages_verified": 0, + "resident_page_bytes": 7835648 + }, + "first_seconds": 0.0536587149836123, + "repeat_seconds": 0.03875553188845515, + "counts": { + "1135": 1588547, + "1136": 2884125 + } + } + ], + "combined_full_source_scan_seconds": 17.303714708192274, + "independent_replay_seconds": 14.489171310095116, + "independent_replay_rows": 418167522, + "indexed_equals_full_scan_and_independent_replay": true, + "bounded_files_unchanged": true +} diff --git a/design/summary-store-gui-result.json b/design/summary-store-gui-result.json new file mode 100644 index 000000000..0aeb212a8 --- /dev/null +++ b/design/summary-store-gui-result.json @@ -0,0 +1,33 @@ +{ + "revision": "0da082b18c770400d04a8c718291339160e83e52", + "source_spikes": 469725567, + "label": "Earlier converted 112.859h engineering dataset; not native1000h acceptance", + "build_attach_and_child_summary_seconds": 49.613298593787476, + "heartbeat": { + "target_interval_ms": 10, + "samples": 4659, + "p50_ms": 9.61997197009623, + "p95_ms": 10.642739781178534, + "max_ms": 333.6789670865983, + "screenshot_intervals_excluded": true + }, + "children": [ + 709, + 710 + ], + "child_counts": [ + 292990, + 346764 + ], + "curation_remained_unsaved": true, + "stages": [ + "Validating source", + "Building summary store", + "Finalizing" + ], + "screenshots": [ + "prompt.png", + "building.png", + "ready.png" + ] +} diff --git a/design/summary-store-result.json b/design/summary-store-result.json new file mode 100644 index 000000000..b5752614a --- /dev/null +++ b/design/summary-store-result.json @@ -0,0 +1,47 @@ +{ + "revision": "9e4ac0049ff6915f3990f8339c4e3fd4749c150f", + "dataset": "Earlier converted 112.859-hour engineering dataset; not 1000-hour acceptance", + "source_spikes": 469725567, + "unit": 49, + "threshold": -341.797119140625, + "timings_seconds": { + "indexed": 0.017951954854652286, + "indexed_repeat": 0.016828396124765277, + "full_scan": 6.47001982992515, + "full_scan_repeat": 2.1761009390465915 + }, + "phases": { + "indexed": [ + [ + "reading prepared unit summaries", + 639754, + 639754 + ] + ], + "full_scan": [ + [ + "validating source", + 9394511724, + 9394511724 + ], + [ + "scanning full source", + 469725567, + 469725567 + ] + ] + }, + "counts": { + "808": 346764, + "809": 292990 + }, + "indexed_equals_full_scan": true, + "independent_replay_verified_rows": 469725567, + "bounded_files_unchanged": true, + "cache_conditions": "Uncontrolled OS cache; source hashing warms the full scan; index built before measurement.", + "build": { + "seconds": 47.388859510887414, + "peak_rss_bytes": 335151104, + "store_bytes": 2348718604 + } +} diff --git a/design/unit-metadata-roundtrip-validation.md b/design/unit-metadata-roundtrip-validation.md new file mode 100644 index 000000000..140d25256 --- /dev/null +++ b/design/unit-metadata-roundtrip-validation.md @@ -0,0 +1,111 @@ +# Unit metadata and display feedback: seven-item acceptance + +This follow-up implements Carl's three-page **PR1428 - unit metadata across +curation rounds.pdf**, received 25 October 2026. Changes remain in PR #1428's +`feature/long-recording-curation` branch. No phylib or exporter change is needed. + +| PDF item | Behavior and evidence | +| --- | --- | +| 1. Source IDs and filenames | Schema descriptors preserve source basenames, CSV/TSV delimiters and column ordering. `cluster_si_unit_ids.tsv` remains plural with header `si_unit_id`; new merge/split IDs have blank scalar source IDs. Complete parent metadata is retained in history. | +| 2. Stale pipeline metrics/classifications | Membership-policy events clear imported fields and quality on new membership. Explicit new-unit labels survive unchanged rounds; prior decisions remain historical. GUI, journal, checkpoint and export use the same projection. | +| 3. Parameter-file growth | One final managed override block replaces itself; only recognizable old generated suffixes are removed. Original Python code, comments, CRLF, encoding cookies and BOMs survive. Raw-data sentinel strings normalize to Python `None`. | +| 4. Eight-unit cap | Default 32, saved nonnegative setting; zero shows all and any positive integer is accepted. Display IDs and cache capacity are independent; truncation never changes merge membership. | +| 5. Legend | Removed outright from every metric axis. Authoritative cluster/Merge colors are retained. | +| 6. Camera action | Unit Stability captures its actual Qt FigureCanvas, retaining the usual screenshot path/naming/return contract. Regression tests trigger the screenshot action and inspect the PNG. Real capture also calls that same view method. | +| 7. Rate readability | Default saved width 0.6 points. Dataset-local display bins default to native resolution and permit aligned coarsening. Counts/exposure and finite measurement sums/counts add before division; zero exposure remains unavailable and final short edges are retained. | + +## Metadata compatibility and policy + +Imported values remain unchanged for untouched units, including legacy empty +strings and typed JSON values. New producer values are blank even when parent +values agree. New memberships are unreviewed; an explicit `705 = good` applies +to unit 705 until it is transformed again. No producer SNR, classifier, or +violation metric is recomputed or copied from a preferred parent. + +Layout descriptors validate filenames, columns, duplicate fields and collisions. +Typed JSON/table disagreement fails with file, field and unit context. Read-only +source aliases may be symlinks; output writes refuse symlink targets. Legacy +omitted-null rows and Python scalar representations remain readable, and old +blank values retain their canonical revision hashes. + +Version-1 event meaning is preserved. `BoundedSession.migrate_metadata()` records +an explicit policy transition, recovering source names from the exact original +source identity and revision. Saving creates a new immutable generation without +changing the base manifest, assignments, allocation IDs or review ledger. It +clears ambiguous resolved values on active derived units while retaining explicit +label journal intent. Already exported values without their earlier journal +cannot establish curator intent; they remain imported values rather than being +retroactively called explicit decisions. The guide includes migration usage. + +## Real-data acceptance + +The fixture is Carl's earlier converted engineering test export, computation +`b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`: 469,725,567 spikes, 705 original +units and a 112.859-hour elapsed clock. Its exposure declaration remains a test +conversion, not independently verified acquisition truth. Carl's newly mentioned +500-hour export was not available locally. + +Fresh outputs exercise: + +1. Accept `[40,44,48] -> 705` and `[49,50,51,53] -> 706` through the GUI + proposition workflow; assert producer fields and quality clear before explicit + good labels and a custom curator note are recorded. +2. Re-prepare, split 705 into 707/708 by a source-amplitude predicate, assert new + membership values clear, then explicitly label both children. +3. Re-prepare, merge 707/708 into 709, assert clearing again, then label 709. + +The independent Qt-free oracle checked every one of the 469,725,567 assignments +in **each round**, all unchanged source metadata cells, blank producer cells, +explicit group labels, and the two accepted review records. All 45 original +table filenames survive. The 91 remaining propositions remain pending. Params +are exactly **892 bytes in all three outputs**, with one managed block. +History grows from 5 to 8 to 11 records rather than losing parent decisions. + +The same oracle verified all **67 original download files** were unchanged and +**12 immutable files per output** matched the converted source. A separate copy +of the earlier reviewed bounded package was migrated: its manifest, assignments +and accepted reviews were unchanged; ambiguous producer values became blank and +explicit good labels on 705/706 survived. The data-only process exited zero. + +The combined GUI/data harness completed all assertions and printed PASS, then +exited 143 (SIGTERM). The signal's source is unknown; no traceback or verified +product termination path was found. This is retained as a combined-harness +limitation, not described as a clean process exit. Independent data verification, +the test suites, and both standalone capture processes exited normally. The +original independent checker also needed a harness-only fix to flatten column +cluster arrays before combining them with scalar amplitude masks; saved outputs +were unchanged and all rows were subsequently rechecked. + +## Display and regression checks + +Refreshed real captures use units 24, 26, 27 and 32, with no legend and 0.6-point +rate lines. The actual camera image is included in +`docs/images/unit-metadata-refinements/`. A generated **513-hour, twelve-unit** +fixture uses 6156 native five-minute bins and exact ten-minute display coarsening +to 3078 bins. It is synthetic stress coverage, not Carl's 500-hour data. + +Focused coverage includes metadata aliases/multi-column CSVs, typed values, +safe names and conflicts, blank legacy revisions, immutable old generation +reopen, migration identity, snapshot saves, policy event versions, provenance, +undo/redo, encoding/BOM/CRLF preservation, all display settings, actual camera +capture, cache limits, nonuniform-grid rejection, zero-exposure groups, merged +weighted means and final partial bins. + +Local verification ran `make test-full` (499 core + 431 application tests, one +existing benchmark skip), then the application target after two added symlink +regressions (433 passed). The final parameter/replay run passed 23 cases, +including two added encoding regressions. The final metadata run passed 24 cases, including two added structured-label +serialization regressions. This covers 936 distinct current tests; full CI runs the final tree together. Lint and format checks passed. +Documentation and wheel checks are recorded with the final handoff. + +`make doc-check` and `uv build` passed. The built wheel contains both new +runtime modules (`metadata.py` and `parameters.py`) with bytes matching the +working source. All refreshed image files were visually inspected. Source +symlink regressions skip only the specific Windows missing-privilege condition; +they run normally on systems supporting symlink creation. + +Local reports/scripts are under +`/home/cyrille/GIT/IBL/phy-data/carl/aind-b1b0782a-b3ea-4f34-81d7-b3c6e36452b3/pdf-metadata-validation/`. +Captures are in sibling `pdf-refinements-screenshots` and +`pdf-refinements-synthetic-513h` directories. Arrays and credentials are not +repository artifacts. diff --git a/design/unit-stability-comparison-validation.md b/design/unit-stability-comparison-validation.md new file mode 100644 index 000000000..a08b07fb6 --- /dev/null +++ b/design/unit-stability-comparison-validation.md @@ -0,0 +1,74 @@ +# Unit Stability comparison validation + +Carl's PR #1428 feedback requested independent metric visibility and comparison +of multiple clusters on long recordings. The view now overlays up to eight +selected units using authoritative selection colors, with saved firing-rate, +amplitude and depth toggles. The display limit does not change merge membership. +Existing preparation, export, journal and replay formats are unchanged. + +## Data and screenshots + +The real-data gallery uses the existing converted AIND test export from +computation `b1b0782a-b3ea-4f34-81d7-b3c6e36452b3`. Its clock spans +112.859 hours including gaps, with 113 summary bins and 705 source units. +This is the earlier local export, not Carl's newly mentioned 500-hour recording. +The conversion's acquisition mask remains unverified; these are software +integration checks, not scientific validation of exposure. + +Before and after captures select the same units, 40, 44 and 48, in a +2100 × 1200 Qt window. The baseline at `6ac9010d` displays only unit 40. +The new view displays all three, permits a full-height rate-only panel, and +preserves the same IDs and colors in Merge View. The authoritative table +presentation order is 40, 48, 44; colors follow that shared selection mapping. +Rate and amplitude are present; depth remains explicitly unavailable. + +The screenshot tool opens a disposable copy of the bounded package and checked +all 72 input file hashes remained unchanged. Full counts read from the source +summaries are 612,536 (40), 207,903 (44), and 336,413 (48). + +A separate generated 500-hour fixture contains 120,000 spikes, four units, +rate/amplitude/depth summaries and 1,000 bins. Each selected unit has exactly +30,000 source spikes. It supplies duration and missing-real-depth test coverage; +it must not be presented as Carl's 500-hour recording. + +Both capture processes exited normally after explicitly draining deferred Qt +deletions. Captures use Xvfb, Qt's X11 platform and software Mesa. Single runs, +concurrent with the test suite, measured selection/block at 0.372 s on the AIND +package and 0.623 s on the synthetic fixture. The two rate-only redraws together +took 0.094 s and 0.529 s respectively. These are observations, not benchmark +guarantees or CI timing thresholds. + +The gallery is in `docs/images/unit-stability-comparison/`. Reproduction options +are documented in `docs/long-recordings.md`; local capture manifests, source +hashes, scripts and logs are retained under +`/home/cyrille/GIT/IBL/phy-data/carl/stability-comparison/`. + +## Regression coverage and review + +Focused tests exercise exact per-unit rates with partial/zero exposure and a +short final bin, finite-value weighted merged means, pending split children +beside valid units, units without sampled evidence, row-at-a-time aggregation, +and absence of complete-spike-array reads in bounded mode. Rate-only loading +does not open trend arrays; toggle redraws reuse cached summaries. + +Selection tests cover normal/Similarity and Merge ordering, authoritative +colors, initial attachment during Merge mode, deferred hidden-view updates, +empty selection, frozen updates, display truncation, and merge/split undo/redo. +All eight metric visibility combinations retain stable axes/callback counts; +saved flags and QAction checks survive closing and reopening the view. +Ordinary optional Unit Stability retains its continuous-acquisition assumption +and refreshes cached counts on cluster edits. + +The implementation and existing adapter tests passed 25 focused cases. +An independent Sol 6.1-high audit found and reproduced a hidden-view palette +reset; the scoped fix and regression were included. Final review found no +remaining product blocker. A minimal standalone ordinary-GUI probe completed +all count assertions but exited 139 during interpreter teardown; repeating it +with explicit deferred Qt deletion exited normally. This remains a harness +cleanup limitation consistent with the earlier roundtrip record, not a verified +new product defect. + +Final local validation: `make test-full` passed 864 tests (499 core, 365 +application), with one existing benchmark skip; its lint and formatting checks +passed. `make doc-check` passed, including strict site generation and current +generated documentation. No packaging or dependency changes were made. diff --git a/docs/api.md b/docs/api.md index 07713a259..857ec4bd5 100644 --- a/docs/api.md +++ b/docs/api.md @@ -118,6 +118,7 @@ phy: interactive visualization and manual spike sorting of large-scale ephys dat * [phy.apps.capture_exceptions](#phyappscapture_exceptions) * [phy.apps.exceptionHandler](#phyappsexceptionhandler) * [phy.apps.BaseController](#phyappsbasecontroller) +* [phy.apps.CancelledError](#phyappscancellederror) * [phy.apps.FeatureMixin](#phyappsfeaturemixin) * [phy.apps.Path](#phyappspath) * [phy.apps.QtDialogLogger](#phyappsqtdialoglogger) @@ -1167,6 +1168,8 @@ A Qt main window containing docking widgets. This class derives from `QMainWindo **Events** close(gui) +close_accepted(gui) # Capture state after all vetoes, before state.save(). +closed(gui) # Emitted only after closure is accepted. show(gui) close_view(view, gui) @@ -7205,6 +7208,18 @@ is logically much simpler, and faster to execute. --- +#### Clustering.membership_snapshot + + +**`Clustering.membership_snapshot(self, cluster_ids)`** + +Read-only views of current per-unit original row IDs. + +Supported clustering operations replace these arrays, including undo; +retained snapshots therefore remain valid after subsequent edits. + +--- + #### Clustering.merge @@ -7269,6 +7284,19 @@ All changes are lost. --- +#### Clustering.restore_partition + + +**`Clustering.restore_partition(self, target, groups, *, new_cluster_ids=None)`** + +Restore an exact whole-unit partition into fresh, undoable clusters. + +``groups`` maps historical parent IDs to sorted spike rows. Historical +IDs identify provenance only; they are never revived as live IDs. +Validation and assignment touch only this unit's rows. + +--- + #### Clustering.spikes_in_clusters @@ -10117,6 +10145,13 @@ Component that brings manual clustering facilities to a GUI: Whether automatic navigation and similar-cluster selection skip noise and MUA clusters. The default is True. +* `clustering_factory : callable, optional` + Construct the clustering model. Defaults to Clustering; bounded curation + supplies a guarded implementation with the same constructor interface. + +* `cluster_meta_factory : callable, optional` + Construct metadata from groups and labels. Defaults to create_cluster_meta. + **Events** When this component is attached to a GUI, the following events are emitted: @@ -10380,6 +10415,18 @@ Reset the wizard. --- +#### Supervisor.restore_parents + + +**`Supervisor.restore_parents(self, target=None, *, groups=None, colors=None, new_cluster_ids=None)`** + +Restore earliest recorded merge components as real units in the Merge workspace. + +This is a new curation action; unrelated later edits are preserved. +Explicit groups and IDs support validated bounded semantic commands. + +--- + #### Supervisor.save @@ -12782,6 +12829,12 @@ peak channel. --- +### phy.apps.CancelledError + +The Future was cancelled. + +--- + ### phy.apps.FeatureMixin @@ -13249,6 +13302,15 @@ Create a trace view. --- +#### TemplateController.create_unit_stability_view + + +**`TemplateController.create_unit_stability_view(self)`** + +Optionally inspect selected-unit activity over the loaded recording. + +--- + #### TemplateController.create_waveform_view diff --git a/docs/changelog.md b/docs/changelog.md index 6f29ea4da..c97073283 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -11,13 +11,192 @@ been included in a stable release. The current entries cover all user-visible changes committed since 23 July 2026; test-only commits are represented by the behavior they verify rather than listed separately. +### Long recordings + +- RP summary builds retain only counters and shared exposure, with batches sized + to the configured memory budget. `prepare-large` checks RP budgets before + constructing the package and exposes `--rp-summary-memory-bytes`; both build + paths retain the 64 MiB defaults and report actionable budget errors. + +- Fix sampled correlogram `D` and `Shift+D` exclusion shortcuts when native + OpenGL canvas focus leaves widget focus in another dock. + +- Optional original-unit RP summaries and exact timestamp summary stores accelerate + refractory-period diagnostics, including offline merges and amplitude splits + against the verified prepared snapshot. Existing stores and authenticated source + fallback remain supported; scientific calculations and curation assignments + are unchanged. + +- Unit Stability adds live refractory-period contamination for visible selected + units, recomputed from original ticks and raw amplitudes after supported edits. + Its diagnostic deduplication never changes sorting assignments or exports; + missing evidence and background work have independent panel status. +- Cancelling a close/save prompt preserves the live merge workspace, selection + callbacks, status reporting and draft protection. GUI state collection and + resource cleanup now wait until closure is accepted. +- Bounded curation protects unsaved semantic edits in background recovery drafts, + separate from validated manual checkpoints. A fixed status-bar indicator shows + confirmed protection and checkpoint age; a passive Save checkpoint reminder + highlights after 15 minutes of unsaved work, with interval, snooze and disable + controls. Disabling reminders leaves draft protection active. +- Sampled correlogram axis labels identify active pending SLAY suggestions with + matching colors and a compact legend. Overlapping suggestions retain their + membership tooltips; trace colors keep their existing meaning. +- Sampled Correlogram View can exclude near-zero spike pairs before binning, + independently for auto- (`D`) and cross-correlograms (`Shift+D`). The exclusion + half-width defaults to 0.3 ms with both switches off. This changes displayed + pair counts and their chance reference; spike times, assignments and curation + history remain unchanged. +- Bounded curation applies new journal events to current state instead of replaying + every earlier merge after each edit. Metadata-only actions preserve assignments + and membership caches. Cached undo/redo uses affected rows within a 64 MiB + inverse-patch cache; evicted changes fall back to validated replay. Saves and loads + retain full independent journal validation. Metadata edits refresh affected table + rows and preserve unchanged stability plots; custom metrics remain refreshed. +- Mixed split/restore exports compile merge runs once for writing, while retaining + the sequential interpreter for independent output verification. +- Sampled correlograms show a thin chance line calculated from the same retained + observation windows. It is the mean off-center expected pair count, without + extrapolating full-recording firing rates or central-bin conventions. +- Moving the final eligible primary unit to good clears obsolete Similarity + candidates. Batch navigation no longer queues a mutation against an old primary + context. Parent colors now save with the default configuration directory. +- `Ctrl+Shift+Space` selects up to the preceding N eligible Similarity candidates + in current table order. Any Merge row, including the blue reference, can be + dragged to another row without changing the reference identity or color. + +- Preparation, replay, and summary-store/index CLI commands now report stage + progress, rate and ETA, support Ctrl-C cancellation, and offer bounded + parallel work with `--workers` (default 1). Summary accumulation uses capped + lookup tables and tiled histograms. Replay tries native copy-on-write clones + with a space-checked copy fallback, retaining source/output verification. + +- Right-clicking a sampled correlogram now transfers its row cluster between + primary and Similarity roles in bounded mode, with the same reference and + close/reopen behavior as ordinary correlograms. + +- Completed background preparation shows a clear terminal state with a Close + button. Task details remain available from **File > Show background task**. +- The curation comparison tool can run from a data directory or another checkout. + It records its own checkout revision, or `unknown` when Git metadata is unavailable. + +- Unit Stability automatically marks and omits rate bins with negligible recorded + time from the plotted trace, keeping tiny acquisition fragments from flattening + the rest of the rate plot. Exact summaries and saved curation remain unchanged. + +- Rapid candidate navigation preserves pending selection operations. Curation + actions settle the displayed selection before choosing targets and recording + undo history, including bounded merges, labels and quality assignments. + +- Background task cleanup tolerates Qt destruction order when closing Phy. + Detached workers finish without retaining Qt objects or sending callbacks to + deleted owners. Store-preparation dialogs clean up their preflight tasks too. + +- Prepared amplitude indexes accelerate full-recording rate and trend updates + after threshold splits without scanning every spike in the original units. + Existing stores can be upgraded from the GUI in the background or with + `build-amplitude-index`. Indexes preserve native threshold comparisons, + authenticate only the pages used, and fall back to verified rows when needed. + +- The bounded GUI offers to build missing summary stores in the background, + with a destination picker, independent disk budget, per-stage progress and ETA, + cancellation and task details. Curation remains available during construction; + completed stores take effect without reopening. Build and attach actions are + also available from File, with dataset-local prompt preferences. + +- Bounded split summaries can read only the original units needed from an + attached summary snapshot, rather than scanning the full recording. Shared + calculations and histogram accumulation also speed up the source fallback. + Background summary status now reports validation and scan progress. + +- Added optional, independently budgeted per-unit summary snapshot stores, with + build and attach commands for existing bounded packages. Stores preserve the + original scalar values and native time bins without changing saved curation. + +- SLAY merge suggestions and saved accept/reject decisions now survive bounded + curation, full-sorting replay, and subsequent preparation. Suggestions retain + their original IDs; pending suggestions affected by merges or splits become + stale rather than being silently reassigned. +- Fixed saving bounded amplitude splits after merge undo/redo when NumPy cluster + IDs appear in journal metadata. +- Bounded amplitude splits now recompute exact full-recording rates, counts and + available amplitude/depth trends in the background. Results combine on merges + and survive save/reopen through a disposable cache. Source validation, retry + and relocation controls preserve curation when the source is unavailable. +- Added `prepare-large` and `apply-curation` for bounded shared-window evidence, + full-duration exposure-aware summaries, semantic merges/labels/source-amplitude + splits, and replay into a new complete sorting. +- Added Unit Stability, precise window-relative amplitude/feature inspection, + sampled interval/correlogram views, and explicit full-versus-evidence counts. + Standard datasets retain their existing curation workflow and default layout. +- Bounded Evidence Amplitude now defaults to an all-retained-windows overview on + the recording clock, with a saved overview/window scope toggle. Inspecting a + window switches the view to that window. `Alt`-right-drag previews a source + amplitude threshold. `K` splits retained evidence and records the predicate; + `apply-curation` evaluates every source spike. Finite values strictly below + the threshold are selected; equality and nonfinite values stay in the remainder. +- Added source-grounded whole-output curation acceptance checks, with explicit + metadata-policy differences, saved-generation binding, and independent + all-source validation of cumulative merge and split predicates. Permanent controller + tests run the same actions through full and bounded modes across four rounds + and three sampling configurations, including points omitted from display. +- Unit Stability overlays up to 32 selected units by default, with consistent + colors and no legend. Its saved display limit accepts zero to show all selected + units, without a hard positive upper limit. Saved view settings include the + positive rate-line width (0.6 points by default) and the **Show firing rate**, + **Show amplitude**, and **Show depth** toggles, which default on. Its + dataset-local display-bin setting defaults to native resolution and permits + exact coarsening by integer multiples of the native bin width. The screenshot + action captures the Matplotlib Qt canvas. Full-source rates use acquisition + exposure, and split-child metrics show computation status until exact live + summaries are ready. On ordinary recordings, firing rates identify their + continuous-acquisition assumption. +- Bounded replay preserves producer metadata table filenames, delimiters, and + column layouts. New merge and split memberships clear producer values and + source IDs; quality labels are membership-scoped and start unreviewed until + assigned. Legacy journals retain inherited-metadata behavior until explicitly + migrated with the bounded session `migrate_metadata()` API. Replay parameter + overrides are kept in one managed final block while original source code + remains intact. +- Bounded saves use validated atomic generations and reject conflicting saves + from stale sessions. Unsupported selected-row splits are blocked. +- Sparse cluster IDs no longer require dense allocations during clustering. +- Bounded amplitude plots label seconds from window start and display the + window's recording-time range above the plot. +- Long-recording preparation accepts explicitly declared elapsed-tick + coordinates and can select whole validated producer evidence windows, while + keeping the existing spike and output-byte budgets. + ### Documentation - Documented uv-first installation of exact previous phy releases in separate environments, including how to intentionally replace a tool installation. +- Added a long-recording workflow guide covering bounded evidence preparation, + supported curation, full-sorting replay, and limits on interpreting sampled + measurements. ### Added +- **Restore parents in Merge Mode** restores an older merged unit's + earliest recorded merge components as real clusters without reversing + intervening unrelated edits. Nested merge chains restore all components in + one action, stopping at real split boundaries; old immediate-restore journals + keep their original replay semantics. It preserves nested ancestry across + save/reopen, uses fresh IDs with historical parent labels, and supports undo/redo and full-source bounded + replay. **Exclude current row** keeps a parent out of the pending merge; + read-only parent inspection remains available separately. + +- **Inspect parents (read-only)** opens an isolated comparison of a merged unit's + exact immediate parents, with consistent colors across available plots. + Ordinary merges record durable lineage; bounded merges use the saved journal. + Missing historical lineage is reported explicitly. An integrated dark workspace + pairs readable parent IDs/counts with color swatches and preserves pre-merge + colors when available. Back or Esc restores the curation workspace; editing + shortcuts are disabled during inspection. + +- Ctrl-click multiple SLAY merge suggestions to compare their deduplicated units + in one Merge workspace. Selection is read-only; an explicit merge records all + selected reviews atomically, with undo/redo restoring the combined workspace. - Select the preceding Similarity View batch with `Control+Shift+Space`, using the same saved batch size as `Control+Space`. - Drag the blue reference row anywhere in Merge View while preserving its @@ -40,7 +219,8 @@ behavior they verify rather than listed separately. - Record phy/phylib versions, checkout revisions and UTC timestamps in `phy.log` at startup and in dataset-local `phy_curation_history.jsonl` after successful - curation saves. `phy --version` now identifies the phy checkout itself. + curation saves, including bounded GUI checkpoint saves. `phy --version` now + identifies the phy checkout itself. - Added a standalone graphics diagnostic with embedded coding-agent instructions, selectable probes, synthetic selection tests and screenshots, crash/hang logs, @@ -120,6 +300,23 @@ behavior they verify rather than listed separately. ### Fixed +- Require PyQt5-sip 12.20.1 or later to avoid native shutdown crashes when + Qt cleanup callbacks create or destroy wrapped objects. + +- Table mouse handlers verify the Qt event class before accessing mouse-only + methods, preventing exceptions from generic or mismatched event wrappers + during context-menu interaction. +- Accepted SLAY suggestions return to their accepted display state when their + complete recorded membership is remerged after parent restoration. Partial + reassembly remains historical; additional membership is accepted-modified. + +- Keep summary-store finalization warnings visible even when the destination + path is long; the full path remains in Details and the tooltip. + +- Action prompts and snippets accept negative numbers, scientific notation, and + comma-separated negative values without confusing their signs with ID ranges. +- On macOS, horizontal table scrollbars reserve space so the last cluster row + remains fully visible when scrolling to the bottom. - Settle pending table selections before curation actions and discard obsolete candidate updates after reference changes. Moving the final selected cluster to a quality group clears Similarity View before subsequent batch selection. diff --git a/docs/cli.md b/docs/cli.md index 0bb61a764..16b554a1f 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -25,6 +25,35 @@ GUI commands accept: --clear-cache remove and rebuild the dataset .phy cache ``` +## Long recordings + +Prepare bounded evidence, curate it with `template-gui`, then replay supported +actions into a new full sorting. See the [long-recording guide](long-recordings.md) +for input requirements, interpretation limits, and the complete workflow. + +```bash +phy prepare-large /data/recording/params.py /data/recording-bounded \ + --duration 3600000 \ + --valid-intervals /data/recording/valid-intervals.npy \ + --max-spikes 2000000 \ + --max-bytes 536870912 \ + --window-seconds 30 \ + --stratum-seconds 3600 \ + --seed 0 \ + --bin-seconds 3600 \ + --batch-size 100000 + +phy template-gui /data/recording-bounded/params.py + +phy apply-curation /data/recording/params.py /data/recording-bounded \ + /data/recording-curated --batch-size 100000 +``` + +`--duration` is acquisition duration in seconds. `--valid-intervals` reads an +integer `.npy` array of `[start, end)` sample pairs. `--max-bytes` caps the +prepared package size, not process memory. The output directories must be new; +the original sorting remains the replay parent. + ## Raw trace viewer ```bash diff --git a/docs/clustering.md b/docs/clustering.md index c0552ea7f..dccbc6598 100644 --- a/docs/clustering.md +++ b/docs/clustering.md @@ -20,14 +20,13 @@ selection. Cluster View is dimmed and read-only while the workspace is active, b scrollable; its overlay reminds you that `V` returns to the normal workflow. Every row in Merge View is part of the pending merge. Continue exploring Similarity View, where -sorting, filtering, `Control+Space`/`Control+Shift+Space`, and multi-selection remain available. -The Merge View status shows the number of staged clusters, selected similar clusters, and the -total that `G` will merge. +sorting, filtering, `Control+Space`, `Control+Shift+Space`, and multi-selection remain available. +The Merge View status shows the number of staged clusters, selected similar clusters, and the total that `G` will merge. Move candidates between the two views with right-click or drag-and-drop. Drag within -Merge View to reorder any row, including the blue reference. Reordering preserves the reference -identity and every cluster's color. The blue reference can also be transferred when another -staged row remains. The first remaining row then becomes the blue reference and +Merge View to reorder any staged row, including the blue reference. Reordering preserves the +reference identity and color. The reference can be transferred when another staged row remains. +The first remaining staged row then becomes the blue reference and the old reference remains selected in Similarity. The final staged row cannot be transferred, and the selection order shown by scientific views is always the Merge View order followed by selected Similarity View rows in visible table order. Transfers, table sorting, and Merge reordering redraw @@ -72,6 +71,19 @@ derived from `P12`; this release does not generate derived proposition rows. Click a pending row to stage it in Merge View immediately; this atomically replaces any manual or proposition workspace already open in the same dock. Clicking a completed, stale, or invalid row cancels any active workspace and only highlights that row. + +Use **Ctrl+left-click** to add or remove pending suggestions from the selection. +Their units appear together in one Merge workspace, with shared units included +once and the first selected suggestion supplying the reference order. Plain +click selects one suggestion again. Selecting suggestions only changes the +comparison; it does not modify spike assignments or mark reviews accepted. +Clearing the selection or cancelling restores the Normal selection from before +review. Completed or stale suggestions cannot be mixed into a combined review. + +Pressing `G` explicitly merges the displayed combined set and records each +selected suggestion's acceptance in one undoable operation; a changed candidate +set is marked `accepted_modified`. Unselected suggestions are never accepted +automatically. Reject and reset shortcuts require a single selected suggestion. You can still add, remove, and reorder candidates in a pending review. `Alt+Down` and `Alt+Up` replace the current workspace with the next or previous pending proposition in the current visible table order, wrapping at either end. @@ -221,3 +233,83 @@ cluster_id neurontype ## Undo and redo You can undo and redo clustering actions (merge, split, move, label) with the **Control+Z** and **Control+Y** keyboard shortcuts. + +## Restore a merged unit's parents + +Select a merged unit and choose **Restore parents in Merge Mode** from its +Cluster View context menu or the View menu. Phy restores its earliest recorded merge +components as real clusters and stages them in the existing Merge workspace. +For example, merge `1 + 2 → 100`, then `100 + 3 → 101`: restoring `101` +stages the equivalents of `1`, `2` and `3` in one action. This +works after intervening curation actions and after saving and reopening the same +dataset. Later unrelated merges, labels and review decisions are preserved. + +Restored clusters receive fresh IDs. The Merge table's parent-origin column +shows their historical IDs, and their comparison colors are retained where known. +New memberships start unclassified; the merged unit's quality or custom labels +are not silently copied to every parent. Historical SLAY decisions remain +recorded and show that their accepted result was subsequently restored. When +the complete accepted membership is merged again, the suggestion returns to its +accepted status. Adding further membership shows accepted-modified; partial +reassembly remains historical. Previously modified acceptances retain their +recorded scope and are not silently reinterpreted. + +Compare the parents, add further Similarity candidates, and press `G` to merge +the chosen combination. To leave a parent separate, click its Merge row and +use **Exclude current row**. Right-click still transfers a row to Similarity and +leaves it selected; `G` includes selected Similarity rows as well as staged rows. +The Merge status shows the total that will be merged. + +Restoration is one new undoable action. Undo reverses the restoration without +reversing earlier unrelated work; Redo restores its Merge workspace. Pressing +`V`, cancelling, or closing Merge View leaves the restored clusters intact and +returns to Normal mode. Normal-mode splitting and quality/label tools remain +available there. Saving stores the actual curation; transient Merge staging is +not automatically reopened. + +Exact recorded ancestry is required. Earlier ordinary merges without lineage, +changed or corrupt partitions, and bounded parents without retained evidence +are unavailable with an explanation. Nested merge ancestry is expanded all at +once, stopping at genuine split boundaries or unknown earlier ancestry. A known +merge with missing or inconsistent descendants rejects the entire restore before +changing assignments. Editable restoration is not limited to the read-only +comparison's 16-parent limit; every restored component appears in Merge View. +Historical IDs are labels, while fresh live IDs preserve unambiguous history. + +Bounded restoration records an exact operation for full-source replay, including +parents formed by earlier source-amplitude splits. It never substitutes sampled +spike membership for full-recording membership. Save/reopen within the same +bounded package retains this history. After full replay and a fresh preparation, +restored live children remain available, but historical merges from before that +preparation cannot be restored: the new package has no recoverable parent anchor. Older +bounded clients cannot read journals containing the new recursive restoration +operation. Existing immediate-parent restoration events keep their original +meaning on reopen and replay. + +## Inspect a merged unit's parents + +Right-click a merged unit in Cluster View and choose **Inspect parents (read-only)**. A dark, +read-only workspace inside the main window compares its immediate parents. +A parent table uses white IDs and counts with colored swatches; the same colors +identify each parent in the correlogram, waveform, amplitude, and feature plots. +New merges preserve the colors used before merging when that information is +available. Earlier merges use a consistent fallback palette. + +Available plots depend on the dataset's stored evidence. Click **Back**, press +**Esc**, or select another cluster to restore the curation workspace. Editing +shortcuts are disabled during inspection. Inspection does not change assignments, +labels, review decisions, or undo history. + +Ordinary datasets record exact parent membership for merges made with this +version, including after splits, and save it in `_phy_merge_parents.npz`. +Keep that file with the dataset. Earlier merges without recorded lineage cannot +be reconstructed reliably and have **Show parents** disabled. Bounded datasets +recover the exact retained parent groups from their saved curation journal, +without scanning the original recording. + +The comparison supports up to 16 immediate parents. It follows the existing +per-view spike budgets; ordinary correlograms can be sampled. Bounded plots show +retained-window evidence, with full counts shown separately when known. +Split-derived full counts may be unavailable. When raw/stored waveforms are +unavailable, explicitly labeled template traces show up to 100 templates per +parent. This command inspects parents; it does not undo the merge. diff --git a/docs/customization.md b/docs/customization.md index 0472b20fb..b7bc7cef0 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -291,7 +291,11 @@ template_gui('params.py') The existing `close` event can be vetoed by a save prompt. Use `connect(callback, event='closed', sender=gui)` for cleanup that must happen only -after closure is accepted. A cancelled prompt emits no `closed` event. +after closure is accepted. To collect GUI state before it is written to disk, +use `close_accepted` instead. It runs after every close veto has been checked +and before the state save. A cancelled prompt emits neither event. Keep +destructive cleanup out of `close` callbacks: all callbacks for that event run +even when another callback vetoes closure. Trace views keep their `traces(interval)` provider contract. Explicit navigation emits `trace_navigation(view, interval, direction, phase, serial)`: `direction` is diff --git a/docs/images/amplitude-index-task/building.png b/docs/images/amplitude-index-task/building.png new file mode 100644 index 000000000..29512ff19 Binary files /dev/null and b/docs/images/amplitude-index-task/building.png differ diff --git a/docs/images/amplitude-index-task/indexing.png b/docs/images/amplitude-index-task/indexing.png new file mode 100644 index 000000000..33ab28802 Binary files /dev/null and b/docs/images/amplitude-index-task/indexing.png differ diff --git a/docs/images/amplitude-index-task/prompt.png b/docs/images/amplitude-index-task/prompt.png new file mode 100644 index 000000000..86881750e Binary files /dev/null and b/docs/images/amplitude-index-task/prompt.png differ diff --git a/docs/images/amplitude-index-task/ready.png b/docs/images/amplitude-index-task/ready.png new file mode 100644 index 000000000..be363705a Binary files /dev/null and b/docs/images/amplitude-index-task/ready.png differ diff --git a/docs/images/amplitude-main-gui/main-reopened.png b/docs/images/amplitude-main-gui/main-reopened.png new file mode 100644 index 000000000..6d09833a2 Binary files /dev/null and b/docs/images/amplitude-main-gui/main-reopened.png differ diff --git a/docs/images/amplitude-main-gui/main-threshold-preview.png b/docs/images/amplitude-main-gui/main-threshold-preview.png new file mode 100644 index 000000000..af6f834fd Binary files /dev/null and b/docs/images/amplitude-main-gui/main-threshold-preview.png differ diff --git a/docs/images/amplitude-threshold-workflow/amplitude-after.png b/docs/images/amplitude-threshold-workflow/amplitude-after.png new file mode 100644 index 000000000..5f13a31ed Binary files /dev/null and b/docs/images/amplitude-threshold-workflow/amplitude-after.png differ diff --git a/docs/images/amplitude-threshold-workflow/amplitude-before.png b/docs/images/amplitude-threshold-workflow/amplitude-before.png new file mode 100644 index 000000000..397411ccd Binary files /dev/null and b/docs/images/amplitude-threshold-workflow/amplitude-before.png differ diff --git a/docs/images/amplitude-threshold-workflow/amplitude-preview.png b/docs/images/amplitude-threshold-workflow/amplitude-preview.png new file mode 100644 index 000000000..4d1fddd6d Binary files /dev/null and b/docs/images/amplitude-threshold-workflow/amplitude-preview.png differ diff --git a/docs/images/live-summaries/after-split.png b/docs/images/live-summaries/after-split.png new file mode 100644 index 000000000..9601d9307 Binary files /dev/null and b/docs/images/live-summaries/after-split.png differ diff --git a/docs/images/live-summaries/before-split.png b/docs/images/live-summaries/before-split.png new file mode 100644 index 000000000..612efe3ae Binary files /dev/null and b/docs/images/live-summaries/before-split.png differ diff --git a/docs/images/live-summaries/recomputing.png b/docs/images/live-summaries/recomputing.png new file mode 100644 index 000000000..f275c1c5c Binary files /dev/null and b/docs/images/live-summaries/recomputing.png differ diff --git a/docs/images/long-recording-evidence.png b/docs/images/long-recording-evidence.png new file mode 100644 index 000000000..294d03924 Binary files /dev/null and b/docs/images/long-recording-evidence.png differ diff --git a/docs/images/long-recording-overview.png b/docs/images/long-recording-overview.png new file mode 100644 index 000000000..cfd729bf7 Binary files /dev/null and b/docs/images/long-recording-overview.png differ diff --git a/docs/images/rate-coverage/after.png b/docs/images/rate-coverage/after.png new file mode 100644 index 000000000..f21c6378b Binary files /dev/null and b/docs/images/rate-coverage/after.png differ diff --git a/docs/images/rate-coverage/before.png b/docs/images/rate-coverage/before.png new file mode 100644 index 000000000..9c6b26920 Binary files /dev/null and b/docs/images/rate-coverage/before.png differ diff --git a/docs/images/summary-store-task/building.png b/docs/images/summary-store-task/building.png new file mode 100644 index 000000000..9254d3497 Binary files /dev/null and b/docs/images/summary-store-task/building.png differ diff --git a/docs/images/summary-store-task/prompt.png b/docs/images/summary-store-task/prompt.png new file mode 100644 index 000000000..4ffccd33c Binary files /dev/null and b/docs/images/summary-store-task/prompt.png differ diff --git a/docs/images/summary-store-task/ready.png b/docs/images/summary-store-task/ready.png new file mode 100644 index 000000000..2ebbd15a0 Binary files /dev/null and b/docs/images/summary-store-task/ready.png differ diff --git a/docs/images/unit-metadata-refinements/carl-camera.png b/docs/images/unit-metadata-refinements/carl-camera.png new file mode 100644 index 000000000..0ec124cbb Binary files /dev/null and b/docs/images/unit-metadata-refinements/carl-camera.png differ diff --git a/docs/images/unit-metadata-refinements/carl-coarsened-rate.png b/docs/images/unit-metadata-refinements/carl-coarsened-rate.png new file mode 100644 index 000000000..a880270ad Binary files /dev/null and b/docs/images/unit-metadata-refinements/carl-coarsened-rate.png differ diff --git a/docs/images/unit-metadata-refinements/carl-native-rate.png b/docs/images/unit-metadata-refinements/carl-native-rate.png new file mode 100644 index 000000000..46175875b Binary files /dev/null and b/docs/images/unit-metadata-refinements/carl-native-rate.png differ diff --git a/docs/images/unit-metadata-refinements/synthetic-513h-coarsened.png b/docs/images/unit-metadata-refinements/synthetic-513h-coarsened.png new file mode 100644 index 000000000..c09fc1d2a Binary files /dev/null and b/docs/images/unit-metadata-refinements/synthetic-513h-coarsened.png differ diff --git a/docs/images/unit-metadata-refinements/synthetic-513h-native.png b/docs/images/unit-metadata-refinements/synthetic-513h-native.png new file mode 100644 index 000000000..afb66fbbf Binary files /dev/null and b/docs/images/unit-metadata-refinements/synthetic-513h-native.png differ diff --git a/docs/images/unit-stability-comparison/after-merge.png b/docs/images/unit-stability-comparison/after-merge.png new file mode 100644 index 000000000..79d632f23 Binary files /dev/null and b/docs/images/unit-stability-comparison/after-merge.png differ diff --git a/docs/images/unit-stability-comparison/after-overview.png b/docs/images/unit-stability-comparison/after-overview.png new file mode 100644 index 000000000..be2aa1aae Binary files /dev/null and b/docs/images/unit-stability-comparison/after-overview.png differ diff --git a/docs/images/unit-stability-comparison/after-rate-only.png b/docs/images/unit-stability-comparison/after-rate-only.png new file mode 100644 index 000000000..457b1b4e5 Binary files /dev/null and b/docs/images/unit-stability-comparison/after-rate-only.png differ diff --git a/docs/images/unit-stability-comparison/before-overview.png b/docs/images/unit-stability-comparison/before-overview.png new file mode 100644 index 000000000..74ebcc426 Binary files /dev/null and b/docs/images/unit-stability-comparison/before-overview.png differ diff --git a/docs/images/unit-stability-comparison/synthetic-500h-overview.png b/docs/images/unit-stability-comparison/synthetic-500h-overview.png new file mode 100644 index 000000000..a93b42325 Binary files /dev/null and b/docs/images/unit-stability-comparison/synthetic-500h-overview.png differ diff --git a/docs/long-recordings.md b/docs/long-recordings.md new file mode 100644 index 000000000..5bc03e726 --- /dev/null +++ b/docs/long-recordings.md @@ -0,0 +1,893 @@ +# Curating long recordings + +Phy's long-recording workflow prepares a bounded evidence dataset for interactive +review, then replays supported curation actions against the complete local +sorting. Preparation reads source arrays in batches; it does not load the full +sorting into the GUI. The source dataset is retained unchanged, and replay +writes a separate output dataset. + +This workflow supports a single monotonic event axis. Existing sources without +an explicit time-base declaration use `acquisition_samples`, the legacy +fixed-rate sample-coordinate contract. Sources with `time_base` may instead +declare `elapsed_ticks`: nonnegative integer elapsed-time coordinates with a +declared `ticks_per_second`. In either case, `num_samples` is the exclusive +upper bound of the canonical coordinate axis, and `valid_intervals` are +half-open `[start, end)` intervals on that same axis. For elapsed ticks, +`num_samples` is a tick bound, not a physical frame count. Explicit elapsed +sources must provide authoritative valid intervals; Phy cannot infer +acquisition gaps or filler from periods with no spikes. Multi-segment recordings +are not supported. + +The `time_base` declaration is a dictionary such as +`{'kind': 'elapsed_ticks', 'ticks_per_second': 30000.0}` in `params.py` (or +`recording.time_base` in the waveform manifest). For this workflow, +`ticks_per_second`, `sample_rate`, and the physical waveform sample rate must +be equal. Unequal event and waveform rates need separate waveform-axis support. +A source containing `timestamps.json` must declare its coordinate contract +explicitly; Phy does not parse that file to guess a conversion. Elapsed ticks +cannot index raw voltage, so an elapsed source with a real `dat_path` is not +supported. Stored waveforms can be used without raw data. + +For explicit elapsed exports, the waveform manifest must declare +`recording.sample_index_coordinates` and +`recording.window_bounds_coordinates` as `elapsed_ticks` when those sidecars are +present. The waveform-aligned `sample_index[w]` must equal +`spike_times[subset_spikes[w]]`; it is neither a source row ID nor a raw frame +offset. The manifest's `sample_index_coordinates` and +`window_bounds_coordinates` must each equal the declared `time_base.kind`. +Producer window bounds describe canonical elapsed coordinates and must not +cross unsupported gaps. The 512 MiB output cap applies to package bytes, not +process RSS; waveform source, retained, and omitted counts are reported in the +CLI and manifest. + +The screenshots below show the bounded GUI views using a deterministic +synthetic eight-hour sorting. These captures document the interface before +the latest Unit Stability display refinements; their unit cap and legend are +historical. The overview plots full-duration rates and +available source means; gray marks the synthetic acquisition gap and cyan marks +the retained evidence windows. The evidence view places windowed amplitudes at +top left, sampled ISI at top right, sampled correlograms at middle right, and +features below. They illustrate the interface and its sampling context; they +are not biological data or scientific examples. + +![Full-duration Unit Stability with a synthetic acquisition gap](images/long-recording-overview.png) + +![Windowed source amplitudes, features, sampled ISI and correlogram](images/long-recording-evidence.png) + +Recreate these images from source with Qt's X11 platform and software OpenGL +(the script writes a temporary synthetic source and bounded package): + +```bash +QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 \ + xvfb-run -a -s '-screen 0 2400x1600x24 +extension GLX' \ + uv run python tools/capture_long_recording_views.py +``` + +### Refractory-period contamination + +Unit Stability's fourth panel estimates contamination for the current selected +units. It uses original integer ticks and raw source amplitudes, including spikes +outside the sampled evidence windows. After a merge, source-amplitude split, +parent restoration, Undo/Redo or reopening, it follows the current membership. +Removing a merge candidate affects the selection used by the subsequent merge. +Diagnostic duplicate removal changes neither sorting assignments nor exports. + +The fixed calculation matches the [phytastic reference](https://github.com/goatsofnaxos/phytastic/tree/992b2588729a5f1e4f16bd745f8cf5db6b1866a3/reference/rp-contamination): +remove spikes within 0.3 ms by descending absolute source amplitude (earlier +spikes win ties), then count every later pair with 0.3 ms < interval ≤ 1 ms. +Pairs belong to the earlier spike's bin. Deduplication uses complete chained +components across input boundaries. Signed amplitudes remain the input to +source-amplitude membership splits. Nonfinite or missing scores are unavailable. + +The scientific grid is always 30-minute bins, with centered six-hour windows +every hour and a dashed 10% guide. Display-bin controls do not change it. Periods +use Python sample rounding; the final padded bin can add a center beyond the +recording end. Exposure comes from declared recording duration and valid +intervals; gaps reduce recorded time without resetting spike-pair counting. +Ordinary datasets need authoritative `num_samples` and compatible clock/exposure +metadata; the last spike does not establish recording duration. + +Windows with fewer than 1,000 spikes after deduplication have no estimate. Low +violation counts are uncertain, adjacent windows overlap, and changing unit +activity within a window affects interpretation. A value of 100% is estimator +saturation, not certainty that every spike is a contaminant. The panel makes no +automatic clean/contaminated classification. + +Only displayed selected units request work while the panel is enabled and +visible. Pending, unavailable or failed RP work leaves the other evidence panels +usable. Unless optional prepared RP artifacts are available (below), original +source files must remain available and unchanged. Full content +authentication and scanning run in a background worker and may take seconds or +longer for large recordings. A bounded 256 MiB in-memory original-unit tick cache +accelerates repeated merges and splits; larger or evicted memberships use the +verified full-source fallback. Completed curves have a separate bounded cache. +Caches are disposable and are rebuilt after reopening the view. Computation +reports unavailable if an exact unresolved duplicate component exceeds its +memory budget; no approximate curve is substituted. + +### Preparing RP acceleration + +Both RP capabilities are opt-in. To prepare original-unit RP summaries and a +separate row store containing exact timestamps: + +```bash +phy prepare-large /data/full/params.py /data/bounded \ + --rp-summaries --summary-store /data/summary-store --store-timestamps +``` + +To add either capability to an existing bounded package: + +```bash +phy build-rp-summaries /data/bounded +phy build-summary-store /data/bounded /data/new-summary-store --timestamps +``` + +`--rp-summaries` does not require a row store. It writes small original-unit +results under `.phy/refractory-summaries`, with a pinned catalog reference in +`.phy/refractory-summaries.json`. Counts use the RP calculation's fixed 30-minute +grid, independently of the configurable native summary bins. Complete duplicate +components and later partners span source batches and bin boundaries. Counters +from different original units cannot be added to calculate a merge. + +The single-pass counter builder retains only two int64 counters per unit/bin. +It shares acquisition exposure across units, updates only touched bins, and +serializes each unit as it completes. A shared resource planner caps effective +batch sizes against explicit memory and disk budgets. After source discovery and +authentication, preparation checks these budgets before constructing the bounded +package. The standalone builder checks before authenticating/scanning source +arrays. The algorithm allocation +budget is not a hard process-RSS limit: Python and NumPy overhead and mapped +source pages require additional memory. If an exact duplicate component cannot +fit its planned allocation, that unit may be marked unavailable while other +units are still prepared. + +Both budgets default to 64 MiB. For `prepare-large`, set them with +`--rp-summary-max-bytes` (disk) and `--rp-summary-memory-bytes` (memory). For +standalone `build-rp-summaries`, use `--max-bytes` and `--memory-bytes`: + +```bash +phy build-rp-summaries /data/bounded --max-bytes 67108864 --memory-bytes 67108864 +``` + +`--timestamps` adds exact integer offsets relative to the actual native bin +starts. The smallest unsigned integer width that fits every bin span is used; +signed source amplitudes retain their original dtype, including float64 precision. +For 30 kHz and 30-minute bins, offsets need four bytes per spike: 6.75 billion +spikes add 27 GB (decimal), before catalog overhead. Other fields and wider bins +change the total; store estimates and byte-budget checks include the offsets. +Existing stores without timestamps remain readable by rate/amplitude summaries +and retain the RP source fallback. + +RP uses original-unit summaries first, then timestamp rows for originals, merges +and supported amplitude-threshold histories, including nested edits, parent +restoration and undo/redo. Membership filters run before diagnostic deduplication. +Timestamp queries stream only the selected original ancestors, with bounded +chronological merging rather than a recording-sized concatenation and sort. +Template-based predicates require the original source. With source unavailable, +such requests report unavailable; timestamp rows do not imply template support. + +**Offline results describe the authenticated prepared snapshot**, including its +source identity, assignment revision, scientific algorithm, sample rate, +duration, valid intervals and grids. They do not certify the current contents of +the original files. Supported requests do not open, stat or hash those files. +Prepared unit payloads are verified before derived results are published; +corruption or missing capabilities retains the authenticated original-source +fallback. Changed references or row-file signatures invalidate timestamp caches. +To reconnect a copied timestamp store, use `phy attach-summary-store` with its +new path. RP counters travel with the bounded package. + +Timestamp query scratch uses the reader's existing 64 MiB allowance, plus +one accumulator's bounded component state. Prepared query result grids have +a separate 8 MiB limit; oversized requests report unavailable. Existing store +budgets and cancellation checks continue to apply. + +Artifacts publish atomically and never overwrite an existing artifact directory. +Optional preparation failure preserves the completed bounded package; retry via +the corresponding build command. A later I/O failure also leaves a ready package +intact. Preparation and RP queries do not change saved +assignments, curation history or exports. The store-building commands still +prepare the amplitude index by default; `--rows-only` skips that separate index. + +For reproducible measurements on a disposable package copy, run +`tools/benchmark_refractory.py` in separate processes for `source`, +`build-counters`, `counters`, `build-timestamps` and `timestamps`. Supply +`--output report.json`, and `--store` for the timestamp builder. The report +includes authentication bytes, timestamp query bytes, peak process memory, +first-query and repeated-query timings, result fingerprints and cancellation +latency. Use `--membership merge` or `--membership amplitude-child` in a fresh +process to include first-use source authentication for those cases; the default +`--membership all` retains the reader across cases. OS cache state is +uncontrolled; a fresh process is not a cold disk. + + +### Comparing clusters on a real recording + +These actual Qt captures use the same converted AIND test export, selected +clusters **40, 44, and 48**, 113 summary bins, and 2100 × 1200 window size. +The elapsed clock spans 112.9 hours including declared gaps. Rate and source +amplitude are available; depth trends are unavailable. The exposure mask is +the test conversion's declaration, not independent acquisition verification. + +| Before: only unit 40 displayed | After: all three selected units | +| --- | --- | +| ![Before: three selected clusters but one stability curve](images/unit-stability-comparison/before-overview.png) | ![After: selected cluster rate and amplitude overlays](images/unit-stability-comparison/after-overview.png) | + +Turning off **Show amplitude** and **Show depth** expands the rate comparison: + +![Rate-only comparison of units 40, 44 and 48](images/unit-stability-comparison/after-rate-only.png) + +These captures predate the current Unit Stability display refinements; the +overlaid rates remain representative, while any legend or unit-display limit +visible in them is historical. The same colors and cluster IDs follow the staged +Merge candidates: + +![Merge View candidates match the firing-rate curves](images/unit-stability-comparison/after-merge.png) + +To capture an existing package, use a fresh output directory outside it. The +script opens a temporary copy and verifies the input file hashes are unchanged: + +```bash +QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 \ + xvfb-run -a -s '-screen 0 2400x1600x24 +extension GLX' \ + uv run python tools/capture_long_recording_views.py --comparison \ + --bounded-dir /data/recording-bounded --cluster-ids 40 44 48 \ + --dataset-label 'Recording test export' --output-dir /tmp/stability-captures +``` + +A separate [synthetic 500-hour example](images/unit-stability-comparison/synthetic-500h-overview.png) +exercises rate, amplitude, and depth together over 1000 bins. It is generated +test data, not Carl's 500-hour recording. Reproduce it with `--comparison +--synthetic-hours 500 --output-dir /tmp/stability-500h` instead of `--bounded-dir` +and `--cluster-ids`. + +### Latest display refinements + +The following captures show the current controls on Carl's earlier converted +112.9-hour test export, with units **24, 26, 27, and 32**. The camera image was +saved through Unit Stability's own screenshot action. Legends are removed and +native rate lines use the new 0.6-point default. Declared exposure remains the +conversion's test mask, not independent acquisition verification. + +![Camera capture with no legend and thin rate lines](images/unit-metadata-refinements/carl-camera.png) + +A separate generated 513-hour fixture displays twelve selected units with +6156 native five-minute bins. Selecting ten-minute display bins groups these +into 3078 bins by adding counts/exposure and measurement sums/counts; prepared +files remain unchanged. This is generated test data, not Carl's 500-hour export. + +| Native five-minute bins | Ten-minute display bins | +| --- | --- | +| ![Twelve synthetic units at native resolution](images/unit-metadata-refinements/synthetic-513h-native.png) | ![The same units with exact display coarsening](images/unit-metadata-refinements/synthetic-513h-coarsened.png) | + +Reproduce the generated stress captures with `--comparison --synthetic-hours +513 --synthetic-units 12 --summary-bin-seconds 300 --output-dir +/tmp/stability-513h`. The capture script also exercises the view's camera action +and writes `camera-rate-only.png`. Display coarsening starts at the native +prepared resolution; it never changes preparation's default bin size. + +## Prepare bounded evidence + +Run `prepare-large` with the source `params.py` and a new output directory: + +```bash +phy prepare-large /data/recording/params.py /data/recording-bounded \ + --duration 3600000 \ + --valid-intervals /data/recording/valid-intervals.npy \ + --max-spikes 2000000 \ + --max-bytes 536870912 \ + --window-seconds 30 \ + --stratum-seconds 3600 \ + --seed 0 \ + --bin-seconds 3600 \ + --batch-size 100000 +``` + +Preparation, summary-store/index construction, and replay print throttled +per-stage progress to stderr, including processed counts, elapsed time, rate, +and ETA when a total is known. Ctrl-C cancels the operation; a partially written +sorting or index is not published. An already completed row snapshot can remain +available if subsequent index construction is cancelled. + +These four CLI commands accept `--workers 1` through `--workers 32` (default +`1`). For example, add `--workers 4` to try parallel file hashing, summary +accumulation, row packing, and independent per-unit index construction. Work +queues are bounded, and configured scratch budgets are shared across workers. +More workers can help large workloads on fast storage but can slow smaller +jobs or increase I/O contention; choose using a representative local run. + +`--duration` is in seconds and must agree with declared acquisition metadata. +The `.npy` valid-interval file contains an integer array of shape `[W, 2]` with +ordered, nonoverlapping coordinate pairs. Without it, legacy acquisition-sample +sources treat the full declared extent as valid exposure. Explicit elapsed +sources require authoritative `valid_intervals` in metadata or supplied +explicitly through the CLI/API; there is no full-extent +default for them. + +`--max-bytes` limits the bounded output package size, including its summaries and +window plan. It is not a process-memory or peak-RSS limit. The source unit IDs +must fit nonnegative `int32`; sample coordinates and full-source spike row IDs +use `int64`. + +Preparation uses `--window-policy auto` by default. When validated producer +windows are available, it selects among those whole windows and preserves their +acquisition boundaries. Producer-window mode requires valid producer windows; +it does not generate rescue windows to compensate for missing or malformed +producer evidence. Without producer windows, the original shared-window planner +uses the configured window length, strata, and seed. Inspect the saved window +plan in the output package when documenting or repeating an analysis. +Windows that exceed the budget are omitted, so a high-density interval can +reduce retained evidence. Preparation does not shorten an over-budget window or +silently thin spikes inside it. The generated planner supplements its survey of +shared windows with deterministic rescue evidence for units missed by the +survey. This improves the chance of seeing rare units, but makes the evidence +selection unequal: rescue windows must not be treated as a probability sample. +The explicit `producer` policy uses only producer windows. The `auto` policy +can supplement producer windows with generated rescue evidence for units still +missing from the selected evidence. + +Overlapping producer windows are allowed; selection uses their union while +retaining their acquisition boundaries. Preparation records exact +full-recording spike counts and rates using valid exposure. If source scalar +amplitudes or depths are available, it +also records per-bin finite-value means and availability counts. It does not +invent missing measurements or convert source values to physical units. Stored +waveforms are included only where available in the source; raw traces are not +required when stored waveform data are sufficient for the views being used. +The default spike and byte budgets remain 2,000,000 spikes and 512 MiB. Output +byte budgets describe package bytes, not resident memory. Waveform availability +can exceed the bounded output budget: preparation reports waveform counts +retained, omitted, and available in the source on the CLI, and stores the counts +in the manifest so truncation is visible. +Producer metadata tables retain their source filenames, delimiters, and column +order, including multi-column CSV files. For a new merge or split membership, +producer values and source-unit IDs are blank; imported custom fields are also +cleared. Quality labels belong to the current unit +membership: a new membership starts unreviewed until explicitly labeled. +Untouched memberships keep their labels, and label history remains in the +curation journal. Existing legacy journals keep their inherited-metadata +behavior until explicitly migrated with the bounded session's +`migrate_metadata()` API. This migration preserves label intent while adopting +membership-scoped metadata. Use the full-count, rate, amplitude-mean, and +depth-mean summaries for the measurements they explicitly cover; producer +metrics are not recomputed during merge or split. + +For an already saved legacy bounded session, close the GUI and explicitly +migrate before applying its curation. Supply the original producer params if +the source has moved; this also recovers its original metadata filenames: + +```python +from phy.apps.large_recording.curation import BoundedSession + +session = BoundedSession('/data/recording-bounded') +try: + session.migrate_metadata('/data/original-recording/params.py') + session.save() +finally: + session.close() +``` + +Migration publishes a new save generation and retains the older generations, +assignments, review decisions, and explicit label events. A legacy session +remains readable under its old rules until migrated. Already exported values +alone cannot reveal whether a label was inherited or explicitly assigned; keep +the original source and saved bounded journal to recover that distinction. +The same applies to metadata filenames already changed by an older export. +Conflicting JSON/table metadata is reported with the filename, field, and unit; +reconcile the input representations rather than relying on silent precedence. + +Replay keeps source parameter code intact and maintains one final marked block +for its `num_samples`, `valid_intervals`, and `dat_path` overrides. Original +assignments can remain in the file because they may be used by other user +expressions; the managed block, rather than every declaration in the file, is +the stable replay override. + +## Review and curate + +Open the bounded output with the normal GUI command: + +```bash +phy template-gui /data/recording-bounded/params.py +``` + +The bounded manifest explicitly selects this mode. Bounded mode has its own +configuration namespace and default view layout; it does not replace the normal +Phy layout or restore ordinary saved dock geometry. The GUI keeps full-recording +counts and rates distinct from counts in selected evidence rows. Unit Stability +shows time-binned counts/rates, available source scalar-amplitude means, +evidence windows, and acquisition gaps. Missing measurements and units without +evidence remain visible as unavailable. + +Unit Stability overlays up to 32 selected clusters by default for responsiveness, +using the same +colors as the cluster and Merge views and no legend. The view menu's display +limit can be changed; zero displays all selected units, with no hard positive +upper limit. A nonzero limit affects only the displayed curves, not cluster +selection or merge membership. Use the **Show firing rate**, **Show amplitude**, +and **Show depth** toggles to choose plotted measurements. These choices are +saved across sessions; all three are on by default, and turning all three off +leaves the view empty. The default rate-line width is 0.6 points; its positive +width setting is saved with the view. The display-bin setting is local to the +dataset: zero uses the prepared native bins (or the view's native bins on an +ordinary recording), while a coarser bin groups adjacent bins by adding counts +and exposure, and additive trend summaries, exactly. It accepts only integer +multiples of the native bin width, so it cannot display finer bins. The default +is native resolution, preserving the prepared bin size (for example, 300 or +3600 seconds). The screenshot action captures the Matplotlib Qt canvas. The +full-source counts and rates use acquisition exposure, including declared gaps; +source amplitude and depth summaries appear only when available. + +The firing-rate trace automatically leaves gaps in bins with less than 0.1% of +their displayed duration recorded. Small gray ticks mark these bins, and a note +reports how many were omitted. This display convention prevents tiny fragments +of acquisition near gaps from dominating the rate scale; it is not a confidence +estimate or a limit on firing rate. High rates in bins meeting the coverage rule +remain visible. Coverage is evaluated after display coarsening, using the actual +bin widths, including a shorter final bin. Exact counts, exposure, cached rates, +and saved curation are unchanged. No summary-store rebuild is needed. Exposure +still depends on the producer's recording intervals; this display rule cannot +correct inaccurate acquisition metadata. + +The following generated example has a 19–22 Hz trace and one spike in a bin +with only 0.4 ms recorded. Previously the resulting 2500 Hz estimate flattened +the trace; the updated plot marks the low-coverage bin and keeps the normal +rates readable. These are synthetic GUI captures, not Carl's native dataset. + +| Before | After | +| --- | --- | +| ![Before: tiny exposure dominates the rate scale](images/rate-coverage/before.png) | ![After: low-coverage bin marked and normal rates visible](images/rate-coverage/after.png) | + +Feature View uses window-relative seconds and labels the current window with its +recording-time range. Unit Stability keeps the full-recording time context +visible while individual windows are inspected. + +The Sampled ISI view excludes intervals crossing retained-window boundaries. +The Sampled Correlogram view shows raw pair counts from retained windows and a +thin horizontal chance line computed from those same windows. Conditional on +each unit's window count, the line averages the expected off-center bin counts +for independent uniform sample times, including finite-window exposure. It does +not use full-recording counts or duration. Both views are explicitly labeled as +sampled evidence. The line is not an exact lag-dependent null curve or a +confidence limit, and its expectation does not describe the folded central bin. +The central bin counts unordered within-unit pairs and combines both temporal orientations for cross-unit pairs whose absolute delay +is less than one bin, so tied sample times do not depend on source row order. +For exact pair counts, each unit may have at most 46,340 spikes in an evidence +window; the view reports an error for a larger per-unit window. Prepare shorter +windows if this limit is reached. + +When pending SLAY suggestions are active, sampled correlogram axis IDs use the +suggestions' colors. The legend identifies current pending groups; an asterisk +marks IDs belonging to overlapping groups, with full membership in the tooltip. +These annotations update without recomputing the correlograms. Waveform and +correlogram trace colors retain their existing meaning. + +#### Excluding near-zero pairs + +In **Sampled Correlogram View**, use **Set exclusion zone** to set the half-width +around zero lag in milliseconds (default **0.3 ms**, meaning ±0.3 ms). Enable +**Toggle auto exclusion** with `D` for autocorrelograms and **Toggle cross +exclusion** with `Shift+D` for cross-correlograms. Both start off. The shortcuts +apply while the first Sampled Correlogram View has focus; the menu controls work +in every instance. The width and switches are saved with the dataset's GUI state. +The view status reports which exclusions are active. + +Exclusion applies to individual spike-pair delays **before binning**. For example, +with 0.5 ms bins and a ±0.3 ms zone, a 0.1 ms pair is excluded while a 0.4 ms pair +in the same bin remains counted. Boundaries are inclusive on the recording's +sample clock; at 30 kHz, ±0.3 ms excludes delays up to nine samples. Setting the +width to zero excludes exact-time pairs when enabled. Auto and cross switches +operate independently, and no pair is formed across separate observation windows. + +The same retained spikes are used before and after toggling. These controls +change only displayed pair contributions and the corresponding window-local +chance calculation. They do not delete duplicate events, change spike times or +assignments, or create curation-history entries. Pairs outside the zone remain +unchanged, including longer-lag pairs involving a near-coincident spike. An +artificially suppressed near-zero count is not evidence of a clean refractory +period; turn exclusion off to inspect the original counts. + +The Evidence Amplitude view opens in a sampled **overview**: its horizontal +axis uses the original recording clock and displays retained evidence windows +together. Use the view menu's **Toggle amplitude scope** action to switch between +this overview and the current evidence window. **View > Inspect evidence +window** selects a retained window and switches Evidence Amplitude to that +window context; the overview remains available by toggling the scope back. +The window scope uses seconds from that window's start and shows its recording- +time range. Changing the inspected window resets its time origin. +Displayed points may be further limited by the view's point budget. This only +limits what is drawn: split predicates are evaluated over every source spike +when applied. + +Bounded curation supports whole-unit merges, cluster labels, and source-amplitude +splits. Outside Merge mode, select exactly one unit in Evidence Amplitude and +use `Alt` plus right-drag to place or adjust the horizontal threshold preview. +Finite source amplitudes strictly below the threshold are selected; equality +and nonfinite values stay in the remainder. The preview is visual evidence from +the displayed sample. Pressing `K` requires evidence on both sides of the +threshold and commits the predicate. Preview state clears when selection or +view context changes. The command action **Split by source amplitude** remains +available for directly entering a threshold. +In bounded mode, `K` splits the retained evidence rows and records the semantic +source-amplitude predicate; `phy apply-curation` later evaluates that predicate +against every source spike. Thus the bounded GUI assignment is provisional for +unseen spikes until full-source replay. Source `amplitudes.npy` values are used +during replay. After a split, Phy automatically computes exact full-recording +counts, rates and available amplitude/depth trends in the background. With an +attached amplitude index (below), it queries sorted ranges for the required +original units without reading every spike. A row-only store scans those units; +otherwise it reads the original source in bounded chunks. All paths apply +the recorded membership predicates and use the preparation's existing time +bins and acquisition exposure. The split children show a computation status until complete results +are ready; unrelated selected units retain their plots. This does not require +applying curation or exporting a full dataset. + +Computed summaries combine on subsequent merges, and completed results are +reused after undo/redo and reopening. A separate bounded cache in +`.phy/live-summary-cache` is disposable; deleting or losing it does not affect +curation saves. Computation leaves the source, preparation manifest and saved +curation generations unchanged. The original-source fallback validates the +required files on first use; later splits reuse validated readers while their +file fingerprints remain unchanged. Closing the GUI cancels work without waiting for a complete scan. +Saving curation does not wait for summary computation. +The debug console records one `Full summary job` line per computation, including +elapsed seconds and its path: `amplitude-index`, `row-store`, `source`, or +`prepared/cache`. This distinguishes indexed work from fallback scans or reused +results when reporting performance problems. + +Without a compatible summary store, new computations require the original +source directory to be accessible and match the prepared source revision. If it moved, use **File > Locate summary +source**; the location is remembered in dataset-local GUI state without changing +the manifest. Use **File > Retry full summaries** after resolving an error. Valid +cached results can be displayed even when the original source is offline. +Summary arrays that exceed the cache budget report unavailable rather than +showing a sampled estimate; exact known table counts remain available. + +Merge and label actions +are journaled with the bounded assignments and metadata in an atomic checkpoint +generation. +Reopening loads the last complete generation. A reopened session starts a new +undo baseline. Each save checks that the checkpoint has not changed since this +session opened. If another session has saved first, the stale save fails; reopen +the bounded dataset before continuing to avoid overwriting that generation. + +Each successful GUI checkpoint save also appends a record to +`phy_curation_history.jsonl` beside the bounded package's `params.py`, using the +same software versions, checkout revisions, session IDs and UTC timestamps as +ordinary curation (see [curation provenance](quickstart.md#curation-provenance)). +A failed checkpoint save does not append a successful-save record. This history +is separate from the immutable checkpoint and leaves the original source alone. +Direct scripting calls to `BoundedSession.save()` do not create GUI session records. + +### Recovery drafts and checkpoint reminders + +The bounded GUI protects unsaved curation in background recovery drafts. Drafts +contain semantic edits and review decisions, rather than a fresh copy of every +spike assignment. They live in local application data, separately from the +dataset's validated checkpoint. `apply-curation` uses the checkpoint saved with +**Save** or `Ctrl+S`; it does not consume recovery drafts. + +The bottom-right status area shows whether the latest working revision has +confirmed draft protection, whether protection is pending, or whether an error +needs attention. A protected draft is a local recovery aid, not a replacement +for backing up the dataset and its saved checkpoints. If Phy finds a compatible +unfinished draft on reopening, it offers recovery without replacing the saved +checkpoint. Recovered work remains unsaved until you save a checkpoint. + +After 15 minutes of unsaved work, **Save checkpoint** gains a steady amber +background once input pauses. The reminder stays outside the plots, never +takes focus, and never opens a dialog or starts a checkpoint save automatically. +Its adjacent options menu offers 5-, 15- and 30-minute intervals, **Remind me +later**, reminder disabling, and retrying draft protection. Turning reminders +off leaves background protection active. Saving remains an explicit action +when you reach a useful checkpoint. + +The Evidence Amplitude View includes the full finite range of the selected +units' displayed amplitudes, with padding, in both overview and window modes. +Background outliers do not set that range. Evidence and display budgets still +apply: spikes absent from the sample are not loaded just to determine the axis. + +New curation events update current semantic state and affected evidence rows. +Metadata labels do not replay earlier assignments or invalidate unchanged +membership summaries. Undo/redo retains inverse patches within a 64 MiB cache; +large or evicted changes use the full validated journal as a fallback. Each +save/load still verifies assignments and metadata against the complete journal. +A long journal can therefore still affect checkpoint validation time, while +ordinary editing avoids the earlier spike-count times journal-length cost. + +`Ctrl+Space` selects the next configured N eligible Similarity candidates; +`Ctrl+Shift+Space` selects up to N rows before the first selected eligible row. +Filtering and sorting define the order. With no eligible selection, backward +navigation starts at the end; batches do not wrap across an endpoint. In Merge +mode, dragging the blue row changes its position while preserving its reference +identity, color and Similarity calculation. + +Lasso, feature, and waveform splits remain unavailable in bounded mode because +the selected rows do not define how unseen source spikes should be assigned. +Ordinary datasets retain their standard split tools, including the graphical +amplitude-threshold preview. + +### Accelerate summaries on very long recordings + +On billion-spike datasets, scanning the entire source after each split can take +minutes, and even scanning one very large unit can interrupt curation. +An amplitude index moves this work into one-time preparation. When opening a +bounded dataset without a compatible indexed store, Phy offers to prepare one. +If a row store already exists, it offers to add only the amplitude index; this +upgrade works even with the original source offline. The nonmodal prompt shows estimated additional disk +space, a destination picker, available space and an independent store budget +(default 64 GiB). It never starts a large build without your choice. + +Choose **Build in background** to keep curating while it runs, or **Continue +without** to retain the existing full-source fallback. **Don't ask again for this +dataset** suppresses future prompts for that package. Build and attach actions +remain available from **File > Build summary store** and **File > Attach summary +store**. **File > Attach amplitude index** reconnects an index stored separately. +Compatible stores are reused automatically, including offline snapshots. + +The status bar shows the current stage and progress, then an estimated time +remaining **for that stage** once throughput settles. Validation measures bytes; +construction and amplitude sorting measure rows; index authentication measures +bytes. Finalizing and attachment are indeterminate stages, +so a completed scan is not presented as a completed task. **Hide** hides only the +display; **File > Show background task** restores it. **Cancel** cleans unfinished +staging data. A short final publication step cannot be cancelled and displays +**Finishing…**. Accepted GUI closure cancels/detaches work without waiting for a +scan; cancelling the save/close prompt keeps the task alive. + +New full-source summary scans wait while construction owns recording I/O. +Existing cached curves remain available, and merges/splits/undo and curation +saves remain independent. Successful construction attaches the store and retries +summaries for the current curation without reopening. If attachment fails, the +completed store is retained; **Details** identifies its path for a later attach. +A newer store choice made during a build is preserved. Cancellation between +stages retains completed artifacts and stops subsequent long preparation; a +completed row store remains usable if amplitude-index construction is cancelled. + +Actual screenshots from the earlier converted engineering dataset: +[prompt](images/amplitude-index-task/prompt.png), +[row preparation](images/amplitude-index-task/building.png), +[amplitude-index progress and ETA](images/amplitude-index-task/indexing.png), and +[ready with restored child rates](images/amplitude-index-task/ready.png). + +The equivalent command-line workflow remains available: + +```bash +phy build-summary-store BOUNDED /data/summary-store +phy template-gui BOUNDED/params.py +``` + +The destination must be a new directory outside the bounded package and original +source. The command validates the original source and stores exact scalar values +and native time-bin IDs grouped by original unit. It does not change the +preparation manifest, journal, assignments or saved checkpoint. Construction uses +bounded batches and write buffers; it requires enough free space for the new +store. The default independent store budget is 64 GiB; increase `--max-bytes` +when needed. `--source-dir` locates a relocated original source. Keep the store +on fast local storage where possible. + +Both this command and `prepare-large --summary-store /data/summary-store` +build the row snapshot and its amplitude index. For `prepare-large`, +`--summary-store-max-bytes` sets the combined budget. If an optional stage fails, +keep the completed bounded package and row store. Retry only the failed stage +with `build-summary-store` or `build-amplitude-index`. + +A 1,000-bin dataset with float32 amplitudes needs approximately six bytes per +source spike for its row snapshot: two for the bin and four for the amplitude (about 29.2 GB for +4.87 billion spikes). Depth, when available, adds its original scalar width. +Bin IDs use the smallest suitable unsigned dtype; offsets and counts retain +64-bit range. No lossy amplitude conversion is performed. The amplitude index additionally +stores finite amplitudes/depths in sorted order plus block aggregates and +authentication data; the GUI estimate includes both assets. + +An existing row store can be upgraded without revalidating the original source: + +```bash +phy build-amplitude-index BOUNDED /data/summary-store/amplitude-index +``` + +`build-summary-store --rows-only` retains the row-only preparation option. +The 64 GiB budget covers the **combined** row store and amplitude index. The GUI +also checks the additional temporary disk space needed for sorting. Preparation +can take several minutes and uses bounded memory and external sorting for large +segments. Keep the resulting store on fast local storage. + +For each original unit and native time bin, the index sorts finite amplitudes +using their original dtype and builds a tree of counts and scalar sums. A new +threshold queries aggregate ranges plus small endpoint blocks. Nested splits +and splits of merged units combine those intervals. Query cost depends on the +number of original units, bins and intervals, rather than every source spike. +Counts and finite-value counts remain exact. Floating sums must meet the +existing tolerance (relative 1e-9, absolute 1e-6); numerically unstable cases use +the verified row path. NaN/infinity and threshold boundary semantics match +full-source replay. Merges continue to combine completed summaries without a scan. + +The store represents the **source snapshot used during preparation**, just like +prepared summaries. Range queries verify the pages they consume against pinned +SHA-256 tree roots, avoiding a whole-unit integrity scan on every split. Row-only +queries checksum each consumed unit before publication. Neither certifies that +current original files are unchanged. Full-source replay/export continues to +validate the original source. Missing, incompatible or corrupt amplitude indexes +fall back to verified rows; missing/damaged rows fall back to validated source +reads. Template-based engine predicates also use source reads because template +values are not indexed. Neither accelerator changes curation assignments or replay. + +The range reader keeps at most 64 MiB of authenticated data pages with the default +engine budget, an 8 MiB endpoint-block cache per query, and separately capped hash +node caches (16,384 entries per file). Query outputs and arithmetic scratch are +bounded; complex or oversized histories can fall back to the chunked row path. + +The small discovery reference is `.phy/live-summary-store.json`. To move a store, +recover a lost reference, or share it with another package having the identical +source snapshot, summary grid and scalar definitions: + +```bash +phy attach-summary-store BOUNDED /new/location/summary-store +``` + +The conventional `amplitude-index` subdirectory is rediscovered by the CLI and +GUI attach action after moving the entire store. For an index kept elsewhere, +attach its matching row store first, then use: + +```bash +phy attach-amplitude-index BOUNDED /new/location/amplitude-index +``` + +Payload checks remain selective after attachment. Stores are separate from the +256 MiB disposable result cache and are never automatically evicted. To remove +one, close Phy, remove its reference, and delete the store only after checking +that no other package uses it. Saving curation never depends on either cache. + +The reproducible `tools/benchmark_summary_store.py` compares indexed results +against a full scan and independent cumulative assignment replay. Run it on a +fresh copy of the bounded package. Report build time, peak memory, disk usage, +cache conditions and split timings separately. Measurements on smaller datasets +do not establish acceptance on a 1,000-hour dataset. + +### Comparing ordinary and bounded curation + +Perform the same documented merges, amplitude threshold splits and explicit +manual-label decisions on separate copies of one source. Compare the ordinary +saved sorting against the complete `apply-curation` output, rather than against +the retained evidence package: + +```bash +uv run python tools/compare_curation_modes.py compare \ + /data/ordinary-final /data/bounded-full-output \ + --fields group notes --output /data/comparison.json +``` + +The report checks every spike's time and cluster partition through a two-way +ID mapping, then checks the requested manual labels. Numeric cluster IDs may +differ between runs. Use a fresh report path outside both input folders. +This basic mode compares only the requested manual fields; it excludes producer +metrics whose inheritance policy may differ. + +For acceptance, enable the stronger whole-output contract with the original +immutable source, the bounded package used for the final replay, and independent +expected final curator decisions: + +```bash +uv run python tools/compare_curation_modes.py compare \ + /data/ordinary-final /data/bounded-full-output \ + --source /data/original-source --bounded-dir /data/final-bounded \ + --expectations /data/expected-labels.json --output /data/full-comparison.json +``` + +The expectations file maps replay unit IDs to reviewed fields, for example +`{"708": {"group": "good", "notes": "reviewed"}, "49": {"group": null}}`. +Write it from the planned decisions and the allocated ID ledger, rather than +copying values from an output being tested. Include every surviving explicit +label decision, including cleared labels. Across multiple rounds, keep +`--source` pointing to the original source and supply the final round's package. +Put the report outside every input folder. + +This mode checks every imported metadata field, byte-identical immutable +arrays/sidecars, preserved replay table layouts, parameters, and the exact saved +generation's journal, metadata, review state and retained assignments. Unknown +or missing files fail. An independent chunked oracle applies the cumulative +merge and threshold-split history to every original source spike, including +spikes omitted from the bounded evidence, and checks exact replay assignments. +It evaluates original scalar attributes, comparator equality and the declared +nonfinite policy across repeated curation rounds. +New memberships must have cleared producer values unless +explicitly reviewed; native ancestor inheritance is checked and reported as a +permitted difference. Native source aliases and untouched blank source columns +are admitted only when their original bytes match. A generated native whitening +inverse is checked against its source matrix. GUI caches/logs may differ; +generated cluster summaries must still have the correct catalog and manual +labels. Existing suggestion decisions must survive unchanged; new SLAY decisions +use the separate proposition acceptance procedure. + +Without `--bounded-dir`, first-round source checks do not verify preparation or +saved-generation binding. Later-round verification requires that package. +The report states which bindings were verified; use the complete command above +for acceptance. The repository's `design/curation-output-equivalence.md` records +the contract, permanent controller tests and real-data evidence. + +For graphical split comparisons, choose finite source amplitudes: ordinary +TemplateModel displays nonfinite amplitudes as zero, while bounded replay +keeps them in the remainder. Select **template** amplitudes in ordinary +Amplitude View to compare its stored `amplitudes.npy` values; feature amplitudes +represent a different quantity. The tool also provides independent ordinary-engine +and streamed references; neither replaces a full ordinary GUI acceptance run. +The repository's `design/curation-user-acceptance.md` provides the action ledger, +additional user checks and evidence limits. + +## Unit Stability on ordinary recordings + +Unit Stability can also be opened as an optional view for an ordinary dataset. +It evaluates selected units and bins their loaded spikes over the recording +duration. Its firing rate assumes continuous acquisition because ordinary +datasets do not supply valid acquisition intervals to the view; the plot labels +that assumption. The Unit Stability view menu's **Show firing rate**, +**Show amplitude**, and **Show depth** toggles and rate-line width are saved +across sessions, with all three toggles on by default. The display-bin setting +is dataset-local. The ordinary default view layout remains unchanged. +Use the bounded manifest workflow above when known acquisition gaps must be +represented explicitly. + +## Apply to the complete sorting + +After saving the bounded session, replay its journal against the exact source +assignment revision used during preparation: + +```bash +phy apply-curation /data/recording/params.py /data/recording-bounded \ + /data/recording-curated --batch-size 100000 +``` + +Replay checks the source identity and parent assignment revision, streams the +complete assignment array in batches, and writes a new full sorting. It rejects +a journal prepared from a different source revision. Keep the original source +and bounded package; they establish the lineage of the curated output. To review +the curated full sorting with bounded evidence again, run `prepare-large` on +the curated output to produce a fresh package and revision-specific summaries. +Live summary recomputation already provides split-child rates and trends during +the original session; re-preparation starts a new curation round. Replay +applies the recorded threshold split to every source spike using its source +amplitude value. + +Replay tries native copy-on-write file clones on supported Linux and macOS +filesystems, then falls back to ordinary copies when cloning is unsupported. +Fallback checks free space, and output is verified before publication. These +are independent files, never hardlinks to the source. Cloning can save copying +time and space; source hashing and output verification still run. + +When the source includes SLAY suggestions in `curation.json`, preparation and +replay preserve that file exactly, together with saved accept/reject decisions +in `curation_review.json`. Subsequent bounded rounds retain those decisions, +including rounds with no new edits or with the proposition view disabled. +There is no need to copy either file by hand. + +Suggestions keep their original cluster IDs and source order. A saved acceptance +remains part of the review history even if its resulting cluster is later +merged or split. Pending suggestions whose original clusters disappear become +stale; known merge or split causes are shown without assigning the suggestion +to replacement clusters automatically. Legacy outputs without that history can +only report that an original cluster is missing. + +Bounded packages bind suggestions and review history to file hashes. A committed +checkpoint supplies the saved decisions even if a loose review copy is missing +or outdated. Changing the bound suggestion file requires preparing a new +package; incompatible or damaged documents stop saving or replay. +Older bounded packages with unbound suggestion or review documents require +migration before they can be replayed with this integrity check. Retain their +source and saved checkpoints so existing curation can be recovered; preparing +the original source again alone does not transfer those saved edits. + +## Interpreting evidence + +Full counts and exposure-based rates describe the complete sorting. Window plots, +waveforms, feature scatterplots, and other bounded measurements describe only +the retained evidence. Survey and rescue selection can overrepresent some +periods or units, and waveform availability can vary across units and time. +These views do not establish full-recording quality, contamination, refractory +violations, or continuous biological identity. Use them to guide review, not as +scientific claims about unseen spikes. Long-duration coordinates preserve the +declared source time axis; silence alone is never evidence that the acquisition was +inactive. + +For reproducible synthetic capacity measurements, run +`uv run python tools/benchmark_long_recording.py`. The benchmark reports +preparation and replay time and peak memory in separate processes and checks +replay against a streamed oracle. It is capped at two million synthetic spikes; +its results are not a substitute for measurements on real chronic datasets. diff --git a/docs/plugins.md b/docs/plugins.md index 011d55f6d..ec9b13c76 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -1108,3 +1108,90 @@ class ExampleOpenGLViewPlugin(IPlugin): controller.at_least_one_view('MyOpenGLView') ``` + + +## Running an intensive task in the background + +Use `phy.gui.tasks.BackgroundTaskManager` for a user-requested background job. +The runner provides a single task slot, cooperative cancellation, per-stage +progress, and process-wide exclusion for heavyweight recording I/O. It does not +replace view rendering or the persistent live-summary reader. + +Worker functions receive immutable requests and a `TaskContext`. They must not +read a controller, session, widget, Qt model or OpenGL object. Keep large arrays +inside the worker and return small immutable results or artifact paths. For +example, this worker hashes a file in bounded blocks: + +```python +from dataclasses import dataclass +from hashlib import sha256 +from pathlib import Path + +from phy.gui.tasks import TaskProgress + + +@dataclass(frozen=True) +class HashRequest: + path: str + + +def hash_file_in_background(request, context): + path = Path(request.path) + total = path.stat().st_size + digest = sha256() + done = 0 + with path.open('rb') as stream: + while block := stream.read(1024 * 1024): + context.check_cancel() + digest.update(block) + done += len(block) + context.report(TaskProgress('Hashing', done, total, 'bytes')) + return digest.hexdigest() +``` + +Create the manager on the GUI thread and retain it in your plugin. Connect its +`finished` signal to a GUI-thread callback before submitting a `TaskSpec`: + +```python +from phy.gui.tasks import BackgroundTaskManager, TaskSpec +from phy.gui.task_widgets import TaskWidget + +manager = BackgroundTaskManager() +widget = TaskWidget(manager, gui) +gui.statusBar().addPermanentWidget(widget) +manager.finished.connect(on_finished) # receives a TaskOutcome on the GUI thread +manager.submit(TaskSpec( + key='hash:' + str(path), title='Hashing recording', + worker=hash_file_in_background, request=HashRequest(str(path)))) +``` + +The `TaskOutcome` states are `succeeded`, `cancelled` and `failed`; a successful +result is in `result`, and a failure message is in `error`. Do not wait for a +worker in a GUI callback. Progress uses a latest-value mailbox sampled around +four times per second, so a stalled GUI cannot accumulate one event per row. +`TaskWidget` supplies a progress bar, smoothed per-stage ETA, Cancel, Hide and +bounded details. A different stage or progress unit starts a fresh ETA estimate. + +On accepted GUI closure, disconnect your completion callback, call +`widget.dispose()`, then `manager.detach()`. Do not detach when a close/save +prompt is vetoed. The manager keeps terminal polling active after detachment, +without calling the owner's callbacks. Workers retain only plain Python task +state; they never access Qt delivery objects. If Qt destroys the manager first, +its destruction handler requests cancellation and releases retained manager +ownership on the GUI thread. No worker join is required during closure. For dataset tasks, check the dataset and GUI +identity again before adopting results; do not restore a selection captured at +submission time. + +For an atomic artifact publication, call `context.commit()` after the final +cancellation check and immediately before the short noncancellable publication +step. A late cancellation must not turn a successfully published artifact into +cancelled work. Report a published artifact separately from a subsequent +attachment error, so users can recover it. Avoid placing long scans or ordinary +computation inside the commit boundary. + +Tasks use dedicated threads initially. Set `heavy=False` only for small +metadata work or tasks that do not compete for recording I/O. Existing live +summary scans share the same cancellable I/O permit. Keep worker functions +module-level and requests serializable where possible, so another execution +backend can be added later without changing the UI contract. Task persistence, +resumable builds and arbitrary dependency queues are not provided. diff --git a/docs/shortcuts.md b/docs/shortcuts.md index 30cc0de55..604eb79a4 100644 --- a/docs/shortcuts.md +++ b/docs/shortcuts.md @@ -266,6 +266,21 @@ Keyboard shortcuts Snippets - change_n_spikes_waveforms :wn +SampledCorrelogramView +---------------------- + +Keyboard shortcuts +- change_bin_size alt+wheel +- change_window_size ctrl+wheel +- toggle_auto_exclusion d +- toggle_cross_exclusion shift+d +- transfer_cluster right click + +Snippets +- set_bin :cb +- set_refractory_period :cr +- set_window :cw + ``` diff --git a/docs/visualization.md b/docs/visualization.md index dfc45912e..6277df9f0 100644 --- a/docs/visualization.md +++ b/docs/visualization.md @@ -320,7 +320,9 @@ class CorrelogramLimitPlugin(IPlugin): view.max_n_clusters = 30 ``` -The horizontal line shows the baseline firing rate. Vertical lines show the refractory period, which defaults to 2 ms. You can change it with the view menu or with the `:cr` snippet. +The horizontal line shows the expected chance-level pair count. In bounded mode +it is calculated from the retained observation windows and represents the mean +off-center expectation; it does not extrapolate the full recording. Vertical lines show the refractory period, which defaults to 2 ms. You can change it with the view menu or with the `:cr` snippet. The parameter `controller.n_spikes_correlograms` (100,000 by default) bounds the number of spikes per selected cluster. The default diff --git a/mkdocs.yml b/mkdocs.yml index bf8a4ad12..f59e59417 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -17,6 +17,7 @@ nav: - How-to and customization: - Configuration and state: configuration.md - Performance and spike sampling: performance.md + - Curating long recordings: long-recordings.md - Change keyboard shortcuts: keyboard_customization.md - Plugin introduction: customization.md - Plugin examples: plugins.md diff --git a/phy/apps/__init__.py b/phy/apps/__init__.py index db51602ea..f546940c0 100644 --- a/phy/apps/__init__.py +++ b/phy/apps/__init__.py @@ -7,6 +7,7 @@ import logging import sys +from concurrent.futures import CancelledError from contextlib import contextmanager from pathlib import Path from traceback import format_exception @@ -19,6 +20,10 @@ from phy.utils.profiling import _enable_pdb, _enable_profiler from .base import BaseController, FeatureMixin, TemplateMixin, TraceMixin, WaveformMixin # noqa +from .large_recording.refractory_resources import ( + DEFAULT_RP_MAX_BYTES, + DEFAULT_RP_MEMORY_BYTES, +) logger = logging.getLogger(__name__) @@ -174,6 +179,279 @@ def cli_template_describe(ctx, params_path): template_describe(params_path) +# ------------------------------------------------------------------------------ +# Long-recording batch commands +# ------------------------------------------------------------------------------ + + +@phycli.command('prepare-large') +@click.argument('params-path', type=click.Path(exists=True, dir_okay=False, path_type=Path)) +@click.argument('output-dir', type=click.Path(path_type=Path)) +@click.option('--duration', 'duration_seconds', type=click.FloatRange(min=0, min_open=True)) +@click.option('--valid-intervals', type=click.Path(exists=True, dir_okay=False, path_type=Path)) +@click.option('--max-spikes', type=click.IntRange(min=1), default=2000000, show_default=True) +@click.option('--max-bytes', type=click.IntRange(min=1), default=536870912, show_default=True) +@click.option('--window-seconds', type=click.FloatRange(min=0, min_open=True), default=30.0) +@click.option('--stratum-seconds', type=click.FloatRange(min=0, min_open=True), default=3600.0) +@click.option('--seed', type=click.IntRange(min=0), default=0) +@click.option('--bin-seconds', type=click.FloatRange(min=0, min_open=True), default=3600.0) +@click.option('--batch-size', type=click.IntRange(min=1), default=100000) +@click.option('--workers', type=click.IntRange(min=1, max=32), default=1, show_default=True) +@click.option( + '--window-policy', + type=click.Choice(['auto', 'producer', 'generated']), + default='auto', + show_default=True, + help='Prefer producer waveform windows, require them, or generate new windows.', +) +@click.option( + '--summary-store', + type=click.Path(path_type=Path), + help='Build a separate unit-contiguous acceleration store at this new path.', +) +@click.option('--rp-summaries', is_flag=True, help='Prepare exact original-unit RP summaries.') +@click.option('--rp-summary-max-bytes', type=click.IntRange(min=1), default=DEFAULT_RP_MAX_BYTES) +@click.option( + '--rp-summary-memory-bytes', + type=click.IntRange(min=1), + default=DEFAULT_RP_MEMORY_BYTES, + show_default=True, + help='Memory budget for exact RP summary construction.', +) +@click.option('--store-timestamps', is_flag=True, help='Include exact ticks in --summary-store.') +@click.option('--summary-store-max-bytes', type=click.IntRange(min=1), default=68719476736) +def cli_prepare_large(params_path, output_dir, valid_intervals=None, **kwargs): + """Prepare bounded shared-window evidence and complete-sorting summaries. + + VALID_INTERVALS is an optional int64 .npy array of acquisition [start, end) tick pairs. + Duration/exposure must be authoritative; it is never inferred from spike silence. + """ + import json + + import numpy as np + + from .large_recording.prepare import prepare_large + from .large_recording.progress import ProgressReporter + + try: + intervals = np.load(valid_intervals, allow_pickle=False) if valid_intervals else None + with ProgressReporter() as progress: + output = prepare_large( + params_path, + output_dir, + valid_intervals=intervals, + cancel=progress.check_cancelled, + progress=progress, + **kwargs, + ) + except CancelledError as error: + raise click.ClickException('Operation cancelled.') from error + except (ValueError, OSError) as error: + raise click.ClickException(str(error)) from error + click.echo(f'Prepared bounded evidence: {output}') + manifest = json.loads((output / '_phy_curation_manifest.json').read_text(encoding='utf-8')) + coverage = manifest['waveform_coverage'] + click.echo( + f'Stored waveforms: {coverage["retained_rows"]:,} retained / ' + f'{coverage["source_rows"]:,} source; {coverage["dropped_rows"]:,} omitted.' + ) + + +@phycli.command('build-rp-summaries') +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.option('--source-dir', type=click.Path(exists=True, path_type=Path)) +@click.option('--max-bytes', type=click.IntRange(min=1), default=DEFAULT_RP_MAX_BYTES) +@click.option('--memory-bytes', type=click.IntRange(min=1), default=DEFAULT_RP_MEMORY_BYTES) +@click.option('--batch-size', type=click.IntRange(min=1), default=100000) +def cli_build_rp_summaries(bounded_dir, **kwargs): + """Prepare optional exact RP counts for the original units of a bounded package.""" + from .large_recording.progress import ProgressReporter + from .large_recording.refractory_store import build_refractory_summaries + + try: + with ProgressReporter() as progress: + output = build_refractory_summaries( + bounded_dir, cancel=progress.check_cancelled, progress=progress, **kwargs + ) + except CancelledError as error: + raise click.ClickException('Operation cancelled.') from error + except (ValueError, OSError) as error: + raise click.ClickException(str(error)) from error + click.echo(f'Prepared RP summaries: {output}') + + +@phycli.command('build-summary-store') +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.argument('output-dir', type=click.Path(path_type=Path)) +@click.option('--source-dir', type=click.Path(exists=True, path_type=Path)) +@click.option('--max-bytes', type=click.IntRange(min=1), default=68719476736) +@click.option('--batch-size', type=click.IntRange(min=1), default=1000000) +@click.option('--workers', type=click.IntRange(min=1, max=32), default=1, show_default=True) +@click.option('--timestamps', is_flag=True, help='Include exact ticks for curated RP queries.') +@click.option( + '--amplitude-index/--rows-only', + default=True, + show_default=True, + help='Also prepare fast amplitude-threshold summaries.', +) +def cli_build_summary_store(bounded_dir, output_dir, **kwargs): + """Accelerate an existing bounded package without changing its saved curation.""" + from .large_recording.progress import ProgressReporter + from .large_recording.summary_store import build_summary_store + + accelerate = kwargs.pop('amplitude_index') + workers = kwargs.pop('workers') + output = None + try: + with ProgressReporter() as progress: + if accelerate: + from .large_recording.range_build import preflight_summary_store + + preflight_summary_store( + bounded_dir, kwargs['max_bytes'], timestamps=kwargs['timestamps'] + ) + output, reference = build_summary_store( + bounded_dir, + output_dir, + progress=progress, + cancel=progress.check_cancelled, + workers=workers, + return_reference=True, + **kwargs, + ) + if accelerate: + _build_amplitude_index( + bounded_dir, + output / 'amplitude-index', + kwargs['max_bytes'], + progress, + reference, + workers=workers, + cancel=progress.check_cancelled, + ) + except CancelledError as error: + raise click.ClickException('Operation cancelled.') from error + except (ValueError, OSError) as error: + message = str(error) + if output is not None: + message = ( + f'Row snapshot ready at {output}; amplitude-index preparation failed: ' + f'{error}. Retry with build-amplitude-index.' + ) + raise click.ClickException(message) from error + click.echo(f'Prepared summary snapshot: {output}') + + +@phycli.command('attach-summary-store') +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.argument('store-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +def cli_attach_summary_store(bounded_dir, store_dir): + """Attach an existing compatible summary snapshot without rebuilding.""" + from .large_recording.summary_store import attach_summary_store + + try: + _, reference = attach_summary_store(bounded_dir, store_dir, return_reference=True) + candidate = store_dir / 'amplitude-index' + if candidate.is_dir(): + from .large_recording.range_index import attach_amplitude_index + + attach_amplitude_index(bounded_dir, candidate, expected_reference=reference) + except (ValueError, OSError, KeyError, TypeError) as error: + raise click.ClickException(str(error)) from error + click.echo(f'Attached summary snapshot: {store_dir}') + + +def _build_amplitude_index( + bounded_dir, output_dir, max_bytes, progress, reference=None, workers=1, cancel=None +): + from .large_recording.range_build import build_amplitude_index + from .large_recording.range_intervals import RangeUnavailableError + + try: + options = {'expected_reference': reference} if reference is not None else {} + return build_amplitude_index( + bounded_dir, + output_dir, + max_bytes=max_bytes, + progress=progress, + workers=workers, + cancel=cancel, + **options, + ) + except RangeUnavailableError as error: + click.echo(f'Using the verified row store: {error}', err=True) + + +@phycli.command('build-amplitude-index') +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.argument('output-dir', type=click.Path(path_type=Path)) +@click.option('--max-bytes', type=click.IntRange(min=1), default=68719476736) +@click.option('--workers', type=click.IntRange(min=1, max=32), default=1, show_default=True) +def cli_build_amplitude_index(bounded_dir, output_dir, max_bytes, workers): + """Add fast amplitude queries to an existing attached summary store.""" + from .large_recording.progress import ProgressReporter + + try: + with ProgressReporter() as progress: + path = _build_amplitude_index( + bounded_dir, + output_dir, + max_bytes, + progress, + workers=workers, + cancel=progress.check_cancelled, + ) + except CancelledError as error: + raise click.ClickException('Operation cancelled.') from error + except (OSError, ValueError, KeyError, TypeError) as error: + raise click.ClickException(str(error)) from error + if path: + click.echo(f'Prepared amplitude index: {path}') + + +@phycli.command('attach-amplitude-index') +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.argument('index-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +def cli_attach_amplitude_index(bounded_dir, index_dir): + """Attach a compatible amplitude index to its original row store.""" + from .large_recording.range_index import attach_amplitude_index + + try: + attach_amplitude_index(bounded_dir, index_dir) + except (OSError, ValueError, KeyError, TypeError) as error: + raise click.ClickException(str(error)) from error + click.echo(f'Attached amplitude index: {index_dir}') + + +@phycli.command('apply-curation') +@click.argument('source-params', type=click.Path(exists=True, dir_okay=False, path_type=Path)) +@click.argument('bounded-dir', type=click.Path(exists=True, file_okay=False, path_type=Path)) +@click.argument('output-dir', type=click.Path(path_type=Path)) +@click.option('--batch-size', type=click.IntRange(min=1), default=100000) +@click.option('--workers', type=click.IntRange(min=1, max=32), default=1, show_default=True) +def cli_apply_curation(source_params, bounded_dir, output_dir, batch_size, workers): + """Replay committed bounded curation into a new complete sorting.""" + from .large_recording.progress import ProgressReporter + from .large_recording.replay import apply_curation + + try: + with ProgressReporter() as progress: + output = apply_curation( + source_params, + bounded_dir, + output_dir, + batch_size=batch_size, + workers=workers, + cancel=progress.check_cancelled, + progress=progress, + ) + except CancelledError as error: + raise click.ClickException('Operation cancelled.') from error + except (ValueError, OSError) as error: + raise click.ClickException(str(error)) from error + click.echo(f'Published complete curated sorting: {output}') + + # ------------------------------------------------------------------------------ # Kwik GUI # ------------------------------------------------------------------------------ @@ -224,6 +502,11 @@ def cli_alf_convert(ctx, subdirs, out_dir): from phylib.io.merge import Merger from phylib.io.model import load_model + if any((Path(path) / '_phy_curation_manifest.json').exists() for path in subdirs): + raise click.ClickException( + 'Apply bounded curation to the complete sorting before ALF conversion.' + ) + out_dir = Path(out_dir) if len(subdirs) >= 2: @@ -253,6 +536,11 @@ def template_extract_waveforms( """Extract spike waveforms.""" from phylib.io.model import load_model + if (Path(params_path).parent / '_phy_curation_manifest.json').exists(): + raise click.ClickException( + 'Extract waveforms on the original source and regenerate bounded evidence; bounded package assets are immutable.' + ) + model = load_model(params_path) model.save_spikes_subset_waveforms( max_n_spikes_per_template=n_spikes_per_cluster, max_n_channels=nc diff --git a/phy/apps/_parent_review.py b/phy/apps/_parent_review.py new file mode 100644 index 000000000..d0a76f025 --- /dev/null +++ b/phy/apps/_parent_review.py @@ -0,0 +1,952 @@ +"""Exact merge-parent lineage and isolated, read-only comparison providers.""" + +import hashlib +import json +import logging +import os +import tempfile +from contextlib import suppress +from pathlib import Path +from types import MappingProxyType +from zipfile import BadZipFile + +import numpy as np +from phylib.stats import correlograms +from phylib.utils import Bunch, connect, emit, unconnect + +from phy.gui.qt import Qt +from phy.utils import phy_config_dir +from phy.utils.color import colormaps + +logger = logging.getLogger(__name__) + + +def _fingerprint(assignments, model): + digest = hashlib.sha256() + digest.update(str(len(assignments)).encode()) + for start in range(0, len(assignments), 1_000_000): + digest.update(np.asarray(assignments[start : start + 1_000_000], dtype=' 16: + return # Display limits must never restrict otherwise valid curation. + selected = getattr(sender, 'selection_color_indices', {}) + colors = {int(p): int(selected[p]) for p in parents if p in selected} + used = set(colors.values()) + for parent in parents: + if parent not in colors: + slot = next(i for i in range(len(colormaps.default)) if i not in used) + colors[int(parent)] = slot + used.add(slot) + self._pending_colors = colors + + def _on_cluster(self, sender, up): + self._membership_revision += 1 + self._reassembly_cache = None + if up.history == 'undo': + for target in up.added: + self.restorations.pop(int(target), None) + if up.description == 'restore_parents' and up.history != 'undo': + self.restorations[int(up.parent_restore_target)] = list(up.parent_restore_origins) + for child, parent in up.parent_restore_origins.items(): + self.origins[int(child)] = self._historical_origin(parent) + if parent in self.records: + self.records[int(child)] = self.records[parent] + self.known_merges.add(int(child)) + if parent in self.color_records: + self.color_records[int(child)] = self.color_records[parent] + if up.description == 'merge' and up.history != 'undo' and len(up.deleted) >= 2: + target = int(up.added[0]) + if not hasattr(self.controller, 'bounded_session'): + # Keep references: Clustering replaces these arrays, never mutates them. + self.records[target] = dict(up.parent_spike_ids) + self.known_merges.add(target) + if up.history != 'redo': + colors = self._pending_colors + if colors is not None and set(colors) == set(up.deleted): + self.color_records[target] = colors + else: + self.color_records.pop(target, None) + self._pending_colors = None + + @staticmethod + def _parse_colors(value): + if not isinstance(value, dict): + raise ValueError('invalid optional parent colors') + result = {} + for target, groups in value.items(): + if not isinstance(groups, dict): + raise ValueError('invalid optional parent colors') + colors = {} + for parent, index in groups.items(): + if type(index) is not int or index < 0: + raise ValueError('invalid optional parent color index') + colors[int(parent)] = index + if len(set(colors.values())) != len(colors): + raise ValueError('duplicate optional parent color indices') + result[int(target)] = colors + return result + + def _bounded_color_path(self): + identity = hashlib.sha256(str(self.controller.dir_path.resolve()).encode()).hexdigest()[ + :20 + ] + config_dir = self.controller.config_dir or phy_config_dir() + return Path(config_dir) / f'parent-colors-{identity}.json' + + def _bounded_binding(self): + session = self.controller.bounded_session + value = [session.manifest['source'], session.manifest.get('bounded_files'), session.events] + return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() + + def _load_bounded_colors(self): + try: + value = json.loads(self._bounded_color_path().read_text()) + if value['binding'] == self._bounded_binding(): + self.color_records = self._parse_colors(value['colors']) + except (OSError, ValueError, KeyError, TypeError): + pass # Disposable display hints never control journal validity. + + def colors(self, target, groups=None): + """Immutable parent→palette slots, persisted where known, stable otherwise. + + Historical merges without optional display hints use numeric parent order. + ``groups`` lets a caller reuse an already validated exact partition. + """ + groups = self.parents(target) if groups is None else groups + saved = self.color_records.get(int(target), {}) + colors, used = {}, set() + for parent in groups: + preferred = saved.get(parent) + if preferred is None: + preferred = next( + ( + value[parent] + for value in reversed(list(self.color_records.values())) + if parent in value + ), + None, + ) + if preferred is None or preferred in used: + preferred = next(i for i in range(len(groups) + len(used) + 1) if i not in used) + colors[parent] = preferred + used.add(preferred) + return MappingProxyType(colors) + + def _load(self): + if not self.path.exists(): + return + try: + with self.path.open('rb') as stream, np.load(stream, allow_pickle=False) as data: + if int(data['version']) != 1 or str(data['fingerprint']) != _fingerprint( + self.controller.supervisor.clustering.spike_clusters, self.controller.model + ): + raise ValueError('saved assignments differ from recorded lineage') + catalog = json.loads(str(data['catalog'])) + if not isinstance(catalog, dict): + raise ValueError('invalid lineage catalog') + self.known_merges = {int(target) for target in catalog} + if 'known_merges' in data: + known = json.loads(str(data['known_merges'])) + if not isinstance(known, list) or any( + type(i) is not int or i < 0 for i in known + ): + raise ValueError('invalid recorded merge index') + self.known_merges.update(known) + records = {} + for target, parents in catalog.items(): + target = int(target) + groups = {} + for parent in parents: + ids = data[f'g_{target}_{parent}'] + if ( + ids.dtype.kind not in 'iu' + or ids.ndim != 1 + or ( + len(ids) + and ( + ids[0] < 0 + or ids[-1] >= len(self.controller.model.spike_times) + or np.any(ids[1:] <= ids[:-1]) + ) + ) + ): + raise ValueError('invalid parent spike membership') + ids.flags.writeable = False + groups[int(parent)] = ids + if len(groups) < 2: + raise ValueError('a merge needs at least two parents') + records[target] = groups + self.records = records + if 'origins' in data: + origins = json.loads(str(data['origins'])) + if not isinstance(origins, dict) or any( + type(value) is not int or value < 0 for value in origins.values() + ): + raise ValueError('invalid restored parent origins') + self.origins = {int(child): parent for child, parent in origins.items()} + if 'restorations' in data: + restorations = json.loads(str(data['restorations'])) + if not isinstance(restorations, dict) or any( + not isinstance(children, list) + or len(children) < 2 + or len(set(children)) != len(children) + or any(type(c) is not int or c < 0 for c in children) + for children in restorations.values() + ): + raise ValueError('invalid restored merge history') + self.restorations = {int(t): children for t, children in restorations.items()} + try: + self.color_records = self._parse_colors(json.loads(str(data['color_indices']))) + except (OSError, ValueError, KeyError, TypeError, BadZipFile): + self.color_records = {} + except (OSError, ValueError, KeyError, TypeError, BadZipFile) as error: + logger.warning('Merge-parent history unavailable: %s.', error) + self.records = {} + self.origins = {} + self.restorations = {} + + def _on_saved(self, sender): + if hasattr(self.controller, 'bounded_session'): + # The journal is already committed; optional cache failures must not + # turn a successful curation save into a reported failure. + try: + path = self._bounded_color_path() + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, filename = tempfile.mkstemp(prefix='.parent-colors-', dir=path.parent) + try: + with os.fdopen(descriptor, 'w') as stream: + json.dump( + {'binding': self._bounded_binding(), 'colors': self.color_records}, + stream, + ) + os.replace(filename, path) + finally: + if os.path.exists(filename): + os.unlink(filename) + except (OSError, ValueError, TypeError): + logger.debug('Could not save optional parent colors.', exc_info=True) + return + live = self.controller.supervisor.clustering.spikes_per_cluster + # Keep nested ancestry reachable through live merged or restored units. + # A restored alias shares immutable partitions with its historical unit. + reachable, pending = set(), [*live, *self.restorations] + store = getattr(self.controller.supervisor, 'merge_propositions', None) + if store is not None: + # Historical accepted results anchor exact reassembly after Save/reopen. + pending.extend( + review.result_unit_id + for review in store.catalog.reviews.values() + if review.result_unit_id is not None + ) + while pending: + target = pending.pop() + if target in reachable: + continue + reachable.add(target) + pending.extend(self.records.get(target, {})) + if target in self.origins: + pending.append(self.origins[target]) + records = { + target: groups for target, groups in self.records.items() if target in reachable + } + arrays = { + f'g_{target}_{parent}': ids + for target, groups in records.items() + for parent, ids in groups.items() + } + arrays.update( + version=np.asarray(1), + fingerprint=np.asarray( + _fingerprint( + self.controller.supervisor.clustering.spike_clusters, self.controller.model + ) + ), + catalog=np.asarray(json.dumps({str(t): sorted(g) for t, g in records.items()})), + known_merges=np.asarray(json.dumps(sorted(self.known_merges & reachable))), + origins=np.asarray( + json.dumps({t: p for t, p in self.origins.items() if t in reachable}) + ), + restorations=np.asarray(json.dumps(self.restorations)), + color_indices=np.asarray( + json.dumps({t: self.color_records[t] for t in records if t in self.color_records}) + ), + ) + descriptor, filename = tempfile.mkstemp( + prefix='.phy-parents-', suffix='.npz', dir=self.path.parent + ) + try: + with os.fdopen(descriptor, 'wb') as stream: + np.savez(stream, **arrays) + stream.flush() + os.fsync(stream.fileno()) + os.replace(filename, self.path) + finally: + if os.path.exists(filename): + os.unlink(filename) + + @staticmethod + def _check_partition(groups, expected): + if not groups or any(len(ids) == 0 for ids in groups.values()): + raise ValueError('Recorded parents contain an empty component.') + union = np.sort(np.concatenate(list(groups.values()))) + if not np.array_equal(union, expected) or np.any(union[1:] == union[:-1]): + raise ValueError('Recorded parents do not exactly partition this unit.') + + def _historical_origin(self, unit): + visited = set() + while unit in self.origins: + if unit in visited: + raise ValueError('Recorded parent identity aliases contain a cycle.') + visited.add(unit) + unit = self.origins[unit] + return int(unit) + + def _recursive_groups(self, target, expected): + result, visited = {}, set() + pending = [(target, expected)] + while pending: + unit, rows = pending.pop() + if unit in visited: + raise ValueError( + 'Recorded merge ancestry repeats a component or contains a cycle.' + ) + visited.add(unit) + groups = self.records.get(unit) + if groups is None: + if unit in self.known_merges: + raise ValueError( + 'Recorded merge ancestry is incomplete; no assignments changed.' + ) + origin = self._historical_origin(unit) + if origin in result: + raise ValueError( + 'Recorded merge ancestry has duplicate historical identities.' + ) + result[origin] = rows + continue + self._check_partition(groups, rows) + pending.extend(reversed(list(groups.items()))) + return result + + def parents(self, target, *, recursive=False): + target = int(target) + live = self.controller.supervisor.clustering.spikes_per_cluster + if target not in live: + raise ValueError('Choose a current merged unit.') + session = getattr(self.controller, 'bounded_session', None) + if session is not None: + _, groups = session.restore_parent_groups(target, recursive=recursive) + else: + groups = self.records.get(target) + if groups is None: + raise ValueError( + 'Merge parents unavailable: this merge predates recorded lineage.' + ) + if recursive: + groups = self._recursive_groups(target, live[target]) + # Check exact partition, including splits, undo/redo and external changes. + self._check_partition(groups, live[target]) + result = {} + saved = self.color_records.get(target, {}) + for parent in sorted(groups, key=lambda p: (saved.get(p, len(colormaps.default)), p)): + ids = np.asarray(groups[parent]).view() + ids.flags.writeable = False + result[int(parent)] = ids + return MappingProxyType(result) + + def reassembled_results(self, catalog): + """Project accepted ordinary memberships without rescanning on selection changes.""" + reviews = tuple( + (key, value.result_unit_id, value.applied_unit_ids) + for key, value in catalog.reviews.items() + if value.result_unit_id is not None + ) + signature = self._membership_revision, reviews + if self._reassembly_cache is not None and self._reassembly_cache[0] == signature: + return self._reassembly_cache[1] + clustering = self.controller.supervisor.clustering + result = {} + for key, target, applied in reviews: + groups = self.records.get(target) + if not groups: + continue + rows = np.sort(np.concatenate(list(groups.values()))) + if not len(rows) or np.any(rows[1:] == rows[:-1]): + continue + try: + self._recursive_groups(target, rows) + except ValueError: + continue # Broken ancestry is never proof of a live acceptance. + units = np.unique(clustering.spike_clusters[rows]) + if len(units) != 1: + continue + current = int(units[0]) + entry = catalog.entry_for(key) + if entry is None or entry.proposition is None: + continue + result[key] = { + 'result_unit_id': current, + 'modified': ( + applied != entry.proposition.unit_ids + or len(clustering.spikes_per_cluster[current]) != len(rows) + ), + } + self._reassembly_cache = signature, result + return result + + def proposition_retirements(self): + """Current ordinary merge/restore paths, excluding discarded Undo branches.""" + live = self.controller.supervisor.clustering.spikes_per_cluster + pending, visited, retired = [*live, *self.restorations], set(), {} + controlled = {str(unit) for unit in self.known_merges} + controlled.update(str(parent) for groups in self.records.values() for parent in groups) + while pending: + target = pending.pop() + if target in visited: + continue + visited.add(target) + for parent in self.records.get(target, {}): + if parent not in live: + retired[str(parent)] = {'operation': 'merge', 'replacements': [target]} + pending.append(parent) + retired.update( + { + str(target): {'operation': 'restore_parents', 'replacements': children} + for target, children in self.restorations.items() + } + ) + controlled.update(str(target) for target in self.restorations) + return controlled, retired + + def full_counts(self, target, groups=None): + """Exact counts from saved summaries/whole-unit merges; splits stay unknown.""" + session = getattr(self.controller, 'bounded_session', None) + if session is None: + return { + p: len(ids) + for p, ids in (self.parents(target) if groups is None else groups).items() + } + return session.restore_parent_counts(target, recursive=False) + + +class ParentProviders: + """Providers over explicit spike arrays, never live cluster-ID lookups. + + Parent IDs belong only to this display. No selector, mutable assignment or + controller provider is replaced. All display sampling uses shared budgets. + """ + + def __init__(self, controller, target, groups): + self.controller, self.target = controller, int(target) + self.model, self.groups = controller.model, groups + self.channels = list(controller.get_best_channels(target)) + self.ids = list(groups) + self.bounded = hasattr(controller, 'bounded_session') + if len(groups) > 16: + raise ValueError('Parent comparison supports at most 16 immediate parents.') + + def sampled(self, parent, per_cluster, total): + from .base import _allocate_spike_counts, _sample_spikes_evenly + + allocated = _allocate_spike_counts( + [len(self.groups[p]) for p in self.ids], per_cluster=per_cluster, total=total + ) + return _sample_spikes_evenly(self.groups[parent], int(allocated[self.ids.index(parent)])) + + def feature_ids(self, parent): + ids = self.sampled( + parent, + getattr(self.controller, 'n_spikes_features', 2500), + getattr(self.controller, 'n_spikes_features_total', 40000), + ) + rows = getattr(self.model, 'features_rows', None) + return np.intersect1d(ids, rows) if rows is not None else ids + + def feature_times(self, parent=None, **kwargs): + ids = self.feature_ids(parent) if parent is not None else np.array([], dtype=np.int64) + return Bunch(data=self.model.spike_times[ids], spike_ids=ids, lim=(0, self.model.duration)) + + def features(self, parent=None, channel_ids=None, **kwargs): + if parent is None: + return Bunch() + ids = self.feature_ids(parent) + if not len(ids): + return Bunch() + channels = self.channels if channel_ids is None else channel_ids + return self.controller._get_spike_features(ids, channels) + + def amplitudes(self, parents, **kwargs): + output = [] + for parent in parents: + if parent is None: + ids = np.array([], dtype=np.int64) + else: + ids = self.sampled( + parent, + self.controller.n_spikes_amplitudes, + self.controller.n_spikes_amplitudes_total, + ) + values = self.model.amplitudes + output.append( + Bunch( + spike_ids=ids, + spike_times=self.model.spike_times[ids], + amplitudes=values[ids].reshape(-1), + ) + ) + return output + + def waveform_ids(self, parent): + from .base import _sample_spikes_evenly + + per_parent = getattr(self.controller, 'n_spikes_waveforms', 100) + total = getattr(self.controller, 'n_spikes_waveforms_total', None) + ids = self.sampled(parent, per_parent, total) + if getattr(self.model, 'spike_waveforms', None) is not None: + ids = np.intersect1d(self.groups[parent], self.model.spike_waveforms.spike_ids) + count = min(per_parent, total // len(self.ids)) if total is not None else per_parent + ids = _sample_spikes_evenly(ids, count) + return ids + + def waveforms(self, parent): + ids = self.waveform_ids(parent) + data = self.model.get_waveforms(ids, self.channels) + if data is None: + raise ValueError('Raw/stored waveforms unavailable for these parents.') + data = data - np.median(data, axis=1)[:, None, :] + data = self.controller.raw_data_filter.apply(data, axis=1) + return Bunch( + data=data, + spike_ids=ids, + channel_ids=self.channels, + channel_labels=self.controller._get_channel_labels(self.channels), + channel_positions=self.model.channel_positions[self.channels], + masks=np.ones((len(data), len(self.channels))), + ) + + def templates(self, parent): + """Template traces weighted by exact membership, never template-based grouping.""" + templates, counts = np.unique( + self.model.spike_templates[self.groups[parent]], return_counts=True + ) + keep = np.argsort(-counts, kind='stable')[:100] + traces, weights = [], [] + for index in keep: + template = self.model.get_template(int(templates[index])) + if not template: + continue + waveform = np.zeros((self.model.n_samples_waveforms, self.model.n_channels)) + waveform[:, template.channel_ids] = template.template + traces.append(waveform[:, self.channels]) + weights.append(counts[index]) + if not traces: + raise ValueError('No template waveforms available for these parent spikes.') + masks = np.tile(np.asarray(weights)[:, None] / max(weights), (1, len(self.channels))) + return Bunch( + data=np.asarray(traces), + masks=masks, + channel_ids=self.channels, + channel_labels=self.controller._get_channel_labels(self.channels), + channel_positions=self.model.channel_positions[self.channels], + ) + + def correlograms(self, parents, bin_size, window_size): + if self.bounded: + from .large_recording.statistics import window_correlograms + + # Only retained evidence rows are visited. No full-source I/O. + ids = np.sort(np.concatenate([self.groups[p] for p in parents])) + labels = np.empty(len(ids), dtype=np.int64) + for index, parent in enumerate(parents): + labels[np.searchsorted(ids, self.groups[parent])] = index + return window_correlograms( + self.model.spike_samples[ids], + labels, + self.controller.evidence_windows, + list(range(len(parents))), + self.model.sample_rate, + bin_size, + window_size, + ) + from .base import _allocate_spike_counts + + budgets = _allocate_spike_counts( + [len(self.groups[p]) for p in self.ids], + per_cluster=self.controller.n_spikes_correlograms, + total=self.controller.n_spikes_correlograms_total, + ) + sampled = [] + for parent in parents: + ids = self.groups[parent] + n = int(budgets[self.ids.index(parent)]) + # Regular thinning can erase short-lag pairs. Independent reproducible + # sampling avoids imposing an artificial refractory period. + if n < len(ids): + ids = ids[np.random.default_rng(parent).choice(len(ids), size=n, replace=False)] + sampled.append(ids) + ids = np.concatenate(sampled) + labels = np.concatenate([np.full(len(s), index) for index, s in enumerate(sampled)]) + times = self.model.spike_times[ids] + order = np.argsort(times, kind='stable') + return correlograms( + times[order], + labels[order], + cluster_ids=np.arange(len(parents)), + sample_rate=self.model.sample_rate, + bin_size=bin_size, + window_size=window_size, + ) + + +class ParentInspection: + """Own review widgets and callbacks; never borrow live providers or curation actions.""" + + def __init__(self, controller): + self.controller = controller + self.lineage = ParentLineage(controller) + controller.supervisor.parent_lineage = self.lineage + controller.supervisor.parent_origins.update(self.lineage.origins) + controller.supervisor._refresh_propositions() + self.window = None + self.views = [] + self._gui = None + connect(self._on_selection, event='select', sender=controller.supervisor) + connect(self._on_mutation, event='cluster', sender=controller.supervisor) + + def _on_selection(self, sender, *args, **kwargs): + self.close_review() + + def _on_mutation(self, sender, *args, **kwargs): + self.close_review() + + def attach(self, gui): + from phy.gui.qt import QEvent, QMenu, QObject + + self.lineage.bind() + self.controller.supervisor._refresh_propositions() + unconnect(self._on_selection, self._on_mutation) + connect(self._on_selection, event='select', sender=self.controller.supervisor) + connect(self._on_mutation, event='cluster', sender=self.controller.supervisor) + self._gui = gui + table = self.controller.supervisor.cluster_view + inspection = self + + class ContextMenu(QObject): + def eventFilter(self, obj, event): + if event.type() != QEvent.ContextMenu: + return False + row = table._row_for_proxy_index(table.table_view.indexAt(event.pos())) + if row is None: + return False + target = int(row['id']) + menu = QMenu(table.table_view) + menu.setToolTipsVisible(True) + restore = menu.addAction('Restore parents in Merge Mode') + action = menu.addAction('Inspect parents (read-only)') + try: + groups = inspection.lineage.parents(target) + if any(not len(ids) for ids in groups.values()): + restore.setEnabled(False) + restore.setToolTip( + 'Every parent needs retained evidence before restoration.' + ) + if len(groups) > 16: + raise ValueError( + 'Parent comparison supports at most 16 immediate parents.' + ) + except ValueError as error: + action.setEnabled(False) + action.setToolTip(str(error)) + if 'groups' not in locals(): + restore.setEnabled(False) + restore.setToolTip(str(error)) + restore.triggered.connect(lambda checked=False: inspection.restore_parents(target)) + action.triggered.connect(lambda checked=False: inspection._try_show(target)) + try: + menu.exec_(event.globalPos()) + finally: + menu.deleteLater() + return True + + self._context_menu = ContextMenu(gui) + table.table_view.viewport().installEventFilter(self._context_menu) + connect(self._on_gui_closed, event='close_accepted', sender=gui) + gui.view_actions.add( + self.show_selected, + name='show_parents', + docstring='Inspect parents (read-only).', + ) + gui.view_actions.add( + self.restore_parents, + name='restore_parents', + docstring='Restore parents in Merge Mode.', + ) + + def restore_parents(self, target=None): + """Restore recorded parents through the native Supervisor command.""" + self.close_review() + try: + return self.controller.supervisor.restore_parents(target) + except ValueError as error: + logger.warning('Cannot restore merge parents: %s', error) + if self._gui is not None: + self._gui.statusBar().showMessage(str(error), 10000) + + def _try_show(self, target): + try: + return self.show(target) + except ValueError as error: + logger.warning('Cannot inspect merge parents: %s', error) + if self._gui is not None: + self._gui.statusBar().showMessage(str(error), 10000) + + def show_selected(self): + selected = self.controller.supervisor.selected + if len(selected) != 1: + raise ValueError('Select one merged unit to show its parents.') + return self.show(selected[0]) + + def show(self, target): + try: + return self._show(target) + except Exception: + self.close_review() + if hasattr(self, '_temporary'): + self._temporary.cleanup() + del self._temporary + self.providers = None + raise + + def _show(self, target): + from phy.cluster.views import AmplitudeView, CorrelogramView, FeatureView, WaveformView + + from ._parent_workspace import ParentWorkspace + + groups = self.lineage.parents(target) + self.close_review() + if self._gui is None: + raise ValueError('Attach the main GUI before inspecting parents.') + if self.controller.supervisor.selected != [target]: + self.controller.supervisor.select([target]) + self.controller.supervisor._settle_selection() + providers = ParentProviders(self.controller, target, groups) + self.providers = providers + self._temporary = tempfile.TemporaryDirectory(prefix='phy-parent-review-') + colors = self.lineage.colors(target, groups) + workspace = ParentWorkspace( + self._gui, + self.controller.supervisor, + target, + groups, + self.lineage.full_counts(target, groups), + colors, + providers.bounded, + Path(self._temporary.name), + self.close_review, + ) + self._workspace = workspace + self.window = window = workspace.gui + self.host_gui = self._gui + self.return_button = workspace.return_button + self.parent_table = workspace.parent_table + ccg = CorrelogramView( + correlograms=providers.correlograms, sample_rate=self.controller.model.sample_rate + ) + ccg.ex_status = ( + 'Read-only parents; selected windows only, raw pair counts.' + if providers.bounded + else 'Read-only parents; sampled pair counts.' + ) + specs = [(ccg, providers.ids)] + waveform_ids = [p for p in groups if len(providers.waveform_ids(p))] + if waveform_ids and ( + getattr(self.controller.model, 'spike_waveforms', None) is not None + or getattr(self.controller.model, 'traces', None) is not None + ): + specs.append( + ( + WaveformView( + waveforms={'waveforms': providers.waveforms}, + sample_rate=self.controller.model.sample_rate, + ), + waveform_ids, + ) + ) + if len(waveform_ids) < len(groups): + workspace.scope.setText( + 'Parents without retained waveforms are omitted from that plot.' + ) + elif getattr(self.controller.model, 'spike_templates', None) is not None: + specs.append( + ( + WaveformView( + waveforms={'templates': providers.templates}, + sample_rate=self.controller.model.sample_rate, + ), + [p for p in groups if len(groups[p])], + ) + ) + workspace.scope.setText( + workspace.scope.text() + + ' Raw/stored waveforms unavailable: showing up to 100 template traces per parent.' + ) + if getattr(self.controller.model, 'amplitudes', None) is not None: + specs.append( + ( + AmplitudeView( + amplitudes=providers.amplitudes, + duration=self.controller.model.duration, + split_is_eligible=lambda: False, + ), + providers.ids, + ) + ) + if ( + getattr(self.controller.model, 'features', None) is not None + or getattr(self.controller.model, 'spike_waveforms', None) is not None + ): + specs.append( + ( + FeatureView( + features=providers.features, attributes={'time': providers.feature_times} + ), + [p for p in groups if len(providers.feature_ids(p))], + ) + ) + try: + for view, ids in specs: + # add_view, deliberately not attach: no global selection/split/ + # channel callbacks and no actions capable of reaching curation. + window.add_view(view, position='right') + view._cluster_color_index_by_id = colors + # Canvas click handlers normally publish channel/time/transfer + # events that ordinary views elsewhere in the application may + # consume. Keep these display-only views local, including when + # the user modifier-clicks; PanZoom remains independently active. + view.on_mouse_click = lambda event: None + self.views.append(view) + if ids: + view.on_select(cluster_ids=ids) + # Two columns with two rows leave the correlogram matrix usable. + # The same arrangement gracefully handles unavailable data views. + if len(self.views) > 1: + window.splitDockWidget(self.views[0].dock, self.views[1].dock, Qt.Horizontal) + if len(self.views) > 2: + window.splitDockWidget(self.views[0].dock, self.views[2].dock, Qt.Vertical) + if len(self.views) > 3: + window.splitDockWidget(self.views[1].dock, self.views[3].dock, Qt.Vertical) + if len(self.views) > 1: + window.resizeDocks([v.dock for v in self.views[:2]], [610, 460], Qt.Horizontal) + if len(self.views) > 2: + window.resizeDocks( + [self.views[0].dock, self.views[2].dock], [430, 300], Qt.Vertical + ) + if len(self.views) > 3: + window.resizeDocks( + [self.views[1].dock, self.views[3].dock], [430, 300], Qt.Vertical + ) + workspace.show() + return window + except Exception: + self.close_review() + raise + + def _dispose_review(self): + for view in self.views: + owned = ( + view, + view.canvas, + getattr(view, 'dock', None), + getattr(view.canvas, 'panzoom', None), + getattr(view.canvas, 'axes', None), + *getattr(view.canvas, '_attached', ()), + ) + # None is a meaningful sender in phylib's registry. Passing it + # would disconnect unrelated application-wide callbacks. + unconnect(*(obj for obj in owned if obj is not None)) + with suppress(RuntimeError): # Qt may already have destroyed the owning window. + view.canvas.close() + view._closed = True + self.views = [] + if self.window is not None: + unconnect(self.window) + self.window = None + self.providers = None + if hasattr(self, '_temporary'): + self._temporary.cleanup() + del self._temporary + + def close_review(self): + if self.window is None or getattr(self, '_closing', False): + return + self._closing = True + try: + # Mark the workspace inactive before restoration can flush deferred selections. + self._workspace.restore() + self._dispose_review() + self._workspace = None + finally: + self._closing = False + + def _on_gui_closed(self, sender): + # Restore the workspace before geometry saving, after close vetoes. + self.close_review() + + def close(self): + self.close_review() + if self._gui is not None and hasattr(self, '_context_menu'): + with suppress(RuntimeError): + self.controller.supervisor.cluster_view.table_view.viewport().removeEventFilter( + self._context_menu + ) + self._gui = None + self.lineage.close() + unconnect(self._on_selection, self._on_mutation, self._on_gui_closed) diff --git a/phy/apps/_parent_workspace.py b/phy/apps/_parent_workspace.py new file mode 100644 index 000000000..c0ad1c552 --- /dev/null +++ b/phy/apps/_parent_workspace.py @@ -0,0 +1,260 @@ +"""An embedded read-only comparison workspace with reversible GUI ownership.""" + +from contextlib import suppress + +from phylib.utils import unconnect + +from phy.gui import GUI +from phy.gui.qt import ( + QAbstractItemView, + QAction, + QApplication, + QColor, + QDockWidget, + QEvent, + QHeaderView, + QKeySequence, + QLabel, + QObject, + Qt, + QTableWidget, + QTableWidgetItem, +) +from phy.utils.color import selected_cluster_color + +_DARK_STYLE = """ +QMainWindow, QToolBar, QDockWidget, QTableWidget { background: #171b22; color: #edf0f5; } +QToolBar { border: 0; padding: 5px; spacing: 12px; } +QToolButton { color: #f5f7fa; background: #303945; border: 1px solid #526174; + border-radius: 4px; padding: 7px 11px; } +QToolButton:hover, QToolButton:focus { background: #425166; } +QHeaderView::section { color: #d7dce4; background: #242b35; border: 0; padding: 5px; } +QTableWidget { border: 0; gridline-color: #2e3642; } +QDockWidget::title { color: #d7dce4; background: #242b35; padding: 4px; } +QScrollBar { background: #202630; } +""" + + +class _ReviewGUI(GUI): + """A Qt.Widget child, with no independent window or persistent close path.""" + + def closeEvent(self, event): + event.accept() + self._return_to_unit() + + +class ParentWorkspace(QObject): + """Own the temporary host dock, keyboard guard and exact restoration snapshot.""" + + def __init__( + self, host, supervisor, target, groups, counts, colors, bounded, config_dir, on_back + ): + super().__init__(host) + self.host, self.supervisor, self.on_back = host, supervisor, on_back + self.active = True + self.original_state = host.saveState() + self.original_focus = QApplication.focusWidget() + self.original_docks = [ + d for d in host.findChildren(QDockWidget) if d.parentWidget() is host + ] + self.visibility = {d: not d.isHidden() for d in self.original_docks} + self.action_states = {a: a.isEnabled() for a in host.findChildren(QAction)} + self._action_guards = [] + self._blocked_sequences = [] + + try: + self._build(target, groups, counts, colors, bounded, config_dir, on_back) + except Exception: + # Construction has not touched the host layout/actions yet, but the + # child GUI already owns global event-registry callbacks. + if hasattr(self, 'gui'): + unconnect(self.gui) + self.gui.setParent(None) + self.gui.deleteLater() + if hasattr(self, 'host_dock'): + self.host_dock.deleteLater() + self.active = False + self.deleteLater() + raise + + def _build(self, target, groups, counts, colors, bounded, config_dir, on_back): + host = self.host + self.gui = _ReviewGUI( + name='ParentReview', + subtitle=f'Parents of {target}', + config_dir=config_dir, + default_state_path=None, + ) + self.gui.setParent(host, Qt.Widget) + self.gui._return_to_unit = on_back + self.gui.menuBar().hide() + self.gui.statusBar().hide() + self.gui.setStyleSheet(_DARK_STYLE) + self.gui._toolbar.setMovable(False) + self.gui._toolbar.setFloatable(False) + self.gui._toolbar.setToolButtonStyle(Qt.ToolButtonTextOnly) + self.gui.file_actions.add( + on_back, name='return_to_merged_unit', docstring='Back to merged unit' + ) + back = self.gui.file_actions.get('return_to_merged_unit') + back.setText('Back to merged unit') + self.gui._toolbar.addAction(back) + self.return_button = self.gui._toolbar.widgetForAction(back) + self.return_button.setObjectName('parent-review-return') + title = QLabel(f'Parents of {target} · Read only · Esc to return') + title.setStyleSheet('color: #edf0f5; background: transparent; font-size: 13px;') + self.gui._toolbar.addWidget(title) + self.gui._toolbar.show() + + self.parent_table = QTableWidget(len(groups), 4, self.gui) + table = self.parent_table + table.setObjectName('parent-review-table') + table.setHorizontalHeaderLabels( + ('', 'Parent', 'Retained' if bounded else 'Spikes', 'Full') + ) + table.verticalHeader().hide() + table.setEditTriggers(QAbstractItemView.NoEditTriggers) + table.setSelectionMode(QAbstractItemView.NoSelection) + table.setFocusPolicy(Qt.NoFocus) + table.setWordWrap(False) + table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) + table.horizontalHeader().setStretchLastSection(True) + for row, (parent, ids) in enumerate(groups.items()): + color = QColor( + *(round(float(c) * 255) for c in selected_cluster_color(colors[parent])[:3]) + ) + full = counts.get(parent) + values = ('■', str(parent), f'{len(ids):,}', '—' if full is None else f'{full:,}') + for column, value in enumerate(values): + item = QTableWidgetItem(value) + item.setFlags(Qt.ItemIsEnabled) + item.setForeground(color if column == 0 else QColor('#edf0f5')) + item.setTextAlignment( + Qt.AlignCenter if column == 0 else Qt.AlignRight | Qt.AlignVCenter + ) + item.setToolTip( + f'{target} ← {parent}' + + ( + '; full-recording count unavailable' + if full is None + else f'; {full:,} full spikes' + ) + ) + table.setItem(row, column, item) + table.setColumnHidden(3, not bounded) + table.resizeColumnsToContents() + self.table_dock = QDockWidget('Immediate parents', self.gui) + self.table_dock.setObjectName('ParentReviewTable') + self.table_dock.setFeatures(QDockWidget.NoDockWidgetFeatures) + self.table_dock.setWidget(table) + self.table_dock.setMinimumWidth(218) + self.table_dock.setMaximumWidth(280) + self.gui.addDockWidget(Qt.LeftDockWidgetArea, self.table_dock) + self.scope = QLabel( + 'Retained windows only; full counts when known.' + if bounded + else 'Exact parent membership; plots use display sampling.' + ) + self.scope.setWordWrap(True) + self.scope.setStyleSheet('color: #c4ccd7; background: #171b22; padding: 4px;') + self.gui.statusBar().addWidget(self.scope, 1) + self.gui.statusBar().show() + + self.host_dock = QDockWidget(host) + self.host_dock.setObjectName('ParentReviewWorkspace') + self.host_dock.setFeatures(QDockWidget.NoDockWidgetFeatures) + self.host_dock.setTitleBarWidget(QLabel('')) + self.host_dock.setWidget(self.gui) + + def _activate(self): + for dock in self.original_docks: + if dock is not self.supervisor.cluster_view.dock: + dock.hide() + self.host.addDockWidget(Qt.RightDockWidgetArea, self.host_dock) + self.host.resizeDocks( + [self.supervisor.cluster_view.dock, self.host_dock], + [220, max(600, self.host.width() - 230)], + Qt.Horizontal, + ) + + navigation = {'select', 'next', 'previous', 'first', 'last', 'next_best', 'previous_best'} + allowed = { + group.get(name) + for group in self.host.actions + if group is self.supervisor.select_actions + for name in navigation + if group.get(name) is not None + } + for action in self.action_states: + if action in allowed or action.text().replace('&', '').lower() in ('exit', 'about'): + continue + self._blocked_sequences.extend(s for s in action.shortcuts() if not s.isEmpty()) + + def guard(action=action): + if self.active and action.isEnabled(): + action.setEnabled(False) + + action.changed.connect(guard) + self._action_guards.append((action, guard)) + action.setEnabled(False) + QApplication.instance().installEventFilter(self) + + def show(self): + self._activate() + self.host_dock.show() + self.gui.show() + self.host_dock.raise_() + self.return_button.setFocus(Qt.OtherFocusReason) + + def eventFilter(self, obj, event): + if not self.active: + return False + if event.type() not in (QEvent.KeyPress, QEvent.ShortcutOverride): + return False + current = obj + while current is not None and current is not self.host: + current = current.parent() + focus = QApplication.focusWidget() + if current is None and (focus is None or focus.window() is not self.host): + return False + if event.key() == Qt.Key_Escape: + event.accept() + if event.type() == QEvent.KeyPress: + self.on_back() + return True + sequence = QKeySequence(int(event.modifiers()) | event.key()) + if event.text() == ':' or any( + s.matches(sequence) == QKeySequence.ExactMatch for s in self._blocked_sequences + ): + event.accept() + return True + return False + + def restore(self): + if not self.active: + return + self.active = False # Visibility/focus changes may synchronously publish selections. + QApplication.instance().removeEventFilter(self) + self.host_dock.hide() + self.host.removeDockWidget(self.host_dock) + self.host_dock.setParent(None) + self.host.restoreState(self.original_state) + for dock, visible in self.visibility.items(): + with suppress(RuntimeError): + dock.setVisible(visible) + for action, guard in self._action_guards: + with suppress(RuntimeError, TypeError): + action.changed.disconnect(guard) + for action, enabled in self.action_states.items(): + with suppress(RuntimeError): + action.setEnabled(enabled) + focus_restored = False + if self.original_focus is not None: + with suppress(RuntimeError): + self.original_focus.setFocus(Qt.OtherFocusReason) + focus_restored = True + if not focus_restored: + with suppress(RuntimeError): + self.supervisor.cluster_view.table_view.setFocus(Qt.OtherFocusReason) + self.host_dock.deleteLater() + self.deleteLater() diff --git a/phy/apps/base.py b/phy/apps/base.py index fa3082627..7079c70ff 100644 --- a/phy/apps/base.py +++ b/phy/apps/base.py @@ -1245,6 +1245,10 @@ def __init__( # Set up the Selector instance, responsible for selecting the spikes for display. self._set_selector() + from ._parent_review import ParentInspection + + self.parent_inspection = ParentInspection(self) + emit('controller_ready', self) def close(self, close_model=True): @@ -1253,6 +1257,7 @@ def close(self, close_model=True): Closing a GUI does not necessarily end a controller's lifetime: callers may recreate a GUI around the same model. Resource cleanup is therefore explicit. """ + self.parent_inspection.close() self._trace_prefetch.close() if close_model and not self._model_closed: _close_trace_reader(getattr(self.model, 'traces', None)) @@ -2460,7 +2465,11 @@ def create_gui(self, default_views=None, **kwargs): subtitle=str(self.dir_path), config_dir=self.config_dir, local_path=self.cache_dir / 'state.json', - default_state_path=Path(inspect.getfile(self.__class__)).parent / 'static/state.json', + default_state_path=getattr( + self, + 'default_state_path', + Path(inspect.getfile(self.__class__)).parent / 'static/state.json', + ), view_creator=self.view_creator, default_views=default_views, enable_threading=self._enable_threading, @@ -2509,6 +2518,7 @@ def on_view_attached(view, gui_): gui.set_default_actions() self.create_misc_actions(gui) gui.create_views() + self.parent_inspection.attach(gui) # Bind the `select_more` event to add clusters to the existing selection. @connect @@ -2522,9 +2532,6 @@ def on_request_select(sender, cluster_ids): # Prompt save. @connect(sender=gui) def on_close(sender): - unconnect(on_view_attached, self) - unconnect(on_select_more, self) - unconnect(on_request_select, self) # Show save prompt if an action was done. do_prompt_save = kwargs.get('do_prompt_save', True) if do_prompt_save and self.supervisor.is_dirty(): # pragma: no cover @@ -2540,6 +2547,8 @@ def on_close(sender): handler = StatusBarHandler(gui) handler.setLevel(logging.INFO) logging.getLogger('phy').addHandler(handler) + # Embedders may destroy the GUI without sending an accepted close. + gui.destroyed.connect(lambda: logging.getLogger('phy').removeHandler(handler)) # Save the memcache when closing the GUI. @connect(sender=gui) # noqa @@ -2563,8 +2572,15 @@ def on_close(sender): # noqa gui.state['GUI_VERSION'] = self.gui_version self.context.save_memcache() - # Remove the status bar handler when closing the GUI. + @connect(event='closed', sender=gui) + def on_closed(sender): + # Close callbacks may veto an attempt. Keep live selection hooks + # and logging until the GUI has actually accepted closure. + unconnect(on_view_attached, self) + unconnect(on_select_more, self) + unconnect(on_request_select, self) logging.getLogger('phy').removeHandler(handler) + unconnect(on_closed) try: emit('gui_ready', self, gui) diff --git a/phy/apps/large_recording/__init__.py b/phy/apps/large_recording/__init__.py new file mode 100644 index 000000000..373145000 --- /dev/null +++ b/phy/apps/large_recording/__init__.py @@ -0,0 +1 @@ +"""Bounded evidence preparation and full-sorting curation replay.""" diff --git a/phy/apps/large_recording/_immutable.py b/phy/apps/large_recording/_immutable.py new file mode 100644 index 000000000..71cccfd01 --- /dev/null +++ b/phy/apps/large_recording/_immutable.py @@ -0,0 +1,66 @@ +"""JSON-compatible immutable records for shared journal/runtime history.""" + +import sys +from dataclasses import is_dataclass + + +def _readonly(*args, **kwargs): + raise TypeError('Committed bounded curation records are read-only.') + + +class FrozenDict(dict): + __setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = _readonly + __ior__ = _readonly + + def __deepcopy__(self, memo): + return self + + +class FrozenList(list): + __setitem__ = __delitem__ = append = clear = extend = insert = pop = remove = _readonly + reverse = sort = __iadd__ = __imul__ = _readonly + + def __deepcopy__(self, memo): + return self + + +def freeze(value): + if isinstance(value, (FrozenDict, FrozenList)): + return value + if isinstance(value, dict): + return FrozenDict({key: freeze(item) for key, item in value.items()}) + if isinstance(value, list): + return FrozenList(freeze(item) for item in value) + if isinstance(value, tuple): + return tuple(freeze(item) for item in value) + return value + + +def thaw(value): + if isinstance(value, dict): + return {key: thaw(item) for key, item in value.items()} + if isinstance(value, list): + return [thaw(item) for item in value] + if isinstance(value, tuple): + return tuple(thaw(item) for item in value) + return value + + +def retained_bytes(*values): + """Conservatively count nested Python payloads, deduplicating shared objects.""" + pending, seen, total = list(values), set(), 0 + while pending: + value = pending.pop() + identity = id(value) + if identity in seen: + continue + seen.add(identity) + total += sys.getsizeof(value) + if isinstance(value, dict): + pending.extend(value.keys()) + pending.extend(value.values()) + elif isinstance(value, (list, tuple)): + pending.extend(value) + elif is_dataclass(value): + pending.append(vars(value)) + return total diff --git a/phy/apps/large_recording/adapter.py b/phy/apps/large_recording/adapter.py new file mode 100644 index 000000000..7d37c2e72 --- /dev/null +++ b/phy/apps/large_recording/adapter.py @@ -0,0 +1,757 @@ +"""Manifest-gated template controller for bounded recording evidence.""" + +from copy import deepcopy +from functools import partial +from pathlib import Path + +import numpy as np +from phylib.io.model import get_template_params +from phylib.utils import Bunch, connect, emit, unconnect + +from phy.cluster._propositions import ( + MergePropositionController, + decode_curation_mapping, + decode_review_mapping, +) + +from ..base import _allocate_spike_counts, _sample_spikes_evenly +from ..template.gui import TemplateController +from .curation import BoundedSession +from .model import BoundedTemplateModel +from .statistics import window_correlograms, window_isi +from .supervisor import BoundedSupervisor +from .views import EvidenceAmplitudeView, SampledCorrelogramView, SampledISIView + + +class BoundedTemplateController(TemplateController): + gui_name = 'BoundedTemplateGUI' + # Bounded mode has its own state namespace and initial view list. Importing + # ordinary saved dock geometry would suppress the new evidence views. + default_state_path = None + default_views = ( + 'UnitStabilityView', + 'WaveformView', + 'EvidenceAmplitudeView', + 'FeatureView', + 'ProbeView', + 'SampledISIView', + 'SampledCorrelogramView', + ) + + def __init__(self, dir_path=None, model=None, **kwargs): + if model is not None: + raise ValueError( + 'Open bounded packages from their directory, without a supplied model.' + ) + self._recovery_enabled = kwargs.pop('recovery_enabled', True) + self._recovery_root = kwargs.pop('recovery_root', None) + if self._recovery_root is None and kwargs.get('config_dir') is not None: + # Explicit controller configurations keep their recovery data local + # to that configuration; the normal default is persistent app data. + self._recovery_root = Path(kwargs['config_dir']) / 'recovery' + self.bounded_session = BoundedSession(dir_path) + self.evidence_window_index = 0 + kwargs['enable_threading'] = False + kwargs.update(get_template_params(Path(dir_path) / 'params.py')) + kwargs.pop('dir_path', None) + super().__init__(dir_path=dir_path, **kwargs) + + def _create_model(self, dir_path=None, **kwargs): + model = BoundedTemplateModel(dir_path=dir_path, session=self.bounded_session, **kwargs) + if model.sample_rate != self.bounded_session.manifest['sample_rate']: + model.close() + raise ValueError('Bounded params sampling rate disagrees with the manifest.') + model.spike_clusters = self.bounded_session.assignments.copy() + model.metadata = deepcopy(self.bounded_session.metadata) + model.duration = self.bounded_session.manifest['num_samples'] / model.sample_rate + + def reject_save(*args, **kwargs): + raise ValueError('Save bounded curation through supervisor.save() as one transaction.') + + model.save_spike_clusters = reject_save + model.save_metadata = reject_save + model.save_spikes_subset_waveforms = reject_save + model.freeze_source() + return model + + def _cache_methods(self): + # Ordinary persistent feature caches omit the current evidence window. + # Bounded queries are already capped; evaluate them against live state. + return + + def close(self, close_model=True): + recovery = getattr(self, 'recovery', None) + if recovery is not None: + recovery.close() + actions = getattr(self, '_summary_store_actions', None) + if actions is not None: + actions.close() + cleanup = getattr(self, '_live_summary_cleanup', None) + if cleanup is not None: + cleanup() + service = getattr(self, '_live_summaries', None) + if service is not None: + service.close() + self._live_summaries = None + super().close(close_model=close_model) + if close_model: + self.bounded_session.close() + + def _attach_live_summaries(self, gui): + service = self._live_summaries + gui.state.add_local_keys(['LiveSummaries.source_path']) + source_path = gui.state.get('LiveSummaries', {}).get('source_path') + if source_path: + service.retry(source_path=source_path) + + def refresh_summaries(): + if gui._closed: + return + supervisor = self.supervisor + data = supervisor.cluster_info + for view in ( + supervisor.cluster_view, + supervisor.similarity_view, + supervisor.merge_view, + ): + if view is not None: + view.change(data) + emit('bounded_summary_changed', supervisor) + + @connect(event='bounded_state_changed', sender=self.supervisor) + def on_state(sender): + service.synchronize() + + def cleanup(): + service.suspend() + service.changed.disconnect(refresh_summaries) + unconnect(on_state, on_closed) + self._live_summary_cleanup = None + + @connect(event='closed', sender=gui) + def on_closed(sender): + cleanup() + + service.changed.connect(refresh_summaries) + self._live_summary_cleanup = cleanup + + @gui.file_actions.add + def retry_full_summaries(): + """Retry computing exact full-recording summaries after a split.""" + service.retry() + + @gui.file_actions.add(prompt=True) + def locate_summary_source(path): + """Locate the original source directory for exact summary computation.""" + source_path = Path(path).expanduser().resolve() + gui.state['LiveSummaries'] = {'source_path': str(source_path)} + service.retry(source_path=source_path) + + service.resume() + + def get_live_summary(self, cluster_id): + service = getattr(self, '_live_summaries', None) + return None if service is None else service.get_summary(int(cluster_id)) + + def get_summary_status(self, cluster_id): + service = getattr(self, '_live_summaries', None) + return ( + 'Split evidence pending full-data replay.' + if service is None + else service.status(int(cluster_id)) + ) + + def _set_supervisor(self): + session = self.bounded_session + propositions = self._load_merge_propositions() + self.supervisor = BoundedSupervisor( + spike_clusters=self.model.spike_clusters.copy(), + cluster_groups=self.model.metadata.get('group', {}), + cluster_metrics=self.cluster_metrics, + metadata_independent_metrics=self._metadata_independent_metrics, + cluster_labels=self.model.metadata, + similarity=self.similarity_functions[self.similarity], + session=session, + merge_propositions=propositions, + ) + self.supervisor._validate_native() + connect(self._on_curation_saved, event='curation_saved', sender=self.supervisor) + from .recovery_gui import RecoveryCoordinator + + self.recovery = RecoveryCoordinator( + self, root=self._recovery_root, enabled=self._recovery_enabled + ) + self.supervisor.recovery = self.recovery + + def _load_merge_propositions(self): + session = self.bounded_session + session.validate_proposition_documents() + self._merge_proposition_sha256 = None + if not self.enable_merge_propositions: + return None + item = session.proposition_documents.get('curation.json') + if item is None: + return None + from .curation import _read_json + + catalog = decode_curation_mapping( + _read_json(session.path / item['filename']), retired_units=session.retired_units + ) + self._merge_proposition_sha256 = item['sha256'] + reviews = session.extra_documents.get('curation_review.json') + if reviews is not None: + _, mapping = decode_review_mapping(reviews) + catalog = catalog._replace(reviews=mapping) + return MergePropositionController(catalog) + + def _set_cluster_metrics(self): + super()._set_cluster_metrics() + self.cluster_metrics['full_count'] = self.get_full_count + self.cluster_metrics['evidence_count'] = lambda c: self.supervisor.n_spikes(c) + self.cluster_metrics['waveform_count'] = self.get_waveform_count + self.cluster_metrics['evidence'] = lambda c: ( + self.get_summary_status(c) if self.get_full_count(c) is None else 'sampled windows' + ) + # Snapshot actual providers before plugins attach. Replacing even a + # built-in metric name later invalidates its membership-only guarantee. + self._metadata_independent_metrics = dict(self.cluster_metrics) + + def _set_view_creator(self): + super()._set_view_creator() + for name in ( + 'ISIView', + 'CorrelogramView', + 'FiringRateView', + 'TraceView', + 'TraceImageView', + ): + self.view_creator.pop(name, None) + self.view_creator.pop('AmplitudeView', None) + self.view_creator['EvidenceAmplitudeView'] = self.create_evidence_amplitude_view + self.view_creator['UnitStabilityView'] = self.create_unit_stability_view + self.view_creator['SampledISIView'] = lambda: SampledISIView(cluster_stat=self._get_isi) + self.view_creator['SampledCorrelogramView'] = self.create_sampled_correlogram_view + + def create_sampled_correlogram_view(self): + """Create a sampled correlogram view with row-cluster transfer.""" + + def proposition_context(): + supervisor = self.supervisor + # Rendering must not project/mutate the catalog: table model signals + # can arrive between a merge's prepared and committed review states. + controller = supervisor.merge_propositions + table = supervisor.merge_propositions_view + return ( + controller.catalog if controller is not None else None, + supervisor._active_merge_proposition_keys(), + table.visible_keys() if table is not None else None, + ) + + view = SampledCorrelogramView( + correlograms=partial(self._window_correlograms, return_baseline=True), + exclusion_correlograms=partial(self._window_correlograms, return_baseline=True), + proposition_context=proposition_context, + sample_rate=self.model.sample_rate, + ) + + @connect(sender=view) + def on_request_correlogram_transfer(sender, row_cluster_id, column_cluster_id): + # The row determines the target for both diagonal and off-diagonal cells. + self.supervisor.transfer_cluster(row_cluster_id) + + @connect(event='merge_propositions_changed', sender=self.supervisor) + def on_propositions_changed(sender): + view.refresh_proposition_labels() + + table_signals = [] + + def on_proposition_table_changed(*args): + view.refresh_proposition_labels() + + @connect(sender=view) + def on_view_attached(view_, gui): + connect(on_gui_closed, event='closed', sender=gui) + table = self.supervisor.merge_propositions_view + if table is not None: + # Qt model signals cover clearing a filter as well as applying + # it; Table's table_filter event only covers nonempty filters. + table_signals.extend( + ( + table._proxy.rowsInserted, + table._proxy.rowsRemoved, + table._proxy.modelReset, + table._proxy.layoutChanged, + ) + ) + for signal in table_signals: + signal.connect(on_proposition_table_changed) + + def cleanup(): + for signal in table_signals: + signal.disconnect(on_proposition_table_changed) + table_signals.clear() + unconnect( + on_request_correlogram_transfer, + on_propositions_changed, + on_proposition_table_changed, + on_view_attached, + on_close_view, + on_gui_closed, + ) + + def on_gui_closed(sender): + cleanup() + + @connect(sender=view) + def on_close_view(view_, gui): + cleanup() + + return view + + def _get_waveforms_dict(self): + functions = super()._get_waveforms_dict() + if not self.bounded_session.manifest['capabilities']['stored_waveforms']: + functions.pop('waveforms', None) + functions.pop('mean_waveforms', None) + return functions + + def create_waveform_view(self): + view = super().create_waveform_view() + if view is None: + return + plot = view.plot + + def plot_and_clear_preview(**kwargs): + # Sampling, waveform mode, and channel layout may change the drawn + # traces. Require a fresh preview rather than leaving stale colors. + result = plot(**kwargs) + for amplitude_view in getattr(self, '_evidence_amplitude_views', ()): + amplitude_view.clear_amplitude_split_threshold() + return result + + view.plot = plot_and_clear_preview + return view + + def create_feature_view(self): + if ( + self.model.features is None + and not self.bounded_session.manifest['capabilities']['stored_waveforms'] + ): + return + view = super().create_feature_view() + if view is not None: + view.ex_status = self._window_status() + return view + + def _source_units(self, cluster_id): + version = self.bounded_session.membership_revision + cached = getattr(self, '_lineage_cache', None) + if cached is not None and cached[0] is version: + return cached[1].get(int(cluster_id)) + from .live_summaries import membership_expressions + + def sources(expression): + if expression['kind'] == 'source': + return {expression['unit']} + if expression['kind'] == 'split': + return None + parts = [sources(part) for part in expression['parts']] + return None if any(part is None for part in parts) else set.union(*parts) + + units = { + unit: sources(expression) + for unit, expression in membership_expressions( + self.bounded_session.unit_ids, self.bounded_session.events + ).items() + } + self._lineage_cache = version, units + return units.get(int(cluster_id)) + + def get_full_count(self, cluster_id): + units = self._source_units(cluster_id) + if units is None: + summary = self.get_live_summary(cluster_id) + if summary is not None: + return int(np.sum(summary['counts'])) + service = getattr(self, '_live_summaries', None) + return None if service is None else service.total_count(int(cluster_id)) + if not hasattr(self, '_full_counts'): + self._full_counts = dict( + zip(self.bounded_session.unit_ids, self.bounded_session.manifest['counts']) + ) + counts = self._full_counts + return sum(int(counts[c]) for c in units) + + def get_waveform_count(self, cluster_id): + stored = self.model.spike_waveforms + if stored is None: + return 0 + if ( + not hasattr(self, '_waveform_membership_cache') + or self._waveform_membership_cache[0] is not self.bounded_session.membership_revision + ): + labels = self.supervisor.clustering.spike_clusters[stored.spike_ids] + ids, counts = np.unique(labels, return_counts=True) + self._waveform_membership_cache = ( + self.bounded_session.membership_revision, + dict(zip(ids, counts)), + ) + return int(self._waveform_membership_cache[1].get(cluster_id, 0)) + + def get_mean_firing_rate(self, cluster_id): + count = self.get_full_count(cluster_id) + if count is None: + return None + intervals = np.asarray(self.bounded_session.manifest['valid_intervals']) + exposure = np.sum(intervals[:, 1] - intervals[:, 0]) / self.model.sample_rate + return count / exposure + + @property + def evidence_windows(self): + if not hasattr(self, '_evidence_windows'): + self._evidence_windows = np.load( + self.dir_path / self.bounded_session.manifest['windows_file'] + ) + return self._evidence_windows + + def _get_isi(self, cluster_id): + ids = self.supervisor.clustering.spikes_per_cluster.get(cluster_id, []) + samples = self.model.spike_samples[ids] + return Bunch(data=window_isi(samples, self.evidence_windows, self.model.sample_rate)) + + def _window_correlograms( + self, + cluster_ids, + bin_size, + window_size, + return_baseline=False, + *, + exclusion_ms=0.3, + exclude_auto=False, + exclude_cross=False, + ): + return window_correlograms( + self.model.spike_samples, + self.supervisor.clustering.spike_clusters, + self.evidence_windows, + cluster_ids, + self.model.sample_rate, + bin_size, + window_size, + return_baseline=return_baseline, + exclusion_ms=exclusion_ms, + exclude_auto=exclude_auto, + exclude_cross=exclude_cross, + ) + + def create_unit_stability_view(self): + from .stability import UnitStabilityView + + return UnitStabilityView(self) + + @property + def current_evidence_window(self): + return self.evidence_windows[self.evidence_window_index] + + def _window_ids(self, cluster_id=None): + start, end = self.current_evidence_window + if cluster_id is None: + first, last = np.searchsorted(self.model.spike_samples, [start, end]) + return np.arange(first, last, dtype=np.int64) + ids = self.supervisor.clustering.spikes_per_cluster.get( + cluster_id, np.array([], dtype=np.int64) + ) + times = self.model.spike_samples[ids] + first, last = np.searchsorted(times, [start, end]) + return ids[first:last] + + def _window_time(self, ids): + # Subtract int64 samples before floating conversion, even at hour 1000. + return ( + self.model.spike_samples[ids] - self.current_evidence_window[0] + ) / self.model.sample_rate + + def _get_feature_view_spike_ids(self, cluster_id=None, load_all=False): + ids = self._window_ids(cluster_id) + if self.model.features is None: + if self.model.spike_waveforms is None: + return np.array([], dtype=np.int64) + ids = np.intersect1d(ids, self.model.spike_waveforms.spike_ids) + if getattr(self.model, 'features_rows', None) is not None: + ids = np.intersect1d(ids, self.model.features_rows) + limit = self.n_spikes_features_background if cluster_id is None else self.n_spikes_features + return ids if load_all else _sample_spikes_evenly(ids, limit) + + def _get_feature_view_spike_times(self, cluster_id=None, load_all=False): + ids = self._get_feature_view_spike_ids(cluster_id, load_all=load_all) + if not len(ids): + return + start, end = self.current_evidence_window + return Bunch( + data=self._window_time(ids), + spike_ids=ids, + lim=(0.0, (end - start) / self.model.sample_rate), + ) + + def _resolve_spike_amplitudes(self, spike_ids, name, first_cluster): + if name == 'source': + return self.bounded_session.attributes['amplitudes.npy'].reshape(-1)[spike_ids] + return super()._resolve_spike_amplitudes(spike_ids, name, first_cluster) + + def _evidence_amplitudes(self, cluster_ids, load_all=False, scope='window'): + def eligible_ids(cluster_id=None): + if cluster_id is None: + # Sample conceptual row coordinates before gathering assignments. + # Interactive updates must not scan all retained spikes. + first, last = 0, self.model.n_spikes + if scope == 'window': + first, last = np.searchsorted( + self.model.spike_samples, self.current_evidence_window + ) + count = min(last - first, self.n_spikes_amplitudes_background) + if not count: + return np.array([], dtype=np.int64) + ids = np.arange(count, dtype=np.int64) + if count > 1: + ids *= last - first - 1 + ids //= count - 1 + return ids + first + if scope == 'window': + return self._window_ids(cluster_id) + return self.supervisor.clustering.spikes_per_cluster.get( + cluster_id, np.array([], dtype=np.int64) + ) + + def spike_times(ids): + if scope == 'window': + return self._window_time(ids) + return self.model.spike_samples[ids] / self.model.sample_rate + + active = [c for c in cluster_ids if c is not None] + eligible = [eligible_ids(c) for c in active] + counts = _allocate_spike_counts( + [len(ids) for ids in eligible], + per_cluster=None if load_all else self.n_spikes_amplitudes, + total=None if load_all else self.n_spikes_amplitudes_total, + ) + values = self.bounded_session.attributes['amplitudes.npy'].reshape(-1) + output = [] + if None in cluster_ids: + ids = eligible_ids() + ids = ids[~np.isin(self.supervisor.clustering.spike_clusters[ids], active)] + ids = _sample_spikes_evenly(ids, self.n_spikes_amplitudes_background) + ids = ids[np.isfinite(values[ids])] + output.append( + Bunch(amplitudes=values[ids], spike_ids=ids, spike_times=spike_times(ids)) + ) + for ids, count in zip(eligible, counts): + ids = _sample_spikes_evenly(ids, int(count)) + ids = ids[np.isfinite(values[ids])] + output.append( + Bunch(amplitudes=values[ids], spike_ids=ids, spike_times=spike_times(ids)) + ) + return output + + def create_evidence_amplitude_view(self): + array = self.bounded_session.attributes.get('amplitudes.npy') + if array is None or (array.ndim != 1 and array.shape[1:] != (1,)): + return + start, end = self.current_evidence_window + + def amplitudes(cluster_ids, load_all=False): + return self._evidence_amplitudes( + cluster_ids, load_all=load_all, scope=view.amplitude_scope + ) + + def split_is_eligible(): + return ( + len(self.supervisor.selected) == 1 + and not self.supervisor.selection.state.is_merge_mode + and 'amplitudes.npy' + in self.bounded_session.capabilities['predicate_split_attributes'] + ) + + view = EvidenceAmplitudeView( + amplitudes={'source': amplitudes}, + amplitudes_type='source', + duration=(end - start) / self.model.sample_rate, + split_is_eligible=split_is_eligible, + ) + view._controller = self + self._evidence_amplitude_views = getattr(self, '_evidence_amplitude_views', []) + self._evidence_amplitude_views.append(view) + self._update_amplitude_scope(view) + + @connect(sender=self.supervisor) + def on_select(sender, cluster_ids, **kwargs): + view.clear_amplitude_split_threshold() + self.supervisor._update_graphical_split_action() + + @connect(sender=self.supervisor) + def on_bounded_state_changed(sender): + view.clear_amplitude_split_threshold() + + @connect(event='amplitude_split_preview_changed', sender=view) + def on_preview(sender, **kwargs): + self.supervisor._update_graphical_split_action() + + @connect(event='view_attached', sender=view) + def on_attached(sender, gui): + def visibility_changed(visible): + if not visible: + view.clear_amplitude_split_threshold() + self.supervisor._update_graphical_split_action() + + view.dock.visibilityChanged.connect(visibility_changed) + + @connect(event='selected_channel_changed') + @connect(event='selected_feature_changed') + def on_context_changed(sender): + if getattr(sender, 'gui', None) is self.supervisor.gui: + view.clear_amplitude_split_threshold() + + @connect(event='close_view', sender=view) + def on_close(view_, gui): + view.clear_amplitude_split_threshold() + self._evidence_amplitude_views.remove(view) + for callback in ( + on_select, + on_bounded_state_changed, + on_preview, + on_context_changed, + on_attached, + on_close, + ): + unconnect(callback) + self.supervisor._update_graphical_split_action() + + return view + + def _update_amplitude_scope(self, view): + start, end = self.current_evidence_window + overview = view.amplitude_scope == 'overview' + view.duration = self.model.duration if overview else (end - start) / self.model.sample_rate + if overview: + view.window_caption = 'Sampled overview | All retained evidence windows' + if hasattr(view, 'window_label'): + view.window_label.setText(view.window_caption) + else: + view.set_window_context( + self.evidence_window_index, + start / self.model.sample_rate, + end / self.model.sample_rate, + ) + view.ex_status = ( + 'All retained windows; original recording clock; sampled source amplitudes.' + if overview + else self._window_status() + ) + if hasattr(view, 'time_axis_label'): + view.time_axis_label.setText( + 'Recording time (seconds)' if overview else 'Seconds from window start' + ) + view.canvas.panzoom.reset() + if view.cluster_ids: + view.plot() + view.update_status() + + def _window_status(self): + start, end = self.current_evidence_window + return ( + f'Evidence window {self.evidence_window_index}: {start / self.model.sample_rate:.3f}–' + f'{end / self.model.sample_rate:.3f} s; time axis is seconds from window start; nonfinite amplitudes omitted.' + ) + + def inspect_evidence_window(self, index): + index = int(index) + if not 0 <= index < len(self.evidence_windows): + raise ValueError('Evidence window index is outside the retained plan.') + self.evidence_window_index = index + for view in getattr(self, '_evidence_amplitude_views', ()): + view.amplitude_scope = 'window' + gui = getattr(self.supervisor, 'gui', None) + if gui is not None: + for view in gui.list_views('FeatureView'): + view.ex_status = self._window_status() + view.canvas.panzoom.reset() + if view.cluster_ids: + view.plot() + view.update_status() + + def create_gui(self, *args, **kwargs): + from phy.gui.gui import _prompt_save + + from .recovery_gui import wait_operation + from .recovery_status import attach_checkpoint_status + from .summary_service import LiveSummaryService + + do_prompt_save = kwargs.get('do_prompt_save', True) + offer_recovery = kwargs.pop('offer_recovery', do_prompt_save) + if offer_recovery: + self.recovery.offer_startup() + # Only bounded mode supplies this close handler; ordinary saving and + # prompts remain untouched. Cancellation must leave protection running. + kwargs['do_prompt_save'] = False + if getattr(self, '_live_summaries', None) is None: + self._live_summaries = LiveSummaryService(self.bounded_session) + gui = super().create_gui(*args, **kwargs) + + @connect(event='close', sender=gui) + def recovery_close(sender): + if do_prompt_save and self.supervisor.is_dirty(): + choice = _prompt_save() + if choice == 'cancel': + return False + try: + if choice == 'save': + self.supervisor.save() + if self.supervisor.is_dirty(): + return False + else: + wait_operation(self.recovery.discard(), 'Discarding recovery draft…', gui) + except Exception: + # Status contains the error; preserve the GUI and live work. + return False + + @connect(event='closed', sender=gui) + def recovery_closed(sender): + self.recovery.suspend() + unconnect(recovery_close, recovery_closed) + + self.recovery.start() + attach_checkpoint_status(self, gui) + gui.setWindowTitle( + f'phy — Bounded evidence ({self.model.n_spikes:,} / ' + f'{self.bounded_session.manifest["num_spikes"]:,} spikes)' + ) + + @self.supervisor.actions.add(prompt=True, name='Split by source amplitude') + def split_by_source_amplitude(threshold): + """Split one selected unit below a source amplitude threshold (source units).""" + ids = self.supervisor.selected + if len(ids) != 1: + raise ValueError('Select one unit for a source-amplitude threshold split.') + return self.supervisor.split_source_amplitude(ids[0], float(threshold)) + + @gui.view_actions.add(prompt=True, prompt_default=lambda: self.evidence_window_index) + def inspect_evidence_window(index): + """Inspect a retained evidence window by its zero-based index.""" + self.inspect_evidence_window(index) + + split_action = self.supervisor.actions.get('split') + if split_action is not None: + self.supervisor._update_graphical_split_action() + split_action.setToolTip( + 'Selected-row splits cannot assign unseen source spikes; use a source-amplitude predicate.' + ) + predicate_action = self.supervisor.actions.get('Split by source amplitude') + if predicate_action is not None: + predicate_action.setEnabled( + 'amplitudes.npy' in self.bounded_session.capabilities['predicate_split_attributes'] + ) + + self._attach_live_summaries(gui) + from .summary_task_gui import SummaryStoreActions + + self._summary_store_actions = SummaryStoreActions(self, gui) + return gui diff --git a/phy/apps/large_recording/curation.py b/phy/apps/large_recording/curation.py new file mode 100644 index 000000000..ea8844183 --- /dev/null +++ b/phy/apps/large_recording/curation.py @@ -0,0 +1,1732 @@ +"""Semantic bounded curation and crash-consistent, immutable save generations.""" + +import copy +import hashlib +import json +import os +import shutil +import uuid +import warnings +from collections import OrderedDict +from contextlib import contextmanager +from pathlib import Path + +import numpy as np + +from ._immutable import freeze, thaw +from .metadata import POLICY, complete_schema, validate_schema +from .source import _time_base, hash_json + +MANIFEST = '_phy_curation_manifest.json' +BASE_ASSIGNMENTS = '_phy_spike_clusters_base.npy' +RESTORE_SCRATCH_BYTES = 8 * 1024 * 1024 +HISTORY_CACHE_BYTES = 64 * 1024 * 1024 +BOOLEAN_CAPABILITIES = ( + 'merge', + 'restore_parents', + 'label', + 'split', + 'stored_waveforms', + 'raw_traces', + 'normalized_correlograms', +) + + +def _json_bytes(value): + return ( + json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n' + ).encode() + + +def _digest(value): + return hashlib.sha256(_json_bytes(value)).hexdigest() + + +def _hash_file(path): + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + while chunk := stream.read(1024 * 1024): + digest.update(chunk) + return digest.hexdigest() + + +def _read_json(path): + with Path(path).open(encoding='utf8') as stream: + return json.load(stream) + + +def _write_json(path, value): + with Path(path).open('wb') as stream: + stream.write(_json_bytes(value)) + stream.flush() + os.fsync(stream.fileno()) + + +def _fsync_directory(path): + if os.name != 'nt': + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _safe_file(root, name): + if ( + not isinstance(name, str) + or Path(name).name != name + or name in ('', '.', '..') + or any(c in name for c in ('\\', '\0', '\n', '\r')) + ): + raise ValueError('Manifest/checkpoint filename must be a plain local filename.') + path = Path(root) / name + if path.is_symlink(): + raise ValueError('Manifest/checkpoint files must not be symbolic links.') + return path + + +def _validate_digest(value): + if ( + not isinstance(value, str) + or len(value) != 64 + or any(c not in '0123456789abcdef' for c in value) + ): + raise ValueError('Invalid SHA-256 digest.') + return value + + +@contextmanager +def _commit_lock(root): + """Hold a process-safe OS lock; process exit releases it automatically.""" + with _safe_file(root, 'commit.lock').open('a+b') as stream: + if os.name == 'nt': + import msvcrt + + # Windows byte-range locking requires at least one byte in the file. + stream.seek(0, os.SEEK_END) + if stream.tell() == 0: + stream.write(b'\0') + stream.flush() + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1) + try: + yield + finally: + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(stream.fileno(), fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + + +def _current_pointer(root): + try: + return _read_json(root / 'current.json') + except FileNotFoundError: + return None + + +def _integer(value, name): + if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < 0: + raise ValueError(f'{name} must be a nonnegative integer.') + return int(value) + + +def _validate_capabilities(manifest): + capabilities = manifest.get('capabilities', {}) + if not isinstance(capabilities, dict): + raise ValueError('Bounded capabilities must be a mapping.') + if ( + set(capabilities) + - set(BOOLEAN_CAPABILITIES) + - { + 'full_attributes', + 'predicate_split_attributes', + } + ): + raise ValueError('Unsupported bounded capability declaration.') + result = {} + for name in BOOLEAN_CAPABILITIES: + value = capabilities.get( + name, capabilities.get('merge', False) if name == 'restore_parents' else False + ) + if type(value) is not bool: + raise ValueError(f'Bounded capability {name!r} must be a boolean.') + result[name] = value + if result['split']: + raise ValueError('General selected-row splits are unsupported in bounded mode.') + for name in ('full_attributes', 'predicate_split_attributes'): + values = capabilities.get(name, []) + if ( + not isinstance(values, list) + or any(not isinstance(value, str) for value in values) + or len(set(values)) != len(values) + ): + raise ValueError(f'Bounded capability {name!r} must be a unique string list.') + result[name] = list(values) + if set(result['predicate_split_attributes']) - {'amplitudes.npy'}: + raise ValueError( + 'Unsupported bounded predicate attribute; only raw amplitudes are supported.' + ) + return result + + +def _field_name(field): + if ( + not isinstance(field, str) + or not field + or field in ('.', '..') + or any(char in field for char in ('/', '\\', '\0', '\n', '\r', '\t')) + ): + raise ValueError('Metadata fields must be nonempty safe local field names.') + return field + + +def normalize_metadata(metadata): + """Return JSON-compatible metadata with integer cluster keys.""" + if not isinstance(metadata, dict): + raise ValueError('Cluster metadata must be a field-to-cluster mapping.') + result = {} + for field, values in metadata.items(): + _field_name(field) + if not isinstance(values, dict): + raise ValueError('Invalid cluster metadata field.') + result[field] = {} + for key, value in values.items(): + try: + cluster = int(key) + except (ValueError, TypeError) as error: + raise ValueError('Invalid metadata cluster ID.') from error + if str(cluster) != str(key) or cluster < 0: + raise ValueError('Invalid metadata cluster ID.') + _json_bytes(value) + result[field][cluster] = copy.deepcopy(value) + return result + + +def validate_predicate(predicate): + """Validate a threshold on a canonical full-source scalar attribute.""" + if not isinstance(predicate, dict) or set(predicate) != { + 'attribute', + 'operator', + 'threshold', + 'nonfinite', + }: + raise ValueError('Threshold requires attribute/operator/threshold/nonfinite.') + if predicate['attribute'] not in ('amplitudes.npy', 'spike_templates.npy'): + raise ValueError('Unsupported full-source threshold attribute.') + if predicate['operator'] not in ('<', '<=', '>', '>='): + raise ValueError('Unsupported threshold comparator.') + threshold = predicate['threshold'] + if isinstance(threshold, bool) or not isinstance(threshold, (int, float)): + raise ValueError('Threshold must be a finite number.') + if not np.isfinite(threshold) or predicate['nonfinite'] not in ('keep', 'reject'): + raise ValueError('Threshold needs a finite threshold and explicit nonfinite policy.') + return copy.deepcopy(predicate) + + +def evaluate_predicate(values, predicate): + values = np.asarray(values).reshape(-1) + finite = np.isfinite(values) + if predicate['nonfinite'] == 'reject' and not finite.all(): + raise ValueError('Nonfinite source values violate threshold policy.') + operators = {'<': np.less, '<=': np.less_equal, '>': np.greater, '>=': np.greater_equal} + return finite & operators[predicate['operator']](values, predicate['threshold']) + + +def _flatten_parent_nodes(nodes): + """Expand recorded merge nodes, stopping at source/split boundaries.""" + pending = list(reversed(nodes)) + leaves, seen = [], set() + while pending: + node = pending.pop() + unit, created, parts = node + if parts is not None: + pending.extend(reversed(parts)) + continue + reference = (unit, created) + if reference in seen: + raise ValueError('Recorded restoration contains a repeated historical component.') + seen.add(reference) + leaves.append(node) + return leaves + + +def _parent_references(nodes): + return [{'unit': unit, 'event_index': created} for unit, created, _ in nodes] + + +def _merge_lineage(unit_ids, events): + """Historical merge topology; split children deliberately start new leaves. + + Restore aliases retain the original node rather than inventing new ancestry. + The caller must validate the journal before using the resulting graph. + """ + active = {int(unit): (int(unit), -1, None) for unit in unit_ids} + merges = {} + for index, event in enumerate(events): + operation = event['operation'] + if operation == 'merge': + parts = tuple(active.pop(parent) for parent in event['parents']) + node = (event['target'], index, parts) + merges[index] = parts + active[event['target']] = node + elif operation == 'threshold_split': + active.pop(event['parent']) + active.update({child: (child, index, None) for child in event['children']}) + elif operation == 'restore_parents': + active.pop(event['target']) + parts = merges[event['merge_event_index']] + if event['version'] == 4: + parts = _flatten_parent_nodes(parts) + active.update(dict(zip(event['children'], parts, strict=True))) + return active, merges + + +def interpret_events(unit_ids, metadata, events): + """Validate event intent and resolve the final catalog and metadata.""" + active = set(map(int, unit_ids)) + if not active or any(i < 0 for i in active): + raise ValueError('Full source unit catalog must contain nonnegative IDs.') + allocated = set(active) + origins = dict.fromkeys(active) + merge_parents = {} + lineage = {unit: (unit, -1, None) for unit in active} + merge_nodes = {} + metadata = normalize_metadata(metadata) + if not isinstance(events, list): + raise ValueError('Semantic journal must be an ordered event list.') + next_id = max(active) + 1 + for event_index, event in enumerate(events): + if not isinstance(event, dict) or event.get('version') not in (1, 2, 3, 4): + raise ValueError('Unsupported semantic journal event version.') + operation = event.get('operation') + if event['version'] in (3, 4) and operation != 'restore_parents': + raise ValueError('Version 3 requires a restore-parents event.') + if operation == 'metadata_policy': + if ( + set(event) != {'version', 'operation', 'policy', 'schema'} + or event['version'] != 2 + or event['policy'] != POLICY + ): + raise ValueError('Malformed metadata policy migration event.') + validate_schema(event['schema']) + # Old resolved values have no reliable curator intent. Preserve only + # explicit label events on the current membership scope. + derived = set() + labels = {} + for previous in events[:event_index]: + op = previous['operation'] + if op == 'merge': + derived.add(previous['target']) + elif op == 'threshold_split' or op == 'restore_parents': + derived.update(previous['children']) + elif op == 'label': + for unit in previous['ids']: + labels[(previous['field'], unit)] = previous['value'] + for field, values in metadata.items(): + for unit in derived & active: + values[unit] = copy.deepcopy(labels.get((field, unit))) + elif operation == 'merge': + if set(event) != {'version', 'operation', 'parents', 'target', 'metadata'}: + raise ValueError('Malformed merge event.') + parents = [_integer(i, 'Parent ID') for i in event['parents']] + target = _integer(event['target'], 'Target ID') + if target > np.iinfo(np.int32).max: + raise ValueError('Target cluster ID exceeds the current Phy loader namespace.') + if len(parents) < 2 or len(set(parents)) != len(parents): + raise ValueError('Merge requires at least two distinct complete units.') + if not set(parents) <= active or target in allocated or target < next_id: + raise ValueError('Merge references inactive units or colliding target ID.') + resolved = event['metadata'] + if not isinstance(resolved, dict) or any(not isinstance(f, str) for f in resolved): + raise ValueError('Merge metadata must contain resolved field values.') + if event['version'] == 2: + expected = dict.fromkeys(set(metadata) | {'group'}) + if resolved != expected: + raise ValueError('New membership must clear producer metadata and quality.') + _json_bytes(resolved) + for field in resolved: + _field_name(field) + active.difference_update(parents) + active.add(target) + merge_parents[event_index] = [(parent, origins.pop(parent)) for parent in parents] + origins[target] = event_index + parts = tuple(lineage.pop(parent) for parent in parents) + merge_nodes[event_index] = parts + lineage[target] = (target, event_index, parts) + allocated.add(target) + next_id = target + 1 + for values in metadata.values(): + for parent in parents: + values.pop(parent, None) + for field, value in resolved.items(): + metadata.setdefault(field, {})[target] = copy.deepcopy(value) + elif operation == 'label': + if set(event) != {'version', 'operation', 'field', 'ids', 'value'}: + raise ValueError('Malformed label event.') + ids = [_integer(i, 'Label ID') for i in event['ids']] + field = event['field'] + _field_name(field) + if not ids or len(set(ids)) != len(ids) or not set(ids) <= active: + raise ValueError('Label references inactive units or invalid metadata field.') + _json_bytes(event['value']) + values = metadata.setdefault(field, {}) + for cluster in ids: + values[cluster] = copy.deepcopy(event['value']) + elif operation == 'threshold_split': + if set(event) != { + 'version', + 'operation', + 'parent', + 'children', + 'predicate', + 'metadata', + }: + raise ValueError('Malformed threshold split event.') + parent = _integer(event['parent'], 'Parent ID') + children = [_integer(i, 'Child ID') for i in event['children']] + if any(child > np.iinfo(np.int32).max for child in children): + raise ValueError('Child cluster ID exceeds the current Phy loader namespace.') + validate_predicate(event['predicate']) + if parent not in active or len(children) != 2 or len(set(children)) != 2: + raise ValueError('Threshold split requires an active parent and two children.') + if any(i in allocated or i < next_id for i in children): + raise ValueError('Threshold split child ID collision.') + resolved = normalize_metadata(event['metadata']) + if event['version'] == 2: + expected = {field: dict.fromkeys(children) for field in set(metadata) | {'group'}} + if resolved != expected: + raise ValueError('New membership must clear producer metadata and quality.') + if any(not set(v) <= set(children) for v in resolved.values()): + raise ValueError('Split metadata must refer only to explicit children.') + active.remove(parent) + active.update(children) + origins.pop(parent) + origins.update(dict.fromkeys(children)) + lineage.pop(parent) + lineage.update({child: (child, event_index, None) for child in children}) + allocated.update(children) + next_id = max(children) + 1 + for values in metadata.values(): + values.pop(parent, None) + for field, values in resolved.items(): + metadata.setdefault(field, {}).update(values) + elif operation == 'restore_parents': + if set(event) != ( + { + 'version', + 'operation', + 'target', + 'children', + 'merge_event_index', + 'merge_prefix_sha256', + 'source_revision', + 'metadata', + } + | ({'parent_references'} if event['version'] == 4 else set()) + ) or event['version'] not in (3, 4): + raise ValueError('Malformed restore-parents event.') + target = _integer(event['target'], 'Restore target ID') + origin = _integer(event['merge_event_index'], 'Merge event index') + children = [_integer(i, 'Restored child ID') for i in event['children']] + if ( + target not in active + or origins.get(target) != origin + or origin not in merge_parents + ): + raise ValueError('Restore requires an unchanged live recorded merge membership.') + if event['merge_prefix_sha256'] != hash_json(events[: origin + 1]): + raise ValueError('Restore merge prefix binding is invalid.') + if not isinstance(event['source_revision'], str) or not event['source_revision']: + raise ValueError('Restore requires a source revision binding.') + parts = merge_nodes[origin] + if event['version'] == 4: + parts = _flatten_parent_nodes(parts) + references = event['parent_references'] + if not isinstance(references, list) or any( + not isinstance(ref, dict) + or set(ref) != {'unit', 'event_index'} + or type(ref['unit']) is not int + or ref['unit'] < 0 + or type(ref['event_index']) is not int + or ref['event_index'] < -1 + for ref in references + ): + raise ValueError('Malformed recursive restore parent references.') + if references != _parent_references(parts): + raise ValueError( + 'Recursive restore parent references disagree with merge ancestry.' + ) + if len(children) != len(parts) or len(set(children)) != len(children): + raise ValueError('Restore requires one distinct child for every resolved parent.') + if any(i in allocated or i < next_id or i > np.iinfo(np.int32).max for i in children): + raise ValueError('Restored child ID collision or unsupported namespace.') + resolved = normalize_metadata(event['metadata']) + expected = {field: dict.fromkeys(children) for field in set(metadata) | {'group'}} + if resolved != expected: + raise ValueError('Restored membership must clear producer metadata and quality.') + active.remove(target) + active.update(children) + origins.pop(target) + origins.update( + { + child: node[1] if node[2] is not None else None + for child, node in zip(children, parts, strict=True) + } + ) + lineage.pop(target) + lineage.update(dict(zip(children, parts, strict=True))) + allocated.update(children) + next_id = max(children) + 1 + for values in metadata.values(): + values.pop(target, None) + for field, values in resolved.items(): + metadata.setdefault(field, {}).update(values) + else: + raise ValueError(f'Unsupported semantic operation: {operation!r}.') + return active, metadata, next_id + + +def project_assignments(assignments, events, attributes=None): + """Interpret a validated journal against a bounded array or full-source batch.""" + output = np.asarray(assignments, dtype=np.int64).reshape(-1).copy() + attributes = attributes or {} + predicate_names = { + event['predicate']['attribute'] + for event in events + if event['operation'] == 'threshold_split' + } + restores = {} + if any(event['operation'] == 'restore_parents' for event in events): + from .live_summaries import membership_expressions + + # Infer the initial catalog for a source batch, including units absent + # from this batch. The validated journal never recycles allocated IDs. + initial, allocated = set(map(int, np.unique(output))), set() + for event in events: + if event['operation'] == 'merge': + initial.update(event['parents']) + allocated.add(event['target']) + elif event['operation'] == 'threshold_split': + initial.add(event['parent']) + allocated.update(event['children']) + elif event['operation'] == 'restore_parents': + initial.add(event['target']) + allocated.update(event['children']) + membership_expressions(initial - allocated, events, restore_sources=restores) + for event_index, event in enumerate(events): + if event['operation'] == 'merge': + output[np.isin(output, event['parents'])] = event['target'] + elif event['operation'] == 'threshold_split': + predicate = event['predicate'] + attribute = predicate['attribute'] + if attribute not in attributes: + raise ValueError(f'Full-source threshold attribute is unavailable: {attribute}.') + mask = output == event['parent'] + values = np.asarray(attributes[attribute]).reshape(-1) + if len(values) != len(output): + raise ValueError('Threshold attribute is not a scalar per-spike array.') + selected = np.zeros(len(output), dtype=bool) + selected[mask] = evaluate_predicate(values[mask], predicate) + output[mask & ~selected] = event['children'][0] + output[mask & selected] = event['children'][1] + elif event['operation'] == 'restore_parents': + rows = np.flatnonzero(output == event['target']) + expressions = restores[event_index] + size = _restore_batch_size(expressions, len(predicate_names)) + for start in range(0, len(rows), size): + chunk = rows[start : start + size] + base = np.asarray(assignments).reshape(-1)[chunk] + values = { + name: np.asarray(attributes[name]).reshape(-1)[chunk] + for name in predicate_names + if name in attributes + } + covered = np.zeros(len(chunk), dtype=bool) + memo = {} + for child, expression in zip(event['children'], expressions, strict=True): + mask = _membership_mask(expression, base, values, memo) + if np.any(covered & mask): + raise ValueError('Restored source parent memberships overlap.') + output[chunk[mask]] = child + covered |= mask + if not covered.all(): + raise ValueError('Restored source parents do not partition the target.') + elif event['operation'] not in ('label', 'metadata_policy'): + raise ValueError('Unsupported semantic projection operation.') + return output + + +def _restore_batch_size(expressions, attribute_count): + """Bound historical mask memoization even for many or deeply nested parents.""" + pending, seen = list(expressions), set() + while pending: + expression = pending.pop() + identity = id(expression) + if identity in seen: + continue + seen.add(identity) + if expression['kind'] == 'union': + pending.extend(expression['parts']) + elif expression['kind'] == 'split': + pending.append(expression['parent']) + return max(1, RESTORE_SCRATCH_BYTES // (len(seen) + 8 * attribute_count + 64)) + + +def _membership_mask(expression, assignments, attributes, memo): + """Evaluate an authenticated historical parent on one bounded batch.""" + key = id(expression) + if key in memo: + return memo[key] + kind = expression['kind'] + if kind == 'source': + mask = assignments == expression['unit'] + elif kind == 'union': + mask = np.zeros(len(assignments), dtype=bool) + for part in expression['parts']: + mask |= _membership_mask(part, assignments, attributes, memo) + elif kind == 'split': + parent = _membership_mask(expression['parent'], assignments, attributes, memo) + predicate = expression['predicate'] + if predicate['attribute'] not in attributes: + raise ValueError('Historical parent requires an unavailable full-source attribute.') + selected = evaluate_predicate(attributes[predicate['attribute']][parent], predicate) + mask = parent.copy() + mask[parent] = selected if expression['selected'] else ~selected + else: + raise ValueError('Unsupported historical membership expression.') + memo[key] = mask + return mask + + +def merge_origins(unit_ids, events): + """Resolve live equivalent-merge origins in an already validated journal.""" + active, _ = _merge_lineage(unit_ids, events) + return {unit: node[1] if node[2] is not None else None for unit, node in active.items()} + + +class BoundedSession: + """Bounded semantic state; reopen establishes a new undo baseline. + + Snapshot/restore integrate with the controller's undo stack. Saving publishes + one pointer after every generation file has been flushed and verified. + """ + + def __init__(self, dataset_path): + self.global_ids = None + self.base_assignments = None + self.attributes = {} + try: + self._initialize(dataset_path) + except BaseException: + self.close() + raise + + def _initialize(self, dataset_path): + self.path = Path(dataset_path) + if self.path.is_file(): + self.path = self.path.parent + self.manifest = _read_json(self.path / MANIFEST) + manifest = self.manifest + required = { + 'source', + 'sample_rate', + 'num_samples', + 'valid_intervals', + 'num_spikes', + 'bounded_num_spikes', + 'unit_ids', + 'counts', + 'next_cluster_id', + 'global_spike_ids_file', + 'windows_file', + } + if manifest.get('format') != 'phy_bounded_curation' or manifest.get('format_version') != 1: + raise ValueError('Unsupported bounded curation manifest version.') + if not required <= set(manifest): + raise ValueError( + 'Incomplete bounded curation manifest; regenerate with prepare-large.' + ) + source = manifest['source'] + if not isinstance(source, dict) or not {'identity', 'revision', 'path'} <= set(source): + raise ValueError('Bounded manifest needs source identity and assignment revision.') + if not isinstance(source['identity'], dict) or not isinstance(source['revision'], str): + raise ValueError('Invalid source identity or revision.') + identity = source['identity'] + identity_fields = {'format_version', 'acquisition', 'time_base', 'arrays', 'sha256'} + if ( + not identity_fields <= set(identity) + or identity.get('format_version') != 1 + or identity['sha256'] + != hash_json({k: v for k, v in identity.items() if k != 'sha256'}) + or len(source['revision']) != 64 + or any(c not in '0123456789abcdef' for c in source['revision']) + ): + raise ValueError('Invalid source coordinate identity or assignment revision digest.') + n = _integer(manifest['bounded_num_spikes'], 'Bounded spike count') + full_n = _integer(manifest['num_spikes'], 'Full spike count') + samples = _integer(manifest['num_samples'], 'Recording sample count') + if not n or n > full_n or not samples or not np.isfinite(manifest['sample_rate']): + raise ValueError('Invalid bounded counts or recording duration.') + if manifest['sample_rate'] <= 0: + raise ValueError('Sampling rate must be positive.') + expected_time_base = { + 'sample_rate': manifest['sample_rate'], + 'num_samples': samples, + 'valid_intervals': manifest['valid_intervals'], + } + if manifest.get('time_base') is not None: + contract = _time_base(manifest['time_base']) + if contract['ticks_per_second'] != manifest['sample_rate']: + raise ValueError('Bounded tick frequency disagrees with sampling rate.') + expected_time_base['contract'] = contract + timestamps_hash = identity['time_base'].get('timestamps_sha256') + if timestamps_hash is not None: + if ( + not isinstance(timestamps_hash, str) + or len(timestamps_hash) != 64 + or any(c not in '0123456789abcdef' for c in timestamps_hash) + ): + raise ValueError('Invalid source timestamps digest.') + expected_time_base['timestamps_sha256'] = timestamps_hash + if identity['time_base'] != expected_time_base: + raise ValueError('Bounded time base disagrees with immutable source identity.') + self.capabilities = _validate_capabilities(manifest) + self.unit_ids = [_integer(i, 'Unit ID') for i in manifest['unit_ids']] + if any(unit > np.iinfo(np.int32).max for unit in self.unit_ids): + raise ValueError('Unit IDs exceed the current Phy loader namespace.') + if not self.unit_ids or len(set(self.unit_ids)) != len(self.unit_ids): + raise ValueError('Full unit catalog must contain distinct unit IDs.') + counts = np.asarray(manifest['counts']) + if ( + counts.shape != (len(self.unit_ids),) + or counts.dtype.kind not in 'iu' + or np.any(counts < 0) + or sum(map(int, counts)) != full_n + ): + raise ValueError('Full unit counts do not match the source spike count/catalog.') + from phy.cluster._propositions import MergePropositionCatalog + + MergePropositionCatalog((), (), retired_units=manifest.get('retired_units', {})) + if set(manifest.get('retired_units', {})) & set(map(str, self.unit_ids)): + raise ValueError('Retired units cannot remain in the active source catalog.') + self.base_next_cluster_id = _integer(manifest['next_cluster_id'], 'Next cluster ID') + if self.base_next_cluster_id <= max(self.unit_ids): + raise ValueError('Cluster allocator collides with the complete source catalog.') + intervals = np.asarray(manifest['valid_intervals']) + if ( + intervals.ndim != 2 + or intervals.shape[1] != 2 + or not len(intervals) + or intervals.dtype.kind not in 'iu' + ): + raise ValueError('Valid acquisition intervals must be integer [start, end) pairs.') + if ( + np.any(intervals[:, 0] < 0) + or np.any(intervals[:, 1] > samples) + or np.any(intervals[:, 1] <= intervals[:, 0]) + or np.any(intervals[1:, 0] < intervals[:-1, 1]) + ): + raise ValueError('Invalid or overlapping acquisition intervals.') + self.global_ids = np.load( + _safe_file(self.path, manifest['global_spike_ids_file']), mmap_mode='r' + ) + if self.global_ids.dtype != np.int64 or self.global_ids.shape != (n,): + raise ValueError('Global spike IDs must be a one-dimensional int64 mapping.') + if ( + np.any(self.global_ids < 0) + or np.any(self.global_ids >= full_n) + or np.any(self.global_ids[1:] <= self.global_ids[:-1]) + ): + raise ValueError('Global spike IDs must be sorted, unique source row indices.') + windows = np.load(_safe_file(self.path, manifest['windows_file']), mmap_mode='r') + if ( + windows.ndim != 2 + or windows.shape[1] != 2 + or not len(windows) + or windows.dtype != np.int64 + ): + raise ValueError('Evidence windows must be int64 sample intervals.') + if ( + np.any(windows[:, 0] < 0) + or np.any(windows[:, 1] > samples) + or np.any(windows[:, 1] <= windows[:, 0]) + or np.any(windows[1:, 0] < windows[:-1, 1]) + ): + raise ValueError('Invalid or overlapping evidence windows.') + for start, stop in windows: + if not any(left <= start and stop <= right for left, right in intervals): + raise ValueError('Evidence windows cross unsupported acquisition gaps.') + for name, digest in manifest.get('bounded_files', {}).items(): + _validate_digest(digest) + if _hash_file(_safe_file(self.path, name)) != digest: + raise ValueError(f'Bounded package integrity check failed: {name}.') + hashed_files = manifest.get('bounded_files', {}) + if not { + BASE_ASSIGNMENTS, + manifest['global_spike_ids_file'], + manifest['windows_file'], + 'spike_times.npy', + } <= set(hashed_files): + raise ValueError('Bounded manifest lacks required immutable array digests.') + self.base_assignments = np.load(self.path / BASE_ASSIGNMENTS, mmap_mode='r') + if ( + self.base_assignments.shape != (n,) + or self.base_assignments.dtype.kind not in 'iu' + or not set(np.unique(self.base_assignments)) <= set(self.unit_ids) + ): + raise ValueError('Immutable bounded assignments do not match the full catalog.') + self.metadata_schema = validate_schema( + manifest.get('metadata_schema', {'version': 1, 'tables': []}) + ) + if manifest.get('metadata_policy') not in (None, POLICY): + raise ValueError('Unsupported bounded metadata policy.') + self.base_metadata = normalize_metadata( + manifest.get('base_metadata', manifest.get('metadata', {})) + ) + if any(not set(values) <= set(self.unit_ids) for values in self.base_metadata.values()): + raise ValueError('Base metadata refers to units outside the full source catalog.') + bounded_times = np.load(self.path / 'spike_times.npy', mmap_mode='r').reshape(-1) + if ( + bounded_times.shape != (n,) + or bounded_times.dtype.kind not in 'iu' + or np.any(bounded_times[1:] < bounded_times[:-1]) + ): + raise ValueError('Bounded spike sample coordinates have invalid alignment/order.') + window_ids = np.searchsorted(windows[:, 0], bounded_times, side='right') - 1 + if np.any(window_ids < 0) or np.any(bounded_times >= windows[window_ids, 1]): + raise ValueError('Bounded spikes lie outside the recorded evidence windows.') + self.attributes = {} + for name in ('amplitudes.npy', 'spike_templates.npy'): + if (self.path / name).exists(): + self.attributes[name] = np.load(self.path / name, mmap_mode='r') + for name in self.capabilities['predicate_split_attributes']: + array = self.attributes.get(name) + if ( + array is None + or name not in identity['arrays'] + or not (array.ndim == 1 or array.shape[1:] == (1,)) + or len(array) != n + or array.dtype.kind not in 'iuf' + ): + raise ValueError( + f'Bounded predicate attribute is not available as a source scalar: {name}.' + ) + self.assignments = np.asarray(self.base_assignments, dtype=np.int64).copy() + self.metadata = copy.deepcopy(self.base_metadata) + self._events = freeze([]) + self.extra_documents = {} + if 'proposition_documents' not in manifest and any( + (self.path / name).exists() for name in ('curation.json', 'curation_review.json') + ): + raise ValueError( + 'Legacy bounded propositions have no preparation binding; reprepare the source.' + ) + self.proposition_documents = manifest.get('proposition_documents', {}) + if not isinstance(self.proposition_documents, dict) or set(self.proposition_documents) - { + 'curation.json', + 'curation_review.json', + }: + raise ValueError('Invalid bounded proposition document inventory.') + for name, item in self.proposition_documents.items(): + expected_name = ( + '_phy_curation_review_base.json' if name == 'curation_review.json' else name + ) + if ( + not isinstance(item, dict) + or set(item) != {'filename', 'sha256'} + or item['filename'] != expected_name + or hashed_files.get(expected_name) != item['sha256'] + ): + raise ValueError('Proposition documents must have immutable preparation digests.') + _validate_digest(item['sha256']) + value = _read_json(_safe_file(self.path, expected_name)) + if not isinstance(value, dict): + raise ValueError('Proposition documents must contain JSON objects.') + if name == 'curation_review.json': + self.extra_documents[name] = value + if ( + 'curation.json' in self.proposition_documents + and 'curation_review.json' not in self.extra_documents + ): + from phy.cluster._propositions import encode_review_mapping + + self.extra_documents['curation_review.json'] = encode_review_mapping( + {}, source_sha256=self.proposition_documents['curation.json']['sha256'] + ) + self.validate_proposition_documents() + self.next_cluster_id = self.base_next_cluster_id + self.checkpoint_path = None + self._expected_pointer = None + pointer_path = self.path / '.phy-curation' / 'current.json' + if pointer_path.exists(): + self._load_checkpoint(pointer_path) + if self.metadata_policy is None: + warnings.warn( + 'Legacy bounded metadata preserves inherited values; use ' + 'migrate_metadata() to adopt membership-scoped metadata.', + UserWarning, + stacklevel=2, + ) + + self._reset_runtime() + + def _reset_runtime(self): + from phylib.io.array import _spikes_per_cluster + + from .runtime import SemanticState + + self._runtime = SemanticState.from_session(self) + self.metadata = self._runtime.metadata + self._assignment_groups = _spikes_per_cluster(self.assignments) + for rows in self._assignment_groups.values(): + rows.flags.writeable = False + self._transitions = OrderedDict() + self._transition_bytes = 0 + self.history_cache_bytes = getattr(self, 'history_cache_bytes', HISTORY_CACHE_BYTES) + self._prepared = None + self._catalog_cache = None + self.last_changed_groups = {} + + def validate_proposition_documents(self): + """Keep producer input and its inherited ledger bound to preparation.""" + for name, item in self.proposition_documents.items(): + path = _safe_file(self.path, item['filename']) + if not path.is_file() or _hash_file(path) != item['sha256']: + raise ValueError(f'Bounded proposition document changed: {name}.') + if 'proposition_documents' in self.manifest: + for name in ('curation.json',): + if name not in self.proposition_documents and (self.path / name).exists(): + raise ValueError('Unbound bounded proposition document.') + review = self.extra_documents.get('curation_review.json') + has_review = 'curation_review.json' in self.extra_documents + if has_review and 'proposition_documents' not in self.manifest: + raise ValueError( + 'Legacy bounded reviews have no preparation binding; reprepare the source.' + ) + if 'curation.json' in self.proposition_documents and not isinstance(review, dict): + raise ValueError('Bounded proposition checkpoints require a review ledger mapping.') + if has_review: + from phy.cluster._propositions import decode_review_mapping + + source, _ = decode_review_mapping(review) + expected = self.proposition_documents.get('curation.json', {}).get('sha256') + if ( + source.get('filename') != 'curation.json' + or expected is None + or source.get('sha256') != expected + ): + raise ValueError('Bounded review source filename/hash does not match preparation.') + + @property + def retired_units(self): + """Cumulative retirement history, without retargeting source suggestions.""" + result = copy.deepcopy(self.manifest.get('retired_units', {})) + # Events have already passed the complete-unit journal validator. + if hasattr(self, '_runtime'): + return copy.deepcopy(self._catalog_projection()[0]) + interpret_events(self.unit_ids, self.base_metadata, self.events) + for event in self.events: + if event['operation'] == 'merge': + for parent in event['parents']: + result[str(parent)] = {'operation': 'merge', 'replacements': [event['target']]} + elif event['operation'] == 'threshold_split': + result[str(event['parent'])] = { + 'operation': 'threshold_split', + 'replacements': list(event['children']), + } + elif event['operation'] == 'restore_parents': + result[str(event['target'])] = { + 'operation': 'restore_parents', + 'replacements': list(event['children']), + } + return result + + @property + def restored_parent_ids(self): + """Display origins for fresh restored identities still in the live catalog.""" + if hasattr(self, '_runtime'): + return dict(self._catalog_projection()[1]) + active, _, _ = interpret_events(self.unit_ids, self.base_metadata, self.events) + result = {} + for event in self.events: + if event['operation'] == 'restore_parents': + original = ( + [ref['unit'] for ref in event['parent_references']] + if event['version'] == 4 + else self.events[event['merge_event_index']]['parents'] + ) + result.update(dict(zip(event['children'], original, strict=True))) + return {child: parent for child, parent in result.items() if child in active} + + def _catalog_projection(self): + key = self._runtime.membership_key + if self._catalog_cache is not None and self._catalog_cache[0] is key: + return self._catalog_cache[1:] + retired = copy.deepcopy(self.manifest.get('retired_units', {})) + origins = {} + for event in self.events: + operation = event['operation'] + parents = ( + event['parents'] + if operation == 'merge' + else [event['parent']] + if operation == 'threshold_split' + else [event['target']] + if operation == 'restore_parents' + else [] + ) + children = [event['target']] if operation == 'merge' else event.get('children', []) + for parent in parents: + retired[str(parent)] = {'operation': operation, 'replacements': list(children)} + if operation == 'restore_parents': + original = ( + [ref['unit'] for ref in event['parent_references']] + if event['version'] == 4 + else self.events[event['merge_event_index']]['parents'] + ) + origins.update(dict(zip(children, original, strict=True))) + origins = { + child: parent for child, parent in origins.items() if child in self._runtime.active + } + self._catalog_cache = (key, retired, origins) + return retired, origins + + def _validated_state(self, assignments, metadata, events, next_cluster_id): + self._validate_event_capabilities(events) + _, projected_metadata, minimum = interpret_events( + self.unit_ids, self.base_metadata, events + ) + projected = project_assignments(self.base_assignments, events, self.attributes) + values = np.asarray(assignments) + if values.dtype.kind not in 'iu' or values.shape != projected.shape: + raise ValueError('Checkpoint assignments have invalid shape or dtype.') + if not np.array_equal(values, projected): + raise ValueError('Checkpoint assignments disagree with semantic journal projection.') + if normalize_metadata(metadata) != projected_metadata: + raise ValueError('Checkpoint metadata disagrees with semantic journal projection.') + minimum = max(minimum, self.base_next_cluster_id) + next_cluster_id = _integer(next_cluster_id, 'Next cluster ID') + if next_cluster_id < minimum: + raise ValueError('Checkpoint allocator collides with journal IDs.') + return projected, projected_metadata, next_cluster_id + + def _load_checkpoint(self, pointer_path): + pointer = _read_json(pointer_path) + generation = _safe_file(pointer_path.parent / 'generations', pointer['generation']) + descriptor = _read_json(generation / 'checkpoint.json') + if _digest(descriptor) != pointer['sha256']: + raise ValueError('Checkpoint commit pointer digest is invalid.') + if descriptor.get('version') != 1 or descriptor.get('manifest_sha256') != _digest( + self.manifest + ): + raise ValueError('Checkpoint belongs to a different bounded manifest.') + for name, digest in descriptor['files'].items(): + _validate_digest(digest) + if _hash_file(_safe_file(generation, name)) != digest: + raise ValueError(f'Checkpoint corruption: {name}.') + if not {'spike_clusters.npy', 'journal.json', 'metadata.json'} <= set(descriptor['files']): + raise ValueError('Incomplete checkpoint file inventory.') + events = _read_json(generation / 'journal.json') + for event in events: + if event.get('operation') in ('threshold_split', 'restore_parents'): + event['metadata'] = normalize_metadata(event['metadata']) + metadata = _read_json(generation / 'metadata.json') + assignments = np.load(generation / 'spike_clusters.npy', mmap_mode='r') + values, metadata, next_id = self._validated_state( + assignments, metadata, events, descriptor['next_cluster_id'] + ) + self.assignments, self.metadata = values, metadata + self._events = freeze(events) + if 'metadata_policy' in descriptor and ( + descriptor['metadata_policy'] != self.metadata_policy + or descriptor.get('metadata_schema') != self.effective_metadata_schema + or descriptor.get('metadata_provenance') != self.metadata_provenance + ): + raise ValueError( + 'Checkpoint metadata policy/schema/provenance disagrees with journal.' + ) + self.next_cluster_id = next_id + self.checkpoint_path = generation + self._expected_pointer = copy.deepcopy(pointer) + documents = descriptor.get('extra_documents', []) + if ( + not isinstance(documents, list) + or any(not isinstance(name, str) for name in documents) + or len(set(documents)) != len(documents) + or not set(documents) <= set(descriptor['files']) + or set(documents) + & {'checkpoint.json', 'spike_clusters.npy', 'journal.json', 'metadata.json'} + ): + raise ValueError('Extra checkpoint documents must be in the hash inventory.') + self.extra_documents = { + name: _read_json(_safe_file(generation, name)) for name in documents + } + self.validate_proposition_documents() + + @property + def events(self): + """Immutable JSON-compatible journal records, safe to share in history.""" + return self._events + + def snapshot(self): + return { + 'assignments': self.assignments.copy(), + 'metadata': thaw(self.metadata), + 'events': thaw(self.events), + 'next_cluster_id': self.next_cluster_id, + } + + def journal_state(self): + """Return a compact history prefix without copying bounded spike arrays. + + Commands append event dictionaries and never modify earlier events. The + tuple shares those immutable event records between history entries. + """ + return {'events': tuple(self.events), 'next_cluster_id': self.next_cluster_id} + + def restore_journal(self, state): + """Apply cached inverse/forward patches; validate unknown prefixes in full.""" + events = list(state['events']) + next_id = _integer(state['next_cluster_id'], 'Next cluster ID') + common = 0 + for previous, following in zip(self.events, events): + if previous is not following: + break + common += 1 + steps = [(event, False) for event in reversed(self.events[common:])] + steps += [(event, True) for event in events[common:]] + transitions, semantic = [], self._runtime + for event, forward in steps: + transition = self._transitions.get(id(event)) + if transition is None or transition.event is not event: + break + expected = transition.before if forward else transition.after + if semantic is not expected: + break + semantic = transition.after if forward else transition.before + transitions.append((transition, forward)) + else: + if next_id < max(semantic.next_id, self.base_next_cluster_id): + raise ValueError('History allocator collides with semantic journal IDs.') + changed = set() + for transition, forward in transitions: + self._apply_transition(transition, forward) + changed.update(transition.old_groups) + changed.update(transition.new_groups) + self.last_changed_groups = { + cluster: self._assignment_groups[cluster] + for cluster in changed + if cluster in self._assignment_groups + } + self._events = freeze(events) + self.next_cluster_id = max(self.next_cluster_id, next_id) + self._prepared = None + return + # Eviction, deserialized history, and arbitrary externally supplied states + # retain the independent replay path. Nothing is mutated until it succeeds. + self._validate_event_capabilities(events) + _, metadata, minimum = interpret_events(self.unit_ids, self.base_metadata, events) + if next_id < max(minimum, self.base_next_cluster_id): + raise ValueError('History allocator collides with semantic journal IDs.') + assignments = project_assignments(self.base_assignments, events, self.attributes) + self.assignments, self.metadata = assignments, metadata + self._events = freeze(events) + self.next_cluster_id = max(self.next_cluster_id, next_id) + self._reset_runtime() + self.last_changed_groups = self._assignment_groups + + def close(self): + """Release file-backed bounded readers independently of the GUI model.""" + for array in (self.global_ids, self.base_assignments, *self.attributes.values()): + mapping = getattr(array, '_mmap', None) + if mapping is not None and not mapping.closed: + mapping.close() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def restore(self, snapshot): + assignments, metadata, next_id = self._validated_state(**snapshot) + self.assignments, self.metadata = assignments, metadata + self._events = freeze(snapshot['events']) + self.next_cluster_id = next_id + self._reset_runtime() + + @property + def membership_revision(self): + """Opaque identity shared by metadata-only transitions and their undo.""" + return self._runtime.membership_key + + def membership_snapshot(self, unit_ids): + """Return authoritative immutable expressions without replaying the journal.""" + return { + int(unit): self._runtime.active[int(unit)].expression + for unit in unit_ids + if int(unit) in self._runtime.active + } + + def _prepare_event(self, event): + from .runtime import Transition + + prepared = self._prepared + if ( + prepared is not None + and prepared.before is self._runtime + and prepared.allocator == self.next_cluster_id + and prepared.event == event + ): + return prepared + # Own a detached event before retaining its immutable dictionaries in + # expression/lineage nodes; caller mutation must never change committed state. + # Reject cyclic/non-JSON payloads before recursively freezing records. + _json_bytes(event) + event = freeze(copy.deepcopy(event)) + semantic = self._runtime.advance( + self, event, len(self.events), self.events, allocator=self.next_cluster_id + ) + operation = event['operation'] + parents = ( + event['parents'] + if operation == 'merge' + else [event['parent']] + if operation == 'threshold_split' + else [event['target']] + if operation == 'restore_parents' + else [] + ) + empty = np.empty(0, dtype=np.int64) + old = {parent: self._assignment_groups.get(parent, empty) for parent in parents} + new = {} + if operation == 'merge': + rows = np.concatenate(list(old.values())) + rows.sort() + new[event['target']] = rows + elif operation == 'threshold_split': + rows = old[event['parent']] + predicate = event['predicate'] + values = self.attributes.get(predicate['attribute']) + if values is None: + raise ValueError('Full-source threshold attribute is unavailable.') + selected = evaluate_predicate(np.asarray(values).reshape(-1)[rows], predicate) + new = dict(zip(event['children'], (rows[~selected], rows[selected]), strict=True)) + elif operation == 'restore_parents': + _, parts = self._runtime.restore_nodes(event['target'], event['version'] == 4) + expressions = [part.expression for part in parts] + rows = old[event['target']] + gathered = [[] for _ in parts] + size = _restore_batch_size(expressions, len(self.attributes)) + for start in range(0, len(rows), size): + chunk = rows[start : start + size] + base = self.base_assignments[chunk] + values = { + name: np.asarray(attribute).reshape(-1)[chunk] + for name, attribute in self.attributes.items() + } + covered, memo = np.zeros(len(chunk), dtype=bool), {} + for i, expression in enumerate(expressions): + mask = _membership_mask(expression, base, values, memo) + if np.any(covered & mask): + raise ValueError('Restored source parent memberships overlap.') + covered |= mask + gathered[i].append(chunk[mask]) + if not covered.all(): + raise ValueError('Restored source parents do not partition the target.') + new = { + child: np.concatenate(parts) if parts else empty + for child, parts in zip(event['children'], gathered, strict=True) + } + for rows in new.values(): + rows.flags.writeable = False + prepared = Transition(event, self._runtime, semantic, old, new, self.next_cluster_id) + self._prepared = prepared + return prepared + + def _apply_transition(self, transition, forward=True): + old, new = ( + (transition.old_groups, transition.new_groups) + if forward + else (transition.new_groups, transition.old_groups) + ) + for cluster, rows in new.items(): + self.assignments[rows] = cluster + for cluster in old: + self._assignment_groups.pop(cluster, None) + self._assignment_groups.update( + {cluster: rows for cluster, rows in new.items() if len(rows)} + ) + self._runtime = transition.after if forward else transition.before + self.metadata = self._runtime.metadata + + def _append(self, event): + transition = self._prepare_event(event) + self._apply_transition(transition) + self._events = freeze(self.events + [transition.event]) + self.next_cluster_id = max(self.next_cluster_id, transition.after.next_id) + self._transitions[id(transition.event)] = transition + self._transition_bytes += transition.nbytes + while self._transitions and self._transition_bytes > self.history_cache_bytes: + _, discarded = self._transitions.popitem(last=False) + self._transition_bytes -= discarded.nbytes + self._prepared = None + self.last_changed_groups = transition.new_groups + return thaw(transition.event) + + def _require_capability(self, operation, predicate=None): + if operation == 'threshold_split': + predicate = validate_predicate(predicate) + if predicate['attribute'] not in self.capabilities['predicate_split_attributes']: + raise ValueError( + 'Predicate split capability is unavailable in this bounded package.' + ) + elif not self.capabilities.get(operation, False): + raise ValueError( + f'{operation.capitalize()} capability is disabled in this bounded package.' + ) + + def _validate_event_capabilities(self, events): + policy = self.manifest.get('metadata_policy') == POLICY + for event in events: + if isinstance(event, dict): + operation = event.get('operation') + if operation == 'metadata_policy': + if policy: + raise ValueError('Metadata policy migration has already been applied.') + policy = True + elif operation in ('merge', 'label', 'threshold_split'): + if event.get('version') != (2 if policy else 1): + raise ValueError('Semantic event version disagrees with metadata policy.') + self._require_capability(operation, event.get('predicate')) + elif operation == 'restore_parents': + self._require_capability(operation) + if not policy or event.get('version') not in (3, 4): + raise ValueError( + 'Restore parents requires current metadata policy/version.' + ) + if event.get('source_revision') != self.manifest['source']['revision']: + raise ValueError('Restore source revision disagrees with preparation.') + + @property + def metadata_policy(self): + return ( + self._runtime.policy + if hasattr(self, '_runtime') + else self._metadata_policy(self.events) + ) + + def _metadata_policy(self, events): + return ( + POLICY + if ( + self.manifest.get('metadata_policy') == POLICY + or any(e['operation'] == 'metadata_policy' for e in events) + ) + else None + ) + + @property + def effective_metadata_schema(self): + if hasattr(self, '_runtime'): + return complete_schema(self._runtime.schema, self.metadata) + return self._metadata_schema(self.events, self.metadata) + + def _metadata_schema(self, events, metadata): + schema = self.metadata_schema + for event in events: + if event['operation'] == 'metadata_policy': + schema = event['schema'] + return complete_schema(schema, metadata) + + @property + def metadata_provenance(self): + return self._metadata_provenance(self.events) + + def _metadata_provenance(self, events): + result = copy.deepcopy(self.manifest.get('metadata_provenance', {'history': []})) + metadata = copy.deepcopy(self.base_metadata) + for index, event in enumerate(events): + operation = event['operation'] + if operation in ('merge', 'threshold_split', 'restore_parents'): + parents = ( + event['parents'] + if operation == 'merge' + else [event['target'] if operation == 'restore_parents' else event['parent']] + ) + children = [event['target']] if operation == 'merge' else event['children'] + result.setdefault('history', []).append( + { + 'operation': operation, + 'source_revision': self.manifest['source']['revision'], + 'event_index': index, + **( + {'predicate': copy.deepcopy(event['predicate'])} + if operation == 'threshold_split' + else {} + ), + 'parents': parents, + 'children': children, + 'parent_metadata': { + field: {str(unit): values.get(unit) for unit in parents} + for field, values in metadata.items() + }, + **( + { + key: copy.deepcopy(event[key]) + for key in ( + 'merge_event_index', + 'merge_prefix_sha256', + 'source_revision', + ) + } + if operation == 'restore_parents' + else {} + ), + **( + {'parent_references': copy.deepcopy(event['parent_references'])} + if operation == 'restore_parents' and event['version'] == 4 + else {} + ), + 'policy': POLICY if event['version'] >= 2 else 'legacy_inherited', + } + ) + elif operation == 'label' or operation == 'metadata_policy': + result.setdefault('history', []).append(copy.deepcopy(event)) + # Event metadata is already resolved and validated. Scan it once + # instead of replaying every prefix of a potentially long journal. + if operation in ('merge', 'threshold_split', 'restore_parents'): + for values in metadata.values(): + for parent in parents: + values.pop(parent, None) + for field, resolved in event['metadata'].items(): + values = {event['target']: resolved} if operation == 'merge' else resolved + metadata.setdefault(field, {}).update(copy.deepcopy(values)) + elif operation == 'label': + values = metadata.setdefault(event['field'], {}) + for unit in event['ids']: + values[unit] = copy.deepcopy(event['value']) + elif operation == 'metadata_policy': + _, metadata, _ = interpret_events( + self.unit_ids, self.base_metadata, events[: index + 1] + ) + return result + + def migrate_metadata(self, source_params=None): + """Explicitly clear ambiguous inherited values; retain label journal intent. + + The original manifest and generations remain immutable. Saving commits a + policy transition and schema in the same atomic generation as assignments. + Reopen a supervisor after migrating an already-open GUI session. + """ + if self.metadata_policy == POLICY: + return None + from .source import Source + + source_params = source_params or self.manifest.get('source', {}).get('path') + if not source_params: + raise ValueError('Migration requires source_params to recover original table names.') + with Source( + source_params, + duration_seconds=self.manifest['num_samples'] / self.manifest['sample_rate'], + valid_intervals=self.manifest['valid_intervals'], + ) as source: + if source.identity != self.manifest['source']['identity']: + raise ValueError('Migration source identity does not match preparation.') + if source.revision != self.manifest['source']['revision']: + raise ValueError('Migration source revision does not match preparation.') + if source.metadata != self.base_metadata: + raise ValueError('Migration base metadata does not match source metadata.') + schema = source.metadata_schema + return self._append( + {'version': 2, 'operation': 'metadata_policy', 'policy': POLICY, 'schema': schema} + ) + + def preflight_merge(self, parents, target, metadata=None): + self._require_capability('merge') + event = { + 'version': 2 if self.metadata_policy else 1, + 'operation': 'merge', + 'parents': [int(i) for i in parents], + 'target': _integer(target, 'Target ID'), + 'metadata': ( + dict.fromkeys(set(self.metadata) | {'group'}) + if self.metadata_policy + else copy.deepcopy(metadata or {}) + ), + } + if event['target'] < self.next_cluster_id: + raise ValueError('Merge target is below the complete catalog allocator.') + self._prepare_event(event) + return event + + def record_merge(self, parents, target, metadata=None): + return self._append(self.preflight_merge(parents, target, metadata)) + + def restore_parent_plan(self, target, *, recursive=True): + """Return authenticated historical parent references and exact expressions.""" + target = _integer(target, 'Restore target ID') + index, nodes = self._runtime.restore_nodes(target, recursive) + if recursive: + refs = [{'unit': node.unit, 'event_index': node.index} for node in nodes] + else: + # Legacy immediate aliases use their then-live IDs in this public API. + from .live_summaries import membership_expressions + + historical = {} + membership_expressions(self.unit_ids, self.events[: index + 1], history=historical) + created = {unit: event_index for event_index, unit in historical} + refs = [ + {'unit': parent, 'event_index': created[parent]} + for parent in self.events[index]['parents'] + ] + return index, refs, thaw([node.expression for node in nodes]) + + def restore_parent_groups(self, target, *, recursive=False): + """Resolve all parents, including leaves with no retained evidence. + + Legacy callers retain immediate-parent semantics. Recursive restoration + expands recorded merges only; source units and threshold-split children + remain indivisible historical components. + """ + index, refs, expressions = self.restore_parent_plan(target, recursive=recursive) + rows = self._assignment_groups.get(target, np.empty(0, dtype=np.int64)) + parents = [ref['unit'] for ref in refs] + if len(set(parents)) != len(parents): + raise ValueError('Repeated historical parent identity in restoration.') + gathered = {parent: [] for parent in parents} + size = _restore_batch_size(expressions, len(self.attributes)) + for start in range(0, len(rows), size): + chunk = rows[start : start + size] + base = self.base_assignments[chunk] + attributes = {name: values[chunk] for name, values in self.attributes.items()} + memo, covered = {}, np.zeros(len(chunk), dtype=bool) + for parent, expression in zip(parents, expressions, strict=True): + mask = _membership_mask(expression, base, attributes, memo) + if np.any(mask & covered): + raise ValueError('Recorded parents overlap in target membership.') + covered |= mask + gathered[parent].append(chunk[mask]) + if not covered.all(): + raise ValueError( + 'Recorded parents do not exactly partition the target membership.' + ) + groups = { + parent: np.concatenate(parts) if parts else np.empty(0, dtype=np.int64) + for parent, parts in gathered.items() + } + return index, groups + + def restore_parent_counts(self, target, *, recursive=False): + """Known full-source historical counts; split scopes stay explicitly unknown.""" + _, refs, _ = self.restore_parent_plan(target, recursive=recursive) + _, nodes = self._runtime.restore_nodes(target, recursive) + return {ref['unit']: node.count for ref, node in zip(refs, nodes, strict=True)} + + def preflight_restore_parents(self, target, children, *, recursive=False): + self._require_capability('restore_parents') + if not self.metadata_policy: + raise ValueError('Migrate metadata before restoring merge parents.') + index, references, _ = self.restore_parent_plan(target, recursive=recursive) + children = [_integer(child, 'Restored child ID') for child in children] + if any(child < self.next_cluster_id for child in children): + raise ValueError('Restored children collide with the complete catalog allocator.') + event = { + 'version': 4 if recursive else 3, + 'operation': 'restore_parents', + 'target': int(target), + 'children': children, + 'merge_event_index': index, + 'merge_prefix_sha256': hash_json(self.events[: index + 1]), + 'source_revision': self.manifest['source']['revision'], + 'metadata': { + field: dict.fromkeys(children) for field in set(self.metadata) | {'group'} + }, + } + if recursive: + event['parent_references'] = references + self._prepare_event(event) + return event + + def record_restore_parents(self, target, children, *, recursive=False): + return self._append(self.preflight_restore_parents(target, children, recursive=recursive)) + + def preflight_label(self, field, ids, value): + self._require_capability('label') + complete_schema(self.effective_metadata_schema, {**self.metadata, field: {}}) + event = { + 'version': 2 if self.metadata_policy else 1, + 'operation': 'label', + 'field': field, + 'ids': [int(i) for i in ids], + 'value': copy.deepcopy(value), + } + self._prepare_event(event) + return event + + def record_label(self, field, ids, value): + return self._append(self.preflight_label(field, ids, value)) + + def record_threshold_split(self, parent, children, predicate, metadata=None): + """Apply an explicitly enabled full-source scalar predicate.""" + self._require_capability('threshold_split', predicate) + children = [int(i) for i in children] + if any(i < self.next_cluster_id for i in children): + raise ValueError('Threshold children collide with the complete catalog allocator.') + return self._append( + { + 'version': 2 if self.metadata_policy else 1, + 'operation': 'threshold_split', + 'parent': int(parent), + 'children': children, + 'predicate': validate_predicate(predicate), + 'metadata': ( + {field: dict.fromkeys(children) for field in set(self.metadata) | {'group'}} + if self.metadata_policy + else normalize_metadata(metadata or {}) + ), + } + ) + + def preflight_split(self, parent, selected_id, remainder_id, predicate, metadata=None): + self._require_capability('threshold_split', predicate) + children = [int(remainder_id), int(selected_id)] + if any(i < self.next_cluster_id for i in children): + raise ValueError('Threshold children collide with the complete catalog allocator.') + event = { + 'version': 2 if self.metadata_policy else 1, + 'operation': 'threshold_split', + 'parent': int(parent), + 'children': children, + 'predicate': validate_predicate(predicate), + 'metadata': ( + {field: dict.fromkeys(children) for field in set(self.metadata) | {'group'}} + if self.metadata_policy + else normalize_metadata(metadata or {}) + ), + } + self._prepare_event(event) + return event + + def record_split(self, parent, selected_id, remainder_id, predicate, metadata=None): + return self._append( + self.preflight_split(parent, selected_id, remainder_id, predicate, metadata) + ) + + def save( + self, + assignments=None, + metadata=None, + events=None, + next_cluster_id=None, + extra_documents=None, + ): + """Validate, flush a generation, then atomically replace its commit pointer.""" + self.validate_proposition_documents() + live_prefix = self.events if events is None else None + assignments = self.assignments if assignments is None else assignments + metadata = self.metadata if metadata is None else metadata + events = self.events if events is None else events + next_cluster_id = self.next_cluster_id if next_cluster_id is None else next_cluster_id + values, metadata, next_id = self._validated_state( + assignments, metadata, events, next_cluster_id + ) + if extra_documents is not None and not isinstance(extra_documents, dict): + raise ValueError('Extra checkpoint documents must be a filename-to-JSON mapping.') + documents = copy.deepcopy(self.extra_documents) + if extra_documents is not None: + documents.update(copy.deepcopy(extra_documents)) + if not isinstance(documents, dict): + raise ValueError('Extra checkpoint documents must be a filename-to-JSON mapping.') + for name, value in documents.items(): + _safe_file(self.path, name) + if name in ('checkpoint.json', 'spike_clusters.npy', 'journal.json', 'metadata.json'): + raise ValueError('Extra document collides with a checkpoint state file.') + _json_bytes(value) + previous_documents = self.extra_documents + try: + self.extra_documents = documents + self.validate_proposition_documents() + finally: + self.extra_documents = previous_documents + root = self.path / '.phy-curation' + generations = root / 'generations' + generations.mkdir(parents=True, exist_ok=True) + _fsync_directory(root) + _fsync_directory(self.path) + with _commit_lock(root): + if _current_pointer(root) != self._expected_pointer: + raise ValueError( + 'Bounded curation checkpoint changed in another session; ' + 'reopen the dataset before saving to avoid losing its changes.' + ) + return self._save_generation( + generations, values, metadata, events, next_id, documents, live_prefix=live_prefix + ) + + def _save_generation( + self, generations, values, metadata, events, next_id, documents, live_prefix=None + ): + root = generations.parent + identifier = uuid.uuid4().hex + stage = generations / f'.{identifier}.tmp' + final = generations / identifier + stage.mkdir() + pointer_tmp = root / f'.current-{identifier}.tmp' + try: + np.save(stage / 'spike_clusters.npy', values) + # Windows _commit (os.fsync) requires a writable descriptor. + with (stage / 'spike_clusters.npy').open('r+b') as stream: + os.fsync(stream.fileno()) + _write_json(stage / 'journal.json', events) + _write_json(stage / 'metadata.json', metadata) + for name, value in documents.items(): + _write_json(stage / name, value) + descriptor = { + 'version': 1, + 'manifest_sha256': _digest(self.manifest), + 'next_cluster_id': next_id, + 'metadata_policy': self._metadata_policy(events), + 'metadata_schema': self._metadata_schema(events, metadata), + 'metadata_provenance': self._metadata_provenance(events), + 'files': { + name: _hash_file(stage / name) + for name in ('spike_clusters.npy', 'journal.json', 'metadata.json', *documents) + }, + 'extra_documents': sorted(documents), + } + _write_json(stage / 'checkpoint.json', descriptor) + _fsync_directory(stage) + os.replace(stage, final) + _fsync_directory(generations) + pointer = {'generation': identifier, 'sha256': _digest(descriptor)} + _write_json(pointer_tmp, pointer) + self.validate_proposition_documents() + os.replace(pointer_tmp, root / 'current.json') + _fsync_directory(root) + except BaseException: + shutil.rmtree(stage, ignore_errors=True) + pointer_tmp.unlink(missing_ok=True) + raise + newer_edit = live_prefix is not None and self.events is not live_prefix + same_prefix = events is self.events + if not newer_edit: + self.assignments = values + self.metadata = self._runtime.metadata if same_prefix else metadata + self.next_cluster_id = next_id + if not same_prefix: + self._events = freeze(events) + self._reset_runtime() + else: + self.next_cluster_id = max(self.next_cluster_id, next_id) + self.checkpoint_path = final + self.extra_documents = documents + self._expected_pointer = pointer + return final diff --git a/phy/apps/large_recording/file_copy.py b/phy/apps/large_recording/file_copy.py new file mode 100644 index 000000000..0bcfeaa38 --- /dev/null +++ b/phy/apps/large_recording/file_copy.py @@ -0,0 +1,63 @@ +"""Copy-on-write clones with conservative full-copy fallback; never hardlinks.""" + +import ctypes +import errno +import os +import shutil +import sys +from pathlib import Path + + +def reflink(source, destination): + """Attempt a native clone; never remove a destination owned by a caller.""" + source, destination = Path(source), Path(destination) + if destination.exists(): + raise FileExistsError(destination) + created = False + unsupported = {errno.EXDEV, errno.ENOTTY, errno.EOPNOTSUPP, errno.ENOSYS, errno.EINVAL} + try: + if sys.platform.startswith('linux'): + import fcntl + + with source.open('rb') as src, destination.open('xb') as dst: + created = True + fcntl.ioctl(dst.fileno(), 0x40049409, src.fileno()) # FICLONE + elif sys.platform == 'darwin': + library = ctypes.CDLL(None, use_errno=True) + clone = getattr(library, 'clonefile', None) + if clone is None: + return False + clone.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int] + clone.restype = ctypes.c_int + if clone(os.fsencode(source), os.fsencode(destination), 0): + code = ctypes.get_errno() + raise OSError(code, os.strerror(code)) + else: + return False + return True + except OSError as error: + # Only Linux's successful exclusive open establishes ownership. In + # particular EEXIST must leave an existing destination untouched. + if created: + destination.unlink(missing_ok=True) + if error.errno not in unsupported or destination.exists(): + raise + return False + + +def copy_source_file(source, destination, reserve_bytes=0): + """Clone or copy while reserving bytes for the rewritten assignments.""" + source, destination = Path(source), Path(destination) + if destination.exists(): + raise FileExistsError(destination) + if reflink(source, destination): + return True + needed = source.stat().st_size + reserve_bytes + free = shutil.disk_usage(destination.parent).free + if free < needed: + raise OSError( + f'Insufficient disk space for full replay copy: need {needed:,} bytes, ' + f'{free:,} available.' + ) + shutil.copyfile(source, destination) + return False diff --git a/phy/apps/large_recording/live_summaries.py b/phy/apps/large_recording/live_summaries.py new file mode 100644 index 000000000..31c7e3beb --- /dev/null +++ b/phy/apps/large_recording/live_summaries.py @@ -0,0 +1,778 @@ +"""Exact, bounded source scans for immutable curated unit memberships. + +Instances belong to the background worker. Only completed, read-only summary +arrays cross back to the GUI; neither a session nor a model is used here. +""" + +import hashlib +import json +import os +import tempfile +import zipfile +from concurrent.futures import CancelledError +from contextlib import suppress +from pathlib import Path +from threading import Lock + +import numpy as np + +from .curation import evaluate_predicate, validate_predicate +from .metadata import read_metadata +from .source import close_array, hash_json + +VERSION = 2 +_reader_lock = Lock() +_reader_pool = {} + + +def acquire_source_engine(package_path, source_dir=None, factory=None): + """Lease a worker-owned reader shared by serialized heavy-I/O services.""" + factory = factory or LiveSummaryEngine + key = (str(Path(package_path).resolve()), str(source_dir), factory) + with _reader_lock: + if key not in _reader_pool: + _reader_pool[key] = [factory(package_path, source_dir=source_dir), 0] + record = _reader_pool[key] + record[1] += 1 + return key, record[0] + + +def release_source_engine(key): + with _reader_lock: + record = _reader_pool[key] + record[1] -= 1 + if not record[1]: + record[0].close() + del _reader_pool[key] + + +def _union(parts): + flattened = [] + for part in parts: + flattened.extend(part['parts'] if part['kind'] == 'union' else [part]) + # Reuniting both children restores the exact parent membership, independent + # of how the GUI allocated their transient IDs. + siblings = {} + for index, part in enumerate(flattened): + if part['kind'] == 'split' and part['predicate']['nonfinite'] == 'keep': + binding = hash_json({'parent': part['parent'], 'predicate': part['predicate']}) + previous = siblings.get(binding) + if previous is not None and flattened[previous]['selected'] != part['selected']: + return _union( + [p for i, p in enumerate(flattened) if i not in (previous, index)] + + [part['parent']] + ) + siblings[binding] = index + flattened.sort(key=hash_json) + return flattened[0] if len(flattened) == 1 else {'kind': 'union', 'parts': flattened} + + +def membership_expressions(unit_ids, events, *, restore_sources=None, history=None): + """Resolve journal memberships without retaining labels or allocated IDs. + + The caller supplies an already validated semantic journal. Expressions are + JSON values rooted exclusively in the preparation's original unit IDs. + """ + active = {int(unit): {'kind': 'source', 'unit': int(unit)} for unit in unit_ids} + merges = {} + historical = {(-1, unit): expression for unit, expression in active.items()} + for index, event in enumerate(events): + operation = event['operation'] + if operation == 'merge': + parts = [active.pop(unit) for unit in event['parents']] + merges[index] = parts + active[event['target']] = _union(parts) + historical[(index, event['target'])] = active[event['target']] + elif operation == 'threshold_split': + parent = active.pop(event['parent']) + predicate = validate_predicate(event['predicate']) + for selected, child in enumerate(event['children']): + active[child] = { + 'kind': 'split', + 'parent': parent, + 'predicate': predicate, + 'selected': bool(selected), + } + historical[(index, child)] = active[child] + elif operation == 'restore_parents': + active.pop(event['target']) + parts = ( + [ + historical[(ref['event_index'], ref['unit'])] + for ref in event['parent_references'] + ] + if event['version'] == 4 + else merges[event['merge_event_index']] + ) + active.update(dict(zip(event['children'], parts, strict=True))) + historical.update( + { + (index, child): expression + for child, expression in zip(event['children'], parts, strict=True) + } + ) + if restore_sources is not None: + restore_sources[index] = parts + elif operation not in ('label', 'metadata_policy'): + raise ValueError('Unsupported membership operation.') + if history is not None: + history.update(historical) + return active + + +def _membership_contains(actual, required, memo=None): + """Prove scope containment using only canonical membership structure. + + A filtered scope is a subset of its parent, and equal filters preserve + containment. Unknown predicate relationships deliberately yield no proof. + """ + memo = {} if memo is None else memo + key = (id(actual), id(required)) + if key in memo: + return memo[key] + if actual == required: + memo[key] = True + return True + memo[key] = False + if required['kind'] == 'union': + proof = all(_membership_contains(actual, part, memo) for part in required['parts']) + elif required['kind'] == 'split' and _membership_contains(actual, required['parent'], memo): + proof = True + elif actual['kind'] == 'union': + proof = any(_membership_contains(part, required, memo) for part in actual['parts']) + elif actual['kind'] == required['kind'] == 'split': + proof = ( + actual['predicate'] == required['predicate'] + and actual['selected'] == required['selected'] + and _membership_contains(actual['parent'], required['parent'], memo) + ) + else: + proof = False + memo[key] = proof + return proof + + +def _check_cancel(cancel): + if cancel is not None and cancel(): + raise CancelledError() + + +def _signature(stat): + return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) + + +def _freeze(summary): + for array in ( + summary['counts'], + *summary['trend_sums'].values(), + *summary['trend_counts'].values(), + ): + array.flags.writeable = False + return summary + + +class LiveSummaryEngine: + """Resolve prepared/cache summaries and scan missing expressions together. + + ``max_bytes`` bounds completed outputs of one request and all resident + derived summaries. ``cache_bytes`` bounds this package's derived disk cache. + No cache is needed to save or replay curation. + """ + + def __init__( + self, + package_path, + source_dir=None, + batch_size=1000000, + max_bytes=67108864, + cache_bytes=268435456, + ): + self.path = Path(package_path) + self.manifest = json.loads((self.path / '_phy_curation_manifest.json').read_text()) + self.source_dir = Path(source_dir or self.manifest['source']['path']) + if self.source_dir.name == 'params.py': + self.source_dir = self.source_dir.parent + self.batch_size = int(batch_size) + self.max_bytes, self.cache_bytes = int(max_bytes), int(cache_bytes) + if self.batch_size <= 0 or self.max_bytes <= 0 or self.cache_bytes < 0: + raise ValueError('Live summary budgets must be positive.') + self.files = self.manifest.get('summaries', self.manifest) + self.fields = sorted(key[:-9] for key in self.files if key.endswith('_sum_file')) + self.edges = np.load(self.path / self.files['edges_file'], allow_pickle=False) + self.exposure = np.load(self.path / self.files['exposure_file'], allow_pickle=False) + if ( + self.edges.dtype != np.int64 + or self.edges.ndim != 1 + or len(self.edges) < 2 + or self.edges[0] != 0 + or self.edges[-1] != self.manifest['num_samples'] + or np.any(np.diff(self.edges) <= 0) + or self.exposure.shape != (len(self.edges) - 1,) + ): + raise ValueError('Invalid native summary grid.') + self.bins = len(self.edges) - 1 + self.summary_bytes = self.bins * 8 * (1 + 2 * len(self.fields)) + self.binding = { + 'version': VERSION, + 'source': self.manifest['source']['identity'], + 'revision': self.manifest['source']['revision'], + 'edges': self.edges.tolist(), + 'fields': self.fields, + } + self.binding_digest = hash_json(self.binding) + self.cache_dir = self.path / '.phy' / 'live-summary-cache' + self.arrays, self.handles, self.signatures = {}, {}, {} + self.path_signatures = {} + self.metadata_signature = None + self.resident = {} + self.range_index = None + self.range_reference = None + self.last_resolution_path = 'prepared/cache' + + def key(self, expression): + return hash_json({'binding_sha256': self.binding_digest, 'expression': expression}) + + def close(self): + if self.range_index is not None: + self.range_index.close() + self.range_index = None + self.range_reference = None + for array in self.arrays.values(): + close_array(array) + for handle in self.handles.values(): + handle.close() + self.arrays.clear() + self.handles.clear() + self.signatures.clear() + self.path_signatures.clear() + self.resident.clear() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def _empty(self): + return { + 'counts': np.zeros(self.bins, dtype=np.int64), + 'trend_sums': {f: np.zeros(self.bins, dtype=np.float64) for f in self.fields}, + 'trend_counts': {f: np.zeros(self.bins, dtype=np.int64) for f in self.fields}, + } + + def _prepared(self, expression): + if expression['kind'] != 'source': + return None + row = self.manifest['unit_ids'].index(expression['unit']) + result = self._empty() + names = [('counts', None, self.files['counts_file'])] + for field in self.fields: + names.extend( + [ + ('trend_sums', field, self.files[f'{field}_sum_file']), + ('trend_counts', field, self.files[f'{field}_count_file']), + ] + ) + for kind, field, filename in names: + array = np.load(self.path / filename, mmap_mode='r', allow_pickle=False) + try: + target = result[kind] if field is None else result[kind][field] + if array.shape != (len(self.manifest['unit_ids']), self.bins): + raise ValueError('Invalid prepared summary shape.') + target[:] = array[row] + finally: + close_array(array) + return _freeze(result) + + def _flat(self, summary): + return { + 'counts': summary['counts'], + **{f'{f}_sum': summary['trend_sums'][f] for f in self.fields}, + **{f'{f}_count': summary['trend_counts'][f] for f in self.fields}, + } + + def _cached(self, key): + path = self.cache_dir / f'{key}.npz' + try: + if path.stat().st_size > self.summary_bytes + 16384: + return None + expected = {'counts': np.dtype('int64')} + for field in self.fields: + expected[f'{field}_sum'] = np.dtype('float64') + expected[f'{field}_count'] = np.dtype('int64') + with path.open('rb') as stream: + with zipfile.ZipFile(stream) as archive: + entries = archive.infolist() + names = {f'{name}.npy' for name in expected} | {'metadata.npy'} + if ( + len(entries) != len(names) + or {info.filename for info in entries} != names + or sum(info.file_size for info in entries) > self.summary_bytes + 16384 + ): + return None + for info in entries: + with archive.open(info) as member: + version = np.lib.format.read_magic(member) + if version == (1, 0): + shape, _, dtype = np.lib.format.read_array_header_1_0(member) + elif version == (2, 0): + shape, _, dtype = np.lib.format.read_array_header_2_0(member) + else: + return None + if info.filename == 'metadata.npy': + if shape != () or dtype.kind != 'U' or dtype.itemsize > 16384: + return None + size = dtype.itemsize + else: + name = info.filename[:-4] + if shape != (self.bins,) or dtype != expected[name]: + return None + size = self.bins * dtype.itemsize + if member.tell() + size != info.file_size: + return None + stream.seek(0) + with np.load(stream, allow_pickle=False) as record: + metadata = json.loads(str(record['metadata'])) + if not isinstance(metadata, dict): + return None + result = self._empty() + arrays = self._flat(result) + if ( + metadata.get('version') != VERSION + or metadata.get('key') != key + or set(record.files) != set(arrays) | {'metadata'} + ): + return None + for name, target in arrays.items(): + value = record[name] + if ( + value.shape != target.shape + or value.dtype != target.dtype + or hashlib.sha256(value.tobytes()).hexdigest() + != metadata['hashes'][name] + ): + return None + if (name == 'counts' or name.endswith('_count')) and np.any(value < 0): + return None + if not np.isfinite(value).all(): + return None + target[:] = value + if any( + np.any(result['trend_counts'][f] > result['counts']) for f in self.fields + ): + return None + return _freeze(result) + except (OSError, ValueError, KeyError, TypeError, EOFError, zipfile.BadZipFile): + return None + + def _publish(self, key, summary): + if self.summary_bytes + 16384 > self.cache_bytes: + return + temporary = None + try: + self.cache_dir.mkdir(parents=True, exist_ok=True) + arrays = self._flat(summary) + metadata = { + 'version': VERSION, + 'key': key, + 'hashes': { + name: hashlib.sha256(value.tobytes()).hexdigest() + for name, value in arrays.items() + }, + } + with tempfile.NamedTemporaryFile( + dir=self.cache_dir, suffix='.tmp', delete=False + ) as stream: + temporary = Path(stream.name) + np.savez(stream, metadata=json.dumps(metadata), **arrays) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, self.cache_dir / f'{key}.npz') + records = sorted(self.cache_dir.glob('*.npz'), key=lambda p: p.stat().st_mtime_ns) + total = sum(p.stat().st_size for p in records) + for record in records: + if total <= self.cache_bytes: + break + size = record.stat().st_size + record.unlink() + total -= size + except OSError: + pass # Derived cache availability must not affect curation. + finally: + if temporary is not None: + with suppress(OSError): + temporary.unlink(missing_ok=True) + + def _metadata_state(self): + names = [ + p + for p in self.source_dir.iterdir() + if p.name.startswith('cluster_') + and p.stem != 'cluster_info' + and p.suffix in ('.csv', '.tsv') + ] + names.extend(p for p in self.source_dir.glob('_phy_cluster_metadata*') if p.is_file()) + return {p.name: _signature(p.stat()) for p in names} + + def _unchanged(self): + for name, handle in self.handles.items(): + expected = self.signatures[name] + if ( + _signature(os.fstat(handle.fileno())) != expected + or _signature((self.source_dir / name).stat()) != self.path_signatures[name] + ): + raise ValueError(f'Source changed during live summary: {name}.') + if ( + self.metadata_signature is not None + and self._metadata_state() != self.metadata_signature + ): + raise ValueError('Source metadata changed during live summary.') + + def _open(self, names, cancel, progress=None): + validated = set(self.arrays) + try: + _check_cancel(cancel) + self._unchanged() + metadata_before = self._metadata_state() + # Bind metadata before cancellation can retain an authenticated + # assignment file from an otherwise incomplete multi-file open. + self.metadata_signature = metadata_before + new_names = names - self.arrays.keys() + total_bytes = sum((self.source_dir / n).stat().st_size for n in new_names) + hashed_bytes = 0 + for name in sorted(new_names): + _check_cancel(cancel) + path = self.source_dir / name + self.path_signatures[name] = _signature(path.stat()) + handle = path.open('rb') + self.handles[name] = handle + self.signatures[name] = _signature(os.fstat(handle.fileno())) + # Windows 3.12 path stat reports creation time as ctime, while + # fstat can report metadata change time. Bind both snapshots + # using identity/size/mtime, and retain each provider's ctime + # for its own subsequent stability checks. + if self.path_signatures[name][:-1] != self.signatures[name][:-1]: + raise ValueError(f'Source changed during live summary: {name}.') + digest = hashlib.sha256() + while block := handle.read(1024 * 1024): + _check_cancel(cancel) + digest.update(block) + hashed_bytes += len(block) + if progress: + progress('validating source', hashed_bytes, total_bytes) + array = np.load(path, mmap_mode='r', allow_pickle=False) + self.arrays[name] = array + inventory = self.manifest['source_array_inventory'][name] + if ( + list(array.shape) != inventory['shape'] + or str(array.dtype) != inventory['dtype'] + or array.nbytes != inventory['bytes'] + or len(array) != self.manifest['num_spikes'] + or not np.issubdtype(array.dtype, np.number) + ): + raise ValueError(f'Source shape/dtype inventory mismatch: {name}.') + if name != 'spike_positions.npy' and not ( + array.ndim == 1 or array.shape[1:] == (1,) + ): + raise ValueError(f'Source must contain scalar rows: {name}.') + if name != 'spike_clusters.npy': + expected = self.manifest['source']['identity']['arrays'][name] + if digest.hexdigest() != expected: + raise ValueError(f'Source hash mismatch: {name}.') + else: + revision = hash_json( + { + 'assignments': digest.hexdigest(), + 'metadata': read_metadata(self.source_dir)[0], + } + ) + if revision != self.manifest['source']['revision']: + raise ValueError('Source assignment revision mismatch.') + self._unchanged() + validated.add(name) + if metadata_before != self._metadata_state(): + raise ValueError('Source metadata changed during validation.') + self.metadata_signature = metadata_before + self._unchanged() + except CancelledError: + # Request cancellation does not revoke previously authenticated files. + for name in set(self.handles) - validated: + close_array(self.arrays.pop(name, None)) + self.handles.pop(name).close() + self.signatures.pop(name, None) + self.path_signatures.pop(name, None) + raise + except BaseException: + self.close() + raise + + def _required(self, expression): + kind = expression['kind'] + if kind == 'source': + return set() + if kind == 'union': + return set().union(*(self._required(p) for p in expression['parts'])) + if kind == 'split': + return {expression['predicate']['attribute']} | self._required(expression['parent']) + raise ValueError('Unsupported membership expression.') + + def _mask(self, expression, batch, memo=None): + # Parents and sibling predicates are shared within a bounded batch. + memo = {} if memo is None else memo + key = hash_json(expression) + if key in memo: + return memo[key] + kind = expression['kind'] + if kind == 'source': + mask = batch['spike_clusters.npy'] == expression['unit'] + elif kind == 'union': + mask = np.zeros(len(batch['spike_times.npy']), dtype=bool) + for part in expression['parts']: + mask |= self._mask(part, batch, memo) + else: + parent = self._mask(expression['parent'], batch, memo) + predicate = expression['predicate'] + predicate_key = hash_json({'parent': expression['parent'], 'predicate': predicate}) + if predicate_key not in memo: + memo[predicate_key] = evaluate_predicate( + batch[predicate['attribute']][parent], predicate + ) + selected = memo[predicate_key] + mask = parent.copy() + mask[parent] = selected if expression['selected'] else ~selected + memo[key] = mask + return mask + + def _accumulate(self, summary, columns, selected, scalars): + summary['counts'] += np.bincount(columns[selected], minlength=self.bins) + for field, values in scalars.items(): + finite = selected & np.isfinite(values) + summary['trend_sums'][field] += np.bincount( + columns[finite], weights=values[finite].astype(np.float64), minlength=self.bins + ) + summary['trend_counts'][field] += np.bincount(columns[finite], minlength=self.bins) + + def _chunk_size(self, expressions, row_bytes=64): + nodes = set() + + def visit(e): + key = hash_json(e) + if key in nodes: + return + nodes.add(key) + if e['kind'] == 'split': + visit(e['parent']) + elif e['kind'] == 'union': + for part in e['parts']: + visit(part) + + for expression in expressions.values(): + visit(expression) + return min(self.batch_size, max(1, self.max_bytes // (row_bytes + 2 * len(nodes)))) + + def _indexed(self, expressions, cancel, progress): + from .summary_store import StoreIntegrityError, SummaryStore + + # Template predicates are supported by the source fallback. They must + # never be evaluated from a lossy or absent indexed scalar. + if any(self._required(e) - {'amplitudes.npy'} for e in expressions.values()): + return None + + # Keep authenticated immutable pages across worker queries. Reattachment + # changes the small reference and invalidates all pinned range readers. + from .range_index import AmplitudeRangeIndex + from .range_intervals import RangeUnavailableError + from .summary_store import summary_store_reference + + reference = summary_store_reference(self.path, allow_invalid=True) + if reference != self.range_reference: + if self.range_index is not None: + self.range_index.close() + self.range_index = None + self.range_reference = reference + with suppress(OSError, ValueError, KeyError, TypeError, OverflowError): + self.range_index = AmplitudeRangeIndex(self) + if self.range_index is not None: + try: + result = self.range_index.resolve(expressions, cancel, progress) + self.last_resolution_path = 'amplitude-index' + return result + except RangeUnavailableError: + pass # Unsupported/numerically unstable queries use verified rows. + except (OSError, StoreIntegrityError): + self.range_index.close() + self.range_index = None + + def ancestors(expression): + if expression['kind'] == 'source': + return {expression['unit']} + if expression['kind'] == 'split': + return ancestors(expression['parent']) + return set().union(*(ancestors(p) for p in expression['parts'])) + + ancestry = {unit: ancestors(e) for unit, e in expressions.items()} + originals = sorted(set().union(*ancestry.values())) + outputs = {unit: self._empty() for unit in expressions} + try: + store = SummaryStore(self) + except (OSError, ValueError, KeyError, TypeError, OverflowError): + return None + with store: + total = sum(store.index['units'][str(u)]['count'] for u in originals) + done = 0 + # Bound all masks, input records and bin-index scratch space, even + # for long journals. No recording-sized expression intermediates. + chunk_size = self._chunk_size(expressions, store.dtype.itemsize + 64) + for original in originals: + targets = {u: e for u, e in expressions.items() if original in ancestry[u]} + for data in store.batches(original, chunk_size, cancel): + columns = data['bin'].astype(np.intp) + if np.any(columns >= self.bins): + raise StoreIntegrityError('Summary store bin outside native grid.') + batch = { + 'spike_times.npy': columns, + 'spike_clusters.npy': np.full(len(data), original, dtype=np.int64), + } + if 'amplitude' in self.fields: + batch['amplitudes.npy'] = data['amplitude'] + memo = {} + scalars = {field: data[field] for field in self.fields} + for unit, expression in targets.items(): + _check_cancel(cancel) + selected = self._mask(expression, batch, memo) + self._accumulate(outputs[unit], columns, selected, scalars) + done += len(data) + if progress: + progress('reading prepared unit summaries', done, total) + _check_cancel(cancel) + self.last_resolution_path = 'row-store' + return outputs + + def remember(self, expressions, results): + """Remember immutable completed results within the resident byte budget.""" + for unit, value in results.items(): + if unit not in expressions: + continue + key = self.key(expressions[unit]) + if key not in self.resident: + while ( + self.resident + and (len(self.resident) + 1) * self.summary_bytes > self.max_bytes + ): + self.resident.pop(next(iter(self.resident))) + if self.summary_bytes <= self.max_bytes: + self.resident[key] = _freeze(value) + + def cached(self, expressions, cancel=None): + """Resolve available prepared, cached and additive results without source IO.""" + if len(expressions) * self.summary_bytes > self.max_bytes: + raise ValueError('Live summary output budget exceeded.') + + def resolve_one(expression): + _check_cancel(cancel) + key = self.key(expression) + if key in self.resident: + return self.resident[key] + value = self._prepared(expression) or self._cached(key) + if value is None and expression['kind'] == 'union': + value = self._empty() + for expression_part in expression['parts']: + part = resolve_one(expression_part) + if part is None: + return None + for name, target in self._flat(value).items(): + target += self._flat(part)[name] + value = _freeze(value) + return value + + results = {} + for unit, expression in expressions.items(): + value = resolve_one(expression) + if value is not None: + results[unit] = value + return results + + def resolve(self, expressions, cancel=None, progress=None): + """Return complete summaries, scanning every unresolved membership once.""" + self.last_resolution_path = 'prepared/cache' + results = self.cached(expressions, cancel) + missing = { + unit: expression for unit, expression in expressions.items() if unit not in results + } + if not missing: + return results + from .summary_store import StoreIntegrityError + + try: + indexed = self._indexed(missing, cancel, progress) + except (OSError, StoreIntegrityError): + # Missing, incompatible or damaged acceleration is disposable. + # The original source retains its full validation guarantees. + indexed = None + if indexed is not None: + for unit, summary in indexed.items(): + results[unit] = _freeze(summary) + self._publish(self.key(missing[unit]), summary) + return results + self.last_resolution_path = 'source' + names = {'spike_times.npy', 'spike_clusters.npy'} + for expression in missing.values(): + names |= self._required(expression) + if 'amplitude' in self.fields: + names.add('amplitudes.npy') + depth_name = 'spike_depths.npy' + if 'depth' in self.fields: + if depth_name not in self.manifest['source_array_inventory']: + depth_name = 'spike_positions.npy' + names.add(depth_name) + self._open(names, cancel, progress=progress) + outputs = {unit: self._empty() for unit in missing} + try: + chunk_size = self._chunk_size(missing, 128) + for start in range(0, self.manifest['num_spikes'], chunk_size): + _check_cancel(cancel) + stop = start + chunk_size + batch = { + name: array[start:stop].reshape(-1) + for name, array in self.arrays.items() + if name != 'spike_positions.npy' + } + times = batch['spike_times.npy'] + if ( + not np.issubdtype(times.dtype, np.integer) + or np.any(times < 0) + or np.any(times >= self.manifest['num_samples']) + ): + raise ValueError('Source spike times outside recording bounds.') + columns = np.searchsorted(self.edges, times, side='right') - 1 + scalars = {} + if 'amplitude' in self.fields: + scalars['amplitude'] = batch['amplitudes.npy'] + if 'depth' in self.fields: + if depth_name == 'spike_positions.npy': + axis = self.manifest['source']['identity']['acquisition']['depth_axis'] + scalars['depth'] = self.arrays[depth_name][start:stop, axis] + else: + scalars['depth'] = batch[depth_name] + memo = {} + for unit, expression in missing.items(): + _check_cancel(cancel) + selected = self._mask(expression, batch, memo) + self._accumulate(outputs[unit], columns, selected, scalars) + if progress: + progress( + 'scanning full source', + min(stop, self.manifest['num_spikes']), + self.manifest['num_spikes'], + ) + _check_cancel(cancel) + self._unchanged() + for unit, summary in outputs.items(): + results[unit] = _freeze(summary) + self._publish(self.key(missing[unit]), summary) + return results + except CancelledError: + raise + except BaseException: + self.close() + raise diff --git a/phy/apps/large_recording/metadata.py b/phy/apps/large_recording/metadata.py new file mode 100644 index 000000000..446a3e018 --- /dev/null +++ b/phy/apps/large_recording/metadata.py @@ -0,0 +1,211 @@ +"""Lossless producer table layout and typed canonical unit metadata.""" + +import ast +import csv +import json +from pathlib import Path + +SCHEMA_FILE = '_phy_cluster_metadata_schema.json' +POLICY = 'membership_v1' + + +def normalize_value(value): + """Empty table cells represent missing values, including in typed JSON.""" + return None if value == '' else value + + +def cell(value): + if value is None: + return '' + if isinstance(value, (dict, list, bool)): + return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + return str(value) + + +def _legacy_cell_matches(text, value): + if text == str(value): + return True + if not isinstance(value, (dict, list)): + return False + try: + # Old csv.writer used Python repr, while the JSON sidecar sorted keys + # and converted tuples to lists. Compare JSON meaning without exec or + # Python's bool/int equality conflating true with 1. + candidate = json.loads(json.dumps(ast.literal_eval(text), allow_nan=False)) + options = {'sort_keys': True, 'separators': (',', ':'), 'allow_nan': False} + return json.dumps(candidate, **options) == json.dumps(value, **options) + except (SyntaxError, TypeError, ValueError): + return False + + +def validate_schema(schema): + if ( + not isinstance(schema, dict) + or set(schema) != {'version', 'tables'} + or schema['version'] != 1 + ): + raise ValueError('Unsupported metadata table schema.') + if not isinstance(schema['tables'], list): + raise ValueError('Metadata schema tables must be an ordered list.') + names, fields = set(), set() + for table in schema['tables']: + if not isinstance(table, dict) or set(table) != {'filename', 'delimiter', 'columns'}: + raise ValueError('Invalid metadata table descriptor.') + name, columns = table['filename'], table['columns'] + if ( + not isinstance(name, str) + or Path(name).name != name + or '\\' in name + or any(c in name for c in '\0\n\r') + or not name.startswith('cluster_') + or Path(name).suffix not in ('.tsv', '.csv') + or Path(name).stem.casefold() == 'cluster_info' + or name.casefold() in names + ): + raise ValueError(f'Unsafe, reserved or colliding metadata filename: {name!r}.') + if table['delimiter'] != ('\t' if name.endswith('.tsv') else ','): + raise ValueError(f'Invalid metadata delimiter: {name}.') + if ( + not isinstance(columns, list) + or len(columns) < 2 + or columns.count('cluster_id') != 1 + or any( + not isinstance(f, str) or not f or any(c in f for c in '/\\\0\n\r\t') + for f in columns + ) + or len(set(columns)) != len(columns) + ): + raise ValueError(f'Invalid or duplicate metadata columns: {name}.') + for field in columns: + if field != 'cluster_id': + if field in fields: + raise ValueError(f'Duplicate metadata field {field!r} in {name}.') + fields.add(field) + names.add(name.casefold()) + return {'version': 1, 'tables': sorted(schema['tables'], key=lambda t: t['filename'])} + + +def complete_schema(schema, metadata): + if 'cluster_id' in metadata: + raise ValueError('cluster_id is reserved for the metadata unit index.') + schema = json.loads(json.dumps(validate_schema(schema))) + fields = {f for t in schema['tables'] for f in t['columns']} + for field in sorted(set(metadata) - fields): + schema['tables'].append( + { + 'filename': f'cluster_{field}.tsv', + 'delimiter': '\t', + 'columns': ['cluster_id', field], + } + ) + return validate_schema(schema) + + +def read_metadata(path): + path = Path(path) + schema_path = path / SCHEMA_FILE + declared = json.loads(schema_path.read_text()) if schema_path.exists() else None + tables, parsed = [], {} + filenames = sorted([*path.glob('cluster_*.tsv'), *path.glob('cluster_*.csv')]) + for filename in filenames: + if filename.stem == 'cluster_info': + continue + with filename.open(encoding='utf-8', newline='') as stream: + reader = csv.reader(stream, delimiter='\t' if filename.suffix == '.tsv' else ',') + columns = next(reader, []) + table = { + 'filename': filename.name, + 'delimiter': '\t' if filename.suffix == '.tsv' else ',', + 'columns': columns, + } + tables.append(table) + validate_schema({'version': 1, 'tables': tables}) + for field in columns: + if field != 'cluster_id': + parsed.setdefault(field, {}) + seen = set() + for row in reader: + if len(row) != len(columns): + raise ValueError(f'Malformed metadata row in {filename.name}.') + raw_id = row[columns.index('cluster_id')] + try: + unit = int(raw_id) + except ValueError as error: + raise ValueError(f'Invalid unit ID in {filename.name}: {raw_id!r}.') from error + if unit < 0 or unit in seen: + raise ValueError(f'Duplicate or negative unit {unit} in {filename.name}.') + seen.add(unit) + for field, value in zip(columns, row): + if field != 'cluster_id': + parsed.setdefault(field, {})[unit] = ( + value if declared is None else normalize_value(value) + ) + schema = validate_schema({'version': 1, 'tables': tables}) + if declared is not None and validate_schema(declared) != schema: + raise ValueError('Metadata table files or columns disagree with metadata schema.') + sidecar = path / '_phy_cluster_metadata.json' + if not sidecar.exists(): + if declared is not None: + raise ValueError('Metadata schema requires the canonical typed JSON sidecar.') + return parsed, schema + raw = json.loads(sidecar.read_text(encoding='utf-8')) + if not isinstance(raw, dict): + raise ValueError('Cluster metadata JSON must be a field mapping.') + canonical = {} + for field, values in raw.items(): + if not isinstance(values, dict): + raise ValueError('Cluster metadata fields must map integer cluster IDs to values.') + canonical[field] = {} + for key, value in values.items(): + unit = int(key) + if str(unit) != key or unit < 0: + raise ValueError('Cluster metadata IDs must be nonnegative canonical integers.') + canonical[field][unit] = value + complete_schema(schema, canonical) # Validate field-derived filenames as well. + for table in tables: + for field in table['columns']: + if field == 'cluster_id': + continue + left, right = parsed.get(field, {}), canonical.get(field, {}) + for unit in set(left) | set(right): + if declared is None and unit not in left and right.get(unit) is None: + continue # Legacy writer omitted rows for JSON null values. + if ( + declared is None + and unit in left + and unit in right + and _legacy_cell_matches(left[unit], right[unit]) + ): + continue # Legacy csv.writer used Python representations for typed values. + if unit not in left or unit not in right or cell(left[unit]) != cell(right[unit]): + raise ValueError( + f'Metadata conflict in {table["filename"]}, field {field}, unit {unit}.' + ) + if declared is not None and set(canonical) != set(parsed): + raise ValueError('Canonical metadata fields disagree with table schema.') + return canonical, complete_schema(schema, canonical) + + +def write_metadata(path, metadata, schema): + """Keep source basenames, delimiters and column order, including blank rows.""" + schema = complete_schema(schema, metadata) + filenames = [table['filename'] for table in schema['tables']] + for filename in [*filenames, '_phy_cluster_metadata.json', SCHEMA_FILE]: + if (path / filename).is_symlink(): + raise ValueError(f'Metadata output must not overwrite a symbolic link: {filename}.') + for table in schema['tables']: + fields = [f for f in table['columns'] if f != 'cluster_id'] + units = sorted({u for f in fields for u in metadata.get(f, {})}) + with (path / table['filename']).open('w', encoding='utf-8', newline='') as stream: + writer = csv.writer(stream, delimiter=table['delimiter']) + writer.writerow(table['columns']) + for unit in units: + writer.writerow( + [ + unit if f == 'cluster_id' else cell(metadata.get(f, {}).get(unit)) + for f in table['columns'] + ] + ) + (path / '_phy_cluster_metadata.json').write_text(json.dumps(metadata, sort_keys=True) + '\n') + (path / SCHEMA_FILE).write_text(json.dumps(schema, sort_keys=True) + '\n') + return schema diff --git a/phy/apps/large_recording/model.py b/phy/apps/large_recording/model.py new file mode 100644 index 000000000..9f0de0389 --- /dev/null +++ b/phy/apps/large_recording/model.py @@ -0,0 +1,65 @@ +"""Bounded template loading without dense caches indexed by cluster namespace.""" + +from types import MappingProxyType + +import numpy as np +from phylib.io.model import TemplateModel + + +class BoundedTemplateModel(TemplateModel): + """Load committed assignments and original templates as separate concepts. + + The controller derives live unit evidence from Supervisor assignments. + phylib's eager merged-cluster waveform cache allocates by the maximum + absolute ID and does not track subsequent GUI edits; bounded mode does not + expose that cache as current scientific evidence. + """ + + def __init__(self, *args, session, **kwargs): + self._bounded_session = session + super().__init__(*args, **kwargs) + self.sparse_clusters = None + + def freeze_source(self): + """Prevent public model edits from bypassing semantic curation.""" + names = set() + for name, value in vars(self).items(): + if not name.startswith('_') and isinstance(value, np.ndarray): + value.flags.writeable = False + names.add(name) + self.metadata = MappingProxyType( + {name: MappingProxyType(values) for name, values in self.metadata.items()} + ) + names.update( + ( + 'metadata', + 'save_spike_clusters', + 'save_metadata', + 'save_spikes_subset_waveforms', + 'sample_rate', + 'duration', + 'n_channels', + 'n_channels_dat', + 'n_samples_waveforms', + 'dtype', + 'offset', + ) + ) + self._protected_source_names = frozenset(names) + + def __setattr__(self, name, value): + if name in getattr(self, '_protected_source_names', ()): + raise ValueError('Bounded model source is read-only; use semantic curation commands.') + super().__setattr__(name, value) + + def _load_spike_clusters(self): + return self._bounded_session.assignments.copy() + + def get_merge_map(self): + return {}, np.array([], dtype=np.int64) + + def cluster_waveforms(self): + return None + + def get_cluster_mean_waveforms(self, *args, **kwargs): + raise ValueError('Use the controller waveform/template providers for live bounded units.') diff --git a/phy/apps/large_recording/parameters.py b/phy/apps/large_recording/parameters.py new file mode 100644 index 000000000..b76a300ca --- /dev/null +++ b/phy/apps/large_recording/parameters.py @@ -0,0 +1,119 @@ +"""Maintain replay-owned parameter overrides without rewriting user Python.""" + +import ast +import io +import tokenize + +BEGIN = '# BEGIN PHY CURATION PARAMETERS' +END = '# END PHY CURATION PARAMETERS' +KEYS = ('num_samples', 'valid_intervals', 'dat_path') + + +def _assignments(nodes): + values = {} + for node, key in zip(nodes, KEYS, strict=True): + if ( + not isinstance(node, ast.Assign) + or len(node.targets) != 1 + or not isinstance(node.targets[0], ast.Name) + or node.targets[0].id != key + or node.col_offset != 0 + ): + raise ValueError('Not a generated parameter assignment.') + values[key] = ast.literal_eval(node.value) + return values + + +def _without_managed_block(text): + markers = [] + for token in tokenize.generate_tokens(io.StringIO(text).readline): + if token.type == tokenize.COMMENT and token.start[1] == 0 and token.string in (BEGIN, END): + markers.append((token.string, token.start[0])) + if not markers: + return text + if len(markers) != 2 or [item[0] for item in markers] != [BEGIN, END]: + raise ValueError('Malformed Phy curation parameter block.') + lines = text.splitlines(keepends=True) + first, last = markers[0][1] - 1, markers[1][1] - 1 + if ''.join(lines[last + 1 :]).strip(): + raise ValueError('Phy curation parameter block must be the final content in params.py.') + nodes = ast.parse(''.join(lines[first + 1 : last])).body + if len(nodes) != 3: + raise ValueError('Unexpected code inside Phy curation parameter block.') + try: + _assignments(nodes) + except (ValueError, TypeError) as error: + raise ValueError('Unexpected code inside Phy curation parameter block.') from error + return ''.join(lines[:first]) + + +def _strip_legacy_suffix(text, overrides): + """Remove only recognizable duplicated trailing triples from the old writer.""" + while True: + nodes = ast.parse(text).body + if len(nodes) < 6: + return text + tail = nodes[-3:] + try: + values = _assignments(tail) + except (ValueError, TypeError): + return text + if values != overrides: + return text + previous = { + target.id + for node in nodes[:-3] + if isinstance(node, ast.Assign) + for target in node.targets + if isinstance(target, ast.Name) + } + if not set(KEYS) <= previous: + return text + lines = text.splitlines(keepends=True) + if any(node.lineno != node.end_lineno for node in tail): + return text + if [node.lineno for node in tail] != list(range(tail[0].lineno, tail[0].lineno + 3)): + return text + if any( + lines[node.lineno - 1].rstrip('\r\n') != f'{key} = {values[key]!r}' + for node, key in zip(tail, KEYS, strict=True) + ): + return text + if ''.join(lines[tail[-1].end_lineno :]).strip(): + return text + # The old writer inserted one blank line immediately before every triple. + stop = tail[0].lineno - 1 + if stop and not lines[stop - 1].strip(): + stop -= 1 + text = ''.join(lines[:stop]) + + +def rewrite_replay_params(text, *, num_samples, valid_intervals, dat_path): + """Return source text with one stable, final block of replay-owned values. + + Original assignments may feed later user expressions and therefore remain + intact. Only this marked block and confidently identified legacy generated + suffixes are replaced; imports, comments and executable source are retained. + """ + if not isinstance(text, str): + raise TypeError('Parameter source must be text.') + ast.parse(text) # Validate syntax without executing user source again. + overrides = dict(zip(KEYS, (num_samples, valid_intervals, dat_path), strict=True)) + # Recognize old suffix values before normalizing legacy no-raw-data strings. + prefix = _strip_legacy_suffix(_without_managed_block(text), overrides) + paths = dat_path if isinstance(dat_path, (list, tuple)) else [dat_path] + if all( + path is None or (isinstance(path, str) and path.strip() in ('', 'None')) for path in paths + ): + overrides['dat_path'] = None + newline = '\r\n' if '\r\n' in text else '\n' + if prefix and not prefix.endswith(newline * 2): + prefix += newline if prefix.endswith(newline) else newline * 2 + block = newline.join([BEGIN, *(f'{key} = {ascii(overrides[key])}' for key in KEYS), END, '']) + return prefix + block + + +def rewrite_replay_params_bytes(contents, **overrides): + """Preserve a Python encoding cookie/BOM as well as original line endings.""" + encoding, _ = tokenize.detect_encoding(io.BytesIO(contents).readline) + return rewrite_replay_params(contents.decode(encoding), **overrides).encode(encoding) diff --git a/phy/apps/large_recording/prepare.py b/phy/apps/large_recording/prepare.py new file mode 100644 index 000000000..43efa84ac --- /dev/null +++ b/phy/apps/large_recording/prepare.py @@ -0,0 +1,893 @@ +"""Publish a self-contained bounded evidence package from a full sorting.""" + +import json +import os +import shutil +import tempfile +from contextlib import suppress +from pathlib import Path + +import numpy as np + +from .metadata import POLICY, SCHEMA_FILE, write_metadata +from .refractory_resources import ( + DEFAULT_RP_MAX_BYTES, + DEFAULT_RP_MEMORY_BYTES, + plan_refractory_summaries, +) +from .source import ( + PER_SPIKE, + STATIC, + WAVEFORMS, + Source, + close_array, + hash_file, + hash_json, + publish_directory, +) +from .streaming import check_cancel +from .summaries import build_summaries, scalar_attributes, summary_size + + +def _row_bounds(times, windows): + return [ + ( + int(np.searchsorted(times, start, side='left')), + int(np.searchsorted(times, end, side='left')), + ) + for start, end in windows + ] + + +def _union(windows, block_starts=()): + result = [] + for start, end in sorted(windows, key=lambda row: (int(row[0]), int(row[1]))): + if result and ( + start < result[-1][1] or (start == result[-1][1] and start not in block_starts) + ): + result[-1][1] = max(result[-1][1], int(end)) + else: + result.append([int(start), int(end)]) + return result + + +def _selected_waveform_count(source, windows): + ids = source.arrays.get('_phy_spikes_subset.spikes.npy') + if ids is None: + return 0 + return sum( + int(np.searchsorted(ids, stop) - np.searchsorted(ids, start)) + for start, stop in _row_bounds(source.arrays['spike_times.npy'].reshape(-1), windows) + ) + + +def _producer_windows(source): + """Validate optional producer plans without loading waveform tensors.""" + stem = '_phy_spikes_subset.' + bounds = source.arrays.get(stem + 'window_bounds.npy') + types = source.arrays.get(stem + 'window_types.npy') + strata = source.arrays.get(stem + 'window_strata.npy') + if bounds is None: + if types is not None or strata is not None: + raise ValueError('Producer window types/strata require window_bounds.') + return None, None + if bounds.ndim != 2 or bounds.shape[1] != 2 or bounds.dtype.kind not in 'iu': + raise ValueError('Producer window_bounds must be an integer (W, 2) array.') + for label, values in (('types', types), ('strata', strata)): + if values is not None and ( + values.ndim != 1 or len(values) != len(bounds) or values.dtype.kind not in 'iu' + ): + raise ValueError(f'Producer window_{label} must be an aligned integer vector.') + manifest_path = source.path / (stem + 'manifest.json') + info = json.loads(manifest_path.read_text()) if manifest_path.exists() else {} + coordinates = info.get('recording', {}).get('window_bounds_coordinates') + clock = getattr(source, 'time_base', None) + kind = clock['kind'] if clock else 'acquisition_samples' + if coordinates is not None and coordinates != kind: + raise ValueError('Producer window_bounds_coordinates disagrees with the source time_base.') + if kind == 'elapsed_ticks' and coordinates is None: + raise ValueError('Elapsed-tick producer windows require window_bounds_coordinates.') + previous = -1 + for index, (first, last) in enumerate(bounds): + first, last = int(first), int(last) + block = int(np.searchsorted(source.valid_intervals[:, 0], first, side='right') - 1) + if first < previous or first < 0 or last <= first or last > source.num_samples: + raise ValueError( + 'Producer window bounds must be sorted, positive, and inside recording.' + ) + if block < 0 or last > source.valid_intervals[block, 1]: + raise ValueError('Producer window crosses an acquisition block or gap.') + previous = first + code = int(types[index]) if types is not None else 0 + stratum = int(strata[index]) if strata is not None else (-1 if code == 1 else 0) + if code not in (0, 1): + raise ValueError('Producer window_types codes must be 0 (survey) or 1 (rescue).') + if stratum < -1 or (code == 1 and stratum != -1) or (code == 0 and stratum < 0): + raise ValueError( + 'Producer window_strata must be nonnegative for survey and -1 for rescue.' + ) + if source.arrays.keys() >= WAVEFORMS: + union = _union(bounds, set(source.valid_intervals[:, 0])) + if _selected_waveform_count(source, union) != len(source.arrays[stem + 'spikes.npy']): + raise ValueError('Stored waveform rows fall outside the producer window plan.') + provenance = { + 'sha256': hash_json( + { + 'files': { + name: hash_file(source.path / name) + for name in ( + stem + 'window_bounds.npy', + stem + 'window_types.npy', + stem + 'window_strata.npy', + ) + if name in source.arrays + }, + 'coordinates': coordinates, + } + ), + 'window_bounds_coordinates': coordinates, + 'num_windows': len(bounds), + } + return (bounds, types, strata), provenance + + +def _distributed_indices(count): + """Visit sorted windows in a reproducible dyadic spread, using constant memory.""" + if not count: + return + bits = (count - 1).bit_length() + for value in range(1 << bits): + index, remainder = 0, value + for _ in range(bits): + index = (index << 1) | (remainder & 1) + remainder >>= 1 + if index < count: + yield index + + +def prepare_large( + params_path, + output_dir, + duration_seconds=None, + valid_intervals=None, + max_spikes=2000000, + max_bytes=536870912, + window_seconds=30, + stratum_seconds=3600, + seed=0, + batch_size=100000, + bin_seconds=3600, + window_policy='auto', + summary_store=None, + summary_store_max_bytes=68719476736, + workers=1, + cancel=None, + progress=None, + rp_summaries=False, + rp_summary_max_bytes=DEFAULT_RP_MAX_BYTES, + store_timestamps=False, + rp_summary_memory_bytes=DEFAULT_RP_MEMORY_BYTES, +): + """Choose complete shared windows, write bounded arrays, and publish atomically. + + Survey windows use a seeded offset within each acquisition stratum. A second + pass tries one first-spike rescue window for every unit without evidence. + Candidate windows that exceed either budget are explicitly omitted; spikes + within accepted windows are never independently thinned. + """ + if store_timestamps and summary_store is None: + raise ValueError('store_timestamps requires a summary_store destination.') + output_dir = Path(output_dir) + with Source( + params_path, + duration_seconds, + valid_intervals, + batch_size, + workers=workers, + cancel=cancel, + progress=progress, + ) as source: + if rp_summaries: + if 'amplitudes.npy' not in source.arrays: + raise ValueError('Raw source amplitudes unavailable for RP summaries.') + # Source discovery/authentication is required, but no bounded output + # should be built when requested RP resources are already impossible. + rp_manifest = { + 'sample_rate': source.sample_rate, + 'num_samples': source.num_samples, + 'unit_ids': source.unit_ids, + 'valid_intervals': source.valid_intervals.tolist(), + 'source': { + 'identity': source.identity, + 'revision': source.revision, + 'path': str(source.path), + }, + 'source_array_inventory': { + name: {'dtype': str(array.dtype)} for name, array in source.arrays.items() + }, + } + native_bins = summary_size(source, bin_seconds)[2] + rp_plan = plan_refractory_summaries( + rp_manifest, + max_bytes=rp_summary_max_bytes, + memory_bytes=rp_summary_memory_bytes, + batch_size=batch_size, + native_grid_bytes=(2 * native_bins + 1) * 8, + disk_option='--rp-summary-max-bytes', + memory_option='--rp-summary-memory-bytes', + ) + destination = output_dir.parent + while not destination.exists(): + destination = destination.parent + if shutil.disk_usage(destination).free < rp_plan.disk_bytes: + raise OSError(f'RP summaries need {rp_plan.disk_bytes} bytes of free disk space.') + output = _prepare_source( + source, + output_dir, + max_spikes, + max_bytes, + window_seconds, + stratum_seconds, + seed, + batch_size, + bin_seconds, + window_policy, + workers, + cancel, + progress, + ) + if rp_summaries: + from .refractory_store import build_refractory_summaries + + try: + build_refractory_summaries( + output, + source_dir=source.path, + max_bytes=rp_summary_max_bytes, + memory_bytes=rp_summary_memory_bytes, + batch_size=batch_size, + cancel=cancel, + progress=progress, + ) + except (ValueError, OSError) as error: + raise ValueError( + f'Bounded package is ready at {output}; optional RP summaries failed: {error}. ' + 'Use build-rp-summaries to retry without preparing again.' + ) from error + if summary_store is not None: + from .summary_store import build_summary_store + + try: + from .range_build import preflight_summary_store + + preflight_summary_store(output, summary_store_max_bytes, timestamps=store_timestamps) + _, reference = build_summary_store( + output, + summary_store, + source_dir=source.path, + max_bytes=summary_store_max_bytes, + workers=workers, + cancel=cancel, + progress=progress, + return_reference=True, + timestamps=store_timestamps, + ) + from .range_build import build_amplitude_index + from .range_intervals import RangeUnavailableError + + # Unsupported scalar dtypes keep the verified row snapshot. + with suppress(RangeUnavailableError): + build_amplitude_index( + output, + Path(summary_store) / 'amplitude-index', + max_bytes=summary_store_max_bytes, + workers=workers, + cancel=cancel, + progress=progress, + expected_reference=reference, + ) + except (ValueError, OSError) as error: + raise ValueError( + f'Bounded package is ready at {output}; optional summary store failed: ' + f'{error}. Use build-summary-store to retry without preparing again.' + ) from error + return output + + +def _prepare_source( + source, + output_dir, + max_spikes, + max_bytes, + window_seconds, + stratum_seconds, + seed, + batch_size, + bin_seconds, + window_policy, + workers=1, + cancel=None, + progress=None, +): + if window_policy not in ('auto', 'producer', 'generated'): + raise ValueError('window_policy must be auto, producer, or generated.') + producer, producer_provenance = _producer_windows(source) + available = ( + producer is not None and bool(len(producer[0])) and source.arrays.keys() >= WAVEFORMS + ) + if window_policy == 'producer' and not available: + raise ValueError( + 'Producer policy requires nonempty window bounds and stored waveform data.' + ) + resolved_policy = 'producer' if available and window_policy != 'generated' else 'generated' + output_dir = Path(output_dir).resolve() + missing_static = { + 'templates.npy', + 'channel_map.npy', + 'channel_positions.npy', + } - source.arrays.keys() + if missing_static: + raise ValueError(f'Bounded GUI preparation requires: {", ".join(sorted(missing_static))}.') + if output_dir.exists(): + raise ValueError(f'Output already exists: {output_dir}.') + if output_dir == source.path or source.path in output_dir.parents: + raise ValueError('Bounded output must be outside the source dataset directory.') + if int(max_spikes) != max_spikes or max_spikes <= 0 or max_bytes <= 0: + raise ValueError('max_spikes and max_bytes must be positive budgets.') + widths = [] + for label, seconds in ( + ('window_seconds', window_seconds), + ('stratum_seconds', stratum_seconds), + ): + width = float(seconds) * source.sample_rate + if ( + not np.isfinite(width) + or width < 1 + or not np.isclose(width, round(width), rtol=0, atol=1e-6) + ): + raise ValueError(f'{label} must specify a positive integer sample width.') + widths.append(int(round(width))) + width, stratum = widths + times = source.arrays['spike_times.npy'].reshape(-1) + assignments = source.arrays['spike_clusters.npy'].reshape(-1) + summary_bytes = summary_size(source, bin_seconds)[0] + producer_documents = [ + source.path / name + for name in ('curation.json', 'curation_review.json') + if (source.path / name).is_file() + ] + producer_hashes = {path.name: hash_file(path) for path in producer_documents} + fixed_bytes = ( + sum( + path.stat().st_size * (2 if path.name == 'curation_review.json' else 1) + for path in producer_documents + ) + + summary_bytes + + sum((source.path / name).stat().st_size for name in source.arrays.keys() & STATIC) + ) + # Reserve headers, manifest, params, metadata, and window records explicitly. + metadata_bytes = sum( + len(str(value).encode('utf-8')) + 64 + for values in source.metadata.values() + for value in values.values() + ) + overhead = 32768 + metadata_bytes + 1024 * len(source.arrays) + fixed_bytes += overhead + # Candidate records remain present even when rejected. Reserve them before + # selection so an omission cannot silently exceed the byte budget. + if resolved_policy == 'producer': + fixed_bytes += len(producer[0]) * 512 + row_bytes = 16 # int64 global row mapping and baseline assignment + for name in source.arrays.keys() & PER_SPIKE: + array = source.arrays[name] + row_bytes += array.dtype.itemsize * int(np.prod(array.shape[1:], dtype=np.int64)) + waveform_sidecars = source.arrays.keys() & {'_phy_spikes_subset.sample_index.npy'} + waveform_bytes = 0 + if source.arrays.keys() >= WAVEFORMS: + for name in WAVEFORMS | waveform_sidecars: + array = source.arrays[name] + waveform_bytes += array.dtype.itemsize * int(np.prod(array.shape[1:], dtype=np.int64)) + if fixed_bytes > max_bytes: + raise ValueError( + f'Output budget exceeded before selecting evidence: estimated ' + f'{fixed_bytes} bytes; increase max_bytes or bin_seconds.' + ) + windows, plan, omitted = [], [], [] + rng = np.random.default_rng(seed) + + def accept(start, end, kind, segment, stratum_id): + candidate = _union([*windows, [start, end]], set(source.valid_intervals[:, 0])) + n = sum(stop - first for first, stop in _row_bounds(times, candidate)) + n_waveforms = _selected_waveform_count(source, candidate) + size = ( + fixed_bytes + + n * row_bytes + + n_waveforms * waveform_bytes + + (len(candidate) + len(plan) + len(omitted) + 1) * 256 + ) + record = { + 'start': int(start), + 'end': int(end), + 'kind': kind, + 'segment': 0, + 'block': int(segment), + 'stratum': int(stratum_id), + } + if (len(plan) + len(omitted) + 1) * 256 + fixed_bytes > max_bytes: + raise ValueError('Window plan metadata exceeds max_bytes; increase max_bytes.') + if n > max_spikes or size > max_bytes: + omitted.append( + {**record, 'reason': 'spike_budget' if n > max_spikes else 'byte_budget'} + ) + return False + windows[:] = candidate + plan.append(record) + return True + + producer_estimate = None + if resolved_policy == 'producer': + bounds, types, strata = producer + # Counting intersections uses sparse ID binary searches, never waveform data. + union = _union(bounds, set(source.valid_intervals[:, 0])) + all_spikes = sum(stop - first for first, stop in _row_bounds(times, union)) + all_waveforms = _selected_waveform_count(source, union) + producer_estimate = { + 'spikes': all_spikes, + 'waveform_rows': all_waveforms, + 'bytes': fixed_bytes + + all_spikes * row_bytes + + all_waveforms * waveform_bytes + + (len(bounds) + len(union)) * 256, + } + del union + for ordinal, index in enumerate(_distributed_indices(len(bounds)), start=1): + check_cancel(cancel) + first, last = map(int, bounds[index]) + block = int(np.searchsorted(source.valid_intervals[:, 0], first, side='right') - 1) + code = int(types[index]) if types is not None else 0 + kind = 'survey' if code == 0 else 'rescue' + stratum_id = int(strata[index]) if strata is not None else (-1 if code else index) + accept(first, last, kind, block, stratum_id) + if progress is not None: + progress('selecting producer windows', ordinal, len(bounds)) + else: + # Candidate enumeration is scalar and bounded by output-window metadata, + # rather than constructing recording-length arrays. + total_windows = sum( + (int(last) - int(first) + stratum - 1) // stratum + for first, last in source.valid_intervals + ) + selected_windows = 0 + for segment, (first, last) in enumerate(source.valid_intervals): + for start in range(int(first), int(last), stratum): + check_cancel(cancel) + end = min(start + stratum, int(last)) + length = min(width, end - start) + offset = int(rng.integers(0, end - start - length + 1)) + accept( + start + offset, start + offset + length, 'survey', segment, start // stratum + ) + selected_windows += 1 + if progress is not None: + progress('selecting survey windows', selected_windows, total_windows) + if (len(plan) + len(omitted)) * 256 + fixed_bytes > max_bytes: + raise ValueError( + 'Window plan metadata exceeds max_bytes; increase stratum_seconds.' + ) + row_bounds = _row_bounds(times, windows) + n_bounded = sum(stop - first for first, stop in row_bounds) + evidence = set() + evidence_rows = 0 + for first, stop in row_bounds: + for start in range(first, stop, batch_size): + check_cancel(cancel) + end = min(start + batch_size, stop) + evidence.update(np.unique(assignments[start:end]).tolist()) + evidence_rows += end - start + if progress is not None: + progress('checking bounded rows', evidence_rows, n_bounded) + missing = set(source.unit_ids.tolist()) - evidence + for batch in source.iter_batches(): + check_cancel(cancel) + if window_policy == 'producer': + break + if not missing: + break + if progress is not None: + progress( + 'scanning source spikes for rescue', + min(batch['stop'], source.n_spikes), + source.n_spikes, + ) + units, positions = np.unique(batch['spike_clusters.npy'], return_index=True) + for unit, position in zip(units.tolist(), positions.tolist(), strict=True): + if unit not in missing: + continue + sample = int(batch['spike_times.npy'][position]) + segment = int(np.searchsorted(source.valid_intervals[:, 0], sample, side='right') - 1) + first, last = source.valid_intervals[segment] + start = max(int(first), min(sample - width // 2, int(last) - width)) + end = min(start + width, int(last)) + accept(start, end, 'rescue', segment, -1) + # One deterministic rescue attempt per unit, including rejected attempts. + missing.remove(unit) + row_bounds = _row_bounds(times, windows) + n_bounded = sum(stop - first for first, stop in row_bounds) + if not n_bounded: + raise ValueError( + 'No bounded evidence fits the budgets; increase max_spikes/max_bytes ' + 'or shorten window_seconds (tied spikes remain together).' + ) + output_dir.parent.mkdir(parents=True, exist_ok=True) + estimated_bytes = ( + fixed_bytes + + n_bounded * row_bytes + + _selected_waveform_count(source, windows) * waveform_bytes + + (len(windows) + len(plan) + len(omitted)) * 256 + ) + free = shutil.disk_usage(output_dir.parent).free + if free < estimated_bytes: + raise OSError( + f'Insufficient disk space for bounded preparation: estimated {estimated_bytes:,} bytes, {free:,} available.' + ) + temporary = Path( + tempfile.mkdtemp(prefix=f'.{output_dir.name}.prepare-', dir=output_dir.parent) + ) + global_ids, base, destinations = None, None, {} + try: + global_ids = np.lib.format.open_memmap( + temporary / '_phy_spike_global_ids.npy', mode='w+', dtype=np.int64, shape=(n_bounded,) + ) + for name in source.arrays.keys() & PER_SPIKE: + array = source.arrays[name] + destinations[name] = np.lib.format.open_memmap( + temporary / name, mode='w+', dtype=array.dtype, shape=(n_bounded, *array.shape[1:]) + ) + base = np.lib.format.open_memmap( + temporary / '_phy_spike_clusters_base.npy', + mode='w+', + dtype=np.int64, + shape=(n_bounded,), + ) + cursor = 0 + bounded_counts = {int(unit): 0 for unit in source.unit_ids} + for first, stop in row_bounds: + for start in range(first, stop, batch_size): + check_cancel(cancel) + end = min(start + batch_size, stop) + length = end - start + global_ids[cursor : cursor + length] = np.arange(start, end, dtype=np.int64) + base[cursor : cursor + length] = assignments[start:end] + for name, target in destinations.items(): + target[cursor : cursor + length] = source.arrays[name][start:end] + ids, counts = np.unique(assignments[start:end], return_counts=True) + for unit, count in zip(ids.tolist(), counts.tolist(), strict=True): + bounded_counts[unit] += count + cursor += length + if progress is not None: + progress('writing bounded rows', cursor, n_bounded) + for array in (global_ids, base, *destinations.values()): + array.flush() + _copy_files( + ((source.path / name, temporary / name) for name in source.arrays.keys() & STATIC), + cancel=cancel, + progress=progress, + stage='copying static arrays', + ) + if source.arrays.keys() >= WAVEFORMS: + _copy_waveforms(source, temporary, global_ids, row_bounds, cancel, progress) + waveform_counts = {int(unit): 0 for unit in source.unit_ids} + waveform_ids_path = temporary / '_phy_spikes_subset.spikes.npy' + if waveform_ids_path.exists(): + waveform_ids = np.load(waveform_ids_path, mmap_mode='r') + for start in range(0, len(waveform_ids), batch_size): + ids, counts = np.unique( + base[waveform_ids[start : start + batch_size]], return_counts=True + ) + for unit, count in zip(ids, counts): + waveform_counts[int(unit)] += int(count) + waveform_ids._mmap.close() + np.save(temporary / '_phy_curation_windows.npy', np.asarray(windows, dtype=np.int64)) + metadata = source.metadata + write_metadata(temporary, metadata, source.metadata_schema) + # Standard loader stays self-contained; no original raw path is referenced. + params = { + key: source.params[key] + for key in ( + 'sample_rate', + 'n_channels_dat', + 'dtype', + 'offset', + 'hp_filtered', + 'acquisition_id', + 'depth_axis', + 'amplitude_units', + 'depth_units', + 'position_units', + 'waveform_units', + ) + if key in source.params + } + params.update( + dat_path=None, + sample_rate=source.sample_rate, + num_samples=source.num_samples, + valid_intervals=source.valid_intervals.tolist(), + ) + if getattr(source, 'time_base', None) is not None: + params['time_base'] = source.time_base + params.setdefault('dtype', 'int16') + params.setdefault('n_channels_dat', len(source.arrays.get('channel_map.npy', []))) + (temporary / 'params.py').write_text( + ''.join(f'{key} = {value!r}\n' for key, value in params.items()), encoding='utf-8' + ) + summaries = build_summaries( + source, + temporary, + bin_seconds, + max_bytes=max_bytes, + workers=workers, + cancel=cancel, + progress=progress, + ) + final_windows = [] + for start, end in windows: + contributors = [ + record for record in plan if record['start'] < end and record['end'] > start + ] + kinds = sorted({record['kind'] for record in contributors}) + final_windows.append( + { + 'start': start, + 'end': end, + 'segment': 0, + 'block': contributors[0]['block'], + 'kind': kinds[0] if len(kinds) == 1 else 'mixed', + 'kinds': kinds, + 'strata': sorted({record['stratum'] for record in contributors}), + 'exposure_seconds': (end - start) / source.sample_rate, + } + ) + manifest = { + 'format': 'phy_bounded_curation', + 'format_version': 1, + 'source': { + 'identity': source.identity, + 'revision': source.revision, + 'path': str(source.path), + }, + 'sample_rate': source.sample_rate, + 'num_samples': source.num_samples, + 'duration_seconds': source.num_samples / source.sample_rate, + 'valid_intervals': source.valid_intervals.tolist(), + 'num_spikes': source.n_spikes, + 'bounded_num_spikes': n_bounded, + 'unit_ids': source.unit_ids.tolist(), + 'counts': source.counts.tolist(), + 'bounded_counts': [bounded_counts[int(unit)] for unit in source.unit_ids], + 'waveform_counts': [waveform_counts[int(unit)] for unit in source.unit_ids], + 'waveform_coverage': { + 'source_rows': len(source.arrays['_phy_spikes_subset.spikes.npy']) + if source.arrays.keys() >= WAVEFORMS + else 0, + 'retained_rows': sum(waveform_counts.values()), + 'dropped_rows': ( + len(source.arrays['_phy_spikes_subset.spikes.npy']) + if source.arrays.keys() >= WAVEFORMS + else 0 + ) + - sum(waveform_counts.values()), + }, + 'producer_window_plan': producer_provenance, + 'producer_window_estimate': producer_estimate, + 'next_cluster_id': source.next_cluster_id, + 'global_spike_ids_file': '_phy_spike_global_ids.npy', + 'base_assignments_file': '_phy_spike_clusters_base.npy', + 'windows_file': '_phy_curation_windows.npy', + 'windows': final_windows, + 'accepted_window_candidates': plan, + 'omitted_windows': omitted, + 'metadata': metadata, + 'base_metadata': metadata, + 'metadata_schema': source.metadata_schema, + 'metadata_policy': POLICY, + 'metadata_provenance': source.metadata_provenance, + 'summaries': summaries, + **{key: value for key, value in summaries.items() if key.endswith('_file')}, + 'selection': { + 'algorithm': 'shared_windows_v1', + 'window_policy': window_policy, + 'resolved_window_policy': resolved_policy, + 'seed': int(seed), + 'window_seconds': window_seconds, + 'stratum_seconds': stratum_seconds, + }, + 'budgets': { + 'max_spikes': int(max_spikes), + 'max_bytes': int(max_bytes), + 'batch_size': int(batch_size), + 'summary_bytes': int(summary_bytes), + 'estimated_bytes': int( + fixed_bytes + + n_bounded * row_bytes + + _selected_waveform_count(source, windows) * waveform_bytes + + (len(windows) + len(plan) + len(omitted)) * 256 + ), + }, + 'capabilities': { + 'merge': True, + 'restore_parents': True, + 'label': True, + 'split': False, + 'full_attributes': sorted(scalar_attributes(source)), + 'predicate_split_attributes': ( + ['amplitudes.npy'] if 'amplitude' in scalar_attributes(source) else [] + ), + 'stored_waveforms': bool(sum(waveform_counts.values())), + 'raw_traces': False, + 'normalized_correlograms': False, + }, + 'source_array_inventory': { + name: { + 'role': 'per_spike' + if name in PER_SPIKE + else 'stored_waveform' + if name in WAVEFORMS + else 'waveform_sidecar' + if name in waveform_sidecars + else 'static' + if name in STATIC + else 'excluded_window_sidecar', + 'shape': list(array.shape), + 'dtype': str(array.dtype), + 'bytes': int(array.nbytes), + } + for name, array in source.arrays.items() + }, + 'excluded_files': sorted( + p.name + for p in source.path.iterdir() + if p.name not in (PER_SPIKE | STATIC | WAVEFORMS | waveform_sidecars) + and p.name + not in ( + 'params.py', + '_phy_cluster_metadata.json', + SCHEMA_FILE, + 'curation.json', + 'curation_review.json', + ) + and (not p.name.startswith('cluster_') or p.stem == 'cluster_info') + ), + } + if getattr(source, 'time_base', None) is not None: + manifest['time_base'] = source.time_base + manifest['retired_units'] = source.retired_units + manifest['proposition_documents'] = {} + for document in producer_documents: + # Root review is a convenience copy; its inherited baseline is immutable. + name = ( + '_phy_curation_review_base.json' + if document.name == 'curation_review.json' + else document.name + ) + _copy_files( + ((document, temporary / name),), + cancel=cancel, + progress=progress, + stage=f'copying producer document {document.name}', + ) + manifest['proposition_documents'][document.name] = { + 'filename': name, + 'sha256': producer_hashes[document.name], + } + if hash_file(temporary / name) != producer_hashes[document.name]: + raise ValueError('Producer proposition document changed during preparation.') + if name != document.name: + _copy_files( + ((document, temporary / document.name),), + cancel=cancel, + progress=progress, + stage=f'copying producer document {document.name}', + ) + bound_paths = [ + *temporary.glob('*.npy'), + temporary / 'params.py', + temporary / '_phy_cluster_metadata.json', + temporary / SCHEMA_FILE, + *(temporary / table['filename'] for table in source.metadata_schema['tables']), + *(temporary / item['filename'] for item in manifest['proposition_documents'].values()), + ] + manifest['bounded_files'] = {p.name: hash_file(p) for p in sorted(bound_paths)} + manifest['preparation_identity'] = hash_json(manifest) + (temporary / '_phy_curation_manifest.json').write_text( + json.dumps(manifest, indent=2, sort_keys=True) + '\n', encoding='utf-8' + ) + actual_bytes = sum(p.stat().st_size for p in temporary.iterdir()) + if actual_bytes > max_bytes: + raise ValueError(f'Final output exceeds max_bytes: {actual_bytes} bytes.') + for array in (global_ids, base, *destinations.values()): + close_array(array) + for path in temporary.iterdir(): + if path.is_file(): + # Windows _commit (os.fsync) requires a writable descriptor. + with path.open('r+b') as stream: + os.fsync(stream.fileno()) + _fsync_directory(temporary) + if output_dir.exists(): + raise ValueError(f'Output already exists: {output_dir}.') + from .curation import BoundedSession + + checked = BoundedSession(temporary) + checked.close() + check_cancel(cancel) + publish_directory(temporary, output_dir) + _fsync_directory(output_dir.parent) + except BaseException: + for array in (global_ids, base, *destinations.values()): + close_array(array) + shutil.rmtree(temporary, ignore_errors=True) + raise + return output_dir + + +def _fsync_directory(path): + if os.name != 'nt': + descriptor = os.open(path, os.O_RDONLY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + + +def _copy_files(files, cancel=None, progress=None, stage='copying files'): + """Copy files in bounded chunks, reporting byte progress and checking cancel.""" + files = list(files) + total = sum(source.stat().st_size for source, _ in files) + copied = 0 + for source, destination in files: + with source.open('rb') as src, destination.open('wb') as dst: + while block := src.read(1024 * 1024): + check_cancel(cancel) + dst.write(block) + copied += len(block) + if progress is not None: + progress(stage, copied, total) + if progress is not None and not total: + progress(stage, 0, 0) + + +def _copy_waveforms(source, output, global_ids, row_bounds, cancel=None, progress=None): + """Intersect sparse row IDs with selected spans in bounded working memory.""" + upstream_ids = source.arrays['_phy_spikes_subset.spikes.npy'] + spans = [ + (int(np.searchsorted(upstream_ids, first)), int(np.searchsorted(upstream_ids, stop))) + for first, stop in row_bounds + ] + n = sum(stop - first for first, stop in spans) + targets = {} + waveform_names = WAVEFORMS | (source.arrays.keys() & {'_phy_spikes_subset.sample_index.npy'}) + try: + for name in waveform_names: + original = source.arrays[name] + targets[name] = np.lib.format.open_memmap( + output / name, mode='w+', dtype=original.dtype, shape=(n, *original.shape[1:]) + ) + cursor = 0 + for first, stop in spans: + for start in range(first, stop, source.batch_size): + check_cancel(cancel) + end = min(start + source.batch_size, stop) + length = end - start + targets['_phy_spikes_subset.spikes.npy'][cursor : cursor + length] = ( + np.searchsorted(global_ids, upstream_ids[start:end]) + ) + for name in waveform_names - {'_phy_spikes_subset.spikes.npy'}: + targets[name][cursor : cursor + length] = source.arrays[name][start:end] + cursor += length + if progress is not None: + progress('retaining waveform spikes', cursor, n) + for array in targets.values(): + array.flush() + finally: + for array in targets.values(): + close_array(array) diff --git a/phy/apps/large_recording/progress.py b/phy/apps/large_recording/progress.py new file mode 100644 index 000000000..57d060e00 --- /dev/null +++ b/phy/apps/large_recording/progress.py @@ -0,0 +1,146 @@ +"""Throttled progress reporting for bounded-recording command-line work.""" + +import signal +import sys +import threading +import time +from concurrent.futures import CancelledError +from numbers import Integral + + +def _duration(seconds): + seconds = max(0, int(seconds)) + hours, remainder = divmod(seconds, 3600) + minutes, seconds = divmod(remainder, 60) + if hours: + return f'{hours:d}:{minutes:02d}:{seconds:02d}' + if minutes: + return f'{minutes:d}:{seconds:02d}' + return f'{seconds:d}s' + + +class ProgressReporter: + """Render throttled stage progress to stderr and expose cooperative cancel.""" + + def __init__(self, stream=None, interval=2.0, clock=time.monotonic): + if interval < 0: + raise ValueError('Progress reporting interval must be nonnegative.') + self.stream = stream if stream is not None else sys.stderr + self.interval = float(interval) + self.clock = clock + self._lock = threading.Lock() + self._cancelled = threading.Event() + self._stage = None + self._stage_started = None + self._stage_initial_done = 0 + self._last_report = None + self._last_values = None + self._previous_sigint = None + + def __enter__(self): + try: + self._previous_sigint = signal.getsignal(signal.SIGINT) + signal.signal(signal.SIGINT, self._handle_sigint) + except ValueError: + # Signal handlers can only be installed by the main thread. + self._previous_sigint = None + return self + + def __exit__(self, exc_type, exc_value, traceback): + if self._previous_sigint is not None: + signal.signal(signal.SIGINT, self._previous_sigint) + self._previous_sigint = None + + def _handle_sigint(self, signum, frame): + self.cancel() + raise CancelledError('Operation cancelled.') + + def cancel(self): + """Request cancellation; the next worker callback raises CancelledError.""" + self._cancelled.set() + + def check_cancelled(self): + if self._cancelled.is_set(): + raise CancelledError('Operation cancelled.') + + @staticmethod + def _validate(stage, done, total): + if not isinstance(stage, str) or not stage.strip(): + raise ValueError('Progress stage must be a nonempty string.') + for name, value in (('done', done), ('total', total)): + if value is None and name == 'total': + continue + if isinstance(value, bool) or not isinstance(value, Integral): + raise ValueError(f'Progress {name} must be a nonnegative integer or None.') + if value < 0: + raise ValueError(f'Progress {name} must be nonnegative.') + + @staticmethod + def _unit(stage): + name = stage.lower() + if any(word in name for word in ('finalizing', 'attaching')): + return None + if 'window' in name: + return 'windows' + if 'row' in name: + return 'rows' + if any(word in name for word in ('byte', 'hash', 'copy', 'authenticating')): + return 'bytes' + return 'spikes' + + @staticmethod + def _number(value): + return f'{int(value):,}' + + @staticmethod + def _rate(value): + return f'{value:,.0f}' if value.is_integer() else f'{value:,.1f}' + + def _message(self, stage, done, total, now): + unit = self._unit(stage) + if unit is None: + return stage + elapsed = max(now - self._stage_started, 0.0) + processed = max(done - self._stage_initial_done, 0) + rate = processed / elapsed if elapsed > 0 else 0.0 + if total: + percent = min(100.0, 100.0 * done / total) + message = ( + f'{stage}: {self._number(done)} / {self._number(total)} {unit} ({percent:.1f}%)' + ) + remaining = max(total - done, 0) + eta = ( + _duration(remaining / rate) + if rate > 0 + else ('0s' if not remaining else 'calculating') + ) + message += f', elapsed {_duration(elapsed)}, {self._rate(rate)} {unit}/s, ETA {eta}' + else: + message = f'{stage}: {self._number(done)} {unit}, elapsed {_duration(elapsed)}' + if rate > 0: + message += f', {self._rate(rate)} {unit}/s' + return message + + def __call__(self, stage, done, total): + self._validate(stage, done, total) + with self._lock: + self.check_cancelled() + now = self.clock() + stage_changed = stage != self._stage + if stage_changed: + self._stage = stage + self._stage_started = now + self._stage_initial_done = done + self._last_report = None + complete = total is not None and total > 0 and done >= total + should_report = ( + stage_changed + or complete + or self._last_report is None + or now - self._last_report >= self.interval + ) + self._last_values = (stage, done, total) + if should_report: + self.stream.write(self._message(stage, done, total, now) + '\n') + self.stream.flush() + self._last_report = now diff --git a/phy/apps/large_recording/range_build.py b/phy/apps/large_recording/range_build.py new file mode 100644 index 000000000..1d7a54a4d --- /dev/null +++ b/phy/apps/large_recording/range_build.py @@ -0,0 +1,577 @@ +"""Bounded offline sorting and authenticated block-tree construction.""" + +import json +import math +import os +import shutil +import tempfile +from dataclasses import dataclass +from pathlib import Path +from threading import Lock + +import numpy as np + +from .curation import _fsync_directory +from .range_files import PAGE_BYTES, authenticate_file +from .range_intervals import RangeUnavailableError +from .range_math import add_stats, node_dtype, row_stats +from .source import hash_json, publish_directory +from .streaming import bounded_map, worker_count +from .summary_store import ( + _ANY_REFERENCE, + SummaryStore, + SummaryStorePublishedError, + _atomic_json, + summary_store_reference, +) + +FORMAT = 'phy_amplitude_range_index' +VERSION = 1 +DEFAULT_DIRECTORY = 'amplitude-index' + + +def layout(engine): + inventory = engine.manifest['source_array_inventory'] + if 'amplitude' not in engine.fields: + raise RangeUnavailableError('Scalar amplitudes are required for range indexing.') + names = [('amplitude', np.dtype(inventory['amplitudes.npy']['dtype']))] + if names[0][1].kind not in 'fiu' or names[0][1].itemsize > 8: + raise RangeUnavailableError('This amplitude dtype uses the verified row fallback.') + if 'depth' in engine.fields: + name = 'spike_depths.npy' if 'spike_depths.npy' in inventory else 'spike_positions.npy' + dtype = np.dtype(inventory[name]['dtype']) + if dtype.kind not in 'fiu' or dtype.itemsize > 8: + raise RangeUnavailableError('This depth dtype uses the verified row fallback.') + names.append(('depth', dtype)) + payload = np.dtype(names) + directory = np.dtype( + [ + ('start', ' max_bytes: + raise ValueError( + f'Combined store estimate {estimate:,} exceeds max_bytes; ' + 'increase the store budget or use build-summary-store --rows-only.' + ) + + +class _SortedRuns: + """Stable bounded runs and vectorized pairwise merging, never row-wise heap merge.""" + + def __init__(self, directory, dtype, memory_bytes, cancel): + self.directory, self.dtype = directory, dtype + # Reserve stable-sort permutations/workspace even for one-byte scalars. + self.limit = max( + dtype.itemsize, memory_bytes // (4 * dtype.itemsize + 16) * dtype.itemsize + ) + self.parts, self.bytes, self.runs = [], 0, [] + self.cancel = cancel + self.merge_rows = max(1, memory_bytes // (8 * dtype.itemsize + 96)) + + def add(self, records): + rows = max(1, self.limit // self.dtype.itemsize) + for first in range(0, len(records), rows): + part = records[first : first + rows].copy() + if self.parts and self.bytes + part.nbytes > self.limit: + self._flush() + self.parts.append(part) + self.bytes += part.nbytes + if self.bytes >= self.limit: + self._flush() + + def _flush(self): + from .live_summaries import _check_cancel + + _check_cancel(self.cancel) + values = np.concatenate(self.parts) + values = values[np.argsort(values['amplitude'], kind='stable')] + handle, filename = tempfile.mkstemp(prefix='sorted-', dir=self.directory) + with os.fdopen(handle, 'wb') as stream: + stream.write(values.tobytes()) + self.runs.append(Path(filename)) + self.parts.clear() + self.bytes = 0 + + def _merge(self, left_path, right_path): + from .live_summaries import _check_cancel + + handle, filename = tempfile.mkstemp(prefix='merged-', dir=self.directory) + with ( + os.fdopen(handle, 'wb') as output, + left_path.open('rb') as left, + right_path.open('rb') as right, + ): + a = b = np.empty(0, dtype=self.dtype) + while True: + _check_cancel(self.cancel) + if not len(a): + a = np.frombuffer( + left.read(self.merge_rows * self.dtype.itemsize), dtype=self.dtype + ) + if not len(b): + b = np.frombuffer( + right.read(self.merge_rows * self.dtype.itemsize), dtype=self.dtype + ) + if not len(a) and not len(b): + break + if not len(a): + output.write(b.tobytes()) + b = b[:0] + continue + if not len(b): + output.write(a.tobytes()) + a = a[:0] + continue + bound = min(a['amplitude'][-1], b['amplitude'][-1]) + na = int(np.searchsorted(a['amplitude'], bound, side='right')) + # If the left chunk ends at the boundary, future left rows + # may have the same key. Keep right ties until those are read. + side = 'left' if bound == a['amplitude'][-1] else 'right' + nb = int(np.searchsorted(b['amplitude'], bound, side=side)) + aa, bb = a[:na], b[:nb] + if not na: + result = bb + elif not nb: + result = aa + else: + result = np.empty(na + nb, dtype=self.dtype) + positions_a = np.arange(na) + np.searchsorted( + bb['amplitude'], aa['amplitude'], side='left' + ) + positions_b = np.arange(nb) + np.searchsorted( + aa['amplitude'], bb['amplitude'], side='right' + ) + result[positions_a] = aa + result[positions_b] = bb + output.write(result.tobytes()) + a, b = a[na:], b[nb:] + left_path.unlink() + right_path.unlink() + return Path(filename) + + def finish(self): + if not self.runs: + values = np.concatenate(self.parts) if self.parts else np.empty(0, dtype=self.dtype) + self.parts.clear() + return values[np.argsort(values['amplitude'], kind='stable')], None + if self.parts: + self._flush() + while len(self.runs) > 1: + output = [] + for i in range(0, len(self.runs), 2): + output.append( + self._merge(self.runs[i], self.runs[i + 1]) + if i + 1 < len(self.runs) + else self.runs[i] + ) + self.runs = output + path = self.runs.pop() + return None, path + + +def _align(stream, width=64): + count = (-stream.tell()) % width + if count: + stream.write(b'\0' * count) + + +def _write_segment( + sorter, + total, + nonfinite, + values_file, + meta_file, + fields, + block_rows, + memory_bytes, + directory_dtype, + node, + cancel, +): + from .live_summaries import _check_cancel + + records, run = sorter.finish() + n = len(records) if records is not None else run.stat().st_size // sorter.dtype.itemsize + entry = np.zeros(1, dtype=directory_dtype) + entry['start'], entry['finite'], entry['total'] = values_file.tell(), n, total + if 'depth' in fields: + for kind in ('sum', 'count', 'abs', 'error'): + entry['nf_depth_' + kind] = nonfinite['depth_' + kind] + if not n: + return entry + blocks = (n + block_rows - 1) // block_rows + leaves = 1 << (blocks - 1).bit_length() + entry['leaves'] = leaves + _align(meta_file) + entry['keys'] = meta_file.tell() + handle, tree_name = tempfile.mkstemp(prefix='aggregate-', dir=sorter.directory) + tree_path = Path(tree_name) + stream = None + try: + with os.fdopen(handle, 'w+b') as tree: + stream = None if records is not None else run.open('rb') + tree.truncate(2 * leaves * node.itemsize) + tree.seek(leaves * node.itemsize) + batch_blocks = max( + 1, + min( + 8192, memory_bytes // (block_rows * (sorter.dtype.itemsize + 32 * len(fields))) + ), + ) + first, last = None, None + for start in range(0, n, batch_blocks * block_rows): + _check_cancel(cancel) + stop = min(n, start + batch_blocks * block_rows) + chunk = ( + records[start:stop] + if records is not None + else np.frombuffer( + stream.read((stop - start) * sorter.dtype.itemsize), dtype=sorter.dtype + ) + ) + if first is None: + first = chunk['amplitude'][0] + last = chunk['amplitude'][-1] + values_file.write(chunk.tobytes()) + meta_file.write(chunk['amplitude'][::block_rows].tobytes()) + full = len(chunk) // block_rows * block_rows + if full: + stats = row_stats(chunk[:full].reshape(-1, block_rows), fields, node) + tree.write(stats.tobytes()) + if full < len(chunk): + tree.write(row_stats(chunk[full:], fields, node).tobytes()) + entry['minimum'], entry['maximum'] = first, last + # Unused leaves are known zeros; write in bounded chunks, including Windows. + remaining = (leaves - blocks) * node.itemsize + zero = bytes(min(1048576, max(1, memory_bytes // 8), remaining)) + while remaining: + _check_cancel(cancel) + part = min(remaining, len(zero)) + tree.write(zero[:part]) + remaining -= part + tree.flush() + width = leaves // 2 + while width: + node_batch = max(1, min(8192, memory_bytes // (8 * node.itemsize))) + for first_node in range(width, 2 * width, node_batch): + _check_cancel(cancel) + count = min(node_batch, 2 * width - first_node) + tree.seek(2 * first_node * node.itemsize) + children = np.frombuffer(tree.read(2 * count * node.itemsize), dtype=node) + parents = add_stats(children[::2], children[1::2], fields) + tree.seek(first_node * node.itemsize) + tree.write(parents.tobytes()) + tree.flush() + width //= 2 + _align(meta_file) + entry['tree'] = meta_file.tell() + tree.seek(0) + while raw := tree.read(1048576): + _check_cancel(cancel) + meta_file.write(raw) + finally: + if stream is not None: + stream.close() + if run is not None: + run.unlink(missing_ok=True) + tree_path.unlink(missing_ok=True) + return entry + + +def build_amplitude_index( + package_path, + output_dir, + block_rows=128, + max_bytes=68719476736, + memory_bytes=67108864, + units=None, + cancel=None, + progress=None, + before_publish=None, + attach=True, + expected_reference=_ANY_REFERENCE, + workers=1, +): + """Prepare an optional sorted range accelerator from a verified row snapshot.""" + from .live_summaries import LiveSummaryEngine, _check_cancel + + worker_count(workers) + # Keep at least 1 MiB per active sorter within the one global allowance. + workers = min(workers, max(1, memory_bytes // 1048576)) + worker_memory = memory_bytes // (workers + 1) + package, output = Path(package_path).resolve(), Path(output_dir).resolve() + if output.exists(): + raise ValueError(f'Amplitude index already exists: {output}.') + if output == package or package in output.parents: + raise ValueError('Amplitude index must be outside the bounded package.') + if memory_bytes < 1048576 or max_bytes <= 0: + raise ValueError('Index memory must be at least 1 MiB and disk budget must be positive.') + staged = None + initial_reference = summary_store_reference(package, allow_invalid=True) + if expected_reference is not _ANY_REFERENCE and initial_reference != expected_reference: + raise ValueError('The attached summary store changed before amplitude-index preparation.') + with LiveSummaryEngine(package) as engine, SummaryStore(engine) as store: + if output == engine.source_dir.resolve() or engine.source_dir.resolve() in output.parents: + raise ValueError('Amplitude index must be outside the original source.') + estimate = estimate_range_index(engine, block_rows, units, workers=workers) + row_bytes = sum((store.path / name).stat().st_size for name in ('data.bin', 'index.json')) + if row_bytes + estimate.final_bytes > max_bytes: + raise ValueError('Combined row store and amplitude index exceed max_bytes.') + output.parent.mkdir(parents=True, exist_ok=True) + if shutil.disk_usage(output.parent).free < estimate.peak_extra_bytes: + raise OSError('Insufficient free space for amplitude index and sorting scratch.') + payload, directory_dtype, node = layout(engine) + counts = dict(zip(engine.manifest['unit_ids'], engine.manifest['counts'])) + selected = set(counts if units is None else units) + staged = Path(tempfile.mkdtemp(prefix=f'.{output.name}.building-', dir=output.parent)) + scratch = staged / 'sorting' + scratch.mkdir() + completed = 0 + total_rows = sum(int(counts[u]) for u in selected) + try: + with ( + (staged / 'values.bin').open('wb') as values_file, + (staged / 'nodes.bin').open('wb') as meta_file, + (staged / 'segments.bin').open('w+b') as directories, + ): + directories.truncate(len(counts) * engine.bins * directory_dtype.itemsize) + progress_lock = Lock() + + def advance(rows): + nonlocal completed + with progress_lock: + completed += rows + if progress: + progress('sorting amplitude ranges', completed, total_rows) + + def build_unit(item): + ordinal, unit = item + unit_dir = scratch / str(ordinal) + unit_dir.mkdir() + # Each worker owns its authenticated stream and output files. + with ( + SummaryStore(engine, path=store.path) as unit_store, + (unit_dir / 'values.bin').open('wb') as values_file, + (unit_dir / 'nodes.bin').open('wb') as meta_file, + (unit_dir / 'segments.bin').open('w+b') as directories, + ): + if unit_store.index != store.index: + raise ValueError('Summary store catalog changed during index build.') + directories.truncate(engine.bins * directory_dtype.itemsize) + current, sorter, total = None, None, 0 + nonfinite = np.zeros(1, dtype=node) + + def finish(current, sorter, total, nonfinite, ordinal): + if current is None: + return + entry = _write_segment( + sorter, + total, + nonfinite[0], + values_file, + meta_file, + engine.fields, + block_rows, + worker_memory, + directory_dtype, + node, + cancel, + ) + directories.seek(current * directory_dtype.itemsize) + directories.write(entry.tobytes()) + + batch_rows = max( + 1, min(500000, worker_memory // (8 * unit_store.dtype.itemsize + 32)) + ) + for rows in unit_store.batches(unit, batch_rows, cancel): + bin_ids = rows['bin'] + if np.any(bin_ids >= engine.bins) or np.any( + bin_ids[1:] < bin_ids[:-1] + ): + raise RangeUnavailableError( + 'Row snapshot bins are invalid or unordered.' + ) + boundaries = np.r_[0, np.flatnonzero(np.diff(bin_ids)) + 1, len(rows)] + for first, last in zip(boundaries[:-1], boundaries[1:]): + _check_cancel(cancel) + bin_id = int(bin_ids[first]) + if current is not None and bin_id < current: + raise RangeUnavailableError('Row snapshot bin order changed.') + if bin_id != current: + finish(current, sorter, total, nonfinite, ordinal) + current, total = bin_id, 0 + sorter = _SortedRuns(unit_dir, payload, worker_memory, cancel) + nonfinite = np.zeros(1, dtype=node) + chunk = rows[first:last] + finite = np.isfinite(chunk['amplitude']) + total += len(chunk) + if 'depth' in engine.fields and np.any(~finite): + packed = np.empty(np.count_nonzero(~finite), dtype=payload) + for field in engine.fields: + packed[field] = chunk[field][~finite] + nonfinite = add_stats( + nonfinite, + row_stats(packed, engine.fields, node), + engine.fields, + ) + packed = np.empty(np.count_nonzero(finite), dtype=payload) + for field in engine.fields: + packed[field] = chunk[field][finite] + sorter.add(packed) + advance(len(rows)) + finish(current, sorter, total, nonfinite, ordinal) + return ordinal, unit_dir + + items = ( + (i, u) for i, u in enumerate(engine.manifest['unit_ids']) if u in selected + ) + for ordinal, unit_dir in bounded_map(build_unit, items, workers): + _check_cancel(cancel) + _align(meta_file) + values_offset, meta_offset = values_file.tell(), meta_file.tell() + for filename, target in ( + ('values.bin', values_file), + ('nodes.bin', meta_file), + ): + with (unit_dir / filename).open('rb') as chunk_file: + while raw := chunk_file.read(min(1048576, worker_memory // 4)): + _check_cancel(cancel) + target.write(raw) + # Rebase file offsets in bounded chunks. Empty bins remain zero. + with (unit_dir / 'segments.bin').open('rb') as chunk_file: + directories.seek(ordinal * engine.bins * directory_dtype.itemsize) + chunk_rows = max(1, worker_memory // (8 * directory_dtype.itemsize)) + while raw := chunk_file.read(chunk_rows * directory_dtype.itemsize): + entries = np.frombuffer(raw, dtype=directory_dtype).copy() + present = entries['total'] > 0 + finite = entries['finite'] > 0 + entries['start'][present] += values_offset + entries['keys'][finite] += meta_offset + entries['tree'][finite] += meta_offset + directories.write(entries.tobytes()) + shutil.rmtree(unit_dir) + for stream_ in (values_file, meta_file, directories): + stream_.flush() + os.fsync(stream_.fileno()) + scratch.rmdir() + auth_sizes = { + name: (staged / f'{name}.bin').stat().st_size + for name in ('values', 'nodes', 'segments') + } + auth_done = dict.fromkeys(auth_sizes, 0) + + def authenticate(name): + def advance_auth(stage, done, total): + if total and progress: + with progress_lock: + auth_done[name] = done + progress( + 'authenticating range index', + sum(auth_done.values()), + sum(auth_sizes.values()), + ) + + return name, authenticate_file(staged / f'{name}.bin', cancel, advance_auth) + + files = dict(bounded_map(authenticate, auth_sizes, workers)) + catalog = { + 'format': FORMAT, + 'version': VERSION, + 'arithmetic_version': 1, + 'binding_sha256': engine.binding_digest, + 'parent_sha256': hash_json(store.index), + 'parent_path': str(store.path), + 'block_rows': block_rows, + 'indexed_units': sorted(selected), + 'files': files, + } + _atomic_json(staged / 'range.json', catalog) + actual = sum(p.stat().st_size for p in staged.iterdir()) + if actual + row_bytes > max_bytes: + raise ValueError('Combined index exceeds max_bytes after construction.') + _check_cancel(cancel) + if before_publish: + before_publish() + publish_directory(staged, output) + staged = None + try: + _fsync_directory(output.parent) + if attach: + from .range_index import attach_amplitude_index + + attach_amplitude_index( + package, + output, + expected_reference=initial_reference, + check_cancel=lambda: _check_cancel(cancel), + ) + except (ValueError, OSError) as error: + raise SummaryStorePublishedError(output, str(error)) from error + return output + finally: + if staged is not None: + shutil.rmtree(staged) diff --git a/phy/apps/large_recording/range_files.py b/phy/apps/large_recording/range_files.py new file mode 100644 index 000000000..0d758b615 --- /dev/null +++ b/phy/apps/large_recording/range_files.py @@ -0,0 +1,257 @@ +"""Bounded, selectively verified pages anchored by a published Merkle root.""" + +import hashlib +import os +from collections import OrderedDict +from pathlib import Path + +import numpy as np + +from .summary_store import StoreIntegrityError + +PAGE_BYTES = 4096 +_DIGEST_BYTES = 32 +_EMPTY = hashlib.sha256(b'P').digest() + + +def _signature(stat): + return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) + + +def tree_leaves(size): + pages = max(1, (int(size) + PAGE_BYTES - 1) // PAGE_BYTES) + return 1 << (pages - 1).bit_length() + + +def authenticate_file(path, cancel=None, progress=None): + """Build a packed hash tree without a file-sized mapping or heap allocation.""" + from .live_summaries import _check_cancel + + path = Path(path) + size = path.stat().st_size + leaves = tree_leaves(size) + hashes = path.with_suffix(path.suffix + '.hashes') + with path.open('rb') as source, hashes.open('w+b') as target: + target.truncate(2 * leaves * _DIGEST_BYTES) + target.seek(leaves * _DIGEST_BYTES) + done = 0 + for index in range(leaves): + if index % 256 == 0: + _check_cancel(cancel) + raw = source.read(PAGE_BYTES) if done < size else b'' + done += len(raw) + target.write(hashlib.sha256(b'P' + raw).digest() if raw else _EMPTY) + if progress and index % 4096 == 0 and done < size: + progress('authenticating range index', min(done, size), size) + target.flush() + if progress: + progress('finalizing range authentication', 0, 0) + width = leaves // 2 + while width: + for start in range(width, 2 * width, 8192): + _check_cancel(cancel) + stop = min(start + 8192, 2 * width) + target.seek(2 * start * _DIGEST_BYTES) + children = target.read((stop - start) * 2 * _DIGEST_BYTES) + parents = b''.join( + hashlib.sha256(b'N' + children[i : i + 64]).digest() + for i in range(0, len(children), 64) + ) + target.seek(start * _DIGEST_BYTES) + target.write(parents) + target.flush() + width //= 2 + target.seek(_DIGEST_BYTES) + root = target.read(_DIGEST_BYTES).hex() + target.flush() + os.fsync(target.fileno()) + if progress: + progress('authenticating range index', size, size) + return {'bytes': size, 'root': root} + + +class PageCache: + """One exact byte budget shared by all files of a range reader.""" + + def __init__(self, max_bytes): + self.max_bytes = int(max_bytes) + self.size = 0 + self.pages = OrderedDict() + + def get(self, key): + value = self.pages.get(key) + if value is not None: + self.pages.move_to_end(key) + return value + + def put(self, key, value): + if len(value) > self.max_bytes: + return + if key in self.pages: + self.size -= len(self.pages.pop(key)) + while self.pages and self.size + len(value) > self.max_bytes: + _, previous = self.pages.popitem(last=False) + self.size -= len(previous) + self.pages[key] = value + self.size += len(value) + + def clear(self): + self.pages.clear() + self.size = 0 + + +class VerifiedFile: + """Verify only consumed pages; cache immutable bytes and trusted tree nodes.""" + + def __init__(self, path, descriptor, cache, cancel=None): + self.path = Path(path) + self.size = int(descriptor['bytes']) + self.root = bytes.fromhex(descriptor['root']) + if self.size < 0 or len(self.root) != _DIGEST_BYTES: + raise StoreIntegrityError('Invalid range file descriptor.') + self.leaves = tree_leaves(self.size) + self.cache, self.cancel = cache, cancel + self.handles = [] + self.nodes = OrderedDict({1: self.root}) + self.bytes_read = self.pages_verified = 0 + self.hash_bytes_read = 0 + try: + for p, expected in ( + (self.path, self.size), + (self.path.with_suffix(self.path.suffix + '.hashes'), 2 * self.leaves * 32), + ): + before = _signature(p.stat()) + handle = p.open('rb') + self.handles.append(handle) + after = _signature(os.fstat(handle.fileno())) + if before[:-1] != after[:-1] or after[2] != expected: + raise StoreIntegrityError('Range file size or identity changed.') + if len(self.handles) == 1: + self.path_signature, self.fd_signature = before, after + else: + self.hash_path_signature, self.hash_fd_signature = before, after + self.data, self.hashes = self.handles + if self._node(1) != self.root: + raise StoreIntegrityError('Range root checksum mismatch.') + except BaseException: + self.close() + raise + + def close(self): + for handle in self.handles: + handle.close() + self.handles.clear() + + def unchanged(self): + if ( + _signature(os.fstat(self.data.fileno())) != self.fd_signature + or _signature(self.path.stat()) != self.path_signature + or _signature(os.fstat(self.hashes.fileno())) != self.hash_fd_signature + or _signature(self.path.with_suffix(self.path.suffix + '.hashes').stat()) + != self.hash_path_signature + ): + raise StoreIntegrityError('Range index changed during computation.') + + def _node(self, index): + self.hashes.seek(index * 32) + raw = self.hashes.read(32) + self.hash_bytes_read += len(raw) + if len(raw) != 32: + raise StoreIntegrityError('Truncated range checksum tree.') + return raw + + def _trust(self, index, digest): + self.nodes[index] = digest + self.nodes.move_to_end(index) + while len(self.nodes) > 16384: + self.nodes.popitem(last=False) + + def _page(self, index): + from .live_summaries import _check_cancel + + _check_cancel(self.cancel) + key = (self.root, self.size, index) + cached = self.cache.get(key) + if cached is not None: + return cached + self.data.seek(index * PAGE_BYTES) + raw = self.data.read(min(PAGE_BYTES, self.size - index * PAGE_BYTES)) + if not raw or len(raw) != min(PAGE_BYTES, self.size - index * PAGE_BYTES): + raise StoreIntegrityError('Truncated range data page.') + self.bytes_read += len(raw) + node = self.leaves + index + digest = hashlib.sha256(b'P' + raw).digest() + pending = [(node, digest)] + while node != 1 and node not in self.nodes: + sibling = node ^ 1 + other = self._node(sibling) + pending.append((sibling, other)) + digest = hashlib.sha256( + b'N' + (other + digest if node & 1 else digest + other) + ).digest() + node //= 2 + pending.append((node, digest)) + expected = self.root if node == 1 else self.nodes[node] + if digest != expected: + raise StoreIntegrityError('Range page checksum mismatch.') + for index_, value in pending: + self._trust(index_, value) + self.cache.put(key, raw) + self.pages_verified += 1 + return raw + + def read(self, offset, size): + offset, size = int(offset), int(size) + if offset < 0 or size < 0 or offset + size > self.size: + raise StoreIntegrityError('Range read exceeds the published file.') + if not size: + return b'' + chunks = [] + while size: + page, within = divmod(offset, PAGE_BYTES) + raw = self._page(page) + count = min(size, len(raw) - within) + chunks.append(raw[within : within + count]) + offset += count + size -= count + return b''.join(chunks) + + def gather(self, offsets, dtype): + """Read aligned scalar/record locations, grouping requests by verified page.""" + dtype = np.dtype(dtype) + offsets = np.asarray(offsets, dtype=np.int64) + if np.any(offsets < 0) or np.any(offsets > self.size - dtype.itemsize): + raise StoreIntegrityError('Range gather exceeds the published file.') + output = np.empty(len(offsets), dtype=dtype) + order = np.argsort(offsets // PAGE_BYTES, kind='stable') + page_ids = offsets[order] // PAGE_BYTES + boundaries = np.r_[0, np.flatnonzero(np.diff(page_ids)) + 1, len(order)] + for first, stop in zip(boundaries[:-1], boundaries[1:]): + if first == stop: + continue + selected = order[first:stop] + page = page_ids[first] + positions = offsets[selected] % PAGE_BYTES + raw = self._page(int(page)) + if len(selected) == 1 and int(positions[0]) + dtype.itemsize <= len(raw): + output[selected[0]] = np.frombuffer( + raw, dtype=dtype, count=1, offset=int(positions[0]) + )[0] + elif np.any(positions + dtype.itemsize > len(raw)): + for item in selected: + output[item] = np.frombuffer( + self.read(offsets[item], dtype.itemsize), dtype=dtype + )[0] + else: + # Records and scalar keys are aligned by the builder. + if np.any(positions % dtype.itemsize): + for item in selected: + output[item] = np.frombuffer( + self.read(offsets[item], dtype.itemsize), dtype=dtype + )[0] + else: + usable = len(raw) // dtype.itemsize * dtype.itemsize + output[selected] = np.frombuffer(raw[:usable], dtype=dtype)[ + positions // dtype.itemsize + ] + return output diff --git a/phy/apps/large_recording/range_index.py b/phy/apps/large_recording/range_index.py new file mode 100644 index 000000000..012853831 --- /dev/null +++ b/phy/apps/large_recording/range_index.py @@ -0,0 +1,425 @@ +"""Sublinear amplitude interval queries over an authenticated prepared snapshot.""" + +import json +import math +from collections import OrderedDict +from pathlib import Path + +import numpy as np + +from .curation import evaluate_predicate +from .range_build import FORMAT, VERSION, layout +from .range_files import PageCache, VerifiedFile +from .range_intervals import IntervalProgram, RangeUnavailableError +from .range_math import add_stats, row_stats, validate_sums +from .source import hash_json +from .summary_store import ( + _ANY_REFERENCE, + StoreIntegrityError, + _atomic_json, + _attachment_lock, + summary_store_reference, +) + + +class AmplitudeRangeIndex: + """Worker-owned readers; all consumed pages are verified against pinned roots.""" + + def __init__(self, engine, path=None): + self.engine = engine + self.files = {} + self.cache = PageCache(engine.max_bytes) + self.endpoint_bytes = 0 + reference = json.loads(summary_store_reference(engine.path)) + index_reference = reference.get('amplitude_index', {}) + self.path = Path(path if path is not None else index_reference['path']) + if not self.path.is_absolute(): + self.path = Path(reference['path']) / self.path + catalog_path = self.path / 'range.json' + if catalog_path.stat().st_size > 2097152: + raise StoreIntegrityError('Range catalog exceeds limit.') + self.catalog = json.loads(catalog_path.read_text()) + self.catalog_sha256 = hash_json(self.catalog) + if path is None and self.catalog_sha256 != index_reference.get('catalog_sha256'): + raise StoreIntegrityError('Range catalog checksum mismatch.') + if ( + self.catalog['format'] != FORMAT + or self.catalog['version'] != VERSION + or self.catalog['arithmetic_version'] != 1 + or self.catalog['binding_sha256'] != engine.binding_digest + or self.catalog['parent_sha256'] != reference['index_sha256'] + ): + raise StoreIntegrityError('Range index snapshot binding mismatch.') + self.payload, self.directory_dtype, self.node = layout(engine) + self.fields = engine.fields + self.block_rows = self.catalog['block_rows'] + if type(self.block_rows) is not int or not 1 <= self.block_rows <= 65536: + raise StoreIntegrityError('Invalid range block size.') + self.ordinals = {int(unit): i for i, unit in enumerate(engine.manifest['unit_ids'])} + self.indexed_units = set(self.catalog['indexed_units']) + if not self.indexed_units <= self.ordinals.keys(): + raise StoreIntegrityError('Range catalog contains unknown units.') + expected_directory = len(self.ordinals) * engine.bins * self.directory_dtype.itemsize + if self.catalog['files']['segments']['bytes'] != expected_directory: + raise StoreIntegrityError('Range directory size mismatch.') + max_payload = ( + sum( + int(n) + for u, n in zip(engine.manifest['unit_ids'], engine.manifest['counts']) + if u in self.indexed_units + ) + * self.payload.itemsize + ) + if self.catalog['files']['values']['bytes'] > max_payload: + raise StoreIntegrityError('Range values exceed source inventory.') + try: + for name in ('values', 'nodes', 'segments'): + self.files[name] = VerifiedFile( + self.path / f'{name}.bin', self.catalog['files'][name], self.cache + ) + except BaseException: + self.close() + raise + self.last_metrics = {} + + def close(self): + for file in self.files.values(): + file.close() + self.files.clear() + self.cache.clear() + self.endpoint_bytes = 0 + + def unchanged(self): + for file in self.files.values(): + file.unchanged() + + def _block(self, directory, block, segment, cache): + key = (int(segment), int(block)) + if key in cache: + cache.move_to_end(key) + return cache[key] + count = min(self.block_rows, int(directory['finite']) - int(block) * self.block_rows) + if count <= 0: + raise StoreIntegrityError('Range endpoint block exceeds its segment.') + offset = int(directory['start']) + int(block) * self.block_rows * self.payload.itemsize + records = np.frombuffer( + self.files['values'].read(offset, count * self.payload.itemsize), dtype=self.payload + ) + if np.any(~np.isfinite(records['amplitude'])): + raise StoreIntegrityError('Range finite partition contains nonfinite values.') + while cache and self.endpoint_bytes + records.nbytes > 8388608: + self.endpoint_bytes -= cache.popitem(last=False)[1].nbytes + self.endpoint_bytes += records.nbytes + cache[key] = records + return records + + def _cuts(self, directories, segments, predicate, cache, cancel): + from .live_summaries import _check_cancel + + count = directories['finite'] + blocks = (count + self.block_rows - 1) // self.block_rows + lo = np.zeros(len(directories), dtype=np.int64) + hi = blocks.copy() + dtype = self.payload['amplitude'] + while np.any(lo < hi): + _check_cancel(cancel) + selected = np.flatnonzero(lo < hi) + middle = (lo[selected] + hi[selected]) // 2 + values = self.files['nodes'].gather( + directories['keys'][selected] + middle * dtype.itemsize, dtype + ) + if np.any(~np.isfinite(values)): + raise StoreIntegrityError('Range boundary keys are not finite.') + before = evaluate_predicate(values, predicate) + lo[selected[before]] = middle[before] + 1 + hi[selected[~before]] = middle[~before] + candidate = lo - 1 + ranks = np.zeros(len(directories), dtype=np.int64) + selected = np.flatnonzero(candidate >= 0) + if len(selected): + rows, valid = self._blocks( + directories[selected], candidate[selected], segments[selected], cache, cancel + ) + ranks[selected] = candidate[selected] * self.block_rows + ( + evaluate_predicate(rows['amplitude'], predicate).reshape(rows.shape) & valid + ).sum(axis=1) + return ranks + + def _blocks(self, directories, blocks, segments, cache, cancel): + from .live_summaries import _check_cancel + + rows = np.zeros((len(directories), self.block_rows), dtype=self.payload) + valid = np.zeros(rows.shape, dtype=bool) + for i in range(len(directories)): + _check_cancel(cancel) + records = self._block(directories[i], blocks[i], segments[i], cache) + rows[i, : len(records)] = records + valid[i, : len(records)] = True + return rows, valid + + def _tree_ranges(self, directories, first, stop, cancel): + from .live_summaries import _check_cancel + + output = np.zeros(len(directories), dtype=self.node) + left = first + directories['leaves'] + right = stop + directories['leaves'] + while np.any(left < right): + _check_cancel(cancel) + use_left = np.flatnonzero((left < right) & ((left & 1) != 0)) + if len(use_left): + offsets = directories['tree'][use_left] + left[use_left] * self.node.itemsize + values = self.files['nodes'].gather(offsets, self.node) + output[use_left] = add_stats(output[use_left], values, self.fields) + left[use_left] += 1 + use_right = np.flatnonzero((left < right) & ((right & 1) != 0)) + if len(use_right): + right[use_right] -= 1 + offsets = directories['tree'][use_right] + right[use_right] * self.node.itemsize + values = self.files['nodes'].gather(offsets, self.node) + output[use_right] = add_stats(output[use_right], values, self.fields) + left //= 2 + right //= 2 + return output + + def _ranges(self, directories, segments, lower, upper, cache, cancel): + from .live_summaries import _check_cancel + + first = lower // self.block_rows + stop = upper // self.block_rows + partial_left = lower % self.block_rows != 0 + first = first + partial_left + full_last = (upper == directories['finite']) & (upper % self.block_rows != 0) + stop = stop + full_last + output = self._tree_ranges(directories, np.minimum(first, stop), stop, cancel) + positions = np.arange(self.block_rows) + for chosen, blocks, starts, ends in [ + ( + partial_left, + lower // self.block_rows, + lower % self.block_rows, + np.minimum(self.block_rows, upper - (lower // self.block_rows) * self.block_rows), + ), + ( + (upper % self.block_rows != 0) & ~full_last & (stop >= first), + stop, + np.zeros(len(stop), dtype=np.int64), + upper % self.block_rows, + ), + ]: + selected = np.flatnonzero(chosen) + if not len(selected): + continue + rows, valid = self._blocks( + directories[selected], blocks[selected], segments[selected], cache, cancel + ) + valid &= (positions >= starts[selected, None]) & (positions < ends[selected, None]) + output[selected] = add_stats( + output[selected], row_stats(rows, self.fields, self.node, valid), self.fields + ) + if np.any(output['amplitude_count'] != upper - lower): + raise StoreIntegrityError('Range aggregate rank/count mismatch.') + return output + + def resolve(self, expressions, cancel=None, progress=None): + from .live_summaries import _check_cancel + + program = IntervalProgram(expressions) + if not set(program.originals) <= self.indexed_units: + raise RangeUnavailableError('Some original units use the row fallback.') + if self.block_rows * (self.payload.itemsize + 40) + 256 > self.engine.max_bytes: + raise RangeUnavailableError('Range endpoint exceeds arithmetic scratch budget.') + self.unchanged() + for file in self.files.values(): + file.cancel = cancel + before = { + name: (f.bytes_read, f.hash_bytes_read, f.pages_verified) + for name, f in self.files.items() + } + if len(expressions) * self.engine.bins * 24 * len(self.fields) > self.engine.max_bytes: + raise RangeUnavailableError('Range arithmetic scratch budget exceeded.') + outputs = {u: self.engine._empty() for u in expressions} + absolute = {u: {f: np.zeros(self.engine.bins) for f in self.fields} for u in expressions} + errors = {u: {f: np.zeros(self.engine.bins) for f in self.fields} for u in expressions} + operations = { + u: {f: np.zeros(self.engine.bins, dtype=np.int64) for f in self.fields} + for u in expressions + } + chunk_bins = min( + 128, + max( + 1, + self.engine.max_bytes + // ( + max(1, len(program.cuts)) + * (self.block_rows * (self.payload.itemsize + 40) + 256) + ), + ), + ) + entry_limit = max( + 1, + self.engine.max_bytes + // ( + 4 * self.directory_dtype.itemsize + + 5 * self.node.itemsize + + 160 + + self.block_rows * (self.payload.itemsize + 40) + ), + ) + endpoint_cache = OrderedDict() + self.endpoint_bytes = 0 + all_units = list(expressions) + done = 0 + total = len(program.originals) * self.engine.bins + for original in program.originals: + ordinal = self.ordinals[original] + for first in range(0, self.engine.bins, chunk_bins): + _check_cancel(cancel) + count = min(chunk_bins, self.engine.bins - first) + segments = ordinal * self.engine.bins + np.arange( + first, first + count, dtype=np.int64 + ) + directories = np.frombuffer( + self.files['segments'].read( + int(segments[0]) * self.directory_dtype.itemsize, + count * self.directory_dtype.itemsize, + ), + dtype=self.directory_dtype, + ) + if np.any(directories['finite'] < 0) or np.any( + directories['total'] < directories['finite'] + ): + raise StoreIntegrityError('Range segment counts are invalid.') + cuts = { + key: self._cuts(directories, segments, predicate, endpoint_cache, cancel) + for key, predicate in program.cuts.items() + } + targets, bins, which, lower, upper = [], [], [], [], [] + for i, directory in enumerate(directories): + states = program.evaluate( + original, + int(directory['finite']), + int(directory['total'] - directory['finite']), + {key: int(value[i]) for key, value in cuts.items()}, + interval_limit=max(128, self.engine.max_bytes // 96), + ) + for unit, (parts, nonfinite) in states.items(): + if nonfinite: + outputs[unit]['counts'][first + i] += ( + directory['total'] - directory['finite'] + ) + if 'depth' in self.fields: + for kind, sink in [ + ('sum', outputs[unit]['trend_sums']), + ('count', outputs[unit]['trend_counts']), + ('abs', absolute[unit]), + ('error', errors[unit]), + ]: + sink['depth'][first + i] += directory['nf_depth_' + kind] + operations[unit]['depth'][first + i] += 1 + for lo, hi in parts: + targets.append(unit) + bins.append(first + i) + which.append(i) + lower.append(lo) + upper.append(hi) + if len(targets) > entry_limit: + raise RangeUnavailableError( + 'Range interval scratch budget exceeded.' + ) + if targets: + selected = np.asarray(which, dtype=np.int64) + stats = self._ranges( + directories[selected], + segments[selected], + np.asarray(lower, dtype=np.int64), + np.asarray(upper, dtype=np.int64), + endpoint_cache, + cancel, + ) + targets = np.asarray(targets) + bins = np.asarray(bins, dtype=np.int64) + for unit in all_units: + chosen = targets == unit + if not np.any(chosen): + continue + indices = bins[chosen] + np.add.at( + outputs[unit]['counts'], indices, stats['amplitude_count'][chosen] + ) + for field in self.fields: + np.add.at( + outputs[unit]['trend_sums'][field], + indices, + stats[field + '_sum'][chosen], + ) + np.add.at( + outputs[unit]['trend_counts'][field], + indices, + stats[field + '_count'][chosen], + ) + np.add.at( + absolute[unit][field], indices, stats[field + '_abs'][chosen] + ) + np.add.at( + errors[unit][field], indices, stats[field + '_error'][chosen] + ) + np.add.at(operations[unit][field], indices, 1) + done += count + if progress: + progress('querying amplitude ranges', done, total) + _check_cancel(cancel) + self.unchanged() + for unit in outputs: + validate_sums( + outputs[unit], absolute[unit], errors[unit], operations[unit], self.fields + ) + self.last_metrics = { + 'payload_bytes_read': sum(f.bytes_read - before[n][0] for n, f in self.files.items()), + 'authentication_bytes_read': sum( + f.hash_bytes_read - before[n][1] for n, f in self.files.items() + ), + 'pages_verified': sum(f.pages_verified - before[n][2] for n, f in self.files.items()), + 'resident_page_bytes': self.cache.size, + } + return outputs + + +def attach_amplitude_index( + package_path, + index_path, + expected_reference=_ANY_REFERENCE, + before_attach=None, + check_cancel=None, +): + """Attach only to the matching prepared row snapshot, preserving newer choices.""" + from .live_summaries import LiveSummaryEngine + + with LiveSummaryEngine(package_path) as engine: + index = AmplitudeRangeIndex(engine, path=index_path) + try: + lock = engine.path / '.phy' / 'summary-store-attachment' + lock.mkdir(parents=True, exist_ok=True) + with _attachment_lock(lock, check_cancel): + raw = summary_store_reference(engine.path, allow_invalid=True) + if expected_reference is not _ANY_REFERENCE and raw != expected_reference: + raise ValueError( + 'The attached store changed during amplitude-index preparation.' + ) + reference = json.loads(raw) + if reference['index_sha256'] != index.catalog['parent_sha256']: + raise ValueError('The amplitude index needs its original row store.') + if before_attach: + before_attach() + path = Path(index_path).resolve() + try: + path_text = str(path.relative_to(Path(reference['path']).resolve())) + except ValueError: + path_text = str(path) + reference['amplitude_index'] = { + 'path': path_text, + 'catalog_sha256': index.catalog_sha256, + } + _atomic_json(engine.path / '.phy' / 'live-summary-store.json', reference) + finally: + index.close() + return Path(index_path) diff --git a/phy/apps/large_recording/range_intervals.py b/phy/apps/large_recording/range_intervals.py new file mode 100644 index 000000000..8541ce57e --- /dev/null +++ b/phy/apps/large_recording/range_intervals.py @@ -0,0 +1,109 @@ +"""Compile semantic membership graphs into finite rank intervals per segment.""" + +from .curation import validate_predicate +from .source import hash_json + + +class RangeUnavailableError(ValueError): + """The verified row path remains available for this unsupported query.""" + + +def normalize(parts): + result = [] + for lo, hi in sorted(parts): + if lo >= hi: + continue + if result and lo <= result[-1][1]: + result[-1] = (result[-1][0], max(hi, result[-1][1])) + else: + result.append((lo, hi)) + return result + + +class IntervalProgram: + """Keep rejection obligations even if later operations select no finite rows.""" + + def __init__(self, expressions): + self.nodes, self.roots, self.cuts = [], {}, {} + known, visiting, objects = {}, set(), {} + + def compile_one(expression): + identity = id(expression) + if identity in objects: + return objects[identity] + if identity in visiting: + raise RangeUnavailableError('Cyclic membership expression.') + visiting.add(identity) + kind = expression['kind'] + if kind == 'source': + node = ('source', int(expression['unit'])) + elif kind == 'union': + node = ('union', tuple(compile_one(p) for p in expression['parts'])) + elif kind == 'split': + predicate = validate_predicate(expression['predicate']) + if predicate['attribute'] != 'amplitudes.npy': + raise RangeUnavailableError('Only amplitude predicates use the range index.') + parent = compile_one(expression['parent']) + operator = predicate['operator'] + bound = '<' if operator in ('<', '>=') else '<=' + cut = hash_json({'operator': bound, 'threshold': predicate['threshold']}) + self.cuts[cut] = dict(predicate, operator=bound, nonfinite='keep') + node = ( + 'split', + parent, + cut, + operator, + bool(expression['selected']), + predicate['nonfinite'], + ) + else: + raise RangeUnavailableError('Unsupported membership expression.') + visiting.remove(identity) + if node not in known: + known[node] = len(self.nodes) + self.nodes.append(node) + objects[identity] = known[node] + if len(self.nodes) > 8192: + raise RangeUnavailableError('Membership graph exceeds range query budget.') + return known[node] + + try: + for unit, expression in expressions.items(): + self.roots[unit] = compile_one(expression) + except RecursionError as error: + raise RangeUnavailableError( + 'Membership history exceeds range compilation budget.' + ) from error + self.originals = sorted({node[1] for node in self.nodes if node[0] == 'source'}) + + def evaluate(self, original, finite_count, nonfinite_count, cuts, interval_limit=100000): + states = [] + slots = 0 + for node in self.nodes: + kind = node[0] + if kind == 'source': + match = node[1] == original + intervals = [(0, finite_count)] if match and finite_count else [] + nonfinite = match + elif kind == 'union': + intervals = normalize([p for parent in node[1] for p in states[parent][0]]) + nonfinite = any(states[parent][1] for parent in node[1]) + else: + _, parent, cut, operator, selected, policy = node + parts, parent_nonfinite = states[parent] + if policy == 'reject' and parent_nonfinite and nonfinite_count: + raise ValueError('Nonfinite source values violate threshold policy.') + rank = cuts[cut] + lower = operator in ('<', '<=') + if not selected: + lower = not lower + intervals = [ + (lo, min(hi, rank)) if lower else (max(lo, rank), hi) for lo, hi in parts + ] + intervals = [(lo, hi) for lo, hi in intervals if lo < hi] + nonfinite = parent_nonfinite and not selected + slots += len(intervals) + if slots > interval_limit: + raise RangeUnavailableError('Membership intervals exceed query memory budget.') + states.append((intervals, nonfinite)) + return {unit: states[root] for unit, root in self.roots.items()} diff --git a/phy/apps/large_recording/range_math.py b/phy/apps/large_recording/range_math.py new file mode 100644 index 000000000..a4dc9c0e8 --- /dev/null +++ b/phy/apps/large_recording/range_math.py @@ -0,0 +1,94 @@ +"""Typed threshold boundaries and conservative float64 aggregation bounds.""" + +import numpy as np + +from .curation import evaluate_predicate +from .range_intervals import RangeUnavailableError + +EPS = np.finfo(np.float64).eps +SUM_RTOL = 1e-9 +SUM_ATOL = 1e-6 + + +def node_dtype(fields): + return np.dtype( + [ + (f'{field}_{kind}', ' allowed): + raise RangeUnavailableError('Trend arithmetic needs the verified row fallback.') + + +def typed_rank(values, predicate): + """Reference scalar search using the same array ufunc as semantic replay. + + Deliberately avoid searchsorted's different scalar-promotion rules. + """ + lo, hi = 0, len(values) + while lo < hi: + middle = (lo + hi) // 2 + if evaluate_predicate(values[middle : middle + 1], predicate)[0]: + lo = middle + 1 + else: + hi = middle + return lo diff --git a/phy/apps/large_recording/recovery.py b/phy/apps/large_recording/recovery.py new file mode 100644 index 000000000..f3b67e95c --- /dev/null +++ b/phy/apps/large_recording/recovery.py @@ -0,0 +1,375 @@ +"""Private semantic recovery drafts; never a source for committed curation replay.""" + +import copy +import json +import logging +import math +import os +import sys +import time +import uuid +from datetime import datetime +from pathlib import Path + +import numpy as np + +from ._immutable import freeze +from .curation import ( + BoundedSession, + _current_pointer, + _digest, + _fsync_directory, + _integer, + _read_json, + _safe_file, + _write_json, + interpret_events, + normalize_metadata, + project_assignments, +) + +logger = logging.getLogger(__name__) +FORMAT = 'phy_bounded_recovery' +VERSION = 1 +SOFT_BUDGET = 256 * 1024 * 1024 + + +def default_recovery_root(): + override = os.environ.get('PHY_RECOVERY_ROOT') + if override: + return Path(override).expanduser() + if sys.platform == 'win32': + root = Path(os.environ.get('LOCALAPPDATA', Path.home() / 'AppData' / 'Local')) + elif sys.platform == 'darwin': + root = Path.home() / 'Library' / 'Application Support' + else: + root = Path(os.environ.get('XDG_DATA_HOME', Path.home() / '.local' / 'share')) + return root / 'phy' / 'recovery' + + +def recovery_bindings(session): + return freeze( + { + 'manifest_sha256': _digest(session.manifest), + 'source_identity': session.manifest['source']['identity']['sha256'], + 'source_revision': session.manifest['source']['revision'], + 'proposition_documents': session.proposition_documents, + } + ) + + +class OwnerLock: + """A live process owns a branch; PID files and timestamps are not locks.""" + + def __init__(self, path): + flags = os.O_CREAT | os.O_RDWR | getattr(os, 'O_NOFOLLOW', 0) + descriptor = os.open(path, flags, 0o600) + self.stream = os.fdopen(descriptor, 'r+b') + if os.name != 'nt': + os.fchmod(descriptor, 0o600) + try: + if os.name == 'nt': + import msvcrt + + self.stream.seek(0, os.SEEK_END) + if not self.stream.tell(): + self.stream.write(b'\0') + self.stream.flush() + self.stream.seek(0) + msvcrt.locking(self.stream.fileno(), msvcrt.LK_NBLCK, 1) + else: + import fcntl + + fcntl.flock(self.stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + except BaseException: + self.stream.close() + raise + + def close(self): + if self.stream.closed: + return + if os.name == 'nt': + import msvcrt + + self.stream.seek(0) + msvcrt.locking(self.stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + fcntl.flock(self.stream.fileno(), fcntl.LOCK_UN) + self.stream.close() + + +def _private_directory(path): + """Create private ancestors and persist every newly created directory entry.""" + path = Path(path) + missing, parent = [], path + while not parent.exists(): + missing.append(parent) + parent = parent.parent + for directory in reversed(missing): + directory.mkdir(mode=0o700, exist_ok=True) + _fsync_directory(directory) + _fsync_directory(directory.parent) + if path.is_symlink() or not path.is_dir(): + raise ValueError('Recovery storage must be a real directory.') + if os.name != 'nt' and path.stat().st_mode & 0o077: + # A supplied root may be a shared directory such as /tmp. Never chmod + # caller-owned ancestors or turn them into private application storage. + raise ValueError('Recovery storage must be a private directory (0700).') + + +def _atomic_json(directory, name, value): + target = _safe_file(directory, name) + temporary = _safe_file(directory, f'.{uuid.uuid4().hex}.tmp') + try: + descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + os.close(descriptor) + _write_json(temporary, value) + os.replace(temporary, target) + _fsync_directory(directory) + finally: + temporary.unlink(missing_ok=True) + + +def _retired_through(branch): + try: + record = _read_json(_safe_file(branch, 'retired.json')) + except FileNotFoundError: + return -1 + if record.get('format') != FORMAT or record.get('version') != VERSION: + raise ValueError('Recovery retirement record is invalid.') + return _integer(record['through_revision'], 'Retired recovery revision') + + +def _verified_heads(branch, bindings, with_slots=False, include_retired=False): + retired = _retired_through(branch) + if include_retired: + retired = -1 + valid, errors = [], [] + for name in ('head-0.json', 'head-1.json'): + try: + wrapper = _read_json(_safe_file(branch, name)) + payload = wrapper['payload'] + if wrapper['sha256'] != _digest(payload): + raise ValueError('Recovery draft checksum mismatch.') + if payload.get('format') != FORMAT or payload.get('version') != VERSION: + raise ValueError('Unsupported recovery draft format.') + if payload['bindings'] != bindings or payload['session_id'] != branch.name: + raise ValueError('Recovery draft belongs to another preparation/session.') + revision = _integer(payload['revision'], 'Recovery revision') + created = payload['created_at'] + if ( + type(created) not in (int, float) + or not math.isfinite(created) + or not isinstance(payload['events'], list) + or payload.get('reviews') is not None + and not isinstance(payload['reviews'], dict) + ): + raise ValueError('Recovery draft header is malformed.') + datetime.fromtimestamp(created).astimezone() # Validate displayable timestamps here. + _integer(payload['next_cluster_id'], 'Recovery allocator') + if revision > retired: + valid.append((payload, name) if with_slots else payload) + except FileNotFoundError: + continue + except (ValueError, TypeError, KeyError, OSError, OverflowError, RecursionError) as error: + errors.append(str(error)) + return sorted( + valid, key=lambda item: (item[0] if with_slots else item)['revision'], reverse=True + ), errors + + +class RecoveryStore: + """Two independent atomic heads per private writer, outside disposable caches.""" + + def __init__(self, session, root=None, session_id=None, soft_budget=SOFT_BUDGET): + self.bindings = recovery_bindings(session) + self.dataset_path = Path(session.path) + root = Path(root or default_recovery_root()) + _private_directory(root) + self.directory = root / self.bindings['manifest_sha256'] + _private_directory(self.directory) + self.session_id = session_id or uuid.uuid4().hex + self.branch = _safe_file(self.directory, self.session_id) + _private_directory(self.branch) + self.owner = OwnerLock(_safe_file(self.branch, 'owner.lock')) + self.soft_budget = soft_budget + try: + _fsync_directory(self.directory) + _fsync_directory(self.directory.parent) + except BaseException: + self.owner.close() + raise + + def write(self, payload): + if payload['bindings'] != self.bindings or payload['session_id'] != self.session_id: + raise ValueError('Recovery snapshot bindings changed.') + revision = _integer(payload['revision'], 'Recovery revision') + if revision <= _retired_through(self.branch): + return {'retired': True} + heads, _ = _verified_heads(self.branch, self.bindings, with_slots=True) + # Coalescing skips revision numbers: parity would overwrite the only + # previous head for revisions 1,3. Rotate by the latest verified slot. + slot = 1 if heads and heads[0][1] == 'head-0.json' else 0 + _atomic_json( + self.branch, + f'head-{slot}.json', + {'sha256': _digest(payload), 'payload': payload}, + ) + # This is a soft budget: never delete the only unresolved draft to meet it. + size = sum( + path.stat().st_size + for branch in self.directory.iterdir() + if branch.is_dir() and not branch.is_symlink() + for path in branch.glob('head-*.json') + if path.is_file() and not path.is_symlink() + ) + warning = None + if size > self.soft_budget: + warning = 'Recovery storage exceeds its soft budget; unresolved drafts were retained.' + try: + current = _current_pointer(self.dataset_path / '.phy-curation') + conflict = current != payload['base_pointer'] + except (OSError, ValueError): + conflict = True + return {'retired': False, 'warning': warning, 'checkpoint_conflict': conflict} + + def probe(self): + _atomic_json(self.branch, 'health.json', {'format': FORMAT, 'checked_at': time.time()}) + + def retire(self, through_revision, reason='discarded', branch=None): + branch = Path(branch or self.branch) + if branch.parent != self.directory or branch.is_symlink(): + raise ValueError('Recovery branch must belong to this preparation.') + owner = None + if branch != self.branch: + owner = OwnerLock(_safe_file(branch, 'owner.lock')) + try: + previous = _retired_through(branch) + through = max(previous, _integer(through_revision, 'Recovery revision')) + _atomic_json( + branch, + 'retired.json', + { + 'format': FORMAT, + 'version': VERSION, + 'through_revision': through, + 'reason': reason, + 'retired_at': time.time(), + }, + ) + # Retirement is already durable. Cleanup is deliberately narrower: + # never remove newer, corrupt, unbound, or unknown head contents. + warning = None + try: + self._prune_retired(branch, through) + except OSError as error: + warning = f'Recovery draft retired, but storage cleanup failed: {error}' + logger.warning(warning) + return {'warning': warning} + finally: + if owner is not None: + owner.close() + + def _prune_retired(self, branch, through): + heads, _ = _verified_heads(branch, self.bindings, with_slots=True, include_retired=True) + removed = False + for payload, name in heads: + if payload['revision'] <= through: + _safe_file(branch, name).unlink() + removed = True + if removed: + _fsync_directory(branch) + + def candidates(self, base_pointer): + candidates, warnings = [], [] + for branch in self.directory.iterdir(): + if not branch.is_dir() or branch.is_symlink() or branch == self.branch: + continue + try: + owner = OwnerLock(_safe_file(branch, 'owner.lock')) + except OSError: + continue # Another live process owns this branch. + try: + heads, errors = _verified_heads(branch, self.bindings) + if heads: + latest = heads[0] + if latest['base_pointer'] == base_pointer: + candidates.append({'branch': str(branch), 'payload': latest}) + else: + warnings.append( + 'An older-checkpoint recovery branch was retained separately.' + ) + warnings.extend(errors) + except (OSError, ValueError, TypeError, KeyError) as error: + warnings.append(str(error)) + finally: + owner.close() + candidates.sort(key=lambda item: item['payload']['created_at'], reverse=True) + return candidates, warnings + + def close(self): + self.owner.close() + + +def build_recovered_state(session, payload): + """Reconstruct off the GUI thread without changing live/canonical state.""" + from phy.cluster._propositions import decode_review_mapping + + if payload['bindings'] != recovery_bindings(session): + raise ValueError('Recovery draft preparation/source bindings do not match.') + if payload['base_pointer'] != session._expected_pointer: + raise ValueError('Recovery base checkpoint changed; automatic rebasing is unavailable.') + session.validate_proposition_documents() + events = copy.deepcopy(payload['events']) + if not isinstance(events, list): + raise ValueError('Recovery journal must be an ordered list.') + for event in events: + if event.get('operation') in ('threshold_split', 'restore_parents'): + event['metadata'] = normalize_metadata(event['metadata']) + session._validate_event_capabilities(events) + _, metadata, minimum = interpret_events(session.unit_ids, session.base_metadata, events) + next_id = _integer(payload['next_cluster_id'], 'Recovery allocator') + if next_id < max(minimum, session.base_next_cluster_id): + raise ValueError('Recovery allocator collides with semantic journal IDs.') + documents = dict(session.extra_documents) + reviews = payload.get('reviews') + if reviews is not None: + source, _ = decode_review_mapping(reviews) + expected = session.proposition_documents.get('curation.json', {}).get('sha256') + if ( + source.get('filename') != 'curation.json' + or source.get('sha256') != expected + or expected is None + ): + raise ValueError('Recovery SLAY ledger is not bound to the producer document.') + documents['curation_review.json'] = reviews + elif 'curation.json' in session.proposition_documents: + raise ValueError('Recovery draft omitted its SLAY ledger.') + # The detached shell shares only read-only source readers. It owns no file + # lifetime and must not be closed: adoption keeps the original live session. + recovered = object.__new__(BoundedSession) + recovered.__dict__ = dict(session.__dict__) + recovered.assignments = project_assignments( + session.base_assignments, events, session.attributes + ) + recovered.metadata = metadata + recovered._events = freeze(events) + recovered.next_cluster_id = max(next_id, session.next_cluster_id) + recovered.extra_documents = documents + recovered.validate_proposition_documents() + recovered._reset_runtime() + from .supervisor import GuardedClustering, MutationPolicy + + recovered._recovery_clustering = GuardedClustering( + recovered.assignments.copy(), + new_cluster_id=recovered.next_cluster_id, + spikes_per_cluster=recovered._assignment_groups, + policy=MutationPolicy(), + ) + if not np.array_equal(recovered._recovery_clustering.spike_clusters, recovered.assignments): + raise ValueError('Recovered native assignments disagree with semantic projection.') + recovered._certified_assignments = recovered.assignments + recovered._certified_native = recovered._recovery_clustering._spike_clusters + return recovered diff --git a/phy/apps/large_recording/recovery_gui.py b/phy/apps/large_recording/recovery_gui.py new file mode 100644 index 000000000..f91063619 --- /dev/null +++ b/phy/apps/large_recording/recovery_gui.py @@ -0,0 +1,544 @@ +"""Coalesced background draft protection at settled bounded curation boundaries.""" + +import copy +import logging +import threading +import time +import uuid +from collections import deque +from concurrent.futures import Future +from contextlib import suppress +from pathlib import Path + +from phylib.utils import emit + +from phy.gui.qt import QObject, Qt, QTimer, pyqtSignal + +from ._immutable import freeze +from .recovery import ( + FORMAT, + VERSION, + RecoveryStore, + build_recovered_state, + default_recovery_root, + recovery_bindings, +) + +logger = logging.getLogger(__name__) + + +class _Delivery(QObject): + finished = pyqtSignal(object) + + +class _Writer: + """One active operation and one latest pending snapshot; controls stay ordered.""" + + def __init__(self, factory, delivery): + self.factory, self.delivery = factory, delivery + self.condition = threading.Condition() + self.pending = None + self.controls = deque() + self.stopping = False + self.thread = threading.Thread(target=self._run, name='phy-recovery', daemon=True) + self.thread.start() + + def submit(self, kind, revision, operation, snapshot=False): + future = Future() + with self.condition: + if self.stopping: + future.set_exception(RuntimeError('Recovery writer is closed.')) + return future + item = (kind, revision, operation, future) + if snapshot: + if self.pending is not None: + self.pending[-1].cancel() + self.pending = item + else: + self.controls.append(item) + self.condition.notify() + return future + + def stop(self): + with self.condition: + self.stopping = True + self.condition.notify() + + def _deliver(self, kind, revision, future): + # GUI/interpreter shutdown never changes a completed disk write. + with suppress(RuntimeError): + self.delivery.finished.emit((kind, revision, future)) + + def _run(self): + store = None + try: + while True: + with self.condition: + self.condition.wait_for(lambda: self.controls or self.pending or self.stopping) + if self.controls: + item = self.controls.popleft() + elif self.pending is not None: + item, self.pending = self.pending, None + elif self.stopping: + return + else: + continue + kind, revision, operation, future = item + if not future.set_running_or_notify_cancel(): + continue + try: + if store is None: + store = self.factory() + result = operation(store) + except Exception as error: + future.set_exception(error) + else: + future.set_result(result) + self._deliver(kind, revision, future) + finally: + if store is not None: + store.close() + + +class RecoveryCoordinator(QObject): + """Expose protection acknowledgements separately from canonical Save state.""" + + changed = pyqtSignal() + + def __init__(self, controller, root=None, enabled=True, idle_ms=1000, maximum_ms=5000): + super().__init__() + self.controller = controller + self.supervisor = controller.supervisor + self.session = controller.bounded_session + self.root = Path(root) if root is not None else default_recovery_root() + self.enabled = bool(enabled) + self.session_id = uuid.uuid4().hex + self.bindings = recovery_bindings(self.session) + self.idle_ms, self.maximum_ms = idle_ms, maximum_ms + self._last_token = self.supervisor.recovery_token() + self._current_revision = self._protected_revision = self._checkpoint_revision = 0 + self._last_protected_at = None + self._last_checkpoint_at = ( + (self.session.checkpoint_path / 'checkpoint.json').stat().st_mtime + if self.session.checkpoint_path is not None + else None + ) + self._state = ( + 'protected' + if self.enabled and self._last_checkpoint_at is not None + else 'ready' + if self.enabled + else 'disabled' + ) + self._error = self._warning = None + self._error_revision = None + self._writer = None + self._closed = self._started = self._retired = False + self._retry_ms = 1000 + self._restored_from = None + self.pending_drafts = [] + self.startup_error = None + self._delivery = _Delivery() + self._delivery.finished.connect(self._completed, Qt.QueuedConnection) + self._idle = QTimer(self) + self._idle.setSingleShot(True) + self._idle.timeout.connect(self.request_flush) + self._deadline = QTimer(self) + self._deadline.setSingleShot(True) + self._deadline.timeout.connect(self.request_flush) + + @property + def status(self): + return { + 'enabled': self.enabled, + 'state': self._state, + 'current_revision': self._current_revision, + 'protected_revision': self._protected_revision, + 'last_protected_at': self._last_protected_at, + 'last_checkpoint_at': self._last_checkpoint_at, + 'error': self._error, + 'warning': self._warning, + 'startup_error': self.startup_error, + 'recovery_path': str(self.root) if self.root is not None else None, + } + + def _announce(self): + self.changed.emit() + emit('recovery_status_changed', self.supervisor) + + def _ensure_writer(self): + if self._writer is None: + session, root, session_id = self.session, self.root, self.session_id + self._writer = _Writer( + lambda: RecoveryStore(session, root=root, session_id=session_id), self._delivery + ) + return self._writer + + def start(self): + if not self.enabled or self._closed: + return + self._started = True + self._ensure_writer() + if self._retired and self.supervisor.is_dirty(): + self.observe(force=True) + elif self._current_revision > self._protected_revision: + self._schedule() + + def suspend(self): + if self.enabled and not self._closed and self._started: + self.request_flush() + self._started = False + self._idle.stop() + self._deadline.stop() + + def observe(self, force=False): + if not self.enabled or self._closed: + return + token = self.supervisor.recovery_token() + if not force and token == self._last_token: + return + self._last_token = token + self._current_revision += 1 + self._retired = False + self._state = 'pending' + if self._started: + self._schedule() + self._announce() + + def _schedule(self): + self._idle.start(self.idle_ms) + if not self._deadline.isActive(): + self._deadline.start(self.maximum_ms) + + def _snapshot(self): + # All references are immutable. JSON encoding and ledger materialization + # belong to the worker, never to an interactive spike-array transaction. + events, allocator, _ = self.supervisor.recovery_token() + catalog = ( + self.supervisor.merge_propositions.catalog + if self.supervisor.merge_propositions is not None + else None + ) + ledger = freeze(self.session.extra_documents.get('curation_review.json')) + base = copy.deepcopy(self.session._expected_pointer) + revision, created = self._current_revision, time.time() + source_hash = self.session.proposition_documents.get('curation.json', {}).get('sha256') + session_id, bindings, path_hint = self.session_id, self.bindings, str(self.session.path) + + def materialize(store): + reviews = catalog.review_mapping(source_sha256=source_hash) if catalog else ledger + payload = { + 'format': FORMAT, + 'version': VERSION, + 'session_id': session_id, + 'revision': revision, + 'created_at': created, + 'bindings': bindings, + 'base_pointer': base, + 'dataset_path_hint': path_hint, + 'events': list(events), + 'next_cluster_id': allocator, + 'reviews': reviews, + } + result = store.write(payload) + return {**result, 'protected_at': time.time(), 'base_pointer': base} + + return revision, materialize + + def request_flush(self): + if not self.enabled or self._closed or self._retired: + return None + if getattr(self.supervisor, '_recovery_depth', 0): + if self._started: + self._idle.start(self.idle_ms) + return None + self.observe() + if self._current_revision <= self._protected_revision: + if self._state == 'error': + return self._ensure_writer().submit( + 'probe', self._current_revision, lambda store: store.probe() + ) + return None + self._idle.stop() + self._deadline.stop() + revision, operation = self._snapshot() + self._state = 'saving' + self._announce() + return self._ensure_writer().submit('snapshot', revision, operation, snapshot=True) + + def _completed(self, payload): + kind, revision, future = payload + if self._closed or future.cancelled(): + return + if kind == 'snapshot' and revision <= max( + self._checkpoint_revision, self._protected_revision + ): + return # An explicit durable Save already protects this older work. + try: + result = future.result() + except Exception as error: + if kind == 'checkpoint': + self._warning = f'Checkpoint saved, but recovery retirement failed: {error}' + self._announce() + return + self._error = str(error) + self._error_revision = revision + self._state = 'error' + logger.warning('Automatic recovery failed: %s', error) + if self._started: + self._idle.start(self._retry_ms) + self._retry_ms = min(60000, self._retry_ms * 2) + else: + if kind == 'snapshot' and not result.get('retired'): + if result['base_pointer'] != self.session._expected_pointer: + self._state = 'pending' + if self._started: + self._schedule() + self._announce() + return + if result.get('checkpoint_conflict'): + self._error = ( + 'Another session saved a different checkpoint. This recovery draft ' + 'was retained separately; automatic rebasing is unavailable.' + ) + self._error_revision = revision + self._state = 'error' + self._announce() + return + self._protected_revision = max(self._protected_revision, revision) + self._last_protected_at = result['protected_at'] + self._warning = result.get('warning') + if self._error_revision is None or revision >= self._error_revision: + self._error = None + self._error_revision = None + self._retry_ms = 1000 + self._state = ( + 'protected' + if self._protected_revision >= self._current_revision + else 'pending' + ) + elif kind in ('checkpoint', 'retire') and result and result.get('warning'): + self._warning = result['warning'] + elif kind == 'probe': + self._error = None + self._error_revision = None + self.startup_error = None + self._state = ( + 'protected' + if self._last_protected_at is not None or self._last_checkpoint_at is not None + else 'ready' + ) + elif kind == 'discard': + if result and result.get('warning'): + self._warning = result['warning'] + self._retired = revision >= self._current_revision + self._state = 'pending' + self._protected_revision = 0 + self._last_protected_at = None + self._error = None + if not self._retired and self._started: + self._schedule() + self._announce() + + def checkpoint_saved(self, token): + if not self.enabled or self._closed: + self._last_checkpoint_at = time.time() + if not self._closed: + self._state = 'disabled' + self._announce() + return + self.observe() + # Save's captured state can differ from a newer edit. Retire only its + # acknowledged prefix; newer queued snapshots must survive. + revision = token[0] + self._checkpoint_revision = max(self._checkpoint_revision, revision) + self._last_checkpoint_at = time.time() + restored = self._restored_from + + def retire_checkpoint(store): + results = [store.retire(revision, reason='checkpointed')] + if restored is not None: + results.append( + store.retire( + restored['payload']['revision'], 'checkpointed', restored['branch'] + ) + ) + return { + 'warning': '; '.join(r['warning'] for r in results if r.get('warning')) or None + } + + self._ensure_writer().submit('checkpoint', revision, retire_checkpoint) + if self.supervisor.recovery_token() == token[1]: + self._protected_revision = self._current_revision + self._last_protected_at = self._last_checkpoint_at + self._state = 'protected' + self._error = None + else: + self._state = 'pending' + if self._started: + self._schedule() + self._announce() + + def checkpoint_failed(self, error): + self.observe() + self._state = 'error' + self._error = f'Checkpoint save failed or durability is uncertain: {error}' + self._announce() + + def checkpoint_token(self): + self.observe() + return self._current_revision, self.supervisor.recovery_token() + + def discard(self): + if not self.enabled or self._closed: + future = Future() + future.set_result(None) + return future + self.observe() + self._idle.stop() + self._deadline.stop() + revision = self._current_revision + restored = self._restored_from + + def retire(store): + results = [store.retire(revision, reason='discarded')] + if restored is not None: + results.append( + store.retire(restored['payload']['revision'], 'discarded', restored['branch']) + ) + return { + 'warning': '; '.join(r['warning'] for r in results if r.get('warning')) or None + } + + return self._ensure_writer().submit('discard', revision, retire) + + def candidates(self): + base = copy.deepcopy(self.session._expected_pointer) + return self._ensure_writer().submit('candidates', 0, lambda store: store.candidates(base)) + + def restore(self, candidate): + session, payload = self.session, candidate['payload'] + return self._ensure_writer().submit( + 'restore', 0, lambda store: build_recovered_state(session, payload) + ) + + def retire_candidate(self, candidate): + return self._ensure_writer().submit( + 'retire', + 0, + lambda store: store.retire( + candidate['payload']['revision'], 'discarded', candidate['branch'] + ), + ) + + def offer_startup(self): + if not self.enabled or self._closed: + return + try: + drafts, warnings = wait_operation(self.candidates(), 'Checking recovery drafts…') + self.pending_drafts = drafts + if warnings: + self.startup_error = '; '.join(dict.fromkeys(warnings)) + self._announce() + if not drafts: + return + choice = choose_recovery(drafts) + action, index = (choice, 0) if isinstance(choice, str) else choice + candidate = drafts[index] + if action == 'restore': + recovered = wait_operation( + self.restore(candidate), 'Reconstructing recovery draft…' + ) + self._restored_from = candidate + self.restored(recovered) + elif action == 'discard': + wait_operation(self.retire_candidate(candidate), 'Discarding recovery draft…') + except Exception as error: + self.startup_error = str(error) + self._error = f'Recovery could not be restored: {error}' + self._state = 'error' + self._announce() + + def restored(self, recovered): + self.supervisor.adopt_recovery(recovered) + for name in ('_lineage_cache', '_waveform_membership_cache'): + if hasattr(self.controller, name): + delattr(self.controller, name) + self.observe(force=True) + self.request_flush() + + def close(self): + if self._closed: + return + self.suspend() + self._closed = True + if self._writer is not None: + self._writer.stop() + + +def wait_operation(future, title, parent=None): + """Wait with an active Qt event loop, never doing disk/reconstruction work here.""" + from PyQt5.QtWidgets import QProgressDialog + + from phy.gui.qt import QEventLoop + + if future.done(): + return future.result() + progress = QProgressDialog(title, '', 0, 0, parent) + progress.setCancelButton(None) + progress.setWindowModality(Qt.ApplicationModal) + progress.setMinimumDuration(100) + progress.show() + loop = QEventLoop() + timer = QTimer() + timer.setInterval(10) + timer.timeout.connect(lambda: loop.quit() if future.done() else None) + timer.start() + loop.exec_() + timer.stop() + progress.close() + return future.result() + + +from phy.gui.qt import mockable + + +@mockable +def choose_recovery(candidates): # pragma: no cover -- exercised through mockable choice + from datetime import datetime + + from PyQt5.QtWidgets import QComboBox, QDialog, QDialogButtonBox, QLabel, QVBoxLayout + + dialog = QDialog() + dialog.setWindowTitle('Recover unsaved bounded curation') + layout = QVBoxLayout(dialog) + layout.addWidget( + QLabel( + 'A recovery draft contains unsaved assignments, labels and review decisions.\n' + 'Restoring it does not change the saved checkpoint or full-source replay.\n' + 'The restored draft starts a new Undo baseline.' + ) + ) + choices = QComboBox() + for candidate in candidates: + payload = candidate['payload'] + stamp = ( + datetime.fromtimestamp(payload['created_at']) + .astimezone() + .strftime('%Y-%m-%d %H:%M:%S %Z') + ) + choices.addItem(f'{stamp} — {len(payload["events"])} journal events') + layout.addWidget(choices) + buttons = QDialogButtonBox() + restore = buttons.addButton('Restore draft', QDialogButtonBox.AcceptRole) + discard = buttons.addButton( + 'Keep checkpoint and discard draft', QDialogButtonBox.DestructiveRole + ) + later = buttons.addButton('Decide later', QDialogButtonBox.RejectRole) + selection = ['later'] + restore.clicked.connect(lambda: (selection.__setitem__(0, 'restore'), dialog.accept())) + discard.clicked.connect(lambda: (selection.__setitem__(0, 'discard'), dialog.accept())) + later.clicked.connect(dialog.reject) + layout.addWidget(buttons) + dialog.exec_() + return selection[0], choices.currentIndex() diff --git a/phy/apps/large_recording/recovery_status.py b/phy/apps/large_recording/recovery_status.py new file mode 100644 index 000000000..b2e5ec01c --- /dev/null +++ b/phy/apps/large_recording/recovery_status.py @@ -0,0 +1,325 @@ +"""A passive draft-protection indicator and user-controlled checkpoint reminder.""" + +import logging +import math +import time +from contextlib import suppress +from datetime import datetime + +from phylib.utils import connect, unconnect + +from phy.gui.qt import ( + QActionGroup, + QApplication, + QEvent, + QHBoxLayout, + QKeySequence, + QLabel, + QMenu, + QPushButton, + Qt, + QTimer, + QWidget, + QWindow, +) + +logger = logging.getLogger(__name__) +_NORMAL = 'QPushButton {background:#292d32;color:#eeeeee;border:1px solid #666;padding:3px 8px;}' +_REMINDER = ( + 'QPushButton {background:#e6bd6b;color:#20180a;border:1px solid #e6bd6b;padding:3px 8px;}' +) +_INPUT_EVENTS = { + QEvent.KeyPress, + QEvent.MouseButtonPress, + QEvent.MouseMove, + QEvent.Wheel, +} + + +def _timestamp(value): + try: + value = float(value) + except (TypeError, ValueError): + return None + return value if math.isfinite(value) and value >= 0 else None + + +def _age_label(saved_at, now): + if saved_at is None: + return 'No checkpoint yet' + seconds = max(0, now - saved_at) + if seconds < 60: + return 'Checkpoint just now' + if seconds < 3600: + return f'Checkpoint {int(seconds // 60)} min ago' + if seconds < 86400: + return f'Checkpoint {int(seconds // 3600)} h ago' + return f'Checkpoint {int(seconds // 86400)} days ago' + + +class CheckpointStatus(QWidget): + """Keep reminders outside plots and never trigger a save from a timer. + + The recovery coordinator owns the durability acknowledgements. This widget + only reads its small status dictionary; it never captures or serializes data. + """ + + def __init__(self, controller, gui, *, clock=time.monotonic, wall_clock=time.time): + super().__init__(gui) + self.controller = controller + self.gui = gui + self.recovery = controller.recovery + self._clock, self._wall_clock = clock, wall_clock + self._closed = False + self._dirty = False + self._dirty_since = None + self._saved_at = None + self._observed_revision = None + self._snoozed_until = 0 + self._last_input = self._clock() + self._highlighted = False + self._checkpoint_error = None + preferences = gui.state.get('CheckpointReminder', {}) + self.reminders_enabled = bool(preferences.get('enabled', True)) + minutes = preferences.get('interval_minutes', 15) + self.interval_minutes = minutes if minutes in (5, 15, 30) else 15 + + self.label = QLabel(self) + self.label.setObjectName('checkpointProtectionStatus') + shortcut = QKeySequence('Ctrl+S').toString(QKeySequence.NativeText) + for actions in gui.actions: + save = actions.get('save') + if save is not None and not save.shortcut().isEmpty(): + shortcut = save.shortcut().toString(QKeySequence.NativeText) + break + self.save_button = QPushButton(f'Save checkpoint · {shortcut}', self) + self.save_button.setObjectName('saveCheckpointButton') + self.save_button.setFocusPolicy(Qt.NoFocus) + self.save_button.setStyleSheet(_NORMAL) + self.save_button.clicked.connect(self._save) + self.save_button.setAccessibleName('Save checkpoint') + self.options = QPushButton(self) + self.options.setObjectName('checkpointReminderOptions') + self.options.setText('⋮') + self.options.setAccessibleName('Checkpoint reminder options') + self.options.setToolTip('Checkpoint reminder options') + self.options.setFocusPolicy(Qt.NoFocus) + self.options.setStyleSheet('QPushButton::menu-indicator {image:none; width:0px;}') + menu = QMenu(self.options) + self.reminder_action = menu.addAction('Checkpoint reminders') + self.reminder_action.setCheckable(True) + self.reminder_action.setChecked(self.reminders_enabled) + self.reminder_action.toggled.connect(self.set_reminders_enabled) + self.snooze_action = menu.addAction('Remind me later') + self.snooze_action.triggered.connect(self.snooze) + intervals = menu.addMenu('Remind after') + self.interval_group = QActionGroup(self) + self.interval_group.setExclusive(True) + self.interval_actions = {} + for minutes in (5, 15, 30): + action = intervals.addAction(f'{minutes} minutes of unsaved curation') + action.setCheckable(True) + action.setChecked(minutes == self.interval_minutes) + self.interval_group.addAction(action) + action.triggered.connect(lambda checked, value=minutes: self.set_interval(value)) + self.interval_actions[minutes] = action + menu.addSeparator() + menu.addAction('Retry draft protection').triggered.connect(self.recovery.request_flush) + self.options.setMenu(menu) + + layout = QHBoxLayout(self) + layout.setContentsMargins(6, 0, 2, 0) + layout.setSpacing(8) + layout.addWidget(self.label) + layout.addWidget(self.save_button) + layout.addWidget(self.options) + # Reserve the same area before and after highlighting or changing status. + metrics = self.label.fontMetrics() + self.label.setFixedWidth( + max( + metrics.horizontalAdvance(f'{state} · Checkpoint 999 min ago') + for state in ( + 'Draft protected ✓', + 'Protecting draft…', + 'Protection failed', + 'Draft protection ready', + 'Draft needs attention', + 'Draft protection off', + 'Checkpoint failed', + ) + ) + + 8 + ) + self.save_button.setFixedWidth(self.save_button.sizeHint().width() + 8) + self.options.setFixedWidth(24) + self.setFixedWidth(self.sizeHint().width()) + gui._status_bar.addPermanentWidget(self) + self.recovery.changed.connect(self.refresh) + self._timer = QTimer(self) + self._timer.setInterval(1000) + self._timer.timeout.connect(self._tick) + self._timer.start() + QApplication.instance().installEventFilter(self) + + @connect(event='closed', sender=gui) + def on_closed(sender): + self.dispose() + + self._on_closed = on_closed + gui.destroyed.connect(self.dispose) + self.refresh() + + def eventFilter(self, receiver, event): + if not self._closed and event.type() in _INPUT_EVENTS: + inside = isinstance(receiver, QWidget) and ( + receiver is self.gui or self.gui.isAncestorOf(receiver) + ) + if isinstance(receiver, QWindow): + window = receiver + while window is not None: + if window is self.gui.windowHandle(): + inside = True + break + window = window.parent() + if inside: + self._last_input = self._clock() + return False + + def _tick(self): + self.refresh(read_dirty=False) + + def refresh(self, *, read_dirty=True): + if self._closed: + return + status = self.recovery.status + previous = self._highlighted + now = self._clock() + revision = status.get('current_revision', 0) + saved_at = _timestamp(status.get('last_checkpoint_at')) + saved_changed = saved_at != self._saved_at + if read_dirty or revision != self._observed_revision or saved_changed: + dirty = bool(self.controller.supervisor.is_dirty()) + if dirty and (self._dirty_since is None or saved_changed): + self._dirty_since = now + elif not dirty: + self._dirty_since = None + self._dirty = dirty + if saved_changed: + self._checkpoint_error = None + self._highlighted = False + self._observed_revision = revision + self._saved_at = saved_at + enabled = status.get('enabled', True) + state = status.get('state') + if not enabled or state in ('disabled', 'closed'): + protection = 'Draft protection off' + elif state == 'error' or status.get('error'): + protection = 'Protection failed' + elif status.get('warning') or status.get('startup_error'): + protection = 'Draft needs attention' + elif state == 'protected' and revision == status.get('protected_revision'): + protection = 'Draft protected ✓' + elif state in ('pending', 'saving') or revision != status.get('protected_revision'): + protection = 'Protecting draft…' + else: + protection = 'Draft protection ready' + if self._checkpoint_error: + protection = 'Checkpoint failed' + self.label.setText(f'{protection} · {_age_label(saved_at, self._wall_clock())}') + tooltip = ( + 'Draft protection preserves a recoverable working copy. Save checkpoint ' + 'commits validated curation for reopening and apply-curation. ' + 'Checkpoint reminders do not affect draft protection.' + ) + protected_at = _timestamp(status.get('last_protected_at')) + if protected_at is not None: + try: + stamp = ( + datetime.fromtimestamp(protected_at).astimezone().isoformat(timespec='seconds') + ) + except (OverflowError, OSError, ValueError): + stamp = str(protected_at) + tooltip += f' Last confirmed draft protection: {stamp}.' + error = ( + self._checkpoint_error + or status.get('error') + or status.get('startup_error') + or status.get('warning') + ) + if error: + tooltip += f' {str(error)[:2048]}' + self.label.setToolTip(tooltip) + self.save_button.setToolTip(tooltip + ' Save when you reach a useful stopping point.') + eligible = ( + self.reminders_enabled + and self._dirty + and self._dirty_since is not None + and now - self._dirty_since >= self.interval_minutes * 60 + and now >= self._snoozed_until + ) + if not eligible: + self._highlighted = False + elif now - self._last_input >= 1: + self._highlighted = True + if previous != self._highlighted: + self.save_button.setStyleSheet(_REMINDER if self._highlighted else _NORMAL) + self.save_button.setProperty('checkpointReminder', self._highlighted) + self.save_button.setAccessibleDescription( + 'Checkpoint reminder: save at a useful stopping point.' if self._highlighted else '' + ) + self.save_button.setEnabled(state != 'closed' and (self._dirty or saved_at is None)) + + def _save(self): + if self._closed: + return + try: + self.controller.supervisor.save() + except Exception as error: + self._checkpoint_error = str(error) + logger.warning('Checkpoint save failed: %s', error) + self.refresh() + + def _preferences(self): + self.gui.state['CheckpointReminder'] = { + 'enabled': self.reminders_enabled, + 'interval_minutes': self.interval_minutes, + } + + def set_reminders_enabled(self, enabled): + self.reminders_enabled = bool(enabled) + self.reminder_action.setChecked(self.reminders_enabled) + self._preferences() + self.refresh() + + def set_interval(self, minutes): + if minutes not in (5, 15, 30): + raise ValueError('Choose a 5, 15 or 30 minute checkpoint reminder interval.') + self.interval_minutes = minutes + self.interval_actions[minutes].setChecked(True) + self._preferences() + self.refresh() + + def snooze(self): + self._snoozed_until = self._clock() + self.interval_minutes * 60 + self.refresh() + + def dispose(self, *args): + if self._closed: + return + self._closed = True + unconnect(self._on_closed) + for cleanup in ( + self._timer.stop, + lambda: self.recovery.changed.disconnect(self.refresh), + lambda: QApplication.instance().removeEventFilter(self), + ): + with suppress(RuntimeError, TypeError): + cleanup() + + +def attach_checkpoint_status(controller, gui): + """Attach one status area to a bounded GUI after recovery is initialized.""" + widget = getattr(gui, '_checkpoint_status', None) + if widget is None: + widget = gui._checkpoint_status = CheckpointStatus(controller, gui) + return widget diff --git a/phy/apps/large_recording/refractory.py b/phy/apps/large_recording/refractory.py new file mode 100644 index 000000000..4160469f1 --- /dev/null +++ b/phy/apps/large_recording/refractory.py @@ -0,0 +1,213 @@ +"""Exact diagnostic refractory contamination, independent of display binning. + +The fixed contract follows phytastic reference 992b2588. Streaming keeps complete +close components across input boundaries; resource exhaustion never approximates. +""" + +import numpy as np + +from .live_summaries import _check_cancel + +VERSION = 1 +BIN_SECONDS = 1800.0 + + +class RefractoryUnavailable(ValueError): # noqa: N818 + """Required scientific evidence or exact-computation resources are unavailable.""" + + +def deduplicate(ticks, amplitudes, radius, cancel=None): + """Amplitude-priority suppression in O(n log n), stable on finite ties. + + Scores use float64 absolute raw amplitudes, as in the reference. Signed raw + values must remain available separately for membership predicates. + """ + t = np.asarray(ticks) + if np.asarray(amplitudes).dtype.kind not in 'fiu': + raise RefractoryUnavailable('Real numeric source amplitudes required.') + scores = np.abs(np.asarray(amplitudes, dtype=np.float64)) + if not np.isfinite(scores).all(): + raise RefractoryUnavailable('Nonfinite source amplitudes.') + keep = np.ones(len(t), dtype=bool) + boundaries = np.r_[0, np.flatnonzero(np.diff(t) > radius) + 1, len(t)] + starts, ends = boundaries[:-1], boundaries[1:] + pairs = starts[ends - starts == 2] + keep[np.where(scores[pairs + 1] > scores[pairs], pairs, pairs + 1)] = False + large = ends - starts > 2 + for start, end in zip(starts[large], ends[large]): + _check_cancel(cancel) + local = t[start:end] + blocked = np.zeros(end - start, dtype=bool) + chosen = np.zeros(end - start, dtype=bool) + for k, index in enumerate(np.argsort(-scores[start:end], kind='stable')): + if k % 4096 == 0: + _check_cancel(cancel) + if blocked[index]: + continue + chosen[index] = True + lo = np.searchsorted(local, local[index] - radius) + hi = np.searchsorted(local, local[index] + radius, side='right') + blocked[lo:hi] = True + keep[start:end] = chosen + return keep + + +def window_curve(violations, spikes, recorded_seconds, fs): + """Fixed centered six-hour windows every hour, including the padded endpoint.""" + n_bins = len(spikes) + centres = np.arange(0, n_bins + 1, 2) + lo, hi = np.clip(centres - 6, 0, n_bins), np.clip(centres + 6, 0, n_bins) + cv, cn, cr = (np.r_[0, np.cumsum(x)] for x in (violations, spikes, recorded_seconds)) + v, n, total = cv[hi] - cv[lo], cn[hi] - cn[lo], (cr[hi] - cr[lo]) * fs + tr, tc = round(1.0 * fs * 1e-3), round(0.3 * fs * 1e-3) + with np.errstate(invalid='ignore', divide='ignore'): + arg = 1 - v * (total - 2 * n * tc) / (n.astype(float) ** 2 * (tr - tc)) + contamination = np.where(arg < 0, 1.0, 1 - np.sqrt(np.maximum(arg, 0))) + return centres / 2, np.where(n >= 1000, contamination, np.nan) + + +class RefractoryGeometry: + """Validated scientific grid and immutable exposure shared by memberships.""" + + def __init__(self, fs, num_samples, valid_intervals): + self.fs, self.num_samples = float(fs), int(num_samples) + if not np.isfinite(self.fs) or self.fs <= 0: + raise RefractoryUnavailable('Unsupported sample rate.') + self.radius = round(0.3 * self.fs * 1e-3) + self.tr = round(1.0 * self.fs * 1e-3) + self.bin_samples = round(BIN_SECONDS * self.fs) + if not np.isfinite(fs) or self.radius < 0 or self.tr <= self.radius: + raise RefractoryUnavailable('Unsupported sample rate.') + if num_samples <= 0 or self.bin_samples <= 0: + raise RefractoryUnavailable('Recording duration unavailable.') + self.n_bins = (self.num_samples + self.bin_samples - 1) // self.bin_samples + if self.num_samples > np.iinfo(np.int64).max - self.tr or self.n_bins > 200000: + raise RefractoryUnavailable( + 'Scientific grid or sample arithmetic exceeds resource budget.' + ) + self.recorded = np.zeros(self.n_bins) + self.valid_intervals = tuple(tuple(interval) for interval in valid_intervals) + previous = 0 + for a, b in self.valid_intervals: + if not (0 <= previous <= a < b <= num_samples): + raise RefractoryUnavailable('Invalid recorded exposure intervals.') + for k in range( + int(a // self.bin_samples), + min((int(b) + self.bin_samples - 1) // self.bin_samples, self.n_bins), + ): + self.recorded[k] += max( + 0, min(b, (k + 1) * self.bin_samples) - max(a, k * self.bin_samples) + ) + previous = b + if not np.any(self.recorded): + raise RefractoryUnavailable('Recorded exposure unavailable.') + self.recorded /= self.fs + self.recorded.flags.writeable = False + + +class RefractoryAccumulator: + """Bounded streaming state for one globally monotonic current membership.""" + + def __init__(self, fs, num_samples, valid_intervals, max_component=1000000, *, geometry=None): + geometry = geometry or RefractoryGeometry(fs, num_samples, valid_intervals) + if ( + geometry.fs != fs + or geometry.num_samples != num_samples + or geometry.valid_intervals != tuple(tuple(interval) for interval in valid_intervals) + ): + raise ValueError('RP geometry does not match recording.') + for name in ('fs', 'num_samples', 'radius', 'tr', 'bin_samples', 'n_bins', 'recorded'): + setattr(self, name, getattr(geometry, name)) + self.spikes = np.zeros(self.n_bins, dtype=np.int64) + self.violations = np.zeros(self.n_bins, dtype=np.int64) + self.max_component = int(max_component) + self.ticks = np.empty(0, dtype=np.int64) + self.scores = np.empty(0) + self.partners = np.empty(0, dtype=np.int64) + self.removed = self.largest_component = 0 + self.last_tick = -1 + + def feed(self, ticks, amplitudes, cancel=None, final=False): + ticks, amplitudes = np.asarray(ticks), np.asarray(amplitudes) + if amplitudes.dtype.kind not in 'fiu': + raise RefractoryUnavailable('Real numeric source amplitudes required.') + if ticks.dtype.kind not in 'iu' or ticks.ndim != 1 or ticks.shape != amplitudes.shape: + raise RefractoryUnavailable('Integer ticks and scalar raw amplitudes required.') + if len(ticks) and (ticks.min() < 0 or ticks.max() > np.iinfo(np.int64).max): + raise RefractoryUnavailable('Source ticks outside signed int64 range.') + ticks = ticks.astype(np.int64, copy=False) + if len(ticks): + if ticks[0] < self.last_tick or np.any(np.diff(ticks) < 0): + raise RefractoryUnavailable('Source timestamps must be globally monotonic.') + if ticks[0] < 0 or ticks[-1] >= self.num_samples: + raise RefractoryUnavailable('Source timestamps outside recording.') + self.last_tick = int(ticks[-1]) + if not np.isfinite(amplitudes).all(): + raise RefractoryUnavailable('Nonfinite source amplitudes.') + t = np.concatenate((self.ticks, ticks)) + a = np.concatenate((self.scores, amplitudes)) + gaps = np.diff(t) + if not np.any(gaps <= self.radius): + # Isolated spikes cannot suppress one another. Keep the trailing + # spike pending until the next batch proves its component complete. + largest = int(bool(len(t))) + if largest > self.max_component: + raise RefractoryUnavailable('Exact duplicate component exceeds memory budget.') + stop = len(t) if final else max(0, len(t) - 1) + resolved = t[:stop] + else: + boundaries = np.r_[0, np.flatnonzero(gaps > self.radius) + 1, len(t)] + largest = int(np.max(np.diff(boundaries), initial=0)) + if largest > self.max_component: + raise RefractoryUnavailable('Exact duplicate component exceeds memory budget.') + stop = len(t) if final else int(boundaries[-2]) + keep = deduplicate(t[:stop], a[:stop], self.radius, cancel) + self.removed += int(np.count_nonzero(~keep)) + resolved = t[:stop][keep] + self.largest_component = max(self.largest_component, largest) + if len(resolved): + bins = resolved // self.bin_samples + starts = np.r_[0, np.flatnonzero(np.diff(bins)) + 1] + self.spikes[bins[starts]] += np.diff(np.r_[starts, len(bins)]) + self.ticks, self.scores = t[stop:].copy(), a[stop:].copy() + partners = np.concatenate((self.partners, resolved)) + # The first unresolved original tick bounds every future kept tick. + watermark = t[stop] if stop < len(t) else (self.num_samples + self.tr if final else -1) + done = len(partners) if final else np.searchsorted(partners, watermark - self.tr) + # Deduplication guarantees strictly more than radius between retained + # ticks. Only spikes with a successor inside tr can contribute a pair. + candidates = np.flatnonzero(np.diff(partners) <= self.tr) + candidates = candidates[candidates < done] + if len(candidates): + earlier = partners[candidates] + nv = np.searchsorted(partners, earlier + self.tr, side='right') - candidates - 1 + bins = earlier // self.bin_samples + starts = np.r_[0, np.flatnonzero(np.diff(bins)) + 1] + self.violations[bins[starts]] += np.add.reduceat(nv, starts) + self.partners = partners[done:].copy() + + def finish_counters(self, cancel=None): + """Resolve pending evidence without allocating display curves.""" + self.feed(np.empty(0, dtype=np.int64), np.empty(0), cancel, final=True) + result = { + 'status': 'ready', + 'duplicates_removed': self.removed, + 'spikes': self.spikes, + 'violations': self.violations, + 'largest_component': self.largest_component, + } + for value in result.values(): + if isinstance(value, np.ndarray): + value.flags.writeable = False + return result + + def finish(self, cancel=None): + """Return counters with exposure and the fixed diagnostic curve.""" + result = self.finish_counters(cancel) + centres, curve = window_curve(self.violations, self.spikes, self.recorded, self.fs) + for value in (centres, curve): + value.flags.writeable = False + result.update( + recorded_seconds=self.recorded, window_centres_h=centres, contamination=curve + ) + return result diff --git a/phy/apps/large_recording/refractory_engine.py b/phy/apps/large_recording/refractory_engine.py new file mode 100644 index 000000000..6ea2c88fb --- /dev/null +++ b/phy/apps/large_recording/refractory_engine.py @@ -0,0 +1,195 @@ +"""Worker-only demand scans and bounded timestamp-bearing acceleration.""" + +from collections import OrderedDict + +import numpy as np + +from .live_summaries import _check_cancel +from .refractory import VERSION, RefractoryAccumulator, RefractoryUnavailable +from .source import hash_json + + +def ancestors(expression): + if expression['kind'] == 'source': + return {expression['unit']} + if expression['kind'] == 'split': + return ancestors(expression['parent']) + return set().union(*(ancestors(p) for p in expression['parts'])) + + +class RefractoryEngine: + """Non-additive results; cached root rows retain original signed precision. + + The source lease is serialized with other recording I/O. Each reuse checks + the pinned reader signatures; only full content authentication creates trust. + Root rows are disposable and never alter the sorting or export membership. + """ + + def __init__( + self, source, root_bytes=268435456, result_bytes=8388608, component_budget=1000000 + ): + self.source = source + self.component_budget = component_budget + self.artifact_stamp = None + self.root_bytes, self.result_bytes = root_bytes, result_bytes + self.roots, self.results = OrderedDict(), OrderedDict() + self.last_path = None + m = source.manifest + self.binding = hash_json( + { + 'version': VERSION, + 'identity': m['source']['identity'], + 'revision': m['source']['revision'], + 'fs': m['sample_rate'], + 'num_samples': m['num_samples'], + 'intervals': m['valid_intervals'], + } + ) + + def key(self, expression): + return hash_json({'binding': self.binding, 'membership': expression}) + + @staticmethod + def _bytes(value): + return sum(v.nbytes for v in value.values() if isinstance(v, np.ndarray)) + + def _trim(self, cache, budget): + size = sum(self._bytes(v) for v in cache.values()) + while cache and (size > budget or len(cache) > 512): + _, value = cache.popitem(last=False) + size -= self._bytes(value) + + def resolve(self, expressions, cancel=None, progress=None): + from .refractory_store import resolve_prepared + + _check_cancel(cancel) + prepared = resolve_prepared(self, expressions, cancel, progress) + missing = {u: e for u, e in expressions.items() if u not in prepared} + if not missing: + return prepared + try: + prepared.update(self._resolve_source(missing, cancel, progress)) + except (OSError, ValueError) as error: + if not prepared: + raise + prepared.update({u: {'status': 'unavailable', 'message': str(error)} for u in missing}) + return prepared + + def _resolve_source(self, expressions, cancel=None, progress=None): + s, m = self.source, self.source.manifest + names = {'spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy'} + for e in expressions.values(): + names |= s._required(e) + if 'amplitudes.npy' not in m['source_array_inventory']: + raise RefractoryUnavailable('Raw source amplitudes unavailable.') + s._open(names, cancel, progress) + results, missing = {}, {} + for unit, expression in expressions.items(): + key = self.key(expression) + if key in self.results: + results[unit] = self.results[key] + self.results.move_to_end(key) + else: + missing[unit] = expression + if not missing: + self.last_path = 'result cache' + return results + required_roots = set().union(*(ancestors(e) for e in missing.values())) + accumulators = { + u: RefractoryAccumulator( + m['sample_rate'], + m['num_samples'], + m['valid_intervals'], + max_component=max(1, self.component_budget // len(missing)), + ) + for u in missing + } + cached = all( + root in self.roots and names <= self.roots[root].keys() for root in required_roots + ) + pending_roots, cache_size = {}, 0 + # Admit roots before scanning, using exact manifest counts. Oversized + # roots never transiently accumulate a recording-sized list of rows. + counts = dict(zip(m['unit_ids'], m['counts'], strict=True)) + row_bytes = sum(np.dtype(m['source_array_inventory'][n]['dtype']).itemsize for n in names) + admitted = set() + for root in sorted(required_roots): + cost = counts[root] * row_bytes + if cache_size + cost <= self.root_bytes: + admitted.add(root) + cache_size += cost + cache_size = 0 + if cached: + self.last_path = 'unit ticks' + rows = { + name: np.concatenate([self.roots[r][name] for r in sorted(required_roots)]) + for name in names + } + order = np.argsort(rows['spike_times.npy'], kind='stable') + rows = {n: v[order] for n, v in rows.items()} + total = len(order) + for r in required_roots: + self.roots.move_to_end(r) + else: + self.last_path = 'source scan' + total = m['num_spikes'] + rows = s.arrays + previous = -1 + unavailable = {} + for start in range(0, total, s._chunk_size(missing, 128)): + _check_cancel(cancel) + stop = min(start + s._chunk_size(missing, 128), total) + batch = {n: rows[n][start:stop].reshape(-1) for n in names} + ticks = batch['spike_times.npy'] + if ticks.dtype.kind not in 'iu' or ( + len(ticks) and (ticks.min() < 0 or ticks.max() > np.iinfo(np.int64).max) + ): + raise RefractoryUnavailable('Source timestamps exceed signed int64 range.') + ticks = ticks.astype(np.int64, copy=False) + batch['spike_times.npy'] = ticks + if len(ticks) and ( + ticks.dtype.kind not in 'iu' + or ticks[0] < previous + or np.any(np.diff(ticks) < 0) + or ticks[0] < 0 + or ticks[-1] >= m['num_samples'] + ): + raise RefractoryUnavailable('Source timestamps are not valid monotonic ticks.') + if len(ticks): + previous = int(ticks[-1]) + memo = {} + for unit, expression in missing.items(): + _check_cancel(cancel) + if unit in unavailable: + continue + try: + selected = s._mask(expression, batch, memo) + accumulators[unit].feed( + ticks[selected], batch['amplitudes.npy'][selected], cancel + ) + except ValueError as error: + unavailable[unit] = {'status': 'unavailable', 'message': str(error)} + if not cached and cache_size <= self.root_bytes: + for root in admitted: + selected = s._mask({'kind': 'source', 'unit': root}, batch, memo) + part = {n: v[selected].copy() for n, v in batch.items()} + cache_size += self._bytes(part) + pending_roots.setdefault(root, []).append(part) + if cache_size > self.root_bytes: + pending_roots.clear() + if progress: + progress(f'RP {self.last_path}', stop, total) + _check_cancel(cancel) + s._unchanged() + pending_results = {} + for unit, accumulator in accumulators.items(): + value = unavailable[unit] if unit in unavailable else accumulator.finish(cancel) + pending_results[self.key(missing[unit])] = value + results[unit] = value + _check_cancel(cancel) + self.results.update(pending_results) + for root, parts in pending_roots.items(): + self.roots[root] = {n: np.concatenate([p[n] for p in parts]) for n in names} + self._trim(self.roots, self.root_bytes) + self._trim(self.results, self.result_bytes) + return results diff --git a/phy/apps/large_recording/refractory_resources.py b/phy/apps/large_recording/refractory_resources.py new file mode 100644 index 000000000..c2096d267 --- /dev/null +++ b/phy/apps/large_recording/refractory_resources.py @@ -0,0 +1,133 @@ +"""Shared, allocation-based planning for exact RP counter builds.""" + +import json +from dataclasses import dataclass + +import numpy as np + +from .refractory import BIN_SECONDS, RefractoryUnavailable + +DEFAULT_RP_MAX_BYTES = 67108864 +DEFAULT_RP_MEMORY_BYTES = 67108864 +# Authentication reads 1 MiB blocks; allow the old and new block to coexist. +AUTH_BYTES = 2 * 1048576 +# Two NPY headers and ZIP entries fit within 1 KiB per unit. Catalog entries +# (IDs, filename, SHA256, status and scalar statistics) get another 1 KiB. +UNIT_ARCHIVE_BYTES = 1024 +UNIT_CATALOG_BYTES = 1024 +# Dictionaries, arrays, per-unit stream state and bounded partner tails. +UNIT_STATE_BYTES = 8192 +# Includes pending input copies, dedup sorting/masks and feed temporaries. +COMPONENT_ROW_BYTES = 256 + + +@dataclass(frozen=True) +class RefractoryBuildPlan: + """Algorithm allocation allowances; not a ceiling on total process RSS.""" + + units: int + bins: int + disk_bytes: int + fixed_bytes: int + component_bytes: int + max_component: int + batch_size: int + row_bytes: int + + @property + def memory_bytes(self): + return self.fixed_bytes + self.component_bytes + self.batch_size * self.row_bytes + + +def estimate_refractory_disk(manifest, bins): + """Bound the two int64 arrays, archive overhead and catalog, without curves.""" + units = len(manifest['unit_ids']) + # Include arbitrary source binding/exposure metadata rather than assuming + # a fixed number of acquisition intervals or a fixed source path length. + binding_bytes = len(json.dumps(manifest.get('source', {})).encode()) + binding_bytes += len(json.dumps(manifest['valid_intervals']).encode()) + catalog_bytes = 65536 + binding_bytes + units * UNIT_CATALOG_BYTES + if catalog_bytes > 16777216: + raise RefractoryUnavailable('RP catalog exceeds reader resource limit.') + return catalog_bytes + units * (16 * bins + UNIT_ARCHIVE_BYTES) + + +def plan_refractory_summaries( + manifest, + max_bytes=DEFAULT_RP_MAX_BYTES, + memory_bytes=DEFAULT_RP_MEMORY_BYTES, + batch_size=100000, + native_grid_bytes=0, + disk_option='--max-bytes', + memory_option='--memory-bytes', +): + """Validate geometry and budgets before allocating grids or scanning spikes. + + Counters and one shared exposure grid remain resident. Authentication and + serialization scratch are reserved alongside them. Remaining memory is split + between complete duplicate components and batch processing. A requested batch + size is an upper bound, never an additional independent memory allowance. + """ + if min(max_bytes, memory_bytes, batch_size) <= 0 or native_grid_bytes < 0: + raise ValueError('RP budgets and batch size must be positive.') + fs, samples = float(manifest['sample_rate']), int(manifest['num_samples']) + if not np.isfinite(fs) or fs <= 0: + raise RefractoryUnavailable('Unsupported RP sample rate.') + width, radius, tr = round(BIN_SECONDS * fs), round(0.0003 * fs), round(0.001 * fs) + if width <= 0 or tr <= radius: + raise RefractoryUnavailable('Unsupported RP sample rate.') + bins = (samples + width - 1) // width + if samples <= 0 or samples > np.iinfo(np.int64).max - tr or bins > 200000: + raise RefractoryUnavailable( + 'Scientific grid or sample arithmetic exceeds resource budget.' + ) + units = len(manifest['unit_ids']) + disk_bytes = estimate_refractory_disk(manifest, bins) + geometry = f'{units} units × {bins} bins' + if disk_bytes > max_bytes: + raise ValueError( + f'RP disk budget for {geometry}: need {disk_bytes} bytes, configured {max_bytes}; ' + f'increase {disk_option}.' + ) + inventory = manifest.get('source_array_inventory', {}) + names = ('spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy') + input_bytes = sum( + np.dtype(inventory.get(n, {}).get('dtype', 'float64')).itemsize for n in names + ) + row_bytes = max(256, 128 + 8 * input_bytes) + # np.savez uses at most a 16 MiB write buffer, or one counter array if smaller. + serialization_bytes = min(16 * 1048576, bins * 8) + 65536 + fixed_bytes = ( + units * (16 * bins + UNIT_STATE_BYTES) + + bins * 8 + # Geometry retains an outer tuple and one pair per acquisition interval; + # validating a shared geometry temporarily constructs a second copy. + + 128 * len(manifest['valid_intervals']) + # Binding/catalog serialization may be large even with few units/bins. + # Allow simultaneous encoded/string metadata and catalog bookkeeping. + + 4 * (disk_bytes - units * (16 * bins + UNIT_ARCHIVE_BYTES)) + + native_grid_bytes + + AUTH_BYTES + + serialization_bytes + ) + minimum = fixed_bytes + units * COMPONENT_ROW_BYTES + row_bytes + if minimum > memory_bytes: + raise ValueError( + f'RP memory budget for {geometry}: need at least {minimum} bytes, ' + f'configured {memory_bytes}; increase {memory_option}.' + ) + spare = memory_bytes - fixed_bytes + component_rows = max(units, (spare // 2) // COMPONENT_ROW_BYTES) + max_component = component_rows // max(1, units) + component_bytes = units * max_component * COMPONENT_ROW_BYTES + effective_batch = min(batch_size, (spare - component_bytes) // row_bytes) + return RefractoryBuildPlan( + units, + bins, + disk_bytes, + fixed_bytes, + component_bytes, + max_component, + effective_batch, + row_bytes, + ) diff --git a/phy/apps/large_recording/refractory_service.py b/phy/apps/large_recording/refractory_service.py new file mode 100644 index 000000000..cf40776fe --- /dev/null +++ b/phy/apps/large_recording/refractory_service.py @@ -0,0 +1,279 @@ +"""Selected-visible RP work with isolated, coalesced Qt delivery.""" + +import hashlib +from collections import OrderedDict +from concurrent.futures import CancelledError +from contextlib import suppress +from pathlib import Path +from queue import Full, Queue +from threading import Event, Thread +from time import monotonic + +import numpy as np + +from phy.gui.qt import QObject, Qt, QTimer, pyqtSignal +from phy.gui.tasks import heavy_io + +from .live_summaries import ( + _check_cancel, + _signature, + acquire_source_engine, + release_source_engine, +) +from .refractory import RefractoryAccumulator, RefractoryUnavailable +from .refractory_engine import RefractoryEngine +from .source import Source, hash_json + + +class _Delivery(QObject): + finished = pyqtSignal(object) + progress = pyqtSignal(object) + + +class _Worker: + def __init__(self, path, bounded, source_path, delivery): + self.path, self.bounded, self.source_path = path, bounded, source_path + self.delivery = delivery + self.stopped = Event() + self.jobs = Queue(maxsize=1) + self.thread = Thread(target=self.run, daemon=True) + self.thread.start() + + def stop(self): + self.stopped.set() + with suppress(Full): + self.jobs.put_nowait(None) + + def run(self): + lease = engine = source = None + signatures, cache = {}, OrderedDict() + try: + while not self.stopped.is_set(): + job = self.jobs.get() + if job is None: + break + payload, cancel = job + error, results = None, {} + last_progress = [0.0] + + def cancelled(cancel=cancel): + return self.stopped.is_set() or cancel.is_set() + + def check(): + _check_cancel(cancelled) + + def progress(phase, done, total, cancel=cancel, last_progress=last_progress): + now = monotonic() + if now - last_progress[0] >= 0.25 or done == total: + last_progress[0] = now + self.delivery.progress.emit((cancel, phase, done, total)) + + try: + with heavy_io( + check, waiting=lambda: progress('waiting for recording I/O', 0, 0) + ): + check() + if self.bounded: + if engine is None: + lease, reader = acquire_source_engine(self.path, self.source_path) + engine = RefractoryEngine(reader) + results = engine.resolve(payload, cancelled, progress) + else: + if source is None: + source = Source( + self.path / 'params.py', cancel=cancelled, progress=progress + ) + names = ['spike_times.npy', 'amplitudes.npy', 'params.py'] + names += [ + n + for n in ( + '_phy_spikes_subset.manifest.json', + 'timestamps.json', + ) + if (self.path / n).exists() + ] + signatures = {n: _signature((self.path / n).stat()) for n in names} + + def unchanged(signatures=signatures): + if any( + _signature((self.path / n).stat()) != sig + for n, sig in signatures.items() + ): + raise ValueError( + 'Original timing, amplitudes or exposure changed; reopen the view.' + ) + + unchanged() + pending_cache = {} + for unit, ids in payload.items(): + check() + # Worker-only canonicalization; membership arrays are frozen snapshots. + digest = hashlib.sha256() + for start in range(0, len(ids), 100000): + check() + digest.update( + memoryview( + np.ascontiguousarray(ids[start : start + 100000]) + ).cast('B') + ) + key = hash_json( + { + 'rows': digest.hexdigest(), + 'dtype': str(ids.dtype), + 'count': len(ids), + 'source': source.identity['sha256'], + } + ) + if key in cache: + value = cache[key] + else: + try: + if 'amplitudes.npy' not in source.arrays: + raise RefractoryUnavailable( + 'Raw source amplitudes unavailable.' + ) + acc = RefractoryAccumulator( + source.sample_rate, + source.num_samples, + source.valid_intervals, + ) + for start in range(0, len(ids), 100000): + check() + rows = ids[start : start + 100000] + acc.feed( + source.arrays['spike_times.npy'].reshape(-1)[rows], + source.arrays['amplitudes.npy'].reshape(-1)[rows], + cancelled, + ) + value = acc.finish(cancelled) + except RefractoryUnavailable as exc: + value = {'status': 'unavailable', 'message': str(exc)} + pending_cache[key] = value + results[unit] = value + unchanged() + check() + cache.update(pending_cache) + while ( + len(cache) > 128 + or sum( + v.nbytes + for r in cache.values() + for v in r.values() + if isinstance(v, np.ndarray) + ) + > 8388608 + ): + cache.popitem(last=False) + check() + except Exception as exc: + error = exc + results = {} + if not isinstance(exc, CancelledError): + cache.clear() + self.delivery.finished.emit((cancel, results, error)) + finally: + if lease is not None: + release_source_engine(lease) + if source is not None: + source.close() + + +class RefractoryService(QObject): + """One current demand, one cancellable job; no session/model reaches workers.""" + + changed = pyqtSignal() + + def __init__(self, controller): + super().__init__() + self.controller = controller + self.results, self.message = {}, 'Select a unit.' + self._token = self._payload = self._running = self._worker = None + self._membership_references = () + self._closed = False + self._delivery = _Delivery() + self._delivery.finished.connect(self._completed, Qt.QueuedConnection) + self._delivery.progress.connect(self._progress, Qt.QueuedConnection) + self._timer = QTimer(self) + self._timer.setSingleShot(True) + self._timer.timeout.connect(self._start) + + def request(self, ids, enabled=True): + if self._closed: + return + ids = tuple(ids) if enabled else () + session = getattr(self.controller, 'bounded_session', None) + if session is not None: + payload = ( + session.membership_snapshot(ids) if hasattr(session, 'membership_snapshot') else {} + ) + references = tuple(payload.values()) + else: + supervisor = getattr(self.controller, 'supervisor', None) + payload = ( + supervisor.clustering.membership_snapshot(ids) if supervisor is not None else {} + ) + references = tuple(supervisor.clustering.spikes_per_cluster[u] for u in payload) + token = (ids, tuple((u, id(value)) for u, value in zip(payload, references, strict=True))) + if token == self._token: + return + self._token, self._payload = token, payload + self._membership_references = references + self.results = {} + self.message = ( + 'RP pending: validating original evidence.' + if payload + else ('Select a unit.' if not ids else 'RP evidence unavailable.') + ) + if self._running is not None: + self._running.set() + self._timer.start(0) + + def _start(self): + if self._closed or self._running is not None or not self._payload: + return + path = getattr(self.controller, 'dir_path', None) + if path is None: + self.message = 'RP evidence unavailable: original source path missing.' + self.changed.emit() + return + if self._worker is None: + session = getattr(self.controller, 'bounded_session', None) + summary = getattr(self.controller, '_live_summaries', None) + self._worker = _Worker( + Path(path), + session is not None, + getattr(summary, '_source_path', None), + self._delivery, + ) + self._running = Event() + self._worker.jobs.put_nowait((self._payload, self._running)) + + def _completed(self, delivery): + cancel, results, error = delivery + if self._closed or cancel is not self._running: + return + self._running = None + if cancel.is_set(): + self._timer.start(0) + return + self.results = results if error is None else {} + self.message = f'RP unavailable: {error}' if error is not None else '' + self.changed.emit() + + def _progress(self, delivery): + cancel, phase, done, total = delivery + if self._closed or cancel is not self._running or cancel.is_set(): + return + self.message = f'RP {phase}' + (f' ({done / total:.0%})' if total else '') + self.changed.emit() + + def close(self): + self._closed = True + self._timer.stop() + self.results.clear() + self._payload = None + self._membership_references = () + if self._running is not None: + self._running.set() + if self._worker is not None: + self._worker.stop() diff --git a/phy/apps/large_recording/refractory_store.py b/phy/apps/large_recording/refractory_store.py new file mode 100644 index 000000000..00c54bb14 --- /dev/null +++ b/phy/apps/large_recording/refractory_store.py @@ -0,0 +1,410 @@ +"""Optional exact RP artifacts, bound to an authenticated prepared snapshot.""" + +import hashlib +import json +import os +import shutil +import tempfile +from collections import OrderedDict +from io import BytesIO +from pathlib import Path + +import numpy as np + +from .live_summaries import LiveSummaryEngine, _check_cancel, _signature +from .refractory import ( + BIN_SECONDS, + VERSION, + RefractoryAccumulator, + RefractoryGeometry, + RefractoryUnavailable, + window_curve, +) +from .refractory_resources import ( + DEFAULT_RP_MAX_BYTES, + DEFAULT_RP_MEMORY_BYTES, + estimate_refractory_disk, + plan_refractory_summaries, +) +from .source import hash_file, hash_json, publish_directory +from .summary_store import ( + StoreIntegrityError, + SummaryStore, + _atomic_json, + _attachment_lock, + summary_store_reference, +) + +REFERENCE = 'refractory-summaries.json' + + +def refractory_binding(source): + """Include scientific parameters as well as source identity and assignments.""" + m = source.manifest + return { + 'algorithm': VERSION, + 'bin_seconds': BIN_SECONDS, + 'identity': m['source']['identity'], + 'revision': m['source']['revision'], + 'sample_rate': m['sample_rate'], + 'num_samples': m['num_samples'], + 'valid_intervals': m['valid_intervals'], + } + + +def estimate_refractory_summaries(source): + """Conservative disk bound, including per-unit array headers and metadata.""" + m = source.manifest + samples = round(BIN_SECONDS * m['sample_rate']) + if samples <= 0: + raise RefractoryUnavailable('Unsupported RP sample rate.') + bins = (m['num_samples'] + samples - 1) // samples + return estimate_refractory_disk(m, bins) + + +def _prepare_counters(source, plan, geometry, cancel, progress): + m = source.manifest + names = {'spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy'} + if 'amplitudes.npy' not in m['source_array_inventory']: + raise RefractoryUnavailable('Raw source amplitudes unavailable.') + source._open(names, cancel, progress) + accumulators = { + u: RefractoryAccumulator( + m['sample_rate'], + m['num_samples'], + m['valid_intervals'], + max_component=plan.max_component, + geometry=geometry, + ) + for u in m['unit_ids'] + } + unavailable = {} + chunk = plan.batch_size + for start in range(0, m['num_spikes'], chunk): + _check_cancel(cancel) + stop = min(start + chunk, m['num_spikes']) + ticks, labels, amplitudes = ( + source.arrays[n][start:stop].reshape(-1) + for n in ('spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy') + ) + # Group each source batch once, instead of scanning it once per unit. + order = np.argsort(labels, kind='stable') + sorted_labels = labels[order] + boundaries = np.r_[0, np.flatnonzero(np.diff(sorted_labels)) + 1, len(order)] + for first, last in zip(boundaries[:-1], boundaries[1:]): + _check_cancel(cancel) + unit = int(sorted_labels[first]) + if unit in unavailable: + continue + selected = order[first:last] + try: + accumulators[unit].feed(ticks[selected], amplitudes[selected], cancel) + except RefractoryUnavailable as error: + unavailable[unit] = {'status': 'unavailable', 'message': str(error)} + del accumulators[unit] + if progress: + progress('preparing RP summaries', stop, m['num_spikes']) + source._unchanged() + for unit in m['unit_ids']: + _check_cancel(cancel) + if unit in unavailable: + yield unit, unavailable.pop(unit) + else: + acc = accumulators.pop(unit) + yield unit, acc.finish_counters(cancel) + + +def build_refractory_summaries( + package_path, + source_dir=None, + max_bytes=DEFAULT_RP_MAX_BYTES, + memory_bytes=DEFAULT_RP_MEMORY_BYTES, + batch_size=100000, + cancel=None, + progress=None, +): + """Publish original-unit counters atomically, independently of row stores. + + A single authenticated source scan maintains complete close components for + every original unit. One plan covers counters, shared exposure, unresolved + components, source batches and serialization. No display curves are built. + Existing artifacts are never overwritten. The package survives failure. + """ + output = Path(package_path) / '.phy' / 'refractory-summaries' + if output.exists(): + raise ValueError(f'RP summaries already exist: {output}.') + if min(max_bytes, memory_bytes, batch_size) <= 0: + raise ValueError('RP budgets must be positive.') + with LiveSummaryEngine( + package_path, + source_dir=source_dir, + batch_size=batch_size, + max_bytes=memory_bytes, + ) as source: + m = source.manifest + plan = plan_refractory_summaries( + m, + max_bytes, + memory_bytes, + batch_size, + native_grid_bytes=source.edges.nbytes + source.exposure.nbytes, + ) + geometry = RefractoryGeometry(m['sample_rate'], m['num_samples'], m['valid_intervals']) + if progress: + progress( + f'RP plan: {plan.units} units × {plan.bins} bins; ' + f'disk <= {plan.disk_bytes} bytes; allocations <= {plan.memory_bytes} bytes; ' + f'batch {plan.batch_size}', + 0, + m['num_spikes'], + ) + output.parent.mkdir(parents=True, exist_ok=True) + if shutil.disk_usage(output.parent).free < plan.disk_bytes: + raise OSError(f'RP summaries need {plan.disk_bytes} bytes of free disk space.') + temporary = Path(tempfile.mkdtemp(prefix='.rp-building-', dir=output.parent)) + try: + results = _prepare_counters(source, plan, geometry, cancel, progress) + catalog = {'binding': refractory_binding(source), 'units': {}} + for index, (unit, result) in enumerate(results): + _check_cancel(cancel) + arrays = {k: v for k, v in result.items() if k in ('spikes', 'violations')} + item = {k: v for k, v in result.items() if not isinstance(v, np.ndarray)} + if arrays: + filename = f'{index}.npz' + with (temporary / filename).open('wb') as stream: + np.savez(stream, **arrays) + stream.flush() + os.fsync(stream.fileno()) + item.update(file=filename, sha256=hash_file(temporary / filename)) + catalog['units'][str(unit)] = item + _atomic_json(temporary / 'index.json', catalog) + if sum(p.stat().st_size for p in temporary.iterdir()) > max_bytes: + raise ValueError('RP summaries exceed disk budget.') + _check_cancel(cancel) + lock = output.parent / 'rp-summary-publication' + lock.mkdir(exist_ok=True) + with _attachment_lock(lock, lambda: _check_cancel(cancel)): + if output.exists(): + raise ValueError(f'RP summaries already exist: {output}.') + # Pin before publication: interruption can leave a dangling + # reference, but never an unattachable completed directory. + _atomic_json( + output.parent / REFERENCE, + {'index_sha256': hash_json(catalog)}, + ) + publish_directory(temporary, output) + finally: + if temporary.exists(): + shutil.rmtree(temporary) + return output + + +def _counters(source, expressions, cancel, result_bytes=8388608): + path = source.path / '.phy' + reference = path / REFERENCE + if not reference.exists(): + return {} + catalog_path = path / 'refractory-summaries' / 'index.json' + if reference.stat().st_size > 65536 or catalog_path.stat().st_size > 16777216: + raise StoreIntegrityError('RP catalog exceeds limit.') + reference_bytes = reference.read_bytes() + catalog = json.loads(catalog_path.read_bytes()) + if hash_json(catalog) != json.loads(reference_bytes)['index_sha256'] or catalog[ + 'binding' + ] != refractory_binding(source): + raise StoreIntegrityError('RP summary binding mismatch.') + originals = {u: e for u, e in expressions.items() if e['kind'] == 'source'} + if _result_bytes(source, len(originals)) > result_bytes: + return { + u: {'status': 'unavailable', 'message': 'RP result grids exceed memory budget.'} + for u in originals + } + results = {} + recorded = None + for unit, expression in expressions.items(): + _check_cancel(cancel) + if expression['kind'] != 'source': + continue + item = catalog['units'][str(expression['unit'])] + result = {k: v for k, v in item.items() if k not in ('file', 'sha256')} + if 'file' in item: + filename = item['file'] + if Path(filename).name != filename: + raise StoreIntegrityError('Invalid RP array path.') + with (catalog_path.parent / filename).open('rb') as stream: + raw = stream.read(16777217) + if len(raw) > 16777216: + raise StoreIntegrityError('RP unit arrays exceed limit.') + if hashlib.sha256(raw).hexdigest() != item['sha256']: + raise StoreIntegrityError('RP summary checksum mismatch.') + with np.load(BytesIO(raw), allow_pickle=False) as data: + result.update({k: data[k] for k in data.files}) + if recorded is None: + m = source.manifest + recorded = RefractoryGeometry( + m['sample_rate'], m['num_samples'], m['valid_intervals'] + ).recorded + centres, curve = window_curve( + result['violations'], result['spikes'], recorded, source.manifest['sample_rate'] + ) + result.update(recorded_seconds=recorded, window_centres_h=centres, contamination=curve) + for value in result.values(): + if isinstance(value, np.ndarray): + value.flags.writeable = False + results[unit] = result + _check_cancel(cancel) + if reference.read_bytes() != reference_bytes: + raise StoreIntegrityError('RP summary reference changed while reading.') + return results + + +def _unit_batches(store, source, root, batch_size, cancel): + previous = -1 + for rows in store.batches(root, batch_size, cancel): + bins = rows['bin'].astype(np.int64) + if np.any(bins < 0) or np.any(bins >= source.bins): + raise StoreIntegrityError('Timestamp bin outside native grid.') + offsets = rows['tick_offset'] + if np.any(offsets >= (source.edges[bins + 1] - source.edges[bins]).astype(np.uint64)): + raise StoreIntegrityError('Timestamp offset outside native bin.') + ticks = source.edges[bins] + offsets.astype(np.int64) + if len(ticks) and (ticks[0] < previous or np.any(np.diff(ticks) < 0)): + raise StoreIntegrityError('Timestamp rows must be monotonic.') + if len(ticks): + previous = int(ticks[-1]) + yield { + 'spike_times.npy': ticks, + 'spike_clusters.npy': np.full(len(rows), root, dtype=np.int64), + 'amplitudes.npy': rows['amplitude'], + } + + +def _chronological(store, source, roots, cancel): + """Merge ordered unit chunks using watermarks; scratch never scales with spikes.""" + roots = sorted(roots) + # Account for buffers, packed arrays, masks, sort indices and feed scratch. + if len(roots) * 512 > source.max_bytes: + raise RefractoryUnavailable('RP ancestor streams exceed memory budget.') + batch_size = min(source.batch_size, max(1, source.max_bytes // (512 * len(roots)))) + streams = [_unit_batches(store, source, r, batch_size, cancel) for r in roots] + active = {i: next(stream, None) for i, stream in enumerate(streams)} + active = {i: b for i, b in active.items() if b is not None} + while active: + _check_cancel(cancel) + watermark = min(b['spike_times.npy'][-1] for b in active.values()) + parts = [] + for i, batch in list(active.items()): + stop = np.searchsorted(batch['spike_times.npy'], watermark, side='right') + if stop: + parts.append({k: v[:stop] for k, v in batch.items()}) + if stop == len(batch['spike_times.npy']): + following = next(streams[i], None) + if following is None: + del active[i] + else: + active[i] = following + else: + active[i] = {k: v[stop:] for k, v in batch.items()} + batch = {k: np.concatenate([p[k] for p in parts]) for k in parts[0]} + order = np.argsort(batch['spike_times.npy'], kind='stable') + yield {k: v[order] for k, v in batch.items()} + + +def _result_bytes(source, units): + m = source.manifest + samples = round(BIN_SECONDS * m['sample_rate']) + if samples <= 0: + raise RefractoryUnavailable('Unsupported RP sample rate.') + bins = (m['num_samples'] + samples - 1) // samples + return units * (4096 + bins * 40) + + +def resolve_prepared(engine, expressions, cancel, progress): + """Try verified snapshot evidence before any source open/stat/hash operation.""" + from .refractory_engine import ancestors + + source = engine.source + results = {} + try: + results = _counters(source, expressions, cancel, engine.result_bytes) + if results: + engine.last_path = 'prepared RP counters' + except (OSError, ValueError, KeyError, TypeError): + pass # Authenticated source fallback remains available. + remaining = {u: e for u, e in expressions.items() if u not in results} + supported = { + u: e for u, e in remaining.items() if not source._required(e) - {'amplitudes.npy'} + } + if not supported or summary_store_reference(source.path, allow_invalid=True) is None: + return results + try: + reference = summary_store_reference(source.path) + with SummaryStore(source) as store: + if not store.timestamps or 'amplitude' not in store.dtype.names: + return results + if ( + _result_bytes(source, len(supported)) + + sum(engine._bytes(value) for value in results.values()) + > engine.result_bytes + ): + results.update( + { + u: { + 'status': 'unavailable', + 'message': 'RP result grids exceed memory budget.', + } + for u in supported + } + ) + return results + stamp = ( + reference, + hash_json(store.index), + _signature(store.signature), + _signature(store.path_signature), + ) + if stamp != engine.artifact_stamp: + engine.prepared_results = OrderedDict() + engine.artifact_stamp = stamp + pending = {} + for unit, expression in supported.items(): + _check_cancel(cancel) + key = engine.key(expression) + if key in engine.prepared_results: + pending[unit] = engine.prepared_results[key] + continue + m = source.manifest + acc = RefractoryAccumulator( + m['sample_rate'], m['num_samples'], m['valid_intervals'] + ) + error = None + for batch in _chronological(store, source, ancestors(expression), cancel): + if error is None: + try: + mask = source._mask(expression, batch) + acc.feed( + batch['spike_times.npy'][mask], + batch['amplitudes.npy'][mask], + cancel, + ) + except RefractoryUnavailable as exc: + error = {'status': 'unavailable', 'message': str(exc)} + if progress: + progress('RP prepared timestamp rows', 0, None) + pending[unit] = error if error else acc.finish(cancel) + _check_cancel(cancel) + # Recheck attachment and signatures even for a cached result. + if ( + summary_store_reference(source.path) != stamp[0] + or _signature(os.fstat(store.stream.fileno())) != stamp[2] + or _signature((store.path / 'data.bin').stat()) != stamp[3] + ): + raise StoreIntegrityError('RP timestamp snapshot changed while reading.') + for unit, value in pending.items(): + engine.prepared_results[engine.key(supported[unit])] = value + engine._trim(engine.prepared_results, engine.result_bytes) + results.update(pending) + engine.last_path = 'prepared timestamp rows' + except (OSError, ValueError, KeyError, TypeError): + engine.artifact_stamp = None + return results diff --git a/phy/apps/large_recording/replay.py b/phy/apps/large_recording/replay.py new file mode 100644 index 000000000..9385b2920 --- /dev/null +++ b/phy/apps/large_recording/replay.py @@ -0,0 +1,312 @@ +"""Stream semantic curation into a new complete sorting, never the source.""" + +import os +import shutil +import tempfile +from pathlib import Path + +import numpy as np + +from .curation import ( + BoundedSession, + _digest, + _fsync_directory, + _write_json, + interpret_events, + project_assignments, +) +from .file_copy import copy_source_file +from .metadata import complete_schema, write_metadata +from .parameters import rewrite_replay_params_bytes +from .replay_program import AssignmentProgram +from .source import PER_SPIKE, Source, _has_raw_paths, close_array, hash_file, publish_directory +from .streaming import UnitRows, bounded_map, check_cancel, worker_count + + +def _merge_mapping(unit_ids, events): + """Resolve a whole-unit merge journal once, independently of spike count.""" + lineage = {int(unit): [int(unit)] for unit in unit_ids} + for event in events: + if event['operation'] == 'merge': + members = [] + for parent in event['parents']: + members.extend(lineage.pop(parent)) + lineage[event['target']] = members + mapping = {old: new for new, members in lineage.items() for old in members} + keys = np.array(sorted(mapping), dtype=np.int64) + targets = np.array([mapping[int(key)] for key in keys], dtype=np.int64) + return keys, targets + + +def _write_metadata(path, metadata, schema=None): + return write_metadata(path, metadata, schema or {'version': 1, 'tables': []}) + + +def apply_curation( + source_params, + bounded_dir, + output_dir, + batch_size=100000, + workers=1, + cancel=None, + progress=None, +): + """Validate identity/revision and replay only the last committed generation. + + The output is published as one new directory after validation. Full source + arrays remain file-backed; only one assignment batch and the unit map reside + in memory. Arbitrary selected-row splits have no journal interpretation. + """ + worker_count(workers) + check_cancel(cancel) + session = BoundedSession(bounded_dir) + source = None + try: + if session.checkpoint_path is None: + raise ValueError('Save a bounded semantic checkpoint before applying curation.') + manifest = session.manifest + source = Source( + source_params, + duration_seconds=manifest['num_samples'] / manifest['sample_rate'], + valid_intervals=manifest['valid_intervals'], + batch_size=batch_size, + workers=workers, + cancel=cancel, + progress=progress, + ) + return _apply_curation(source, session, output_dir, batch_size, workers, cancel, progress) + finally: + if source is not None: + source.close() + session.close() + + +def _apply_curation( + source, session, output_dir, batch_size, workers=1, cancel=None, progress=None +): + session.validate_proposition_documents() + manifest = session.manifest + if 'metadata_schema' in manifest and source.metadata_schema != manifest['metadata_schema']: + raise ValueError('Source metadata schema changed since bounded preparation.') + if ( + 'metadata_provenance' in manifest + and source.metadata_provenance != manifest['metadata_provenance'] + ): + raise ValueError('Source metadata provenance changed since bounded preparation.') + expected = manifest['source'] + if source.identity != expected['identity']: + raise ValueError('Source coordinate/feature identity does not match bounded preparation.') + if source.revision != expected['revision']: + raise ValueError('Source assignment revision does not match journal parent revision.') + if source.metadata != session.base_metadata: + raise ValueError('Bounded base metadata does not match the source metadata revision.') + if ( + source.unit_ids.tolist() != manifest['unit_ids'] + or source.n_spikes != manifest['num_spikes'] + ): + raise ValueError('Source catalog or spike count does not match bounded preparation.') + for name, item in session.proposition_documents.items(): + if hash_file(source.path / name) != item['sha256']: + raise ValueError('Source proposition documents changed since preparation.') + # Identity/revision bind the complete source. Validate the actual projection + # too, so a tampered bounded base cannot silently replay unrelated evidence. + source_assignments = source.arrays['spike_clusters.npy'].reshape(-1) + for start in range(0, len(session.global_ids), batch_size): + rows = session.global_ids[start : start + batch_size] + if not np.array_equal( + source_assignments[rows], + session.base_assignments[start : start + batch_size], + ): + raise ValueError('Immutable bounded assignments do not match source rows.') + for name in sorted(source.arrays.keys() & (PER_SPIKE - {'spike_clusters.npy'})): + bounded = np.load(session.path / name, mmap_mode='r', allow_pickle=False) + try: + if bounded.shape != (len(session.global_ids), *source.arrays[name].shape[1:]): + raise ValueError(f'Bounded attribute has invalid source alignment: {name}.') + for start in range(0, len(session.global_ids), batch_size): + rows = session.global_ids[start : start + batch_size] + if not np.array_equal( + source.arrays[name][rows], + bounded[start : start + batch_size], + equal_nan=True, + ): + raise ValueError(f'Bounded attribute does not match source rows: {name}.') + finally: + close_array(bounded) + active_units, metadata, _ = interpret_events( + source.unit_ids, session.base_metadata, session.events + ) + output = Path(output_dir).resolve() + if output.exists(): + raise FileExistsError(f'Curated output already exists: {output}.') + if output == source.path or source.path in output.parents: + raise ValueError('Curated output must be outside the immutable source directory.') + output.parent.mkdir(parents=True, exist_ok=True) + # Unchanged files may clone without allocating their payload. Each fallback + # checks its full copy cost while retaining this assignment/header reserve. + estimated_bytes = source.n_spikes * 8 + 1024 * 1024 + free = shutil.disk_usage(output.parent).free + if free < estimated_bytes: + raise OSError( + f'Insufficient disk space for full replay: estimated at least {estimated_bytes:,} bytes, {free:,} available.' + ) + stage = Path(tempfile.mkdtemp(prefix=f'.{output.name}-', dir=output.parent)) + curated = None + assignments = None + try: + # Copy only validated canonical assets, not GUI caches or producer reviews. + copied = 0 + copy_bytes = sum( + (source.path / name).stat().st_size + for name in source.arrays + if name != 'spike_clusters.npy' + ) + for name in source.arrays: + check_cancel(cancel) + if name != 'spike_clusters.npy': + copy_source_file(source.path / name, stage / name, estimated_bytes) + copied += (source.path / name).stat().st_size + if progress: + progress('copying source files', copied, copy_bytes) + shutil.copyfile(source.params_path, stage / 'params.py') + upstream_manifest = source.path / '_phy_spikes_subset.manifest.json' + if upstream_manifest.exists(): + shutil.copyfile(upstream_manifest, stage / upstream_manifest.name) + if source.time_base is not None and source.timestamps_path.exists(): + shutil.copyfile(source.timestamps_path, stage / 'timestamps.json') + # Preserve source params semantics and make external raw paths absolute. + # The full export can contain no raw traces; immutable array rows suffice. + dat_path = source.params.get('dat_path') + if _has_raw_paths(dat_path): + raw_paths = dat_path if isinstance(dat_path, (list, tuple)) else [dat_path] + resolved = [ + str((source.path / raw).resolve()) if _has_raw_paths(raw) else raw + for raw in raw_paths + ] + dat_path = resolved if isinstance(dat_path, (list, tuple)) else resolved[0] + params_path = stage / 'params.py' + params_path.write_bytes( + rewrite_replay_params_bytes( + params_path.read_bytes(), + num_samples=source.num_samples, + valid_intervals=source.valid_intervals.tolist(), + dat_path=dat_path, + ) + ) + assignments = np.lib.format.open_memmap( + stage / 'spike_clusters.npy', + mode='w+', + dtype=np.int64, + shape=source.arrays['spike_clusters.npy'].shape, + ) + flat = assignments.reshape(-1) + has_split = any( + event['operation'] in ('threshold_split', 'restore_parents') + for event in session.events + ) + keys, targets = ( + (None, None) if has_split else _merge_mapping(source.unit_ids, session.events) + ) + lookup = UnitRows(keys) if keys is not None else None + program = AssignmentProgram(source.unit_ids, session.events) if has_split else None + + def project(batch): + check_cancel(cancel) + values = batch['spike_clusters.npy'] + projected = program.project(values, batch) if has_split else targets[lookup(values)] + return batch['start'], batch['stop'], projected + + for start, stop, projected in bounded_map(project, source.iter_batches(), workers): + check_cancel(cancel) + flat[start:stop] = projected + if progress: + progress('replaying assignments', stop, source.n_spikes) + assignments.flush() + assignments._mmap.close() + del flat, assignments + assignments = None + _write_metadata(stage, metadata, complete_schema(source.metadata_schema, metadata)) + _write_json(stage / '_phy_curation_journal.json', session.events) + proposition_hashes = {} + item = session.proposition_documents.get('curation.json') + if item is not None: + shutil.copyfile(session.path / item['filename'], stage / 'curation.json') + proposition_hashes['curation.json'] = hash_file(stage / 'curation.json') + if proposition_hashes['curation.json'] != item['sha256']: + raise ValueError('Producer propositions changed during replay.') + review = session.extra_documents.get('curation_review.json') + if review is not None and item is not None: + _write_json(stage / 'curation_review.json', review) + proposition_hashes['curation_review.json'] = hash_file(stage / 'curation_review.json') + # Re-reading verifies alignment, full catalog and immutable byte digests. + curated = Source( + stage / 'params.py', + batch_size=batch_size, + workers=workers, + cancel=cancel, + progress=progress, + ) + if curated.identity != source.identity or curated.n_spikes != source.n_spikes: + raise ValueError('Curated output changed immutable source coordinates.') + if curated.metadata != metadata: + raise ValueError('Curated output metadata failed exact round-trip validation.') + actual = curated.arrays['spike_clusters.npy'].reshape(-1) + + def verify(batch): + check_cancel(cancel) + start, stop = batch['start'], batch['stop'] + # Keep the sequential reference independent of the compiled writer. + # This validation is intentionally not replaced by a second call to + # the new compiler. Merge-only journals retain their existing fast map. + expected_batch = ( + project_assignments(batch['spike_clusters.npy'], session.events, batch) + if has_split + else targets[lookup(batch['spike_clusters.npy'])] + ) + if not np.array_equal(actual[start:stop], expected_batch): + raise ValueError('Curated output assignments failed semantic replay verification.') + return stop + + for stop in bounded_map(verify, source.iter_batches(), workers): + if progress: + progress('verifying replay', stop, source.n_spikes) + _write_json( + stage / '_phy_curation_lineage.json', + { + 'format': 'phy_curation_lineage', + 'format_version': 1, + 'coordinate_identity': source.identity, + 'parent_revision': source.revision, + 'journal_sha256': _digest(session.events), + 'revision': curated.revision, + 'preparation_sha256': _digest(manifest), + 'next_cluster_id': session.next_cluster_id, + 'unit_ids': sorted(active_units), + 'retired_units': session.retired_units, + 'proposition_documents': proposition_hashes, + 'metadata_provenance': session.metadata_provenance, + 'metadata_policy': session.metadata_policy, + }, + ) + curated.close() + for path in stage.iterdir(): + if path.is_file(): + # Windows _commit (os.fsync) requires a writable descriptor. + with path.open('r+b') as stream: + os.fsync(stream.fileno()) + _fsync_directory(stage) + # Refuse replacement even when a racing caller creates the target. + if output.exists(): + raise FileExistsError(f'Curated output already exists: {output}.') + session.validate_proposition_documents() + check_cancel(cancel) + publish_directory(stage, output) + _fsync_directory(output.parent) + except BaseException: + if curated is not None: + curated.close() + if assignments is not None: + assignments._mmap.close() + shutil.rmtree(stage, ignore_errors=True) + raise + return output diff --git a/phy/apps/large_recording/replay_program.py b/phy/apps/large_recording/replay_program.py new file mode 100644 index 000000000..2cb70c98f --- /dev/null +++ b/phy/apps/large_recording/replay_program.py @@ -0,0 +1,112 @@ +"""Batch projection compiled once from an already validated semantic journal.""" + +from copy import deepcopy + +import numpy as np + +from .curation import _membership_mask, _restore_batch_size, evaluate_predicate +from .live_summaries import membership_expressions +from .streaming import UnitRows + + +class AssignmentProgram: + """Collapse merge runs around explicit split/restore boundaries. + + Compilation is independent of spike count. Every structural event remains in + order, including predicates with rejection obligations whose children later + remerge. Restoration always uses immutable original assignments/attributes. + The reference journal interpreter remains independent of this implementation. + """ + + def __init__(self, unit_ids, events): + events = deepcopy(events) + active = set(map(int, unit_ids)) + self.steps = [] + self.predicate_names = { + event['predicate']['attribute'] + for event in events + if event['operation'] == 'threshold_split' + } + restores = {} + if any(event['operation'] == 'restore_parents' for event in events): + membership_expressions(unit_ids, events, restore_sources=restores) + mapping = {unit: unit for unit in active} + + def flush(): + if any(old != target for old, target in mapping.items()): + keys = np.array(sorted(mapping), dtype=np.int64) + targets = np.array([mapping[int(key)] for key in keys], dtype=np.int64) + self.steps.append(('map', UnitRows(keys), targets)) + + for index, event in enumerate(events): + operation = event['operation'] + if operation == 'merge': + parents = set(event['parents']) + target = event['target'] + mapping = { + old: target if value in parents else value for old, value in mapping.items() + } + active.difference_update(parents) + active.add(target) + elif operation in ('threshold_split', 'restore_parents'): + flush() + if operation == 'threshold_split': + self.steps.append(('split', event)) + active.remove(event['parent']) + else: + expressions = restores[index] + size = _restore_batch_size(expressions, len(self.predicate_names)) + self.steps.append(('restore', event, expressions, size)) + active.remove(event['target']) + active.update(event['children']) + mapping = {unit: unit for unit in active} + elif operation not in ('label', 'metadata_policy'): + raise ValueError('Unsupported semantic projection operation.') + flush() + + @property + def merge_runs(self): + return sum(step[0] == 'map' for step in self.steps) + + def project(self, assignments, attributes=None): + original = np.asarray(assignments).reshape(-1) + output = original.astype(np.int64, copy=True) + attributes = attributes or {} + for step in self.steps: + if step[0] == 'map': + _, lookup, targets = step + output = targets[lookup(output)] + elif step[0] == 'split': + event = step[1] + predicate = event['predicate'] + name = predicate['attribute'] + if name not in attributes: + raise ValueError(f'Full-source threshold attribute is unavailable: {name}.') + values = np.asarray(attributes[name]).reshape(-1) + if len(values) != len(output): + raise ValueError('Threshold attribute is not a scalar per-spike array.') + rows = np.flatnonzero(output == event['parent']) + selected = evaluate_predicate(values[rows], predicate) + output[rows] = np.where(selected, event['children'][1], event['children'][0]) + else: + _, event, expressions, size = step + rows = np.flatnonzero(output == event['target']) + for start in range(0, len(rows), size): + chunk = rows[start : start + size] + base = original[chunk] + values = { + name: np.asarray(attributes[name]).reshape(-1)[chunk] + for name in self.predicate_names + if name in attributes + } + covered = np.zeros(len(chunk), dtype=bool) + memo = {} + for child, expression in zip(event['children'], expressions, strict=True): + mask = _membership_mask(expression, base, values, memo) + if np.any(covered & mask): + raise ValueError('Restored source parent memberships overlap.') + output[chunk[mask]] = child + covered |= mask + if not covered.all(): + raise ValueError('Restored source parents do not partition the target.') + return output diff --git a/phy/apps/large_recording/runtime.py b/phy/apps/large_recording/runtime.py new file mode 100644 index 000000000..0b90d6cf7 --- /dev/null +++ b/phy/apps/large_recording/runtime.py @@ -0,0 +1,277 @@ +"""Disposable incremental state; persisted journals retain independent full validation.""" + +import copy +from dataclasses import dataclass + +import numpy as np + +from ._immutable import freeze, retained_bytes, thaw +from .curation import ( + POLICY, + _integer, + interpret_events, + normalize_metadata, +) +from .metadata import complete_schema +from .source import hash_json + + +@dataclass(frozen=True) +class Node: + """An immutable historical membership; restore aliases share the original node.""" + + unit: int + index: int + parts: object + expression: dict + count: object + + def __post_init__(self): + object.__setattr__(self, 'expression', freeze(self.expression)) + + def lineage(self): + return ( + self.unit, + self.index, + tuple(p.lineage() for p in self.parts) if self.parts is not None else None, + ) + + +def leaves(nodes): + pending = list(reversed(nodes)) + result, seen = [], set() + while pending: + node = pending.pop() + if node.parts is not None: + pending.extend(reversed(node.parts)) + else: + reference = (node.unit, node.index) + if reference in seen: + raise ValueError('Recorded restoration contains a repeated historical component.') + seen.add(reference) + result.append(node) + return result + + +@dataclass(frozen=True) +class SemanticState: + active: dict + metadata: dict + next_id: int + policy: object + schema: dict + membership_key: object + + def __post_init__(self): + object.__setattr__(self, 'active', freeze(self.active)) + object.__setattr__(self, 'metadata', freeze(self.metadata)) + object.__setattr__(self, 'schema', freeze(self.schema)) + + @classmethod + def initial(cls, session): + nodes = { + unit: Node(unit, -1, None, {'kind': 'source', 'unit': unit}, int(count)) + for unit, count in zip(session.unit_ids, session.manifest['counts'], strict=True) + } + return cls( + nodes, + copy.deepcopy(session.base_metadata), + session.base_next_cluster_id, + session.manifest.get('metadata_policy'), + session.metadata_schema, + object(), + ) + + @classmethod + def from_session(cls, session): + state = cls.initial(session) + prefix = [] + for index, event in enumerate(session.events): + state = state.advance(session, event, index, prefix) + prefix.append(event) + return state + + def restore_nodes(self, target, recursive): + node = self.active.get(target) + if node is None or node.parts is None: + raise ValueError('No recoverable merge origin in this preparation for this live unit.') + return node.index, leaves(node.parts) if recursive else node.parts + + def advance(self, session, event, index, prefix, allocator=None): + """Validate one event against current state, without touching spike arrays.""" + from .live_summaries import _union + + operation = event.get('operation') + if operation not in ( + 'metadata_policy', + 'merge', + 'label', + 'threshold_split', + 'restore_parents', + ): + raise ValueError(f'Unsupported semantic operation: {operation!r}.') + if operation == 'metadata_policy': + # Migration is exceptional and must retain historical explicit-label intent. + session._validate_event_capabilities([*prefix, event]) + _, metadata, minimum = interpret_events( + session.unit_ids, session.base_metadata, [*prefix, event] + ) + return SemanticState( + self.active, + metadata, + max(minimum, self.next_id), + POLICY, + event['schema'], + self.membership_key, + ) + session._require_capability(operation, event.get('predicate')) + expected_version = (3, 4) if operation == 'restore_parents' else (2 if self.policy else 1,) + if type(event.get('version')) is not int or event['version'] not in expected_version: + raise ValueError('Semantic event version disagrees with metadata policy.') + children = [event.get('target')] if operation == 'merge' else event.get('children', []) + if any( + _integer(child, 'Allocated ID') < (self.next_id if allocator is None else allocator) + for child in children + ): + raise ValueError('Allocated ID collides with the complete catalog allocator.') + if operation == 'restore_parents': + metadata, minimum = self._restore_metadata(session, event, prefix) + else: + # The public interpreter remains the full-history reference. For ordinary + # operations its existing validator can also validate a single transition. + _, metadata, minimum = interpret_events(list(self.active), self.metadata, [event]) + if operation == 'label': + complete_schema(complete_schema(self.schema, self.metadata), metadata) + return SemanticState( + self.active, + metadata, + max(self.next_id, minimum), + self.policy, + self.schema, + self.membership_key, + ) + active = dict(self.active) + if operation == 'merge': + parts = tuple(active.pop(parent) for parent in event['parents']) + counts = [p.count for p in parts] + active[event['target']] = Node( + event['target'], + index, + parts, + _union([p.expression for p in parts]), + sum(counts) if None not in counts else None, + ) + elif operation == 'threshold_split': + parent = active.pop(event['parent']) + for selected, child in enumerate(event['children']): + expression = { + 'kind': 'split', + 'parent': parent.expression, + 'predicate': event['predicate'], + 'selected': bool(selected), + } + active[child] = Node(child, index, None, expression, None) + elif operation == 'restore_parents': + _, parts = self.restore_nodes(event['target'], event['version'] == 4) + active.pop(event['target']) + active.update(dict(zip(event['children'], parts, strict=True))) + return SemanticState( + active, metadata, max(self.next_id, minimum), self.policy, self.schema, object() + ) + + def _restore_metadata(self, session, event, prefix): + required = { + 'version', + 'operation', + 'target', + 'children', + 'merge_event_index', + 'merge_prefix_sha256', + 'source_revision', + 'metadata', + } | ({'parent_references'} if event['version'] == 4 else set()) + if not self.policy or set(event) != required: + raise ValueError('Malformed restore-parents event.') + target = _integer(event['target'], 'Restore target ID') + origin, parts = self.restore_nodes(target, event['version'] == 4) + if _integer(event['merge_event_index'], 'Merge event index') != origin: + raise ValueError('Restore requires an unchanged live recorded merge membership.') + if event['merge_prefix_sha256'] != hash_json(prefix[: origin + 1]): + raise ValueError('Restore merge prefix binding is invalid.') + if event['source_revision'] != session.manifest['source']['revision']: + raise ValueError('Restore source revision disagrees with preparation.') + if event['version'] == 4: + refs = event['parent_references'] + expected = [{'unit': p.unit, 'event_index': p.index} for p in parts] + if ( + not isinstance(refs, list) + or any( + not isinstance(ref, dict) + or set(ref) != {'unit', 'event_index'} + or type(ref['unit']) is not int + or type(ref['event_index']) is not int + for ref in refs + ) + or refs != expected + ): + raise ValueError( + 'Recursive restore parent references disagree with merge ancestry.' + ) + children = [_integer(i, 'Restored child ID') for i in event['children']] + if len(children) != len(parts) or len(set(children)) != len(children): + raise ValueError('Restore requires one distinct child for every resolved parent.') + if any(i > np.iinfo(np.int32).max for i in children): + raise ValueError('Restored child ID exceeds the current Phy loader namespace.') + resolved = normalize_metadata(event['metadata']) + expected = {field: dict.fromkeys(children) for field in set(self.metadata) | {'group'}} + if resolved != expected: + raise ValueError('Restored membership must clear producer metadata and quality.') + metadata = thaw(self.metadata) + for values in metadata.values(): + values.pop(target, None) + for field, values in resolved.items(): + metadata.setdefault(field, {}).update(values) + return metadata, max(children) + 1 + + +@dataclass(frozen=True) +class Transition: + event: dict + before: SemanticState + after: SemanticState + old_groups: dict + new_groups: dict + allocator: int + + def __post_init__(self): + object.__setattr__(self, 'old_groups', freeze(self.old_groups)) + object.__setattr__(self, 'new_groups', freeze(self.new_groups)) + + @property + def nbytes(self): + # Charge the full changed-node graph conservatively. Labels retain the + # same membership map, so their accounting never traverses lineage. + changed = set(self.old_groups) | set(self.new_groups) + nodes = [ + state.active[unit] + for state in (self.before, self.after) + for unit in changed + if unit in state.active + ] + return ( + 4096 + + 256 * len(self.before.active) + + retained_bytes( + self.event, + self.before.metadata, + self.after.metadata, + self.before.schema, + self.after.schema, + *nodes, + ) + + sum( + rows.nbytes + for groups in (self.old_groups, self.new_groups) + for rows in groups.values() + ) + ) diff --git a/phy/apps/large_recording/source.py b/phy/apps/large_recording/source.py new file mode 100644 index 000000000..2a2f5cd4a --- /dev/null +++ b/phy/apps/large_recording/source.py @@ -0,0 +1,767 @@ +"""Validated, file-backed source sorting on one monotonic integer time axis.""" + +import ctypes +import errno +import hashlib +import json +import os +import runpy +import sys +from pathlib import Path +from threading import Lock + +import numpy as np + +from .metadata import read_metadata +from .streaming import bounded_map, check_cancel, worker_count + +PER_SPIKE = frozenset( + ( + 'spike_times.npy', + 'spike_clusters.npy', + 'spike_templates.npy', + 'amplitudes.npy', + 'pc_features.npy', + 'template_features.npy', + 'spike_positions.npy', + 'spike_depths.npy', + ) +) +STATIC = frozenset( + ( + 'templates.npy', + 'templates_ind.npy', + 'template_ind.npy', + 'channel_map.npy', + 'channel_positions.npy', + 'channel_shanks.npy', + 'channel_map_si.npy', + 'channel_groups.npy', + 'whitening_mat.npy', + 'whitening_mat_inv.npy', + 'similar_templates.npy', + 'pc_feature_ind.npy', + 'template_feature_ind.npy', + ) +) +WAVEFORMS = frozenset( + ( + '_phy_spikes_subset.spikes.npy', + '_phy_spikes_subset.channels.npy', + '_phy_spikes_subset.waveforms.npy', + ) +) +WAVEFORM_SIDECARS = frozenset(('_phy_spikes_subset.sample_index.npy',)) +WINDOW_SIDECARS = frozenset( + ( + '_phy_spikes_subset.window_bounds.npy', + '_phy_spikes_subset.window_types.npy', + '_phy_spikes_subset.window_strata.npy', + ) +) + + +def hash_file(path, batch_bytes=1024 * 1024, cancel=None, progress=None): + """Hash bytes incrementally, including the array header, with bounded scratch.""" + if batch_bytes <= 0: + raise ValueError('Hash batch_bytes must be positive.') + digest = hashlib.sha256() + with Path(path).open('rb') as stream: + before = os.fstat(stream.fileno()) + for block in iter(lambda: stream.read(batch_bytes), b''): + check_cancel(cancel) + digest.update(block) + if progress: + progress(len(block)) + check_cancel(cancel) + after = os.fstat(stream.fileno()) + current = Path(path).stat() + signature = lambda stat: (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns) + if signature(before) != signature(after) or signature(before) != signature(current): + raise ValueError(f'File changed during hashing: {path}.') + return digest.hexdigest() + + +def hash_files(paths, workers=1, cancel=None, progress=None): + """Hash independent files in bounded threads; preserve input key order.""" + worker_count(workers) + paths = dict(paths) + total = sum(Path(path).stat().st_size for path in paths.values()) + completed = 0 + lock = Lock() + + def advance(size): + nonlocal completed + with lock: + completed += size + if progress: + progress('hashing source files', completed, total) + + def run(item): + name, path = item + return name, hash_file(path, cancel=cancel, progress=advance) + + return dict(bounded_map(run, paths.items(), workers)) + + +def hash_json(value): + """Hash canonical JSON, normalizing integer metadata dictionary keys.""" + + def normalize(item): + if isinstance(item, dict): + return {str(key): normalize(val) for key, val in item.items()} + if isinstance(item, (list, tuple)): + return [normalize(val) for val in item] + if isinstance(item, np.generic): + return item.item() + return item + + payload = json.dumps(normalize(value), sort_keys=True, separators=(',', ':'), allow_nan=False) + return hashlib.sha256(payload.encode('utf-8')).hexdigest() + + +def assignment_revision(path, metadata): + """Identify mutable assignments and resolved cluster metadata.""" + path = Path(path) + if path.is_dir(): + path = path / 'spike_clusters.npy' + return hash_json({'assignments': hash_file(path), 'metadata': metadata}) + + +def close_array(array): + """Release a file-backed array handle, including on Windows.""" + mapping = getattr(array, '_mmap', None) + if mapping is not None and not mapping.closed: + mapping.close() + + +def publish_directory(staged, destination): + """Atomically publish a complete directory without replacing any target. + + Ordinary POSIX rename can replace an empty destination directory. Native + exclusive rename prevents a racing publication from silently replacing it. + """ + if os.name == 'nt': + os.rename(staged, destination) + return + library = ctypes.CDLL(None, use_errno=True) + if sys.platform.startswith('linux'): + rename = getattr(library, 'renameat2', None) + if rename is None: + raise OSError(errno.ENOSYS, 'Atomic exclusive directory publication is unavailable.') + rename.argtypes = [ + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_int, + ctypes.c_char_p, + ctypes.c_uint, + ] + rename.restype = ctypes.c_int + result = rename(-100, os.fsencode(staged), -100, os.fsencode(destination), 1) + elif sys.platform == 'darwin': + rename = getattr(library, 'renamex_np', None) + if rename is None: + raise OSError(errno.ENOSYS, 'Atomic exclusive directory publication is unavailable.') + rename.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_uint] + rename.restype = ctypes.c_int + result = rename(os.fsencode(staged), os.fsencode(destination), 4) + else: + raise OSError(errno.ENOSYS, 'Atomic exclusive directory publication is unavailable.') + if result: + code = ctypes.get_errno() + raise OSError(code, os.strerror(code), str(destination)) + + +def _vector(array, name): + if array.ndim == 1 or (array.ndim == 2 and array.shape[1] == 1): + return array.reshape(-1) + raise ValueError(f'{name} must be a vector or column vector.') + + +def _metadata(path): + return read_metadata(path)[0] + + +def _time_base(value): + """Normalize an explicit producer clock without inferring conversions.""" + if not isinstance(value, dict) or set(value) != {'kind', 'ticks_per_second'}: + raise ValueError('time_base must declare kind and ticks_per_second.') + if value['kind'] not in ('acquisition_samples', 'elapsed_ticks'): + raise ValueError('time_base.kind must be acquisition_samples or elapsed_ticks.') + rate = value['ticks_per_second'] + if isinstance(rate, bool) or not isinstance(rate, (int, float)): + raise ValueError('time_base.ticks_per_second must be positive and finite.') + rate = float(rate) + if not np.isfinite(rate) or rate <= 0: + raise ValueError('time_base.ticks_per_second must be positive and finite.') + return {'kind': value['kind'], 'ticks_per_second': rate} + + +def _has_raw_paths(dat_path): + paths = dat_path if isinstance(dat_path, (list, tuple)) else [dat_path] + return any(path is not None and str(path).strip() not in ('', 'None') for path in paths) + + +class Source: + """Read source arrays in batches without constructing a GUI model. + + Duration must come from producer metadata or an explicit argument: the last + spike is never used as acquisition exposure. Intervals are half-open samples. + """ + + def __init__( + self, + params_path, + duration_seconds=None, + valid_intervals=None, + batch_size=100000, + workers=1, + cancel=None, + progress=None, + ): + self.arrays = {} + self.workers = worker_count(workers) + self.cancel, self.progress = cancel, progress + try: + self._initialize(params_path, duration_seconds, valid_intervals, batch_size) + except BaseException: + self.close() + raise + + def _initialize( + self, params_path, duration_seconds=None, valid_intervals=None, batch_size=100000 + ): + self.params_path = Path(params_path).resolve() + self.path = self.params_path.parent + self.params = { + key: value + for key, value in runpy.run_path(str(self.params_path)).items() + if not key.startswith('__') + } + self.batch_size = int(batch_size) + if self.batch_size <= 0: + raise ValueError('batch_size must be positive.') + self.batch_size = max(1, self.batch_size // self.workers) + if 'dtype' in self.params: + try: + raw_dtype = np.dtype(self.params['dtype']) + except (TypeError, ValueError) as error: + raise ValueError('params.py dtype must be a valid raw numeric dtype.') from error + if not np.issubdtype(raw_dtype, np.number): + raise ValueError('params.py dtype must be a valid raw numeric dtype.') + self.sample_rate = float(self.params.get('sample_rate', 0)) + if not np.isfinite(self.sample_rate) or self.sample_rate <= 0: + raise ValueError('A positive finite sample_rate is required.') + upstream = self.path / '_phy_spikes_subset.manifest.json' + recording = {} + info = {} + if upstream.exists(): + info = json.loads(upstream.read_text(encoding='utf-8')) + if info.get('format') != 'phy_spikes_subset' or info.get('format_version') != 1: + raise ValueError('Unsupported waveform manifest format or version.') + recording = info.get('recording', {}) + upstream_rate = recording.get('sampling_frequency_hz', self.sample_rate) + if upstream_rate != self.sample_rate: + raise ValueError('Waveform manifest sampling rate disagrees with params.py.') + self.upstream_recording = recording + declared_clocks = [ + _time_base(container['time_base']) + for container in (self.params, recording) + if 'time_base' in container + ] + if len(declared_clocks) == 2 and declared_clocks[0] != declared_clocks[1]: + raise ValueError('time_base disagrees between params and waveform manifest.') + self.time_base = declared_clocks[0] if declared_clocks else None + self.timestamps_path = self.path / 'timestamps.json' + if self.time_base is None and self.timestamps_path.exists(): + raise ValueError( + 'timestamps.json requires an explicit time_base in params.py or manifest ' + 'recording. Convert num_samples, valid_intervals and waveform sidecars ' + 'to the spike_times.npy coordinates; automatic timestamp mapping is unsupported.' + ) + if self.time_base is not None: + if self.time_base['ticks_per_second'] != self.sample_rate: + raise ValueError('time_base ticks_per_second must equal sample_rate.') + for container in (self.params, recording): + if container.get('waveform_sample_rate', self.sample_rate) != self.sample_rate: + raise ValueError('waveform_sample_rate must equal sample_rate.') + kind = self.time_base['kind'] + if recording.get('frame_coordinates', kind) != kind: + raise ValueError('recording.frame_coordinates must equal time_base.kind.') + for suffix, field in ( + ('window_bounds', 'window_bounds_coordinates'), + ('sample_index', 'sample_index_coordinates'), + ): + if (self.path / f'_phy_spikes_subset.{suffix}.npy').exists(): + coordinates = recording.get(field) + if coordinates is None and kind == 'acquisition_samples': + coordinates = kind + if coordinates != kind: + raise ValueError(f'recording.{field} must equal time_base.kind.') + if kind == 'elapsed_ticks' and _has_raw_paths(self.params.get('dat_path')): + raise ValueError('elapsed_ticks cannot reference raw dat_path traces.') + if self.params.get('num_segments', recording.get('num_segments', 1)) != 1: + raise ValueError('Only a single monotonic acquisition segment is supported.') + duration_samples = None + if duration_seconds is not None: + duration_samples = float(duration_seconds) * self.sample_rate + if ( + not np.isfinite(duration_samples) + or duration_samples <= 0 + or duration_samples > np.iinfo(np.int64).max + or not np.isclose(duration_samples, round(duration_samples), rtol=0, atol=1e-6) + ): + raise ValueError('duration_seconds must specify a positive integer sample count.') + duration_samples = int(round(duration_samples)) + if ( + 'num_samples' in self.params + and 'num_samples' in recording + and self.params['num_samples'] != recording['num_samples'] + ): + raise ValueError( + 'Producer sample counts disagree between params and waveform manifest.' + ) + declared_samples = self.params.get('num_samples', recording.get('num_samples')) + if declared_samples is None: + declared_samples = duration_samples + elif duration_samples is not None and int(declared_samples) != duration_samples: + raise ValueError('Explicit duration disagrees with acquisition metadata.') + if declared_samples is None: + raise ValueError( + 'Acquisition exposure is missing; provide duration_seconds or num_samples.' + ) + self.num_samples = int(declared_samples) + if ( + self.num_samples <= 0 + or self.num_samples > np.iinfo(np.int64).max + or self.num_samples != declared_samples + ): + raise ValueError('num_samples must be a positive int64 sample count.') + if ( + 'valid_intervals' in self.params + and 'valid_intervals' in recording + and not np.array_equal( + np.asarray(self.params['valid_intervals']), + np.asarray(recording['valid_intervals']), + ) + ): + raise ValueError( + 'Producer valid_intervals disagree between params and waveform manifest.' + ) + declared_intervals = self.params.get('valid_intervals', recording.get('valid_intervals')) + if valid_intervals is not None and declared_intervals is not None: + if not np.array_equal(np.asarray(valid_intervals), np.asarray(declared_intervals)): + raise ValueError('Explicit valid_intervals disagree with acquisition metadata.') + if valid_intervals is None: + valid_intervals = declared_intervals + if ( + self.time_base is not None + and self.time_base['kind'] == 'elapsed_ticks' + and valid_intervals is None + ): + raise ValueError('elapsed_ticks requires explicit authoritative valid_intervals.') + intervals = [[0, self.num_samples]] if valid_intervals is None else valid_intervals + raw_intervals = np.asarray(intervals) + if raw_intervals.ndim != 2 or raw_intervals.shape[1] != 2 or not len(raw_intervals): + raise ValueError('valid_intervals must be nonempty sample [start, end) pairs.') + self.valid_intervals = raw_intervals.astype(np.int64) + if ( + not np.array_equal(raw_intervals, self.valid_intervals) + or np.any(self.valid_intervals[:, 0] < 0) + or np.any(self.valid_intervals[:, 1] > self.num_samples) + or np.any(self.valid_intervals[:, 1] <= self.valid_intervals[:, 0]) + or np.any(self.valid_intervals[1:, 0] < self.valid_intervals[:-1, 1]) + ): + raise ValueError( + 'valid_intervals must be ordered, disjoint integer acquisition samples.' + ) + sample_index_path = self.path / '_phy_spikes_subset.sample_index.npy' + if ( + self.time_base is None + and sample_index_path.exists() + and recording.get('sample_index_coordinates', 'acquisition_samples') + != 'acquisition_samples' + ): + raise ValueError( + 'Legacy waveform sample_index coordinates must be acquisition_samples; ' + 'declare an explicit time_base for elapsed_ticks.' + ) + names = {p.name for p in self.path.glob('*.npy')} + unknown = names - PER_SPIKE - STATIC - WAVEFORMS - WAVEFORM_SIDECARS - WINDOW_SIDECARS + # Replay lineage and original optional sidecars are retained; bounded + # outputs deliberately cannot be used as full-source sorting inputs. + if unknown: + raise ValueError(f'Unregistered source arrays: {", ".join(sorted(unknown))}.') + self.arrays = { + name: np.load(self.path / name, mmap_mode='r', allow_pickle=False) + for name in sorted(names) + } + for required in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy'): + if required not in self.arrays: + raise ValueError(f'Missing required source array {required}.') + self.n_spikes = len(_vector(self.arrays['spike_times.npy'], 'spike_times.npy')) + self.metadata, self.metadata_schema = read_metadata(self.path) + self.validate() + counts = {} + + def count_batch(batch): + check_cancel(self.cancel) + return np.unique(batch['spike_clusters.npy'], return_counts=True) + + counted = 0 + for ids, values in bounded_map(count_batch, self.iter_batches(), self.workers): + for cluster_id, count in zip(ids.tolist(), values.tolist(), strict=True): + counts[cluster_id] = counts.get(cluster_id, 0) + count + counted += int(values.sum()) + if self.progress: + self.progress('counting source units', counted, self.n_spikes) + for values in self.metadata.values(): + for cluster_id in values: + counts.setdefault(cluster_id, 0) + lineage_path = self.path / '_phy_curation_lineage.json' + lineage = {} + if lineage_path.exists(): + lineage = json.loads(lineage_path.read_text(encoding='utf-8')) + if ( + lineage.get('format') != 'phy_curation_lineage' + or lineage.get('format_version') != 1 + ): + raise ValueError('Unsupported curation lineage format or version.') + for unit in lineage.get('unit_ids', []): + if not isinstance(unit, int) or unit < 0: + raise ValueError('Lineage unit IDs must be nonnegative integers.') + counts.setdefault(unit, 0) + self.metadata_provenance = lineage.get('metadata_provenance', {'history': []}) + self.retired_units = lineage.get('retired_units', {}) + if not isinstance(self.retired_units, dict): + raise ValueError('Lineage retired_units must be a mapping.') + for unit, record in self.retired_units.items(): + if ( + not isinstance(unit, str) + or not unit.isdecimal() + or str(int(unit)) != unit + or int(unit) > np.iinfo(np.int32).max + or not isinstance(record, dict) + or set(record) != {'operation', 'replacements'} + or record['operation'] not in ('merge', 'threshold_split', 'restore_parents') + ): + raise ValueError('Invalid lineage retired unit record.') + replacements = record['replacements'] + if ( + not isinstance(replacements, list) + or not replacements + or any( + type(value) is not int or value < 0 or value > np.iinfo(np.int32).max + for value in replacements + ) + or len(set(replacements)) != len(replacements) + or (record['operation'] == 'merge' and len(replacements) != 1) + or (record['operation'] == 'threshold_split' and len(replacements) != 2) + or (record['operation'] == 'restore_parents' and len(replacements) < 2) + or int(unit) in replacements + or int(unit) in counts + ): + raise ValueError('Invalid lineage retired unit replacements.') + documents = lineage.get('proposition_documents', {}) + if not isinstance(documents, dict): + raise ValueError('Lineage proposition documents must be a mapping.') + for name, digest in documents.items(): + if ( + name not in ('curation.json', 'curation_review.json') + or not isinstance(digest, str) + or len(digest) != 64 + or any(c not in '0123456789abcdef' for c in digest) + or (self.path / name).is_symlink() + or hash_file(self.path / name) != digest + ): + raise ValueError('Lineage proposition document integrity check failed.') + if any(unit < 0 or unit > np.iinfo(np.int32).max for unit in counts): + raise ValueError( + 'Unit IDs must fit nonnegative int32 for the current Phy loader; spike sample/row coordinates remain int64.' + ) + self.unit_ids = np.array(sorted(counts), dtype=np.int64) + minimum_next = int(self.unit_ids[-1]) + 1 if len(self.unit_ids) else 0 + self.next_cluster_id = lineage.get('next_cluster_id', minimum_next) + if not isinstance(self.next_cluster_id, int) or self.next_cluster_id < minimum_next: + raise ValueError('Lineage next_cluster_id collides with the source unit catalog.') + self.counts = np.array( + [counts[cluster_id] for cluster_id in self.unit_ids], dtype=np.int64 + ) + immutable = sorted(names - {'spike_clusters.npy'} - WINDOW_SIDECARS) + # Optional subset planning metadata describes a sampling policy, not a + # new immutable spike-coordinate identity. + acquisition = { + key: self.params[key] + for key in ( + 'acquisition_id', + 'n_channels_dat', + 'dtype', + 'offset', + 'depth_axis', + 'amplitude_units', + 'depth_units', + 'position_units', + 'waveform_units', + ) + if key in self.params + } + array_hashes = hash_files( + {name: self.path / name for name in [*immutable, 'spike_clusters.npy']}, + workers=self.workers, + cancel=self.cancel, + progress=self.progress, + ) + assignments_hash = array_hashes.pop('spike_clusters.npy') + self.identity = { + 'format_version': 1, + 'acquisition': acquisition, + 'time_base': { + 'sample_rate': self.sample_rate, + 'num_samples': self.num_samples, + 'valid_intervals': self.valid_intervals.tolist(), + }, + 'arrays': array_hashes, + } + if self.time_base is not None: + self.identity['time_base']['contract'] = self.time_base.copy() + if self.timestamps_path.exists(): + self.identity['time_base']['timestamps_sha256'] = hash_file(self.timestamps_path) + self.identity['sha256'] = hash_json(self.identity) + declared_source = info.get('source_sorting', {}) + if not isinstance(declared_source, dict): + raise ValueError('Waveform manifest source_sorting must be a mapping.') + if declared_source.get('num_spikes', self.n_spikes) != self.n_spikes: + raise ValueError('Waveform reservoir source spike count does not match this sorting.') + declared_times = declared_source.get('spike_times_sha256') + if ( + declared_times is not None + and declared_times != self.identity['arrays']['spike_times.npy'] + ): + raise ValueError( + 'Waveform reservoir source coordinate fingerprint does not match this sorting.' + ) + self.revision = hash_json( + { + 'assignments': assignments_hash, + 'metadata': self.metadata, + } + ) + if lineage: + if ( + lineage.get('coordinate_identity') != self.identity + or lineage.get('revision') != self.revision + ): + raise ValueError( + 'Curation lineage does not match immutable identity or assignments.' + ) + + def close(self): + """Release canonical array mappings after a batch command.""" + for array in self.arrays.values(): + close_array(array) + self.arrays.clear() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def iter_batches(self): + """Yield bounded row slices; vector fields use one-dimensional views.""" + for start in range(0, self.n_spikes, self.batch_size): + check_cancel(self.cancel) + stop = min(start + self.batch_size, self.n_spikes) + batch = {'start': start, 'stop': stop} + for name in self.arrays.keys() & PER_SPIKE: + array = self.arrays[name] + if name in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy'): + array = _vector(array, name) + batch[name] = array[start:stop] + yield batch + + def validate(self): + """Check source row, clock, sparse channel, and feature alignment.""" + for name in self.arrays.keys() & PER_SPIKE: + if self.arrays[name].shape[0] != self.n_spikes: + raise ValueError(f'{name} is not aligned with source spikes.') + for name in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy'): + array = _vector(self.arrays[name], name) + if not np.issubdtype(array.dtype, np.integer): + raise ValueError(f'{name} must contain integer coordinates.') + times = _vector(self.arrays['spike_times.npy'], 'spike_times.npy') + # Monotonic sources expose a clock mismatch at their endpoints. Check + # these before scanning hundreds of millions of rows or hashing assets; + # the complete monotonicity and bounds validation below remains required. + if len(times) and (times[0] < 0 or times[-1] >= self.num_samples): + raise ValueError( + 'Spike time endpoints fall outside declared num_samples; check that ' + 'spike_times.npy, num_samples, valid_intervals and waveform sidecars ' + 'use the same time base. Convert producer metadata to canonical ' + 'coordinates before preparing this sorting.' + ) + previous = -1 + for batch in self.iter_batches(): + times = batch['spike_times.npy'] + if ( + np.any(times < previous) + or np.any(times[1:] < times[:-1]) + or np.any(times < 0) + or np.any(times >= self.num_samples) + ): + raise ValueError( + 'Spike sample times must be monotonic and within acquisition bounds.' + ) + if len(times): + previous = int(times[-1]) + interval_ids = np.searchsorted(self.valid_intervals[:, 0], times, side='right') - 1 + if np.any(interval_ids < 0) or np.any(times >= self.valid_intervals[interval_ids, 1]): + raise ValueError('Spike times fall outside valid acquisition intervals.') + for name in ('spike_clusters.npy', 'spike_templates.npy'): + if np.any(batch[name] < 0): + raise ValueError(f'{name} must contain nonnegative IDs.') + templates = self.arrays.get('templates.npy') + if templates is not None and np.any(batch['spike_templates.npy'] >= len(templates)): + raise ValueError('spike_templates.npy references an unavailable template.') + if self.progress: + self.progress('validating source rows', batch['stop'], self.n_spikes) + waveforms = self.arrays.keys() & WAVEFORMS + if waveforms and waveforms != WAVEFORMS: + raise ValueError('Stored waveforms require spikes, channels, and waveforms together.') + sample_index = self.arrays.get('_phy_spikes_subset.sample_index.npy') + if sample_index is not None and not waveforms: + raise ValueError('Stored waveform sample_index requires the waveform triplet.') + if waveforms: + ids = self.arrays['_phy_spikes_subset.spikes.npy'] + if ids.ndim != 1 or ids.dtype != np.dtype('int64'): + raise ValueError('Stored waveform row IDs must be a one-dimensional int64 array.') + channels = self.arrays['_phy_spikes_subset.channels.npy'] + values = self.arrays['_phy_spikes_subset.waveforms.npy'] + n_channels = len(self.arrays.get('channel_map.npy', [])) + if ( + values.ndim != 3 + or channels.shape != (len(ids), values.shape[2]) + or len(values) != len(ids) + or not np.issubdtype(channels.dtype, np.integer) + ): + raise ValueError('Stored waveform tensors and channels are not aligned.') + if sample_index is not None and ( + sample_index.ndim != 1 + or not np.issubdtype(sample_index.dtype, np.integer) + or len(sample_index) != len(ids) + ): + raise ValueError('Stored waveform sample_index must be an aligned integer vector.') + last = -1 + # Sparse-padding checks create temporary boolean arrays and gathers; + # cap their tensor bytes independently of the source row batch size. + row_bytes = max(1, values.dtype.itemsize * int(np.prod(values.shape[1:]))) + waveform_batch = min(self.batch_size, max(1, 8 * 1024 * 1024 // row_bytes)) + for start in range(0, len(ids), waveform_batch): + rows = ids[start : start + waveform_batch] + slots = channels[start : start + waveform_batch] + if ( + np.any(rows <= last) + or np.any(rows[1:] <= rows[:-1]) + or np.any(rows < 0) + or np.any(rows >= self.n_spikes) + ): + raise ValueError('Stored waveform row IDs must be sorted, unique source rows.') + if sample_index is not None: + coordinates = sample_index[start : start + waveform_batch] + if ( + np.any(coordinates < 0) + or np.any(coordinates >= self.num_samples) + or not np.array_equal( + coordinates, self.arrays['spike_times.npy'].reshape(-1)[rows] + ) + ): + raise ValueError( + 'Stored waveform sample_index must equal spike_times.npy at waveform ' + 'row IDs in canonical time-base coordinates.' + ) + if len(rows): + last = int(rows[-1]) + if np.any((slots < -1) | (slots >= n_channels)): + raise ValueError( + 'Sparse waveform channels must index model channels or use -1.' + ) + block = values[start : start + waveform_batch] + if np.any(np.moveaxis(block, 1, 2)[slots == -1] != 0): + raise ValueError('Sparse waveform padding channels must contain zeros.') + channel_map = self.arrays.get('channel_map.npy') + if channel_map is not None: + channels = _vector(channel_map, 'channel_map.npy') + if ( + not np.issubdtype(channels.dtype, np.integer) + or np.any(channels < 0) + or len(np.unique(channels)) != len(channels) + ): + raise ValueError('channel_map.npy must contain unique nonnegative raw column IDs.') + raw_channels = self.params.get('n_channels_dat') + if raw_channels is not None and ( + int(raw_channels) != raw_channels + or raw_channels <= 0 + or np.any(channels >= raw_channels) + ): + raise ValueError('channel_map.npy contains columns outside n_channels_dat.') + for name in ('channel_groups.npy', 'channel_shanks.npy', 'channel_map_si.npy'): + if name in self.arrays and len(_vector(self.arrays[name], name)) != len(channels): + raise ValueError(f'{name} must align with model channels.') + for name in ('whitening_mat.npy', 'whitening_mat_inv.npy'): + if name in self.arrays and self.arrays[name].shape != ( + len(channels), + len(channels), + ): + raise ValueError(f'{name} must contain a model-channel square matrix.') + templates = self.arrays.get('templates.npy') + if templates is not None: + # phylib uses singular template_ind; KS2's plural sidecar does + # not turn a dense tensor into a sparse tensor in the loader. + sparse = self.arrays.get('template_ind.npy') + if templates.ndim != 3: + raise ValueError('templates.npy must be a template/sample/channel tensor.') + if sparse is None and templates.shape[2] != len(channels): + raise ValueError('Dense templates must align with model channels.') + for index_name in ('template_ind.npy', 'templates_ind.npy'): + sparse = self.arrays.get(index_name) + if sparse is None: + continue + if sparse.shape != (len(templates), templates.shape[2]): + raise ValueError(f'{index_name} must align with sparse templates.') + if not np.issubdtype(sparse.dtype, np.integer): + raise ValueError(f'{index_name} must contain integer channel indices.') + if np.any((sparse < -1) | (sparse >= len(channels))): + raise ValueError(f'{index_name} contains invalid model channel IDs.') + positions = self.arrays.get('channel_positions.npy') + if positions is not None and ( + positions.shape != (len(channels), 2) or not np.all(np.isfinite(positions)) + ): + raise ValueError( + 'channel_positions.npy must contain finite x/y model channel coordinates.' + ) + for feature, indices in ( + ('pc_features.npy', 'pc_feature_ind.npy'), + ('template_features.npy', 'template_feature_ind.npy'), + ): + if feature in self.arrays and indices not in self.arrays: + raise ValueError(f'{feature} requires {indices}.') + if feature in self.arrays: + values = self.arrays[feature] + lookup = self.arrays[indices] + if lookup.ndim != 2 or values.ndim < 2 or values.shape[-1] != lookup.shape[1]: + raise ValueError(f'{feature} and {indices} sparse axes do not agree.') + templates = self.arrays.get('templates.npy') + if templates is not None and len(lookup) != len(templates): + raise ValueError(f'{indices} must align with templates.') + if not np.issubdtype(lookup.dtype, np.integer): + raise ValueError(f'{indices} must contain integer indices.') + limit = ( + len(self.arrays.get('channel_map.npy', [])) + if feature == 'pc_features.npy' + else len(lookup) + ) + for start in range(0, len(lookup), self.batch_size): + rows = lookup[start : start + self.batch_size] + if np.any((rows < -1) | (rows >= limit)): + raise ValueError(f'{indices} contains invalid sparse indices.') + return self diff --git a/phy/apps/large_recording/stability.py b/phy/apps/large_recording/stability.py new file mode 100644 index 000000000..942c273b9 --- /dev/null +++ b/phy/apps/large_recording/stability.py @@ -0,0 +1,825 @@ +"""Selected-unit full-duration evidence with explicit acquisition exposure.""" + +from collections import OrderedDict +from sys import getsizeof + +import numpy as np +from phylib.utils import Bunch, connect, unconnect + +from phy.cluster.views import ManualClusteringView +from phy.gui.qt import screenshot, screenshot_default_path +from phy.plot.plot import PlotCanvasMpl +from phy.utils.color import selected_cluster_color + +from .refractory_service import RefractoryService + + +class UnitStabilityView(ManualClusteringView): + """Compare exact rates and available source trends for selected units.""" + + plot_canvas_class = PlotCanvasMpl + # Apply the display limit locally, retaining the full presentation selection. + max_n_clusters = 0 + defer_hidden_updates = True + display_limit = 32 + rate_line_width = 0.6 + display_bin_seconds = 0.0 + summary_cache_bytes = 64 * 1024 * 1024 + # A display convention, not a confidence or physiological rate threshold. + _min_rate_coverage = 0.001 + _default_position = 'right' + ex_status = 'Full-duration evidence; sampling cannot establish chronic unit identity.' + _metrics = ('firing_rate', 'amplitude', 'depth', 'refractory') + + def __init__(self, controller): + super().__init__() + self.controller = controller + self.canvas.subplots(4, 1, sharex=True) + self.show_firing_rate = self.show_amplitude = self.show_depth = True + self.show_refractory = True + self._rp = RefractoryService(controller) + self._rp.changed.connect(self._update_refractory) + self._rp_lines = {} + self._rp_note = None + self._rp_background = None + self._rp_blit = self.canvas.canvas.supports_blit + self._rp_draw_connection = self.canvas.canvas.mpl_connect( + 'draw_event', self._capture_refractory_background + ) + self.state_attrs += tuple(f'show_{metric}' for metric in self._metrics) + self.state_attrs += ('display_limit', 'rate_line_width') + self.local_state_attrs += ('display_bin_seconds',) + self._summary_arrays = {} + self._selected_summaries = OrderedDict() + self._common_data = None + self._attaching = False + self._bounded_membership_dirty = False + self._bounded_revision = getattr( + getattr(controller, 'bounded_session', None), 'membership_revision', None + ) + self._footer = self.canvas.figure.text(0.12, 0.025, '', fontsize=8) + + def _array(self, name): + if name not in self._summary_arrays: + self._summary_arrays[name] = np.load(self.controller.dir_path / name, mmap_mode='r') + return self._summary_arrays[name] + + def _common(self): + if self._common_data is not None: + return self._common_data + controller = self.controller + session = getattr(controller, 'bounded_session', None) + if session is None: + edges = np.linspace(0, controller.model.duration, 101) + self._common_data = Bunch( + edges=edges, + exposure=np.diff(edges), + windows=[], + intervals=[[0, controller.model.duration]], + footer='', + ) + else: + manifest = session.manifest + summary = manifest.get('summaries', manifest) + edges = self._array(summary['edges_file']) / controller.model.sample_rate + missing = [c for c, n in zip(session.unit_ids, manifest['bounded_counts']) if not n] + footer = '' + if missing: + footer = ( + f'{len(missing)} source units without evidence: ' + f'{", ".join(map(str, missing[:12]))}' + (' …' if len(missing) > 12 else '') + ) + self._common_data = Bunch( + edges=edges, + exposure=self._array(summary['exposure_file']), + windows=controller.evidence_windows / controller.model.sample_rate, + intervals=np.asarray(manifest['valid_intervals']) / controller.model.sample_rate, + summary=summary, + lookup={int(c): i for i, c in enumerate(session.unit_ids)}, + footer=footer, + ) + return self._common_data + + def get_data(self, cluster_id, metrics=None): + """Load only requested metrics, caching bounded selected-unit summary rows. + + Counts share the manifest's exposure. Trend sums are combined with their + finite-value counts, never averaged as equally weighted unit means. + """ + metrics = [m for m in (self._metrics if metrics is None else metrics) if m != 'refractory'] + common = self._common() + data = self._selected_summaries.get(cluster_id) + controller = self.controller + session = getattr(controller, 'bounded_session', None) + if data is None: + data = Bunch(common.copy()) + data.update( + counts=None, + trends={}, + trend_sums={}, + trend_counts={}, + loaded=set(), + pending=False, + display=None, + ) + if session is None: + data.provenance = 'Loaded recording; continuous acquisition assumed.' + else: + units = controller._source_units(cluster_id) + get_live = getattr(controller, 'get_live_summary', lambda c: None) + data.live_summary = get_live(cluster_id) if units is None else None + data.pending = units is None and data.live_summary is None + data.rows = [] if units is None else [common.lookup[c] for c in units] + get_status = getattr( + controller, + 'get_summary_status', + lambda c: 'Split evidence pending full-data replay.', + ) + data.provenance = ( + get_status(cluster_id) + if data.pending + else 'Complete source sorting; exact counts and finite-value means.' + ) + self._selected_summaries[cluster_id] = data + else: + self._selected_summaries.move_to_end(cluster_id) + if data.pending: + self._trim_cache() + return data + for metric in metrics: + if metric in data.loaded: + continue + if metric == 'firing_rate': + if session is None: + data.counts = np.histogram(controller.get_spike_times(cluster_id), data.edges)[ + 0 + ] + else: + if data.live_summary is not None: + counts = data.live_summary['counts'] + else: + counts = np.zeros(len(data.exposure), dtype=np.int64) + grid = self._array(common.summary['counts_file']) + for row in data.rows: + counts += grid[row] + data.counts = counts + data.rates = np.full(len(data.exposure), np.nan) + np.divide(data.counts, data.exposure, out=data.rates, where=data.exposure > 0) + elif session is not None: + sum_file, count_file = f'{metric}_sum_file', f'{metric}_count_file' + if sum_file in common.summary and count_file in common.summary: + if data.live_summary is not None: + total = data.live_summary['trend_sums'][metric] + valid = data.live_summary['trend_counts'][metric] + else: + total = np.zeros(len(data.exposure)) + valid = np.zeros(len(data.exposure), dtype=np.int64) + sums = self._array(common.summary[sum_file]) + counts = self._array(common.summary[count_file]) + for row in data.rows: + total += sums[row] + valid += counts[row] + mean = np.full(len(data.exposure), np.nan) + np.divide(total, valid, out=mean, where=(valid > 0) & (data.exposure > 0)) + data.trend_sums[metric] = total + data.trend_counts[metric] = valid + data.trends[metric] = mean + data.loaded.add(metric) + data.display = None + self._trim_cache() + return data + + @property + def displayed_ids(self): + """Presentation subset; the supervisor selection remains authoritative.""" + return self.cluster_ids[: self.display_limit] if self.display_limit else self.cluster_ids + + @staticmethod + def _data_bytes(data): + # Common arrays are shared/mapped, and are deliberately outside the row cache. + overhead = getsizeof(data) + getsizeof(data.loaded) + rows = data.get('rows', []) + overhead += getsizeof(rows) + sum(map(getsizeof, rows)) + arrays = [data.get('counts'), data.get('rates')] + for key in ('trends', 'trend_sums', 'trend_counts'): + overhead += getsizeof(data.get(key, {})) + arrays.extend(data.get(key, {}).values()) + display = data.get('display') + if display is not None: + overhead += getsizeof(display) + getsizeof(display.trends) + arrays.extend([display.edges, display.exposure, display.counts, display.rates]) + arrays.extend(display.trends.values()) + return overhead + sum( + a.nbytes + getsizeof(a) - (a.nbytes if a.flags.owndata else 0) + for a in arrays + if isinstance(a, np.ndarray) + ) + + def _trim_cache(self): + total = sum(self._data_bytes(data) for data in self._selected_summaries.values()) + while self._selected_summaries and total > self.summary_cache_bytes: + _, data = self._selected_summaries.popitem(last=False) + total -= self._data_bytes(data) + + def _display_factor(self, seconds=None): + seconds = self.display_bin_seconds if seconds is None else float(seconds) + if not np.isfinite(seconds) or seconds < 0: + raise ValueError('Display bin size must be zero (native) or finite and positive.') + if seconds == 0: + return 1 + widths = np.diff(self._common().edges) + native = widths[0] if len(widths) else np.nan + if ( + not np.all(np.isfinite(widths)) + or not np.isfinite(native) + or native <= 0 + or not np.allclose(widths[:-1], native, rtol=1e-10, atol=1e-10) + or widths[-1] <= 0 + or (widths[-1] > native and not np.isclose(widths[-1], native, rtol=1e-10, atol=1e-10)) + ): + raise ValueError( + 'Display bin size in seconds requires uniform native bins, ' + 'with an optional shorter final bin. Use 0 for native bins.' + ) + factor = seconds / native + if ( + not np.isfinite(factor) + or factor < 1 + or not np.isclose(factor, round(factor), rtol=1e-10, atol=1e-10) + ): + raise ValueError( + 'Display bin size must be an integer multiple of the native bin size.' + ) + return int(round(factor)) + + def get_display_data(self, cluster_id, metrics=None): + """Group adjacent native bins using additive evidence, without accessing spikes.""" + data = self.get_data(cluster_id, metrics) + factor = self._display_factor() + if data.pending or factor == 1: + return data + if data.display is None or data.display.factor != factor: + starts = np.arange(0, len(data.exposure), min(factor, len(data.exposure))) + exposure = np.add.reduceat(data.exposure, starts) + counts = None if data.counts is None else np.add.reduceat(data.counts, starts) + rates = np.full(len(starts), np.nan) + if counts is not None: + np.divide(counts, exposure, out=rates, where=exposure > 0) + trends = {} + for metric, total in data.trend_sums.items(): + sums = np.add.reduceat(total, starts) + valid = np.add.reduceat(data.trend_counts[metric], starts) + mean = np.full(len(starts), np.nan) + np.divide(sums, valid, out=mean, where=(valid > 0) & (exposure > 0)) + trends[metric] = mean + data.display = Bunch( + factor=factor, + edges=np.r_[data.edges[starts], data.edges[-1]], + exposure=exposure, + counts=counts, + rates=rates, + trends=trends, + pending=False, + provenance=data.provenance, + ) + display = data.display + self._trim_cache() + return display + + def set_display_limit(self, value): + """Set maximum displayed units (0 for all; otherwise a positive integer).""" + number = float(value) + if not np.isfinite(number) or number != int(number) or number < 0: + raise ValueError('Display limit must be an nonnegative integer (0 shows all).') + self.display_limit = int(number) + self.plot() + + def set_rate_line_width(self, value): + """Set rate line width in points (finite and positive).""" + number = float(value) + if not np.isfinite(number) or number <= 0: + raise ValueError('Rate line width must be finite and positive.') + self.rate_line_width = number + self.plot() + + def set_display_bin_seconds(self, value): + """Set display bin size in seconds (0 uses native prepared bins).""" + self._display_factor(value) + self.display_bin_seconds = float(value) + for data in self._selected_summaries.values(): + data.display = None + self.plot() + + def set_state(self, state): + state = dict(state) + for key, default in ( + ('display_limit', 32), + ('rate_line_width', 0.6), + ('display_bin_seconds', 0.0), + ): + if key not in state: + continue + try: + number = float(state[key]) + valid = np.isfinite(number) + if key == 'display_limit': + valid = valid and number.is_integer() and number >= 0 + elif key == 'rate_line_width': + valid = valid and number > 0 + else: + self._display_factor(number) + state[key] = int(number) if key == 'display_limit' and valid else number + if not valid: + state[key] = default + except (ValueError, TypeError, OverflowError): + state[key] = default + super().set_state(state) + + def screenshot(self, dir=None): + """Save the actual Matplotlib Qt canvas using normal screenshot naming.""" + path = screenshot_default_path(self, dir=dir) + return screenshot(self.canvas.canvas, path=path) + + @property + def status(self): + n = len(self.cluster_ids) + return ( + f'Showing first {self.display_limit} of {n} selected units; ' + 'display truncation does not change the selection or merge operation.' + if self.display_limit and n > self.display_limit + else '' + ) + + def _layout_axes(self, visible): + self._rp_background = None + axes = list(self.canvas.iter_ax()) + for metric, ax in zip(self._metrics, axes): + if metric != 'refractory': + ax.clear() + ax.set_visible(metric in visible) + for index, metric in enumerate(visible): + ax = axes[self._metrics.index(metric)] + height = 0.76 / len(visible) + ax.set_position( + [ + 0.12, + 0.15 + (len(visible) - 1 - index) * height, + 0.84, + height * (0.84 if len(visible) > 1 else 1), + ] + ) + ax.tick_params(axis='x', labelbottom=index == len(visible) - 1) + if index == len(visible) - 1: + ax.set_xlabel('Elapsed acquisition clock (hours)') + return axes + + def plot(self, **kwargs): + visible = [metric for metric in self._metrics if getattr(self, f'show_{metric}')] + axes = self._layout_axes(visible) + self._footer.set_text('') + # Reuse an existing axis for the explicitly empty panel. + if not visible: + axes[0].set_visible(True) + axes[0].set_position([0.12, 0.15, 0.84, 0.76]) + axes[0].set_axis_off() + axes[0].text( + 0.02, + 0.6, + 'No metrics enabled. Use Show firing rate, amplitude or depth.', + transform=axes[0].transAxes, + ) + else: + common = self._common() + self._footer.set_text(common.footer) + first_ax = axes[self._metrics.index(visible[0])] + notes = [] + evidence = [m for m in visible if m != 'refractory'] + unavailable = {metric: [] for metric in evidence} + low_rate_coverage = None + rate_plotted = False + if not self.cluster_ids: + notes.append('Select a unit to inspect full-duration evidence.') + for index, cluster_id in enumerate(self.displayed_ids): + data = self.get_display_data(cluster_id, evidence) + if data.pending: + notes.append(f'Unit {cluster_id}: {data.provenance}') + continue + color = selected_cluster_color(self.cluster_color_index(cluster_id, index)) + x = (data.edges[:-1] + data.edges[1:]) / 7200 + for metric in evidence: + ax = axes[self._metrics.index(metric)] + values = data.rates if metric == 'firing_rate' else data.trends.get(metric) + rate_markers = {} + if metric == 'firing_rate': + if low_rate_coverage is None: + low_rate_coverage = (data.exposure > 0) & ( + data.exposure < self._min_rate_coverage * np.diff(data.edges) + ) + # Keep exact cached rates available; only the trace is masked. + values = np.where(low_rate_coverage, np.nan, values) + finite = np.isfinite(values) + isolated = finite & ~np.r_[False, finite[:-1]] & ~np.r_[finite[1:], False] + if np.any(isolated): + rate_markers = { + 'marker': '.', + 'markersize': 3, + 'markevery': np.flatnonzero(isolated).tolist(), + } + if values is not None and np.any(np.isfinite(values)): + rate_plotted |= metric == 'firing_rate' + ax.plot( + x, + values, + color=color, + label=str(cluster_id), + linewidth=self.rate_line_width if metric == 'firing_rate' else 1.5, + **rate_markers, + ) + elif metric != 'firing_rate': + unavailable[metric].append(cluster_id) + if low_rate_coverage is not None and np.any(low_rate_coverage): + ax = axes[0] + n_omitted = np.count_nonzero(low_rate_coverage) + # Axes-relative y coordinates cannot inflate the firing-rate scale. + ax.plot( + x[low_rate_coverage], + np.full(n_omitted, 0.02), + transform=ax.get_xaxis_transform(), + linestyle='none', + marker='|', + color='0.5', + label='_low_acquisition_coverage', + ) + self._footer.set_text( + '\n'.join( + filter( + None, + ( + common.footer, + f'{n_omitted} rate bin{"s" if n_omitted != 1 else ""} omitted: ' + 'too little recorded time.', + ), + ) + ) + ) + if not rate_plotted: + ax.text( + 0.02, + 0.85, + 'No rate bins with sufficient recorded time.', + transform=ax.transAxes, + va='top', + fontsize=8, + ) + labels = ('Rate (Hz)', 'Mean amplitude\n(source units)', 'Mean depth\n(source units)') + for metric in evidence: + ax = axes[self._metrics.index(metric)] + ax.set_axis_on() + ax.set_ylabel(labels[self._metrics.index(metric)]) + if unavailable[metric]: + missing = ', '.join(map(str, unavailable[metric])) + message = ( + f'{metric.title()} measurement unavailable.' + if not ax.lines + else f'{metric.title()} measurement unavailable for units: {missing}.' + ) + ax.text(0.02, 0.96, message, transform=ax.transAxes, va='top', fontsize=8) + for start, end in common.windows: + ax.axvspan(start / 3600, end / 3600, color='cyan', alpha=0.15) + previous = 0 + for start, end in common.intervals: + if start > previous: + ax.axvspan(previous / 3600, start / 3600, color='gray', alpha=0.4) + previous = end + if previous < common.edges[-1]: + ax.axvspan(previous / 3600, common.edges[-1] / 3600, color='gray', alpha=0.4) + ax.set_xlim(common.edges[0] / 3600, common.edges[-1] / 3600) + provenance = ( + 'Complete source sorting; exact counts and finite-value means.' + if getattr(self.controller, 'bounded_session', None) is not None + else 'Loaded recording; continuous acquisition assumed.' + ) + if visible[0] != 'refractory': + first_ax.set_title(provenance, fontsize=9) + if notes and visible[0] != 'refractory': + first_ax.text( + 0.02, + 0.96, + '\n'.join(notes), + transform=first_ax.transAxes, + va='top', + fontsize=8, + ) + self.update_status() + self._rp.request( + self.displayed_ids, + enabled=self.show_refractory and self._dock_visible and self.auto_update, + ) + if self.show_refractory: + axes[3].set_xlim(*self._refractory_xlim()) + self._update_refractory(draw=False) + self.canvas.update() + + def _refractory_xlim(self): + common = self._common() + fs = getattr(self.controller.model, 'sample_rate', None) + if fs is None or not np.isfinite(fs) or fs <= 0: + return common.edges[0] / 3600, common.edges[-1] / 3600 + session = getattr(self.controller, 'bounded_session', None) + num_samples = ( + getattr(session, 'manifest', {}).get('num_samples') if session is not None else None + ) + if num_samples is None: + num_samples = round(common.edges[-1] * fs) + bin_samples = max(1, round(1800 * fs)) + n_bins = (num_samples + bin_samples - 1) // bin_samples + return common.edges[0] / 3600, max(common.edges[-1] / 3600, n_bins // 2) + + def _update_refractory(self, draw=True): + """Update persistent RP artists without rebuilding tables or other axes.""" + if ( + self._closed + or not self.show_refractory + or not self._dock_visible + or not self.auto_update + ): + return + ax = list(self.canvas.iter_ax())[3] + if self._rp_note is None: + ax.axhline(10, color='0.65', linestyle='--', linewidth=0.8) + ax.set_ylabel('RP contamination (%)') + ax.set_ylim(0, 100) + ax.set_title('≤1 ms; 0.3 ms diagnostic dedup; 6 h windows every 1 h', fontsize=8) + self._rp_note = ax.text( + 0.02, + 0.96, + '', + transform=ax.transAxes, + va='top', + fontsize=8, + animated=self._rp_blit, + clip_on=True, + ) + common = self._common() + previous = 0 + for start, end in common.intervals: + if start > previous: + ax.axvspan(previous / 3600, start / 3600, color='gray', alpha=0.4) + previous = end + if previous < common.edges[-1]: + ax.axvspan(previous / 3600, common.edges[-1] / 3600, color='gray', alpha=0.4) + if self._refractory_xlim()[1] > common.edges[-1] / 3600: + ax.axvspan( + common.edges[-1] / 3600, self._refractory_xlim()[1], color='gray', alpha=0.4 + ) + selected = set(self.displayed_ids) + for unit in list(self._rp_lines): + if unit not in selected: + self._rp_lines.pop(unit).remove() + for index, unit in enumerate(self.displayed_ids): + if unit not in self._rp_lines: + (self._rp_lines[unit],) = ax.plot( + [], [], label=str(unit), linewidth=1.2, animated=self._rp_blit + ) + line = self._rp_lines[unit] + line.set_color(selected_cluster_color(self.cluster_color_index(unit, index))) + data = self._rp.results.get(unit) + if data is not None and data.get('status') == 'unavailable': + data = None + line.set_data( + data['window_centres_h'] if data is not None else [], + data['contamination'] * 100 if data is not None else [], + ) + note = self._rp.message + ready = [r for r in self._rp.results.values() if r.get('status') != 'unavailable'] + if ready: + right = max(self._refractory_xlim()[1], max(r['window_centres_h'][-1] for r in ready)) + limits = (self._common().edges[0] / 3600, right) + if ax.get_xlim() != limits: + ax.set_xlim(*limits) + self._rp_background = None + finite_min = min( + ( + float(np.nanmin(r['contamination'])) + for r in ready + if np.isfinite(r['contamination']).any() + ), + default=0, + ) + limits = (min(0, 100 * finite_min), 100) + if ax.get_ylim() != limits: + ax.set_ylim(*limits) + self._rp_background = None + failures = [ + f'Unit {u}: {r["message"]}' + for u, r in self._rp.results.items() + if r.get('status') == 'unavailable' + ] + if failures: + note = 'RP unavailable. ' + '; '.join(failures[:3]) + elif ready and all(not np.isfinite(r['contamination']).any() for r in ready): + note = 'RP unavailable in windows with fewer than 1,000 post-dedup spikes.' + self._rp_note.set_text(note) + if draw: + if self._rp_background is not None: + self._draw_refractory_artists() + else: + self.canvas.canvas.draw_idle() + + def _capture_refractory_background(self, event): + if self._rp_blit and not self._closed and self.show_refractory and self._dock_visible: + ax = list(self.canvas.iter_ax())[3] + self._rp_background = self.canvas.canvas.copy_from_bbox(ax.bbox) + self._draw_refractory_artists() + + def _draw_refractory_artists(self): + ax = list(self.canvas.iter_ax())[3] + self.canvas.canvas.restore_region(self._rp_background) + for line in self._rp_lines.values(): + ax.draw_artist(line) + if self._rp_note is not None: + ax.draw_artist(self._rp_note) + self.canvas.canvas.blit(ax.bbox) + + def on_select(self, cluster_ids=None, **kwargs): + if self._attaching: + supervisor = self.controller.supervisor + cluster_ids = supervisor.selected + self._update_cluster_color_indices(supervisor, cluster_ids) + self.cluster_ids = tuple(cluster_ids or ()) + selected = set(self.displayed_ids) + self._selected_summaries = OrderedDict( + (c, d) for c, d in self._selected_summaries.items() if c in selected + ) + self.plot(**kwargs) + + def _update_cluster_color_indices(self, sender, cluster_ids): + # Hidden-view replay already adopted the authoritative palette at receipt. + if sender is not self: + super()._update_cluster_color_indices(sender, cluster_ids) + + def on_select_threaded(self, sender, cluster_ids, gui=None, **kwargs): + # The base intentionally ignores empty selections; this evidence panel must clear. + if not cluster_ids: + if ( + not self.auto_update + or self._closed + or sender.__class__.__name__ in ('ClusterView', 'SimilarityView') + ): + return + self._update_cluster_color_indices(sender, cluster_ids) + if self.defer_hidden_updates and not self._dock_visible: + self.cluster_ids = () + self._pending_selection = ([], dict(kwargs)) + return + self._pending_selection = None + self.on_select([], **kwargs) + return + result = super().on_select_threaded(sender, cluster_ids, gui=gui, **kwargs) + self.cluster_ids = tuple(self.cluster_ids) + return result + + def _toggle_metric(self, metric, checked): + setattr(self, f'show_{metric}', bool(checked)) + if hasattr(self, 'actions'): + self.actions.get(f'toggle_{metric}').setChecked(bool(checked)) + if not self._closed: + self.plot() + + def toggle_firing_rate(self, checked): + """Show firing rate.""" + self._toggle_metric('firing_rate', checked) + + def toggle_amplitude(self, checked): + """Show amplitude.""" + self._toggle_metric('amplitude', checked) + + def toggle_depth(self, checked): + """Show depth.""" + self._toggle_metric('depth', checked) + + def toggle_refractory(self, checked): + """Show refractory-period contamination.""" + self._toggle_metric('refractory', checked) + + def toggle_auto_update(self, checked): + """Freeze pending RP work along with the other selected-unit evidence.""" + super().toggle_auto_update(checked) + if not checked: + self._rp.request((), enabled=False) + elif not self._closed: + supervisor = getattr(self.controller, 'supervisor', None) + if supervisor is not None: + ids = list(supervisor.selected) + self._update_cluster_color_indices(supervisor, ids) + self.on_select(ids) + else: + self.plot() + + def _invalidate(self): + self._selected_summaries.clear() + + def _release_cache(self): + self._rp.close() + self.canvas.canvas.mpl_disconnect(self._rp_draw_connection) + self._rp_background = None + self._summary_arrays.clear() + self._selected_summaries.clear() + self._common_data = None + + def close(self): + """Release mapped summary references and cached rows, including unattached views.""" + result = super().close() + self._release_cache() + return result + + def attach(self, gui): + self._attaching = True + try: + super().attach(gui) + finally: + self._attaching = False + + def on_rp_visibility(visible): + if not visible: + self._rp.request((), enabled=False) + elif not self._closed: + self._rp.request( + self.displayed_ids, enabled=self.show_refractory and self.auto_update + ) + self._update_refractory() + + self.dock.visibilityChanged.connect(on_rp_visibility) + for metric in self._metrics: + self.actions.add( + getattr(self, f'toggle_{metric}'), + checkable=True, + checked=getattr(self, f'show_{metric}'), + docstring=f'Show {metric.replace("_", " ")}.', + ) + self.actions.get(f'toggle_{metric}').setText(f'Show {metric.replace("_", " ")}') + + for action in ( + self.set_display_limit, + self.set_rate_line_width, + self.set_display_bin_seconds, + ): + self.actions.add(action, prompt=True) + + @self.actions.add(prompt=True) + def show_source_unit(cluster_id): + """Inspect a full source unit, including one without sampled evidence.""" + session = getattr(self.controller, 'bounded_session', None) + if session is not None and int(cluster_id) not in session.unit_ids: + raise ValueError('Unknown source unit ID.') + self._cluster_color_index_by_id = {} + self.on_select([int(cluster_id)]) + + @connect(event='bounded_state_changed', sender=self.controller.supervisor) + def on_state(sender): + session = getattr(self.controller, 'bounded_session', None) + revision = getattr(session, 'membership_revision', None) + if ( + revision is not None + and revision is self._bounded_revision + and not self._bounded_membership_dirty + ): + return + self._bounded_revision = revision + self._bounded_membership_dirty = False + self._invalidate() + if not self._closed: + self.plot() + + @connect(event='cluster', sender=self.controller.supervisor) + def on_cluster(sender, up): + if up.description.startswith('metadata_'): + return + # Native notifications precede semantic commit. A later exception + # may restore the old token; its rollback still needs a refresh. + self._bounded_membership_dirty = True + self._invalidate() + # Supervisor selection callbacks may precede this listener. Refresh + # ordinary data after invalidation even if the selected IDs stayed put. + if ( + getattr(self.controller, 'bounded_session', None) is None + and self.auto_update + and not self._closed + and not (self.defer_hidden_updates and not self._dock_visible) + ): + self.plot() + + @connect(event='bounded_summary_changed', sender=self.controller.supervisor) + def on_summary(sender): + self._invalidate() + if self.auto_update and not self._closed: + if self.defer_hidden_updates and not self._dock_visible: + if self._pending_selection is None: + self._pending_selection = (list(self.cluster_ids), {}) + else: + self.plot() + + @connect(event='close_view', sender=self) + def on_close(sender, *args): + unconnect(on_state, on_cluster, on_summary, on_close) + self._release_cache() diff --git a/phy/apps/large_recording/statistics.py b/phy/apps/large_recording/statistics.py new file mode 100644 index 000000000..92df03e7b --- /dev/null +++ b/phy/apps/large_recording/statistics.py @@ -0,0 +1,231 @@ +"""Descriptive statistics restricted to retained contiguous observation windows.""" + +from decimal import ROUND_FLOOR, Decimal + +import numpy as np +from phylib.stats import correlograms + + +def window_isi(samples, windows, sample_rate): + intervals = [] + for start, end in windows: + first, last = np.searchsorted(samples, [start, end]) + intervals.append(np.diff(samples[first:last]) / sample_rate) + return np.concatenate(intervals) if intervals else np.array([], dtype=np.float64) + + +def _window_chance_baseline( + counts, + n_samples, + bin_samples, + n_positive_bins, + *, + exclusion_samples=0, + exclude_auto=False, + exclude_cross=False, +): + """Mean off-center bin expectation under uniform independent sample clocks. + + Condition on each unit's count in this observation window, and place its + spikes independently with replacement on the ``n_samples`` integer clocks. + At a positive delay d there are ``n_samples - d`` possible clock pairs. + Average their probabilities over the displayed positive bins, including + zero exposure where a bin extends beyond this window. Negative bins have + the same expectation. Auto pairs use the factorial count n*(n-1), excluding + self-pairs. The folded central bin has a different convention and is excluded. + Optional pair exclusion also removes its clock exposure, while the mean's + denominator remains the number of all displayed off-center bins. + + This is an exact mean of the off-center null expectations, not an exact + null curve (which tapers with lag), a confidence bound, or a recording-wide + firing rate. It assumes stationarity only within this evidence window. + """ + counts = np.asarray(counts, dtype=np.float64) + pairs = np.outer(counts, counts) + pairs[np.diag_indices(len(counts))] -= counts + if not n_positive_bins: + return np.zeros_like(pairs) + length = int(n_samples) + first = int(bin_samples) + last = min((int(n_positive_bins) + 1) * first - 1, length - 1) + n_delays = max(0, last - first + 1) + exposure = n_delays * (2 * length - first - last) / 2 + probability = exposure / length**2 / n_positive_bins + if not (exclude_auto or exclude_cross): + return pairs * probability + # A cutoff can remove part of an off-center bin. Keep the denominator equal + # to the number of displayed off-center bins, including fully masked bins. + first = max(first, exclusion_samples + 1) + n_delays = max(0, last - first + 1) + exposure = n_delays * (2 * length - first - last) / 2 + filtered = exposure / length**2 / n_positive_bins + probabilities = np.full(pairs.shape, filtered if exclude_cross else probability) + np.fill_diagonal(probabilities, filtered if exclude_auto else probability) + return pairs * probabilities + + +def _exclusion_sample_radius(exclusion_ms, sample_rate): + """Floor a decimal millisecond radius without rounding an integer boundary down.""" + try: + width = float(exclusion_ms) + except (TypeError, ValueError) as error: + raise ValueError('exclusion_ms must be finite and nonnegative.') from error + if not np.isfinite(width) or width < 0: + raise ValueError('exclusion_ms must be finite and nonnegative.') + # Decimal input spellings preserve boundaries such as 0.3 ms * 30000 Hz = 9, + # while genuinely fractional radii still exclude only integer delays below it. + radius = Decimal(str(exclusion_ms)) * Decimal(str(sample_rate)) / 1000 + return min(int(radius.to_integral_value(rounding=ROUND_FLOOR)), 2**63 - 1) + + +def _excluded_positive_correlograms( + ticks, + labels, + n_clusters, + sample_rate, + bin_size, + window_size, + exclusion_samples, + exclude_auto, + exclude_cross, +): + """Count integer-lag pairs with a temporary exclusion mask before binning. + + Like phylib's shift kernel, use linear temporary storage and retire a source + only when its partners exceed the maximum displayed lag. A short excluded + pair must not retire that source: its later partners may have valid delays. + """ + assert sample_rate > 0 + assert np.all(np.diff(ticks) >= 0), 'The spike times must be increasing.' + bin_size = np.clip(bin_size, 1e-5, 1e5) + bin_samples = int(sample_rate * bin_size) + assert bin_samples >= 1 + window_size = np.clip(window_size, 1e-5, 1e5) + n_positive_bins = int(0.5 * window_size / bin_size) + result = np.zeros((n_clusters, n_clusters, n_positive_bins + 1), dtype=np.int64) + active = np.ones(len(ticks), dtype=bool) + shift = 1 + while active[:-shift].any(): + delays = ticks[shift:] - ticks[:-shift] + active[:-shift][delays >= (n_positive_bins + 1) * bin_samples] = False + keep = active[:-shift].copy() + if exclude_auto and exclude_cross: + keep &= delays > exclusion_samples + else: + same = labels[:-shift] == labels[shift:] + eligible = same if exclude_auto else ~same + keep &= ~eligible | (delays > exclusion_samples) + indices = np.ravel_multi_index( + (labels[:-shift][keep], labels[shift:][keep], delays[keep] // bin_samples), + result.shape, + ) + increments = np.bincount(indices) + result.ravel()[: len(increments)] += increments + shift += 1 + return result + + +def window_correlograms( + samples, + clusters, + windows, + cluster_ids, + sample_rate, + bin_size, + window_size, + return_baseline=False, + *, + exclusion_ms=0.3, + exclude_auto=False, + exclude_cross=False, +): + """Exact window-local pair counts and an optional observed-window chance level. + + Positive/negative lag bins follow phylib's floor-to-bin convention. The + central bin counts unordered within-unit pairs and cross-unit pairs with + absolute delays below one bin. Cross-unit central counts sum both temporal + orientations, making them independent of equal-time source row order. + + Optional visual pair exclusion removes integer sample delays whose absolute + value is at most ``exclusion_ms`` milliseconds before binning, independently + for same-unit (``exclude_auto``) and cross-unit (``exclude_cross``) pairs. + Both switches default to False. Zero width removes exact ties when enabled. + Selected spikes and observation windows remain unchanged. + + With ``return_baseline=True``, return ``(counts, chance)``. The horizontal + ``chance`` matrix sums the per-window conditional-uniform mean off-center + expectations described in ``_window_chance_baseline``. It uses precisely the + same selected spikes, integer bin width and finite observed windows as the + histogram; gaps and full-recording counts do not contribute. It is not the + expected central-bin height and is zero when there are no off-center bins. + """ + exclusion_samples = _exclusion_sample_radius(exclusion_ms, sample_rate) + selected = np.isin(clusters, cluster_ids) + order = np.argsort(cluster_ids) + sorted_ids = np.asarray(cluster_ids)[order] + result = None + baseline = np.zeros((len(cluster_ids), len(cluster_ids)), dtype=np.float64) + for start, end in windows: + first, last = np.searchsorted(samples, [start, end]) + mask = selected[first:last] + ticks = samples[first:last][mask] - start + if len(ticks) and ticks.max() >= 2**50: + raise ValueError( + 'Observation window is too long for exact correlogram sample conversion.' + ) + # Avoid phylib's lookup allocation indexed by absolute cluster ID. + labels = order[np.searchsorted(sorted_ids, clusters[first:last][mask])] + counts = np.bincount(labels, minlength=len(cluster_ids)) + if np.any(counts > 46340): + raise ValueError( + 'Evidence window has too many spikes for exact correlogram counts; prepare shorter windows.' + ) + if exclude_auto or exclude_cross: + positive = _excluded_positive_correlograms( + ticks, + labels, + len(cluster_ids), + sample_rate, + bin_size, + window_size, + exclusion_samples, + exclude_auto, + exclude_cross, + ) + else: + # phylib truncates float times * rate to integer samples. A common + # quarter-sample offset preserves every integer tick after conversion + # without changing any pair delay, including late-clock recordings. + times = (ticks.astype(np.float64) + 0.25) / sample_rate + positive = correlograms( + times, + labels, + sample_rate=sample_rate, + cluster_ids=np.arange(len(cluster_ids)), + bin_size=bin_size, + window_size=window_size, + symmetrize=False, + ).astype(np.int64) + if return_baseline: + baseline += _window_chance_baseline( + counts, + end - start, + int(sample_rate * np.clip(bin_size, 1e-5, 1e5)), + positive.shape[2] - 1, + exclusion_samples=exclusion_samples, + exclude_auto=exclude_auto, + exclude_cross=exclude_cross, + ) + # Accumulate before symmetrization to preserve exact central counts and + # int64 totals across many windows. Self-spike pairs are never counted. + if result is None: + result = positive + else: + result += positive + if result is None: + raise ValueError('Correlograms require at least one observation window.') + center = result[..., 0] + result[..., 0].T + np.fill_diagonal(center, np.diag(result[..., 0])) + result[..., 0] = center + result = np.dstack((result[..., 1:][..., ::-1].transpose(1, 0, 2), result)) + return (result, baseline) if return_baseline else result diff --git a/phy/apps/large_recording/streaming.py b/phy/apps/large_recording/streaming.py new file mode 100644 index 000000000..f0a1c0e6a --- /dev/null +++ b/phy/apps/large_recording/streaming.py @@ -0,0 +1,81 @@ +"""Bounded lookup and scheduling shared by offline streaming passes.""" + +from collections import deque +from concurrent.futures import CancelledError, ThreadPoolExecutor + +import numpy as np + + +def check_cancel(cancel): + if cancel is not None and cancel(): + raise CancelledError() + + +def worker_count(workers): + """Reject accidental unbounded or silently truncated worker requests.""" + if type(workers) is not int or not 1 <= workers <= 32: + raise ValueError('workers must be an integer between 1 and 32.') + return workers + + +def bounded_map(function, items, workers=1): + """Yield ordered results with at most workers tasks and results resident.""" + worker_count(workers) + if workers == 1: + yield from map(function, items) + return + iterator = iter(items) + exhausted = object() + with ThreadPoolExecutor(max_workers=workers) as pool: + pending = deque() + try: + for _ in range(workers): + item = next(iterator, exhausted) + if item is exhausted: + break + pending.append(pool.submit(function, item)) + while pending: + yield pending.popleft().result() + item = next(iterator, exhausted) + if item is not exhausted: + pending.append(pool.submit(function, item)) + finally: + for future in pending: + future.cancel() + + +class UnitRows: + """Validated unit-to-row map, with a capped dense fast path for compact IDs.""" + + def __init__(self, units, max_bytes=8 * 1024 * 1024): + self.units = np.asarray(units) + if ( + self.units.ndim != 1 + or self.units.dtype.kind not in 'iu' + or np.any(self.units < 0) + or np.any(self.units[1:] <= self.units[:-1]) + ): + raise ValueError('Unit catalog must contain sorted unique nonnegative integers.') + self.table = None + # Avoid a huge allocation for a handful of sparse, high-valued IDs. + limit = min(max_bytes, max(4096, len(self.units) * 64)) + size = int(self.units[-1]) + 1 if len(self.units) else 0 + if size * 4 <= limit and len(self.units) <= np.iinfo(np.int32).max: + self.table = np.full(size, -1, dtype=np.int32) + self.table[self.units] = np.arange(len(self.units), dtype=np.int32) + + def __call__(self, values): + values = np.asarray(values) + if values.dtype.kind not in 'iu' or np.any(values < 0): + raise ValueError('Source unit catalog mismatch.') + if self.table is not None: + if np.any(values >= len(self.table)): + raise ValueError('Source unit catalog mismatch.') + rows = self.table[values] + if np.any(rows < 0): + raise ValueError('Source unit catalog mismatch.') + else: + rows = np.searchsorted(self.units, values) + if np.any(rows >= len(self.units)) or np.any(self.units[rows] != values): + raise ValueError('Source unit catalog mismatch.') + return rows diff --git a/phy/apps/large_recording/summaries.py b/phy/apps/large_recording/summaries.py new file mode 100644 index 000000000..fe70db408 --- /dev/null +++ b/phy/apps/large_recording/summaries.py @@ -0,0 +1,199 @@ +"""Exact file-backed counts and additive source-measurement summaries.""" + +from contextlib import ExitStack +from pathlib import Path + +import numpy as np + +from .source import close_array +from .streaming import UnitRows, bounded_map, check_cancel, worker_count + + +def scalar_attributes(source): + """Return available scalar measurements without inventing physical units.""" + attributes = {} + amplitude = source.arrays.get('amplitudes.npy') + if amplitude is not None and (amplitude.ndim == 1 or amplitude.shape[1:] == (1,)): + attributes['amplitude'] = amplitude.reshape(-1) + depth = source.arrays.get('spike_depths.npy') + if depth is not None and (depth.ndim == 1 or depth.shape[1:] == (1,)): + attributes['depth'] = depth.reshape(-1) + elif (positions := source.arrays.get('spike_positions.npy')) is not None: + axis = source.params.get('depth_axis') + if axis is not None: + if ( + not isinstance(axis, int) + or positions.ndim != 2 + or not 0 <= axis < positions.shape[1] + ): + raise ValueError('depth_axis must declare a valid spike_positions.npy coordinate.') + attributes['depth'] = positions[:, axis] + return attributes + + +def summary_size(source, bin_seconds=3600): + """Estimate exact array bytes before allocating the dense output grid.""" + step = float(bin_seconds) * source.sample_rate + if not np.isfinite(step) or step < 1 or not np.isclose(step, round(step), rtol=0, atol=1e-6): + raise ValueError('bin_seconds must specify a positive integer sample width.') + step = int(round(step)) + bins = (source.num_samples + step - 1) // step + size = len(source.unit_ids) * bins * 8 * (1 + 2 * len(scalar_attributes(source))) + size += (bins * 2 + 1) * 8 + return size, step, bins + + +def build_summaries( + source, + output_dir, + bin_seconds=3600, + max_bytes=536870912, + workers=1, + cancel=None, + progress=None, +): + """Stream exact full counts, exposure, and finite-value sums/counts. + + Exposure is one shared vector. Summing parent-unit counts on merge must + divide by this vector once. Scalar means are sums/counts, never medians. + """ + worker_count(workers) + check_cancel(cancel) + size, step, bins = summary_size(source, bin_seconds) + if size + 1024 * (1 + 2 * len(scalar_attributes(source))) > max_bytes: + raise ValueError( + f'Summary budget exceeded: need at least {size} array bytes; ' + 'increase bin_seconds or max_bytes.' + ) + with ExitStack() as stack: + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + result = { + 'counts_file': '_phy_summary_counts.npy', + 'edges_file': '_phy_summary_edges.npy', + 'exposure_file': '_phy_summary_exposure.npy', + } + shape = (len(source.unit_ids), bins) + counts = np.lib.format.open_memmap( + output_dir / result['counts_file'], mode='w+', dtype=np.int64, shape=shape + ) + stack.callback(close_array, counts) + counts[:] = 0 + attributes = scalar_attributes(source) + grids = {} + for field in attributes: + for kind, dtype in (('sum', np.float64), ('count', np.int64)): + key = f'{field}_{kind}_file' + result[key] = f'_phy_summary_{field}_{kind}.npy' + array = np.lib.format.open_memmap( + output_dir / result[key], mode='w+', dtype=dtype, shape=shape + ) + stack.callback(close_array, array) + array[:] = 0 + grids[field, kind] = array + edges = np.lib.format.open_memmap( + output_dir / result['edges_file'], mode='w+', dtype=np.int64, shape=(bins + 1,) + ) + stack.callback(close_array, edges) + # Bounded chunks also avoid a recording-duration-sized temporary arange. + for start in range(0, bins + 1, source.batch_size): + stop = min(start + source.batch_size, bins + 1) + edges[start:stop] = np.arange(start, stop, dtype=np.int64) * step + edges[-1] = source.num_samples + exposure = np.lib.format.open_memmap( + output_dir / result['exposure_file'], mode='w+', dtype=np.float64, shape=(bins,) + ) + stack.callback(close_array, exposure) + exposure[:] = 0 + for start, end in source.valid_intervals: + first, last = int(start // step), int((end - 1) // step) + for offset in range(first, last + 1, source.batch_size): + stop = min(offset + source.batch_size, last + 1) + exposure[offset:stop] += ( + np.minimum(edges[offset + 1 : stop + 1], end) + - np.maximum(edges[offset:stop], start) + ) / source.sample_rate + # Output grids and all simultaneous worker histograms share max_bytes. + # Map only compact IDs; a sparse int32 catalog never allocates a huge LUT. + available = max_bytes - size + lookup = UnitRows(source.unit_ids, max_bytes=min(8 * 1024 * 1024, available // 8)) + if lookup.table is not None: + available -= lookup.table.nbytes + # Reserve one consumer result while the next worker is scheduled. + per_worker = available // (workers + 1) + fields = 1 + 2 * len(attributes) + row_bytes = 128 + 64 * len(attributes) + batch_rows = max(1, min(source.batch_size, per_worker // (2 * row_bytes))) + tile_bins = min( + max(1, batch_rows // max(1, len(source.unit_ids))), + per_worker // max(1, 16 * fields * len(source.unit_ids)), + ) + times = source.arrays['spike_times.npy'].reshape(-1) + assignments = source.arrays['spike_clusters.npy'].reshape(-1) + + def tasks(): + for start in range(0, source.n_spikes, batch_rows): + stop = min(start + batch_rows, source.n_spikes) + first = start + while first < stop: + begin = int(times[first] // step) + end = min(bins, begin + tile_bins, int(times[stop - 1] // step) + 1) + last = first + int( + np.searchsorted(times[first:stop], min(end * step, source.num_samples)) + ) + yield first, last, begin, end + first = last + + def histogram(task): + check_cancel(cancel) + first, last, begin, end = task + rows = lookup(assignments[first:last]) + columns = times[first:last] // step - begin + width = end - begin + flat = rows.astype(np.int64) * width + columns + cells = len(source.unit_ids) * width + histograms = {None: np.bincount(flat, minlength=cells).reshape(-1, width)} + for field, values in attributes.items(): + values = values[first:last] + finite = np.isfinite(values) + histograms[field, 'sum'] = np.bincount( + flat[finite], weights=values[finite].astype(np.float64), minlength=cells + ).reshape(-1, width) + histograms[field, 'count'] = np.bincount(flat[finite], minlength=cells).reshape( + -1, width + ) + return last, begin, end, histograms + + if tile_bins: + for stop, begin, end, histograms in bounded_map(histogram, tasks(), workers): + check_cancel(cancel) + counts[:, begin:end] += histograms.pop(None) + for key, values in histograms.items(): + grids[key][:, begin:end] += values + if progress: + progress('building full summaries', stop, source.n_spikes) + else: + # Extremely tight budgets cannot fit even a unit-by-one-bin + # histogram. Preserve the bounded scatter path in that case. + for start in range(0, source.n_spikes, batch_rows): + check_cancel(cancel) + stop = min(start + batch_rows, source.n_spikes) + rows = lookup(assignments[start:stop]) + columns = times[start:stop] // step + np.add.at(counts, (rows, columns), 1) + for field, values in attributes.items(): + values = values[start:stop] + finite = np.isfinite(values) + np.add.at(grids[field, 'sum'], (rows[finite], columns[finite]), values[finite]) + np.add.at(grids[field, 'count'], (rows[finite], columns[finite]), 1) + if progress: + progress('building full summaries', stop, source.n_spikes) + for array in (counts, edges, exposure, *grids.values()): + array.flush() + result['estimators'] = { + 'counts': 'exact', + 'exposure': 'acquisition_seconds', + **dict.fromkeys(attributes, 'finite_sum_and_count'), + } + result['measurement_units'] = {field: f'source {field} units' for field in attributes} + return result diff --git a/phy/apps/large_recording/summary_service.py b/phy/apps/large_recording/summary_service.py new file mode 100644 index 000000000..3a3438881 --- /dev/null +++ b/phy/apps/large_recording/summary_service.py @@ -0,0 +1,386 @@ +"""Controller-owned, deferred coordination of exact full-recording summaries.""" + +import logging +from concurrent.futures import CancelledError +from contextlib import suppress +from copy import deepcopy +from pathlib import Path +from queue import Full, Queue +from threading import Event, Thread +from time import monotonic + +from phy.gui.qt import QObject, Qt, QTimer, pyqtSignal, pyqtSlot +from phy.gui.tasks import heavy_io + +from .live_summaries import ( + LiveSummaryEngine, + _check_cancel, + acquire_source_engine, + membership_expressions, + release_source_engine, +) + +logger = logging.getLogger(__name__) + + +class _Delivery(QObject): + finished = pyqtSignal(object) + progress = pyqtSignal(object) + + +class _SummaryWorker: + """One daemon owns pinned, validated source readers across serial jobs.""" + + def __init__(self, package_path, source_path, delivery): + self.package_path = package_path + self.source_path = source_path + self.delivery = delivery + self.stopped = Event() + self.jobs = Queue(maxsize=1) + self.thread = Thread(target=self._run, daemon=True) + self.thread.start() + + def submit(self, expressions, cancel): + self.jobs.put_nowait((expressions, cancel)) + + def stop(self): + self.stopped.set() + # A queued job observes stopped before opening any source. + with suppress(Full): + self.jobs.put_nowait(None) + + def _run(self): + engine = None + lease = None + try: + while True: + job = self.jobs.get() + if job is None: + return + expressions, cancel = job + results, error = {}, None + try: + if self.stopped.is_set() or cancel.is_set(): + raise CancelledError() + last_progress = [0.0] + + def progress(phase, done, total, last_progress=last_progress, cancel=cancel): + now = monotonic() + if now - last_progress[0] >= 0.25 or done == total: + last_progress[0] = now + self.delivery.progress.emit((cancel, phase, done, total)) + + def check_cancel(cancel=cancel): + _check_cancel(lambda: self.stopped.is_set() or cancel.is_set()) + + with heavy_io( + check_cancel, waiting=lambda: progress('waiting for recording I/O', 0, 0) + ): + if engine is None: + lease, engine = acquire_source_engine( + self.package_path, self.source_path, factory=LiveSummaryEngine + ) + started = monotonic() + try: + results = engine.resolve( + expressions, cancel=cancel.is_set, progress=progress + ) + finally: + logger.debug( + 'Full summary job: path=%s, units=%d, elapsed=%.3fs', + getattr(engine, 'last_resolution_path', 'unknown'), + len(expressions), + monotonic() - started, + ) + except Exception as exc: + error = exc + if self.stopped.is_set(): + # Terminal delivery means all source handles are released; + # a resumed GUI may now create the next worker safely. + self.delivery.finished.emit((expressions, results, error, cancel)) + return + self.delivery.finished.emit((expressions, results, error, cancel)) + finally: + if lease is not None: + release_source_engine(lease) + + +class LiveSummaryService(QObject): + """Keep additive summary primitives outside the curation transaction. + + All public methods run on the owning Qt thread. Construction is suspended; + ``resume`` starts deferred work. Workers receive immutable membership + snapshots and own their source handles. Closing never waits for a scan. + """ + + changed = pyqtSignal() + + def __init__(self, session, parent=None): + super().__init__(parent) + self._session = session + self._package_path = Path(session.path) + self._source_path = None + self._engine = LiveSummaryEngine(self._package_path) + self._expressions = {} + self._events = None + self._errors = {} + self._completed_keys = set() + self._totals = {} + self._source_counts = dict( + zip(session.unit_ids, getattr(session, 'manifest', {}).get('counts', [])) + ) + self._pending = {} + self._closed = False + self._suspended = True + self._waiting_reason = None + self._running = None + self._progress_text = None + self._running_keys = set() + self._worker = None + self._delivery = _Delivery() + self._delivery.finished.connect(self._completed, Qt.QueuedConnection) + self._delivery.progress.connect(self._progress, Qt.QueuedConnection) + self._timer = QTimer(self) + self._timer.setSingleShot(True) + self._timer.timeout.connect(self._synchronize) + self._refresh() + self._announced_expressions = self._expressions + + def _refresh(self): + if self._closed: + return False + revision = getattr(self._session, 'membership_revision', self._session.events) + if self._events is revision: + return False + expressions = membership_expressions(self._session.unit_ids, self._session.events) + changed = expressions != self._expressions + self._expressions = expressions + self._events = revision + if changed: + self._pending = dict(expressions) + totals = {} + for expression in expressions.values(): + total = self._expression_total(expression) + if total is not None: + totals[self._engine.key(expression)] = total + self._totals = totals + self._completed_keys.intersection_update( + self._engine.key(expression) for expression in expressions.values() + ) + return changed + + def _cached(self, expressions): + try: + results = self._engine.cached(expressions) + self._engine.remember(expressions, results) + self._remember_totals(expressions, results) + return results + except Exception as error: + self._record_error(expressions, error) + return {} + + def _record_error(self, expressions, error): + prefix = 'unavailable' if isinstance(error, OSError) else 'error' + message = f'{prefix}: {error}; retry full summaries or locate the source' + for expression in expressions.values(): + key = self._engine.key(expression) + self._errors[key] = message + if len(self._errors) > 256: + self._errors.pop(next(iter(self._errors))) + + def _expression_total(self, expression): + key = self._engine.key(expression) + if key in self._totals: + return self._totals[key] + if not isinstance(expression, dict): + return None + if expression['kind'] == 'source': + value = self._source_counts.get(expression['unit']) + return None if value is None else int(value) + if expression['kind'] == 'union': + parts = [self._expression_total(part) for part in expression['parts']] + return None if any(part is None for part in parts) else sum(parts) + return None + + def _remember_totals(self, expressions, results): + for unit, result in results.items(): + if self._expressions.get(unit) == expressions[unit]: + key = self._engine.key(expressions[unit]) + self._totals[key] = int(result['counts'].sum()) + + def total_count(self, cluster_id): + """Keep exact scalar counts even when optional native-bin arrays are evicted.""" + if self._closed: + return None + self._refresh() + expression = self._expressions.get(int(cluster_id)) + if expression is None: + return None + total = self._expression_total(expression) + if total is None: + self.get_summary(cluster_id) + total = self._expression_total(expression) + return total + + def get_summary(self, cluster_id): + """Return readonly primitives for the unit's current expression, if ready.""" + if self._closed: + return None + self._refresh() + cluster_id = int(cluster_id) + expression = self._expressions.get(cluster_id) + if expression is None: + return None + return self._cached({cluster_id: expression}).get(cluster_id) + + def status(self, cluster_id): + """Describe missing source evidence without presenting sampled substitutes.""" + if self._closed: + return 'unavailable: summary service closed' + if self.get_summary(cluster_id) is not None: + return 'ready' + expression = self._expressions.get(int(cluster_id)) + if expression is None: + return 'unavailable: inactive unit' + key = self._engine.key(expression) + if key in self._errors: + return self._errors[key] + if key in self._completed_keys: + return 'unavailable: summary cache budget; retry full summaries' + if self._waiting_reason: + return self._waiting_reason + if self._suspended: + return 'cancelled: summary computation suspended' + if self._running is not None and key in self._running_keys: + return self._progress_text or 'validating source / recomputing full summaries' + return 'pending full summary computation' + + def synchronize(self): + """Coalesce requests until after transaction observers and rollback finish.""" + if not self._closed and not self._timer.isActive(): + self._timer.start(0) + + @pyqtSlot() + def _synchronize(self): + if self._closed: + return + self._refresh() + if self._expressions != self._announced_expressions: + self._announced_expressions = self._expressions + self.changed.emit() + if self._suspended or self._running is not None or not self._pending: + return + missing = {} + capacity = max(1, self._engine.max_bytes // self._engine.summary_bytes) + while self._pending and len(missing) < capacity: + cluster_id = next(iter(self._pending)) + expression = self._pending.pop(cluster_id) + if self._engine.key(expression) in self._errors: + continue + available = self._cached({cluster_id: expression}) + if not available and self._engine.key(expression) not in self._errors: + missing[cluster_id] = expression + if not missing: + return + expressions = deepcopy(missing) + cancel = Event() + self._running = cancel + self._running_keys = {self._engine.key(e) for e in expressions.values()} + self._progress_text = None + if self._worker is None: + self._worker = _SummaryWorker(self._package_path, self._source_path, self._delivery) + self._worker.submit(expressions, cancel) + self.changed.emit() + + @pyqtSlot(object) + def _progress(self, payload): + cancel, phase, done, total = payload + if self._closed or self._suspended or cancel is not self._running or cancel.is_set(): + return + self._refresh() + if not self._running_keys.intersection( + self._engine.key(e) for e in self._expressions.values() + ): + return + self._progress_text = f'{phase}: {min(100, int(100 * done / max(1, total)))}%' + self.changed.emit() + + @pyqtSlot(object) + def _completed(self, payload): + expressions, results, error, cancel = payload + if self._closed: + return + self._running = None + self._running_keys.clear() + self._progress_text = None + self._refresh() + # A cancelled/relocated source job must never overwrite a later retry. + if not cancel.is_set(): + if results: + self._engine.remember(expressions, results) + self._remember_totals(expressions, results) + current_keys = {self._engine.key(e) for e in self._expressions.values()} + self._completed_keys.update( + self._engine.key(expressions[unit]) for unit in results + ) + self._completed_keys.intersection_update(current_keys) + if error is not None and not isinstance(error, CancelledError): + self._record_error(expressions, error) + self._refresh() + if not self._suspended: + self.changed.emit() + self.synchronize() + + def _stop_worker(self): + if self._running is not None: + self._running.set() + if self._worker is not None: + self._worker.stop() + self._worker = None + + def retry(self, source_path=None): + """Retry failures, optionally using a relocated immutable source sorting.""" + if self._closed: + return + if source_path is not None: + self._source_path = Path(source_path) + self._errors.clear() + self._pending = dict(self._expressions) + self._stop_worker() + self.synchronize() + if not self._suspended: + self.changed.emit() + + def suspend(self): + """Cancel work after an accepted GUI close, retaining reusable results.""" + if self._closed: + return + self._suspended = True + self._timer.stop() + self._stop_worker() + + def pause(self, reason): + """Keep cached plots available while another task owns recording I/O.""" + self.suspend() + self._waiting_reason = str(reason) + self.changed.emit() + + def resume(self): + """Resume a newly attached GUI without touching curation persistence.""" + if not self._closed: + self._waiting_reason = None + self._suspended = False + self._pending = dict(self._expressions) + self.synchronize() + + def close(self): + """Cancel nonblocking; a late queued result cannot touch session or GUI.""" + if self._closed: + return + self.suspend() + self._closed = True + self._session = None + self._timer.stop() + self._engine.close() + self._delivery.finished.disconnect(self._completed) + self._delivery.progress.disconnect(self._progress) diff --git a/phy/apps/large_recording/summary_store.py b/phy/apps/large_recording/summary_store.py new file mode 100644 index 000000000..12eca4b05 --- /dev/null +++ b/phy/apps/large_recording/summary_store.py @@ -0,0 +1,527 @@ +"""Optional, independently budgeted unit-contiguous summary snapshot storage.""" + +import errno +import hashlib +import json +import os +import shutil +import tempfile +from collections import OrderedDict +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from threading import Lock +from time import sleep + +import numpy as np + +from .curation import _commit_lock, _fsync_directory, _safe_file +from .source import hash_json, publish_directory +from .streaming import UnitRows, bounded_map, worker_count + +VERSION = 1 +REFERENCE = 'live-summary-store.json' + + +def binding(engine, version=VERSION): + """Bind a store to the same exact source snapshot and native grid as summaries.""" + result = {'version': version, 'summary_binding': engine.binding} + if version == 2: + from .refractory_store import refractory_binding + + result['refractory_binding'] = refractory_binding(engine) + return result + + +def _atomic_json(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + temporary = None + try: + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream: + temporary = Path(stream.name) + stream.write(json.dumps(value, sort_keys=True).encode()) + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, path) + _fsync_directory(path.parent) + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + +def _bin_dtype(bins): + for dtype in ('uint8', 'uint16', 'uint32', 'uint64'): + if bins - 1 <= np.iinfo(dtype).max: + return np.dtype(dtype) + raise ValueError('Too many native summary bins.') + + +@dataclass(frozen=True) +class StoreEstimate: + payload_bytes: int + estimated_bytes: int + source_spikes: int + record_bytes: int + source_path: str + + +class SummaryStorePublishedError(OSError): + """A completed artifact remains available after finalization/attachment failed.""" + + def __init__(self, path, message): + self.path = Path(path) + super().__init__(message) + + +def _layout(engine, timestamps=False): + inventory = engine.manifest['source_array_inventory'] + names = {'spike_times.npy', 'spike_clusters.npy'} + specs = [('bin', _bin_dtype(engine.bins))] + scalar_names = {} + for field in engine.fields: + name = 'amplitudes.npy' if field == 'amplitude' else 'spike_depths.npy' + if name not in inventory and field == 'depth': + name = 'spike_positions.npy' + names.add(name) + scalar_names[field] = name + specs.append((field, np.dtype(inventory[name]['dtype']))) + if timestamps: + span = int(np.max(np.diff(engine.edges))) + specs.append(('tick_offset', _bin_dtype(span))) + return np.dtype(specs), names, scalar_names + + +def estimate_summary_store(package_path, source_dir=None, timestamps=False): + """Read package metadata only; use exactly the builder's disk calculation.""" + from .live_summaries import LiveSummaryEngine + + with LiveSummaryEngine(package_path, source_dir=source_dir) as engine: + dtype, _, _ = _layout(engine, timestamps) + count = int(engine.manifest['num_spikes']) + payload = count * dtype.itemsize + return StoreEstimate( + payload, + payload + 65536 + 512 * len(engine.manifest['unit_ids']), + count, + dtype.itemsize, + str(engine.source_dir), + ) + + +def build_summary_store( + package_path, + output_dir, + source_dir=None, + max_bytes=68719476736, + batch_size=1000000, + buffer_bytes=33554432, + cancel=None, + progress=None, + attach=True, + before_publish=None, + return_reference=False, + workers=1, + timestamps=False, +): + """Build an exact prepared-snapshot asset without modifying saved curation. + + The caller selects a new directory outside the bounded package. Source + validation is mandatory. Unit ranges preserve original row order. Bounded + batches and a globally capped write buffer avoid a recording-sized sort or + permutation. Publication never replaces an existing store. + """ + from .live_summaries import LiveSummaryEngine, _check_cancel + + worker_count(workers) + package_path, output_dir = Path(package_path).resolve(), Path(output_dir).resolve() + if output_dir == package_path or package_path in output_dir.parents: + raise ValueError('Summary store must be outside the bounded package.') + if output_dir.exists(): + raise ValueError(f'Summary store already exists: {output_dir}.') + if min(max_bytes, batch_size, buffer_bytes) <= 0: + raise ValueError('Summary store budgets must be positive.') + temporary = None + initial_reference = summary_store_reference(package_path, allow_invalid=True) + published_reference = None + with LiveSummaryEngine(package_path, source_dir=source_dir, batch_size=batch_size) as engine: + source_path = engine.source_dir.resolve() + if output_dir == source_path or source_path in output_dir.parents: + raise ValueError('Summary store must be outside the original source.') + dtype, names, scalar_names = _layout(engine, timestamps) + count = int(engine.manifest['num_spikes']) + payload_bytes = count * dtype.itemsize + # Includes the small catalog and headers, independently of bounded budgets. + estimate = payload_bytes + 65536 + 512 * len(engine.manifest['unit_ids']) + if estimate > max_bytes: + raise ValueError( + f'Summary store needs approximately {estimate:,} bytes; increase max_bytes.' + ) + output_dir.parent.mkdir(parents=True, exist_ok=True) + if shutil.disk_usage(output_dir.parent).free < estimate: + raise OSError(f'Insufficient free space for summary store: need {estimate:,} bytes.') + engine._open(names, cancel, progress=progress) + units = np.asarray(engine.manifest['unit_ids'], dtype=np.int64) + counts = np.asarray(engine.manifest['counts'], dtype=np.int64) + if np.any(counts < 0) or sum(map(int, counts)) != count: + raise ValueError('Invalid source unit counts.') + offsets = np.zeros(len(units) + 1, dtype=np.int64) + np.cumsum(counts, out=offsets[1:]) + lookup = UnitRows(units) + cursors = offsets[:-1].copy() + pending = np.zeros(len(units), dtype=np.int64) + digests = [hashlib.sha256() for _ in units] + buffers, buffered = OrderedDict(), 0 + # Divide the existing buffer allowance between packing work/results and + # buffered writes. More workers never multiply the scratch allowance. + packing_bytes = max(1, buffer_bytes // 2) + buffer_bytes = max(1, buffer_bytes - packing_bytes) + batch_size = min( + batch_size, max(1, packing_bytes // ((workers + 1) * (4 * dtype.itemsize + 96))) + ) + read_lock = Lock() + temporary = Path( + tempfile.mkdtemp(prefix=f'.{output_dir.name}.building-', dir=output_dir.parent) + ) + try: + with (temporary / 'data.bin').open('w+b') as stream: + stream.truncate(payload_bytes) + + def flush(unit): + nonlocal buffered + chunks = buffers.pop(unit) + stream.seek(int(cursors[unit]) * dtype.itemsize) + for chunk in chunks: + stream.write(chunk) + digests[unit].update(chunk) + cursors[unit] += len(chunk) // dtype.itemsize + buffered -= len(chunk) + pending[unit] -= len(chunk) // dtype.itemsize + + def read_rows(name, start, stop, axis=None): + array = engine.arrays[name] + width = int(np.prod(array.shape[1:])) + handle = engine.handles[name] + column = axis is not None and array.flags.f_contiguous + offset = ( + array.offset + + ((axis * len(array) + start) if column else start * width) + * array.dtype.itemsize + ) + size = (stop - start) * (1 if column else width) * array.dtype.itemsize + if hasattr(os, 'pread'): + raw = os.pread(handle.fileno(), size, offset) + else: + # Shared authenticated handles must never race seek/read. + with read_lock: + handle.seek(offset) + raw = handle.read(size) + if len(raw) != size: + raise ValueError('Source truncated during store construction.') + values = np.frombuffer(raw, dtype=array.dtype) + if column: + return values + values = values.reshape((stop - start, *array.shape[1:])) + return values[:, axis] if axis is not None else values + + def pack(start): + _check_cancel(cancel) + stop = min(count, start + batch_size) + times = read_rows('spike_times.npy', start, stop).reshape(-1) + if np.any(times < 0) or np.any(times >= engine.manifest['num_samples']): + raise ValueError('Source spike times outside recording bounds.') + assignments = read_rows('spike_clusters.npy', start, stop).reshape(-1) + rows = lookup(assignments) + # NumPy uses its native stable integer sort here. A Python + # counting scatter would add a loop over every source spike. + order = np.argsort(rows, kind='stable') + sorted_rows = rows[order] + data = np.empty(stop - start, dtype=dtype) + data['bin'] = np.searchsorted(engine.edges, times, side='right') - 1 + if timestamps: + if times.dtype.kind not in 'iu' or np.any(times > np.iinfo(np.int64).max): + raise ValueError('Exact timestamps require signed int64 ticks.') + data['tick_offset'] = times.astype(np.int64) - engine.edges[data['bin']] + for field, name in scalar_names.items(): + axis = ( + engine.manifest['source']['identity']['acquisition']['depth_axis'] + if name == 'spike_positions.npy' + else None + ) + data[field] = read_rows(name, start, stop, axis=axis).reshape(-1) + return stop, sorted_rows, data[order] + + for stop, sorted_rows, data in bounded_map( + pack, range(0, count, batch_size), workers + ): + _check_cancel(cancel) + boundaries = np.r_[0, np.flatnonzero(np.diff(sorted_rows)) + 1, len(data)] + for first, last in zip(boundaries[:-1], boundaries[1:]): + unit = int(sorted_rows[first]) + if cursors[unit] + pending[unit] + last - first > offsets[unit + 1]: + raise ValueError('Source unit count mismatch.') + chunk = data[first:last].tobytes() + if len(chunk) >= buffer_bytes: + if unit in buffers: + flush(unit) + stream.seek(int(cursors[unit]) * dtype.itemsize) + stream.write(chunk) + digests[unit].update(chunk) + cursors[unit] += last - first + continue + while buffers and buffered + len(chunk) > buffer_bytes: + flush(next(iter(buffers))) + buffers.setdefault(unit, []).append(chunk) + buffered += len(chunk) + pending[unit] += last - first + if buffered >= buffer_bytes: + flush(unit) + if progress: + progress('building summary store', stop, count) + if progress: + progress('finalizing summary store', 0, 0) + while buffers: + _check_cancel(cancel) + flush(next(iter(buffers))) + if not np.array_equal(cursors, offsets[1:]): + raise ValueError('Source unit counts changed.') + stream.flush() + os.fsync(stream.fileno()) + engine._unchanged() + catalog = { + 'binding': binding(engine, 2 if timestamps else VERSION), + 'capabilities': ['timestamps'] if timestamps else [], + 'dtype': dtype.descr, + 'payload_bytes': payload_bytes, + 'units': { + str(int(unit)): { + 'start': int(offsets[i]), + 'count': int(counts[i]), + 'sha256': digests[i].hexdigest(), + } + for i, unit in enumerate(units) + }, + } + _atomic_json(temporary / 'index.json', catalog) + actual_bytes = sum(p.stat().st_size for p in temporary.iterdir()) + if actual_bytes > max_bytes: + raise ValueError(f'Summary store exceeds max_bytes: {actual_bytes:,} bytes.') + _check_cancel(cancel) + # A GUI task may enter its noncancellable publication boundary here. + if before_publish is not None: + before_publish() + publish_directory(temporary, output_dir) + temporary = None + try: + _fsync_directory(output_dir.parent) + if attach: + if progress: + progress('attaching summary store', 0, 0) + _, published_reference = attach_summary_store( + package_path, + output_dir, + expected_reference=initial_reference, + check_cancel=lambda: _check_cancel(cancel), + return_reference=True, + ) + except (OSError, ValueError) as error: + raise SummaryStorePublishedError(output_dir, str(error)) from error + return (output_dir, published_reference) if return_reference else output_dir + finally: + if temporary is not None: + shutil.rmtree(temporary) + + +class StoreIntegrityError(ValueError): + """Disposable acceleration data failed its integrity contract.""" + + +class SummaryStore: + """Read and verify only requested units from a prepared source snapshot. + + This certifies the indexed snapshot, not the current contents of original + source files. Every consumed unit is hashed before its results can publish. + """ + + def __init__(self, engine, path=None): + reference = ( + json.loads(summary_store_reference(engine.path)) + if path is None + else {'path': str(path)} + ) + self.path = Path(reference['path']) + index_path = self.path / 'index.json' + if index_path.stat().st_size > 16777216: + raise StoreIntegrityError('Summary store catalog exceeds limit.') + self.index = json.loads(index_path.read_text()) + version = self.index['binding']['version'] + if version not in (1, 2): + raise StoreIntegrityError('Unsupported summary store version.') + if ( + 'index_sha256' in reference and hash_json(self.index) != reference['index_sha256'] + ) or self.index['binding'] != binding(engine, version): + raise StoreIntegrityError('Summary store binding mismatch.') + self.dtype = np.dtype([tuple(s) for s in self.index['dtype']]) + self.timestamps = version == 2 and self.index.get('capabilities') == ['timestamps'] + if version == 2 and not self.timestamps: + raise StoreIntegrityError('Invalid timestamp capability.') + expected, _, _ = _layout(engine, self.timestamps) + if self.dtype.hasobject or self.dtype != expected: + raise StoreIntegrityError('Summary store scalar dtype mismatch.') + end = 0 + for unit, count in zip(engine.manifest['unit_ids'], engine.manifest['counts']): + item = self.index['units'][str(unit)] + if item['start'] != end or item['count'] != count: + raise StoreIntegrityError('Summary store unit ranges mismatch.') + end += int(count) + if ( + set(self.index['units']) != set(map(str, engine.manifest['unit_ids'])) + or end * self.dtype.itemsize != self.index['payload_bytes'] + ): + raise StoreIntegrityError('Summary store payload mismatch.') + self.stream = (self.path / 'data.bin').open('rb') + try: + self.signature = os.fstat(self.stream.fileno()) + self.path_signature = (self.path / 'data.bin').stat() + if self.signature.st_size != self.index['payload_bytes']: + raise StoreIntegrityError('Summary store payload size mismatch.') + except BaseException: + self.close() + raise + + def close(self): + self.stream.close() + + def batches(self, unit, batch_size, cancel=None): + from .live_summaries import _check_cancel, _signature + + item = self.index['units'][str(unit)] + digest = hashlib.sha256() + for start in range(0, item['count'], batch_size): + _check_cancel(cancel) + size = min(batch_size, item['count'] - start) * self.dtype.itemsize + self.stream.seek((item['start'] + start) * self.dtype.itemsize) + raw = self.stream.read(size) + if len(raw) != size: + raise StoreIntegrityError('Truncated summary store.') + digest.update(raw) + yield np.frombuffer(raw, dtype=self.dtype) + if digest.hexdigest() != item['sha256']: + raise StoreIntegrityError('Summary store unit checksum mismatch.') + if _signature(os.fstat(self.stream.fileno())) != _signature(self.signature) or _signature( + (self.path / 'data.bin').stat() + ) != _signature(self.path_signature): + raise StoreIntegrityError('Summary store changed while reading.') + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +@contextmanager +def _attachment_lock(path, check_cancel=None): + if check_cancel is None: + with _commit_lock(path): + yield + return + with _safe_file(path, 'commit.lock').open('a+b') as stream: + if os.name == 'nt': + import msvcrt + + stream.seek(0, os.SEEK_END) + if stream.tell() == 0: + stream.write(b'\0') + stream.flush() + + def acquire(): + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) + + def release(): + stream.seek(0) + msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) + else: + import fcntl + + def acquire(): + fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) + + def release(): + fcntl.flock(stream.fileno(), fcntl.LOCK_UN) + + while True: + check_cancel() + try: + acquire() + break + except OSError as error: + if error.errno not in (errno.EACCES, errno.EAGAIN, errno.EDEADLK): + raise + sleep(0.05) + try: + check_cancel() + yield + finally: + release() + + +_ANY_REFERENCE = object() + + +@dataclass(frozen=True) +class ReferenceStamp: + signature: tuple + + +def summary_store_reference(package_path, allow_invalid=False): + path = Path(package_path) / '.phy' / REFERENCE + try: + stat = path.stat() + if stat.st_size > 65536: + if allow_invalid: + return ReferenceStamp( + (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) + ) + raise ValueError('Summary store reference exceeds limit.') + return path.read_bytes() + except FileNotFoundError: + return None + + +def attach_summary_store( + package_path, + store_path, + expected_reference=_ANY_REFERENCE, + before_attach=None, + check_cancel=None, + return_reference=False, +): + """Attach a snapshot under a short cross-process reference lock. + + An optional expected reference prevents overwriting a newer user choice. + Payload integrity checks remain selective during use. + """ + from .live_summaries import LiveSummaryEngine + + with LiveSummaryEngine(package_path) as engine, SummaryStore(engine, path=store_path) as store: + lock_path = engine.path / '.phy' / 'summary-store-attachment' + lock_path.mkdir(parents=True, exist_ok=True) + with _attachment_lock(lock_path, check_cancel): + if ( + expected_reference is not _ANY_REFERENCE + and summary_store_reference(engine.path, allow_invalid=True) != expected_reference + ): + raise ValueError( + 'The attached summary store changed while this build was running; attach the completed store manually.' + ) + if before_attach is not None: + before_attach() + reference = { + 'path': str(store.path.resolve()), + 'index_sha256': hash_json(store.index), + } + _atomic_json(engine.path / '.phy' / REFERENCE, reference) + if return_reference: + return Path(store_path), json.dumps(reference, sort_keys=True).encode() + return Path(store_path) diff --git a/phy/apps/large_recording/summary_task_gui.py b/phy/apps/large_recording/summary_task_gui.py new file mode 100644 index 000000000..1279d3f90 --- /dev/null +++ b/phy/apps/large_recording/summary_task_gui.py @@ -0,0 +1,571 @@ +"""Dataset-specific store controls on top of reusable background task UI.""" + +import shutil +from contextlib import suppress +from dataclasses import dataclass, replace +from pathlib import Path +from uuid import uuid4 + +from phylib.utils import connect, unconnect +from PyQt5 import sip +from PyQt5.QtWidgets import QFileDialog + +from phy.gui.qt import ( + QApplication, + QCheckBox, + QDialog, + QHBoxLayout, + QLabel, + QLineEdit, + QObject, + QPushButton, + QSpinBox, + Qt, + QTimer, + QVBoxLayout, + pyqtSignal, +) +from phy.gui.task_widgets import TaskWidget +from phy.gui.tasks import BackgroundTaskManager, TaskSpec + +from .summary_store import summary_store_reference +from .summary_tasks import ( + StoreRequest, + connect_amplitude_index, + connect_summary_store, + inspect_summary_store, + prepare_amplitude_index, + prepare_summary_store, +) + + +def _free_space(path): + path = Path(path).expanduser().resolve().parent + while not path.exists() and path != path.parent: + path = path.parent + return shutil.disk_usage(path).free + + +@dataclass(frozen=True) +class DestinationRequest: + text: str + package: str = '' + source: str = '' + + +@dataclass(frozen=True) +class DestinationStatus: + text: str + free_bytes: int + exists: bool + problem: str = '' + + +def check_destination(request, context): + context.check_cancel() + path = Path(request.text).expanduser() + free = _free_space(path) + exists = path.exists() + context.check_cancel() + problem = '' + destination = path.resolve() + for label, root in [('bounded package', request.package), ('original source', request.source)]: + if root: + root = Path(root).resolve() + if destination == root or root in destination.parents: + problem = f'Choose a destination outside the {label}.' + return DestinationStatus(request.text, free, exists, problem) + + +class StorePrompt(QDialog): + """Nonmodal opt-in; no source scans or allocation occur in this dialog.""" + + build_requested = pyqtSignal(str, bool, object) + continued = pyqtSignal(bool) + + def __init__( + self, + inspection, + destination, + suppressed=False, + parent=None, + max_bytes=68719476736, + package='', + ): + super().__init__(parent) + self.inspection = inspection + self.package = package + self._preflight_closed = False + self._disk_key = uuid4().hex + self._disk_manager = BackgroundTaskManager() + self._disk_manager.finished.connect(self._disk_finished) + self._disk_timer = QTimer(self) + self._disk_timer.setSingleShot(True) + self._disk_timer.setInterval(250) + self._disk_timer.timeout.connect(self._disk_check) + self.finished.connect(self._dispose_preflight) + self.destroyed.connect(lambda *_: self._dispose_preflight()) + self.setWindowTitle('Prepare faster full-recording summaries?') + self.setAttribute(Qt.WA_ShowWithoutActivating, True) + layout = QVBoxLayout(self) + text = 'Prepare faster full-recording rate and trend updates after amplitude splits. This one-time task can take a while. You can keep curating while it runs.' + explanation = QLabel(text, self) + explanation.setWordWrap(True) + layout.addWidget(explanation) + layout.addWidget( + QLabel( + f'Estimated additional space: {(inspection.additional_bytes or inspection.estimate.estimated_bytes) / 1e9:.2f} GB', + self, + ) + ) + if inspection.peak_bytes: + layout.addWidget( + QLabel( + f'Free space needed during preparation: {inspection.peak_bytes / 1e9:.2f} GB; ' + f'combined store estimate: {inspection.budget_bytes / 1e9:.2f} GB', + self, + ) + ) + row = QHBoxLayout() + self.destination = QLineEdit(str(destination), self) + self.choose = QPushButton('Choose parent folder…', self) + row.addWidget(self.destination) + row.addWidget(self.choose) + layout.addLayout(row) + self.budget = QSpinBox(self) + self.budget.setRange(1, 1048576) + self.budget.setValue(max(1, int(max_bytes) // 1073741824)) + self.budget.setSuffix(' GiB store budget') + self.budget.valueChanged.connect(self._check) + layout.addWidget(self.budget) + self.available = QLabel('', self) + self.problem = QLabel('', self) + layout.addWidget(self.available) + layout.addWidget(self.problem) + self.suppress = QCheckBox('Don’t ask again for this dataset', self) + self.suppress.setChecked(suppressed) + layout.addWidget(self.suppress) + buttons = QHBoxLayout() + self.build_button = QPushButton('Build in background', self) + self.continue_button = QPushButton('Continue without', self) + buttons.addWidget(self.build_button) + buttons.addWidget(self.continue_button) + layout.addLayout(buttons) + self.choose.clicked.connect(self._choose) + self.destination.textChanged.connect(self._check) + self.build_button.clicked.connect(self._build) + self.continue_button.clicked.connect(self._continue) + self._check() + self.resize(750, 320) + + def _choose(self): + parent = QFileDialog.getExistingDirectory( + self, 'Choose parent folder for the new summary store' + ) + if parent: + self.destination.setText(str(Path(parent) / 'summary-store')) + + def _check(self): + if self._preflight_closed: + return + self.build_button.setEnabled(False) + self.available.setText('Checking available space…') + self.problem.setText('') + if self._disk_manager.busy: + self._disk_manager.cancel() + self._disk_timer.start() + + def _disk_check(self): + if self._disk_manager.busy: + return # Its terminal callback starts only the latest requested path. + text = self.destination.text() + if not text.strip(): + self.problem.setText('Choose a destination for the new store.') + return + self._disk_manager.submit( + TaskSpec( + f'destination:{self._disk_key}', + 'Checking destination', + check_destination, + DestinationRequest(text, self.package, self.inspection.estimate.source_path), + heavy=False, + ) + ) + + def _disk_finished(self, outcome): + if self._preflight_closed: + return + if self._disk_manager.spec.request.text != self.destination.text(): + self._disk_timer.start(0) + return + if outcome.state == 'cancelled': + self._disk_timer.start(0) + return + if outcome.state == 'failed': + self.problem.setText(outcome.error) + return + result = outcome.result + self.available.setText(f'Available space: {result.free_bytes / 1e9:.2f} GB') + problem = result.problem + if result.exists: + problem = ( + 'Choose a new directory. Use File > Attach summary store for an existing store.' + ) + elif result.free_bytes < ( + self.inspection.peak_bytes or self.inspection.estimate.estimated_bytes + ): + problem = 'There is not enough free space at this location.' + elif ( + self.inspection.budget_bytes or self.inspection.estimate.estimated_bytes + ) > self.budget.value() * 1073741824: + problem = 'The estimate exceeds the store budget. Increase the budget to build.' + elif not self.inspection.source_available: + problem = 'Source unavailable. Use File > Locate summary source, or attach an existing store.' + self.problem.setText(problem) + self.build_button.setEnabled(not problem) + + def _dispose_preflight(self, *args): + if self._preflight_closed: + return + self._preflight_closed = True + with suppress(TypeError, RuntimeError): + self._disk_timer.stop() + with suppress(TypeError, RuntimeError): + self._disk_manager.finished.disconnect(self._disk_finished) + self._disk_manager.detach() + + def _build(self): + if self.build_button.isEnabled(): + self.build_requested.emit( + self.destination.text(), + self.suppress.isChecked(), + self.budget.value() * 1073741824, + ) + self.accept() + + def _continue(self): + self.continued.emit(self.suppress.isChecked()) + self.reject() + + +class SummaryStoreActions(QObject): + """Own one GUI generation; workers receive only frozen request snapshots.""" + + def __init__(self, controller, gui): + super().__init__(gui) + self.controller, self.gui = controller, gui + self.package = str(controller.dir_path) + self.service = controller._live_summaries + self.manager = BackgroundTaskManager() + self.widget = TaskWidget(self.manager, gui) + gui._status_bar.addPermanentWidget(self.widget, 1) + self.widget.hide() + self.dialog = None + self._closed = self._checked = self._paused = False + self._manual = False + self._mode = None + self._request = None + self._inspection = None + self._prepare_ranges = False + self._binding = controller.bounded_session.manifest.get('preparation_identity', '') + gui.state.add_local_keys( + ['SummaryStore.suppress_prompt', 'SummaryStore.destination', 'SummaryStore.max_bytes'] + ) + self.manager.finished.connect(self._finished) + # Some embedders delete the GUI before closing its controller. + gui.destroyed.connect(lambda: self.close()) + + @gui.file_actions.add + def build_summary_store(): + """Prepare a reusable summary store in the background.""" + self.build_dialog() + + @gui.file_actions.add + def attach_summary_store(): + """Attach an existing compatible store, including a relocated one.""" + if self.manager.busy: + self.widget.show() + return + path = QFileDialog.getExistingDirectory(gui, 'Attach summary store') + if path: + self.attach(path) + + @gui.file_actions.add + def attach_amplitude_index(): + """Attach a compatible amplitude index stored separately from its row store.""" + if self.manager.busy: + self.widget.show() + return + path = QFileDialog.getExistingDirectory(gui, 'Attach amplitude index') + if path: + self.attach_index(path) + + @gui.file_actions.add + def show_background_task(): + """Show progress and details for the current background task.""" + self.widget.show() + + @connect(event='closed', sender=gui) + def on_closed(sender): + self.close() + + self._on_closed = on_closed + + @connect(event='show', sender=gui) + def on_shown(sender): + QTimer.singleShot(0, self._automatic_check) + + self._on_shown = on_shown + if gui.isVisible(): + QTimer.singleShot(0, self._automatic_check) + + def _valid(self): + return ( + not self._closed + and not self.gui._closed + and self.controller.bounded_session.manifest.get('preparation_identity', '') + == self._binding + ) + + def _automatic_check(self): + if self._checked or not self._valid(): + return + self._checked = True + if not self.gui.state.get('SummaryStore', {}).get('suppress_prompt', False): + self._inspect() + + def _request_for(self, destination=''): + try: + source = self.gui.state.get('LiveSummaries', {}).get('source_path') + return StoreRequest( + self.package, + source, + destination, + summary_store_reference(self.package, allow_invalid=True), + dataset_id=self._binding, + ) + except (OSError, ValueError) as error: + self.widget.notice(f'Could not read summary-store settings: {error}') + return None + + def _submit(self, mode, worker, request, heavy): + if request is None: + self._resume() + return + self._mode, self._request = mode, request + try: + self.manager.submit( + TaskSpec( + f'summary-store:{mode}:{self.package}:{self._binding}', + { + 'inspect': 'Checking summary store', + 'build': 'Preparing faster summaries', + 'attach': 'Attaching summary store', + 'build-range': 'Preparing fast amplitude splits', + 'attach-range': 'Attaching amplitude index', + }[mode], + worker, + request, + heavy=heavy, + ) + ) + except (ValueError, TypeError, OSError) as error: + self.widget.notice(str(error)) + self._resume() + + def _inspect(self): + if not self._valid() or self.manager.busy: + return + self._submit('inspect', inspect_summary_store, self._request_for(), False) + + def build_dialog(self): + if not self._valid(): + return + if self.dialog is not None and self.dialog.isVisible(): + self.dialog.raise_() + self.dialog.activateWindow() + return + self._manual = True + if self.manager.busy: + if self._mode != 'inspect': + self.widget.show() + return + self._inspect() + + def _remember(self, suppress, destination=None): + state = dict(self.gui.state.get('SummaryStore', {})) + state['suppress_prompt'] = bool(suppress) + if destination is not None: + state['destination'] = str(destination) + self.gui.state['SummaryStore'] = state + + def build(self, destination, suppress=False, max_bytes=68719476736): + if not self._valid() or self.manager.busy: + return + self._remember(suppress, destination) + self.gui.state['SummaryStore']['max_bytes'] = int(max_bytes) + request = self._request_for(str(Path(destination).expanduser().absolute())) + if request is None: + return + request = replace(request, max_bytes=int(max_bytes)) + self._paused = True + self.service.pause('waiting for summary-store preparation') + inspection = self._inspection + self._prepare_ranges = inspection is None or inspection.range_supported + if inspection is not None and inspection.compatible and inspection.range_supported: + self._submit('build-range', prepare_amplitude_index, request, True) + else: + self._submit('build', prepare_summary_store, request, True) + + def attach(self, path): + if not self._valid() or self.manager.busy: + return + self._prepare_ranges = False + self._paused = True + self.service.pause('waiting for summary-store attachment') + self._submit( + 'attach', + connect_summary_store, + self._request_for(str(Path(path).expanduser().absolute())), + False, + ) + + def attach_index(self, path): + if not self._valid() or self.manager.busy: + return + self._prepare_ranges = False + self._paused = True + self.service.pause('waiting for amplitude-index attachment') + self._submit( + 'attach-range', + connect_amplitude_index, + self._request_for(str(Path(path).expanduser().absolute())), + False, + ) + + def _resume(self): + if self._paused and self._valid(): + self._paused = False + self.service.resume() + + def _finished(self, outcome): + if not self._valid(): + return + mode, request = self._mode, self._request + if outcome.state != 'succeeded': + self._resume() + if mode in ('attach', 'attach-range'): + self.widget.notice( + f'Store remains at {request.destination}; attachment did not complete. See Details.' + ) + return + if mode == 'inspect': + self.widget.hide() + inspection = self._inspection = outcome.result + if ( + inspection.compatible + and (inspection.optimized or not inspection.range_supported) + and not self._manual + ): + return + state = self.gui.state.get('SummaryStore', {}) + destination = state.get('destination', self.package + '.summary-store') + if inspection.compatible and inspection.range_supported: + destination = str(Path(inspection.path) / 'amplitude-index') + if Path(destination).exists(): + destination += '-' + uuid4().hex[:8] + self.dialog = StorePrompt( + inspection, + destination, + state.get('suppress_prompt', False), + self.gui, + max_bytes=state.get('max_bytes', 68719476736), + package=self.package, + ) + self.dialog.build_requested.connect(self.build) + self.dialog.continued.connect(self._remember) + active, focus = QApplication.activeWindow(), QApplication.focusWidget() + self.dialog.setAttribute(Qt.WA_ShowWithoutActivating, not self._manual) + self.dialog.show() + if self._manual: + self.dialog.raise_() + self.dialog.activateWindow() + else: + # Native platform activation may arrive after QWidget.show(). + QTimer.singleShot(0, lambda: self._restore_activation(active, focus)) + self._manual = False + elif mode in ('build', 'build-range'): + if self.manager.cancellation_requested: + self._prepare_ranges = False + artifact = outcome.result + if artifact.warning: + self.widget.notice( + f'Store created; finalization needs attention. See Details. Path: {artifact.path}' + ) + self.widget.log.appendPlainText(artifact.warning) + self._resume() + else: + self._submit( + 'attach-range' if mode == 'build-range' else 'attach', + connect_amplitude_index if mode == 'build-range' else connect_summary_store, + replace(request, destination=artifact.path), + False, + ) + elif mode == 'attach' and (self._prepare_ranges or outcome.result.amplitude_index): + self.service.retry() + # A committed row snapshot remains usable after cancellation; avoid + # starting another long task if cancellation arrived during commit. + if self.manager.cancellation_requested: + self.service.retry() + self._resume() + self.widget.notice('Summary store ready; amplitude-index preparation cancelled.') + return + self._submit( + 'build-range' if self._prepare_ranges else 'attach-range', + prepare_amplitude_index if self._prepare_ranges else connect_amplitude_index, + replace( + request, + destination=( + str(Path(outcome.result.path) / 'amplitude-index') + if self._prepare_ranges + else outcome.result.amplitude_index + ), + expected_reference=outcome.result.reference, + ), + self._prepare_ranges, + ) + elif mode in ('attach', 'attach-range'): + self.service.retry() + self._resume() + self.widget.notice('Summary store ready. New splits use the prepared store.') + + def _restore_activation(self, active, focus): + # Reassert the GUI even if it is still active: native activation of + # the newly shown dialog may already be queued behind this callback. + if not self._valid() or QApplication.activeWindow() not in (self.dialog, None, self.gui): + return + target = active if active is not None and not sip.isdeleted(active) else self.gui + target.activateWindow() + if target.windowHandle() is not None: + target.windowHandle().requestActivate() + QApplication.setActiveWindow(target) + if focus is not None and not sip.isdeleted(focus): + focus.setFocus(Qt.OtherFocusReason) + + def close(self): + if self._closed: + return + self._closed = True + with suppress(TypeError, RuntimeError): + self.manager.finished.disconnect(self._finished) + try: + self.widget.dispose() + finally: + try: + self.manager.detach() + finally: + try: + if self.dialog is not None and not sip.isdeleted(self.dialog): + self.dialog.close() + finally: + unconnect(self._on_closed, self._on_shown) diff --git a/phy/apps/large_recording/summary_tasks.py b/phy/apps/large_recording/summary_tasks.py new file mode 100644 index 000000000..c89c06f9c --- /dev/null +++ b/phy/apps/large_recording/summary_tasks.py @@ -0,0 +1,221 @@ +"""Immutable adapters between summary snapshots and generic GUI tasks.""" + +import json +from dataclasses import dataclass +from pathlib import Path + +from phy.gui.tasks import TaskProgress + +from .live_summaries import LiveSummaryEngine +from .summary_store import ( + ReferenceStamp, + StoreEstimate, + SummaryStore, + SummaryStorePublishedError, + attach_summary_store, + build_summary_store, + estimate_summary_store, +) + + +@dataclass(frozen=True) +class StoreRequest: + package: str + source: str | None = None + destination: str = '' + expected_reference: bytes | ReferenceStamp | None = None + max_bytes: int = 68719476736 + dataset_id: str = '' + + +@dataclass(frozen=True) +class StoreInspection: + estimate: StoreEstimate + compatible: bool + source_available: bool + path: str = '' + optimized: bool = False + range_supported: bool = True + additional_bytes: int = 0 + peak_bytes: int = 0 + budget_bytes: int = 0 + + +@dataclass(frozen=True) +class StoreArtifact: + path: str + warning: str = '' + reference: bytes | None = None + amplitude_index: str = '' + + +def _check_binding(request, context): + context.check_cancel() + if request.dataset_id: + manifest = json.loads((Path(request.package) / '_phy_curation_manifest.json').read_text()) + if manifest.get('preparation_identity', '') != request.dataset_id: + raise ValueError('The prepared dataset changed; reopen it before starting this task.') + + +def inspect_summary_store(request, context): + _check_binding(request, context) + estimate = estimate_summary_store(request.package, source_dir=request.source) + from .range_build import estimate_range_index + from .range_index import AmplitudeRangeIndex + from .range_intervals import RangeUnavailableError + + available = Path(estimate.source_path).is_dir() + compatible, optimized, supported, path = False, False, True, '' + with LiveSummaryEngine(request.package) as engine: + try: + with SummaryStore(engine) as store: + compatible, path = True, str(store.path) + estimate = estimate_summary_store( + request.package, source_dir=request.source, timestamps=store.timestamps + ) + available = True # Existing rows are sufficient; original source may be offline. + except (OSError, ValueError, KeyError, TypeError): + pass + try: + ranges = estimate_range_index(engine) + additional = ranges.final_bytes + (0 if compatible else estimate.estimated_bytes) + peak = ranges.peak_extra_bytes + (0 if compatible else estimate.estimated_bytes) + budget = ranges.final_bytes + estimate.estimated_bytes + except RangeUnavailableError: + supported = False + additional = peak = budget = estimate.estimated_bytes + if compatible and supported: + try: + index = AmplitudeRangeIndex(engine) + try: + optimized = index.indexed_units == set(engine.manifest['unit_ids']) + finally: + index.close() + except (OSError, ValueError, KeyError, TypeError): + pass + return StoreInspection( + estimate, compatible, available, path, optimized, supported, additional, peak, budget + ) + + +def prepare_summary_store(request, context): + _check_binding(request, context) + + def cancel(): + context.check_cancel() + return False + + def commit(): + _check_binding(request, context) + context.commit() + + def progress(phase, done, total): + stages = { + 'validating source': ('Validating source', 'bytes'), + 'building summary store': ('Building summary store', 'rows'), + 'finalizing summary store': ('Finalizing', ''), + } + stage, unit = stages[phase] + context.report( + TaskProgress(stage, int(done) if total else None, int(total) if total else None, unit) + ) + + try: + path = build_summary_store( + request.package, + request.destination, + source_dir=request.source, + max_bytes=request.max_bytes, + cancel=cancel, + progress=progress, + attach=False, + before_publish=commit, + ) + return StoreArtifact(str(path)) + except SummaryStorePublishedError as error: + return StoreArtifact(str(error.path), str(error)) + + +def connect_summary_store(request, context): + context.report(TaskProgress('Attaching summary store')) + _check_binding(request, context) + + def commit(): + _check_binding(request, context) + context.commit() + + _, reference = attach_summary_store( + request.package, + request.destination, + expected_reference=request.expected_reference, + before_attach=commit, + check_cancel=context.check_cancel, + return_reference=True, + ) + candidate = Path(request.destination) / 'amplitude-index' + return StoreArtifact( + request.destination, + reference=reference, + amplitude_index=str(candidate) if candidate.is_dir() else '', + ) + + +def prepare_amplitude_index(request, context): + from .range_build import build_amplitude_index + from .summary_store import summary_store_reference + + _check_binding(request, context) + if summary_store_reference(request.package, allow_invalid=True) != request.expected_reference: + raise ValueError('The attached summary store changed; prepare its accelerator again.') + + def cancel(): + context.check_cancel() + return False + + def commit(): + _check_binding(request, context) + context.commit() + + def progress(phase, done, total): + context.report( + TaskProgress( + phase.capitalize(), + int(done), + int(total), + 'rows' if phase == 'sorting amplitude ranges' else 'bytes', + ) + ) + + try: + path = build_amplitude_index( + request.package, + request.destination, + max_bytes=request.max_bytes, + cancel=cancel, + progress=progress, + before_publish=commit, + attach=False, + ) + return StoreArtifact(str(path)) + except SummaryStorePublishedError as error: + return StoreArtifact(str(error.path), str(error)) + + +def connect_amplitude_index(request, context): + from .range_index import attach_amplitude_index + + context.report(TaskProgress('Attaching amplitude index')) + _check_binding(request, context) + + def commit(): + _check_binding(request, context) + context.commit() + + attach_amplitude_index( + request.package, + request.destination, + expected_reference=request.expected_reference, + before_attach=commit, + check_cancel=context.check_cancel, + ) + return StoreArtifact(request.destination) diff --git a/phy/apps/large_recording/supervisor.py b/phy/apps/large_recording/supervisor.py new file mode 100644 index 000000000..7f172919b --- /dev/null +++ b/phy/apps/large_recording/supervisor.py @@ -0,0 +1,921 @@ +"""Guarded native commands paired with semantic state, history and checkpoints.""" + +from contextlib import contextmanager +from copy import deepcopy +from functools import wraps +from types import MappingProxyType + +import numpy as np +from phylib.utils import emit + +from phy.cluster._history import History +from phy.cluster._utils import ClusterMeta +from phy.cluster.clustering import Clustering, _concatenate_spike_clusters +from phy.cluster.supervisor import Supervisor, _is_group_masked + +from .curation import evaluate_predicate, interpret_events + + +def _table_values_equal(previous, current): + """Compare display values without assuming a scalar metric result.""" + if isinstance(previous, np.ndarray) or isinstance(current, np.ndarray): + for equal_nan in (True, False): + try: + return bool(np.array_equal(previous, current, equal_nan=equal_nan)) + except (TypeError, ValueError): + # Object/string arrays do not necessarily support isnan. If a + # nested object also has ambiguous equality, refresh its value. + continue + return False + try: + return bool(previous == current) + except (TypeError, ValueError): + return False + + +class MutationPolicy: + """Only semantic commands may mutate native bounded state.""" + + def __init__(self): + self.depth = 0 + + def require(self): + if not self.depth: + raise ValueError( + 'Bounded curation requires a semantic command. Use supervisor.merge(), ' + 'supervisor.label(), or split_source_amplitude(); arbitrary splits are unavailable.' + ) + + @contextmanager + def command(self): + self.depth += 1 + try: + yield + finally: + self.depth -= 1 + + +class GuardedClustering(Clustering): + def __init__(self, *args, policy, **kwargs): + self.policy = policy + super().__init__(*args, **kwargs) + + @property + def spike_clusters(self): + result = self._spike_clusters.view() + result.flags.writeable = bool(getattr(self, '_internal_merge_write', False)) + return result + + @property + def cluster_ids(self): + result = self._cluster_ids.view() + result.flags.writeable = False + return result + + @property + def spikes_per_cluster(self): + return MappingProxyType(self._spikes_per_cluster) + + def _update_cluster_ids(self, *args, **kwargs): + super()._update_cluster_ids(*args, **kwargs) + for ids in self._spikes_per_cluster.values(): + ids.flags.writeable = False + + def _do_merge(self, *args, **kwargs): + # The native primitive writes through its public property. Restrict that + # permission to the primitive itself, before any observer is called. + self._internal_merge_write = True + try: + return super()._do_merge(*args, **kwargs) + finally: + self._internal_merge_write = False + + def merge(self, *args, **kwargs): + self.policy.require() + return super().merge(*args, **kwargs) + + def restore_partition(self, *args, **kwargs): + self.policy.require() + return super().restore_partition(*args, **kwargs) + + def assign(self, *args, **kwargs): + self.policy.require() + return super().assign(*args, **kwargs) + + def reset(self): + self.policy.require() + return super().reset() + + def undo(self): + self.policy.require() + transition = getattr(self, '_bounded_transition', lambda: None)() + if transition is None: + return super().undo() + item = self._undo_stack.back() + if item is None: + return None + _, _, undo_state = item + pairs = [ + (rows, np.full(len(rows), unit, dtype=np.int64)) + for unit, rows in transition.old_groups.items() + if len(rows) + ] + spike_ids, clusters = _concatenate_spike_clusters(*pairs) + up = self._do_assign(spike_ids, clusters) + up.history, up.undo_state = 'undo', undo_state + emit('cluster', self, up) + return up + + def redo(self): + self.policy.require() + return super().redo() + + +class GuardedMeta(ClusterMeta): + def __init__(self, policy): + self.policy = policy + super().__init__() + + def set(self, *args, **kwargs): + self.policy.require() + return super().set(*args, **kwargs) + + def add_field(self, *args, **kwargs): + self.policy.require() + return super().add_field(*args, **kwargs) + + def from_dict(self, *args, **kwargs): + self.policy.require() + return super().from_dict(*args, **kwargs) + + def undo(self): + self.policy.require() + return super().undo() + + def redo(self): + self.policy.require() + return super().redo() + + +class SessionHistory(History): + def __init__(self, session): + self.session = session + super().__init__(session.journal_state()) + + def capture(self): + self.add(self.session.journal_state()) + + def undo(self): + self.back() + self.session.restore_journal(self.current_item) + + def redo(self): + self.forward() + self.session.restore_journal(self.current_item) + + +def semantic_command(method): + @wraps(method) + def execute(self, *args, **kwargs): + self._settle_selection() + with self._transaction(): + return method(self, *args, **kwargs) + + return execute + + +class BoundedSupervisor(Supervisor): + """Native UI/history operations paired with a validated semantic journal.""" + + def __init__(self, *args, session, metadata_independent_metrics=None, **kwargs): + self.session = session + self._metadata_independent_metrics = dict(metadata_independent_metrics or {}) + self._bounded_table_revision = session.membership_revision + self._bounded_table_metadata = session.metadata + self._bounded_metadata_ids = set() + self.policy = MutationPolicy() + self.select_actions = None + self.cluster_view = None + self.similarity_view = None + + def clustering_factory(*args, **kwargs): + return GuardedClustering(*args, policy=self.policy, **kwargs) + + def meta_factory(groups, labels): + meta = GuardedMeta(self.policy) + data = {} + for field, values in labels.items(): + for cluster, value in values.items(): + data.setdefault(cluster, {})[field] = value + with self.policy.command(): + meta.add_field('group') + meta.from_dict(data) + return meta + + # Generation state supersedes disposable clustering caches. + kwargs['context'] = None + kwargs['new_cluster_id'] = session.next_cluster_id + kwargs['clustering_factory'] = clustering_factory + kwargs['cluster_meta_factory'] = meta_factory + super().__init__(*args, **kwargs) + self._metadata_independent_metrics['n_spikes'] = self.cluster_metrics['n_spikes'] + self.session_history = SessionHistory(session) + self._saved_data_events = tuple(session.events) + self.clustering._bounded_transition = self._native_undo_transition + self.parent_origins.update(session.restored_parent_ids) + self._proposition_projection_key = None + self._validate_native(metadata=False, full=True) + # Native construction already made the same immutable row index. + self.session._assignment_groups = dict(self.clustering.spikes_per_cluster) + + def _native_undo_transition(self): + events = self.session.events + if not events: + return None + transition = self.session._transitions.get(id(events[-1])) + if ( + transition is None + or transition.after is not self.session._runtime + or not transition.old_groups + ): + return None + return transition + + def recovery_token(self): + reviews = ( + tuple(self.merge_propositions.catalog.reviews.items()) + if self.merge_propositions is not None + else self.session.extra_documents.get('curation_review.json') + ) + return ( + tuple(self.session.events), + max(self.session.next_cluster_id, self.clustering.new_cluster_id()), + reviews, + ) + + @contextmanager + def _transaction(self): + self._recovery_depth = getattr(self, '_recovery_depth', 0) + 1 + try: + with self._transaction_state(): + yield + finally: + self._recovery_depth -= 1 + recovery = getattr(self, 'recovery', None) + if self._recovery_depth == 0 and recovery is not None: + # Failed commands may consume allocator IDs, but their provisional + # assignments/reviews have already been rolled back at this point. + recovery.observe() + + @contextmanager + def _transaction_state(self): + """Roll native and semantic state back if an observer or command fails.""" + clustering = self.clustering + arrays = ( + clustering._spike_clusters, + dict(clustering._spikes_per_cluster), + clustering._cluster_ids.copy(), + ) + data, fields = deepcopy(self.cluster_meta._data), dict(self.cluster_meta._fields) + parent_origins = dict(self.parent_origins) + restored_partitions = dict(clustering._restored_partitions) + lineage = self.parent_lineage + lineage_state = ( + ( + dict(lineage.records), + dict(lineage.color_records), + dict(lineage.origins), + dict(lineage.restorations), + ) + if lineage is not None + else None + ) + histories = [ + clustering._undo_stack, + self.cluster_meta._undo_stack, + self._global_history, + self.session_history, + ] + if self.merge_propositions is not None: + histories.append(self.merge_propositions._history) + history_states = [(list(h._history), h._index) for h in histories] + journal, selection, dirty = ( + self.session.journal_state(), + self.selection.snapshot(), + self._is_dirty, + ) + propositions = ( + self.merge_propositions.snapshot() if self.merge_propositions is not None else None + ) + workflow, columns = self._workflow_context(), list(self.columns) + try: + yield + except Exception: + clustering._spike_clusters, clustering._spikes_per_cluster, clustering._cluster_ids = ( + arrays + ) + # The old per-unit row arrays are immutable. Reconstruct on failure + # instead of copying the complete assignment vector on every command. + for cluster, rows in arrays[1].items(): + clustering._spike_clusters[rows] = cluster + self.cluster_meta._data, self.cluster_meta._fields = data, fields + self.parent_origins = parent_origins + clustering._restored_partitions = restored_partitions + if lineage_state is not None: + (lineage.records, lineage.color_records, lineage.origins, lineage.restorations) = ( + lineage_state + ) + for history, (items, index) in zip(histories, history_states): + history._history, history._index = items, index + self.session.restore_journal(journal) + self.session.next_cluster_id = max( + self.session.next_cluster_id, clustering.new_cluster_id() + ) + self.selection.restore(selection) + if propositions is not None: + self.merge_propositions.restore(propositions) + self._is_dirty = dirty + self.columns = columns + self._lineage_cache = None + if self.gui is not None: + self._reset_cluster_view() + self._restore_history_context( + selection, + { + 'mode': 'merge' if selection.is_merge_mode else 'post_merge', + 'tables': workflow, + }, + 'undo', + ) + self._refresh_bounded() + self._update_save_feedback() + raise + + def _require_capability(self, name): + if not self.session.manifest.get('capabilities', {}).get(name, False): + raise ValueError(f'This bounded package does not allow {name} operations.') + + def get_cluster_info(self, cluster_id, exclude=()): + info = super().get_cluster_info(cluster_id, exclude=exclude) + # Producer TSV labels may use metric names. They must not overwrite + # authoritative complete-sorting counts/rates with inherited values. + for name in ( + 'n_spikes', + 'fr', + 'full_count', + 'evidence_count', + 'waveform_count', + 'evidence', + ): + if name not in exclude and name in self.cluster_metrics: + info[name] = self.cluster_metrics[name](cluster_id) + return info + + def _select_after_merge(self, *args, **kwargs): + if self.gui is not None: + return super()._select_after_merge(*args, **kwargs) + + def _select_after_split(self, *args, **kwargs): + if self.gui is not None: + return super()._select_after_split(*args, **kwargs) + + def _restore_history_context(self, selection, workflow_context, direction): + if self.gui is not None: + return super()._restore_history_context(selection, workflow_context, direction) + self.selection.restore(selection) + + def _reset_cluster_view(self, *args, **kwargs): + if self.gui is not None: + return super()._reset_cluster_view(*args, **kwargs) + + def _workflow_context(self): + return super()._workflow_context() if self.gui is not None else {} + + def _validate_native(self, metadata=True, full=False): + # Local patches and the maintained nonempty catalog prove a normal + # transition without scanning unrelated spike assignments. Save retains + # the complete independent semantic projection and array comparison. + if full or getattr(self, 'full_validation', False): + valid = np.array_equal(self.clustering.spike_clusters, self.session.assignments) + else: + groups = self.session._assignment_groups + native = self.clustering.spikes_per_cluster + valid = set(native) == set(groups) + if valid: + for cluster, rows in self.session.last_changed_groups.items(): + if not len(rows): + continue + if not np.array_equal(native.get(cluster), rows) or not np.all( + self.clustering.spike_clusters[rows] == cluster + ): + valid = False + break + if not valid: + raise ValueError('Native assignments disagree with the bounded semantic command.') + if metadata: + active, expected = self.session._runtime.active, self.session.metadata + for field in set(self.cluster_meta.fields) | set(expected): + for cluster in active: + actual = ( + self.cluster_meta.get(field, cluster) + if field in self.cluster_meta.fields + else None + ) + if actual != expected.get(field, {}).get(cluster): + raise ValueError( + 'Native metadata disagrees with the bounded semantic command.' + ) + + def _synchronize_metadata(self): + # Native ClusterMeta.undo does not retain nonstacked inherited merge + # labels. The semantic projection is authoritative in bounded mode. + data = {} + for field, values in self.session.metadata.items(): + if field not in self.cluster_meta.fields: + with self.policy.command(): + self.cluster_meta.add_field(field) + for cluster, value in values.items(): + data.setdefault(cluster, {})[field] = value + self.cluster_meta._data = data + + def _reassembled_results(self): + """Proof of reassembly from immutable expression scopes, never spike scans.""" + from phy.cluster._propositions import ReviewDecision + + from .live_summaries import _membership_contains, membership_expressions + from .source import hash_json + + if self.merge_propositions is None: + return {} + history = {} + active = membership_expressions( + self.session.unit_ids, self.session.events, history=history + ) + historical_by_unit = {unit: expression for (_, unit), expression in history.items()} + + live = set(self.clustering.cluster_ids) + current = {unit: expression for unit, expression in active.items() if unit in live} + atom_cache, proof_cache = {}, {} + + def atoms(expression): + key = id(expression) + if key not in atom_cache: + parts = expression['parts'] if expression['kind'] == 'union' else [expression] + atom_cache[key] = frozenset(hash_json(part) for part in parts) + return atom_cache[key] + + result = {} + catalog = self.merge_propositions.catalog + for key, review in catalog.reviews.items(): + if review.decision is not ReviewDecision.ACCEPTED: + continue + expression = historical_by_unit.get(review.result_unit_id) + if expression is None or not catalog._result_was_restored(review.result_unit_id): + continue + expected_atoms = atoms(expression) + matches = [ + (unit, expression != scope) + for unit, scope in current.items() + if expected_atoms <= atoms(scope) + or _membership_contains(scope, expression, proof_cache) + ] + # Distinct live memberships must never both prove the same full scope. + if len(matches) == 1: + unit, modified = matches[0] + result[key] = {'result_unit_id': unit, 'modified': modified} + return result + + def _project_proposition_state(self): + if self.merge_propositions is not None: + key = ( + self.merge_propositions, + self.session.membership_revision, + tuple(map(int, self.clustering.cluster_ids)), + tuple(self.merge_propositions.catalog.reviews.items()), + ) + if key == getattr(self, '_proposition_projection_key', None): + return + self.merge_propositions.project_live_ids( + self.clustering.cluster_ids, + retired_units=self.session.retired_units, + reassembled_results=self._reassembled_results(), + ) + self._proposition_projection_key = key + + def _cluster_metadata_changed(self, field, cluster_ids): + # Native metadata notifications still update filters, sorting, masking, + # selection, and plugin listeners synchronously. Retain their row scope + # for the final semantic refresh, including label undo/redo. + cluster_ids = list(cluster_ids) + self._bounded_metadata_ids.update(cluster_ids) + if self.gui is not None: + return super()._cluster_metadata_changed(field, cluster_ids) + + def _metadata_refresh_ids(self): + changed = set(self._bounded_metadata_ids) + previous, current = self._bounded_table_metadata, self.session.metadata + for field in set(previous) | set(current): + before, after = previous.get(field, {}), current.get(field, {}) + changed.update( + cluster + for cluster in set(before) | set(after) + if before.get(cluster) != after.get(cluster) + ) + return sorted(changed & set(self.clustering.cluster_ids)) + + def _metadata_refresh_rows(self): + changed = set(self._metadata_refresh_ids()) + custom = { + name: provider + for name, provider in self.cluster_metrics.items() + if self._metadata_independent_metrics.get(name) is not provider + } + authoritative = { + 'n_spikes', + 'fr', + 'full_count', + 'evidence_count', + 'waveform_count', + 'evidence', + } + rows = [] + for cluster in self.clustering.cluster_ids: + if cluster in changed: + rows.append(self.get_cluster_info(cluster)) + elif custom: + row = {'id': cluster} + for name, provider in custom.items(): + value = provider(cluster) + # Match get_cluster_info's producer-metadata precedence and + # authoritative bounded count/rate/masking fields exactly. + if name in self.cluster_meta.fields and name not in authoritative: + value = self.cluster_meta.get(name, cluster) + if name == 'is_masked': + value = _is_group_masked(self.cluster_meta.get('group', cluster)) + row[name] = value + rows.append(row) + return rows + + def _refresh_bounded(self): + self.parent_origins = self.session.restored_parent_ids + if self.merge_propositions is not None: + self._project_proposition_state() + self._refresh_propositions() + if self.gui is not None: + metadata_only = self._bounded_table_revision is self.session.membership_revision + data = self._metadata_refresh_rows() if metadata_only else self.cluster_info + for view in (self.cluster_view, self.similarity_view, self.merge_view): + if view is None: + continue + if metadata_only: + patches = [] + for row in data: + previous = view.get(row['id']) + if previous is None: + continue + patch = { + key: value + for key, value in row.items() + if key not in previous or not _table_values_equal(previous[key], value) + } + if patch: + patches.append({'id': row['id'], **patch}) + view.change(patches) + else: + view.change(data) + self._bounded_table_revision = self.session.membership_revision + self._bounded_table_metadata = self.session.metadata + self._bounded_metadata_ids.clear() + emit('bounded_state_changed', self) + + def _capture(self): + if self.session.metadata_policy: + self._synchronize_metadata() + self._validate_native() + self.session_history.capture() + self._global_history.add_to_current_action(self.session_history) + self._is_dirty = tuple(self.session.events) != self._saved_data_events + self._update_save_feedback() + self._synchronize_metadata() + self._refresh_bounded() + + @semantic_command + def merge(self, cluster_ids=None, to=None): + self._require_capability('merge') + parents = list(self.selected if cluster_ids is None else cluster_ids) + if len(parents) < 2: + return + target = max(self.clustering.new_cluster_id(), self.session.next_cluster_id) + target = target if to is None else int(to) + self.session.preflight_merge(parents, target) + with self.policy.command(): + out = super().merge(cluster_ids=cluster_ids, to=target) + if out is None: + return + resolved = { + field: self.cluster_meta.get(field, target) for field in self.cluster_meta.fields + } + self.session.record_merge(parents, target, metadata=resolved) + self._capture() + return out + + @semantic_command + def restore_parents(self, target=None, *, groups=None, colors=None, new_cluster_ids=None): + """Restore complete semantic parents, then edit their fresh live IDs.""" + self._require_capability('merge') + if target is None: + selected = list(self.selected) + if len(selected) != 1: + raise ValueError('Select one current merged unit to restore its parents.') + target = selected[0] + target = int(target) + _, expected = self.session.restore_parent_groups(target, recursive=True) + if groups is not None and ( + list(groups) != list(expected) + or any(not np.array_equal(groups[parent], rows) for parent, rows in expected.items()) + ): + raise ValueError('Restored groups must match the complete semantic parent partition.') + if any(not len(rows) for rows in expected.values()): + raise ValueError( + 'A complete source parent has no retained evidence; restoration requires ' + 'evidence for every parent and cannot omit scientific units.' + ) + first = max(self.clustering.new_cluster_id(), self.session.next_cluster_id) + children = ( + list(range(first, first + len(expected))) + if new_cluster_ids is None + else list(new_cluster_ids) + ) + event = self.session.preflight_restore_parents(target, children, recursive=True) + with self.policy.command(): + out = super().restore_parents( + target, + groups=expected, + colors=colors, + new_cluster_ids=children, + ) + if out is None: + return None + self.session._append(event) + self._capture() + return out + + @semantic_command + def label(self, name, value, cluster_ids=None): + self._require_capability('label') + if name in ( + 'n_spikes', + 'fr', + 'full_count', + 'evidence_count', + 'waveform_count', + 'evidence', + ): + raise ValueError('Bounded count/rate/evidence columns are read-only metrics.') + ids = list(self.selected if cluster_ids is None else np.atleast_1d(cluster_ids)) + if not ids or self.selection.state.is_merge_mode: + return + # Validate intent without mutating either semantic or native state. + event = self.session.preflight_label(name, ids, value) + with self.policy.command(): + super().label(name, value, cluster_ids=ids) + self.session._append(event) + self._capture() + + def _graphical_split_views(self): + if self.gui is None: + return [] + return [ + view + for view in self.gui.list_views('EvidenceAmplitudeView') + if not view._closed + and view.gui is self.gui + and view._dock_visible + and view.split_threshold is not None + and np.isfinite(view.split_threshold) + and list(view.cluster_ids) == list(self.selected) + and len(self.selected) == 1 + and not self.selection.state.is_merge_mode + and view.amplitudes_type == 'source' + ] + + def _update_graphical_split_action(self): + actions = getattr(self, 'actions', None) + action = actions.get('split') if actions is not None else None + if action is not None: + capable = 'amplitudes.npy' in self.session.capabilities['predicate_split_attributes'] + action.setEnabled(capable and len(self._graphical_split_views()) == 1) + + def _set_merge_mode_ui(self, active): + if self.gui is None: + return + super()._set_merge_mode_ui(active) + if active: + for view in self.gui.list_views('EvidenceAmplitudeView'): + view.clear_amplitude_split_threshold() + self._update_graphical_split_action() + + def split(self, spike_ids=None, spike_clusters_rel=0): + self._settle_selection() + if spike_ids is not None or spike_clusters_rel != 0: + raise ValueError( + 'Lasso, feature and waveform splits cannot be replayed on unseen spikes. ' + 'Use Split by source amplitude for a full-source scalar predicate.' + ) + views = self._graphical_split_views() + if len(views) != 1: + raise ValueError('Exactly one visible source-amplitude threshold preview is required.') + view = views[0] + threshold = view.split_threshold + cluster_id = int(self.selected[0]) + try: + out = self.split_source_amplitude(cluster_id, threshold) + except Exception as error: + # A transaction may have published transient native selection updates + # before rollback. Keep the user's predicate available for correction. + view.split_threshold = threshold + view._replot_displayed_amplitudes() + emit( + 'amplitude_split_preview_changed', + view, + cluster_id=cluster_id, + amplitudes_type='source', + threshold=threshold, + ) + view._show_split_status(str(error)) + raise + view.clear_split_selection() + self._update_graphical_split_action() + return out + + @semantic_command + def split_source_amplitude(self, cluster_id, threshold): + if 'amplitudes.npy' not in self.session.manifest.get('capabilities', {}).get( + 'predicate_split_attributes', [] + ): + raise ValueError('This package does not support source-amplitude predicate splits.') + if self.selection.state.is_merge_mode: + raise ValueError('Leave Merge mode before splitting by source amplitude.') + if 'amplitudes.npy' not in self.session.attributes: + raise ValueError('The source has no scalar per-spike amplitudes.') + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': float(threshold), + 'nonfinite': 'keep', + } + ids = self.clustering.spikes_per_cluster.get(int(cluster_id), np.array([], dtype=np.int64)) + selected = ids[ + evaluate_predicate(self.session.attributes['amplitudes.npy'][ids], predicate) + ] + if not len(selected) or len(selected) == len(ids): + raise ValueError('Both sides of the threshold must have evidence spikes.') + selected_id = max(self.clustering.new_cluster_id(), self.session.next_cluster_id) + remainder_id = selected_id + 1 + self.clustering._new_cluster_id = selected_id + metadata = { + field: { + child: self.cluster_meta.get(field, cluster_id) + for child in (selected_id, remainder_id) + } + for field in self.cluster_meta.fields + } + event = self.session.preflight_split( + int(cluster_id), selected_id, remainder_id, predicate, metadata=metadata + ) + with self.policy.command(): + out = Supervisor.split(self, selected) + self.session._append(event) + self._capture() + return out + + @semantic_command + def _reject_merge_proposition(self, sender, key): + return super()._reject_merge_proposition(sender, key) + + @semantic_command + def _reset_merge_proposition(self, sender, key): + return super()._reset_merge_proposition(sender, key) + + def adopt_recovery(self, recovered): + """Adopt a fully prepared draft before attaching GUI views; new undo baseline.""" + from phy.cluster._history import CurationHistoryEntry + from phy.cluster._propositions import decode_review_mapping + from phy.cluster._selection import CurationSelectionController + + if self.gui is not None and not self.gui._closed: + raise RuntimeError('Restore a recovery draft before creating curation views.') + if ( + recovered.assignments is not recovered._certified_assignments + or recovered._recovery_clustering._spike_clusters is not recovered._certified_native + ): + raise ValueError('Recovered assignment certification changed before adoption.') + session = self.session + for name in ( + 'assignments', + 'metadata', + '_events', + 'next_cluster_id', + 'extra_documents', + '_runtime', + '_assignment_groups', + '_transitions', + '_transition_bytes', + '_prepared', + '_catalog_cache', + 'last_changed_groups', + ): + setattr(session, name, getattr(recovered, name)) + native = recovered._recovery_clustering + for name, value in vars(native).items(): + if name != 'policy': + setattr(self.clustering, name, value) + self.clustering._bounded_transition = self._native_undo_transition + self.cluster_meta._undo_stack.clear() + self._synchronize_metadata() + self._global_history.clear(CurationHistoryEntry()) + self.selection = CurationSelectionController() + self.session_history = SessionHistory(session) + if self.merge_propositions is not None: + _, reviews = decode_review_mapping(session.extra_documents['curation_review.json']) + catalog = self.merge_propositions.catalog._replace(reviews=reviews) + self.merge_propositions.restore(catalog) + self.merge_propositions._history.clear(catalog) + self.parent_origins = session.restored_parent_ids + self._proposition_projection_key = None + self._project_proposition_state() + self._bounded_table_revision = session.membership_revision + self._bounded_table_metadata = session.metadata + self._bounded_metadata_ids.clear() + self._is_dirty = True + self._validate_native() + + @semantic_command + def undo(self): + with self.policy.command(): + super().undo() + self._after_history() + + @semantic_command + def redo(self): + with self.policy.command(): + super().redo() + self._after_history() + + def _after_history(self): + self._validate_native(metadata=False) + # Never reuse allocated IDs after branching or restoring a snapshot. + self.session.next_cluster_id = max( + self.session.next_cluster_id, self.clustering.new_cluster_id() + ) + self._is_dirty = tuple(self.session.events) != self._saved_data_events + self._update_save_feedback() + self._synchronize_metadata() + self._refresh_bounded() + + def save(self): + if getattr(self, '_recovery_depth', 0): + raise RuntimeError('Cannot save curation before the current action has settled.') + recovery = getattr(self, 'recovery', None) + token = recovery.checkpoint_token() if recovery is not None else None + try: + self._save_checkpoint() + except Exception as error: + if recovery is not None: + recovery.checkpoint_failed(error) + raise + if recovery is not None: + recovery.checkpoint_saved(token) + + def _save_checkpoint(self): + self._settle_selection() + saved_state = self.recovery_token() + saved_catalog = ( + self.merge_propositions.catalog if self.merge_propositions is not None else None + ) + self._validate_native(full=True) + self.session.validate_proposition_documents() + documents = None + if self.merge_propositions is not None: + documents = dict(self.session.extra_documents) + documents.update( + { + 'curation_review.json': self.merge_propositions.catalog.review_mapping( + source_sha256=self.session.proposition_documents['curation.json']['sha256'] + ) + } + ) + self.session.save( + assignments=self.clustering.spike_clusters, + metadata=self.session.metadata, + next_cluster_id=max(self.session.next_cluster_id, self.clustering.new_cluster_id()), + extra_documents=documents, + ) + if saved_catalog is not None: + self.merge_propositions._saved_reviews = self.merge_propositions._review_fingerprint( + saved_catalog + ) + self._saved_data_events = saved_state[0] + self._is_dirty = tuple(self.session.events) != self._saved_data_events + self._update_save_feedback(saved=not self.is_dirty()) + emit('curation_saved', self) diff --git a/phy/apps/large_recording/tests/__init__.py b/phy/apps/large_recording/tests/__init__.py new file mode 100644 index 000000000..ba239ecd8 --- /dev/null +++ b/phy/apps/large_recording/tests/__init__.py @@ -0,0 +1 @@ +"""Long-recording workflow regression tests.""" diff --git a/phy/apps/large_recording/tests/test_adapter.py b/phy/apps/large_recording/tests/test_adapter.py new file mode 100644 index 000000000..e3aa56b4d --- /dev/null +++ b/phy/apps/large_recording/tests/test_adapter.py @@ -0,0 +1,738 @@ +"""Bounded GUI correctness and ordinary-controller isolation.""" + +import json + +import numpy as np +import pytest +from click.testing import CliRunner +from phylib.utils import connect, emit, unconnect + +from phy.apps import phycli +from phy.apps.large_recording.adapter import BoundedTemplateController +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.tests.test_source import make_sorting +from phy.apps.template.gui import TemplateController +from phy.gui.qt import mock_dialogs + + +def make_controller(tmp_path, sparse=False, propositions=None, amplitudes=None): + params = make_gui_sorting(tmp_path / 'source') + if amplitudes is not None: + np.save(params.parent / 'amplitudes.npy', amplitudes) + if propositions is not None: + (params.parent / 'curation.json').write_text(json.dumps(propositions)) + output = prepare_large( + params, + tmp_path / 'bounded', + window_seconds=3 if sparse else 20, + stratum_seconds=20, + max_spikes=5 if sparse else 100, + bin_seconds=5, + batch_size=2, + ) + controller = TemplateController( + dir_path=output, + config_dir=tmp_path / 'config', + plugins=[], + enable_threading=False, + clear_cache=True, + ) + return params, controller + + +def make_gui_sorting(path): + params = make_sorting(path) + times = np.load(path / 'spike_times.npy') + np.save(path / 'spike_times.npy', times * 30000) + params.write_text( + params.read_text() + .replace('sample_rate = 1.0', 'sample_rate = 30000.0') + .replace('num_samples = 20', 'num_samples = 600000') + ) + return params + + +def test_manifest_factory_reserves_complete_ids_and_guards_mutations(tmp_path): + _, controller = make_controller(tmp_path, sparse=True) + try: + assert isinstance(controller, BoundedTemplateController) + with pytest.raises(ValueError): + controller.model.spike_clusters[0] = 123 + with pytest.raises(ValueError): + controller.model.spike_clusters = np.array([123]) + with pytest.raises(ValueError): + controller.model.sample_rate = 1.0 + with pytest.raises(TypeError): + controller.model.metadata['group'][0] = 'noise' + supervisor = controller.supervisor + assert 99 not in supervisor.clustering.cluster_ids + assert supervisor.clustering.new_cluster_id() == 100 + assert controller.get_full_count(0) == 4 + assert controller.get_mean_firing_rate(0) == 0.2 + for operation in ( + lambda: supervisor.clustering.merge([0, 1]), + lambda: supervisor.clustering.assign([0]), + lambda: supervisor.clustering.split([0]), + supervisor.clustering.undo, + supervisor.clustering.redo, + supervisor.clustering.reset, + lambda: supervisor.cluster_meta.set('group', [0], 'noise', add_to_stack=False), + lambda: supervisor.cluster_meta.from_dict({0: {'group': 'noise'}}), + lambda: controller.model.save_spike_clusters(supervisor.clustering.spike_clusters), + lambda: controller.model.save_metadata('group', {0: 'noise'}), + lambda: supervisor.split([0]), + ): + with pytest.raises(ValueError): + operation() + with pytest.raises(ValueError): + supervisor.clustering.spike_clusters[0] = 8 + assert not controller.bounded_session.events + with pytest.raises(ValueError): + supervisor.cluster_meta.add_field('group', 'noise') + with pytest.raises(TypeError): + supervisor.clustering.spikes_per_cluster[0] = np.array([0]) + with pytest.raises(ValueError): + supervisor.clustering.spikes_per_cluster[0][0] = 1 + assert 'CorrelogramView' not in controller.view_creator + assert 'FiringRateView' not in controller.view_creator + finally: + controller.close() + + +def test_loader_and_native_history_do_not_allocate_by_sparse_unit_id(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'source') + labels = np.load(params.parent / 'spike_clusters.npy').astype(np.int64) + labels[labels == 99] = 2_000_000_000 + np.save(params.parent / 'spike_clusters.npy', labels) + (params.parent / 'cluster_group.tsv').write_text( + 'cluster_id\tgroup\n0\tgood\n1\tmua\n2\tgood\n2000000000\tnoise\n' + ) + output = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + controller = TemplateController(dir_path=output, config_dir=tmp_path / 'config', plugins=[]) + try: + assert controller.model.sparse_clusters is None + first = controller.supervisor.merge([0, 1]) + assert first.added == [2_000_000_001] + controller.supervisor.merge([2, 2_000_000_001]) + controller.supervisor.undo() + assert 2_000_000_001 in controller.supervisor.clustering.cluster_ids + values = controller._window_correlograms([2, 2_000_000_001], 0.001, 0.004) + assert values.shape == (2, 2, 5) + controller.supervisor.save() + finally: + controller.close() + reopened = TemplateController(dir_path=output, config_dir=tmp_path / 'config', plugins=[]) + try: + assert 2_000_000_001 in reopened.model.cluster_ids + assert reopened.model.sparse_clusters is None + finally: + reopened.close() + + +def test_merge_label_history_save_reopen_replay_regenerate(tmp_path): + params, controller = make_controller(tmp_path) + path = controller.dir_path + try: + supervisor = controller.supervisor + original_file = (path / 'spike_clusters.npy').read_bytes() + up = supervisor.merge([0, 1]) + assert up.added == [100] + assert controller.get_full_count(100) == 7 + supervisor.label('group', 'noise', [100]) + supervisor.undo() + assert controller.bounded_session.metadata['group'][100] is None + assert supervisor.cluster_meta.get('group', 100) is None + supervisor.redo() + assert controller.bounded_session.metadata['group'][100] == 'noise' + supervisor.undo() + supervisor.undo() + np.testing.assert_array_equal( + supervisor.clustering.spike_clusters, controller.bounded_session.base_assignments + ) + supervisor.merge([1, 2]) + assert supervisor.clustering.new_cluster_id() == 102 + supervisor.label('quality', 'reviewed', [101]) + supervisor.save() + assert not supervisor.is_dirty() + assert (path / 'spike_clusters.npy').read_bytes() == original_file + expected = supervisor.clustering.spike_clusters.copy() + finally: + controller.close() + reopened = TemplateController( + dir_path=path, config_dir=tmp_path / 'config', plugins=[], enable_threading=False + ) + try: + np.testing.assert_array_equal(reopened.supervisor.clustering.spike_clusters, expected) + assert reopened.supervisor.clustering.new_cluster_id() == 102 + assert reopened.supervisor.cluster_meta.get('quality', 101) == 'reviewed' + assert reopened.supervisor._global_history.current_position == 0 + finally: + reopened.close() + output = apply_curation(params, path, tmp_path / 'curated', batch_size=2) + source = np.load(params.parent / 'spike_clusters.npy') + oracle = source.copy() + oracle[np.isin(source, [1, 2])] = 101 + np.testing.assert_array_equal(np.load(output / 'spike_clusters.npy'), oracle) + regenerated = prepare_large( + output / 'params.py', + tmp_path / 'regenerated', + window_seconds=20, + stratum_seconds=20, + bin_seconds=5, + ) + assert BoundedSession(regenerated).unit_ids == [0, 99, 101] + + +def test_source_threshold_replays_every_spike_and_full_metrics_pending(tmp_path): + params, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + up = supervisor.split_source_amplitude(0, 4) + assert set(up.added) == {100, 101} + assert controller.get_full_count(100) is None + assert controller.get_mean_firing_rate(101) is None + supervisor.undo() + assert controller.get_full_count(0) == 4 + supervisor.redo() + supervisor.save() + output = apply_curation(params, controller.dir_path, tmp_path / 'curated', batch_size=2) + source = np.load(params.parent / 'spike_clusters.npy') + amplitudes = np.load(params.parent / 'amplitudes.npy') + oracle = source.copy() + oracle[(source == 0) & (amplitudes < 4)] = 100 + oracle[(source == 0) & ~(amplitudes < 4)] = 101 + np.testing.assert_array_equal(np.load(output / 'spike_clusters.npy'), oracle) + finally: + controller.close() + + +@pytest.mark.parametrize('entry', ['prompt', 'snippet']) +def test_negative_source_threshold_entry_replays_exact_membership(qtbot, tmp_path, entry): + amplitudes = np.arange(12, dtype=np.float32) + # Equality and nonfinite source values belong to the remainder. + amplitudes[[0, 3, 6, 9]] = [-900, -896, np.nan, np.inf] + params, controller = make_controller(tmp_path, amplitudes=amplitudes) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + source = np.load(params.parent / 'spike_clusters.npy') + supervisor.select([0]) + qtbot.waitUntil(lambda: supervisor.selected == [0]) + if entry == 'prompt': + with mock_dialogs(('-896', True)): + supervisor.actions.get('Split by source amplitude').trigger() + else: + gui.snippets.run(':split_by_source_amplitude -8.96e2') + oracle = source.copy() + selected = (source == 0) & np.isfinite(amplitudes) & (amplitudes < -896) + oracle[selected] = 100 + oracle[(source == 0) & ~selected] = 101 + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, oracle) + supervisor.undo() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, source) + supervisor.redo() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, oracle) + supervisor.save() + output = apply_curation(params, controller.dir_path, tmp_path / 'curated', batch_size=2) + np.testing.assert_array_equal(np.load(output / 'spike_clusters.npy'), oracle) + finally: + gui.close() + controller.close() + + +def test_failed_save_leaves_dirty_previous_checkpoint(tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + supervisor.merge([0, 1]) + supervisor.save() + history = controller.dir_path / 'phy_curation_history.jsonl' + saved_history = history.read_text() + assert len(saved_history.splitlines()) == 1 + supervisor.label('group', 'noise', [100]) + from phy.apps.large_recording import curation + + original = curation._write_json + + def fail(path, value): + if path.name == 'journal.json': + raise OSError('interrupted') + return original(path, value) + + monkeypatch.setattr(curation, '_write_json', fail) + with pytest.raises(OSError, match='interrupted'): + supervisor.save() + assert supervisor.is_dirty() + assert history.read_text() == saved_history + assert BoundedSession(controller.dir_path).metadata['group'][100] is None + finally: + controller.close() + + +def test_standard_controller_retains_existing_path_and_save_format(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'ordinary') + controller = TemplateController( + dir_path=params.parent, + config_dir=tmp_path / 'config', + plugins=[], + enable_threading=False, + sample_rate=30000, + n_channels_dat=3, + dtype='int16', + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + assert type(controller) is TemplateController + assert controller.gui_name == 'TemplateGUI' + assert controller.default_views[0] == 'WaveformView' + assert 'FiringRateView' in controller.view_creator + up = controller.supervisor.merge([0, 1]) + controller.supervisor.save() + assert up.added == [100] + assert not (params.parent / '.phy-curation').exists() + assert not (params.parent / '_phy_curation_manifest.json').exists() + assert 100 in np.load(params.parent / 'spike_clusters.npy') + finally: + gui.close() + controller.close() + + +def test_sampled_correlogram_transfers_rows_and_disconnects_when_closed( + qtbot, tmp_path, monkeypatch +): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['SampledCorrelogramView'], do_prompt_save=False) + qtbot.addWidget(gui) + supervisor = controller.supervisor + calls = [] + transfer_cluster = supervisor.transfer_cluster + + def record_transfer(cluster_id, *args, **kwargs): + calls.append(cluster_id) + return transfer_cluster(cluster_id, *args, **kwargs) + + monkeypatch.setattr(supervisor, 'transfer_cluster', record_transfer) + try: + supervisor.select([0]) + supervisor.similarity_view.select([1, 2]) + supervisor.block() + assert supervisor.selection.state.cluster_ids == (0,) + assert supervisor.selection.state.similar_ids == (1, 2) + + view = gui.get_view('SampledCorrelogramView') + view.dock.close() + supervisor.select([0]) + supervisor.similarity_view.select([1, 2]) + supervisor.block() + emit('request_correlogram_transfer', view, 1, 2) + supervisor.block() + assert calls == [] + assert supervisor.selection.state.cluster_ids == (0,) + assert supervisor.selection.state.similar_ids == (1, 2) + + reopened_view = gui.create_and_add_view('SampledCorrelogramView') + emit('request_correlogram_transfer', reopened_view, 1, 2) + supervisor.block() + assert calls == [1] + assert supervisor.selection.state.cluster_ids == (0, 1) + assert supervisor.selection.state.similar_ids == (2,) + finally: + gui.close() + controller.close() + + +def test_sampled_correlogram_transfer_preserves_merge_reference(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['SampledCorrelogramView'], do_prompt_save=False) + qtbot.addWidget(gui) + supervisor = controller.supervisor + try: + supervisor.select([0]) + supervisor.similarity_view.select([1, 2]) + supervisor.block() + supervisor.toggle_merge_mode() + supervisor.block() + state = supervisor.selection.state + assert state.reference_id == 0 + assert state.merge_ids == (0, 1, 2) + + view = gui.get_view('SampledCorrelogramView') + emit('request_correlogram_transfer', view, 0, 1) + supervisor.block() + assert supervisor.selection.state.reference_id == 1 + assert supervisor.selection.state.merge_ids == (1, 2) + assert supervisor.selection.state.similar_ids == (0,) + + emit('request_correlogram_transfer', view, 1, 2) + supervisor.block() + assert supervisor.selection.state.reference_id == 2 + assert supervisor.selection.state.merge_ids == (2,) + assert supervisor.selection.state.similar_ids == (0, 1) + + emit('request_correlogram_transfer', view, 2, 2) + supervisor.block() + assert supervisor.selection.state.reference_id == 2 + assert supervisor.selection.state.merge_ids == (2,) + assert supervisor.selection.state.similar_ids == (0, 1) + finally: + gui.close() + controller.close() + + +def test_ordinary_correlogram_transfer_still_works(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'ordinary') + controller = TemplateController( + dir_path=params.parent, + config_dir=tmp_path / 'config', + plugins=[], + enable_threading=False, + sample_rate=30000, + n_channels_dat=3, + dtype='int16', + ) + gui = controller.create_gui(default_views=['CorrelogramView'], do_prompt_save=False) + qtbot.addWidget(gui) + supervisor = controller.supervisor + try: + supervisor.select([0]) + supervisor.similarity_view.select([1, 2]) + supervisor.block() + view = gui.get_view('CorrelogramView') + emit('request_correlogram_transfer', view, 1, 2) + supervisor.block() + assert supervisor.selection.state.cluster_ids == (0, 1) + assert supervisor.selection.state.similar_ids == (2,) + finally: + gui.close() + controller.close() + + +def test_malformed_manifest_fails_before_model_loading(tmp_path): + params = make_sorting(tmp_path / 'ordinary') + (params.parent / '_phy_curation_manifest.json').write_text(json.dumps({'format_version': 99})) + with pytest.raises(ValueError, match='Unsupported'): + TemplateController(dir_path=params.parent, plugins=[]) + + +def test_cli_preparation_and_replay(tmp_path): + params = make_sorting(tmp_path / 'source') + runner = CliRunner() + output = tmp_path / 'bounded' + result = runner.invoke( + phycli, + [ + 'prepare-large', + str(params), + str(output), + '--window-seconds', + '20', + '--stratum-seconds', + '20', + '--bin-seconds', + '5', + '--batch-size', + '2', + ], + ) + assert result.exit_code == 0, result.output + session = BoundedSession(output) + session.record_merge([0, 1], 100, {'group': 'good'}) + session.save() + result = runner.invoke( + phycli, + [ + 'apply-curation', + str(params), + str(output), + str(tmp_path / 'curated'), + '--batch-size', + '2', + ], + ) + assert result.exit_code == 0, result.output + + +def test_stability_gui_and_exact_trends(qtbot, tmp_path): + _, controller = make_controller(tmp_path, sparse=True) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + try: + assert 'Bounded evidence' in gui.windowTitle() + view = gui.list_views('UnitStabilityView')[0] + data = view.get_data(0) + assert data.counts.sum() == 4 + np.testing.assert_allclose(data.trends['amplitude'], [1.5, np.nan, 6, 9], equal_nan=True) + view.on_select([99]) # Unit absent from evidence still has full-duration counts. + assert view.get_data(99).counts.sum() == 2 + controller.supervisor.merge([0, 1]) + controller.supervisor.block() + assert view.get_data(100).counts.sum() == 7 + finally: + gui.close() + controller.close() + + +def test_observer_mutation_rolls_back_native_and_semantic_state(tmp_path): + _, controller = make_controller(tmp_path) + supervisor = controller.supervisor + once = [] + + @connect(event='cluster', sender=supervisor.clustering) + def mutate(sender, up): + if not once: + once.append(True) + sender.assign([0]) + + try: + with pytest.raises(ValueError, match='Native assignments'): + supervisor.merge([0, 1]) + np.testing.assert_array_equal( + supervisor.clustering.spike_clusters, controller.bounded_session.base_assignments + ) + assert not controller.bounded_session.events + assert supervisor._global_history.current_position == 0 + assert not supervisor.is_dirty() + finally: + unconnect(mutate) + controller.close() + + +def test_evidence_navigation_never_reuses_old_feature_cache(tmp_path): + _, controller = make_controller(tmp_path, sparse=True) + try: + first = controller._get_features(0, channel_ids=[0, 1], load_all=True) + assert first.spike_ids.tolist() == [0, 3] + controller.inspect_evidence_window(1) + assert not controller._get_feature_view_spike_ids(0, load_all=True).size + assert not controller._get_features(0, channel_ids=[0, 1], load_all=True) + finally: + controller.close() + + +def test_late_clock_evidence_preserves_submillisecond_positions(tmp_path): + params = make_gui_sorting(tmp_path / 'source') + origin = 1000 * 3600 * 30000 + times = np.load(params.parent / 'spike_times.npy') + origin + times[1:4] = origin + np.array([30, 31, 60]) + np.save(params.parent / 'spike_times.npy', times) + params.write_text( + params.read_text().replace('num_samples = 600000', f'num_samples = {origin + 600000}') + + f'valid_intervals = [[{origin}, {origin + 600000}]]\n' + ) + output = prepare_large( + params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20, bin_seconds=3600 + ) + controller = TemplateController(dir_path=output, config_dir=tmp_path / 'config', plugins=[]) + try: + positions = controller._window_time(np.array([1, 2])) + assert positions[1] - positions[0] == pytest.approx(1 / 30000) + assert np.float32(positions[0]) != np.float32(positions[1]) + finally: + controller.close() + + +def test_empty_window_and_nonfinite_amplitude_measurements(qtbot, tmp_path): + _, controller = make_controller(tmp_path, sparse=True) + view = controller.create_evidence_amplitude_view() + try: + controller.inspect_evidence_window(1) + view.on_select([0]) + assert view.data_bounds == (0, 0, view.duration, 1) + assert all(not len(b.amplitudes) for b in view._displayed_bunchs) + finally: + view.canvas.close() + controller.close() + + +def test_proposition_reviews_checkpoint_and_failed_review_history(tmp_path): + from phy.cluster._propositions import MergePropositionController, decode_curation_mapping + + mapping = {'format_version': '2', 'unit_ids': [0, 1, 2, 99], 'merges': [{'unit_ids': [0, 1]}]} + _, controller = make_controller(tmp_path, propositions=mapping) + supervisor = controller.supervisor + producer = controller.dir_path / 'curation.json' + supervisor.merge_propositions = MergePropositionController(decode_curation_mapping(mapping)) + key = supervisor.merge_propositions.catalog.propositions[0].key + try: + with pytest.raises(RuntimeError, match='observer'), supervisor._transaction(): + supervisor.merge_propositions.accept(key, [0, 1], 100) + raise RuntimeError('observer') + assert supervisor.merge_propositions._history.current_position == 0 + assert not supervisor.merge_propositions.catalog.reviews + supervisor.merge_propositions.reject(key) + supervisor.save() + controller.close() + reopened = TemplateController( + dir_path=producer.parent, config_dir=tmp_path / 'config', plugins=[] + ) + try: + assert ( + reopened.supervisor.merge_propositions.catalog.status_for(key).value == 'rejected' + ) + assert not reopened.supervisor.is_dirty() + finally: + reopened.close() + finally: + controller.close() + + +def test_nonfinite_source_amplitudes_are_omitted_from_plots_and_kept_in_replay(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'source') + amplitudes = np.load(params.parent / 'amplitudes.npy') + amplitudes[3] = np.inf + amplitudes[6] = np.nan + np.save(params.parent / 'amplitudes.npy', amplitudes) + output = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + controller = TemplateController(dir_path=output, config_dir=tmp_path / 'config', plugins=[]) + view = controller.create_evidence_amplitude_view() + try: + view.on_select([0]) + assert np.all(np.isfinite(view.data_bounds)) + assert all(np.all(np.isfinite(b.amplitudes)) for b in view._displayed_bunchs) + controller.supervisor.split_source_amplitude(0, 4) + controller.supervisor.save() + curated = apply_curation(params, output, tmp_path / 'curated') + labels = np.load(curated / 'spike_clusters.npy') + assert labels[0] == 100 + assert labels[3] == labels[6] == 101 + finally: + view.canvas.close() + controller.close() + + +@pytest.mark.parametrize('operation', ['merge', 'label', 'move']) +@pytest.mark.parametrize('shortcut', [False, True]) +def test_pending_navigation_settles_exact_native_and_semantic_targets( + qtbot, tmp_path, operation, shortcut +): + from timeit import default_timer + + params, controller = make_controller(tmp_path) + gui = controller.create_gui(view_count={}, default_views=[], do_prompt_save=False) + qtbot.addWidget(gui) + supervisor = controller.supervisor + try: + supervisor.select([0]) + supervisor.block() + view = supervisor.similarity_view + view.sort_by('id', 'asc') + view.select([1]) + supervisor.block() + view.debouncer.delay = 60_000 + view.debouncer._last_submission_time = default_timer() + view.next() + view.select_toggle(1) + view.select_toggle(1) + assert view.get_selected_ids() == [2] + assert supervisor.selected == [0, 1] + assert view.debouncer.has_pending + + args = { + 'merge': (), + 'label': ('group', 'noise'), + 'move': ('noise', 'similar'), + }[operation] + if shortcut: + supervisor._on_action(supervisor.action_creator, operation, *args) + else: + getattr(supervisor, operation)(*args) + supervisor.block() + event = controller.bounded_session.events[-1] + source = np.load(params.parent / 'spike_clusters.npy') + expected = source.copy() + if operation == 'merge': + assert event['parents'] == [0, 2] + expected[np.isin(source, [0, 2])] = event['target'] + assert set(supervisor.clustering.cluster_ids) == {1, 99, event['target']} + else: + assert event['ids'] == ([2] if operation == 'move' else [0, 2]) + assert supervisor.cluster_meta.get('group', 2) == 'noise' + assert supervisor.cluster_meta.get('group', 1) == 'mua' + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, expected) + before = supervisor._global_history.current_item.selection_before + assert before.cluster_ids == (0,) + assert before.similar_ids == (2,) + supervisor.save() + replay = apply_curation(params, controller.dir_path, tmp_path / 'replay', batch_size=2) + np.testing.assert_array_equal(np.load(replay / 'spike_clusters.npy'), expected) + if operation != 'merge': + replay_groups = (replay / 'cluster_group.tsv').read_text() + assert '1\tmua\n' in replay_groups + assert '2\tnoise\n' in replay_groups + finally: + gui.close() + controller.close() + + +def test_bounded_save_history_appends_and_survives_reopening(tmp_path): + params, controller = make_controller(tmp_path) + bounded = controller.dir_path + history = bounded / 'phy_curation_history.jsonl' + original_assignments = (bounded / 'spike_clusters.npy').read_bytes() + try: + assert not history.exists() + controller.supervisor.merge([0, 1]) + controller.supervisor.save() + checkpoint = controller.bounded_session.checkpoint_path + assert checkpoint.is_dir() + assert ( + json.loads((bounded / '.phy-curation' / 'current.json').read_text())['generation'] + == checkpoint.name + ) + first = json.loads(history.read_text()) + assert first['event'] == 'curation_saved' + assert first['dataset_path'] == str(bounded.resolve()) + assert first['software']['phy']['version'] + assert first['software']['phylib']['version'] + assert 'Curation session started:' in (bounded / 'phy.log').read_text() + controller.supervisor.save() + records = [json.loads(line) for line in history.read_text().splitlines()] + assert len(records) == 2 + assert records[0]['session_id'] == records[1]['session_id'] + assert (bounded / 'spike_clusters.npy').read_bytes() == original_assignments + assert not (params.parent / 'phy_curation_history.jsonl').exists() + finally: + controller.close() + reopened = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + try: + reopened.supervisor.save() + records = [json.loads(line) for line in history.read_text().splitlines()] + assert len(records) == 3 + assert records[-1]['session_id'] != records[0]['session_id'] + assert not reopened.supervisor.is_dirty() + finally: + reopened.close() + + +def test_sampled_correlogram_chance_line_tracks_live_window_counts(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + view = controller.create_sampled_correlogram_view() + try: + view.cluster_ids = [0, 1] + before = view.get_clusters_data() + assert before[0].firing_rate > 0 + assert before[1].firing_rate > 0 + expected_hist, expected_baseline = controller._window_correlograms( + [0, 1], view.bin_size, view.window_size, return_baseline=True + ) + for bunch in before: + i, j = bunch.pair_index + np.testing.assert_array_equal(bunch.correlogram, expected_hist[i, j]) + assert bunch.firing_rate == expected_baseline[i, j] + assert bunch.data_bounds[3] >= bunch.firing_rate + # A live edit changes both providers together; no full-recording rate cache. + update = controller.supervisor.merge([0, 1]) + view.cluster_ids = update.added + after = view.get_clusters_data()[0] + assert after.firing_rate > before[0].firing_rate + assert after.firing_rate > before[3].firing_rate + controller.supervisor.undo() + view.cluster_ids = [0, 1] + np.testing.assert_array_equal( + [b.firing_rate for b in view.get_clusters_data()], + [b.firing_rate for b in before], + ) + finally: + view.canvas.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_assignment_oracle.py b/phy/apps/large_recording/tests/test_assignment_oracle.py new file mode 100644 index 000000000..c1b098b64 --- /dev/null +++ b/phy/apps/large_recording/tests/test_assignment_oracle.py @@ -0,0 +1,107 @@ +"""Literal all-source expectations for the independent acceptance oracle.""" + +from types import SimpleNamespace + +import numpy as np +import pytest + +from tools.curation_output_contract import _assignment_oracle + + +def _split( + parent, children, operator='<', threshold=4, nonfinite='keep', attribute='amplitudes.npy' +): + return { + 'operation': 'threshold_split', + 'parents': [parent], + 'children': children, + 'predicate': { + 'attribute': attribute, + 'operator': operator, + 'threshold': threshold, + 'nonfinite': nonfinite, + }, + } + + +def _check(original, values, expected, history, chunk_size=2, attribute='amplitudes.npy'): + source = SimpleNamespace( + arrays={ + 'spike_clusters.npy': np.asarray(original, dtype=np.int16), + attribute: np.asarray(values), + } + ) + curated = SimpleNamespace(arrays={'spike_clusters.npy': np.asarray(expected)}) + return _assignment_oracle(source, curated, history, chunk_size) + + +@pytest.mark.parametrize('attribute', ['amplitudes.npy', 'spike_templates.npy']) +@pytest.mark.parametrize('column', [False, True]) +@pytest.mark.parametrize( + ('operator', 'expected'), + [ + ('<', [40001, 40000, 40000, 9]), + ('<=', [40001, 40001, 40000, 9]), + ('>', [40000, 40000, 40001, 9]), + ('>=', [40000, 40001, 40001, 9]), + ], +) +def test_predicate_boundaries_and_child_order(attribute, column, operator, expected): + values = np.array([1, 4, 7, 2]) + if column: + values = values[:, None] + report = _check( + [0, 0, 0, 9], + values, + expected, + [_split(0, [40000, 40001], operator=operator, attribute=attribute)], + attribute=attribute, + ) + assert report == { + 'verified': True, + 'source_rows': 4, + 'membership_events': 1, + 'threshold_splits': 1, + } + + +@pytest.mark.parametrize('operator', ['<', '<=', '>', '>=']) +def test_nonfinite_keep_stays_in_remainder(operator): + _check( + [0, 0, 0, 9], + [np.nan, np.inf, -np.inf, np.nan], + [10, 10, 10, 9], + [_split(0, [10, 11], operator=operator)], + ) + + +def test_nonfinite_reject_only_applies_to_current_parent(): + history = [_split(0, [10, 11], nonfinite='reject')] + _check([0, 0, 9], [1, 7, np.nan], [11, 10, 9], history) + with pytest.raises(ValueError, match='rejects nonfinite'): + _check([0, 0, 9], [np.nan, 7, 1], [10, 10, 9], history) + + +@pytest.mark.parametrize('chunk_size', [1, 2, 7, 100]) +def test_cumulative_merge_split_remerge_and_split(chunk_size): + history = [ + {'operation': 'merge', 'parents': [0, 1], 'children': [10]}, + _split(10, [11, 12]), + {'operation': 'merge', 'parents': [12, 2], 'children': [13]}, + {'operation': 'label', 'field': 'group', 'ids': [13], 'value': 'good'}, + _split(13, [14, 15], operator='>=', threshold=2), + ] + original, values = [0, 1, 0, 1, 2, 2, 9], [1, 3, 4, 7, 2, 5, 0] + expected = [14, 15, 11, 11, 15, 15, 9] + _check(original, values, expected, history, chunk_size) + # Wrong rows remain detectable across chunk boundaries and after subsequent merges. + for row in (0, 3, 6): + wrong = expected.copy() + wrong[row] = 15 if expected[row] != 15 else 14 + with pytest.raises(ValueError, match=f'at spike {row}$'): + _check(original, values, wrong, history, chunk_size) + + +def test_reject_nonscalar_attribute(): + with pytest.raises(ValueError, match='scalar per source spike'): + _check([0, 0], [[1, 2], [3, 4]], [11, 11], [_split(0, [10, 11])]) diff --git a/phy/apps/large_recording/tests/test_attachment_cancel.py b/phy/apps/large_recording/tests/test_attachment_cancel.py new file mode 100644 index 000000000..fe5f2d5a8 --- /dev/null +++ b/phy/apps/large_recording/tests/test_attachment_cancel.py @@ -0,0 +1,46 @@ +"""Late cancellation preserves complete artifacts and the prior attachment.""" + +from concurrent.futures import CancelledError +from contextlib import contextmanager + +import pytest + +from phy.apps.large_recording import range_index, summary_store +from phy.apps.large_recording.live_summaries import LiveSummaryEngine +from phy.apps.large_recording.range_build import build_amplitude_index +from phy.apps.large_recording.tests.test_live_summaries import package + + +@pytest.mark.parametrize('kind', ['rows', 'index']) +def test_builder_cancellation_reaches_attachment_lock(tmp_path, monkeypatch, kind): + _, bounded = package(tmp_path) + if kind == 'index': + summary_store.build_summary_store(bounded, tmp_path / 'rows') + reference = summary_store.summary_store_reference(bounded) + stopped = False + + @contextmanager + def waiting_lock(path, check_cancel=None): + nonlocal stopped + stopped = True + assert check_cancel is not None + check_cancel() + pytest.fail('Attachment lock did not honor cancellation.') + yield + + module = summary_store if kind == 'rows' else range_index + monkeypatch.setattr(module, '_attachment_lock', waiting_lock) + output = tmp_path / 'completed' + builder = summary_store.build_summary_store if kind == 'rows' else build_amplitude_index + with pytest.raises(CancelledError): + builder(bounded, output, cancel=lambda: stopped) + assert output.is_dir() + assert summary_store.summary_store_reference(bounded) == reference + # Publication completed before attachment: the artifact remains usable. + with LiveSummaryEngine(bounded) as engine: + if kind == 'rows': + with summary_store.SummaryStore(engine, path=output) as store: + assert set(store.index['units']) == set(map(str, engine.manifest['unit_ids'])) + else: + index = range_index.AmplitudeRangeIndex(engine, path=output) + index.close() diff --git a/phy/apps/large_recording/tests/test_batch_selection.py b/phy/apps/large_recording/tests/test_batch_selection.py new file mode 100644 index 000000000..08a4f04c5 --- /dev/null +++ b/phy/apps/large_recording/tests/test_batch_selection.py @@ -0,0 +1,97 @@ +"""Batch navigation must not change curation targets or saved assignments.""" + +import sys + +import numpy as np + +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.apps.template.gui import TemplateController +from phy.gui.qt import Qt + + +def test_good_then_batch_at_end_saves_reopens_and_replays(qtbot, tmp_path): + params, controller = make_controller(tmp_path) + path = controller.dir_path + source_bytes = (params.parent / 'spike_clusters.npy').read_bytes() + gui = controller.create_gui(default_views=[], do_prompt_save=False) + gui.show() + try: + supervisor = controller.supervisor + target = supervisor.merge([0, 2]).added[0] + expected = supervisor.clustering.spike_clusters.copy() + supervisor.cluster_view.sort_by('id', 'asc') + supervisor.select([target]) + supervisor.block() + modifier = Qt.MetaModifier if sys.platform == 'darwin' else Qt.ControlModifier + # No event-loop wait between the two shortcuts and Save. + qtbot.keyClick(gui, Qt.Key_G, Qt.AltModifier) + qtbot.keyClick(gui, Qt.Key_Space, modifier) + supervisor.save() + supervisor.block() + assert supervisor.selection.state.reference_id is None + assert supervisor.similarity_view.get_ids() == [] + assert supervisor.cluster_meta.get('group', target) == 'good' + assert not supervisor.is_dirty() + assert not supervisor.task_logger._processing + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, expected) + finally: + gui.close() + controller.close() + reopened = TemplateController(dir_path=path, config_dir=tmp_path / 'config', plugins=[]) + try: + np.testing.assert_array_equal(reopened.bounded_session.assignments, expected) + assert reopened.supervisor.cluster_meta.get('group', target) == 'good' + replay = apply_curation(params, path, tmp_path / 'replay', batch_size=2) + np.testing.assert_array_equal(np.load(replay / 'spike_clusters.npy'), expected) + assert f'{target}\tgood\n' in (replay / 'cluster_group.tsv').read_text() + assert (params.parent / 'spike_clusters.npy').read_bytes() == source_bytes + finally: + reopened.close() + + +def test_reordered_blue_proposition_preserves_colors_history_and_saved_membership(qtbot, tmp_path): + propositions = { + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 2]}], + } + params, controller = make_controller(tmp_path, propositions=propositions) + path = controller.dir_path + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + key = supervisor.merge_propositions.catalog.propositions[0].key + supervisor._activate_merge_proposition(supervisor.merge_propositions_view, key) + view = supervisor.merge_view + view.emit_cluster_drop(view, (0,), 2) + staged = supervisor.selection.snapshot() + assert staged.merge_ids == (2, 0) + assert staged.reference_id == 0 + assert dict(staged.color_indices) == {0: 0, 2: 1} + supervisor.actions.merge() + supervisor.block() + target = supervisor.selected_clusters[0] + expected = supervisor.clustering.spike_clusters.copy() + supervisor.undo() + supervisor.block() + assert supervisor.selection.state == staged + supervisor.redo() + supervisor.block() + supervisor.save() + assert dict(controller.parent_inspection.lineage.colors(target)) == {0: 0, 2: 1} + finally: + gui.close() + controller.close() + reopened = TemplateController(dir_path=path, config_dir=tmp_path / 'config', plugins=[]) + try: + np.testing.assert_array_equal(reopened.bounded_session.assignments, expected) + assert dict(reopened.parent_inspection.lineage.colors(target)) == {0: 0, 2: 1} + assert set(reopened.parent_inspection.lineage.parents(target)) == {0, 2} + replay = apply_curation(params, path, tmp_path / 'replay', batch_size=2) + np.testing.assert_array_equal(np.load(replay / 'spike_clusters.npy'), expected) + review = reopened.supervisor.merge_propositions.catalog.reviews[key] + assert review.result_unit_id == target + assert set(review.applied_unit_ids) == {0, 2} + finally: + reopened.close() diff --git a/phy/apps/large_recording/tests/test_ccg_exclusion.py b/phy/apps/large_recording/tests/test_ccg_exclusion.py new file mode 100644 index 000000000..ee2ca7860 --- /dev/null +++ b/phy/apps/large_recording/tests/test_ccg_exclusion.py @@ -0,0 +1,240 @@ +"""Independent all-pairs and discrete-clock oracles for visual CCG exclusion.""" + +from itertools import product + +import numpy as np +import pytest + +from phy.apps.large_recording.statistics import _window_chance_baseline, window_correlograms + +TOGGLES = list(product((False, True), repeat=2)) + + +def _all_pairs(samples, clusters, windows, ids, bin_samples, half_bins, radius, auto, cross): + """Enumerate unordered source rows directly, independently of the shift kernel.""" + expected = np.zeros((len(ids), len(ids), 2 * half_bins + 1), dtype=np.int64) + lookup = {label: i for i, label in enumerate(ids)} + for start, stop in windows: + rows = [i for i, tick in enumerate(samples) if start <= tick < stop and clusters[i] in ids] + for i, left in enumerate(rows): + for right in rows[i + 1 :]: + lag = int(samples[right]) - int(samples[left]) + a, b = lookup[clusters[left]], lookup[clusters[right]] + if lag <= radius and (auto if a == b else cross): + continue + delay_bin = lag // bin_samples + if delay_bin > half_bins: + continue + expected[a, b, half_bins + delay_bin] += 1 + if a != b or delay_bin: + expected[b, a, half_bins - delay_bin] += 1 + return expected + + +@pytest.mark.parametrize('auto,cross', TOGGLES) +@pytest.mark.parametrize( + 'width,radius', [(0, 0), (0.1, 3), (0.3, 9), (0.4, 12), (0.32, 9), (0.5, 15), (10, 300)] +) +def test_exclusion_matches_independent_pairs_at_late_clocks(width, radius, auto, cross): + origin = 1000 * 3600 * 30000 + offsets = np.array([0, 0, 1, 3, 9, 10, 12, 14, 15, 16, 23, 30, 44, 45, 60]) + samples = origin + np.concatenate((offsets, [99, 100], 300 + offsets)) + clusters = np.resize(np.array([2_000_000_001, 2, 2, 2_000_000_001, 99]), len(samples)) + windows = np.array([[origin, origin + 100], [origin + 300, origin + 400]]) + original_samples, original_clusters = samples.copy(), clusters.copy() + # Swap tied rows and reverse output cluster order independently. Unselected + # cluster 99 and a selected spike in the gap do not contribute. + for swap_ties, ids in product((False, True), ([2_000_000_001, 2], [2, 2_000_000_001])): + labels = clusters.copy() + if swap_ties: + labels[[0, 1]] = labels[[1, 0]] + expected = _all_pairs(samples, labels, windows, ids, 15, 3, radius, auto, cross) + actual = window_correlograms( + samples, + labels, + windows, + ids, + 30000, + 0.0005, + 0.003, + exclusion_ms=width, + exclude_auto=auto, + exclude_cross=cross, + ) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(actual, actual.transpose(1, 0, 2)[..., ::-1]) + assert actual.dtype == np.int64 + np.testing.assert_array_equal(samples, original_samples) + np.testing.assert_array_equal(clusters, original_clusters) + + +@pytest.mark.parametrize('auto,cross', TOGGLES) +def test_empty_and_fully_excluded_windows(auto, cross): + samples = np.array([0, 0, 1, 2], dtype=np.int64) + clusters = np.array([3, 9, 3, 9]) + windows = np.array([[0, 3], [100, 110]]) + hist, baseline = window_correlograms( + samples, + clusters, + windows, + [9, 3, 42], + 1000, + 0.001, + 0.004, + True, + exclusion_ms=100, + exclude_auto=auto, + exclude_cross=cross, + ) + expected = _all_pairs(samples, clusters, windows, [9, 3, 42], 1, 2, 100, auto, cross) + np.testing.assert_array_equal(hist, expected) + np.testing.assert_array_equal(hist[2], 0) + np.testing.assert_array_equal(baseline[2], 0) + if auto: + np.testing.assert_array_equal(hist[np.arange(3), np.arange(3)], 0) + if cross: + np.testing.assert_array_equal(hist[0, 1], 0) + + +def test_cutoff_is_on_pair_lag_before_binning_and_does_not_delete_spikes(): + # 0.1 and 0.4 ms occupy the same central 0.5 ms bin at 30 kHz. + # All three spikes remain eligible as partners at longer delays. + samples = np.array([0, 3, 12, 60], dtype=np.int64) + clusters = np.array([0, 1, 1, 0]) + hist = window_correlograms( + samples, + clusters, + [[0, 100]], + [0, 1], + 30000, + 0.0005, + 0.004, + exclude_cross=True, + ) + assert hist[0, 1, 4] == 1 # 0.4 ms survives; 0.1 ms does not. + assert hist[0, 1, 1] == 2 # Both former near-zero partners pair with the later spike. + assert hist[1, 1, 4] == 1 # Auto pairs remain enabled independently. + + +@pytest.mark.parametrize('width', [-1, -0.01, np.nan, np.inf, -np.inf, None, 'invalid']) +def test_exclusion_width_must_be_finite_and_nonnegative_even_when_disabled(width): + with pytest.raises(ValueError, match='finite and nonnegative'): + window_correlograms( + np.array([0]), np.array([0]), [[0, 1]], [0], 30000, 0.0005, 0.004, exclusion_ms=width + ) + + +def test_legacy_positional_baseline_and_disabled_options_preserve_output(): + samples = np.array([0, 0, 3, 12, 60]) + clusters = np.array([0, 1, 1, 0, 1]) + args = samples, clusters, [[0, 100]], [1, 0], 30000, 0.0005, 0.004, True + expected = window_correlograms(*args) + actual = window_correlograms(*args, exclusion_ms=100, exclude_auto=False, exclude_cross=False) + for a, b in zip(actual, expected, strict=True): + np.testing.assert_array_equal(a, b) + with pytest.raises(TypeError): + window_correlograms(*args, 0.3) + + +def _clock_baseline(counts, length, bin_samples, half_bins, radius, auto, cross): + """Sum over every ordered pair of independent uniform clock positions.""" + expected = np.zeros((len(counts), len(counts)), dtype=float) + if not half_bins: + return expected + for a, n_a in enumerate(counts): + for b, n_b in enumerate(counts): + allowed = 0 + for left, right in product(range(length), repeat=2): + lag = right - left + if not 1 <= lag // bin_samples <= half_bins: + continue + if lag <= radius and (auto if a == b else cross): + continue + allowed += 1 + partners = n_a * (n_b - (a == b)) + expected[a, b] = partners * allowed / length**2 / half_bins + return expected + + +@pytest.mark.parametrize('auto,cross', TOGGLES) +def test_chance_baseline_exhaustive_uniform_clock_oracle(auto, cross): + counts = np.array([3, 2, 1, 0]) + for length, bin_samples, half_bins, radius in product( + range(1, 8), (1, 2, 3), (0, 1, 3), range(10) + ): + actual = _window_chance_baseline( + counts, + length, + bin_samples, + half_bins, + exclusion_samples=radius, + exclude_auto=auto, + exclude_cross=cross, + ) + expected = _clock_baseline(counts, length, bin_samples, half_bins, radius, auto, cross) + np.testing.assert_allclose(actual, expected, atol=1e-15) + + +@pytest.mark.parametrize('auto,cross', TOGGLES) +@pytest.mark.parametrize('width,radius', [(0, 0), (0.3, 0), (2, 2), (3.5, 3), (100, 100)]) +def test_returned_baseline_matches_window_local_oracle(auto, cross, width, radius): + samples = np.array([0, 1, 1, 2, 100, 101, 102]) + clusters = np.array([0, 0, 1, 1, 0, 1, 1]) + windows = np.array([[0, 7], [100, 104]]) + _, actual = window_correlograms( + samples, + clusters, + windows, + [1, 0, 9], + 1000, + 0.002, + 0.012, + True, + exclusion_ms=width, + exclude_auto=auto, + exclude_cross=cross, + ) + expected = np.zeros((3, 3)) + for start, stop in windows: + counts = [ + np.sum((samples >= start) & (samples < stop) & (clusters == c)) for c in [1, 0, 9] + ] + expected += _clock_baseline(counts, stop - start, 2, 3, radius, auto, cross) + np.testing.assert_allclose(actual, expected) + + +def test_default_cutoff_with_half_ms_bins_leaves_off_center_baseline_unchanged(): + samples = np.array([0, 3, 12, 30, 60]) + clusters = np.array([0, 0, 1, 1, 0]) + args = samples, clusters, [[0, 100]], [0, 1], 30000, 0.0005, 0.004, True + _, expected = window_correlograms(*args) + _, actual = window_correlograms(*args, exclude_auto=True, exclude_cross=True) + np.testing.assert_array_equal(actual, expected) + + +@pytest.mark.parametrize('auto,cross', TOGGLES) +def test_window_accumulation_and_central_fold_preserve_int64(monkeypatch, auto, cross): + # Isolate accumulation from pair generation: each per-window count fits in + # int32, while the sum and folded cross-unit center exceed its maximum. + from phy.apps.large_recording import statistics + + def positive(*args, **kwargs): + return np.full((2, 2, 2), 2**30, dtype=np.int64) + + monkeypatch.setattr(statistics, 'correlograms', positive) + monkeypatch.setattr(statistics, '_excluded_positive_correlograms', positive) + hist = window_correlograms( + np.array([0, 10, 20]), + np.array([0, 1, 0]), + [[0, 2], [10, 12], [20, 22]], + [0, 1], + 1000, + 0.001, + 0.002, + exclude_auto=auto, + exclude_cross=cross, + ) + assert hist.dtype == np.int64 + assert hist[0, 0, 1] == 3 * 2**30 + assert hist[0, 1, 1] == 6 * 2**30 + assert hist[0, 1, 0] == 3 * 2**30 diff --git a/phy/apps/large_recording/tests/test_ccg_exclusion_view.py b/phy/apps/large_recording/tests/test_ccg_exclusion_view.py new file mode 100644 index 000000000..a1babceb5 --- /dev/null +++ b/phy/apps/large_recording/tests/test_ccg_exclusion_view.py @@ -0,0 +1,276 @@ +"""Sampled-only controls, stable evidence, and visualization/curation separation.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.tests.test_adapter import make_gui_sorting +from phy.apps.large_recording.tests.test_ccg_exclusion import _all_pairs +from phy.apps.large_recording.views import SampledCorrelogramView +from phy.apps.template.gui import TemplateController +from phy.cluster.views import CorrelogramView +from phy.gui import GUI +from phy.gui.qt import QApplication, QLineEdit, QPoint, Qt, QWidget + + +def _provider(ids, bin_size, window_size, **kwargs): + return np.zeros((len(ids), len(ids), 5), dtype=np.int64), np.zeros((len(ids), len(ids))) + + +def test_legacy_provider_and_ordinary_view_keep_their_contract(qtbot, tmp_path): + calls = [] + + def legacy(ids, bin_size, window_size): + calls.append((ids, bin_size, window_size)) + return _provider(ids, bin_size, window_size) + + gui = GUI(config_dir=tmp_path / 'config') + qtbot.addWidget(gui) + view = SampledCorrelogramView(correlograms=legacy, sample_rate=30000) + try: + view.attach(gui) + view.cluster_ids = [0, 1] + view.get_clusters_data() + assert len(calls) == 1 + assert view.actions.get('toggle_auto_exclusion') is None + assert view.actions.get('toggle_cross_exclusion') is None + assert 'toggle_auto_exclusion' not in CorrelogramView.default_shortcuts + assert 'toggle_cross_exclusion' not in CorrelogramView.default_shortcuts + finally: + gui.close() + + +@pytest.mark.parametrize('invalid', [-0.1, float('nan'), float('inf'), 'invalid']) +def test_exclusion_width_rejects_invalid_values_without_changing_settings(invalid): + view = SampledCorrelogramView( + correlograms=_provider, exclusion_correlograms=_provider, sample_rate=30000 + ) + try: + with pytest.raises(ValueError): + view.set_exclusion_zone(invalid) + assert view.exclusion_ms == 0.3 + assert not view.exclude_auto and not view.exclude_cross + view.set_exclusion_zone(0) + assert view.exclusion_ms == 0 + finally: + view.canvas.close() + + +@pytest.mark.parametrize('auto_key', [Qt.Key_D, Qt.Key_X]) +def test_shortcuts_are_dock_scoped_and_independent(qtbot, tmp_path, auto_key): + gui = GUI(config_dir=tmp_path / 'config') + qtbot.addWidget(gui) + view = SampledCorrelogramView( + correlograms=_provider, + exclusion_correlograms=_provider, + sample_rate=30000, + shortcuts={'toggle_auto_exclusion': 'x'} if auto_key == Qt.Key_X else None, + ) + other = QLineEdit() + try: + view.attach(gui) + gui.add_view(other) + with qtbot.waitExposed(gui): + gui.show() + gui.activateWindow() + qtbot.waitUntil(gui.isActiveWindow) + qtbot.mouseClick(view.canvas, Qt.LeftButton, pos=QPoint(20, 20)) + qtbot.waitUntil( + view.canvas.hasFocus if isinstance(view.canvas, QWidget) else view.canvas.isActive + ) + qtbot.keyClick(view.canvas, auto_key) + qtbot.waitUntil(lambda: view.exclude_auto) + assert not view.exclude_cross + assert view.actions.get('toggle_auto_exclusion').isChecked() + qtbot.keyClick(view.canvas, Qt.Key_D, modifier=Qt.ShiftModifier) + qtbot.waitUntil(lambda: view.exclude_cross) + assert view.exclude_auto + assert 'EXCL auto+cross ±0.3 ms' in view.dock.status + other.setFocus() + qtbot.waitUntil(other.hasFocus) + qtbot.keyClicks(other, 'dD') + assert other.text() == 'dD' + assert view.exclude_auto and view.exclude_cross + second = SampledCorrelogramView( + correlograms=_provider, exclusion_correlograms=_provider, sample_rate=30000 + ) + second.attach(gui) + assert not second.actions.get('toggle_auto_exclusion').shortcut().toString() + assert not second.actions.get('toggle_cross_exclusion').shortcut().toString() + finally: + gui.close() + + +def _make_close_spike_controller(tmp_path): + params = make_gui_sorting(tmp_path / 'source') + np.save( + params.parent / 'spike_times.npy', + np.array([0, 3, 12, 60, 63, 75, 90, 93, 105, 120, 123, 135], dtype=np.int64), + ) + output = prepare_large( + params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20, max_spikes=100 + ) + return params, TemplateController( + dir_path=output, config_dir=tmp_path / 'config', plugins=[], enable_threading=False + ) + + +@pytest.mark.parametrize('auto_key', [Qt.Key_D, Qt.Key_X]) +def test_exclusion_keys_in_full_bounded_gui_change_counts_without_curation( + qtbot, tmp_path, auto_key +): + _, controller = _make_close_spike_controller(tmp_path) + gui = controller.create_gui(do_prompt_save=False) + qtbot.addWidget(gui) + view = gui.get_view('SampledCorrelogramView') + if auto_key == Qt.Key_X: + view.actions.get('toggle_auto_exclusion').setShortcut('X') + assignments = controller.bounded_session.assignments.copy() + try: + with qtbot.waitExposed(gui): + gui.show() + gui.activateWindow() + qtbot.waitUntil(gui.isActiveWindow) + controller.supervisor.select([0, 1, 2]) + controller.supervisor.block() + view.set_exclusion_zone(2) + original, _ = view._get_correlograms_data() + view.dock.raise_() + qtbot.mouseClick(view.canvas, Qt.LeftButton, pos=QPoint(20, 20)) + qtbot.waitUntil( + view.canvas.hasFocus if isinstance(view.canvas, QWidget) else view.canvas.isActive + ) + if not isinstance(view.canvas, QWidget): + view.canvas.requestActivate() + qtbot.waitUntil(lambda: QApplication.focusWindow() == view.canvas) + qtbot.keyClick(view.canvas, auto_key) + qtbot.waitUntil(lambda: view.exclude_auto) + auto, _ = view._get_correlograms_data() + assert auto[0, 0].sum() < original[0, 0].sum() + np.testing.assert_array_equal(auto[0, 1], original[0, 1]) + qtbot.keyClick(view.canvas, Qt.Key_D, modifier=Qt.ShiftModifier) + qtbot.waitUntil(lambda: view.exclude_cross) + both, _ = view._get_correlograms_data() + assert both[0, 1].sum() < original[0, 1].sum() + np.testing.assert_array_equal(both[0, 0], auto[0, 0]) + qtbot.keyClick(view.canvas, auto_key) + qtbot.keyClick(view.canvas, Qt.Key_D, modifier=Qt.ShiftModifier) + qtbot.waitUntil(lambda: not view.exclude_auto and not view.exclude_cross) + np.testing.assert_array_equal(view._get_correlograms_data()[0], original) + np.testing.assert_array_equal(controller.bounded_session.assignments, assignments) + assert not controller.bounded_session.events + assert not controller.supervisor.is_dirty() + finally: + gui.close() + controller.close() + + +def test_view_exclusion_preserves_data_history_and_settings_across_reopen(qtbot, tmp_path): + params, controller = _make_close_spike_controller(tmp_path) + gui = controller.create_gui(default_views=['SampledCorrelogramView'], do_prompt_save=False) + qtbot.addWidget(gui) + directory = controller.dir_path + view = gui.get_view('SampledCorrelogramView') + session = controller.bounded_session + immutable = { + path: path.read_bytes() + for folder in (params.parent, directory) + for path in folder.glob('*.npy') + } + assignments = session.assignments.copy() + history = controller.supervisor._global_history.current_position + evidence_ids = controller.model.spike_samples.copy() + try: + controller.supervisor.select([0, 1, 2]) + controller.supervisor.block() + view.set_bin(0.5) + original, baseline = view._get_correlograms_data() + center = original.shape[2] // 2 + view.toggle_cross_exclusion(True) + filtered, adjusted = view._get_correlograms_data() + assert original[0, 1, center] > 0 + assert filtered[0, 1, center] == 0 # 0.1 ms pairs excluded. + assert filtered[0, 2, center] > 0 # 0.4 ms pairs in that same bin retained. + np.testing.assert_array_equal(filtered[0, 0], original[0, 0]) + np.testing.assert_array_equal(adjusted, baseline) + view.toggle_cross_exclusion(False) + np.testing.assert_array_equal(view._get_correlograms_data()[0], original) + view.set_exclusion_zone(2) + view.toggle_auto_exclusion(True) + assert view._get_correlograms_data()[0][0, 0].sum() < original[0, 0].sum() + view.toggle_cross_exclusion(True) + assert '±2 ms' in view.status + assert not session.events + assert controller.supervisor._global_history.current_position == history + assert not controller.supervisor.is_dirty() + np.testing.assert_array_equal(session.assignments, assignments) + np.testing.assert_array_equal(controller.model.spike_samples, evidence_ids) + assert all(path.read_bytes() == data for path, data in immutable.items()) + # Large exclusion widths can remove every pair; the empty histogram still renders. + view.set_exclusion_zone(1000) + assert view._get_correlograms_data()[0].sum() == 0 + view.plot() + view.set_exclusion_zone(2) + finally: + gui.close() + controller.close() + + reopened = TemplateController( + dir_path=directory, config_dir=tmp_path / 'config', plugins=[], enable_threading=False + ) + reopened_gui = reopened.create_gui( + default_views=['SampledCorrelogramView'], do_prompt_save=False + ) + qtbot.addWidget(reopened_gui) + try: + restored = reopened_gui.get_view('SampledCorrelogramView') + assert restored.exclusion_ms == 2 + assert restored.exclude_auto and restored.exclude_cross + assert restored.actions.get('toggle_auto_exclusion').isChecked() + assert restored.actions.get('toggle_cross_exclusion').isChecked() + assert not reopened.bounded_session.events + assert not reopened.supervisor.is_dirty() + finally: + reopened_gui.close() + reopened.close() + + +def test_exclusion_uses_live_memberships_after_merge_split_and_undo(tmp_path): + _, controller = _make_close_spike_controller(tmp_path) + view = controller.create_sampled_correlogram_view() + supervisor = controller.supervisor + samples = controller.model.spike_samples.copy() + view._set_bin_window(bin_size=0.0005, window_size=0.003) + view.exclude_auto = view.exclude_cross = True + + def checked_counts(ids): + view.cluster_ids = ids + actual, _ = view._get_correlograms_data() + expected = _all_pairs( + samples, + supervisor.clustering.spike_clusters, + controller.evidence_windows, + ids, + 15, + 3, + 9, + True, + True, + ) + np.testing.assert_array_equal(actual, expected) + np.testing.assert_array_equal(controller.model.spike_samples, samples) + return actual + + try: + before = checked_counts([0, 1]) + merged = supervisor.merge([0, 1]).added + after_merge = checked_counts(merged) + children = supervisor.split_source_amplitude(merged[0], 4.5).added + checked_counts(children) + supervisor.undo() + np.testing.assert_array_equal(checked_counts(merged), after_merge) + supervisor.undo() + np.testing.assert_array_equal(checked_counts([0, 1]), before) + finally: + view.canvas.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_cli.py b/phy/apps/large_recording/tests/test_cli.py new file mode 100644 index 000000000..cf5a432ce --- /dev/null +++ b/phy/apps/large_recording/tests/test_cli.py @@ -0,0 +1,307 @@ +"""Batch CLI coverage and window-policy regressions.""" + +import json +import signal +from concurrent.futures import CancelledError +from io import StringIO + +import pytest +from click.testing import CliRunner + +from phy.apps import phycli +from phy.apps.large_recording.progress import ProgressReporter +from phy.apps.large_recording.tests.test_source import make_sorting + + +def test_progress_reporter_throttles_and_reports_counts_rate_and_eta(): + now = [0.0] + output = StringIO() + progress = ProgressReporter(stream=output, interval=2, clock=lambda: now[0]) + + progress('building full summaries', 0, 100) + now[0] = 1 + progress('building full summaries', 50, 100) + assert output.getvalue().count('\n') == 1 + now[0] = 2 + progress('building full summaries', 50, 100) + progress('building full summaries', 100, 100) + + lines = output.getvalue().splitlines() + assert len(lines) == 3 + assert '0 / 100 spikes' in lines[0] + assert '50 / 100 spikes (50.0%)' in lines[1] + assert '25 spikes/s' in lines[1] + assert 'elapsed 2s' in lines[1] + assert 'ETA 2s' in lines[1] + assert '100 / 100 spikes (100.0%)' in lines[2] + + +def test_progress_reporter_handles_unknown_totals_and_stage_changes(): + output = StringIO() + progress = ProgressReporter(stream=output, interval=60, clock=lambda: 0.0) + progress('hashing source bytes', 0, 0) + progress('copying source files', 12, None) + lines = output.getvalue().splitlines() + assert len(lines) == 2 + assert lines[0].startswith('hashing source bytes: 0 bytes, elapsed 0s') + assert lines[1].startswith('copying source files: 12 bytes, elapsed 0s') + assert 'nan' not in output.getvalue().lower() + + +@pytest.mark.parametrize('done,total', [(-1, 10), (0, -1)]) +def test_progress_reporter_rejects_negative_counts(done, total): + progress = ProgressReporter(stream=StringIO()) + with pytest.raises(ValueError, match='nonnegative'): + progress('building full summaries', done, total) + + +def test_progress_reporter_cancel_is_cooperative(): + progress = ProgressReporter(stream=StringIO()) + progress.cancel() + with pytest.raises(CancelledError, match='cancelled'): + progress('building full summaries', 1, 10) + + +def test_sigint_cancels_immediately_and_restores_handler(): + original = signal.getsignal(signal.SIGINT) + progress = ProgressReporter(stream=StringIO()) + + with pytest.raises(CancelledError, match='cancelled'), progress: + assert signal.getsignal(signal.SIGINT) == progress._handle_sigint + progress._handle_sigint(signal.SIGINT, None) + + assert signal.getsignal(signal.SIGINT) == original + + +def test_apply_curation_cli_uses_workers_and_keeps_progress_off_stdout(tmp_path, monkeypatch): + from phy.apps.large_recording import replay + + source = tmp_path / 'source' + source.mkdir() + (source / 'params.py').write_text('sample_rate = 1\n') + bounded = tmp_path / 'bounded' + bounded.mkdir() + output = tmp_path / 'curated' + calls = {} + + def fake_apply(source_params, bounded_dir, output_dir, **kwargs): + calls.update(kwargs) + kwargs['progress']('replaying assignments', 1, 4) + kwargs['progress']('replaying assignments', 4, 4) + return output + + monkeypatch.setattr(replay, 'apply_curation', fake_apply) + result = CliRunner().invoke( + phycli, + [ + 'apply-curation', + str(source / 'params.py'), + str(bounded), + str(output), + '--workers', + '3', + ], + ) + + assert result.exit_code == 0, result.output + assert result.stdout == f'Published complete curated sorting: {output}\n' + assert 'replaying assignments: 1 / 4 spikes' in result.stderr + assert 'replaying assignments: 4 / 4 spikes' in result.stderr + assert calls['workers'] == 3 + assert callable(calls['cancel']) + + +def test_cancelled_cli_operation_reports_error_on_stderr(tmp_path, monkeypatch): + from phy.apps.large_recording import replay + + source = tmp_path / 'source' + source.mkdir() + params = source / 'params.py' + params.write_text('sample_rate = 1\n') + bounded = tmp_path / 'bounded' + bounded.mkdir() + + def cancel_apply(*args, **kwargs): + kwargs['progress'].cancel() + kwargs['cancel']() + + monkeypatch.setattr(replay, 'apply_curation', cancel_apply) + result = CliRunner().invoke( + phycli, + ['apply-curation', str(params), str(bounded), str(tmp_path / 'curated')], + ) + + assert result.exit_code == 1 + assert result.stdout == '' + assert 'Operation cancelled.' in result.stderr + + +def test_apply_curation_cli_reports_bytes_and_spikes(tmp_path): + from phy.apps.large_recording.curation import BoundedSession + from phy.apps.large_recording.tests.test_live_summaries import package + + source, bounded = package(tmp_path) + session = BoundedSession(bounded) + session.record_merge([0, 1], 100, {'group': 'good'}) + session.save() + session.close() + output = tmp_path / 'curated' + result = CliRunner().invoke( + phycli, + [ + 'apply-curation', + str(source / 'params.py'), + str(bounded), + str(output), + '--workers', + '2', + ], + ) + + assert result.exit_code == 0, result.output + assert result.stdout == f'Published complete curated sorting: {output}\n' + assert 'copying source files:' in result.stderr and 'bytes' in result.stderr + assert 'replaying assignments:' in result.stderr and 'spikes' in result.stderr + + +def test_prepare_cli_reports_waveform_coverage_and_window_policy(tmp_path): + params = make_sorting(tmp_path / 'source') + output = tmp_path / 'bounded' + result = CliRunner().invoke( + phycli, + [ + 'prepare-large', + str(params), + str(output), + '--workers', + '2', + '--window-policy', + 'generated', + '--window-seconds', + '20', + '--stratum-seconds', + '20', + ], + ) + assert result.exit_code == 0, result.output + assert f'Prepared bounded evidence: {output}' in result.stdout + assert '5 retained / 5 source; 0 omitted' in result.stdout + assert 'writing bounded rows:' in result.stderr + assert 'copying static arrays:' in result.stderr and 'bytes' in result.stderr + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + assert manifest['selection']['window_policy'] == 'generated' + + +def test_prepare_cli_explains_missing_producer_windows(tmp_path): + params = make_sorting(tmp_path / 'source') + output = tmp_path / 'bounded' + result = CliRunner().invoke( + phycli, + ['prepare-large', str(params), str(output), '--window-policy', 'producer'], + ) + assert result.exit_code == 1 + assert 'producer' in result.output.lower() + assert not output.exists() + + +def test_build_and_attach_summary_store_commands(tmp_path): + from phy.apps.large_recording.live_summaries import LiveSummaryEngine + from phy.apps.large_recording.summary_store import SummaryStore + from phy.apps.large_recording.tests.test_live_summaries import package + + _, bounded = package(tmp_path) + output = tmp_path / 'store' + runner = CliRunner() + result = runner.invoke( + phycli, ['build-summary-store', str(bounded), str(output), '--batch-size', '2'] + ) + assert result.exit_code == 0, result.output + assert 'building summary store:' in result.stderr + assert '(100.0%)' in result.stderr + (bounded / '.phy' / 'live-summary-store.json').unlink() + result = runner.invoke(phycli, ['attach-summary-store', str(bounded), str(output)]) + assert result.exit_code == 0, result.output + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + assert sum(len(data) for data in store.batches(0, 2)) == 4 + + +def test_prepare_with_summary_store_and_recoverable_optional_failure(tmp_path): + params = make_sorting(tmp_path / 'source') + runner = CliRunner() + bounded = tmp_path / 'bounded' + output = tmp_path / 'store' + result = runner.invoke( + phycli, ['prepare-large', str(params), str(bounded), '--summary-store', str(output)] + ) + assert result.exit_code == 0, result.output + assert output.is_dir() + failed_bounded = tmp_path / 'bounded-second' + result = runner.invoke( + phycli, ['prepare-large', str(params), str(failed_bounded), '--summary-store', str(output)] + ) + assert result.exit_code == 1 + assert 'Bounded package is ready' in result.output + assert 'build-summary-store to retry' in result.output + assert (failed_bounded / '_phy_curation_manifest.json').is_file() + + +def test_upgrade_row_store_and_attach_index_commands(tmp_path): + from phy.apps.large_recording.summary_store import summary_store_reference + from phy.apps.large_recording.tests.test_live_summaries import package + + _, bounded = package(tmp_path) + store, ranges = tmp_path / 'store', tmp_path / 'ranges' + runner = CliRunner() + result = runner.invoke( + phycli, ['build-summary-store', str(bounded), str(store), '--rows-only'] + ) + assert result.exit_code == 0, result.output + assert 'amplitude_index' not in json.loads(summary_store_reference(bounded)) + result = runner.invoke( + phycli, ['build-amplitude-index', str(bounded), str(ranges), '--workers', '2'] + ) + assert result.exit_code == 0, result.output + assert 'sorting amplitude ranges:' in result.stderr + assert 'amplitude_index' in json.loads(summary_store_reference(bounded)) + runner.invoke(phycli, ['attach-summary-store', str(bounded), str(store)]) + result = runner.invoke(phycli, ['attach-amplitude-index', str(bounded), str(ranges)]) + assert result.exit_code == 0, result.output + assert 'amplitude_index' in json.loads(summary_store_reference(bounded)) + + +def test_combined_budget_fails_before_row_preparation(tmp_path): + from phy.apps.large_recording.tests.test_live_summaries import package + + _, bounded = package(tmp_path) + store = tmp_path / 'store' + result = CliRunner().invoke( + phycli, ['build-summary-store', str(bounded), str(store), '--max-bytes', '1000000'] + ) + assert result.exit_code == 1 + assert 'Combined store estimate' in result.output + assert not store.exists() + + +def test_default_pipeline_preserves_newer_choice_between_stages(tmp_path, monkeypatch): + from phy.apps.large_recording import summary_store + from phy.apps.large_recording.range_build import build_amplitude_index + from phy.apps.large_recording.tests.test_live_summaries import package + + _, bounded = package(tmp_path) + original = summary_store.build_summary_store + chosen = tmp_path / 'newer-index' + + def choose_between_stages(*args, **kwargs): + result = original(*args, **kwargs) + build_amplitude_index(bounded, chosen) + return result + + monkeypatch.setattr(summary_store, 'build_summary_store', choose_between_stages) + store = tmp_path / 'store' + result = CliRunner().invoke(phycli, ['build-summary-store', str(bounded), str(store)]) + assert result.exit_code == 1 + assert 'Row snapshot ready' in result.output + assert 'changed before' in result.output + assert not (store / 'amplitude-index').exists() + reference = json.loads(summary_store.summary_store_reference(bounded)) + assert reference['amplitude_index']['path'] == str(chosen) diff --git a/phy/apps/large_recording/tests/test_controller_equivalence.py b/phy/apps/large_recording/tests/test_controller_equivalence.py new file mode 100644 index 000000000..e0f1398ec --- /dev/null +++ b/phy/apps/large_recording/tests/test_controller_equivalence.py @@ -0,0 +1,413 @@ +"""The same user commands on a full sorting and genuine bounded evidence.""" + +import gc +import shutil +from contextlib import contextmanager + +import numpy as np +import pytest +from phylib.io.model import load_model +from phylib.utils.event import _EVENT + +import tools.compare_curation_modes as comparison +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.tests.test_adapter import make_gui_sorting +from phy.apps.template.gui import TemplateController +from phy.gui.qt import QApplication, QCoreApplication, QEvent +from phy.plot.tests import mouse_drag +from phy.plot.transform import NDC, Range + + +def _make_source(path): + params = make_gui_sorting(path) + seconds = np.r_[np.arange(50), np.arange(60, 120)] + units = np.array([0, 1, 2, 50, 51, 99], dtype=np.int32) + clusters = np.tile(units, len(seconds)) + times = np.repeat(seconds * 30000, len(units)) + np.tile( + np.arange(len(units)) * 300, len(seconds) + ) + amplitudes = np.repeat( + np.where(seconds % 2 == 0, 1, np.where(seconds % 4 == 1, 4, 7)), len(units) + ).astype(np.float32) + arrays = { + 'spike_times.npy': times.astype(np.int64), + 'spike_clusters.npy': clusters, + 'spike_templates.npy': (np.arange(len(times)) % 3).astype(np.int32), + 'amplitudes.npy': amplitudes, + 'spike_positions.npy': np.column_stack((np.zeros(len(times)), times / 30000)), + 'spike_depths.npy': (times / 30000).astype(np.float64), + 'pc_features.npy': np.arange(len(times) * 4, dtype=np.float32).reshape(-1, 2, 2), + 'whitening_mat.npy': np.eye(3, dtype=np.float32), + 'whitening_mat_inv.npy': np.eye(3, dtype=np.float32), + } + waveform_ids = np.arange(0, len(times), 7, dtype=np.int64) + arrays.update( + { + '_phy_spikes_subset.spikes.npy': waveform_ids, + '_phy_spikes_subset.channels.npy': np.tile([0, 1], (len(waveform_ids), 1)), + '_phy_spikes_subset.waveforms.npy': np.arange( + len(waveform_ids) * 8 * 2, dtype=np.float32 + ).reshape(-1, 8, 2), + } + ) + for name, values in arrays.items(): + np.save(path / name, values) + params.write_text( + params.read_text().replace('num_samples = 600000', 'num_samples = 3600000') + + 'valid_intervals = [[0, 1500000], [1800000, 3600000]]\n' + ) + (path / 'cluster_group.tsv').write_text( + 'cluster_id\tgroup\n0\tgood\n1\tmua\n2\tgood\n50\tgood\n51\tmua\n99\tnoise\n' + ) + (path / 'cluster_snr.tsv').write_text( + 'cluster_id\tsnr\n0\t8\n1\t10\n2\t12\n50\t16\n51\t18\n99\t14\n' + ) + (path / 'cluster_si_unit_ids.tsv').write_text( + 'cluster_id\tsi_unit_id\n0\t0\n1\t1\n2\t2\n50\t50\n51\t51\n99\t99\n' + ) + (path / 'cluster_notes.tsv').write_text( + 'cluster_id\tnotes\n50\tproducer parent A\n51\tproducer parent B\n99\toriginal control\n' + ) + return params + + +def _hashes(path): + return {str(p.relative_to(path)): hash_file(p) for p in path.rglob('*') if p.is_file()} + + +@contextmanager +def _open(path, config, bounded): + baseline = {id(item) for item in _EVENT._callbacks} + model = None if bounded else load_model(path / 'params.py') + controller = TemplateController( + dir_path=path, + model=model, + config_dir=config, + plugins=[], + enable_threading=False, + ) + controller.n_spikes_amplitudes = 5 + controller.n_spikes_amplitudes_total = 5 + controller.n_spikes_amplitudes_background = 8 + view_name = 'EvidenceAmplitudeView' if bounded else 'AmplitudeView' + gui = None + try: + # Explicit view_count prevents saved/default layout from adding other + # renderers: the controller, Supervisor and real amplitude provider stay native. + gui = controller.create_gui( + view_count={view_name: 1}, default_views=[view_name], do_prompt_save=False + ) + gui.resize(900, 700) + gui.show() + QApplication.processEvents() + view = gui.get_view(view_name) + if not bounded: + view.amplitudes_type = 'template' + yield controller, gui, view + finally: + if gui is not None: + gui.close() + gui.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + QApplication.processEvents() + controller.close() + # Global callbacks may own controller/history cycles after closing a GUI. + # Retain exactly the callbacks that preceded this isolated controller. + _EVENT._callbacks = [item for item in _EVENT._callbacks if id(item) in baseline] + del controller, model + gc.collect() + + +def _snapshot(supervisor): + return ( + supervisor.clustering.spike_clusters.copy(), + { + field: { + int(unit): supervisor.cluster_meta.get(field, int(unit)) + for unit in supervisor.clustering.cluster_ids + } + for field in ('group', 'notes') + }, + ) + + +def _assert_snapshot(supervisor, expected): + actual = _snapshot(supervisor) + np.testing.assert_array_equal(actual[0], expected[0]) + assert actual[1] == expected[1] + + +def _split(qtbot, controller, gui, view, parent, threshold): + supervisor = controller.supervisor + supervisor.select([parent]) + supervisor.block() + qtbot.wait(20) + view.plot() + ids = supervisor.clustering.spikes_per_cluster[parent].copy() + amplitudes = np.asarray(controller.model.amplitudes[ids]).reshape(-1) + assert np.all(np.isfinite(amplitudes)) + drawn = next(b for b in view.get_clusters_data() if b.cluster_id == parent) + assert len(drawn.spike_ids) <= 5 < len(ids), 'The display must not be the split input.' + selected = amplitudes < threshold + assert selected.any() and (~selected).any(), 'Both children must have retained evidence.' + width, height = view.canvas.get_size() + point = (width // 3, height // 2) + target = Range(view.data_bounds, NDC).apply([[0, threshold]])[0][1] + normalized_y = 1 - 2 * point[1] / height + pan = view.canvas.panzoom.pan + view.canvas.panzoom.pan = ( + pan[0], + normalized_y / view.canvas.panzoom._zoom_aspect()[1] - target, + ) + # Move the viewport by representable steps if inverse-transform rounding + # lands just above the requested boundary; no stored value is rewritten. + draw_threshold = threshold + for _ in range(16): + if view._threshold_from_window_pos(point) <= threshold: + break + draw_threshold = np.nextafter(draw_threshold, -np.inf) + below = Range(view.data_bounds, NDC).apply([[0, draw_threshold]])[0][1] + view.canvas.panzoom.pan = ( + pan[0], + normalized_y / view.canvas.panzoom._zoom_aspect()[1] - below, + ) + mouse_drag( + qtbot, + view.canvas, + (point[0] - 10, point[1]), + point, + button='right', + modifiers=('Alt',), + ) + assert view.split_threshold == pytest.approx(threshold, abs=1e-12, rel=0) + np.testing.assert_array_equal(selected, amplitudes < view.split_threshold) + action = supervisor.actions.get('split') + assert action.isEnabled() + action.trigger() + supervisor.block() + after = supervisor.clustering.spike_clusters[ids] + low, rest = np.unique(after[selected]), np.unique(after[~selected]) + assert len(low) == len(rest) == 1 and low[0] != rest[0] + return int(low[0]), int(rest[0]) + + +def _run_ledger(qtbot, path, config, bounded, actions, aliases): + aliases = dict(aliases) + history, future = [], [] + opened = _open(path, config, bounded) + controller, gui, view = opened.__enter__() + try: + for action in actions: + op, *args = action + supervisor = controller.supervisor + if op == 'reopen': + opened.__exit__(None, None, None) + opened = _open(path, config, bounded) + controller, gui, view = opened.__enter__() + history.clear() + future.clear() + continue + if op == 'save': + supervisor.save() + continue + if op in ('undo', 'redo'): + origin, destination = (history, future) if op == 'undo' else (future, history) + current = _snapshot(supervisor) + expected = origin.pop() if origin else current + if expected is not current: + destination.append(current) + getattr(supervisor, op)() + supervisor.block() + _assert_snapshot(supervisor, expected) + continue + history.append(_snapshot(supervisor)) + future.clear() + if op == 'merge': + result, *parents = args + up = supervisor.merge([aliases[parent] for parent in parents]) + supervisor.block() + assert len(up.added) == 1 + aliases[result] = int(up.added[0]) + elif op == 'split': + parent, low, rest, threshold = args + aliases[low], aliases[rest] = _split( + qtbot, controller, gui, view, aliases[parent], threshold + ) + elif op == 'label': + parent, field, value = args + supervisor.label(field, value, cluster_ids=[aliases[parent]]) + supervisor.block() + assert supervisor.cluster_meta.get(field, aliases[parent]) == value + else: + raise AssertionError(op) + supervisor = controller.supervisor + state = _snapshot(supervisor) + supervisor.save() + finally: + opened.__exit__(None, None, None) + return aliases, state + + +ROUND_ONE = [ + ('merge', 'merged', 'a', 'b'), + ('undo',), + ('redo',), + ('split', 'merged', 'low', 'rest', 4.0), + ('undo',), + ('redo',), + ('merge', 'final', 'low', 'c'), + ('label', 'final', 'group', 'good'), + ('label', 'rest', 'group', 'mua'), + ('label', 'final', 'notes', 'reviewed merged child'), + ('label', 'rest', 'notes', 'reviewed remainder'), + ('label', 'rest', 'group', 'noise'), + ('undo',), + ('redo',), + ('undo',), + ('label', 'rest', 'notes', 'branch kept'), + ('redo',), # A new edit discarded the noise redo branch. + ('label', 'control', 'group', None), + ('label', 'control', 'notes', 'cleared group on unchanged membership'), + ('save',), + ('reopen',), + ('save',), +] + +ROUND_TWO = [ + ('merge', 'reunited', 'final', 'rest'), + ('split', 'reunited', 'second_low', 'second_rest', 4.0), + ('label', 'second_low', 'group', 'good'), + ('label', 'second_rest', 'group', 'mua'), + ('label', 'second_low', 'notes', 'reviewed round two low'), + # Seed an explicit note before editing it: ordinary inherited parent notes + # and bounded new-membership clearing intentionally have different baselines. + ('label', 'second_rest', 'notes', 'round two draft'), + ('label', 'second_rest', 'notes', 'reviewed round two remainder'), + ('undo',), + ('redo',), + ('save',), + ('reopen',), + ('save',), +] + + +EXPECTED_ONE = { + 'final': {'group': 'good', 'notes': 'reviewed merged child'}, + 'rest': {'group': 'mua', 'notes': 'branch kept'}, + 'control': {'group': None, 'notes': 'cleared group on unchanged membership'}, +} +EXPECTED_TWO = { + 'second_low': {'group': 'good', 'notes': 'reviewed round two low'}, + 'second_rest': {'group': 'mua', 'notes': 'reviewed round two remainder'}, + 'control': {'group': None, 'notes': 'cleared group on unchanged membership'}, +} +NO_EDITS = [('save',), ('reopen',), ('save',)] +UNREVIEWED = [('merge', 'unreviewed', 'review_a', 'review_b'), *NO_EDITS] + + +@pytest.mark.parametrize('window,budget,seed', [(2, 32, 0), (3, 48, 11), (4, 48, 23)]) +def test_same_controller_actions_match_full_replay(qtbot, tmp_path, capsys, window, budget, seed): + params = _make_source(tmp_path / 'source') + source_hashes = _hashes(params.parent) + ordinary = tmp_path / 'ordinary' + shutil.copytree(params.parent, ordinary) + ordinary_aliases = bounded_aliases = { + 'a': 0, + 'b': 1, + 'c': 2, + 'review_a': 50, + 'review_b': 51, + 'control': 99, + } + source_params = params + for round_index, (actions, expected_manual) in enumerate( + zip( + (ROUND_ONE, ROUND_TWO, NO_EDITS, UNREVIEWED), + (EXPECTED_ONE, EXPECTED_TWO, EXPECTED_TWO, EXPECTED_TWO), + strict=True, + ) + ): + round_source_hashes = _hashes(source_params.parent) + package = prepare_large( + source_params, + tmp_path / f'bounded-{round_index}', + seed=seed + round_index, + max_spikes=budget, + window_seconds=window, + stratum_seconds=30, + bin_seconds=10, + batch_size=17, + ) + source_labels = np.load(source_params.parent / 'spike_clusters.npy').reshape(-1) + kept = np.load(package / '_phy_spike_global_ids.npy') + assert 0 < len(kept) < len(source_labels) + for unit in np.unique(source_labels): + assert np.any(source_labels[kept] == unit) + assert np.count_nonzero(source_labels[kept] == unit) < np.count_nonzero( + source_labels == unit + ), 'Every active unit must contain unseen source spikes.' + ordinary_aliases, ordinary_state = _run_ledger( + qtbot, + ordinary, + tmp_path / 'config-ordinary', + False, + actions, + ordinary_aliases, + ) + bounded_aliases, bounded_state = _run_ledger( + qtbot, + package, + tmp_path / 'config-bounded', + True, + actions, + bounded_aliases, + ) + for aliases, state in ( + (ordinary_aliases, ordinary_state), + (bounded_aliases, bounded_state), + ): + for alias, fields in expected_manual.items(): + for field, value in fields.items(): + assert state[1][field][aliases[alias]] == value + expected_labels = { + bounded_aliases[alias]: fields for alias, fields in expected_manual.items() + } + output = apply_curation( + source_params, package, tmp_path / f'curated-{round_index}', batch_size=17 + ) + report = comparison.compare_outputs( + ordinary, + output, + fields=('group', 'notes'), + chunk_size=13, + source=params.parent, + expected_labels=expected_labels, + bounded_dir=package, + ) + assert report['ok'], report.get('error', report) + assert report['file_contract']['ok'], report + inventory = report['file_contract']['inventories'] + assert '_phy_merge_parents.npz' in inventory['ordinary']['state_artifacts'] + assert '_phy_merge_parents.npz' not in inventory['replay']['state_artifacts'] + for difference in report['permitted_membership_policy_differences']: + if difference['field'] in ('group', 'notes'): + assert round_index == 3, difference + assert difference['right_id'] == bounded_aliases['unreviewed'], difference + else: + assert difference['field'] in ('snr', 'si_unit_id'), difference + assert difference['right'] == '', difference + assert report['rows'] == len(source_labels) + if round_index == 2: + no_op_files = [p.name for p in source_params.parent.glob('*.npy')] + [ + 'cluster_group.tsv', + 'cluster_notes.tsv', + ] + for name in no_op_files: + assert hash_file(source_params.parent / name) == hash_file(output / name), name + assert _hashes(source_params.parent) == round_source_hashes + assert _hashes(params.parent) == source_hashes + source_params = output / 'params.py' + captured = capsys.readouterr() + assert 'Traceback (most recent call last)' not in captured.err, captured.err diff --git a/phy/apps/large_recording/tests/test_curation.py b/phy/apps/large_recording/tests/test_curation.py new file mode 100644 index 000000000..ed667ef8d --- /dev/null +++ b/phy/apps/large_recording/tests/test_curation.py @@ -0,0 +1,458 @@ +"""Exact bounded journal projection and transactional persistence regressions.""" + +import json +import shutil + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import BASE_ASSIGNMENTS, BoundedSession +from phy.apps.large_recording.source import Source, hash_file +from phy.apps.tests.large_recording_fixtures import make_long_recording_fixture + + +def make_session(tmp_path): + fixture = make_long_recording_fixture(tmp_path) + # The highest complete-source unit is intentionally absent from evidence. + clusters = np.load(fixture.full / 'spike_clusters.npy') + clusters[-1] = 99 + np.save(fixture.full / 'spike_clusters.npy', clusters) + (fixture.full / 'cluster_group.tsv').write_text('cluster_id\tgroup\n0\tgood\n1\tnoise\n') + source = Source(fixture.full / 'params.py', batch_size=5) + rows = np.array([0, 2, 5, 8, 13, 21, 25], dtype=np.int64) + for name in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy', 'amplitudes.npy'): + np.save(fixture.bounded / name, source.arrays[name][rows]) + np.save(fixture.bounded / BASE_ASSIGNMENTS, clusters[rows]) + np.save(fixture.bounded / '_phy_spike_global_ids.npy', rows) + np.save(fixture.bounded / 'windows.npy', np.array([[0, source.num_samples]], dtype=np.int64)) + manifest = { + 'format': 'phy_bounded_curation', + 'format_version': 1, + 'source': { + 'identity': source.identity, + 'revision': source.revision, + 'path': str(source.params_path), + }, + 'sample_rate': source.sample_rate, + 'num_samples': source.num_samples, + 'valid_intervals': source.valid_intervals.tolist(), + 'num_spikes': source.n_spikes, + 'bounded_num_spikes': len(rows), + 'unit_ids': source.unit_ids.tolist(), + 'counts': source.counts.tolist(), + 'next_cluster_id': 100, + 'global_spike_ids_file': '_phy_spike_global_ids.npy', + 'windows_file': 'windows.npy', + 'base_metadata': source.metadata, + 'capabilities': { + 'merge': True, + 'label': True, + 'split': False, + 'predicate_split_attributes': ['amplitudes.npy'], + }, + 'bounded_files': { + name: hash_file(fixture.bounded / name) + for name in ( + BASE_ASSIGNMENTS, + '_phy_spike_global_ids.npy', + 'windows.npy', + 'spike_times.npy', + ) + }, + } + (fixture.bounded / '_phy_curation_manifest.json').write_text(json.dumps(manifest)) + return source, BoundedSession(fixture.bounded) + + +@pytest.mark.parametrize('command', ['record_threshold_split', 'record_split']) +def test_split_numpy_metadata_keys_save_and_reopen(tmp_path, command): + source, session = make_session(tmp_path) + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 0.5, + 'nonfinite': 'keep', + } + children = [np.int64(100), np.int64(101)] + metadata = {'group': {children[0]: 'good', children[1]: 'noise'}} + try: + if command == 'record_threshold_split': + session.record_threshold_split(0, children, predicate, metadata) + else: + session.record_split(0, *children, predicate, metadata) + session.save() + with_metadata = session.events[-1]['metadata']['group'] + assert all(type(key) is int for key in with_metadata) + reopened = BoundedSession(session.path) + try: + np.testing.assert_array_equal(reopened.assignments, session.assignments) + assert reopened.metadata['group'][100] == 'good' + assert reopened.metadata['group'][101] == 'noise' + finally: + reopened.close() + finally: + session.close() + source.close() + + +def test_merge_label_snapshot_branch_reopen(tmp_path): + source, session = make_session(tmp_path) + baseline = session.snapshot() + session.record_merge([0, 1], 100, {'group': 'good'}) + first = session.snapshot() + session.record_label('group', [100], 'mua') + second = session.snapshot() + session.restore(first) + assert session.metadata['group'][100] == 'good' + session.restore(second) + assert session.metadata['group'][100] == 'mua' + session.restore(baseline) + session.record_merge([1, 2], 100, {'group': 'noise'}) + session.record_label('custom', [99, 100], 'reviewed') + session.save(extra_documents={'supplemental.json': {'accepted': [100]}}) + reopened = BoundedSession(session.path) + assert reopened.next_cluster_id == 101 + assert reopened.events == session.events + assert reopened.metadata == session.metadata + assert np.array_equal(reopened.assignments, session.assignments) + assert reopened.extra_documents == {'supplemental.json': {'accepted': [100]}} + assert source.unit_ids.tolist() == [0, 1, 2, 99] + assert 99 not in session.base_assignments + + +@pytest.mark.parametrize('parents,target', [([0, 1], 99), ([0, 0], 100), ([0, 3], 100)]) +def test_merge_collision_and_invalid_parents_do_not_mutate(tmp_path, parents, target): + _, session = make_session(tmp_path) + before = session.snapshot() + with pytest.raises(ValueError): + session.record_merge(parents, target) + assert session.events == before['events'] + assert np.array_equal(session.assignments, before['assignments']) + + +def test_save_requires_exact_semantic_projection(tmp_path): + _, session = make_session(tmp_path) + session.record_merge([0, 1], 100, {'group': 'good'}) + with pytest.raises(ValueError, match='projection'): + session.save(assignments=session.base_assignments) + with pytest.raises(ValueError, match='metadata'): + session.save(metadata={}) + assert not (session.path / '.phy-curation' / 'current.json').exists() + + +@pytest.mark.parametrize('fail_at', ['journal.json', 'checkpoint.json', 'pointer']) +def test_interrupted_save_recovers_previous_generation(tmp_path, monkeypatch, fail_at): + from phy.apps.large_recording import curation + + _, session = make_session(tmp_path) + session.record_merge([0, 1], 100, {'group': 'good'}) + session.save() + previous = session.snapshot() + session.record_label('group', [100], 'mua') + original = curation._write_json + + def fail(path, value): + if path.name == fail_at or (fail_at == 'pointer' and path.name.startswith('.current-')): + raise OSError('injected interrupted write') + return original(path, value) + + monkeypatch.setattr(curation, '_write_json', fail) + with pytest.raises(OSError, match='interrupted'): + session.save() + reopened = BoundedSession(session.path) + assert reopened.events == previous['events'] + assert reopened.metadata == previous['metadata'] + assert session.metadata['group'][100] == 'mua' + + +def test_checkpoint_corruption_is_rejected(tmp_path): + _, session = make_session(tmp_path) + session.save() + (session.checkpoint_path / 'journal.json').write_text('[]\nchanged') + with pytest.raises(ValueError, match='corruption'): + BoundedSession(session.path) + + +def test_bound_base_corruption_is_rejected(tmp_path): + _, session = make_session(tmp_path) + session.close() + shutil.copyfile(session.path / 'spike_times.npy', session.path / BASE_ASSIGNMENTS) + with pytest.raises(ValueError, match='integrity'): + BoundedSession(session.path) + + +def test_threshold_projection_is_serialized_and_nonfinite_policy_explicit(tmp_path): + _, session = make_session(tmp_path) + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 15.0, + 'nonfinite': 'keep', + } + session.record_split(2, 100, 101, predicate, {'group': {100: 'noise', 101: 'good'}}) + expected = session.base_assignments.astype(np.int64).copy() + mask = expected == 2 + selected = np.load(session.path / 'amplitudes.npy') < 15 + expected[mask & selected] = 100 + expected[mask & ~selected] = 101 + assert np.array_equal(session.assignments, expected) + session.save() + assert BoundedSession(session.path).events == session.events + with pytest.raises(ValueError, match='Unsupported'): + session.record_split(0, 102, 103, dict(predicate, attribute='waveform_peak')) + + +@pytest.mark.parametrize('boundary', ['generation', 'pointer']) +def test_atomic_publication_failure_preserves_previous_commit(tmp_path, monkeypatch, boundary): + from phy.apps.large_recording import curation + + _, session = make_session(tmp_path) + session.save() + session.record_merge([0, 1], 100, {'group': 'good'}) + original = curation.os.replace + + def fail(source, destination): + if (boundary == 'generation' and destination.parent.name == 'generations') or ( + boundary == 'pointer' and destination.name == 'current.json' + ): + raise OSError('injected atomic publication failure') + return original(source, destination) + + monkeypatch.setattr(curation.os, 'replace', fail) + with pytest.raises(OSError, match='publication'): + session.save() + assert BoundedSession(session.path).events == [] + assert len(session.events) == 1 + + +def test_nonfinite_predicate_keep_and_reject_are_explicit(): + from phy.apps.large_recording.curation import evaluate_predicate + + values = np.array([1.0, np.nan, np.inf, -np.inf, 3.0]) + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 2.0, + 'nonfinite': 'keep', + } + assert evaluate_predicate(values, predicate).tolist() == [True, False, False, False, False] + with pytest.raises(ValueError, match='Nonfinite'): + evaluate_predicate(values, dict(predicate, nonfinite='reject')) + + +def test_semantically_corrupt_checkpoint_rejected_even_with_valid_file_hashes(tmp_path): + from phy.apps.large_recording.curation import _digest + + _, session = make_session(tmp_path) + session.record_merge([0, 1], 100, {'group': 'good'}) + session.save() + generation = session.checkpoint_path + journal = json.loads((generation / 'journal.json').read_text()) + journal[0]['target'] = 99 + (generation / 'journal.json').write_text(json.dumps(journal)) + descriptor = json.loads((generation / 'checkpoint.json').read_text()) + descriptor['files']['journal.json'] = hash_file(generation / 'journal.json') + (generation / 'checkpoint.json').write_text(json.dumps(descriptor)) + pointer = {'generation': generation.name, 'sha256': _digest(descriptor)} + (session.path / '.phy-curation' / 'current.json').write_text(json.dumps(pointer)) + with pytest.raises(ValueError, match='colliding'): + BoundedSession(session.path) + + +def test_compact_history_preserves_allocator_and_reconstructs_assignments(tmp_path): + _, session = make_session(tmp_path) + before = session.journal_state() + session.record_merge([0, 1], 100, {'group': 'good'}) + after = session.journal_state() + merged = session.assignments.copy() + assert set(after) == {'events', 'next_cluster_id'} + assert after['events'][0] is session.events[0] + session.restore_journal(before) + assert session.events == [] + assert session.next_cluster_id == 101 + assert np.array_equal(session.assignments, session.base_assignments) + session.restore_journal(after) + assert np.array_equal(session.assignments, merged) + session.restore_journal(before) + session.record_merge([1, 2], 101, {'group': 'noise'}) + assert session.next_cluster_id == 102 + + +def test_session_close_releases_own_file_mappings(tmp_path): + _, session = make_session(tmp_path) + mappings = [ + array._mmap + for array in ( + session.global_ids, + session.base_assignments, + *session.attributes.values(), + ) + ] + session.close() + assert all(mapping.closed for mapping in mappings) + session.close() + + +def test_stale_session_save_rejected_without_losing_first_commit(tmp_path): + _, first = make_session(tmp_path) + second = BoundedSession(first.path) + first.record_merge([0, 1], 100, {'group': 'good'}) + second.record_merge([1, 2], 100, {'group': 'noise'}) + first.save(extra_documents={'supplemental.json': {'accepted': [100]}}) + with pytest.raises(ValueError, match='reopen'): + second.save(extra_documents={'supplemental.json': {'rejected': [100]}}) + reopened = BoundedSession(first.path) + assert reopened.events == first.events + assert reopened.extra_documents == first.extra_documents + assert second.events != reopened.events + # The winning session can commit again without reopening. + first.record_label('group', [100], 'mua') + first.save() + assert BoundedSession(first.path).metadata['group'][100] == 'mua' + + +def test_failed_save_releases_commit_lock(tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + _, session = make_session(tmp_path) + session.save() + other = BoundedSession(session.path) + original = curation._write_json + + def fail(path, value): + if path.name == 'journal.json': + raise OSError('injected locked save failure') + return original(path, value) + + with monkeypatch.context() as patch: + patch.setattr(curation, '_write_json', fail) + with pytest.raises(OSError, match='locked'): + session.save() + other.record_label('group', [0], 'mua') + other.save() + assert BoundedSession(session.path).metadata['group'][0] == 'mua' + + +def _concurrent_save_worker(path, barrier, results, label): + session = BoundedSession(path) + try: + session.record_label('group', [0], label) + barrier.wait(timeout=20) + try: + session.save() + except ValueError as error: + results.put(('conflict', str(error))) + else: + results.put(('saved', label)) + finally: + session.close() + + +def test_concurrent_process_saves_compare_generation_under_lock(tmp_path): + import multiprocessing + + _, session = make_session(tmp_path) + session.save() + context = multiprocessing.get_context('spawn') + barrier = context.Barrier(2) + results = context.Queue() + processes = [ + context.Process( + target=_concurrent_save_worker, + args=(str(session.path), barrier, results, label), + ) + for label in ('good', 'noise') + ] + for process in processes: + process.start() + try: + outcomes = [results.get(timeout=30) for _ in processes] + for process in processes: + process.join(timeout=10) + assert process.exitcode == 0 + assert sorted(status for status, _ in outcomes) == ['conflict', 'saved'] + winner = next(value for status, value in outcomes if status == 'saved') + assert 'reopen' in next(value for status, value in outcomes if status == 'conflict') + assert BoundedSession(session.path).metadata['group'][0] == winner + finally: + for process in processes: + if process.is_alive(): + process.terminate() + process.join(timeout=5) + results.close() + + +def _replace_capabilities(session, capabilities): + session.close() + path = session.path / '_phy_curation_manifest.json' + manifest = json.loads(path.read_text()) + if capabilities is None: + manifest.pop('capabilities', None) + else: + manifest['capabilities'] = capabilities + path.write_text(json.dumps(manifest)) + return BoundedSession(session.path) + + +@pytest.mark.parametrize( + 'capabilities', [None, {}, {'merge': False, 'label': False, 'split': False}] +) +def test_readonly_capabilities_reject_public_mutations_without_state_changes( + tmp_path, capabilities +): + _, session = make_session(tmp_path) + session = _replace_capabilities(session, capabilities) + before = session.snapshot() + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 15.0, + 'nonfinite': 'keep', + } + commands = [ + lambda: session.preflight_merge([0, 1], 100), + lambda: session.record_merge([0, 1], 100), + lambda: session.preflight_label('group', [0], 'good'), + lambda: session.record_label('group', [0], 'good'), + lambda: session.preflight_split(2, 100, 101, predicate), + lambda: session.record_split(2, 100, 101, predicate), + lambda: session.record_threshold_split(2, [101, 100], predicate), + ] + for command in commands: + with pytest.raises(ValueError, match='capability'): + command() + assert session.events == before['events'] + assert session.metadata == before['metadata'] + assert session.next_cluster_id == before['next_cluster_id'] + assert np.array_equal(session.assignments, before['assignments']) + + +@pytest.mark.parametrize( + 'capabilities', + [ + {'merge': 'true'}, + {'label': 'false'}, + {'stored_waveforms': 1}, + {'raw_traces': None}, + {'split': True}, + {'predicate_split_attributes': 'amplitudes.npy'}, + {'predicate_split_attributes': ['amplitudes.npy', 'amplitudes.npy']}, + {'predicate_split_attributes': ['spike_templates.npy']}, + {'predicate_split_attributes': ['waveform_peak']}, + {'predicate_split_attributes': [True]}, + {'full_attributes': 'amplitude'}, + ], +) +def test_malformed_or_unsupported_capabilities_fail_validation(tmp_path, capabilities): + _, session = make_session(tmp_path) + with pytest.raises(ValueError, match='capability|capabilities|unsupported|Unsupported'): + _replace_capabilities(session, capabilities) + + +def test_predicate_capability_requires_an_available_scalar_source_attribute(tmp_path): + _, session = make_session(tmp_path) + session.close() + values = np.load(session.path / 'amplitudes.npy') + np.save(session.path / 'amplitudes.npy', np.column_stack([values, values])) + with pytest.raises(ValueError, match='source scalar'): + BoundedSession(session.path) diff --git a/phy/apps/large_recording/tests/test_curation_comparison.py b/phy/apps/large_recording/tests/test_curation_comparison.py new file mode 100644 index 000000000..e6914ad8c --- /dev/null +++ b/phy/apps/large_recording/tests/test_curation_comparison.py @@ -0,0 +1,307 @@ +"""Independent full ordinary Supervisor versus bounded journal/replay acceptance.""" + +import subprocess +from pathlib import Path + +import numpy as np +import pytest + +import tools.compare_curation_modes as comparison +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.tests.test_source import make_sorting + + +@pytest.mark.parametrize('other_repository', [False, True]) +def test_revision_uses_script_checkout_from_any_cwd(tmp_path, monkeypatch, other_repository): + root = Path(comparison.__file__).resolve().parents[1] + expected = subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip() + if other_repository: + subprocess.run(['git', 'init', '--quiet', str(tmp_path)], check=True) + monkeypatch.chdir(tmp_path) + left, right = outputs(tmp_path, [0, 1], [8, 9]) + result = comparison.compare_outputs(left, right) + assert result['ok'], result + assert result['revision'] == expected + + +def test_revision_without_git_is_unknown(monkeypatch): + monkeypatch.setenv('PATH', '') + assert comparison.revision() == 'unknown' + + +@pytest.mark.parametrize('enclosing_repository', [False, True]) +def test_revision_without_checkout_metadata_is_unknown( + tmp_path, monkeypatch, enclosing_repository +): + if enclosing_repository: + subprocess.run(['git', 'init', '--quiet', str(tmp_path)], check=True) + subprocess.run( + [ + 'git', + '-C', + str(tmp_path), + '-c', + 'user.name=Test', + '-c', + 'user.email=test@example.invalid', + 'commit', + '--quiet', + '--allow-empty', + '-m', + 'Unrelated enclosing repository', + ], + check=True, + ) + archive = tmp_path / 'archive' + (archive / 'tools').mkdir(parents=True) + monkeypatch.setattr( + comparison, '__file__', str(archive / 'tools' / 'compare_curation_modes.py') + ) + assert comparison.revision() == 'unknown' + + +def ledger(): + return { + 'aliases': {'a': 0, 'b': 1, 'c': 99}, + 'fields': ['group', 'notes'], + 'actions': [ + {'op': 'merge', 'parents': ['a', 'b'], 'as': 'ab'}, + {'op': 'undo'}, + {'op': 'redo'}, + { + 'op': 'split', + 'parent': 'ab', + 'threshold': 4.0, + 'selected': 'low', + 'remainder': 'rest', + }, + {'op': 'label', 'ids': ['low'], 'field': 'group', 'value': 'good'}, + {'op': 'label', 'ids': ['rest'], 'field': 'group', 'value': 'noise'}, + {'op': 'label', 'ids': ['low'], 'field': 'notes', 'value': 'finite below 4'}, + {'op': 'label', 'ids': ['rest'], 'field': 'notes', 'value': 'equal/nonfinite'}, + {'op': 'undo'}, + {'op': 'redo'}, + {'op': 'save'}, + {'op': 'reopen'}, + {'op': 'save'}, + ], + 'expected_labels': { + 'low': {'group': 'good', 'notes': 'finite below 4'}, + 'rest': {'group': 'noise', 'notes': 'equal/nonfinite'}, + }, + } + + +@pytest.mark.parametrize('budget,seed', [(5, 0), (9, 11)]) +def test_ordinary_supervisor_against_bounded_all_rows(tmp_path, budget, seed): + params = make_sorting(tmp_path / 'source') + values = np.load(params.parent / 'amplitudes.npy') + values[:5] = [np.nan, np.inf, -np.inf, 4, 3] + np.save(params.parent / 'amplitudes.npy', values) + bounded = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=budget, + seed=seed, + window_seconds=3, + stratum_seconds=20, + batch_size=2, + ) + ordinary = tmp_path / 'ordinary' + comparison.run_reference(params.parent, ledger(), ordinary) + session = BoundedSession(bounded) + before = session.journal_state() + merged = session.next_cluster_id + session.record_merge([0, 1], merged) + after = session.journal_state() + session.restore_journal(before) + session.restore_journal(after) + low, rest = session.next_cluster_id, session.next_cluster_id + 1 + session.record_threshold_split( + merged, + [rest, low], + {'attribute': 'amplitudes.npy', 'operator': '<', 'threshold': 4.0, 'nonfinite': 'keep'}, + ) + for alias, unit in [('low', low), ('rest', rest)]: + for field, value in ledger()['expected_labels'][alias].items(): + session.record_label(field, [unit], value) + session.save() + session.close() + reopened = BoundedSession(bounded) + reopened.save() + reopened.close() + replay = tmp_path / 'replay' + apply_curation(params, bounded, replay, batch_size=2) + result = comparison.compare_outputs(ordinary, replay, chunk_size=2) + assert result['ok'], result + assert result['rows'] == len(np.load(params.parent / 'spike_clusters.npy')) + streamed = tmp_path / 'streamed' + report = comparison.run_reference( + params.parent, ledger(), streamed, engine='streamed', chunk_size=2 + ) + assert report['evidence'] == 'streamed reference, NOT full ordinary GUI' + assert comparison.compare_outputs(ordinary, streamed, chunk_size=3)['ok'] + + +def outputs(tmp_path, left, right): + paths = [tmp_path / 'left', tmp_path / 'right'] + for path, ids in zip(paths, (left, right), strict=True): + path.mkdir() + np.save(path / 'spike_clusters.npy', np.asarray(ids)) + np.save(path / 'spike_times.npy', np.arange(len(ids), dtype=np.int64)) + return paths + + +def test_exact_mapping_detects_conflict_across_chunks(tmp_path): + left, right = outputs(tmp_path, [0, 1, 0, 1], [8, 9, 8, 8]) + report = comparison.compare_outputs(left, right, chunk_size=1) + assert not report['ok'] + assert report['partition_mismatch_rows'] == 1 + assert report['examples'][0]['row'] == 3 + + +def test_semantic_labels_follow_permuted_ids(tmp_path): + left, right = outputs(tmp_path, [0, 1, 0], [100, 200, 100]) + comparison.write_labels(left, {'group': {0: 'good', 1: 'noise'}}) + comparison.write_labels(right, {'group': {100: 'good', 200: 'noise'}}) + assert comparison.compare_outputs(left, right)['ok'] + comparison.write_labels(right, {'group': {100: 'noise', 200: 'good'}}) + assert len(comparison.compare_outputs(left, right)['manual_label_mismatches']) == 2 + + +@pytest.mark.parametrize('bad', ['rows', 'nan', 'times', 'shape']) +def test_invalid_outputs_fail_as_json_data(tmp_path, bad): + left, right = outputs(tmp_path, [0, 1], [8, 9]) + if bad == 'rows': + np.save(right / 'spike_clusters.npy', np.array([8])) + elif bad == 'nan': + np.save(right / 'spike_clusters.npy', np.array([8.0, np.nan])) + elif bad == 'times': + np.save(right / 'spike_times.npy', np.array([1, 0])) + else: + np.save(right / 'spike_clusters.npy', np.zeros((2, 2), dtype=int)) + result = comparison.compare_outputs(left, right) + assert not result['ok'] and result['error'] + + +def test_unmapped_zero_spike_label_units_require_explicit_review(tmp_path): + left, right = outputs(tmp_path, [0, 1], [8, 9]) + comparison.write_labels(left, {'group': {0: 'good', 1: 'noise', 99: 'mua'}}) + comparison.write_labels(right, {'group': {8: 'good', 9: 'noise', 100: 'mua'}}) + result = comparison.compare_outputs(left, right) + assert not result['ok'] + assert result['unmapped_label_ids']['left']['group'] == [99] + + +def test_csv_multiple_manual_fields_and_generated_info(tmp_path): + left, right = outputs(tmp_path, [0, 1], [8, 9]) + (left / 'cluster_manual.csv').write_text('cluster_id,group,notes\n0,good,yes\n1,noise,no\n') + (left / 'cluster_info.tsv').write_text('cluster_id\tgroup\n0\twrong\n') + comparison.write_labels( + right, {'group': {8: 'good', 9: 'noise'}, 'notes': {8: 'yes', 9: 'no'}} + ) + assert comparison.compare_outputs(left, right)['ok'] + + +def test_reference_handles_column_clusters(tmp_path): + params = make_sorting(tmp_path / 'source', columns=True) + comparison.run_reference(params.parent, ledger(), tmp_path / 'ordinary') + comparison.run_reference( + params.parent, ledger(), tmp_path / 'streamed', engine='streamed', chunk_size=2 + ) + assert comparison.compare_outputs(tmp_path / 'ordinary', tmp_path / 'streamed')['ok'] + + +@pytest.mark.parametrize('fail', [False, True]) +def test_reference_releases_supervisor_callbacks_and_states(tmp_path, monkeypatch, fail): + import gc + import weakref + + from phylib.utils.event import _EVENT + + from phy.cluster.supervisor import Supervisor + + params = make_sorting(tmp_path / 'source') + before = {id(item) for item in _EVENT._callbacks} + refs = [] + original = Supervisor.__init__ + + def track(self, *args, **kwargs): + original(self, *args, **kwargs) + refs.append(weakref.ref(self)) + + monkeypatch.setattr(Supervisor, '__init__', track) + actions = [{'op': 'reopen'}, {'op': 'reopen'}] + if fail: + actions.append({'op': 'label', 'ids': ['missing'], 'field': 'group', 'value': 'good'}) + definition = {'aliases': {'a': 0}, 'fields': ['group'], 'actions': actions} + if fail: + with pytest.raises(KeyError): + comparison.run_reference(params.parent, definition, tmp_path / 'reference') + else: + comparison.run_reference(params.parent, definition, tmp_path / 'reference') + gc.collect() + assert len(refs) == 3 + assert all(ref() is None for ref in refs) + assert {id(item) for item in _EVENT._callbacks} == before + + +@pytest.mark.parametrize('inside', [True, False]) +def test_compare_cli_cannot_overwrite_input_or_existing_report(tmp_path, monkeypatch, inside): + import sys + + left, right = outputs(tmp_path, [0, 1], [8, 9]) + target = left / 'spike_clusters.npy' if inside else tmp_path / 'existing.json' + if not inside: + target.write_text('preserve this report') + before = target.read_bytes() + monkeypatch.setattr( + sys, + 'argv', + ['compare_curation_modes', 'compare', str(left), str(right), '--output', str(target)], + ) + assert comparison.main() == 1 + assert target.read_bytes() == before + + +@pytest.mark.parametrize('threshold', [-100.0, 100.0]) +def test_streamed_empty_split_rejected_and_snapshots_closed(tmp_path, threshold): + params = make_sorting(tmp_path / 'source') + definition = { + 'aliases': {'a': 0}, + 'actions': [ + { + 'op': 'split', + 'parent': 'a', + 'threshold': threshold, + 'selected': 'low', + 'remainder': 'rest', + } + ], + } + with pytest.raises(ValueError, match='both selected and remainder'): + comparison.run_reference( + params.parent, definition, tmp_path / 'reference', engine='streamed', chunk_size=2 + ) + assert not list((tmp_path / 'reference').glob('.history-*.npy')) + + +def test_streamed_allocator_and_inactive_aliases_after_undo(tmp_path): + params = make_sorting(tmp_path / 'source') + actions = [ + {'op': 'merge', 'parents': ['a', 'b'], 'as': 'first'}, + {'op': 'undo'}, + {'op': 'merge', 'parents': ['a', 'b'], 'as': 'second'}, + ] + definition = {'aliases': {'a': 0, 'b': 1}, 'actions': actions} + report = comparison.run_reference( + params.parent, definition, tmp_path / 'reference', engine='streamed', chunk_size=2 + ) + assert report['aliases']['second'] > report['aliases']['first'] + actions.append({'op': 'label', 'ids': ['first'], 'field': 'group', 'value': 'good'}) + with pytest.raises(ValueError, match='active units'): + comparison.run_reference( + params.parent, definition, tmp_path / 'invalid', engine='streamed', chunk_size=2 + ) diff --git a/phy/apps/large_recording/tests/test_elapsed_workflow.py b/phy/apps/large_recording/tests/test_elapsed_workflow.py new file mode 100644 index 000000000..aeba29650 --- /dev/null +++ b/phy/apps/large_recording/tests/test_elapsed_workflow.py @@ -0,0 +1,82 @@ +"""Independent discontinuous-clock preparation and replay oracle.""" + +import json +from contextlib import closing + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import Source, hash_file +from phy.apps.large_recording.tests.test_source import make_sorting + + +def test_elapsed_producer_evidence_replay_and_exposure(tmp_path): + params = make_sorting(tmp_path / 'source') + contract = {'kind': 'elapsed_ticks', 'ticks_per_second': 1.0} + intervals = [[0, 7], [10, 20]] + params.write_text( + params.read_text() + f'time_base = {contract!r}\nvalid_intervals = {intervals!r}\n' + ) + source_path = params.parent + samples = np.load(source_path / 'spike_times.npy') + labels = np.load(source_path / 'spike_clusters.npy') + waveform_ids = np.load(source_path / '_phy_spikes_subset.spikes.npy') + np.save(source_path / '_phy_spikes_subset.sample_index.npy', samples[waveform_ids]) + np.save(source_path / '_phy_spikes_subset.window_bounds.npy', np.array(intervals, 'int64')) + (source_path / 'timestamps.json').write_text('{"provenance": "producer-owned clock"}\n') + (source_path / '_phy_spikes_subset.manifest.json').write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': { + 'time_base': contract, + 'window_bounds_coordinates': 'elapsed_ticks', + 'sample_index_coordinates': 'elapsed_ticks', + }, + } + ) + ) + original = {p.name: hash_file(p) for p in source_path.iterdir() if p.is_file()} + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=5) + manifest = json.loads((bounded / '_phy_curation_manifest.json').read_text()) + assert manifest['time_base'] == contract + assert manifest['selection']['resolved_window_policy'] == 'producer' + np.testing.assert_array_equal(np.load(bounded / '_phy_spike_global_ids.npy'), np.arange(12)) + np.testing.assert_array_equal( + np.load(bounded / '_phy_spikes_subset.sample_index.npy'), samples[waveform_ids] + ) + # Independent exposure oracle, including the partial bin before the gap. + np.testing.assert_array_equal(np.load(bounded / manifest['exposure_file']), [5, 2, 5, 5]) + counts = np.load(bounded / manifest['counts_file']) + for row, unit in enumerate(manifest['unit_ids']): + expected, _ = np.histogram(samples[labels == unit], bins=[0, 5, 10, 15, 20]) + np.testing.assert_array_equal(counts[row], expected) + with closing(BoundedSession(bounded)) as session: + session.record_merge([0, 1], 100) + session.save() + with closing(BoundedSession(bounded)) as reopened: + np.testing.assert_array_equal(reopened.assignments, np.where(labels < 2, 100, labels)) + output = apply_curation(params, bounded, tmp_path / 'curated') + np.testing.assert_array_equal( + np.load(output / 'spike_clusters.npy'), np.where(labels < 2, 100, labels) + ) + assert (output / 'timestamps.json').read_bytes() == ( + source_path / 'timestamps.json' + ).read_bytes() + with Source(params) as source, Source(output / 'params.py') as curated: + assert source.identity == curated.identity + again = prepare_large(output / 'params.py', tmp_path / 'again', bin_seconds=5) + with closing(BoundedSession(again)) as session: + assert session.manifest['time_base'] == contract + assert original == {p.name: hash_file(p) for p in source_path.iterdir() if p.is_file()} + # A metadata edit cannot change the coordinate interpretation of saved evidence. + path = again / '_phy_curation_manifest.json' + altered = json.loads(path.read_text()) + altered['time_base']['kind'] = 'acquisition_samples' + path.write_text(json.dumps(altered)) + with pytest.raises(ValueError, match='time base'): + BoundedSession(again) diff --git a/phy/apps/large_recording/tests/test_export_validator.py b/phy/apps/large_recording/tests/test_export_validator.py new file mode 100644 index 000000000..dc4808ee3 --- /dev/null +++ b/phy/apps/large_recording/tests/test_export_validator.py @@ -0,0 +1,207 @@ +"""Focused contract and report tests for the AIND export validator.""" + +import json + +import tools.validate_aind_export as validator +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.tests.test_source import make_sorting +from tools.validate_aind_export import main, validate_export + + +def test_validator_reports_engineering_evidence_and_input_hashes(tmp_path): + params = make_sorting(tmp_path / 'source') + params.write_text( + params.read_text() + + "time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': 1.0}\n" + + 'valid_intervals = [[0, 20]]\n' + ) + report = validate_export( + params, + phy_revision='phy-test-revision', + exporter_revision='exporter-test-revision', + batch_size=4, + ) + + assert report['status'] == 'passed' + assert report['failures'] == [] + assert report['engineering_validation_only'] is True + assert report['acquisition_truth_established'] is False + assert report['source']['num_spikes'] == 12 + assert report['source']['num_samples'] == 20 + assert report['source']['exposure']['valid_samples'] == 20 + assert report['source']['input_files']['spike_times.npy']['sha256'] + assert report['phy_revision'] == 'phy-test-revision' + assert report['exporter_revision'] == 'exporter-test-revision' + assert report['timing_seconds']['total'] >= 0 + + +def test_validator_preparation_report_matches_manifest_and_preserves_source(tmp_path): + params = make_sorting(tmp_path / 'source') + params.write_text( + params.read_text().replace('num_samples = 20', 'num_samples = 120') + + "time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': 1.0}\n" + + 'valid_intervals = [[0, 120]]\n' + ) + source_path = params.parent + before_hashes = { + path.name: hash_file(path) for path in source_path.iterdir() if path.is_file() + } + output_dir = tmp_path / 'bounded' + + report = validate_export( + params, + phy_revision='phy-test-revision', + exporter_revision='exporter-test-revision', + output_dir=output_dir, + batch_size=4, + ) + + assert report['status'] == 'passed', report['failures'] + output = report['prepared_output'] + manifest = json.loads((output_dir / '_phy_curation_manifest.json').read_text()) + disk_bytes = sum(path.stat().st_size for path in output_dir.rglob('*') if path.is_file()) + assert output['num_spikes'] == manifest['bounded_num_spikes'] + assert output['num_units'] == len(manifest['unit_ids']) + assert output['waveform_coverage'] == manifest['waveform_coverage'] + assert output['budgets'] == manifest['budgets'] + assert output['output_bytes'] == disk_bytes + assert report['source']['input_files'] == { + name: {'bytes': (source_path / name).stat().st_size, 'sha256': digest} + for name, digest in before_hashes.items() + } + assert { + path.name: hash_file(path) for path in source_path.iterdir() if path.is_file() + } == before_hashes + + +def test_validator_reports_source_rejection_as_json_failure(tmp_path): + params = make_sorting(tmp_path / 'source') + (params.parent / 'timestamps.json').write_text(json.dumps({'frames': []})) + + report = validate_export( + params, + phy_revision='phy-test-revision', + exporter_revision='exporter-test-revision', + ) + + assert report['status'] == 'failed' + assert len(report['failures']) == 1 + assert 'explicit time_base' in report['failures'][0]['message'] + assert report['acquisition_truth_established'] is False + + +def test_validator_requires_explicit_aind_time_and_exposure_contract(tmp_path): + params = make_sorting(tmp_path / 'source') + + report = validate_export( + params, + phy_revision='phy-test-revision', + exporter_revision='exporter-test-revision', + ) + + assert report['status'] == 'failed' + assert ( + report['failures'][0]['message'] == 'AIND export requires an explicit time_base contract.' + ) + + +def test_validator_rejects_nested_preparation_destination(tmp_path): + params = make_sorting(tmp_path / 'source') + params.write_text( + params.read_text() + + "time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': 1.0}\n" + + 'valid_intervals = [[0, 20]]\n' + ) + + report = validate_export( + params, + phy_revision='phy-test-revision', + exporter_revision='exporter-test-revision', + output_dir=params.parent / 'derived', + ) + + assert report['status'] == 'failed' + assert 'outside the immutable source' in report['failures'][0]['message'] + assert not (params.parent / 'derived').exists() + + +def test_cli_report_cannot_overwrite_source_params(tmp_path, capsys): + params = make_sorting(tmp_path / 'source') + original = params.read_bytes() + + result = main( + [ + str(params), + '--phy-revision', + 'phy-test-revision', + '--exporter-revision', + 'exporter-test-revision', + '--report', + str(params), + ] + ) + + assert result == 1 + assert params.read_bytes() == original + report = json.loads(capsys.readouterr().out) + assert report['status'] == 'failed' + assert 'outside the immutable source' in report['failures'][0]['message'] + + +def test_cli_report_cannot_target_future_prepared_output(tmp_path, capsys): + params = make_sorting(tmp_path / 'source') + params.write_text( + params.read_text() + + "time_base = {'kind': 'elapsed_ticks', 'ticks_per_second': 1.0}\n" + + 'valid_intervals = [[0, 20]]\n' + ) + output_dir = tmp_path / 'prepared' + report_path = output_dir / 'params.py' + + result = main( + [ + str(params), + '--phy-revision', + 'phy-test-revision', + '--exporter-revision', + 'exporter-test-revision', + '--output-dir', + str(output_dir), + '--report', + str(report_path), + ] + ) + + assert result == 1 + assert not output_dir.exists() + report = json.loads(capsys.readouterr().out) + assert report['status'] == 'failed' + assert 'prepared output directories' in report['failures'][0]['message'] + + +def test_cli_report_exclusive_create_preserves_racing_file(tmp_path, monkeypatch, capsys): + params = make_sorting(tmp_path / 'source') + report_path = tmp_path / 'report.json' + + def create_report_during_validation(*args, **kwargs): + report_path.write_text('keep me', encoding='utf-8') + return {'status': 'passed'} + + monkeypatch.setattr(validator, 'validate_export', create_report_during_validation) + result = main( + [ + str(params), + '--phy-revision', + 'phy-test-revision', + '--exporter-revision', + 'exporter-test-revision', + '--report', + str(report_path), + ] + ) + + assert result == 1 + assert report_path.read_text(encoding='utf-8') == 'keep me' + report = json.loads(capsys.readouterr().out) + assert report['status'] == 'failed' + assert 'already exists' in report['failures'][0]['message'] diff --git a/phy/apps/large_recording/tests/test_graphical_split.py b/phy/apps/large_recording/tests/test_graphical_split.py new file mode 100644 index 000000000..88fac0809 --- /dev/null +++ b/phy/apps/large_recording/tests/test_graphical_split.py @@ -0,0 +1,380 @@ +"""Graphical threshold previews commit full-source semantic commands.""" + +import numpy as np +import pytest +from phylib.utils import connect, emit, unconnect + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.tests.test_adapter import make_controller, make_gui_sorting +from phy.apps.template.gui import TemplateController +from phy.gui.qt import Qt +from phy.plot.tests import mouse_click, mouse_drag +from phy.plot.transform import NDC, Range + + +def drag_threshold(qtbot, view, threshold): + qtbot.wait(50) + width, height = view.canvas.get_size() + ndc = Range(view.data_bounds, NDC).apply([[0, threshold]])[0] + screen = (ndc + np.asarray(view.canvas.panzoom.pan)) * view.canvas.panzoom._zoom_aspect() + pixel = ((screen[0] + 1) * width / 2, (1 - screen[1]) * height / 2) + mouse_drag( + qtbot, view.canvas, (pixel[0] - 10, pixel[1]), pixel, button='right', modifiers=('Alt',) + ) + assert view.split_threshold == pytest.approx(threshold, abs=0.03) + + +def test_drag_k_semantic_commit_waveform_preview_history_save_replay(qtbot, tmp_path): + params, controller = make_controller(tmp_path) + gui = controller.create_gui( + default_views=['EvidenceAmplitudeView', 'WaveformView'], do_prompt_save=False + ) + supervisor = controller.supervisor + requests = [] + + @connect(event='request_split', sender=supervisor) + def on_request(sender): + requests.append(True) + return np.array([0], dtype=np.int64) + + try: + gui.show() + supervisor.select([0]) + supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + waveform = gui.get_view('WaveformView') + waveform.waveforms_type = 'waveforms' + waveform.plot() + drag_threshold(qtbot, view, 4.5) + threshold = view.split_threshold + drawn = waveform._displayed_bunchs[0].spike_ids + amplitudes = controller.bounded_session.attributes['amplitudes.npy'] + np.testing.assert_array_equal( + waveform._highlighted_spike_ids, drawn[amplitudes[drawn] < threshold] + ) + assert waveform._highlighted_spike_color == view.split_preview_color + assert supervisor.actions.get('split').isEnabled() + assert view.on_request_split(supervisor).size == 0 + before = supervisor.clustering.spike_clusters.copy() + view.canvas.setFocus() + qtbot.keyClick(view.canvas, Qt.Key_K) + supervisor.block() + assert not requests + assert controller.bounded_session.events[-1]['operation'] == 'threshold_split' + predicate = controller.bounded_session.events[-1]['predicate'] + assert predicate['threshold'] == threshold + after = supervisor.clustering.spike_clusters.copy() + assert view.split_threshold is None + assert not supervisor.actions.get('split').isEnabled() + supervisor.undo() + supervisor.block() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + supervisor.redo() + supervisor.block() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, after) + supervisor.save() + bounded = controller.dir_path + finally: + unconnect(on_request) + gui.close() + controller.close() + + reopened = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + try: + np.testing.assert_array_equal(reopened.supervisor.clustering.spike_clusters, after) + result = apply_curation(params, bounded, tmp_path / 'replay', batch_size=2) + source = np.load(params.parent / 'spike_clusters.npy') + values = np.load(params.parent / 'amplitudes.npy') + children = reopened.bounded_session.events[-1]['children'] + expected = source.copy() + expected[(source == 0) & (values < threshold)] = children[1] + expected[(source == 0) & ~(values < threshold)] = children[0] + np.testing.assert_array_equal(np.load(result / 'spike_clusters.npy'), expected) + finally: + reopened.close() + + +def test_overview_original_clock_all_windows_budget_and_window_toggle(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'source') + bounded = prepare_large( + params, tmp_path / 'bounded', window_seconds=3, stratum_seconds=5, bin_seconds=5 + ) + controller = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + try: + gui.show() + controller.supervisor.select([0]) + controller.supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + assert view.amplitude_scope == 'overview' + data = view.get_clusters_data(load_all=True)[0] + assert len(data.spike_ids) > len(controller._window_ids(0)) + np.testing.assert_allclose( + data.spike_times, controller.model.spike_samples[data.spike_ids] / 30000 + ) + controller.n_spikes_amplitudes = 2 + controller.n_spikes_amplitudes_total = 2 + assert len(view.get_clusters_data()[-1].spike_ids) <= 2 + drag_threshold(qtbot, view, 4.5) + controller.inspect_evidence_window(0) + assert view.split_threshold is None + assert view.amplitude_scope == 'window' + local = view.get_clusters_data(load_all=True)[0] + np.testing.assert_array_equal(local.spike_ids, controller._window_ids(0)) + view.toggle_amplitude_scope() + assert view.amplitude_scope == 'overview' + assert view.state['amplitude_scope'] == 'overview' + finally: + gui.close() + controller.close() + + +def test_invalid_preview_and_row_splits_preserve_state(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + supervisor = controller.supervisor + try: + gui.show() + supervisor.select([0]) + supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + drag_threshold(qtbot, view, 4.5) + before = supervisor.clustering.spike_clusters.copy() + with pytest.raises(ValueError, match='cannot be replayed'): + supervisor.split([0]) + assert view.split_threshold is not None + view.split_threshold = -1 + with pytest.raises(ValueError, match='Both sides'): + supervisor.split() + assert view.split_threshold == -1 + supervisor.actions.get('split').trigger() + supervisor.block() + assert view.dock.status == 'Both sides of the threshold must have evidence spikes.' + assert view.split_threshold == -1 + assert supervisor.actions.get('split').isEnabled() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + assert controller.bounded_session.events == [] + view.clear_split_selection() + view.canvas.lasso.add((-0.5, -0.5)) + view.canvas.lasso.add((0.5, -0.5)) + view.canvas.lasso.add((0, 0.5)) + assert view.on_request_split(supervisor).size == 0 + with pytest.raises(ValueError, match='Exactly one'): + supervisor.split() + assert not supervisor.actions.get('split').isEnabled() + finally: + gui.close() + controller.close() + + +def test_preview_invalidated_by_context_and_hidden_dock(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui( + default_views=['EvidenceAmplitudeView', 'WaveformView'], do_prompt_save=False + ) + supervisor = controller.supervisor + try: + gui.show() + supervisor.select([0]) + supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + waveform = gui.get_view('WaveformView') + drag_threshold(qtbot, view, 4.5) + waveform.plot() + assert view.split_threshold is None + for event in ('selected_channel_changed', 'selected_feature_changed'): + drag_threshold(qtbot, view, 4.5) + emit(event, waveform) + assert view.split_threshold is None + assert not len(waveform._highlighted_spike_ids) + drag_threshold(qtbot, view, 4.5) + waveform.next_waveforms_type() + assert view.split_threshold is None + waveform.waveforms_type = 'waveforms' + waveform.plot() + assert not len(waveform._highlighted_spike_ids) + drag_threshold(qtbot, view, 4.5) + mouse_click(qtbot, view.canvas, (20, 20), button='right', modifiers=('Control',)) + assert view.split_threshold is None + drag_threshold(qtbot, view, 4.5) + view.actions.get('clear_amplitude_split_threshold').trigger() + assert view.split_threshold is None + drag_threshold(qtbot, view, 4.5) + view.dock.hide() + assert view.split_threshold is None + assert not supervisor.actions.get('split').isEnabled() + view.dock.show() + drag_threshold(qtbot, view, 4.5) + supervisor.select([0, 1]) + supervisor.block() + assert view.split_threshold is None + assert not view._can_set_split_threshold() + supervisor.select([0]) + supervisor.block() + drag_threshold(qtbot, view, 4.5) + supervisor.toggle_merge_mode() + supervisor.block() + assert view.split_threshold is None + assert not view._can_set_split_threshold() + finally: + gui.close() + controller.close() + + +def test_commit_scope_other_gui_ambiguous_and_closed_previews(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + supervisor = controller.supervisor + other = None + try: + gui.show() + supervisor.select([0]) + supervisor.block() + first = gui.get_view('EvidenceAmplitudeView') + second = gui.create_and_add_view('EvidenceAmplitudeView') + supervisor.select([0]) + supervisor.block() + # Simulate contradictory preview state without the exclusive activation + # event, as a plugin or restored stale callback could create it. + first.split_threshold = 3 + second.split_threshold = 4 + with pytest.raises(ValueError, match='Exactly one'): + supervisor.split() + second.clear_split_selection() + # A foreign view answering the global legacy event cannot intercept K. + other = controller.create_evidence_amplitude_view() + other.on_select([0]) + other.split_threshold = 6 + other.gui = object() + foreign_requests = [] + + @connect(event='request_split') + def foreign_request(sender): + foreign_requests.append(True) + return np.array([1], dtype=np.int64) + + try: + supervisor.split() + supervisor.block() + assert not foreign_requests + assert controller.bounded_session.events[-1]['predicate']['threshold'] == 3 + finally: + unconnect(foreign_request) + supervisor.undo() + supervisor.block() + supervisor.select([0]) + supervisor.block() + drag_threshold(qtbot, first, 4.5) + # Closing the originating dock invalidates its pending predicate. + first.close() + assert first.split_threshold is None + with pytest.raises(ValueError, match='Exactly one'): + supervisor.split() + finally: + if other is not None: + other.canvas.close() + gui.close() + controller.close() + + +def test_failed_semantic_observer_preserves_preview_and_assignments(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + supervisor = controller.supervisor + try: + gui.show() + supervisor.select([0]) + supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + drag_threshold(qtbot, view, 4.5) + threshold = view.split_threshold + before = supervisor.clustering.spike_clusters.copy() + + @connect(event='cluster', sender=supervisor.clustering) + def fail(sender, up): + raise RuntimeError('observer failed') + + try: + with pytest.raises(RuntimeError, match='observer failed'): + supervisor.split() + supervisor.block() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + assert controller.bounded_session.events == [] + assert supervisor.selected == [0] + assert view.split_threshold == threshold + assert supervisor.actions.get('split').isEnabled() + finally: + unconnect(fail) + finally: + gui.close() + controller.close() + + +def test_pending_reference_selection_invalidates_old_split_preview(qtbot, tmp_path): + from timeit import default_timer + + _, controller = make_controller(tmp_path) + gui = controller.create_gui( + view_count={'EvidenceAmplitudeView': 1}, + default_views=['EvidenceAmplitudeView'], + do_prompt_save=False, + ) + supervisor = controller.supervisor + try: + gui.show() + supervisor.select([0]) + supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + drag_threshold(qtbot, view, 4.5) + assert supervisor._graphical_split_views() == [view] + assignments = supervisor.clustering.spike_clusters.copy() + supervisor.cluster_view.debouncer.delay = 60_000 + supervisor.cluster_view.debouncer._last_submission_time = default_timer() + supervisor.cluster_view.select([1]) + assert supervisor.selected == [0] + assert supervisor.cluster_view.get_selected_ids() == [1] + + with pytest.raises(ValueError, match='threshold preview'): + supervisor.split() + assert supervisor.selected == [1] + assert view.split_threshold is None + assert not controller.bounded_session.events + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, assignments) + finally: + gui.close() + controller.close() + + +@pytest.mark.parametrize('scope', ['overview', 'window']) +def test_evidence_amplitude_fits_selected_points_without_expanding_budget(qtbot, tmp_path, scope): + params = make_gui_sorting(tmp_path / 'source') + clusters = np.load(params.parent / 'spike_clusters.npy') + amplitudes = np.full(len(clusters), 1e6, dtype=np.float32) + amplitudes[clusters == 0] = [-1000, -1100, -1050, -1450] + np.save(params.parent / 'amplitudes.npy', amplitudes) + bounded = prepare_large( + params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20, bin_seconds=5 + ) + controller = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + try: + gui.show() + controller.supervisor.select([0]) + controller.supervisor.block() + view = gui.get_view('EvidenceAmplitudeView') + view.amplitude_scope = scope + assert view.data_bounds[1] < -1450 + assert 0 < view.data_bounds[3] < 1e6 + selected = next(bunch for bunch in view._displayed_bunchs if bunch.cluster_id == 0) + assert selected.amplitudes.min() == -1450 + controller.n_spikes_amplitudes = 2 + controller.n_spikes_amplitudes_total = 2 + view.plot() + selected = next(bunch for bunch in view._displayed_bunchs if bunch.cluster_id == 0) + assert len(selected.spike_ids) <= 2 + assert view.data_bounds[1] < selected.amplitudes.min() + assert view.data_bounds[3] > selected.amplitudes.max() + finally: + gui.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_gui_lifecycle.py b/phy/apps/large_recording/tests/test_gui_lifecycle.py new file mode 100644 index 000000000..ad0a547aa --- /dev/null +++ b/phy/apps/large_recording/tests/test_gui_lifecycle.py @@ -0,0 +1,248 @@ +"""GUI transaction, proposition review, and pending-metric regressions.""" + +import json + +import numpy as np +import pytest +from phylib.utils import connect, unconnect + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.tests.test_adapter import make_controller, make_gui_sorting +from phy.apps.template.gui import TemplateController + + +def test_elapsed_producer_windows_open_and_navigate_in_gui(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'source') + intervals = [[0, 210000], [300000, 600000]] + contract = {'kind': 'elapsed_ticks', 'ticks_per_second': 30000.0} + params.write_text( + params.read_text() + f'time_base = {contract!r}\nvalid_intervals = {intervals!r}\n' + ) + np.save(params.parent / '_phy_spikes_subset.window_bounds.npy', np.array(intervals, 'int64')) + (params.parent / '_phy_spikes_subset.manifest.json').write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': {'window_bounds_coordinates': 'elapsed_ticks'}, + } + ) + ) + output = prepare_large(params, tmp_path / 'bounded', window_policy='producer', bin_seconds=5) + controller = TemplateController( + dir_path=output, config_dir=tmp_path / 'config', plugins=[], enable_threading=False + ) + gui = None + try: + gui = controller.create_gui(do_prompt_save=False) + controller.supervisor.select([0, 1]) + controller.supervisor.block() + controller.inspect_evidence_window(1) + assert controller.model.sample_rate == 30000.0 + assert controller.model.traces is None + assert controller.get_mean_firing_rate(0) == pytest.approx(4 / 17) + view = gui.get_view('EvidenceAmplitudeView') + assert view.duration == 10 + assert view.window_label.text() == ('Evidence window 1 | Recording time: 10.000–20.000 s') + finally: + if gui is not None: + gui.close() + controller.close() + + +def test_window_time_labels_follow_navigation(qtbot, tmp_path): + _, controller = make_controller(tmp_path, sparse=True) + gui = controller.create_gui(default_views=['EvidenceAmplitudeView'], do_prompt_save=False) + try: + view = gui.get_view('EvidenceAmplitudeView') + assert view.time_axis_label.text() == 'Recording time (seconds)' + assert view.amplitude_scope == 'overview' + initial = view.window_label.text() + controller.inspect_evidence_window(1) + start, end = controller.current_evidence_window / controller.model.sample_rate + assert view.window_label.text() == ( + f'Evidence window 1 | Recording time: {start:.3f}–{end:.3f} s' + ) + assert view.window_label.text() != initial + assert view.duration == end - start + finally: + gui.close() + controller.close() + + +def test_gui_observer_mutation_rolls_back_views_selection_and_journal(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + once = [] + + try: + supervisor.select([0]) + supervisor.block() + assignments = supervisor.clustering.spike_clusters.copy() + events = list(controller.bounded_session.events) + selection = supervisor.selection.snapshot() + cluster_ids = supervisor.cluster_view.get_ids() + similarity_ids = supervisor.similarity_view.get_ids() + histories = tuple( + (history._index, len(history._history)) + for history in ( + supervisor.clustering._undo_stack, + supervisor.cluster_meta._undo_stack, + supervisor._global_history, + supervisor.session_history, + ) + ) + dirty = supervisor.is_dirty() + + @connect(event='cluster', sender=supervisor.clustering) + def mutate(sender, up): + if not once: + once.append(True) + sender.assign([0]) + + with pytest.raises((ValueError, KeyError)): + supervisor.merge([0, 1]) + supervisor.block() + + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, assignments) + assert controller.bounded_session.events == events + assert supervisor.selection.snapshot() == selection + assert supervisor.cluster_view.get_ids() == cluster_ids + assert supervisor.similarity_view.get_ids() == similarity_ids + assert ( + tuple( + (history._index, len(history._history)) + for history in ( + supervisor.clustering._undo_stack, + supervisor.cluster_meta._undo_stack, + supervisor._global_history, + supervisor.session_history, + ) + ) + == histories + ) + assert supervisor.is_dirty() == dirty + finally: + if 'mutate' in locals(): + unconnect(mutate) + gui.close() + controller.close() + + +def test_gui_proposition_review_undo_redo_and_checkpoint_reopen(qtbot, tmp_path): + params = make_gui_sorting(tmp_path / 'source') + proposal = { + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}], + } + (params.parent / 'curation.json').write_text(json.dumps(proposal), encoding='utf-8') + bounded = prepare_large( + params, + tmp_path / 'bounded', + window_seconds=20, + stratum_seconds=20, + bin_seconds=5, + batch_size=2, + ) + config = tmp_path / 'config' + controller = TemplateController( + dir_path=bounded, config_dir=config, plugins=[], enable_threading=False + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + proposition = supervisor.merge_propositions.catalog.propositions[0] + key = proposition.key + + try: + supervisor._review_merge_proposition(supervisor.merge_propositions_view, key) + assert supervisor.selection.state.is_merge_mode + assert supervisor.selected_merge == [0, 1] + + merged = supervisor.merge() + supervisor.block() + assert merged.added == [100] + assert supervisor.merge_propositions.catalog.status_for(key).value == 'accepted' + assert controller.bounded_session.events[-1]['target'] == 100 + + supervisor.undo() + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key).value == 'pending' + assert controller.bounded_session.events == [] + + supervisor.redo() + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key).value == 'accepted' + assert controller.bounded_session.events[-1]['target'] == 100 + supervisor.save() + finally: + gui.close() + controller.close() + + reopened = TemplateController( + dir_path=bounded, config_dir=config, plugins=[], enable_threading=False + ) + try: + key = reopened.supervisor.merge_propositions.catalog.propositions[0].key + assert reopened.supervisor.merge_propositions.catalog.status_for(key).value == 'accepted' + assert reopened.bounded_session.events[-1]['target'] == 100 + finally: + reopened.close() + + +def test_default_bounded_views_refresh_threshold_child_metrics(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(do_prompt_save=False) + try: + controller._live_summaries.suspend() + supervisor = controller.supervisor + update = supervisor.split_source_amplitude(0, 4) + supervisor.block() + assert set(update.added) == {100, 101} + for cluster_id in update.added: + row = supervisor.cluster_view._model.row_by_id(cluster_id) + assert row['fr'] is None + assert row['full_count'] is None + assert 'suspended' in row['evidence'] + controller._live_summaries.resume() + qtbot.waitUntil(lambda: all(controller.get_full_count(c) == 2 for c in update.added)) + supervisor.block() + for cluster_id in update.added: + row = supervisor.cluster_view._model.row_by_id(cluster_id) + assert row['full_count'] == 2 + assert row['fr'] == 0.1 + finally: + gui.close() + controller.close() + + +def test_merge_redo_then_amplitude_split_saves_and_reopens(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + bounded = controller.dir_path + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + try: + supervisor.merge([0, 1]) + supervisor.block() + supervisor.undo() + supervisor.block() + supervisor.redo() + supervisor.block() + split = supervisor.split_source_amplitude(2, 6.0) + supervisor.block() + assignments = supervisor.clustering.spike_clusters.copy() + supervisor.save() + children = list(split.added) + finally: + gui.close() + controller.close() + reopened = TemplateController( + dir_path=bounded, config_dir=tmp_path / 'config', plugins=[], enable_threading=False + ) + try: + np.testing.assert_array_equal(reopened.bounded_session.assignments, assignments) + assert set(reopened.bounded_session.events[-1]['children']) == set(children) + assert len(reopened.bounded_session.events) == 2 + finally: + reopened.close() diff --git a/phy/apps/large_recording/tests/test_incremental_curation.py b/phy/apps/large_recording/tests/test_incremental_curation.py new file mode 100644 index 000000000..c66f58d6e --- /dev/null +++ b/phy/apps/large_recording/tests/test_incremental_curation.py @@ -0,0 +1,286 @@ +"""Interactive commands must not replay unrelated historical spike assignments.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.tests.test_curation import make_session + + +def test_label_has_no_assignment_projection(tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + source, session = make_session(tmp_path) + try: + session.record_merge([0, 1], 100, {'group': 'good'}) + assignments = session.assignments + + def forbidden(*args, **kwargs): + pytest.fail('A label projected spike assignments.') + + monkeypatch.setattr(curation, 'project_assignments', forbidden) + event = session.preflight_label('group', [100], 'mua') + assert session.events[-1]['operation'] == 'merge' + session._append(event) + assert session.assignments is assignments + assert session.metadata['group'][100] == 'mua' + with pytest.raises(ValueError, match='inactive'): + session.record_label('group', [0], 'good') + assert session.assignments is assignments + finally: + session.close() + source.close() + + +def test_incremental_events_and_history_match_full_oracle(tmp_path, monkeypatch): + from phy.apps.large_recording import curation + from phy.apps.large_recording.tests.test_restore_parents import _package, _predicate + + _, session = _package(tmp_path) + oracle = curation.project_assignments + interpreter = curation.interpret_events + states = [] + + def one_event(units, metadata, events): + assert len(events) <= 1, 'An interactive command reinterpreted its journal.' + return interpreter(units, metadata, events) + + def forbidden(*args, **kwargs): + pytest.fail('An interactive command replayed its journal.') + + try: + monkeypatch.setattr(curation, 'project_assignments', forbidden) + monkeypatch.setattr(curation, 'interpret_events', one_event) + states.append(session.journal_state()) + commands = [ + lambda: session.record_merge([0, 1], 100), + lambda: session.record_threshold_split(100, [101, 102], _predicate()), + lambda: session.record_merge([102, 2], 103), + lambda: session.record_label('notes', [103], {'checked': True}), + lambda: session.record_restore_parents(103, [104, 105], recursive=True), + ] + assignments = session.assignments + for command in commands: + command() + assert session.assignments is assignments + states.append(session.journal_state()) + expected = oracle(session.base_assignments, session.events, session.attributes) + np.testing.assert_array_equal(session.assignments, expected) + active, metadata, _ = interpreter( + session.unit_ids, session.base_metadata, session.events + ) + assert set(session._runtime.active) == active + assert session.metadata == metadata + for state in [*reversed(states), *states]: + session.restore_journal(state) + expected = oracle(session.base_assignments, session.events, session.attributes) + np.testing.assert_array_equal(session.assignments, expected) + assert session.assignments is assignments + session.restore_journal(states[2]) + token = session.membership_revision + session.record_label('group', [101], 'good') + assert session.membership_revision is token + assert session.next_cluster_id == 106 + session.record_merge([101, 102], 106) + assert session.membership_revision is not token + assert session.next_cluster_id == 107 + expected = oracle(session.base_assignments, session.events, session.attributes) + np.testing.assert_array_equal(session.assignments, expected) + finally: + session.close() + + +def test_history_cache_eviction_replays_and_preserves_allocator(tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + source, session = make_session(tmp_path) + try: + session.history_cache_bytes = 0 + before = session.journal_state() + session.record_merge([0, 1], 100, {'group': 'good'}) + after = session.journal_state() + assert not session._transitions and session._transition_bytes == 0 + calls = [] + original = curation.project_assignments + + def measured(*args, **kwargs): + calls.append(True) + return original(*args, **kwargs) + + monkeypatch.setattr(curation, 'project_assignments', measured) + session.restore_journal(before) + assert calls and session.next_cluster_id == 101 + np.testing.assert_array_equal(session.assignments, session.base_assignments) + session.restore_journal(after) + assert len(calls) == 2 + assert session.metadata['group'][100] == 'good' + finally: + session.close() + source.close() + + +def test_prepared_event_revalidates_allocator_and_detaches_values(tmp_path): + source, session = make_session(tmp_path) + try: + event = session.preflight_merge([0, 1], 100) + session.next_cluster_id = 200 + with pytest.raises(ValueError, match='allocator'): + session._append(event) + assert not session.events + event = session.preflight_label('notes', [0], {'checked': []}) + session._append(event) + event['value']['checked'].append('caller mutation') + assert session.events[-1]['value'] == {'checked': []} + assert session.metadata['notes'][0] == {'checked': []} + finally: + session.close() + source.close() + + +def test_metadata_only_journal_has_constant_interpretation_scope(tmp_path, monkeypatch): + from phy.apps.large_recording import curation, runtime + + source, session = make_session(tmp_path) + scopes = [] + interpreter = curation.interpret_events + + def measured(units, metadata, events): + scopes.append((len(units), len(events))) + return interpreter(units, metadata, events) + + try: + monkeypatch.setattr(runtime, 'interpret_events', measured) + assignments = session.assignments + revision = session.membership_revision + for i in range(1000): + session.record_label('group', [0], 'good' if i % 2 else 'mua') + assert set(scopes) == {(4, 1)} + assert session.assignments is assignments + assert session.membership_revision is revision + assert all(not t.old_groups and not t.new_groups for t in session._transitions.values()) + finally: + session.close() + source.close() + + +def test_shared_journal_records_are_immutable_and_snapshots_detached(tmp_path): + source, session = make_session(tmp_path) + try: + session.record_merge([0, 1], 100) + state = session.journal_state() + with pytest.raises(TypeError, match='read-only'): + state['events'][0]['parents'][0] = 123456 + with pytest.raises(TypeError, match='read-only'): + session.events.append({'operation': 'bad'}) + with pytest.raises(AttributeError): + session.events = [] + snapshot = session.snapshot() + snapshot['events'][0]['parents'][0] = 123456 + with pytest.raises(ValueError, match='inactive'): + session.restore(snapshot) + assert session.events[0]['parents'] == [0, 1] + session.restore_journal(state) + assert session.metadata == session._runtime.metadata + finally: + session.close() + source.close() + + +def test_restore_plan_expressions_are_detached_from_runtime(tmp_path): + from phy.apps.large_recording.tests.test_restore_parents import _package + + _, session = _package(tmp_path) + try: + session.record_merge([0, 1], 100) + expressions = session.restore_parent_plan(100)[2] + expressions[0]['unit'] = 123456 + assert session.restore_parent_plan(100)[2][0]['unit'] == 0 + session.record_restore_parents(100, [101, 102], recursive=True) + assert set(session.assignments) == {2, 99, 101, 102} + finally: + session.close() + + +def test_save_preserves_cached_prefix_and_explicit_snapshot_rebuilds_runtime( + tmp_path, monkeypatch +): + from phy.apps.large_recording import curation + + source, session = make_session(tmp_path) + original = curation.project_assignments + try: + baseline = session.snapshot() + before = session.journal_state() + session.record_merge([0, 1], 100) + after = session.journal_state() + event = session.events[-1] + session.save() + assert session.events[-1] is event + + def forbid(*args, **kwargs): + pytest.fail('Saving discarded cached incremental history.') + + monkeypatch.setattr(curation, 'project_assignments', forbid) + session.restore_journal(before) + session.restore_journal(after) + monkeypatch.setattr(curation, 'project_assignments', original) + session.save(**baseline) + assert set(session._runtime.active) == set(session.unit_ids) + assert not session.events + session.record_label('group', [0], 'mua') + session.record_merge([0, 2], 100) + expected = original(session.base_assignments, session.events, session.attributes) + np.testing.assert_array_equal(session.assignments, expected) + finally: + session.close() + source.close() + + +def test_history_budget_accounts_for_nested_metadata(tmp_path): + source, session = make_session(tmp_path) + try: + session.history_cache_bytes = 64 * 1024 + session.record_label('notes', [0], {'values': [0] * 100000}) + for _ in range(3): + session.record_label('group', [0], 'good') + assert not session._transitions + assert session._transition_bytes == 0 + assert session.metadata['notes'][0]['values'] == [0] * 100000 + finally: + session.close() + source.close() + + +def test_cyclic_label_payload_is_rejected_before_freezing(tmp_path): + source, session = make_session(tmp_path) + try: + cyclic = [] + cyclic.append(cyclic) + with pytest.raises(ValueError, match='Circular reference'): + session.record_label('notes', [0], cyclic) + assert not session.events + finally: + session.close() + source.close() + + +@pytest.mark.parametrize('budget', [0, 1]) +def test_evicted_transition_releases_previous_row_arrays(tmp_path, budget): + import gc + import weakref + + source, session = make_session(tmp_path) + try: + session.history_cache_bytes = budget + old_rows = weakref.ref(session._assignment_groups[0]) + event = session.preflight_merge([0, 1], 100) + transition = weakref.ref(session._prepared) + session._append(event) + gc.collect() + assert not session._transitions + assert session._transition_bytes == 0 + assert transition() is None + assert old_rows() is None + assert not hasattr(session, 'last_transition') + finally: + session.close() + source.close() diff --git a/phy/apps/large_recording/tests/test_incremental_supervisor.py b/phy/apps/large_recording/tests/test_incremental_supervisor.py new file mode 100644 index 000000000..1c74bd183 --- /dev/null +++ b/phy/apps/large_recording/tests/test_incremental_supervisor.py @@ -0,0 +1,171 @@ +"""Native history and derived membership caches follow semantic transition scope.""" + +import numpy as np +import pytest +from phylib.utils import connect, unconnect + +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.apps.large_recording.tests.test_curation import make_session + + +class NoCopy(np.ndarray): + def copy(self, *args, **kwargs): + pytest.fail('An interactive command copied the complete spike assignment array.') + + +def test_thousand_event_label_and_undo_skip_spike_and_membership_work(tmp_path, monkeypatch): + from phy.apps.large_recording import curation, live_summaries, runtime + from phy.apps.large_recording.supervisor import BoundedSupervisor + from phy.cluster._propositions import MergePropositionController, decode_curation_mapping + + source, session = make_session(tmp_path) + try: + for i in range(1000): + session.record_label('group', [0], 'good' if i % 2 else 'mua') + supervisor = BoundedSupervisor( + spike_clusters=session.assignments.copy(), + session=session, + cluster_labels=session.metadata, + ) + mapping = { + 'format_version': '2', + 'unit_ids': session.unit_ids, + 'merges': [{'unit_ids': [0, 1]}], + } + supervisor.merge_propositions = MergePropositionController( + decode_curation_mapping(mapping) + ) + supervisor._project_proposition_state() + session.restored_parent_ids # Warm the one membership projection. + revision = session.membership_revision + supervisor.clustering._spike_clusters = supervisor.clustering._spike_clusters.view(NoCopy) + session.assignments = session.assignments.view(NoCopy) + original_equal = np.array_equal + original_interpreter = runtime.interpret_events + + def forbid(*args, **kwargs): + pytest.fail('A metadata-only action replayed or rebuilt membership state.') + + def compare(a, b, *args, **kwargs): + assert np.shape(a) != session.assignments.shape, 'Full assignment scan during label.' + return original_equal(a, b, *args, **kwargs) + + def interpret(units, metadata, events): + assert len(events) == 1 + return original_interpreter(units, metadata, events) + + monkeypatch.setattr(curation, 'project_assignments', forbid) + monkeypatch.setattr(live_summaries, 'membership_expressions', forbid) + monkeypatch.setattr(supervisor, '_reassembled_results', forbid) + monkeypatch.setattr(session, 'snapshot', forbid) + monkeypatch.setattr(runtime, 'interpret_events', interpret) + monkeypatch.setattr(np, 'array_equal', compare) + supervisor.label('group', 'noise', [0]) + assert session.metadata['group'][0] == 'noise' + assert session.membership_revision is revision + supervisor.undo() + assert session.metadata['group'][0] == 'good' + assert session.membership_revision is revision + supervisor.redo() + assert session.metadata['group'][0] == 'noise' + assert session.membership_revision is revision + finally: + session.close() + source.close() + + +def test_bounded_native_undo_uses_local_patch(tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + _, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + original = supervisor.clustering.spike_clusters.copy() + supervisor.merge([0, 1], to=100) + supervisor.clustering._spike_clusters_base = ( + supervisor.clustering._spike_clusters_base.view(NoCopy) + ) + + def forbid(*args, **kwargs): + pytest.fail('Cached native undo replayed semantic assignments.') + + monkeypatch.setattr(curation, 'project_assignments', forbid) + supervisor.undo() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, original) + supervisor.redo() + np.testing.assert_array_equal( + supervisor.clustering.spike_clusters, supervisor.session.assignments + ) + finally: + controller.close() + + +def test_label_keeps_controller_membership_metric_caches(tmp_path, monkeypatch): + from phy.apps.large_recording import live_summaries + + _, controller = make_controller(tmp_path) + try: + full_count = controller.get_full_count(0) + waveform_count = controller.get_waveform_count(0) + lineage = controller._lineage_cache + waveforms = controller._waveform_membership_cache + + def forbid(*args, **kwargs): + pytest.fail('A label invalidated a membership metric cache.') + + monkeypatch.setattr(live_summaries, 'membership_expressions', forbid) + controller.supervisor.label('group', 'mua', [0]) + assert controller.get_full_count(0) == full_count + assert controller.get_waveform_count(0) == waveform_count + assert controller._lineage_cache is lineage + assert controller._waveform_membership_cache is waveforms + controller.supervisor.undo() + assert controller.get_full_count(0) == full_count + assert controller.get_waveform_count(0) == waveform_count + assert controller._lineage_cache is lineage + assert controller._waveform_membership_cache is waveforms + finally: + controller.close() + + +@pytest.mark.parametrize('operation', ['merge', 'split', 'undo', 'redo', 'restore']) +def test_observer_cannot_write_unrelated_public_assignment_rows(tmp_path, operation): + _, controller = make_controller(tmp_path) + supervisor = controller.supervisor + if operation in ('undo', 'redo', 'restore'): + supervisor.merge([0, 1], to=100) + if operation == 'redo': + supervisor.undo() + before = supervisor.clustering.spike_clusters.copy() + before_events = supervisor.session.events + before_history = supervisor._global_history.current_position + before_groups = dict(supervisor.clustering.spikes_per_cluster) + before_revision = supervisor.session.membership_revision + + @connect(event='cluster', sender=supervisor.clustering) + def mutate(sender, up): + unrelated = sender.spikes_per_cluster[2][0] + sender.spike_clusters[unrelated] = 99 + + try: + with pytest.raises(ValueError, match='read-only'): + if operation == 'merge': + supervisor.merge([0, 1]) + elif operation == 'split': + supervisor.split_source_amplitude(0, 4) + elif operation == 'restore': + supervisor.restore_parents(100) + else: + getattr(supervisor, operation)() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + np.testing.assert_array_equal(supervisor.session.assignments, before) + assert supervisor.session.events == before_events + assert supervisor._global_history.current_position == before_history + assert supervisor.session.membership_revision is before_revision + assert set(supervisor.clustering.spikes_per_cluster) == set(before_groups) + for cluster, rows in before_groups.items(): + np.testing.assert_array_equal(supervisor.clustering.spikes_per_cluster[cluster], rows) + np.testing.assert_array_equal(supervisor.session._assignment_groups[cluster], rows) + finally: + unconnect(mutate) + controller.close() diff --git a/phy/apps/large_recording/tests/test_live_summaries.py b/phy/apps/large_recording/tests/test_live_summaries.py new file mode 100644 index 000000000..5e84d070b --- /dev/null +++ b/phy/apps/large_recording/tests/test_live_summaries.py @@ -0,0 +1,578 @@ +"""Live memberships and exact summaries compared with independent full replay.""" + +import json +import os +from concurrent.futures import CancelledError + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import BoundedSession, project_assignments +from phy.apps.large_recording.live_summaries import LiveSummaryEngine, membership_expressions +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.source import hash_file, hash_json +from phy.apps.large_recording.tests.test_source import make_sorting + + +def split(parent, children, attribute='amplitudes.npy', threshold=4, nonfinite='keep'): + return { + 'version': 1, + 'operation': 'threshold_split', + 'parent': parent, + 'children': children, + 'metadata': {}, + 'predicate': { + 'attribute': attribute, + 'operator': '>=', + 'threshold': threshold, + 'nonfinite': nonfinite, + }, + } + + +def merge(parents, target): + return { + 'version': 1, + 'operation': 'merge', + 'parents': parents, + 'target': target, + 'metadata': {}, + } + + +def package(tmp_path, columns=False, positions=False): + params = make_sorting(tmp_path / 'source', columns=columns) + amplitude = np.load(params.parent / 'amplitudes.npy') + amplitude[1], amplitude[8] = np.nan, np.inf + np.save(params.parent / 'amplitudes.npy', amplitude[:, None] if columns else amplitude) + if positions: + (params.parent / 'spike_depths.npy').unlink() + params.write_text(params.read_text() + 'depth_axis = 1\n') + bounded = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=8, + window_seconds=3, + stratum_seconds=20, + bin_seconds=5, + batch_size=2, + valid_intervals=[[0, 7], [10, 20]], + ) + return params.parent, bounded + + +def test_accepted_top_level_summary_manifest_still_resolves(tmp_path): + _, bounded = package(tmp_path) + path = bounded / '_phy_curation_manifest.json' + manifest = json.loads(path.read_text()) + manifest.pop('summaries') + manifest.pop('preparation_identity') + manifest['preparation_identity'] = hash_json(manifest) + path.write_text(json.dumps(manifest)) + session = BoundedSession(bounded) + try: + expressions = membership_expressions(session.unit_ids, [split(0, [100, 101])]) + with LiveSummaryEngine(bounded, batch_size=2) as engine: + result = engine.resolve({c: expressions[c] for c in (100, 101)}) + np.testing.assert_array_equal(result[100]['counts'], [2, 0, 0, 0]) + np.testing.assert_array_equal(result[101]['counts'], [0, 0, 1, 1]) + finally: + session.close() + + +def oracle(source, engine, events, unit): + assignments = np.load(source / 'spike_clusters.npy').reshape(-1) + attrs = { + name: np.load(source / name).reshape(-1) + for name in ('amplitudes.npy', 'spike_templates.npy') + } + assignments = project_assignments(assignments, events, attrs) + times = np.load(source / 'spike_times.npy').reshape(-1) + depth = ( + np.load(source / 'spike_depths.npy').reshape(-1) + if (source / 'spike_depths.npy').exists() + else np.load(source / 'spike_positions.npy')[:, 1] + ) + result = engine._empty() + for index in range(len(times)): + if assignments[index] != unit: + continue + column = next( + i + for i, (a, b) in enumerate(zip(engine.edges[:-1], engine.edges[1:])) + if a <= times[index] < b + ) + result['counts'][column] += 1 + for field, values in [('amplitude', attrs['amplitudes.npy']), ('depth', depth)]: + if np.isfinite(values[index]): + result['trend_sums'][field][column] += values[index] + result['trend_counts'][field][column] += 1 + return result + + +@pytest.mark.parametrize('columns,positions', [(False, False), (True, True)]) +def test_exact_nested_split_merge_native_bins_and_offline_cache(tmp_path, columns, positions): + source, bounded = package(tmp_path, columns, positions) + before = {p.name: hash_file(p) for p in source.iterdir()} + manifest_before = hash_file(bounded / '_phy_curation_manifest.json') + events = [ + split(1, [100, 101]), + merge([101, 2], 102), + split(102, [103, 104], 'spike_templates.npy', 1), + merge([100, 103], 105), + ] + expressions = membership_expressions([0, 1, 2, 99], events) + with LiveSummaryEngine(bounded, batch_size=2) as engine: + result = engine.resolve(expressions) + np.testing.assert_array_equal(engine.exposure, [5, 2, 5, 5]) + for unit, summary in result.items(): + expected = oracle(source, engine, events, unit) + for name, values in engine._flat(summary).items(): + np.testing.assert_allclose(values, engine._flat(expected)[name]) + assert not values.flags.writeable + assert set(engine.arrays) == { + 'spike_times.npy', + 'spike_clusters.npy', + 'amplitudes.npy', + 'spike_templates.npy', + 'spike_positions.npy' if positions else 'spike_depths.npy', + } + engine.remember(expressions, result) + assert len(engine.resident) * engine.summary_bytes <= engine.max_bytes + assert {p.name: hash_file(p) for p in source.iterdir()} == before + assert hash_file(bounded / '_phy_curation_manifest.json') == manifest_before + source.rename(tmp_path / 'relocated') + with LiveSummaryEngine(bounded) as engine: + cached = engine.cached(expressions) + assert set(cached) == set(expressions) + assert not engine.arrays + combined = {'kind': 'union', 'parts': [expressions[104], expressions[105]]} + summary = engine.cached({200: combined})[200] + np.testing.assert_array_equal( + summary['counts'], result[104]['counts'] + result[105]['counts'] + ) + + +def test_membership_identity_ignores_labels_and_transient_ids(): + a = membership_expressions([0, 1], [split(0, [2, 3])]) + b = membership_expressions( + [0, 1], + [ + split(0, [20, 30]), + {'operation': 'label', 'ids': [30], 'field': 'group', 'value': 'good'}, + ], + ) + assert a[2] == b[20] and a[3] == b[30] + assert ( + membership_expressions([0, 1], [merge([0, 1], 2)])[2] + == (membership_expressions([0, 1], [merge([1, 0], 20)])[20]) + ) + + +def test_reject_only_parent_rows_and_keep_nonfinite_remainder(tmp_path): + source, bounded = package(tmp_path) + with LiveSummaryEngine(bounded, batch_size=1) as engine: + events = [split(0, [100, 101], nonfinite='reject')] + result = engine.resolve(membership_expressions([0, 1, 2, 99], events)) + assert sum(result[u]['counts'].sum() for u in (100, 101)) == 4 + with pytest.raises(ValueError, match='Nonfinite'): + engine.resolve( + membership_expressions([0, 1, 2, 99], [split(1, [100, 101], nonfinite='reject')]) + ) + assert not engine.arrays + + +@pytest.mark.parametrize('change', ['scalar', 'assignments', 'metadata', 'shape', 'missing']) +def test_source_changes_never_publish_completed_summary(tmp_path, change): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + if change == 'metadata': + (source / 'cluster_group.tsv').write_text('cluster_id\tgroup\n0\tnoise\n') + else: + name = 'spike_clusters.npy' if change == 'assignments' else 'amplitudes.npy' + path = source / name + array = np.load(path) + if change == 'missing': + path.unlink() + else: + array[0] = 99 + np.save(path, array[:-1] if change == 'shape' else array) + with LiveSummaryEngine(bounded) as engine: + with pytest.raises((ValueError, FileNotFoundError)): + engine.resolve(expressions) + assert not engine.arrays and not engine.handles + assert not list((bounded / '.phy' / 'live-summary-cache').glob('*.npz')) + + +def test_cache_tamper_is_miss_and_relocation_supported(tmp_path): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with LiveSummaryEngine(bounded) as engine: + result = engine.resolve(expressions) + cache = engine.cache_dir / f'{engine.key(expressions[100])}.npz' + with np.load(cache) as record: + content = {name: record[name] for name in record.files} + content['counts'] = content['counts'] + 5 + np.savez(cache, **content) + relocated = tmp_path / 'moved' + source.rename(relocated) + with LiveSummaryEngine(bounded, source_dir=relocated) as engine: + assert 100 not in engine.cached(expressions) + actual = engine.resolve(expressions) + np.testing.assert_array_equal(actual[100]['counts'], result[100]['counts']) + + +def test_cancellation_and_output_disk_budgets(tmp_path): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with LiveSummaryEngine(bounded, max_bytes=1) as engine: + with pytest.raises(ValueError, match='budget'): + engine.resolve(expressions) + assert not engine.arrays + with LiveSummaryEngine(bounded, cache_bytes=1) as engine: + with pytest.raises(CancelledError): + engine.resolve(expressions, cancel=lambda: True) + assert not engine.arrays + engine.resolve(expressions) + assert not engine.cache_dir.exists() + + +def test_pinned_source_change_between_jobs_rejected(tmp_path): + source, bounded = package(tmp_path) + events = [split(1, [100, 101])] + with LiveSummaryEngine(bounded) as engine: + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + path = source / 'amplitudes.npy' + # Mutate a mapped payload without truncating its file (unsupported on Windows). + before = path.stat() + with path.open('r+b') as stream: + stream.seek(engine.arrays['amplitudes.npy'].offset) + stream.write(np.array([500], dtype=engine.arrays['amplitudes.npy'].dtype).tobytes()) + stream.flush() + os.fsync(stream.fileno()) + os.utime(path, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000)) + events.append(split(0, [102, 103])) + with pytest.raises(ValueError, match='changed'): + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + assert not engine.arrays + + +def test_reunited_children_restore_prepared_membership(): + expressions = membership_expressions([0, 1], [split(0, [2, 3]), merge([3, 2], 4)]) + assert expressions[4] == {'kind': 'source', 'unit': 0} + + +@pytest.mark.parametrize('phase', ['hash', 'scan']) +def test_mid_job_cancellation_retains_only_authenticated_readers(tmp_path, phase): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with LiveSummaryEngine(bounded, batch_size=1) as engine: + + def cancel(): + if phase == 'hash': + return bool(engine.handles) + return bool(engine.arrays) and len(engine.arrays) >= 4 + + with pytest.raises(CancelledError): + engine.resolve(expressions, cancel) + if phase == 'hash': + assert not engine.arrays and not engine.handles + else: + assert engine.arrays and engine.handles + assert not any(handle.closed for handle in engine.handles.values()) + assert not list(engine.cache_dir.glob('*.npz')) + + +def test_same_job_source_replacement_never_publishes(tmp_path): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with LiveSummaryEngine(bounded, batch_size=1) as engine: + replaced = [] + + def mutate(): + if len(engine.arrays) >= 4 and not replaced: + path = source / 'amplitudes.npy' + old = path.with_suffix('.old') + path.rename(old) + np.save(path, np.load(old)) + replaced.append(True) + return False + + # Windows can prevent replacement of an open file altogether. Either + # that refusal or our fingerprint check must abort without publishing. + with pytest.raises((ValueError, PermissionError)) as failure: + engine.resolve(expressions, mutate) + if isinstance(failure.value, PermissionError): + assert os.name == 'nt' + else: + assert 'changed' in str(failure.value) + assert not engine.arrays and not engine.handles + assert not list(engine.cache_dir.glob('*.npz')) + + +@pytest.mark.parametrize('bin_seconds', [2, 6]) +def test_zero_exposure_and_short_final_native_bins(tmp_path, bin_seconds): + params = make_sorting(tmp_path / 'source') + depth = np.load(params.parent / 'spike_depths.npy') + depth[3], depth[7] = np.nan, -np.inf + np.save(params.parent / 'spike_depths.npy', depth[:, None]) + bounded = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=8, + window_seconds=3, + stratum_seconds=20, + bin_seconds=bin_seconds, + batch_size=2, + valid_intervals=[[0, 7], [10, 20]], + ) + events = [split(0, [100, 101])] + with LiveSummaryEngine(bounded, batch_size=2) as engine: + result = engine.resolve(membership_expressions([0, 1, 2, 99], events)) + for unit, summary in result.items(): + expected = oracle(params.parent, engine, events, unit) + for name, values in engine._flat(summary).items(): + np.testing.assert_allclose(values, engine._flat(expected)[name]) + if bin_seconds == 2: + assert engine.exposure[4] == 0 + assert all(summary['counts'][4] == 0 for summary in result.values()) + else: + assert engine.edges[-1] - engine.edges[-2] == 2 + + +def test_branching_memberships_match_full_projection(tmp_path): + source, bounded = package(tmp_path) + rng = np.random.default_rng(42) + events = [] + active = [0, 1, 2, 99] + next_id = 100 + for _ in range(18): + if len(active) >= 3 and rng.random() < 0.4: + parents = list(map(int, rng.choice(active, size=2, replace=False))) + events.append(merge(parents, next_id)) + active = [unit for unit in active if unit not in parents] + [next_id] + next_id += 1 + else: + parent = int(rng.choice(active)) + events.append( + split( + parent, + [next_id, next_id + 1], + 'amplitudes.npy' if rng.random() < 0.5 else 'spike_templates.npy', + float(rng.integers(0, 10)), + ) + ) + active = [unit for unit in active if unit != parent] + [next_id, next_id + 1] + next_id += 2 + with LiveSummaryEngine(bounded, batch_size=2) as engine: + for journal in [ + events, + events[:9], + events[:6] + [split(0, [1000, 1001])] + if 0 in membership_expressions([0, 1, 2, 99], events[:6]) + else events[:4], + ]: + expressions = membership_expressions([0, 1, 2, 99], journal) + results = engine.resolve(expressions) + for unit, summary in results.items(): + expected = oracle(source, engine, journal, unit) + for name, values in engine._flat(summary).items(): + np.testing.assert_allclose(values, engine._flat(expected)[name]) + + +def test_reject_split_reunion_still_checks_full_source_nonfinite(tmp_path): + source, bounded = package(tmp_path) + events = [split(1, [100, 101], nonfinite='reject'), merge([100, 101], 102)] + with LiveSummaryEngine(bounded) as engine, pytest.raises(ValueError, match='Nonfinite'): + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + + +@pytest.mark.parametrize('metadata', ['[]', 'null', '42', '{"key":null}']) +def test_valid_json_wrong_cache_metadata_is_disposable(tmp_path, metadata): + source, bounded = package(tmp_path) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with LiveSummaryEngine(bounded) as engine: + expected = engine.resolve(expressions) + cache = engine.cache_dir / f'{engine.key(expressions[100])}.npz' + np.savez(cache, metadata=metadata) + assert 100 not in engine.cached(expressions) + actual = engine.resolve(expressions) + np.testing.assert_array_equal(actual[100]['counts'], expected[100]['counts']) + + +def test_positions_validation_hashes_unselected_columns_too(tmp_path): + source, bounded = package(tmp_path, positions=True) + path = source / 'spike_positions.npy' + positions = np.load(path) + positions[0, 0] = 99 + np.save(path, positions) + with LiveSummaryEngine(bounded) as engine: + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])]) + with pytest.raises(ValueError, match='hash mismatch'): + engine.resolve(expressions) + + +def test_reader_reuses_validated_files_and_opens_new_predicates_only(tmp_path, monkeypatch): + from pathlib import Path + + source, bounded = package(tmp_path) + original = Path.open + opened = [] + + def record(path, *args, **kwargs): + if path.parent == source and path.suffix == '.npy': + opened.append(path.name) + return original(path, *args, **kwargs) + + monkeypatch.setattr(Path, 'open', record) + events = [split(1, [100, 101])] + with LiveSummaryEngine(bounded) as engine: + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + first = list(opened) + events.append(split(0, [102, 103], 'spike_templates.npy', 1)) + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + assert opened[len(first) :] == ['spike_templates.npy'] + assert opened.count('spike_times.npy') == 1 + assert opened.count('spike_clusters.npy') == 1 + (source / 'cluster_group.tsv').write_text('cluster_id\tgroup\n0\tnoise\n') + events.append(split(99, [104, 105])) + with pytest.raises(ValueError, match='metadata changed'): + engine.resolve(membership_expressions([0, 1, 2, 99], events)) + assert not engine.arrays + + +def test_disk_cache_growth_and_resident_eviction_are_bounded(tmp_path): + source, bounded = package(tmp_path) + with LiveSummaryEngine(bounded, cache_bytes=17000, max_bytes=500) as engine: + events = [split(1, [100, 101])] + first = membership_expressions([0, 1, 2, 99], events) + first = {100: first[100], 101: first[101]} + result = engine.resolve(first) + engine.remember(first, result) + events.append(split(0, [102, 103])) + second = membership_expressions([0, 1, 2, 99], events) + second = {102: second[102], 103: second[103]} + more = engine.resolve(second) + engine.remember(second, more) + assert len(engine.resident) * engine.summary_bytes <= engine.max_bytes + assert ( + sum(path.stat().st_size for path in engine.cache_dir.glob('*.npz')) + <= engine.cache_bytes + ) + + +def test_cache_header_claiming_huge_array_is_rejected_before_numpy_load(tmp_path, monkeypatch): + import io + import zipfile + + source, bounded = package(tmp_path) + expression = membership_expressions([0, 1, 2, 99], [split(1, [100, 101])])[100] + with LiveSummaryEngine(bounded) as engine: + engine.resolve({100: expression}) + cache = engine.cache_dir / f'{engine.key(expression)}.npz' + with zipfile.ZipFile(cache) as archive: + entries = {info.filename: archive.read(info) for info in archive.infolist()} + header = io.BytesIO() + np.lib.format.write_array_header_1_0( + header, {'descr': ' previous_history + previous_history = len(history) + current.close() + session.close() + # A full no-op round retains the explicit label on this membership. + noop = prepared(output / 'params.py', tmp_path / f'noop-bounded-{round_id}') + assert all(noop.metadata['group'][unit] == 'good' for unit in children) + noop.save() + noop_output = apply_curation( + output / 'params.py', noop.path, tmp_path / f'noop-output-{round_id}' + ) + noop.close() + params = noop_output / 'params.py' + + +def test_typed_tables_roundtrip_and_conflicts(tmp_path): + schema = { + 'version': 1, + 'tables': [ + { + 'filename': 'cluster_si_unit_ids.tsv', + 'delimiter': '\t', + 'columns': ['cluster_id', 'si_unit_id'], + }, + { + 'filename': 'cluster_metrics.csv', + 'delimiter': ',', + 'columns': ['snr', 'cluster_id', 'flag', 'details'], + }, + ], + } + metadata = { + 'si_unit_id': {0: 40, 1: None}, + 'snr': {0: 12.26, 1: None}, + 'flag': {0: True, 1: False}, + 'details': {0: ['a', 1], 1: {'x': 2}}, + 'group': {0: 'good', 1: None}, + } + write_metadata(tmp_path, metadata, schema) + assert read_metadata(tmp_path)[0] == metadata + assert read_metadata(tmp_path)[1] == complete_schema(schema, metadata) + metric = tmp_path / 'cluster_metrics.csv' + metric.write_text(metric.read_text().replace('12.26', '99.0')) + with pytest.raises(ValueError, match='cluster_metrics.csv, field snr, unit 0'): + read_metadata(tmp_path) + + +@pytest.mark.parametrize( + 'filename', ['../cluster_metric.tsv', 'cluster_info.tsv', 'cluster_bad\\evil.tsv', 'params.py'] +) +def test_unsafe_or_reserved_filenames(filename): + with pytest.raises(ValueError, match='filename'): + validate_schema( + { + 'version': 1, + 'tables': [ + {'filename': filename, 'delimiter': '\t', 'columns': ['cluster_id', 'metric']} + ], + } + ) + + +def test_duplicate_fields_and_casefold_collisions(tmp_path): + (tmp_path / 'cluster_a.tsv').write_text('cluster_id\tsnr\n0\t1\n') + (tmp_path / 'cluster_b.csv').write_text('cluster_id,snr\n0,1\n') + with pytest.raises(ValueError, match='Duplicate metadata field'): + read_metadata(tmp_path) + with pytest.raises(ValueError, match='colliding'): + validate_schema( + { + 'version': 1, + 'tables': [ + { + 'filename': 'cluster_A.tsv', + 'delimiter': '\t', + 'columns': ['cluster_id', 'a'], + }, + { + 'filename': 'cluster_a.tsv', + 'delimiter': '\t', + 'columns': ['cluster_id', 'b'], + }, + ], + } + ) + + +def test_legacy_blank_omitted_rows_and_conflicting_edit(tmp_path): + (tmp_path / 'cluster_metric.tsv').write_text('cluster_id\tmetric\n0\t4\n2\t\n') + (tmp_path / '_phy_cluster_metadata.json').write_text( + json.dumps({'metric': {'0': 4, '1': None, '2': ''}}) + ) + metadata, schema = read_metadata(tmp_path) + assert metadata['metric'] == {0: 4, 1: None, 2: ''} + write_metadata(tmp_path, metadata, schema) + assert read_metadata(tmp_path)[0] == metadata + assert '1\t\n' in (tmp_path / 'cluster_metric.tsv').read_text() + (tmp_path / 'cluster_metric.tsv').write_text('cluster_id\tmetric\n0\t9\n1\t\n2\t\n') + with pytest.raises(ValueError, match='field metric, unit 0'): + read_metadata(tmp_path) + + +def test_legacy_migration_atomic_reopen_history_and_reviews(tmp_path): + source, session = make_session(tmp_path) + session.record_merge([0, 1], 100, {'group': 'good', 'producer': 9}) + session.record_label('group', [100], 'good') + session.record_merge([100, 2], 101, {'group': 'good', 'producer': 9}) + session.record_label('comment', [101], 'explicit decision') + review = {'opaque_review': ['unchanged']} + legacy_generation = session.save(extra_documents={'review.json': review}) + manifest_hash = hash_file(session.path / '_phy_curation_manifest.json') + old_hash = hash_file(legacy_generation / 'metadata.json') + before = session.snapshot() + event = session.migrate_metadata() + assert event['operation'] == 'metadata_policy' + assert session.metadata['group'][101] is None # Parent's explicit label expires. + assert session.metadata['producer'][101] is None + assert session.metadata['comment'][101] == 'explicit decision' + migrated = session.snapshot() + session.restore(before) + assert session.metadata['group'][101] == 'good' + session.restore(migrated) + assert session.metadata['group'][101] is None + np.testing.assert_array_equal(session.assignments, before['assignments']) + assert session.next_cluster_id == before['next_cluster_id'] + session.save() + reopened = BoundedSession(session.path) + assert reopened.metadata_policy == POLICY + assert reopened.metadata == session.metadata + assert reopened.extra_documents['review.json'] == review + assert hash_file(session.path / '_phy_curation_manifest.json') == manifest_hash + assert hash_file(legacy_generation / 'metadata.json') == old_hash + reopened.record_label('group', [101], 'good') + assert reopened.metadata['group'][101] == 'good' + reopened.record_merge([101, 99], 102, {'group': 'good'}) + assert reopened.metadata['group'][102] is None + source.close() + session.close() + reopened.close() + + +def test_legacy_interpretation_is_unchanged(): + events = [ + { + 'version': 1, + 'operation': 'merge', + 'parents': [0, 1], + 'target': 2, + 'metadata': {'group': 'good', 'snr': 12.26}, + } + ] + _, metadata, _ = interpret_events([0, 1], {'snr': {0: 12.26, 1: 8}}, events) + assert metadata == {'group': {2: 'good'}, 'snr': {2: 12.26}} + + +def test_blank_legacy_metadata_preserves_revision_and_v1_values(tmp_path): + from phy.apps.large_recording.source import assignment_revision + + params = make_sorting(tmp_path / 'full') + (params.parent / 'cluster_metric.tsv').write_text('cluster_id\tmetric\n0\t\n') + with Source(params) as source: + legacy = {'group': {0: 'good', 1: 'mua', 2: 'good', 99: 'noise'}, 'metric': {0: ''}} + assert source.metadata == legacy + assert source.revision == assignment_revision(params.parent, legacy) + _, projected, _ = interpret_events([0, 1], {'metric': {0: ''}}, []) + assert projected == {'metric': {0: ''}} + + +def test_save_snapshot_policy_schema_and_provenance_use_supplied_state(tmp_path): + source, session = make_session(tmp_path) + session.record_merge([0, 1], 100, {'group': 'good'}) + legacy = session.snapshot() + session.migrate_metadata() + session.record_label('group', [100], 'good') + # Save an earlier valid history prefix, as undo/history clients can do. + session.save(**legacy) + reopened = BoundedSession(session.path) + assert reopened.events == legacy['events'] + assert reopened.metadata == legacy['metadata'] + assert reopened.metadata_policy is None + assert len(reopened.metadata_provenance['history']) == 1 + source.close() + session.close() + reopened.close() + + +def test_migration_rejects_same_metadata_with_changed_source_coordinates(tmp_path): + source, session = make_session(tmp_path) + source.close() + amplitudes = np.load(source.path / 'amplitudes.npy') + amplitudes[0] += 1 + np.save(source.path / 'amplitudes.npy', amplitudes) + with pytest.raises(ValueError, match='identity'): + session.migrate_metadata() + assert not session.events + session.close() + + +def test_gui_membership_quality_metadata_and_history(tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + + _, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + supervisor.label('producer_metric', 42, [0, 1]) + supervisor.label('classification', 'sua', [0, 1]) + supervisor.merge([0, 1]) + session = controller.bounded_session + for field in ('producer_metric', 'classification', 'group'): + assert session.metadata[field][100] is None + assert supervisor.cluster_meta.get(field, 100) is None + assert supervisor.cluster_meta.get('group', 2) == 'good' + supervisor.label('group', 'good', [100]) + supervisor.undo() + assert supervisor.cluster_meta.get('group', 100) is None + supervisor.redo() + assert supervisor.cluster_meta.get('group', 100) == 'good' + supervisor.split_source_amplitude(100, 4) + children = session.events[-1]['children'] + for field in ('producer_metric', 'classification', 'group'): + assert all(supervisor.cluster_meta.get(field, child) is None for child in children) + supervisor.undo() + assert supervisor.cluster_meta.get('group', 100) == 'good' + supervisor.redo() + assert all(supervisor.cluster_meta.get('group', child) is None for child in children) + supervisor.save() + finally: + controller.close() + + +def test_migration_keeps_explicit_target_quality_and_old_generation_reopens(tmp_path): + source, session = make_session(tmp_path) + # The original spelling cannot be inferred from the group header alone. + (source.path / 'cluster_group.tsv').rename(source.path / 'cluster_quality_archive.tsv') + session.record_merge([0, 1], 100, {'group': 'noise'}) + session.record_label('group', [100], 'good') + session.save() + pointer_path = session.path / '.phy-curation' / 'current.json' + legacy_pointer = pointer_path.read_bytes() + legacy_metadata = session.snapshot()['metadata'] + session.migrate_metadata() + assert session.metadata['group'][100] == 'good' + assert ( + session.effective_metadata_schema['tables'][0]['filename'] == 'cluster_quality_archive.tsv' + ) + session.save() + migrated_pointer = pointer_path.read_bytes() + pointer_path.write_bytes(legacy_pointer) + with pytest.warns(UserWarning, match='Legacy bounded metadata'): + old = BoundedSession(session.path) + assert old.metadata == legacy_metadata + assert old.metadata_policy is None + old.close() + pointer_path.write_bytes(migrated_pointer) + migrated = BoundedSession(session.path) + assert migrated.metadata['group'][100] == 'good' + assert migrated.metadata_policy == POLICY + migrated.close() + source.close() + session.close() + + +def test_v2_resolved_metadata_cannot_smuggle_parent_measurements(): + event = { + 'version': 2, + 'operation': 'merge', + 'parents': [0, 1], + 'target': 2, + 'metadata': {'group': 'good', 'snr': 12.26}, + } + with pytest.raises(ValueError, match='clear producer metadata'): + interpret_events([0, 1], {'snr': {0: 12.26, 1: 8}}, [event]) + + +def test_legacy_typed_python_table_representations(tmp_path): + metadata = {'flag': {'0': True}, 'details': {'0': ['a', 1]}} + (tmp_path / '_phy_cluster_metadata.json').write_text(json.dumps(metadata)) + (tmp_path / 'cluster_flag.tsv').write_text('cluster_id\tflag\n0\tTrue\n') + (tmp_path / 'cluster_details.tsv').write_text("cluster_id\tdetails\n0\t['a', 1]\n") + assert read_metadata(tmp_path)[0] == {'flag': {0: True}, 'details': {0: ['a', 1]}} + + +def test_merge_empty_catalog_unit_does_not_inherit_identity(tmp_path): + params = metadata_sorting(tmp_path) + session = prepared(params, tmp_path / 'bounded') + session.record_merge([0, 88], 100) + assert session.metadata['si_unit_id'][100] is None + session.save() + output = apply_curation(params, session.path, tmp_path / 'out') + with Source(output / 'params.py') as curated: + assert 88 not in curated.unit_ids + assert curated.metadata['si_unit_id'][100] is None + assert curated.counts[curated.unit_ids.tolist().index(100)] == 4 + session.close() + + +def test_replay_rejects_unsourced_manifest_metadata(tmp_path): + source, session = make_session(tmp_path) + session.close() + manifest_path = session.path / '_phy_curation_manifest.json' + manifest = json.loads(manifest_path.read_text()) + manifest['base_metadata']['group']['0'] = 'fabricated' + manifest_path.write_text(json.dumps(manifest)) + session = BoundedSession(session.path) + session.save() + with pytest.raises(ValueError, match='base metadata does not match'): + apply_curation(source.params_path, session.path, tmp_path / 'out') + assert not (tmp_path / 'out').exists() + source.close() + session.close() + + +def test_replay_rejects_changed_original_table_basename(tmp_path): + params = metadata_sorting(tmp_path) + session = prepared(params, tmp_path / 'bounded') + session.save() + (params.parent / 'cluster_si_unit_ids.tsv').rename(params.parent / 'cluster_si_unit_id.tsv') + with pytest.raises(ValueError, match='metadata schema changed'): + apply_curation(params, session.path, tmp_path / 'out') + session.close() + + +def test_readonly_source_symlink_preserves_table_alias_and_target(tmp_path): + params = make_sorting(tmp_path / 'source') + producer = tmp_path / 'immutable-producer-si.tsv' + producer.write_text('cluster_id\tsi_unit_id\n0\t40\n1\t44\n2\t48\n99\t99\n') + alias = params.parent / 'cluster_si_unit_ids.tsv' + _symlink_or_skip(alias, producer) + original_hash = hash_file(producer) + with Source(params) as source: + assert source.metadata['si_unit_id'][0] == '40' + descriptor = next( + table for table in source.metadata_schema['tables'] if 'si_unit_id' in table['columns'] + ) + assert descriptor['filename'] == 'cluster_si_unit_ids.tsv' + session = prepared(params, tmp_path / 'bounded') + session.save() + output = apply_curation(params, session.path, tmp_path / 'out') + assert (output / 'cluster_si_unit_ids.tsv').is_file() + assert not (output / 'cluster_si_unit_ids.tsv').is_symlink() + assert alias.is_symlink() + assert hash_file(producer) == original_hash + session.close() + + +def test_metadata_output_refuses_existing_symlink_without_mutating_target(tmp_path): + producer = tmp_path / 'producer.tsv' + producer.write_text('immutable producer data') + destination = tmp_path / 'out' + destination.mkdir() + _symlink_or_skip(destination / 'cluster_si_unit_ids.tsv', producer) + schema = { + 'version': 1, + 'tables': [ + { + 'filename': 'cluster_si_unit_ids.tsv', + 'delimiter': '\t', + 'columns': ['cluster_id', 'si_unit_id'], + } + ], + } + original_hash = hash_file(producer) + with pytest.raises(ValueError, match='output must not overwrite a symbolic link'): + write_metadata(destination, {'si_unit_id': {0: '40'}}, schema) + assert hash_file(producer) == original_hash + + +def _symlink_or_skip(path, target): + try: + path.symlink_to(target) + except OSError as error: + if getattr(error, 'winerror', None) == 1314: + pytest.skip('This Windows account has no symbolic-link privilege.') + raise + + +@pytest.mark.parametrize('value', [{'z': (1, 2), 'a': True}, [{'z': 2, 'a': True}]]) +def test_legacy_structured_label_key_order_and_tuple_json_equivalence(tmp_path, value): + metadata = {'details': {0: value}} + table = tmp_path / 'cluster_details.tsv' + with table.open('w', newline='') as stream: + writer = csv.writer(stream, delimiter='\t') + writer.writerow(['cluster_id', 'details']) + writer.writerow([0, value]) + sidecar = tmp_path / '_phy_cluster_metadata.json' + sidecar.write_text(json.dumps(metadata, sort_keys=True)) + actual, _ = read_metadata(tmp_path) + assert actual['details'][0] == json.loads(json.dumps(value)) + # A changed boolean is a real conflict, not legacy serialization variance. + table.write_text(table.read_text().replace('True', '1')) + with pytest.raises(ValueError, match='field details, unit 0'): + read_metadata(tmp_path) diff --git a/phy/apps/large_recording/tests/test_metadata_refresh.py b/phy/apps/large_recording/tests/test_metadata_refresh.py new file mode 100644 index 000000000..2130afa94 --- /dev/null +++ b/phy/apps/large_recording/tests/test_metadata_refresh.py @@ -0,0 +1,321 @@ +"""Metadata edits update table semantics without rebuilding scientific evidence.""" + +import numpy as np +import pytest +from phylib.utils import connect, emit, unconnect + +from phy.apps.large_recording.tests.test_adapter import make_controller + + +def test_label_undo_redo_keep_scientific_artists_and_refresh_only_changed_rows( + qtbot, tmp_path, monkeypatch +): + from phy.apps.large_recording.adapter import BoundedTemplateController + + builtin_calls = [] + channel_label = BoundedTemplateController.get_best_channel_label + + def measured_channel_label(self, cluster): + builtin_calls.append(cluster) + return channel_label(self, cluster) + + monkeypatch.setattr( + BoundedTemplateController, 'get_best_channel_label', measured_channel_label + ) + _, controller = make_controller(tmp_path) + supervisor = controller.supervisor + metrics = [] + + def quality_metric(cluster): + metrics.append(cluster) + return supervisor.cluster_meta.get('group', cluster) + + supervisor.cluster_metrics['quality_metric'] = quality_metric + supervisor.columns.append('quality_metric') + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + events = [] + + @connect(event='bounded_state_changed', sender=supervisor) + def on_state(sender): + events.append('bounded') + + @connect(event='cluster', sender=supervisor) + def on_cluster(sender, up): + events.append('cluster') + + try: + supervisor.select([0]) + supervisor.block() + view = gui.get_view('UnitStabilityView') + view.on_select([0]) + data = view.get_data(0) + artists = tuple( + artist for ax in view.canvas.iter_ax() for artist in (*ax.lines, *ax.patches) + ) + selected = supervisor.selection.snapshot() + metrics.clear() + events.clear() + + def forbid(*args, **kwargs): + raise AssertionError('Unchanged scientific evidence was invalidated or redrawn.') + + monkeypatch.setattr(view, 'plot', forbid) + monkeypatch.setattr(view, '_invalidate', forbid) + patches = [] + change = supervisor.cluster_view.change + + def record(objects): + patches.extend(objects) + return change(objects) + + monkeypatch.setattr(supervisor.cluster_view, 'change', record) + for index, (action, group) in enumerate( + ( + (lambda: supervisor.label('group', 'mua', [0]), 'mua'), + (supervisor.undo, 'good'), + (supervisor.redo, 'mua'), + ) + ): + metrics.clear() + builtin_calls.clear() + action() + supervisor.block() + assert supervisor.cluster_view._model.row_by_id(0)['group'] == group + assert supervisor.cluster_view._model.row_by_id(0)['quality_metric'] == group + assert supervisor.selection.snapshot() == selected + if index == 0: + assert set(metrics) == set(supervisor.clustering.cluster_ids) + assert set(builtin_calls) == {0} + assert set(patches[-1]) == {'id', 'quality_metric'} + assert view.get_data(0) is data + assert ( + tuple( + artist for ax in view.canvas.iter_ax() for artist in (*ax.lines, *ax.patches) + ) + == artists + ) + assert events.count('bounded') == 3 + assert events.count('cluster') == 3 + finally: + unconnect(on_state, on_cluster) + gui.close() + controller.close() + + +def test_metadata_refresh_preserves_table_filter_sort_and_selection(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + try: + table = supervisor.cluster_view + table.sort_by('id', 'desc') + table.filter("group == 'good'") + supervisor.select([0]) + supervisor.block() + assert 0 in table.get_ids() + assert supervisor.selected == [0] + supervisor.label('group', 'mua', [0]) + supervisor.block() + assert table._model.row_by_id(0)['group'] == 'mua' + assert 0 not in table.get_ids() + assert supervisor.selected == table.get_selected_ids() + assert 0 not in supervisor.selected + assert table._current_sort == ('id', 'desc') + supervisor.undo() + supervisor.block() + assert table._model.row_by_id(0)['group'] == 'good' + assert 0 in table.get_ids() + assert supervisor.selected == [0] + assert table.get_selected_ids() == [0] + assert table._current_sort == ('id', 'desc') + supervisor.redo() + supervisor.block() + assert 0 not in table.get_ids() + assert 0 not in supervisor.selected + finally: + gui.close() + controller.close() + + +def test_membership_undo_and_new_summary_still_refresh_stability(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + gui.show() + supervisor = controller.supervisor + try: + supervisor.select([0]) + supervisor.block() + view = gui.get_view('UnitStabilityView') + view.on_select([0]) + old = view.get_data(0) + calls = [] + plot = view.plot + + def measured(*args, **kwargs): + calls.append(True) + return plot(*args, **kwargs) + + monkeypatch.setattr(view, 'plot', measured) + supervisor.merge([0, 1], to=100) + supervisor.block() + assert calls + assert int(view.get_data(100).counts.sum()) == 7 + calls.clear() + supervisor.undo() + supervisor.block() + assert calls + assert view.get_data(0) is not old + np.testing.assert_array_equal(view.get_data(0).counts, old.counts) + calls.clear() + current = view.get_data(0) + emit('bounded_summary_changed', supervisor) + assert calls + assert view.get_data(0) is not current + finally: + gui.close() + controller.close() + + +def test_hidden_stability_invalidates_then_reveals_current_membership(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + supervisor = controller.supervisor + view = gui.get_view('UnitStabilityView') + try: + view._dock_visible = False + view.on_select([0]) + old = view.get_data(0) + supervisor.merge([0, 1], to=100) + supervisor.block() + assert view.cluster_ids == tuple(supervisor.selected) == (100,) + emit('bounded_summary_changed', supervisor) + assert not view._selected_summaries + assert view._pending_selection is not None + assert not view._rp.results and view._rp._worker is None + view._dock_visible = True + view._flush_pending_selection() + assert view.get_data(100) is not old + assert int(view.get_data(100).counts.sum()) == 7 + assert view.cluster_ids == (100,) + finally: + gui.close() + controller.close() + + +def test_native_membership_failure_still_refreshes_unchanged_revision( + qtbot, tmp_path, monkeypatch +): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + supervisor = controller.supervisor + view = gui.get_view('UnitStabilityView') + try: + supervisor.select([0]) + supervisor.block() + view.on_select([0]) + before = view.get_data(0) + revision = supervisor.session.membership_revision + calls = [] + plot = view.plot + + def measured(*args, **kwargs): + calls.append(True) + return plot(*args, **kwargs) + + @connect(event='cluster', sender=supervisor) + def reject(sender, up): + if not up.description.startswith('metadata_'): + raise RuntimeError('reject native membership') + + monkeypatch.setattr(view, 'plot', measured) + with pytest.raises(RuntimeError, match='reject native membership'): + supervisor.merge([0, 1], to=100) + assert calls + assert supervisor.session.membership_revision is revision + assert tuple(view.cluster_ids) == (0,) + np.testing.assert_array_equal(view.get_data(0).counts, before.counts) + finally: + if 'reject' in locals(): + unconnect(reject) + gui.close() + controller.close() + + +def test_array_metric_label_undo_redo_compares_without_ambiguous_truth(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + supervisor = controller.supervisor + supervisor.cluster_metrics['array_metric'] = lambda cluster: np.array( + [cluster, len(supervisor.session.events), np.nan] + ) + supervisor.columns.append('array_metric') + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor.select([0]) + supervisor.block() + for action, group, events in ( + (lambda: supervisor.label('group', 'mua', [0]), 'mua', 1), + (supervisor.undo, 'good', 0), + (supervisor.redo, 'mua', 1), + ): + action() + supervisor.block() + row = supervisor.cluster_view._model.row_by_id(0) + assert row['group'] == group + np.testing.assert_array_equal(row['array_metric'], [0, events, np.nan]) + other = supervisor.cluster_view._model.row_by_id(2) + np.testing.assert_array_equal(other['array_metric'], [2, events, np.nan]) + finally: + gui.close() + controller.close() + + +@pytest.mark.parametrize( + 'previous, current, expected', + [ + (np.array([1, np.nan]), np.array([1, np.nan]), True), + (np.array(['a', 'b']), np.array(['a', 'b']), True), + (np.array(['a', 'b']), np.array(['a', 'c']), False), + (np.array([1, 2]), np.array([1]), False), + ('good', 'good', True), + ('good', 'mua', False), + ], +) +def test_table_metric_value_equality(previous, current, expected): + from phy.apps.large_recording.supervisor import _table_values_equal + + assert _table_values_equal(previous, current) is expected + + +@pytest.mark.parametrize('name', ['good_count', 'ch']) +def test_cross_row_metric_and_replaced_builtin_refresh_every_live_row(qtbot, tmp_path, name): + _, controller = make_controller(tmp_path) + supervisor = controller.supervisor + calls = [] + + def count_good(cluster): + calls.append(cluster) + return sum( + supervisor.cluster_meta.get('group', unit) == 'good' + for unit in supervisor.clustering.cluster_ids + ) + + supervisor.cluster_metrics[name] = count_good + if name not in supervisor.columns: + supervisor.columns.append(name) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + assert supervisor.cluster_view._model.row_by_id(2)[name] == 2 + for action, expected in ( + (lambda: supervisor.label('group', 'mua', [0]), 1), + (supervisor.undo, 2), + (supervisor.redo, 1), + ): + calls.clear() + action() + supervisor.block() + assert set(calls) == set(supervisor.clustering.cluster_ids) + for unit in supervisor.clustering.cluster_ids: + assert supervisor.cluster_view._model.row_by_id(unit)[name] == expected + finally: + gui.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_multi_propositions.py b/phy/apps/large_recording/tests/test_multi_propositions.py new file mode 100644 index 000000000..4307ed6b5 --- /dev/null +++ b/phy/apps/large_recording/tests/test_multi_propositions.py @@ -0,0 +1,58 @@ +"""Combined suggestion review is exact and journaled only on explicit merge.""" + +import numpy as np + +from ..adapter import BoundedTemplateController +from ..replay import apply_curation +from .test_adapter import make_controller + + +def test_combined_suggestions_checkpoint_and_replay(tmp_path, qtbot): + mapping = { + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}, {'unit_ids': [1, 2]}], + } + source_params, controller = make_controller(tmp_path, propositions=mapping) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + keys = tuple(p.key for p in supervisor.merge_propositions.catalog.propositions) + original = controller.bounded_session.assignments.copy() + producer_before = (controller.dir_path / 'curation.json').read_bytes() + try: + supervisor._activate_merge_propositions(supervisor.merge_propositions_view, keys) + assert supervisor.selected == [0, 1, 2] + assert not controller.bounded_session.events + np.testing.assert_array_equal(controller.bounded_session.assignments, original) + target = supervisor.merge().added[0] + assert controller.bounded_session.events[-1]['parents'] == [0, 1, 2] + assert len(supervisor.merge_propositions.catalog.reviews) == 2 + supervisor.undo() + np.testing.assert_array_equal(controller.bounded_session.assignments, original) + assert not supervisor.merge_propositions.catalog.reviews + assert supervisor.selection.state.merge.proposition_ids == keys + supervisor.redo() + supervisor.save() + assert (controller.dir_path / 'curation.json').read_bytes() == producer_before + package = controller.dir_path + finally: + gui.close() + controller.close() + reopened = BoundedTemplateController( + dir_path=package, config_dir=tmp_path / 'reopened', plugins=[] + ) + try: + assert len(reopened.supervisor.merge_propositions.catalog.reviews) == 2 + assert all( + r.result_unit_id == target + for r in reopened.supervisor.merge_propositions.catalog.reviews.values() + ) + assert reopened.bounded_session.events[-1]['parents'] == [0, 1, 2] + finally: + reopened.close() + + output = apply_curation(source_params, package, tmp_path / 'curated') + source_assignments = np.load(source_params.parent / 'spike_clusters.npy') + expected = source_assignments.copy() + expected[np.isin(expected, [0, 1, 2])] = target + np.testing.assert_array_equal(np.load(output / 'spike_clusters.npy'), expected) diff --git a/phy/apps/large_recording/tests/test_output_contract.py b/phy/apps/large_recording/tests/test_output_contract.py new file mode 100644 index 000000000..b8719867e --- /dev/null +++ b/phy/apps/large_recording/tests/test_output_contract.py @@ -0,0 +1,792 @@ +"""Reject undeclared full-output changes, including internally consistent metadata edits.""" + +import csv +import hashlib +import json +import shutil +from types import SimpleNamespace + +import numpy as np +import pytest + +import tools.compare_curation_modes as comparison +from phy._provenance import _append_curation_save, _new_session +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.metadata import SCHEMA_FILE, read_metadata, write_metadata +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import assignment_revision, hash_file +from phy.apps.large_recording.tests.test_source import make_sorting + + +def _inventory(path): + return { + str(item.relative_to(path)): hash_file(item) for item in path.rglob('*') if item.is_file() + } + + +def _pair(tmp_path, aliases=False, twin=False, split=False, unclassified=False, sparse=False): + params = make_sorting(tmp_path / 'source') + source = params.parent + assert sum((twin, split, unclassified)) <= 1 + if unclassified: + (source / 'cluster_group.tsv').unlink() + params.write_text(params.read_text() + "exporter_tag = 'fixture-v1'\n") + (source / 'cluster_snr.tsv').write_text( + 'cluster_id\tsnr\n0\t12\n1\t12\n2\t12\n99\t12\n' + if twin + else 'cluster_id\tsnr\n0\t12\n1\t13\n2\t22\n99\t3\n' + ) + (source / 'cluster_notes.tsv').write_text( + 'cluster_id\tnotes\n0\tfirst\n1\tsecond\n2\tcontrol\n99\tlast\n' + ) + (source / 'cluster_empty.tsv').write_text('cluster_id\tempty\n0\t\n1\t\n2\t\n99\t\n') + np.save(source / '_phy_spikes_subset.window_bounds.npy', np.array([[0, 20]], dtype=np.int64)) + (source / 'curation.json').write_text( + '{"format_version":"2","unit_ids":[0,1,2,99],"merges":[{"unit_ids":[0,1]}]}\n' + ) + if aliases: + (source / 'cluster_si_unit_ids.tsv').write_text( + 'cluster_id\tsi_unit_id\n0\t10\n1\t11\n2\t12\n99\t99\n' + ) + (source / 'cluster_import.csv').write_text( + 'producer,cluster_id,score\nfirst,0,1.5\nsecond,1,2.5\ncontrol,2,3.5\nlast,99,4.5\n' + ) + original = _inventory(source) + fields = list(read_metadata(source)[0]) + if 'group' not in fields: + fields.append('group') + definition = { + 'aliases': {'a': 0, 'b': 1, 'c': 2, 'd': 99}, + 'fields': fields, + 'actions': [ + {'op': 'merge', 'parents': ['a', 'b'], 'as': 'merged'}, + {'op': 'label', 'ids': ['merged'], 'field': 'group', 'value': 'good'}, + {'op': 'label', 'ids': ['merged'], 'field': 'notes', 'value': 'reviewed'}, + {'op': 'save'}, + ], + 'expected_labels': {'merged': {'group': 'good', 'notes': 'reviewed'}}, + } + if split: + definition['actions'] = [ + {'op': 'merge', 'parents': ['a', 'b'], 'as': 'merged'}, + { + 'op': 'split', + 'parent': 'merged', + 'threshold': 4.0, + 'selected': 'low', + 'remainder': 'rest', + }, + *[ + {'op': 'label', 'ids': [alias], 'field': field, 'value': value} + for alias in ('low', 'rest') + for field, value in (('group', 'good'), ('notes', 'reviewed')) + ], + {'op': 'save'}, + ] + definition['expected_labels'] = { + alias: {'group': 'good', 'notes': 'reviewed'} for alias in ('low', 'rest') + } + if unclassified: + definition['actions'] = [ + a for a in definition['actions'] if not (a['op'] == 'label' and a['field'] == 'group') + ] + definition['expected_labels'] = {'merged': {'notes': 'reviewed'}} + if twin: + definition['actions'][-1:-1] = [ + {'op': 'merge', 'parents': ['c', 'd'], 'as': 'twin'}, + {'op': 'label', 'ids': ['twin'], 'field': 'group', 'value': 'good'}, + {'op': 'label', 'ids': ['twin'], 'field': 'notes', 'value': 'reviewed'}, + ] + ordinary = tmp_path / 'ordinary-full' + shutil.copytree(source, ordinary) + reference = tmp_path / 'ordinary-reference' + comparison.run_reference(source, definition, reference) + for item in reference.iterdir(): + if item.name == 'spike_clusters.npy' or item.name.startswith('cluster_'): + shutil.copyfile(item, ordinary / item.name) + bounded = prepare_large( + params, + tmp_path / 'bounded', + window_seconds=2 if sparse else 20, + stratum_seconds=5 if sparse else 20, + max_spikes=6 if sparse else 100, + window_policy='generated' if sparse else 'auto', + bin_seconds=5, + batch_size=2, + ) + session = BoundedSession(bounded) + try: + merged = session.next_cluster_id + assert merged == 100 + session.record_merge([0, 1], merged) + targets = [merged] + if split: + session.record_threshold_split( + merged, + [102, 101], + { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 4.0, + 'nonfinite': 'keep', + }, + ) + targets = [101, 102] + for unit in targets: + if not unclassified: + session.record_label('group', [unit], 'good') + session.record_label('notes', [unit], 'reviewed') + if twin: + session.record_merge([2, 99], 101) + session.record_label('group', [101], 'good') + session.record_label('notes', [101], 'reviewed') + session.save() + finally: + session.close() + right = apply_curation(params, bounded, tmp_path / 'replay', batch_size=2) + return SimpleNamespace( + source=source, + ordinary=ordinary, + right=right, + bounded=bounded, + expected={ + unit: ( + {'notes': 'reviewed'} if unclassified else {'group': 'good', 'notes': 'reviewed'} + ) + for unit in ([101, 102] if split else [100, 101] if twin else [100]) + }, + original=original, + ) + + +def _compare(pair, bounded=True): + return comparison.compare_outputs( + pair.ordinary, + pair.right, + fields=('group', 'notes'), + chunk_size=2, + source=pair.source, + expected_labels=pair.expected, + bounded_dir=pair.bounded if bounded else None, + ) + + +@pytest.fixture +def contract_pair(tmp_path): + pair = _pair(tmp_path) + try: + yield pair + finally: + assert _inventory(pair.source) == pair.original + + +def _change_json(path, mutate): + content = json.loads(path.read_text()) + mutate(content) + path.write_text(json.dumps(content) + '\n') + + +def _refresh_revision(right): + metadata, _ = read_metadata(right) + _change_json( + right / '_phy_curation_lineage.json', + lambda document: document.update(revision=assignment_revision(right, metadata)), + ) + + +def _edit_metadata(right, field, unit, value): + metadata, schema = read_metadata(right) + metadata[field][unit] = value + write_metadata(right, metadata, schema) + # Keep the typed sidecar, every TSV and the lineage revision consistent. + # The checker must reject the metadata policy violation, not just a stale hash. + _refresh_revision(right) + + +def _journal_hash(journal): + payload = json.dumps(journal, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n' + return hashlib.sha256(payload.encode('utf-8')).hexdigest() + + +def _forge_split_threshold(pair, threshold, inherited=False): + """Change intent coherently, leaving assignments and curator expectations untouched.""" + journal_path = pair.right / '_phy_curation_journal.json' + lineage_path = pair.right / '_phy_curation_lineage.json' + journal = json.loads(journal_path.read_text()) + lineage = json.loads(lineage_path.read_text()) + lineage['metadata_provenance']['history'][1]['predicate']['threshold'] = threshold + if not inherited: + journal[1]['predicate']['threshold'] = threshold + lineage['journal_sha256'] = _journal_hash(journal) + journal_path.write_text(json.dumps(journal) + '\n') + manifest_path = pair.bounded / '_phy_curation_manifest.json' + manifest = json.loads(manifest_path.read_text()) + if inherited: + manifest['metadata_provenance']['history'][1]['predicate']['threshold'] = threshold + manifest_path.write_text(json.dumps(manifest) + '\n') + lineage['preparation_sha256'] = _journal_hash(manifest) + lineage_path.write_text(json.dumps(lineage) + '\n') + pointer_path = pair.bounded / '.phy-curation/current.json' + pointer = json.loads(pointer_path.read_text()) + generation = pair.bounded / '.phy-curation/generations' / pointer['generation'] + saved_journal = generation / 'journal.json' + saved_journal.write_text(json.dumps(journal) + '\n') + descriptor_path = generation / 'checkpoint.json' + descriptor = json.loads(descriptor_path.read_text()) + descriptor['files']['journal.json'] = hash_file(saved_journal) + descriptor['metadata_provenance'] = lineage['metadata_provenance'] + descriptor['manifest_sha256'] = _journal_hash(manifest) + descriptor_path.write_text(json.dumps(descriptor) + '\n') + pointer['sha256'] = _journal_hash(descriptor) + pointer_path.write_text(json.dumps(pointer) + '\n') + + +@pytest.mark.parametrize('bounded', [False, True]) +def test_coherent_threshold_forgery_rejected_by_source_assignments(tmp_path, bounded): + pair = _pair(tmp_path, split=True) + try: + assert _compare(pair, bounded=bounded)['ok'] + # All amplitudes are <1000; the unchanged output still has two children. + # Journal, cumulative provenance, saved generation and all hashes agree. + _forge_split_threshold(pair, 1000.0) + assert comparison.compare_outputs(pair.ordinary, pair.right)['ok'] + result = _compare(pair, bounded=bounded) + assert not result['ok'], result + assert 'cumulative source predicates' in result['error'], result + finally: + assert _inventory(pair.source) == pair.original + + +def test_threshold_oracle_checks_spikes_absent_from_bounded_evidence(tmp_path): + pair = _pair(tmp_path, split=True, sparse=True) + try: + assert _compare(pair)['ok'] + manifest = json.loads((pair.bounded / '_phy_curation_manifest.json').read_text()) + retained = np.load(pair.bounded / manifest['global_spike_ids_file']) + amplitudes = np.load(pair.source / 'amplitudes.npy') + parents = np.isin(np.load(pair.source / 'spike_clusters.npy'), [0, 1]) + changed = parents & ((amplitudes < 4.0) != (amplitudes < 5.0)) + assert np.flatnonzero(changed).tolist() == [4] + assert not changed[retained].any() + # Saved retained assignments still obey either threshold; only a check + # over all original-source rows can detect this contradiction. + _forge_split_threshold(pair, 5.0) + result = _compare(pair) + assert not result['ok'], result + assert 'cumulative source predicates' in result['error'], result + finally: + assert _inventory(pair.source) == pair.original + + +def test_inherited_split_semantics_checked_after_no_edit_round(tmp_path): + pair = _pair(tmp_path, split=True) + try: + pair.bounded = prepare_large( + pair.right / 'params.py', + tmp_path / 'bounded-next', + window_seconds=20, + stratum_seconds=20, + max_spikes=100, + bin_seconds=5, + batch_size=2, + ) + session = BoundedSession(pair.bounded) + try: + assert session.events == [] + session.save() + finally: + session.close() + pair.right = apply_curation( + pair.right / 'params.py', pair.bounded, tmp_path / 'replay-next', batch_size=2 + ) + assert _compare(pair)['ok'] + # There are no current membership events: checking just the latest + # journal would miss this forged threshold in an earlier round. + assert json.loads((pair.right / '_phy_curation_journal.json').read_text()) == [] + _forge_split_threshold(pair, 1000.0, inherited=True) + assert comparison.compare_outputs(pair.ordinary, pair.right)['ok'] + result = _compare(pair) + assert not result['ok'], result + assert 'cumulative source predicates' in result['error'], result + finally: + assert _inventory(pair.source) == pair.original + + +def test_curated_original_history_is_not_reapplied_to_source_assignments(tmp_path): + pair = _pair(tmp_path, split=True) + original = pair.source + try: + pair.source = pair.right + curated_source_inventory = _inventory(pair.source) + pair.ordinary = tmp_path / 'ordinary-curated-source' + shutil.copytree(pair.source, pair.ordinary) + pair.bounded = prepare_large( + pair.source / 'params.py', + tmp_path / 'bounded-from-curated-source', + window_seconds=20, + stratum_seconds=20, + max_spikes=100, + bin_seconds=5, + batch_size=2, + ) + session = BoundedSession(pair.bounded) + try: + assert session.events == [] + session.save() + finally: + session.close() + pair.right = apply_curation( + pair.source / 'params.py', + pair.bounded, + tmp_path / 'replay-from-curated-source', + batch_size=2, + ) + pair.expected = {} + result = _compare(pair) + assert result['ok'], result + oracle = result['file_contract']['assignment_oracle'] + assert oracle['membership_events'] == oracle['threshold_splits'] == 0 + assert oracle['source_rows'] == 12 + assert _inventory(pair.source) == curated_source_inventory + finally: + assert _inventory(original) == pair.original + + +@pytest.mark.parametrize('aliases', [False, True]) +def test_complete_file_contract_accepts_declared_metadata_differences(tmp_path, aliases): + pair = _pair(tmp_path, aliases=aliases) + try: + result = _compare(pair) + assert result['ok'], result + assert result['rows'] == 12 + metadata, _ = read_metadata(pair.right) + assert metadata['snr'][100] is None + assert metadata['snr'][2] == '22' + assert metadata['group'][100] == 'good' + if aliases: + for name in ('cluster_si_unit_ids.tsv', 'cluster_import.csv'): + assert (pair.ordinary / name).read_bytes() == (pair.source / name).read_bytes() + assert (pair.ordinary / 'cluster_si_unit_id.tsv').exists() + assert (pair.ordinary / 'cluster_producer.tsv').exists() + finally: + assert _inventory(pair.source) == pair.original + + +@pytest.mark.parametrize('name', ['cluster_si_unit_ids.tsv', 'cluster_import.csv']) +def test_ordinary_source_alias_allowance_requires_unchanged_bytes(tmp_path, name): + pair = _pair(tmp_path, aliases=True) + try: + assert _compare(pair)['ok'] + path = pair.ordinary / name + # Change only a retired parent's value in the loose producer alias. + # Active canonical fields and the curation outputs still agree. + if name.endswith('.tsv'): + path.write_text(path.read_text().replace('0\t10', '0\t777')) + else: + path.write_text(path.read_text().replace('first,0,1.5', 'forged,0,1.5')) + assert not _compare(pair)['ok'] + finally: + assert _inventory(pair.source) == pair.original + + +def test_first_round_source_binding_checks_journal_without_bounded_package(contract_pair): + pair = contract_pair + assert _compare(pair, bounded=False)['ok'] + path = pair.right / '_phy_curation_journal.json' + journal = json.loads(path.read_text()) + journal[-1]['value'] = 'forged label intent' + path.write_text(json.dumps(journal) + '\n') + _change_json( + pair.right / '_phy_curation_lineage.json', + lambda document: document.update(journal_sha256=_journal_hash(journal)), + ) + result = _compare(pair, bounded=False) + assert not result['ok'] + assert 'Journal details disagree with cumulative history' in result['error'] + + +def test_ordinary_derived_whitening_inverse_must_be_correct(contract_pair): + pair = contract_pair + assert not (pair.source / 'whitening_mat.npy').exists() + assert not (pair.source / 'whitening_mat_inv.npy').exists() + inverse = np.eye(3, dtype=np.float64) + path = pair.ordinary / 'whitening_mat_inv.npy' + np.save(path, inverse) + assert _compare(pair)['ok'] + inverse[0, 0] = 2 + np.save(path, inverse) + result = _compare(pair) + assert not result['ok'] + assert 'Invalid native derived whitening inverse' in result['error'] + + +@pytest.mark.parametrize( + 'corruption', + [ + 'amplitude', + 'waveform', + 'channels', + 'window_bounds', + 'assignment', + 'manual_label', + 'changed_membership_producer', + 'untouched_producer', + 'ordinary_untouched_producer', + 'clock', + 'exposure', + 'auxiliary_parameter', + 'new_parameter', + 'missing_asset', + 'unknown_file', + 'ordinary_unknown_file', + 'metadata_filename', + 'metadata_header', + 'metadata_schema', + 'journal', + 'parent_revision', + 'review_binding', + 'ordinary_missing_empty_table', + 'unrecorded_empty_field', + 'malformed_history', + 'parent_metadata_history', + ], +) +def test_complete_file_contract_rejects_output_corruption(contract_pair, corruption): + pair = contract_pair + right = pair.right + assert _compare(pair)['ok'] + assets = { + 'amplitude': ('amplitudes.npy', (0,)), + 'waveform': ('_phy_spikes_subset.waveforms.npy', (0, 0, 0)), + 'channels': ('channel_positions.npy', (0, 0)), + 'window_bounds': ('_phy_spikes_subset.window_bounds.npy', (0, 1)), + } + if corruption in assets: + name, index = assets[corruption] + values = np.load(right / name) + values[index] += 1 + np.save(right / name, values) + elif corruption == 'assignment': + values = np.load(right / 'spike_clusters.npy') + values[0] = 2 + np.save(right / 'spike_clusters.npy', values) + _refresh_revision(right) + elif corruption == 'manual_label': + _edit_metadata(right, 'group', 100, 'noise') + elif corruption == 'changed_membership_producer': + _edit_metadata(right, 'snr', 100, '999') + elif corruption == 'untouched_producer': + _edit_metadata(right, 'snr', 2, '999') + elif corruption == 'ordinary_untouched_producer': + path = pair.ordinary / 'cluster_snr.tsv' + path.write_text(path.read_text().replace('2\t22', '2\t999')) + elif corruption in ('clock', 'exposure', 'auxiliary_parameter', 'new_parameter'): + changes = { + 'clock': 'sample_rate = 2.0\n', + 'exposure': 'valid_intervals = [[0, 3], [5, 20]]\n', + 'auxiliary_parameter': "exporter_tag = 'changed'\n", + 'new_parameter': "unexplained_option = 'changed'\n", + } + path = right / 'params.py' + path.write_text(path.read_text() + changes[corruption]) + elif corruption == 'missing_asset': + (right / 'spike_templates.npy').unlink() + elif corruption == 'unknown_file': + (right / 'unexplained.txt').write_text('This is not an allowed generated output.\n') + elif corruption == 'ordinary_unknown_file': + (pair.ordinary / 'unexplained.txt').write_text('Not an ordinary GUI cache or table.\n') + elif corruption == 'metadata_filename': + (right / 'cluster_snr.tsv').rename(right / 'cluster_snrs.tsv') + + def rename(document): + for table in document['tables']: + if table['filename'] == 'cluster_snr.tsv': + table['filename'] = 'cluster_snrs.tsv' + + _change_json(right / SCHEMA_FILE, rename) + elif corruption == 'metadata_header': + path = right / 'cluster_snr.tsv' + with path.open(newline='') as stream: + rows = list(csv.reader(stream, delimiter='\t')) + with path.open('w', newline='') as stream: + csv.writer(stream, delimiter='\t').writerows([list(reversed(row)) for row in rows]) + + def reorder(document): + for table in document['tables']: + if table['filename'] == 'cluster_snr.tsv': + table['columns'].reverse() + + _change_json(right / SCHEMA_FILE, reorder) + elif corruption == 'metadata_schema': + _change_json(right / SCHEMA_FILE, lambda document: document.update(version=2)) + elif corruption == 'journal': + path = right / '_phy_curation_journal.json' + journal = json.loads(path.read_text()) + journal[0]['target'] = 101 + path.write_text(json.dumps(journal) + '\n') + _change_json( + right / '_phy_curation_lineage.json', + lambda document: document.update(journal_sha256=_journal_hash(journal)), + ) + elif corruption == 'parent_revision': + _change_json( + right / '_phy_curation_lineage.json', + lambda document: document.update(parent_revision='0' * 64), + ) + elif corruption == 'review_binding': + path = right / 'curation_review.json' + _change_json(path, lambda document: document['source'].update(sha256='0' * 64)) + _change_json( + right / '_phy_curation_lineage.json', + lambda document: document['proposition_documents'].update( + {'curation_review.json': hash_file(path)} + ), + ) + elif corruption == 'ordinary_missing_empty_table': + (pair.ordinary / 'cluster_empty.tsv').unlink() + elif corruption == 'unrecorded_empty_field': + metadata, schema = read_metadata(right) + metadata['invented'] = dict.fromkeys(metadata['group']) + write_metadata(right, metadata, schema) + _refresh_revision(right) + elif corruption == 'malformed_history': + _change_json( + right / '_phy_curation_lineage.json', + lambda document: document.update(metadata_provenance=[]), + ) + elif corruption == 'parent_metadata_history': + + def change_snapshot(document): + document['metadata_provenance']['history'][0]['parent_metadata']['snr']['0'] = '999' + + _change_json(right / '_phy_curation_lineage.json', change_snapshot) + else: + raise AssertionError(corruption) + result = _compare(pair) + assert not result['ok'], (corruption, result) + if corruption == 'journal': + assert 'Journal details disagree with cumulative history' in result['error'] + elif corruption == 'ordinary_missing_empty_table': + assert 'Missing native metadata field/table coverage' in result['error'] + elif corruption == 'unrecorded_empty_field': + assert 'Unexpected replay metadata fields without label intent' in result['error'] + elif corruption == 'parent_metadata_history': + assert 'Parent metadata provenance disagrees with independent history' in result['error'] + elif corruption == 'malformed_history': + assert result['error'] + + +def test_strict_contract_standalone_cli(contract_pair, tmp_path): + import subprocess + import sys + from pathlib import Path + + pair = contract_pair + repository = Path(__file__).resolve().parents[4] + expectations = tmp_path / 'expectations.json' + expectations.write_text(json.dumps(pair.expected)) + output = tmp_path / 'cli-report.json' + result = subprocess.run( + [ + sys.executable, + str(repository / 'tools/compare_curation_modes.py'), + 'compare', + str(pair.ordinary), + str(pair.right), + '--source', + str(pair.source), + '--bounded-dir', + str(pair.bounded), + '--expectations', + str(expectations), + '--output', + str(output), + '--chunk-size', + '2', + ], + cwd=repository, + capture_output=True, + text=True, + ) + assert result.returncode == 0, result.stdout + result.stderr + report = json.loads(output.read_text()) + assert report['ok'] and report['file_contract']['saved_generation_verified'] + + +def test_source_only_contract_checks_new_unit_row_ancestry(tmp_path): + pair = _pair(tmp_path, twin=True) + assert _compare(pair)['ok'] + values = np.load(pair.right / 'spike_clusters.npy') + swapped = np.where(values == 100, 101, 100).astype(values.dtype) + np.save(pair.right / 'spike_clusters.npy', swapped) + _refresh_revision(pair.right) + # Same partitions and identical labels allow this rename in the basic check; + # the stored provenance still names the WRONG source parents for those IDs. + assert comparison.compare_outputs(pair.ordinary, pair.right)['ok'] + result = comparison.compare_outputs( + pair.ordinary, + pair.right, + source=pair.source, + expected_labels=pair.expected, + chunk_size=2, + ) + assert not result['ok'] and 'Assignment disagrees' in result['error'] + assert _inventory(pair.source) == pair.original + + +@pytest.mark.parametrize('corruption', ['allocator', 'retirement']) +def test_saved_generation_and_retired_identity_binding(contract_pair, corruption): + pair = contract_pair + path = pair.right / '_phy_curation_lineage.json' + if corruption == 'allocator': + _change_json(path, lambda d: d.update(next_cluster_id=d['next_cluster_id'] + 1)) + else: + _change_json( + path, + lambda d: d['retired_units'].update( + {'999': {'operation': 'merge', 'replacements': [100]}} + ), + ) + result = _compare(pair) + assert not result['ok'] + assert ('saved checkpoint' if corruption == 'allocator' else 'independent history') in result[ + 'error' + ] + + +def test_generated_summary_requires_complete_active_catalog(contract_pair): + pair = contract_pair + path = pair.ordinary / 'cluster_info.tsv' + path.write_text( + 'cluster_id\tgroup\tnotes\n2\tgood\tcontrol\n99\tnoise\tlast\n100\tgood\treviewed\n' + ) + assert _compare(pair)['ok'] + path.write_text('cluster_id\tgroup\tnotes\n99\tnoise\tlast\n100\tgood\treviewed\n') + result = _compare(pair) + assert not result['ok'] and 'cluster_info catalog' in result['error'] + + +def test_native_blank_source_column_can_retain_retired_rows(contract_pair): + pair = contract_pair + path = pair.ordinary / 'cluster_empty.tsv' + shutil.copyfile(pair.source / path.name, path) + result = _compare(pair) + assert result['ok'], result + assert any( + a['policy'] == 'byte-pinned blank source column' + for a in result['file_contract']['ordinary_aliases'] + ) + path.write_text(path.read_text().replace('0\t\n', '0\tforged\n')) + assert not _compare(pair)['ok'] + + +def test_membership_can_introduce_implicit_unreviewed_group(tmp_path): + pair = _pair(tmp_path, unclassified=True) + result = _compare(pair) + assert result['ok'], result.get('error', result) + assert _inventory(pair.source) == pair.original + + +@pytest.mark.parametrize('corruption', ['metadata', 'extra_payload', 'single_parent']) +def test_source_only_rejects_invalid_membership_journal(contract_pair, corruption): + pair = contract_pair + journal_path = pair.right / '_phy_curation_journal.json' + lineage_path = pair.right / '_phy_curation_lineage.json' + journal = json.loads(journal_path.read_text()) + lineage = json.loads(lineage_path.read_text()) + if corruption == 'metadata': + journal[0]['metadata']['snr'] = 'forged producer metadata' + elif corruption == 'extra_payload': + journal[0]['unexplained'] = True + else: + journal[0]['parents'] = [0] + lineage['metadata_provenance']['history'][0]['parents'] = [0] + journal_path.write_text(json.dumps(journal) + '\n') + lineage['journal_sha256'] = _journal_hash(journal) + lineage_path.write_text(json.dumps(lineage) + '\n') + report = comparison.compare_outputs( + pair.ordinary, + pair.right, + source=pair.source, + expected_labels=pair.expected, + chunk_size=2, + ) + assert not report['ok'] + expected = { + 'metadata': 'clearing policy', + 'extra_payload': 'event schema', + 'single_parent': 'parent cardinality', + } + assert expected[corruption] in report['error'], report + + +@pytest.mark.parametrize( + 'key,value', + [ + ('operator', '=='), + ('attribute', 'spike_depths.npy'), + ('threshold', True), + ('nonfinite', 'drop'), + ], +) +def test_source_only_rejects_invalid_threshold_predicate(tmp_path, key, value): + pair = _pair(tmp_path, split=True) + assert _compare(pair)['ok'] + path = pair.right / '_phy_curation_journal.json' + journal = json.loads(path.read_text()) + journal[1]['predicate'][key] = value + path.write_text(json.dumps(journal) + '\n') + lineage_path = pair.right / '_phy_curation_lineage.json' + lineage = json.loads(lineage_path.read_text()) + lineage['journal_sha256'] = _journal_hash(journal) + lineage['metadata_provenance']['history'][1]['predicate'][key] = value + lineage_path.write_text(json.dumps(lineage) + '\n') + result = comparison.compare_outputs( + pair.ordinary, + pair.right, + source=pair.source, + expected_labels=pair.expected, + chunk_size=2, + ) + assert not result['ok'] and 'predicate schema' in result['error'], result + assert _inventory(pair.source) == pair.original + + +def test_native_transformed_producer_difference_is_ancestry_bounded(contract_pair): + pair = contract_pair + path = pair.ordinary / 'cluster_snr.tsv' + with path.open(newline='') as stream: + rows = list(csv.reader(stream, delimiter='\t')) + rows = [row for row in rows if row[0] != '100'] + rows.append(['100', '12']) # A real source parent's metric, not a new measurement. + with path.open('w', newline='') as stream: + csv.writer(stream, delimiter='\t').writerows(rows) + result = _compare(pair) + assert result['ok'], result + assert any( + d['field'] == 'snr' and d['right_id'] == 100 and d['left'] == '12' and d['right'] == '' + for d in result['permitted_membership_policy_differences'] + ) + rows[-1] = ['100', '999'] + with path.open('w', newline='') as stream: + csv.writer(stream, delimiter='\t').writerows(rows) + result = _compare(pair) + assert not result['ok'] and 'unsupported ancestor value' in result['error'] + + +@pytest.mark.parametrize('role', ['ordinary', 'replay']) +def test_gui_provenance_history_is_an_ordinary_auxiliary_file(contract_pair, role): + pair = contract_pair + directory = pair.ordinary if role == 'ordinary' else pair.right + _append_curation_save(directory, _new_session()) + history = directory / 'phy_curation_history.jsonl' + original_history = history.read_bytes() + result = _compare(pair) + if role == 'ordinary': + assert result['ok'], result + else: + assert not result['ok'] + assert 'Unexpected replay files' in result['error'] + assert history.read_bytes() == original_history + assert _inventory(pair.source) == pair.original diff --git a/phy/apps/large_recording/tests/test_parameters.py b/phy/apps/large_recording/tests/test_parameters.py new file mode 100644 index 000000000..68db02648 --- /dev/null +++ b/phy/apps/large_recording/tests/test_parameters.py @@ -0,0 +1,145 @@ +"""Replay parameters retain Python semantics and stop accumulating overrides.""" + +import ast + +import pytest + +from phy.apps.large_recording.parameters import ( + BEGIN, + END, + rewrite_replay_params, + rewrite_replay_params_bytes, +) + +VALUES = {'num_samples': 20, 'valid_intervals': [[0, 8], [10, 20]], 'dat_path': None} + + +@pytest.mark.parametrize('ending', ['', '\n', '\r\n']) +def test_managed_parameters_are_idempotent_and_keep_user_source(ending): + original = '# User comment\nimport pathlib\nnum_samples = 7\n' + original += 'derived = num_samples * 2\nvalid_intervals = [[0, 7]]\n' + original += 'alias = dat_path = "relative.bin"' + ending + rewritten = rewrite_replay_params(original, **VALUES) + assert rewritten.startswith(original) + for _ in range(3): + assert rewrite_replay_params(rewritten, **VALUES) == rewritten + namespace = {} + exec(rewritten, namespace) + assert namespace['derived'] == 14 and namespace['alias'] == 'relative.bin' + assert {key: namespace[key] for key in VALUES} == VALUES + assert rewritten.count(BEGIN) == rewritten.count(END) == 1 + + +def test_legacy_literal_suffixes_collapse_without_deleting_originals(): + original = "num_samples = 20\nvalid_intervals = [[0, 8], [10, 20]]\ndat_path = r'None'\n" + legacy = original + ( + "\nnum_samples = 20\nvalid_intervals = [[0, 8], [10, 20]]\ndat_path = 'None'\n" * 3 + ) + values = dict(VALUES, dat_path='None') + rewritten = rewrite_replay_params(legacy, **values) + assert rewritten.startswith(original) + assert len(rewritten) < len(legacy) + assert rewrite_replay_params(rewritten, **VALUES) == rewritten + assert 'dat_path = None' in rewritten + assert ( + sum( + isinstance(node, ast.Assign) + and isinstance(node.targets[0], ast.Name) + and node.targets[0].id == 'num_samples' + for node in ast.parse(rewritten).body + ) + == 2 + ) + + +def test_nonliteral_chained_conditional_and_commented_assignments_remain(): + original = 'num_samples = 10 + 10\nvalid_intervals = [[0, 20]]\ndat_path = None\n' + original += 'if True:\n num_samples = 19\n' + original += "num_samples = valid_intervals = dat_path = 'keep'\n" + original += 'num_samples = 20 # user annotation\nvalid_intervals = [[0, 8], [10, 20]]\ndat_path = None\n' + assert rewrite_replay_params(original, **VALUES).startswith(original) + + +@pytest.mark.parametrize( + 'source', + [ + BEGIN + '\nnum_samples = 1\n', + END + '\n' + BEGIN + '\n', + BEGIN + '\nprint("keep")\n' + END + '\n', + BEGIN + + '\nnum_samples = 20\nvalid_intervals = []\ndat_path = None\n' + + END + + '\nprint("keep")\n', + ], +) +def test_malformed_or_modified_managed_blocks_fail_without_deleting_code(source): + with pytest.raises(ValueError): + rewrite_replay_params(source, **VALUES) + + +def test_marker_strings_and_quoted_paths_are_safe(): + source = f'documentation = """\n{BEGIN}\n{END}\n"""\n' + path = "a'quote\\folder/\u00e9lectrode.bin" + result = rewrite_replay_params(source, **dict(VALUES, dat_path=path)) + assert result.startswith(source) + namespace = {} + exec(result, namespace) + assert namespace['dat_path'] == path + + +def test_crlf_prefix_is_preserved_byte_for_byte(): + original = '# \u00e9lectrode\r\nnum_samples = 7\r\nderived = num_samples * 2\r\n' + result = rewrite_replay_params(original, **VALUES) + assert result.startswith(original) + assert '\n' not in result.replace('\r\n', '') + assert rewrite_replay_params(result, **VALUES) == result + + +@pytest.mark.parametrize('encoding', ['utf-8-sig', 'cp1252']) +def test_python_encoding_and_bom_survive_with_unicode_generated_paths(encoding): + text = f'# coding: {encoding}\r\n# \u00e9lectrode\r\nnum_samples = 7\r\n' + original = text.encode(encoding) + values = dict(VALUES, dat_path='\u00e9lectrode/\u4e2d\u6587.bin') + result = rewrite_replay_params_bytes(original, **values) + assert result.startswith(original) + assert rewrite_replay_params_bytes(result, **values) == result + namespace = {} + exec(result, namespace) + assert namespace['dat_path'] == values['dat_path'] + + +def test_three_replay_rounds_preserve_crlf_and_stable_file_size(tmp_path): + from phy.apps.large_recording.curation import BoundedSession + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.replay import apply_curation + from phy.apps.large_recording.tests.test_curation import make_session + + source, session = make_session(tmp_path) + params = source.params_path + original = params.read_text().replace('\n', '\r\n').encode('utf8') + params.write_bytes(original) + source.close() + session.save() + sizes = [] + for index in range(3): + output = apply_curation(params, session.path, tmp_path / f'output-{index}') + session.close() + params = output / 'params.py' + content = params.read_bytes() + assert content.startswith(original) + assert content.count(BEGIN.encode()) == 1 + assert b'\n' not in content.replace(b'\r\n', b'') + sizes.append(len(content)) + if index < 2: + bounded = prepare_large( + params, + tmp_path / f'bounded-{index}', + window_seconds=20, + stratum_seconds=20, + max_spikes=100, + bin_seconds=5, + batch_size=2, + ) + session = BoundedSession(bounded) + session.save() + assert len(set(sizes)) == 1 diff --git a/phy/apps/large_recording/tests/test_prepare.py b/phy/apps/large_recording/tests/test_prepare.py new file mode 100644 index 000000000..732547faf --- /dev/null +++ b/phy/apps/large_recording/tests/test_prepare.py @@ -0,0 +1,250 @@ +"""Production bounded preparation: budgets, rows, waveforms, and publication.""" + +import json + +import numpy as np +import pytest +from phylib.io.model import load_model + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.source import PER_SPIKE, hash_file +from phy.apps.large_recording.tests.test_source import make_sorting + + +@pytest.mark.parametrize('channel_map', [[0, 1, 2], [2, 0, 1]]) +def test_prepare_exact_arrays_waveforms_and_source_unchanged(tmp_path, channel_map): + params = make_sorting(tmp_path / 'full', columns=True) + np.save(params.parent / 'channel_map.npy', np.asarray(channel_map, dtype=np.int32)) + before = {p.name: hash_file(p) for p in params.parent.iterdir()} + output = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=8, + window_seconds=3, + stratum_seconds=20, + seed=0, + bin_seconds=5, + batch_size=2, + ) + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + windows = np.load(output / manifest['windows_file']) + samples = np.load(params.parent / 'spike_times.npy').reshape(-1) + expected_ids = np.array( + [ + index + for index, sample in enumerate(samples) + if any(start <= sample < end for start, end in windows) + ], + dtype=np.int64, + ) + global_ids = np.load(output / manifest['global_spike_ids_file']) + np.testing.assert_array_equal(global_ids, expected_ids) + assert len(global_ids) <= 8 + for name in PER_SPIKE: + if (params.parent / name).exists(): + np.testing.assert_array_equal( + np.load(output / name), np.load(params.parent / name)[expected_ids] + ) + source_waveform_ids = np.load(params.parent / '_phy_spikes_subset.spikes.npy') + expected_waveform_rows = [ + row for row, spike in enumerate(source_waveform_ids) if spike in expected_ids + ] + np.testing.assert_array_equal( + global_ids[np.load(output / '_phy_spikes_subset.spikes.npy')], + source_waveform_ids[expected_waveform_rows], + ) + for suffix in ('channels', 'waveforms'): + np.testing.assert_array_equal( + np.load(output / f'_phy_spikes_subset.{suffix}.npy'), + np.load(params.parent / f'_phy_spikes_subset.{suffix}.npy')[expected_waveform_rows], + ) + assert before == {p.name: hash_file(p) for p in params.parent.iterdir()} + assert 'dat_path = None' in (output / 'params.py').read_text() + assert manifest['next_cluster_id'] == 100 + assert sum(manifest['counts']) == len(samples) + assert sum(manifest['bounded_counts']) == len(global_ids) + model = load_model(output / 'params.py') + try: + ids = np.load(output / '_phy_spikes_subset.spikes.npy') + channels = np.load(output / '_phy_spikes_subset.channels.npy') + sparse = np.load(output / '_phy_spikes_subset.waveforms.npy') + expected = np.zeros((len(ids), 8, 3), dtype=np.float32) + for row, slots in enumerate(channels): + for slot, channel in enumerate(slots): + if channel >= 0: + expected[row, :, channel] = sparse[row, :, slot] + np.testing.assert_array_equal(model.get_waveforms(ids, channel_ids=[0, 1, 2]), expected) + finally: + model.close() + + +def test_deterministic_budgets_and_zero_evidence_catalog(tmp_path): + params = make_sorting(tmp_path / 'full') + outputs = [ + prepare_large( + params, + tmp_path / name, + max_spikes=5, + window_seconds=3, + stratum_seconds=20, + seed=0, + bin_seconds=5, + batch_size=2, + ) + for name in ('one', 'two') + ] + manifests = [ + json.loads((path / '_phy_curation_manifest.json').read_text()) for path in outputs + ] + assert manifests[0] == manifests[1] + assert manifests[0]['unit_ids'][-1] == 99 + assert manifests[0]['bounded_counts'][-1] == 0 + assert manifests[0]['omitted_windows'] + for path in outputs: + ids = np.load(path / '_phy_spike_global_ids.npy') + times = np.load(path / 'spike_times.npy') + assert len(ids) <= 5 + # All three tied samples at 1 retain their separate source identities. + assert np.count_nonzero(times == 1) == 2 + + +def test_rejected_budget_or_interrupted_publication_leaves_no_output(tmp_path, monkeypatch): + params = make_sorting(tmp_path / 'full') + with pytest.raises(ValueError, match='No bounded evidence'): + prepare_large( + params, tmp_path / 'empty', max_spikes=1, window_seconds=3, stratum_seconds=20, seed=0 + ) + with pytest.raises(ValueError, match='Output budget'): + prepare_large(params, tmp_path / 'too-big', max_bytes=10) + import phy.apps.large_recording.prepare as module + + def fail(*args, **kwargs): + raise OSError('simulated interruption') + + monkeypatch.setattr(module, 'build_summaries', fail) + with pytest.raises(OSError, match='interruption'): + prepare_large(params, tmp_path / 'interrupted', window_seconds=20, stratum_seconds=20) + assert not (tmp_path / 'interrupted').exists() + assert not list(tmp_path.glob('.interrupted.prepare-*')) + + +def test_prepare_missing_waveforms_is_explicit(tmp_path): + params = make_sorting(tmp_path / 'full') + for path in params.parent.glob('_phy_spikes_subset.*.npy'): + path.unlink() + output = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + assert not manifest['capabilities']['stored_waveforms'] + assert not (output / '_phy_spikes_subset.waveforms.npy').exists() + + +def test_spikeinterface_singular_sparse_template_indices(tmp_path): + params = make_sorting(tmp_path / 'full') + templates = np.load(params.parent / 'templates.npy')[:, :, :2] + templates[1, :, 1] = 0 + np.save(params.parent / 'templates.npy', templates) + indices = np.array([[0, 2], [1, -1], [2, 0]], dtype=np.int32) + np.save(params.parent / 'template_ind.npy', indices) + output = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + model = load_model(output / 'params.py') + try: + np.testing.assert_array_equal(model.sparse_templates.cols, indices) + finally: + model.close() + + +def test_adjacent_acquisition_blocks_retain_observation_boundaries(tmp_path): + params = make_sorting(tmp_path / 'full') + output = prepare_large( + params, + tmp_path / 'bounded', + valid_intervals=[[0, 10], [10, 20]], + window_seconds=10, + stratum_seconds=10, + ) + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + np.testing.assert_array_equal(np.load(output / manifest['windows_file']), [[0, 10], [10, 20]]) + assert manifest['windows'][0]['block'] != manifest['windows'][1]['block'] + + +def test_disk_preflight_rejects_before_writing_package(tmp_path, monkeypatch): + from types import SimpleNamespace + + from phy.apps.large_recording import prepare + + params = make_sorting(tmp_path / 'full') + monkeypatch.setattr(prepare.shutil, 'disk_usage', lambda path: SimpleNamespace(free=0)) + with pytest.raises(OSError, match='Insufficient disk'): + prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + assert not (tmp_path / 'bounded').exists() + assert not list(tmp_path.glob('.bounded.prepare-*')) + + +def test_final_windows_records_match_retained_samples_and_gaps(tmp_path): + params = make_sorting(tmp_path / 'full') + output = prepare_large( + params, + tmp_path / 'bounded', + valid_intervals=[[0, 7], [10, 20]], + window_seconds=5, + stratum_seconds=20, + bin_seconds=5, + ) + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + intervals = np.load(output / manifest['windows_file']) + assert [[row['start'], row['end']] for row in manifest['windows']] == intervals.tolist() + for row in manifest['windows']: + start, end = row['start'], row['end'] + assert any(first <= start and end <= last for first, last in [[0, 7], [10, 20]]) + assert row['exposure_seconds'] == end - start + assert manifest['capabilities']['predicate_split_attributes'] == ['amplitudes.npy'] + + +def test_prepare_protects_loader_and_preserves_producer_documents(tmp_path): + params = make_sorting(tmp_path / 'full') + (params.parent / 'curation.json').write_text( + json.dumps({'format_version': '2', 'unit_ids': [0, 1], 'merges': [{'unit_ids': [0, 1]}]}) + ) + (params.parent / 'curation_review.json').write_text( + json.dumps( + { + 'format_version': '1', + 'source': { + 'filename': 'curation.json', + 'sha256': hash_file(params.parent / 'curation.json'), + }, + 'reviews': {}, + } + ) + ) + output = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + manifest = json.loads((output / '_phy_curation_manifest.json').read_text()) + assert manifest['bounded_files']['params.py'] == hash_file(output / 'params.py') + assert manifest['bounded_files']['_phy_cluster_metadata.json'] == hash_file( + output / '_phy_cluster_metadata.json' + ) + for name in ('curation.json', 'curation_review.json'): + assert (output / name).read_bytes() == (params.parent / name).read_bytes() + assert name not in manifest['excluded_files'] + + +def test_cancel_after_final_validation_prevents_publication(tmp_path, monkeypatch): + from concurrent.futures import CancelledError + + from phy.apps.large_recording.curation import BoundedSession + + params = make_sorting(tmp_path / 'source') + original_close = BoundedSession.close + stopped = False + + def close_and_cancel(session): + nonlocal stopped + original_close(session) + stopped = True + + monkeypatch.setattr(BoundedSession, 'close', close_and_cancel) + output = tmp_path / 'cancelled' + with pytest.raises(CancelledError): + prepare_large(params, output, window_seconds=3, stratum_seconds=20, cancel=lambda: stopped) + assert not output.exists() + assert not list(tmp_path.glob('.cancelled-*')) diff --git a/phy/apps/large_recording/tests/test_producer_windows.py b/phy/apps/large_recording/tests/test_producer_windows.py new file mode 100644 index 000000000..9c071d5e1 --- /dev/null +++ b/phy/apps/large_recording/tests/test_producer_windows.py @@ -0,0 +1,177 @@ +"""Producer plans retain complete windows and preserve sparse waveform row alignment.""" + +import json + +import numpy as np +import pytest + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.tests.test_source import make_sorting + +STEM = '_phy_spikes_subset.' + + +def producer_sorting(path): + params = make_sorting(path) + bounds = np.array([[0, 3], [5, 7], [10, 12], [14, 15], [18, 20]]) + np.save(path / (STEM + 'window_bounds.npy'), bounds) + np.save(path / (STEM + 'window_types.npy'), np.zeros(5, dtype=np.uint8)) + np.save(path / (STEM + 'window_strata.npy'), np.arange(5, dtype=np.int32)) + return params + + +def read_manifest(path): + return json.loads((path / '_phy_curation_manifest.json').read_text()) + + +def test_auto_prefers_producer_and_exact_waveform_remapping(tmp_path): + params = producer_sorting(tmp_path / 'source') + output = prepare_large(params, tmp_path / 'bounded', window_policy='producer', batch_size=2) + manifest = read_manifest(output) + assert manifest['selection']['resolved_window_policy'] == 'producer' + assert manifest['waveform_coverage'] == { + 'source_rows': 5, + 'retained_rows': 5, + 'dropped_rows': 0, + } + np.testing.assert_array_equal( + np.load(output / manifest['windows_file']), + np.load(params.parent / (STEM + 'window_bounds.npy')), + ) + ids = np.load(output / manifest['global_spike_ids_file']) + upstream_ids = np.load(params.parent / (STEM + 'spikes.npy')) + np.testing.assert_array_equal(ids[np.load(output / (STEM + 'spikes.npy'))], upstream_ids) + for suffix in ('waveforms.npy', 'channels.npy'): + np.testing.assert_array_equal( + np.load(output / (STEM + suffix)), np.load(params.parent / (STEM + suffix)) + ) + assert manifest['producer_window_plan']['sha256'] + assert manifest['producer_window_estimate']['spikes'] == 12 + auto = prepare_large(params, tmp_path / 'auto') + assert read_manifest(auto)['selection']['resolved_window_policy'] == 'producer' + + +def test_budget_distributes_complete_windows_across_recording(tmp_path): + params = producer_sorting(tmp_path / 'source') + output = prepare_large(params, tmp_path / 'bounded', window_policy='producer', max_spikes=7) + manifest = read_manifest(output) + # Dyadic traversal takes the first and last windows before exhausting budget. + assert manifest['bounded_num_spikes'] == 7 + assert [(r['start'], r['end']) for r in manifest['accepted_window_candidates']] == [ + (0, 3), + (18, 20), + ] + assert manifest['omitted_windows'] + assert all(r['reason'] == 'spike_budget' for r in manifest['omitted_windows']) + assert manifest['waveform_coverage']['dropped_rows'] > 0 + + +def test_generated_override_and_missing_producer(tmp_path): + params = producer_sorting(tmp_path / 'source') + output = prepare_large( + params, + tmp_path / 'bounded', + window_policy='generated', + window_seconds=20, + stratum_seconds=20, + ) + assert read_manifest(output)['selection']['resolved_window_policy'] == 'generated' + params = make_sorting(tmp_path / 'legacy') + with pytest.raises(ValueError, match='requires nonempty'): + prepare_large(params, tmp_path / 'missing', window_policy='producer') + with pytest.raises(ValueError, match='window_policy'): + prepare_large(params, tmp_path / 'bad', window_policy='invalid') + + +@pytest.mark.parametrize( + 'name,value,match', + [ + ('window_bounds.npy', np.array([0, 3]), 'integer'), + ('window_bounds.npy', np.array([[0.0, 3.0]]), 'integer'), + ('window_bounds.npy', np.array([[3, 2]]), 'bounds'), + ('window_bounds.npy', np.array([[0, 21]]), 'bounds'), + ('window_bounds.npy', np.array([[5, 6], [0, 3]]), 'sorted'), + ('window_types.npy', np.zeros(4, dtype=np.uint8), 'aligned'), + ('window_types.npy', np.full(5, 2, dtype=np.uint8), 'codes'), + ('window_strata.npy', np.full(5, -2), 'strata'), + ], +) +def test_invalid_sidecars_rejected_even_for_generated(tmp_path, name, value, match): + params = producer_sorting(tmp_path / 'source') + np.save(params.parent / (STEM + name), value) + if name == 'window_bounds.npy': + for suffix in ('window_types.npy', 'window_strata.npy'): + (params.parent / (STEM + suffix)).unlink() + with pytest.raises(ValueError, match=match): + prepare_large(params, tmp_path / 'bounded', window_policy='generated') + + +@pytest.mark.parametrize('intervals', [[[0, 10], [10, 20]], [[0, 9], [10, 20]]]) +def test_producer_window_cannot_cross_block_or_gap(tmp_path, intervals): + params = producer_sorting(tmp_path / 'source') + with params.open('a') as stream: + stream.write(f'valid_intervals = {intervals!r}\n') + np.save(params.parent / (STEM + 'window_bounds.npy'), np.array([[0, 11]])) + for suffix in ('window_types.npy', 'window_strata.npy'): + (params.parent / (STEM + suffix)).unlink() + with pytest.raises(ValueError, match='block|gap'): + prepare_large(params, tmp_path / 'bounded') + + +def test_overlaps_union_without_duplicate_spikes(tmp_path): + params = producer_sorting(tmp_path / 'source') + np.save(params.parent / (STEM + 'window_bounds.npy'), np.array([[0, 12], [10, 20]])) + for suffix in ('window_types.npy', 'window_strata.npy'): + (params.parent / (STEM + suffix)).unlink() + output = prepare_large(params, tmp_path / 'bounded', window_policy='producer') + manifest = read_manifest(output) + assert manifest['bounded_num_spikes'] == 12 + np.testing.assert_array_equal(np.load(output / manifest['windows_file']), [[0, 20]]) + + +@pytest.mark.parametrize('policy', ['auto', 'producer', 'generated']) +def test_waveforms_outside_producer_windows_rejected(tmp_path, policy): + params = producer_sorting(tmp_path / 'source') + np.save(params.parent / (STEM + 'window_bounds.npy'), np.array([[0, 3]])) + for suffix in ('window_types.npy', 'window_strata.npy'): + (params.parent / (STEM + suffix)).unlink() + with pytest.raises(ValueError, match='outside'): + prepare_large(params, tmp_path / 'bounded', window_policy=policy) + + +def test_legacy_acquisition_coordinate_declaration(tmp_path): + params = producer_sorting(tmp_path / 'source') + (params.parent / (STEM + 'manifest.json')).write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': {'window_bounds_coordinates': 'acquisition_samples'}, + } + ) + ) + output = prepare_large(params, tmp_path / 'bounded', window_policy='producer') + assert read_manifest(output)['waveform_coverage']['retained_rows'] == 5 + + +def test_wrong_window_coordinates_rejected_for_generated(tmp_path): + params = producer_sorting(tmp_path / 'source') + (params.parent / (STEM + 'manifest.json')).write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': {'window_bounds_coordinates': 'elapsed_ticks'}, + } + ) + ) + with pytest.raises(ValueError, match='coordinates|time_base'): + prepare_large(params, tmp_path / 'bounded', window_policy='generated') + + +def test_producer_policy_requires_waveform_triplet(tmp_path): + params = producer_sorting(tmp_path / 'source') + for suffix in ('spikes.npy', 'channels.npy', 'waveforms.npy'): + (params.parent / (STEM + suffix)).unlink() + with pytest.raises(ValueError, match='requires nonempty'): + prepare_large(params, tmp_path / 'bounded', window_policy='producer') diff --git a/phy/apps/large_recording/tests/test_proposition_labels.py b/phy/apps/large_recording/tests/test_proposition_labels.py new file mode 100644 index 000000000..606c1751a --- /dev/null +++ b/phy/apps/large_recording/tests/test_proposition_labels.py @@ -0,0 +1,179 @@ +"""SLAY annotations alter only sampled correlogram labels, with explicit overlaps.""" + +import numpy as np +from phylib.utils import emit + +from phy.apps.large_recording.views import SampledCorrelogramView +from phy.cluster._proposition_annotations import WHITE, proposition_label_color +from phy.cluster._propositions import decode_curation_mapping +from phy.gui import GUI + +from .test_adapter import make_controller + + +def _mapping(groups): + return { + 'format_version': '2', + 'unit_ids': list(dict.fromkeys(unit for group in groups for unit in group)), + 'merges': [{'unit_ids': group} for group in groups], + } + + +def _provider(ids, bin_size, window_size): + n = len(ids) + return np.ones((n, n, 5), dtype=np.int64), np.zeros((n, n)) + + +def test_pdf_axis_colors_legend_overlap_and_label_only_refresh(qtbot, tmp_path): + catalog = decode_curation_mapping(_mapping([[449, 461, 466, 467, 469], [479, 491, 498]])) + keys = tuple(p.key for p in catalog.propositions) + context = [catalog, keys[:1], keys] + calls = [] + + def provider(*args): + calls.append(args) + return _provider(*args) + + gui = GUI(config_dir=tmp_path / 'config') + qtbot.addWidget(gui) + view = SampledCorrelogramView( + correlograms=provider, proposition_context=lambda: tuple(context), sample_rate=30000 + ) + try: + view.attach(gui) + with qtbot.waitExposed(gui): + gui.show() + view.on_select(cluster_ids=[449, 461, 466, 467, 469, 479, 491, 498, 511]) + texts = view.text_visual._acc.text + assert texts == [str(unit) for unit in view.cluster_ids for _ in range(2)] + expected = [proposition_label_color(0)] * 5 + [proposition_label_color(1)] * 3 + [WHITE] + np.testing.assert_allclose(view.text_visual._acc.color, np.repeat(expected, 2, axis=0)) + assert 'P1 (active)' in view.proposition_legend.text() + assert 'P2' in view.proposition_legend.text() + assert 'pending now' in view.proposition_legend.toolTip() + histogram = view.correlogram_visual._acc.hist.copy() + colors = view.correlogram_visual._acc.color.copy() + # Filtering/sorting tables affects neither membership nor label slots. + context[2] = keys[:1] + view.refresh_proposition_labels() + assert len(calls) == 1 + assert 'hidden by proposition filter' in view.proposition_legend.toolTip() + np.testing.assert_allclose(view.text_visual._acc.color, np.repeat(expected, 2, axis=0)) + # A review-only update invalidates the red label group without rebinning. + context[0] = catalog.reject(keys[1]) + view.refresh_proposition_labels() + assert len(calls) == 1 + assert view._proposition_labels.annotations[479].color == WHITE + np.testing.assert_array_equal(view.correlogram_visual._acc.hist, histogram) + np.testing.assert_array_equal(view.correlogram_visual._acc.color, colors) + # An overlapping source proposition adds a marker to both axis labels. + context[0] = decode_curation_mapping( + _mapping([[449, 461, 466, 467, 469], [479, 491, 498], [449, 479]]) + ) + view.refresh_proposition_labels() + assert texts != view.text_visual._acc.text + assert view.text_visual._acc.text[:2] == ['449*', '449*'] + assert '449*: P1, P3' in view.proposition_legend.toolTip() + assert '* multiple groups' in view.proposition_legend.text() + assert len(calls) == 1 + # Hidden views adopt only the latest small annotation snapshot and + # upload its labels when shown, without recomputing the histogram. + view.dock.hide() + qtbot.waitUntil(lambda: not view._dock_visible) + context[0] = catalog.reject(keys[1]) + view.refresh_proposition_labels() + assert view._proposition_labels_pending + view.dock.show() + qtbot.waitUntil(lambda: not view._proposition_labels_pending) + np.testing.assert_array_equal(view.text_visual._acc.color[10:16], np.ones((6, 4))) + assert len(calls) == 1 + view.toggle_labels(False) + assert view.text_visual._hidden + view.toggle_labels(True) + assert not view.text_visual._hidden + finally: + gui.close() + + +def test_bounded_catalog_updates_reviews_undo_and_cleanup(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path, propositions=_mapping([[0, 1], [1, 2]])) + gui = controller.create_gui(default_views=['SampledCorrelogramView'], do_prompt_save=False) + qtbot.addWidget(gui) + supervisor = controller.supervisor + view = gui.get_view('SampledCorrelogramView') + keys = tuple(p.key for p in supervisor.merge_propositions.catalog.propositions) + try: + with qtbot.waitExposed(gui): + gui.show() + supervisor._activate_merge_proposition(supervisor.merge_propositions_view, keys[0]) + supervisor.block() + # The blue label group is independent of trace slot/reference identity. + assert view._proposition_labels.annotations[1].color == proposition_label_color(0) + assert supervisor.selection_color_indices[0] == 0 + assert supervisor.selection_color_indices[1] != 0 + before = dict(supervisor.selection_color_indices) + supervisor._refresh_propositions() + assert dict(supervisor.selection_color_indices) == before + assert view._proposition_labels.annotations[1].text == '1*' + supervisor.reject_merge_proposition() + supervisor.block() + assert [group.key for group in view._proposition_labels.groups] == [keys[1]] + supervisor.undo() + supervisor.block() + assert view._proposition_labels.annotations[1].text == '1*' + assert view._proposition_labels.groups[0].key == keys[0] + supervisor.redo() + supervisor.block() + supervisor._reset_merge_proposition(supervisor.merge_propositions_view, keys[0]) + supervisor.block() + assert view._proposition_labels.groups[0].key == keys[0] + assert view._proposition_labels.annotations[1].text == '1*' + + supervisor._activate_merge_propositions(supervisor.merge_propositions_view, keys) + supervisor.block() + assert view._proposition_labels.annotations[2].color == proposition_label_color(1) + supervisor._activate_merge_proposition(supervisor.merge_propositions_view, keys[0]) + supervisor.block() + # Merged descendants never inherit pending source membership. + target = supervisor.merge().added[0] + supervisor.block() + assert not view._proposition_labels.annotations[target].groups + supervisor.undo() + supervisor.block() + assert view._proposition_labels.annotations[1].text == '1*' + + # Review-only refreshes use the small text projection even for unchanged IDs. + def reject_count(*args, **kwargs): + raise AssertionError('A label-only notification must not recompute CCGs.') + + monkeypatch.setattr(view, 'exclusion_correlograms', reject_count) + supervisor._refresh_propositions() + table = supervisor.merge_propositions_view + table.filter("proposition == 'P1 · 0, 1'") + assert table.visible_keys() == (keys[0],) + assert 'P2: pending; hidden by proposition filter' in view.proposition_legend.toolTip() + table.filter('') + assert 'hidden by proposition filter' not in view.proposition_legend.toolTip() + table.sort_by('proposition', 'desc') + assert view._proposition_labels.groups[0].key == keys[0] + # The adapter subscription is removed when its view closes. + view.close() + monkeypatch.setattr(view, 'refresh_proposition_labels', reject_count) + emit('merge_propositions_changed', supervisor) + finally: + gui.close() + controller.close() + + +def test_missing_propositions_keep_original_labels_and_no_legend(qtbot, tmp_path): + gui = GUI(config_dir=tmp_path / 'config') + qtbot.addWidget(gui) + view = SampledCorrelogramView(correlograms=_provider, sample_rate=30000) + try: + view.attach(gui) + view.on_select(cluster_ids=[0, 1]) + assert view.proposition_legend is None + assert view.text_visual._acc.text == ['0', '0', '1', '1'] + np.testing.assert_array_equal(view.text_visual._acc.color, np.ones((4, 4))) + finally: + gui.close() diff --git a/phy/apps/large_recording/tests/test_proposition_persistence.py b/phy/apps/large_recording/tests/test_proposition_persistence.py new file mode 100644 index 000000000..09772dcd5 --- /dev/null +++ b/phy/apps/large_recording/tests/test_proposition_persistence.py @@ -0,0 +1,342 @@ +"""Producer bytes, durable decisions and retirement survive bounded replay rounds.""" + +import json +from pathlib import Path + +import pytest + +from phy.apps.large_recording.adapter import BoundedTemplateController +from phy.apps.large_recording.curation import BoundedSession, _digest +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import Source, hash_file +from phy.apps.large_recording.tests.test_adapter import make_gui_sorting +from phy.apps.template.gui import TemplateController +from phy.cluster._propositions import PropositionReview, encode_review_mapping, proposition_key + + +class PropositionsDisabledController(BoundedTemplateController): + enable_merge_propositions = False + + +def prepare(tmp_path): + params = make_gui_sorting(tmp_path / 'source') + producer = b'{"format_version":"2", "unit_ids":[0,1,2,99], "merges":[{"unit_ids":[0,1]},{"unit_ids":[1,2]}], "producer": {"unchanged":true}}\n' + (params.parent / 'curation.json').write_bytes(producer) + review = encode_review_mapping( + { + proposition_key([1, 2]): PropositionReview('rejected'), + proposition_key([77, 78]): PropositionReview('accepted', [77, 78], 90), + }, + source_sha256=hash_file(params.parent / 'curation.json'), + ) + (params.parent / 'curation_review.json').write_text(json.dumps(review)) + bounded = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + return params, bounded, producer, review + + +@pytest.mark.parametrize('mode', ['direct', 'enabled', 'disabled']) +def test_three_noop_rounds_preserve_exact_source_and_complete_ledger(tmp_path, mode): + params, bounded, producer, review = prepare(tmp_path) + original_reviews = review['reviews'] + for round_index in range(3): + if mode == 'direct': + session = BoundedSession(bounded) + session.save() + session.close() + else: + controller_class = ( + PropositionsDisabledController if mode == 'disabled' else TemplateController + ) + controller = controller_class( + dir_path=bounded, config_dir=tmp_path / 'config', plugins=[] + ) + try: + if mode == 'disabled': + assert controller.supervisor.merge_propositions is None + else: + assert controller.supervisor.merge_propositions is not None + controller.supervisor.save() + finally: + controller.close() + # A committed generation outranks every loose-root review state. + root_review = bounded / 'curation_review.json' + if round_index == 0: + root_review.write_text('{malformed') + elif round_index == 1: + root_review.write_text(json.dumps(dict(review, reviews={}))) + else: + root_review.unlink(missing_ok=True) + reopened = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + try: + assert ( + reopened.supervisor.merge_propositions.catalog.review_mapping()['reviews'] + == original_reviews + ) + finally: + reopened.close() + output = apply_curation(params, bounded, tmp_path / f'curated-{round_index}') + assert (output / 'curation.json').read_bytes() == producer + assert ( + json.loads((output / 'curation_review.json').read_text())['reviews'] + == original_reviews + ) + lineage = json.loads((output / '_phy_curation_lineage.json').read_text()) + assert lineage['proposition_documents'] == { + name: hash_file(output / name) for name in ('curation.json', 'curation_review.json') + } + params = output / 'params.py' + bounded = prepare_large( + params, tmp_path / f'bounded-{round_index}', window_seconds=20, stratum_seconds=20 + ) + + +def test_accepted_and_rejected_decisions_and_retirements_survive_replay(tmp_path): + params, bounded, producer, review = prepare(tmp_path) + controller = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + try: + supervisor = controller.supervisor + key = proposition_key([0, 1]) + supervisor.merge_propositions.accept(key, [0, 1], 100) + supervisor.merge([0, 1], to=100) + supervisor.save() + expected_reviews = supervisor.merge_propositions.catalog.review_mapping()['reviews'] + finally: + controller.close() + output = apply_curation(params, bounded, tmp_path / 'curated') + assert (output / 'curation.json').read_bytes() == producer + assert json.loads((output / 'curation_review.json').read_text())['reviews'] == expected_reviews + source = Source(output / 'params.py') + try: + assert source.retired_units == { + '0': {'operation': 'merge', 'replacements': [100]}, + '1': {'operation': 'merge', 'replacements': [100]}, + } + finally: + source.close() + second = prepare_large( + output / 'params.py', tmp_path / 'second', window_seconds=20, stratum_seconds=20 + ) + session = BoundedSession(second) + session.record_split( + 100, + 101, + 102, + {'attribute': 'amplitudes.npy', 'operator': '<', 'threshold': 4.0, 'nonfinite': 'keep'}, + ) + session.save() + session.close() + final = apply_curation(output / 'params.py', second, tmp_path / 'final') + lineage = json.loads((final / '_phy_curation_lineage.json').read_text()) + assert lineage['retired_units']['100'] == { + 'operation': 'threshold_split', + 'replacements': [102, 101], + } + assert lineage['retired_units']['0'] == {'operation': 'merge', 'replacements': [100]} + + +@pytest.mark.parametrize('target', ['curation.json', '_phy_curation_review_base.json']) +def test_mutation_after_load_rejects_save_and_replay(tmp_path, target): + params, bounded, _, _ = prepare(tmp_path) + session = BoundedSession(bounded) + session.save() + (bounded / target).write_text('{}') + try: + with pytest.raises(ValueError, match='changed'): + session.save() + with pytest.raises(ValueError, match='integrity'): + apply_curation(params, bounded, tmp_path / 'bad') + assert not (tmp_path / 'bad').exists() + finally: + session.close() + + +def test_generation_extra_document_requires_hash_inventory(tmp_path): + _, bounded, _, _ = prepare(tmp_path) + session = BoundedSession(bounded) + generation = session.save() + session.close() + descriptor = json.loads((generation / 'checkpoint.json').read_text()) + descriptor['files'].pop('curation_review.json') + (generation / 'checkpoint.json').write_text(json.dumps(descriptor)) + pointer = bounded / '.phy-curation/current.json' + data = json.loads(pointer.read_text()) + data['sha256'] = _digest(descriptor) + pointer.write_text(json.dumps(data)) + with pytest.raises(ValueError, match='hash inventory'): + BoundedSession(bounded) + + +@pytest.mark.parametrize('operation', ['prepare', 'replay']) +def test_copy_race_rejects_producer_mutation_without_publication(tmp_path, monkeypatch, operation): + from phy.apps.large_recording import prepare as preparation + from phy.apps.large_recording import replay + + params, bounded, _, _ = prepare(tmp_path) + session = BoundedSession(bounded) + session.save() + session.close() + if operation == 'prepare': + original_copy = preparation._copy_files + + def mutate_files(files, *args, **kwargs): + files = list(files) + result = original_copy(files, *args, **kwargs) + for _, destination in files: + if Path(destination).name == 'curation.json': + Path(destination).write_text('{}') + return result + + monkeypatch.setattr(preparation, '_copy_files', mutate_files) + else: + original_copy = replay.shutil.copyfile + + def mutate_copy(source, destination, *args, **kwargs): + result = original_copy(source, destination, *args, **kwargs) + if Path(destination).name == 'curation.json': + Path(destination).write_text('{}') + return result + + monkeypatch.setattr(replay.shutil, 'copyfile', mutate_copy) + output = tmp_path / 'bad' + with pytest.raises(ValueError, match='changed'): + if operation == 'prepare': + prepare_large(params, output, window_seconds=20, stratum_seconds=20) + else: + apply_curation(params, bounded, output) + assert not output.exists() + + +@pytest.mark.parametrize( + 'filename, digest', + [ + ('../curation.json', 'valid'), + ('other.json', 'valid'), + ('curation.json', None), + ('curation.json', '0' * 64), + ('curation.json', 'xyz'), + ], +) +def test_bounded_inherited_review_requires_exact_filename_and_hash(tmp_path, filename, digest): + params, _, _, review = prepare(tmp_path) + review['source']['filename'] = filename + if digest is None: + review['source'].pop('sha256') + elif digest != 'valid': + review['source']['sha256'] = digest + (params.parent / 'curation_review.json').write_text(json.dumps(review)) + with pytest.raises(ValueError, match='filename/hash'): + prepare_large(params, tmp_path / 'bad', window_seconds=20, stratum_seconds=20) + assert not (tmp_path / 'bad').exists() + + +def test_gui_save_rejects_producer_mutation_since_load(tmp_path): + _, bounded, _, _ = prepare(tmp_path) + controller = TemplateController(dir_path=bounded, config_dir=tmp_path / 'config', plugins=[]) + try: + (bounded / 'curation.json').write_text('{}') + with pytest.raises(ValueError, match='changed'): + controller.supervisor.save() + assert not (bounded / '.phy-curation/current.json').exists() + finally: + controller.close() + + +def test_replay_rejects_source_producer_mutation(tmp_path): + params, bounded, _, _ = prepare(tmp_path) + session = BoundedSession(bounded) + session.save() + session.close() + (params.parent / 'curation.json').write_text('{}') + with pytest.raises(ValueError, match='changed since preparation'): + apply_curation(params, bounded, tmp_path / 'bad') + assert not (tmp_path / 'bad').exists() + + +def test_legacy_bounded_propositions_require_repreparation(tmp_path): + _, bounded, _, _ = prepare(tmp_path) + path = bounded / '_phy_curation_manifest.json' + manifest = json.loads(path.read_text()) + manifest.pop('proposition_documents') + path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match='reprepare'): + BoundedSession(bounded) + + +def test_legacy_checkpoint_review_without_loose_root_requires_repreparation(tmp_path): + from phy.apps.large_recording.curation import _hash_file + from phy.apps.large_recording.tests.test_curation import make_session + + _, session = make_session(tmp_path) + generation = session.save(extra_documents={'supplemental.json': {}}) + session.close() + (generation / 'supplemental.json').rename(generation / 'curation_review.json') + descriptor_path = generation / 'checkpoint.json' + descriptor = json.loads(descriptor_path.read_text()) + descriptor['extra_documents'] = ['curation_review.json'] + descriptor['files'].pop('supplemental.json') + descriptor['files']['curation_review.json'] = _hash_file(generation / 'curation_review.json') + descriptor_path.write_text(json.dumps(descriptor)) + pointer_path = session.path / '.phy-curation/current.json' + pointer = json.loads(pointer_path.read_text()) + pointer['sha256'] = _digest(descriptor) + pointer_path.write_text(json.dumps(pointer)) + with pytest.raises(ValueError, match='reprepare'): + BoundedSession(session.path) + + +@pytest.mark.parametrize('mode', ['direct', 'disabled']) +def test_suggestions_without_reviews_publish_empty_bound_ledger(tmp_path, mode): + params, _, producer, _ = prepare(tmp_path) + (params.parent / 'curation_review.json').unlink() + bounded = prepare_large(params, tmp_path / 'empty', window_seconds=20, stratum_seconds=20) + if mode == 'direct': + session = BoundedSession(bounded) + session.save() + session.close() + else: + controller = PropositionsDisabledController( + dir_path=bounded, config_dir=tmp_path / 'config', plugins=[] + ) + try: + assert controller.supervisor.merge_propositions is None + controller.supervisor.save() + finally: + controller.close() + output = apply_curation(params, bounded, tmp_path / 'curated') + assert (output / 'curation.json').read_bytes() == producer + assert json.loads((output / 'curation_review.json').read_text()) == { + 'format_version': '1', + 'source': {'filename': 'curation.json', 'sha256': hash_file(output / 'curation.json')}, + 'reviews': {}, + } + + +def test_null_review_cannot_remove_inherited_decisions(tmp_path): + _, bounded, _, review = prepare(tmp_path) + session = BoundedSession(bounded) + try: + with pytest.raises(ValueError, match='ledger mapping'): + session.save(extra_documents={'curation_review.json': None}) + assert session.extra_documents['curation_review.json'] == review + assert not (bounded / '.phy-curation/current.json').exists() + finally: + session.close() + + +def test_committed_generation_cannot_omit_required_review_ledger(tmp_path): + _, bounded, _, _ = prepare(tmp_path) + session = BoundedSession(bounded) + generation = session.save() + session.close() + descriptor_path = generation / 'checkpoint.json' + descriptor = json.loads(descriptor_path.read_text()) + descriptor['extra_documents'] = [] + descriptor['files'].pop('curation_review.json') + descriptor_path.write_text(json.dumps(descriptor)) + pointer_path = bounded / '.phy-curation/current.json' + pointer = json.loads(pointer_path.read_text()) + pointer['sha256'] = _digest(descriptor) + pointer_path.write_text(json.dumps(pointer)) + with pytest.raises(ValueError, match='ledger mapping'): + BoundedSession(bounded) diff --git a/phy/apps/large_recording/tests/test_range_foundations.py b/phy/apps/large_recording/tests/test_range_foundations.py new file mode 100644 index 000000000..045b01c51 --- /dev/null +++ b/phy/apps/large_recording/tests/test_range_foundations.py @@ -0,0 +1,154 @@ +"""Selective authentication and exact interval/threshold semantics.""" + +import json +from pathlib import Path + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import evaluate_predicate, project_assignments +from phy.apps.large_recording.live_summaries import membership_expressions +from phy.apps.large_recording.range_files import ( + PAGE_BYTES, + PageCache, + VerifiedFile, + authenticate_file, +) +from phy.apps.large_recording.range_intervals import IntervalProgram +from phy.apps.large_recording.range_math import typed_rank +from phy.apps.large_recording.summary_store import StoreIntegrityError +from phy.apps.large_recording.tests.test_live_summaries import merge, split + + +@pytest.mark.parametrize('length', [0, 1, 64, 4096, 4097, 100000]) +def test_verified_random_reads_and_bounded_cache(tmp_path, length): + raw = np.random.default_rng(1).integers(0, 256, length, dtype=np.uint8).tobytes() + path = tmp_path / 'values.bin' + path.write_bytes(raw) + descriptor = authenticate_file(path) + cache = PageCache(2 * PAGE_BYTES) + reader = VerifiedFile(path, descriptor, cache) + try: + for start in range(0, length, 1137): + assert reader.read(start, min(777, length - start)) == raw[start : start + 777] + reader.unchanged() + assert cache.size <= cache.max_bytes + finally: + reader.close() + + +def test_corruption_is_selective_and_detected_before_use(tmp_path): + path = tmp_path / 'data.bin' + path.write_bytes(bytes(range(256)) * 1000) + descriptor = authenticate_file(path) + with path.open('r+b') as stream: + stream.seek(40 * PAGE_BYTES + 2) + stream.write(b'x') + reader = VerifiedFile(path, descriptor, PageCache(8192)) + try: + assert reader.read(0, 8) == bytes(range(8)) + assert reader.bytes_read == PAGE_BYTES # No whole-file integrity scan. + with pytest.raises(StoreIntegrityError, match='checksum'): + reader.read(40 * PAGE_BYTES, 16) + finally: + reader.close() + + +def test_changed_pinned_file_and_hash_tree_corruption(tmp_path): + path = tmp_path / 'data.bin' + path.write_bytes(b'a' * 10000) + descriptor = authenticate_file(path) + reader = VerifiedFile(path, descriptor, PageCache(8192)) + try: + with path.open('r+b') as stream: + stream.write(b'b') + with pytest.raises(StoreIntegrityError, match='changed'): + reader.unchanged() + finally: + reader.close() + authenticate_file(path) + hashes = path.with_suffix('.bin.hashes') + with hashes.open('r+b') as stream: + stream.seek(32) + stream.write(b'x' * 32) + with pytest.raises(StoreIntegrityError, match='root'): + VerifiedFile(path, descriptor, PageCache(8192)) + + +@pytest.mark.parametrize('dtype', ['float32', 'float64', 'int64', 'uint64']) +@pytest.mark.parametrize('operator', ['<', '<=']) +def test_rank_boundaries_match_canonical_array_comparisons(dtype, operator): + values = np.array([0, 1, 1, 2, 7], dtype=dtype) + if dtype in ('int64', 'uint64'): + values = np.r_[values, np.array([2**53, 2**53 + 1, 2**63 - 1], dtype=dtype)] + for threshold in [ + -1, + 0, + 1, + 1.000000001, + float(np.nextafter(np.float32(1), np.float32(2))), + 2**53, + float(2**53), + 1e30, + ]: + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': operator, + 'threshold': threshold, + 'nonfinite': 'keep', + } + assert typed_rank(values, predicate) == int(evaluate_predicate(values, predicate).sum()) + + +def test_interval_graph_matches_replay_for_nested_merges_and_all_comparators(): + original = np.repeat([0, 1, 2], 12) + amplitude = np.tile(np.array([-np.inf, -2, -0.0, 0.0, 1, 1, 2, 3, 4, 8, np.inf, np.nan]), 3) + for operator in ['<', '<=', '>', '>=']: + events = [ + split(0, [10, 11], threshold=2), + merge([10, 1], 12), + split(12, [13, 14], threshold=1), + ] + events[-1]['predicate']['operator'] = operator + expressions = membership_expressions([0, 1, 2], events) + program = IntervalProgram(expressions) + expected = project_assignments(original, events, {'amplitudes.npy': amplitude}) + for source in [0, 1, 2]: + rows = np.flatnonzero(original == source) + finite = rows[np.isfinite(amplitude[rows])] + finite = finite[np.argsort(amplitude[finite], kind='stable')] + nonfinite = rows[~np.isfinite(amplitude[rows])] + cuts = {key: typed_rank(amplitude[finite], pred) for key, pred in program.cuts.items()} + actual = program.evaluate(source, len(finite), len(nonfinite), cuts) + for unit, (parts, include_nonfinite) in actual.items(): + selected = [int(i) for lo, hi in parts for i in finite[lo:hi]] + if include_nonfinite: + selected.extend(nonfinite.tolist()) + assert ( + sorted(selected) + == np.flatnonzero((original == source) & (expected == unit)).tolist() + ) + + +def test_reject_obligation_survives_empty_descendant_and_unrelated_units(): + events = [ + split(0, [10, 11], threshold=2, nonfinite='reject'), + split(11, [12, 13], threshold=-999), + ] + expressions = membership_expressions([0, 1], events) + program = IntervalProgram({13: expressions[13]}) + cuts = dict.fromkeys(program.cuts, 0) + with pytest.raises(ValueError, match='Nonfinite'): + program.evaluate(0, 5, 1, cuts) + assert program.evaluate(1, 5, 1, cuts)[13] == ([], False) + + +def test_root_remains_anchor_after_node_cache_eviction(tmp_path): + path = tmp_path / 'data.bin' + path.write_bytes(b'a' * PAGE_BYTES + b'b' * PAGE_BYTES) + reader = VerifiedFile(path, authenticate_file(path), PageCache(4096)) + try: + reader.nodes.clear() + assert reader.read(PAGE_BYTES, 4) == b'bbbb' + finally: + reader.close() diff --git a/phy/apps/large_recording/tests/test_range_index.py b/phy/apps/large_recording/tests/test_range_index.py new file mode 100644 index 000000000..4430edbf5 --- /dev/null +++ b/phy/apps/large_recording/tests/test_range_index.py @@ -0,0 +1,291 @@ +"""Range acceleration is an exact optional optimization of full curation replay.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.live_summaries import LiveSummaryEngine, membership_expressions +from phy.apps.large_recording.range_build import build_amplitude_index +from phy.apps.large_recording.range_index import AmplitudeRangeIndex +from phy.apps.large_recording.summary_store import build_summary_store +from phy.apps.large_recording.tests.test_live_summaries import merge, oracle, package, split + + +@pytest.mark.parametrize('workers', [1, 3]) +@pytest.mark.parametrize('block_rows', [1, 2, 3, 128]) +@pytest.mark.parametrize('columns,positions', [(False, False), (True, True)]) +def test_range_queries_match_independent_full_replay( + tmp_path, block_rows, columns, positions, workers +): + source, bounded = package(tmp_path, columns, positions) + build_summary_store(bounded, tmp_path / 'store', batch_size=2) + build_amplitude_index(bounded, tmp_path / 'ranges', block_rows=block_rows, workers=workers) + with LiveSummaryEngine(bounded) as engine: + index = AmplitudeRangeIndex(engine) + try: + for operator in ['<', '<=', '>', '>=']: + events = [split(0, [10, 11]), merge([10, 1], 12), split(12, [13, 14], threshold=6)] + events[-1]['predicate']['operator'] = operator + expressions = membership_expressions([0, 1, 2, 99], events) + actual = index.resolve(expressions) + for unit, summary in actual.items(): + expected = oracle(source, engine, events, unit) + for name, values in engine._flat(summary).items(): + np.testing.assert_allclose( + values, engine._flat(expected)[name], rtol=1e-9, atol=1e-6 + ) + finally: + index.close() + + +def assert_summary(engine, actual, expected): + for name, values in engine._flat(actual).items(): + target = engine._flat(expected)[name] + if np.issubdtype(values.dtype, np.integer): + np.testing.assert_array_equal(values, target) + else: + np.testing.assert_allclose(values, target, rtol=1e-9, atol=1e-6) + + +@pytest.mark.parametrize('dtype', ['float32', 'float64', 'int64', 'uint64']) +def test_dtype_boundaries_and_nonfinite_bins_match_replay(tmp_path, dtype): + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'source') + values = np.array([0, 1, 1, 2, 2, 3, 1, 4, 5, 6, 8, 9], dtype=dtype) + if dtype.startswith('float'): + values[[1, 4]] = [np.nan, np.inf] # all-nonfinite unit/bin with finite depth + else: + values[-3:] = [2**53 + 1, 2**63 - 1, 2**63 - 1 if dtype == 'int64' else 2**64 - 1] + np.save(params.parent / 'amplitudes.npy', values) + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=5, batch_size=2) + build_summary_store(bounded, tmp_path / 'store') + build_amplitude_index(bounded, tmp_path / 'ranges', block_rows=2, workers=3) + with LiveSummaryEngine(bounded) as engine: + index = AmplitudeRangeIndex(engine) + try: + for threshold in [1.000000001, float(2**63), 2**53 + 1, -999, 1e30]: + for operator in ['<', '<=', '>', '>=']: + events = [merge([0, 1, 99], 100), split(100, [101, 102], threshold=threshold)] + events[-1]['predicate']['operator'] = operator + expressions = membership_expressions(engine.manifest['unit_ids'], events) + expressions = {u: expressions[u] for u in [101, 102]} + actual = index.resolve(expressions) + for unit in expressions: + assert_summary( + engine, actual[unit], oracle(params.parent, engine, events, unit) + ) + finally: + index.close() + + +def test_external_sort_is_stable_and_bounded_with_duplicate_keys(tmp_path): + from phy.apps.large_recording.range_build import _SortedRuns + + rng = np.random.default_rng(8) + values = np.empty(10000, dtype=[('amplitude', 'f4'), ('depth', 'i8')]) + values['amplitude'] = rng.integers(-100, 100, len(values)) + values['depth'] = np.arange(len(values)) + sorter = _SortedRuns(tmp_path, values.dtype, 2048, None) + for first in range(0, len(values), 37): + sorter.add(values[first : first + 37]) + records, path = sorter.finish() + assert records is None + actual = np.fromfile(path, dtype=values.dtype) + np.testing.assert_array_equal(actual, values[np.argsort(values['amplitude'], kind='stable')]) + path.unlink() + assert not list(tmp_path.iterdir()) + + +def test_unstable_arithmetic_uses_verified_rows_and_reject_still_raises(tmp_path, monkeypatch): + from phy.apps.large_recording import range_index + from phy.apps.large_recording.range_intervals import RangeUnavailableError + + source, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + build_amplitude_index(bounded, tmp_path / 'ranges') + + def unstable(*args): + raise RangeUnavailableError('unstable arithmetic') + + monkeypatch.setattr(range_index, 'validate_sums', unstable) + with LiveSummaryEngine(bounded) as engine: + engine._publish = lambda *args: None + events = [split(0, [100, 101])] + expressions = membership_expressions(engine.manifest['unit_ids'], events) + actual = engine.resolve({u: expressions[u] for u in [100, 101]}) + assert engine.range_index is not None + assert not engine.arrays # fallback reads the verified rows, not full-source arrays + for unit, summary in actual.items(): + assert_summary(engine, summary, oracle(source, engine, events, unit)) + events = [split(1, [100, 101], nonfinite='reject')] + expressions = membership_expressions(engine.manifest['unit_ids'], events) + with pytest.raises(ValueError, match='Nonfinite'): + engine.resolve({100: expressions[100]}) + + +def test_corrupt_accelerator_falls_back_and_reattachment_invalidates_readers(tmp_path): + from phy.apps.large_recording.range_index import attach_amplitude_index + from phy.apps.large_recording.summary_store import attach_summary_store + + source, bounded = package(tmp_path) + store = build_summary_store(bounded, tmp_path / 'store') + ranges = build_amplitude_index(bounded, tmp_path / 'ranges') + events = [split(0, [100, 101])] + with LiveSummaryEngine(bounded) as engine: + engine._publish = lambda *args: None + e = membership_expressions(engine.manifest['unit_ids'], events) + e = {u: e[u] for u in [100, 101]} + engine.resolve(e) + previous = engine.range_index + with (ranges / 'nodes.bin').open('r+b') as stream: + stream.write(b'x') + actual = engine.resolve(e) + assert engine.range_index is None + assert previous.files == {} + for unit in e: + assert_summary(engine, actual[unit], oracle(source, engine, events, unit)) + replacement = build_amplitude_index(bounded, tmp_path / 'replacement') + actual = engine.resolve(e) + assert engine.range_index.path == replacement + attach_summary_store(bounded, store) + engine.resolve(e) + assert engine.range_index is None + attach_amplitude_index(bounded, replacement) + engine.resolve(e) + assert engine.range_index is not None + + +def test_cancel_budget_and_automatic_attachment_conflict_leave_recoverable_artifacts(tmp_path): + from concurrent.futures import CancelledError + + from phy.apps.large_recording.range_index import attach_amplitude_index + from phy.apps.large_recording.summary_store import ( + SummaryStorePublishedError, + summary_store_reference, + ) + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + reference = summary_store_reference(bounded) + with pytest.raises(ValueError, match='max_bytes'): + build_amplitude_index(bounded, tmp_path / 'too-big', max_bytes=1) + with pytest.raises(CancelledError): + build_amplitude_index(bounded, tmp_path / 'cancelled', cancel=lambda: True) + assert not list(tmp_path.glob('.*.building-*')) + assert summary_store_reference(bounded) == reference + first = build_amplitude_index(bounded, tmp_path / 'first', attach=False) + + def choose_first(): + attach_amplitude_index(bounded, first) + + with pytest.raises(SummaryStorePublishedError, match='changed'): + build_amplitude_index(bounded, tmp_path / 'second', before_publish=choose_first) + assert (tmp_path / 'second' / 'range.json').is_file() + with LiveSummaryEngine(bounded) as engine: + index = AmplitudeRangeIndex(engine) + assert index.path == first + index.close() + + +def test_ill_conditioned_depth_falls_back_without_changing_source_order_sum(tmp_path): + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.range_intervals import RangeUnavailableError + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'source') + depth = np.zeros(12) + depth[[0, 3, 6, 9]] = [1e20, 1, -1e20, 0] + np.save(params.parent / 'spike_depths.npy', depth) + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=20) + build_summary_store(bounded, tmp_path / 'store') + build_amplitude_index(bounded, tmp_path / 'ranges', block_rows=2) + events = [split(0, [100, 101], threshold=-1)] + with LiveSummaryEngine(bounded) as engine: + expressions = membership_expressions(engine.manifest['unit_ids'], events) + expressions = {101: expressions[101]} + index = AmplitudeRangeIndex(engine) + try: + with pytest.raises(RangeUnavailableError, match='arithmetic'): + index.resolve(expressions) + finally: + index.close() + actual = engine.resolve(expressions) + assert not engine.arrays + assert_summary(engine, actual[101], oracle(params.parent, engine, events, 101)) + + +@pytest.mark.parametrize('stage', ['sort', 'hash', 'publish']) +def test_failed_build_cleans_staging_without_changing_attachment(tmp_path, monkeypatch, stage): + from phy.apps.large_recording import range_build + from phy.apps.large_recording.summary_store import summary_store_reference + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + previous = summary_store_reference(bounded) + + def fail(*args, **kwargs): + raise OSError('injected disk failure') + + if stage == 'sort': + monkeypatch.setattr(range_build._SortedRuns, 'finish', fail) + elif stage == 'hash': + monkeypatch.setattr(range_build, 'authenticate_file', fail) + else: + monkeypatch.setattr(range_build, 'publish_directory', fail) + with pytest.raises(OSError, match='injected'): + build_amplitude_index(bounded, tmp_path / 'failed') + assert not (tmp_path / 'failed').exists() + assert not list(tmp_path.glob('.*.building-*')) + assert summary_store_reference(bounded) == previous + + +def test_small_query_budget_falls_back_before_endpoint_allocation(tmp_path): + from phy.apps.large_recording.range_intervals import RangeUnavailableError + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + build_amplitude_index(bounded, tmp_path / 'ranges') + events = [split(0, [100, 101])] + with LiveSummaryEngine(bounded, max_bytes=512) as engine: + expressions = membership_expressions(engine.manifest['unit_ids'], events) + expression = {100: expressions[100]} + index = AmplitudeRangeIndex(engine) + try: + with pytest.raises(RangeUnavailableError, match='endpoint'): + index.resolve(expression) + finally: + index.close() + engine.resolve(expression) + assert not engine.arrays + + +def test_tiny_scalar_sort_reserves_permutation_workspace(tmp_path): + from phy.apps.large_recording.range_build import _SortedRuns + + dtype = np.dtype([('amplitude', 'u1')]) + sorter = _SortedRuns(tmp_path, dtype, 1048576, None) + assert sorter.limit * (4 + 16) <= 1048576 + + +def test_parallel_index_bytes_are_deterministic_and_cancel_cleans(tmp_path): + from concurrent.futures import CancelledError + + from phy.apps.large_recording.source import hash_file + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store', workers=3) + first = build_amplitude_index(bounded, tmp_path / 'serial', workers=1, attach=False) + second = build_amplitude_index(bounded, tmp_path / 'parallel', workers=3, attach=False) + for name in ('values.bin', 'nodes.bin', 'segments.bin'): + assert hash_file(first / name) == hash_file(second / name) + assert hash_file(first / (name + '.hashes')) == hash_file(second / (name + '.hashes')) + + def progress(stage, done, total): + if stage == 'sorting amplitude ranges': + raise CancelledError() + + with pytest.raises(CancelledError): + build_amplitude_index(bounded, tmp_path / 'cancelled', workers=3, progress=progress) + assert not (tmp_path / 'cancelled').exists() + assert not list(tmp_path.glob('.cancelled.building-*')) diff --git a/phy/apps/large_recording/tests/test_recovery.py b/phy/apps/large_recording/tests/test_recovery.py new file mode 100644 index 000000000..6f42e40b4 --- /dev/null +++ b/phy/apps/large_recording/tests/test_recovery.py @@ -0,0 +1,347 @@ +"""Private recovery heads survive interruption without publishing curation.""" + +import json +import os +import subprocess +import sys +import time + +import numpy as np +import pytest + +from phy.apps.large_recording import recovery +from phy.apps.large_recording.curation import BoundedSession, _digest +from phy.apps.large_recording.recovery import ( + FORMAT, + VERSION, + RecoveryStore, + build_recovered_state, +) +from phy.apps.large_recording.tests.test_curation import make_session + + +def payload(session, store, revision): + return { + 'format': FORMAT, + 'version': VERSION, + 'session_id': store.session_id, + 'revision': revision, + 'created_at': time.time(), + 'bindings': store.bindings, + 'base_pointer': session._expected_pointer, + 'events': list(session.events), + 'next_cluster_id': session.next_cluster_id, + 'reviews': None, + } + + +def test_two_heads_fallback_retirement_and_active_owner(tmp_path): + source, session = make_session(tmp_path) + root = tmp_path / 'recovery' + first = RecoveryStore(session, root) + reader = RecoveryStore(session, root) + try: + session.record_label('group', [0], 'mua') + first.write(payload(session, first, 1)) + session.record_label('group', [0], 'good') + first.write(payload(session, first, 2)) + assert not reader.candidates(None)[0] # Live owner is never offered. + first.close() + newest = max( + first.branch.glob('head-*.json'), + key=lambda p: json.loads(p.read_text())['payload']['revision'], + ) + newest.write_text('{partial') + drafts, warnings = reader.candidates(None) + assert warnings and len(drafts) == 1 + assert drafts[0]['payload']['revision'] == 1 + recovered = build_recovered_state(session, drafts[0]['payload']) + assert recovered.metadata['group'][0] == 'mua' + assert session.metadata['group'][0] == 'good' + reader.retire(1, branch=first.branch) + assert not reader.candidates(None)[0] + finally: + first.close() + reader.close() + session.close() + source.close() + + +@pytest.mark.parametrize('phase', ['before_replace', 'after_replace']) +def test_process_exit_during_snapshot_keeps_a_verified_head(tmp_path, phase): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + session.record_label('group', [0], 'mua') + store.write(payload(session, store, 1)) + session.record_label('group', [0], 'good') + item = payload(session, store, 2) + item_path = tmp_path / 'payload.json' + item_path.write_text(json.dumps(item)) + store.close() + script = """ +import json, os, sys +from phy.apps.large_recording import recovery +from phy.apps.large_recording.curation import BoundedSession +session = BoundedSession(sys.argv[1]) +item = json.load(open(sys.argv[3])) +store = recovery.RecoveryStore(session, sys.argv[2], session_id=item['session_id']) +if sys.argv[4] == 'before_replace': + original = recovery._write_json + def fail(path, value): + original(path, value) + os._exit(91) + recovery._write_json = fail +else: + recovery._fsync_directory = lambda path: os._exit(92) +store.write(item) +""" + try: + result = subprocess.run( + [ + sys.executable, + '-c', + script, + str(session.path), + str(tmp_path / 'recovery'), + str(item_path), + phase, + ], + timeout=30, + capture_output=True, + ) + assert result.returncode == (91 if phase == 'before_replace' else 92) + reader = RecoveryStore(session, tmp_path / 'recovery') + try: + drafts, _ = reader.candidates(None) + assert len(drafts) == 1 + head = drafts[0]['payload'] + assert head['revision'] == (1 if phase == 'before_replace' else 2) + expected = 'mua' if phase == 'before_replace' else 'good' + assert build_recovered_state(session, head).metadata['group'][0] == expected + finally: + reader.close() + finally: + session.close() + source.close() + + +def test_full_active_journal_recovers_undo_branch_and_allocator(tmp_path): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + try: + baseline = session.journal_state() + session.record_merge([0, 1], 100) + session.save() + session.restore_journal(baseline) + session.record_merge([1, 2], 101) + item = payload(session, store, 1) + recovered = build_recovered_state(session, item) + assert recovered.events == session.events + assert recovered.next_cluster_id == 102 + np.testing.assert_array_equal(recovered.assignments, session.assignments) + with BoundedSession(session.path) as saved: + assert saved.events[0]['target'] == 100 + item['next_cluster_id'] = 101 + with pytest.raises(ValueError, match='allocator'): + build_recovered_state(session, item) + item['next_cluster_id'] = 102 + item['bindings'] = dict(item['bindings'], source_revision='changed') + with pytest.raises(ValueError, match='bindings'): + build_recovered_state(session, item) + finally: + store.close() + session.close() + source.close() + + +def test_recovery_is_not_seen_by_session_load_or_apply(tmp_path): + from phy.apps.large_recording.replay import apply_curation + + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + try: + session.record_label('group', [0], 'mua') + session.save() + session.record_label('group', [0], 'noise') + store.write(payload(session, store, 1)) + with BoundedSession(session.path) as saved: + assert saved.metadata['group'][0] == 'mua' + output = apply_curation( + source.params_path, session.path, tmp_path / 'output', batch_size=5 + ) + rows = (output / 'cluster_group.tsv').read_text() + assert '0\tmua' in rows and '0\tnoise' not in rows + finally: + store.close() + session.close() + source.close() + + +def test_other_checkpoint_never_rebases_or_deletes_a_draft(tmp_path): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + session.record_label('group', [0], 'mua') + store.write(payload(session, store, 1)) + store.close() + try: + session.save() + reader = RecoveryStore(session, tmp_path / 'recovery') + try: + drafts, warnings = reader.candidates(session._expected_pointer) + assert not drafts and warnings + assert list(store.branch.glob('head-*.json')) + finally: + reader.close() + finally: + session.close() + source.close() + + +def test_skipped_revisions_preserve_two_independent_heads(tmp_path): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + try: + session.record_label('group', [0], 'mua') + store.write(payload(session, store, 1)) + session.record_label('group', [0], 'good') + store.write(payload(session, store, 3)) + heads = list(store.branch.glob('head-*.json')) + assert len(heads) == 2 + assert {json.loads(path.read_text())['payload']['revision'] for path in heads} == {1, 3} + newest = max(heads, key=lambda p: json.loads(p.read_text())['payload']['revision']) + newest.write_text('{torn') + store.close() + reader = RecoveryStore(session, tmp_path / 'recovery') + try: + drafts, _ = reader.candidates(None) + assert drafts[0]['payload']['revision'] == 1 + finally: + reader.close() + finally: + store.close() + session.close() + source.close() + + +@pytest.mark.skipif(os.name == 'nt', reason='POSIX mode bits') +def test_private_permissions_and_new_ancestor_directory_sync(tmp_path, monkeypatch): + source, session = make_session(tmp_path) + root = tmp_path / 'new-parent' / 'app' / 'recovery' + synced = [] + original = recovery._fsync_directory + + def sync(path): + synced.append(path) + original(path) + + monkeypatch.setattr(recovery, '_fsync_directory', sync) + store = RecoveryStore(session, root) + try: + store.write(payload(session, store, 1)) + store.retire(0) + for path in (root, store.directory, store.branch): + assert path.stat().st_mode & 0o777 == 0o700 + for name in ('owner.lock', 'head-0.json', 'retired.json'): + assert (store.branch / name).stat().st_mode & 0o777 == 0o600 + assert tmp_path in synced + assert root.parent in synced + finally: + store.close() + session.close() + source.close() + + +def test_retirement_prunes_only_verified_old_heads_and_locks_foreign_owner(tmp_path): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + other = RecoveryStore(session, tmp_path / 'recovery') + try: + store.write(payload(session, store, 1)) + store.write(payload(session, store, 3)) + with pytest.raises(OSError): + other.retire(1, branch=store.branch) + assert not (store.branch / 'retired.json').exists() + store.retire(1) + heads = list(store.branch.glob('head-*.json')) + assert len(heads) == 1 + assert json.loads(heads[0].read_text())['payload']['revision'] == 3 + # Unknown bytes must never be garbage-collected, even after retirement. + (store.branch / 'head-0.json').write_text('{unknown') + store.retire(3) + assert (store.branch / 'head-0.json').read_text() == '{unknown' + assert not (store.branch / 'head-1.json').exists() + finally: + store.close() + other.close() + session.close() + source.close() + + +def test_exit_after_retirement_before_pruning_cannot_resurrect_draft(tmp_path): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + store.write(payload(session, store, 1)) + branch = store.branch + store.close() + script = """ +import os, sys +from phy.apps.large_recording.recovery import RecoveryStore +from phy.apps.large_recording.curation import BoundedSession +session = BoundedSession(sys.argv[1]) +store = RecoveryStore(session, sys.argv[2], session_id=sys.argv[3]) +store._prune_retired = lambda *args: os._exit(93) +store.retire(1) +""" + try: + result = subprocess.run( + [ + sys.executable, + '-c', + script, + str(session.path), + str(tmp_path / 'recovery'), + store.session_id, + ], + timeout=30, + capture_output=True, + ) + assert result.returncode == 93 + assert list(branch.glob('head-*.json')) + reader = RecoveryStore(session, tmp_path / 'recovery') + try: + assert not reader.candidates(None)[0] + finally: + reader.close() + finally: + session.close() + source.close() + + +@pytest.mark.parametrize('created', [None, {}, 1e100]) +def test_malformed_header_does_not_hide_other_valid_heads(tmp_path, created): + source, session = make_session(tmp_path) + store = RecoveryStore(session, tmp_path / 'recovery') + try: + store.write(payload(session, store, 1)) + store.write(payload(session, store, 3)) + newest = next( + path + for path in store.branch.glob('head-*.json') + if json.loads(path.read_text())['payload']['revision'] == 3 + ) + wrapper = json.loads(newest.read_text()) + wrapper['payload']['created_at'] = created + wrapper['sha256'] = recovery._digest(wrapper['payload']) + newest.write_text(json.dumps(wrapper)) + store.close() + reader = RecoveryStore(session, tmp_path / 'recovery') + try: + drafts, warnings = reader.candidates(None) + assert drafts[0]['payload']['revision'] == 1 + assert warnings + finally: + reader.close() + finally: + store.close() + session.close() + source.close() diff --git a/phy/apps/large_recording/tests/test_recovery_gui.py b/phy/apps/large_recording/tests/test_recovery_gui.py new file mode 100644 index 000000000..7a914e082 --- /dev/null +++ b/phy/apps/large_recording/tests/test_recovery_gui.py @@ -0,0 +1,523 @@ +"""Stable transaction capture, worker acknowledgement, and explicit draft lifecycle.""" + +import json +import threading +from concurrent.futures import CancelledError + +import numpy as np +import pytest +from phylib.utils import connect, unconnect + +from phy.apps.large_recording import recovery, recovery_gui +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.gui.qt import mock_dialogs + + +def protected(qtbot, coordinator): + qtbot.waitUntil( + lambda: ( + coordinator.status['protected_revision'] == coordinator.status['current_revision'] + and coordinator.status['state'] == 'protected' + ), + timeout=5000, + ) + + +def latest(coordinator): + folder = next(iter(coordinator.root.glob('*'))) / coordinator.session_id + heads = [json.loads(path.read_text())['payload'] for path in folder.glob('head-*.json')] + return max(heads, key=lambda head: head['revision']) + + +def test_capture_has_no_spike_work_and_waits_for_outer_transaction(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.root = tmp_path / 'recovery' + coordinator.start() + supervisor = controller.supervisor + writes, owner = [], threading.get_ident() + original = recovery.RecoveryStore.write + + def write(store, payload): + writes.append(threading.get_ident()) + return original(store, payload) + + def forbid(*args, **kwargs): + pytest.fail('Recovery capture scanned or copied spike state.') + + try: + monkeypatch.setattr(recovery.RecoveryStore, 'write', write) + monkeypatch.setattr(controller.bounded_session, 'snapshot', forbid) + monkeypatch.setattr(recovery, 'project_assignments', forbid) + supervisor.label('group', 'mua', [0]) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + assert writes and all(thread != owner for thread in writes) + assert latest(coordinator)['events'][-1]['value'] == 'mua' + assert not (controller.dir_path / '.phy-curation' / 'current.json').exists() + finally: + controller.close() + + +def test_failed_observer_never_protects_provisional_merge(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.root = tmp_path / 'recovery' + coordinator.start() + supervisor = controller.supervisor + + @connect(event='bounded_state_changed', sender=supervisor) + def reject(sender): + assert coordinator.request_flush() is None + with pytest.raises(RuntimeError, match='current action has settled'): + supervisor.save() + raise RuntimeError('observer rolls back') + + try: + with pytest.raises(RuntimeError, match='rolls back'): + supervisor.merge([0, 1], to=100) + unconnect(reject) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + draft = latest(coordinator) + assert draft['events'] == [] + assert draft['next_cluster_id'] >= 101 + assert supervisor.session.events == [] + finally: + unconnect(reject) + controller.close() + + +def test_one_active_one_pending_newest_snapshot(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.root = tmp_path / 'recovery' + coordinator.start() + entered, release = threading.Event(), threading.Event() + calls = [] + original = recovery.RecoveryStore.write + + def slow(store, payload): + calls.append(payload['revision']) + if len(calls) == 1: + entered.set() + assert release.wait(5) + return original(store, payload) + + monkeypatch.setattr(recovery.RecoveryStore, 'write', slow) + try: + supervisor = controller.supervisor + supervisor.label('group', 'mua', [0]) + first = coordinator.request_flush() + qtbot.waitUntil(entered.is_set) + supervisor.label('group', 'noise', [0]) + middle = coordinator.request_flush() + supervisor.label('group', 'good', [0]) + last = coordinator.request_flush() + assert middle.cancelled() + assert coordinator.status['protected_revision'] == 0 + release.set() + qtbot.waitUntil(last.done) + protected(qtbot, coordinator) + assert first.done() and calls == [1, 3] + assert latest(coordinator)['events'][-1]['value'] == 'good' + finally: + release.set() + controller.close() + + +def test_failed_fsync_never_acknowledges_protection_and_retry_succeeds( + qtbot, tmp_path, monkeypatch +): + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.root = tmp_path / 'recovery' + coordinator.start() + controller.supervisor.label('group', 'mua', [0]) + original = recovery._atomic_json + + def fail(*args, **kwargs): + raise OSError('disk full') + + try: + monkeypatch.setattr(recovery, '_atomic_json', fail) + failed = coordinator.request_flush() + qtbot.waitUntil(failed.done) + qtbot.waitUntil(lambda: coordinator.status['state'] == 'error') + assert coordinator.status['protected_revision'] == 0 + assert coordinator.status['last_protected_at'] is None + assert 'disk full' in coordinator.status['error'] + assert controller.supervisor.is_dirty() + monkeypatch.setattr(recovery, '_atomic_json', original) + succeeded = coordinator.request_flush() + qtbot.waitUntil(succeeded.done) + protected(qtbot, coordinator) + finally: + controller.close() + + +def test_explicit_save_with_newer_edit_keeps_draft_and_dirty(qtbot, tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.root = tmp_path / 'recovery' + coordinator.start() + supervisor = controller.supervisor + supervisor.label('group', 'mua', [0]) + original = curation._write_json + once = [] + + def edit_during_save(path, value): + original(path, value) + if path.name == 'journal.json' and not once: + once.append(True) + supervisor.label('notes', 'newer than saved checkpoint', [0]) + + try: + monkeypatch.setattr(curation, '_write_json', edit_during_save) + supervisor.save() + assert supervisor.is_dirty() + assert len(supervisor.session.events) == 2 + with BoundedSession(controller.dir_path) as saved: + assert len(saved.events) == 1 + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + draft = latest(coordinator) + assert len(draft['events']) == 2 + assert draft['base_pointer'] == supervisor.session._expected_pointer + finally: + controller.close() + + +def test_reject_reset_and_undo_protect_review_only_changes(qtbot, tmp_path): + mapping = {'format_version': '2', 'unit_ids': [0, 1, 2, 99], 'merges': [{'unit_ids': [0, 1]}]} + _, controller = make_controller(tmp_path, propositions=mapping) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor, coordinator = controller.supervisor, controller.recovery + key = supervisor.merge_propositions.catalog.propositions[0].key + try: + supervisor._reject_merge_proposition(supervisor.merge_propositions_view, key) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + draft = latest(coordinator) + assert draft['events'] == [] + assert draft['reviews']['reviews'][key]['decision'] == 'rejected' + recovered = recovery.build_recovered_state(controller.bounded_session, draft) + assert ( + recovered.extra_documents['curation_review.json']['reviews'][key]['decision'] + == 'rejected' + ) + supervisor.undo() + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + assert latest(coordinator)['reviews']['reviews'] == {} + finally: + gui.close() + controller.close() + + +def test_startup_restore_stays_unsaved_and_discard_is_durable(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + path = controller.dir_path + root = tmp_path / 'recovery' + coordinator = controller.recovery + coordinator.root = root + coordinator.start() + controller.supervisor.merge([0, 1], to=100) + controller.supervisor.label('group', 'mua', [100]) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + controller.close() + qtbot.waitUntil(lambda: not coordinator._writer.thread.is_alive()) + from phy.apps.template.gui import TemplateController + + reopened = TemplateController( + dir_path=path, config_dir=tmp_path / 'new-config', recovery_root=root, plugins=[] + ) + gui = None + try: + with mock_dialogs('restore'): + gui = reopened.create_gui(default_views=[], do_prompt_save=False, offer_recovery=True) + assert reopened.supervisor.is_dirty() + assert reopened.supervisor._global_history.current_position == 0 + assert reopened.bounded_session.metadata['group'][100] == 'mua' + assert reopened.bounded_session.next_cluster_id == 101 + assert not (path / '.phy-curation' / 'current.json').exists() + future = reopened.recovery.discard() + qtbot.waitUntil(future.done) + future.result() + reader = recovery.RecoveryStore(reopened.bounded_session, root) + try: + assert not reader.candidates(None)[0] + finally: + reader.close() + finally: + if gui is not None: + gui.close() + reopened.close() + + +def test_ready_disabled_save_and_dirty_clean_notifications(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + coordinator, supervisor = controller.recovery, controller.supervisor + assert coordinator.status['state'] == 'ready' + assert coordinator.status['protected_revision'] == 0 + assert coordinator.status['last_protected_at'] is None + dirty = [] + coordinator.changed.connect(lambda: dirty.append(supervisor.is_dirty())) + try: + supervisor.label('group', 'mua', [0]) + assert supervisor.is_dirty() + supervisor.undo() + assert not supervisor.is_dirty() + supervisor.label('group', 'noise', [0]) + assert supervisor.is_dirty() + assert dirty == [True, False, True] + path = controller.dir_path + finally: + controller.close() + from phy.apps.template.gui import TemplateController + + disabled = TemplateController( + dir_path=path, config_dir=tmp_path / 'disabled', recovery_enabled=False, plugins=[] + ) + try: + disabled.supervisor.label('group', 'mua', [0]) + disabled.supervisor.save() + assert disabled.recovery._writer is None + assert disabled.recovery.status['state'] == 'disabled' + assert disabled.recovery.status['last_checkpoint_at'] is not None + finally: + disabled.close() + + +def test_stale_completions_cannot_replace_newer_protection_or_error(qtbot, tmp_path): + from concurrent.futures import Future + + _, controller = make_controller(tmp_path) + coordinator = controller.recovery + coordinator.start() + try: + for group in ('mua', 'noise'): + controller.supervisor.label('group', group, [0]) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + before = dict(coordinator.status) + old_error = Future() + old_error.set_exception(OSError('old failed write')) + coordinator._completed(('snapshot', 1, old_error)) + assert coordinator.status == before + controller.supervisor.label('group', 'good', [0]) + new_error = Future() + new_error.set_exception(OSError('new failed write')) + coordinator._completed(('snapshot', 3, new_error)) + stale_success = Future() + stale_success.set_result({'retired': False, 'protected_at': 1, 'base_pointer': None}) + coordinator._completed(('snapshot', 1, stale_success)) + assert coordinator.status['state'] == 'error' + assert coordinator.status['error'] == 'new failed write' + assert coordinator.status['protected_revision'] == 2 + finally: + controller.close() + + +def test_save_rebases_only_own_newer_queued_snapshot(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + coordinator, supervisor = controller.recovery, controller.supervisor + coordinator.start() + entered, release = threading.Event(), threading.Event() + original = recovery.RecoveryStore.write + calls = [] + + def slow(store, payload): + calls.append(payload['revision']) + if len(calls) == 1: + entered.set() + assert release.wait(5) + return original(store, payload) + + monkeypatch.setattr(recovery.RecoveryStore, 'write', slow) + try: + supervisor.label('group', 'mua', [0]) + coordinator.request_flush() + qtbot.waitUntil(entered.is_set) + supervisor.save() + supervisor.label('group', 'noise', [0]) + future = coordinator.request_flush() + release.set() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + assert latest(coordinator)['base_pointer'] == supervisor.session._expected_pointer + assert latest(coordinator)['events'][-1]['value'] == 'noise' + assert supervisor.is_dirty() + assert coordinator.status['warning'] is None + finally: + release.set() + controller.close() + + +@pytest.mark.parametrize('choice', ['save', 'close', 'cancel']) +def test_actual_close_save_discard_cancel_contract(qtbot, tmp_path, choice): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=True, offer_recovery=False) + coordinator, supervisor = controller.recovery, controller.supervisor + try: + supervisor.label('group', 'mua', [0]) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + with mock_dialogs(choice): + gui.close() + if choice == 'cancel': + assert not gui._closed + assert coordinator._started + assert coordinator._writer.thread.is_alive() + assert supervisor.is_dirty() + else: + assert gui._closed + assert not coordinator._started + pointer = controller.dir_path / '.phy-curation' / 'current.json' + assert pointer.exists() == (choice == 'save') + assert supervisor.is_dirty() == (choice == 'close') + finally: + if not gui._closed: + with mock_dialogs('close'): + gui.close() + controller.close() + + +def test_failed_discard_keeps_gui_and_worker_alive(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=True, offer_recovery=False) + coordinator = controller.recovery + original = recovery.RecoveryStore.retire + try: + controller.supervisor.label('group', 'mua', [0]) + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, coordinator) + + def fail(*args, **kwargs): + raise OSError('discard is not durable') + + monkeypatch.setattr(recovery.RecoveryStore, 'retire', fail) + with mock_dialogs('close'): + gui.close() + assert not gui._closed + assert coordinator._started + qtbot.waitUntil(lambda: coordinator.status['state'] == 'error') + assert 'discard is not durable' in coordinator.status['error'] + finally: + monkeypatch.setattr(recovery.RecoveryStore, 'retire', original) + if not gui._closed: + with mock_dialogs('close'): + gui.close() + controller.close() + + +def test_post_pointer_fsync_failure_reports_uncertain_save(qtbot, tmp_path, monkeypatch): + from phy.apps.large_recording import curation + + _, controller = make_controller(tmp_path) + coordinator, supervisor = controller.recovery, controller.supervisor + original = curation._fsync_directory + root = controller.dir_path / '.phy-curation' + once = [] + + def fail_after_pointer(path): + if path == root and (root / 'current.json').exists() and not once: + once.append(True) + raise OSError('directory sync failed after pointer publication') + return original(path) + + try: + supervisor.label('group', 'mua', [0]) + monkeypatch.setattr(curation, '_fsync_directory', fail_after_pointer) + with pytest.raises(OSError, match='directory sync failed'): + supervisor.save() + assert supervisor.is_dirty() + assert coordinator.status['state'] == 'error' + assert coordinator.status['last_checkpoint_at'] is None + assert 'durability is uncertain' in coordinator.status['error'] + with BoundedSession(controller.dir_path) as saved: + assert saved.metadata['group'][0] == 'mua' + assert supervisor.session._expected_pointer is None + finally: + controller.close() + + +def test_other_writer_checkpoint_conflict_never_claims_restorable_protection(qtbot, tmp_path): + from phy.apps.template.gui import TemplateController + + _, controller = make_controller(tmp_path) + other = TemplateController( + dir_path=controller.dir_path, config_dir=tmp_path / 'other-config', plugins=[] + ) + coordinator = other.recovery + coordinator.start() + try: + other.supervisor.label('group', 'mua', [0]) + controller.supervisor.save() + future = coordinator.request_flush() + qtbot.waitUntil(future.done) + qtbot.waitUntil(lambda: coordinator.status['state'] == 'error') + assert coordinator.status['protected_revision'] == 0 + assert coordinator.status['last_protected_at'] is None + assert 'Another session saved' in coordinator.status['error'] + assert latest(coordinator)['events'][-1]['value'] == 'mua' + assert other.bounded_session._expected_pointer is None + finally: + other.close() + controller.close() + + +@pytest.mark.parametrize('newer_foreign_head', [False, True]) +def test_confirmed_save_retires_recovered_source_without_pruning_newer_foreign_head( + qtbot, tmp_path, newer_foreign_head +): + from phy.apps.template.gui import TemplateController + + _, original = make_controller(tmp_path) + root = tmp_path / 'recovery' + original.recovery.root = root + original.recovery.start() + original.supervisor.label('group', 'mua', [0]) + future = original.recovery.request_flush() + qtbot.waitUntil(future.done) + protected(qtbot, original.recovery) + branch = root / original.recovery.bindings['manifest_sha256'] / original.recovery.session_id + path = original.dir_path + original.close() + qtbot.waitUntil(lambda: not original.recovery._writer.thread.is_alive()) + restored = TemplateController( + dir_path=path, config_dir=tmp_path / 'restored-config', recovery_root=root, plugins=[] + ) + try: + with mock_dialogs('restore'): + restored.recovery.offer_startup() + if newer_foreign_head: + source = recovery.RecoveryStore(restored.bounded_session, root, session_id=branch.name) + try: + newer = dict(restored.recovery._restored_from['payload'], revision=3) + source.write(newer) + finally: + source.close() + restored.supervisor.save() + qtbot.waitUntil(lambda: (branch / 'retired.json').exists()) + qtbot.waitUntil(lambda: len(list(branch.glob('head-*.json'))) == int(newer_foreign_head)) + if newer_foreign_head: + head = next(branch.glob('head-*.json')) + assert json.loads(head.read_text())['payload']['revision'] == 3 + assert restored.recovery.status['state'] == 'protected' + assert not restored.supervisor.is_dirty() + finally: + restored.close() diff --git a/phy/apps/large_recording/tests/test_recovery_status.py b/phy/apps/large_recording/tests/test_recovery_status.py new file mode 100644 index 000000000..4b318fbbc --- /dev/null +++ b/phy/apps/large_recording/tests/test_recovery_status.py @@ -0,0 +1,315 @@ +"""Checkpoint reminders never publish data, interrupt input, or invent protection.""" + +from types import SimpleNamespace + +import pytest +from phylib.utils import connect, unconnect + +from phy.apps.large_recording.recovery_status import CheckpointStatus +from phy.gui import GUI +from phy.gui.qt import QApplication, QLineEdit, QObject, Qt, pyqtSignal + + +class Clock: + value = 0 + + def monotonic(self): + return self.value + + def time(self): + return 1_700_000_000 + self.value + + def advance(self, seconds): + self.value += seconds + + +class Recovery(QObject): + changed = pyqtSignal() + + def __init__(self): + super().__init__() + self.value = { + 'enabled': True, + 'state': 'protected', + 'current_revision': 0, + 'protected_revision': 0, + 'last_protected_at': None, + 'last_checkpoint_at': 1_700_000_000, + 'error': None, + } + self.flushes = 0 + + @property + def status(self): + return dict(self.value) + + def update(self, **values): + self.value.update(values) + self.changed.emit() + + def request_flush(self): + self.flushes += 1 + + +class Supervisor: + dirty = False + saves = 0 + reads = 0 + save_error = None + + def is_dirty(self): + self.reads += 1 + return self.dirty + + def save(self): + self.saves += 1 + if self.save_error: + raise self.save_error + + +@pytest.fixture +def status(qtbot, tmp_path): + gui = GUI(config_dir=tmp_path / 'config', size=(1100, 650)) + gui.set_default_actions() + qtbot.addWidget(gui) + controller = SimpleNamespace(recovery=Recovery(), supervisor=Supervisor()) + clock = Clock() + widget = CheckpointStatus(controller, gui, clock=clock.monotonic, wall_clock=clock.time) + widget._timer.stop() # Test the real timer callback using a deterministic clock. + with qtbot.waitExposed(gui): + gui.show() + gui.activateWindow() + qtbot.waitUntil(gui.isActiveWindow) + yield widget, controller, clock, gui + widget.dispose() + gui.close() + + +def _edit(controller, clock, **kwargs): + controller.supervisor.dirty = True + controller.recovery.update( + current_revision=1, + protected_revision=1, + last_protected_at=clock.time(), + **kwargs, + ) + + +def test_reminder_tracks_curation_and_waits_for_idle_without_stealing_focus(status, qtbot): + widget, controller, clock, gui = status + field = QLineEdit() + gui.add_view(field) + field.setFocus() + qtbot.waitUntil(field.hasFocus) + size = widget.size() + initial_reads = controller.supervisor.reads + clock.advance(3600) + for _ in range(3): + widget._tick() + assert not widget.save_button.property('checkpointReminder') + assert controller.supervisor.reads == initial_reads + assert not controller.supervisor.saves + _edit(controller, clock) + clock.advance(899) + widget._tick() + assert not widget.save_button.property('checkpointReminder') + clock.advance(2) + qtbot.keyClicks(field, 'curation') + widget._tick() + assert not widget.save_button.property('checkpointReminder') # Wait for a pause. + clock.advance(1.1) + widget._tick() + assert widget.save_button.property('checkpointReminder') + assert '#e6bd6b' in widget.save_button.styleSheet() + assert widget.size() == size + assert QApplication.focusWidget() is field + qtbot.keyClicks(field, 'dD') + widget._tick() + assert widget.save_button.property('checkpointReminder') # Remains visible while typing. + assert field.text() == 'curationdD' + assert not controller.supervisor.saves + + +def test_snooze_disable_interval_and_successful_checkpoint_reset(status): + widget, controller, clock, gui = status + _edit(controller, clock) + widget.set_interval(5) + clock.advance(301) + widget._tick() + assert widget.save_button.property('checkpointReminder') + widget.snooze() + assert not widget.save_button.property('checkpointReminder') + clock.advance(299) + widget._tick() + assert not widget.save_button.property('checkpointReminder') + clock.advance(2) + widget._tick() + assert widget.save_button.property('checkpointReminder') + widget.set_reminders_enabled(False) + assert not widget.save_button.property('checkpointReminder') + assert gui.state['CheckpointReminder'] == {'enabled': False, 'interval_minutes': 5} + assert controller.recovery.status['enabled'] # Disabling reminders preserves recovery. + widget.set_reminders_enabled(True) + assert widget.save_button.property('checkpointReminder') + controller.supervisor.dirty = False + controller.recovery.update(last_checkpoint_at=clock.time()) + assert not widget.save_button.property('checkpointReminder') + assert 'Checkpoint just now' in widget.label.text() + assert '#e6bd6b' not in widget.save_button.styleSheet() + assert not widget.save_button.isEnabled() + clock.advance(10000) + widget._tick() + assert not widget.save_button.property('checkpointReminder') + assert not controller.supervisor.saves + + +def test_only_acknowledged_recovery_is_called_protected_and_save_errors_are_visible(status): + widget, controller, clock, _ = status + controller.supervisor.dirty = True + controller.recovery.update(current_revision=23, protected_revision=17) + assert 'Protecting draft' in widget.label.text() + controller.recovery.update(state='error', error='Disk full', last_protected_at=clock.time()) + assert 'Protection failed' in widget.label.text() + assert 'Disk full' in widget.label.toolTip() + assert 'Last confirmed' in widget.label.toolTip() + controller.supervisor.save_error = OSError('Read-only checkpoint destination') + widget.save_button.click() + assert controller.supervisor.saves == 1 + assert 'Checkpoint failed' in widget.label.text() + assert 'Read-only checkpoint' in widget.label.toolTip() + controller.supervisor.save_error = None + widget.save_button.click() + assert controller.supervisor.saves == 2 + assert 'Checkpoint failed' in widget.label.text() # No invented success timestamp. + clock.advance(1) + controller.supervisor.dirty = False + controller.recovery.update( + state='protected', protected_revision=23, last_checkpoint_at=clock.time(), error=None + ) + assert 'Draft protected' in widget.label.text() + assert 'Checkpoint just now' in widget.label.text() + + +def test_no_checkpoint_is_explicit_and_preferences_restore(status): + widget, controller, _, gui = status + controller.recovery.update(last_checkpoint_at=None) + assert 'No checkpoint yet' in widget.label.text() + assert widget.save_button.isEnabled() + widget.set_interval(30) + widget.set_reminders_enabled(False) + widget.dispose() + restored = CheckpointStatus(controller, gui) + try: + restored._timer.stop() + assert not restored.reminders_enabled + assert restored.interval_minutes == 30 + assert not restored.reminder_action.isChecked() + assert restored.interval_actions[30].isChecked() + finally: + restored.dispose() + + +def test_recovery_warnings_and_startup_failures_are_visible(status): + widget, controller, _, _ = status + controller.recovery.update(warning='Another session saved; reopen before checkpointing.') + assert 'Draft needs attention' in widget.label.text() + assert 'Another session saved' in widget.label.toolTip() + controller.recovery.update(warning=None, startup_error='Recovery discovery failed: disk error') + assert 'Draft needs attention' in widget.label.text() + assert 'disk error' in widget.label.toolTip() + assert controller.recovery.status['state'] == 'protected' + assert ( + controller.recovery.status['current_revision'] + == controller.recovery.status['protected_revision'] + ) + controller.recovery.update(state='error', error='Recovery could not be restored: disk error') + assert 'Protection failed' in widget.label.text() + + +def test_fresh_session_is_ready_until_durability_is_acknowledged(status): + widget, controller, _, _ = status + controller.recovery.update( + state='ready', + current_revision=0, + protected_revision=0, + last_protected_at=None, + last_checkpoint_at=None, + ) + assert 'Draft protection ready' in widget.label.text() + assert 'No checkpoint yet' in widget.label.text() + assert not widget.save_button.property('checkpointReminder') + + +def test_undo_to_checkpoint_restarts_reminder_at_the_next_edit(status): + widget, controller, clock, _ = status + _edit(controller, clock) + clock.advance(901) + widget._tick() + assert widget.save_button.property('checkpointReminder') + # Undo may return to the saved state without changing the checkpoint stamp. + controller.supervisor.dirty = False + controller.recovery.update(current_revision=2) + assert not widget.save_button.property('checkpointReminder') + clock.advance(5000) + controller.supervisor.dirty = True + controller.recovery.update(current_revision=3) + assert not widget.save_button.property('checkpointReminder') + clock.advance(899) + widget._tick() + assert not widget.save_button.property('checkpointReminder') + clock.advance(2) + widget._tick() + assert widget.save_button.property('checkpointReminder') + + +def test_cancelled_close_keeps_status_active_and_disposal_disconnects(status): + widget, controller, clock, gui = status + + @connect(event='close', sender=gui) + def cancel(sender): + return False + + try: + gui.close() + assert not gui._closed + assert not widget._closed + _edit(controller, clock) + assert 'Draft protected' in widget.label.text() + finally: + unconnect(cancel) + widget.dispose() + last = widget.label.text() + controller.recovery.update(state='error', error='Late worker result') + assert widget.label.text() == last + + +def test_real_recovery_dirty_undo_clean_dirty_restarts_reminder(qtbot, tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=False, offer_recovery=False) + widget = gui._checkpoint_status + clock = Clock() + widget._timer.stop() + widget._clock, widget._wall_clock = clock.monotonic, clock.time + widget._last_input = clock.value + supervisor = controller.supervisor + try: + assert not supervisor.is_dirty() + supervisor.label('group', 'mua', [0]) + assert supervisor.is_dirty() + clock.advance(901) + widget._tick() + assert widget.save_button.property('checkpointReminder') + supervisor.undo() + assert not supervisor.is_dirty() + assert not widget.save_button.property('checkpointReminder') + clock.advance(5000) + supervisor.label('group', 'good', [0]) + assert not widget.save_button.property('checkpointReminder') + clock.advance(901) + widget._tick() + assert widget.save_button.property('checkpointReminder') + finally: + gui.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_refractory.py b/phy/apps/large_recording/tests/test_refractory.py new file mode 100644 index 000000000..65b8a016a --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory.py @@ -0,0 +1,132 @@ +"""Independent pairwise oracle, boundary streaming, and scientific grid tests.""" + +from concurrent.futures import CancelledError + +import numpy as np +import pytest + +from phy.apps.large_recording.refractory import ( + RefractoryAccumulator, + RefractoryGeometry, + RefractoryUnavailable, + deduplicate, + window_curve, +) + + +def test_shared_geometry_counter_only_and_sparse_updates(monkeypatch): + width = 1800 * 30000 + intervals = [[0, width * 2000]] + geometry = RefractoryGeometry(30000, width * 2000, intervals) + left, right = ( + RefractoryAccumulator(30000, width * 2000, intervals, geometry=geometry) for _ in range(2) + ) + assert left.recorded is right.recorded is geometry.recorded + assert not geometry.recorded.flags.writeable + + def no_full_grid(*args, **kwargs): + raise AssertionError('A sparse feed must not allocate a full histogram grid.') + + monkeypatch.setattr(np, 'bincount', no_full_grid) + ticks = np.array([0, 30, width * 1999, width * 1999 + 30]) + left.feed(ticks[:3], np.ones(3)) + left.feed(ticks[3:], np.ones(1)) + right.feed(ticks, np.ones(4)) + counters, full = left.finish_counters(), right.finish() + assert 'contamination' not in counters + assert 'recorded_seconds' not in counters + for name in ('spikes', 'violations'): + np.testing.assert_array_equal(counters[name], full[name]) + assert not counters[name].flags.writeable + assert counters['spikes'][[0, 1999]].tolist() == [2, 2] + assert counters['violations'][[0, 1999]].tolist() == [1, 1] + with pytest.raises(ValueError, match='geometry'): + RefractoryAccumulator(30000, width * 2000, [[1, width * 2000]], geometry=geometry) + + +def brute(t, a, radius=9): + chosen = [] + for i in sorted(range(len(t)), key=lambda i: (-abs(float(a[i])), i)): + if all(abs(int(t[i]) - int(t[j])) > radius for j in chosen): + chosen.append(i) + return np.array(sorted(chosen), dtype=int) + + +@pytest.mark.parametrize('seed', range(12)) +def test_independent_oracle_and_every_stream_boundary(seed): + rng = np.random.default_rng(seed) + t = np.cumsum(rng.integers(0, 16, 220)).astype(np.int64) + a = rng.integers(-4, 5, len(t)).astype(np.float32) + keep = brute(t, a) + np.testing.assert_array_equal(np.flatnonzero(deduplicate(t, a, 9)), keep) + kept = t[keep] + expected_v = sum(9 < int(y) - int(x) <= 30 for i, x in enumerate(kept) for y in kept[i + 1 :]) + for chunk in (1, 2, 9, 17, 1000): + acc = RefractoryAccumulator(30000, 100000, [[0, 1000], [1100, 100000]]) + for start in range(0, len(t), chunk): + acc.feed(t[start : start + chunk], a[start : start + chunk]) + r = acc.finish() + assert r['duplicates_removed'] == len(t) - len(kept) + assert r['spikes'].sum() == len(kept) + assert r['violations'].sum() == expected_v + assert r['recorded_seconds'].sum() == pytest.approx(99900 / 30000) + + +def test_bin_boundary_later_partner_gap_and_padded_endpoint(): + edge = 1800 * 30000 + t = np.array([edge - 20, edge + 10, edge + 40], dtype=np.int64) + acc = RefractoryAccumulator(30000, edge * 3 + 1, [[0, edge], [edge + 5, edge * 3 + 1]]) + acc.feed(t, np.ones(3)) + result = acc.finish() + np.testing.assert_array_equal(result['spikes'], [1, 2, 0, 0]) + np.testing.assert_array_equal(result['violations'], [1, 1, 0, 0]) + np.testing.assert_array_equal(result['window_centres_h'], [0, 1, 2]) + assert result['window_centres_h'][-1] > acc.num_samples / acc.fs / 3600 + assert np.isnan(result['contamination']).all() + + +def test_cutoff_saturation_no_extra_clipping(): + _, curve = window_curve(np.array([100]), np.array([1000]), np.array([1800.0]), 30000) + np.testing.assert_array_equal(curve, [1.0]) + _, curve = window_curve(np.array([100]), np.array([999]), np.array([1800.0]), 30000) + assert np.isnan(curve).all() + + +def test_nonfinite_chain_budget_cancel_and_original_signed_precision(): + t = np.arange(200, dtype=np.int64) + acc = RefractoryAccumulator(30000, 1000, [[0, 1000]], max_component=100) + with pytest.raises(RefractoryUnavailable, match='budget'): + acc.feed(t, np.ones(200)) + with pytest.raises(RefractoryUnavailable, match='Nonfinite'): + deduplicate(t[:2], [1, np.nan], 9) + with pytest.raises(RefractoryUnavailable, match='Real numeric'): + deduplicate(t[:2], [1 + 2j, 3 + 4j], 9) + with pytest.raises(CancelledError): + deduplicate(t, np.ones(200), 9, lambda: True) + np.testing.assert_array_equal( + deduplicate(np.array([0, 1]), [-1.0, 1.0 + 1e-12], 9), [False, True] + ) + np.testing.assert_array_equal(deduplicate(np.array([0, 1]), [-1.0, 1.0], 9), [True, False]) + + +@pytest.mark.parametrize('dtype', ['int32', 'int64', 'uint32', 'uint64']) +def test_integer_tick_normalization_and_unsigned_overflow(dtype): + acc = RefractoryAccumulator(30000, 1000, [[0, 1000]]) + acc.feed(np.array([0, 9, 30], dtype=dtype), np.array([1.0, 2.0, 3.0])) + result = acc.finish() + assert result['spikes'].sum() == 2 + assert result['violations'].sum() == 1 + acc = RefractoryAccumulator(30000, 1000, [[0, 1000]]) + with pytest.raises(RefractoryUnavailable, match='int64'): + acc.feed(np.array([2**64 - 1], dtype=np.uint64), np.array([1.0])) + + +@pytest.mark.parametrize('fs,tc,tr', [(5000, 2, 5), (2500, 1, 2), (1500, 0, 2)]) +def test_python_sample_rounding_and_inclusive_pair_endpoint(fs, tc, tr): + acc = RefractoryAccumulator(fs, fs * 10, [[0, fs * 10]]) + assert acc.radius == tc and acc.tr == tr + acc.feed(np.array([0, tc, tc + tr], dtype=np.int64), np.array([1.0, 2.0, 3.0])) + result = acc.finish() + assert result['duplicates_removed'] == 1 + assert result['spikes'].sum() == 2 + assert result['violations'].sum() == 1 diff --git a/phy/apps/large_recording/tests/test_refractory_engine.py b/phy/apps/large_recording/tests/test_refractory_engine.py new file mode 100644 index 000000000..1c15f87fb --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory_engine.py @@ -0,0 +1,205 @@ +"""Current-membership, cancellation, source-integrity and cache regressions.""" + +from concurrent.futures import CancelledError + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import BoundedSession, project_assignments +from phy.apps.large_recording.live_summaries import ( + LiveSummaryEngine, + acquire_source_engine, + membership_expressions, + release_source_engine, +) +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.refractory_engine import RefractoryEngine +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.tests.test_refractory import brute +from phy.apps.large_recording.tests.test_source import make_sorting + + +def make_package(tmp_path): + params = make_sorting(tmp_path / 'source') + params.write_text(params.read_text().replace('sample_rate = 1.0', 'sample_rate = 30000.0')) + amp = np.arange(12, dtype=np.float64) - 6 + np.save(params.parent / 'amplitudes.npy', amp) + bounded = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=8, + window_seconds=0.0001, + stratum_seconds=0.0002, + bin_seconds=0.0002, + ) + return params.parent, bounded + + +def assert_oracle(engine, session, source): + expressions = session.membership_snapshot(session._runtime.active) + assert expressions == membership_expressions(session.unit_ids, session.events) + labels = np.load(source / 'spike_clusters.npy') + amp = np.load(source / 'amplitudes.npy') + labels = project_assignments(labels, session.events, {'amplitudes.npy': amp}) + ticks = np.load(source / 'spike_times.npy') + results = engine.resolve(expressions) + for unit, r in results.items(): + selected = labels == unit + t, a = ticks[selected], amp[selected] + kept = t[brute(t, a)] + assert r['spikes'].sum() == len(kept) + assert r['duplicates_removed'] == len(t) - len(kept) + assert r['violations'].sum() == sum( + 9 < int(y) - int(x) <= 30 for i, x in enumerate(kept) for y in kept[i + 1 :] + ) + + +def test_live_membership_restore_undo_reopen_and_signed_predicates(tmp_path): + source, bounded = make_package(tmp_path) + original = {p.name: hash_file(p) for p in source.iterdir()} + with BoundedSession(bounded) as session, LiveSummaryEngine(bounded, batch_size=3) as reader: + engine = RefractoryEngine(reader) + assert_oracle(engine, session, source) + session.record_merge([0, 1], 100) + assert_oracle(engine, session, source) + assert engine.last_path == 'unit ticks' + frozen = session.membership_snapshot([100]) + before = session.snapshot() + session.record_threshold_split( + 100, + [101, 102], + { + 'attribute': 'amplitudes.npy', + 'operator': '>=', + 'threshold': 0, + 'nonfinite': 'keep', + }, + ) + assert_oracle(engine, session, source) + after = session.snapshot() + session.restore(before) + assert_oracle(engine, session, source) + session.restore(after) + assert_oracle(engine, session, source) + session.record_merge([101, 102], 103) + assert_oracle(engine, session, source) + session.record_restore_parents(103, [104, 105], recursive=True) + assert_oracle(engine, session, source) + session.record_merge([104, 2], 106) + assert_oracle(engine, session, source) + with pytest.raises(TypeError): + frozen[100]['kind'] = 'source' + session.save() + with BoundedSession(bounded) as reopened, LiveSummaryEngine(bounded) as reader: + assert_oracle(RefractoryEngine(reader), reopened, source) + assert {p.name: hash_file(p) for p in source.iterdir()} == original + + +def test_cancel_reuses_authenticated_readers_and_rejects_warm_mutation(tmp_path): + source, bounded = make_package(tmp_path) + expressions = {0: {'kind': 'source', 'unit': 0}} + with LiveSummaryEngine(bounded, batch_size=3) as reader: + engine = RefractoryEngine(reader) + engine.resolve(expressions) + handles = dict(reader.handles) + with pytest.raises(CancelledError): + engine.resolve({1: {'kind': 'source', 'unit': 1}}, lambda: True) + assert reader.handles == handles + assert not any(h.closed for h in handles.values()) + assert engine.resolve(expressions)[0]['spikes'].sum() > 0 + amp = np.load(source / 'amplitudes.npy', mmap_mode='r+') + amp[0] += 1 + amp.flush() + with pytest.raises(ValueError, match='changed'): + engine.resolve(expressions) + + +def test_root_budget_does_not_retain_oversized_rows(tmp_path): + _, bounded = make_package(tmp_path) + with LiveSummaryEngine(bounded, batch_size=2) as reader: + engine = RefractoryEngine(reader, root_bytes=1) + engine.resolve({0: {'kind': 'source', 'unit': 0}}) + assert not engine.roots + + +def test_two_clients_share_authentication_and_only_final_close_releases(tmp_path): + _, bounded = make_package(tmp_path) + first_key, first = acquire_source_engine(bounded) + second_key, second = acquire_source_engine(bounded) + assert first is second + try: + engine = RefractoryEngine(first) + engine.resolve({0: {'kind': 'source', 'unit': 0}}) + handles = dict(first.handles) + release_source_engine(first_key) + first_key = None + assert not any(h.closed for h in handles.values()) + second._open(set(handles), None) + assert second.handles == handles + with pytest.raises(CancelledError): + second._open(set(handles), lambda: True) + assert second.handles == handles + finally: + if first_key is not None: + release_source_engine(first_key) + release_source_engine(second_key) + assert all(h.closed for h in handles.values()) + + +def test_cancel_mid_scan_retains_trust_but_never_partial_result(tmp_path): + _, bounded = make_package(tmp_path) + with LiveSummaryEngine(bounded, batch_size=2) as reader: + engine = RefractoryEngine(reader) + engine.resolve({0: {'kind': 'source', 'unit': 0}}) + handles = dict(reader.handles) + cancelled = [] + with pytest.raises(CancelledError): + engine.resolve( + {1: {'kind': 'source', 'unit': 1}}, + lambda: bool(cancelled), + lambda *args: cancelled.append(True), + ) + assert reader.handles == handles + assert engine.key({'kind': 'source', 'unit': 1}) not in engine.results + assert engine.resolve({1: {'kind': 'source', 'unit': 1}})[1]['status'] == 'ready' + assert reader.handles == handles + + +def test_cancelled_partial_authentication_keeps_metadata_mutation_guard(tmp_path): + source, bounded = make_package(tmp_path) + with LiveSummaryEngine(bounded) as reader: + with pytest.raises(CancelledError): + reader._open( + {'spike_clusters.npy', 'spike_times.npy'}, + lambda: 'spike_clusters.npy' in reader.arrays, + ) + assert 'spike_clusters.npy' in reader.arrays + with (source / 'cluster_group.tsv').open('a') as stream: + stream.write('100\tgood\n') + with pytest.raises(ValueError, match='metadata changed'): + reader._open({'spike_clusters.npy'}, None) + + +def test_one_nonfinite_unit_does_not_hide_other_rp_results(tmp_path): + source, bounded = make_package(tmp_path) + # Modify before preparation so the evidence identity authentically includes NaN. + from shutil import rmtree + + rmtree(bounded) + amp = np.load(source / 'amplitudes.npy') + amp[0] = np.nan + np.save(source / 'amplitudes.npy', amp) + bounded = prepare_large( + source / 'params.py', + bounded, + max_spikes=8, + window_seconds=0.0001, + stratum_seconds=0.0002, + bin_seconds=0.0002, + ) + with LiveSummaryEngine(bounded) as reader: + results = RefractoryEngine(reader).resolve( + {u: {'kind': 'source', 'unit': u} for u in (0, 1)} + ) + assert results[0]['status'] == 'unavailable' + assert results[1]['status'] == 'ready' diff --git a/phy/apps/large_recording/tests/test_refractory_resources.py b/phy/apps/large_recording/tests/test_refractory_resources.py new file mode 100644 index 000000000..681c1c83b --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory_resources.py @@ -0,0 +1,71 @@ +"""Allocation planning at real long-recording dimensions and budget boundaries.""" + +import pytest + +from phy.apps.large_recording.refractory_resources import ( + COMPONENT_ROW_BYTES, + plan_refractory_summaries, +) + + +def geometry(units=962, bins=2052): + return { + 'sample_rate': 30000, + 'num_samples': bins * 1800 * 30000, + 'unit_ids': list(range(units)), + 'valid_intervals': [[0, bins * 1800 * 30000]], + } + + +def test_carl_dimensions_fit_defaults_and_batch_is_bounded(): + plan = plan_refractory_summaries(geometry(), batch_size=10000000) + assert plan.disk_bytes < 67108864 + assert plan.memory_bytes <= 67108864 + assert plan.batch_size < 10000000 + assert plan.max_component >= 1 + assert plan.disk_bytes >= 16 * 962 * 2052 + + +def test_exact_disk_and_minimum_memory_boundaries(): + manifest = geometry(3, 2) + plan = plan_refractory_summaries(manifest) + minimum = plan.fixed_bytes + 3 * COMPONENT_ROW_BYTES + plan.row_bytes + with pytest.raises(ValueError, match=r'disk budget.*--max-bytes'): + plan_refractory_summaries(manifest, max_bytes=plan.disk_bytes - 1) + exact = plan_refractory_summaries(manifest, max_bytes=plan.disk_bytes, memory_bytes=minimum) + assert exact.batch_size == exact.max_component == 1 + assert exact.memory_bytes == minimum + with pytest.raises(ValueError, match=r'memory budget.*--rp-summary-memory-bytes'): + plan_refractory_summaries( + manifest, memory_bytes=minimum - 1, memory_option='--rp-summary-memory-bytes' + ) + + +def test_dtype_and_native_grid_scratch_are_accounted(): + manifest = geometry(3, 2) + baseline = plan_refractory_summaries(manifest, batch_size=10000000) + manifest['source_array_inventory'] = {'amplitudes.npy': {'dtype': 'float128'}} + wide = plan_refractory_summaries(manifest, native_grid_bytes=4096, batch_size=10000000) + assert wide.fixed_bytes == baseline.fixed_bytes + 4096 + assert wide.row_bytes > baseline.row_bytes + assert wide.batch_size < baseline.batch_size + + +def test_fragmented_exposure_metadata_is_budgeted_with_few_bins(): + manifest = geometry(1, 1) + baseline = plan_refractory_summaries(manifest) + manifest['valid_intervals'] = [[i * 2, i * 2 + 1] for i in range(100000)] + fragmented = plan_refractory_summaries(manifest) + assert fragmented.fixed_bytes >= baseline.fixed_bytes + 128 * 99999 + with pytest.raises(ValueError, match='memory budget'): + plan_refractory_summaries( + manifest, memory_bytes=baseline.fixed_bytes + COMPONENT_ROW_BYTES + baseline.row_bytes + ) + + +@pytest.mark.parametrize('key,value', [('sample_rate', 0), ('num_samples', 0)]) +def test_invalid_scientific_geometry(key, value): + manifest = geometry() + manifest[key] = value + with pytest.raises(ValueError): + plan_refractory_summaries(manifest) diff --git a/phy/apps/large_recording/tests/test_refractory_scaling.py b/phy/apps/large_recording/tests/test_refractory_scaling.py new file mode 100644 index 000000000..29c6df136 --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory_scaling.py @@ -0,0 +1,85 @@ +"""Sparse real-dimension regression for bounded RP summary construction.""" + +import numpy as np + +from phy.apps.large_recording.live_summaries import LiveSummaryEngine +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.refractory_engine import RefractoryEngine +from phy.apps.large_recording.refractory_resources import ( + DEFAULT_RP_MAX_BYTES, + DEFAULT_RP_MEMORY_BYTES, + plan_refractory_summaries, +) +from phy.apps.large_recording.refractory_store import build_refractory_summaries +from phy.apps.large_recording.tests.test_source import make_sorting + + +def test_sparse_carl_dimensions_build_and_read_all_unit_counters(tmp_path): + units = 962 + bins = 2052 + samples_per_bin = 1800 * 30000 + duration = bins * samples_per_bin + params = make_sorting(tmp_path / 'source') + + # One globally ordered event per unit keeps the fixture sparse while the + # scientific counter grids exercise the full unit-by-bin dimensions. + np.save(params.parent / 'spike_times.npy', np.arange(units, dtype=np.int64) * 1000) + np.save(params.parent / 'spike_clusters.npy', np.arange(units, dtype=np.int32)) + np.save(params.parent / 'spike_templates.npy', np.zeros(units, dtype=np.int32)) + np.save(params.parent / 'amplitudes.npy', np.ones(units, dtype=np.float32)) + for name in ( + 'spike_positions.npy', + 'spike_depths.npy', + 'pc_features.npy', + 'pc_feature_ind.npy', + ): + (params.parent / name).unlink(missing_ok=True) + for path in params.parent.glob('_phy_spikes_subset.*.npy'): + path.unlink() + params.write_text( + params.read_text() + .replace('sample_rate = 1.0', 'sample_rate = 30000.0') + .replace('num_samples = 20', f'num_samples = {duration}') + ) + + bounded = prepare_large(params, tmp_path / 'bounded', max_spikes=units) + progress = [] + output = build_refractory_summaries( + bounded, + batch_size=10_000_000, + progress=lambda message, *args: progress.append(message), + ) + + with LiveSummaryEngine(bounded) as source: + plan = plan_refractory_summaries( + source.manifest, + batch_size=10_000_000, + native_grid_bytes=source.edges.nbytes + source.exposure.nbytes, + ) + assert plan.units == units + assert plan.bins == bins + assert plan.batch_size < 10_000_000 + assert plan.memory_bytes <= DEFAULT_RP_MEMORY_BYTES + assert plan.disk_bytes <= DEFAULT_RP_MAX_BYTES + plan_message = next(message for message in progress if 'RP plan:' in message) + assert f'batch {plan.batch_size}' in plan_message + + artifact_bytes = sum(path.stat().st_size for path in output.iterdir()) + assert artifact_bytes <= plan.disk_bytes <= DEFAULT_RP_MAX_BYTES + + params.parent.rename(tmp_path / 'offline-source') + + def no_source(*args, **kwargs): + raise AssertionError('Prepared RP counters must work without source files.') + + with LiveSummaryEngine(bounded) as reader: + reader._open = reader._unchanged = no_source + engine = RefractoryEngine(reader) + for unit in range(units): + result = engine.resolve({unit: {'kind': 'source', 'unit': unit}})[unit] + assert result['status'] == 'ready' + expected_spikes = np.zeros(bins, dtype=np.int64) + expected_spikes[0] = 1 + np.testing.assert_array_equal(result['spikes'], expected_spikes) + np.testing.assert_array_equal(result['violations'], np.zeros(bins, dtype=np.int64)) + assert result['duplicates_removed'] == 0 diff --git a/phy/apps/large_recording/tests/test_refractory_service.py b/phy/apps/large_recording/tests/test_refractory_service.py new file mode 100644 index 000000000..7be6d4d9d --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory_service.py @@ -0,0 +1,219 @@ +"""Demand gating, stale IDs, worker delivery and persistent-artist regressions.""" + +from queue import Queue +from threading import Event + +import numpy as np +from phylib.utils import Bunch + +from phy.apps.large_recording import refractory_service +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.tests.test_refractory_engine import make_package + + +def test_demand_coalescing_stale_completion_reused_id_and_close(qtbot, tmp_path, monkeypatch): + source, bounded = make_package(tmp_path) + workers = [] + + class Worker: + def __init__(self, *args): + self.jobs = Queue() + self.stopped = False + workers.append(self) + + def stop(self): + self.stopped = True + + monkeypatch.setattr(refractory_service, '_Worker', Worker) + with BoundedSession(bounded) as session: + service = refractory_service.RefractoryService( + Bunch(dir_path=bounded, bounded_session=session) + ) + service.request([0], enabled=False) + service._start() + assert not workers + service.request([0]) + service._start() + payload, first = workers[0].jobs.get_nowait() + service.request([0]) + assert not first.is_set() # Unchanged membership and metadata reuse work. + original = session.snapshot() + session.record_merge([0, 1], 100) + service.request([100]) + assert first.is_set() + service._completed((first, {0: {'old': True}}, None)) + assert not service.results + service._start() + _, second = workers[0].jobs.get_nowait() + session.restore(original) + session.record_merge([0, 2], 100) + service.request([100]) + assert second.is_set() + service._completed((second, {100: {'old': True}}, None)) + service._start() + _, third = workers[0].jobs.get_nowait() + service._completed((third, {100: {'current': True}}, None)) + assert service.results[100]['current'] + service.close() + assert workers[0].stopped + service._completed((third, {100: {'late': True}}, None)) + assert not service.results + + +def test_actual_worker_current_membership_delivery_and_hidden_cancel(qtbot, tmp_path): + _, bounded = make_package(tmp_path) + with BoundedSession(bounded) as session: + service = refractory_service.RefractoryService( + Bunch(dir_path=bounded, bounded_session=session) + ) + try: + service.request([0, 1]) + qtbot.waitUntil(lambda: bool(service.results), timeout=10000) + assert set(service.results) == {0, 1} + session.record_merge([0, 1], 100) + service.request([100]) + assert not service.results + qtbot.waitUntil(lambda: 100 in service.results, timeout=10000) + assert service.results[100]['duplicates_removed'] > 0 + service.request([], enabled=False) + assert not service.results + finally: + worker = service._worker + service.close() + qtbot.waitUntil(lambda: not worker.thread.is_alive(), timeout=10000) + + +def test_ordinary_worker_uses_frozen_original_rows(qtbot, tmp_path): + source, _ = make_package(tmp_path) + from phy.cluster.clustering import Clustering + + clustering = Clustering(np.load(source / 'spike_clusters.npy')) + snapshot = clustering.membership_snapshot([0, 1]) + assert not snapshot[0].flags.writeable + service = refractory_service.RefractoryService( + Bunch( + dir_path=source, + supervisor=Bunch(clustering=clustering), + ) + ) + try: + service.request([0]) + qtbot.waitUntil( + lambda: bool(service.results) or service.message.startswith('RP unavailable:'), + timeout=10000, + ) + assert 0 in service.results, service.message + old = snapshot[0].copy() + clustering.merge([0, 1]) + np.testing.assert_array_equal(snapshot[0], old) + target = max(clustering.cluster_ids) + service.request([target]) + qtbot.waitUntil(lambda: target in service.results, timeout=10000) + assert service.results[target]['duplicates_removed'] > 0 + finally: + worker = service._worker + service.close() + if worker is not None: + qtbot.waitUntil(lambda: not worker.thread.is_alive(), timeout=10000) + + +def test_unrelated_late_progress_does_not_publish(qtbot, tmp_path): + service = refractory_service.RefractoryService(Bunch(dir_path=tmp_path)) + service._running = Event() + message = service.message + service._progress((Event(), 'late', 1, 1)) + assert service.message == message + service.close() + + +def test_ordinary_global_validation_failure_discards_all_results(qtbot, tmp_path, monkeypatch): + source, _ = make_package(tmp_path) + from phy.apps.large_recording.refractory import RefractoryAccumulator + from phy.cluster.clustering import Clustering + + clustering = Clustering(np.load(source / 'spike_clusters.npy')) + original = RefractoryAccumulator.finish + changed = [] + + def finish(accumulator, cancel=None): + value = original(accumulator, cancel) + if not changed: + with (source / 'params.py').open('a') as stream: + stream.write('\n# exposure changed during computation\n') + changed.append(True) + return value + + monkeypatch.setattr(RefractoryAccumulator, 'finish', finish) + service = refractory_service.RefractoryService( + Bunch( + dir_path=source, + supervisor=Bunch(clustering=clustering), + ) + ) + try: + service.request([0, 1]) + qtbot.waitUntil(lambda: service.message.startswith('RP unavailable:'), timeout=10000) + assert changed and not service.results + assert 'changed' in service.message + finally: + worker = service._worker + service.close() + qtbot.waitUntil(lambda: not worker.thread.is_alive(), timeout=10000) + + +def test_ordinary_nonfinite_unit_preserves_healthy_unit(qtbot, tmp_path): + source, _ = make_package(tmp_path) + from phy.cluster.clustering import Clustering + + amp = np.load(source / 'amplitudes.npy') + amp[0] = np.nan + np.save(source / 'amplitudes.npy', amp) + service = refractory_service.RefractoryService( + Bunch( + dir_path=source, + supervisor=Bunch(clustering=Clustering(np.load(source / 'spike_clusters.npy'))), + ) + ) + try: + service.request([0, 1]) + qtbot.waitUntil(lambda: bool(service.results), timeout=10000) + assert service.results[0]['status'] == 'unavailable' + assert service.results[1]['status'] == 'ready' + finally: + worker = service._worker + service.close() + qtbot.waitUntil(lambda: not worker.thread.is_alive(), timeout=10000) + + +def test_ordinary_cache_hit_still_rejects_final_source_mutation(qtbot, tmp_path, monkeypatch): + source, _ = make_package(tmp_path) + from phy.cluster.clustering import Clustering + + service = refractory_service.RefractoryService( + Bunch( + dir_path=source, + supervisor=Bunch(clustering=Clustering(np.load(source / 'spike_clusters.npy'))), + ) + ) + try: + service.request([0]) + qtbot.waitUntil(lambda: bool(service.results), timeout=10000) + original = refractory_service.hashlib.sha256 + changed = [] + + def mutate(*args, **kwargs): + if not changed: + with (source / 'params.py').open('a') as stream: + stream.write('\n# changed while hashing a cached membership\n') + changed.append(True) + return original(*args, **kwargs) + + monkeypatch.setattr(refractory_service.hashlib, 'sha256', mutate) + service.request([], enabled=False) + service.request([0]) + qtbot.waitUntil(lambda: service.message.startswith('RP unavailable:'), timeout=10000) + assert changed and not service.results + finally: + worker = service._worker + service.close() + qtbot.waitUntil(lambda: not worker.thread.is_alive(), timeout=10000) diff --git a/phy/apps/large_recording/tests/test_refractory_store.py b/phy/apps/large_recording/tests/test_refractory_store.py new file mode 100644 index 000000000..e3577be63 --- /dev/null +++ b/phy/apps/large_recording/tests/test_refractory_store.py @@ -0,0 +1,505 @@ +"""Prepared-snapshot RP: offline memberships, boundaries, integrity and budgets.""" + +import json +from concurrent.futures import CancelledError +from shutil import copytree, rmtree + +import numpy as np +import pytest +from click.testing import CliRunner + +from phy.apps import phycli +from phy.apps.large_recording.curation import BoundedSession +from phy.apps.large_recording.live_summaries import LiveSummaryEngine +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.refractory import RefractoryAccumulator +from phy.apps.large_recording.refractory_engine import RefractoryEngine +from phy.apps.large_recording.refractory_store import build_refractory_summaries +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.summary_store import ( + SummaryStore, + attach_summary_store, + build_summary_store, + estimate_summary_store, +) +from phy.apps.large_recording.tests.test_refractory import brute +from phy.apps.large_recording.tests.test_refractory_engine import assert_oracle, make_package +from phy.apps.large_recording.tests.test_source import make_sorting + + +def no_source(*args, **kwargs): + raise AssertionError('Prepared RP must not open/stat/hash the source.') + + +def equal_results(left, right): + assert left.keys() == right.keys() + for u in left: + assert left[u].keys() == right[u].keys() + for k in left[u]: + if isinstance(left[u][k], np.ndarray): + np.testing.assert_array_equal(left[u][k], right[u][k]) + else: + assert left[u][k] == right[u][k] + + +@pytest.mark.parametrize('counters,timestamps', [(True, False), (False, True), (True, True)]) +def test_originals_offline_equal_source_and_pairwise_oracle(tmp_path, counters, timestamps): + source, bounded = make_package(tmp_path) + expressions = {u: {'kind': 'source', 'unit': u} for u in (0, 1, 2, 99)} + with LiveSummaryEngine(bounded, batch_size=2) as reader: + expected = RefractoryEngine(reader).resolve(expressions) + if counters: + build_refractory_summaries(bounded, batch_size=2) + if timestamps: + build_summary_store(bounded, tmp_path / 'store', timestamps=True, batch_size=2) + source.rename(tmp_path / 'offline') + with LiveSummaryEngine(bounded, batch_size=1) as reader: + reader._open = reader._unchanged = no_source + engine = RefractoryEngine(reader) + equal_results(engine.resolve(expressions), expected) + equal_results(engine.resolve(expressions), expected) + assert 'prepared' in engine.last_path + + +def test_timestamp_histories_oracle_undo_restore_reopen_and_portability(tmp_path): + source, bounded = make_package(tmp_path) + store = build_summary_store(bounded, tmp_path / 'store', timestamps=True, batch_size=2) + original = {p.name: hash_file(p) for p in source.iterdir()} + copytree(store, tmp_path / 'copied') + rmtree(store) + attach_summary_store(bounded, tmp_path / 'copied') + with BoundedSession(bounded) as session, LiveSummaryEngine(bounded, batch_size=1) as reader: + reader._open = no_source + engine = RefractoryEngine(reader) + assert_oracle(engine, session, source) + session.record_merge([0, 1], 100) + assert_oracle(engine, session, source) + before = session.snapshot() + session.record_threshold_split( + 100, + [101, 102], + { + 'attribute': 'amplitudes.npy', + 'operator': '>=', + 'threshold': -1 + 1e-12, + 'nonfinite': 'keep', + }, + ) + assert_oracle(engine, session, source) + after = session.snapshot() + session.restore(before) + assert_oracle(engine, session, source) + session.restore(after) + assert_oracle(engine, session, source) + session.record_merge([101, 102], 103) + assert_oracle(engine, session, source) + session.record_restore_parents(103, [104, 105], recursive=True) + assert_oracle(engine, session, source) + session.save() + with BoundedSession(bounded) as session, LiveSummaryEngine(bounded) as reader: + reader._open = no_source + assert_oracle(RefractoryEngine(reader), session, source) + assert {p.name: hash_file(p) for p in source.iterdir()} == original + + +@pytest.mark.parametrize('batch_size', [1, 2, 5]) +def test_scientific_and_custom_native_boundaries_precision_gaps(tmp_path, batch_size): + params = make_sorting(tmp_path / 'source') + edge = 1800 * 30000 + duration = 3 * edge + 1 + ticks = np.array( + [ + edge - 20, + edge - 9, + edge - 1, + edge, + edge + 1, + edge + 8, + edge + 10, + edge + 30, + edge + 40, + 2 * edge, + 2 * edge + 10, + 3 * edge, + ] + ) + amplitudes = np.array([-1.0, 1 + 1e-12, 3.0, 2.0, -3.0, 4.0, 4.0, 2.0, 1.0, 3.0, 1.0, 1.0]) + labels = np.array([0, 0, 1, 0, 0, 1, 1, 0, 0, 2, 99, 99], dtype=np.int32) + for name, values in [ + ('spike_times', ticks), + ('amplitudes', amplitudes), + ('spike_clusters', labels), + ]: + np.save(params.parent / f'{name}.npy', values) + params.write_text( + params.read_text() + .replace('sample_rate = 1.0', 'sample_rate = 30000.0') + .replace('num_samples = 20', f'num_samples = {duration}') + ) + bounded = prepare_large( + params, + tmp_path / 'bounded', + max_spikes=8, + valid_intervals=[[0, 2 * edge + 20], [2 * edge + 100, duration]], + bin_seconds=2700, + ) + build_refractory_summaries(bounded, batch_size=batch_size) + build_summary_store(bounded, tmp_path / 'store', timestamps=True, batch_size=batch_size) + with LiveSummaryEngine(bounded, batch_size=batch_size) as source: + source._open = no_source + engine = RefractoryEngine(source) + expressions = { + 0: {'kind': 'source', 'unit': 0}, + 100: {'kind': 'union', 'parts': [{'kind': 'source', 'unit': u} for u in (0, 1)]}, + } + results = engine.resolve(expressions) + for unit, roots in [(0, [0]), (100, [0, 1])]: + mask = np.isin(labels, roots) + t, a = ticks[mask], amplitudes[mask] + acc = RefractoryAccumulator(30000, duration, source.manifest['valid_intervals']) + acc.feed(t, a) + expected = acc.finish() + equal_results({unit: results[unit]}, {unit: expected}) + kept = t[brute(t, a)] + np.testing.assert_array_equal( + results[unit]['spikes'], np.bincount(kept // edge, minlength=4) + ) + v = np.zeros(4, dtype=np.int64) + for i, x in enumerate(kept): + v[x // edge] += sum(9 < int(y) - int(x) <= 30 for y in kept[i + 1 :]) + np.testing.assert_array_equal(results[unit]['violations'], v) + + +@pytest.mark.parametrize('artifact', ['counters', 'timestamps']) +def test_corruption_cancellation_and_cached_replacement_never_publish(tmp_path, artifact): + source, bounded = make_package(tmp_path) + if artifact == 'counters': + path = build_refractory_summaries(bounded, batch_size=2) + payload = path / '0.npz' + else: + path = build_summary_store(bounded, tmp_path / 'store', timestamps=True, batch_size=2) + payload = path / 'data.bin' + expression = {0: {'kind': 'source', 'unit': 0}} + with LiveSummaryEngine(bounded, batch_size=1) as reader: + engine = RefractoryEngine(reader) + assert engine.resolve(expression)[0]['status'] == 'ready' + with pytest.raises(CancelledError): + engine.resolve(expression, cancel=lambda: True) + raw = payload.read_bytes() + payload.write_bytes(bytes([raw[0] ^ 1]) + raw[1:]) + # The corrupted artifact cannot reuse its previously successful cache. + reader._open = no_source + with pytest.raises(AssertionError, match='must not'): + engine.resolve(expression) + if artifact == 'timestamps': + assert engine.artifact_stamp is None + assert hash_file(source / 'amplitudes.npy') + + +def test_timestamp_cancel_mid_read_has_no_partial_cache(tmp_path): + _, bounded = make_package(tmp_path) + build_summary_store(bounded, tmp_path / 'store', timestamps=True, batch_size=1) + cancelled = [] + with LiveSummaryEngine(bounded, batch_size=1) as reader: + engine = RefractoryEngine(reader) + with pytest.raises(CancelledError): + engine.resolve( + {0: {'kind': 'source', 'unit': 0}}, + lambda: bool(cancelled), + lambda *args: cancelled.append(True), + ) + assert not engine.results and not engine.prepared_results + + +def test_old_store_template_fallback_and_counter_budget(tmp_path): + _, bounded = make_package(tmp_path) + with pytest.raises(ValueError, match='budget'): + build_refractory_summaries(bounded, max_bytes=1) + assert not (bounded / '.phy' / 'refractory-summaries').exists() + build_summary_store(bounded, tmp_path / 'old') + with LiveSummaryEngine(bounded) as reader: + engine = RefractoryEngine(reader) + expression = { + 'kind': 'split', + 'parent': {'kind': 'source', 'unit': 0}, + 'predicate': { + 'attribute': 'spike_templates.npy', + 'operator': '>=', + 'threshold': 1, + 'nonfinite': 'keep', + }, + 'selected': True, + } + assert engine.resolve({1: expression})[1]['status'] == 'ready' + assert engine.last_path == 'source scan' + + +def test_estimates_cli_and_compatible_scalar_consumers(tmp_path): + _, bounded = make_package(tmp_path) + runner = CliRunner() + result = runner.invoke(phycli, ['build-rp-summaries', str(bounded), '--batch-size', '2']) + assert result.exit_code == 0, result.output + old = estimate_summary_store(bounded) + new = estimate_summary_store(bounded, timestamps=True) + assert new.payload_bytes > old.payload_bytes + result = runner.invoke( + phycli, + [ + 'build-summary-store', + str(bounded), + str(tmp_path / 'store'), + '--timestamps', + '--batch-size', + '2', + ], + ) + assert result.exit_code == 0, result.output + with LiveSummaryEngine(bounded) as reader, SummaryStore(reader) as store: + assert store.timestamps + assert store.dtype['amplitude'] == np.dtype('float64') + assert ( + sum(p.stat().st_size for p in store.path.iterdir() if p.is_file()) + <= new.estimated_bytes + ) + expression = {0: {'kind': 'source', 'unit': 0}} + # Existing rate/amplitude readers accept the extended row layout. + reader._open = no_source + assert reader.resolve(expression)[0]['counts'].sum() == 4 + + +def test_prepare_optins_and_failure_preserve_bounded_package(tmp_path, monkeypatch): + source, bounded = make_package(tmp_path) + rmtree(bounded) + prepared = prepare_large( + source / 'params.py', + bounded, + rp_summaries=True, + summary_store=tmp_path / 'rows', + store_timestamps=True, + ) + assert (prepared / '.phy' / 'refractory-summaries.json').exists() + with LiveSummaryEngine(prepared) as reader, SummaryStore(reader) as store: + assert store.timestamps + with pytest.raises(ValueError, match='requires'): + prepare_large(source / 'params.py', tmp_path / 'invalid', store_timestamps=True) + assert not (tmp_path / 'invalid').exists() + with pytest.raises(ValueError, match='disk budget.*--rp-summary-max-bytes'): + prepare_large( + source / 'params.py', tmp_path / 'budget', rp_summaries=True, rp_summary_max_bytes=1 + ) + assert not (tmp_path / 'budget').exists() + + def failed_build(*args, **kwargs): + raise OSError('Simulated late write failure.') + + monkeypatch.setattr( + 'phy.apps.large_recording.refractory_store.build_refractory_summaries', failed_build + ) + with pytest.raises(ValueError, match='Bounded package is ready.*build-rp-summaries'): + prepare_large(source / 'params.py', tmp_path / 'late-failure', rp_summaries=True) + with BoundedSession(tmp_path / 'late-failure') as session: + assert session.unit_ids + + +def test_nonfinite_original_and_counters_cancel_are_isolated(tmp_path): + source, bounded = make_package(tmp_path) + rmtree(bounded) + amp = np.load(source / 'amplitudes.npy') + amp[0] = np.nan + np.save(source / 'amplitudes.npy', amp) + prepare_large(source / 'params.py', bounded) + cancelled = [] + with pytest.raises(CancelledError): + build_refractory_summaries( + bounded, + batch_size=1, + cancel=lambda: bool(cancelled), + progress=lambda *args: cancelled.append(True), + ) + assert not (bounded / '.phy' / 'refractory-summaries.json').exists() + assert not list((bounded / '.phy').glob('.rp-building-*')) + build_refractory_summaries(bounded, batch_size=1) + source.rename(tmp_path / 'offline') + with LiveSummaryEngine(bounded) as reader: + reader._open = no_source + result = RefractoryEngine(reader).resolve( + {u: {'kind': 'source', 'unit': u} for u in (0, 1)} + ) + assert result[0]['status'] == 'unavailable' + assert result[1]['status'] == 'ready' + + +def test_timestamp_offset_width_and_invalid_reconstruction(tmp_path): + from phy.apps.large_recording.refractory_store import _unit_batches + from phy.apps.large_recording.summary_store import StoreIntegrityError, _layout + + _, bounded = make_package(tmp_path) + with LiveSummaryEngine(bounded) as reader: + reader.edges = np.array([0, 2**32 + 1], dtype=np.int64) + dtype, _, _ = _layout(reader, timestamps=True) + assert dtype['tick_offset'] == np.dtype('uint64') + reader.bins = 1 + + class FakeStore: + def batches(self, *args): + data = np.zeros(1, dtype=dtype) + data['tick_offset'] = 2**32 + 1 + yield data + + with pytest.raises(StoreIntegrityError, match='offset'): + list(_unit_batches(FakeStore(), reader, 0, 1, None)) + + +def test_timestamp_reference_changes_and_template_split_fallback(tmp_path): + _, bounded = make_package(tmp_path) + build_summary_store(bounded, tmp_path / 'first', timestamps=True) + build_summary_store(bounded, tmp_path / 'second', timestamps=True, attach=False) + with LiveSummaryEngine(bounded) as reader: + engine = RefractoryEngine(reader) + e = {0: {'kind': 'source', 'unit': 0}} + engine.resolve(e) + old_stamp = engine.artifact_stamp + attach_summary_store(bounded, tmp_path / 'second') + engine.resolve(e) + assert old_stamp != engine.artifact_stamp + expression = { + 'kind': 'split', + 'parent': e[0], + 'selected': True, + 'predicate': { + 'attribute': 'spike_templates.npy', + 'operator': '>=', + 'threshold': 1, + 'nonfinite': 'keep', + }, + } + assert engine.resolve({10: expression})[10]['status'] == 'ready' + assert engine.last_path == 'source scan' + + +@pytest.mark.parametrize('counters', [False, True]) +def test_result_grid_budget_is_explicit_and_never_reads_source(tmp_path, counters): + _, bounded = make_package(tmp_path) + if counters: + build_refractory_summaries(bounded) + else: + build_summary_store(bounded, tmp_path / 'store', timestamps=True) + with LiveSummaryEngine(bounded) as reader: + reader._open = no_source + value = RefractoryEngine(reader, result_bytes=1).resolve( + {0: {'kind': 'source', 'unit': 0}} + )[0] + assert value['status'] == 'unavailable' + assert 'budget' in value['message'] + + +def test_offline_unsupported_child_preserves_available_original(tmp_path): + source, bounded = make_package(tmp_path) + build_refractory_summaries(bounded) + source.rename(tmp_path / 'offline') + with LiveSummaryEngine(bounded) as reader: + result = RefractoryEngine(reader).resolve( + { + 0: {'kind': 'source', 'unit': 0}, + 100: { + 'kind': 'split', + 'parent': {'kind': 'source', 'unit': 1}, + 'selected': True, + 'predicate': { + 'attribute': 'spike_templates.npy', + 'operator': '>=', + 'threshold': 1, + 'nonfinite': 'keep', + }, + }, + } + ) + assert result[0]['status'] == 'ready' + assert result[100]['status'] == 'unavailable' + + +def test_counter_publication_failure_is_retryable_without_partial_results(tmp_path, monkeypatch): + from phy.apps.large_recording import refractory_store + + _, bounded = make_package(tmp_path) + publish = refractory_store.publish_directory + + def failed(*args): + raise OSError('injected publication failure') + + monkeypatch.setattr(refractory_store, 'publish_directory', failed) + with pytest.raises(OSError, match='injected'): + build_refractory_summaries(bounded) + assert not (bounded / '.phy' / 'refractory-summaries').exists() + with LiveSummaryEngine(bounded) as reader: + engine = RefractoryEngine(reader) + assert engine.resolve({0: {'kind': 'source', 'unit': 0}})[0]['status'] == 'ready' + assert engine.last_path == 'source scan' + monkeypatch.setattr(refractory_store, 'publish_directory', publish) + build_refractory_summaries(bounded) + with LiveSummaryEngine(bounded) as reader: + reader._open = no_source + assert ( + RefractoryEngine(reader).resolve({0: {'kind': 'source', 'unit': 0}})[0]['status'] + == 'ready' + ) + + +def test_reattachment_during_store_open_never_publishes_old_result(tmp_path, monkeypatch): + from phy.apps.large_recording import refractory_store + + _, bounded = make_package(tmp_path) + build_summary_store(bounded, tmp_path / 'first', timestamps=True) + build_summary_store(bounded, tmp_path / 'second', timestamps=True, attach=False) + original = refractory_store.SummaryStore + + def racing_open(reader): + store = original(reader) + attach_summary_store(bounded, tmp_path / 'second') + return store + + monkeypatch.setattr(refractory_store, 'SummaryStore', racing_open) + with LiveSummaryEngine(bounded) as reader: + reader._open = no_source + engine = RefractoryEngine(reader) + with pytest.raises(AssertionError, match='must not'): + engine.resolve({0: {'kind': 'source', 'unit': 0}}) + assert engine.artifact_stamp is None + assert not engine.prepared_results + + +def test_timestamp_empty_child_and_uint64_offsets_are_exact(tmp_path): + from phy.apps.large_recording.refractory_store import _unit_batches + + _, bounded = make_package(tmp_path) + build_summary_store(bounded, tmp_path / 'store', timestamps=True) + expression = { + 'kind': 'split', + 'parent': {'kind': 'source', 'unit': 0}, + 'selected': True, + 'predicate': { + 'attribute': 'amplitudes.npy', + 'operator': '>=', + 'threshold': 1000, + 'nonfinite': 'keep', + }, + } + with LiveSummaryEngine(bounded) as reader: + reader._open = no_source + result = RefractoryEngine(reader).resolve({100: expression})[100] + assert result['status'] == 'ready' + assert result['spikes'].sum() == result['violations'].sum() == 0 + assert np.isnan(result['contamination']).all() + reader.edges = np.array([0, 2**32 + 1], dtype=np.int64) + reader.bins = 1 + + class FakeStore: + def batches(self, *args): + data = np.zeros( + 1, dtype=[('bin', 'u1'), ('amplitude', 'f8'), ('tick_offset', 'u8')] + ) + data['tick_offset'] = 2**32 + yield data + + rows = list(_unit_batches(FakeStore(), reader, 0, 1, None)) + np.testing.assert_array_equal(rows[0]['spike_times.npy'], [2**32]) diff --git a/phy/apps/large_recording/tests/test_replay.py b/phy/apps/large_recording/tests/test_replay.py new file mode 100644 index 000000000..d3ce71235 --- /dev/null +++ b/phy/apps/large_recording/tests/test_replay.py @@ -0,0 +1,288 @@ +"""Full assignment oracle, revision binding and atomic publication regressions.""" + +import json +from contextlib import closing + +import numpy as np +import pytest + +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import Source, hash_file +from phy.apps.large_recording.tests.test_curation import make_session + + +@pytest.mark.parametrize('workers', [1, 3]) +def test_full_replay_chains_preserve_unseen_units_and_immutable_bytes(tmp_path, workers): + source, session = make_session(tmp_path) + original_hashes = {name: hash_file(source.path / name) for name in source.arrays} + original = source.arrays['spike_clusters.npy'].copy() + session.record_merge([0, 1], 100, {'group': 'good', 'confidence': 0.8}) + session.record_label('group', [100], 'mua') + session.record_merge([100, 2], 101, {'group': 'good', 'confidence': None}) + session.record_label('custom', [99, 101], 'verified') + session.save() + output = apply_curation( + source.params_path, session.path, tmp_path / 'curated', batch_size=3, workers=workers + ) + expected = np.where(np.isin(original, [0, 1, 2]), 101, original) + assert np.array_equal(np.load(output / 'spike_clusters.npy'), expected) + assert expected[-1] == 99 + curated = Source(output / 'params.py') + assert curated.metadata == session.metadata + assert curated.identity == source.identity + assert curated.revision != source.revision + lineage = json.loads((output / '_phy_curation_lineage.json').read_text()) + assert lineage['parent_revision'] == source.revision + assert lineage['revision'] == curated.revision + for name, digest in original_hashes.items(): + assert hash_file(source.path / name) == digest + if name != 'spike_clusters.npy': + assert hash_file(output / name) == digest + with pytest.raises(ValueError, match='revision'): + apply_curation(output / 'params.py', session.path, tmp_path / 'twice') + assert not (tmp_path / 'twice').exists() + second = apply_curation(source.params_path, session.path, tmp_path / 'second', batch_size=7) + assert hash_file(second / 'spike_clusters.npy') == hash_file(output / 'spike_clusters.npy') + + +def test_source_revision_and_feature_identity_are_independently_bound(tmp_path): + source, session = make_session(tmp_path) + session.save() + clusters = source.arrays['spike_clusters.npy'].copy() + amplitudes = source.arrays['amplitudes.npy'].copy() + source.close() + clusters[0] = 2 + np.save(source.path / 'spike_clusters.npy', clusters) + with pytest.raises(ValueError, match='revision'): + apply_curation(source.params_path, session.path, tmp_path / 'wrong_revision') + amplitudes[0] += 1 + np.save(source.path / 'amplitudes.npy', amplitudes) + with pytest.raises(ValueError, match='identity'): + apply_curation(source.params_path, session.path, tmp_path / 'wrong_feature') + assert not (tmp_path / 'wrong_revision').exists() + assert not (tmp_path / 'wrong_feature').exists() + + +@pytest.mark.parametrize('workers', [1, 3]) +def test_full_threshold_split_matches_scalar_oracle(tmp_path, workers): + source, session = make_session(tmp_path) + original = source.arrays['spike_clusters.npy'].copy() + amplitudes = source.arrays['amplitudes.npy'].copy() + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 15.0, + 'nonfinite': 'keep', + } + session.record_split(2, 100, 101, predicate, {'group': {100: 'noise', 101: 'good'}}) + session.record_merge([0, 100], 102, {'group': 'mua'}) + session.save() + expected = original.astype(np.int64) + expected[(original == 2) & (amplitudes < 15)] = 100 + expected[(original == 2) & ~(amplitudes < 15)] = 101 + expected[np.isin(expected, [0, 100])] = 102 + output = apply_curation( + source.params_path, session.path, tmp_path / 'split', batch_size=4, workers=workers + ) + assert np.array_equal(np.load(output / 'spike_clusters.npy'), expected) + assert Source(output / 'params.py').metadata == session.metadata + + +def test_failed_replay_does_not_publish_output(tmp_path, monkeypatch): + from phy.apps.large_recording import replay + + source, session = make_session(tmp_path) + session.save() + original = replay._write_json + + def fail(path, value): + if path.name == '_phy_curation_lineage.json': + raise OSError('injected replay interruption') + return original(path, value) + + monkeypatch.setattr(replay, '_write_json', fail) + with pytest.raises(OSError, match='interruption'): + apply_curation(source.params_path, session.path, tmp_path / 'interrupted') + assert not (tmp_path / 'interrupted').exists() + assert not list(tmp_path.glob('.interrupted-*')) + + +def test_replay_requires_committed_checkpoint_and_new_output(tmp_path): + source, session = make_session(tmp_path) + with pytest.raises(ValueError, match='Save'): + apply_curation(source.params_path, session.path, tmp_path / 'unsaved') + session.save() + with pytest.raises(FileExistsError): + apply_curation(source.params_path, session.path, source.path) + + +def test_replay_preserves_empty_split_children_and_allocator_lineage(tmp_path): + source, session = make_session(tmp_path) + session.record_split( + 2, + 100, + 101, + { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 100.0, + 'nonfinite': 'keep', + }, + ) + session.save() + output = apply_curation(source.params_path, session.path, tmp_path / 'empty_child') + curated = Source(output / 'params.py') + assert 101 in curated.unit_ids + assert curated.counts[curated.unit_ids.tolist().index(101)] == 0 + assert curated.next_cluster_id == 102 + + +def test_bounded_threshold_attribute_must_match_exact_source_rows(tmp_path): + source, session = make_session(tmp_path) + session.save() + session.close() + # Even a manifest that does not hash this optional attribute must not allow + # evidence values different from those used by the full-data predicate. + values = np.load(session.path / 'amplitudes.npy') + values[0] += 1 + np.save(session.path / 'amplitudes.npy', values) + with pytest.raises(ValueError, match='does not match source rows'): + apply_curation(source.params_path, session.path, tmp_path / 'bad_evidence') + assert not (tmp_path / 'bad_evidence').exists() + + +@pytest.mark.parametrize('kind', ['acquisition_samples', 'elapsed_ticks']) +def test_replay_preserves_explicit_clock_metadata_and_timestamp_bytes(tmp_path, kind): + source, session = make_session(tmp_path) + params = source.params_path + intervals = source.valid_intervals.tolist() + rate = source.sample_rate + source.close() + session.close() + contract = {'kind': kind, 'ticks_per_second': rate} + params.write_text( + params.read_text() + + f'\ntime_base = {contract!r}\nvalid_intervals = {intervals!r}\ndat_path = "None"\n' + ) + timestamps = params.parent / 'timestamps.json' + timestamps.write_bytes(b'{"producer": "clock mapping", "gaps": [4, 8]}\n') + upstream_path = params.parent / '_phy_spikes_subset.manifest.json' + upstream = json.loads(upstream_path.read_text()) + upstream['recording'].update( + { + 'time_base': contract, + 'frame_coordinates': kind, + 'window_bounds_coordinates': kind, + 'sample_index_coordinates': kind, + } + ) + upstream_path.write_text(json.dumps(upstream)) + source = Source(params) + manifest_path = session.path / '_phy_curation_manifest.json' + manifest = json.loads(manifest_path.read_text()) + manifest['source']['identity'] = source.identity + manifest['time_base'] = contract + manifest_path.write_text(json.dumps(manifest)) + from phy.apps.large_recording.curation import BoundedSession + + session = BoundedSession(session.path) + session.record_merge([0, 1], 100) + session.save() + output = apply_curation(params, session.path, tmp_path / 'curated') + assert (output / 'timestamps.json').read_bytes() == timestamps.read_bytes() + with Source(output / 'params.py') as curated: + assert curated.identity == source.identity + assert curated.time_base == contract + assert curated.params['dat_path'] is None + session.close() + source.close() + + +def test_parallel_replay_cancel_cleans_stage(tmp_path): + from concurrent.futures import CancelledError + + source, session = make_session(tmp_path) + session.record_merge([0, 1], 100) + session.save() + cancelled = False + + def progress(stage, done, total): + nonlocal cancelled + if stage == 'replaying assignments': + cancelled = True + + with pytest.raises(CancelledError): + apply_curation( + source.params_path, + session.path, + tmp_path / 'cancelled', + batch_size=3, + workers=3, + cancel=lambda: cancelled, + progress=progress, + ) + assert not (tmp_path / 'cancelled').exists() + assert not list(tmp_path.glob('.cancelled-*')) + + +def test_parallel_sparse_split_ties_nonfinite_and_metadata(tmp_path): + from phy.apps.large_recording.curation import BoundedSession + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'full') + assignments = np.load(params.parent / 'spike_clusters.npy') + assignments[assignments == 99] = 1000000000 + np.save(params.parent / 'spike_clusters.npy', assignments) + amplitude = np.load(params.parent / 'amplitudes.npy') + amplitude[[2, 5, 8]] = [np.nan, 15, 14] + np.save(params.parent / 'amplitudes.npy', amplitude) + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=5) + with closing(BoundedSession(bounded)) as session: + session.record_split( + 2, + 1000000001, + 1000000002, + { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': 15, + 'nonfinite': 'keep', + }, + ) + session.record_merge([0, 1000000001], 1000000003) + session.record_label('group', [1000000000, 1000000003], 'good') + session.save() + output = apply_curation(params, bounded, tmp_path / 'curated', workers=3, batch_size=6) + expected = assignments.astype(np.int64) + expected[(assignments == 2) & (amplitude < 15)] = 1000000001 + expected[(assignments == 2) & ~(amplitude < 15)] = 1000000002 + expected[np.isin(expected, [0, 1000000001])] = 1000000003 + np.testing.assert_array_equal(np.load(output / 'spike_clusters.npy'), expected) + with Source(output / 'params.py', workers=3) as curated: + assert curated.metadata == session.metadata + np.testing.assert_array_equal(np.load(params.parent / 'spike_clusters.npy'), assignments) + + +def test_replay_detects_corrupt_clone_and_cleans(tmp_path, monkeypatch): + from phy.apps.large_recording import replay + + source, session = make_session(tmp_path) + session.save() + copy = replay.copy_source_file + + def corrupt(src, dst, reserve_bytes): + result = copy(src, dst, reserve_bytes) + if src.name == 'amplitudes.npy': + values = np.load(dst) + values[0] += 1 + np.save(dst, values) + return result + + monkeypatch.setattr(replay, 'copy_source_file', corrupt) + original = hash_file(source.path / 'amplitudes.npy') + with pytest.raises(ValueError, match='immutable source coordinates'): + apply_curation(source.params_path, session.path, tmp_path / 'corrupt', workers=3) + assert not (tmp_path / 'corrupt').exists() + assert not list(tmp_path.glob('.corrupt-*')) + assert hash_file(source.path / 'amplitudes.npy') == original diff --git a/phy/apps/large_recording/tests/test_replay_program.py b/phy/apps/large_recording/tests/test_replay_program.py new file mode 100644 index 000000000..fd740b5d0 --- /dev/null +++ b/phy/apps/large_recording/tests/test_replay_program.py @@ -0,0 +1,131 @@ +"""Compiled projection agrees with the independent sequential interpreter.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import project_assignments +from phy.apps.large_recording.replay_program import AssignmentProgram +from phy.apps.large_recording.tests.test_restore_parents import _package, _predicate + + +def test_many_merges_compile_to_one_map_with_sparse_ids(): + units = [0, 2, 1000000, 2000000000] + original = np.array(units * 5, dtype=np.int64) + events = [ + {'operation': 'merge', 'parents': [0, 2], 'target': 2000000001}, + {'operation': 'label', 'field': 'notes', 'ids': [1000000], 'value': 'x'}, + {'operation': 'merge', 'parents': [1000000, 2000000001], 'target': 2000000002}, + ] + program = AssignmentProgram(units, events) + assert program.merge_runs == 1 + np.testing.assert_array_equal(program.project(original), project_assignments(original, events)) + events[0]['parents'].append(2000000000) + np.testing.assert_array_equal(program.project(original)[3::4], 2000000000) + + +@pytest.mark.parametrize('recursive', [False, True]) +@pytest.mark.parametrize('batch_size', [1, 3, 100]) +def test_mixed_split_nested_restore_and_merge_matches_reference(tmp_path, recursive, batch_size): + params, session = _package(tmp_path) + try: + session.record_threshold_split(0, [100, 101], _predicate()) + session.record_merge([101, 1], 102) + session.record_merge([102, 2], 103) + session.record_label('notes', [103], 'inspect') + children = [104, 105, 106] if recursive else [104, 105] + session.record_restore_parents(103, children, recursive=recursive) + session.record_merge([100, children[0]], 107) + original = np.load(params.parent / 'spike_clusters.npy') + attributes = {'amplitudes.npy': np.load(params.parent / 'amplitudes.npy')} + expected = project_assignments(original, session.events, attributes) + program = AssignmentProgram(session.unit_ids, session.events) + actual = np.concatenate( + [ + program.project( + original[start : start + batch_size], + { + name: values[start : start + batch_size] + for name, values in attributes.items() + }, + ) + for start in range(0, len(original), batch_size) + ] + ) + np.testing.assert_array_equal(actual, expected) + finally: + session.close() + + +@pytest.mark.parametrize('policy', ['keep', 'reject']) +@pytest.mark.parametrize('operator', ['<', '<=', '>', '>=']) +def test_predicate_boundaries_and_rejection_survive_remerging(policy, operator): + original = np.array([0, 0, 0, 1, 1]) + values = np.array([0.5, 1, np.nan, np.inf, 2]) + events = [ + {'operation': 'merge', 'parents': [0, 1], 'target': 2}, + { + 'operation': 'threshold_split', + 'parent': 2, + 'children': [3, 4], + 'predicate': { + 'attribute': 'amplitudes.npy', + 'operator': operator, + 'threshold': 1, + 'nonfinite': policy, + }, + }, + {'operation': 'merge', 'parents': [3, 4], 'target': 5}, + ] + program = AssignmentProgram([0, 1], events) + if policy == 'reject': + with pytest.raises(ValueError, match='Nonfinite'): + program.project(original, {'amplitudes.npy': values}) + else: + np.testing.assert_array_equal( + program.project(original, {'amplitudes.npy': values}), + project_assignments(original, events, {'amplitudes.npy': values}), + ) + with pytest.raises(ValueError, match='unavailable'): + program.project(original) + with pytest.raises(ValueError, match='scalar'): + program.project(original, {'amplitudes.npy': values[:-1]}) + + +def test_empty_batch_and_uint64_precision(): + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '>', + 'threshold': 2**63 + 1, + 'nonfinite': 'keep', + } + events = [ + {'operation': 'threshold_split', 'parent': 0, 'children': [1, 2], 'predicate': predicate} + ] + program = AssignmentProgram([0], events) + values = np.array([2**63, 2**63 + 1, 2**63 + 2], dtype=np.uint64) + original = np.zeros(3, dtype=np.int64) + np.testing.assert_array_equal(program.project(original, {'amplitudes.npy': values}), [1, 1, 2]) + assert program.project(original[:0], {'amplitudes.npy': values[:0]}).size == 0 + + +def test_compiled_writer_corruption_is_rejected_by_independent_verifier(tmp_path, monkeypatch): + from phy.apps.large_recording.replay import apply_curation + + params, session = _package(tmp_path) + try: + session.record_threshold_split(0, [100, 101], _predicate()) + session.record_merge([101, 1], 102) + session.save() + original = AssignmentProgram.project + + def corrupted(self, assignments, attributes=None): + return np.roll(original(self, assignments, attributes), 1) + + monkeypatch.setattr(AssignmentProgram, 'project', corrupted) + output = tmp_path / 'corrupt-output' + with pytest.raises(ValueError, match='semantic replay verification'): + apply_curation(params, session.path, output, batch_size=100) + assert not output.exists() + assert not list(tmp_path.glob('.corrupt-output-*')) + finally: + session.close() diff --git a/phy/apps/large_recording/tests/test_restore_parents.py b/phy/apps/large_recording/tests/test_restore_parents.py new file mode 100644 index 000000000..0820d70ff --- /dev/null +++ b/phy/apps/large_recording/tests/test_restore_parents.py @@ -0,0 +1,770 @@ +"""Exact historical parent restoration, independent of retained evidence size.""" + +import json +from copy import deepcopy + +import numpy as np +import pytest + +from phy.apps.large_recording.curation import BoundedSession, interpret_events, project_assignments +from phy.apps.large_recording.live_summaries import LiveSummaryEngine, membership_expressions +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.replay import apply_curation +from phy.apps.large_recording.source import Source +from phy.apps.large_recording.tests.test_source import make_sorting +from tools.curation_output_contract import _assignment_oracle, _history + + +def _package(tmp_path): + params = make_sorting(tmp_path / 'source') + path = prepare_large( + params, + tmp_path / 'bounded', + window_seconds=20, + stratum_seconds=20, + batch_size=2, + bin_seconds=5, + ) + return params, BoundedSession(path) + + +def _predicate(): + return {'attribute': 'amplitudes.npy', 'operator': '<', 'threshold': 4.0, 'nonfinite': 'keep'} + + +def test_older_restore_preserves_later_edits_and_replay_without_threshold_split(tmp_path): + params, session = _package(tmp_path) + original = np.load(params.parent / 'spike_clusters.npy') + session.record_merge([0, 1], 100) + session.record_merge([2, 99], 101) + session.record_label('group', [101], 'mua') + session.record_label('notes', [100], 'merged review') + session.record_restore_parents(100, [102, 103]) + expected = np.array([102 if v == 0 else 103 if v == 1 else 101 for v in original]) + assert session.metadata['group'] == {101: 'mua', 102: None, 103: None} + assert session.metadata['notes'] == {102: None, 103: None} + session.save() + path = session.path + session.close() + with BoundedSession(path) as reopened: + np.testing.assert_array_equal(reopened.assignments, expected) + assert reopened.restored_parent_ids == {102: 0, 103: 1} + output = apply_curation(params, path, tmp_path / 'curated', batch_size=2) + with Source(params) as source, Source(output / 'params.py') as curated: + np.testing.assert_array_equal(curated.arrays['spike_clusters.npy'], expected) + assert curated.metadata['group'][101] == 'mua' + assert curated.retired_units['100'] == { + 'operation': 'restore_parents', + 'replacements': [102, 103], + } + _assignment_oracle(source, curated, curated.metadata_provenance['history'], 2) + _history( + source, + curated, + json.loads((output / '_phy_curation_journal.json').read_text()), + json.loads((path / '_phy_curation_manifest.json').read_text()), + {101: {'group': 'mua'}}, + ) + second = prepare_large( + output / 'params.py', tmp_path / 'second', window_seconds=20, stratum_seconds=20 + ) + with BoundedSession(second) as prepared: + assert set(prepared.unit_ids) == {101, 102, 103} + with pytest.raises(ValueError, match='No recoverable merge origin'): + prepared.restore_parent_groups(101) + prepared.record_merge([102, 103], 104) + prepared.record_restore_parents(104, [105, 106]) + + +def test_nested_restored_composite_survives_reopen_with_earlier_threshold(tmp_path): + params, session = _package(tmp_path) + original = np.load(params.parent / 'spike_clusters.npy') + amplitudes = np.load(params.parent / 'amplitudes.npy') + session.record_threshold_split(0, [100, 101], _predicate()) + session.record_merge([101, 1], 102) + session.record_merge([102, 2], 103) + session.record_label('group', [99], 'good') + session.record_restore_parents(103, [104, 105]) + session.save() + path = session.path + session.close() + with BoundedSession(path) as session: + index, groups = session.restore_parent_groups(104) + assert index == 1 and list(groups) == [101, 1] + session.record_restore_parents(104, [106, 107]) + expected = original.copy().astype(np.int64) + expected[(original == 0) & (amplitudes >= 4)] = 100 + expected[(original == 0) & (amplitudes < 4)] = 106 + expected[original == 1] = 107 + expected[original == 2] = 105 + np.testing.assert_array_equal(session.assignments, expected) + expressions = membership_expressions(session.unit_ids, session.events) + before = membership_expressions(session.unit_ids, session.events[:1]) + assert expressions[106] == before[101] + assert session.metadata['group'][99] == 'good' + session.save() + with LiveSummaryEngine(path, batch_size=2) as engine: + summaries = engine.resolve(expressions) + for unit, summary in summaries.items(): + assert int(summary['counts'].sum()) == int(np.sum(expected == unit)) + output = apply_curation(params, path, tmp_path / 'curated', batch_size=2) + with Source(params) as source, Source(output / 'params.py') as curated: + np.testing.assert_array_equal(curated.arrays['spike_clusters.npy'], expected) + history = curated.metadata_provenance['history'] + _assignment_oracle(source, curated, history, 1) + _history( + source, + curated, + json.loads((output / '_phy_curation_journal.json').read_text()), + json.loads((path / '_phy_curation_manifest.json').read_text()), + {99: {'group': 'good'}}, + ) + wrong = deepcopy(history) + wrong[-1]['children'].reverse() + with pytest.raises(ValueError, match='Assignment disagrees'): + _assignment_oracle(source, curated, wrong, 2) + + +@pytest.mark.parametrize('mutation', ['prefix', 'revision', 'origin', 'children', 'metadata']) +def test_restore_binding_corruption_rejected_without_mutation(tmp_path, mutation): + _, session = _package(tmp_path) + with session: + session.record_merge([0, 1], 100) + event = session.preflight_restore_parents(100, [101, 102]) + if mutation == 'prefix': + event['merge_prefix_sha256'] = '0' * 64 + elif mutation == 'revision': + event['source_revision'] = 'other source' + elif mutation == 'origin': + event['merge_event_index'] = 3 + elif mutation == 'children': + event['children'] = [101] + else: + event['metadata']['group'][101] = 'good' + before = session.snapshot() + with pytest.raises(ValueError): + session._append(event) + assert session.events == before['events'] + np.testing.assert_array_equal(session.assignments, before['assignments']) + + +def test_split_or_nested_consumed_target_is_not_restorable(tmp_path): + _, session = _package(tmp_path) + with session: + session.record_merge([0, 1], 100) + session.record_merge([100, 2], 101) + with pytest.raises(ValueError, match='No recoverable'): + session.preflight_restore_parents(100, [102, 103]) + session.record_threshold_split(101, [102, 103], _predicate()) + with pytest.raises(ValueError, match='No recoverable'): + session.preflight_restore_parents(102, [104, 105]) + + +def test_full_source_parent_absent_from_retained_evidence_is_not_omitted(tmp_path): + from phy.apps.large_recording.tests.test_curation import make_session + + source, session = make_session(tmp_path) + try: + session.migrate_metadata(source.params_path) + session.record_merge([0, 99], 100) + _, groups = session.restore_parent_groups(100) + assert list(groups) == [0, 99] and len(groups[99]) == 0 + session.record_restore_parents(100, [101, 102]) + assert 102 in interpret_events(session.unit_ids, session.base_metadata, session.events)[0] + full = project_assignments( + source.arrays['spike_clusters.npy'], + session.events, + {'amplitudes.npy': source.arrays['amplitudes.npy']}, + ) + assert np.sum(full == 102) == 1 + finally: + session.close() + source.close() + + +def test_native_restore_history_metadata_and_full_counts(tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.apps.template.gui import TemplateController + + _, controller = make_controller(tmp_path) + path = controller.dir_path + try: + supervisor = controller.supervisor + supervisor.merge([0, 1], to=100) + supervisor.merge([2, 99], to=101) + supervisor.label('group', 'mua', [101]) + before = controller.bounded_session.snapshot() + out = supervisor.restore_parents(100) + assert out.added == [102, 103] + assert supervisor.selection.state.is_merge_mode + assert supervisor.selected_merge == [102, 103] + assert supervisor.parent_origins == {102: 0, 103: 1} + assert controller.get_full_count(102) == 4 + assert controller.get_full_count(103) == 3 + assert supervisor.cluster_meta.get('group', 102) is None + supervisor.undo() + assert supervisor.session.events == before['events'] + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before['assignments']) + supervisor.redo() + assert supervisor.session.events[-1]['operation'] == 'restore_parents' + assert supervisor.parent_origins == {102: 0, 103: 1} + supervisor.save() + finally: + controller.close() + reopened = TemplateController(dir_path=path, config_dir=tmp_path / 'reopened', plugins=[]) + try: + assert reopened.supervisor.parent_origins == {102: 0, 103: 1} + assert reopened.get_full_count(102) == 4 + assert reopened.supervisor.cluster_meta.get('group', 101) == 'mua' + finally: + reopened.close() + + +@pytest.mark.parametrize('phase', ['append', 'capture']) +def test_post_native_restore_failure_rolls_back_all_provenance(tmp_path, monkeypatch, phase): + from phy.apps.large_recording.tests.test_adapter import make_controller + + _, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + supervisor.merge([0, 1], to=100) + before = supervisor.session.snapshot() + histories = supervisor._global_history.current_position + origins = dict(supervisor.parent_origins) + lineage = supervisor.parent_lineage + lineage_before = ( + ( + dict(lineage.records), + dict(lineage.color_records), + dict(lineage.origins), + dict(lineage.restorations), + ) + if lineage is not None + else None + ) + + def fail(*args, **kwargs): + raise RuntimeError('injected post-native restore failure') + + monkeypatch.setattr( + supervisor.session if phase == 'append' else supervisor, + '_append' if phase == 'append' else '_capture', + fail, + ) + with pytest.raises(RuntimeError, match='post-native'): + supervisor.restore_parents(100) + assert supervisor.session.events == before['events'] + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before['assignments']) + assert supervisor.parent_origins == origins + assert not supervisor.clustering._restored_partitions + assert supervisor._global_history.current_position == histories + if lineage_before is not None: + assert ( + lineage.records, + lineage.color_records, + lineage.origins, + lineage.restorations, + ) == lineage_before + finally: + controller.close() + + +def test_native_restore_rejects_zero_evidence_parent_before_any_mutation(tmp_path): + from phy.apps.large_recording.supervisor import BoundedSupervisor + from phy.apps.large_recording.tests.test_curation import make_session + + source, session = make_session(tmp_path) + try: + session.migrate_metadata(source.params_path) + session.record_merge([0, 99], 100) + supervisor = BoundedSupervisor( + spike_clusters=session.assignments.copy(), + session=session, + cluster_labels=session.metadata, + ) + before = session.snapshot() + with pytest.raises(ValueError, match='no retained evidence'): + supervisor.restore_parents(100) + assert session.events == before['events'] + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before['assignments']) + assert supervisor._global_history.current_position == 0 + finally: + session.close() + source.close() + + +def test_restore_scratch_budget_subdivides_source_batches(tmp_path, monkeypatch): + import phy.apps.large_recording.curation as curation + + params, session = _package(tmp_path) + with session: + session.record_merge([0, 1, 2], 100) + session.record_restore_parents(100, [101, 102, 103]) + batches = [] + original = curation._membership_mask + + def tracked(expression, assignments, attributes, memo): + batches.append(len(assignments)) + return original(expression, assignments, attributes, memo) + + monkeypatch.setattr(curation, 'RESTORE_SCRATCH_BYTES', 64) + monkeypatch.setattr(curation, '_membership_mask', tracked) + source = np.load(params.parent / 'spike_clusters.npy') + actual = project_assignments(source, session.events) + expected = np.array( + [101 if v == 0 else 102 if v == 1 else 103 if v == 2 else v for v in source] + ) + np.testing.assert_array_equal(actual, expected) + assert batches and max(batches) == 1 + + +def test_accepted_review_becomes_historical_across_reopen_replay_and_reprepare(tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.apps.template.gui import TemplateController + from phy.cluster._propositions import PropositionStatus, proposition_key + + params, controller = make_controller( + tmp_path, + propositions={ + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}], + }, + ) + path = controller.dir_path + key = proposition_key([0, 1]) + try: + supervisor = controller.supervisor + supervisor.merge_propositions.accept(key, [0, 1], 100) + supervisor.merge([0, 1], to=100) + reviews = supervisor.merge_propositions.catalog.review_mapping()['reviews'] + supervisor.restore_parents(100) + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.undo() + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + supervisor.redo() + supervisor.save() + finally: + controller.close() + + def check(package, config): + controller = TemplateController(dir_path=package, config_dir=config, plugins=[]) + try: + catalog = controller.supervisor.merge_propositions.catalog + assert catalog.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + assert catalog.review_mapping()['reviews'] == reviews + finally: + controller.close() + + check(path, tmp_path / 'reopened') + output = apply_curation(params, path, tmp_path / 'curated', batch_size=2) + second = prepare_large( + output / 'params.py', tmp_path / 'second', window_seconds=20, stratum_seconds=20 + ) + check(second, tmp_path / 'reprepared') + + +def test_proposition_row_and_dock_refresh_immediately_after_restore_undo_redo(qtbot, tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.cluster._propositions import proposition_key + + _, controller = make_controller( + tmp_path, + propositions={ + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}], + }, + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + supervisor.block() + key = proposition_key([0, 1]) + supervisor.merge_propositions.accept(key, [0, 1, 2], 100) + supervisor.merge([0, 1, 2], to=100) + supervisor.block() + view = supervisor.merge_propositions_view + view.select_key(key) + reviews = supervisor.merge_propositions.catalog.review_mapping()['reviews'] + + def check(status): + selection = supervisor.selection.snapshot() + row = view._model.row_by_id(view._id_by_key[key]) + assert row['status'] == status + assert row['_catalog_status'] == status + assert status in view.dock.status + assert supervisor.merge_propositions.catalog.status_for(key).value == status + assert supervisor.merge_propositions.catalog.review_mapping()['reviews'] == reviews + assert supervisor.selection.snapshot() == selection + + check('accepted_modified') + restored = supervisor.restore_parents(100) + check('accepted_restored') + assert 'subsequently restored' in view._model.row_by_id(view._id_by_key[key])['reason'] + assert supervisor.selected_merge == restored.added + assert not supervisor.selection.state.merge.proposition_ids + supervisor.undo() + check('accepted_modified') + supervisor.redo() + check('accepted_restored') + assert supervisor.selected_merge == restored.added + assert not supervisor.selection.state.merge.proposition_ids + finally: + gui.close() + controller.close() + + +@pytest.mark.parametrize('workers', [1, 4]) +def test_recursive_restore_flattens_merges_and_stops_at_split_boundaries(tmp_path, workers): + params, session = _package(tmp_path) + original = np.load(params.parent / 'spike_clusters.npy') + amplitudes = np.load(params.parent / 'amplitudes.npy') + with session: + session.record_threshold_split(0, [100, 101], _predicate()) + session.record_merge([101, 1], 102) + session.record_merge([102, 2], 103) + session.record_label('group', [99], 'good') + index, groups = session.restore_parent_groups(103, recursive=True) + assert index == 2 and list(groups) == [101, 1, 2] + assert session.restore_parent_counts(103, recursive=True) == {101: None, 1: 3, 2: 3} + event = session.preflight_restore_parents(103, [104, 105, 106], recursive=True) + assert event['version'] == 4 + assert event['parent_references'] == [ + {'unit': 101, 'event_index': 0}, + {'unit': 1, 'event_index': -1}, + {'unit': 2, 'event_index': -1}, + ] + session._append(event) + expected = original.astype(np.int64).copy() + expected[(original == 0) & (amplitudes >= 4)] = 100 + expected[(original == 0) & (amplitudes < 4)] = 104 + expected[original == 1] = 105 + expected[original == 2] = 106 + np.testing.assert_array_equal(session.assignments, expected) + assert session.restored_parent_ids == {104: 101, 105: 1, 106: 2} + assert session.metadata['group'][99] == 'good' + session.save() + path = session.path + with BoundedSession(path) as reopened: + np.testing.assert_array_equal(reopened.assignments, expected) + reopened.record_merge([104, 105, 106], 107) + assert list(reopened.restore_parent_groups(107, recursive=True)[1]) == [101, 1, 2] + reopened.record_restore_parents(107, [108, 109, 110], recursive=True) + reopened.save() + output = apply_curation(params, path, tmp_path / 'curated', batch_size=2, workers=workers) + expected[expected == 104] = 108 + expected[expected == 105] = 109 + expected[expected == 106] = 110 + with Source(params) as source, Source(output / 'params.py') as curated: + np.testing.assert_array_equal(curated.arrays['spike_clusters.npy'], expected) + _assignment_oracle(source, curated, curated.metadata_provenance['history'], 2) + _history( + source, + curated, + json.loads((output / '_phy_curation_journal.json').read_text()), + json.loads((path / '_phy_curation_manifest.json').read_text()), + {99: {'group': 'good'}}, + ) + + +def test_v3_restores_immediate_parents_while_v4_restores_all_recorded_leaves(tmp_path): + _, session = _package(tmp_path) + with session: + session.record_merge([0, 1], 100) + session.record_merge([100, 2], 101) + legacy = session.preflight_restore_parents(101, [102, 103]) + assert legacy['version'] == 3 and 'parent_references' not in legacy + session._append(legacy) + assert session.restored_parent_ids == {102: 100, 103: 2} + assert list(session.restore_parent_groups(102, recursive=True)[1]) == [0, 1] + session.record_merge([102, 103], 104) + recursive = session.preflight_restore_parents(104, [105, 106, 107], recursive=True) + before = session.snapshot() + broken = deepcopy(recursive) + broken['parent_references'][0]['unit'] = 99 + with pytest.raises(ValueError, match='parent references'): + session._append(broken) + assert session.events == before['events'] + np.testing.assert_array_equal(session.assignments, before['assignments']) + session._append(recursive) + assert session.restored_parent_ids == {105: 0, 106: 1, 107: 2} + + +def test_recursive_native_restore_is_one_undoable_action(tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + + _, controller = make_controller(tmp_path) + try: + supervisor = controller.supervisor + supervisor.merge([0, 1], to=100) + supervisor.merge([100, 2], to=101) + supervisor.label('group', 'mua', [99]) + before = controller.bounded_session.snapshot() + out = supervisor.restore_parents(101) + assert out.added == [102, 103, 104] + assert supervisor.parent_origins == {102: 0, 103: 1, 104: 2} + assert supervisor.selected_merge == out.added + assert controller.bounded_session.events[-1]['version'] == 4 + assert len(controller.bounded_session.events) == len(before['events']) + 1 + supervisor.undo() + assert controller.bounded_session.events == before['events'] + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before['assignments']) + assert supervisor.cluster_meta.get('group', 99) == 'mua' + supervisor.redo() + assert supervisor.selected_merge == out.added + assert supervisor.cluster_meta.get('group', 99) == 'mua' + finally: + controller.close() + + +def test_recursive_restore_over_sixteen_leaves_and_repeated_aliases(): + from phy.apps.large_recording.source import hash_json + + units = list(range(20)) + original = np.repeat(units, 2) + events = [] + target = 100 + events.append( + { + 'version': 2, + 'operation': 'merge', + 'parents': [0, 1], + 'target': target, + 'metadata': {'group': None}, + } + ) + for unit in units[2:]: + events.append( + { + 'version': 2, + 'operation': 'merge', + 'parents': [target, unit], + 'target': target + 1, + 'metadata': {'group': None}, + } + ) + target += 1 + origin = len(events) - 1 + children = list(range(target + 1, target + 21)) + event = { + 'version': 4, + 'operation': 'restore_parents', + 'target': target, + 'children': children, + 'merge_event_index': origin, + 'merge_prefix_sha256': hash_json(events), + 'source_revision': 'test', + 'parent_references': [{'unit': unit, 'event_index': -1} for unit in units], + 'metadata': {'group': dict.fromkeys(children)}, + } + events.append(event) + active, _, _ = interpret_events(units, {}, events) + assert active == set(children) + np.testing.assert_array_equal(project_assignments(original, events), np.repeat(children, 2)) + broken = deepcopy(events) + broken[-1]['parent_references'][0]['unit'] = False + with pytest.raises(ValueError, match='parent references'): + interpret_events(units, {}, broken) + events.append( + { + 'version': 2, + 'operation': 'merge', + 'parents': children, + 'target': 200, + 'metadata': {'group': None}, + } + ) + again = deepcopy(event) + again.update( + target=200, + children=list(range(201, 221)), + merge_event_index=len(events) - 1, + merge_prefix_sha256=hash_json(events), + metadata={'group': dict.fromkeys(range(201, 221))}, + ) + events.append(again) + interpret_events(units, {}, events) + np.testing.assert_array_equal( + project_assignments(original, events), np.repeat(range(201, 221), 2) + ) + + +@pytest.mark.parametrize('extra', [False, True]) +def test_bounded_remerge_reassembles_review_scope_with_fresh_ids(qtbot, tmp_path, extra): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.cluster._propositions import PropositionStatus, proposition_key + + _, controller = make_controller( + tmp_path, + propositions={ + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}], + }, + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + supervisor.block() + key = proposition_key([0, 1]) + supervisor.merge_propositions.accept(key, [0, 1], 100) + supervisor.merge([0, 1], to=100) + original_review = supervisor.merge_propositions.catalog.review_mapping()['reviews'] + supervisor.restore_parents(100) + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + if extra: + supervisor.add_to_merge([2]) + merged = supervisor.merge(to=104) + assert merged is not None + expected = PropositionStatus.ACCEPTED_MODIFIED if extra else PropositionStatus.ACCEPTED + assert supervisor.merge_propositions.catalog.status_for(key) is expected + assert supervisor.merge_propositions.catalog.review_mapping()['reviews'] == original_review + supervisor.undo() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.redo() + assert supervisor.merge_propositions.catalog.status_for(key) is expected + supervisor.save() + finally: + gui.close() + controller.close() + from phy.apps.template.gui import TemplateController + + reopened = TemplateController( + dir_path=controller.dir_path, config_dir=tmp_path / 'reopened', plugins=[] + ) + try: + assert reopened.supervisor.merge_propositions.catalog.status_for(key) is expected + finally: + reopened.close() + + +def test_recursive_native_restore_rejects_hidden_zero_evidence_leaf(tmp_path): + from phy.apps.large_recording.supervisor import BoundedSupervisor + from phy.apps.large_recording.tests.test_curation import make_session + + source, session = make_session(tmp_path) + try: + session.migrate_metadata(source.params_path) + session.record_merge([0, 99], 100) + session.record_merge([100, 1], 101) + assert all(len(rows) for rows in session.restore_parent_groups(101)[1].values()) + supervisor = BoundedSupervisor( + spike_clusters=session.assignments.copy(), + session=session, + cluster_labels=session.metadata, + ) + before = session.snapshot() + with pytest.raises(ValueError, match='no retained evidence'): + supervisor.restore_parents(101) + assert session.events == before['events'] + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before['assignments']) + finally: + session.close() + source.close() + + +def test_bounded_partial_remerge_does_not_reaccept_modified_scope(qtbot, tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.cluster._propositions import PropositionStatus, proposition_key + + _, controller = make_controller( + tmp_path, + propositions={ + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [0, 1]}], + }, + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + supervisor.block() + key = proposition_key([0, 1]) + supervisor.merge_propositions.accept(key, [0, 1, 2], 100) + supervisor.merge([0, 1, 2], to=100) + restored = supervisor.restore_parents(100) + supervisor.deselect_from_merge([restored.added[-1]]) + assert supervisor.merge(to=105) is not None + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + finally: + gui.close() + controller.close() + + +def test_membership_containment_proves_only_structural_subset_relations(): + from phy.apps.large_recording.live_summaries import _membership_contains, _union + + source = {'kind': 'source', 'unit': 0} + other = {'kind': 'source', 'unit': 1} + selected = {'kind': 'split', 'parent': source, 'predicate': _predicate(), 'selected': True} + remainder = {**selected, 'selected': False} + all_units = _union([source, other]) + assert _membership_contains(source, selected) + assert _membership_contains(all_units, _union([selected, other])) + broader_filtered = {**selected, 'parent': all_units} + assert _membership_contains(broader_filtered, selected) + assert not _membership_contains(selected, source) + assert not _membership_contains(remainder, selected) + assert not _membership_contains(_union([selected, other]), all_units) + changed_predicate = {**selected, 'predicate': {**_predicate(), 'threshold': 5.0}} + assert not _membership_contains(changed_predicate, selected) + + +def test_bounded_reassembly_covers_historical_split_scope_after_reunion(qtbot, tmp_path): + from phy.apps.large_recording.tests.test_adapter import make_controller + from phy.cluster._propositions import PropositionStatus, proposition_key + + _, controller = make_controller( + tmp_path, + propositions={ + 'format_version': '2', + 'unit_ids': [0, 1, 2, 99], + 'merges': [{'unit_ids': [1, 2]}], + }, + ) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + try: + supervisor = controller.supervisor + supervisor.block() + # Historical acceptance contains only the selected part of source unit 0. + supervisor.split_source_amplitude(0, 4.0) + children = controller.bounded_session.events[-1]['children'] + remainder, selected = children + target = controller.bounded_session.next_cluster_id + key = proposition_key([1, 2]) + supervisor.merge_propositions.accept(key, [selected, 1, 2], target) + supervisor.merge([selected, 1, 2], to=target) + supervisor.restore_parents(target) + supervisor.add_to_merge([remainder]) + merged = supervisor.merge() + assert merged is not None + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_MODIFIED + ) + supervisor.undo() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.redo() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_MODIFIED + ) + finally: + gui.close() + controller.close() diff --git a/phy/apps/large_recording/tests/test_source.py b/phy/apps/large_recording/tests/test_source.py new file mode 100644 index 000000000..a0642ffe7 --- /dev/null +++ b/phy/apps/large_recording/tests/test_source.py @@ -0,0 +1,469 @@ +"""Exact source clock, alignment, and identity regressions.""" + +import json + +import numpy as np +import pytest + +from phy.apps.large_recording.source import Source, hash_file + + +def make_sorting(path, columns=False): + path.mkdir() + samples = np.array([0, 1, 1, 2, 5, 6, 10, 11, 14, 18, 19, 19], dtype=np.int64) + clusters = np.array([0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 99, 99], dtype=np.int32) + templates = np.arange(len(samples), dtype=np.int32) % 3 + arrays = { + 'spike_times.npy': samples, + 'spike_clusters.npy': clusters, + 'spike_templates.npy': templates, + 'amplitudes.npy': np.arange(len(samples), dtype=np.float32), + 'spike_positions.npy': np.column_stack((np.zeros(len(samples)), samples * 2)), + 'spike_depths.npy': samples.astype(np.float64) * 2, + 'templates.npy': np.arange(3 * 8 * 3, dtype=np.float32).reshape(3, 8, 3), + 'channel_map.npy': np.array([2, 0, 1], dtype=np.int32), + 'channel_positions.npy': np.array([[0, 0], [0, 10], [0, 20]]), + 'pc_features.npy': np.arange(len(samples) * 4, dtype=np.float32).reshape(-1, 2, 2), + 'pc_feature_ind.npy': np.array([[0, 2], [2, 1], [1, 0]], dtype=np.int32), + } + for name, array in arrays.items(): + if columns and name in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy'): + array = array[:, None] + np.save(path / name, array) + ids = np.array([0, 2, 3, 8, 11], dtype=np.int64) + channels = np.array([[0, -1], [2, 1], [1, -1], [2, -1], [0, 1]], dtype=np.int32) + waveforms = np.zeros((len(ids), 8, 2), dtype=np.float32) + for row, spike in enumerate(ids): + for slot, channel in enumerate(channels[row]): + if channel != -1: + waveforms[row, :, slot] = spike + channel + np.arange(8) / 10 + for suffix, array in (('spikes', ids), ('channels', channels), ('waveforms', waveforms)): + np.save(path / f'_phy_spikes_subset.{suffix}.npy', array) + (path / 'params.py').write_text( + "sample_rate = 1.0\nnum_samples = 20\ndat_path = None\nn_channels_dat = 3\ndtype = 'int16'\n" + ) + (path / 'cluster_group.tsv').write_text( + 'cluster_id\tgroup\n0\tgood\n1\tmua\n2\tgood\n99\tnoise\n' + ) + return path / 'params.py' + + +@pytest.mark.parametrize('columns', [False, True]) +def test_source_batches_ties_counts_columns(tmp_path, columns): + source = Source(make_sorting(tmp_path / 'full', columns), batch_size=2) + assert source.n_spikes == 12 + assert source.unit_ids.tolist() == [0, 1, 2, 99] + assert source.counts.tolist() == [4, 3, 3, 2] + assert all(batch['spike_times.npy'].ndim == 1 for batch in source.iter_batches()) + assert all(isinstance(array, np.memmap) for array in source.arrays.values()) + assert source.metadata['group'][99] == 'noise' + + +def test_declared_waveform_source_identity_is_checked(tmp_path): + params = make_sorting(tmp_path / 'full') + manifest = { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': {'num_samples': 20, 'sampling_frequency_hz': 1}, + 'source_sorting': {'num_spikes': 12, 'spike_times_sha256': '0' * 64}, + } + path = params.parent / '_phy_spikes_subset.manifest.json' + path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match='fingerprint'): + Source(params) + manifest['source_sorting']['spike_times_sha256'] = hash_file(params.parent / 'spike_times.npy') + path.write_text(json.dumps(manifest)) + Source(params).close() + manifest['source_sorting']['num_spikes'] = 13 + path.write_text(json.dumps(manifest)) + with pytest.raises(ValueError, match='spike count'): + Source(params) + + +def test_failed_source_validation_closes_readers_and_rejects_unsupported_ids( + tmp_path, monkeypatch +): + params = make_sorting(tmp_path / 'full') + labels = np.load(params.parent / 'spike_clusters.npy').astype(np.int64) + labels[-1] = 2**31 + np.save(params.parent / 'spike_clusters.npy', labels) + original = np.load + readers = [] + + def read(*args, **kwargs): + array = original(*args, **kwargs) + readers.append(array) + return array + + monkeypatch.setattr(np, 'load', read) + with pytest.raises(ValueError, match='int32'): + Source(params) + assert all(array._mmap.closed for array in readers) + + +def test_identity_assignment_and_feature_layers(tmp_path): + params = make_sorting(tmp_path / 'full') + source = Source(params) + source.close() + clusters = np.load(params.parent / 'spike_clusters.npy') + clusters[clusters == 1] = 0 + np.save(params.parent / 'spike_clusters.npy', clusters) + merged = Source(params) + merged.close() + assert merged.identity == source.identity + assert merged.revision != source.revision + values = np.load(params.parent / 'amplitudes.npy') + values[0] = 99 + np.save(params.parent / 'amplitudes.npy', values) + altered = Source(params) + altered.close() + assert altered.identity != merged.identity + assert altered.revision == merged.revision + assert ( + hash_file(params.parent / 'amplitudes.npy') == altered.identity['arrays']['amplitudes.npy'] + ) + + +def test_exposure_gaps_and_missing_duration(tmp_path): + params = make_sorting(tmp_path / 'full') + source = Source(params, valid_intervals=[[0, 7], [10, 20]]) + assert source.valid_intervals.tolist() == [[0, 7], [10, 20]] + with pytest.raises(ValueError, match='outside valid'): + Source(params, valid_intervals=[[0, 5], [10, 20]]) + params.write_text(params.read_text().replace('num_samples = 20\n', '')) + with pytest.raises(ValueError, match='exposure is missing'): + Source(params) + assert Source(params, duration_seconds=20).num_samples == 20 + with pytest.raises(ValueError, match='integer sample count'): + Source(params, duration_seconds=20.5) + + +@pytest.mark.parametrize( + 'failure', ['order', 'alignment', 'unknown', 'segment', 'waveforms', 'ids'] +) +def test_reject_ambiguous_or_misaligned_sources(tmp_path, failure): + params = make_sorting(tmp_path / 'full') + path = params.parent + if failure == 'order': + np.save(path / 'spike_times.npy', np.arange(12)[::-1]) + elif failure == 'alignment': + np.save(path / 'pc_features.npy', np.zeros((11, 2, 2))) + elif failure == 'unknown': + np.save(path / 'mysterious.npy', np.ones(12)) + elif failure == 'segment': + params.write_text(params.read_text() + 'num_segments = 2\n') + elif failure == 'waveforms': + (path / '_phy_spikes_subset.channels.npy').unlink() + else: + np.save(path / '_phy_spikes_subset.spikes.npy', np.array([0, 2, 2, 8, 11], dtype=np.int64)) + with pytest.raises(ValueError): + Source(params, batch_size=2) + + +def test_metadata_json_preserves_typed_values(tmp_path): + params = make_sorting(tmp_path / 'full') + (params.parent / 'cluster_group.tsv').write_text('cluster_id\tgroup\n0\tgood\n') + metadata = {'group': {'0': 'good'}, 'custom': {'99': None, '2': 4}} + (params.parent / '_phy_cluster_metadata.json').write_text(json.dumps(metadata)) + assert Source(params).metadata == {'group': {0: 'good'}, 'custom': {99: None, 2: 4}} + + +def test_replay_lineage_retains_zero_count_catalog_and_allocator(tmp_path): + params = make_sorting(tmp_path / 'full') + source = Source(params) + lineage = { + 'format': 'phy_curation_lineage', + 'format_version': 1, + 'coordinate_identity': source.identity, + 'revision': source.revision, + 'unit_ids': [0, 1, 2, 99, 103], + 'next_cluster_id': 105, + } + (params.parent / '_phy_curation_lineage.json').write_text(json.dumps(lineage)) + reopened = Source(params) + assert reopened.next_cluster_id == 105 + assert reopened.unit_ids[-1] == 103 + assert reopened.counts[-1] == 0 + assert reopened.identity == source.identity + lineage['next_cluster_id'] = 103 + (params.parent / '_phy_curation_lineage.json').write_text(json.dumps(lineage)) + with pytest.raises(ValueError, match='collides'): + Source(params) + + +def test_unknown_upstream_manifest_version_is_rejected(tmp_path): + params = make_sorting(tmp_path / 'full') + (params.parent / '_phy_spikes_subset.manifest.json').write_text( + json.dumps({'format': 'phy_spikes_subset', 'format_version': 2}) + ) + with pytest.raises(ValueError, match='Unsupported waveform manifest'): + Source(params) + + +def test_integer_clock_beyond_32_bits(tmp_path): + from phy.apps.tests.large_recording_fixtures import make_long_recording_fixture + + fixture = make_long_recording_fixture(tmp_path) + source = Source(fixture.full / 'params.py', batch_size=3) + assert source.num_samples == 1000 * 3600 * 30000 + assert source.arrays['spike_times.npy'][-1] > np.iinfo(np.int32).max + assert source.n_spikes == 32 + + +def test_source_heap_does_not_scale_with_spike_arrays(tmp_path): + import tracemalloc + + peaks = [] + for spikes in (1000, 250000): + path = tmp_path / str(spikes) + path.mkdir() + for name, dtype in ( + ('spike_times.npy', np.int64), + ('spike_clusters.npy', np.int32), + ('spike_templates.npy', np.int32), + ): + values = np.lib.format.open_memmap( + path / name, mode='w+', dtype=dtype, shape=(spikes,) + ) + for start in range(0, spikes, 1024): + stop = min(start + 1024, spikes) + values[start:stop] = np.arange(start, stop) if name == 'spike_times.npy' else 0 + values.flush() + del values + (path / 'params.py').write_text(f'sample_rate = 1\nnum_samples = {spikes}\n') + tracemalloc.start() + source = Source(path / 'params.py', batch_size=1024) + _, peak = tracemalloc.get_traced_memory() + tracemalloc.stop() + assert source.n_spikes == spikes + assert sum(source.counts) == spikes + peaks.append(peak) + # This checks allocated heap; file-backed OS pages are intentionally separate. + assert peaks[-1] < 4 * 1024 * 1024 + assert peaks[-1] - peaks[0] < 3 * 1024 * 1024 + + +def test_explicit_intervals_cannot_override_changed_producer_exposure(tmp_path): + params = make_sorting(tmp_path / 'full') + params.write_text(params.read_text() + 'valid_intervals = [[0, 7], [10, 20]]\n') + with pytest.raises(ValueError, match='disagree with acquisition metadata'): + Source(params, valid_intervals=[[0, 20]]) + with Source(params) as source: + arrays = list(source.arrays.values()) + assert source.valid_intervals.tolist() == [[0, 7], [10, 20]] + assert not source.arrays + assert all(array._mmap.closed for array in arrays) + + +def test_exporter_channel_sidecars_and_raw_map_validation(tmp_path): + params = make_sorting(tmp_path / 'full') + np.save( + params.parent / 'channel_map_si.npy', np.array(['hardware2', 'hardware0', 'hardware1']) + ) + np.save(params.parent / 'channel_groups.npy', np.array([1, 1, 0])) + with Source(params) as source: + assert 'channel_map_si.npy' in source.arrays + params.write_text(params.read_text().replace('n_channels_dat = 3', 'n_channels_dat = 2')) + with pytest.raises(ValueError, match='outside n_channels_dat'): + Source(params) + + +@pytest.mark.parametrize( + 'positions', [np.zeros((3, 1)), np.zeros((3, 3)), np.full((3, 2), np.nan)] +) +def test_channel_geometry_must_match_gui_contract(tmp_path, positions): + params = make_sorting(tmp_path / 'source') + np.save(params.parent / 'channel_positions.npy', positions) + with pytest.raises(ValueError, match='finite x/y'): + Source(params) + + +def test_exclusive_publish_preserves_racing_empty_destination(tmp_path): + from phy.apps.large_recording.source import publish_directory + + staged = tmp_path / 'stage' + staged.mkdir() + (staged / 'payload').write_text('complete') + destination = tmp_path / 'destination' + destination.mkdir() + with pytest.raises(FileExistsError): + publish_directory(staged, destination) + assert destination.is_dir() and not list(destination.iterdir()) + assert (staged / 'payload').read_text() == 'complete' + destination.rmdir() + publish_directory(staged, destination) + assert not staged.exists() + assert (destination / 'payload').read_text() == 'complete' + + +def test_clock_endpoint_mismatch_fails_before_full_scan_or_hash(tmp_path, monkeypatch): + from phy.apps.large_recording import source as module + + params = make_sorting(tmp_path / 'source') + times = np.load(params.parent / 'spike_times.npy') + times[-1] = 100 + np.save(params.parent / 'spike_times.npy', times) + + def unexpected(*args, **kwargs): + pytest.fail('Clock endpoint mismatch must fail before scans or hashing.') + + monkeypatch.setattr(Source, 'iter_batches', unexpected) + monkeypatch.setattr(module, 'hash_file', unexpected) + with pytest.raises(ValueError, match='same time base'): + Source(params) + + +def clock_manifest(params, recording): + path = params.parent / '_phy_spikes_subset.manifest.json' + path.write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'recording': recording, + } + ) + ) + return path + + +def test_explicit_clocks_and_legacy_identity(tmp_path): + params = make_sorting(tmp_path / 'source') + with Source(params) as source: + legacy = source.identity + assert source.time_base is None + # Existing exports preserve their exact identity schema. + assert set(legacy['time_base']) == {'sample_rate', 'num_samples', 'valid_intervals'} + contract = {'kind': 'acquisition_samples', 'ticks_per_second': 1} + params.write_text(params.read_text() + f'time_base = {contract!r}\n') + clock_manifest(params, {'time_base': contract}) + with Source(params) as source: + assert source.time_base == contract + assert source.identity != legacy + explicit = source.identity + timestamps = params.parent / 'timestamps.json' + timestamps.write_text('{"mapping": "producer-owned"}') + with Source(params) as source: + assert source.identity != explicit + assert source.identity['time_base']['timestamps_sha256'] == hash_file(timestamps) + timestamps.write_text('{"mapping": "changed"}') + with Source(params) as source: + assert source.identity['time_base']['timestamps_sha256'] == hash_file(timestamps) + + +@pytest.mark.parametrize( + 'contract', + [ + None, + {}, + {'kind': 'clock', 'ticks_per_second': 1}, + {'kind': 'elapsed_ticks', 'ticks_per_second': 0}, + {'kind': 'elapsed_ticks', 'ticks_per_second': float('inf')}, + {'kind': 'elapsed_ticks', 'ticks_per_second': True}, + {'kind': 'elapsed_ticks', 'ticks_per_second': '1'}, + ], +) +def test_invalid_explicit_clock_contract(tmp_path, contract): + params = make_sorting(tmp_path / 'source') + clock_manifest(params, {'time_base': contract}) + with pytest.raises(ValueError, match='time_base'): + Source(params) + + +def test_timestamps_without_contract_fail_before_arrays(tmp_path, monkeypatch): + params = make_sorting(tmp_path / 'source') + (params.parent / 'timestamps.json').write_text('{}') + monkeypatch.setattr(np, 'load', lambda *a, **kw: pytest.fail('Unexpected array read')) + with pytest.raises(ValueError, match='explicit time_base'): + Source(params) + + +@pytest.mark.parametrize( + 'failure', + [ + 'clock', + 'ticks', + 'waveform_rate', + 'manifest_rate', + 'frame_coordinates', + 'missing_intervals', + 'raw', + 'window_coordinates', + 'sample_coordinates', + ], +) +def test_explicit_elapsed_clock_rejects_ambiguous_producer_metadata(tmp_path, failure): + params = make_sorting(tmp_path / 'source') + contract = {'kind': 'elapsed_ticks', 'ticks_per_second': 1} + recording = {'time_base': contract, 'valid_intervals': [[0, 20]]} + if failure == 'clock': + params.write_text( + params.read_text() + + "time_base = {'kind': 'acquisition_samples', 'ticks_per_second': 1}\n" + ) + elif failure == 'ticks': + recording['time_base'] = {**contract, 'ticks_per_second': 2} + elif failure == 'waveform_rate': + params.write_text(params.read_text() + 'waveform_sample_rate = 2\n') + elif failure == 'manifest_rate': + recording['sampling_frequency_hz'] = 2 + elif failure == 'frame_coordinates': + recording['frame_coordinates'] = 'before any clock-time conversion' + elif failure == 'missing_intervals': + recording.pop('valid_intervals') + elif failure == 'raw': + params.write_text(params.read_text() + "dat_path = ['None', 'raw.bin']\n") + elif failure == 'window_coordinates': + np.save(params.parent / '_phy_spikes_subset.window_bounds.npy', [[0, 20]]) + else: + np.save(params.parent / '_phy_spikes_subset.sample_index.npy', [0, 1, 2, 14, 19]) + recording['sample_index_coordinates'] = 'acquisition_samples' + clock_manifest(params, recording) + with pytest.raises(ValueError): + Source(params) + + +@pytest.mark.parametrize('raw', [None, 'None', '', [], [None, 'None', '']]) +def test_elapsed_clock_canonical_sidecars_and_no_raw_sentinels(tmp_path, raw): + params = make_sorting(tmp_path / 'source') + contract = {'kind': 'elapsed_ticks', 'ticks_per_second': 1} + params.write_text(params.read_text() + f'dat_path = {raw!r}\n') + recording = { + 'time_base': contract, + 'valid_intervals': [[0, 7], [10, 20]], + 'frame_coordinates': 'elapsed_ticks', + 'window_bounds_coordinates': 'elapsed_ticks', + 'sample_index_coordinates': 'elapsed_ticks', + } + clock_manifest(params, recording) + np.save(params.parent / '_phy_spikes_subset.window_bounds.npy', [[0, 7], [10, 20]]) + np.save(params.parent / '_phy_spikes_subset.sample_index.npy', [0, 1, 2, 14, 19]) + with Source(params) as source: + assert source.time_base == contract + assert source.upstream_recording == recording + assert source.valid_intervals.tolist() == [[0, 7], [10, 20]] + + +@pytest.mark.parametrize( + 'values', + [ + [0, 1, 2, 14], + [[0], [1], [2], [14], [19]], + [0.0, 1.0, 2.0, 14.0, 19.0], + [-1, 1, 2, 14, 19], + [0, 1, 2, 14, 20], + [0, 1, 2, 13, 19], + ], +) +def test_waveform_sample_index_requires_exact_canonical_alignment(tmp_path, values): + params = make_sorting(tmp_path / 'source') + np.save(params.parent / '_phy_spikes_subset.sample_index.npy', values) + with pytest.raises(ValueError, match='sample_index'): + Source(params) + + +def test_waveform_sample_index_legacy_default_is_acquisition_samples(tmp_path): + params = make_sorting(tmp_path / 'source', columns=True) + np.save(params.parent / '_phy_spikes_subset.sample_index.npy', [0, 1, 2, 14, 19]) + with Source(params) as source: + assert '_phy_spikes_subset.sample_index.npy' in source.identity['arrays'] diff --git a/phy/apps/large_recording/tests/test_stability.py b/phy/apps/large_recording/tests/test_stability.py new file mode 100644 index 000000000..393c17813 --- /dev/null +++ b/phy/apps/large_recording/tests/test_stability.py @@ -0,0 +1,747 @@ +"""Exact selected-unit comparisons and scoped GUI selection behavior.""" + +from itertools import product +from types import MappingProxyType + +import numpy as np +import pytest +from phylib.utils import Bunch + +from phy.apps.large_recording.stability import UnitStabilityView +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.utils.color import selected_cluster_color + + +@pytest.fixture +def summary_view(qtbot, tmp_path): + arrays = { + 'edges': [0, 10, 20, 25], + 'exposure': [8.0, 0.0, 3.0], + 'counts': [[4, 0, 3], [12, 0, 6], [8, 0, 0]], + 'amplitude_sum': [[4.0, 0.0, 15.0], [30.0, 0.0, 8.0], [0.0, 0.0, 0.0]], + 'amplitude_count': [[2, 0, 3], [3, 0, 1], [0, 0, 0]], + 'depth_sum': [[40.0, 0.0, 150.0], [300.0, 0.0, 80.0], [0.0, 0.0, 0.0]], + 'depth_count': [[2, 0, 3], [3, 0, 1], [0, 0, 0]], + } + summary = {} + for key, values in arrays.items(): + name = f'{key}.npy' + np.save(tmp_path / name, np.asarray(values)) + summary[f'{key}_file'] = name + membership = {1: [1], 2: [2], 3: [3], 4: [1, 2], 5: None} + controller = Bunch( + dir_path=tmp_path, + model=Bunch(sample_rate=1.0, duration=25.0), + evidence_windows=np.array([[0, 2], [22, 24]]), + bounded_session=Bunch( + unit_ids=[1, 2, 3], + manifest={ + 'summaries': summary, + 'bounded_counts': [1, 1, 0], + 'valid_intervals': [[0, 8], [20, 23]], + }, + ), + _source_units=lambda cluster: membership[cluster], + get_spike_times=lambda cluster: pytest.fail('Bounded views must never read spike arrays'), + ) + view = UnitStabilityView(controller) + yield view + view.close() + + +@pytest.mark.parametrize('selected', [[1, 2], [1, 2, 3]]) +def test_exact_overlays_and_shared_exposure(summary_view, selected): + view = summary_view + view.on_select(selected) + axes = list(view.canvas.iter_ax()) + assert len(axes[0].lines) == len(selected) + assert [line.get_label() for line in axes[0].lines] == list(map(str, selected)) + expected = {1: [0.5, np.nan, 1.0], 2: [1.5, np.nan, 2.0], 3: [1.0, np.nan, 0.0]} + for index, (cluster, line) in enumerate(zip(selected, axes[0].lines)): + np.testing.assert_allclose(line.get_ydata(), expected[cluster], equal_nan=True) + np.testing.assert_allclose(line.get_xdata(), np.array([5, 15, 22.5]) / 3600) + np.testing.assert_allclose(line.get_color(), selected_cluster_color(index)) + assert '3' in view._footer.get_text() # Unit without bounded evidence remains inspectable. + assert len(axes[1].lines) == 2 # No fabricated all-NaN trend for unit 3. + assert any( + 'Amplitude measurement unavailable for units: 3' in t.get_text() for t in axes[1].texts + ) == (3 in selected) + + +def test_refractory_only_uses_recording_axis_and_freeze_cancels(summary_view): + from threading import Event + + view = summary_view + view.show_firing_rate = view.show_amplitude = view.show_depth = False + view.name = 'UnitStabilityView' + view.on_select([1]) + ax = list(view.canvas.iter_ax())[3] + np.testing.assert_allclose(ax.get_xlim(), [0, 25 / 3600]) + view._rp._token = ('running',) + pending = view._rp._running = Event() + view.toggle_auto_update(False) + assert pending.is_set() + before = view._rp_lines[1].get_ydata().copy() + view._rp.results = { + 1: {'status': 'ready', 'window_centres_h': np.array([0]), 'contamination': np.array([0.2])} + } + view._rp.changed.emit() + np.testing.assert_array_equal(view._rp_lines[1].get_ydata(), before) + view.toggle_auto_update(True) + assert view.auto_update + + +def test_refractory_only_notes_are_persistent_and_never_stale(summary_view): + view = summary_view + view.show_firing_rate = view.show_amplitude = view.show_depth = False + view.on_select([]) + ax = list(view.canvas.iter_ax())[3] + assert len(ax.texts) == 1 + for selected in ([1], [], [2], [1], [1]): + view.on_select(selected) + assert len(ax.texts) == 1 + if selected: + assert not any('Select a unit' in t.get_text() for t in ax.texts) + assert '6 h windows' in ax.get_title() + + +def test_refractory_blit_reuses_artists_and_recaptures_after_resize(summary_view): + view = summary_view + view.on_select([1]) + axes = list(view.canvas.iter_ax()) + other_lines = tuple(axes[0].lines) + rp_line = view._rp_lines[1] + view._rp.results = { + 1: {'status': 'ready', 'window_centres_h': np.array([0]), 'contamination': np.array([0.2])} + } + view._rp.message = '' + view._update_refractory() + assert view._rp_lines[1] is rp_line + assert tuple(axes[0].lines) == other_lines + np.testing.assert_array_equal(rp_line.get_ydata(), [20]) + previous = view._rp_background + view.canvas.figure.set_size_inches(9, 6) + view.canvas.canvas.draw() + if view._rp_blit: + assert view._rp_background is not None and view._rp_background is not previous + view._rp.results[1]['contamination'] = np.array([0.3]) + view._update_refractory() + assert view._rp_lines[1] is rp_line + np.testing.assert_array_equal(rp_line.get_ydata(), [30]) + + +def test_weighted_merged_trends_and_pending_do_not_hide_valid_units(summary_view): + view = summary_view + merged = view.get_data(4) + np.testing.assert_array_equal(merged.counts, [16, 0, 9]) + np.testing.assert_allclose(merged.rates, [2.0, np.nan, 3.0], equal_nan=True) + np.testing.assert_allclose(merged.trends['amplitude'], [6.8, np.nan, 5.75], equal_nan=True) + np.testing.assert_allclose(merged.trends['depth'], [68.0, np.nan, 57.5], equal_nan=True) + view.on_select([5, 4]) + ax = next(view.canvas.iter_ax()) + assert len(ax.lines) == 1 and ax.lines[0].get_label() == '4' + assert any('Unit 5: Split evidence pending' in t.get_text() for t in ax.texts) + + +def test_lazy_metrics_selected_cache_and_all_toggle_layouts(summary_view, monkeypatch): + view = summary_view + loads = [] + original = view._array + + def load(name): + loads.append(name) + return original(name) + + monkeypatch.setattr(view, '_array', load) + view.show_amplitude = view.show_depth = False + view.on_select([1, 2]) + assert not any('amplitude' in name or 'depth' in name for name in loads) + common = view._common() + lookups = common.lookup + view.toggle_amplitude(True) + assert any('amplitude' in name for name in loads) + assert not any('depth' in name for name in loads) + loads.clear() + view.toggle_amplitude(False) + view.toggle_amplitude(True) + assert not loads + assert view._common() is common and view._common().lookup is lookups + axes = list(view.canvas.iter_ax()) + callback_counts = {k: len(v) for k, v in view.canvas.canvas.callbacks.callbacks.items()} + for _ in range(2): + for combination in product((False, True), repeat=4): + for metric, enabled in zip(view._metrics, combination): + getattr(view, f'toggle_{metric}')(enabled) + assert tuple(view.state[f'show_{metric}'] for metric in view._metrics) == combination + assert list(view.canvas.iter_ax()) == axes + assert { + k: len(v) for k, v in view.canvas.canvas.callbacks.callbacks.items() + } == callback_counts + visible = [ax for ax in axes if ax.get_visible()] + if any(combination): + assert len(visible) == sum(combination) + assert visible[-1].get_xlabel() == 'Elapsed acquisition clock (hours)' + assert all(not ax.get_xlabel() for ax in visible[:-1]) + assert visible[0].get_position().y1 == pytest.approx( + 0.91 if len(visible) == 1 else 0.15 + 0.76 - 0.16 * 0.76 / len(visible) + ) + else: + assert any('No metrics enabled' in t.get_text() for t in visible[0].texts) + assert view.state.show_depth + view.on_select([3]) + assert set(view._selected_summaries) == {3} + + +def test_selection_limit_palette_and_clear_lifecycle(summary_view): + view = summary_view + view.display_limit = 8 + # Repeat source rows under distinct cluster IDs to test the display bound. + view.controller._source_units = lambda cluster: [1] + selected = list(range(20, 30)) + sender = Bunch( + selection_color_indices=MappingProxyType({c: 9 - i for i, c in enumerate(selected)}) + ) + view.on_select_threaded(sender, selected) + assert view.cluster_ids == tuple(selected) + assert selected == list(range(20, 30)) + assert len(view._selected_summaries) == 8 + ax = next(view.canvas.iter_ax()) + assert len(ax.lines) == 8 + assert 'Showing first 8 of 10 selected units' in view.status + assert 'does not change the selection or merge operation' in view.status + for i, line in enumerate(ax.lines): + np.testing.assert_allclose(line.get_color(), selected_cluster_color(9 - i)) + view.auto_update = False + view.on_select_threaded(sender, []) + assert view.cluster_ids == tuple(selected) + view.auto_update = True + view.defer_hidden_updates = True + view._dock_visible = False + view.on_select_threaded(sender, selected) + view._dock_visible = True + view._flush_pending_selection() + np.testing.assert_allclose(ax.lines[0].get_color(), selected_cluster_color(9)) + view._dock_visible = False + view.on_select_threaded(sender, []) + assert view.cluster_ids == () and view._pending_selection == ([], {}) + assert len(ax.lines) == 8 + view._dock_visible = True + view._flush_pending_selection() + assert not ax.lines + view.on_select([1]) + view._closed = True + view.on_select_threaded(sender, []) + assert view.cluster_ids == (1,) + view._closed = False + + +def test_ordinary_continuous_assumption_and_invalidation(qtbot): + times = [np.array([0.0, 1.0, 9.0])] + calls = [] + + def get_times(cluster): + calls.append(cluster) + return times[0] + + controller = Bunch(model=Bunch(duration=10.0), get_spike_times=get_times) + view = UnitStabilityView(controller) + try: + view.on_select([7, 8]) + data = view.get_data(7) + assert data.counts.sum() == 3 and not data.trends + assert 'continuous acquisition assumed' in data.provenance + np.testing.assert_allclose(data.exposure, 0.1) + assert calls == [7, 8] + times[0] = np.array([2.0]) + view._invalidate() + assert view.get_data(7).counts.sum() == 1 + finally: + view.close() + + +def test_gui_initial_authoritative_selection_actions_and_curation(qtbot, tmp_path, monkeypatch): + _, controller = make_controller(tmp_path, sparse=True) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + supervisor = controller.supervisor + try: + supervisor.select([0]) + supervisor.block() + supervisor.similarity_view.select([1]) + supervisor.block() + view = UnitStabilityView(controller) + view.attach(gui) + assert view.cluster_ids == tuple(supervisor.selected) == (0, 1) + for metric in view._metrics: + assert view.actions.get(f'toggle_{metric}').isChecked() + view.actions.get('toggle_amplitude').trigger() + assert not view.show_amplitude + assert not view.actions.get('toggle_amplitude').isChecked() + view.toggle_depth(False) + assert not view.actions.get('toggle_depth').isChecked() + # Exercise the real dock camera callback with the Matplotlib Qt widget. + from phy.apps.large_recording import stability + + default_path = stability.screenshot_default_path + paths = [] + + def screenshot_path(widget, dir=None): + path = default_path(widget, dir=tmp_path) + paths.append(path) + return path + + monkeypatch.setattr(stability, 'screenshot_default_path', screenshot_path) + view.dock._dock_widgets['screenshot'].click() + assert paths[-1].read_bytes().startswith(b'\x89PNG\r\n\x1a\n') + assert paths[-1].name.endswith('_UnitStabilityView.png') + assert view.screenshot(tmp_path) == paths[-1] + view.actions.run('set_rate_line_width', 0.75) + view.actions.run('set_display_limit', 64) + view.actions.run('set_display_bin_seconds', 20) + assert 'display_bin_seconds' in view.local_state_attrs + assert 'display_bin_seconds' not in view.state_attrs + state = view.state.copy() + supervisor.toggle_merge_mode() + supervisor.block() + supervisor.similarity_view.select([2, 1]) + supervisor.block() + other = UnitStabilityView(controller) + other.attach(gui) + assert other.cluster_ids == tuple(supervisor.selected) + assert other.cluster_ids + supervisor.add_to_merge((2,), insertion=1) + supervisor.block() + assert other.cluster_ids == tuple(supervisor.selected) + assert other.cluster_ids[1] == 2 + supervisor.similarity_view.sort_by('id', 'desc') + supervisor.block() + assert other.cluster_ids == tuple(supervisor.selected) + for index, line in enumerate(next(other.canvas.iter_ax()).lines): + cluster = int(line.get_label()) + np.testing.assert_allclose( + line.get_color(), + selected_cluster_color(supervisor.selection_color_indices[cluster]), + ) + # Save and restore through GUI view state, including QAction checks. + other.close() + view.close() + restored = UnitStabilityView(controller) + restored.attach(gui) + assert restored.rate_line_width == 0.75 + assert restored.display_limit == 64 + assert restored.display_bin_seconds == 20 + assert restored.show_firing_rate + assert not restored.show_amplitude and not restored.show_depth + assert not restored.actions.get('toggle_amplitude').isChecked() + assert not restored.actions.get('toggle_depth').isChecked() + view = restored + view.set_state(state) + assert not view.show_amplitude and not view.show_depth + supervisor.toggle_merge_mode() + supervisor.block() + supervisor.merge([0, 1]) + supervisor.block() + assert view.get_data(100).counts.sum() == 7 + assert view.get_display_data(100).counts.sum() == 7 + supervisor.undo() + supervisor.block() + assert view.get_data(0).counts.sum() == 4 + assert view.get_display_data(0).counts.sum() == 4 + supervisor.redo() + supervisor.block() + assert view.get_data(100).counts.sum() == 7 + assert view.get_display_data(100).counts.sum() == 7 + supervisor.undo() + supervisor.block() + controller._live_summaries.suspend() + up = supervisor.split_source_amplitude(0, 2) + supervisor.block() + children = up.added + for cluster in children: + assert view.get_data(cluster).pending + view.on_select([children[0], 1]) + assert [line.get_label() for line in next(view.canvas.iter_ax()).lines] == ['1'] + supervisor.undo() + supervisor.block() + assert view.get_data(0).counts.sum() == 4 + assert view.get_display_data(0).counts.sum() == 4 + supervisor.redo() + supervisor.block() + assert view.get_data(children[0]).pending + controller._live_summaries.resume() + qtbot.waitUntil(lambda: controller.get_full_count(children[0]) == 1) + assert not view.get_data(children[0]).pending + view.close() + assert not view._summary_arrays and not view._selected_summaries + finally: + gui.close() + controller.close() + + +def test_500_hour_500_bin_comparison_stays_bounded(summary_view): + view = summary_view + bins = 500 + view._common_data = Bunch( + edges=np.linspace(0, 500 * 3600, bins + 1), + exposure=np.full(bins, 3600.0), + windows=np.array([[0, 30], [499 * 3600, 499 * 3600 + 30]]), + intervals=[[0, 500 * 3600]], + footer='', + lookup={1: 0, 2: 1, 3: 2}, + summary={'counts_file': 'virtual_counts'}, + ) + view._summary_arrays['virtual_counts'] = np.ones((3, bins), dtype=np.int64) + view.controller._source_units = lambda cluster: [1] + view.on_select(list(range(8))) + assert len(view._selected_summaries) == 8 + assert all(len(line.get_xdata()) == bins for line in next(view.canvas.iter_ax()).lines) + + +def test_summary_aggregation_reads_one_row_at_a_time(summary_view): + view = summary_view + reads = [] + + class RowGrid: + def __init__(self, values): + self.values = values + + def __getitem__(self, row): + assert isinstance(row, (int, np.integer)), 'Never materialize multiple unit rows' + reads.append(row) + return self.values[row] + + for key in ('counts', 'amplitude_sum', 'amplitude_count', 'depth_sum', 'depth_count'): + name = f'{key}.npy' + view._summary_arrays[name] = RowGrid(np.load(view.controller.dir_path / name)) + data = view.get_data(4) + np.testing.assert_array_equal(data.counts, [16, 0, 9]) + assert reads == [0, 1] + [0, 0, 1, 1] * 2 + + +def test_ordinary_gui_cluster_event_refreshes_cached_counts(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + times = [np.array([0.0, 1.0])] + ordinary = Bunch( + supervisor=controller.supervisor, + model=Bunch(duration=20.0), + get_spike_times=lambda cluster: times[0], + ) + view = UnitStabilityView(ordinary) + try: + controller.supervisor.select([0]) + controller.supervisor.block() + view.attach(gui) + assert view.get_data(0).counts.sum() == 2 + times[0] = np.array([0.0, 1.0, 2.0, 3.0]) + controller.supervisor.label('group', 'noise', cluster_ids=[0]) + controller.supervisor.block() + ax = next(view.canvas.iter_ax()) + assert np.nansum(ax.lines[0].get_ydata() * 0.2) == pytest.approx(4) + assert view.get_data(0).counts.sum() == 4 + assert view.get_display_data(0).counts.sum() == 4 + finally: + view.close() + gui.close() + controller.close() + + +def test_display_limit_all_and_large_values_preserve_selection(summary_view): + view = summary_view + assert view.display_limit == 32 + view.controller._source_units = lambda cluster: [1] + selected = list(range(40)) + view.on_select(selected) + assert view.cluster_ids == tuple(selected) + assert len(view.displayed_ids) == len(next(view.canvas.iter_ax()).lines) == 32 + assert 'merge operation' in view.status + for limit in (0, 64, 128): + view.set_display_limit(limit) + assert view.displayed_ids == tuple(selected) + assert len(next(view.canvas.iter_ax()).lines) == 40 + assert not view.status + assert view.cluster_ids == tuple(selected) + for ax in view.canvas.iter_ax(): + assert ax.get_legend() is None + assert all(line.get_linewidth() == 0.6 for line in next(view.canvas.iter_ax()).lines) + view.set_rate_line_width(0.7) + assert all(line.get_linewidth() == 0.7 for line in next(view.canvas.iter_ax()).lines) + + +@pytest.mark.parametrize('value', [None, 'bad', np.nan, np.inf, -1, 0]) +def test_invalid_line_width_state_and_action(summary_view, value): + view = summary_view + with pytest.raises((ValueError, TypeError)): + view.set_rate_line_width(value) + view.set_state({'rate_line_width': value}) + assert view.rate_line_width == 0.6 + + +@pytest.mark.parametrize('value', [None, 'bad', np.nan, np.inf, -1, 1.5]) +def test_invalid_display_limit_state_and_action(summary_view, value): + view = summary_view + with pytest.raises((ValueError, TypeError)): + view.set_display_limit(value) + view.set_state({'display_limit': value}) + assert view.display_limit == 32 + + +@pytest.mark.parametrize('value', [None, 'bad', np.nan, np.inf, -1, 5, 15]) +def test_invalid_display_bins_state_and_action(summary_view, value): + view = summary_view + with pytest.raises((ValueError, TypeError)): + view.set_display_bin_seconds(value) + view.set_state({'display_bin_seconds': value}) + assert view.display_bin_seconds == 0 + + +@pytest.mark.parametrize( + 'seconds, expected_edges, counts, exposure, amplitude', + [ + (0, [0, 10, 20, 25], [16, 0, 9], [8, 0, 3], [6.8, np.nan, 5.75]), + (20, [0, 20, 25], [16, 9], [8, 3], [6.8, 5.75]), + (30, [0, 25], [25], [11], [57 / 9]), + (100, [0, 25], [25], [11], [57 / 9]), + ], +) +def test_display_rebin_exact_merged_primitives( + summary_view, seconds, expected_edges, counts, exposure, amplitude +): + view = summary_view + view.set_display_bin_seconds(seconds) + data = view.get_display_data(4) + np.testing.assert_array_equal(data.edges, expected_edges) + np.testing.assert_array_equal(data.counts, counts) + np.testing.assert_array_equal(data.exposure, exposure) + np.testing.assert_allclose(data.trends['amplitude'], amplitude, equal_nan=True) + expected_rates = np.full(len(exposure), np.nan) + np.divide(counts, exposure, out=expected_rates, where=np.asarray(exposure) > 0) + np.testing.assert_allclose(data.rates, expected_rates, equal_nan=True) + view.on_select([4]) + axes = list(view.canvas.iter_ax()) + for ax in axes[:3]: + np.testing.assert_allclose( + ax.lines[0].get_xdata(), (data.edges[:-1] + data.edges[1:]) / 7200 + ) + assert all(ax.get_legend() is None for ax in axes) + + +def test_300_second_native_bins_and_weighted_trends(summary_view, monkeypatch): + view = summary_view + common = view._common() + common.edges = np.array([0, 300, 600, 900, 1000]) + common.exposure = np.array([300.0, 0.0, 100.0, 40.0]) + common.intervals = [[0, 300], [600, 700], [900, 940]] + # Means 1 and 9 have different finite counts: their aggregate is 7, not 5. + view._summary_arrays.update( + { + 'counts.npy': np.array([[30, 0, 20, 4]]), + 'amplitude_sum.npy': np.array([[1.0, 0.0, 27.0, 20.0]]), + 'amplitude_count.npy': np.array([[1, 0, 3, 2]]), + 'depth_sum.npy': np.array([[10.0, 0.0, 270.0, 200.0]]), + 'depth_count.npy': np.array([[1, 0, 3, 2]]), + } + ) + source = view.get_data(1) + assert view._display_factor() == 1 + np.testing.assert_allclose(source.rates, [0.1, np.nan, 0.2, 0.1], equal_nan=True) + monkeypatch.setattr(view, '_array', lambda name: pytest.fail('Cached rows need no I/O')) + for seconds, edges, counts, exposures, means in ( + (600, [0, 600, 1000], [30, 24], [300, 140], [1, 47 / 5]), + (900, [0, 900, 1000], [50, 4], [400, 40], [7, 10]), + (1800, [0, 1000], [54], [440], [8]), + ): + view.set_display_bin_seconds(seconds) + data = view.get_display_data(1) + np.testing.assert_array_equal(data.edges, edges) + np.testing.assert_array_equal(data.counts, counts) + np.testing.assert_array_equal(data.exposure, exposures) + np.testing.assert_allclose(data.trends['amplitude'], means) + assert view.get_display_data(1) is data + view.set_display_bin_seconds(0) + assert view.get_display_data(1) is source + + +def test_negligible_exposure_masks_plot_only_for_sources_merges_and_live_splits(summary_view): + view = summary_view + common = view._common() + common.edges = np.array([0, 300, 600, 900, 1200]) + common.exposure = np.array([300.0, 0.0004, 300.0, 0.0]) + common.intervals = [[0, 300.0004], [600, 900]] + view.show_amplitude = view.show_depth = False + counts = np.array([[6000, 1, 6000, 0], [9000, 0, 9000, 0], [0, 0, 0, 0]]) + view._summary_arrays['counts.npy'] = counts + view.on_select([1, 2, 4]) + ax = next(view.canvas.iter_ax()) + curves = {line.get_label(): line for line in ax.lines if line.get_label().isdigit()} + assert set(curves) == {'1', '2', '4'} + for label, expected in [('1', 20), ('2', 30), ('4', 50)]: + np.testing.assert_allclose( + curves[label].get_ydata(), [expected, np.nan, expected, np.nan], equal_nan=True + ) + assert curves[label].get_marker() == '.' + assert curves[label].get_markevery() == [0, 2] + assert ax.get_ylim()[1] < 100 # Includes the axes-relative omission marker. + assert '1 rate bin omitted: too little recorded time.' in view._footer.get_text() + raw = view.get_data(1, ['firing_rate']) + np.testing.assert_allclose(raw.rates, [20, 2500, 20, np.nan], equal_nan=True) + np.testing.assert_array_equal(raw.counts, counts[0]) + # A completed split uses the same exposure mask as original or merged units. + view.controller.get_live_summary = lambda c: {'counts': counts[0]} + view.on_select([5]) + curve = next(line for line in ax.lines if line.get_label() == '5') + np.testing.assert_allclose(curve.get_ydata(), [20, np.nan, 20, np.nan], equal_nan=True) + assert view.get_data(5, ['firing_rate']).rates[1] == 2500 + # Existing coarsening adds counts/exposure first, then reevaluates coverage. + view.set_display_bin_seconds(600) + curve = next(line for line in ax.lines if line.get_label() == '5') + np.testing.assert_allclose(curve.get_ydata(), [6001 / 300.0004, 20]) + assert 'omitted' not in view._footer.get_text() + assert len(ax.lines) == 1 + view.set_display_bin_seconds(0) + assert '1 rate bin omitted' in view._footer.get_text() + np.testing.assert_array_equal(view._summary_arrays['counts.npy'], counts) + + +def test_high_rates_and_short_fully_recorded_final_bins_are_preserved(summary_view): + view = summary_view + common = view._common() + common.edges = np.array([0, 300, 600, 600.0004]) + common.exposure = np.array([300.0, 0.3, 0.0004]) + common.intervals = [[0, 300.3], [600, 600.0004]] + view.show_amplitude = view.show_depth = False + view._summary_arrays['counts.npy'] = np.array([[6000, 750, 1]]) + view.on_select([1]) + ax = next(view.canvas.iter_ax()) + np.testing.assert_allclose(ax.lines[0].get_ydata(), [20, 2500, 2500]) + assert ax.get_ylim()[1] > 2500 + assert 'omitted' not in view._footer.get_text() + # The actual width of the final coarse bin matters too. + view.set_display_bin_seconds(600) + np.testing.assert_allclose(ax.lines[0].get_ydata(), [6750 / 300.3, 2500]) + + +@pytest.mark.parametrize('zero_exposure', [False, True]) +def test_all_low_coverage_rates_are_explicitly_unavailable(summary_view, zero_exposure): + view = summary_view + common = view._common() + common.exposure = np.array([0 if zero_exposure else 0.0004, 0.0004, 0.0004]) + view.show_amplitude = view.show_depth = False + view._summary_arrays['counts.npy'] = np.array([[0, 1, 0]]) + view.on_select([1]) + ax = next(view.canvas.iter_ax()) + assert not any(line.get_label().isdigit() for line in ax.lines) + assert any('No rate bins with sufficient recorded time.' in t.get_text() for t in ax.texts) + assert f'{2 if zero_exposure else 3} rate bins omitted' in view._footer.get_text() + assert ax.get_ylim()[1] < 1 # Neither the raw peak nor markers set the scale. + view.toggle_firing_rate(False) + assert 'omitted' not in view._footer.get_text() + + +def test_cache_budget_independent_of_limit_and_released(summary_view): + view = summary_view + view.controller._source_units = lambda cluster: [1] + view.display_limit = 0 + budget = 2 * view._data_bytes(view.get_data(-1)) + view._invalidate() + view.summary_cache_bytes = budget + for cluster in range(20): + data = view.get_display_data(cluster) + assert data.counts.sum() == 7 + assert sum(map(view._data_bytes, view._selected_summaries.values())) <= budget + assert 19 in view._selected_summaries and 0 not in view._selected_summaries + view.summary_cache_bytes = 0 + assert view.get_data(30).counts.sum() == 7 + assert not view._selected_summaries + view._invalidate() + assert not view._selected_summaries + + +def test_6156_bins_many_units_cached_operation_bounds(summary_view, monkeypatch): + view = summary_view + bins = 6156 + common = view._common() + common.edges = np.arange(bins + 1) * 300.0 + common.exposure = np.full(bins, 300.0) + common.summary = {'counts_file': 'virtual_counts'} + common.intervals = [[0, bins * 300]] + rows = [] + + class Grid: + def __getitem__(self, row): + rows.append(row) + return np.ones(bins, dtype=np.int64) + + view._summary_arrays['virtual_counts'] = Grid() + view.controller._source_units = lambda cluster: [1] + view.show_amplitude = view.show_depth = False + view.on_select(list(range(12))) + assert len(rows) == 12 + assert len(next(view.canvas.iter_ax()).lines) == 12 + assert all(len(line.get_ydata()) == bins for line in next(view.canvas.iter_ax()).lines) + monkeypatch.setattr(view, '_array', lambda name: pytest.fail('Must reuse cached source rows')) + view.set_display_bin_seconds(900) + view.plot() + assert len(rows) == 12 + assert all(len(line.get_ydata()) == bins // 3 for line in next(view.canvas.iter_ax()).lines) + view.set_display_bin_seconds(0) + assert len(rows) == 12 + + +def test_display_gap_and_unattached_cache_release(summary_view): + view = summary_view + common = view._common() + common.exposure = np.array([0.0, 0.0, 3.0]) + view.set_display_bin_seconds(20) + data = view.get_display_data(4) + assert data.exposure[0] == 0 + assert np.isnan(data.rates[0]) + assert np.isnan(data.trends['amplitude'][0]) + assert np.isnan(data.trends['depth'][0]) + assert view._selected_summaries and view._summary_arrays + view.close() + assert not view._selected_summaries and not view._summary_arrays + assert view._common_data is None + + +def test_pending_summaries_also_obey_cache_budget(summary_view): + view = summary_view + view.controller._source_units = lambda cluster: None + pending = view.get_data(5) + view.summary_cache_bytes = 2 * view._data_bytes(pending) + for cluster in range(20): + assert view.get_data(cluster).pending + assert len(view._selected_summaries) <= 2 + assert ( + sum(map(view._data_bytes, view._selected_summaries.values())) <= view.summary_cache_bytes + ) + + +@pytest.mark.parametrize( + 'edges', + [ + [0, 10, 25, 30], + [0, 10, 20, 35], + [0, 10, 20, 20], + [0, 10, 20, np.inf], + ], +) +def test_seconds_coarsening_rejects_nonuniform_or_invalid_native_bins(summary_view, edges): + view = summary_view + view._common().edges = np.asarray(edges, dtype=float) + assert view._display_factor(0) == 1 + with pytest.raises(ValueError, match='requires uniform native bins'): + view.set_display_bin_seconds(20) + assert view.display_bin_seconds == 0 + view.set_state({'display_bin_seconds': 20}) + assert view.display_bin_seconds == 0 + + +def test_seconds_coarsening_supports_short_final_native_bin(summary_view): + view = summary_view + # The fixture's native widths are 10, 10, 5 seconds. + assert view._display_factor(20) == 2 + view.set_display_bin_seconds(20) + data = view.get_display_data(1) + np.testing.assert_array_equal(data.edges, [0, 20, 25]) + np.testing.assert_array_equal(data.counts, [4, 3]) + np.testing.assert_array_equal(data.exposure, [8, 3]) diff --git a/phy/apps/large_recording/tests/test_statistics.py b/phy/apps/large_recording/tests/test_statistics.py new file mode 100644 index 000000000..6f3150e41 --- /dev/null +++ b/phy/apps/large_recording/tests/test_statistics.py @@ -0,0 +1,152 @@ +"""Independent pair-count oracle and observation-boundary regressions.""" + +import numpy as np + +from phy.apps.large_recording.statistics import window_correlograms, window_isi + + +def test_window_isi_excludes_missing_observation_periods_and_preserves_ties(): + samples = np.array([0, 1, 1, 2, 1000, 1002], dtype=np.int64) + windows = np.array([[0, 3], [1000, 1003]], dtype=np.int64) + np.testing.assert_array_equal(window_isi(samples, windows, 1), [1, 0, 1, 2]) + + +def test_late_sample_ccg_matches_all_pairs_oracle_with_sparse_ids(): + origin = 1000 * 3600 * 30000 + samples = origin + np.array([0, 1, 30, 30, 31, 60, 300, 301, 330], dtype=np.int64) + clusters = np.array([2_000_000_000, 2, 2, 2_000_000_000, 2, 2, 2, 2_000_000_000, 2]) + windows = np.array([[origin, origin + 100], [origin + 300, origin + 400]], dtype=np.int64) + ids = [2_000_000_000, 2] + actual = window_correlograms(samples, clusters, windows, ids, 30000, 0.001, 0.004) + expected = np.zeros((2, 2, 5), dtype=np.int64) + lookup = {cluster: index for index, cluster in enumerate(ids)} + for start, end in windows: + rows = [i for i, tick in enumerate(samples) if start <= tick < end] + for index, left in enumerate(rows): + for right in rows[index + 1 :]: + delay = int(samples[right] - samples[left]) // 30 + if delay > 2: + continue + a, b = lookup[clusters[left]], lookup[clusters[right]] + expected[a, b, 2 + delay] += 1 + if a != b or delay != 0: + expected[b, a, 2 - delay] += 1 + np.testing.assert_array_equal(actual, expected) + + +def test_cross_unit_central_pairs_do_not_depend_on_tied_row_order(): + samples = np.array([0, 0, 10, 10], dtype=np.int64) + windows = np.array([[0, 20]], dtype=np.int64) + a = window_correlograms(samples, np.array([0, 1, 1, 0]), windows, [0, 1], 30000, 0.001, 0.004) + b = window_correlograms(samples, np.array([1, 0, 1, 0]), windows, [0, 1], 30000, 0.001, 0.004) + np.testing.assert_array_equal(a, b) + assert a[0, 1, 2] == 4 + + +def test_window_chance_baseline_matches_discrete_uniform_all_pairs(): + """Enumerate independent clock positions; exclude the folded central bin.""" + from phy.apps.large_recording.statistics import _window_chance_baseline + + for length, bin_samples, half_bins in ((7, 2, 3), (3, 2, 4), (2, 3, 2)): + counts = np.array([3, 2, 1, 0]) + positive_pairs = sum( + 1 + for left in range(length) + for right in range(length) + if 1 <= (right - left) // bin_samples <= half_bins + ) + pair_probability = positive_pairs / length**2 / half_bins + expected = np.outer(counts, counts).astype(float) + expected[np.diag_indices(len(counts))] -= counts + expected *= pair_probability + np.testing.assert_allclose( + _window_chance_baseline(counts, length, bin_samples, half_bins), expected + ) + assert expected[2, 2] == 0 # One spike has no auto-pair partner. + + +def test_window_correlograms_returns_baseline_from_per_window_counts(): + samples = np.array([0, 1, 2, 3, 100, 101, 102], dtype=np.int64) + clusters = np.array([9, 9, 2, 2, 9, 9, 9]) + windows = np.array([[0, 10], [100, 105]], dtype=np.int64) + hist, baseline = window_correlograms( + samples, clusters, windows, [9, 2, 99], 1000, 0.002, 0.008, return_baseline=True + ) + # Off-center bins contain delays [2, 3] and [4, 5]. Count their finite + # exposure independently: (8+7+6+5)/100/2 and (3+2+1)/25/2. + first_probability = 26 / 100 / 2 + second_probability = 6 / 25 / 2 + expected = np.array( + [ + [2 * first_probability + 6 * second_probability, 4 * first_probability, 0], + [4 * first_probability, 2 * first_probability, 0], + [0, 0, 0], + ] + ) + np.testing.assert_allclose(baseline, expected) + np.testing.assert_array_equal( + hist, window_correlograms(samples, clusters, windows, [9, 2, 99], 1000, 0.002, 0.008) + ) + + +def test_window_chance_baseline_matches_independent_poisson_realizations(): + """Simulate a null independently, including auto factorial and central counts.""" + rng = np.random.default_rng(12341) + length, trials, half_bins, bin_samples = 40, 1000, 3, 4 + samples, clusters, windows = [], [], [] + expected_center = np.zeros((2, 2), dtype=float) + for trial in range(trials): + start = trial * length + windows.append([start, start + length]) + counts = rng.poisson([5, 8]) + central_probability = ( + sum( + abs(left - right) < bin_samples + for left in range(length) + for right in range(length) + ) + / length**2 + ) + expected_center[0, 0] += counts[0] * (counts[0] - 1) / 2 * central_probability + expected_center[1, 1] += counts[1] * (counts[1] - 1) / 2 * central_probability + expected_center[0, 1] += counts[0] * counts[1] * central_probability + for label, count in enumerate(counts): + samples.extend(start + rng.integers(length, size=count)) + clusters.extend([label] * count) + order = np.argsort(samples) + hist, baseline = window_correlograms( + np.asarray(samples)[order], + np.asarray(clusters)[order], + np.asarray(windows), + [0, 1], + 1000, + bin_samples / 1000, + 2 * half_bins * bin_samples / 1000, + return_baseline=True, + ) + off_center = np.delete(hist, half_bins, axis=2).mean(axis=2) + np.testing.assert_allclose(off_center, baseline, rtol=0.06) + expected_center[1, 0] = expected_center[0, 1] + np.testing.assert_allclose(hist[..., half_bins], expected_center, rtol=0.06) + # Cross central counts fold both temporal orientations into one wider bin. + assert hist[0, 1, half_bins] > 1.8 * baseline[0, 1] + + +def test_window_chance_baseline_uses_actual_integer_bins_and_excludes_center_only(): + samples = np.array([0, 1, 2, 3], dtype=np.int64) + clusters = np.array([0, 0, 1, 1]) + windows = np.array([[0, 10]], dtype=np.int64) + quantized = window_correlograms( + samples, clusters, windows, [0, 1], 1000, 0.0029, 0.013, return_baseline=True + ) + exact = window_correlograms( + samples, clusters, windows, [0, 1], 1000, 0.002, 0.008, return_baseline=True + ) + for actual, expected in zip(quantized, exact): + np.testing.assert_array_equal(actual, expected) + center_only, baseline = window_correlograms( + samples, clusters, windows, [0, 1], 1000, 0.002, 0.003, return_baseline=True + ) + assert center_only.shape == (2, 2, 1) + assert center_only.max() > 0 + np.testing.assert_array_equal(baseline, np.zeros((2, 2))) diff --git a/phy/apps/large_recording/tests/test_streaming.py b/phy/apps/large_recording/tests/test_streaming.py new file mode 100644 index 000000000..e45086037 --- /dev/null +++ b/phy/apps/large_recording/tests/test_streaming.py @@ -0,0 +1,133 @@ +"""Memory bounds and exact row mapping for streaming accelerators.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.streaming import UnitRows, bounded_map + + +@pytest.mark.parametrize('units', [[0, 2, 4], [0, 2, 2147483647]]) +def test_unit_rows_compact_and_sparse(units): + lookup = UnitRows(np.array(units, dtype=np.int64)) + assert (lookup.table is None) == (units[-1] == 2147483647) + np.testing.assert_array_equal(lookup(np.array(units[::-1])), [2, 1, 0]) + for values in ([-1], [1], [2147483648]): + with pytest.raises(ValueError, match='catalog mismatch'): + lookup(np.array(values)) + assert lookup(np.array([], dtype=np.int64)).size == 0 + + +@pytest.mark.parametrize('units', [[2, 1], [1, 1], [-1, 2], [1.5]]) +def test_unit_rows_reject_invalid_catalog(units): + with pytest.raises(ValueError, match='Unit catalog'): + UnitRows(units) + + +def test_bounded_ordered_map(): + assert list(bounded_map(lambda x: x * 2, range(10), workers=3)) == list(range(0, 20, 2)) + for workers in (0, 33, 1.5, True): + with pytest.raises(ValueError, match='workers'): + list(bounded_map(str, [], workers)) + + +def test_parallel_hashes_equal_and_cancel(tmp_path): + from concurrent.futures import CancelledError + + from phy.apps.large_recording.source import hash_file, hash_files + + paths = {} + for i in range(5): + path = tmp_path / str(i) + path.write_bytes(bytes([i]) * (1024 * 1024 + i)) + paths[str(i)] = path + serial = {name: hash_file(path) for name, path in paths.items()} + progress = [] + assert hash_files(paths, workers=3, progress=lambda *args: progress.append(args)) == serial + assert progress[-1][1:] == (sum(p.stat().st_size for p in paths.values()),) * 2 + with pytest.raises(CancelledError): + hash_files(paths, workers=3, cancel=lambda: True) + + +def test_copy_fallback_space_and_source_immutability(tmp_path, monkeypatch): + from types import SimpleNamespace + + from phy.apps.large_recording import file_copy + + source = tmp_path / 'source' + source.write_bytes(b'original source') + destination = tmp_path / 'destination' + monkeypatch.setattr(file_copy, 'reflink', lambda *_: False) + monkeypatch.setattr(file_copy.shutil, 'disk_usage', lambda *_: SimpleNamespace(free=20)) + with pytest.raises(OSError, match='Insufficient disk space'): + file_copy.copy_source_file(source, destination, reserve_bytes=10) + assert not destination.exists() + monkeypatch.setattr(file_copy.shutil, 'disk_usage', lambda *_: SimpleNamespace(free=1000)) + assert file_copy.copy_source_file(source, destination, reserve_bytes=10) is False + assert source.stat().st_ino != destination.stat().st_ino + destination.write_bytes(b'changed') + assert source.read_bytes() == b'original source' + + +def test_native_clone_or_copy_is_independent(tmp_path): + from phy.apps.large_recording.file_copy import copy_source_file + + source, destination = tmp_path / 'source', tmp_path / 'clone' + source.write_bytes(b'original' * 1024) + copy_source_file(source, destination) + assert destination.read_bytes() == source.read_bytes() + assert source.stat().st_ino != destination.stat().st_ino + destination.write_bytes(b'changed') + assert source.read_bytes() == b'original' * 1024 + + +def test_reflink_preserves_existing_destination(tmp_path): + from phy.apps.large_recording.file_copy import reflink + + source, destination = tmp_path / 'source', tmp_path / 'existing' + source.write_bytes(b'original source') + destination.write_bytes(b'existing destination') + with pytest.raises(FileExistsError): + reflink(source, destination) + assert source.read_bytes() == b'original source' + assert destination.read_bytes() == b'existing destination' + + +def test_hash_rejects_concurrent_file_mutation(tmp_path): + from phy.apps.large_recording.source import hash_file + + path = tmp_path / 'mutating' + path.write_bytes(b'x' * 1024) + changed = False + + def mutate(size): + nonlocal changed + if not changed: + changed = True + with path.open('ab') as stream: + stream.write(b'changed') + + with pytest.raises(ValueError, match='changed during hashing'): + hash_file(path, batch_bytes=512, progress=mutate) + + +def test_reflink_propagates_io_errors_and_cleans_owned_file(tmp_path, monkeypatch): + import errno + import sys + + if not sys.platform.startswith('linux'): + pytest.skip('Linux ioctl-specific failure injection.') + import fcntl + + from phy.apps.large_recording.file_copy import reflink + + source, destination = tmp_path / 'source', tmp_path / 'new' + source.write_bytes(b'original') + + def fail(*args): + raise OSError(errno.ENOSPC, 'injected no space') + + monkeypatch.setattr(fcntl, 'ioctl', fail) + with pytest.raises(OSError, match='no space'): + reflink(source, destination) + assert not destination.exists() + assert source.read_bytes() == b'original' diff --git a/phy/apps/large_recording/tests/test_summaries.py b/phy/apps/large_recording/tests/test_summaries.py new file mode 100644 index 000000000..384a93004 --- /dev/null +++ b/phy/apps/large_recording/tests/test_summaries.py @@ -0,0 +1,107 @@ +"""Full counts and acquisition exposure compared with an independent tiny oracle.""" + +import numpy as np +import pytest + +from phy.apps.large_recording.source import Source +from phy.apps.large_recording.summaries import build_summaries +from phy.apps.large_recording.tests.test_source import make_sorting + + +@pytest.mark.parametrize('workers', [1, 3]) +def test_exact_counts_exposure_and_additive_measurements(tmp_path, workers): + params = make_sorting(tmp_path / 'full', columns=True) + amplitude = np.load(params.parent / 'amplitudes.npy') + amplitude[1] = np.nan + np.save(params.parent / 'amplitudes.npy', amplitude[:, None]) + source = Source(params, valid_intervals=[[0, 7], [10, 20]], batch_size=2) + files = build_summaries(source, tmp_path / 'summary', bin_seconds=5, workers=workers) + counts = np.load(tmp_path / 'summary' / files['counts_file']) + expected = np.zeros((4, 4), dtype=np.int64) + expected_sum = np.zeros((4, 4)) + expected_n = np.zeros((4, 4), dtype=np.int64) + units = np.load(params.parent / 'spike_clusters.npy').reshape(-1) + times = np.load(params.parent / 'spike_times.npy').reshape(-1) + for unit, time, value in zip(units, times, amplitude, strict=True): + row = list(source.unit_ids).index(unit) + column = int(time // 5) + expected[row, column] += 1 + if np.isfinite(value): + expected_sum[row, column] += value + expected_n[row, column] += 1 + np.testing.assert_array_equal(counts, expected) + np.testing.assert_array_equal(counts.sum(axis=1), source.counts) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['edges_file']), [0, 5, 10, 15, 20] + ) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['exposure_file']), [5, 2, 5, 5] + ) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['amplitude_sum_file']), expected_sum + ) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['amplitude_count_file']), expected_n + ) + assert files['measurement_units']['amplitude'] == 'source amplitude units' + assert 'depth_sum_file' in files + + +def test_summary_budget_checked_before_output_allocation(tmp_path): + source = Source(make_sorting(tmp_path / 'full')) + with pytest.raises(ValueError, match='Summary budget'): + build_summaries(source, tmp_path / 'summary', bin_seconds=1, max_bytes=50) + assert not (tmp_path / 'summary').exists() + + +def test_position_coordinates_require_declared_depth_axis(tmp_path): + from phy.apps.large_recording.summaries import scalar_attributes + + params = make_sorting(tmp_path / 'full') + (params.parent / 'spike_depths.npy').unlink() + with Source(params) as source: + assert 'depth' not in scalar_attributes(source) + params.write_text(params.read_text() + 'depth_axis = 1\n') + with Source(params) as source: + np.testing.assert_array_equal( + scalar_attributes(source)['depth'], source.arrays['spike_positions.npy'][:, 1] + ) + + +def test_sparse_ids_gaps_and_partial_last_bin(tmp_path): + params = make_sorting(tmp_path / 'full') + units = np.load(params.parent / 'spike_clusters.npy') + units[units == 2] = 2147483647 + np.save(params.parent / 'spike_clusters.npy', units) + with Source(params, batch_size=2) as source: + files = build_summaries(source, tmp_path / 'summary', bin_seconds=3) + counts = np.load(tmp_path / 'summary' / files['counts_file']) + np.testing.assert_array_equal(counts.sum(axis=1), source.counts) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['edges_file']), [0, 3, 6, 9, 12, 15, 18, 20] + ) + np.testing.assert_array_equal( + np.load(tmp_path / 'summary' / files['exposure_file']), [3, 3, 3, 3, 3, 3, 2] + ) + + +def test_summary_tight_budget_and_parallel_outputs_agree(tmp_path): + from phy.apps.large_recording.summaries import summary_size + + with Source(make_sorting(tmp_path / 'full'), batch_size=3) as source: + size, _, _ = summary_size(source, bin_seconds=5) + outputs = [] + for workers in (1, 3): + directory = tmp_path / str(workers) + files = build_summaries( + source, directory, bin_seconds=5, max_bytes=size + 5120, workers=workers + ) + outputs.append( + { + key: np.load(directory / name) + for key, name in files.items() + if key.endswith('_file') + } + ) + for name in outputs[0]: + np.testing.assert_array_equal(outputs[0][name], outputs[1][name]) diff --git a/phy/apps/large_recording/tests/test_summary_service.py b/phy/apps/large_recording/tests/test_summary_service.py new file mode 100644 index 000000000..c89eb9a7c --- /dev/null +++ b/phy/apps/large_recording/tests/test_summary_service.py @@ -0,0 +1,438 @@ +"""Deterministic Qt delivery and transaction-boundary summary regressions.""" + +from concurrent.futures import CancelledError +from threading import Event, get_ident + +import numpy as np +import pytest +from phylib.utils import Bunch + +from phy.apps.large_recording import summary_service + + +@pytest.fixture +def controlled_service(qtbot, tmp_path, monkeypatch): + owner = get_ident() + calls, engines = [], [] + controls = [] + + class Session: + path = tmp_path + unit_ids = [0] + _events = [] + + @property + def events(self): + assert get_ident() == owner, 'worker accessed live session' + return self._events + + class Engine: + max_bytes = 64 * 1024 * 1024 + summary_bytes = 8 + + def __init__(self, path, source_dir=None): + self.cache = {'base': primitive(10)} + self.source_dir = source_dir + self.closed = False + engines.append(self) + + @staticmethod + def key(expression): + return expression + + def cached(self, expressions): + return {c: self.cache[e] for c, e in expressions.items() if e in self.cache} + + def remember(self, expressions, results): + self.cache.update({expressions[c]: result for c, result in results.items()}) + + def resolve(self, expressions, cancel=None, progress=None): + assert get_ident() != owner + control = controls[len(calls)] + calls.append((expressions, self.source_dir)) + control.progress = progress + control.started.set() + assert control.release.wait(10), 'test did not release summary worker' + if cancel(): + raise CancelledError() + if control.error is not None: + raise control.error + return {c: primitive(control.count) for c in expressions} + + def close(self): + self.closed = True + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def expressions(unit_ids, events): + result = {0: 'base'} + for event in events: + if 'membership' in event: + result = event['membership'].copy() + return result + + monkeypatch.setattr(summary_service, 'LiveSummaryEngine', Engine) + monkeypatch.setattr(summary_service, 'membership_expressions', expressions) + session = Session() + service = summary_service.LiveSummaryService(session) + + def control(count=5, error=None): + item = Bunch(started=Event(), release=Event(), count=count, error=error) + controls.append(item) + return item + + fixture = Bunch( + session=session, service=service, calls=calls, engines=engines, control=control + ) + try: + yield fixture + finally: + service.close() + for item in controls: + item.release.set() + qtbot.waitUntil(lambda: all(engine.closed for engine in engines)) + + +def primitive(count): + counts = np.asarray([count], dtype=np.int64) + counts.flags.writeable = False + return {'counts': counts, 'trend_sums': {}, 'trend_counts': {}} + + +def split(fixture, expressions=None): + fixture.session._events = [ + {'membership': expressions if expressions is not None else {1: 'left', 2: 'right'}} + ] + fixture.service.synchronize() + + +def test_deferred_snapshot_discards_rolled_back_transaction(qtbot, controlled_service): + f = controlled_service + changes = [] + f.service.changed.connect(lambda: changes.append(True)) + f.service.resume() + split(f) + f.session._events = [] # A later transaction observer rejects the operation. + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert not f.calls + assert not changes + assert f.service.get_summary(0)['counts'].sum() == 10 + + +def test_both_children_single_scan_labels_preserve_work(qtbot, controlled_service): + f = controlled_service + job = f.control() + split(f) + assert f.service.get_summary(1) is None + assert not f.calls # Constructor and metric queries cannot start workers. + f.service.resume() + qtbot.waitUntil(job.started.is_set) + assert f.calls[0][0] == {1: 'left', 2: 'right'} + changes = [] + f.service.changed.connect(lambda: changes.append(get_ident())) + f.session._events = f.session.events + [{'operation': 'label'}] + f.service.synchronize() + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert not changes + assert len(f.calls) == 1 + assert 'recomputing' in f.service.status(1) + job.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(1) is not None) + assert f.service.get_summary(2)['counts'].sum() == 5 + assert all(thread == get_ident() for thread in changes) + assert not f.service.get_summary(1)['counts'].flags.writeable + + +def test_branch_completion_cached_but_never_attached_to_reused_id(qtbot, controlled_service): + f = controlled_service + first, second = f.control(3), f.control(7) + f.service.resume() + split(f) + qtbot.waitUntil(first.started.is_set) + split(f, {1: 'different-left', 2: 'different-right'}) + assert f.service.get_summary(1) is None + first.release.set() + qtbot.waitUntil(second.started.is_set) + assert f.service.get_summary(1) is None + second.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(1) is not None) + assert f.service.get_summary(1)['counts'].sum() == 7 + split(f) # Undo to the earlier branch: its result remains reusable. + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert f.service.get_summary(1)['counts'].sum() == 3 + assert len(f.calls) == 2 + + +def test_undo_while_running_and_redo_reuses_result(qtbot, controlled_service): + f = controlled_service + job = f.control() + f.service.resume() + split(f) + qtbot.waitUntil(job.started.is_set) + f.session._events = [] + f.service.synchronize() + job.release.set() + qtbot.waitUntil(lambda: f.service._running is None) + assert f.service.get_summary(1) is None + assert f.service.get_summary(0)['counts'].sum() == 10 + split(f) + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert f.service.get_summary(1)['counts'].sum() == 5 + assert len(f.calls) == 1 + + +def test_source_failure_requires_explicit_retry_and_relocation( + qtbot, controlled_service, tmp_path +): + f = controlled_service + first = f.control(error=FileNotFoundError('source moved')) + second = f.control(8) + f.service.resume() + split(f) + qtbot.waitUntil(first.started.is_set) + first.release.set() + qtbot.waitUntil(lambda: 'source moved' in f.service.status(1)) + assert 'unavailable' in f.service.status(1) + f.service.synchronize() + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert len(f.calls) == 1 + relocated = tmp_path / 'relocated' + f.service.retry(source_path=relocated) + qtbot.waitUntil(second.started.is_set) + assert f.calls[1][1] == relocated + second.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(1) is not None) + assert f.service.status(1) == 'ready' + + +def test_close_nonblocking_drops_queued_delivery(qtbot, controlled_service): + f = controlled_service + job = f.control() + f.service.resume() + split(f) + qtbot.waitUntil(job.started.is_set) + changes = [] + f.service.changed.connect(lambda: changes.append(True)) + f.service.close() # Worker is still blocked; cannot wait for it here. + assert not job.release.is_set() + assert f.service._running.is_set() + assert f.service.get_summary(1) is None + job.release.set() + qtbot.waitUntil(lambda: all(engine.closed for engine in f.engines)) + assert not changes + assert 'closed' in f.service.status(1) + + +def test_suspend_resume_serializes_cancelled_worker(qtbot, controlled_service): + f = controlled_service + first, second = f.control(), f.control(9) + f.service.resume() + split(f) + qtbot.waitUntil(first.started.is_set) + f.service.suspend() + assert 'cancelled' in f.service.status(1) + f.service.resume() + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert len(f.calls) == 1 + first.release.set() + qtbot.waitUntil(second.started.is_set) + second.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(1) is not None) + assert f.service.get_summary(1)['counts'].sum() == 9 + assert f.engines[1].closed + assert not f.engines[-1].closed + f.service.suspend() + qtbot.waitUntil(lambda: all(engine.closed for engine in f.engines[1:])) + + +def test_successive_jobs_reuse_worker_owned_engine(qtbot, controlled_service): + f = controlled_service + first, second = f.control(), f.control(9) + f.service.resume() + split(f) + qtbot.waitUntil(first.started.is_set) + first.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(1) is not None) + split(f, {3: 'nested-left', 4: 'nested-right'}) + qtbot.waitUntil(second.started.is_set) + assert len(f.engines) == 2 # One GUI resolver, one persistent worker reader. + assert not f.engines[1].closed + second.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(3) is not None) + + +def test_cache_error_returns_explicit_status(qtbot, controlled_service, monkeypatch): + f = controlled_service + + def too_large(expressions): + raise ValueError('Live summary output budget exceeded.') + + monkeypatch.setattr(f.service._engine, 'cached', too_large) + assert f.service.get_summary(0) is None + assert 'budget exceeded' in f.service.status(0) + f.service.resume() + qtbot.waitUntil(lambda: not f.service._timer.isActive()) + assert not f.calls + + +def test_aggregate_requests_are_batched_to_output_budget(qtbot, controlled_service): + f = controlled_service + f.service._engine.max_bytes = 16 # Two eight-byte summaries per job. + first, second = f.control(), f.control(9) + f.service.resume() + split(f, {1: 'a', 2: 'b', 3: 'c', 4: 'd'}) + qtbot.waitUntil(first.started.is_set) + assert f.calls[0][0] == {1: 'a', 2: 'b'} + first.release.set() + qtbot.waitUntil(second.started.is_set) + assert f.calls[1][0] == {3: 'c', 4: 'd'} + second.release.set() + qtbot.waitUntil(lambda: f.service.get_summary(4) is not None) + assert len(f.calls) == 2 + + +def test_real_worker_exact_primitives_merge_offline_and_no_curation_side_effects(qtbot, tmp_path): + from copy import deepcopy + + from phy.apps.large_recording.curation import BoundedSession + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'source') + bounded = prepare_large( + params, tmp_path / 'bounded', window_seconds=3, stratum_seconds=20, bin_seconds=5 + ) + session = BoundedSession(bounded) + predicate = { + 'attribute': 'amplitudes.npy', + 'operator': '>=', + 'threshold': 4, + 'nonfinite': 'keep', + } + session.record_split(0, 100, 101, predicate) + events, metadata = deepcopy(session.events), deepcopy(session.metadata) + assignments = session.assignments.copy() + original_files = {p: p.read_bytes() for p in bounded.iterdir() if p.is_file()} + service = summary_service.LiveSummaryService(session) + try: + service.resume() + qtbot.waitUntil(lambda: service.get_summary(100) is not None) + np.testing.assert_array_equal(service.get_summary(100)['counts'], [0, 0, 1, 1]) + np.testing.assert_array_equal(service.get_summary(101)['counts'], [2, 0, 0, 0]) + np.testing.assert_array_equal( + service.get_summary(100)['trend_sums']['amplitude'], [0, 0, 6, 9] + ) + assert session.events == events + assert session.metadata == metadata + np.testing.assert_array_equal(session.assignments, assignments) + assert {p: p.read_bytes() for p in original_files} == original_files + worker = service._worker + service.suspend() + qtbot.waitUntil(lambda: not worker.thread.is_alive()) + params.parent.rename(tmp_path / 'source-offline') + session.record_merge([100, 1], 102) + service.synchronize() + np.testing.assert_array_equal(service.get_summary(102)['counts'], [1, 1, 2, 1]) + assert service.status(102) == 'ready' + assert service.total_count(102) == 5 + assert len(service._totals) <= len(service._expressions) + finally: + service.close() + session.close() + + +def test_evicted_rows_do_not_restart_scans_on_table_redraw(qtbot, controlled_service, monkeypatch): + f = controlled_service + engine = f.service._engine + engine.max_bytes = 16 + + def bounded_remember(expressions, results): + for unit, result in results.items(): + engine.cache[expressions[unit]] = result + while len(engine.cache) > 2: + engine.cache.pop(next(iter(engine.cache))) + + monkeypatch.setattr(engine, 'remember', bounded_remember) + first, second = f.control(), f.control(9) + # Emulate the table refreshing every unit on each completion, with no disk + # cache available to restore rows evicted by the tiny resident budget. + f.service.changed.connect(lambda: [f.service.get_summary(unit) for unit in range(1, 5)]) + f.service.resume() + split(f, {1: 'a', 2: 'b', 3: 'c', 4: 'd'}) + qtbot.waitUntil(first.started.is_set) + first.release.set() + qtbot.waitUntil(second.started.is_set) + second.release.set() + qtbot.waitUntil(lambda: f.service._running is None and not f.service._timer.isActive()) + assert len(f.calls) == 2 + assert f.service.get_summary(1) is None + assert 'cache budget' in f.service.status(1) + assert f.service.total_count(1) == 5 + assert f.service.total_count(4) == 9 + assert len(f.calls) == 2 + + +def test_progress_is_queued_and_stale_or_cancelled_updates_are_ignored(qtbot, controlled_service): + f = controlled_service + job = f.control() + f.service.resume() + split(f) + qtbot.waitUntil(job.started.is_set) + job.progress('reading prepared unit summaries', 1, 2) + qtbot.waitUntil(lambda: '50%' in f.service.status(1)) + running = f.service._running + f.service._progress((Event(), 'stale', 1, 1)) + assert '50%' in f.service.status(1) + running.set() + f.service._progress((running, 'cancelled', 1, 1)) + assert 'cancelled' not in f.service._progress_text + job.release.set() + qtbot.waitUntil(lambda: f.service._running is None) + + +def test_progress_for_undone_memberships_is_ignored(qtbot, controlled_service): + f = controlled_service + job = f.control() + f.service.resume() + split(f) + qtbot.waitUntil(job.started.is_set) + job.progress('reading prepared unit summaries', 1, 2) + qtbot.waitUntil(lambda: '50%' in f.service.status(1)) + split(f, {3: 'other-left', 4: 'other-right'}) + f.service._progress((f.service._running, 'old branch', 9, 10)) + assert f.service.status(3) == 'pending full summary computation' + assert 'old branch' not in f.service._progress_text + # Teardown releases the pending original request; do not start a new one. + f.service.suspend() + job.release.set() + + +def test_membership_revision_skips_label_and_label_undo_expression_scan( + controlled_service, monkeypatch +): + f = controlled_service + f.session.membership_revision = object() + f.service._refresh() + old = f.session.events + + def forbid(*args, **kwargs): + pytest.fail('A label rebuilt summary membership expressions.') + + monkeypatch.setattr(summary_service, 'membership_expressions', forbid) + f.session._events = old + [{'operation': 'label'}] + assert not f.service._refresh() + f.session._events = old + assert not f.service._refresh() + f.session.membership_revision = object() + monkeypatch.setattr(summary_service, 'membership_expressions', lambda *args: {1: 'branch'}) + assert f.service._refresh() + + +def test_closed_summary_refresh_does_not_access_detached_session(controlled_service): + service = controlled_service.service + service.close() + assert not service._refresh() diff --git a/phy/apps/large_recording/tests/test_summary_store.py b/phy/apps/large_recording/tests/test_summary_store.py new file mode 100644 index 000000000..b822fef86 --- /dev/null +++ b/phy/apps/large_recording/tests/test_summary_store.py @@ -0,0 +1,425 @@ +"""Unit-contiguous snapshot construction and selective integrity validation.""" + +import json +from concurrent.futures import CancelledError + +import numpy as np +import pytest + +from phy.apps.large_recording.live_summaries import LiveSummaryEngine +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.summary_store import SummaryStore, _bin_dtype, build_summary_store +from phy.apps.large_recording.tests.test_live_summaries import package + + +@pytest.mark.parametrize('workers', [1, 3]) +@pytest.mark.parametrize('columns,positions', [(False, False), (True, True)]) +def test_store_exact_values_and_package_unchanged(tmp_path, columns, positions, workers): + source, bounded = package(tmp_path, columns, positions) + before = {p.name: hash_file(p) for p in bounded.iterdir() if p.is_file()} + output = build_summary_store( + bounded, tmp_path / 'store', batch_size=2, buffer_bytes=12, workers=workers + ) + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + assert store.dtype['bin'] == np.dtype('uint8') + assignments = np.load(source / 'spike_clusters.npy').reshape(-1) + times = np.load(source / 'spike_times.npy').reshape(-1) + for unit in engine.manifest['unit_ids']: + data = np.concatenate(list(store.batches(unit, 2))) + selected = assignments == unit + np.testing.assert_array_equal( + data['bin'], np.searchsorted(engine.edges, times[selected], side='right') - 1 + ) + amps = np.load(source / 'amplitudes.npy').reshape(-1) + np.testing.assert_array_equal(data['amplitude'], amps[selected]) + np.testing.assert_array_equal(data['depth'], times[selected] * 2) + assert output.is_dir() + assert {p.name: hash_file(p) for p in bounded.iterdir() if p.is_file()} == before + assert not list(tmp_path.glob('.*.building-*')) + + +@pytest.mark.parametrize('workers', [1, 3]) +def test_store_budgets_cancel_and_failure_do_not_publish(tmp_path, workers): + _, bounded = package(tmp_path) + output = tmp_path / 'store' + with pytest.raises(ValueError, match='increase max_bytes'): + build_summary_store(bounded, output, max_bytes=1) + with pytest.raises(ValueError, match='outside'): + build_summary_store(bounded, bounded / 'index') + + def progress(phase, done, total): + if phase == 'building summary store': + raise CancelledError() + + with pytest.raises(CancelledError): + build_summary_store(bounded, output, batch_size=2, progress=progress, workers=workers) + assert not output.exists() + assert not (bounded / '.phy' / 'live-summary-store.json').exists() + assert not list(tmp_path.glob('.*.building-*')) + build_summary_store(bounded, output) + with pytest.raises(ValueError, match='already exists'): + build_summary_store(bounded, output) + + +def test_store_selective_hash_and_corruption(tmp_path): + _, bounded = package(tmp_path) + output = build_summary_store(bounded, tmp_path / 'store') + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + item = store.index['units']['1'] + offset = item['start'] * store.dtype.itemsize + with (output / 'data.bin').open('r+b') as stream: + stream.seek(offset) + byte = stream.read(1) + stream.seek(offset) + stream.write(bytes([byte[0] ^ 1])) + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + list(store.batches(0, 2)) # An unrelated unit remains independently verifiable. + with pytest.raises(ValueError, match='checksum'): + list(store.batches(1, 2)) + index = output / 'index.json' + catalog = json.loads(index.read_text()) + catalog['units']['0']['count'] += 1 + index.write_text(json.dumps(catalog)) + with LiveSummaryEngine(bounded) as engine, pytest.raises(ValueError, match='binding'): + SummaryStore(engine) + + +def test_bin_dtype_boundaries_and_64bit_catalog(tmp_path): + assert _bin_dtype(256) == np.dtype('uint8') + assert _bin_dtype(257) == np.dtype('uint16') + assert _bin_dtype(65537) == np.dtype('uint32') + assert _bin_dtype(2**32 + 1) == np.dtype('uint64') + # Catalog arithmetic uses Python/int64, never a uint32 spike permutation. + offsets = np.cumsum(np.array([2**32 + 7, 5], dtype=np.int64)) + assert int(offsets[-1]) == 2**32 + 12 + + +def test_fortran_positions_preserve_declared_depth_axis(tmp_path): + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'source') + (params.parent / 'spike_depths.npy').unlink() + params.write_text(params.read_text() + 'depth_axis = 1\n') + positions = np.asfortranarray(np.column_stack((np.arange(12) + 1000, np.arange(12) * 7))) + np.save(params.parent / 'spike_positions.npy', positions) + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=5) + build_summary_store(bounded, tmp_path / 'store', batch_size=3) + assignments = np.load(params.parent / 'spike_clusters.npy') + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + for unit in engine.manifest['unit_ids']: + data = np.concatenate(list(store.batches(unit, 2))) + np.testing.assert_array_equal(data['depth'], positions[assignments == unit, 1]) + + +def test_attach_completed_store_after_reference_loss(tmp_path): + from phy.apps.large_recording.summary_store import attach_summary_store + + _, bounded = package(tmp_path) + output = build_summary_store(bounded, tmp_path / 'store') + reference = bounded / '.phy' / 'live-summary-store.json' + reference.unlink() + attach_summary_store(bounded, output) + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + assert len(np.concatenate(list(store.batches(0, 2)))) == 4 + + +def test_real_sparse_payload_seek_beyond_32bit_rows(tmp_path): + import hashlib + from types import SimpleNamespace + + from phy.apps.large_recording.source import hash_json + from phy.apps.large_recording.summary_store import binding + + count = 2**32 + 7 + engine = SimpleNamespace( + path=tmp_path / 'bounded', + binding={'test': 'large offsets'}, + bins=4, + fields=['amplitude'], + manifest={ + 'unit_ids': [0, 1], + 'counts': [count, 1], + 'source_array_inventory': {'amplitudes.npy': {'dtype': 'float32'}}, + }, + ) + store_path = tmp_path / 'store' + store_path.mkdir() + dtype = np.dtype([('bin', 'uint8'), ('amplitude', 'float32')]) + row = np.array([(2, 3.5)], dtype=dtype).tobytes() + with (store_path / 'data.bin').open('wb') as stream: + import os + + if os.name == 'nt': + import ctypes + import msvcrt + + # NTFS requires explicit sparse marking before extending a file: + # https://learn.microsoft.com/windows/win32/api/winioctl/ni-winioctl-fsctl_set_sparse + returned = ctypes.c_ulong() + handle = ctypes.c_void_p(msvcrt.get_osfhandle(stream.fileno())) + success = ctypes.windll.kernel32.DeviceIoControl( + handle, 0x900C4, None, 0, None, 0, ctypes.byref(returned), None + ) + if not success: + pytest.skip('Test filesystem cannot create sparse files.') + stream.seek(count * dtype.itemsize) + stream.write(row) + index = { + 'binding': binding(engine), + 'dtype': dtype.descr, + 'payload_bytes': (count + 1) * dtype.itemsize, + 'units': { + '0': {'start': 0, 'count': count, 'sha256': 'unused'}, + '1': {'start': count, 'count': 1, 'sha256': hashlib.sha256(row).hexdigest()}, + }, + } + (store_path / 'index.json').write_text(json.dumps(index)) + (engine.path / '.phy').mkdir(parents=True) + (engine.path / '.phy' / 'live-summary-store.json').write_text( + json.dumps( + { + 'path': str(store_path), + 'index_sha256': hash_json(index), + } + ) + ) + with SummaryStore(engine) as store: + data = np.concatenate(list(store.batches(1, 2))) + assert data['bin'].tolist() == [2] + assert data['amplitude'].tolist() == [3.5] + + +@pytest.mark.parametrize('operator', ['<', '<=', '>', '>=']) +def test_indexed_nested_histories_match_independent_replay_offline( + tmp_path, monkeypatch, operator +): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.tests.test_live_summaries import merge, oracle, split + + source, bounded = package(tmp_path, columns=True, positions=True) + build_summary_store(bounded, tmp_path / 'store', batch_size=3) + events = [split(1, [100, 101]), merge([101, 2], 102), split(102, [103, 104], threshold=7)] + events[-1]['predicate']['operator'] = operator + expressions = membership_expressions([0, 1, 2, 99], events) + with LiveSummaryEngine(bounded) as engine: + expected = {u: oracle(source, engine, events, u) for u in expressions} + source.rename(tmp_path / 'source-offline') + + def no_source(*args, **kwargs): + raise AssertionError('Indexed summaries opened the original source') + + monkeypatch.setattr(LiveSummaryEngine, '_open', no_source) + progress = [] + with LiveSummaryEngine(bounded, batch_size=2) as engine: + results = engine.resolve(expressions, progress=lambda *p: progress.append(p)) + for unit, summary in results.items(): + for name, values in engine._flat(summary).items(): + np.testing.assert_allclose(values, engine._flat(expected[unit])[name]) + # Only original units 1 and 2 are read, once each, for all their descendants. + assert progress[-1] == ('reading prepared unit summaries', 6, 6) + + +def test_corrupt_index_falls_back_without_publishing_partial_results(tmp_path, monkeypatch): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.tests.test_live_summaries import oracle, split + + source, bounded = package(tmp_path) + output = build_summary_store(bounded, tmp_path / 'store') + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + offset = store.index['units']['0']['start'] * store.dtype.itemsize + with (output / 'data.bin').open('r+b') as stream: + stream.seek(offset + 1) + stream.write(b'\xff') + events = [split(0, [100, 101])] + expressions = membership_expressions([0, 1, 2, 99], events) + calls = [] + original = LiveSummaryEngine._open + + def opened(self, *args, **kwargs): + calls.append(True) + return original(self, *args, **kwargs) + + monkeypatch.setattr(LiveSummaryEngine, '_open', opened) + with LiveSummaryEngine(bounded) as engine: + results = engine.resolve(expressions) + for unit in (100, 101): + for name, values in engine._flat(results[unit]).items(): + np.testing.assert_allclose( + values, engine._flat(oracle(source, engine, events, unit))[name] + ) + assert calls == [True] + + +def test_indexed_nonfinite_reject_is_semantic_error_not_source_fallback(tmp_path, monkeypatch): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.tests.test_live_summaries import split + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + + def no_source(*args, **kwargs): + raise AssertionError('Semantic rejection should not rescan the original source') + + monkeypatch.setattr(LiveSummaryEngine, '_open', no_source) + expressions = membership_expressions([0, 1, 2, 99], [split(1, [100, 101], nonfinite='reject')]) + with LiveSummaryEngine(bounded) as engine, pytest.raises(ValueError, match='Nonfinite'): + engine.resolve(expressions) + assert not list((bounded / '.phy' / 'live-summary-cache').glob('*.npz')) + + +def test_template_predicate_uses_validated_source_fallback(tmp_path): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.tests.test_live_summaries import oracle, split + + source, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + events = [split(0, [100, 101], attribute='spike_templates.npy', threshold=1)] + expressions = membership_expressions([0, 1, 2, 99], events) + progress = [] + with LiveSummaryEngine(bounded) as engine: + results = engine.resolve(expressions, progress=lambda *p: progress.append(p)) + np.testing.assert_array_equal( + results[100]['counts'], oracle(source, engine, events, 100)['counts'] + ) + assert progress[-1][0] == 'scanning full source' + + +def test_cancel_indexed_scan_never_publishes(tmp_path): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.tests.test_live_summaries import split + + _, bounded = package(tmp_path) + build_summary_store(bounded, tmp_path / 'store') + expressions = membership_expressions([0, 1, 2, 99], [split(0, [100, 101])]) + stopped = [False] + + def progress(*args): + stopped[0] = True + + with LiveSummaryEngine(bounded, batch_size=1) as engine, pytest.raises(CancelledError): + engine.resolve(expressions, cancel=lambda: stopped[0], progress=progress) + assert not list((bounded / '.phy' / 'live-summary-cache').glob('*.npz')) + + +def test_racing_publication_never_replaces_empty_target(tmp_path, monkeypatch): + from phy.apps.large_recording import summary_store + + _, bounded = package(tmp_path) + output = tmp_path / 'store' + original = summary_store.publish_directory + + def race(staged, destination): + destination.mkdir() + return original(staged, destination) + + monkeypatch.setattr(summary_store, 'publish_directory', race) + with pytest.raises(OSError): + build_summary_store(bounded, output) + assert output.is_dir() and not list(output.iterdir()) + assert not list(tmp_path.glob('.*.building-*')) + assert not (bounded / '.phy' / 'live-summary-store.json').exists() + + +def test_disk_failure_cleans_unpublished_store(tmp_path, monkeypatch): + import errno + + from phy.apps.large_recording import summary_store + + _, bounded = package(tmp_path) + + def full(*args): + raise OSError(errno.ENOSPC, 'disk full') + + monkeypatch.setattr(summary_store.os, 'fsync', full) + with pytest.raises(OSError, match='disk full'): + build_summary_store(bounded, tmp_path / 'store') + assert not (tmp_path / 'store').exists() + assert not list(tmp_path.glob('.*.building-*')) + + +def test_completed_store_can_attach_after_reference_write_failure(tmp_path, monkeypatch): + from phy.apps.large_recording import summary_store + + _, bounded = package(tmp_path) + output = tmp_path / 'store' + original = summary_store._atomic_json + + def fail_reference(path, value): + if path.name == summary_store.REFERENCE: + raise OSError('reference write failed') + original(path, value) + + monkeypatch.setattr(summary_store, '_atomic_json', fail_reference) + with pytest.raises(OSError, match='reference write failed'): + build_summary_store(bounded, output) + assert output.is_dir() + monkeypatch.setattr(summary_store, '_atomic_json', original) + summary_store.attach_summary_store(bounded, output) + with LiveSummaryEngine(bounded) as engine, SummaryStore(engine) as store: + assert len(np.concatenate(list(store.batches(0, 2)))) == 4 + + +def test_wide_real_scalars_use_float64_accumulators(tmp_path): + from phy.apps.large_recording.live_summaries import membership_expressions + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_live_summaries import split + from phy.apps.large_recording.tests.test_source import make_sorting + + params = make_sorting(tmp_path / 'source') + for name in ('amplitudes.npy', 'spike_depths.npy'): + np.save(params.parent / name, np.load(params.parent / name).astype(np.longdouble)) + bounded = prepare_large(params, tmp_path / 'bounded', bin_seconds=5) + expressions = membership_expressions([0, 1, 2, 99], [split(0, [100, 101])]) + with LiveSummaryEngine(bounded) as engine: + baseline = engine.resolve(expressions) + build_summary_store(bounded, tmp_path / 'store') + import shutil + + shutil.rmtree(bounded / '.phy' / 'live-summary-cache') + with LiveSummaryEngine(bounded) as engine: + indexed = engine.resolve(expressions) + for unit in expressions: + for name, actual in engine._flat(indexed[unit]).items(): + np.testing.assert_array_equal(actual, engine._flat(baseline[unit])[name]) + + +def test_post_publication_sync_failure_preserves_attachable_store(tmp_path, monkeypatch): + from phy.apps.large_recording import summary_store + + _, bounded = package(tmp_path) + output = tmp_path / 'store' + original = summary_store._fsync_directory + + def fail_parent(path): + if path == output.parent and output.exists(): + raise OSError('parent sync failed') + original(path) + + monkeypatch.setattr(summary_store, '_fsync_directory', fail_parent) + with pytest.raises(OSError, match='parent sync failed'): + build_summary_store(bounded, output) + assert output.is_dir() + assert not list(tmp_path.glob('.*.building-*')) + monkeypatch.setattr(summary_store, '_fsync_directory', original) + summary_store.attach_summary_store(bounded, output) + + +def test_automatic_build_attachment_preserves_newer_store_choice(tmp_path): + from phy.apps.large_recording.summary_store import ( + SummaryStorePublishedError, + attach_summary_store, + summary_store_reference, + ) + + _, bounded = package(tmp_path) + first = build_summary_store(bounded, tmp_path / 'first', attach=False) + + def choose_first(): + attach_summary_store(bounded, first) + + with pytest.raises(SummaryStorePublishedError, match='changed while'): + build_summary_store(bounded, tmp_path / 'second', before_publish=choose_first) + assert (tmp_path / 'second' / 'index.json').is_file() + reference = json.loads(summary_store_reference(bounded)) + assert reference['path'] == str(first) diff --git a/phy/apps/large_recording/tests/test_summary_task_gui.py b/phy/apps/large_recording/tests/test_summary_task_gui.py new file mode 100644 index 000000000..94bfd8192 --- /dev/null +++ b/phy/apps/large_recording/tests/test_summary_task_gui.py @@ -0,0 +1,607 @@ +"""Nonmodal store task workflow and live handover without reopening.""" + +from threading import Event + +import pytest + +from phy.apps.large_recording import summary_task_gui +from phy.apps.large_recording.summary_store import StoreEstimate, summary_store_reference +from phy.apps.large_recording.summary_tasks import StoreInspection +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.gui.qt import QTimer +from phy.gui.tasks import TaskProgress + + +@pytest.fixture +def opened(tmp_path): + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + actions = controller._summary_store_actions + actions._checked = True # Automatic prompt gets its own explicit test below. + try: + yield controller, gui, actions + finally: + gui.close() + controller.close() + + +def test_build_keeps_gui_responsive_and_adopts_store_after_curation( + qtbot, opened, tmp_path, monkeypatch +): + from phy.apps.large_recording.live_summaries import LiveSummaryEngine + from phy.apps.large_recording.range_index import AmplitudeRangeIndex + + range_queries = [] + original_range = AmplitudeRangeIndex.resolve + + def observe_range(self, expressions, *args, **kwargs): + result = original_range(self, expressions, *args, **kwargs) + range_queries.append(set(expressions)) + return result + + monkeypatch.setattr(AmplitudeRangeIndex, 'resolve', observe_range) + controller, gui, actions = opened + original = summary_task_gui.prepare_summary_store + started, release, built, deliver = Event(), Event(), Event(), Event() + + def controlled(request, context): + started.set() + assert release.wait(5) + result = original(request, context) + built.set() + assert deliver.wait(5) + return result + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', controlled) + pending_modes = [] + + def observe_pending(state): + if state == 'pending': + pending_modes.append(actions._mode) + assert not actions.widget.bar.isHidden() + assert not actions.widget.cancel_button.isHidden() + assert actions.widget.cancel_button.isEnabled() + assert actions.widget.hide_button.text() == 'Hide' + + actions.manager.state_changed.connect(observe_pending) + heartbeat = [] + timer = QTimer() + timer.setInterval(10) + timer.timeout.connect(lambda: heartbeat.append(True)) + timer.start() + try: + actions.build(tmp_path / 'store') + qtbot.waitUntil(started.is_set) + children = controller.supervisor.split_source_amplitude(0, 4).added + controller.supervisor.undo() + controller.supervisor.redo() + qtbot.waitUntil(lambda: len(heartbeat) >= 5) + assert controller.get_full_count(children[0]) is None + assert 'waiting' in controller.get_summary_status(children[0]) + release.set() + qtbot.waitUntil(built.is_set) + + def forbid_source(*args, **kwargs): + raise AssertionError('GUI handover rescanned the original source') + + monkeypatch.setattr(LiveSummaryEngine, '_open', forbid_source) + deliver.set() + qtbot.waitUntil(lambda: summary_store_reference(controller.dir_path) is not None) + qtbot.waitUntil(lambda: controller.get_full_count(children[0]) == 2) + assert not controller._live_summaries._suspended + assert actions.manager.state == 'succeeded' + assert controller.supervisor.is_dirty() # Building must not save curation. + assert 'ready' in actions.widget.label.text().lower() + assert pending_modes == ['build', 'attach', 'build-range', 'attach-range'] + assert actions.widget.bar.isHidden() + assert actions.widget.cancel_button.isHidden() + assert actions.widget.hide_button.text() == 'Close' + log = actions.widget.log.toPlainText() + actions.widget.hide_button.click() + assert actions.widget.isHidden() + gui.file_actions.run('show_background_task') + assert not actions.widget.isHidden() + assert actions.widget.bar.isHidden() + assert actions.widget.log.toPlainText() == log + assert range_queries + assert set(children) <= set().union(*range_queries) + finally: + timer.stop() + release.set() + deliver.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + + +def test_accepted_close_cancels_old_task_without_attaching_to_reopened_gui( + qtbot, opened, tmp_path, monkeypatch +): + controller, gui, old = opened + started, release = Event(), Event() + + def blocked(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', blocked) + old.build(tmp_path / 'store') + qtbot.waitUntil(started.is_set) + gui.close() + reopened = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + controller._summary_store_actions._checked = True + try: + release.set() + qtbot.waitUntil(lambda: not old.manager.busy) + assert summary_store_reference(controller.dir_path) is None + assert controller._summary_store_actions is not old + assert not controller._live_summaries._suspended + finally: + release.set() + reopened.close() + + +def test_prompt_is_single_and_suppression_is_dataset_local(qtbot, opened): + controller, gui, actions = opened + actions.build_dialog() + qtbot.waitUntil(lambda: actions.dialog is not None) + dialog = actions.dialog + actions.build_dialog() + assert actions.dialog is dialog + dialog.suppress.setChecked(True) + dialog._continue() + assert gui.state['SummaryStore']['suppress_prompt'] + assert not actions.manager.busy + assert not controller._live_summaries._suspended + + +def test_reference_read_error_is_recoverable(qtbot, opened, monkeypatch): + _, _, actions = opened + + def unreadable(*args, **kwargs): + raise OSError('permission denied') + + monkeypatch.setattr(summary_task_gui, 'summary_store_reference', unreadable) + actions.build_dialog() + assert 'permission denied' in actions.widget.label.text() + assert not actions.manager.busy + assert not actions.service._suspended + assert actions.widget.bar.isHidden() + assert actions.widget.cancel_button.isHidden() + assert actions.widget.hide_button.text() == 'Close' + + +@pytest.mark.parametrize('long_path', [False, True]) +def test_preparation_warning_stays_visible_without_completed_progress( + qtbot, opened, tmp_path, monkeypatch, long_path +): + from phy.apps.large_recording.summary_tasks import StoreArtifact + + _, _, actions = opened + + def warning(request, context): + return StoreArtifact(request.destination, warning='Could not publish reference') + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', warning) + destination = tmp_path / ('long-' + 'x' * 120) / 'store' if long_path else tmp_path / 'store' + actions.build(destination) + qtbot.waitUntil(lambda: not actions.manager.busy) + assert actions._mode == 'build' + assert 'needs attention' in actions.widget.label.text() + assert str(destination) in actions.widget.label.toolTip() + assert str(destination) in actions.widget.log.toPlainText() + assert 'Could not publish reference' in actions.widget.log.toPlainText() + assert not actions.widget.isHidden() + assert actions.widget.bar.isHidden() + assert actions.widget.cancel_button.isHidden() + assert actions.widget.hide_button.text() == 'Close' + assert not actions.service._suspended + + +def test_prompt_budget_and_async_preflight(qtbot, tmp_path, monkeypatch): + monkeypatch.setattr(summary_task_gui, '_free_space', lambda path: 1024 * 1073741824) + estimate = StoreEstimate(100 * 1073741824, 100 * 1073741824, 100, 6, str(tmp_path / 'source')) + prompt = summary_task_gui.StorePrompt( + StoreInspection(estimate, False, True), tmp_path / 'store' + ) + try: + qtbot.waitUntil(lambda: 'budget' in prompt.problem.text()) + assert not prompt.build_button.isEnabled() + prompt.budget.setValue(128) + qtbot.waitUntil(prompt.build_button.isEnabled) + prompt.destination.setText(str(tmp_path)) + qtbot.waitUntil(lambda: 'new directory' in prompt.problem.text()) + assert not prompt.build_button.isEnabled() + finally: + prompt.close() + + +def test_cancel_text_survives_late_progress(qtbot, opened): + _, _, actions = opened + actions.manager.state = 'cancelling' + actions.widget.on_progress(TaskProgress('Building', 1, 100, 'rows')) + assert actions.widget.estimate.text() == 'Cancelling…' + actions.manager.state = 'idle' + + +def test_saved_budget_and_package_boundary_are_passed_to_prompt(qtbot, opened): + controller, gui, actions = opened + gui.state['SummaryStore'] = {'max_bytes': 128 * 1073741824} + actions.build_dialog() + qtbot.waitUntil(lambda: actions.dialog is not None) + dialog = actions.dialog + assert dialog.budget.value() == 128 + dialog.destination.setText(str(controller.dir_path / 'inside-store')) + qtbot.waitUntil(lambda: 'outside the bounded package' in dialog.problem.text()) + assert not dialog.build_button.isEnabled() + + +def test_automatic_prompt_occurs_once_per_open(qtbot, opened): + _, _, actions = opened + actions._checked = False + actions._automatic_check() + qtbot.waitUntil(lambda: actions.dialog is not None) + first = actions.dialog + first._continue() + actions._automatic_check() + assert actions.dialog is first + assert not first.isVisible() + + +def test_destination_preflight_does_not_block_gui_or_apply_stale_path( + qtbot, tmp_path, monkeypatch +): + started, release = Event(), Event() + original = summary_task_gui.check_destination + + def blocked(request, context): + if not started.is_set(): + started.set() + assert release.wait(5) + return original(request, context) + + monkeypatch.setattr(summary_task_gui, 'check_destination', blocked) + estimate = StoreEstimate(100, 100, 10, 6, str(tmp_path / 'source')) + prompt = summary_task_gui.StorePrompt( + StoreInspection(estimate, False, True), tmp_path / 'new-store' + ) + heartbeat = [] + timer = QTimer() + timer.setInterval(10) + timer.timeout.connect(lambda: heartbeat.append(True)) + timer.start() + try: + qtbot.waitUntil(started.is_set) + prompt.destination.setText(str(tmp_path)) + qtbot.waitUntil(lambda: len(heartbeat) >= 5) + release.set() + qtbot.waitUntil(lambda: 'new directory' in prompt.problem.text()) + assert not prompt.build_button.isEnabled() + finally: + release.set() + timer.stop() + prompt.close() + + +def test_vetoed_close_keeps_task_alive(qtbot, opened, tmp_path, monkeypatch): + from phylib.utils import connect, unconnect + + _, gui, actions = opened + started, release = Event(), Event() + + def blocked(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', blocked) + + @connect(event='close', sender=gui) + def veto(sender): + return False + + try: + actions.build(tmp_path / 'store') + qtbot.waitUntil(started.is_set) + gui.close() + assert not gui._closed + assert not actions._closed + assert actions.manager.busy + assert not actions.manager._cancel.is_set() + finally: + unconnect(veto) + actions.manager.cancel() + release.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + + +def test_gui_deletion_detaches_worker_before_controller_cleanup(qtbot, tmp_path, monkeypatch): + from PyQt5 import sip + from PyQt5.QtCore import QCoreApplication, QEvent + + _, controller = make_controller(tmp_path) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + actions = controller._summary_store_actions + actions._checked = True + started, release = Event(), Event() + + def blocked(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', blocked) + try: + actions.build(tmp_path / 'store') + qtbot.waitUntil(started.is_set) + gui.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + assert sip.isdeleted(gui) + assert actions._closed + assert actions.manager._cancel.is_set() + release.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + finally: + release.set() + if not sip.isdeleted(gui): + gui.close() + controller.close() + + +def test_automatic_prompt_keeps_main_window_shortcut_ownership(qtbot, opened): + from phy.gui.qt import QApplication + + _, gui, actions = opened + actions._checked = False + gui.show() + qtbot.waitUntil(lambda: actions.dialog is not None and actions.dialog.isVisible()) + qtbot.waitUntil(lambda: QApplication.activeWindow() is gui) + assert actions.dialog.isVisible() + + +def test_prompt_disables_build_with_insufficient_free_space(qtbot, tmp_path, monkeypatch): + monkeypatch.setattr(summary_task_gui, '_free_space', lambda path: 0) + estimate = StoreEstimate(100, 100, 10, 6, str(tmp_path / 'source')) + prompt = summary_task_gui.StorePrompt( + StoreInspection(estimate, False, True), tmp_path / 'store' + ) + try: + qtbot.waitUntil(lambda: 'not enough free space' in prompt.problem.text()) + assert not prompt.build_button.isEnabled() + assert '0.00 GB' in prompt.available.text() + finally: + prompt.close() + + +def test_existing_row_store_upgrades_without_source_or_row_rebuild( + qtbot, opened, tmp_path, monkeypatch +): + from phy.apps.large_recording.live_summaries import LiveSummaryEngine + from phy.apps.large_recording.range_index import AmplitudeRangeIndex + from phy.apps.large_recording.summary_store import build_summary_store + + controller, gui, actions = opened + store = build_summary_store(controller.dir_path, tmp_path / 'store') + source = controller.bounded_session.manifest['source']['path'] + from pathlib import Path + + Path(source).rename(tmp_path / 'offline-source') + + def forbid(*args, **kwargs): + raise AssertionError('Upgrade rebuilt existing rows') + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', forbid) + actions.build_dialog() + qtbot.waitUntil(lambda: actions.dialog is not None) + assert actions._inspection.compatible + assert not actions._inspection.optimized + assert actions._inspection.source_available + actions.dialog.close() + actions.build(store / 'amplitude-index') + qtbot.waitUntil(lambda: actions._mode == 'attach-range' and not actions.manager.busy) + with LiveSummaryEngine(controller.dir_path) as engine: + index = AmplitudeRangeIndex(engine) + index.close() + assert not controller._live_summaries._suspended + + +def test_cancelling_amplitude_preparation_preserves_usable_rows( + qtbot, opened, tmp_path, monkeypatch +): + controller, gui, actions = opened + started, release = Event(), Event() + + def blocked(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + + monkeypatch.setattr(summary_task_gui, 'prepare_amplitude_index', blocked) + controller._live_summaries._errors['stale-error'] = 'unavailable: old source error' + try: + actions.build(tmp_path / 'store') + qtbot.waitUntil(started.is_set) + assert summary_store_reference(controller.dir_path) is not None + actions.manager.cancel() + release.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + assert actions.manager.state == 'cancelled' + assert not controller._live_summaries._errors + assert not controller._live_summaries._suspended + children = controller.supervisor.split_source_amplitude(0, 4).added + qtbot.waitUntil(lambda: controller.get_full_count(children[0]) == 2) + finally: + release.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + + +def test_late_row_commit_cancel_stops_next_long_stage(qtbot, opened, tmp_path, monkeypatch): + controller, gui, actions = opened + original = summary_task_gui.prepare_summary_store + committed, release = Event(), Event() + calls = [] + + def controlled(request, context): + result = original(request, context) + committed.set() + assert release.wait(5) + return result + + def forbid(*args): + calls.append(True) + raise AssertionError('Late cancel started another long stage') + + monkeypatch.setattr(summary_task_gui, 'prepare_summary_store', controlled) + monkeypatch.setattr(summary_task_gui, 'prepare_amplitude_index', forbid) + try: + actions.build(tmp_path / 'store') + qtbot.waitUntil(committed.is_set) + actions.manager.cancel() + release.set() + qtbot.waitUntil(lambda: actions._mode == 'attach' and not actions.manager.busy) + assert not calls + assert summary_store_reference(controller.dir_path) is not None + assert not controller._live_summaries._suspended + finally: + release.set() + qtbot.waitUntil(lambda: not actions.manager.busy) + + +def test_attach_independent_amplitude_index_from_gui(qtbot, opened, tmp_path): + from phy.apps.large_recording.live_summaries import LiveSummaryEngine + from phy.apps.large_recording.range_build import build_amplitude_index + from phy.apps.large_recording.range_index import AmplitudeRangeIndex + from phy.apps.large_recording.summary_store import attach_summary_store, build_summary_store + + controller, gui, actions = opened + store = build_summary_store(controller.dir_path, tmp_path / 'store') + index = build_amplitude_index(controller.dir_path, tmp_path / 'independent-index') + attach_summary_store(controller.dir_path, store) + moved = tmp_path / 'moved-index' + index.rename(moved) + actions.attach_index(moved) + qtbot.waitUntil(lambda: not actions.manager.busy) + assert actions.manager.state == 'succeeded' + with LiveSummaryEngine(controller.dir_path) as engine: + reader = AmplitudeRangeIndex(engine) + assert reader.path == moved + reader.close() + assert not controller._live_summaries._suspended + + +@pytest.mark.parametrize('state', ['idle', 'completed', 'active']) +def test_deleted_task_manager_does_not_interrupt_owner_cleanup(qtbot, opened, state): + from PyQt5 import sip + + from phy.gui import tasks + + controller, gui, actions = opened + manager = actions.manager + started, release = Event(), Event() + + def worker(request, context): + started.set() + assert release.wait(3) + context.check_cancel() + return None + + record = None + try: + if state != 'idle': + manager.submit(tasks.TaskSpec('owner-delete-' + state, 'Delete owner', worker, None)) + assert started.wait(3) + record = manager._lifetime.record + if state == 'completed': + release.set() + qtbot.waitUntil(lambda: not manager.busy) + sip.delete(manager) + actions.close() + actions.close() + assert actions._closed + assert actions.widget._disposed + assert manager._detached + if record is not None: + assert record.context.cancelled.is_set() + assert record.task_id not in tasks._MANAGERS + finally: + release.set() + if record is not None and state == 'active': + qtbot.waitUntil(lambda: record.outcome is not None) + + +def test_owner_cleanup_cancels_task_even_if_widget_cleanup_raises(qtbot, opened, monkeypatch): + _, _, actions = opened + + def fail(): + raise RuntimeError('injected cleanup failure') + + monkeypatch.setattr(actions.widget, 'dispose', fail) + with pytest.raises(RuntimeError, match='injected'): + actions.close() + assert actions.manager._detached + assert actions._closed + actions.close() + + +@pytest.mark.parametrize('deleted', ['manager', 'timer', 'dialog']) +def test_prompt_preflight_cleanup_survives_qt_deletion(qtbot, tmp_path, deleted): + from PyQt5 import sip + + estimate = StoreEstimate(100, 100, 10, 6, str(tmp_path / 'source')) + prompt = summary_task_gui.StorePrompt( + StoreInspection(estimate, False, True), tmp_path / 'store' + ) + manager = prompt._disk_manager + if deleted == 'manager': + sip.delete(manager) + elif deleted == 'timer': + sip.delete(prompt._disk_timer) + else: + sip.delete(prompt) + prompt._dispose_preflight() + prompt._dispose_preflight() + assert prompt._preflight_closed + assert manager._detached + if not sip.isdeleted(prompt): + prompt.close() + + +@pytest.mark.parametrize('completed', [False, True]) +def test_gui_destruction_after_manager_deletion_exits_cleanly_in_subprocess(tmp_path, completed): + import subprocess + import sys + + script = r""" +import sys +import time +from pathlib import Path +from PyQt5 import sip +from phy.gui.qt import create_app +from phy.gui.tasks import TaskSpec +from phy.apps.large_recording.tests.test_adapter import make_controller +app = create_app() +_, controller = make_controller(Path(sys.argv[1])) +gui = controller.create_gui(default_views=[], do_prompt_save=False) +actions = controller._summary_store_actions +actions._checked = True +if COMPLETED: + actions.manager.submit(TaskSpec('destroy-after-completion', 'Complete', lambda r,c: None, None)) + end=time.monotonic()+3 + while actions.manager.busy and time.monotonic(){group.display_id}{suffix}') + hidden = ( + self._proposition_visible_keys is not None + and group.key not in self._proposition_visible_keys + ) + units = [ + str(unit) + for unit, annotation in self._proposition_labels.annotations.items() + if group in annotation.groups + ] + details.append( + f'{group.display_id}: pending{suffix}' + f'{"; hidden by proposition filter" if hidden else ""}; displayed IDs: ' + + ', '.join(units) + ) + if len(groups) > 4: + items.append(f'+{len(groups) - 4} groups (details)') + overlapping = [ + annotation + for annotation in self._proposition_labels.annotations.values() + if len(annotation.groups) > 1 + ] + if overlapping: + items.append('* multiple groups') + details.append( + 'Overlapping IDs use their first listed color (active groups first); * retains all groups.' + ) + details.extend( + f'{annotation.text}: ' + ', '.join(group.display_id for group in annotation.groups) + for annotation in overlapping + ) + legend.setText('SLAY IDs: ' + ' · '.join(items)) + details.append('White IDs have no current pending source-proposition membership.') + legend.setToolTip('\n'.join(details)) + legend.setVisible(bool(groups)) + + def _plot_labels(self): + self._refresh_proposition_annotations() + self._update_display_scale() + n = len(self.cluster_ids) + for k, cluster_id in enumerate(self.cluster_ids): + annotation = self._proposition_labels.annotations[cluster_id] + for pos, anchor, box_index in ( + ([-1, 0], [-1, 0], (k, 0)), + ([0, -1], [0, -1], (n - 1, k)), + ): + self.text_visual.add_batch_data( + pos=pos, + text=annotation.text, + color=annotation.color, + anchor=anchor, + data_bounds=None, + box_index=box_index, + ) + + def _display_scale_for_size(self, width, height): + sx, sy = super()._display_scale_for_size(width, height) + annotations = self._proposition_labels.annotations + max_chars = max((len(str(unit)) for unit in self.cluster_ids), default=1) + label_chars = max((len(item.text) for item in annotations.values()), default=max_chars) + glyph_width = self.text_visual._tex.shape[1] // 16 * self.text_visual.font_size / 12 + return max(0.5, sx - 2 * max(0, label_chars - max_chars) * glyph_width / max(width, 1)), sy + + def refresh_proposition_labels(self): + """Refresh only label buffers after catalog/review changes, never pair counts.""" + if self._closed: + return + self._refresh_proposition_annotations() + if not self.cluster_ids or not self._dock_visible: + self._proposition_labels_pending = bool(self.cluster_ids) + return + self._proposition_labels_pending = False + self.text_visual.reset_batch() + self._plot_labels() + self.canvas.update_visual(self.text_visual) + self.canvas.update() + + def _on_proposition_visibility_changed(self, visible): + if visible and self._proposition_labels_pending: + self.refresh_proposition_labels() + + def _on_proposition_close(self, sender, gui): + self._cleanup_proposition_labels() + + def _on_proposition_gui_closed(self, sender): + self._cleanup_proposition_labels() + + def _cleanup_proposition_labels(self): + if not self._proposition_connections: + return + self._proposition_connections = False + self.dock.visibilityChanged.disconnect(self._on_proposition_visibility_changed) + unconnect(self._on_proposition_close, self._on_proposition_gui_closed) + + @property + def exclusion_ms(self): + return self._exclusion_ms + + @exclusion_ms.setter + def exclusion_ms(self, value): + value = float(value) + if not np.isfinite(value) or value < 0: + raise ValueError('Exclusion half-width must be finite and nonnegative.') + self._exclusion_ms = value + + @property + def status(self): + status = super().status + if self.exclusion_correlograms is not None: + enabled = [ + name + for name, value in (('auto', self.exclude_auto), ('cross', self.exclude_cross)) + if value + ] + if enabled: + # Dock status text is elided in the middle. Keep every active + # switch and the width in the visible prefix. + status = f'EXCL {"+".join(enabled)} ±{self.exclusion_ms:g} ms | {status}' + return status + + def _get_correlograms_data(self): + if self.exclusion_correlograms is not None: + return self.exclusion_correlograms( + self.cluster_ids, + self.bin_size, + self.window_size, + exclusion_ms=self.exclusion_ms, + exclude_auto=self.exclude_auto, + exclude_cross=self.exclude_cross, + ) + return self.correlograms(self.cluster_ids, self.bin_size, self.window_size) + + def _update_exclusion(self): + if hasattr(self, 'actions'): + for name, checked in ( + ('toggle_auto_exclusion', self.exclude_auto), + ('toggle_cross_exclusion', self.exclude_cross), + ): + action = self.actions.get(name) + if action is not None: + action.setChecked(checked) + self.update_status() + if self.cluster_ids: + self.plot() + + def set_exclusion_zone(self, value): + """Set the near-zero pair exclusion half-width in milliseconds. + + Zero excludes exact-time pairs when the corresponding switch is enabled. + Only displayed pair counts change; spike trains and assignments are retained. + """ + self.exclusion_ms = value + self._update_exclusion() + + def toggle_auto_exclusion(self, checked): + """Exclude near-zero pairs from sampled autocorrelograms.""" + self.exclude_auto = bool(checked) + self._update_exclusion() + + def toggle_cross_exclusion(self, checked): + """Exclude near-zero pairs from sampled cross-correlograms.""" + self.exclude_cross = bool(checked) + self._update_exclusion() + + def attach(self, gui): + super().attach(gui) + if self.proposition_context is not None: + self.proposition_legend = QLabel() + self.proposition_legend.setWordWrap(True) + self.proposition_legend.setTextFormat(Qt.RichText) + self.proposition_legend.setStyleSheet('color: white; background: black; padding: 2px;') + self.dock.widget().layout().addWidget(self.proposition_legend) + self.dock.visibilityChanged.connect(self._on_proposition_visibility_changed) + connect(self._on_proposition_close, event='close_view', sender=self) + connect(self._on_proposition_gui_closed, event='closed', sender=gui) + self._proposition_connections = True + self._refresh_proposition_annotations() + if self.exclusion_correlograms is None: + return + self.actions.separator() + self.actions.add( + self.set_exclusion_zone, + prompt=True, + prompt_default=lambda: self.exclusion_ms, + ) + self.actions.add(self.toggle_auto_exclusion, checkable=True, checked=self.exclude_auto) + self.actions.add(self.toggle_cross_exclusion, checkable=True, checked=self.exclude_cross) + # Other view shortcuts are window-wide. Scope these two to this dock so + # typing in a table/filter cannot silently change the displayed counts. + self.dock._widget.setFocusPolicy(Qt.StrongFocus) + for name in ('toggle_auto_exclusion', 'toggle_cross_exclusion'): + action = self.actions.get(name) + gui.removeAction(action) + self.dock.addAction(action) + action.setShortcutContext(Qt.WidgetWithChildrenShortcut) + self.update_status() + + +class EvidenceAmplitudeView(AmplitudeView): + """Sampled source amplitudes with a full-recording clock or local window.""" + + def __init__(self, *args, **kwargs): + self._amplitude_scope = 'overview' + super().__init__(*args, **kwargs) + self.state_attrs += ('amplitude_scope',) + + @property + def amplitude_scope(self): + return self._amplitude_scope + + @amplitude_scope.setter + def amplitude_scope(self, scope): + if scope not in ('overview', 'window'): + raise ValueError('Amplitude scope must be overview or window.') + self.clear_amplitude_split_threshold() + self._amplitude_scope = scope + if hasattr(self, '_controller'): + self._controller._update_amplitude_scope(self) + + def toggle_amplitude_scope(self): + """Toggle the full recording overview and current evidence window.""" + self.amplitude_scope = 'window' if self.amplitude_scope == 'overview' else 'overview' + + def on_request_split(self, sender=None): + # Bounded commits consume a semantic predicate, never sampled row IDs. + return np.array([], dtype=np.int64) + + window_caption = 'Recording time unavailable' + + def set_window_context(self, index, start_seconds, end_seconds): + self.window_caption = ( + f'Evidence window {index} | Recording time: {start_seconds:.3f}–{end_seconds:.3f} s' + ) + if hasattr(self, 'window_label'): + self.window_label.setText(self.window_caption) + + def attach(self, gui): + super().attach(gui) + self.actions.add(self.toggle_amplitude_scope, show_shortcut=False) + layout = self.dock.widget().layout() + self.window_label = QLabel(self.window_caption) + self.window_label.setWordWrap(True) + self.time_axis_label = QLabel( + 'Recording time (seconds)' + if self.amplitude_scope == 'overview' + else 'Seconds from window start' + ) + for label in (self.window_label, self.time_axis_label): + label.setAlignment(Qt.AlignCenter) + label.setStyleSheet('color: white; background-color: black; padding: 4px;') + layout.insertWidget(0, self.window_label) + layout.insertWidget(layout.count() - 1, self.time_axis_label) + + def _get_data_bounds(self, bunchs): + if not any(len(bunch.amplitudes) for bunch in bunchs): + return (0, 0, self.duration, 1) + xmin, ymin, xmax, ymax = super()._get_data_bounds(bunchs) + if ymin == ymax: + ymin, ymax = ymin - 0.5, ymax + 0.5 + return xmin, ymin, xmax, ymax diff --git a/phy/apps/template/gui.py b/phy/apps/template/gui.py index dfa0e3e82..481c75faf 100644 --- a/phy/apps/template/gui.py +++ b/phy/apps/template/gui.py @@ -81,6 +81,14 @@ class TemplateController(WaveformMixin, FeatureMixin, TemplateMixin, TraceMixin, # Internal methods # ------------------------------------------------------------------------- + def __new__(cls, dir_path=None, *args, **kwargs): + if cls is TemplateController and dir_path is not None: + if (Path(dir_path) / '_phy_curation_manifest.json').exists(): + from ..large_recording.adapter import BoundedTemplateController + + return object.__new__(BoundedTemplateController) + return object.__new__(cls) + def _get_waveforms_dict(self): waveforms_dict = super()._get_waveforms_dict() # Remove waveforms and mean_waveforms if there is no raw data file. @@ -142,6 +150,7 @@ def _get_template_features(self, cluster_ids, load_all=False): def _set_view_creator(self): super()._set_view_creator() self.view_creator['TemplateFeatureView'] = self.create_template_feature_view + self.view_creator['UnitStabilityView'] = self.create_unit_stability_view # Public methods # ------------------------------------------------------------------------- @@ -255,6 +264,12 @@ def create_template_feature_view(self): return return TemplateFeatureView(coords=self._get_template_features) + def create_unit_stability_view(self): + """Optionally inspect selected-unit activity over the loaded recording.""" + from ..large_recording.stability import UnitStabilityView + + return UnitStabilityView(self) + # ------------------------------------------------------------------------------ # Template commands @@ -269,9 +284,14 @@ def template_gui(params_path, **kwargs): # pragma: no cover handler = _add_log_file(dir_path / 'phy.log') try: logger.info('Starting Template GUI: %s', _software_info()) - model = load_model(params_path) + bounded = (dir_path / '_phy_curation_manifest.json').exists() + model = None if bounded else load_model(params_path) # Automatically export spike waveforms when using compressed raw ephys. - if model.spike_waveforms is None and isinstance(model.traces, MtscompEphysReader): + if ( + model is not None + and model.spike_waveforms is None + and isinstance(model.traces, MtscompEphysReader) + ): # TODO: customizable values below. model.save_spikes_subset_waveforms(max_n_spikes_per_template=500, max_n_channels=16) finally: @@ -289,6 +309,22 @@ def template_gui(params_path, **kwargs): # pragma: no cover def template_describe(params_path): """Describe a template dataset.""" + if (Path(params_path).parent / '_phy_curation_manifest.json').exists(): + from ..large_recording.curation import BoundedSession + + session = BoundedSession(Path(params_path).parent) + try: + print(f'Bounded evidence: {len(session.assignments):,} spikes') + print( + f'Complete source: {session.manifest["num_spikes"]:,} spikes, {len(session.unit_ids):,} units' + ) + print( + f'Duration: {session.manifest["num_samples"] / session.manifest["sample_rate"]:.3f} s' + ) + print(f'Committed curation: {len(session.events)} semantic operations') + finally: + session.close() + return model = load_model(params_path) model.describe() model.close() diff --git a/phy/apps/tests/large_recording_fixtures.py b/phy/apps/tests/large_recording_fixtures.py new file mode 100644 index 000000000..7041213bd --- /dev/null +++ b/phy/apps/tests/large_recording_fixtures.py @@ -0,0 +1,153 @@ +"""Small, deterministic on-disk example of a 1000-hour two-stage Phy dataset. + +This is reference test data, not a prepare-large implementation. The fake +recording has 32 spikes spread across 1000 hours, not 1000 hours of raw traces. +The full and bounded folders use ordinary Phy filenames. +""" + +import hashlib +import json +import shutil +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + + +@dataclass(frozen=True) +class LongRecordingFixture: + full: Path + bounded: Path + global_ids: np.ndarray + upstream_waveform_ids: np.ndarray + bounded_waveform_ids: np.ndarray + + +def _sha256(path): + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _reference_remap(global_ids, upstream_ids): + """Reference intersection for sorted, unique, nonnegative int64 row IDs.""" + global_ids = np.asarray(global_ids) + upstream_ids = np.asarray(upstream_ids) + for ids in (global_ids, upstream_ids): + if ids.ndim != 1 or ids.dtype != np.dtype('int64'): + raise ValueError('Row IDs must be one-dimensional int64 arrays.') + if np.any(ids < 0) or np.any(ids[1:] <= ids[:-1]): + raise ValueError('Row IDs must be nonnegative, sorted, and unique.') + if not len(global_ids) or not len(upstream_ids): + empty = np.array([], dtype=np.int64) + return empty, empty.copy() + positions = np.searchsorted(global_ids, upstream_ids) + keep = positions < len(global_ids) + keep[keep] &= global_ids[positions[keep]] == upstream_ids[keep] + return positions[keep].astype(np.int64), np.flatnonzero(keep).astype(np.int64) + + +def make_long_recording_fixture(root): + """Write one full Phy dataset and its expected bounded counterpart.""" + root = Path(root) + full, bounded = root / 'full', root / 'bounded' + full.mkdir(parents=True) + bounded.mkdir(parents=True) + + fs = 30_000 + num_samples = 1000 * 3600 * fs # Far beyond signed int32 sample indices. + samples = np.linspace(100, num_samples - 100, 32, dtype=np.int64) + samples[8] = samples[5] # Simultaneous spikes retain distinct source row identities. + samples[6:8] = samples[5] + units = (np.arange(32) % 3).astype(np.int32) + amplitudes = np.arange(1, 33, dtype=np.float32) + templates = np.zeros((3, 12, 4), dtype=np.float32) + for unit in range(3): + templates[unit, :, unit] = -np.arange(12, dtype=np.float32) + + for name, array in ( + ('spike_times.npy', samples), + ('spike_clusters.npy', units), + ('spike_templates.npy', units), + ('amplitudes.npy', amplitudes), + ('templates.npy', templates), + ('channel_map.npy', np.arange(4, dtype=np.int32)), + ('channel_positions.npy', np.array([[0, 0], [20, 0], [0, 20], [20, 20]])), + ): + np.save(full / name, array) + (full / 'params.py').write_text( + "sample_rate = 30000.0\ndat_path = None\nn_channels_dat = 4\ndtype = 'int16'\n", + encoding='utf-8', + ) + + upstream_ids = np.array([1, 2, 8, 13, 18, 21, 28, 31], dtype=np.int64) + channels = np.array( + [[0, 1, -1] if i % 2 == 0 else [2, 3, -1] for i in range(len(upstream_ids))], + dtype=np.int32, + ) + waveforms = np.zeros((len(upstream_ids), 12, 3), dtype=np.float32) + for row, spike_id in enumerate(upstream_ids): + waveforms[row, :, 0] = spike_id + np.arange(12) / 12 + waveforms[row, :, 1] = -(spike_id + np.arange(12) / 12) + stem = '_phy_spikes_subset' + np.save(full / f'{stem}.spikes.npy', upstream_ids) + np.save(full / f'{stem}.channels.npy', channels) + np.save(full / f'{stem}.waveforms.npy', waveforms) + + # Proposed, optional upstream window metadata: simple homogeneous arrays. + starts = np.minimum(samples[upstream_ids] - 10, num_samples - 30 * fs) + bounds = np.column_stack((starts, starts + 30 * fs)).astype(np.int64) + types = np.zeros(len(upstream_ids), dtype=np.uint8) + types[-1] = 1 # rescue + strata = (samples[upstream_ids] // (3600 * fs)).astype(np.int32) + strata[-1] = -1 # rescue has no survey stratum + np.save(full / f'{stem}.window_bounds.npy', bounds) + np.save(full / f'{stem}.window_types.npy', types) + np.save(full / f'{stem}.window_strata.npy', strata) + source_hash = _sha256(full / 'spike_times.npy') + (full / f'{stem}.manifest.json').write_text( + json.dumps( + { + 'format': 'phy_spikes_subset', + 'format_version': 1, + 'source_sorting': {'num_spikes': len(samples), 'spike_times_sha256': source_hash}, + 'recording': { + 'sampling_frequency_hz': fs, + 'num_samples': num_samples, + 'num_channels': 4, + 'num_segments': 1, + }, + 'selection': {'algorithm': 'synthetic_windows_v1', 'seed': 42}, + 'waveform_extraction': {'nbefore_samples': 4, 'nafter_samples': 8}, + 'window_types': {'0': 'survey', '1': 'rescue'}, + }, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + + global_ids = np.array([0, 2, 5, 8, 13, 21, 25, 31], dtype=np.int64) + for name in ('spike_times.npy', 'spike_clusters.npy', 'spike_templates.npy', 'amplitudes.npy'): + np.save(bounded / name, np.load(full / name)[global_ids]) + for name in ('templates.npy', 'channel_map.npy', 'channel_positions.npy', 'params.py'): + shutil.copyfile(full / name, bounded / name) + np.save(bounded / '_phy_spike_global_ids.npy', global_ids) + + bounded_rows, waveform_rows = _reference_remap(global_ids, upstream_ids) + np.save(bounded / f'{stem}.spikes.npy', bounded_rows) + np.save(bounded / f'{stem}.channels.npy', channels[waveform_rows]) + np.save(bounded / f'{stem}.waveforms.npy', waveforms[waveform_rows]) + (bounded / '_phy_curation_manifest.json').write_text( + json.dumps( + { + 'format': 'phy_bounded_curation', + 'format_version': 1, + 'source': {'num_spikes': len(samples), 'spike_times_sha256': source_hash}, + 'global_spike_ids_file': '_phy_spike_global_ids.npy', + 'duration_seconds': 1000 * 3600, + }, + indent=2, + ) + + '\n', + encoding='utf-8', + ) + return LongRecordingFixture(full, bounded, global_ids, upstream_ids, bounded_rows) diff --git a/phy/apps/tests/test_base.py b/phy/apps/tests/test_base.py index 75bffe3e6..1ed0360f5 100644 --- a/phy/apps/tests/test_base.py +++ b/phy/apps/tests/test_base.py @@ -167,6 +167,35 @@ def _mock_controller(tempdir, cls): ) +def test_cancelled_close_preserves_controller_selection_hooks(qtbot, tempdir): + controller = _mock_controller(tempdir, MyController) + gui = controller.create_gui(default_views=[], do_prompt_save=False) + with qtbot.waitExposed(gui): + gui.show() + handlers = set(logging.getLogger('phy').handlers) + + @connect(event='close', sender=gui) + def cancel(sender): + return False + + try: + gui.close() + assert not gui._closed + assert set(logging.getLogger('phy').handlers) == handlers + emit('request_select', controller, [1]) + controller.supervisor.block() + assert controller.supervisor.selected_clusters == [1] + emit('select_more', controller, [2]) + controller.supervisor.block() + assert set(controller.supervisor.selected_clusters) == {1, 2} + gui.create_and_add_view('CorrelogramView') + assert gui.list_views(CorrelogramView)[0].auto_update + finally: + unconnect(cancel) + gui.close() + controller.close() + + def test_correlogram_transfer_request_preserves_effective_selection(qtbot, tempdir): controller = _mock_controller(tempdir, MyController) gui = controller.create_gui(do_prompt_save=False) diff --git a/phy/apps/tests/test_large_recording_contract.py b/phy/apps/tests/test_large_recording_contract.py new file mode 100644 index 000000000..8e882afc1 --- /dev/null +++ b/phy/apps/tests/test_large_recording_contract.py @@ -0,0 +1,151 @@ +"""Reference contract tests for future prepare-large and waveform remapping. + +These tests deliberately do not exercise a production prepare-large command: +that command does not exist yet. Later implementations should reuse this +fixture and replace reference-only checks with command-level assertions. +""" + +import hashlib +import json + +import numpy as np +import pytest +from phylib.io.model import load_model + +from .large_recording_fixtures import _reference_remap, make_long_recording_fixture + + +@pytest.fixture +def long_recording(tmp_path): + return make_long_recording_fixture(tmp_path) + + +def test_long_recording_uses_exact_64_bit_sample_times(long_recording): + full = np.load(long_recording.full / 'spike_times.npy') + bounded = np.load(long_recording.bounded / 'spike_times.npy') + assert full.dtype == bounded.dtype == np.dtype('int64') + assert full[-1] > np.iinfo(np.int32).max + assert full[-1] / 30_000 > 999 * 3600 + np.testing.assert_array_equal(bounded, full[long_recording.global_ids]) + assert np.all(np.diff(long_recording.global_ids) > 0) + assert np.all(np.diff(bounded) >= 0) + assert bounded[2] == bounded[3] # equal times do not collapse distinct spikes + + +def test_two_stage_row_indices_and_waveform_data(long_recording): + full = long_recording.full + bounded = long_recording.bounded + global_ids = np.load(bounded / '_phy_spike_global_ids.npy') + full_waveform_ids = np.load(full / '_phy_spikes_subset.spikes.npy') + bounded_waveform_ids = np.load(bounded / '_phy_spikes_subset.spikes.npy') + assert global_ids.dtype == bounded_waveform_ids.dtype == np.dtype('int64') + np.testing.assert_array_equal( + global_ids[bounded_waveform_ids], np.intersect1d(full_waveform_ids, global_ids) + ) + upstream_rows = np.searchsorted(full_waveform_ids, global_ids[bounded_waveform_ids]) + for suffix in ('channels', 'waveforms'): + np.testing.assert_array_equal( + np.load(bounded / f'_phy_spikes_subset.{suffix}.npy'), + np.load(full / f'_phy_spikes_subset.{suffix}.npy')[upstream_rows], + ) + # A bounded row identifies one source row, and never a waveform tensor row. + assert bounded_waveform_ids.tolist() == [1, 3, 4, 5, 7] + assert global_ids[bounded_waveform_ids].tolist() == [2, 8, 13, 21, 31] + + +def test_ordinary_phy_waveform_files_are_aligned(long_recording): + bounded = long_recording.bounded + spike_ids = np.load(bounded / '_phy_spikes_subset.spikes.npy') + channels = np.load(bounded / '_phy_spikes_subset.channels.npy') + waveforms = np.load(bounded / '_phy_spikes_subset.waveforms.npy', mmap_mode='r') + assert spike_ids.ndim == 1 and np.all(np.diff(spike_ids) > 0) + assert channels.dtype == np.dtype('int32') + assert channels.shape == (len(spike_ids), waveforms.shape[2]) + assert waveforms.shape == (len(spike_ids), 12, 3) + assert np.all((channels == -1) | ((channels >= 0) & (channels < 4))) + assert np.all(waveforms[:, :, -1] == 0) # -1 means a zero-padded channel + assert spike_ids[-1] < len(np.load(bounded / 'spike_times.npy')) + + +def test_window_arrays_use_samples_and_simple_dtypes(long_recording): + full = long_recording.full + bounds = np.load(full / '_phy_spikes_subset.window_bounds.npy') + types = np.load(full / '_phy_spikes_subset.window_types.npy') + strata = np.load(full / '_phy_spikes_subset.window_strata.npy') + spike_samples = np.load(full / 'spike_times.npy') + assert bounds.shape == (len(types), 2) + assert len(types) == len(strata) + assert bounds.dtype == np.dtype('int64') + assert types.dtype == np.dtype('uint8') + assert strata.dtype == np.dtype('int32') + assert np.all(bounds[:, 1] > bounds[:, 0]) + assert np.all(bounds[:, 1] <= 1000 * 3600 * 30_000) + assert np.all((types == 0) | (types == 1)) + assert strata[-1] == -1 and types[-1] == 1 + source_waveform_times = spike_samples[long_recording.upstream_waveform_ids] + assert np.all((bounds[:, 0] <= source_waveform_times) & (source_waveform_times < bounds[:, 1])) + + +def test_reference_remap_handles_empty_and_disjoint_inputs(): + a = np.array([14, 19, 117], dtype=np.int64) + b = np.array([2, 4, 119], dtype=np.int64) + for left, right in ((a, b), (a, b[:0]), (a[:0], b), (a[:0], b[:0])): + bounded_rows, source_rows = _reference_remap(left, right) + assert bounded_rows.dtype == source_rows.dtype == np.dtype('int64') + assert bounded_rows.shape == source_rows.shape == (0,) + rows, upstream_rows = _reference_remap(a, np.array([14, 15, 117, 118])) + assert rows.tolist() == [0, 2] + assert upstream_rows.tolist() == [0, 2] + + +@pytest.mark.parametrize('ids', [[2, 1], [1, 1], [-1, 1]]) +def test_reference_remap_rejects_invalid_row_order(ids): + valid = np.array([1, 2], dtype=np.int64) + invalid = np.array(ids, dtype=np.int64) + for left, right in ((valid, invalid), (invalid, valid)): + with pytest.raises(ValueError, match='nonnegative, sorted, and unique'): + _reference_remap(left, right) + + +def test_manifests_bind_source_index_space_not_mutable_clusters(long_recording): + full = long_recording.full + bounded = long_recording.bounded + source_hash = hashlib.sha256((full / 'spike_times.npy').read_bytes()).hexdigest() + upstream = json.loads((full / '_phy_spikes_subset.manifest.json').read_text()) + downstream = json.loads((bounded / '_phy_curation_manifest.json').read_text()) + assert upstream['source_sorting']['spike_times_sha256'] == source_hash + assert downstream['source']['spike_times_sha256'] == source_hash + assert upstream['source_sorting']['num_spikes'] == len(np.load(full / 'spike_times.npy')) + assert downstream['global_spike_ids_file'] == '_phy_spike_global_ids.npy' + assert downstream['duration_seconds'] == 1000 * 3600 + assert hashlib.sha256((bounded / 'spike_times.npy').read_bytes()).hexdigest() != source_hash + + +def test_bounded_dataset_loads_with_existing_phylib(long_recording): + """The old Phy loader consumes bounded rows, not original global indices.""" + model = load_model(long_recording.bounded / 'params.py') + try: + np.testing.assert_array_equal( + model.spike_waveforms.spike_ids, long_recording.bounded_waveform_ids + ) + assert model.n_spikes == len(long_recording.global_ids) + assert model.n_samples_waveforms == 12 + assert model.spike_times[-1] > 999 * 3600 + np.testing.assert_array_equal( + model.get_waveforms(long_recording.bounded_waveform_ids, channel_ids=[0, 1, 2, 3]), + _expected_dense_waveforms(long_recording.bounded), + ) + finally: + model.close() + + +def _expected_dense_waveforms(path): + """Independent dense expansion of the fixture's sparse channel slots.""" + channels = np.load(path / '_phy_spikes_subset.channels.npy') + waveforms = np.load(path / '_phy_spikes_subset.waveforms.npy') + expected = np.zeros((len(channels), 12, 4), dtype=waveforms.dtype) + for row, channel_row in enumerate(channels): + for slot, channel in enumerate(channel_row): + if channel >= 0: + expected[row, :, channel] = waveforms[row, :, slot] + return expected diff --git a/phy/apps/tests/test_parent_review.py b/phy/apps/tests/test_parent_review.py new file mode 100644 index 000000000..70aef3795 --- /dev/null +++ b/phy/apps/tests/test_parent_review.py @@ -0,0 +1,903 @@ +"""Exact lineage and read-only parent inspection regressions.""" + +from copy import deepcopy +from types import SimpleNamespace + +import numpy as np +import pytest +from phylib.utils import Bunch, emit + +from phy.apps._parent_review import ParentLineage, ParentProviders +from phy.apps.large_recording.tests.test_adapter import make_controller +from phy.apps.tests.test_base import MyControllerFull, _mock_controller +from phy.cluster.clustering import Clustering +from phy.cluster.views import AmplitudeView, CorrelogramView, FeatureView, WaveformView + + +def lineage_controller(path, assignments): + return SimpleNamespace( + dir_path=path, + supervisor=SimpleNamespace(clustering=Clustering(np.asarray(assignments))), + model=SimpleNamespace(spike_times=np.arange(len(assignments))), + ) + + +def test_exact_nested_split_undo_redo_membership(tmp_path): + controller = lineage_controller(tmp_path, [0, 1, 0, 1, 2, 2, 3, 3]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + first = clustering.merge([0, 1]).added[0] + nested = clustering.merge([first, 2]).added[0] + groups = lineage.parents(nested) + assert groups[2].tolist() == [4, 5] + assert groups[first].tolist() == [0, 1, 2, 3] + clustering.undo() + assert set(lineage.parents(first)) == {0, 1} + clustering.redo() + assert set(lineage.parents(nested)) == {first, 2} + split = clustering.split([0, 4]) + children = split.added + before = {int(c): clustering.spikes_per_cluster[c].copy() for c in children} + merged = clustering.merge(children).added[0] + for parent, ids in lineage.parents(merged).items(): + np.testing.assert_array_equal(ids, before[parent]) + assert not ids.flags.writeable + with pytest.raises(ValueError, match='unavailable'): + lineage.parents(3) + finally: + lineage.close() + + +def test_recursive_restore_flattens_both_branches_with_one_native_undo(tmp_path): + controller = lineage_controller(tmp_path, np.repeat(np.arange(6), 3)) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + left = clustering.merge([0, 1]).added[0] + right = clustering.merge([2, 3]).added[0] + target = clustering.merge([left, right]).added[0] + unrelated = clustering.merge([4, 5]).added[0] + before = clustering.spike_clusters.copy() + groups = lineage.parents(target, recursive=True) + assert set(groups) == {0, 1, 2, 3} + out = clustering.restore_partition(target, groups) + assert min(out.added) > unrelated + for child, origin in out.parent_restore_origins.items(): + np.testing.assert_array_equal( + clustering.spikes_per_cluster[child], np.arange(origin * 3, origin * 3 + 3) + ) + restored = clustering.spike_clusters.copy() + clustering.undo() + np.testing.assert_array_equal(clustering.spike_clusters, before) + clustering.redo() + np.testing.assert_array_equal(clustering.spike_clusters, restored) + assert clustering.spikes_per_cluster[unrelated].tolist() == list(range(12, 18)) + finally: + lineage.close() + + +def test_recursive_restore_stops_at_real_split_and_survives_reopen(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + merged = clustering.merge([0, 1]).added[0] + children = clustering.split([0, 2]).added + split_child = next( + child for child in children if clustering.spikes_per_cluster[child].tolist() == [0, 2] + ) + target = clustering.merge([split_child, 2]).added[0] + groups = lineage.parents(target, recursive=True) + assert set(groups) == {split_child, 2} + assert merged not in groups + emit('curation_saved', controller.supervisor) + saved = clustering.spike_clusters.copy() + finally: + lineage.close() + reopened = ParentLineage(lineage_controller(tmp_path, saved)) + try: + actual = reopened.parents(target, recursive=True) + assert set(actual) == set(groups) + for key in groups: + np.testing.assert_array_equal(actual[key], groups[key]) + finally: + reopened.close() + + +@pytest.mark.parametrize('corruption', ['missing', 'overlap', 'cycle', 'duplicate_origin']) +def test_recursive_restore_rejects_broken_known_ancestry_without_mutation(tmp_path, corruption): + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + first = clustering.merge([0, 1]).added[0] + target = clustering.merge([first, 2]).added[0] + before = clustering.spike_clusters.copy() + if corruption == 'missing': + del lineage.records[first] + elif corruption == 'overlap': + lineage.records[first][1] = np.array([1, 3]) + elif corruption == 'cycle': + lineage.records[first] = {target: np.arange(4)} + else: + lineage.origins[1] = 0 + with pytest.raises(ValueError): + lineage.parents(target, recursive=True) + np.testing.assert_array_equal(clustering.spike_clusters, before) + if corruption == 'missing': + emit('curation_saved', controller.supervisor) + reopened = ParentLineage(lineage_controller(tmp_path, before)) + try: + with pytest.raises(ValueError, match='incomplete'): + reopened.parents(target, recursive=True) + finally: + reopened.close() + finally: + lineage.close() + + +def test_recursive_restore_more_than_sixteen_leaves_and_nested_colors(tmp_path): + controller = lineage_controller(tmp_path, np.repeat(np.arange(20), 2)) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + branches = [clustering.merge([i, i + 1]).added[0] for i in range(0, 20, 2)] + target = clustering.merge(branches).added[0] + groups = lineage.parents(target, recursive=True) + assert set(groups) == set(range(20)) + colors = lineage.colors(target, groups) + assert len(set(colors.values())) == 20 + result = clustering.restore_partition(target, groups) + assert len(result.added) == 20 + for child, original in result.parent_restore_origins.items(): + np.testing.assert_array_equal( + clustering.spikes_per_cluster[child], np.array([original * 2, original * 2 + 1]) + ) + finally: + lineage.close() + + +def test_reassembly_membership_and_historical_anchor_survive_save_reopen(tmp_path): + from phy.cluster._propositions import decode_curation_mapping + + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + catalog = decode_curation_mapping( + {'format_version': '2', 'unit_ids': [0, 1, 2], 'merges': [{'unit_ids': [0, 1]}]} + ) + key = catalog.propositions[0].key + try: + target = clustering.merge([0, 1]).added[0] + catalog = catalog.accept(key, [0, 1], target) + controller.supervisor.merge_propositions = SimpleNamespace(catalog=catalog) + restored = clustering.restore_partition(target, lineage.parents(target, recursive=True)) + assert lineage.reassembled_results(catalog) == {} + current = clustering.merge(restored.added).added[0] + assert lineage.reassembled_results(catalog) == { + key: {'result_unit_id': current, 'modified': False} + } + current = clustering.merge([current, 2]).added[0] + assert lineage.reassembled_results(catalog)[key] == { + 'result_unit_id': current, + 'modified': True, + } + emit('curation_saved', controller.supervisor) + saved = clustering.spike_clusters.copy() + finally: + lineage.close() + reopened = ParentLineage(lineage_controller(tmp_path, saved)) + try: + assert target in reopened.records + assert reopened.reassembled_results(catalog)[key] == { + 'result_unit_id': current, + 'modified': True, + } + groups = reopened.parents(current, recursive=True) + assert set(groups) == {0, 1, 2} + finally: + reopened.close() + + +def test_recursive_restore_resolves_legacy_alias_chains_after_reopen(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + try: + target = clustering.merge([0, 1]).added[0] + first = clustering.restore_partition(target, lineage.parents(target)) + target = clustering.merge(first.added).added[0] + second = clustering.restore_partition(target, lineage.parents(target)) + # Represent an existing sidecar created by the old immediate restore path. + lineage.origins.update( + {int(child): int(parent) for child, parent in zip(second.added, first.added)} + ) + target = clustering.merge([*second.added, 2]).added[0] + emit('curation_saved', controller.supervisor) + saved = clustering.spike_clusters.copy() + finally: + lineage.close() + reopened = ParentLineage(lineage_controller(tmp_path, saved)) + try: + groups = reopened.parents(target, recursive=True) + assert set(groups) == {0, 1, 2} + for unit, rows in groups.items(): + np.testing.assert_array_equal(rows, [unit * 2, unit * 2 + 1]) + reopened.origins[first.added[0]] = second.added[0] + with pytest.raises(ValueError, match='cycle'): + reopened.parents(target, recursive=True) + finally: + reopened.close() + + +def test_lineage_save_reopen_and_stale_assignment_rejection(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2]) + lineage = ParentLineage(controller) + target = controller.supervisor.clustering.merge([0, 1]).added[0] + assignments = controller.supervisor.clustering.spike_clusters.copy() + emit('curation_saved', controller.supervisor) + lineage.close() + reopened = lineage_controller(tmp_path, assignments) + loaded = ParentLineage(reopened) + assert loaded.parents(target)[0].tolist() == [0, 1] + loaded.close() + changed = assignments.copy() + changed[[0, 5]] = changed[[5, 0]] + stale = ParentLineage(lineage_controller(tmp_path, changed)) + try: + with pytest.raises(ValueError, match='unavailable'): + stale.parents(target) + finally: + stale.close() + + +def test_restored_nested_lineage_survives_save_reopen_and_repeated_restore(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1, 2, 2, 3, 3]) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + first = clustering.merge([0, 1]).added[0] + nested = clustering.merge([first, 2]).added[0] + emit('curation_saved', controller.supervisor) + saved = clustering.spike_clusters.copy() + lineage.close() + + controller = lineage_controller(tmp_path, saved) + lineage = ParentLineage(controller) + clustering = controller.supervisor.clustering + restored = clustering.restore_partition(nested, lineage.parents(nested)) + alias = next( + child for child, parent in restored.parent_restore_origins.items() if parent == first + ) + assert set(lineage.parents(alias)) == {0, 1} + assert lineage.origins[alias] == first + assert lineage.restorations[nested] == list(restored.parent_restore_origins) + clustering.undo() + assert nested not in lineage.restorations + clustering.redo() + emit('curation_saved', controller.supervisor) + saved = clustering.spike_clusters.copy() + lineage.close() + + controller = lineage_controller(tmp_path, saved) + lineage = ParentLineage(controller) + try: + assert lineage.origins[alias] == first + assert nested in lineage.restorations + groups = lineage.parents(alias) + assert groups[0].tolist() == [0, 1] + assert groups[1].tolist() == [2, 3] + out = controller.supervisor.clustering.restore_partition(alias, groups) + assert set(out.parent_restore_origins.values()) == {0, 1} + finally: + lineage.close() + + +def test_lineage_rejects_membership_that_does_not_partition_live_unit(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1]) + lineage = ParentLineage(controller) + try: + target = controller.supervisor.clustering.merge([0, 1]).added[0] + lineage.records[target][0] = np.array([0]) + with pytest.raises(ValueError, match='partition'): + lineage.parents(target) + finally: + lineage.close() + + +def test_restore_more_than_inspection_palette_limit(tmp_path): + from phy.cluster._selection import CurationSelectionController + + controller = lineage_controller(tmp_path, np.repeat(np.arange(20), 2)) + lineage = ParentLineage(controller) + try: + clustering = controller.supervisor.clustering + target = clustering.merge(list(range(20))).added[0] + groups = lineage.parents(target) + colors = lineage.colors(target, groups) + restored = clustering.restore_partition(target, groups) + selection = CurationSelectionController() + selection.enter_parent_restore( + restored.parent_restore_origins, + {child: colors[parent] for child, parent in restored.parent_restore_origins.items()}, + ) + assert len(selection.state.merge_ids) == 20 + assert len(set(selection.state.color_indices.values())) == 20 + for child, parent in restored.parent_restore_origins.items(): + np.testing.assert_array_equal(clustering.spikes_per_cluster[child], groups[parent]) + finally: + lineage.close() + + +def test_lineage_rejects_changed_source_rows_and_corrupt_archives(tmp_path): + controller = lineage_controller(tmp_path, [0, 0, 1, 1]) + lineage = ParentLineage(controller) + target = controller.supervisor.clustering.merge([0, 1]).added[0] + emit('curation_saved', controller.supervisor) + lineage.close() + controller.model.spike_times[[0, 1]] = controller.model.spike_times[[1, 0]] + changed = ParentLineage(controller) + try: + with pytest.raises(ValueError, match='unavailable'): + changed.parents(target) + finally: + changed.close() + (tmp_path / '_phy_merge_parents.npz').write_bytes(b'PK\x03\x04broken') + corrupt = ParentLineage(controller) + try: + with pytest.raises(ValueError, match='unavailable'): + corrupt.parents(target) + finally: + corrupt.close() + + +def test_providers_use_exact_spikes_without_changing_controller(tempdir): + controller = _mock_controller(tempdir, MyControllerFull) + try: + c = controller.supervisor.clustering + original = {p: c.spikes_per_cluster[p].copy() for p in (0, 1)} + target = c.merge([0, 1]).added[0] + groups = controller.parent_inspection.lineage.parents(target) + providers = ParentProviders(controller, target, groups) + for parent, values in original.items(): + np.testing.assert_array_equal(groups[parent], values) + features = providers.features(parent) + assert set(features.spike_ids) <= set(values) + waveforms = providers.waveforms(parent) + assert set(waveforms.spike_ids) <= set(values) + amplitudes = providers.amplitudes([None, 0, 1]) + for parent, bunch in zip((0, 1), amplitudes[1:]): + assert set(bunch.spike_ids) <= set(original[parent]) + np.testing.assert_array_equal( + bunch.amplitudes, controller.model.amplitudes[bunch.spike_ids] + ) + values = providers.correlograms([0, 1], 0.001, 0.01) + assert values.shape[0:2] == (2, 2) + assert not np.any(c.spike_clusters[original[0]] != target) + finally: + controller.close() + + +def test_review_is_read_only_and_closes_on_selection_and_mutation(qtbot, tempdir, monkeypatch): + from phylib.utils.event import _EVENT + + from phy.gui.qt import Qt + + controller = _mock_controller(tempdir, MyControllerFull) + gui = controller.create_gui(do_prompt_save=False) + gui.resize(1100, 800) + gui.show() + inspection = controller.parent_inspection + supervisor = controller.supervisor + try: + target = supervisor.merge([0, 1]).added[0] + supervisor.select([target]) + supervisor.block() + supervisor.save() + saved_lineage = inspection.lineage.path.read_bytes() + before = supervisor.clustering.spike_clusters.copy() + metadata = supervisor.get_labels('group').copy() + dirty = supervisor.is_dirty() + history = supervisor.clustering._undo_stack._index + original = controller._get_waveforms + selection_settings = dict(controller.selection) + for _ in range(2): + callbacks = list(_EVENT._callbacks) + window = inspection.show(target) + qtbot.wait(30) + assert len(inspection.views) == 4 + assert {type(v) for v in inspection.views} == { + WaveformView, + FeatureView, + AmplitudeView, + CorrelogramView, + } + for view in inspection.views: + assert view.cluster_ids == [0, 1] + assert not hasattr(view, 'actions') + view.on_mouse_click(Bunch(key='Control', button='Left', pos=(0, 0))) + return_action = window.file_actions.get('return_to_merged_unit') + return_button = window._toolbar.widgetForAction(return_action) + assert window._toolbar.isVisible() + assert return_button.isVisible() and return_button.isEnabled() + assert return_button.text() == 'Back to merged unit' + assert return_button.visibleRegion().contains(return_button.rect().center()) + assert window.rect().contains( + return_button.mapTo(window, return_button.rect().center()) + ) + assert inspection.host_gui is gui + assert not window.isWindow() + assert inspection.parent_table.rowCount() == 2 + assert inspection.parent_table.isVisible() + assert window._toolbar.height() < min(100, window.height() / 4) + docks = {type(v): v.dock.geometry() for v in inspection.views} + assert docks[CorrelogramView].left() < docks[WaveformView].left() + assert docks[CorrelogramView].top() < docks[AmplitudeView].top() + assert docks[WaveformView].top() < docks[FeatureView].top() + assert docks[AmplitudeView].left() < docks[FeatureView].left() + assert docks[CorrelogramView].width() >= docks[WaveformView].width() + assert all(rect.width() >= 200 and rect.height() >= 150 for rect in docks.values()) + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + assert supervisor.get_labels('group') == metadata + assert supervisor.is_dirty() == dirty + assert supervisor.clustering._undo_stack._index == history + assert controller._get_waveforms == original + assert dict(controller.selection) == selection_settings + assert supervisor.selected == [target] + with monkeypatch.context() as patcher: + + def forbidden_wait(*args): + pytest.fail('Parent review closure must not pump curation events') + + patcher.setattr('phy.gui.gui._wait', forbidden_wait) + # A QAction trigger or QTest click on a hidden widget would also + # work. Require visible, reachable geometry before real input. + qtbot.mouseClick(return_button, Qt.LeftButton) + assert inspection.window is None + assert inspection.lineage.path.read_bytes() == saved_lineage + assert _EVENT._callbacks == callbacks + inspection.show(target) + supervisor.select([2]) + supervisor.block() + assert inspection.window is None + inspection.show(target) + supervisor.merge([target, 2]) + assert inspection.window is None + finally: + inspection.close_review() + gui.close() + controller.close() + + +def test_bounded_saved_nested_and_split_parents_use_journal_not_templates(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + path = controller.dir_path + config = controller.config_dir + try: + supervisor = controller.supervisor + first = supervisor.merge([0, 1]).added[0] + target = supervisor.merge([first, 2]).added[0] + expected_colors = dict(controller.parent_inspection.lineage.colors(target)) + assert expected_colors == {first: 0, 2: 1} + before = supervisor.clustering.spike_clusters.copy() + groups = controller.parent_inspection.lineage.parents(target) + assert set(groups) == {first, 2} + assert set(groups[first]) == {0, 1, 3, 4, 6, 7, 9} + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, before) + supervisor.save() + finally: + controller.close() + from phy.apps.template.gui import TemplateController + + reopened = TemplateController(dir_path=path, config_dir=config, plugins=[]) + try: + groups = reopened.parent_inspection.lineage.parents(target) + assert set(groups) == {first, 2} + assert dict(reopened.parent_inspection.lineage.colors(target)) == expected_colors + assert len(groups[first]) == 7 + assert reopened.parent_inspection.lineage.full_counts(target) == {first: 7, 2: 3} + provider = ParentProviders(reopened, target, groups) + result = provider.correlograms(list(groups), 0.001, 0.01) + assert result.shape[:2] == (2, 2) + assert not (path / '_phy_merge_parents.npz').exists() + finally: + reopened.close() + + +def test_bounded_predicate_split_merge_reload_and_read_only_window(qtbot, tmp_path): + _, controller = make_controller(tmp_path) + path = controller.dir_path + config = controller.config_dir + try: + supervisor = controller.supervisor + split = supervisor.split_source_amplitude(0, 4.5) + children = split.added + parents = [children[0], 1] + expected = {p: supervisor.clustering.spikes_per_cluster[p].copy() for p in parents} + target = supervisor.merge(parents).added[0] + supervisor.save() + finally: + controller.close() + from phy.apps.template.gui import TemplateController + + reopened = TemplateController(dir_path=path, config_dir=config, plugins=[]) + gui = reopened.create_gui(do_prompt_save=False) + try: + supervisor = reopened.supervisor + supervisor.select([target]) + supervisor.block() + session = reopened.bounded_session + assignments, events = session.assignments.copy(), deepcopy(session.events) + dirty = supervisor.is_dirty() + groups = reopened.parent_inspection.lineage.parents(target) + for parent in parents: + np.testing.assert_array_equal(groups[parent], expected[parent]) + assert reopened.parent_inspection.lineage.full_counts(target)[children[0]] is None + reopened.parent_inspection.show(target) + assert reopened.parent_inspection.window is not None + reopened.parent_inspection.close_review() + np.testing.assert_array_equal(session.assignments, assignments) + assert session.events == events + assert supervisor.is_dirty() == dirty + finally: + gui.close() + reopened.close() + + +def test_premerge_palette_slots_survive_save_reload_undo_and_redo(tmp_path): + # Sparse/high authoritative slots are meaningful: rendering wraps the palette, + # but display metadata must retain the exact slot, not silently renumber it. + controller = lineage_controller(tmp_path, [9, 15, 10, 13, 9, 15, 10, 13]) + expected = {9: 0, 15: 300, 10: 2, 13: 3} + controller.supervisor.selection_color_indices = expected + lineage = ParentLineage(controller) + try: + emit('before_merge', controller.supervisor, (9, 15, 10, 13)) + target = controller.supervisor.clustering.merge([9, 15, 10, 13]).added[0] + assert dict(lineage.colors(target)) == expected + assert list(lineage.parents(target)) == [9, 10, 13, 15] + controller.supervisor.clustering.undo() + controller.supervisor.clustering.redo() + assert dict(lineage.colors(target)) == expected + emit('curation_saved', controller.supervisor) + finally: + lineage.close() + reopened = ParentLineage(controller) + try: + assert dict(reopened.colors(target)) == expected + with pytest.raises(TypeError): + reopened.colors(target)[9] = 4 + finally: + reopened.close() + # Optional corrupt hints must not invalidate the exact scientific partition. + path = tmp_path / '_phy_merge_parents.npz' + with np.load(path, allow_pickle=False) as data: + arrays = dict(data) + arrays['color_indices'] = np.asarray('{"1":{"9":-1}}') + np.savez(path, **arrays) + fallback = ParentLineage(controller) + try: + assert set(fallback.parents(target)) == set(expected) + assert dict(fallback.colors(target)) == {9: 0, 10: 1, 13: 2, 15: 3} + finally: + fallback.close() + + +def test_color_observer_does_not_limit_large_merges(tmp_path): + from phy.utils.color import colormaps + + count = len(colormaps.default) + 1 + controller = lineage_controller(tmp_path, np.arange(count)) + lineage = ParentLineage(controller) + try: + emit('before_merge', controller.supervisor, tuple(range(count))) + target = controller.supervisor.clustering.merge(list(range(count))).added[0] + assert len(lineage.parents(target)) == count + assert target not in lineage.color_records + finally: + lineage.close() + + +def test_real_unsorted_merge_palette_and_exact_workspace_restoration(qtbot, tempdir, monkeypatch): + from phy.gui.qt import QAction, QApplication, QDockWidget, Qt + + controller = _mock_controller(tempdir, MyControllerFull) + gui = controller.create_gui(do_prompt_save=False) + gui.resize(1100, 800) + gui.show() + supervisor = controller.supervisor + inspection = controller.parent_inspection + try: + supervisor.select([9, 15, 10, 13]) + supervisor.block() + supervisor.toggle_merge_mode() + colors = dict(supervisor.selection_color_indices) + assert colors == {9: 0, 15: 1, 10: 2, 13: 3} + target = supervisor.merge().added[0] + supervisor.select([target]) + supervisor.block() + assert dict(inspection.lineage.colors(target)) == colors + supervisor.save() + # Preserve deliberate hidden/disabled states, including a custom action. + ordinary = gui.list_views(WaveformView)[0] + ordinary.dock.hide() + custom = QAction('Custom disabled action', gui) + custom.setEnabled(False) + gui.addAction(custom) + supervisor.cluster_view.table_view.setFocus() + qtbot.wait(20) + state = bytes(gui.saveState()) + gui.restoreState(gui.saveState()) # Normalize Qt's cached pre-show central size. + qtbot.wait(20) + state = bytes(gui.saveState()) + docks = { + d: not d.isHidden() for d in gui.findChildren(QDockWidget) if d.parentWidget() is gui + } + actions = {a: a.isEnabled() for a in gui.findChildren(QAction)} + original_focus = QApplication.focusWidget() + original_views = tuple(gui.views) + assignments = supervisor.clustering.spike_clusters.copy() + history = supervisor.clustering._undo_stack._index + saved = inspection.lineage.path.read_bytes() + inspection.show(target) + qtbot.wait(30) + assert len(inspection.views) == 4 + assert tuple(gui.views) == original_views + assert [inspection.parent_table.item(i, 1).text() for i in range(4)] == [ + '9', + '15', + '10', + '13', + ] + assert inspection.parent_table.isColumnHidden(3) + assert all(dict(v._cluster_color_index_by_id) == colors for v in inspection.views) + assert all( + not action.qaction.isEnabled() for action in supervisor.actions._actions_dict.values() + ) + # Attempts to re-enable actions (for example snippets.mode_off) remain blocked. + supervisor.actions.get('merge').setEnabled(True) + assert not supervisor.actions.get('merge').isEnabled() + for key, modifiers in ( + (Qt.Key_G, Qt.NoModifier), + (Qt.Key_K, Qt.NoModifier), + (Qt.Key_Z, Qt.ControlModifier), + (Qt.Key_S, Qt.ControlModifier), + ): + qtbot.keyClick(inspection.return_button, key, modifier=modifiers) + assert inspection.window is not None + assert supervisor.clustering._undo_stack._index == history + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, assignments) + assert inspection.lineage.path.read_bytes() == saved + # Esc returns without any generic GUI wait/save path. + with monkeypatch.context() as patcher: + patcher.setattr('phy.gui.gui._wait', lambda *a: pytest.fail('nested event pumping')) + qtbot.keyClick(inspection.return_button, Qt.Key_Escape) + assert inspection.window is None + assert bytes(gui.saveState()) == state + assert all(d.isHidden() != visible for d, visible in docks.items()) + assert all(a.isEnabled() == enabled for a, enabled in actions.items()) + assert QApplication.focusWidget() is original_focus + # A partial child-GUI constructor must not leak global event callbacks. + from phylib.utils.event import _EVENT + + callbacks = list(_EVENT._callbacks) + with monkeypatch.context() as patcher: + + def fail_table(*args): + raise RuntimeError('injected table construction failure') + + patcher.setattr('phy.apps._parent_workspace.QTableWidget', fail_table) + with pytest.raises(RuntimeError, match='injected table'): + inspection.show(target) + assert inspection.window is None + assert _EVENT._callbacks == callbacks + assert bytes(gui.saveState()) == state + # A provider failure after workspace construction must leave no hidden docks. + with monkeypatch.context() as patcher: + patcher.setattr( + ParentProviders, + 'waveform_ids', + lambda *a: (_ for _ in ()).throw(ValueError('injected provider failure')), + ) + with pytest.raises(ValueError, match='injected provider'): + inspection.show(target) + assert inspection.window is None + assert bytes(gui.saveState()) == state + assert all(a.isEnabled() == enabled for a, enabled in actions.items()) + # Roll back even if activation fails after hiding/adding real host docks. + from phy.apps._parent_workspace import ParentWorkspace + + activate = ParentWorkspace._activate + with monkeypatch.context() as patcher: + + def fail_after_activation(workspace): + activate(workspace) + raise RuntimeError('injected activation failure') + + patcher.setattr(ParentWorkspace, '_activate', fail_after_activation) + with pytest.raises(RuntimeError, match='injected activation'): + inspection.show(target) + assert inspection.window is None + assert bytes(gui.saveState()) == state + assert all(a.isEnabled() == enabled for a, enabled in actions.items()) + # Main-close geometry is saved only after the temporary workspace is gone. + inspection.show(target) + seen = [] + original_save = gui.save_geometry_state + + def save_original_layout(): + seen.append((inspection.window, bytes(gui.saveState()))) + original_save() + + monkeypatch.setattr(gui, 'save_geometry_state', save_original_layout) + gui.close() + assert seen == [(None, state)] + finally: + inspection.close_review() + gui.close() + controller.close() + + +@pytest.mark.parametrize('count', [7, 16]) +def test_parent_table_keeps_all_rows_readable_and_scrollable(qtbot, tempdir, count): + controller = _mock_controller(tempdir, MyControllerFull) + gui = controller.create_gui(do_prompt_save=False) + gui.resize(1100, 800) + gui.show() + try: + supervisor = controller.supervisor + target = supervisor.merge(list(range(count))).added[0] + supervisor.select([target]) + supervisor.block() + inspection = controller.parent_inspection + inspection.show(target) + qtbot.wait(30) + table = inspection.parent_table + assert table.rowCount() == count + assert inspection.window._toolbar.height() < 100 + assert table.width() <= 280 + for row in range(count): + item = table.item(row, 1) + table.scrollToItem(item) + qtbot.wait(1) + assert table.visualItemRect(item).intersects(table.viewport().rect()) + assert table.rowHeight(row) >= table.fontMetrics().height() + assert item.text() == str(row) + assert all(v.dock.width() >= 200 and v.dock.height() >= 150 for v in inspection.views) + finally: + controller.parent_inspection.close_review() + gui.close() + controller.close() + + +def test_bounded_parent_colors_use_default_config_and_survive_reopen(tmp_path, monkeypatch): + from pathlib import Path + + from phy.apps.template.gui import TemplateController + + _, prepared = make_controller(tmp_path) + path = prepared.dir_path + prepared.close() + monkeypatch.setattr(Path, 'home', classmethod(lambda cls: tmp_path)) + controller = TemplateController(dir_path=path, plugins=[]) + try: + assert controller.config_dir is None + target = controller.supervisor.merge([2, 0]).added[0] + lineage = controller.parent_inspection.lineage + expected = dict(lineage.colors(target)) + hint = lineage._bounded_color_path() + assert hint.parent == tmp_path / '.phy' + controller.supervisor.save() + assert hint.is_file() + finally: + controller.close() + reopened = TemplateController(dir_path=path, plugins=[]) + try: + np.testing.assert_array_equal( + reopened.supervisor.clustering.spike_clusters, + reopened.bounded_session.assignments, + ) + assert set(reopened.parent_inspection.lineage.parents(target)) == {2, 0} + assert dict(reopened.parent_inspection.lineage.colors(target)) == expected + assert not reopened.supervisor.is_dirty() + finally: + reopened.close() + + +def test_bounded_color_hints_are_disposable_and_save_errors_are_isolated( + qtbot, tmp_path, monkeypatch +): + import json + + from phy.apps.template.gui import TemplateController + + _, controller = make_controller(tmp_path) + path, config = controller.dir_path, controller.config_dir + try: + supervisor = controller.supervisor + first = supervisor.merge([0, 1]).added[0] + target = supervisor.merge([first, 2]).added[0] + lineage = controller.parent_inspection.lineage + expected = {first: 0, 2: 1} + assert dict(lineage.colors(target)) == expected + supervisor.save() + hint = lineage._bounded_color_path() + assert hint.is_file() and hint.parent == config + value = json.loads(hint.read_text()) + # Refuse valid colors attached to a different saved semantic history. + value['binding'] = 'stale' + hint.write_text(json.dumps(value)) + finally: + controller.close() + reopened = TemplateController(dir_path=path, config_dir=config, plugins=[]) + try: + lineage = reopened.parent_inspection.lineage + assert set(lineage.parents(target)) == {first, 2} + assert dict(lineage.colors(target)) == {2: 0, first: 1} + # A committed scientific save must succeed even if this optional cache cannot. + original_replace = __import__('os').replace + + def fail_optional(source, destination): + if destination == lineage._bounded_color_path(): + raise OSError('injected optional cache write error') + return original_replace(source, destination) + + with monkeypatch.context() as patcher: + patcher.setattr('phy.apps._parent_review.os.replace', fail_optional) + reopened.supervisor.save() + assert reopened.bounded_session.checkpoint_path.is_dir() + assert set(lineage.parents(target)) == {first, 2} + hint.write_text('{broken optional cache') + finally: + reopened.close() + final = TemplateController(dir_path=path, config_dir=config, plugins=[]) + try: + assert set(final.parent_inspection.lineage.parents(target)) == {first, 2} + assert dict(final.parent_inspection.lineage.colors(target)) == {2: 0, first: 1} + finally: + final.close() + + +def test_parent_review_can_reopen_after_canceled_dirty_main_close(qtbot, tempdir, monkeypatch): + from phy.gui.qt import Qt + + controller = _mock_controller(tempdir, MyControllerFull) + gui = controller.create_gui() + gui.resize(1100, 800) + gui.show() + inspection = controller.parent_inspection + supervisor = controller.supervisor + try: + target = supervisor.merge([0, 1]).added[0] + supervisor.select([target]) + supervisor.block() + assert supervisor.is_dirty() + assignments = supervisor.clustering.spike_clusters.copy() + history = supervisor.clustering._undo_stack._index + metadata = supervisor.get_labels('group').copy() + inspection.show(target) + qtbot.wait(20) + review_window = inspection.window + with monkeypatch.context() as patcher: + patcher.setattr('phy.apps.base._prompt_save', lambda: 'cancel') + assert not gui.close() + assert gui.isVisible() and not gui._closed + assert inspection.window is review_window + assert inspection._gui is gui + inspection.close_review() + inspection.show_selected() + qtbot.wait(20) + assert inspection.host_gui is gui + assert inspection.return_button.isVisible() + qtbot.mouseClick(inspection.return_button, Qt.LeftButton) + assert inspection.window is None + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, assignments) + assert supervisor.clustering._undo_stack._index == history + assert supervisor.get_labels('group') == metadata + assert supervisor.is_dirty() + finally: + inspection.close_review() + with monkeypatch.context() as patcher: + patcher.setattr('phy.apps.base._prompt_save', lambda: 'close') + gui.close() + controller.close() diff --git a/phy/cluster/_proposition_annotations.py b/phy/cluster/_proposition_annotations.py new file mode 100644 index 000000000..f29645986 --- /dev/null +++ b/phy/cluster/_proposition_annotations.py @@ -0,0 +1,102 @@ +"""Small, immutable pending-proposition annotations for displayed unit IDs. + +These colors describe source proposition membership, independently of scientific +trace colors, selection order, and ancestry aliases. No spike arrays are read. +""" + +from collections.abc import Mapping +from colorsys import hsv_to_rgb +from dataclasses import dataclass +from types import MappingProxyType + +WHITE = (1.0, 1.0, 1.0, 1.0) + + +def proposition_label_color(slot): + """Return a separate comparison palette whose first two colors are blue/red.""" + if slot == 0: + return (0.3, 0.65, 1.0, 1.0) + if slot == 1: + return (1.0, 0.4, 0.4, 1.0) + return (*hsv_to_rgb(((slot - 2) * 0.61803398875 + 0.12) % 1, 0.55, 1.0), 1.0) + + +@dataclass(frozen=True) +class PropositionLabelGroup: + key: str + display_id: str + color: tuple[float, float, float, float] + active: bool + + +@dataclass(frozen=True) +class PropositionLabelAnnotation: + unit_id: int + groups: tuple[PropositionLabelGroup, ...] + + @property + def text(self): + # One ASCII marker fits the existing font atlas and flags all overlaps. + return f'{self.unit_id}{"*" if len(self.groups) > 1 else ""}' + + @property + def color(self): + return self.groups[0].color if self.groups else WHITE + + +@dataclass(frozen=True) +class PropositionLabelProjection: + annotations: Mapping[int, PropositionLabelAnnotation] + groups: tuple[PropositionLabelGroup, ...] + color_keys: tuple[str, ...] + + +def project_proposition_labels(catalog, unit_ids, active_keys=(), color_keys=()): + """Project exact live pending memberships in O(source memberships + labels). + + ``color_keys`` reserves slots for temporarily undisplayed groups in the same + workspace. The caller resets it when the active proposition selection changes. + Active groups take priority on overlapping labels; every membership remains + explicit in ``groups`` and the overlap marker. Catalog order breaks ties, + independently of filtered/sorted tables and scientific palette slots. + """ + unit_ids = tuple(map(int, unit_ids)) + wanted = set(unit_ids) + memberships = {unit: [] for unit in unit_ids} + pending, intersecting = {}, set() + if catalog is not None: + for entry in catalog.pending_entries(): + pending[entry.key] = entry + for unit in entry.proposition.unit_ids: + if unit in wanted: + intersecting.add(entry.key) + active_keys = tuple(key for key in active_keys if key in pending) + active = set(active_keys) + ordered = tuple( + dict.fromkeys( + ( + *active_keys, + *color_keys, + *(key for key in pending if key in intersecting), + ) + ) + ) + groups = { + key: PropositionLabelGroup( + key, f'P{pending[key].index + 1}', proposition_label_color(slot), key in active + ) + for slot, key in enumerate(ordered) + if key in pending + } + for key, group in groups.items(): + for unit in pending[key].proposition.unit_ids: + if unit in wanted: + memberships[unit].append(group) + annotations = { + unit: PropositionLabelAnnotation(unit, tuple(memberships[unit])) for unit in unit_ids + } + return PropositionLabelProjection( + MappingProxyType(annotations), + tuple(groups[key] for key in ordered if key in intersecting), + ordered, + ) diff --git a/phy/cluster/_proposition_view.py b/phy/cluster/_proposition_view.py index 54356b542..ccc737eaa 100644 --- a/phy/cluster/_proposition_view.py +++ b/phy/cluster/_proposition_view.py @@ -11,7 +11,7 @@ from phylib.utils import emit -from phy.gui.qt import QAbstractItemView, QColor +from phy.gui.qt import QAbstractItemView, QApplication, QColor, Qt from phy.gui.widgets import Table @@ -58,7 +58,8 @@ def __init__(self, *args, data=None, **kwargs): self._key_by_id = {} self._id_by_key = {} self._current_key = None - self.table_view.setSelectionMode(QAbstractItemView.SingleSelection) + self._selected_keys = () + self.table_view.setSelectionMode(QAbstractItemView.ExtendedSelection) self.set_propositions(data or ()) @property @@ -66,6 +67,25 @@ def current_key(self): """The locally highlighted proposition key, if any.""" return self._current_key + @property + def selected_keys(self): + """Stable proposition keys in selection order.""" + return self._selected_keys + + def select_keys(self, keys): + """Project a multi-selection without emitting cluster selection events.""" + keys = tuple(dict.fromkeys(keys)) + if any(key not in self._id_by_key for key in keys): + return False + self._selected_keys = keys + self._current_key = keys[0] if keys else None + self.set_selected_ids([self._id_by_key[key] for key in keys]) + if keys: + self._set_dock_status(keys[0]) + elif getattr(self, 'dock', None) is not None: + self.dock.set_status('No merge suggestions selected') + return True + @staticmethod def _as_ordered_ids(value): if value is None: @@ -142,7 +162,7 @@ def _normalize_row(self, row, index): def set_propositions(self, rows: Iterable[Mapping]): """Replace the projection while retaining a still-present highlight.""" - previous_key = self._current_key + previous_keys = self._selected_keys normalized = [self._normalize_row(row, index) for index, row in enumerate(rows)] keys = [row['key'] for row in normalized] if len(set(keys)) != len(keys): @@ -150,10 +170,7 @@ def set_propositions(self, rows: Iterable[Mapping]): self._key_by_id = {row['id']: row['key'] for row in normalized} self._id_by_key = {key: row_id for row_id, key in self._key_by_id.items()} self.remove_all_and_add(normalized, fit_columns=not self._column_widths_fitted) - self._current_key = previous_key if previous_key in self._id_by_key else None - if self._current_key is not None: - self.set_selected_ids([self._id_by_key[self._current_key]]) - self._set_dock_status(self._current_key) + self.select_keys(key for key in previous_keys if key in self._id_by_key) def visible_keys(self): """Return stable keys in the table's current visible sorted order.""" @@ -176,6 +193,8 @@ def can_trigger(self, action): """Whether the legacy programmatic action is valid for the current row.""" if action not in self._action_events: raise ValueError(f'Unknown merge proposition action: {action}.') + if len(self._selected_keys) != 1: + return False row_id = self._id_by_key.get(self._current_key) row = self._model.row_by_id(row_id) if row_id is not None else None return bool(row and row.get(f'_can_{action}')) @@ -190,29 +209,28 @@ def trigger(self, action): return True def select_key(self, key): - """Highlight ``key`` locally, without emitting an activation event.""" - row_id = self._id_by_key.get(key) - if row_id is None: - return False - self._current_key = key - self.set_selected_ids([row_id]) - self.scroll_to(row_id) - self._set_dock_status(key) - return True + """Highlight one key locally, without emitting an activation event.""" + return self.select_keys((key,)) def set_active_key(self, key, previous_key=None): """Mark one row active without resetting the table model or its layout.""" - if key not in self._id_by_key: + return self.set_active_keys((key,)) + + def set_active_keys(self, keys): + """Mark the complete review selection active without resetting the model.""" + keys = tuple(keys) + if any(key not in self._id_by_key for key in keys): return False + active = set(keys) patches = [] - previous_id = self._id_by_key.get(previous_key or self._current_key) - if previous_id is not None: - previous = self._model.row_by_id(previous_id) - patches.append({'id': previous_id, 'status': previous['_catalog_status']}) - row_id = self._id_by_key[key] - patches.append({'id': row_id, 'status': 'active'}) - self.change(patches) - return self.select_key(key) + for key, row_id in self._id_by_key.items(): + row = self._model.row_by_id(row_id) + status = 'active' if key in active else row['_catalog_status'] + if status != row['status']: + patches.append({'id': row_id, 'status': status}) + if patches: + self.change(patches) + return self.select_keys(keys) def _select_actionable(self, direction): keys = self.actionable_keys() @@ -241,8 +259,18 @@ def _on_row_clicked(self, index): if not 0 <= index.row() < len(visible_ids): return key = self._key_by_id[visible_ids[index.row()]] - self.select_key(key) - emit('activate_merge_proposition', self, key) + modifiers = QApplication.keyboardModifiers() + if modifiers & (Qt.ControlModifier | Qt.MetaModifier): + keys = list(self._selected_keys) + if key in keys: + keys.remove(key) + else: + keys.append(key) + self.select_keys(keys) + emit('activate_merge_propositions', self, tuple(keys)) + else: + self.select_key(key) + emit('activate_merge_proposition', self, key) def _set_dock_status(self, key): """Expose hidden metadata through the dock status line when available.""" @@ -256,6 +284,8 @@ def _set_dock_status(self, key): detail = f'{detail} · reference {row["reference"]}' if row['reason']: detail = f'{detail} · {row["reason"]}' + if len(self._selected_keys) > 1: + detail = f'{len(self._selected_keys)} suggestions selected · {detail}' dock.set_status(detail) def _foreground_color(self, row, column): diff --git a/phy/cluster/_propositions.py b/phy/cluster/_propositions.py index dfd1710a9..c5a1b9564 100644 --- a/phy/cluster/_propositions.py +++ b/phy/cluster/_propositions.py @@ -70,6 +70,7 @@ class PropositionStatus(Enum): PENDING = 'pending' ACCEPTED = 'accepted' ACCEPTED_MODIFIED = 'accepted_modified' + ACCEPTED_RESTORED = 'accepted_restored' REJECTED = 'rejected' INVALID = 'invalid' STALE = 'stale' @@ -182,6 +183,8 @@ class MergePropositionCatalog: reviews: Mapping[str, PropositionReview] = field(default_factory=dict) live_unit_ids: tuple[int, ...] | None = None source_mapping: Mapping = field(default_factory=dict) + retired_units: Mapping = field(default_factory=dict) + reassembled_results: Mapping = field(default_factory=dict) def __post_init__(self): source_ids = _ids(self.source_unit_ids, minimum=0) @@ -208,6 +211,48 @@ def __post_init__(self): object.__setattr__(self, 'reviews', MappingProxyType(reviews)) object.__setattr__(self, 'live_unit_ids', live_ids) object.__setattr__(self, 'source_mapping', source_mapping) + retired = {} + for key, value in _mapping(self.retired_units, name='retired_units').items(): + if not isinstance(key, str) or not key.isdecimal() or str(int(key)) != key: + raise ValueError( + 'retired_units keys must be canonical non-negative integer strings.' + ) + value = _mapping(value, name='retired unit') + operation = value.get('operation') + if operation not in {'merge', 'threshold_split', 'restore_parents'}: + raise ValueError('Unknown retired-unit operation.') + replacements = _ids(value.get('replacements'), name='replacements', minimum=1) + if operation == 'restore_parents' and len(replacements) < 2: + raise ValueError('A restored merge must retain every immediate parent.') + if any(unit < 0 for unit in replacements) or int(key) in replacements: + raise ValueError( + 'Retired-unit replacements must be distinct non-negative new IDs.' + ) + retired[key] = {'operation': operation, 'replacements': replacements} + object.__setattr__(self, 'retired_units', _freeze(retired)) + reassembled = {} + for key, value in _mapping(self.reassembled_results, name='reassembled_results').items(): + if key not in keys or key not in reviews: + raise ValueError('Reassembled results require a known accepted review.') + if reviews[key].decision is not ReviewDecision.ACCEPTED: + raise ValueError('Reassembled results require a known accepted review.') + value = _mapping(value, name='reassembled result') + if set(value) != {'result_unit_id', 'modified'}: + raise ValueError('Reassembled results require result_unit_id and modified.') + result = value['result_unit_id'] + if ( + not isinstance(result, Integral) + or isinstance(result, bool) + or result not in live_ids + ): + raise ValueError('A reassembled result must identify a current live unit.') + if type(value['modified']) is not bool: + raise ValueError('A reassembled result modified flag must be boolean.') + reassembled[key] = { + 'result_unit_id': int(result), + 'modified': value['modified'], + } + object.__setattr__(self, 'reassembled_results', _freeze(reassembled)) @property def propositions(self): @@ -227,24 +272,65 @@ def status_for(self, key): entry = self.entry_for(key) if entry is None: raise KeyError(key) + return self._status_for_entry(entry) + + def pending_entries(self): + """Iterate current pending entries without repeated catalog or live-ID scans.""" + source_ids, live_ids = set(self.source_unit_ids), set(self.live_unit_ids) + for entry in self.entries: + if entry.key is not None and entry.key not in self.reviews: + if ( + self._status_for_entry(entry, source_ids, live_ids) + is PropositionStatus.PENDING + ): + yield entry + + def _status_for_entry(self, entry, source_ids=None, live_ids=None): + key = entry.key if entry.invalid_reason is not None: return PropositionStatus.INVALID proposition = entry.proposition - if not set(proposition.unit_ids) <= set(self.source_unit_ids): + source_ids = set(self.source_unit_ids) if source_ids is None else source_ids + if not set(proposition.unit_ids) <= source_ids: return PropositionStatus.INVALID review = self.reviews.get(key) if review is not None: if review.decision is ReviewDecision.REJECTED: return PropositionStatus.REJECTED + if self._result_was_restored(review.result_unit_id): + reassembled = self.reassembled_results.get(key) + if reassembled is None: + return PropositionStatus.ACCEPTED_RESTORED + return ( + PropositionStatus.ACCEPTED_MODIFIED + if reassembled['modified'] or review.applied_unit_ids != proposition.unit_ids + else PropositionStatus.ACCEPTED + ) return ( PropositionStatus.ACCEPTED if review.applied_unit_ids == proposition.unit_ids else PropositionStatus.ACCEPTED_MODIFIED ) - if not set(proposition.unit_ids) <= set(self.live_unit_ids): + live_ids = set(self.live_unit_ids) if live_ids is None else live_ids + if not set(proposition.unit_ids) <= live_ids: return PropositionStatus.STALE return PropositionStatus.PENDING + def _result_was_restored(self, result_unit_id): + pending, visited = [result_unit_id], set() + while pending: + unit = pending.pop() + if unit in visited: + continue + visited.add(unit) + retirement = self.retired_units.get(str(unit)) + if retirement is None: + continue + if retirement['operation'] == 'restore_parents': + return True + pending.extend(retirement['replacements']) + return False + def reason_for(self, key): entry = self.entry_for(key) if entry is None: @@ -253,17 +339,50 @@ def reason_for(self, key): return entry.invalid_reason if self.status_for(key) is PropositionStatus.INVALID: return 'One or more unit_ids are absent from curation.json unit_ids.' + if self.status_for(key) is PropositionStatus.ACCEPTED_RESTORED: + review = self.reviews[key] + return ( + f'Historically accepted into {review.result_unit_id}; that result was ' + 'subsequently restored to its parents. The acceptance is no longer live.' + ) if self.status_for(key) is PropositionStatus.STALE: missing = tuple( unit_id for unit_id in entry.proposition.unit_ids if unit_id not in self.live_unit_ids ) + causes = [] + for unit_id in missing: + retirement = self.retired_units.get(str(unit_id)) + if retirement is not None: + verb = { + 'merge': 'merged', + 'threshold_split': 'split', + 'restore_parents': 'restored to its parents', + }[retirement['operation']] + causes.append(f'{unit_id} was {verb}') + if causes: + return f'Source clusters no longer exist: {missing}; ' + '; '.join(causes) + '.' return f'One or more source clusters no longer exist: {missing}.' return None - def project_live_ids(self, live_unit_ids): - return self._replace(live_unit_ids=_ids(live_unit_ids, name='live_unit_ids')) + def project_live_ids(self, live_unit_ids, *, retired_units=None, reassembled_results=None): + """Project current state without changing historical curator decisions. + + The caller supplies reassembly only after proving that a live unit + contains the complete historical accepted membership. ``modified`` + indicates additional membership, not merely different numeric IDs. + Missing or partial membership must have no entry. This derived mapping + is replaced on every projection so a later split cannot retain stale + acceptance, and is never written to the source or review documents. + """ + changes = { + 'live_unit_ids': _ids(live_unit_ids, name='live_unit_ids'), + 'reassembled_results': ({} if reassembled_results is None else reassembled_results), + } + if retired_units is not None: + changes['retired_units'] = retired_units + return self._replace(**changes) def snapshot(self): """Return an immutable snapshot suitable for history entries.""" @@ -292,7 +411,9 @@ def reset(self, key): raise ValueError('Cannot reset a review whose source clusters no longer exist.') reviews = dict(self.reviews) reviews.pop(key, None) - return self._replace(reviews=reviews) + reassembled = dict(self.reassembled_results) + reassembled.pop(key, None) + return self._replace(reviews=reviews, reassembled_results=reassembled) def review_mapping(self, *, source_filename='curation.json', source_sha256=None): source = {'filename': source_filename} @@ -306,7 +427,11 @@ def review_mapping(self, *, source_filename='curation.json', source_sha256=None) def _require_reviewable(self, key): status = self.status_for(key) - if status in {PropositionStatus.INVALID, PropositionStatus.STALE}: + if status in { + PropositionStatus.INVALID, + PropositionStatus.STALE, + PropositionStatus.ACCEPTED_RESTORED, + }: raise ValueError(f'Cannot review a {status.value} merge proposition.') def _with_review(self, key, review): @@ -314,7 +439,9 @@ def _with_review(self, key, review): raise KeyError(key) reviews = dict(self.reviews) reviews[key] = review - return self._replace(reviews=reviews) + reassembled = dict(self.reassembled_results) + reassembled.pop(key, None) + return self._replace(reviews=reviews, reassembled_results=reassembled) def _replace(self, **changes): values = { @@ -323,6 +450,8 @@ def _replace(self, **changes): 'reviews': self.reviews, 'live_unit_ids': self.live_unit_ids, 'source_mapping': self.source_mapping, + 'retired_units': self.retired_units, + 'reassembled_results': self.reassembled_results, } values.update(changes) return type(self)(**values) @@ -355,8 +484,12 @@ def restore(self, snapshot): self._catalog = self._require_catalog(snapshot) return None - def project_live_ids(self, live_unit_ids): - self._catalog = self._catalog.project_live_ids(tuple(map(int, live_unit_ids))) + def project_live_ids(self, live_unit_ids, *, retired_units=None, reassembled_results=None): + self._catalog = self._catalog.project_live_ids( + tuple(map(int, live_unit_ids)), + retired_units=retired_units, + reassembled_results=reassembled_results, + ) return None def reject(self, key): @@ -369,6 +502,13 @@ def prepare_accept(self, key, applied_unit_ids, result_unit_id): """Validate an acceptance without mutating review history.""" return self._catalog.accept(key, applied_unit_ids, result_unit_id) + def prepare_accept_many(self, keys, applied_unit_ids, result_unit_id): + """Validate all selected reviews before changing spike assignments.""" + catalog = self._catalog + for key in keys: + catalog = catalog.accept(key, applied_unit_ids, result_unit_id) + return catalog + def commit_prepared(self, before, after): """Commit a previously validated acceptance against the same catalog.""" before = self._require_catalog(before) @@ -422,7 +562,7 @@ def _review_fingerprint(catalog): ) -def decode_curation_mapping(mapping) -> MergePropositionCatalog: +def decode_curation_mapping(mapping, *, retired_units=None) -> MergePropositionCatalog: """Decode a supported AIND/SpikeInterface v2 curation document. Invalid individual ``merges`` entries become visible invalid catalog entries; @@ -453,7 +593,12 @@ def decode_curation_mapping(mapping) -> MergePropositionCatalog: entries.append(PropositionEntry(index, proposition=proposition, raw_mapping=raw)) except (TypeError, ValueError) as e: entries.append(PropositionEntry(index, invalid_reason=str(e), raw_mapping=raw)) - return MergePropositionCatalog(source_ids, tuple(entries), source_mapping=mapping) + return MergePropositionCatalog( + source_ids, + tuple(entries), + source_mapping=mapping, + retired_units={} if retired_units is None else retired_units, + ) def encode_curation_mapping(catalog: MergePropositionCatalog): diff --git a/phy/cluster/_selection.py b/phy/cluster/_selection.py index 9bae266a0..966a463a8 100644 --- a/phy/cluster/_selection.py +++ b/phy/cluster/_selection.py @@ -54,6 +54,7 @@ class MergeSession: ordered_ids: tuple[int, ...] entry_snapshot: NormalWorkflowSnapshot proposition_id: str | None = None + proposition_ids: tuple[str, ...] = () def __post_init__(self): ordered = _as_unique_ids(self.ordered_ids) @@ -62,6 +63,14 @@ def __post_init__(self): raise ValueError('The merge reference must belong to the staged clusters.') if self.proposition_id is not None and not self.proposition_id: raise ValueError('The merge proposition ID cannot be empty.') + keys = tuple(self.proposition_ids) or ( + (self.proposition_id,) if self.proposition_id else () + ) + if any(not isinstance(key, str) or not key for key in keys) or len(set(keys)) != len(keys): + raise ValueError('Merge proposition IDs must be distinct nonempty strings.') + if keys and self.proposition_id != keys[0]: + raise ValueError('The active proposition must be the first selected proposition.') + object.__setattr__(self, 'proposition_ids', keys) object.__setattr__(self, 'reference_id', reference) object.__setattr__(self, 'ordered_ids', ordered) @@ -349,6 +358,40 @@ def set_presentation_order(self, presentation_order): ) ) + def enter_parent_restore(self, ordered_ids, color_indices=None, workflow_context=None): + """Stage real restored units; leaving Merge keeps these units selected.""" + self._require_normal_mode() + ordered = _as_unique_ids(ordered_ids) + if len(ordered) < 2: + raise ValueError('Parent restoration requires at least two units.') + colors = dict(color_indices or {}) + used = {0} + bindings = {ordered[0]: 0} + for unit in ordered[1:]: + slot = colors.get(unit) + if ( + not isinstance(slot, Integral) + or not 0 <= slot < max(32, 2 * len(ordered)) + or slot in used + ): + slot = next(i for i in range(len(ordered) + len(used)) if i not in used) + bindings[unit] = int(slot) + used.add(int(slot)) + slots = [None] * (max(used) + 1) + for unit, slot in bindings.items(): + slots[slot] = unit + normal = CurationSelectionState(cluster_ids=ordered, color_slots=tuple(slots)) + merge = MergeSession(ordered[0], ordered, NormalWorkflowSnapshot(normal, workflow_context)) + return self._apply( + CurationSelectionState( + mode=WorkflowMode.MERGE, + reference_id=ordered[0], + presentation_order=ordered, + color_slots=tuple(slots), + merge=merge, + ) + ) + def enter_merge_mode(self, workflow_context=None): self._require_normal_mode() current = self._state @@ -369,7 +412,9 @@ def enter_merge_mode(self, workflow_context=None): ) ) - def enter_merge_proposition(self, proposition_id, ordered_ids, workflow_context=None): + def enter_merge_proposition( + self, proposition_id, ordered_ids, workflow_context=None, *, proposition_ids=() + ): """Stage an external merge proposition without changing its entry snapshot.""" self._require_normal_mode() ordered = _as_unique_ids(ordered_ids) @@ -383,6 +428,7 @@ def enter_merge_proposition(self, proposition_id, ordered_ids, workflow_context= ordered, NormalWorkflowSnapshot(current, workflow_context), proposition_id=str(proposition_id), + proposition_ids=tuple(proposition_ids), ) return self._apply( CurationSelectionState( @@ -394,7 +440,7 @@ def enter_merge_proposition(self, proposition_id, ordered_ids, workflow_context= ) ) - def switch_merge_proposition(self, proposition_id, ordered_ids): + def switch_merge_proposition(self, proposition_id, ordered_ids, *, proposition_ids=()): """Replace the active Merge workspace while preserving its Normal entry snapshot.""" self._require_merge_mode() ordered = _as_unique_ids(ordered_ids) @@ -407,6 +453,7 @@ def switch_merge_proposition(self, proposition_id, ordered_ids): ordered, self._state.merge.entry_snapshot, proposition_id=str(proposition_id), + proposition_ids=tuple(proposition_ids), ) return self._apply( CurationSelectionState( @@ -439,6 +486,7 @@ def add_to_merge(self, cluster_ids, insertion=None): tuple(ids), current.merge.entry_snapshot, proposition_id=current.merge.proposition_id, + proposition_ids=current.merge.proposition_ids, ) similar = tuple(cluster_id for cluster_id in current.similar_ids if cluster_id not in new) effective = _ordered_union(merge.ordered_ids, similar) @@ -467,6 +515,7 @@ def remove_from_merge(self, cluster_ids): merge_ids, current.merge.entry_snapshot, proposition_id=current.merge.proposition_id, + proposition_ids=current.merge.proposition_ids, ) similar = _ordered_union(current.similar_ids, removed) effective = _ordered_union(merge.ordered_ids, similar) @@ -550,6 +599,7 @@ def deselect_from_merge(self, cluster_ids): merge_ids, current.merge.entry_snapshot, proposition_id=current.merge.proposition_id, + proposition_ids=current.merge.proposition_ids, ) slots = self._promote_reference_slot(reference) return self._apply( @@ -577,6 +627,7 @@ def reorder_merge(self, cluster_ids, insertion): tuple(remain), current.merge.entry_snapshot, proposition_id=current.merge.proposition_id, + proposition_ids=current.merge.proposition_ids, ) return self._apply( CurationSelectionState( diff --git a/phy/cluster/clustering.py b/phy/cluster/clustering.py index 662ca7439..0774d7732 100644 --- a/phy/cluster/clustering.py +++ b/phy/cluster/clustering.py @@ -7,7 +7,8 @@ import logging import numpy as np -from phylib.io.array import _spikes_in_clusters, _spikes_per_cluster, _unique +from phylib.io.array import _spikes_in_clusters, _spikes_per_cluster +from phylib.io.array import _unique as _unique_dense from phylib.utils._types import _as_array, _is_array_like from phylib.utils.event import emit @@ -22,6 +23,23 @@ # ------------------------------------------------------------------------------ +def _unique(values): + """Preserve dense-ID performance without allocating by sparse absolute IDs.""" + if values is None or len(values) == 0: + return np.array([], dtype=np.int64) + values = np.asarray(values) + if int(values.max()) > max(1024, 4 * len(values)): + return np.unique(values[values >= 0]).astype(np.int64) + return _unique_dense(values) + + +def _largest_cluster(values): + if int(values.max()) > max(1024, 4 * len(values)): + ids, counts = np.unique(values, return_counts=True) + return int(ids[counts.argmax()]) + return int(np.bincount(values).argmax()) + + def _extend_spikes(spike_ids, spike_clusters): """Return all spikes belonging to the clusters containing the specified spikes.""" @@ -81,7 +99,7 @@ def _extend_assignment(spike_ids, old_spike_clusters, spike_clusters_rel, new_cl def _assign_update_info(spike_ids, old_spike_clusters, new_spike_clusters): old_clusters = _unique(old_spike_clusters) new_clusters = _unique(new_spike_clusters) - largest_old_cluster = np.bincount(old_spike_clusters).argmax() + largest_old_cluster = _largest_cluster(old_spike_clusters) descendants = list(set(zip(old_spike_clusters, new_spike_clusters))) update_info = UpdateInfo( description='assign', @@ -142,6 +160,7 @@ class Clustering: def __init__(self, spike_clusters, new_cluster_id=None, spikes_per_cluster=None): super().__init__() self._undo_stack = History(base_item=(None, None, None)) + self._restored_partitions = {} # Spike -> cluster mapping. self._spike_clusters = _as_array(spike_clusters) self._spikes_per_cluster = {} @@ -177,6 +196,20 @@ def spikes_per_cluster(self): """A dictionary {cluster_id: spike_ids}.""" return self._spikes_per_cluster + def membership_snapshot(self, cluster_ids): + """Read-only views of current per-unit original row IDs. + + Supported clustering operations replace these arrays, including undo; + retained snapshots therefore remain valid after subsequent edits. + """ + result = {} + for cluster_id in cluster_ids: + if cluster_id in self._spikes_per_cluster: + rows = self._spikes_per_cluster[cluster_id].view() + rows.flags.writeable = False + result[cluster_id] = rows + return result + @property def cluster_ids(self): """Ordered list of ids of all non-empty clusters.""" @@ -293,9 +326,14 @@ def _do_assign(self, spike_ids, new_spike_clusters): def _do_merge(self, spike_ids, cluster_ids, to): # Create the UpdateInfo instance here. descendants = [(cluster, to) for cluster in cluster_ids] - largest_old_cluster = np.bincount(self.spike_clusters[spike_ids]).argmax() + largest_old_cluster = max( + cluster_ids, key=lambda cluster: (len(self._spikes_per_cluster[cluster]), -cluster) + ) up = UpdateInfo( description='merge', + # Retain the exact pre-merge partition. Arrays are immutable by + # convention and removed from the live mapping below, not edited. + parent_spike_ids={int(c): self._spikes_per_cluster[c] for c in cluster_ids}, spike_ids=list(spike_ids), added=[to], deleted=list(cluster_ids), @@ -370,6 +408,77 @@ def merge(self, cluster_ids, to=None): emit('cluster', self, up) return up + def restore_partition(self, target, groups, *, new_cluster_ids=None): + """Restore an exact whole-unit partition into fresh, undoable clusters. + + ``groups`` maps historical parent IDs to sorted spike rows. Historical + IDs identify provenance only; they are never revived as live IDs. + Validation and assignment touch only this unit's rows. + """ + target = int(target) + if target not in self._spikes_per_cluster: + raise ValueError('Choose a current merged unit.') + if len(groups) < 2: + raise ValueError('Restoration requires at least two recorded parents.') + if any( + isinstance(parent, (bool, np.bool_)) + or not isinstance(parent, (int, np.integer)) + or parent < 0 + for parent in groups + ): + raise ValueError('Recorded parent IDs must be nonnegative integers.') + parents = tuple(map(int, groups)) + arrays = [] + for ids in groups.values(): + ids = np.asarray(ids) + if ( + ids.ndim != 1 + or ids.dtype.kind not in 'iu' + or not len(ids) + or ids[0] < 0 + or ids[-1] >= self._n_spikes + or np.any(ids[1:] <= ids[:-1]) + ): + raise ValueError('Every restored parent needs nonempty sorted exact spike rows.') + arrays.append(ids) + rows = np.concatenate(arrays) + order = np.argsort(rows) + rows = rows[order] + if not np.array_equal(rows, self._spikes_per_cluster[target]): + raise ValueError('Recorded parents do not exactly partition this unit.') + if new_cluster_ids is None: + children = tuple(range(self.new_cluster_id(), self.new_cluster_id() + len(parents))) + else: + children = tuple(new_cluster_ids) + if ( + len(children) != len(parents) + or any( + isinstance(c, (bool, np.bool_)) or not isinstance(c, (int, np.integer)) + for c in children + ) + or len(set(children)) != len(children) + or min(children) < self.new_cluster_id() + or max(children) > np.iinfo(np.int32).max + ): + raise ValueError( + 'Restored clusters require distinct fresh IDs in the loader namespace.' + ) + children = tuple(map(int, children)) + labels = np.concatenate( + [np.full(len(ids), child, dtype=np.int64) for ids, child in zip(arrays, children)] + )[order] + up = self._do_assign(rows, labels) + origins = dict(zip(children, parents)) + self._restored_partitions[tuple(sorted(children))] = (target, origins) + up.description = 'restore_parents' + up.parent_restore_target = target + up.parent_restore_origins = origins + up.clear_metadata = True + undo_state = emit('request_undo_state', self, up) + self._undo_stack.add((rows, labels, undo_state)) + emit('cluster', self, up) + return up + def assign(self, spike_ids, spike_clusters_rel=0): """Make new spike cluster assignments. @@ -533,6 +642,11 @@ def redo(self): # We apply the new assignment. up = self._do_assign(spike_ids, cluster_ids) up.history = 'redo' + restored = self._restored_partitions.get(tuple(sorted(up.added))) + if restored is not None: + up.description = 'restore_parents' + up.parent_restore_target, up.parent_restore_origins = restored + up.clear_metadata = True emit('cluster', self, up) return up diff --git a/phy/cluster/supervisor.py b/phy/cluster/supervisor.py index 71e92ea94..cddb738d5 100644 --- a/phy/cluster/supervisor.py +++ b/phy/cluster/supervisor.py @@ -8,7 +8,8 @@ import inspect import logging import sys -from contextlib import ExitStack +from contextlib import ExitStack, contextmanager +from copy import deepcopy from dataclasses import dataclass from functools import partial from numbers import Integral @@ -441,7 +442,12 @@ class MergeView(Table): def __init__(self, *args, data=None, columns=(), **kwargs): super().__init__(*args, title='MERGE MODE', debounce_events=(), **kwargs) - columns = ['id'] + [column for column in columns if column != 'id'] + columns = ( + ['id'] + + (['parent_origin'] if 'parent_origin' in columns else []) + + [column for column in columns if column not in ('id', 'parent_origin')] + ) + self._column_labels = {'parent_origin': 'Parent'} self._init_table( columns=columns, value_names=columns + [{'data': ['group']}], @@ -760,6 +766,11 @@ class Supervisor: skip_masked_clusters : bool Whether automatic navigation and similar-cluster selection skip noise and MUA clusters. The default is True. + clustering_factory : callable, optional + Construct the clustering model. Defaults to Clustering; bounded curation + supplies a guarded implementation with the same constructor interface. + cluster_meta_factory : callable, optional + Construct metadata from groups and labels. Defaults to create_cluster_meta. Events ------ @@ -795,11 +806,14 @@ def __init__( n_similar_clusters_to_select=None, skip_masked_clusters=True, merge_propositions=None, + clustering_factory=None, + cluster_meta_factory=None, ): super().__init__() self.context = context self.similarity = similarity # function cluster => [(cl, sim), ...] self.actions = None # will be set when attaching the GUI + self.select_actions = None self.gui = None self.merge_view = None self.merge_propositions_view = None @@ -809,6 +823,8 @@ def __init__( self._table_column_orders = {} self._suspend_presentation_order_sync = False self._is_dirty = None + self.parent_lineage = None + self.parent_origins = {} self._sort = sort # Initial sort requested in the constructor # This is populated alongside the existing TaskLogger-derived selection during the # migration to an explicit authoritative curation-selection model. @@ -838,7 +854,7 @@ def __init__( # Create Clustering and ClusterMeta. # Load the cached spikes_per_cluster array. spc = context.load('spikes_per_cluster') if context else None - self.clustering = Clustering( + self.clustering = (clustering_factory or Clustering)( spike_clusters, spikes_per_cluster=spc, new_cluster_id=new_cluster_id ) @@ -846,7 +862,9 @@ def __init__( self._save_spikes_per_cluster() # Create the ClusterMeta instance. - self.cluster_meta = create_cluster_meta(cluster_groups or {}, self.cluster_labels) + self.cluster_meta = (cluster_meta_factory or create_cluster_meta)( + cluster_groups or {}, self.cluster_labels + ) # Create the GlobalHistory instance. self._global_history = GlobalHistory( @@ -863,12 +881,47 @@ def __init__( connect(self._log_action_meta, event='cluster', sender=self.cluster_meta) # Raise supervisor.cluster + @connect(event='request_undo_state', sender=self.clustering) + def on_request_cluster_metadata(sender, up): + # Clustering has updated assignments, but metadata inheritance has + # not run yet. Retain only the affected units, including explicit + # default values that inheritance must not overwrite during undo. + return { + '_phy_cluster_metadata_before': { + int(unit): { + field: deepcopy(self.cluster_meta.get(field, unit)) + for field in self.cluster_meta.fields + } + for unit in up.deleted + } + } + @connect(sender=self.clustering) def on_cluster(sender, up): # NOTE: update the cluster meta of new clusters, depending on the values of the # ancestor clusters. In case of a conflict between the values of the old clusters, # the largest cluster wins and its value is set to its descendants. - if up.added: + before = None + if up.history == 'undo': + before = next( + ( + state['_phy_cluster_metadata_before'] + for state in up.undo_state or () + if isinstance(state, dict) and '_phy_cluster_metadata_before' in state + ), + None, + ) + if before is not None: + for unit in up.added: + if unit in before: + for field, default in self.cluster_meta._fields.items(): + self.cluster_meta.set( + field, [unit], before[unit].get(field, default), add_to_stack=False + ) + elif up.get('clear_metadata'): + for field in self.cluster_meta.fields: + self.cluster_meta.set(field, up.added, None, add_to_stack=False) + elif up.added: self.cluster_meta.set_from_descendants( up.descendants, largest_old_cluster=up.largest_old_cluster ) @@ -1018,6 +1071,8 @@ def _restore_workflow_context(self, context): def get_cluster_info(self, cluster_id, exclude=()): """Return the data associated to a given cluster.""" out = {'id': cluster_id} + if cluster_id in self.parent_origins: + out['parent_origin'] = f'was {self.parent_origins[cluster_id]}' # Cluster metrics. for key, func in self.cluster_metrics.items(): out[key] = func(cluster_id) @@ -1081,8 +1136,17 @@ def _ensure_merge_view(self, state=None): return self.merge_view state = state or self.selection.state data = [self.get_cluster_info(cluster_id) for cluster_id in state.merge_ids] - self.merge_view = MergeView(self.gui, data=data, columns=self.columns) - self.merge_view.set_column_order(self._table_column_orders.get('merge', ())) + self.merge_view = MergeView(self.gui, data=data, columns=self.columns + ['parent_origin']) + saved_order = self._table_column_orders.get('merge', ()) + order = [ + column + for column in saved_order or self.merge_view.columns + if column != 'parent_origin' + ] + if 'id' not in order: + order.insert(0, 'id') + order.insert(order.index('id') + 1, 'parent_origin') + self.merge_view.set_column_order(order) self.merge_view._reference_id = state.reference_id self.merge_view.configure_cluster_drag_drop( 'merge', accepted_roles=('merge', 'similarity'), drag_selected_rows=False @@ -1104,8 +1168,18 @@ def _ensure_merge_view(self, state=None): text='Cancel Merge Mode', callback=lambda checked: self.toggle_merge_mode(), ) + self.merge_view.dock.add_button( + name='exclude_merge_row', + text='Exclude current row', + callback=lambda checked: self._exclude_current_merge_row(), + ) return self.merge_view + def _exclude_current_merge_row(self): + row = self.merge_view._row_for_proxy_index(self.merge_view.table_view.currentIndex()) + if row is not None: + self.deselect_from_merge((int(row['id']),)) + def _show_merge_view(self, state=None): """Reveal the persistent Merge View for the active workspace.""" view = self._ensure_merge_view(state) @@ -1349,9 +1423,12 @@ def _merge_status_text(self): state = self.selection.state staged = len(state.merge_ids) similar = len(state.similar_ids) + keys = self._active_merge_proposition_keys() source = ( - f' — PROPOSITION {state.merge.proposition_id}' - if state.merge is not None and state.merge.proposition_id + f' — {len(keys)} PROPOSITIONS' + if len(keys) > 1 + else f' — PROPOSITION {keys[0]}' + if keys else '' ) return ( @@ -1363,10 +1440,10 @@ def _proposition_rows(self): """Project durable propositions and current live-cluster validity for the view.""" if self.merge_propositions is None: return [] - self.merge_propositions.project_live_ids(self.clustering.cluster_ids) + self._project_proposition_state() catalog = self.merge_propositions.catalog live_ids = set(catalog.live_unit_ids) - active_key = self._active_merge_proposition_key() + active_keys = set(self._active_merge_proposition_keys()) rows = [] for entry in catalog.entries: proposition = entry.proposition @@ -1374,7 +1451,7 @@ def _proposition_rows(self): catalog_status = ( catalog.status_for(key) if entry.key is not None else PropositionStatus.INVALID ) - status = 'active' if key == active_key else catalog_status.value + status = 'active' if key in active_keys else catalog_status.value unit_ids = proposition.unit_ids if proposition is not None else () rows.append( { @@ -1406,6 +1483,10 @@ def _active_merge_proposition_key(self): return state.merge.proposition_id return None + def _active_merge_proposition_keys(self): + state = self.selection.state + return state.merge.proposition_ids if state.is_merge_mode and state.merge else () + def _update_proposition_actions(self): """Keep proposition shortcuts aligned with the current queue state.""" if self.select_actions is None: @@ -1430,11 +1511,13 @@ def _update_proposition_actions(self): view is not None and current is not None and self._active_merge_proposition_key() == current + and len(self._active_merge_proposition_keys()) == 1 and view.can_trigger('reject') ) can_reset = bool( view is not None and not self.selection.state.is_merge_mode + and len(view.selected_keys) == 1 and view.can_trigger('reset') ) enabled = { @@ -1446,13 +1529,37 @@ def _update_proposition_actions(self): for name, value in enabled.items(): (self.select_actions.enable if value else self.select_actions.disable)(name) + def _project_proposition_state(self): + if self.merge_propositions is None: + return + kwargs = {} + if self.parent_lineage is not None and not hasattr(self, 'session'): + controlled, current = self.parent_lineage.proposition_retirements() + retired = { + unit: value + for unit, value in self.merge_propositions.catalog.retired_units.items() + if value['operation'] != 'restore_parents' and unit not in controlled + } + retired.update(current) + kwargs = { + 'retired_units': retired, + 'reassembled_results': self.parent_lineage.reassembled_results( + self.merge_propositions.catalog + ), + } + self.merge_propositions.project_live_ids(self.clustering.cluster_ids, **kwargs) + def _refresh_propositions(self): + self._project_proposition_state() if self.merge_propositions_view is not None: self.merge_propositions_view.set_propositions(self._proposition_rows()) - active_key = self._active_merge_proposition_key() - if active_key is not None: - self.merge_propositions_view.select_key(active_key) + active_keys = self._active_merge_proposition_keys() + if active_keys: + self.merge_propositions_view.select_keys(active_keys) self._update_proposition_actions() + # Annotation subscribers must also see review-only changes, even when + # selected cluster IDs (and therefore scientific view data) stay fixed. + emit('merge_propositions_changed', self) def _apply_selection_change( self, change, callback=None, refresh_similarity=True, publish=True, sync_presentation=True @@ -1499,8 +1606,8 @@ def _set_merge_mode_ui(self, active): if active: can_undo_proposition = ( self._active_merge_proposition_key() is not None - and self._global_history.current_position > 0 - ) + or self._can_undo_parent_restore() + ) and self._global_history.current_position > 0 index = self._global_history.current_position + 1 history = self._global_history._history can_redo_merge = index < len(history) and self._is_merge_history_context( @@ -1722,7 +1829,9 @@ def _on_action(self, sender, name, *args): 'previous_best', 'undo', } - if name == 'undo' and self._active_merge_proposition_key() is not None: + if name == 'undo' and ( + self._active_merge_proposition_key() is not None or self._can_undo_parent_restore() + ): blocked_in_merge.remove('undo') if self.selection.state.is_merge_mode and name in blocked_in_merge: logger.warning('Action `%s` is unavailable in Merge mode.', name) @@ -1928,7 +2037,7 @@ def attach(self, gui): supervisor=self, ) - connect(self._save_gui_state, event='close', sender=gui) + connect(self._save_gui_state, event='close_accepted', sender=gui) @connect(event='close_view') def on_close_view(view, sender): @@ -1960,6 +2069,11 @@ def on_default_actions_created(sender): event='activate_merge_proposition', sender=self.merge_propositions_view, ) + connect( + self._activate_merge_propositions, + event='activate_merge_propositions', + sender=self.merge_propositions_view, + ) connect( self._review_merge_proposition, event='review_merge_proposition', @@ -2000,7 +2114,7 @@ def on_is_busy(sender, is_busy): self._busy[sender] = is_busy self._set_busy(any(self._busy.values())) - @connect(sender=gui) + @connect(event='closed', sender=gui) def on_close(e): # The event registry holds strong references to senders and callbacks. # Release every object owned by this attachment before Qt destroys its @@ -2093,6 +2207,7 @@ def merge(self, cluster_ids=None, to=None): workflow_context = ( {'mode': 'merge', 'tables': self._workflow_context()} if merge_mode else None ) + proposition_ids = selection_before.merge.proposition_ids if proposition_id else () prepared_review = None review_before = None if proposition_id is not None: @@ -2101,11 +2216,18 @@ def merge(self, cluster_ids=None, to=None): # necessarily describe the same unit. to = int(self.clustering.new_cluster_id() if to is None else to) review_before = self.merge_propositions.snapshot() - prepared_review = self.merge_propositions.prepare_accept( - proposition_id, cluster_ids, to - ) + if len(proposition_ids) > 1: + prepared_review = self.merge_propositions.prepare_accept_many( + proposition_ids, cluster_ids, to + ) + else: + prepared_review = self.merge_propositions.prepare_accept( + proposition_id, cluster_ids, to + ) elif to is not None: to = int(to) + # Display-only observers must see source colors before cluster callbacks reset selection. + emit('before_merge', self, cluster_ids) # A merge synchronously emits several related table mutations: metadata # inheritance, addition of the merged cluster, and removal of its # ancestors. Fit each attached table once after the complete operation @@ -2129,7 +2251,7 @@ def merge(self, cluster_ids=None, to=None): if proposition_id is not None: self._set_merge_mode_ui(False) self._hide_merge_view() - self.merge_propositions_view.select_key(proposition_id) + self.merge_propositions_view.select_keys(proposition_ids) self._global_history.action( *controllers, description='merge', @@ -2145,6 +2267,120 @@ def merge(self, cluster_ids=None, to=None): self._set_merge_mode_ui(True) return out + @contextmanager + def _parent_restore_transaction(self, target): + """Roll back a failed restore without copying the recording's assignment vector.""" + clustering = self.clustering + rows = clustering.spikes_per_cluster.get(target) + if rows is None: + raise ValueError('Choose a current merged unit.') + spc, cluster_ids = dict(clustering._spikes_per_cluster), clustering._cluster_ids.copy() + restored = dict(clustering._restored_partitions) + metadata = deepcopy(self.cluster_meta._data) + histories = (clustering._undo_stack, self._global_history) + history_states = [(list(h._history), h._index) for h in histories] + selection, dirty = self.selection.snapshot(), self._is_dirty + workflow = self._workflow_context() if self.gui is not None else None + origins = dict(self.parent_origins) + lineage = self.parent_lineage + lineage_state = ( + ( + dict(lineage.records), + dict(lineage.color_records), + dict(lineage.origins), + dict(lineage.restorations), + set(lineage.known_merges), + ) + if lineage is not None + else None + ) + try: + yield + except Exception: + # Guarded bounded clustering permits writes while its outer semantic + # transaction holds the mutation policy. + clustering._spike_clusters[rows] = target + clustering._spikes_per_cluster, clustering._cluster_ids = spc, cluster_ids + clustering._restored_partitions = restored + self.cluster_meta._data = metadata + for history, (items, index) in zip(histories, history_states): + history._history, history._index = items, index + self.selection.restore(selection) + self.parent_origins = origins + self._is_dirty = dirty + if lineage_state is not None: + ( + lineage.records, + lineage.color_records, + lineage.origins, + lineage.restorations, + lineage.known_merges, + ) = lineage_state + # A refresh may have cached the temporary restored memberships + # before the failure. Recompute against the rolled-back state. + lineage._reassembly_cache = None + if self.gui is not None: + self._reset_cluster_view() + self._restore_history_context( + selection, {'mode': 'post_merge', 'tables': workflow}, 'undo' + ) + self._update_save_feedback() + raise + + def restore_parents(self, target=None, *, groups=None, colors=None, new_cluster_ids=None): + """Restore earliest recorded merge components as real units in the Merge workspace. + + This is a new curation action; unrelated later edits are preserved. + Explicit groups and IDs support validated bounded semantic commands. + """ + self._settle_selection() + if self.selection.state.is_merge_mode: + raise ValueError('Leave Merge mode before restoring another unit.') + if target is None: + if len(self.selected) != 1: + raise ValueError('Select one merged unit to restore its parents.') + target = self.selected[0] + target = int(target) + if groups is None: + if self.parent_lineage is None: + raise ValueError('Merge-parent lineage is unavailable.') + groups = self.parent_lineage.parents(target, recursive=True) + if colors is None and self.parent_lineage is not None: + colors = self.parent_lineage.colors(target, groups) + with self._parent_restore_transaction(target): + return self._restore_parent_partition(target, groups, colors, new_cluster_ids) + + def _restore_parent_partition(self, target, groups, colors, new_cluster_ids): + selection_before = self.selection.snapshot() + workflow_before = self._workflow_context() if self.gui is not None else {} + out = self.clustering.restore_partition(target, groups, new_cluster_ids=new_cluster_ids) + self.parent_origins.update(out.parent_restore_origins) + ordered = tuple(out.parent_restore_origins) + bindings = { + child: colors[parent] + for child, parent in out.parent_restore_origins.items() + if colors is not None and parent in colors + } + change = self.selection.enter_parent_restore(ordered, bindings, workflow_before) + if self.gui is not None: + self._show_merge_view(change.after) + self._set_merge_mode_ui(True) + self._apply_selection_change(change, refresh_similarity=True) + self._global_history.action( + self.clustering, + description='restore_parents', + selection_before=selection_before, + selection_after=self.selection.snapshot(), + workflow_context={'mode': 'post_merge', 'tables': workflow_before}, + workflow_context_after={'mode': 'merge', 'tables': workflow_before}, + ) + self._refresh_propositions() + self._is_dirty = True + self._update_save_feedback() + if self.gui is not None: + self._set_merge_mode_ui(True) + return out + def split(self, spike_ids=None, spike_clusters_rel=0): """Make a new cluster out of the specified spikes.""" self._settle_selection() @@ -2322,11 +2558,11 @@ def _pending_proposition_relative_to(self, key, direction, ordered_keys=None): def _activate_merge_proposition(self, sender, key): """Replace any temporary Merge workspace with the clicked proposition.""" active_key = self._active_merge_proposition_key() - if active_key == key: + if self._active_merge_proposition_keys() == (key,): self.merge_propositions_view.select_key(key) return self.selection.state self.merge_propositions_view.select_key(key) - self.merge_propositions.project_live_ids(self.clustering.cluster_ids) + self._project_proposition_state() catalog = self.merge_propositions.catalog if ( catalog.entry_for(key) is None @@ -2352,6 +2588,55 @@ def _activate_merge_proposition(self, sender, key): self._update_proposition_actions() return change.after + def _activate_merge_propositions(self, sender, keys): + """Compare the stable ordered union; selection never accepts a suggestion.""" + keys = tuple(dict.fromkeys(keys)) + if not keys: + if self.selection.state.is_merge_mode: + self._cancel_merge_mode() + self.merge_propositions_view.set_active_keys(()) + return self.selection.state + if len(keys) == 1: + return self._activate_merge_proposition(sender, keys[0]) + self._project_proposition_state() + catalog = self.merge_propositions.catalog + if any( + catalog.entry_for(key) is None + or catalog.status_for(key) is not PropositionStatus.PENDING + for key in keys + ): + if self.selection.state.is_merge_mode: + self._cancel_merge_mode() + self._refresh_propositions() + self.merge_propositions_view.select_keys(keys) + logger.warning('Only pending suggestions with live units can be reviewed together.') + return self.selection.state + ordered = tuple( + dict.fromkeys( + unit for key in keys for unit in catalog.entry_for(key).proposition.unit_ids + ) + ) + self._settle_selection() + if self.selection.state.is_merge_mode: + change = self.selection.switch_merge_proposition( + keys[0], + ordered, + proposition_ids=keys, + ) + else: + change = self.selection.enter_merge_proposition( + keys[0], + ordered, + self._workflow_context(), + proposition_ids=keys, + ) + self._show_merge_view() + self._set_merge_mode_ui(True) + self._apply_selection_change(change) + self.merge_propositions_view.set_active_keys(keys) + self._update_proposition_actions() + return change.after + def _review_merge_proposition(self, sender, key): """Compatibility alias for explicit programmatic review requests.""" return self._activate_merge_proposition(sender, key) @@ -2366,7 +2651,7 @@ def _navigate_merge_proposition(self, direction, callback=None, ordered_keys=Non if self.merge_propositions_view is not None else None ) - self.merge_propositions.project_live_ids(self.clustering.cluster_ids) + self._project_proposition_state() key = self._pending_proposition_relative_to(current, direction, ordered_keys) if key is not None: self._activate_merge_proposition(self.merge_propositions_view, key) @@ -2396,7 +2681,7 @@ def _reject_merge_proposition(self, sender, key): if self._active_merge_proposition_key() != key: logger.warning('Only the active merge proposition can be rejected.') return - self.merge_propositions.project_live_ids(self.clustering.cluster_ids) + self._project_proposition_state() self.merge_propositions.reject(key) self._refresh_propositions() next_key = self._pending_proposition_relative_to(key, 'next', ordered_keys) @@ -2423,6 +2708,11 @@ def reject_merge_proposition(self, callback=None): if callback: callback(self.selection.state) return + if len(self._active_merge_proposition_keys()) > 1: + logger.warning('Select one suggestion to reject it individually.') + if callback: + callback(self.selection.state) + return self.selection.state key = self._active_merge_proposition_key() if key is not None: self._reject_merge_proposition(self.merge_propositions_view, key) @@ -2434,7 +2724,7 @@ def _reset_merge_proposition(self, sender, key): if self.selection.state.is_merge_mode: self._cancel_merge_mode() before = self.selection.snapshot() - self.merge_propositions.project_live_ids(self.clustering.cluster_ids) + self._project_proposition_state() try: self.merge_propositions.reset(key) except ValueError as e: @@ -2462,6 +2752,11 @@ def reset_merge_proposition(self, callback=None): callback(self.selection.state) return view = self.merge_propositions_view + if self.merge_propositions_view and len(self.merge_propositions_view.selected_keys) > 1: + logger.warning('Select one suggestion to reset its review.') + if callback: + callback(self.selection.state) + return self.selection.state key = view.current_key if view is not None else None if key is not None and view.can_trigger('reset'): self._reset_merge_proposition(view, key) @@ -2638,10 +2933,20 @@ def _update_save_feedback(self, saved=False): if saved: self.gui.status_message = 'Curation changes saved.' + def _can_undo_parent_restore(self): + return ( + self._global_history.current_position > 0 + and self._global_history.current_item.description == 'restore_parents' + ) + def undo(self): """Undo the last action.""" self._settle_selection() - if self.selection.state.is_merge_mode and self._active_merge_proposition_key() is None: + if ( + self.selection.state.is_merge_mode + and self._active_merge_proposition_key() is None + and not self._can_undo_parent_restore() + ): logger.warning('Undo is unavailable while a Merge workspace is active.') return # Selection-only exploration does not create history entries. Preserve the exact diff --git a/phy/cluster/tests/test_clustering.py b/phy/cluster/tests/test_clustering.py index 9557221d7..cc59bd1a5 100644 --- a/phy/cluster/tests/test_clustering.py +++ b/phy/cluster/tests/test_clustering.py @@ -26,6 +26,28 @@ # ------------------------------------------------------------------------------ +def test_sparse_absolute_cluster_ids_do_not_allocate_dense_histograms(monkeypatch): + original = np.bincount + + def bounded_bincount(values, *args, **kwargs): + assert not len(values) or np.max(values) < 1024 + return original(values, *args, **kwargs) + + monkeypatch.setattr(np, 'bincount', bounded_bincount) + high = 2_000_000_000 + clustering = Clustering(np.array([0, 1, 1, high], dtype=np.int64)) + first = clustering.merge([0, 1]) + assert first.largest_old_cluster == 1 + assert first.added == [high + 1] + second = clustering.merge([high, high + 1]) + assert second.largest_old_cluster == high + 1 + clustering.undo() + ae(clustering.spike_clusters, [high + 1, high + 1, high + 1, high]) + clustering.split([0]) + clustering.undo() + ae(clustering.spike_clusters, [high + 1, high + 1, high + 1, high]) + + def test_extend_spikes_simple(): spike_clusters = np.array([3, 5, 2, 9, 5, 5, 2]) spike_ids = np.array([2, 4, 0]) @@ -40,6 +62,48 @@ def test_extend_spikes_simple(): ae(extended, [1, 5, 6]) +def test_restore_partition_is_local_fresh_and_undoable(monkeypatch): + clustering = Clustering(np.array([0, 0, 1, 1, 2, 2, 3, 3])) + merged = clustering.merge([0, 1]).added[0] + unrelated = clustering.merge([2, 3]).added[0] + before = clustering.spike_clusters.copy() + + def no_global_scan(*args, **kwargs): + raise AssertionError('Restoration scanned unrelated spike assignments.') + + monkeypatch.setattr('phy.cluster.clustering._extend_spikes', no_global_scan) + out = clustering.restore_partition(merged, {0: np.array([0, 1]), 1: np.array([2, 3])}) + assert out.description == 'restore_parents' + assert list(out.parent_restore_origins.values()) == [0, 1] + assert min(out.added) > unrelated + ae(clustering.spike_clusters[4:], before[4:]) + restored = clustering.spike_clusters.copy() + clustering.undo() + ae(clustering.spike_clusters, before) + redone = clustering.redo() + assert redone.clear_metadata + assert redone.parent_restore_origins == out.parent_restore_origins + ae(clustering.spike_clusters, restored) + + +def test_restore_partition_rejects_inexact_or_colliding_groups(): + clustering = Clustering(np.array([4, 4, 4, 4, 8])) + before = clustering.spike_clusters.copy() + for groups in ( + {0: np.array([0, 1]), 1: np.array([1, 3])}, + {0: np.array([0, 1]), 1: np.array([2])}, + {0: np.array([], dtype=np.int64), 1: np.array([0, 1, 2, 3])}, + ): + with raises(ValueError): + clustering.restore_partition(4, groups) + ae(clustering.spike_clusters, before) + with raises(ValueError, match='fresh IDs'): + clustering.restore_partition( + 4, {0: np.array([0, 1]), 1: np.array([2, 3])}, new_cluster_ids=[0, 1] + ) + ae(clustering.spike_clusters, before) + + def test_extend_spikes(): n_spikes = 1000 n_clusters = 10 diff --git a/phy/cluster/tests/test_proposition_annotations.py b/phy/cluster/tests/test_proposition_annotations.py new file mode 100644 index 000000000..75736c48a --- /dev/null +++ b/phy/cluster/tests/test_proposition_annotations.py @@ -0,0 +1,106 @@ +"""Pending source membership is independent of traces, tables, and lineage aliases.""" + +from phy.cluster._proposition_annotations import ( + WHITE, + project_proposition_labels, + proposition_label_color, +) +from phy.cluster._propositions import PropositionStatus, decode_curation_mapping + + +def _catalog(groups, live=None): + units = list(dict.fromkeys(unit for group in groups for unit in group)) + catalog = decode_curation_mapping( + { + 'format_version': '2', + 'unit_ids': units, + 'merges': [{'unit_ids': group} for group in groups], + } + ) + return catalog if live is None else catalog.project_live_ids(live) + + +def test_pdf_groups_and_neutral_unit_ignore_display_order(): + catalog = _catalog([[449, 461, 466, 467, 469], [479, 491, 498]]) + keys = tuple(p.key for p in catalog.propositions) + units = [449, 461, 466, 467, 469, 479, 491, 498, 511] + for ordered in (units, units[::-1]): + result = project_proposition_labels(catalog, ordered, keys[:1]) + assert [group.display_id for group in result.groups] == ['P1', 'P2'] + assert result.groups[0].active and not result.groups[1].active + for unit in units[:5]: + assert result.annotations[unit].color == proposition_label_color(0) + for unit in units[5:8]: + assert result.annotations[unit].color == proposition_label_color(1) + assert result.annotations[511].color == WHITE + assert not result.annotations[511].groups + + +def test_multiple_active_groups_overlap_and_paging_reserve_color_slots(): + catalog = _catalog([[1, 2], [2, 3], [4, 5], [6, 7]]) + keys = tuple(p.key for p in catalog.propositions) + active = (keys[1], keys[0]) + first = project_proposition_labels(catalog, [1, 2, 3, 4], active) + overlap = first.annotations[2] + assert overlap.text == '2*' + assert [group.key for group in overlap.groups] == list(active) + assert overlap.color == proposition_label_color(0) + assert [group.active for group in first.groups] == [True, True, False] + second = project_proposition_labels(catalog, [6], active, first.color_keys) + assert second.annotations[6].color == proposition_label_color(3) + third = project_proposition_labels(catalog, [4, 2], active, second.color_keys) + assert third.annotations[4].color == first.annotations[4].color + assert third.annotations[2] == overlap + # A completed group releases its annotation without shifting other groups' + # reserved colors in this workspace. + reviewed = catalog.reject(keys[2]) + fourth = project_proposition_labels(reviewed, [4, 6], active, third.color_keys) + assert fourth.annotations[4].color == WHITE + assert fourth.annotations[6].color == second.annotations[6].color + + +def test_only_authoritative_pending_entries_receive_annotations(): + catalog = _catalog([[1, 2], [3, 4], [5, 6], [7, 8]]) + keys = tuple(p.key for p in catalog.propositions) + catalog = catalog.reject(keys[0]).accept(keys[1], [3, 4], 30) + catalog = catalog.accept(keys[2], [5, 6, 7], 50) + catalog = catalog.project_live_ids( + [1, 2, 3, 4, 5, 6, 7, 80, 30, 50], + retired_units={ + '8': {'operation': 'threshold_split', 'replacements': [80]}, + '30': {'operation': 'restore_parents', 'replacements': [3, 4]}, + }, + ) + assert [catalog.status_for(key) for key in keys] == [ + PropositionStatus.REJECTED, + PropositionStatus.ACCEPTED_RESTORED, + PropositionStatus.ACCEPTED_MODIFIED, + PropositionStatus.STALE, + ] + result = project_proposition_labels(catalog, [1, 3, 5, 7, 80], keys) + assert not result.groups + assert all(annotation.color == WHITE for annotation in result.annotations.values()) + # A restored/reassembled accepted result is still reviewed, never pending. + catalog = catalog.project_live_ids( + catalog.live_unit_ids, + reassembled_results={keys[1]: {'result_unit_id': 30, 'modified': False}}, + ) + assert catalog.status_for(keys[1]) is PropositionStatus.ACCEPTED + assert not list(catalog.pending_entries()) + # Reset is explicit; aliases alone never cause this transition. + catalog = catalog.reset(keys[0]) + assert project_proposition_labels(catalog, [1]).annotations[1].groups[0].key == keys[0] + + +def test_invalid_source_and_missing_catalog_are_neutral(): + catalog = decode_curation_mapping( + { + 'format_version': '2', + 'unit_ids': [1, 2], + 'merges': [{'unit_ids': [1, 99]}, {'unit_ids': [1]}], + } + ) + for source in (catalog, None): + result = project_proposition_labels(source, [1, 99]) + assert not result.groups + assert all(item.color == WHITE for item in result.annotations.values()) diff --git a/phy/cluster/tests/test_proposition_view.py b/phy/cluster/tests/test_proposition_view.py index dfee341b4..27caaed8b 100644 --- a/phy/cluster/tests/test_proposition_view.py +++ b/phy/cluster/tests/test_proposition_view.py @@ -86,3 +86,60 @@ def test_merge_propositions_active_row_changes_in_place(qtbot): assert view._model.row_by_id(1)['status'] == 'active' assert view._model.row_by_id(1)['_catalog_status'] == 'rejected' view.close() + + +def test_control_click_retains_suggestions_and_stable_keys(qtbot): + view = MergePropositionsView( + data=[ + {'key': 'a', 'unit_ids': (1, 2)}, + {'key': 'b', 'unit_ids': (2, 3)}, + {'key': 'c', 'unit_ids': (4, 5)}, + ] + ) + _wait_until_table_ready(qtbot, view) + view.show() + single, multiple = [], [] + + @connect(event='activate_merge_proposition', sender=view) + def activated(sender, key): + single.append(key) + + @connect(event='activate_merge_propositions', sender=view) + def compared(sender, keys): + multiple.append(keys) + + def click(key, modifiers=Qt.NoModifier): + index = view._proxy_index_for_id(view._id_by_key[key]) + qtbot.mouseClick( + view.table_view.viewport(), + Qt.LeftButton, + modifier=modifiers, + pos=view.table_view.visualRect(index).center(), + ) + + try: + click('a') + click('b', Qt.ControlModifier) + assert view.selected_keys == ('a', 'b') + assert single == ['a'] + assert multiple == [('a', 'b')] + view.set_propositions( + [ + {'key': 'c', 'unit_ids': (4, 5)}, + {'key': 'b', 'unit_ids': (2, 3)}, + {'key': 'a', 'unit_ids': (1, 2)}, + ] + ) + assert view.selected_keys == ('a', 'b') + assert view.get_selected_ids() == [2, 1] + click('a', Qt.ControlModifier) + assert view.selected_keys == ('b',) + click('b', Qt.ControlModifier) + assert view.selected_keys == () + assert multiple[-1] == () + click('c') + assert view.selected_keys == ('c',) + assert single[-1] == 'c' + finally: + unconnect(activated, compared) + view.close() diff --git a/phy/cluster/tests/test_propositions.py b/phy/cluster/tests/test_propositions.py index 22caf1194..865a45ad2 100644 --- a/phy/cluster/tests/test_propositions.py +++ b/phy/cluster/tests/test_propositions.py @@ -30,6 +30,246 @@ def _source(merges=None): } +def test_retired_units_explain_stale_without_retargeting_or_overwriting_reviews(): + source = _source([{'unit_ids': [41, 56]}, {'unit_ids': [56, 72]}]) + catalog = decode_curation_mapping(source) + accepted, pending = [entry.key for entry in catalog.entries] + catalog = catalog.accept(accepted, [41, 56], 100) + retired = { + '41': {'operation': 'merge', 'replacements': [100]}, + '56': {'operation': 'merge', 'replacements': [100]}, + '72': {'operation': 'threshold_split', 'replacements': [101, 102]}, + } + catalog = catalog.project_live_ids([100, 101, 102], retired_units=retired) + assert catalog.status_for(accepted) is PropositionStatus.ACCEPTED + assert catalog.reason_for(accepted) is None + assert catalog.status_for(pending) is PropositionStatus.STALE + assert '56 was merged' in catalog.reason_for(pending) + assert '72 was split' in catalog.reason_for(pending) + assert encode_curation_mapping(catalog) == source + retired['56']['operation'] = 'threshold_split' + assert '56 was merged' in catalog.reason_for(pending) + controller = MergePropositionController(catalog) + controller.project_live_ids([100, 101, 102]) + assert controller.catalog.reason_for(pending) == catalog.reason_for(pending) + + +def test_retired_unit_validation(): + for retired in ( + [], + False, + {'01': {'operation': 'merge', 'replacements': [100]}}, + {'41': {'operation': 'label', 'replacements': [100]}}, + {'41': {'operation': 'merge', 'replacements': [41]}}, + {'41': {'operation': 'merge', 'replacements': []}}, + {'41': {'operation': 'threshold_split', 'replacements': [-1]}}, + ): + with raises(ValueError): + decode_curation_mapping(_source(), retired_units=retired) + + +def test_restored_accepted_result_preserves_historical_review_without_live_acceptance(): + catalog = decode_curation_mapping(_source()) + key = catalog.propositions[0].key + catalog = catalog.accept(key, [41, 56], 100) + review = catalog.review_mapping() + restored = catalog.project_live_ids( + [101, 102, 72], + retired_units={ + '41': {'operation': 'merge', 'replacements': [100]}, + '56': {'operation': 'merge', 'replacements': [100]}, + '100': {'operation': 'restore_parents', 'replacements': [101, 102]}, + }, + ) + assert restored.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + assert 'subsequently restored' in restored.reason_for(key) + assert restored.review_mapping() == review + assert catalog.status_for(key) is PropositionStatus.ACCEPTED + with raises(ValueError, match='accepted_restored'): + restored.accept(key, [101, 102], 103) + + +def test_nested_result_retirement_also_marks_acceptance_historical(): + catalog = decode_curation_mapping(_source()) + key = catalog.propositions[0].key + catalog = catalog.accept(key, [41, 56], 100) + projected = catalog.project_live_ids( + [103, 104], + retired_units={ + '100': {'operation': 'merge', 'replacements': [102]}, + '102': {'operation': 'restore_parents', 'replacements': [103, 104]}, + }, + ) + assert projected.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + + +def _restored_catalog(*, modified=False): + catalog = decode_curation_mapping(_source()) + key = catalog.propositions[0].key + applied = [41, 56, 72] if modified else [41, 56] + catalog = catalog.accept(key, applied, 100) + retired = { + '41': {'operation': 'merge', 'replacements': [100]}, + '56': {'operation': 'merge', 'replacements': [100]}, + '100': {'operation': 'restore_parents', 'replacements': [101, 102]}, + '101': {'operation': 'merge', 'replacements': [103]}, + '102': {'operation': 'merge', 'replacements': [103]}, + } + return catalog.project_live_ids([103, 72], retired_units=retired), key + + +def test_proven_complete_reassembly_recovers_acceptance_without_retargeting_review(): + restored, key = _restored_catalog() + historical_review = restored.review_mapping() + # Retirement convergence alone is insufficient evidence: a restore can + # distribute different historical memberships among its replacement IDs. + assert restored.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + proof = {key: {'result_unit_id': np.int64(103), 'modified': False}} + reassembled = restored.project_live_ids([103, 72], reassembled_results=proof) + assert reassembled.status_for(key) is PropositionStatus.ACCEPTED + assert reassembled.reason_for(key) is None + assert reassembled.review_mapping() == historical_review + assert reassembled.reviews[key].result_unit_id == 100 + assert reassembled.reviews[key].applied_unit_ids == (41, 56) + assert encode_curation_mapping(reassembled) == _source() + proof[key]['modified'] = True + assert reassembled.status_for(key) is PropositionStatus.ACCEPTED + assert type(reassembled.reassembled_results[key]['result_unit_id']) is int + with raises(TypeError): + reassembled.reassembled_results[key]['modified'] = True + + +def test_complete_reassembly_with_extra_membership_is_modified_acceptance(): + restored, key = _restored_catalog() + reassembled = restored.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': True}}, + ) + assert reassembled.status_for(key) is PropositionStatus.ACCEPTED_MODIFIED + assert reassembled.review_mapping() == restored.review_mapping() + # Reconstructing an historically modified accepted scope does not convert + # that curator decision into an exact acceptance of the original proposal. + restored, key = _restored_catalog(modified=True) + reassembled = restored.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': False}}, + ) + assert reassembled.status_for(key) is PropositionStatus.ACCEPTED_MODIFIED + assert reassembled.reviews[key].applied_unit_ids == (41, 56, 72) + + +def test_reassembly_projection_clears_after_partial_split_or_another_restore(): + restored, key = _restored_catalog() + reassembled = restored.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': False}}, + ) + # Even a still-live target may have lost part of its accepted membership. + # Every caller must prove complete coverage again on each projection. + assert ( + reassembled.project_live_ids([103, 72]).status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + retired = dict(reassembled.retired_units) + retired['103'] = {'operation': 'restore_parents', 'replacements': [104, 105]} + separated = reassembled.project_live_ids([104, 105, 72], retired_units=retired) + assert separated.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + retired['104'] = {'operation': 'merge', 'replacements': [106]} + retired['105'] = {'operation': 'merge', 'replacements': [106]} + repeated = separated.project_live_ids( + [106, 72], + retired_units=retired, + reassembled_results={key: {'result_unit_id': 106, 'modified': False}}, + ) + assert repeated.status_for(key) is PropositionStatus.ACCEPTED + assert repeated.review_mapping() == restored.review_mapping() + + +def test_reassembly_is_derived_not_saved_or_a_dirty_review_transition(): + restored, key = _restored_catalog() + controller = MergePropositionController(restored) + controller.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': False}}, + ) + assert controller.catalog.status_for(key) is PropositionStatus.ACCEPTED + assert not controller.is_dirty() + snapshot = controller.snapshot() + controller.project_live_ids([101, 102, 72]) + assert controller.catalog.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + controller.restore(snapshot) + assert controller.catalog.status_for(key) is PropositionStatus.ACCEPTED + source, reviews = decode_review_mapping(controller.catalog.review_mapping()) + loaded = decode_curation_mapping(encode_curation_mapping(controller.catalog))._replace( + reviews=reviews + ) + assert loaded.reviews[key].result_unit_id == 100 + assert not loaded.reassembled_results + loaded = loaded.project_live_ids([103, 72], retired_units=controller.catalog.retired_units) + assert loaded.status_for(key) is PropositionStatus.ACCEPTED_RESTORED + assert 'reassembled_results' not in source + + +def test_reassembly_projection_requires_a_known_accepted_review_and_live_result(): + restored, key = _restored_catalog() + for value in ( + [], + {'result_unit_id': 999, 'modified': False}, + {'result_unit_id': True, 'modified': False}, + {'result_unit_id': 103, 'modified': 0}, + {'result_unit_id': 103}, + {'result_unit_id': 103, 'modified': False, 'unknown': 1}, + ): + with raises(ValueError): + restored.project_live_ids([103, 72], reassembled_results={key: value}) + for catalog in ( + decode_curation_mapping(_source()), + decode_curation_mapping(_source()).reject(key), + ): + with raises(ValueError, match='accepted review'): + catalog.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': False}}, + ) + with raises(ValueError, match='accepted review'): + restored.project_live_ids( + [103, 72], + reassembled_results={'merge:unknown': {'result_unit_id': 103, 'modified': False}}, + ) + + +def test_explicit_review_change_drops_old_derived_reassembly(): + restored, key = _restored_catalog() + reassembled = restored.project_live_ids( + [103, 72], + reassembled_results={key: {'result_unit_id': 103, 'modified': False}}, + ) + rejected = reassembled.reject(key) + assert rejected.status_for(key) is PropositionStatus.REJECTED + assert not rejected.reassembled_results + accepted_again = reassembled.accept(key, [103, 72], 104) + assert accepted_again.reviews[key].result_unit_id == 104 + assert not accepted_again.reassembled_results + + +def test_retirement_projection_undo_and_durable_modified_review(): + catalog = decode_curation_mapping(_source()) + key = catalog.propositions[0].key + controller = MergePropositionController(catalog) + before = controller.snapshot() + retired = {'41': {'operation': 'threshold_split', 'replacements': [100, 101]}} + controller.project_live_ids([56, 72, 100, 101], retired_units=retired) + assert '41 was split' in controller.catalog.reason_for(key) + controller.restore(before) + assert controller.catalog.status_for(key) is PropositionStatus.PENDING + modified = catalog.accept(key, [41, 72], 100).project_live_ids( + [56, 100], retired_units={'41': {'operation': 'merge', 'replacements': [100]}} + ) + assert modified.status_for(key) is PropositionStatus.ACCEPTED_MODIFIED + rejected = catalog.reject(key).project_live_ids([56, 100], retired_units=retired) + assert rejected.status_for(key) is PropositionStatus.REJECTED + + def test_aind_v2_decode_preserves_source_and_proposition_order(): source = _source([{'unit_ids': [56, 41], 'new_unit_id': 1000}]) diff --git a/phy/cluster/tests/test_supervisor.py b/phy/cluster/tests/test_supervisor.py index 59f93faac..20d976564 100644 --- a/phy/cluster/tests/test_supervisor.py +++ b/phy/cluster/tests/test_supervisor.py @@ -780,6 +780,150 @@ def test_merge_mode_rejects_cluster_mutations(supervisor): assert set(supervisor.clustering.cluster_ids) >= {30, 20} +def test_restore_parents_preserves_later_edits_and_workspace_history(supervisor, qtbot): + _select(supervisor, [30], [20]) + groups = {p: supervisor.clustering.spikes_per_cluster[p].copy() for p in (30, 20)} + merged = supervisor.merge().added[0] + supervisor.block() + _select(supervisor, [10], [11]) + unrelated = supervisor.merge().added[0] + supervisor.block() + supervisor.label('group', 'mua', [unrelated]) + supervisor.block() + supervisor.label('group', 'good', [merged]) + supervisor.block() + _select(supervisor, [merged]) + before = supervisor.clustering.spike_clusters.copy() + position = supervisor._global_history.current_position + out = supervisor.restore_parents(merged, groups=groups, colors={30: 0, 20: 1}) + supervisor.block() + children = list(out.parent_restore_origins) + assert supervisor.selected_merge == children + assert supervisor.actions.get('undo').isEnabled() + assert supervisor._global_history.current_position == position + 1 + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + assert all(supervisor.cluster_meta.get('group', child) is None for child in children) + assert supervisor.get_cluster_info(children[0])['parent_origin'] == 'was 30' + assert supervisor.merge_view.column_order()[:2] == ['id', 'parent_origin'] + parent_column = supervisor.merge_view.columns.index('parent_origin') + assert supervisor.merge_view._model.headerData(parent_column, Qt.Horizontal) == 'Parent' + assert supervisor.cluster_view._model.headerData(0, Qt.Horizontal) == 'id' + restored = supervisor.clustering.spike_clusters.copy() + + supervisor.undo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, before) + assert supervisor.selected == [merged] + assert supervisor.cluster_meta.get('group', merged) == 'good' + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + supervisor.redo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, restored) + assert supervisor.selected_merge == children + assert all(supervisor.cluster_meta.get('group', child) is None for child in children) + + # The visible exclusion button acts on an actual clicked row. G must not + # include that parent through an accidental Similarity selection. + view = supervisor.merge_view + index = view._proxy_index_for_id(children[1]) + qtbot.mouseClick( + view.table_view.viewport(), Qt.LeftButton, pos=view.table_view.visualRect(index).center() + ) + qtbot.mouseClick(view.dock.get_widget('exclude_merge_row'), Qt.LeftButton) + supervisor.block() + assert children[1] not in supervisor.selected + assert children[1] in supervisor.clustering.cluster_ids + supervisor.toggle_merge_mode() + supervisor.block() + assert supervisor.selected_clusters == children + ae(supervisor.clustering.spike_clusters, restored) + + supervisor.toggle_merge_mode() + supervisor.deselect_from_merge([children[1]]) + supervisor.add_to_merge([2]) + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + assert children[1] in supervisor.clustering.cluster_ids + result = supervisor.selected_clusters[0] + ae( + supervisor.clustering.spikes_per_cluster[result], + np.sort(np.concatenate([groups[30], [4, 5]])), + ) + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + + +def test_restore_workspace_physical_right_click_preserves_transfer_contract(supervisor, qtbot): + _select(supervisor, [30], [20]) + groups = {p: supervisor.clustering.spikes_per_cluster[p].copy() for p in (30, 20)} + target = supervisor.merge().added[0] + supervisor.block() + out = supervisor.restore_parents(target, groups=groups) + supervisor.block() + child = list(out.parent_restore_origins)[1] + view = supervisor.merge_view + index = view._proxy_index_for_id(child) + qtbot.mouseClick( + view.table_view.viewport(), Qt.RightButton, pos=view.table_view.visualRect(index).center() + ) + supervisor.block() + assert child not in supervisor.selected_merge + assert child in supervisor.selected_similar + # Transfer deliberately preserves the effective selection; exclusion has + # its own explicit button and is tested above. + assert child in supervisor.selected + + +@mark.parametrize('restored_quality', [None, 'mua']) +def test_remerge_restored_parent_undo_preserves_exact_metadata(supervisor, restored_quality): + _select(supervisor, [30], [20]) + groups = {p: supervisor.clustering.spikes_per_cluster[p].copy() for p in (30, 20)} + target = supervisor.merge().added[0] + supervisor.block() + out = supervisor.restore_parents(target, groups=groups) + supervisor.block() + first, excluded = out.parent_restore_origins + supervisor.toggle_merge_mode() + if restored_quality is not None: + supervisor.label('group', restored_quality, [first]) + supervisor.block() + assert supervisor.cluster_meta.get('group', 1) == 'good' + _select(supervisor, [first], [1]) + supervisor.toggle_merge_mode() + supervisor.merge() + supervisor.block() + supervisor.undo() + supervisor.block() + assert supervisor.cluster_meta.get('group', first) == restored_quality + assert supervisor.cluster_meta.get('group', excluded) is None + assert supervisor.cluster_meta.get('group', 1) == 'good' + assert first in supervisor.selected_merge + supervisor.redo() + supervisor.block() + assert excluded in supervisor.clustering.cluster_ids + + +def test_restore_parents_rolls_back_observer_failure(supervisor, monkeypatch): + _select(supervisor, [30], [20]) + groups = {p: supervisor.clustering.spikes_per_cluster[p].copy() for p in (30, 20)} + target = supervisor.merge().added[0] + supervisor.block() + before = supervisor.clustering.spike_clusters.copy() + selection = supervisor.selection.snapshot() + history = supervisor._global_history.current_position + workflow = supervisor._workflow_context() + + def fail(*args, **kwargs): + raise RuntimeError('injected restore presentation failure') + + monkeypatch.setattr(supervisor, '_show_merge_view', fail) + with raises(RuntimeError, match='injected'): + supervisor.restore_parents(target, groups=groups) + ae(supervisor.clustering.spike_clusters, before) + assert supervisor.selection.state == selection + assert supervisor._global_history.current_position == history + assert supervisor._workflow_context() == workflow + + def test_merge_mode_next_navigates_similarity_not_cluster(supervisor): _select(supervisor, [30], [20]) supervisor.toggle_merge_mode() @@ -1039,6 +1183,309 @@ def _proposition_supervisor( return supervisor +def test_ordinary_restoration_preserves_accepted_review_with_derived_status( + gui, cluster_ids, cluster_groups, cluster_labels, similarity, tempdir +): + from pathlib import Path + from types import SimpleNamespace + + from phy.apps._parent_review import ParentInspection, ParentLineage + + supervisor = _proposition_supervisor( + gui, cluster_ids, cluster_groups, cluster_labels, similarity, tempdir + ) + lineage = ParentLineage( + SimpleNamespace( + dir_path=Path(tempdir), + supervisor=supervisor, + model=SimpleNamespace(spike_times=np.arange(supervisor.clustering.n_spikes)), + ) + ) + supervisor.parent_lineage = lineage + try: + key = supervisor.merge_propositions.catalog.propositions[0].key + supervisor._activate_merge_proposition(supervisor.merge_propositions_view, key) + target = supervisor.merge().added[0] + supervisor.block() + review = supervisor.merge_propositions.catalog.reviews[key] + assert review.result_unit_id == target + supervisor.restore_parents(target) + supervisor.block() + assert supervisor.merge_propositions.catalog.reviews[key] == review + assert supervisor.merge_propositions.catalog.status_for(key).value == 'accepted_restored' + emit('curation_saved', supervisor) + reopened = Supervisor( + supervisor.clustering.spike_clusters.copy(), + merge_propositions=MergePropositionController(supervisor.merge_propositions.catalog), + ) + # Producer/review loading does not supply ordinary retirement projection; + # the saved parent sidecar must establish it before GUI attachment. + reopened.merge_propositions.project_live_ids( + reopened.clustering.cluster_ids, retired_units={} + ) + assert reopened.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + inspection = ParentInspection( + SimpleNamespace( + dir_path=Path(tempdir), + supervisor=reopened, + model=SimpleNamespace(spike_times=np.arange(reopened.clustering.n_spikes)), + ) + ) + try: + assert reopened.merge_propositions.catalog.status_for(key).value == 'accepted_restored' + finally: + inspection.close() + supervisor.undo() + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + supervisor.redo() + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key).value == 'accepted_restored' + supervisor.toggle_merge_mode() + finally: + lineage.close() + + +@fixture +def lineage_supervisor(gui, cluster_ids, cluster_groups, cluster_labels, similarity, tempdir): + from pathlib import Path + from types import SimpleNamespace + + from phy.apps._parent_review import ParentLineage + + supervisor = _proposition_supervisor( + gui, cluster_ids, cluster_groups, cluster_labels, similarity, tempdir + ) + lineage = ParentLineage( + SimpleNamespace( + dir_path=Path(tempdir), + supervisor=supervisor, + model=SimpleNamespace(spike_times=np.arange(supervisor.clustering.n_spikes)), + ) + ) + supervisor.parent_lineage = lineage + try: + yield supervisor + finally: + lineage.close() + + +def _accept_first_proposition(supervisor): + key = supervisor.merge_propositions.catalog.propositions[0].key + supervisor._activate_merge_proposition(supervisor.merge_propositions_view, key) + target = supervisor.merge().added[0] + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + return key, target + + +def test_recursive_restore_reaches_original_components_as_one_undoable_action( + lineage_supervisor, +): + supervisor = lineage_supervisor + original = supervisor.clustering.spike_clusters.copy() + key, first = _accept_first_proposition(supervisor) + _select(supervisor, [first], [10]) + nested = supervisor.merge().added[0] + supervisor.block() + _select(supervisor, [0], [2]) + unrelated = supervisor.merge().added[0] + supervisor.block() + supervisor.label('group', 'mua', [unrelated]) + supervisor.block() + _select(supervisor, [nested]) + before = supervisor.clustering.spike_clusters.copy() + history_position = supervisor._global_history.current_position + review = supervisor.merge_propositions.catalog.reviews[key] + + out = supervisor.restore_parents(nested) + supervisor.block() + + assert set(out.parent_restore_origins.values()) == {30, 20, 10} + assert len(out.added) == 3 + assert set(out.added).isdisjoint({30, 20, 10, first, nested}) + for child, parent in out.parent_restore_origins.items(): + ae(supervisor.clustering.spikes_per_cluster[child], np.flatnonzero(original == parent)) + assert supervisor.get_cluster_info(child)['parent_origin'] == f'was {parent}' + assert supervisor._global_history.current_position == history_position + 1 + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + assert supervisor.merge_propositions.catalog.reviews[key] == review + restored = supervisor.clustering.spike_clusters.copy() + + supervisor.undo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, before) + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + supervisor.redo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, restored) + assert supervisor.selected_merge == list(out.parent_restore_origins) + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + supervisor.toggle_merge_mode() + supervisor.block() + ae(supervisor.clustering.spike_clusters, restored) + + +def test_ordinary_exact_remerge_recovers_green_through_undo_redo_and_repeated_restore( + lineage_supervisor, +): + supervisor = lineage_supervisor + key, target = _accept_first_proposition(supervisor) + historical_review = supervisor.merge_propositions.catalog.review_mapping() + for _ in range(2): + out = supervisor.restore_parents(target) + supervisor.block() + assert set(out.parent_restore_origins.values()) == {30, 20} + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + restored = supervisor.clustering.spike_clusters.copy() + # Exercise the real G action from the editable workspace. + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + target = supervisor.selected_clusters[0] + remerged = supervisor.clustering.spike_clusters.copy() + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + assert supervisor.merge_propositions_view._model.row_by_id(0)['status'] == 'accepted' + assert supervisor.merge_propositions.catalog.review_mapping() == historical_review + supervisor.undo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, restored) + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.redo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, remerged) + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + assert supervisor.merge_propositions.catalog.review_mapping() == historical_review + + +def test_failed_restore_discards_temporary_reassembly_cache(lineage_supervisor, monkeypatch): + supervisor = lineage_supervisor + key, target = _accept_first_proposition(supervisor) + supervisor.restore_parents(target) + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + target = supervisor.selected_clusters[0] + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + assignments = supervisor.clustering.spike_clusters.copy() + selection = supervisor.selection.snapshot() + history = supervisor._global_history.current_position + reviews = supervisor.merge_propositions.catalog.review_mapping() + restore = supervisor._restore_parent_partition + + def fail_after_refresh(*args, **kwargs): + restore(*args, **kwargs) + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + assert supervisor.parent_lineage._reassembly_cache[1] == {} + raise RuntimeError('injected failure after restoration refresh') + + monkeypatch.setattr(supervisor, '_restore_parent_partition', fail_after_refresh) + with raises(RuntimeError, match='after restoration refresh'): + supervisor.restore_parents(target) + supervisor.block() + ae(supervisor.clustering.spike_clusters, assignments) + assert supervisor.selection.state == selection + assert supervisor._global_history.current_position == history + assert supervisor.merge_propositions.catalog.review_mapping() == reviews + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + row_id = supervisor.merge_propositions_view._id_by_key[key] + row = supervisor.merge_propositions_view._model.row_by_id(row_id) + assert row['status'] == 'accepted' + assert ( + supervisor.merge_propositions_view._foreground_color(row, 'proposition').name() + == '#86d16d' + ) + + +def test_partial_remerge_stays_white_then_complete_with_extra_becomes_modified_green( + lineage_supervisor, +): + supervisor = lineage_supervisor + key, target = _accept_first_proposition(supervisor) + historical_review = supervisor.merge_propositions.catalog.review_mapping() + out = supervisor.restore_parents(target) + supervisor.block() + _, excluded = out.parent_restore_origins + supervisor.deselect_from_merge([excluded]) + supervisor.add_to_merge([10]) + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + partial = supervisor.selected_clusters[0] + assert excluded in supervisor.clustering.cluster_ids + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + + _select(supervisor, [partial, excluded]) + supervisor.toggle_merge_mode() + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_MODIFIED + ) + assert supervisor.merge_propositions.catalog.review_mapping() == historical_review + supervisor.undo() + supervisor.block() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.redo() + supervisor.block() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_MODIFIED + ) + assert supervisor.merge_propositions.catalog.review_mapping() == historical_review + + +def test_split_membership_revokes_reassembled_acceptance_even_with_origin_aliases( + lineage_supervisor, +): + supervisor = lineage_supervisor + key, target = _accept_first_proposition(supervisor) + out = supervisor.restore_parents(target) + supervisor.block() + source_child = next( + child for child, parent in out.parent_restore_origins.items() if parent == 30 + ) + one_spike = supervisor.clustering.spikes_per_cluster[source_child][:1].copy() + supervisor.action_creator.edit_actions.get('merge').trigger() + supervisor.block() + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + before_split = supervisor.clustering.spike_clusters.copy() + supervisor.split(one_spike) + supervisor.block() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + supervisor.undo() + supervisor.block() + ae(supervisor.clustering.spike_clusters, before_split) + assert supervisor.merge_propositions.catalog.status_for(key) is PropositionStatus.ACCEPTED + supervisor.redo() + supervisor.block() + assert ( + supervisor.merge_propositions.catalog.status_for(key) + is PropositionStatus.ACCEPTED_RESTORED + ) + + def test_merge_proposition_review_cancel_restores_exact_entry( gui, cluster_ids, cluster_groups, cluster_labels, similarity, tempdir ): @@ -1135,8 +1582,10 @@ def test_merge_proposition_navigation_shortcuts_and_text_focus( assert supervisor.merge_view.dock is merge_dock assert supervisor.selection.state.merge.proposition_id == first.key - supervisor.merge_propositions_view.filter_edit.setFocus() - qtbot.wait(1) + gui.activateWindow() + field = supervisor.merge_propositions_view.filter_edit + field.setFocus() + qtbot.waitUntil(field.hasFocus) supervisor.next_merge_proposition() assert supervisor.selection.state.merge.proposition_id == first.key assert third.key in supervisor.merge_propositions_view.actionable_keys() @@ -1440,6 +1889,32 @@ def test_supervisor_close_releases_owned_event_callbacks( ) +def test_cancelled_close_preserves_merge_workspace_and_callbacks(supervisor): + _select(supervisor, [30], [20]) + supervisor.toggle_merge_mode() + gui, merge_view = supervisor.gui, supervisor.merge_view + selection = supervisor.selection.state + + @connect(event='close', sender=gui) + def cancel(sender): + return False + + try: + gui.close() + assert not gui._closed + assert supervisor.gui is gui + assert supervisor.merge_view is merge_view + assert supervisor.selection.state == selection + assert supervisor._merge_close_callback is not None + supervisor.toggle_merge_mode() + supervisor.label('group', 'good', [30]) + assert supervisor._is_dirty + supervisor.undo() + assert supervisor.cluster_meta.get('group', 30) != 'good' + finally: + unconnect(cancel) + + def test_saving_gui_state_cancels_transient_merge_selection(supervisor): _select(supervisor, [30], [20]) entry = supervisor.selection.snapshot() @@ -2893,3 +3368,117 @@ def selected(sender, cluster_ids): finally: unconnect(selected) view.debouncer.flush() + + +def test_multi_suggestions_compare_union_then_accept_atomically( + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, +): + supervisor = _proposition_supervisor( + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, + ) + first, overlap, _ = supervisor.merge_propositions.catalog.propositions + keys = (first.key, overlap.key) + _select(supervisor, [11], [10]) + original = supervisor.clustering.spike_clusters.copy() + view = supervisor.merge_propositions_view + supervisor._activate_merge_propositions(view, keys) + assert supervisor.selected == [30, 20, 10] + assert supervisor.selection.state.merge.proposition_ids == keys + assert view.selected_keys == keys + assert not supervisor.merge_propositions.catalog.reviews + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, original) + workspace = supervisor.selection.snapshot() + supervisor._refresh_propositions() + assert view.selected_keys == keys + supervisor.reject_merge_proposition() + assert supervisor.selection.snapshot() == workspace + assert not supervisor.merge_propositions.catalog.reviews + merged = supervisor.merge().added[0] + for key in keys: + review = supervisor.merge_propositions.catalog.reviews[key] + assert review.result_unit_id == merged + assert review.applied_unit_ids == (30, 20, 10) + supervisor.undo() + supervisor.block() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, original) + assert not supervisor.merge_propositions.catalog.reviews + assert supervisor.selection.snapshot() == workspace + assert view.selected_keys == keys + supervisor.redo() + supervisor.block() + assert len(supervisor.merge_propositions.catalog.reviews) == 2 + supervisor._activate_merge_propositions(view, ()) + assert not supervisor.selection.state.is_merge_mode + + +def test_multi_suggestion_cancel_restores_entry_and_rejects_stale( + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, +): + supervisor = _proposition_supervisor( + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, + ) + _select(supervisor, [11], [10]) + entry = supervisor.selection.snapshot() + first, overlap, _ = supervisor.merge_propositions.catalog.propositions + view = supervisor.merge_propositions_view + supervisor._activate_merge_propositions(view, (first.key, overlap.key)) + supervisor._activate_merge_propositions(view, ()) + assert supervisor.selection.snapshot() == entry + assert not supervisor.merge_propositions.catalog.reviews + supervisor.merge_propositions.reject(overlap.key) + supervisor._activate_merge_propositions(view, (first.key, overlap.key)) + assert supervisor.selection.snapshot() == entry + assert supervisor.merge_propositions.catalog.status_for(first.key) is PropositionStatus.PENDING + + +def test_multi_suggestion_preflight_failure_does_not_change_assignments( + monkeypatch, + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, +): + supervisor = _proposition_supervisor( + gui, + cluster_ids, + cluster_groups, + cluster_labels, + similarity, + tempdir, + ) + keys = tuple(p.key for p in supervisor.merge_propositions.catalog.propositions[:2]) + supervisor._activate_merge_propositions(supervisor.merge_propositions_view, keys) + original = supervisor.clustering.spike_clusters.copy() + snapshot = supervisor.selection.snapshot() + + def fail(*args): + raise ValueError('review preflight failed') + + monkeypatch.setattr(supervisor.merge_propositions, 'prepare_accept_many', fail) + with raises(ValueError, match='review preflight failed'): + supervisor.merge() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, original) + assert supervisor.selection.snapshot() == snapshot + assert not supervisor.merge_propositions.catalog.reviews diff --git a/phy/gui/actions.py b/phy/gui/actions.py index 0a0bcc79a..b4d59f6ec 100644 --- a/phy/gui/actions.py +++ b/phy/gui/actions.py @@ -39,9 +39,11 @@ def _parse_arg(s): def _parse_list(s): """Parse a comma-separated list of values (strings or numbers).""" - # Range: 'x-y' - if '-' in s: - m, M = map(_parse_arg, s.split('-')) + # Only nonnegative integer endpoints form a range: a minus sign can also + # belong to a scalar, an exponent, a list item, or a string. + match = re.fullmatch(r'(\+?\d+)-(\+?\d+)', s) + if match: + m, M = map(int, match.groups()) return list(range(m, M + 1)) # List of ids: 'x,y,z' elif ',' in s: diff --git a/phy/gui/gui.py b/phy/gui/gui.py index bb93a791d..23f07c676 100644 --- a/phy/gui/gui.py +++ b/phy/gui/gui.py @@ -567,6 +567,8 @@ class GUI(QMainWindow): ------ close(gui) + close_accepted(gui) # Capture state after all vetoes, before state.save(). + closed(gui) # Emitted only after closure is accepted. show(gui) close_view(view, gui) @@ -750,9 +752,11 @@ def closeEvent(self, e): if False in res: # pragma: no cover e.ignore() return + # State capture and teardown must not run until every close veto has + # been considered. Capture state before its on-disk save below. + emit('close_accepted', self) super().closeEvent(e) self._closed = True - # Save the state to disk when closing the GUI. logger.debug('Save the geometry state.') try: diff --git a/phy/gui/qt.py b/phy/gui/qt.py index c35e202b1..c64bd793c 100644 --- a/phy/gui/qt.py +++ b/phy/gui/qt.py @@ -97,6 +97,7 @@ QInputDialog, QOpenGLWidget, QStyle, + QProxyStyle, QTableView, QTableWidget, QTableWidgetItem, diff --git a/phy/gui/task_widgets.py b/phy/gui/task_widgets.py new file mode 100644 index 000000000..e95358f01 --- /dev/null +++ b/phy/gui/task_widgets.py @@ -0,0 +1,138 @@ +"""Reusable nonmodal task presentation; hiding never cancels work.""" + +from contextlib import suppress + +from PyQt5 import sip +from PyQt5.QtWidgets import QProgressBar + +from .qt import QDialog, QHBoxLayout, QLabel, QPlainTextEdit, QPushButton, QVBoxLayout, QWidget +from .tasks import StageETA + + +def _remaining(seconds): + if seconds < 60: + return f'about {max(1, round(seconds))} s remaining in this stage' + return f'about {max(1, round(seconds / 60))} min remaining in this stage' + + +class TaskWidget(QWidget): + """Compact status-bar task display with bounded expandable details.""" + + def __init__(self, manager, parent=None): + super().__init__(parent) + self._disposed = False + self.manager = manager + self.eta = StageETA() + self._last_stage = None + layout = QHBoxLayout(self) + layout.setContentsMargins(4, 0, 4, 0) + self.label = QLabel('Background task', self) + self.label.setMaximumWidth(420) + self.bar = QProgressBar(self) + self.bar.setMaximumWidth(160) + self.estimate = QLabel('', self) + self.cancel_button = QPushButton('Cancel', self) + self.details_button = QPushButton('Details', self) + self.hide_button = QPushButton('Hide', self) + for widget in ( + self.label, + self.bar, + self.estimate, + self.cancel_button, + self.details_button, + self.hide_button, + ): + layout.addWidget(widget) + self.details = QDialog(parent) + self.details.setWindowTitle('Background task details') + detail_layout = QVBoxLayout(self.details) + self.log = QPlainTextEdit(self.details) + self.log.setReadOnly(True) + self.log.document().setMaximumBlockCount(200) + detail_layout.addWidget(self.log) + self.details.resize(650, 250) + self.cancel_button.clicked.connect(manager.cancel) + self.details_button.clicked.connect(self.details.show) + self.hide_button.clicked.connect(self.hide) + manager.progress.connect(self.on_progress) + manager.finished.connect(self.on_finished) + manager.state_changed.connect(self.on_state) + + def on_state(self, state): + if state == 'pending': + self.eta.reset() + self._last_stage = None + self.label.setText(self.manager.spec.title) + self.label.setToolTip('') + self._set_active(True) + self.bar.setRange(0, 0) + self.estimate.setText('Estimating time remaining…') + self.show() + self.cancel_button.setEnabled(state in ('pending', 'running')) + if state == 'committing': + self.estimate.setText('Finishing…') + elif state == 'cancelling': + self.estimate.setText('Cancelling…') + + def on_progress(self, progress): + self.label.setText(progress.stage) + if progress.stage != self._last_stage: + self.log.appendPlainText(progress.stage) + self._last_stage = progress.stage + if progress.total and progress.done is not None: + self.bar.setRange(0, 1000) + self.bar.setValue(min(1000, int(1000 * progress.done / progress.total))) + self.bar.setFormat('%p%') + else: + self.bar.setRange(0, 0) + remaining = self.eta.update(progress) + self.estimate.setText( + _remaining(remaining) + if remaining is not None + else (progress.message or ('Estimating time remaining…' if progress.total else '')) + ) + if self.manager.state == 'committing': + self.estimate.setText('Finishing…') + elif self.manager.state == 'cancelling': + self.estimate.setText('Cancelling…') + if progress.message: + self.log.appendPlainText(progress.message) + + def _set_active(self, active): + self.bar.setVisible(active) + self.cancel_button.setVisible(active) + self.hide_button.setText('Hide' if active else 'Close') + + def on_finished(self, outcome): + self.cancel_button.setEnabled(False) + self._set_active(False) + self.label.setText( + {'succeeded': 'Done', 'cancelled': 'Cancelled', 'failed': 'Task failed'}[outcome.state] + ) + self.estimate.setText('') + if outcome.error: + self.log.appendPlainText(outcome.error) + self.estimate.setText('See Details') + + def notice(self, message): + self.log.appendPlainText(str(message)) + self.label.setText(str(message)[:160]) + self.label.setToolTip(str(message)) + if not self.manager.busy: + self._set_active(False) + self.show() + + def dispose(self): + if getattr(self, '_disposed', False): + return + self._disposed = True + for name, slot in ( + ('progress', self.on_progress), + ('finished', self.on_finished), + ('state_changed', self.on_state), + ): + # Qt can disconnect receivers while deleting their parent GUI. + with suppress(TypeError, RuntimeError): + getattr(self.manager, name).disconnect(slot) + if not sip.isdeleted(self.details): + self.details.close() diff --git a/phy/gui/tasks.py b/phy/gui/tasks.py new file mode 100644 index 000000000..d0570a960 --- /dev/null +++ b/phy/gui/tasks.py @@ -0,0 +1,332 @@ +"""Small, bounded background tasks with cooperative cancellation and queued delivery. + +Workers receive immutable requests and a TaskContext, never GUI/session objects. +No task queue, persistent jobs, or interruption of native operations is implied. +""" + +from contextlib import contextmanager +from dataclasses import dataclass, fields, is_dataclass +from pathlib import Path +from threading import Event, Lock, Thread +from time import monotonic +from uuid import uuid4 + +from .qt import QObject, QTimer, pyqtSignal, pyqtSlot + +_HEAVY_IO = Lock() +_ACTIVE = set() +_MANAGERS = {} +_ACTIVE_LOCK = Lock() + + +class TaskCancelledError(Exception): + """Cancellation observed before entering a publication boundary.""" + + +@contextmanager +def heavy_io(check_cancel, waiting=None): + """Share one cancellable full-source I/O permit across task implementations.""" + notified = False + while True: + check_cancel() + if _HEAVY_IO.acquire(timeout=0.05): + break + if waiting is not None and not notified: + waiting() + notified = True + try: + check_cancel() + yield + finally: + _HEAVY_IO.release() + + +@dataclass(frozen=True) +class TaskProgress: + stage: str + done: int | None = None + total: int | None = None + unit: str = '' + message: str = '' + + +@dataclass(frozen=True) +class TaskOutcome: + task_id: str + state: str + result: object = None + error: str = '' + + +@dataclass(frozen=True) +class TaskSpec: + key: str + title: str + worker: object + request: object + heavy: bool = True + + +def _immutable(value): + if value is None or isinstance(value, (str, bytes, int, float, bool, Path)): + return + if isinstance(value, (tuple, frozenset)): + for item in value: + _immutable(item) + return + if is_dataclass(value) and value.__dataclass_params__.frozen: + for field in fields(value): + _immutable(getattr(value, field.name)) + return + raise TypeError('Task inputs and results must be immutable values, not GUI/session objects.') + + +class StageETA: + """Smoothed per-stage estimates; clock injection makes timing deterministic.""" + + def __init__(self, clock=monotonic): + self.clock = clock + self.reset() + + def reset(self): + self.stage = None + self.started = self.last_time = self.last_done = self.rate = None + + def update(self, progress): + now = self.clock() + stage = (progress.stage, progress.unit, progress.total) + if stage != self.stage or ( + self.last_done is not None + and progress.done is not None + and progress.done < self.last_done + ): + self.reset() + self.stage, self.started = stage, now + if progress.done is None or progress.total is None or progress.total <= 0: + return None + if self.last_time is not None and now > self.last_time and progress.done > self.last_done: + rate = (progress.done - self.last_done) / (now - self.last_time) + self.rate = rate if self.rate is None else 0.25 * rate + 0.75 * self.rate + if self.last_done is None or progress.done > self.last_done: + self.last_time, self.last_done = now, progress.done + if now - self.started < 2 or not self.rate or progress.done < 1: + return None + return max(0, (progress.total - progress.done) / self.rate) + + +class TaskContext: + """Worker-side cancellation, latest-only progress, and publication state.""" + + def __init__(self, cancelled, lock, mailbox): + self.cancelled, self.lock, self.mailbox = cancelled, lock, mailbox + self.committing = False + + def check_cancel(self): + if not self.committing and self.cancelled.is_set(): + raise TaskCancelledError() + + def report(self, progress): + if not isinstance(progress, TaskProgress): + raise TypeError('Expected TaskProgress.') + _immutable(progress) + if not all(isinstance(v, str) for v in (progress.stage, progress.unit, progress.message)): + raise TypeError('Progress labels must be strings.') + if progress.done is not None and (type(progress.done) is not int or progress.done < 0): + raise ValueError('Progress done must be a nonnegative integer.') + if progress.total is not None and (type(progress.total) is not int or progress.total < 0): + raise ValueError('Progress total must be a nonnegative integer.') + with self.lock: + self.mailbox[0] = progress + + def commit(self): + """Enter a short noncancellable publication boundary after a final check.""" + with self.lock: + if self.cancelled.is_set(): + raise TaskCancelledError() + self.committing = True + self.report( + TaskProgress('Finalizing', message='Finishing; publication cannot be cancelled.') + ) + + +@dataclass +class _TaskRecord: + """Plain Python worker ownership, independent of the manager's Qt lifetime.""" + + task_id: str + context: TaskContext + outcome: TaskOutcome | None = None + + +class _ManagerLifetime: + """The destruction callback captures no QObject or bound Qt method.""" + + def __init__(self): + self.dead = False + self.record = None + + def destroy(self, *args): + self.dead = True + record = self.record + if record is not None: + with record.context.lock: + record.context.cancelled.set() + # QObject.destroyed runs on its GUI owner thread. Workers retain + # only the plain record, so releasing this wrapper here is safe. + _MANAGERS.pop(record.task_id, None) + + +def _run_task(spec, record): + """A worker never retains, calls, or releases a Qt wrapper.""" + context = record.context + try: + if spec.heavy: + context.report( + TaskProgress('Waiting', message='Waiting for other recording I/O to finish.') + ) + with heavy_io(context.check_cancel): + result = spec.worker(spec.request, context) + else: + context.check_cancel() + result = spec.worker(spec.request, context) + _immutable(result) + context.check_cancel() + outcome = TaskOutcome(record.task_id, 'succeeded', result=result) + except TaskCancelledError: + outcome = TaskOutcome(record.task_id, 'cancelled') + except BaseException as error: + outcome = TaskOutcome(record.task_id, 'failed', error=str(error)) + finally: + with _ACTIVE_LOCK: + _ACTIVE.discard(spec.key) + with context.lock: + record.outcome = outcome + + +class BackgroundTaskManager(QObject): + """One task per manager, no backlog, and process-wide key deduplication. + + Workers retain only plain Python state. The GUI polls bounded progress and + terminal mailboxes; it owns Qt cleanup even after the task owner detaches. + QObject destruction cancels work and releases manager ownership immediately. + """ + + progress = pyqtSignal(object) + finished = pyqtSignal(object) + state_changed = pyqtSignal(str) + + def __init__(self): + super().__init__() + self.state = 'idle' + self.task_id = None + self.spec = None + self._cancel = Event() + self._lock = Lock() + self._mailbox = [None] + self._detached = False + self._context = None + self._lifetime = _ManagerLifetime() + self.destroyed.connect(self._lifetime.destroy) + self._timer = QTimer(self) + self._timer.setInterval(250) + self._timer.timeout.connect(self._poll) + + @property + def busy(self): + return self.state in ('pending', 'running', 'cancelling', 'committing') + + def _set_state(self, state): + self.state = state + if not self._detached and not self._lifetime.dead: + self.state_changed.emit(state) + + def submit(self, spec): + if self.busy or self._detached or self._lifetime.dead: + raise ValueError('A background task is already active or its owner has closed.') + _immutable(spec.request) + with _ACTIVE_LOCK: + if spec.key in _ACTIVE: + raise ValueError('This background task is already running.') + _ACTIVE.add(spec.key) + self.spec, self.task_id = spec, uuid4().hex + self._cancel = Event() + self._mailbox = [None] + self._context = TaskContext(self._cancel, self._lock, self._mailbox) + record = _TaskRecord(self.task_id, self._context) + self._lifetime.record = record + _MANAGERS[self.task_id] = self + self._set_state('pending') + # A state observer may synchronously close/delete the manager. + if not self._lifetime.dead: + self._timer.start() + try: + Thread(target=_run_task, args=(spec, record), daemon=True).start() + except BaseException as error: + with _ACTIVE_LOCK: + _ACTIVE.discard(spec.key) + with record.context.lock: + record.outcome = TaskOutcome( + record.task_id, 'failed', error=f'Could not start background worker: {error}' + ) + return record.task_id + + def _present_progress(self, progress, context): + if progress is None or self._detached or self._lifetime.dead: + return + if context.committing: + self._set_state('committing') + elif self.state != 'cancelling': + self._set_state('running') + if not self._detached and not self._lifetime.dead: + self.progress.emit(progress) + + @pyqtSlot() + def _poll(self): + if self._lifetime.dead: + return + record = self._lifetime.record + if record is None: + return + with record.context.lock: + progress, record.context.mailbox[0] = record.context.mailbox[0], None + outcome, record.outcome = record.outcome, None + try: + self._present_progress(progress, record.context) + finally: + # Even a failing progress observer must not strand task ownership. + if outcome is not None: + self._terminal(outcome) + + def _terminal(self, outcome): + if outcome.task_id != self.task_id: + return + try: + if not self._lifetime.dead: + self._timer.stop() + self._set_state(outcome.state) + if not self._detached and not self._lifetime.dead: + self.finished.emit(outcome) + finally: + # A finished callback can submit a new task. Only release this run; + # its callback owns the new timer, mailbox, and registry entry. + _MANAGERS.pop(outcome.task_id, None) + + @property + def cancellation_requested(self): + """A late cancel preserves a committed artifact but stops a task pipeline.""" + return self._cancel.is_set() + + def cancel(self): + if self.busy: + with self._lock: + self._cancel.set() + committing = self._context.committing + self._set_state('committing' if committing else 'cancelling') + + def detach(self): + self._detached = True + self.cancel() + # Keep polling until terminal cleanup on the GUI thread. If Qt already + # deleted this manager, its destruction callback released ownership. + if not self.busy and not self._lifetime.dead: + self._timer.stop() diff --git a/phy/gui/tests/test_actions.py b/phy/gui/tests/test_actions.py index fece68c46..e3e28e6fe 100644 --- a/phy/gui/tests/test_actions.py +++ b/phy/gui/tests/test_actions.py @@ -325,6 +325,12 @@ def _check(args, expected): _check('1.', [1.0]) _check('10.', [10.0]) _check('10.0', [10.0]) + _check('-896', [-896]) + _check('-0.5', [-0.5]) + _check('1e-3', [0.001]) + _check('-8.96e2', [-896.0]) + _check('-1e-3', [-0.001]) + _check('label-with-hyphen', ['label-with-hyphen']) _check('0 1', [0, 1]) _check('0 1.', [0, 1.0]) @@ -332,9 +338,11 @@ def _check(args, expected): _check('0,1', [[0, 1]]) _check('0,10.', [[0, 10.0]]) + _check('1,-2,-0.5,1e-3', [[1, -2, -0.5, 0.001]]) _check('0. 1,10.', [0.0, [1, 10.0]]) _check('2-7', [[2, 3, 4, 5, 6, 7]]) + _check('+2-+7', [[2, 3, 4, 5, 6, 7]]) _check('2 3-5', [2, [3, 4, 5]]) _check('a b,c d,2 3-5', ['a', ['b', 'c'], ['d', 2], [3, 4, 5]]) diff --git a/phy/gui/tests/test_gui.py b/phy/gui/tests/test_gui.py index 812339213..d63b7e29a 100644 --- a/phy/gui/tests/test_gui.py +++ b/phy/gui/tests/test_gui.py @@ -76,6 +76,58 @@ class MyFigure: # ------------------------------------------------------------------------------ +def test_closed_notification_follows_accepted_close(qtbot, tmp_path): + gui = GUI(config_dir=tmp_path) + qtbot.addWidget(gui) + closed = [] + + @connect(event='close', sender=gui) + def reject(sender): + return False + + @connect(event='closed', sender=gui) + def accepted(sender): + assert sender._closed + closed.append(sender) + + try: + gui.show() + assert not gui.close() + assert not gui._closed and not closed + unconnect(reject) + assert gui.close() + assert closed == [gui] + gui.close() + assert closed == [gui] + finally: + unconnect(reject, accepted) + + +def test_closed_notification_survives_geometry_save_failure(qtbot, tmp_path, monkeypatch): + from PyQt5.QtGui import QCloseEvent + + gui = GUI(config_dir=tmp_path) + qtbot.addWidget(gui) + closed = [] + + @connect(event='closed', sender=gui) + def accepted(sender): + closed.append(sender) + + def fail(): + raise OSError('cannot save geometry') + + monkeypatch.setattr(gui, 'save_geometry_state', fail) + try: + with raises(OSError, match='cannot save geometry'): + gui.closeEvent(QCloseEvent()) + assert gui._closed and closed == [gui] + gui.closeEvent(QCloseEvent()) + assert closed == [gui] + finally: + unconnect(accepted) + + def test_gui_noapp(tempdir): if not QApplication.instance(): with raises(RuntimeError): # pragma: no cover diff --git a/phy/gui/tests/test_qt.py b/phy/gui/tests/test_qt.py index 7b058da61..bee94eafb 100644 --- a/phy/gui/tests/test_qt.py +++ b/phy/gui/tests/test_qt.py @@ -4,7 +4,11 @@ # Imports # ------------------------------------------------------------------------------ -from pytest import raises +import subprocess +import sys +from textwrap import dedent + +from pytest import mark, raises from ..qt import ( AsyncCaller, @@ -37,6 +41,35 @@ # ------------------------------------------------------------------------------ +@mark.parametrize('count', [256, 1024, 4096]) +def test_qt_exit_callbacks_can_replace_wrappers(count): + # PyQt's exit visitor must tolerate callbacks that delete/create wrappers. + # A subprocess is essential: the old SIP runtime crashes after Python tests + # have finished, so an in-process assertion cannot detect the regression. + code = dedent(f""" + from PyQt5.QtCore import QCoreApplication, QObject + + app = QCoreApplication([]) + retained = [QObject() for _ in range({count})] + trigger = QObject() + + def rebuild(*args): + retained.clear() + retained.extend(QObject() for _ in range({count * 2})) + print('rebuilt', len(retained), flush=True) + + trigger.destroyed.connect(rebuild) + """) + result = subprocess.run( + [sys.executable, '-X', 'faulthandler', '-c', code], + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, (result.returncode, result.stdout, result.stderr) + assert result.stdout.strip() == f'rebuilt {count * 2}' + + def test_require_qt_with_app(monkeypatch): calls = [] diff --git a/phy/gui/tests/test_task_widgets.py b/phy/gui/tests/test_task_widgets.py new file mode 100644 index 000000000..ad61d9d1c --- /dev/null +++ b/phy/gui/tests/test_task_widgets.py @@ -0,0 +1,104 @@ +"""Task presentation and cleanup tolerate chained runs and destroyed Qt owners.""" + +from threading import Event + +import pytest +from PyQt5 import sip + +from phy.gui.task_widgets import TaskWidget +from phy.gui.tasks import BackgroundTaskManager, TaskCancelledError, TaskProgress, TaskSpec + + +def test_completed_task_can_close_reopen_details_and_start_another_run(qtbot): + manager = BackgroundTaskManager() + widget = TaskWidget(manager) + qtbot.addWidget(widget) + started, release = Event(), Event() + + def worker(request, context): + context.report(TaskProgress('Reading rows', 1, 2, message='Rows checked')) + + def next_worker(request, context): + started.set() + assert release.wait(5) + + try: + manager.submit(TaskSpec('widget-first-run', 'First run', worker, None)) + qtbot.waitUntil(lambda: not manager.busy) + assert widget.label.text() == 'Done' + assert widget.bar.isHidden() + assert widget.cancel_button.isHidden() + assert widget.hide_button.text() == 'Close' + widget.hide_button.click() + assert widget.isHidden() + widget.show() + widget.details_button.click() + assert widget.details.isVisible() + assert 'Rows checked' in widget.log.toPlainText() + widget.details.close() + + widget.notice('Store created; finalization needs attention. See Details.') + assert 'needs attention' in widget.label.text() + assert widget.bar.isHidden() + manager.submit(TaskSpec('widget-next-run', 'Next run', next_worker, None)) + qtbot.waitUntil(started.is_set) + assert widget.label.text() == 'Next run' + assert widget.label.toolTip() == '' + assert not widget.bar.isHidden() + assert not widget.cancel_button.isHidden() + assert widget.cancel_button.isEnabled() + assert widget.hide_button.text() == 'Hide' + finally: + release.set() + qtbot.waitUntil(lambda: not manager.busy) + widget.dispose() + manager.detach() + + +@pytest.mark.parametrize('state', ['cancelled', 'failed']) +def test_unsuccessful_task_has_clear_terminal_controls_and_retains_error(qtbot, state): + manager = BackgroundTaskManager() + widget = TaskWidget(manager) + qtbot.addWidget(widget) + + def worker(request, context): + if state == 'cancelled': + raise TaskCancelledError() + raise ValueError('Could not read source') + + try: + manager.submit(TaskSpec('widget-unsuccessful', 'Reading source', worker, None)) + qtbot.waitUntil(lambda: not manager.busy) + assert manager.state == state + assert widget.label.text() == ('Cancelled' if state == 'cancelled' else 'Task failed') + assert widget.bar.isHidden() + assert widget.cancel_button.isHidden() + assert widget.hide_button.text() == 'Close' + if state == 'failed': + assert widget.estimate.text() == 'See Details' + assert 'Could not read source' in widget.log.toPlainText() + finally: + widget.dispose() + manager.detach() + + +@pytest.mark.parametrize('order', ['manager-first', 'widget-first', 'completed-manager-first']) +def test_dispose_is_safe_and_repeatable_after_qt_deletion(qtbot, order): + manager = BackgroundTaskManager() + widget = TaskWidget(manager) + if order == 'completed-manager-first': + manager.submit(TaskSpec('widget-complete', 'Complete', lambda r, c: None, None)) + qtbot.waitUntil(lambda: not manager.busy) + if order == 'widget-first': + sip.delete(widget) + else: + sip.delete(manager) + widget.dispose() + widget.dispose() + manager.detach() + assert widget._disposed + assert manager._detached + if not sip.isdeleted(widget): + widget.close() + if not sip.isdeleted(manager): + sip.delete(manager) diff --git a/phy/gui/tests/test_tasks.py b/phy/gui/tests/test_tasks.py new file mode 100644 index 000000000..c9754a021 --- /dev/null +++ b/phy/gui/tests/test_tasks.py @@ -0,0 +1,369 @@ +"""Task publication boundaries, bounded delivery, ETA and cancellation.""" + +from dataclasses import dataclass +from threading import Event, get_ident + +import pytest + +from phy.gui.tasks import BackgroundTaskManager, StageETA, TaskProgress, TaskSpec, heavy_io + + +@dataclass(frozen=True) +class Request: + value: int + + +def test_latest_progress_is_bounded_and_delivery_is_on_gui(qtbot): + owner = get_ident() + release, reported = Event(), Event() + manager = BackgroundTaskManager() + changes, outcomes = [], [] + manager.progress.connect(lambda p: changes.append((get_ident(), p))) + manager.finished.connect(lambda o: outcomes.append((get_ident(), o))) + + def worker(request, context): + assert get_ident() != owner + for n in range(20000): + context.report(TaskProgress('Counting', n, 20000, 'items')) + reported.set() + assert release.wait(5) + return request.value + + manager.submit(TaskSpec('count', 'Count', worker, Request(7))) + assert reported.wait(5) # GUI deliberately stalled while worker reports. + assert len(manager._mailbox) == 1 + assert not changes + release.set() + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0][0] == owner + assert outcomes[0][1].result == 7 + assert changes[-1][1].done == 19999 + assert all(thread == owner for thread, _ in changes) + + +def test_duplicate_task_and_precommit_cancel(qtbot): + manager, other = BackgroundTaskManager(), BackgroundTaskManager() + started, release = Event(), Event() + outcomes = [] + manager.finished.connect(outcomes.append) + + def worker(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + return None + + spec = TaskSpec('duplicate', 'Duplicate', worker, Request(1)) + manager.submit(spec) + assert started.wait(5) + with pytest.raises(ValueError, match='already'): + other.submit(spec) + manager.cancel() + release.set() + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0].state == 'cancelled' + + +def test_cancel_after_commit_preserves_success_and_detach_suppresses_callbacks(qtbot): + committed, release = Event(), Event() + manager = BackgroundTaskManager() + outcomes = [] + manager.finished.connect(outcomes.append) + + def worker(request, context): + context.commit() + committed.set() + assert release.wait(5) + context.check_cancel() # A published artifact cannot become cancellation. + return 'published' + + manager.submit(TaskSpec('commit', 'Commit', worker, Request(1))) + assert committed.wait(5) + manager.cancel() + release.set() + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0].state == 'succeeded' + assert outcomes[0].result == 'published' + # Detached owners receive no completion and never block shutdown. + committed.clear() + release.clear() + outcomes.clear() + manager.submit(TaskSpec('detach', 'Detach', worker, Request(1))) + assert committed.wait(5) + manager.detach() + release.set() + qtbot.waitUntil(lambda: not manager.busy) + assert not outcomes + + +def test_heavy_io_is_shared_and_waiting_task_can_cancel(qtbot): + manager = BackgroundTaskManager() + outcomes = [] + manager.finished.connect(outcomes.append) + entered = Event() + + def worker(request, context): + entered.set() + + with heavy_io(lambda: None): + manager.submit(TaskSpec('io', 'IO', worker, Request(1))) + manager.cancel() + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0].state == 'cancelled' + assert not entered.is_set() + + +def test_errors_and_mutable_requests(qtbot): + manager = BackgroundTaskManager() + with pytest.raises(TypeError, match='immutable'): + manager.submit(TaskSpec('mutable', 'Mutable', lambda r, c: None, {})) + outcomes = [] + manager.finished.connect(outcomes.append) + + def worker(request, context): + raise OSError('disk full') + + manager.submit(TaskSpec('error', 'Error', worker, Request(1))) + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0].state == 'failed' + assert outcomes[0].error == 'disk full' + + +def test_eta_resets_per_stage_and_uses_injected_clock(): + now = [0.0] + eta = StageETA(clock=lambda: now[0]) + assert eta.update(TaskProgress('Validate', 0, 100, 'bytes')) is None + now[0] = 1 + assert eta.update(TaskProgress('Validate', 10, 100, 'bytes')) is None + now[0] = 3 + assert eta.update(TaskProgress('Validate', 30, 100, 'bytes')) == 7 + now[0] = 4 + assert eta.update(TaskProgress('Build', 5, 100, 'rows')) is None + now[0] = 7 + assert eta.update(TaskProgress('Build', 20, 100, 'rows')) == 16 + assert eta.update(TaskProgress('Finalize')) is None + + +def test_worker_base_exception_and_startup_failure_are_terminal(qtbot, monkeypatch): + from phy.gui import tasks + + manager = BackgroundTaskManager() + outcomes = [] + manager.finished.connect(outcomes.append) + + def exit_worker(request, context): + raise SystemExit('worker exit') + + manager.submit(TaskSpec('exit', 'Exit', exit_worker, Request(1))) + qtbot.waitUntil(lambda: len(outcomes) == 1) + assert outcomes[0].state == 'failed' + assert not manager.busy + + def fail_start(self): + raise RuntimeError('no thread available') + + monkeypatch.setattr(tasks.Thread, 'start', fail_start) + manager.submit(TaskSpec('startup', 'Startup', exit_worker, Request(1))) + qtbot.waitUntil(lambda: len(outcomes) == 2) + assert outcomes[-1].state == 'failed' + assert not manager.busy + assert 'startup' not in tasks._ACTIVE + assert manager.task_id not in tasks._MANAGERS + + +def test_detached_manager_lives_until_gui_terminal_delivery(qtbot): + import gc + import weakref + + from phy.gui import tasks + + started, release = Event(), Event() + manager = BackgroundTaskManager() + + def worker(request, context): + started.set() + assert release.wait(5) + context.check_cancel() + + task_id = manager.submit(TaskSpec('lifetime', 'Lifetime', worker, Request(1))) + assert started.wait(5) + reference = weakref.ref(manager) + manager.detach() + del manager + gc.collect() + assert reference() is not None + release.set() + qtbot.waitUntil(lambda: task_id not in tasks._MANAGERS) + gc.collect() + assert task_id not in tasks._MANAGERS + + +def test_cancel_wins_before_commit_and_progress_types_are_checked(qtbot): + started, release = Event(), Event() + manager = BackgroundTaskManager() + outcomes = [] + manager.finished.connect(outcomes.append) + published = [] + + def worker(request, context): + with pytest.raises(ValueError): + context.report(TaskProgress('Bad', -1, 100)) + with pytest.raises(TypeError): + context.report(TaskProgress('Bad', message=[])) + started.set() + assert release.wait(5) + context.commit() + published.append(True) + + manager.submit(TaskSpec('cancel-boundary', 'Cancel boundary', worker, Request(1))) + assert started.wait(5) + manager.cancel() + release.set() + qtbot.waitUntil(lambda: bool(outcomes)) + assert outcomes[0].state == 'cancelled' + assert not published + + +def test_eta_stalls_contribute_to_next_rate_sample(): + now = [0.0] + eta = StageETA(clock=lambda: now[0]) + eta.update(TaskProgress('Scan', 0, 100)) + now[0] = 1 + eta.update(TaskProgress('Scan', 10, 100)) + now[0] = 10 + eta.update(TaskProgress('Scan', 10, 100)) + now[0] = 19 + eta.update(TaskProgress('Scan', 10, 100)) + now[0] = 20 + remaining = eta.update(TaskProgress('Scan', 20, 100)) + assert remaining > 8 # The 19-second stall must lower the 10 units/s rate. + + +def test_finished_callback_can_chain_task_without_losing_terminal_poll(qtbot): + from phy.gui import tasks + + manager = BackgroundTaskManager() + outcomes, ids = [], [] + + def finished(outcome): + outcomes.append(outcome) + if len(outcomes) == 1: + ids.append(manager.submit(TaskSpec('chain-2', 'Second', lambda r, c: 2, None))) + + manager.finished.connect(finished) + ids.append(manager.submit(TaskSpec('chain-1', 'First', lambda r, c: 1, None))) + qtbot.waitUntil(lambda: len(outcomes) == 2) + assert [o.result for o in outcomes] == [1, 2] + assert not manager.busy + assert all(task not in tasks._MANAGERS for task in ids) + assert not manager._timer.isActive() + + +@pytest.mark.parametrize('delete_when', ['pending', 'running', 'succeeded']) +def test_state_observer_can_delete_manager_without_late_qt_access(qtbot, delete_when): + from PyQt5 import sip + + from phy.gui import tasks + + manager = BackgroundTaskManager() + started, release = Event(), Event() + + def worker(request, context): + context.report(TaskProgress('Working', 1, 2)) + started.set() + assert release.wait(3) + context.check_cancel() + return 1 + + def state_changed(state): + if state == delete_when: + sip.delete(manager) + + manager.state_changed.connect(state_changed) + task = manager.submit(TaskSpec('delete-state-' + delete_when, 'Delete observer', worker, None)) + record = manager._lifetime.record + if delete_when == 'running': + assert started.wait(3) + qtbot.waitUntil(lambda: sip.isdeleted(manager)) + release.set() + qtbot.waitUntil(lambda: task not in tasks._MANAGERS) + qtbot.waitUntil(lambda: manager.spec.key not in tasks._ACTIVE) + assert sip.isdeleted(manager) + assert manager._lifetime.dead + assert record.context.cancelled.is_set() + + +def test_terminal_registry_released_even_if_state_presentation_fails(qtbot, monkeypatch): + from phy.gui import tasks + + manager = BackgroundTaskManager() + manager.task_id = 'raising-terminal' + tasks._MANAGERS[manager.task_id] = manager + + def fail(state): + raise RuntimeError('observer failed') + + monkeypatch.setattr(manager, '_set_state', fail) + with pytest.raises(RuntimeError, match='observer failed'): + manager._terminal(tasks.TaskOutcome(manager.task_id, 'succeeded')) + assert manager.task_id not in tasks._MANAGERS + + +@pytest.mark.parametrize('committing', [False, True]) +def test_deleted_manager_worker_finishes_without_qt_ownership_in_subprocess(tmp_path, committing): + import subprocess + import sys + + script = r""" +import gc +import threading +import time +import weakref +from PyQt5 import sip +from phy.gui.qt import create_app +from phy.gui.tasks import BackgroundTaskManager, TaskSpec, _ACTIVE, _MANAGERS +app = create_app() +errors=[] +threading.excepthook = lambda arg: errors.append(str(arg.exc_value)) +started, release=threading.Event(), threading.Event() +committing = COMMITTING + +def worker(request, context): + if committing: + context.commit() + started.set() + assert release.wait(3) + context.check_cancel() + return 123 + +manager=BackgroundTaskManager() +task=manager.submit(TaskSpec('destroy-worker', 'Destroy worker', worker, None, heavy=False)) +assert started.wait(3) +record=manager._lifetime.record +reference=weakref.ref(manager) +sip.delete(manager) +manager.detach() +assert task not in _MANAGERS +assert record.context.cancelled.is_set() +del manager +gc.collect() +assert reference() is None, 'worker retains the deleted Qt manager' +release.set() +end=time.monotonic()+3 +while record.outcome is None and time.monotonic() viewport.bottom(): + return False + # A Cocoa overlay scrollbar lies *inside* the viewport: containment + # alone passes even while it hides the lower half of the final row. + horizontal = view.horizontalScrollBar() + if horizontal.isVisible(): + position = view.viewport().mapFromGlobal(horizontal.mapToGlobal(QPoint())) + scrollbar_rect = horizontal.rect().translated(position) + last.setLeft(viewport.left()) + last.setRight(viewport.right()) + return not last.intersects(scrollbar_rect) + return True + + for width, height in [(350, 250), (850, 300), (350, 267)]: + table.resize(width, height) + for column in range(3): + view.setColumnWidth(column, 180) + for text, order in [('', 'asc'), ('id >= 600', 'desc')]: + table.filter(text) + table.sort_by('id', order) + qtbot.waitUntil(last_row_is_readable) + assert view.horizontalScrollBar().isVisible() == (width == 350) + + horizontal = view.horizontalScrollBar() + horizontal.setValue(0) + qtbot.mouseClick( + horizontal, Qt.LeftButton, pos=QPoint(horizontal.width() - 4, horizontal.height() // 2) + ) + assert horizontal.value() > 0 + + +def test_table_scrollbar_style_is_destroyed_without_owning_application_style(qtbot, qapp): + application_style = qapp.style() + table = Table(data=[{'id': 0}]) + scrollbar_style = table.table_view.horizontalScrollBar().style() + assert scrollbar_style is not application_style + sip.delete(table) + assert sip.isdeleted(scrollbar_style) + assert not sip.isdeleted(application_style) + # A second table still gets a usable native base style after the first dies. + other = Table(data=[{'id': 0}]) + qtbot.addWidget(other) + other.show() + assert not other.grab().isNull() + + def test_table_busy(qtbot, table): table.select([1, 2]) table.set_busy(True) diff --git a/phy/gui/widgets.py b/phy/gui/widgets.py index a013c114f..c2e414870 100644 --- a/phy/gui/widgets.py +++ b/phy/gui/widgets.py @@ -45,11 +45,13 @@ QLineEdit, QMimeData, QModelIndex, + QMouseEvent, QObject, QPainter, QPalette, QPlainTextEdit, QPoint, + QProxyStyle, QSize, QSortFilterProxyModel, QSpinBox, @@ -376,7 +378,8 @@ def headerData(self, section, orientation, role=Qt.DisplayRole): if role != Qt.DisplayRole: return None if orientation == Qt.Horizontal and 0 <= section < len(self._table.columns): - return self._table.columns[section] + column = self._table.columns[section] + return getattr(self._table, '_column_labels', {}).get(column, column) return section + 1 def data(self, index, role=Qt.DisplayRole): @@ -562,6 +565,15 @@ def _install_table_filter_focus_watcher(): app.installEventFilter(watcher) +class _TableScrollbarStyle(QProxyStyle): + """Reserve horizontal scrollbar space instead of covering the final table row.""" + + def pixelMetric(self, metric, option=None, widget=None): + if metric == QStyle.PM_ScrollView_ScrollBarOverlap: + return 0 + return super().pixelMetric(metric, option, widget) + + class _TableView(QTableView): """QTableView adapter for cluster-ID-only drag-and-drop intents.""" @@ -826,6 +838,14 @@ def __init__( self.table_view.setModel(self._proxy) self.table_view.setItemDelegate(_TableItemDelegate(self)) self._apply_dark_style() + # Cocoa's transient scrollbar otherwise covers the bottom of the last + # row even at maximum scroll. Keep its native appearance and let Qt + # reserve the space. A default proxy owns its own base style; passing + # QApplication.style() would incorrectly transfer the shared style. + self._horizontal_scrollbar_style = _TableScrollbarStyle() + scrollbar = self.table_view.horizontalScrollBar() + self._horizontal_scrollbar_style.setParent(scrollbar) + scrollbar.setStyle(self._horizontal_scrollbar_style) self._init_table(columns=columns, value_names=value_names, data=data, sort=sort) _install_table_filter_focus_watcher() @@ -959,7 +979,11 @@ def eventFilter(self, obj, event): if obj is self.table_view.viewport() and event.type() == QEvent.Resize: if self._interaction_overlay is not None: self._interaction_overlay.setGeometry(self.table_view.viewport().geometry()) - if obj is self.table_view.viewport() and event.type() == QEvent.MouseMove: + if ( + obj is self.table_view.viewport() + and event.type() == QEvent.MouseMove + and isinstance(event, QMouseEvent) + ): index = self.table_view.indexAt(event.pos()) row_id = self._visible_ids()[index.row()] if index.isValid() else None self._set_hovered_row(row_id) @@ -980,6 +1004,9 @@ def eventFilter(self, obj, event): if ( obj is self.table_view.viewport() and event.type() == QEvent.MouseButtonPress + # Event type numbers do not guarantee the Python wrapper's API. + # Context-menu or generic events must never reach mouse-only calls. + and isinstance(event, QMouseEvent) and event.button() == Qt.RightButton ): # Transfer is deliberately bound only to an unmodified secondary click. diff --git a/pyproject.toml b/pyproject.toml index 9a08579f8..4315761ea 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,6 +38,7 @@ dependencies = [ "pillow", "pip", "PyQt5>=5.15.11,<5.16", + "PyQt5-sip>=12.20.1,<13", "pyopengl>=3.1.9", "qtconsole", "requests", diff --git a/scripts/tests/test_profile_bounded_gui.py b/scripts/tests/test_profile_bounded_gui.py new file mode 100644 index 000000000..c3bd8d969 --- /dev/null +++ b/scripts/tests/test_profile_bounded_gui.py @@ -0,0 +1,97 @@ +"""Guard the standalone GUI profiler's input boundaries without opening Qt.""" + +import importlib.util +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / 'tools' / 'profile_bounded_gui.py' +SPEC = importlib.util.spec_from_file_location('profile_bounded_gui', SCRIPT) +profiler = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(profiler) + + +def arguments(tmp_path): + source = tmp_path / 'input' + source.mkdir() + (source / '_phy_curation_manifest.json').write_text('{}') + return SimpleNamespace( + bounded=source, + output=tmp_path / 'output', + repeats=1, + merges=0, + events=None, + max_copy_bytes=1024, + timeout=1, + merge_undo=False, + profile=False, + ) + + +@pytest.mark.parametrize('location', ['input', 'input/nested', '.']) +def test_nested_output_rejected_before_creation(tmp_path, location): + args = arguments(tmp_path) + args.output = tmp_path / location + with pytest.raises(ValueError, match='non-nested'): + profiler.run(args) + assert sorted(p.name for p in args.bounded.iterdir()) == ['_phy_curation_manifest.json'] + + +def test_copy_budget_and_symlinks_rejected_before_output(tmp_path): + args = arguments(tmp_path) + (args.bounded / 'large').write_bytes(b'x' * 1024) + with pytest.raises(ValueError, match='max-copy-bytes'): + profiler.run(args) + assert not args.output.exists() + (args.bounded / 'large').unlink() + (args.bounded / 'alias').symlink_to(args.bounded / '_phy_curation_manifest.json') + with pytest.raises(ValueError, match='Symbolic links'): + profiler.run(args) + assert not args.output.exists() + + +def test_failed_display_still_reports_unchanged_source(tmp_path, monkeypatch): + args = arguments(tmp_path) + cache = args.bounded / '.phy' + cache.mkdir() + (cache / 'state.json').write_text('{"external": "/not/a/profiling/input"}') + files, _ = profiler._inventory(args.bounded, args.max_copy_bytes) + before = profiler._hashes(args.bounded, files) + + def fail_display(*a, **kw): + raise OSError('test display failure') + + monkeypatch.setattr( + profiler.subprocess, + 'check_output', + lambda *a, **kw: 'test-revision' if kw.get('text') else b'test-revision', + ) + monkeypatch.setattr(profiler.subprocess, 'Popen', fail_display) + with pytest.raises(OSError, match='test display failure'): + profiler.run(args) + report = json.loads((args.output / 'result.json').read_text()) + assert report['status'] == 'failed' + assert report['source_unchanged'] + assert report['source_hashes_before'] == report['source_hashes_after'] == before + assert report['omitted_local_cache_files'] == 1 + assert not (args.output / 'working-package' / '.phy').exists() + assert (args.output / 'working-package' / '_phy_curation_manifest.json').read_text() == '{}' + + +def test_seed_clears_every_membership_metadata_field(tmp_path): + from phy.apps.large_recording.curation import BoundedSession + from phy.apps.large_recording.prepare import prepare_large + from phy.apps.large_recording.tests.test_adapter import make_gui_sorting + + params = make_gui_sorting(tmp_path / 'source') + (params.parent / 'cluster_snr.tsv').write_text( + 'cluster_id\tsnr\n0\t10\n1\t20\n2\t30\n99\t40\n' + ) + bounded = prepare_large(params, tmp_path / 'bounded', window_seconds=20, stratum_seconds=20) + profiler._seed(bounded, 3, 1) + with BoundedSession(bounded) as session: + target = session.events[0]['target'] + assert session.metadata['snr'][target] is None + assert len(session.events) == 3 diff --git a/tools/benchmark_long_recording.py b/tools/benchmark_long_recording.py new file mode 100644 index 000000000..b6bfabeef --- /dev/null +++ b/tools/benchmark_long_recording.py @@ -0,0 +1,398 @@ +"""Reproducible, file-backed capacity benchmark for long-recording services. + +Run from a development environment, for example:: + + uv run python tools/benchmark_long_recording.py --spikes 1000000 + +The benchmark creates synthetic Phy arrays without raw traces, times preparation +and replay in separate child processes, and checks replay against an independent +streamed oracle. It is intentionally capped at two million source spikes. +""" + +import argparse +import json +import os +import platform +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +import numpy as np + +REPOSITORY = Path(__file__).resolve().parents[1] +if str(REPOSITORY) not in sys.path: + sys.path.insert(0, str(REPOSITORY)) + + +def _file_bytes(path): + path = Path(path) + return sum(item.stat().st_size for item in path.rglob('*') if item.is_file()) + + +def _make_source(path, spikes, units, duration_hours, batch_size): + """Write canonical arrays in bounded chunks, without allocating full vectors.""" + path.mkdir(parents=True) + duration_seconds = duration_hours * 3600 + sample_rate = 30_000 + num_samples = round(duration_seconds * sample_rate) + if num_samples <= 0 or num_samples > np.iinfo(np.int64).max: + raise ValueError('duration-hours produces an invalid int64 sample axis.') + + arrays = { + 'spike_times.npy': np.lib.format.open_memmap( + path / 'spike_times.npy', mode='w+', dtype=np.int64, shape=(spikes,) + ), + 'spike_clusters.npy': np.lib.format.open_memmap( + path / 'spike_clusters.npy', mode='w+', dtype=np.int32, shape=(spikes,) + ), + 'spike_templates.npy': np.lib.format.open_memmap( + path / 'spike_templates.npy', mode='w+', dtype=np.int32, shape=(spikes,) + ), + } + for start in range(0, spikes, batch_size): + stop = min(start + batch_size, spikes) + rows = np.arange(start, stop, dtype=np.int64) + arrays['spike_times.npy'][start:stop] = rows * (num_samples - 1) // spikes + assignments = (rows % units).astype(np.int32) + arrays['spike_clusters.npy'][start:stop] = assignments + arrays['spike_templates.npy'][start:stop] = assignments + for array in arrays.values(): + array.flush() + array._mmap.close() + + templates = np.lib.format.open_memmap( + path / 'templates.npy', mode='w+', dtype=np.float32, shape=(units, 4, 2) + ) + templates[:] = 0 + templates.flush() + templates._mmap.close() + np.save(path / 'channel_map.npy', np.array([0, 1], dtype=np.int32)) + np.save(path / 'channel_positions.npy', np.array([[0.0, 0.0], [20.0, 0.0]], dtype=np.float32)) + (path / 'params.py').write_text( + f'sample_rate = {sample_rate}.0\n' + f'num_samples = {num_samples}\n' + 'n_channels_dat = 2\n' + "dtype = 'int16'\n" + 'dat_path = None\n', + encoding='utf-8', + ) + return duration_seconds + + +def _peak_rss_bytes(): + """Return process peak RSS, or an explicit unavailable result.""" + if os.name != 'nt': + try: + import resource + + value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + # Linux and the BSDs report KiB; macOS reports bytes. + return int(value if sys.platform == 'darwin' else value * 1024), 'resource.ru_maxrss' + except (ImportError, AttributeError, OSError): + pass + + try: + import psutil + except ImportError: + return None, 'unavailable (install psutil for sampled peak RSS on Windows)' + + process = psutil.Process() + peak = [process.memory_info().rss] + stopped = threading.Event() + + def sample(): + while not stopped.wait(0.02): + try: + peak[0] = max(peak[0], process.memory_info().rss) + except psutil.Error: + return + + sampler = threading.Thread(target=sample, daemon=True) + sampler.start() + return _SampledRSS(stopped, sampler, peak) + + +class _SampledRSS: + def __init__(self, stopped, sampler, peak): + self.stopped = stopped + self.sampler = sampler + self.peak = peak + + def finish(self): + self.stopped.set() + self.sampler.join() + return int(self.peak[0]), 'psutil sampled every 20 ms' + + +def _measure_rss_start(): + value = _peak_rss_bytes() + return value if isinstance(value, _SampledRSS) else value + + +def _rss_result(handle): + return handle.finish() if isinstance(handle, _SampledRSS) else handle + + +def _phase_prepare(args): + from phy.apps.large_recording.prepare import prepare_large + + rss = _measure_rss_start() + started = time.perf_counter() + bounded = prepare_large( + args.params, + args.bounded_path, + duration_seconds=args.duration_seconds, + max_spikes=args.max_spikes, + max_bytes=args.max_bytes, + window_seconds=args.window_seconds, + stratum_seconds=args.stratum_seconds, + seed=args.seed, + batch_size=args.batch_size, + bin_seconds=args.bin_seconds, + ) + elapsed = time.perf_counter() - started + peak, method = _rss_result(rss) + print( + json.dumps( + { + 'phase': 'prepare', + 'wall_seconds': elapsed, + 'peak_rss_bytes': peak, + 'peak_rss_method': method, + 'bounded_path': str(bounded), + } + ) + ) + + +def _phase_curate(args): + from phy.apps.large_recording.curation import BoundedSession + + session = BoundedSession(args.bounded_path) + try: + if 0 not in session.unit_ids or 1 not in session.unit_ids: + raise ValueError('Synthetic source must contain units 0 and 1.') + session.record_merge([0, 1], session.next_cluster_id) + session.save() + finally: + session.close() + print(json.dumps({'phase': 'curate', 'saved': True})) + + +def _phase_replay(args): + from phy.apps.large_recording.replay import apply_curation + + rss = _measure_rss_start() + started = time.perf_counter() + output = apply_curation( + args.params, args.bounded_path, args.curated_path, batch_size=args.batch_size + ) + elapsed = time.perf_counter() - started + peak, method = _rss_result(rss) + print( + json.dumps( + { + 'phase': 'replay', + 'wall_seconds': elapsed, + 'peak_rss_bytes': peak, + 'peak_rss_method': method, + 'curated_path': str(output), + } + ) + ) + + +def _oracle(source_path, curated_path, spikes, units, batch_size): + """Independent streamed oracle for the benchmark's one known merge.""" + source = np.load(source_path / 'spike_clusters.npy', mmap_mode='r', allow_pickle=False) + output = np.load(curated_path / 'spike_clusters.npy', mmap_mode='r', allow_pickle=False) + expected_target = units + checked = 0 + matches = source.shape == output.shape == (spikes,) + for start in range(0, spikes, batch_size): + stop = min(start + batch_size, spikes) + expected = np.array(source[start:stop], copy=True) + expected[(expected == 0) | (expected == 1)] = expected_target + matches &= np.array_equal(expected, output[start:stop]) + checked += stop - start + source._mmap.close() + output._mmap.close() + return {'matches': bool(matches), 'rows_checked': checked, 'merge_target': expected_target} + + +def _run_phase( + script, + phase, + params, + bounded, + curated, + duration_seconds, + max_spikes, + max_bytes, + window_seconds, + stratum_seconds, + seed, + batch_size, + bin_seconds, +): + command = [ + sys.executable, + str(script), + '--_phase', + phase, + '--params', + str(params), + '--bounded-path', + str(bounded), + '--curated-path', + str(curated), + '--duration-seconds', + str(duration_seconds), + '--max-spikes', + str(max_spikes), + '--max-bytes', + str(max_bytes), + '--window-seconds', + str(window_seconds), + '--stratum-seconds', + str(stratum_seconds), + '--seed', + str(seed), + '--batch-size', + str(batch_size), + '--bin-seconds', + str(bin_seconds), + ] + try: + completed = subprocess.run( + command, cwd=REPOSITORY, check=True, capture_output=True, text=True + ) + except subprocess.CalledProcessError as error: + raise RuntimeError(error.stderr.strip() or error.stdout.strip()) from error + return json.loads(completed.stdout.strip().splitlines()[-1]) + + +def _run(args): + if args.spikes <= 0 or args.spikes > 2_000_000: + raise ValueError('--spikes must be between 1 and 2,000,000.') + if args.units < 2 or args.units > args.spikes: + raise ValueError('--units must be at least 2 and no greater than --spikes.') + if args.batch_size <= 0 or args.duration_hours <= 0: + raise ValueError('--batch-size and --duration-hours must be positive.') + + temporary = None + if args.output_dir: + root = Path(args.output_dir).resolve() + root.mkdir(parents=True, exist_ok=True) + else: + temporary = tempfile.TemporaryDirectory(prefix='phy-long-recording-benchmark-') + root = Path(temporary.name) + source_dir, bounded_dir, curated_dir = ( + root / name for name in ('source', 'bounded', 'curated') + ) + duration_seconds = _make_source( + source_dir, args.spikes, args.units, args.duration_hours, args.batch_size + ) + source_bytes = _file_bytes(source_dir) + common = { + 'params': source_dir / 'params.py', + 'bounded': bounded_dir, + 'curated': curated_dir, + 'duration_seconds': duration_seconds, + 'max_spikes': args.max_spikes, + 'max_bytes': args.max_bytes, + 'window_seconds': args.window_seconds, + 'stratum_seconds': args.stratum_seconds, + 'seed': args.seed, + 'batch_size': args.batch_size, + 'bin_seconds': args.bin_seconds, + } + prepare = _run_phase(Path(__file__).resolve(), 'prepare', **common) + _run_phase(Path(__file__).resolve(), 'curate', **common) + replay = _run_phase(Path(__file__).resolve(), 'replay', **common) + oracle = _oracle(source_dir, curated_dir, args.spikes, args.units, args.batch_size) + if not oracle['matches']: + raise RuntimeError('Independent streamed replay oracle did not match curated assignments.') + + result = { + 'benchmark': 'phy_long_recording_v1', + 'machine': { + 'platform': platform.platform(), + 'machine': platform.machine(), + 'processor': platform.processor(), + 'python': platform.python_version(), + 'numpy': np.__version__, + 'cpu_count': os.cpu_count(), + }, + 'parameters': { + 'spikes': args.spikes, + 'units': args.units, + 'duration_hours': args.duration_hours, + 'sample_rate_hz': 30000, + 'batch_size': args.batch_size, + 'max_spikes': args.max_spikes, + 'max_bytes': args.max_bytes, + 'window_seconds': args.window_seconds, + 'stratum_seconds': args.stratum_seconds, + 'seed': args.seed, + 'bin_seconds': args.bin_seconds, + }, + 'source_file_bytes': source_bytes, + 'bounded_file_bytes': _file_bytes(bounded_dir), + 'curated_file_bytes': _file_bytes(curated_dir), + 'bounded_spikes': int( + json.loads((bounded_dir / '_phy_curation_manifest.json').read_text(encoding='utf-8'))[ + 'bounded_num_spikes' + ] + ), + 'preparation': prepare, + 'replay': replay, + 'independent_streamed_replay_oracle': oracle, + 'output_dir': str(root), + 'output_dir_retained': temporary is None, + } + print(json.dumps(result, indent=2, sort_keys=True)) + if temporary is not None: + temporary.cleanup() + + +def _parser(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--spikes', type=int, default=1_000_000) + parser.add_argument('--units', type=int, default=1000) + parser.add_argument('--duration-hours', type=float, default=1000) + parser.add_argument('--batch-size', type=int, default=100_000) + parser.add_argument('--max-spikes', type=int, default=100_000) + parser.add_argument('--max-bytes', type=int, default=536_870_912) + parser.add_argument('--window-seconds', type=float, default=30) + parser.add_argument('--stratum-seconds', type=float, default=3600) + parser.add_argument('--seed', type=int, default=0) + parser.add_argument('--bin-seconds', type=float, default=3600) + parser.add_argument('--output-dir', type=Path) + parser.add_argument( + '--_phase', choices=('prepare', 'curate', 'replay'), help=argparse.SUPPRESS + ) + parser.add_argument('--params', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--bounded-path', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--curated-path', type=Path, help=argparse.SUPPRESS) + parser.add_argument('--duration-seconds', type=float, help=argparse.SUPPRESS) + return parser + + +def main(): + args = _parser().parse_args() + if args._phase == 'prepare': + _phase_prepare(args) + elif args._phase == 'curate': + _phase_curate(args) + elif args._phase == 'replay': + _phase_replay(args) + else: + _run(args) + + +if __name__ == '__main__': + main() diff --git a/tools/benchmark_refractory.py b/tools/benchmark_refractory.py new file mode 100644 index 000000000..67892ae3c --- /dev/null +++ b/tools/benchmark_refractory.py @@ -0,0 +1,169 @@ +"""Measure exact RP paths on a disposable bounded-package COPY. + +Run each mode in a fresh process. Fresh-process timings include authentication, +with uncontrolled OS cache state; repeated queries measure the in-process cache. +Builders attach disposable artifacts but never save curation. Source mode bypasses +all prepared RP artifacts. This tool never drops OS caches. +""" + +import argparse +import hashlib +import json +import sys +from pathlib import Path +from time import perf_counter + +import numpy as np + +from phy.apps.large_recording.live_summaries import LiveSummaryEngine +from phy.apps.large_recording.refractory_engine import RefractoryEngine +from phy.apps.large_recording.refractory_store import build_refractory_summaries +from phy.apps.large_recording.summary_store import SummaryStore, build_summary_store + + +def peak_rss(): + import resource + + value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return int(value if sys.platform == 'darwin' else value * 1024) + + +def fingerprint(result): + digest = hashlib.sha256() + for key, value in sorted(result.items()): + digest.update(key.encode()) + if isinstance(value, np.ndarray): + digest.update(value.dtype.str.encode()) + digest.update(value.tobytes()) + else: + digest.update(json.dumps(value, sort_keys=True).encode()) + return digest.hexdigest() + + +def run(args): + report = {'mode': args.mode, 'os_cache': 'uncontrolled', 'queries': []} + hashed = [0] + + def progress(phase, done, total): + if phase == 'validating source': + hashed[0] = max(hashed[0], done) + + started = perf_counter() + if args.mode == 'build-counters': + output = build_refractory_summaries( + args.package, source_dir=args.source_dir, progress=progress + ) + elif args.mode == 'build-timestamps': + output = build_summary_store( + args.package, + args.store, + source_dir=args.source_dir, + timestamps=True, + progress=progress, + ) + else: + output = None + with LiveSummaryEngine(args.package, source_dir=args.source_dir) as source: + if args.mode == 'timestamps': + from phy.apps.large_recording import refractory_store + + refractory_store._counters = lambda *a, **kw: {} + engine = RefractoryEngine(source, root_bytes=0) + units = args.units + original = {'kind': 'source', 'unit': units[0]} + merged = {'kind': 'union', 'parts': [{'kind': 'source', 'unit': u} for u in units]} + split = { + 'kind': 'split', + 'parent': merged, + 'selected': True, + 'predicate': { + 'attribute': 'amplitudes.npy', + 'operator': '>=', + 'threshold': args.threshold, + 'nonfinite': 'keep', + }, + } + queries = [('original', original)] + if args.mode != 'counters': + queries += [('merge', merged), ('amplitude-child', split)] + if args.membership != 'all': + queries = [(label, e) for label, e in queries if label == args.membership] + if args.mode != 'source': + + def no_source(*a, **kw): + raise AssertionError('Prepared benchmark accessed original source.') + + source._open = source._unchanged = no_source + read_bytes = [0] + batches = SummaryStore.batches + + def measured_batches(self, *a, **kw): + for rows in batches(self, *a, **kw): + read_bytes[0] += rows.nbytes + yield rows + + SummaryStore.batches = measured_batches + for label, expression in queries: + for repetition in range(2): + before = perf_counter() + read_bytes[0] = 0 + resolve = engine._resolve_source if args.mode == 'source' else engine.resolve + value = resolve({0: expression}, progress=progress)[0] + report['queries'].append( + { + 'membership': label, + 'repeat': repetition, + 'seconds': perf_counter() - before, + 'path': engine.last_path, + 'timestamp_bytes': read_bytes[0], + 'fingerprint': fingerprint(value), + 'status': value['status'], + } + ) + if args.mode == 'timestamps': + cancelled = [False] + triggered = [None] + + def cancel_after_batch(*args): + cancelled[0] = True + triggered[0] = perf_counter() + + before = perf_counter() + # A fresh result engine forces reading; cancel after its first batch. + try: + RefractoryEngine(source).resolve( + {0: merged}, + cancel=lambda: cancelled[0], + progress=cancel_after_batch, + ) + except Exception as error: + from concurrent.futures import CancelledError + + if not isinstance(error, CancelledError): + raise + finished = perf_counter() + report['cancel_seconds'] = finished - triggered[0] + report['cancelled_request_seconds'] = finished - before + report.update( + seconds=perf_counter() - started, peak_rss_bytes=peak_rss(), source_hash_bytes=hashed[0] + ) + if output: + report['artifact_bytes'] = sum(p.stat().st_size for p in output.iterdir() if p.is_file()) + args.output.write_text(json.dumps(report, indent=2) + '\n') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + 'mode', choices=['build-counters', 'build-timestamps', 'source', 'counters', 'timestamps'] + ) + parser.add_argument('package', type=Path) + parser.add_argument('--store', type=Path) + parser.add_argument('--source-dir', type=Path) + parser.add_argument( + '--membership', choices=['all', 'original', 'merge', 'amplitude-child'], default='all' + ) + parser.add_argument('--units', type=int, nargs='+', default=[0, 1]) + parser.add_argument('--threshold', type=float, default=0) + parser.add_argument('--output', type=Path, required=True) + run(parser.parse_args()) diff --git a/tools/benchmark_summary_scenarios.py b/tools/benchmark_summary_scenarios.py new file mode 100644 index 000000000..4dfae5e9f --- /dev/null +++ b/tools/benchmark_summary_scenarios.py @@ -0,0 +1,395 @@ +"""Exact live-summary scaling benchmark; original source is read-only. + +The bounded package must be a fresh benchmark preparation/copy. Curation is +never saved. Derived result cache use/publication is disabled for all timings. +OS caches are uncontrolled: these are not cold-storage latency guarantees. +""" + +import argparse +import hashlib +import json +import os +import platform +import subprocess +import sys +from pathlib import Path +from time import perf_counter + +import numpy as np + +from phy.apps.large_recording.curation import BoundedSession, project_assignments +from phy.apps.large_recording.live_summaries import LiveSummaryEngine, membership_expressions +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.summary_store import ( + SummaryStore, + attach_summary_store, + build_summary_store, +) + + +def progress_logger(): + last = [None, 0.0] + + def progress(phase, done, total): + now = perf_counter() + if phase != last[0] or now - last[1] > 10 or done == total: + print(f'{phase}: {100 * done / max(1, total):.1f}% ({done:,}/{total:,})', flush=True) + last[:] = [phase, now] + + return progress + + +def no_cache(engine): + engine._cached = lambda key: None + engine._publish = lambda *args: None + return engine + + +def compare(engine, actual, expected): + for unit in expected: + for name, values in engine._flat(actual[unit]).items(): + target = engine._flat(expected[unit])[name] + if np.issubdtype(values.dtype, np.integer): + np.testing.assert_array_equal(values, target) + else: + np.testing.assert_allclose(values, target, rtol=1e-9, atol=1e-6) + + +def ancestors(e): + if e['kind'] == 'source': + return {e['unit']} + if e['kind'] == 'split': + return ancestors(e['parent']) + return set().union(*(ancestors(p) for p in e['parts'])) + + +def split(parent, children, threshold): + return { + 'operation': 'threshold_split', + 'parent': int(parent), + 'children': children, + 'predicate': { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': float(threshold), + 'nonfinite': 'keep', + }, + } + + +def run(args): + revision = subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip() + from phy.apps.large_recording import curation, live_summaries, source, summary_store + + components = { + Path(module.__file__).name: hash_file(module.__file__) + for module in (curation, live_summaries, source, summary_store) + } + if args.amplitude_index: + from phy.apps.large_recording import ( + range_build, + range_files, + range_index, + range_intervals, + range_math, + ) + + components.update( + { + Path(module.__file__).name: hash_file(module.__file__) + for module in (range_build, range_files, range_index, range_intervals, range_math) + } + ) + started = perf_counter() + if args.build_range_only: + from phy.apps.large_recording.range_build import build_amplitude_index + + build_amplitude_index(args.bounded, args.amplitude_index, progress=progress_logger()) + import resource + + rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + args.output.write_text( + json.dumps( + { + 'seconds': perf_counter() - started, + 'peak_rss_bytes': int(rss if sys.platform == 'darwin' else rss * 1024), + 'index_bytes': sum(p.stat().st_size for p in args.amplitude_index.iterdir()), + }, + indent=2, + ) + + '\n' + ) + return + if args.build_only: + build_summary_store(args.bounded, args.store, progress=progress_logger()) + try: + import resource + + rss = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + except ImportError: + rss = None + result = { + 'seconds': perf_counter() - started, + 'peak_rss_bytes': int(rss if sys.platform == 'darwin' else rss * 1024) + if rss is not None + else None, + 'store_bytes': sum(p.stat().st_size for p in args.store.iterdir()), + } + args.output.write_text(json.dumps(result, indent=2) + '\n') + return + if not args.store.exists(): + subprocess.run( + [ + sys.executable, + __file__, + '--bounded', + str(args.bounded), + '--store', + str(args.store), + '--output', + str(args.output.with_suffix('.build.json')), + '--build-only', + ], + check=True, + ) + attach_summary_store(args.bounded, args.store) + if args.amplitude_index: + if not args.amplitude_index.exists(): + subprocess.run( + [ + sys.executable, + __file__, + '--bounded', + str(args.bounded), + '--store', + str(args.store), + '--amplitude-index', + str(args.amplitude_index), + '--output', + str(args.output.with_suffix('.range-build.json')), + '--build-range-only', + ], + check=True, + ) + from phy.apps.large_recording.range_index import attach_amplitude_index + + attach_amplitude_index(args.bounded, args.amplitude_index) + before = {p.name: hash_file(p) for p in args.bounded.iterdir() if p.is_file()} + session = BoundedSession(args.bounded) + try: + base = session.events + if base: + raise ValueError('Use a fresh, uncurated bounded package.') + m = session.manifest + counts = {int(u): int(n) for u, n in zip(m['unit_ids'], m['counts']) if n > 0} + ordered = sorted(counts, key=lambda u: counts[u]) + median = ordered[len(ordered) // 2] + largest = ordered[-1] + middle = max(0, len(ordered) // 2 - 5) + typical = ordered[middle : middle + 10] + thresholds = {} + with LiveSummaryEngine(args.bounded) as engine, SummaryStore(engine) as store: + for unit in {median, largest, typical[len(typical) // 2]}: + sample = [] + total = 0 + for data in store.batches(unit, 1000000): + if total < 16384: + finite = data['amplitude'][np.isfinite(data['amplitude'])][: 16384 - total] + sample.append(finite) + total += len(finite) + values = np.concatenate(sample) + if len(values) < 2: + raise ValueError('No usable amplitude threshold sample.') + thresholds[unit] = [ + float(np.quantile(values, 0.25)), + float(np.quantile(values, 0.5)), + ] + next_id = max(m['unit_ids']) + 100 + recipes = [] + + def add(name, events, children): + expressions = membership_expressions(session.unit_ids, events) + recipes.append((name, events, {u: expressions[u] for u in children})) + + for name, unit in [('median_unit', median), ('largest_unit', largest)]: + children = [next_id, next_id + 1] + next_id += 100 + add(name, [split(unit, children, thresholds[unit][1])], children) + children = [next_id, next_id + 1] + grandchildren = [next_id + 2, next_id + 3] + next_id += 100 + add( + 'nested_split_median', + [ + split(median, children, thresholds[median][1]), + split(children[1], grandchildren, thresholds[median][0]), + ], + grandchildren, + ) + for name, parents, threshold in [ + ('merge_two_largest_then_split', ordered[-2:], thresholds[largest][1]), + ('merge_ten_typical_then_split', typical, thresholds[typical[len(typical) // 2]][1]), + ]: + merged = next_id + children = [next_id + 1, next_id + 2] + next_id += 100 + add( + name, + [ + {'operation': 'merge', 'parents': list(map(int, parents)), 'target': merged}, + split(merged, children, threshold), + ], + children, + ) + indexed = {} + reports = [] + with ( + LiveSummaryEngine(args.bounded) as binding_engine, + SummaryStore(binding_engine) as store, + ): + record_bytes = store.dtype.itemsize + # Each scenario gets a fresh engine. A second uncached request tests + # repeat reads, not a result-cache hit. No source fallback is accepted. + for name, events, expressions in recipes: + with no_cache(LiveSummaryEngine(args.bounded)) as engine: + + def forbid_source(*a, **kw): + raise AssertionError('Indexed request opened original source') + + engine._open = forbid_source + progress = [] + start = perf_counter() + result = engine.resolve( + expressions, progress=lambda *p, progress=progress: progress.append(p) + ) + first = perf_counter() - start + first_metrics = ( + dict(engine.range_index.last_metrics) if engine.range_index else None + ) + if args.amplitude_index and first_metrics is None: + raise AssertionError('Range benchmark used row fallback') + start = perf_counter() + repeat = engine.resolve(expressions) + second = perf_counter() - start + compare(engine, repeat, result) + indexed.update(result) + original = set().union(*(ancestors(e) for e in expressions.values())) + rows = sum(counts[u] for u in original) + report = { + 'scenario': name, + 'events': events, + 'original_units': sorted(original), + 'source_rows_read': 0 if first_metrics else rows, + 'original_rows_represented': rows, + 'payload_bytes_read': first_metrics['payload_bytes_read'] + if first_metrics + else rows * record_bytes, + 'first_range_metrics': first_metrics, + 'repeat_range_metrics': dict(engine.range_index.last_metrics) + if engine.range_index + else None, + 'first_seconds': first, + 'repeat_seconds': second, + 'counts': {str(u): int(v['counts'].sum()) for u, v in result.items()}, + } + reports.append(report) + print(json.dumps(report), flush=True) + expressions = {u: e for _, _, expr in recipes for u, e in expr.items()} + # One validated full-source scan computes all scenario expressions. + with no_cache(LiveSummaryEngine(args.bounded)) as engine: + engine._indexed = lambda *a: None + start = perf_counter() + baseline = engine.resolve(expressions, progress=progress_logger()) + full_seconds = perf_counter() - start + compare(engine, indexed, baseline) + # A separate sequential semantic replay is independent of the + # expression-mask resolver and traverses every original source row. + oracle = {u: engine._empty() for u in expressions} + total = m['num_spikes'] + progress = progress_logger() + start = perf_counter() + for first in range(0, total, 1000000): + stop = min(total, first + 1000000) + times = engine.arrays['spike_times.npy'][first:stop].reshape(-1) + assignments = engine.arrays['spike_clusters.npy'][first:stop].reshape(-1) + amplitude = engine.arrays['amplitudes.npy'][first:stop].reshape(-1) + scalars = {'amplitude': amplitude} + if 'depth' in engine.fields: + if 'spike_depths.npy' in engine.arrays: + scalars['depth'] = engine.arrays['spike_depths.npy'][first:stop].reshape( + -1 + ) + else: + axis = m['source']['identity']['acquisition']['depth_axis'] + scalars['depth'] = engine.arrays['spike_positions.npy'][first:stop, axis] + for name, events, targets in recipes: + projected = project_assignments( + assignments, events, {'amplitudes.npy': amplitude} + ) + for unit in targets: + selected = projected == unit + oracle[unit]['counts'] += np.histogram(times[selected], bins=engine.edges)[ + 0 + ] + for field, values in scalars.items(): + finite = selected & np.isfinite(values) + oracle[unit]['trend_counts'][field] += np.histogram( + times[finite], bins=engine.edges + )[0] + oracle[unit]['trend_sums'][field] += np.histogram( + times[finite], + bins=engine.edges, + weights=values[finite].astype(np.float64), + )[0] + progress('independent semantic replay', stop, total) + oracle_seconds = perf_counter() - start + engine._unchanged() + compare(engine, indexed, oracle) + after = {p.name: hash_file(p) for p in args.bounded.iterdir() if p.is_file()} + if before != after: + raise ValueError('Package files changed') + build_report = args.output.with_suffix('.build.json') + report = { + 'revision': revision, + 'component_sha256': components, + 'label': args.label, + 'source_spikes': m['num_spikes'], + 'duration_hours': m['duration_seconds'] / 3600, + 'native_bins': len(engine.edges) - 1, + 'source_units': len(m['unit_ids']), + 'source_dir': m['source']['path'], + 'cache_conditions': 'Uncontrolled OS page cache; no summary result-cache hits or publication. Indexed timings exclude GUI delivery.', + 'hardware': { + 'platform': platform.platform(), + 'ram_bytes': os.sysconf('SC_PHYS_PAGES') * os.sysconf('SC_PAGE_SIZE') + if hasattr(os, 'sysconf') + else None, + }, + 'build': json.loads(build_report.read_text()) if build_report.exists() else None, + 'range_build': json.loads(args.output.with_suffix('.range-build.json').read_text()) + if args.output.with_suffix('.range-build.json').exists() + else None, + 'build_note': 'Build cost may be from an earlier invocation; runtime component hashes identify this verification run.', + 'scenarios': reports, + 'combined_full_source_scan_seconds': full_seconds, + 'independent_replay_seconds': oracle_seconds, + 'independent_replay_rows': m['num_spikes'], + 'indexed_equals_full_scan_and_independent_replay': True, + 'bounded_files_unchanged': True, + } + args.output.write_text(json.dumps(report, indent=2) + '\n') + print('DONE', args.output, flush=True) + finally: + session.close() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bounded', required=True, type=Path) + parser.add_argument('--store', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--label', default='Unspecified engineering dataset') + parser.add_argument('--build-only', action='store_true') + parser.add_argument('--amplitude-index', type=Path) + parser.add_argument('--build-range-only', action='store_true') + run(parser.parse_args()) diff --git a/tools/benchmark_summary_store.py b/tools/benchmark_summary_store.py new file mode 100644 index 000000000..ebcdf21c4 --- /dev/null +++ b/tools/benchmark_summary_store.py @@ -0,0 +1,198 @@ +"""Compare exact unit-indexed summaries with a validated full-source scan. + +Run on a fresh COPY of a bounded package: this writes its disposable caches and +store reference. Does not save curation or alter original source arrays. Builds +run in a separate process so their peak RSS is measured independently. No cache +flushing is attempted; timings describe observed, uncontrolled OS cache state. +""" + +import argparse +import json +import subprocess +import sys +from pathlib import Path +from time import perf_counter + +import numpy as np + +from phy.apps.large_recording.curation import BoundedSession, project_assignments +from phy.apps.large_recording.live_summaries import LiveSummaryEngine, membership_expressions +from phy.apps.large_recording.source import hash_file +from phy.apps.large_recording.summary_store import attach_summary_store, build_summary_store + + +def peak_rss(): + try: + import resource + + value = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return int(value if sys.platform == 'darwin' else value * 1024) + except ImportError: + return None + + +class FullScanEngine(LiveSummaryEngine): + def _indexed(self, expressions, cancel, progress): + return None + + +def verify_replay(engine, events, expected): + """Independent cumulative assignment replay, without expression masks.""" + totals = {unit: engine._empty() for unit in expected} + required = {e['predicate']['attribute'] for e in events if e['operation'] == 'threshold_split'} + for start in range(0, engine.manifest['num_spikes'], 1000000): + stop = start + 1000000 + times = engine.arrays['spike_times.npy'][start:stop].reshape(-1) + attributes = {name: engine.arrays[name][start:stop].reshape(-1) for name in required} + assignments = project_assignments( + engine.arrays['spike_clusters.npy'][start:stop], events, attributes + ) + scalars = {} + for field in engine.fields: + if field == 'amplitude': + scalars[field] = engine.arrays['amplitudes.npy'][start:stop].reshape(-1) + elif 'spike_depths.npy' in engine.arrays: + scalars[field] = engine.arrays['spike_depths.npy'][start:stop].reshape(-1) + else: + axis = engine.manifest['source']['identity']['acquisition']['depth_axis'] + scalars[field] = engine.arrays['spike_positions.npy'][start:stop, axis] + for unit, summary in totals.items(): + selected = assignments == unit + summary['counts'] += np.histogram(times[selected], bins=engine.edges)[0] + for field, values in scalars.items(): + finite = selected & np.isfinite(values) + summary['trend_counts'][field] += np.histogram(times[finite], bins=engine.edges)[0] + summary['trend_sums'][field] += np.histogram( + times[finite], bins=engine.edges, weights=values[finite].astype(np.float64) + )[0] + engine._unchanged() + for unit in expected: + for name, actual in engine._flat(totals[unit]).items(): + target = engine._flat(expected[unit])[name] + if np.issubdtype(actual.dtype, np.integer): + np.testing.assert_array_equal(actual, target) + else: + np.testing.assert_allclose(actual, target, rtol=1e-9, atol=1e-6) + + +def run(args): + if args.build_only: + started = perf_counter() + build_summary_store(args.bounded, args.store) + result = { + 'seconds': perf_counter() - started, + 'peak_rss_bytes': peak_rss(), + 'store_bytes': sum(p.stat().st_size for p in args.store.iterdir()), + } + args.output.write_text(json.dumps(result, indent=2) + '\n') + return + before = {p.name: hash_file(p) for p in args.bounded.iterdir() if p.is_file()} + build_report = args.output.with_suffix('.build.json') + if not args.store.exists(): + subprocess.run( + [ + sys.executable, + __file__, + '--bounded', + str(args.bounded), + '--store', + str(args.store), + '--output', + str(build_report), + '--build-only', + ], + check=True, + ) + attach_summary_store(args.bounded, args.store) + session = BoundedSession(args.bounded) + try: + events = session.events + active = membership_expressions(session.unit_ids, events) + if args.unit not in active: + raise ValueError(f'Unit {args.unit} is not active.') + next_id = max(active) + 100 + operation = { + 'operation': 'threshold_split', + 'parent': args.unit, + 'children': [next_id, next_id + 1], + 'predicate': { + 'attribute': 'amplitudes.npy', + 'operator': '<', + 'threshold': args.threshold, + 'nonfinite': 'keep', + }, + } + expressions = membership_expressions(session.unit_ids, events + [operation]) + children = {u: expressions[u] for u in operation['children']} + results, timings, phases = {}, {}, {} + # Suppress result cache publication for fair repeated uncached jobs. + # Inputs and caches from existing curation are not modified. + for mode, engine_class in [('indexed', LiveSummaryEngine), ('full_scan', FullScanEngine)]: + with engine_class(args.bounded) as engine: + engine._cached = lambda key: None + engine._publish = lambda *a: None + phases[mode] = [] + + def progress(phase, done, total, mode=mode): + if not phases[mode] or phases[mode][-1][0] != phase: + phases[mode].append([phase, done, total]) + else: + phases[mode][-1] = [phase, done, total] + + started = perf_counter() + results[mode] = engine.resolve(children, progress=progress) + timings[mode] = perf_counter() - started + if mode == 'indexed' and not any( + p[0] == 'reading prepared unit summaries' for p in phases[mode] + ): + raise ValueError('Indexed benchmark did not use the acceleration store.') + if mode == 'full_scan': + verify_replay(engine, events + [operation], results['indexed']) + started = perf_counter() + engine.resolve(children) + timings[mode + '_repeat'] = perf_counter() - started + with LiveSummaryEngine(args.bounded) as engine: + for unit in children: + expected = engine._flat(results['full_scan'][unit]) + actual = engine._flat(results['indexed'][unit]) + for name in actual: + if np.issubdtype(actual[name].dtype, np.integer): + np.testing.assert_array_equal(actual[name], expected[name]) + else: + np.testing.assert_allclose( + actual[name], expected[name], rtol=1e-9, atol=1e-6 + ) + after = {p.name: hash_file(p) for p in args.bounded.iterdir() if p.is_file()} + if before != after: + raise ValueError('Bounded package files changed.') + report = { + 'revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), + 'dataset': args.dataset_label, + 'source_spikes': session.manifest['num_spikes'], + 'unit': args.unit, + 'threshold': args.threshold, + 'timings_seconds': timings, + 'phases': phases, + 'counts': {str(u): int(v['counts'].sum()) for u, v in results['indexed'].items()}, + 'indexed_equals_full_scan': True, + 'independent_replay_verified_rows': session.manifest['num_spikes'], + 'bounded_files_unchanged': True, + 'cache_conditions': 'Uncontrolled OS cache; source hashing warms the full scan; index built before measurement.', + 'build': json.loads(build_report.read_text()) if build_report.exists() else None, + } + args.output.write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2)) + finally: + session.close() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bounded', required=True, type=Path) + parser.add_argument('--store', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--unit', type=int, default=49) + parser.add_argument('--threshold', type=float, default=-341.797119140625) + parser.add_argument('--dataset-label', default='Unspecified engineering dataset') + parser.add_argument('--build-only', action='store_true', help=argparse.SUPPRESS) + run(parser.parse_args()) diff --git a/tools/caption_capture_video.py b/tools/caption_capture_video.py new file mode 100644 index 000000000..21005278b --- /dev/null +++ b/tools/caption_capture_video.py @@ -0,0 +1,656 @@ +"""Add in-window keycaps to a native Phy walkthrough recording. + +The optional review cut concatenates selected original-time ranges. It never +speeds up the recording; the sidecar timeline records every retained range and +the short saved-session card that replaces the reopen wait. +""" + +import argparse +import json +import subprocess +from pathlib import Path + +_KEY_LABELS = { + 'G', + 'V', + 'Backspace', + 'Alt + G', + 'Alt + M', + 'Ctrl + Z', + 'Ctrl + Shift + Z', + 'Ctrl + S', + 'Enter', + 'Esc', +} + +_STAGE_ANNOTATIONS = { + '02-first-merge': 'First merge: {pair} becomes {first_merged}', + '03-nested-merge': 'Second merge: {first_merged} plus {third} becomes {merged}', + '04-later-edits': 'Later: merge {unrelated}, then mark MUA', + '05-restored-parents': 'One restore: all three original clusters', + '08-excluded-parent': 'Exclude restored {excluded}; keep the original pair', + '09-exact-remerge': 'Exact pair remerged: SLAY is green again', + '06-later-edits': 'Later: merge {unrelated}, then mark MUA', + '07-restored-parents': 'Restore older {merged}: editable parents', + '09-parents-remain-live': 'Leave Merge Mode; real parents stay live', + '10-new-combination': 'Exclude {excluded}; add candidate {candidate}', + '12-reopened': 'Reopened: merge {final}, separate {excluded}, MUA {unrelated}', +} + +_STAGE_ANNOTATION_SECONDS = 2.7 + + +def _annotation_text(name, report): + template = _STAGE_ANNOTATIONS.get(name) + if template is None: + return None + return template.format( + merged=report.get('merged', '?'), + unrelated=report.get('unrelated', {}).get('result', '?'), + excluded=report.get('excluded_parent', {}).get('live', '?'), + candidate=report.get('new_candidate', '?'), + final=report.get('final_merged', '?'), + pair=', '.join(map(str, report.get('first_parents', []))), + first_merged=report.get('first_merged', '?'), + third=report.get('nested_merge', {}).get('original_components', ['?'])[-1], + ) + + +def timestamp(seconds): + ticks = round(seconds * 100) + seconds, fraction = divmod(ticks, 100) + minutes, seconds = divmod(seconds, 60) + hours, minutes = divmod(minutes, 60) + return f'{hours}:{minutes:02}:{seconds:02}.{fraction:02}' + + +def rounded_box(width, height, radius=9): + return ( + f'm {radius} 0 l {width - radius} 0 ' + f'b {width} 0 {width} 0 {width} {radius} l {width} {height - radius} ' + f'b {width} {height} {width} {height} {width - radius} {height} ' + f'l {radius} {height} b 0 {height} 0 {height} 0 {height - radius} ' + f'l 0 {radius} b 0 0 0 0 {radius} 0' + ) + + +def _key_names(label): + lowered = label.lower() + if 'click' in lowered: + keys = ['RIGHT CLICK' if label.startswith('Right click') else 'LEFT CLICK'] + return ['CTRL'] * label.startswith('Ctrl + ') + keys + if ':' in label and label.split(':', 1)[0] in _KEY_LABELS: + return [part.upper() for part in label.split(':', 1)[0].split(' + ')] + return [] + + +def _press_release(event): + label = event['label'] + if 'click' in label.lower(): + pressed = float(event.get('click_seconds', float(event['seconds']) + 0.9)) + return pressed, pressed + 0.25 + if ':' in label and label.split(':', 1)[0] in _KEY_LABELS: + pressed = float(event.get('key_seconds', float(event['seconds']) + 0.45)) + return pressed, float(event.get('key_released_seconds', pressed + 0.1)) + return None + + +def _ass_header(width, height): + return f"""[Script Info] +ScriptType: v4.00+ +PlayResX: {width} +PlayResY: {height} +ScaledBorderAndShadow: yes + +[V4+ Styles] +Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding +Style: Key,DejaVu Sans,23,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,5,0,0,0,1 +Style: Card,DejaVu Sans,27,&H00FFFFFF,&H00FFFFFF,&H00000000,&H4017191D,0,0,0,0,100,100,0,0,3,2,0,5,36,36,18,1 +Style: Stage,DejaVu Sans,29,&H00FFFFFF,&H00FFFFFF,&H00000000,&H4017191D,-1,0,0,0,100,100,0,0,1,2,0,5,36,36,18,1 + +[Events] +Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text +""" + + +def _keycap_lines(keys, start, end, width, height, y): + if not keys: + return [] + cap_widths = { + 'CTRL': 82, + 'ALT': 72, + 'BACKSPACE': 160, + 'V': 52, + 'M': 52, + 'SHIFT': 90, + 'LEFT CLICK': 148, + 'RIGHT CLICK': 166, + 'ENTER': 86, + 'G': 52, + 'Z': 52, + 'S': 52, + } + gap = 8 + cap_height = 48 + widths = [cap_widths.get(key, max(60, 16 + len(key) * 16)) for key in keys] + total = sum(widths) + gap * (len(widths) - 1) + x = (width - total) // 2 + start_ts, end_ts = timestamp(start), timestamp(end) + lines = [] + for key, cap_width in zip(keys, widths): + shape = rounded_box(cap_width, cap_height) + lines.append( + f'Dialogue: 1,{start_ts},{end_ts},Key,,0,0,0,,{{\\an7\\pos({x},{y})\\fad(90,160)\\p1\\bord2\\3c&HCCFF4D&\\1c&H17191D&\\1a&H40&}}{shape}' + ) + lines.append( + f'Dialogue: 2,{start_ts},{end_ts},Key,,0,0,0,,{{\\an5\\pos({x + cap_width // 2},{y + cap_height // 2})\\fs23\\bold1\\fad(90,160)\\1c&HFFFFFF&\\1a&H00&\\3a&H00&}}{key}' + ) + x += cap_width + gap + return lines + + +def _pointer_badge(event, start, end, width, height): + if not event['label'].startswith('Ctrl + ') or 'point' not in event: + return [] + px, py = event['point'] + badge_width, badge_height = 78, 42 + x = min(max(int(px) + 34, 4), width - badge_width - 4) + y = min(max(int(py) - badge_height - 8, 4), height - badge_height - 4) + start_ts, end_ts = timestamp(start), timestamp(end) + return [ + f'Dialogue: 3,{start_ts},{end_ts},Key,,0,0,0,,{{\\an7\\pos({x},{y})\\fad(90,160)\\p1\\bord2\\3c&HCCFF4D&\\1c&H17191D&\\1a&H40&}}{rounded_box(badge_width, badge_height)}', + f'Dialogue: 4,{start_ts},{end_ts},Key,,0,0,0,,{{\\an5\\pos({x + badge_width // 2},{y + badge_height // 2})\\fs20\\bold1\\fad(90,160)\\1c&HFFFFFF&\\1a&H00&}}CTRL', + ] + + +def _review_items(events, duration, fps, target_seconds, checkpoints, reopen_card_seconds=0.8): + """Select source-time clips and one cloned-frame reload card. + + The target is met by varying only the visible post-input settling dwell. + Every source clip retains its original frames and rate. + """ + reopen_index = next( + (i for i, event in enumerate(events) if event['label'].startswith('Reopen')), + None, + ) + if reopen_index is None: + raise ValueError('Review cuts require a Reopen saved working copy event.') + + reopen_seconds = float(events[reopen_index]['seconds']) + + final_checkpoint = max((float(step['seconds']) for step in checkpoints), default=duration) + pre_reopen_checkpoint = max( + ( + float(step['seconds']) + for step in checkpoints + if float(step['seconds']) <= reopen_seconds + ), + default=reopen_seconds, + ) + + def make_segments(tail): + raw = [] + for index, event in enumerate(events): + if index == reopen_index: + continue + label = event['label'] + start = max(0.0, float(event['seconds']) - 0.2) + trigger = _press_release(event) + if trigger: + action_end = trigger[1] + elif label.startswith(('View menu', 'Type evidence')): + action_end = float(event['seconds']) + 0.35 + else: + action_end = float(event['seconds']) + 0.4 + end = min(duration, action_end + tail) + if index == len(events) - 1: + end = max(end, min(duration, final_checkpoint + 0.3)) + if float(event['seconds']) < reopen_seconds: + end = min(end, max(start + 1 / fps, reopen_seconds - 1 / fps)) + raw.append( + { + 'source_start': start, + 'source_end': end, + 'event_indices': [index], + } + ) + for step in checkpoints: + step_time = float(step['seconds']) + if abs(step_time - reopen_seconds) <= 1.1 / fps: + continue # The reload card represents the checkpoint captured at reopen. + if step.get('name') in _STAGE_ANNOTATIONS: + raw.append( + { + 'source_start': max(0.0, step_time - _STAGE_ANNOTATION_SECONDS + 0.3), + 'source_end': min(duration, step_time + 0.3), + 'event_indices': [], + } + ) + continue + raw.append( + { + 'source_start': max(0.0, step_time - 0.3), + 'source_end': min(duration, step_time + 0.3), + 'event_indices': [], + } + ) + raw.sort(key=lambda item: item['source_start']) + merged = [] + for segment in raw: + if merged and segment['source_start'] <= merged[-1]['source_end'] + 0.12: + merged[-1]['source_end'] = max(merged[-1]['source_end'], segment['source_end']) + merged[-1]['event_indices'].extend(segment['event_indices']) + else: + merged.append(segment) + return merged + + def make_items(tail): + segments = make_segments(tail) + items = [] + for segment in segments: + first = max(0, round(segment['source_start'] * fps)) + last = max(first + 1, round(segment['source_end'] * fps)) + items.append( + { + 'kind': 'source', + 'source_start_frame': first, + 'source_end_frame': last, + 'source_start': first / fps, + 'source_end': last / fps, + 'event_indices': segment['event_indices'], + } + ) + reopen_event = events[reopen_index] + reopen_frame = max( + 0, + round(float(reopen_event['seconds']) * fps) - 1, + round(pre_reopen_checkpoint * fps), + ) + reopen_frame = min(reopen_frame, max(0, int(reopen_seconds * fps))) + card = { + 'kind': 'reload_card', + 'source_frame': reopen_frame, + 'source_time': reopen_frame / fps, + 'duration_frames': max(1, round(reopen_card_seconds * fps)), + 'duration': max(1, round(reopen_card_seconds * fps)) / fps, + 'event_indices': [reopen_index], + 'label': 'REOPENING SAVED SESSION — reload wait omitted', + } + items.append(card) + items.sort(key=lambda item: item.get('source_start', item.get('source_time', 0.0))) + return items + + def duration_for(tail): + return sum( + (item['source_end_frame'] - item['source_start_frame']) / fps + if item['kind'] == 'source' + else item['duration'] + for item in make_items(tail) + ) + + low, high = 0.0, duration + minimum_duration = duration_for(low) + if minimum_duration > target_seconds + 1 / fps: + raise ValueError( + f'Review cut cannot reach {target_seconds:.1f}s without trimming input actions ' + f'or final checkpoints (minimum is {minimum_duration:.2f}s).' + ) + if duration_for(high) < target_seconds - 1 / fps: + raise ValueError( + f'Review cut cannot reach {target_seconds:.1f}s while preserving action timing.' + ) + for _ in range(48): + middle = (low + high) / 2 + if duration_for(middle) < target_seconds: + low = middle + else: + high = middle + tail = (low + high) / 2 + items = make_items(tail) + + output_cursor = 0.0 + event_output_times = {} + for item in items: + item['output_start'] = output_cursor + if item['kind'] == 'source': + item['output_end'] = ( + output_cursor + (item['source_end_frame'] - item['source_start_frame']) / fps + ) + for index in item['event_indices']: + event_output_times[index] = output_cursor + max( + 0.0, float(events[index]['seconds']) - item['source_start'] + ) + else: + item['output_end'] = output_cursor + item['duration'] + event_output_times[item['event_indices'][0]] = output_cursor + output_cursor = item['output_end'] + checkpoint_output_times = {} + for step in checkpoints: + step_time = float(step['seconds']) + item = next( + ( + candidate + for candidate in items + if candidate['kind'] == 'source' + and candidate['source_start'] <= step_time <= candidate['source_end'] + ), + None, + ) + if item is None: + item = next( + ( + candidate + for candidate in items + if candidate['kind'] == 'reload_card' + and abs(step_time - candidate['source_time']) <= 1.1 / fps + ), + None, + ) + checkpoint_output_times[step.get('name')] = item['output_start'] if item else None + else: + checkpoint_output_times[step.get('name')] = item['output_start'] + max( + 0.0, step_time - item['source_start'] + ) + return items, event_output_times, output_cursor, tail, checkpoint_output_times + + +def _filter_escape(path): + return ( + str(path).replace('\\', '\\\\').replace(':', '\\:').replace("'", "\\'").replace(',', '\\,') + ) + + +def _omitted_ranges(items, duration): + spans = sorted( + ( + item['source_start'], + item['source_end'], + ) + for item in items + if item['kind'] == 'source' + ) + spans.extend( + (item['source_time'], item['source_time'] + item['duration']) + for item in items + if item['kind'] != 'source' + ) + spans.sort() + omitted = [] + cursor = 0.0 + card_time = next( + (item['source_time'] for item in items if item['kind'] == 'reload_card'), None + ) + for start, end in spans: + if start > cursor + 1 / 60: + reopen_gap = card_time is not None and cursor <= card_time <= start + omitted.append( + { + 'source_start': cursor, + 'source_end': start, + 'duration_seconds': start - cursor, + 'reason': 'reopen wait replaced by reload card' + if reopen_gap + else 'idle or settled dwell trimmed', + } + ) + cursor = max(cursor, end) + if cursor < duration - 1 / 60: + omitted.append( + { + 'source_start': cursor, + 'source_end': duration, + 'duration_seconds': duration - cursor, + 'reason': 'trailing settled dwell trimmed', + } + ) + return omitted + + +def render(directory, output_name=None, review_cut=False, review_seconds=43.0, overwrite=False): + directory = directory.resolve() + report = json.loads((directory / 'capture.json').read_text()) + if not report['success'] or not report['source_unchanged']: + raise ValueError('Capture must report success and unchanged source data.') + details = json.loads( + subprocess.check_output( + [ + 'ffprobe', + '-v', + 'error', + '-show_streams', + '-show_format', + '-of', + 'json', + str(directory / 'walkthrough.mp4'), + ], + text=True, + ) + ) + video = next(stream for stream in details['streams'] if stream['codec_type'] == 'video') + width, height = int(video['width']), int(video['height']) + duration = float(details['format']['duration']) + fps_num, fps_den = map(int, video['r_frame_rate'].split('/')) + fps = fps_num / fps_den + events = report['input_events'] + if review_cut and not 20.0 <= review_seconds <= 120.0: + raise ValueError('--review-seconds must be between 20 and 120 seconds.') + + items = None + event_output_times = {i: float(event['seconds']) for i, event in enumerate(events)} + review_duration = duration + tail = None + if review_cut: + items, event_output_times, review_duration, tail, checkpoint_output_times = _review_items( + events, duration, fps, review_seconds, report.get('steps', []) + ) + + output_name = output_name or ( + 'review-integrated.mp4' if review_cut else f'review-{report["recording_fps"]}fps.mp4' + ) + destination = Path(output_name) + if not destination.is_absolute(): + destination = directory / destination + destination = destination.resolve() + if destination == (directory / 'walkthrough.mp4').resolve(): + raise ValueError('Output must not overwrite the original walkthrough.') + if destination.exists() and not overwrite: + raise FileExistsError(f'Refusing to overwrite existing output: {destination}') + destination.parent.mkdir(parents=True, exist_ok=True) + ass_path = destination.with_suffix('.ass') + timeline_path = destination.with_suffix('.timeline.json') + if not overwrite and (ass_path.exists() or (review_cut and timeline_path.exists())): + raise FileExistsError('Refusing to overwrite an existing caption or timeline sidecar.') + + lines = [] + key_y = max(0, height - 140) + for index, event in enumerate(events): + keys = _key_names(event['label']) + if not keys: + continue + trigger = _press_release(event) + if trigger is None: + continue + pressed, released = trigger + output_event_time = event_output_times[index] + input_event_time = float(event['seconds']) + offset = output_event_time - input_event_time + cue_start = max(0.0, pressed - 0.15 + offset) + cue_end = released + 0.85 + offset + if review_cut: + containing = next(item for item in items if index in item.get('event_indices', [])) + cue_end = min(cue_end, containing['output_end']) + lines.extend(_keycap_lines(keys, cue_start, cue_end, width, height, key_y)) + lines.extend(_pointer_badge(event, cue_start, cue_end, width, height)) + + if review_cut: + card = next(item for item in items if item['kind'] == 'reload_card') + card_start, card_end = timestamp(card['output_start']), timestamp(card['output_end']) + card_width, card_height = min(650, width - 80), 112 + x, y = (width - card_width) // 2, (height - card_height) // 2 + lines.append( + f'Dialogue: 1,{card_start},{card_end},Key,,0,0,0,,{{\\an7\\pos({x},{y})\\fad(80,130)\\p1\\bord2\\3c&HCCFF4D&\\1c&H17191D&\\1a&H40&}}{rounded_box(card_width, card_height, 14)}' + ) + lines.append( + f'Dialogue: 2,{card_start},{card_end},Key,,0,0,0,,{{\\an5\\pos({width // 2},{height // 2 - 14})\\fs28\\bold1\\fad(80,130)\\1c&HFFFFFF&\\1a&H00&}}REOPENING SAVED SESSION' + ) + lines.append( + f'Dialogue: 2,{card_start},{card_end},Key,,0,0,0,,{{\\an5\\pos({width // 2},{height // 2 + 22})\\fs20\\fad(80,130)\\1c&HFFFFFF&\\1a&H00&}}Reload wait omitted' + ) + + for step in report.get('steps', []): + text = _annotation_text(step.get('name'), report) + step_time = checkpoint_output_times.get(step.get('name')) + if not text or step_time is None: + continue + start = max(0.0, step_time - _STAGE_ANNOTATION_SECONDS + 0.3) + end = min(review_duration, start + _STAGE_ANNOTATION_SECONDS) + stage_start, stage_end = timestamp(start), timestamp(end) + panel_width, panel_height = min(820, width - 60), 104 + x, y = width - panel_width - 24, 82 + lines.append( + f'Dialogue: 5,{stage_start},{stage_end},Stage,,0,0,0,,{{\\an7\\pos({x},{y})\\fad(140,180)\\p1\\bord2\\3c&HCCFF4D&\\1c&H17191D&\\1a&H40&}}{rounded_box(panel_width, panel_height, 12)}' + ) + lines.append( + f'Dialogue: 6,{stage_start},{stage_end},Stage,,0,0,0,,{{\\an5\\pos({x + panel_width // 2},{y + 24})\\fs18\\bold1\\fad(140,180)\\1c&HFFFFFF&\\1a&H00&}}REVIEW NOTE' + ) + lines.append( + f'Dialogue: 6,{stage_start},{stage_end},Stage,,0,0,0,,{{\\an5\\pos({x + panel_width // 2},{y + 66})\\fs26\\bold1\\fad(140,180)\\1c&HFFFFFF&\\1a&H00&}}{text}' + ) + + ass_path.write_text(_ass_header(width, height) + '\n'.join(lines) + '\n') + command = [ + 'ffmpeg', + '-nostdin', + '-y' if overwrite else '-n', + '-v', + 'warning', + '-i', + str(directory / 'walkthrough.mp4'), + ] + if review_cut: + filters = [] + labels = [] + for i, item in enumerate(items): + label = f'v{i}' + labels.append(f'[{label}]') + if item['kind'] == 'source': + filters.append( + f'[0:v]trim=start_frame={item["source_start_frame"]}:end_frame={item["source_end_frame"]},setpts=PTS-STARTPTS[{label}]' + ) + else: + frame = item['source_frame'] + filters.append( + f'[0:v]trim=start_frame={frame}:end_frame={frame + 1},setpts=PTS-STARTPTS,tpad=stop_mode=clone:stop_duration={max(0.0, item["duration"] - 1 / fps):.6f}[{label}]' + ) + ass_filter = _filter_escape(ass_path) + filters.append(''.join(labels) + f'concat=n={len(labels)}:v=1:a=0,ass={ass_filter}[outv]') + command.extend( + [ + '-filter_complex', + ';'.join(filters), + '-map', + '[outv]', + ] + ) + else: + command.extend(['-vf', f'ass={_filter_escape(ass_path)}']) + command.extend( + [ + '-an', + '-c:v', + 'libx264', + '-preset', + 'veryfast', + '-crf', + '22', + '-threads', + '4', + '-pix_fmt', + 'yuv420p', + '-r', + f'{fps_num}/{fps_den}', + '-fps_mode', + 'cfr', + '-movflags', + '+faststart', + str(destination), + ] + ) + subprocess.run(command, cwd=directory, check=True) + + if review_cut: + timeline = { + 'source': str(directory / 'walkthrough.mp4'), + 'output': str(destination), + 'source_fps': f'{fps_num}/{fps_den}', + 'source_duration_seconds': duration, + 'output_duration_seconds': review_duration, + 'review_cut': True, + 'timeline_note': 'Original-speed source frames concatenated; idle dwell and reopen wait omitted. Not a latency benchmark.', + 'settle_tail_seconds': tail, + 'items': items, + 'omitted_source_ranges': _omitted_ranges(items, duration), + 'events': [ + { + 'index': index, + 'label': event['label'], + 'source_seconds': float(event['seconds']), + 'output_seconds': event_output_times[index], + } + for index, event in enumerate(events) + ], + 'checkpoints': [ + { + 'name': step.get('name'), + 'source_seconds': float(step['seconds']), + 'output_seconds': checkpoint_output_times.get(step.get('name')), + 'captured': checkpoint_output_times.get(step.get('name')) is not None, + } + for step in report.get('steps', []) + ], + 'review_annotations': [ + { + 'checkpoint': step.get('name'), + 'text': _annotation_text(step['name'], report), + 'output_start_seconds': max( + 0.0, + checkpoint_output_times[step['name']] - _STAGE_ANNOTATION_SECONDS + 0.3, + ), + 'output_end_seconds': min( + review_duration, + max( + 0.0, + checkpoint_output_times[step['name']] + - _STAGE_ANNOTATION_SECONDS + + 0.3, + ) + + _STAGE_ANNOTATION_SECONDS, + ), + 'label': 'review overlay; not part of application UI', + } + for step in report.get('steps', []) + if step.get('name') in _STAGE_ANNOTATIONS + and checkpoint_output_times.get(step.get('name')) is not None + ], + } + timeline_path.write_text(json.dumps(timeline, indent=2) + '\n') + print(timeline_path) + print(destination) + print(f'{destination.stat().st_size:,} bytes') + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('directory', type=Path) + parser.add_argument('--output-name') + parser.add_argument('--review-cut', action='store_true') + parser.add_argument('--review-seconds', type=float) + parser.add_argument('--overwrite', action='store_true') + args = parser.parse_args() + render( + args.directory, + args.output_name, + review_cut=args.review_cut or args.review_seconds is not None, + review_seconds=args.review_seconds if args.review_seconds is not None else 43.0, + overwrite=args.overwrite, + ) diff --git a/tools/capture_carl_feedback.py b/tools/capture_carl_feedback.py new file mode 100644 index 000000000..4f0e6aedc --- /dev/null +++ b/tools/capture_carl_feedback.py @@ -0,0 +1,802 @@ +"""Exercise Carl's feedback in the real GUI on a disposable data copy. + +Starts its own Xvfb server: no window or recording reaches the desktop. Inputs +are hashed and copied before opening; curation is saved only in the copy. +Records real X11 pixels, Qt input events and state assertions with separate config. +""" + +import argparse +import ctypes +import ctypes.util +import json +import os +import shutil +import subprocess +import time +from copy import deepcopy +from pathlib import Path + + +def run(args): + if args.dataset.resolve() in (args.output.resolve(), *args.output.resolve().parents): + raise ValueError('The capture output must be outside the immutable input dataset.') + args.output.mkdir(parents=True, exist_ok=False) + server_log = (args.output / 'xvfb.log').open('w') + server = subprocess.Popen( + [ + 'Xvfb', + '-displayfd', + '1', + '-screen', + '0', + '1920x1200x24', + '-nolisten', + 'tcp', + '-ac', + '+extension', + 'GLX', + '+render', + ], + stdout=subprocess.PIPE, + stderr=server_log, + text=True, + ) + display = ':' + server.stdout.readline().strip() + if display == ':': + raise RuntimeError('Private X server failed to start.') + os.environ.update( + DISPLAY=display, + QT_QPA_PLATFORM='xcb', + LIBGL_ALWAYS_SOFTWARE='1', + PYOPENGL_PLATFORM='glx', + LP_NUM_THREADS='4', + OPENBLAS_NUM_THREADS='2', + OMP_NUM_THREADS='2', + ) + recording = None + controller = gui = app = None + try: + import numpy as np + import OpenGL.GL # Initialize OpenGL before Qt, as in the application entrypoint. + from phylib.io.model import load_model + from PyQt5.QtCore import QCoreApplication, QEvent, QPoint, QTimer + from PyQt5.QtGui import ( + QColor, + QCursor, + QPainter, + QPen, + QPixmap, + QPolygon, + ) + from PyQt5.QtTest import QTest + from PyQt5.QtWidgets import QInputDialog, QLineEdit, QMenu + + from phy.apps.large_recording.file_copy import copy_source_file + from phy.apps.large_recording.source import hash_file + from phy.apps.template.gui import TemplateController + from phy.gui.qt import QApplication, Qt + + source_dataset = args.dataset.resolve() + files = [ + p + for p in source_dataset.iterdir() + if p.is_file() and p.name not in ('phy.log', 'phy_curation_history.jsonl') + ] + source_hashes = {p.name: hash_file(p) for p in files} + args.dataset = args.output / 'working-dataset' + shutil.copytree( + source_dataset, + args.dataset, + copy_function=copy_source_file, + ignore=shutil.ignore_patterns('.phy', 'phy.log', 'phy_curation_history.jsonl'), + ) + assert not any(p.is_symlink() for p in args.dataset.iterdir()) + renderer = subprocess.run(['glxinfo', '-B'], capture_output=True, text=True, check=True) + (args.output / 'renderer.txt').write_text(renderer.stdout) + app = QApplication.instance() or QApplication([]) + report = { + 'mode': args.mode, + 'dataset': str(source_dataset), + 'working_copy': str(args.dataset), + 'capture_scope': ( + 'Settled X11 pixels; native XTest context click and Qt input events; ' + 'not a spontaneous-redraw test' + ), + 'private_display': display, + 'revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), + 'steps': [], + 'input_events': [], + 'recording_fps': args.fps, + 'pointer': 'Visible native X11 cursor, eased motion and click ring', + 'label': 'Real earlier Carl dataset; engineering validation', + } + bounded = args.mode == 'bounded' + controller = TemplateController( + model=None if bounded else load_model(args.dataset / 'params.py'), + dir_path=args.dataset, + config_dir=args.output / 'config', + plugins=[], + enable_threading=False, + ) + bounded = args.mode == 'bounded' + display_columns = ['id', 'group', 'n_spikes', 'ch'] + if bounded: + display_columns.insert(2, 'full_count') + controller.supervisor.columns = display_columns + report['display_columns'] = display_columns + names = [ + 'SampledCorrelogramView' if bounded else 'CorrelogramView', + 'WaveformView', + 'EvidenceAmplitudeView' if bounded else 'AmplitudeView', + 'FeatureView', + ] + gui = controller.create_gui( + default_views=names, view_count=dict.fromkeys(names, 1), do_prompt_save=False + ) + if hasattr(controller, '_summary_store_actions'): + controller._summary_store_actions._checked = True + supervisor = controller.supervisor + controller.n_spikes_waveforms = 50 + controller.n_spikes_waveforms_total = 350 + gui.resize(1920, 1200) + gui.move(0, 0) + gui.setWindowTitle('Carl feedback — ' + args.mode + ' real-data walkthrough') + gui.show() + + def settle(ms=500): + supervisor.block() + app.processEvents() + QTest.qWait(ms) + app.processEvents() + + settle() + science = [gui.get_view(name) for name in names] + if any(view is None for view in science): + raise RuntimeError(f'Missing scientific view: {names}') + ccg, waveform, amplitude, feature = science + waveform.waveforms_type = 'waveforms' + if not bounded: + amplitude.amplitudes_type = 'template' + tables = [ + supervisor.cluster_view, + supervisor.similarity_view, + supervisor.merge_propositions_view, + ] + for view in tables: + gui.addDockWidget(Qt.LeftDockWidgetArea, view.dock) + for a, b in zip(tables[:-1], tables[1:]): + gui.splitDockWidget(a.dock, b.dock, Qt.Vertical) + gui.addDockWidget(Qt.RightDockWidgetArea, ccg.dock) + gui.splitDockWidget(ccg.dock, waveform.dock, Qt.Horizontal) + gui.splitDockWidget(ccg.dock, amplitude.dock, Qt.Vertical) + gui.splitDockWidget(waveform.dock, feature.dock, Qt.Vertical) + gui.resizeDocks([tables[0].dock, ccg.dock, waveform.dock], [370, 760, 760], Qt.Horizontal) + gui.resizeDocks([v.dock for v in tables], [330, 300, 440], Qt.Vertical) + settle() + started = time.monotonic() + video_log = (args.output / 'ffmpeg.log').open('w') + recording = subprocess.Popen( + [ + 'ffmpeg', + '-nostdin', + '-y', + '-video_size', + '1920x1200', + '-framerate', + str(args.fps), + '-f', + 'x11grab', + '-draw_mouse', + '1', + '-i', + display + '.0', + '-an', + '-c:v', + 'libx264', + '-preset', + 'veryfast', + '-crf', + '20', + '-pix_fmt', + 'yuv420p', + '-movflags', + '+faststart', + str(args.output / 'walkthrough.mp4'), + ], + stdout=video_log, + stderr=video_log, + ) + + def cursor_image(clicked=False): + pixmap = QPixmap(72, 72) + pixmap.fill(Qt.transparent) + painter = QPainter(pixmap) + painter.setRenderHint(QPainter.Antialiasing) + if clicked: + painter.setPen(QPen(QColor('#ffcc4d'), 4)) + painter.drawEllipse(QPoint(28, 28), 22, 22) + painter.setPen(QPen(QColor('#101010'), 2)) + painter.setBrush(QColor('white')) + painter.drawPolygon( + QPolygon( + [ + QPoint(28, 28), + QPoint(28, 53), + QPoint(35, 47), + QPoint(41, 61), + QPoint(48, 58), + QPoint(42, 45), + QPoint(53, 45), + ] + ) + ) + painter.end() + return QCursor(pixmap, 28, 28) + + idle_cursor, clicked_cursor = cursor_image(), cursor_image(True) + app.setOverrideCursor(idle_cursor) + + def input_note(label): + entry = {'seconds': round(time.monotonic() - started, 3), 'label': label} + report['input_events'].append(entry) + print(json.dumps({'input': entry}), flush=True) + return entry + + def show_cursor(cursor): + # Application busy-cursor cleanup can remove an earlier override. + # Re-establish our recording cursor without changing application code. + if app.overrideCursor() is None: + app.setOverrideCursor(cursor) + else: + app.changeOverrideCursor(cursor) + + def move_pointer(widget, pos): + show_cursor(idle_cursor) + origin = QCursor.pos() + target = widget.mapToGlobal(pos) + for step in range(1, 17): + fraction = step / 16 + eased = fraction * fraction * (3 - 2 * fraction) + QCursor.setPos( + round(origin.x() + (target.x() - origin.x()) * eased), + round(origin.y() + (target.y() - origin.y()) * eased), + ) + QTest.qWait(25) + QTest.qWait(120) + + def click(widget, button, modifiers=Qt.NoModifier, pos=None, label=None): + pos = pos if pos is not None else widget.rect().center() + button_name = 'Right click' if button == Qt.RightButton else 'Left click' + prefix = 'Ctrl + ' if modifiers & Qt.ControlModifier else '' + event = input_note(prefix + button_name + (': ' + label if label else '')) + move_pointer(widget, pos) + event['point'] = [QCursor.pos().x(), QCursor.pos().y()] + show_cursor(clicked_cursor) + QTest.qWait(100) + event['click_seconds'] = round(time.monotonic() - started, 3) + QTest.mousePress(widget, button, modifiers, pos) + QTest.qWait(100) + QTest.mouseRelease(widget, button, modifiers, pos) + show_cursor(clicked_cursor) + QTest.qWait(200) + show_cursor(idle_cursor) + + def native_context_click(): + # Route the context-menu gesture through X11/XTest into Qt's xcb + # platform plugin, rather than manufacturing a ContextMenu event. + assert os.environ['DISPLAY'] == display + x11 = ctypes.CDLL(ctypes.util.find_library('X11')) + xtst = ctypes.CDLL(ctypes.util.find_library('Xtst')) + x11.XOpenDisplay.argtypes = [ctypes.c_char_p] + x11.XOpenDisplay.restype = ctypes.c_void_p + x11.XFlush.argtypes = [ctypes.c_void_p] + x11.XCloseDisplay.argtypes = [ctypes.c_void_p] + xtst.XTestFakeButtonEvent.argtypes = [ + ctypes.c_void_p, + ctypes.c_uint, + ctypes.c_int, + ctypes.c_ulong, + ] + xtst.XTestFakeButtonEvent.restype = ctypes.c_int + connection = x11.XOpenDisplay(display.encode()) + if not connection: + raise RuntimeError('Cannot open the private X11 display for context click.') + try: + for pressed in (1, 0): + if not xtst.XTestFakeButtonEvent(connection, 3, pressed, 0): + raise RuntimeError('XTest context-menu button event failed.') + x11.XFlush(connection) + finally: + x11.XCloseDisplay(connection) + + def key(widget, value, modifiers=Qt.NoModifier, label='Keyboard shortcut'): + event = input_note(label) + QTest.qWait(250) + event['key_seconds'] = round(time.monotonic() - started, 3) + QTest.keyClick(widget, value, modifiers) + event['key_released_seconds'] = round(time.monotonic() - started, 3) + QTest.qWait(250) + + def capture(name, title, window=None, **facts): + target = window or gui + if window is None: + gui.resize(1920, 1200) + gui.move(0, 0) + gui.statusBar().showMessage(title) + settle(800) + frame = target.frameGeometry() + pixmap = ( + app.primaryScreen() + .grabWindow(0) + .copy(frame.x(), frame.y(), frame.width(), frame.height()) + ) + path = args.output / (name + '.png') + assert pixmap.save(str(path), 'PNG') + entry = { + 'name': name, + 'title': title, + 'seconds': round(time.monotonic() - started, 3), + 'selected': list(map(int, supervisor.selected)), + **facts, + } + report['steps'].append(entry) + (args.output / 'capture.json').write_text(json.dumps(report, indent=2)) + print(json.dumps(entry), flush=True) + + def click_row(table, unit, modifiers=Qt.NoModifier): + index = table._proxy_index_for_id(unit) + assert index.isValid(), unit + table.table_view.scrollTo(index) + settle(150) + row = table._row_for_proxy_index(index) + label = row.get('proposition') or f'Cluster {unit}' + click( + table.table_view.viewport(), + Qt.LeftButton, + modifiers, + table.table_view.visualRect(index).center(), + label=str(label), + ) + settle() + + catalog = supervisor.merge_propositions.catalog + choices = [ + p + for p in catalog.propositions + if len(p.unit_ids) == 2 + and all(unit in supervisor.clustering.cluster_ids for unit in p.unit_ids) + ] + assert choices, 'The real-data fixture needs a live pair SLAY suggestion.' + proposal = next( + (p for p in choices if bounded and tuple(p.unit_ids) == (25, 27)), choices[0] + ) + first_parents = list(map(int, proposal.unit_ids)) + report['workflow'] = 'recursive-restore-and-exact-slay-reassembly' + report['propositions'] = [{'key': proposal.key, 'unit_ids': first_parents}] + report['first_parents'] = first_parents + initial = supervisor.clustering.spike_clusters.copy() + initial_events = list(controller.bounded_session.events) if bounded else None + propositions = supervisor.merge_propositions_view + if bounded: + # Select real retained evidence for the initial pair. Later candidates + # must also have stored waveforms in this same inspected window. + stored = controller.model.spike_waveforms.spike_ids + stored_labels = initial[stored] + slots = np.searchsorted( + controller.evidence_windows[:, 1], + controller.model.spike_samples[stored], + side='right', + ) + counts = np.stack( + [ + np.bincount( + slots[stored_labels == unit], minlength=len(controller.evidence_windows) + ) + for unit in first_parents + ] + ) + score = (counts > 0).sum(axis=0) * 10000 + counts.sum(axis=0) + window_index = int(np.argmax(score)) + assert np.all(counts[:, window_index] > 0) + controller.inspect_evidence_window(window_index) + amplitude.amplitude_scope = 'overview' + report['evidence_window'] = window_index + report['window_waveforms_by_unit'] = dict( + zip(map(str, first_parents), map(int, counts[:, window_index])) + ) + for index, unit in enumerate(first_parents): + click_row( + supervisor.cluster_view, unit, Qt.ControlModifier if index else Qt.NoModifier + ) + capture('01-initial', 'Compare the two source clusters before the first merge') + + def assert_slay_status(accepted): + status = supervisor.merge_propositions.catalog.status_for(proposal.key).value + row_id = propositions._id_by_key[proposal.key] + row = propositions._model.row_by_id(row_id) + assert row['_catalog_status'] == status, (row, status) + color = propositions._foreground_color(row, 'proposition') + if accepted: + assert status == 'accepted', status + assert color is not None and color.name() == '#86d16d', (row, color) + else: + assert status == 'accepted_restored', status + assert color is None, (row, color) + return status + + click_row(propositions, propositions._id_by_key[proposal.key]) + gui.activateWindow() + app.setActiveWindow(gui) + gui.setFocus() + key(gui, Qt.Key_G, label='G: merge the first two source clusters') + settle() + first_merged = int(supervisor.selected[0]) + expected = initial.copy() + expected[np.isin(initial, first_parents)] = first_merged + np.testing.assert_array_equal(expected, supervisor.clustering.spike_clusters) + accepted_review = dict( + supervisor.merge_propositions.catalog.reviews[proposal.key].mapping() + ) + assert accepted_review['result_unit_id'] == first_merged + assert_slay_status(True) + report['first_merged'] = first_merged + capture('02-first-merge', 'First merge accepted: the SLAY suggestion is green') + + candidates = [ + int(unit) + for unit in supervisor.similarity_view.get_ids() + if int(unit) not in set(first_parents) | {first_merged} + and (not bounded or np.any((stored_labels == unit) & (slots == window_index))) + ] + assert candidates, 'No similar third source cluster has evidence in the selected window.' + third = candidates[0] + click_row(supervisor.cluster_view, first_merged) + click_row(supervisor.cluster_view, third, Qt.ControlModifier) + key(gui, Qt.Key_G, label='G: merge the first result with one more source cluster') + settle() + merged = int(supervisor.selected[0]) + originals = first_parents + [third] + expected[np.isin(initial, originals)] = merged + np.testing.assert_array_equal(expected, supervisor.clustering.spike_clusters) + report['nested_merge'] = { + 'immediate_inputs': [first_merged, third], + 'original_components': originals, + 'result': merged, + } + report['merged'] = merged + report['union'] = originals + report['nested_merge_slay_status'] = supervisor.merge_propositions.catalog.status_for( + proposal.key + ).value + capture( + '03-nested-merge', + 'Second merge contains the first merge plus a third source cluster', + immediate_parents=[first_merged, third], + original_components=originals, + ) + + unrelated_inputs = [ + int(unit) + for unit in supervisor.clustering.cluster_ids + if int(unit) not in set(originals) | {first_merged, merged} + ][:2] + assert len(unrelated_inputs) == 2 + click_row(supervisor.cluster_view, unrelated_inputs[0]) + click_row(supervisor.cluster_view, unrelated_inputs[1], Qt.ControlModifier) + key(gui, Qt.Key_G, label='G: make an unrelated later merge') + settle() + unrelated = int(supervisor.selected[0]) + key(gui, Qt.Key_M, Qt.AltModifier, 'Alt + M: label the unrelated unit MUA') + settle() + after_later = supervisor.clustering.spike_clusters.copy() + before_restore_history = supervisor._global_history.current_position + unrelated_rows = np.flatnonzero(np.isin(initial, unrelated_inputs)) + report['unrelated'] = {'inputs': unrelated_inputs, 'result': unrelated, 'group': 'mua'} + + def assert_unrelated_preserved(): + np.testing.assert_array_equal( + supervisor.clustering.spike_clusters[unrelated_rows], + after_later[unrelated_rows], + ) + assert supervisor.cluster_meta.get('group', unrelated) == 'mua' + + assert_unrelated_preserved() + click_row(supervisor.cluster_view, unrelated) + capture('04-later-edits', 'A later unrelated merge and MUA label must remain intact') + + # Expected scientific memberships come directly from immutable input + # labels, not the production recursive-lineage resolver being exercised. + original_groups = {unit: np.flatnonzero(initial == unit) for unit in originals} + assert all(len(rows) for rows in original_groups.values()) + click_row(supervisor.cluster_view, merged) + table = supervisor.cluster_view + index = table._proxy_index_for_id(merged) + table.table_view.scrollTo(index) + settle(150) + point = table.table_view.visualRect(index).center() + restore_menu_errors = [] + + def choose_restore_action(): + try: + menu = app.activePopupWidget() + assert isinstance(menu, QMenu) + action = next( + action + for action in menu.actions() + if action.text() == 'Restore parents in Merge Mode' + ) + assert action.isEnabled() + click( + menu, + Qt.LeftButton, + Qt.NoModifier, + menu.actionGeometry(action).center(), + 'Restore all merge components in Merge Mode', + ) + except Exception as error: + restore_menu_errors.append(error) + menu = app.activePopupWidget() + if menu is not None: + menu.close() + + input_note('Right click: older nested merge context menu') + move_pointer(table.table_view.viewport(), point) + QTimer.singleShot(650, choose_restore_action) + native_context_click() + settle(1000) + if restore_menu_errors: + raise restore_menu_errors[0] + assert controller.parent_inspection.window is None + assert supervisor.selection.state.is_merge_mode + restored = {} + for old_parent, rows in original_groups.items(): + values = np.unique(supervisor.clustering.spike_clusters[rows]) + assert len(values) == 1 + restored[old_parent] = int(values[0]) + assert len(set(restored.values())) == 3 + assert merged not in supervisor.clustering.cluster_ids + assert first_merged not in supervisor.clustering.cluster_ids + assert set(supervisor.selection.state.merge.ordered_ids) == set(restored.values()) + assert supervisor._global_history.current_position == before_restore_history + 1 + for old_parent, child in restored.items(): + np.testing.assert_array_equal( + supervisor.clustering.spikes_per_cluster[child], original_groups[old_parent] + ) + assert supervisor.parent_origins[child] == old_parent + assert len({supervisor.selection_color_indices[unit] for unit in restored.values()}) == 3 + assert_unrelated_preserved() + assert_slay_status(False) + report['restored'] = restored + report['restored_live_units'] = True + report['recursive_restore_exact'] = True + report['one_restore_history_entry'] = True + report['restored_historical_ids_visible'] = True + report['restored_color_indices'] = { + str(old): supervisor.selection_color_indices[new] for old, new in restored.items() + } + capture( + '05-restored-parents', + 'One restoration returns all three original components, not the intermediate merge', + restored=restored, + slay_status='accepted_restored', + ) + + restored_assignments = supervisor.clustering.spike_clusters.copy() + key(gui, Qt.Key_Z, Qt.ControlModifier, 'Ctrl + Z: undo the whole recursive restoration') + settle() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, after_later) + assert_unrelated_preserved() + key( + gui, + Qt.Key_Z, + Qt.ControlModifier | Qt.ShiftModifier, + 'Ctrl + Shift + Z: redo the whole recursive restoration', + ) + settle() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, restored_assignments) + assert supervisor.selection.state.is_merge_mode + assert_slay_status(False) + assert_unrelated_preserved() + capture('06-restore-history', 'One Undo/Redo reverses the entire recursive restoration') + + key(gui, Qt.Key_V, label='V: leave Merge Mode; all three restored clusters stay live') + settle() + assert not supervisor.selection.state.is_merge_mode + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, restored_assignments) + assert set(restored.values()) <= set(supervisor.clustering.cluster_ids) + assert_unrelated_preserved() + capture( + '07-parents-remain-live', 'The restored source components remain real live clusters' + ) + key(gui, Qt.Key_V, label='V: stage the restored components again') + settle() + + excluded = restored[third] + click_row(supervisor.merge_view, excluded) + exclude_button = supervisor.merge_view.dock.get_widget('exclude_merge_row') + assert ( + exclude_button is not None + and exclude_button.isVisible() + and exclude_button.isEnabled() + ) + click(exclude_button, Qt.LeftButton, label='Exclude the third source component') + settle() + chosen = [restored[unit] for unit in first_parents] + assert set(supervisor.selected) == set(chosen) + assert excluded in supervisor.clustering.cluster_ids + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, restored_assignments) + report['excluded_parent'] = {'original': third, 'live': excluded} + report['chosen'] = chosen + assert_slay_status(False) + capture( + '08-excluded-parent', + 'Exclude the third component and keep the original suggested pair', + ) + final_parent_groups = { + unit: supervisor.clustering.spikes_per_cluster[unit].copy() for unit in chosen + } + final_parent_colors = {unit: supervisor.selection_color_indices[unit] for unit in chosen} + key(gui, Qt.Key_G, label='G: remerge the exact original SLAY pair') + settle() + final_merged = int(supervisor.selected[0]) + expected = initial.copy() + expected[np.isin(initial, first_parents)] = final_merged + expected[initial == third] = excluded + expected[np.isin(initial, unrelated_inputs)] = unrelated + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, expected) + assert_slay_status(True) + assert_unrelated_preserved() + assert ( + dict(supervisor.merge_propositions.catalog.reviews[proposal.key].mapping()) + == accepted_review + ) + report['final_merged'] = final_merged + report['exact_remerge_slay_green'] = True + report['historical_review_preserved'] = True + report['later_edits_preserved'] = True + report['excluded_parent_stays_independent'] = True + capture('09-exact-remerge', 'The exact SLAY pair is merged again: its suggestion is green') + + key(gui, Qt.Key_Z, Qt.ControlModifier, 'Ctrl + Z: undo the remerge; SLAY becomes white') + settle() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, restored_assignments) + assert_slay_status(False) + assert_unrelated_preserved() + key( + gui, + Qt.Key_Z, + Qt.ControlModifier | Qt.ShiftModifier, + 'Ctrl + Shift + Z: redo the remerge; SLAY becomes green', + ) + settle() + np.testing.assert_array_equal(supervisor.clustering.spike_clusters, expected) + assert_slay_status(True) + assert_unrelated_preserved() + report['remerge_undo_redo_status_correct'] = True + capture( + '10-remerge-history', + 'Undo/Redo keeps the SLAY color synchronized with actual membership', + ) + + if bounded: + assert len(controller.bounded_session.events) == len(initial_events) + 6 + key(gui, Qt.Key_S, Qt.ControlModifier, 'Ctrl + S: save the revised curation') + settle() + report['assigned_spikes'] = int(np.count_nonzero(initial != expected)) + capture( + '11-revised-save', + 'Saved: remerged pair, independent third component and later MUA edit', + ) + input_note('Reopen the saved working copy') + gui.close() + controller.close() + gui.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + app.processEvents() + gui = controller = None + controller = TemplateController( + model=None if bounded else load_model(args.dataset / 'params.py'), + dir_path=args.dataset, + config_dir=args.output / 'config', + plugins=[], + enable_threading=False, + ) + controller.supervisor.columns = display_columns + gui = controller.create_gui( + default_views=names, view_count=dict.fromkeys(names, 1), do_prompt_save=False + ) + if hasattr(controller, '_summary_store_actions'): + controller._summary_store_actions._checked = True + supervisor = controller.supervisor + propositions = supervisor.merge_propositions_view + gui.resize(1920, 1200) + gui.move(0, 0) + gui.show() + supervisor.select([final_merged]) + settle() + if bounded: + report['reopened_initial_evidence_window'] = controller.evidence_window_index + + def choose_evidence_window(): + dialog = app.activeModalWidget() + assert isinstance(dialog, QInputDialog) + edit = dialog.findChild(QLineEdit) + assert edit is not None and edit.isVisible() + input_note('Type evidence window index, then Enter') + move_pointer(edit, edit.rect().center()) + edit.selectAll() + QTest.keyClicks(edit, str(report['evidence_window']), delay=120) + key( + edit, + Qt.Key_Return, + label=f'Enter: inspect evidence window {report["evidence_window"]}', + ) + + QTimer.singleShot(800, choose_evidence_window) + input_note('View menu: Inspect evidence window') + gui.view_actions.get('inspect_evidence_window').trigger() + settle() + assert controller.evidence_window_index == report['evidence_window'] + report['reopened_selected_evidence_window'] = controller.evidence_window_index + report['reopen_window_action'] = ( + 'Explicit Inspect evidence window dialog; not automatic restoration' + ) + np.testing.assert_array_equal(expected, supervisor.clustering.spike_clusters) + assert_unrelated_preserved() + groups = controller.parent_inspection.lineage.parents(final_merged, recursive=False) + assert set(groups) == set(chosen) + for parent in chosen: + np.testing.assert_array_equal(groups[parent], final_parent_groups[parent]) + assert ( + dict(controller.parent_inspection.lineage.colors(final_merged, groups)) + == final_parent_colors + ) + assert_slay_status(True) + assert ( + dict(supervisor.merge_propositions.catalog.reviews[proposal.key].mapping()) + == accepted_review + ) + report['reopened_parent_colors_preserved'] = True + report['reopened_lineage_correct'] = True + report['reopened_slay_green'] = True + report['historical_review_statuses'] = { + proposal.key: supervisor.merge_propositions.catalog.status_for(proposal.key).value + } + capture( + '12-reopened', 'Reopened: green SLAY pair, independent third component and later edits' + ) + assert {p.name: hash_file(p) for p in files} == source_hashes + report['source_unchanged'] = True + report['success'] = True + (args.output / 'capture.json').write_text(json.dumps(report, indent=2)) + finally: + if recording is not None: + recording.terminate() + recording.wait(timeout=30) + if gui is not None: + gui.close() + if controller is not None: + controller.close() + if app is not None: + from PyQt5 import sip + + for widget in app.topLevelWidgets(): + widget.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + app.processEvents() + sip.delete(app) + server.terminate() + server.wait(timeout=10) + server_log.close() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--dataset', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + parser.add_argument('--mode', required=True, choices=['ordinary', 'bounded']) + parser.add_argument('--fps', type=int, default=30) + args = parser.parse_args() + if not 1 <= args.fps <= 60: + parser.error('--fps must be between 1 and 60.') + run(args) diff --git a/tools/capture_live_summaries.py b/tools/capture_live_summaries.py new file mode 100644 index 000000000..52ad493ea --- /dev/null +++ b/tools/capture_live_summaries.py @@ -0,0 +1,356 @@ +"""Capture and verify a live full-source summary recomputation on a package copy. + +Example (requires a display or xvfb-run):: + + uv run --no-sync python tools/capture_live_summaries.py \ + --bounded /path/to/bounded --output /fresh/capture --unit 49 --control 50 + +Inputs are read only. The output retains working-bounded/, config/, three real +GUI screenshots and capture.json. Hash preflight warms the filesystem cache; +reported first-job latency includes worker validation and scan, but is not a +cold-storage benchmark. This tool does not establish acquisition exposure truth. +""" + +import argparse +import json +import shutil +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +from capture_long_recording_views import _capture, _close_capture + +from phy.apps.large_recording.curation import project_assignments +from phy.apps.large_recording.source import close_array, hash_file, hash_json +from phy.apps.template.gui import TemplateController +from phy.gui.qt import QApplication, Qt + +REPOSITORY = Path(__file__).resolve().parents[1] +PROVENANCE = 'Converted engineering validation; acquisition exposure unverified' + + +def _package_hashes(path): + return {str(p.relative_to(path)): hash_file(p) for p in sorted(path.rglob('*')) if p.is_file()} + + +def _required_arrays(manifest, events): + names = {'spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy'} + names.update( + event['predicate']['attribute'] + for event in events + if event['operation'] == 'threshold_split' + ) + if 'depth_sum_file' in manifest['summaries']: + names.add( + 'spike_depths.npy' + if 'spike_depths.npy' in manifest['source_array_inventory'] + else 'spike_positions.npy' + ) + return sorted(names) + + +def _wait(predicate, timeout, description, service): + deadline = time.perf_counter() + timeout + while not predicate(): + QApplication.processEvents() + if service._errors: + raise RuntimeError(f'{description}: {list(service._errors.values())}') + if time.perf_counter() >= deadline: + raise TimeoutError(description) + time.sleep(0.01) + + +def _verify_source(source, manifest, events, actual, batch_size): + """Replay every source row independently of the membership-expression engine.""" + arrays = {} + started = time.perf_counter() + try: + for name in _required_arrays(manifest, events): + arrays[name] = np.load(source / name, mmap_mode='r', allow_pickle=False) + edges = np.asarray(actual[next(iter(actual))]['edges']) + bins = len(edges) - 1 + fields = list(actual[next(iter(actual))]['trend_sums']) + expected = { + unit: { + 'counts': np.zeros(bins, dtype=np.int64), + 'trend_sums': {f: np.zeros(bins, dtype=np.float64) for f in fields}, + 'trend_counts': {f: np.zeros(bins, dtype=np.int64) for f in fields}, + } + for unit in actual + } + n_spikes = manifest['num_spikes'] + for start in range(0, n_spikes, batch_size): + stop = min(start + batch_size, n_spikes) + batch = { + name: array[start:stop].reshape(-1) + for name, array in arrays.items() + if name != 'spike_positions.npy' + } + assignments = project_assignments(batch['spike_clusters.npy'], events, batch) + times = batch['spike_times.npy'] + scalars = {'amplitude': batch['amplitudes.npy']} + if 'depth' in fields: + if 'spike_depths.npy' in batch: + scalars['depth'] = batch['spike_depths.npy'] + else: + axis = manifest['source']['identity']['acquisition']['depth_axis'] + scalars['depth'] = arrays['spike_positions.npy'][start:stop, axis] + for unit, summary in expected.items(): + selected = assignments == unit + summary['counts'] += np.histogram(times[selected], bins=edges)[0] + for field in fields: + finite = selected & np.isfinite(scalars[field]) + summary['trend_sums'][field] += np.histogram( + times[finite], + bins=edges, + weights=scalars[field][finite].astype(np.float64), + )[0] + summary['trend_counts'][field] += np.histogram(times[finite], bins=edges)[0] + for unit, summary in expected.items(): + observed = actual[unit] + np.testing.assert_array_equal(observed['counts'], summary['counts']) + for field in fields: + np.testing.assert_array_equal( + observed['trend_counts'][field], summary['trend_counts'][field] + ) + np.testing.assert_allclose( + observed['trend_sums'][field], + summary['trend_sums'][field], + rtol=1e-9, + atol=1e-6, + ) + means = np.full(bins, np.nan) + np.divide( + summary['trend_sums'][field], + summary['trend_counts'][field], + out=means, + where=(summary['trend_counts'][field] > 0) & (observed['exposure'] > 0), + ) + np.testing.assert_allclose( + observed['trends'][field], means, rtol=1e-9, atol=1e-6, equal_nan=True + ) + + return { + 'all_source_rows_checked': int(n_spikes), + 'batch_size': batch_size, + 'verified_unit_ids': list(actual), + 'counts_comparison': 'exact int64', + 'finite_counts_comparison': 'exact int64', + 'finite_sums_comparison': {'dtype': 'float64', 'rtol': 1e-9, 'atol': 1e-6}, + 'seconds': time.perf_counter() - started, + } + finally: + for array in arrays.values(): + close_array(array) + + +def capture(args): + bounded = args.bounded.resolve() + output = args.output.resolve() + manifest = json.loads((bounded / '_phy_curation_manifest.json').read_text()) + source = Path(manifest['source']['path']).resolve() + if source.name == 'params.py': + source = source.parent + if ( + bounded == output + or bounded in output.parents + or source == output + or source in output.parents + ): + raise ValueError('--output must be outside both the bounded input and its source sorting.') + output.mkdir(parents=True, exist_ok=False) + before_package = _package_hashes(bounded) + working = output / 'working-bounded' + shutil.copytree(bounded, working, ignore=shutil.ignore_patterns('.phy', 'phy.log')) + config = output / 'config' + app = QApplication.instance() or QApplication(sys.argv[:1]) + controller = TemplateController( + dir_path=working, config_dir=config, plugins=[], enable_threading=False + ) + gui = None + try: + gui = controller.create_gui( + default_views=['EvidenceAmplitudeView', 'UnitStabilityView'], do_prompt_save=False + ) + service = controller._live_summaries + service.suspend() + session, supervisor = controller.bounded_session, controller.supervisor + initial_events = json.loads(json.dumps(session.events)) + names = _required_arrays(manifest, initial_events) + before_source = {name: hash_file(source / name) for name in names} + required_bytes = sum((source / name).stat().st_size for name in names) + retained = session.attributes['amplitudes.npy'].reshape(-1)[ + session.assignments == args.unit + ] + finite = retained[np.isfinite(retained)] + if len(finite) < 2: + raise ValueError('Selected unit requires at least two finite retained amplitudes.') + threshold = float(np.median(finite)) + selected = np.isfinite(retained) & (retained < threshold) + if not selected.any() or selected.all(): + raise ValueError('Median threshold must leave retained evidence in both children.') + gui.resize(2200, 1250) + gui.setWindowTitle(f'Live exact summaries — {PROVENANCE}') + gui.show() + service.suspend() + amplitude, stability = ( + gui.get_view(name) for name in ('EvidenceAmplitudeView', 'UnitStabilityView') + ) + for name in ('SimilarityView', 'MergePropositionsView', 'PropositionView'): + for view in gui.list_views(name): + view.dock.hide() + gui.splitDockWidget(amplitude.dock, stability.dock, Qt.Horizontal) + gui.resizeDocks([amplitude.dock, stability.dock], [1100, 1100], Qt.Horizontal) + amplitude.amplitude_scope = 'overview' + if args.rate_only: + stability.toggle_amplitude(False) + stability.toggle_depth(False) + controls = [] if args.control is None else [args.control] + supervisor.select([args.unit, *controls]) + supervisor.block() + _capture(gui, output / 'before-split.png') + split_started = time.perf_counter() + update = supervisor.split_source_amplitude(args.unit, threshold) + split_seconds = time.perf_counter() - split_started + children = list(map(int, update.added)) + event = json.loads(json.dumps(session.events[-1])) + supervisor.select([*children, *controls]) + supervisor.block() + if any(controller.get_full_count(child) is not None for child in children): + raise RuntimeError('Fresh split unexpectedly resolved without a live worker.') + timing = {} + + def observe(): + now = time.perf_counter() + if service._running is not None: + timing.setdefault('job_started', now) + if all(controller.get_full_count(child) is not None for child in children): + timing.setdefault('summaries_ready', time.perf_counter()) + + service.changed.connect(observe) + resumed = time.perf_counter() + service.resume() + _wait(lambda: 'job_started' in timing, args.timeout, 'Worker did not start', service) + recomputing_started = all(controller.get_full_count(child) is None for child in children) + _capture(gui, output / 'recomputing.png') + recomputing_finished = all(controller.get_full_count(child) is None for child in children) + _wait( + lambda: all(controller.get_full_count(child) is not None for child in children), + args.timeout, + 'Full-source recomputation did not finish', + service, + ) + observe() + supervisor.block() + _capture(gui, output / 'after-split.png') + events = json.loads(json.dumps(session.events)) + actual = {} + native_edges = np.load(working / manifest['summaries']['edges_file'], allow_pickle=False) + cached_lookup_started = time.perf_counter() + for unit in [*children, *controls]: + data = stability.get_data(unit, metrics=stability._metrics) + np.testing.assert_array_equal(data.edges, native_edges / manifest['sample_rate']) + actual[unit] = { + 'edges': native_edges, + 'counts': data.counts, + 'trend_sums': data.trend_sums, + 'trend_counts': data.trend_counts, + 'trends': data.trends, + 'exposure': data.exposure, + } + if int(data.counts.sum()) != controller.get_full_count(unit): + raise AssertionError('GUI full count disagrees with its displayed summary.') + cached_lookup_seconds = time.perf_counter() - cached_lookup_started + oracle = _verify_source(source, manifest, events, actual, args.batch_size) + after_source = {name: hash_file(source / name) for name in names} + after_package = _package_hashes(bounded) + if before_source != after_source or before_package != after_package: + raise AssertionError('Original source arrays or bounded package changed.') + report = { + 'format': 'phy_live_summary_capture', + 'format_version': 1, + 'capture_tool_sha256': hash_file(Path(__file__)), + 'capture_revision': subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=REPOSITORY, text=True + ).strip(), + 'provenance': PROVENANCE, + 'dataset_label': args.dataset_label, + 'acceptance_scope': 'Existing converted engineering package; not new dataset acceptance', + 'input_package': str(bounded), + 'working_package': str(working), + 'source_directory': str(source), + 'source_binding': manifest['source'], + 'parent_unit': args.unit, + 'control_units': controls, + 'children': children, + 'threshold': threshold, + 'split_event': event, + 'events_sha256': hash_json(events), + 'initial_event_count': len(initial_events), + 'final_event_count': len(events), + 'native_bins': len(next(iter(actual.values()))['counts']), + 'source_spikes': manifest['num_spikes'], + 'retained_spikes': manifest['bounded_num_spikes'], + 'full_counts': {str(unit): int(data['counts'].sum()) for unit, data in actual.items()}, + 'timing_seconds': { + 'bounded_split': split_seconds, + 'resume_to_worker_launch_notification': timing['job_started'] - resumed, + 'first_job_validation_scan_and_gui_delivery': timing['summaries_ready'] - resumed, + 'worker_notification_to_exact_results': timing['summaries_ready'] + - timing['job_started'], + 'resume_to_exact_results': timing['summaries_ready'] - resumed, + 'completed_cached_summary_lookup': cached_lookup_seconds, + }, + 'timing_context': 'Preflight SHA256 warms filesystem cache; not cold-storage latency', + 'source_required_bytes': required_bytes, + 'source_array_inventory': { + name: manifest['source_array_inventory'][name] for name in names + }, + 'source_sha256_before': before_source, + 'source_sha256_after': after_source, + 'input_package_sha256_before': before_package, + 'input_package_sha256_after': after_package, + 'inputs_unchanged': True, + 'oracle': oracle, + 'rate_only': args.rate_only, + 'recomputing_capture_pending_at_entry': recomputing_started, + 'recomputing_capture_pending_at_exit': recomputing_finished, + 'recomputing_capture_note': 'A short job may finish during screenshot rendering; pending flags report observed state.', + 'screenshots': ['before-split.png', 'recomputing.png', 'after-split.png'], + 'gui_size': [gui.width(), gui.height()], + } + (output / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report), flush=True) + return report + finally: + if gui is not None: + _close_capture(gui, controller) + else: + controller.close() + app.quit() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bounded', required=True, type=Path) + parser.add_argument( + '--output', required=True, type=Path, help='Fresh exclusive output directory.' + ) + parser.add_argument('--unit', type=int, default=49) + parser.add_argument('--control', type=int, help='Optional unchanged comparison unit, e.g. 50.') + parser.add_argument('--dataset-label', default='Existing converted engineering package') + parser.add_argument('--rate-only', action='store_true') + parser.add_argument('--timeout', type=float, default=300) + parser.add_argument('--batch-size', type=int, default=100000) + args = parser.parse_args() + if args.timeout <= 0 or args.batch_size <= 0: + parser.error('--timeout and --batch-size must be positive.') + if args.unit == args.control: + parser.error('--control must differ from --unit.') + capture(args) + + +if __name__ == '__main__': + main() diff --git a/tools/capture_long_recording_views.py b/tools/capture_long_recording_views.py new file mode 100644 index 000000000..d05f821fa --- /dev/null +++ b/tools/capture_long_recording_views.py @@ -0,0 +1,575 @@ +"""Capture reproducible screenshots of the bounded-evidence Qt views. + +The script builds a temporary synthetic Phy sorting, prepares it with the real +long-recording workflow, opens the real GUI, and saves screenshots. Existing +bounded inputs are copied into a temporary directory before opening. + +Run with a display, or under a virtual X server:: + + QT_QPA_PLATFORM=xcb LIBGL_ALWAYS_SOFTWARE=1 \ + xvfb-run -a -s '-screen 0 2400x1600x24 +extension GLX' \ + uv run python tools/capture_long_recording_views.py --amplitude-split + +Use ``--amplitude-split --bounded-dir PATH --cluster-ids ID`` for an existing +fresh bounded package, optionally with ``--threshold SOURCE_VALUE``. The three +PNG captures and ``capture.json`` include the exact committed threshold and +retained child sizes; graphical threshold values reflect pixel quantization. +""" + +import argparse +import json +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +import numpy as np +from PyQt5.QtCore import QCoreApplication, QEvent, QPoint, QPointF +from PyQt5.QtGui import QMouseEvent +from PyQt5.QtTest import QTest + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.source import hash_file +from phy.apps.template.gui import TemplateController +from phy.gui.qt import QApplication, Qt +from phy.plot.transform import NDC, Range + +REPOSITORY = Path(__file__).resolve().parents[1] +DEFAULT_OUTPUT = REPOSITORY / 'docs' / 'images' +SAMPLE_RATE = 30_000 +HOURS = 8 +CLUSTER_IDS = np.array([0, 2, 7, 99], dtype=np.int32) + + +def _make_source(path, hours=HOURS, unit_count=4): + """Write a varied but deterministic synthetic source sorting.""" + path.mkdir(parents=True) + rng = np.random.default_rng(20261013) + cluster_ids = CLUSTER_IDS if unit_count == 4 else np.arange(unit_count, dtype=np.int32) + samples = SAMPLE_RATE * 3600 * hours + intervals = np.array( + [[0, 3 * 3600 * SAMPLE_RATE], [int(3.5 * 3600 * SAMPLE_RATE), samples]], + dtype=np.int64, + ) + valid = intervals[:, 1] - intervals[:, 0] + cumulative = np.cumsum(valid) + offsets = rng.integers(0, cumulative[-1], size=120_000, dtype=np.int64) + interval_index = np.searchsorted(cumulative, offsets, side='right') + previous = np.where(interval_index == 0, 0, cumulative[np.maximum(interval_index - 1, 0)]) + spike_times = intervals[interval_index, 0] + offsets - previous + order = np.argsort(spike_times, kind='stable') + spike_times = spike_times[order] + + unit_index = np.arange(len(spike_times), dtype=np.int64) % len(cluster_ids) + unit_index = unit_index[order] + elapsed = spike_times / SAMPLE_RATE + hour_phase = elapsed / 3600 + amplitudes = ( + 35 + + unit_index * 9 + + 5 * np.sin(hour_phase * np.pi / 3) + + 2 * hour_phase + + rng.normal(0, 2.5, len(spike_times)) + ).astype(np.float32) + depths = ( + 250 + + unit_index * 180 + + 20 * np.sin(hour_phase * np.pi / 2) + + rng.normal(0, 8, len(spike_times)) + ).astype(np.float32) + templates_for_spike = unit_index.astype(np.int32) + + np.save(path / 'spike_times.npy', spike_times.astype(np.int64)) + np.save(path / 'spike_clusters.npy', cluster_ids[unit_index]) + np.save(path / 'spike_templates.npy', templates_for_spike) + np.save(path / 'amplitudes.npy', amplitudes) + np.save(path / 'spike_depths.npy', depths) + + channel_map = np.arange(4, dtype=np.int32) + channel_positions = np.array([[0, 0], [20, 100], [0, 200], [20, 300]], dtype=np.float32) + np.save(path / 'channel_map.npy', channel_map) + np.save(path / 'channel_positions.npy', channel_positions) + + templates = np.zeros((len(cluster_ids), 40, len(channel_map)), dtype=np.float32) + time = np.arange(40, dtype=np.float32) + for unit in range(len(cluster_ids)): + center = 13 + (unit % len(channel_map)) * 3 + pulse = -np.exp(-0.5 * ((time - center) / 3.5) ** 2) * (35 + 8 * unit) + for channel in range(len(channel_map)): + templates[unit, :, channel] = pulse * np.exp( + -0.7 * abs(channel - unit % len(channel_map)) + ) + np.save(path / 'templates.npy', templates) + + pc_feature_ind = np.array( + [ + [unit % len(channel_map), (unit + 1) % len(channel_map), (unit + 2) % len(channel_map)] + for unit in range(len(cluster_ids)) + ], + dtype=np.int32, + ) + np.save(path / 'pc_feature_ind.npy', pc_feature_ind) + features = np.empty((len(spike_times), 3, 3), dtype=np.float32) + features[:, 0, :] = unit_index[:, None] * 3.5 + rng.normal(0, 0.65, (len(spike_times), 3)) + features[:, 1, :] = np.sin(hour_phase[:, None] * np.pi / 2) + rng.normal( + 0, 0.7, (len(spike_times), 3) + ) + features[:, 2, :] = np.cos(hour_phase[:, None] * np.pi / 3) + rng.normal( + 0, 0.6, (len(spike_times), 3) + ) + np.save(path / 'pc_features.npy', features) + + # Stored waveforms are a display reservoir, aligned to sorted source rows. + waveform_ids = np.arange(0, len(spike_times), 8, dtype=np.int64) + waveform_channels = np.tile( + np.arange(len(channel_map), dtype=np.int32), (len(waveform_ids), 1) + ) + waveforms = templates[unit_index[waveform_ids]].copy() + waveforms += rng.normal(0, 2.2, waveforms.shape).astype(np.float32) + stem = '_phy_spikes_subset' + np.save(path / f'{stem}.spikes.npy', waveform_ids) + np.save(path / f'{stem}.channels.npy', waveform_channels) + np.save(path / f'{stem}.waveforms.npy', waveforms) + + with (path / 'cluster_group.tsv').open('w', encoding='utf-8') as stream: + stream.write('cluster_id\tgroup\n') + for unit in cluster_ids: + stream.write(f'{unit}\t{"mua" if unit == 7 else "good"}\n') + (path / 'params.py').write_text( + f'sample_rate = {SAMPLE_RATE}.0\n' + f'num_samples = {samples}\n' + 'n_channels_dat = 4\n' + "dtype = 'int16'\n" + 'dat_path = None\n' + f'valid_intervals = {intervals.tolist()!r}\n', + encoding='utf-8', + ) + return path / 'params.py', intervals + + +def _wait_for_render(): + QApplication.processEvents() + QTest.qWait(1200) + QApplication.processEvents() + + +def _capture(gui, destination): + _wait_for_render() + # Phy's OpenGL canvases are native child windows. QWidget.grab() omits + # those children on some Qt/X11 combinations, so grab the rendered screen + # and crop to the application window instead. + screen = QApplication.primaryScreen() + frame = gui.frameGeometry() + pixmap = screen.grabWindow(0).copy(frame.x(), frame.y(), frame.width(), frame.height()) + if not pixmap.save(str(destination), 'PNG'): + raise OSError(f'Could not save screenshot: {destination}') + + +def _close_capture(gui, controller): + gui.close() + controller.close() + gui.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) + QApplication.processEvents() + + +def _capture_comparison(bounded, config_dir, output_dir, selected, dataset_label): + """Capture actual GUI comparisons on an isolated, disposable package.""" + controller = TemplateController( + dir_path=bounded, config_dir=config_dir, plugins=[], enable_threading=False + ) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + try: + gui.resize(2100, 1200) + gui.show() + _wait_for_render() + supervisor = controller.supervisor + started = time.perf_counter() + supervisor.select(selected) + supervisor.block() + selection_seconds = time.perf_counter() - started + view = gui.get_view('UnitStabilityView') + assert list(view.cluster_ids) == supervisor.selected + assert len(view.cluster_ids) >= 2, 'Select at least two retained clusters.' + assert all(ax.get_legend() is None for ax in view.canvas.iter_ax()) + _capture(gui, output_dir / 'after-overview.png') + started = time.perf_counter() + view.toggle_amplitude(False) + view.toggle_depth(False) + rate_only_seconds = time.perf_counter() - started + _capture(gui, output_dir / 'after-rate-only.png') + camera = view.screenshot(dir=output_dir / 'camera') + shutil.copyfile(camera, output_dir / 'camera-rate-only.png') + native = float(np.diff(view.get_data(selected[0]).edges)[0]) + view.set_display_bin_seconds(2 * native) + _capture(gui, output_dir / 'after-rate-coarsened.png') + supervisor.toggle_merge_mode() + supervisor.block() + assert supervisor.selection.state.is_merge_mode + assert list(view.cluster_ids) == supervisor.selected + _capture(gui, output_dir / 'after-merge.png') + manifest = controller.bounded_session.manifest + report = { + 'dataset_label': dataset_label, + 'capture_revision': subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=REPOSITORY, text=True + ).strip(), + 'clock_hours': manifest['num_samples'] / manifest['sample_rate'] / 3600, + 'selected_cluster_ids': selected, + 'displayed_cluster_ids': list(map(int, view.displayed_ids)), + 'merge_cluster_ids': supervisor.selected_merge, + 'summary_bins': len(view.get_data(selected[0]).exposure), + 'full_counts': { + str(unit): int(view.get_data(unit).counts.sum()) for unit in view.displayed_ids + }, + 'timing_seconds': { + 'select_and_block': selection_seconds, + 'rate_only_redraws': rate_only_seconds, + }, + 'gui_size': [gui.width(), gui.height()], + 'display_bins': len(view.get_display_data(selected[0]).exposure), + 'rate_line_width': view.rate_line_width, + 'display_limit': view.display_limit, + 'display_bin_seconds': view.display_bin_seconds, + 'screenshots': [ + 'after-overview.png', + 'after-rate-only.png', + 'after-merge.png', + 'after-rate-coarsened.png', + 'camera-rate-only.png', + ], + 'source_arrays_modified': False, + } + (output_dir / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report), flush=True) + finally: + _close_capture(gui, controller) + + +def _capture_amplitude_split(bounded, config_dir, output_dir, selected, threshold, dataset_label): + """Capture a real threshold drag and K commit on a disposable bounded copy.""" + controller = TemplateController( + dir_path=bounded, config_dir=config_dir, plugins=[], enable_threading=False + ) + gui = controller.create_gui( + default_views=['EvidenceAmplitudeView', 'WaveformView'], do_prompt_save=False + ) + try: + supervisor = controller.supervisor + if controller.bounded_session.events: + raise ValueError('Amplitude capture requires a fresh bounded package without edits.') + if len(selected) != 1: + raise ValueError('Amplitude capture requires exactly one cluster ID.') + unit = selected[0] + ids = supervisor.clustering.spikes_per_cluster.get(unit, np.array([], dtype=np.int64)) + values = controller.bounded_session.attributes.get('amplitudes.npy') + if values is None or not len(ids): + raise ValueError('Select a retained unit with source amplitude evidence.') + amplitudes = values.reshape(-1)[ids] + finite = amplitudes[np.isfinite(amplitudes)] + if not len(finite): + raise ValueError('The selected unit has no finite source amplitudes.') + threshold = float(np.median(finite)) if threshold is None else float(threshold) + if not np.isfinite(threshold): + raise ValueError('The threshold must be finite.') + if not np.any(np.isfinite(amplitudes) & (amplitudes < threshold)) or not np.any( + ~(np.isfinite(amplitudes) & (amplitudes < threshold)) + ): + raise ValueError('Both threshold children must have retained evidence.') + + gui.resize(2200, 1250) + gui.show() + _wait_for_render() + for name in ('ClusterView', 'SimilarityView', 'MergePropositionsView', 'PropositionView'): + for view in gui.list_views(name): + view.dock.hide() + amplitude = gui.get_view('EvidenceAmplitudeView') + waveform = gui.get_view('WaveformView') + gui.splitDockWidget(amplitude.dock, waveform.dock, Qt.Horizontal) + gui.resizeDocks([amplitude.dock, waveform.dock], [1450, 700], Qt.Horizontal) + controller.n_spikes_waveforms = 60 + controller.n_spikes_waveforms_total = 60 + supervisor.select(selected) + supervisor.block() + amplitude.amplitude_scope = 'overview' + waveform.waveforms_type = 'waveforms' + waveform.plot() + _wait_for_render() + _capture(gui, output_dir / 'amplitude-before.png') + + # Deliver actual Qt events to the native OpenGL window. Reuse the view's + # transform so the drag is expressed in unscaled source amplitude units. + canvas = amplitude.canvas + width, height = canvas.get_size() + ndc = Range(amplitude.data_bounds, NDC).apply([[amplitude.duration / 2, threshold]])[0] + screen = (ndc + np.asarray(canvas.panzoom.pan)) * canvas.panzoom._zoom_aspect() + point = QPoint(round((screen[0] + 1) * width / 2), round((1 - screen[1]) * height / 2)) + if not 0 <= point.y() < height: + raise ValueError('The threshold is outside the displayed amplitude range.') + start = QPoint(max(0, point.x() - 20), point.y()) + QTest.mousePress(canvas, Qt.RightButton, Qt.AltModifier, start) + move = QMouseEvent( + QEvent.MouseMove, QPointF(point), Qt.NoButton, Qt.RightButton, Qt.AltModifier + ) + QApplication.sendEvent(canvas, move) + QTest.mouseRelease(canvas, Qt.RightButton, Qt.AltModifier, point) + _wait_for_render() + actual_threshold = amplitude.split_threshold + if actual_threshold is None or not supervisor.actions.get('split').isEnabled(): + raise RuntimeError('The actual Alt-right drag did not create an eligible preview.') + _capture(gui, output_dir / 'amplitude-preview.png') + highlighted = int(len(waveform._highlighted_spike_ids)) + if hasattr(canvas, 'requestActivate'): + canvas.requestActivate() + elif hasattr(canvas, 'setFocus'): + canvas.setFocus() + _wait_for_render() + QTest.keyClick(canvas, Qt.Key_K) + supervisor.block() + _wait_for_render() + if not controller.bounded_session.events: + raise RuntimeError('The actual K key did not commit the threshold predicate.') + event = controller.bounded_session.events[-1] + if event['operation'] != 'threshold_split' or amplitude.split_threshold is not None: + raise RuntimeError('K did not finish the expected semantic threshold split.') + _capture(gui, output_dir / 'amplitude-after.png') + report = { + 'dataset_label': dataset_label, + 'workflow': 'amplitude_split', + 'selected_cluster_ids': selected, + 'amplitude_scope': amplitude.amplitude_scope, + 'requested_source_threshold': threshold, + 'exact_source_threshold': event['predicate']['threshold'], + 'predicate': event['predicate'], + 'retained_parent_count': int(len(ids)), + 'retained_split_sizes': { + str(child): int(supervisor.n_spikes(child)) for child in event['children'] + }, + 'highlighted_waveform_traces': highlighted, + 'gui_size': [gui.width(), gui.height()], + 'screenshots': [ + 'amplitude-before.png', + 'amplitude-preview.png', + 'amplitude-after.png', + ], + 'source_arrays_modified': False, + 'capture_revision': subprocess.check_output( + ['git', 'rev-parse', 'HEAD'], cwd=REPOSITORY, text=True + ).strip(), + } + (output_dir / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report), flush=True) + finally: + _close_capture(gui, controller) + + +def _capture_views(bounded, config_dir, output_dir, stability): + views = ( + ['UnitStabilityView'] + if stability + else [ + 'EvidenceAmplitudeView', + 'FeatureView', + 'SampledISIView', + 'SampledCorrelogramView', + ] + ) + controller = TemplateController( + dir_path=bounded, + config_dir=config_dir, + plugins=[], + enable_threading=False, + ) + gui = controller.create_gui(default_views=views, do_prompt_save=False) + try: + gui.resize(2100, 1200) + gui.show() + _wait_for_render() + # Focus the captures on the plotted evidence rather than the GUI tables. + similarity = gui.get_view('SimilarityView') + if similarity is not None: + similarity.dock.hide() + cluster_table = gui.get_view('ClusterView') + if cluster_table is not None: + cluster_table.dock.hide() + if not stability: + amplitude, feature, isi, correlogram = ( + gui.get_view(name) + for name in ( + 'EvidenceAmplitudeView', + 'FeatureView', + 'SampledISIView', + 'SampledCorrelogramView', + ) + ) + gui.splitDockWidget(amplitude.dock, feature.dock, Qt.Vertical) + gui.splitDockWidget(amplitude.dock, isi.dock, Qt.Horizontal) + gui.splitDockWidget(isi.dock, correlogram.dock, Qt.Vertical) + gui.resizeDocks([amplitude.dock, isi.dock], [1000, 1000], Qt.Horizontal) + gui.resizeDocks([amplitude.dock, feature.dock], [550, 550], Qt.Vertical) + gui.resizeDocks([isi.dock, correlogram.dock], [550, 550], Qt.Vertical) + _wait_for_render() + windows = controller.evidence_windows + times = controller.model.spike_samples + counts = [ + int(np.searchsorted(times, end) - np.searchsorted(times, start)) + for start, end in windows + ] + best_window = int(np.argmax(counts)) + controller.inspect_evidence_window(best_window) + selected = [0] if stability else [0, 2] + controller.supervisor.select(selected) + controller.supervisor.block() + _wait_for_render() + if stability: + filename = 'long-recording-overview.png' + else: + filename = 'long-recording-evidence.png' + destination = output_dir / filename + _capture(gui, destination) + print( + f'{destination} ({gui.width()}x{gui.height()}, window {best_window}, ' + f'{counts[best_window]} evidence spikes)' + ) + finally: + _close_capture(gui, controller) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output-dir', type=Path, default=DEFAULT_OUTPUT) + parser.add_argument( + '--bounded-dir', type=Path, help='Existing package; copied before opening.' + ) + modes = parser.add_mutually_exclusive_group() + modes.add_argument( + '--comparison', action='store_true', help='Capture cluster overlay controls.' + ) + modes.add_argument( + '--amplitude-split', + action='store_true', + help='Capture a source-amplitude drag and K split.', + ) + parser.add_argument( + '--threshold', type=float, help='Source amplitude threshold; default: median.' + ) + parser.add_argument( + '--cluster-ids', + type=int, + nargs='+', + help='Selected IDs; exactly one for amplitude splits.', + ) + parser.add_argument('--dataset-label', help='Dataset provenance label stored in capture.json.') + parser.add_argument('--synthetic-hours', type=int, default=HOURS) + parser.add_argument('--synthetic-units', type=int, default=4) + parser.add_argument('--summary-bin-seconds', type=float, default=1800) + args = parser.parse_args() + if args.synthetic_hours < 4: + parser.error('--synthetic-hours must be at least 4.') + if args.synthetic_units < 2: + parser.error('--synthetic-units must be at least 2.') + if args.bounded_dir and not (args.comparison or args.amplitude_split): + parser.error('--bounded-dir requires --comparison or --amplitude-split.') + if args.threshold is not None and not args.amplitude_split: + parser.error('--threshold requires --amplitude-split.') + if args.amplitude_split and args.cluster_ids and len(args.cluster_ids) != 1: + parser.error('--amplitude-split requires exactly one --cluster-ids ID.') + if args.bounded_dir: + source = args.bounded_dir.resolve() + if not (source / '_phy_curation_manifest.json').is_file(): + parser.error('--bounded-dir must contain a bounded curation manifest.') + if source == args.output_dir.resolve() or source in args.output_dir.resolve().parents: + parser.error('--output-dir must be outside the input bounded package.') + if args.amplitude_split: + if not args.cluster_ids or len(args.cluster_ids) != 1: + parser.error( + '--bounded-dir amplitude splits require exactly one --cluster-ids ID.' + ) + elif not args.cluster_ids or len(args.cluster_ids) < 2: + parser.error('--bounded-dir comparisons require at least two --cluster-ids.') + args.output_dir.mkdir(parents=True, exist_ok=True) + app = QApplication.instance() or QApplication(sys.argv[:1]) + + with tempfile.TemporaryDirectory(prefix='phy-long-recording-screenshots-') as temporary: + root = Path(temporary) + if args.bounded_dir: + bounded = root / 'bounded' + original_hashes = { + str(path.relative_to(source)): hash_file(path) + for path in source.rglob('*') + if path.is_file() + } + shutil.copytree(source, bounded, ignore=shutil.ignore_patterns('.phy', '*.log')) + capture = _capture_amplitude_split if args.amplitude_split else _capture_comparison + extra = [args.threshold] if args.amplitude_split else [] + capture( + bounded, + root / 'config', + args.output_dir, + args.cluster_ids, + *extra, + args.dataset_label + or 'Existing bounded package; acquisition exposure as declared.', + ) + checked_hashes = { + str(path.relative_to(source)): hash_file(path) + for path in source.rglob('*') + if path.is_file() + } + if original_hashes != checked_hashes: + raise RuntimeError('The input bounded package changed during capture.') + report_path = args.output_dir / 'capture.json' + report = json.loads(report_path.read_text()) + report['input_sha256'] = original_hashes + report['input_package_unchanged'] = True + report_path.write_text(json.dumps(report, indent=2) + '\n') + app.quit() + return + params, intervals = _make_source( + root / 'source', hours=args.synthetic_hours, unit_count=args.synthetic_units + ) + bounded = prepare_large( + params, + root / 'bounded', + duration_seconds=args.synthetic_hours * 3600, + valid_intervals=intervals, + max_spikes=20_000, + max_bytes=268_435_456, + window_seconds=30, + stratum_seconds=3600, + seed=0, + batch_size=50_000, + bin_seconds=args.summary_bin_seconds, + ) + if args.amplitude_split: + _capture_amplitude_split( + bounded, + root / 'config', + args.output_dir, + args.cluster_ids or [0], + args.threshold, + args.dataset_label or f'Synthetic {args.synthetic_hours}-hour fixture.', + ) + elif args.comparison: + _capture_comparison( + bounded, + root / 'config', + args.output_dir, + args.cluster_ids + or ( + list(map(int, CLUSTER_IDS[:3])) + if args.synthetic_units == 4 + else list(range(min(12, args.synthetic_units))) + ), + args.dataset_label or f'Synthetic {args.synthetic_hours}-hour fixture.', + ) + else: + _capture_views(bounded, root / 'config-stability', args.output_dir, stability=True) + _capture_views(bounded, root / 'config-evidence', args.output_dir, stability=False) + app.quit() + + +if __name__ == '__main__': + main() diff --git a/tools/capture_summary_store_task.py b/tools/capture_summary_store_task.py new file mode 100644 index 000000000..81d3b8dec --- /dev/null +++ b/tools/capture_summary_store_task.py @@ -0,0 +1,128 @@ +"""Capture actual GUI store preparation and measure the Qt heartbeat on a copy. + +Original inputs are read-only; the output includes a copied bounded package and +new external store. This is a GUI responsiveness trial, not cold-storage timing. +""" + +import argparse +import json +import shutil +import subprocess +import sys +import time +from pathlib import Path + +import numpy as np +from capture_long_recording_views import _capture, _close_capture + +from phy.apps.template.gui import TemplateController +from phy.gui.qt import QApplication, QTimer + + +def run(args): + args.output.mkdir(parents=True, exist_ok=False) + package = args.output / 'bounded' + shutil.copytree( + args.bounded, + package, + ignore=shutil.ignore_patterns('live-summary-cache', 'live-summary-store.json'), + ) + app = QApplication.instance() or QApplication(sys.argv[:1]) + controller = TemplateController( + dir_path=package, config_dir=args.output / 'config', plugins=[] + ) + gui = controller.create_gui(default_views=['UnitStabilityView'], do_prompt_save=False) + actions = controller._summary_store_actions + actions._checked = True + gui.resize(2200, 1250) + gui.setWindowTitle('Summary-store preparation — converted engineering dataset') + gui.show() + controller.supervisor.select([49, 50]) + controller.supervisor.block() + actions.build_dialog() + captures, samples, phases = [], [], [] + + def capture(name): + started = time.perf_counter() + _capture(gui, args.output / name) + captures.append((started, time.perf_counter())) + + def wait_until(predicate, timeout=180): + deadline = time.perf_counter() + timeout + while not predicate(): + if time.perf_counter() > deadline: + raise TimeoutError('GUI summary task did not complete in time.') + app.processEvents() + time.sleep(0.001) + + timer = QTimer() + timer.setInterval(10) + timer.timeout.connect(lambda: samples.append(time.perf_counter())) + actions.manager.progress.connect(lambda p: phases.append((time.perf_counter(), p.stage))) + try: + wait_until(lambda: actions.dialog is not None) + actions.dialog.destination.setText(str(args.output / 'store')) + wait_until(actions.dialog.build_button.isEnabled) + capture('prompt.png') + timer.start() + started = time.perf_counter() + actions.dialog._build() + children = list( + map(int, controller.supervisor.split_source_amplitude(49, -341.797119140625).added) + ) + controller.supervisor.select([*children, 50]) + controller.supervisor.block() + wait_until(lambda: any(stage == 'Building summary store' for _, stage in phases)) + # Allow measured throughput to stabilize before capturing the ETA. + eta_ready = time.perf_counter() + 3 + wait_until(lambda: time.perf_counter() >= eta_ready) + capture('building.png') + wait_until(lambda: any(stage == 'Sorting amplitude ranges' for _, stage in phases)) + eta_ready = time.perf_counter() + 3 + wait_until(lambda: time.perf_counter() >= eta_ready) + capture('indexing.png') + wait_until(lambda: not actions.manager.busy and actions._mode == 'attach-range') + wait_until(lambda: all(controller.get_full_count(u) is not None for u in children)) + duration = time.perf_counter() - started + timer.stop() + capture('ready.png') + intervals = [ + (a, b, b - a) + for a, b in zip(samples[:-1], samples[1:]) + if not any(a <= end and b >= first for first, end in captures) + ] + values = np.array([item[2] for item in intervals]) + report = { + 'revision': subprocess.check_output(['git', 'rev-parse', 'HEAD'], text=True).strip(), + 'source_spikes': controller.bounded_session.manifest['num_spikes'], + 'label': 'Earlier converted 112.859h engineering dataset; not native1000h acceptance', + 'build_attach_and_child_summary_seconds': duration, + 'heartbeat': { + 'target_interval_ms': 10, + 'samples': len(values), + 'p50_ms': float(np.quantile(values, 0.5) * 1000), + 'p95_ms': float(np.quantile(values, 0.95) * 1000), + 'max_ms': float(values.max() * 1000), + 'screenshot_intervals_excluded': True, + }, + 'children': children, + 'child_counts': [int(controller.get_full_count(u)) for u in children], + 'curation_remained_unsaved': controller.supervisor.is_dirty(), + 'stages': list(dict.fromkeys(stage for _, stage in phases)), + 'screenshots': ['prompt.png', 'building.png', 'indexing.png', 'ready.png'], + } + (args.output / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(report, indent=2), flush=True) + finally: + timer.stop() + if actions.manager.busy: + actions.manager.cancel() + wait_until(lambda: not actions.manager.busy) + _close_capture(gui, controller) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bounded', required=True, type=Path) + parser.add_argument('--output', required=True, type=Path) + run(parser.parse_args()) diff --git a/tools/compare_curation_modes.py b/tools/compare_curation_modes.py new file mode 100644 index 000000000..22ae6a33b --- /dev/null +++ b/tools/compare_curation_modes.py @@ -0,0 +1,574 @@ +"""Independent acceptance comparison for complete ordinary and bounded outputs. + +Manual protocol (same ledger on both branches): alias each original unit ID, +merge parents into ``as``, split all spikes of ``parent`` with finite amplitude +strictly below ``threshold`` into ``selected`` (equal/nonfinite => ``remainder``), +then explicitly label every final unit's group and notes. Undo/redo apply to +curation commands; save/reopen are history boundaries. Save, reopen, save again +without editing, and preserve both outputs. Compare COMPLETE replay arrays, +never bounded evidence arrays. Producer metrics (SNR etc.) are excluded: clearing +them on transformed units is an intentional bounded metadata policy. + +Ledger JSON: {"aliases": {"a": 0, "b": 1}, "actions": [ + {"op": "merge", "parents": ["a", "b"], "as": "ab"}, + {"op": "split", "parent": "ab", "threshold": 1.5, + "selected": "low", "remainder": "rest"}, + {"op": "label", "ids": ["low"], "field": "group", "value": "good"}, + {"op": "undo"}, {"op": "redo"}, {"op": "save"}, {"op": "reopen"}], + "expected_labels": {"low": {"group": "good"}}, "fields": ["group", "notes"]}. +Explicit final labels avoid comparing legacy ordinary metadata inheritance with +bounded transformed-unit clearing. Use each GUI's reported IDs to track aliases. +Amplitude predicates must use raw amplitudes.npy; TemplateModel sanitizes nonfinite +values to zero, so GUI lasso/predicate selection on displayed amplitudes alone is +not this protocol. The ordinary engine runs full Supervisor commands without attaching GUI views; +the streamed engine is a separate baseline, NOT full ordinary GUI evidence. +""" + +import argparse +import copy +import csv +import gc +import hashlib +import json +import shutil +import subprocess +from pathlib import Path + +import numpy as np + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + while block := stream.read(1024 * 1024): + h.update(block) + return h.hexdigest() + + +def revision(): + """Identify this checkout without depending on the report's working directory.""" + root = Path(__file__).resolve().parents[1] + try: + top, commit = subprocess.check_output( + ['git', 'rev-parse', '--show-toplevel', 'HEAD'], + cwd=root, + text=True, + stderr=subprocess.DEVNULL, + ).splitlines() + except (OSError, subprocess.CalledProcessError): + return 'unknown' + # An unpacked source archive may itself be inside an unrelated repository. + return commit if Path(top).resolve() == root else 'unknown' + + +def labels(path, fields): + result = {field: {} for field in fields} + tables = sorted(Path(path).glob('cluster_*.tsv')) + sorted(Path(path).glob('cluster_*.csv')) + for table in tables: + # GUI-generated summary duplicates authoritative label tables. + if table.stem == 'cluster_info': + continue + with table.open(newline='') as stream: + reader = csv.DictReader(stream, delimiter=',' if table.suffix == '.csv' else '\t') + if 'cluster_id' not in (reader.fieldnames or []): + raise ValueError(f'Label table lacks cluster_id: {table}') + for row in reader: + unit = int(row['cluster_id']) + for field in fields: + if field in row: + if unit in result[field]: + raise ValueError(f'Duplicate {field} label for {unit}') + result[field][unit] = row[field] + return result + + +def write_labels(path, data): + for field, values in data.items(): + if not field.isidentifier(): + raise ValueError('Label fields must be identifiers') + with (Path(path) / f'cluster_{field}.tsv').open('w', newline='') as stream: + writer = csv.writer(stream, delimiter='\t') + writer.writerow(['cluster_id', field]) + writer.writerows(sorted(values.items())) + + +def compare_outputs( + left, + right, + fields=('group', 'notes'), + chunk_size=100000, + source=None, + expected_labels=None, + bounded_dir=None, +): + """Exact all-row partition equivalence, O(chunk_size + number of units) RAM. + + A two-way raw-ID mapping proves equivalence without partition hash collisions. + SHA256 is used only to identify saved inputs/coordinates, not as that proof. + """ + report = { + 'ok': False, + 'method': 'exact all-row two-way ID mapping', + 'revision': revision(), + 'left': str(Path(left).resolve()), + 'right': str(Path(right).resolve()), + } + try: + if chunk_size <= 0: + raise ValueError('chunk_size must be positive') + arrays = [ + np.load(Path(p) / 'spike_clusters.npy', mmap_mode='r', allow_pickle=False) + for p in (left, right) + ] + times = [ + np.load(Path(p) / 'spike_times.npy', mmap_mode='r', allow_pickle=False) + for p in (left, right) + ] + for a in arrays + times: + if a.ndim not in (1, 2) or (a.ndim == 2 and a.shape[1] != 1): + raise ValueError('Expected scalar per-spike arrays') + if a.dtype.kind not in 'iu': + raise ValueError('Assignments and source sample times must be integers, no NaNs') + arrays = [a.reshape(-1) for a in arrays] + times = [a.reshape(-1) for a in times] + if len({len(a) for a in arrays + times}) != 1: + raise ValueError('Unequal source/output row counts') + report['rows'] = len(arrays[0]) + report['assignment_dtypes'] = [str(a.dtype) for a in arrays] + if times[0].dtype != times[1].dtype: + raise ValueError('Unequal source time dtypes') + forward, reverse = {}, {} + mismatches, examples = 0, [] + for start in range(0, len(arrays[0]), chunk_size): + stop = start + chunk_size + if not np.array_equal(times[0][start:stop], times[1][start:stop]): + raise ValueError(f'Source time row alignment differs at chunk {start}') + aa, bb = arrays[0][start:stop], arrays[1][start:stop] + if np.any(aa < 0) or np.any(bb < 0): + raise ValueError('Negative cluster ID') + # Unique raw pairs retain exact integer comparison; process first occurrences + # in source row order so diagnostics are stable across chunk sizes. + pairs = np.empty(len(aa), dtype=[('left', aa.dtype), ('right', bb.dtype)]) + pairs['left'], pairs['right'] = aa, bb + unique, first, counts = np.unique(pairs, return_index=True, return_counts=True) + for pair_index in np.argsort(first): + a, b = int(unique[pair_index]['left']), int(unique[pair_index]['right']) + if forward.get(a, b) != b or reverse.get(b, a) != a: + mismatches += int(counts[pair_index]) + if len(examples) < 10: + examples.append( + {'row': start + int(first[pair_index]), 'left': a, 'right': b} + ) + else: + forward[a], reverse[b] = b, a + report.update( + partition_mismatch_rows=mismatches, + examples=examples, + id_mapping={str(k): v for k, v in sorted(forward.items())}, + ) + report['saved_provenance'] = { + side: { + name: json.loads((Path(p) / name).read_text()) + for name in ('comparison_reference.json', '_phy_curation_lineage.json') + if (Path(p) / name).exists() + } + for side, p in (('left', left), ('right', right)) + } + report['input_hashes'] = { + side: { + name: digest(Path(p) / name) for name in ('spike_times.npy', 'spike_clusters.npy') + } + for side, p in (('left', left), ('right', right)) + } + permitted = set() + if source is not None: + if __package__: + from tools.curation_output_contract import compare_file_contract + else: + from curation_output_contract import compare_file_contract + + contract, a_labels, b_labels = compare_file_contract( + left, right, source, forward, expected_labels, bounded_dir, chunk_size + ) + report['file_contract'] = contract + permitted = { + (d['field'], d['left_id'], d['right_id'], d['left'], d['right']) + for d in contract['permitted_metadata_differences'] + } + report['permitted_membership_policy_differences'] = contract[ + 'permitted_metadata_differences' + ] + else: + a_labels, b_labels = labels(left, fields), labels(right, fields) + differences = [] + for field in fields: + for a, b in forward.items(): + av, bv = a_labels.get(field, {}).get(a, ''), b_labels.get(field, {}).get(b, '') + if av != bv and (field, a, b, av, bv) not in permitted: + differences.append( + {'field': field, 'left_id': a, 'right_id': b, 'left': av, 'right': bv} + ) + unmapped = { + 'left': { + field: sorted(set(values) - set(forward)) for field, values in a_labels.items() + }, + 'right': { + field: sorted(set(values) - set(reverse)) for field, values in b_labels.items() + }, + } + report['unmapped_label_ids'] = unmapped + report['manual_label_mismatches'] = differences + report['compared_fields'] = list(fields) + report['ok'] = ( + mismatches == 0 + and not differences + and not any(ids for side in unmapped.values() for ids in side.values()) + ) + except (ValueError, OSError, KeyError, TypeError, AttributeError, IndexError) as error: + report['error'] = str(error) + return report + + +def run_reference(source, ledger, output, engine='ordinary', chunk_size=100000): + """Execute a common action ledger independently of bounded journal code. + + Streaming uses disk snapshots and direct masks. Ordinary uses full Supervisor + split with ALL matching source row IDs, never a bounded predicate projector. + Output is a comparison artifact (assignments, times, manual TSVs), not a full + sorting export. No source file is modified. + """ + source, output = Path(source).resolve(), Path(output).resolve() + if output.exists() or source == output or source in output.parents: + raise ValueError('Output must be new and outside the immutable source') + if engine not in ('ordinary', 'streamed') or chunk_size <= 0: + raise ValueError('Invalid reference engine or chunk size') + fields = ledger.get('fields', ['group', 'notes']) + data = labels(source, fields) + aliases = {k: int(v) for k, v in ledger['aliases'].items()} + amplitudes = np.load(source / 'amplitudes.npy', mmap_mode='r').reshape(-1) + output.mkdir(parents=True) + shutil.copyfile(source / 'spike_times.npy', output / 'spike_times.npy') + shutil.copyfile(source / 'spike_clusters.npy', output / 'spike_clusters.npy') + history, future = [], [] + snapshots = [] + state = None + current = None + allocator = 0 + callback_ids = set() + + def dispose(): + nonlocal state, current + from phylib.utils.event import _EVENT + + _EVENT._callbacks = [item for item in _EVENT._callbacks if id(item) not in callback_ids] + callback_ids.clear() + if engine == 'streamed' and state is not None: + state.flush() + state._mmap.close() + current = None + state = None + # Supervisor contains cycles through history and action creators. + gc.collect() + + def reopen(): + nonlocal state, allocator + dispose() + if engine == 'ordinary': + from phy.cluster.supervisor import Supervisor + + class ReferenceSupervisor(Supervisor): + # Presentation hooks only: native command/history/metadata code is unchanged. + def _apply_selection_change(self, *args, **kwargs): + pass + + def _set_merge_mode_ui(self, *args): + pass + + def _reveal_cluster_result(self, *args): + pass + + def _hide_merge_view(self): + pass + + def _workflow_context(self): + return {} + + def _reset_cluster_view(self): + pass + + from phylib.utils.event import _EVENT + + existing = {id(item) for item in _EVENT._callbacks} + try: + state = ReferenceSupervisor( + np.load(output / 'spike_clusters.npy').reshape(-1), + cluster_groups=data.get('group', {}), + cluster_labels={f: d for f, d in data.items() if f != 'group'}, + new_cluster_id=allocator or None, + ) + finally: + callback_ids.update( + id(item) for item in _EVENT._callbacks if id(item) not in existing + ) + state.cluster_view = state.similarity_view = state.select_actions = None + else: + state = np.load(output / 'spike_clusters.npy', mmap_mode='r+').reshape(-1) + + def assignments(): + return state.clustering.spike_clusters if engine == 'ordinary' else state + + def persist(): + nonlocal data + if engine == 'ordinary': + data = {field: state.get_labels(field) for field in fields} + np.save(output / 'spike_clusters.npy', assignments()) + else: + state.flush() + write_labels(output, data) + + try: + reopen() + for index, action in enumerate(ledger['actions']): + op = action['op'] + if op in ('save', 'reopen'): + persist() + if op == 'reopen': + reopen() + history.clear() + future.clear() + continue + if op in ('undo', 'redo'): + if engine == 'ordinary': + getattr(state, op)() + else: + origin, destination = (history, future) if op == 'undo' else (future, history) + if not origin: + raise ValueError(f'No {op} available') + snap = output / f'.history-{index}.npy' + state.flush() + shutil.copyfile(output / 'spike_clusters.npy', snap) + saved_array = np.load(snap, mmap_mode='r').reshape(-1) + snapshots.append(saved_array) + destination.append((saved_array, copy.deepcopy(data))) + saved, data = origin.pop() + for start in range(0, len(state), chunk_size): + state[start : start + chunk_size] = saved[start : start + chunk_size] + continue + if engine == 'streamed': + # Disk snapshots keep RAM bounded even for large reference runs. + snap = output / f'.history-{index}.npy' + state.flush() + shutil.copyfile(output / 'spike_clusters.npy', snap) + saved_array = np.load(snap, mmap_mode='r').reshape(-1) + snapshots.append(saved_array) + history.append((saved_array, copy.deepcopy(data))) + future.clear() + if op == 'label': + ids = [aliases[a] for a in action['ids']] + active = set() + for start in range(0, len(assignments()), chunk_size): + active.update(map(int, np.unique(assignments()[start : start + chunk_size]))) + if not ids or not set(ids) <= active: + raise ValueError('Label aliases must refer to active units') + if engine == 'ordinary': + state.label(action['field'], action['value'], ids) + else: + data.setdefault(action['field'], {}).update( + dict.fromkeys(ids, action['value']) + ) + continue + current = assignments() + next_id = max( + allocator, + ( + max( + ( + int(np.max(current[start : start + chunk_size])) + for start in range(0, len(current), chunk_size) + ), + default=-1, + ) + + 1 + ), + ) + if engine == 'ordinary': + next_id = int(state.clustering.new_cluster_id()) + active = set() + for start in range(0, len(current), chunk_size): + active.update(map(int, np.unique(current[start : start + chunk_size]))) + if op == 'merge': + parents = [aliases[a] for a in action['parents']] + if ( + len(parents) < 2 + or len(set(parents)) != len(parents) + or not set(parents) <= active + ): + raise ValueError('Merge requires distinct active parent aliases') + if engine == 'ordinary': + state.merge(parents) + else: + for start in range(0, len(current), chunk_size): + block = current[start : start + chunk_size] + block[np.isin(block, parents)] = next_id + if engine == 'streamed': + for values in data.values(): + for parent in parents: + values.pop(parent, None) + allocator = next_id + 1 + aliases[action['as']] = next_id + elif op == 'split': + parent, threshold = aliases[action['parent']], float(action['threshold']) + if parent not in active: + raise ValueError('Split parent alias is inactive') + if not np.isfinite(threshold): + raise ValueError('Threshold must be finite') + if engine == 'ordinary': + selected = np.flatnonzero( + (current == parent) & np.isfinite(amplitudes) & (amplitudes < threshold) + ) + if not len(selected) or len(selected) == np.count_nonzero(current == parent): + raise ValueError('Split must have both selected and remainder rows') + state.split(selected) + else: + selected_count, remainder_count = 0, 0 + for start in range(0, len(current), chunk_size): + mask = current[start : start + chunk_size] == parent + values = amplitudes[start : start + chunk_size] + below = np.isfinite(values) & (values < threshold) + selected_count += int(np.count_nonzero(mask & below)) + remainder_count += int(np.count_nonzero(mask & ~below)) + if not selected_count or not remainder_count: + raise ValueError('Split must have both selected and remainder rows') + for start in range(0, len(current), chunk_size): + block = current[start : start + chunk_size] + values = amplitudes[start : start + chunk_size] + mask = block == parent + below = np.isfinite(values) & (values < threshold) + block[mask & below] = next_id + block[mask & ~below] = next_id + 1 + if engine == 'streamed': + for values in data.values(): + values.pop(parent, None) + allocator = next_id + 2 + aliases[action['selected']], aliases[action['remainder']] = next_id, next_id + 1 + else: + raise ValueError(f'Unknown ledger operation: {op}') + persist() + for alias, expected in ledger.get('expected_labels', {}).items(): + for field, value in expected.items(): + if str(data[field].get(aliases[alias], '')) != str(value): + raise ValueError(f'Final label expectation failed: {alias}.{field}') + report = { + 'engine': engine, + 'evidence': ( + 'full ordinary Supervisor, no GUI views attached' + if engine == 'ordinary' + else 'streamed reference, NOT full ordinary GUI' + ), + 'revision': revision(), + 'source': str(source), + 'aliases': aliases, + 'ledger': ledger, + 'input_hashes': { + name: digest(source / name) + for name in ('spike_times.npy', 'spike_clusters.npy', 'amplitudes.npy') + }, + } + (output / 'comparison_reference.json').write_text(json.dumps(report, indent=2) + '\n') + return report + finally: + for saved_array in snapshots: + saved_array._mmap.close() + for snap in output.glob('.history-*.npy'): + snap.unlink() + dispose() + mapping = getattr(amplitudes, '_mmap', None) + if mapping is not None: + mapping.close() + + +def report_path(path, inputs): + """Reject existing paths and all locations inside either immutable input.""" + path = Path(path).resolve() + for root in inputs: + root = Path(root).resolve() + if path == root or root in path.parents: + raise ValueError('Report must be outside both input directories') + if path.exists(): + raise FileExistsError(f'Report already exists: {path}') + return path + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='command', required=True) + compare = sub.add_parser('compare') + compare.add_argument('ordinary') + compare.add_argument('bounded_replay') + compare.add_argument('--fields', nargs='+', default=['group', 'notes']) + compare.add_argument('--output', required=True) + compare.add_argument('--chunk-size', type=int, default=100000) + compare.add_argument( + '--source', help='Original immutable sorting: enable the whole-file contract.' + ) + compare.add_argument( + '--expectations', help='JSON map of replay unit IDs to explicit final field values.' + ) + compare.add_argument( + '--bounded-dir', help='Final round package, to verify preparation/parent binding.' + ) + reference = sub.add_parser('reference') + reference.add_argument('source') + reference.add_argument('ledger') + reference.add_argument('output') + reference.add_argument('--engine', choices=['ordinary', 'streamed'], default='ordinary') + reference.add_argument('--chunk-size', type=int, default=100000) + args = parser.parse_args() + if args.command == 'compare': + try: + if (args.expectations or args.bounded_dir) and not args.source: + raise ValueError('--expectations and --bounded-dir require --source') + inputs = [args.ordinary, args.bounded_replay] + if args.bounded_dir: + inputs.append(args.bounded_dir) + if args.source: + source_path = Path(args.source).resolve() + inputs.append(source_path.parent if source_path.is_file() else source_path) + destination = report_path(args.output, inputs) + result = compare_outputs( + args.ordinary, + args.bounded_replay, + args.fields, + args.chunk_size, + source=args.source, + expected_labels=json.loads(Path(args.expectations).read_text()) + if args.expectations + else None, + bounded_dir=args.bounded_dir, + ) + # Exclusive creation also rejects another writer winning after validation. + with destination.open('x') as stream: + json.dump(result, stream, indent=2, allow_nan=False) + stream.write('\n') + except (ValueError, OSError) as error: + print(json.dumps({'ok': False, 'error': str(error)})) + return 1 + print(json.dumps({'ok': result['ok'], 'report': args.output})) + return 0 if result['ok'] else 1 + try: + result = run_reference( + args.source, + json.loads(Path(args.ledger).read_text()), + args.output, + args.engine, + args.chunk_size, + ) + except (ValueError, OSError, KeyError) as error: + print(json.dumps({'ok': False, 'error': str(error)})) + return 1 + print(json.dumps({'ok': True, 'evidence': result['evidence'], 'output': args.output})) + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/curation_output_contract.py b/tools/curation_output_contract.py new file mode 100644 index 000000000..3ad867b31 --- /dev/null +++ b/tools/curation_output_contract.py @@ -0,0 +1,1036 @@ +"""Source-grounded file contract for independent curation acceptance. + +This checker does not call the bounded assignment projector or metadata event +interpreter. It checks native files, full row identities, and cumulative action +semantics against the original source and explicit final curator expectations. +""" + +import ast +import csv +import hashlib +import json +import runpy +from pathlib import Path + +import numpy as np + +from phy.apps.large_recording.source import Source + + +def _json(path): + return json.loads(Path(path).read_text(encoding='utf-8')) + + +def _hash(path): + value = hashlib.sha256() + with Path(path).open('rb') as stream: + for block in iter(lambda: stream.read(1024 * 1024), b''): + value.update(block) + return value.hexdigest() + + +def _json_hash(value, newline=False): + text = json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + return hashlib.sha256((text + ('\n' if newline else '')).encode()).hexdigest() + + +def _cell(value): + if value is None or value == '': + return '' + if isinstance(value, (dict, list, bool)): + return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + return str(value) + + +def _table(path): + with path.open(encoding='utf-8', newline='') as stream: + reader = csv.DictReader(stream, delimiter=',' if path.suffix == '.csv' else '\t') + columns = reader.fieldnames or [] + if ( + len(columns) < 2 + or columns.count('cluster_id') != 1 + or len(set(columns)) != len(columns) + ): + raise ValueError(f'Invalid metadata columns: {path.name}') + values = {field: {} for field in columns if field != 'cluster_id'} + seen = set() + for row in reader: + if None in row or any(v is None for v in row.values()): + raise ValueError(f'Malformed metadata row: {path.name}') + unit = int(row['cluster_id']) + if unit < 0 or unit in seen: + raise ValueError(f'Invalid or duplicate metadata unit: {path.name}') + seen.add(unit) + for field in values: + values[field][unit] = row[field] + return columns, values + + +def _native_metadata(path, source, fields, active_ids): + """Native canonical tables take precedence only over proven source aliases.""" + tables = { + p.name: _table(p) + for p in sorted([*path.glob('cluster_*.tsv'), *path.glob('cluster_*.csv')]) + if p.stem != 'cluster_info' + } + source_tables = {t['filename']: t for t in source.metadata_schema['tables']} + canonical, aliases = {}, [] + for field in fields: + name = f'cluster_{field}.tsv' + if name in tables and tables[name][0] == ['cluster_id', field]: + canonical[field] = tables[name][1][field] + result = {} + active_ids = set(active_ids) + + def current_rows(name, field, rows): + # Native loading omits completely blank imported columns, leaving their + # original files untouched even after some original IDs are retired. + # Recognize only an exact byte-pinned, entirely blank source column. + if ( + set(rows) - active_ids + and name in source_tables + and all(not _cell(v) for v in source.metadata.get(field, {}).values()) + and _hash(path / name) == _hash(source.path / name) + ): + aliases.append( + {'filename': name, 'field': field, 'policy': 'byte-pinned blank source column'} + ) + return {u: v for u, v in rows.items() if u in active_ids} + return rows + + for name, (columns, values) in tables.items(): + if len(values) == 1: + field = next(iter(values)) + if name == f'cluster_{field}.tsv' and field in canonical: + if field not in fields: + raise ValueError(f'Unexpected native metadata field: {field}') + result[field] = current_rows(name, field, canonical[field]) + continue + descriptor = source_tables.get(name) + if descriptor is None or columns != descriptor['columns']: + raise ValueError(f'Unsupported ordinary metadata layout: {name}') + if _hash(path / name) != _hash(source.path / name): + raise ValueError(f'Ordinary source alias changed: {name}') + for field, rows in values.items(): + if field in canonical: + aliases.append( + {'filename': name, 'field': field, 'policy': 'unchanged source alias'} + ) + elif field in result: + raise ValueError(f'Ambiguous ordinary metadata field: {field}') + else: + result[field] = current_rows(name, field, rows) + return result, aliases, set(tables) + + +def _parameters(path, source): + values = { + k: v for k, v in runpy.run_path(str(path / 'params.py')).items() if not k.startswith('__') + } + + def parameter_code(filename): + tree = ast.parse(filename.read_bytes()) + tree.body = [ + node + for node in tree.body + if not ( + isinstance(node, ast.Assign) + and len(node.targets) == 1 + and isinstance(node.targets[0], ast.Name) + and node.targets[0].id in ('dat_path', 'num_samples', 'valid_intervals') + ) + ] + return ast.dump(tree, include_attributes=False) + + if parameter_code(path / 'params.py') != parameter_code(source.params_path): + raise ValueError('Changed parameter Python outside managed overrides') + allowed_added = {'num_samples', 'valid_intervals'} + if set(values) - set(source.params) - allowed_added: + raise ValueError('Unexpected added parameter keys') + if set(source.params) - set(values): + raise ValueError('Missing source parameter keys') + for key, value in source.params.items(): + if key in ('dat_path', 'num_samples', 'valid_intervals'): + continue + if callable(value) or type(value).__name__ == 'module': + continue # Unchanged helper/import syntax was checked above. + if not np.array_equal(values[key], value): + raise ValueError(f'Changed source parameter: {key}') + if values.get('num_samples', source.num_samples) != source.num_samples: + raise ValueError('Changed recording extent') + if not np.array_equal( + values.get('valid_intervals', source.valid_intervals), source.valid_intervals + ): + raise ValueError('Changed acquisition exposure') + + def raw_paths(value, base): + items = value if isinstance(value, (tuple, list)) else [value] + return [ + str((base / str(p)).resolve()) + for p in items + if p is not None and str(p).strip() not in ('', 'None') + ] + + expected = raw_paths(source.params.get('dat_path'), source.path) + actual = raw_paths(values.get('dat_path'), path) + if actual != expected: + raise ValueError('Changed raw data reference') + + +def _history_records(provenance): + if not isinstance(provenance, dict) or not isinstance(provenance.get('history'), list): + raise ValueError('Malformed metadata provenance/history') + if any( + not isinstance(record, dict) or not isinstance(record.get('operation'), str) + for record in provenance['history'] + ): + raise ValueError('Malformed metadata history record') + return provenance['history'] + + +def _predicate(value, arrays): + if not isinstance(value, dict) or set(value) != { + 'attribute', + 'operator', + 'threshold', + 'nonfinite', + }: + raise ValueError('Malformed threshold predicate') + threshold = value['threshold'] + if ( + value['attribute'] not in ('amplitudes.npy', 'spike_templates.npy') + or value['attribute'] not in arrays + or value['operator'] not in ('<', '<=', '>', '>=') + or value['nonfinite'] not in ('keep', 'reject') + or isinstance(threshold, bool) + or not isinstance(threshold, (int, float)) + or not np.isfinite(threshold) + ): + raise ValueError('Unsupported threshold predicate schema') + + +def _event_schema(event, record, arrays): + operation = event.get('operation') + keys = { + 'merge': {'version', 'operation', 'parents', 'target', 'metadata'}, + 'threshold_split': {'version', 'operation', 'parent', 'children', 'predicate', 'metadata'}, + 'restore_parents': { + 'version', + 'operation', + 'target', + 'children', + 'merge_event_index', + 'merge_prefix_sha256', + 'source_revision', + 'metadata', + }, + 'label': {'version', 'operation', 'field', 'ids', 'value'}, + } + if operation == 'restore_parents' and event.get('version') == 4: + keys[operation].add('parent_references') + if ( + operation not in keys + or set(event) != keys[operation] + or type(event['version']) is not int + or event['version'] not in ((3, 4) if operation == 'restore_parents' else (2,)) + ): + raise ValueError('Malformed current journal event schema') + if operation == 'label': + return + metadata = event['metadata'] + # New memberships also introduce the built-in unreviewed group field. + fields = set(record['parent_metadata']) | {'group'} + if not isinstance(metadata, dict) or set(metadata) != fields: + raise ValueError('Journal membership metadata field coverage disagrees') + if operation == 'merge': + valid = all(value is None for value in metadata.values()) + else: + if operation == 'threshold_split': + _predicate(event['predicate'], arrays) + children = {str(u) for u in event['children']} + valid = all( + isinstance(values, dict) + and set(values) == children + and all(value is None for value in values.values()) + for values in metadata.values() + ) + if not valid: + raise ValueError('Journal membership metadata contradicts clearing policy') + + +def _history(source, curated, journal, manifest, expected_labels): + """Track only action ancestry and explicit label intent, never spike projection.""" + original = _history_records(source.metadata_provenance) + history = _history_records(curated.metadata_provenance) + if history[: len(original)] != original: + raise ValueError('Lost original metadata provenance') + if set(curated.metadata_provenance) != set(source.metadata_provenance) or any( + curated.metadata_provenance[k] != value + for k, value in source.metadata_provenance.items() + if k != 'history' + ): + raise ValueError('Changed non-history metadata provenance') + inherited = ( + _history_records(manifest.get('metadata_provenance', {'history': []})) + if manifest is not None + else original + ) + if history[: len(inherited)] != inherited or len(history) != len(inherited) + len(journal): + raise ValueError('Cumulative metadata history disagrees with preparation/journal') + for event_index, (event, record) in enumerate( + zip(journal, history[len(inherited) :], strict=True) + ): + _event_schema(event, record, source.arrays) + operation = event['operation'] + if operation != record['operation']: + raise ValueError('Journal operation/version disagrees with history') + if operation == 'merge': + valid = record['parents'] == event['parents'] and record['children'] == [ + event['target'] + ] + elif operation == 'threshold_split': + valid = ( + record['parents'] == [event['parent']] + and record['children'] == event['children'] + and record['predicate'] == event['predicate'] + ) + elif operation == 'restore_parents': + origin = event['merge_event_index'] + valid = ( + type(origin) is int + and 0 <= origin < event_index + and journal[origin]['operation'] == 'merge' + and event['merge_prefix_sha256'] == _json_hash(journal[: origin + 1]) + and record['parents'] == [event['target']] + and record['children'] == event['children'] + and record.get('parent_references') == event.get('parent_references') + and all( + record[key] == event[key] + for key in ('merge_event_index', 'merge_prefix_sha256', 'source_revision') + ) + ) + elif operation == 'label': + valid = record == event + else: + raise ValueError('Unsupported metadata policy transition in contract') + if not valid: + raise ValueError('Journal details disagree with cumulative history') + if operation in ('merge', 'threshold_split', 'restore_parents'): + parent_revision = ( + manifest['source']['revision'] if manifest is not None else source.revision + ) + if record['event_index'] != event_index: + raise ValueError('Membership provenance has wrong event index') + if record['source_revision'] != parent_revision: + raise ValueError('Membership provenance has wrong source revision') + fields = set(source.metadata) + if any( + record['operation'] in ('merge', 'threshold_split', 'restore_parents') + for record in history[len(original) :] + ): + fields.add('group') + fields.update( + record['field'] for record in history[len(original) :] if record['operation'] == 'label' + ) + if any(set(values) - fields for values in expected_labels.values()): + raise ValueError('Expected labels have no source field or recorded label intent') + if set(curated.metadata) != fields: + raise ValueError('Unexpected replay metadata fields without label intent') + candidates = { + int(u): {f: {_cell(source.metadata.get(f, {}).get(int(u)))} for f in fields} + for u in source.unit_ids + } + resolved = { + f: {int(u): _cell(v) for u, v in values.items()} for f, values in source.metadata.items() + } + active = set(candidates) + origins = dict.fromkeys(active) + merge_origins = {} + component_nodes = {unit: (unit, -1, None) for unit in active} + merge_components = {} + next_id = source.next_cluster_id + retired = dict(source.retired_units) + explicit = {} + for record in history[len(original) :]: + operation = record['operation'] + id_lists = ('ids',) if operation == 'label' else ('parents', 'children') + for key in id_lists: + ids = record.get(key) + if ( + not isinstance(ids, list) + or not ids + or any(type(u) is not int or u < 0 for u in ids) + or len(set(ids)) != len(ids) + ): + raise ValueError('Malformed unit IDs in metadata history') + if operation == 'label': + field, value = record['field'], _cell(record['value']) + if field not in fields or not set(record['ids']) <= active: + raise ValueError('History label has unknown field/unit') + for unit in record['ids']: + candidates[unit][field] = {value} + explicit.setdefault(unit, {})[field] = value + resolved.setdefault(field, {})[unit] = value + elif operation in ('merge', 'threshold_split', 'restore_parents'): + record_keys = { + 'operation', + 'source_revision', + 'event_index', + 'parents', + 'children', + 'parent_metadata', + 'policy', + } + if operation == 'threshold_split': + record_keys.add('predicate') + elif operation == 'restore_parents': + record_keys.update({'merge_event_index', 'merge_prefix_sha256'}) + if 'parent_references' in record: + record_keys.add('parent_references') + if set(record) != record_keys: + raise ValueError('Unexpected membership provenance fields') + parents, children = record['parents'], record['children'] + if ( + (operation == 'merge' and len(parents) < 2) + or (operation == 'threshold_split' and len(parents) != 1) + or (operation == 'restore_parents' and len(parents) != 1) + ): + raise ValueError('Invalid membership parent cardinality') + if operation == 'threshold_split': + _predicate(record['predicate'], source.arrays) + if ( + record.get('policy') != 'membership_v1' + or len(set(parents)) != len(parents) + or not set(parents) <= active + ): + raise ValueError('Unsupported or inactive membership history') + if ( + (operation == 'merge' and len(children) != 1) + or (operation == 'threshold_split' and len(children) != 2) + or (operation == 'restore_parents' and len(children) < 2) + or len(set(children)) != len(children) + or min(children) < next_id + ): + raise ValueError('Invalid allocated history identities') + snapshot = { + f: {str(u): values.get(u, '') for u in parents} for f, values in resolved.items() + } + recorded = { + f: {str(u): _cell(v) for u, v in values.items()} + for f, values in record['parent_metadata'].items() + } + if snapshot != recorded: + raise ValueError('Parent metadata provenance disagrees with independent history') + inherited = {f: set().union(*(candidates[u][f] for u in parents)) for f in fields} + key = (record['source_revision'], record['event_index']) + if operation == 'merge': + merge_origins[key] = [origins.pop(parent) for parent in parents] + origins[children[0]] = key + parts = tuple(component_nodes.pop(parent) for parent in parents) + merge_components[key] = parts + component_nodes[children[0]] = (children[0], record['event_index'], parts) + elif operation == 'threshold_split': + origins.pop(parents[0]) + origins.update(dict.fromkeys(children)) + component_nodes.pop(parents[0]) + component_nodes.update( + {child: (child, record['event_index'], None) for child in children} + ) + else: + reference = (record['source_revision'], record['merge_event_index']) + if origins.pop(parents[0]) != reference or reference not in merge_origins: + raise ValueError('Restore does not reference its unchanged live merge origin') + parts = merge_components[reference] + component_nodes.pop(parents[0]) + if 'parent_references' in record: + pending = list(reversed(parts)) + leaves = [] + while pending: + node = pending.pop() + if node[2] is None: + leaves.append(node) + else: + pending.extend(reversed(node[2])) + parts = leaves + refs = record['parent_references'] + if refs != [{'unit': node[0], 'event_index': node[1]} for node in parts]: + raise ValueError( + 'Recursive references disagree with independent merge ancestry' + ) + if not isinstance(refs, list) or len(refs) != len(children): + raise ValueError('Recursive restoration references lose a parent') + if any( + not isinstance(ref, dict) + or set(ref) != {'unit', 'event_index'} + or type(ref['unit']) is not int + or type(ref['event_index']) is not int + or ref['unit'] < 0 + or ref['event_index'] < -1 + or ref['event_index'] >= record['merge_event_index'] + for ref in refs + ): + raise ValueError('Invalid recursive historical reference') + if len({(ref['event_index'], ref['unit']) for ref in refs}) != len(refs): + raise ValueError('Repeated recursive historical reference') + origins.update(dict.fromkeys(children)) + else: + if len(children) != len(merge_origins[reference]): + raise ValueError('Restore loses an immediate historical parent') + origins.update(dict(zip(children, merge_origins[reference], strict=True))) + component_nodes.update(dict(zip(children, parts, strict=True))) + active.difference_update(parents) + for parent in parents: + retired[str(parent)] = {'operation': operation, 'replacements': children} + for parent in parents: + explicit.pop(parent, None) + for values in resolved.values(): + values.pop(parent, None) + resolved.setdefault('group', {}) + for child in children: + candidates[child] = ( + {f: {''} for f in fields} + if operation == 'restore_parents' + else {f: set(v) for f, v in inherited.items()} + ) + for values in resolved.values(): + values[child] = '' + active.add(child) + next_id = max(children) + 1 + else: + raise ValueError(f'Unsupported cumulative history operation: {operation}') + if retired != curated.retired_units: + raise ValueError('Retired unit lineage disagrees with independent history') + if curated.next_cluster_id < next_id: + raise ValueError('Allocation floor disagrees with cumulative history') + if active != set(map(int, curated.unit_ids)): + raise ValueError('Final catalog disagrees with independent action ancestry') + if not set(expected_labels) <= active: + raise ValueError('Explicit expectations refer to inactive units') + for unit, values in explicit.items(): + for field, value in values.items(): + if expected_labels.get(unit, {}).get(field) != value: + raise ValueError( + f'Missing or wrong independent final label expectation: {unit}.{field}' + ) + for unit, values in expected_labels.items(): + for field, value in values.items(): + intended = explicit.get(unit, {}).get( + field, + _cell(source.metadata.get(field, {}).get(unit)) + if unit in set(map(int, source.unit_ids)) + else '', + ) + if value != intended: + raise ValueError('Independent expectation disagrees with recorded label intent') + return fields, candidates, explicit, active, history[len(original) :] + + +def _assignment_oracle(source, curated, history, chunk_size): + """Independently execute cumulative membership intent on every original row. + + Attribute values always come from the immutable original source. Only a + chunk of assignments is copied, including when earlier rounds split a unit + that is subsequently merged or split again. Labels have no row effect. + """ + original = source.arrays['spike_clusters.npy'].reshape(-1) + current = curated.arrays['spike_clusters.npy'].reshape(-1) + membership = [r for r in history if r['operation'] != 'label'] + attributes = {} + for record in membership: + if record['operation'] != 'threshold_split': + continue + name = record['predicate']['attribute'] + values = source.arrays[name] + if values.shape not in ((len(original),), (len(original), 1)): + raise ValueError('Predicate attribute must be a scalar per source spike') + attributes[name] = values.reshape(-1) + if len(current) != len(original): + raise ValueError('Assignment oracle requires complete source rows') + references = { + (r.get('source_revision'), r['merge_event_index']) + for r in membership + if r['operation'] == 'restore_parents' + } + leaf_references = { + (r.get('source_revision'), ref['event_index'], ref['unit']) + for r in membership + if r['operation'] == 'restore_parents' + for ref in r.get('parent_references', []) + } + # Retain only referenced pre-merge parent masks, and bound their aggregate + # scratch space independently of the number of source spikes or restores. + slots = sum( + len(r['parents']) + for i, r in enumerate(history) + if r['operation'] == 'merge' + and (r.get('source_revision'), r.get('event_index', i)) in references + ) + chunk_size = min(chunk_size, max(1, (32 * 1024 * 1024) // (slots + len(leaf_references) + 64))) + for start in range(0, len(original), chunk_size): + stop = start + chunk_size + expected = np.array(original[start:stop], dtype=np.int64, copy=True) + snapshots = {} + leaf_masks = {} + last_revision = object() + for event_index, record in enumerate(history): + revision = record.get('source_revision') + if revision is not None and revision != last_revision: + for rev, created, unit in leaf_references: + if rev == revision and created == -1: + leaf_masks[(rev, created, unit)] = expected == unit + last_revision = revision + if record['operation'] == 'label': + continue + parents, children = record['parents'], record['children'] + if record['operation'] == 'merge': + key = (record.get('source_revision'), record.get('event_index', event_index)) + if key in references: + snapshots[key] = [expected == parent for parent in parents] + expected[np.isin(expected, parents)] = children[0] + continue + if record['operation'] == 'restore_parents': + key = (record.get('source_revision'), record['merge_event_index']) + if 'parent_references' in record: + masks = [] + for ref in record['parent_references']: + reference = ( + record.get('source_revision'), + ref['event_index'], + ref['unit'], + ) + if reference not in leaf_masks: + raise ValueError('Restore oracle missing historical leaf mask') + masks.append(leaf_masks[reference]) + else: + if key not in snapshots or len(snapshots[key]) != len(children): + raise ValueError( + 'Restore oracle has no complete original parent partition' + ) + masks = snapshots[key] + target = expected == parents[0] + covered = np.zeros(len(expected), dtype=bool) + for child, mask in zip(children, masks, strict=True): + if np.any(mask & ~target) or np.any(mask & covered): + raise ValueError('Restore oracle parent partition is no longer intact') + expected[mask] = child + covered |= mask + if not np.array_equal(covered, target): + raise ValueError('Restore oracle partition does not cover its target') + continue + if record['operation'] != 'threshold_split': + raise ValueError('Unsupported independent assignment operation') + parent_rows = np.flatnonzero(expected == parents[0]) + predicate = record['predicate'] + values = attributes[predicate['attribute']][start:stop][parent_rows] + finite = np.isfinite(values) + if predicate['nonfinite'] == 'reject' and not finite.all(): + raise ValueError('Predicate rejects nonfinite values in source parent rows') + threshold = predicate['threshold'] + operator = predicate['operator'] + if operator == '<': + selected = values < threshold + elif operator == '<=': + selected = values <= threshold + elif operator == '>': + selected = values > threshold + else: # Schema has already restricted the fourth operator to >=. + selected = values >= threshold + # Nonfinite values always remain in the first (remainder) child. + expected[parent_rows] = np.where(finite & selected, children[1], children[0]) + for child in children: + key = ( + record.get('source_revision'), + record.get('event_index', event_index), + child, + ) + if key in leaf_references: + leaf_masks[key] = expected == child + mismatch = np.flatnonzero(expected != current[start:stop]) + if len(mismatch): + row = start + int(mismatch[0]) + raise ValueError( + f'Assignment disagrees with cumulative source predicates at spike {row}' + ) + return { + 'verified': True, + 'source_rows': len(original), + 'membership_events': len(membership), + 'threshold_splits': sum(r['operation'] == 'threshold_split' for r in membership), + } + + +def _local_file(root, name): + if ( + not isinstance(name, str) + or not name + or Path(name).name != name + or any(c in name for c in ('\\', '\0', '\n', '\r')) + ): + raise ValueError('Unsafe checkpoint asset name') + path = root / name + if path.is_symlink() or not path.is_file(): + raise ValueError('Missing or linked checkpoint asset') + return path + + +def _checkpoint(bounded, manifest, lineage, journal, right, curated, chunk_size): + """Bind the exact saved generation, including allocator and retained rows.""" + root = Path(bounded) + pointer = _json(root / '.phy-curation/current.json') + generation = pointer['generation'] + if ( + not isinstance(generation, str) + or len(generation) != 32 + or any(c not in '0123456789abcdef' for c in generation) + ): + raise ValueError('Invalid checkpoint generation') + directory = root / '.phy-curation/generations' / generation + descriptor = _json(_local_file(directory, 'checkpoint.json')) + if set(pointer) != {'generation', 'sha256'} or descriptor.get('version') != 1: + raise ValueError('Unsupported checkpoint pointer/descriptor') + if pointer['sha256'] != _json_hash(descriptor, newline=True) or descriptor[ + 'manifest_sha256' + ] != _json_hash(manifest, newline=True): + raise ValueError('Checkpoint pointer/manifest binding changed') + required = {'spike_clusters.npy', 'journal.json', 'metadata.json'} + inventory = descriptor['files'] + if not required <= set(inventory) or not set(descriptor['extra_documents']) <= set(inventory): + raise ValueError('Checkpoint inventory is incomplete') + if {p.name for p in directory.iterdir()} != set(inventory) | {'checkpoint.json'}: + raise ValueError('Unexpected checkpoint generation assets') + for name, digest in inventory.items(): + if _hash(_local_file(directory, name)) != digest: + raise ValueError('Checkpoint asset hash changed') + if _json(directory / 'journal.json') != journal or _json(directory / 'metadata.json') != _json( + right / '_phy_cluster_metadata.json' + ): + raise ValueError('Export differs from saved journal/metadata generation') + for key in ('next_cluster_id', 'metadata_policy', 'metadata_provenance'): + if descriptor[key] != lineage[key]: + raise ValueError(f'Export differs from saved checkpoint: {key}') + if descriptor['metadata_schema'] != curated.metadata_schema: + raise ValueError('Export metadata schema differs from saved checkpoint') + if 'curation_review.json' in inventory and _json(directory / 'curation_review.json') != _json( + right / 'curation_review.json' + ): + raise ValueError('Export review differs from saved checkpoint') + name = manifest['global_spike_ids_file'] + ids_path = _local_file(root, name) + if _hash(ids_path) != manifest['bounded_files'][name]: + raise ValueError('Retained row identity hash changed') + ids = saved = None + try: + ids = np.load(ids_path, mmap_mode='r', allow_pickle=False) + saved = np.load(directory / 'spike_clusters.npy', mmap_mode='r', allow_pickle=False) + if ( + ids.dtype != np.int64 + or ids.shape != (manifest['bounded_num_spikes'],) + or saved.shape != ids.shape + or saved.dtype.kind not in 'iu' + ): + raise ValueError('Invalid saved retained assignment alignment') + if np.any(ids < 0) or np.any(ids >= curated.n_spikes) or np.any(ids[1:] <= ids[:-1]): + raise ValueError('Invalid retained row coordinates') + full = curated.arrays['spike_clusters.npy'].reshape(-1) + for start in range(0, len(ids), chunk_size): + if not np.array_equal( + full[ids[start : start + chunk_size]], saved[start : start + chunk_size] + ): + raise ValueError('Full replay disagrees with saved retained assignments') + finally: + for array in (ids, saved): + if array is not None: + array._mmap.close() + return generation + + +def compare_file_contract( + left, right, source_path, mapping, expected_labels=None, bounded_dir=None, chunk_size=100000 +): + """Return file report plus normalized native/replay label maps. + + ``source_path`` is the original immutable source even across multiple rounds. + Current preparation binding is verified when ``bounded_dir`` is supplied; + older revisions are recorded ancestry, not independently fetched snapshots. + """ + left, right = Path(left), Path(right) + source_path = Path(source_path) + params = source_path if source_path.is_file() else source_path / 'params.py' + expected_labels = { + int(u): {f: _cell(v) for f, v in values.items()} + for u, values in (expected_labels or {}).items() + } + source = curated = None + try: + source = Source(params, batch_size=chunk_size) + curated = Source(right / 'params.py', batch_size=chunk_size) + if source.identity != curated.identity: + raise ValueError('Replay immutable coordinate identity differs from original source') + lineage = _json(right / '_phy_curation_lineage.json') + lineage_keys = { + 'format', + 'format_version', + 'coordinate_identity', + 'parent_revision', + 'journal_sha256', + 'revision', + 'preparation_sha256', + 'next_cluster_id', + 'unit_ids', + 'retired_units', + 'proposition_documents', + 'metadata_provenance', + 'metadata_policy', + } + if set(lineage) != lineage_keys: + raise ValueError('Unexpected lineage fields') + proposition_hashes = { + name: _hash(right / name) + for name in ('curation.json', 'curation_review.json') + if (right / name).exists() + } + if lineage['proposition_documents'] != proposition_hashes: + raise ValueError('Missing or wrong proposition lineage bindings') + journal = _json(right / '_phy_curation_journal.json') + if lineage.get('metadata_policy') != 'membership_v1': + raise ValueError('Strict file contract requires membership_v1 replay') + if lineage.get('journal_sha256') != _json_hash(journal, newline=True): + raise ValueError('Journal hash disagrees with lineage') + manifest = None + if bounded_dir is not None: + manifest = _json(Path(bounded_dir) / '_phy_curation_manifest.json') + if ( + manifest.get('format') != 'phy_bounded_curation' + or manifest.get('format_version') != 1 + ): + raise ValueError('Unsupported bounded preparation format') + if lineage.get('preparation_sha256') != _json_hash(manifest, newline=True): + raise ValueError('Preparation hash disagrees with lineage') + if ( + lineage.get('parent_revision') != manifest['source']['revision'] + or manifest['source']['identity'] != source.identity + ): + raise ValueError('Lineage parent/identity disagrees with preparation') + elif lineage.get('parent_revision') != source.revision: + raise ValueError('Later-round parent verification requires bounded_dir') + fields, candidates, explicit, active, history = _history( + source, curated, journal, manifest, expected_labels + ) + saved_generation = None + if bounded_dir is not None: + saved_generation = _checkpoint( + Path(bounded_dir), manifest, lineage, journal, right, curated, chunk_size + ) + native, aliases, native_tables = _native_metadata(left, source, fields, mapping.keys()) + if set(native) != fields: + raise ValueError('Missing native metadata field/table coverage') + replay_metadata = { + f: {int(u): _cell(v) for u, v in values.items()} + for f, values in curated.metadata.items() + } + mapped = {int(a): int(b) for a, b in mapping.items()} + reverse = {b: a for a, b in mapped.items()} + if len(reverse) != len(mapped) or not set(reverse) <= active: + raise ValueError('Partition mapping disagrees with final catalog') + untouched = set(map(int, source.unit_ids)) & active + assignment_oracle = _assignment_oracle(source, curated, history, chunk_size) + differences = [] + for field in fields: + for unit in active: + value = replay_metadata.get(field, {}).get(unit, '') + expected = expected_labels.get(unit, {}).get( + field, + _cell(source.metadata.get(field, {}).get(unit)) if unit in untouched else '', + ) + if value != expected: + raise ValueError( + f'Replay metadata violates label/clearing policy: {unit}.{field}' + ) + if unit not in reverse: + # Empty source units are deliberately not silently matched. + raise ValueError(f'Final metadata unit has no mapped source rows: {unit}') + left_id = reverse[unit] + native_value = native.get(field, {}).get(left_id, '') + allowed = ( + {expected} + if field in expected_labels.get(unit, {}) or unit in untouched + else candidates[unit][field] | {''} + ) + if native_value not in allowed: + raise ValueError( + f'Ordinary metadata has unsupported ancestor value: {left_id}.{field}' + ) + if native_value != value: + differences.append( + { + 'field': field, + 'left_id': left_id, + 'right_id': unit, + 'left': native_value, + 'right': value, + 'policy': 'native ancestor inheritance versus cleared new membership', + } + ) + if set(native.get(field, {})) - set(mapped): + raise ValueError(f'Unmapped ordinary metadata units: {field}') + for path in (left, right): + _parameters(path, source) + immutable = set(source.arrays) - {'spike_clusters.npy'} + immutable.update( + n + for n in ('_phy_spikes_subset.manifest.json', 'timestamps.json', 'curation.json') + if (source.path / n).exists() + ) + for name in sorted(immutable): + expected_hash = _hash(source.path / name) + for path in (left, right): + if not (path / name).is_file() or _hash(path / name) != expected_hash: + raise ValueError(f'Immutable asset missing or changed: {path.name}/{name}') + # Source layouts are authoritative for replay; only new label tables may be added. + source_schema = {t['filename']: t for t in source.metadata_schema['tables']} + right_schema = {t['filename']: t for t in curated.metadata_schema['tables']} + for name, table in source_schema.items(): + if right_schema.get(name) != table: + raise ValueError(f'Replay source metadata layout changed: {name}') + for name, table in right_schema.items(): + if name not in source_schema: + non_id = [f for f in table['columns'] if f != 'cluster_id'] + if ( + len(non_id) != 1 + or name != f'cluster_{non_id[0]}.tsv' + or table['columns'] != ['cluster_id', non_id[0]] + or non_id[0] in source.metadata + ): + raise ValueError(f'Unexpected replay metadata table: {name}') + for path in (left, right): + review = path / 'curation_review.json' + base_review = ( + _json(source.path / 'curation_review.json') + if (source.path / 'curation_review.json').exists() + else {'reviews': {}} + ) + if review.exists(): + from phy.cluster._propositions import decode_review_mapping + + doc = _json(review) + decode_review_mapping(doc) + if ( + doc.get('source', {}).get('filename') != 'curation.json' + or doc.get('source', {}).get('sha256') != _hash(source.path / 'curation.json') + or doc['reviews'] != base_review['reviews'] + ): + raise ValueError( + 'Review binding or inherited decisions changed without expectations' + ) + elif base_review['reviews'] or ( + path == right and (source.path / 'curation.json').exists() + ): + raise ValueError('Missing inherited or generated proposition reviews') + right_required = ( + immutable + | { + 'spike_clusters.npy', + 'params.py', + '_phy_cluster_metadata.json', + '_phy_cluster_metadata_schema.json', + '_phy_curation_lineage.json', + '_phy_curation_journal.json', + } + | set(right_schema) + ) + if (source.path / 'curation.json').exists(): + right_required.add('curation_review.json') + left_required = immutable | {'spike_clusters.npy', 'params.py'} | native_tables + derived_static = [] + inverse_name = 'whitening_mat_inv.npy' + if inverse_name not in source.arrays and (left / inverse_name).exists(): + matrix = source.arrays.get('whitening_mat.npy') + matrix = np.eye(len(source.arrays['channel_map.npy'])) if matrix is None else matrix + expected_inverse = np.linalg.inv(matrix) + actual_inverse = np.load(left / inverse_name, allow_pickle=False) + if actual_inverse.dtype != expected_inverse.dtype or not np.array_equal( + actual_inverse, expected_inverse + ): + raise ValueError('Invalid native derived whitening inverse') + left_required.add(inverse_name) + derived_static.append(inverse_name) + inventories = {} + for role, path, required in ( + ('ordinary', left, left_required), + ('replay', right, right_required), + ): + names = {p.name for p in path.iterdir()} + optional = ( + {'phy.log', 'phy_curation_history.jsonl', 'cluster_info.tsv', '.phy'} + if role == 'ordinary' + else set() + ) + if role == 'ordinary': + optional.update({'curation_review.json', '_phy_merge_parents.npz'}) + for name in ( + '_phy_cluster_metadata.json', + '_phy_cluster_metadata_schema.json', + '_phy_curation_lineage.json', + '_phy_curation_journal.json', + ): + if (source.path / name).exists() and (path / name).exists(): + if _hash(source.path / name) != _hash(path / name): + raise ValueError(f'Native source snapshot changed: {name}') + optional.add(name) + if required - names: + raise ValueError(f'Missing {role} assets: {sorted(required - names)}') + if names - required - optional: + raise ValueError(f'Unexpected {role} files: {sorted(names - required - optional)}') + for name in names: + item = path / name + if item.is_symlink() or (item.is_dir() and name != '.phy'): + raise ValueError(f'Unexpected non-file output asset: {name}') + if (path / 'cluster_info.tsv').exists(): + _, summary = _table(path / 'cluster_info.tsv') + summary_ids = set(next(iter(summary.values()))) + if summary_ids != set(mapped): + raise ValueError('Generated cluster_info catalog disagrees') + for field in {'group', 'notes'} | { + f for values in expected_labels.values() for f in values + }: + expected_map = ( + native.get(field, {}) + if role == 'ordinary' + else replay_metadata.get(field, {}) + ) + for unit, value in summary.get(field, {}).items(): + if unit not in mapped or value != expected_map.get(unit, ''): + raise ValueError('Generated cluster_info manual labels disagree') + inventories[role] = { + 'required': sorted(required), + 'state_artifacts': sorted(names - required), + 'sha256': {name: _hash(path / name) for name in sorted(required)}, + } + return ( + { + 'ok': True, + 'assignment_oracle': assignment_oracle, + 'immutable_files': sorted(immutable), + 'native_derived_static_files': derived_static, + 'all_metadata_fields': sorted(fields), + 'permitted_metadata_differences': differences, + 'ordinary_aliases': aliases, + 'inventories': inventories, + 'preparation_verified': manifest is not None, + 'saved_generation_verified': saved_generation, + 'historical_parents': ( + 'recorded cumulative ancestry; current parent bound to supplied manifest' + if manifest is not None + else 'current parent matches original source; preparation not supplied' + ), + }, + native, + replay_metadata, + ) + except (TypeError, AttributeError, IndexError) as error: + raise ValueError(f'Malformed contract document: {error}') from error + finally: + if curated is not None: + curated.close() + if source is not None: + source.close() diff --git a/tools/extract_shortcuts.py b/tools/extract_shortcuts.py index 113ec15e6..7abeeb329 100644 --- a/tools/extract_shortcuts.py +++ b/tools/extract_shortcuts.py @@ -4,6 +4,7 @@ from phylib.utils.testing import captured_output from phy.apps.base import BaseController +from phy.apps.large_recording.views import SampledCorrelogramView from phy.cluster import views from phy.cluster.supervisor import ActionCreator from phy.gui import GUI @@ -13,6 +14,7 @@ view_names = [v for v in dir(views) if v.endswith('View') and v != 'ManualClusteringView'] view_classes = [getattr(views, name) for name in view_names] +view_classes.append(SampledCorrelogramView) def _get_shortcuts(cls): diff --git a/tools/profile_bounded_actions.py b/tools/profile_bounded_actions.py new file mode 100644 index 000000000..45d7d536d --- /dev/null +++ b/tools/profile_bounded_actions.py @@ -0,0 +1,181 @@ +"""Profile bounded commands on a new synthetic sorting, never a supplied dataset. + +Separate setup from action latency. OS caches are uncontrolled; optional cProfile +results are diagnostic and are not mixed into the unprofiled timing samples. +""" + +import argparse +import cProfile +import json +import os +import platform +import subprocess +import sys +from pathlib import Path +from time import perf_counter, process_time + +import numpy as np + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from phy.apps.large_recording import curation +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.supervisor import BoundedSupervisor +from tools.benchmark_long_recording import _make_source, _peak_rss_bytes + + +def _journal(units, events, merges): + """A fixed merge prefix followed by metadata-only work keeps the live catalog fixed.""" + result = [] + target = 0 + for index in range(merges): + next_id = units + index + result.append( + { + 'version': 2, + 'operation': 'merge', + 'parents': [target, index + 1], + 'target': next_id, + 'metadata': {'group': None}, + } + ) + target = next_id + while len(result) < events: + result.append( + { + 'version': 2, + 'operation': 'label', + 'field': 'group', + 'ids': [units - 1], + 'value': 'good' if len(result) % 2 else 'mua', + } + ) + return result + + +def run(args): + if args.spikes > 50_000_000 or args.units > 10_000: + raise ValueError('Synthetic profiling is capped at 50M rows and 10,000 units.') + if args.spikes < args.units or args.units < 3 or args.repeats < 1: + raise ValueError('Require spikes >= units >= 3 and repeats >= 1.') + if not 0 <= args.merges < args.units - 1: + raise ValueError('Merge prefix must leave the measured original unit active.') + if any(events < args.merges for events in args.events): + raise ValueError('Every journal length must include the fixed merge prefix.') + args.output.mkdir(parents=True, exist_ok=False) + setup = perf_counter() + params = args.output / 'source' / 'params.py' + _make_source(params.parent, args.spikes, args.units, 1000, args.batch_size) + bounded = prepare_large( + params, + args.output / 'bounded', + window_seconds=3_600_000, + stratum_seconds=3_600_000, + max_spikes=args.spikes, + max_bytes=max(512 * 1024 * 1024, args.spikes * 64), + bin_seconds=1800, + batch_size=args.batch_size, + ) + setup_seconds = perf_counter() - setup + original = curation.project_assignments + calls = [] + + def measured_projection(assignments, *a, **kw): + started = perf_counter() + result = original(assignments, *a, **kw) + calls.append({'rows': len(assignments), 'seconds': perf_counter() - started}) + return result + + report = { + 'revision': subprocess.check_output( + ['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True + ).strip(), + 'python': sys.version, + 'numpy': np.__version__, + 'platform': platform.platform(), + 'source_spikes': args.spikes, + 'units': args.units, + 'fixed_merges': args.merges, + 'setup_seconds': setup_seconds, + 'cache_conditions': 'uncontrolled OS caches; warm synthetic arrays', + 'measurements': [], + } + try: + for length in args.events: + with curation.BoundedSession(bounded) as session: + events = _journal(args.units, length, args.merges) + _, _, next_id = curation.interpret_events( + session.unit_ids, session.base_metadata, events + ) + session.restore_journal({'events': tuple(events), 'next_cluster_id': next_id}) + supervisor = BoundedSupervisor( + spike_clusters=session.assignments.copy(), + session=session, + cluster_groups=session.metadata.get('group', {}), + cluster_labels=session.metadata, + ) + samples = [] + for repeat in range(args.repeats): + calls.clear() + curation.project_assignments = measured_projection + wall, cpu = perf_counter(), process_time() + try: + current = supervisor.cluster_meta.get('group', args.units - 1) + supervisor.label( + 'group', 'mua' if current == 'good' else 'good', [args.units - 1] + ) + finally: + curation.project_assignments = original + samples.append( + { + 'wall_seconds': perf_counter() - wall, + 'cpu_seconds': process_time() - cpu, + 'projector_calls': list(calls), + } + ) + if args.profile: + profile = cProfile.Profile() + current = supervisor.cluster_meta.get('group', args.units - 1) + profile.runcall( + supervisor.label, + 'group', + 'mua' if current == 'good' else 'good', + [args.units - 1], + ) + profile.dump_stats(args.output / f'label-{length}.prof') + actual = session.assignments + expected = original(session.base_assignments, session.events, session.attributes) + np.testing.assert_array_equal(actual, expected) + row = { + 'initial_events': length, + 'samples': samples, + 'p50_seconds': float(np.median([s['wall_seconds'] for s in samples])), + 'p95_seconds': float(np.percentile([s['wall_seconds'] for s in samples], 95)), + } + report['measurements'].append(row) + print(json.dumps(row), flush=True) + del supervisor + finally: + curation.project_assignments = original + report['peak_rss_bytes'], report['rss_method'] = _peak_rss_bytes() + (args.output / 'result.json').write_text(json.dumps(report, indent=2) + '\n') + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--spikes', type=int, default=1_000_000) + parser.add_argument('--units', type=int, default=859) + parser.add_argument('--merges', type=int, default=100) + parser.add_argument('--events', type=int, nargs='+', default=[100, 213, 1000]) + parser.add_argument('--repeats', type=int, default=3) + parser.add_argument('--batch-size', type=int, default=100_000) + parser.add_argument('--profile', action='store_true') + run(parser.parse_args()) + + +if __name__ == '__main__': + main() diff --git a/tools/profile_bounded_gui.py b/tools/profile_bounded_gui.py new file mode 100644 index 000000000..91c0ee08d --- /dev/null +++ b/tools/profile_bounded_gui.py @@ -0,0 +1,495 @@ +"""Profile real bounded GUI actions on a guarded copy under a private Xvfb. + +Example: uv run --no-sync python tools/profile_bounded_gui.py --bounded PACKAGE +--output NEW_DIRECTORY --events 213 --merges 100 --profile + +Requires Xvfb and glxinfo. Never opens the input in a controller. The copy budget +includes caches and old generations; raise it explicitly for larger packages. +GUI readiness means the supervisor queue and view busy flags have drained plus +an additional Qt timer turn; it is not a presentation/compositor timing claim. +""" + +import argparse +import cProfile +import hashlib +import importlib.metadata +import json +import os +import platform +import select +import subprocess +import sys +import time +import traceback +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def _inventory(source, maximum): + """Reject aliases and unexpected file types before copying or hashing.""" + files = [] + size = 0 + for path in sorted(source.rglob('*')): + if path.is_symlink(): + raise ValueError(f'Symbolic links are not supported: {path}') + if path.is_dir(): + continue + if not path.is_file(): + raise ValueError(f'Not a regular file: {path}') + size += path.stat().st_size + if size > maximum: + raise ValueError(f'Package exceeds --max-copy-bytes ({maximum:,}).') + files.append(path.relative_to(source)) + return files, size + + +def _hashes(source, files): + hashes = {} + for relative in files: + digest = hashlib.sha256() + with (source / relative).open('rb') as stream: + for block in iter(lambda: stream.read(8 * 1024 * 1024), b''): + digest.update(block) + hashes[str(relative)] = digest.hexdigest() + return hashes + + +def _validate(args): + source, output = args.bounded.resolve(), args.output.resolve() + if not source.is_dir() or not (source / '_phy_curation_manifest.json').is_file(): + raise ValueError('--bounded must be an existing prepared bounded package.') + if source == output or source in output.parents or output in source.parents: + raise ValueError('Input and output must be separate, non-nested directories.') + if output.exists(): + raise FileExistsError('The output must be a new directory.') + if args.repeats < 1 or args.merges < 0 or args.max_copy_bytes < 1 or args.timeout < 1: + raise ValueError('Require positive repeats, timeout, copy budget and nonnegative merges.') + if args.events is not None and args.events < args.merges: + raise ValueError('--events must include the requested merge prefix.') + if args.merges and args.events is None: + raise ValueError('--merges requires --events.') + return source, output + + +def _seed(package, events, merges): + from phy.apps.large_recording.curation import BoundedSession, interpret_events + + with BoundedSession(package) as session: + initial = len(session.events) + if events is not None: + live, _, _ = interpret_events(session.unit_ids, session.base_metadata, session.events) + ids = sorted(live) + if merges >= len(ids) - 1: + raise ValueError('Seed merges must leave a separate unit for measured actions.') + journal = list(session.events) + target = ids[0] + allocator = session.next_cluster_id + for index in range(merges): + journal.append( + { + 'version': 2, + 'operation': 'merge', + 'parents': [target, ids[index + 1]], + 'target': allocator, + 'metadata': dict.fromkeys(set(session.metadata) | {'group'}), + } + ) + target, allocator = allocator, allocator + 1 + for index in range(events - merges): + journal.append( + { + 'version': 2, + 'operation': 'label', + 'field': 'group', + 'ids': [ids[-1]], + 'value': 'mua' if index % 2 else 'good', + } + ) + session.restore_journal({'events': tuple(journal), 'next_cluster_id': allocator}) + session.save() + return { + 'original_events': initial, + 'initial_events': len(session.events), + 'synthetic_events_added': events or 0, + 'synthetic_merges_added': merges, + } + + +def _worker(args): + # Import order matches the application/capture harness: OpenGL before Qt. + import OpenGL.GL as GL + from PyQt5.QtCore import QTimer + from PyQt5.QtTest import QTest + + from phy.apps.template.gui import TemplateController + from phy.gui.qt import QApplication + + output = args.output + report = {'measurements': [], 'status': 'failed'} + controller = gui = None + wall, cpu = time.perf_counter(), time.process_time() + try: + report.update(_seed(output / 'working-package', args.events, args.merges)) + app = QApplication.instance() or QApplication([]) + setup = time.perf_counter() + controller = TemplateController( + dir_path=output / 'working-package', + config_dir=output / 'config', + plugins=[], + enable_threading=not args.no_threading, + ) + names = ['EvidenceAmplitudeView', 'UnitStabilityView'] + gui = controller.create_gui( + default_views=names, view_count=dict.fromkeys(names, 1), do_prompt_save=False + ) + gui.resize(1280, 900) + gui.show() + supervisor = controller.supervisor + supervisor.set_skip_masked_clusters(False) + + def ready(block=True): + if block: + supervisor.block() + app.processEvents() + tick = [] + QTimer.singleShot(0, lambda: tick.append(True)) + while not tick: + app.processEvents() + if supervisor._is_busy or not supervisor.task_logger.has_finished(): + raise RuntimeError('GUI did not reach the documented ready condition.') + + ready() + if any(gui.get_view(name) is None for name in names): + raise RuntimeError('A requested default scientific view is missing.') + report['gui_setup_seconds'] = time.perf_counter() - setup + report['views'] = names + report['threading'] = controller._enable_threading + report['requested_threading'] = not args.no_threading + report['ready_definition'] = 'supervisor.block + processEvents + zero-delay Qt timer' + report['versions'] = { + name: importlib.metadata.version(name) + for name in ('phy', 'phylib', 'numpy', 'PyQt5', 'PyOpenGL') + } + # Query an actual shown scientific canvas, not the unbound process context. + canvas = gui.get_view(names[0]).canvas + canvas.makeCurrent() + report['opengl'] = { + name: str(GL.glGetString(value)) + for name, value in [ + ('vendor', GL.GL_VENDOR), + ('renderer', GL.GL_RENDERER), + ('version', GL.GL_VERSION), + ] + } + report['python'] = sys.version + report['platform'] = platform.platform() + heartbeat = QTimer() + heartbeat.setInterval(10) + beats = [] + heartbeat.timeout.connect(lambda: beats.append(time.perf_counter())) + heartbeat.start() + QTest.qWait(30) + + def measure(name, operation, profiled=False): + before = list(supervisor.selected_clusters) + initial_events = len(controller.bounded_session.events) + beats.clear() + start, start_cpu = time.perf_counter(), time.process_time() + beats.append(start) + profiler = cProfile.Profile() if profiled else None + if profiler: + profiler.enable() + operation() + returned = time.perf_counter() + supervisor.block() + blocked = time.perf_counter() + ready(block=False) + ended = time.perf_counter() + if profiler: + profiler.disable() + profiler.dump_stats(output / f'{name}.prof') + gaps = [b - a for a, b in zip(beats, beats[1:] + [ended])] + row = { + 'action': name, + 'profiled': profiled, + 'initial_events': initial_events, + 'selected_before': before, + 'selected_after': list(supervisor.selected_clusters), + 'action_return_seconds': returned - start, + 'supervisor_wait_seconds': blocked - returned, + 'additional_ready_seconds': ended - blocked, + 'wall_seconds': ended - start, + 'cpu_seconds': time.process_time() - start_cpu, + 'heartbeat_interval_seconds': 0.01, + 'heartbeat_ticks': len(beats) - 1, + 'heartbeat_max_gap_seconds': max(gaps, default=0), + 'heartbeat_max_delay_seconds': max(0, max(gaps, default=0) - 0.01), + } + report['measurements'].append(row) + (output / 'worker-result.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps(row), flush=True) + return row + + actions = supervisor.action_creator.edit_actions + for repeat in range(args.repeats): + ids = supervisor.cluster_view.get_navigable_ids() + if len(ids) < 2: + raise ValueError('At least two navigable units are needed for move/next timing.') + chosen = ids[0] + # Preparation is outside measurement; force a real group change on every repeat. + supervisor.label('group', 'unsorted', [chosen]) + supervisor.select([chosen]) + ready() + row = measure(f'move_best_to_good-{repeat}', actions.move_best_to_good) + if supervisor.cluster_meta.get('group', chosen) != 'good': + raise AssertionError('Move did not change the selected unit to good.') + if row['selected_after'] == row['selected_before']: + raise AssertionError('Move did not advance selection to the next unit.') + measure(f'label-{repeat}', lambda: actions.label('group', 'mua')) + if args.merge_undo: + supervisor.select(supervisor.cluster_view.get_navigable_ids()[:2]) + ready() + measure(f'merge-{repeat}', actions.merge) + measure(f'undo-{repeat}', actions.undo) + if args.profile: + ids = supervisor.cluster_view.get_navigable_ids() + supervisor.label('group', 'unsorted', [ids[0]]) + supervisor.select([ids[0]]) + ready() + measure('move_best_to_good-profile', actions.move_best_to_good, profiled=True) + measure('label-profile', lambda: actions.label('group', 'good'), profiled=True) + if args.merge_undo: + supervisor.select(supervisor.cluster_view.get_navigable_ids()[:2]) + ready() + measure('merge-profile', actions.merge, profiled=True) + measure('undo-profile', actions.undo, profiled=True) + heartbeat.stop() + report['status'] = 'ok' + except Exception: + report['error'] = traceback.format_exc() + raise + finally: + cleanup_errors = [] + for obj in (gui, controller): + if obj is not None: + try: + obj.close() + except Exception: + cleanup_errors.append(traceback.format_exc()) + if cleanup_errors: + report['cleanup_errors'] = cleanup_errors + report['status'] = 'failed' + report['worker_wall_seconds'] = time.perf_counter() - wall + report['worker_cpu_seconds'] = time.process_time() - cpu + from tools.benchmark_long_recording import _peak_rss_bytes + + report['peak_rss_bytes'], report['rss_method'] = _peak_rss_bytes() + (output / 'worker-result.json').write_text(json.dumps(report, indent=2) + '\n') + if cleanup_errors: + raise RuntimeError('GUI cleanup failed; see worker-result.json.') + + +def run(args): + started, cpu = time.perf_counter(), time.process_time() + source, output = _validate(args) + files, size = _inventory(source, args.max_copy_bytes) + output.mkdir(parents=True, exist_ok=False, mode=0o700) + before = _hashes(source, files) + report = { + 'source': str(source), + 'output': str(output), + 'source_bytes': size, + 'source_hashes_before': before, + 'status': 'failed', + 'revision': subprocess.check_output( + ['git', '-C', str(ROOT), 'rev-parse', 'HEAD'], text=True + ).strip(), + 'cache_conditions': 'uncontrolled OS caches; copied bounded package', + 'private_config': str(output / 'config'), + 'configuration': { + 'repeats': args.repeats, + 'events': args.events, + 'merges': args.merges, + 'merge_undo': args.merge_undo, + 'profile': args.profile, + 'max_copy_bytes': args.max_copy_bytes, + 'worker_timeout_seconds': args.timeout, + }, + } + server = None + try: + from phy.apps.large_recording.file_copy import copy_source_file + + package = output / 'working-package' + package.mkdir() + copied = [ + relative + for relative in files + if '.phy' not in relative.parts and relative.name != 'phy.log' + ] + report['omitted_local_cache_files'] = len(files) - len(copied) + for relative in copied: + target = package / relative + target.parent.mkdir(parents=True, exist_ok=True) + copy_source_file(source / relative, target) + if _hashes(package, copied) != {str(p): before[str(p)] for p in copied}: + raise RuntimeError('Working copy does not match source hashes.') + report['copy_and_hash_seconds'] = time.perf_counter() - started + with (output / 'xvfb.log').open('w') as server_log: + server = subprocess.Popen( + [ + 'Xvfb', + '-displayfd', + '1', + '-screen', + '0', + '1280x900x24', + '-nolisten', + 'tcp', + '-ac', + '+extension', + 'GLX', + '+render', + ], + stdout=subprocess.PIPE, + stderr=server_log, + text=True, + ) + if not select.select([server.stdout], [], [], 20)[0]: + raise RuntimeError('Timed out starting private Xvfb.') + display = ':' + server.stdout.readline().strip() + if display == ':': + raise RuntimeError('Private Xvfb failed to start.') + env = dict( + os.environ, + DISPLAY=display, + QT_QPA_PLATFORM='xcb', + LIBGL_ALWAYS_SOFTWARE='1', + PYOPENGL_PLATFORM='glx', + LP_NUM_THREADS='4', + OPENBLAS_NUM_THREADS='2', + OMP_NUM_THREADS='2', + XDG_CONFIG_HOME=str(output / 'xdg-config'), + XDG_CACHE_HOME=str(output / 'xdg-cache'), + IPYTHONDIR=str(output / 'ipython'), + JUPYTER_CONFIG_DIR=str(output / 'jupyter'), + MPLCONFIGDIR=str(output / 'matplotlib'), + ) + report['private_display'] = display + report['rendering_environment'] = { + key: env[key] + for key in ( + 'QT_QPA_PLATFORM', + 'LIBGL_ALWAYS_SOFTWARE', + 'PYOPENGL_PLATFORM', + 'LP_NUM_THREADS', + ) + } + renderer = subprocess.run( + ['glxinfo', '-B'], env=env, capture_output=True, text=True, timeout=20 + ) + report['renderer_exit_code'] = renderer.returncode + (output / 'renderer.txt').write_text(renderer.stdout + renderer.stderr) + renderer.check_returncode() + command = [ + sys.executable, + str(Path(__file__).resolve()), + '--worker', + '--bounded', + str(source), + '--output', + str(output), + '--repeats', + str(args.repeats), + '--merges', + str(args.merges), + ] + if args.events is not None: + command += ['--events', str(args.events)] + if args.profile: + command += ['--profile'] + if args.merge_undo: + command += ['--merge-undo'] + if args.no_threading: + command += ['--no-threading'] + with ( + (output / 'worker.stdout').open('w') as stdout, + (output / 'worker.stderr').open('w') as stderr, + ): + try: + worker = subprocess.run( + command, + env=env, + cwd=ROOT, + stdout=stdout, + stderr=stderr, + timeout=args.timeout, + ) + report['worker_exit_code'] = worker.returncode + except subprocess.TimeoutExpired: + report['worker_exit_code'] = None + report['timed_out'] = True + raise + path = output / 'worker-result.json' + if path.exists(): + report['worker'] = json.loads(path.read_text()) + worker.check_returncode() + report['status'] = 'ok' + except Exception: + report['error'] = traceback.format_exc() + raise + finally: + if server is not None: + server.terminate() + try: + server.wait(timeout=10) + except subprocess.TimeoutExpired: + server.kill() + server.wait() + report['xvfb_exit_code'] = server.returncode + try: + after_files, _ = _inventory(source, args.max_copy_bytes) + report['source_hashes_after'] = _hashes(source, after_files) + report['source_unchanged'] = report['source_hashes_after'] == before + except Exception: + report['source_unchanged'] = False + report['source_hash_error'] = traceback.format_exc() + report['total_wall_seconds'] = time.perf_counter() - started + report['parent_cpu_seconds'] = time.process_time() - cpu + children = os.times() + report['child_cpu_seconds'] = children.children_user + children.children_system + report['total_cpu_seconds'] = report['parent_cpu_seconds'] + report['child_cpu_seconds'] + report['peak_child_rss_bytes'] = report.get('worker', {}).get('peak_rss_bytes') + if not report['source_unchanged']: + report['status'] = 'failed' + (output / 'result.json').write_text(json.dumps(report, indent=2) + '\n') + if not report['source_unchanged']: + raise RuntimeError('Input hashes changed during profiling.') + return report + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--bounded', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + parser.add_argument('--events', type=int, help='Synthetic events to append to copy only.') + parser.add_argument('--merges', type=int, default=0) + parser.add_argument('--repeats', type=int, default=3) + parser.add_argument('--merge-undo', action='store_true') + parser.add_argument('--profile', action='store_true') + parser.add_argument('--no-threading', action='store_true') + parser.add_argument('--max-copy-bytes', type=int, default=4 * 1024**3) + parser.add_argument('--timeout', type=float, default=300) + parser.add_argument('--worker', action='store_true', help=argparse.SUPPRESS) + args = parser.parse_args() + sys.path.insert(0, str(ROOT)) + if args.worker: + _worker(args) + else: + report = run(args) + print(json.dumps({'status': report['status'], 'report': str(args.output / 'result.json')})) + + +if __name__ == '__main__': + main() diff --git a/tools/validate_aind_export.py b/tools/validate_aind_export.py new file mode 100644 index 000000000..122ddf0d3 --- /dev/null +++ b/tools/validate_aind_export.py @@ -0,0 +1,220 @@ +"""Validate an AIND-produced sorting against Phy's declared source contract. + +This checks software interoperability. It cannot establish acquisition truth; +the exporter revision and authoritative exposure/filler policy must be supplied +and reviewed by the producer. +""" + +import argparse +import json +import sys +import time +from pathlib import Path + +REPOSITORY = Path(__file__).resolve().parents[1] +if str(REPOSITORY) not in sys.path: + sys.path.insert(0, str(REPOSITORY)) + +from phy.apps.large_recording.prepare import prepare_large +from phy.apps.large_recording.source import Source, hash_file + +REPORT_FORMAT = 'phy_aind_export_validation' +REPORT_VERSION = 1 + + +def _failure(error): + return {'type': type(error).__name__, 'message': str(error)} + + +def _cli_failure(error, args): + report = { + 'format': REPORT_FORMAT, + 'format_version': REPORT_VERSION, + 'status': 'failed', + 'failures': [_failure(error)], + 'engineering_validation_only': True, + 'acquisition_truth_established': False, + 'phy_revision': args.phy_revision, + 'exporter_revision': args.exporter_revision, + } + sys.stdout.write(json.dumps(report, indent=2, sort_keys=True) + '\n') + return 1 + + +def _input_inventory(source_path): + """Hash regular files in the source without interpreting their contents.""" + return { + path.name: {'bytes': path.stat().st_size, 'sha256': hash_file(path)} + for path in sorted(source_path.iterdir()) + if path.is_file() + } + + +def validate_export( + params_path, + *, + phy_revision, + exporter_revision, + output_dir=None, + max_spikes=2_000_000, + max_bytes=536_870_912, + batch_size=100_000, +): + """Return a JSON-serializable validation report; never edits the source.""" + started = time.perf_counter() + params_path = Path(params_path).resolve() + source_path = params_path.parent + report = { + 'format': REPORT_FORMAT, + 'format_version': REPORT_VERSION, + 'status': 'failed', + 'failures': [], + 'engineering_validation_only': True, + 'acquisition_truth_established': False, + 'requires_authoritative_exposure_and_filler_policy': True, + 'phy_revision': phy_revision, + 'exporter_revision': exporter_revision, + 'source': {'params_path': str(params_path), 'path': str(source_path)}, + 'budgets': {'max_spikes': int(max_spikes), 'max_bytes': int(max_bytes)}, + 'timing_seconds': {}, + } + if not phy_revision or not exporter_revision: + report['failures'].append( + _failure(ValueError('Both Phy and exporter revisions must be supplied.')) + ) + report['timing_seconds']['total'] = time.perf_counter() - started + return report + try: + phase = time.perf_counter() + with Source(params_path, batch_size=batch_size) as source: + report['timing_seconds']['source_validation'] = time.perf_counter() - phase + report['source'].update( + { + 'sha256': source.identity['sha256'], + 'num_spikes': source.n_spikes, + 'num_units': len(source.unit_ids), + 'sample_rate_hz': source.sample_rate, + 'num_samples': source.num_samples, + 'time_base': source.time_base, + 'exposure': { + 'valid_intervals': source.valid_intervals.tolist(), + 'valid_samples': int( + (source.valid_intervals[:, 1] - source.valid_intervals[:, 0]).sum() + ), + 'valid_seconds': float( + (source.valid_intervals[:, 1] - source.valid_intervals[:, 0]).sum() + / source.sample_rate + ), + }, + 'array_counts': { + name: {'rows': int(len(array)), 'shape': list(array.shape)} + for name, array in sorted(source.arrays.items()) + }, + } + ) + source_root = source.path + declared_intervals = ( + 'valid_intervals' in source.params + or 'valid_intervals' in source.upstream_recording + ) + if source.time_base is None: + raise ValueError('AIND export requires an explicit time_base contract.') + if source.time_base['kind'] != 'elapsed_ticks': + raise ValueError('AIND export time_base.kind must be elapsed_ticks.') + if not declared_intervals: + raise ValueError( + 'AIND export requires explicit authoritative valid_intervals in params.py ' + 'or the waveform manifest.' + ) + phase = time.perf_counter() + report['source']['input_files'] = _input_inventory(source_root) + report['timing_seconds']['input_hashing'] = time.perf_counter() - phase + if output_dir is not None: + destination = Path(output_dir).resolve() + if destination == source_root or source_root in destination.parents: + raise ValueError('Prepared output must be outside the immutable source directory.') + if destination.exists(): + raise ValueError(f'Prepared output must be fresh; already exists: {destination}.') + phase = time.perf_counter() + prepared = prepare_large( + params_path, + destination, + max_spikes=max_spikes, + max_bytes=max_bytes, + batch_size=batch_size, + ) + report['timing_seconds']['prepare'] = time.perf_counter() - phase + manifest = json.loads((prepared / '_phy_curation_manifest.json').read_text()) + report['prepared_output'] = { + 'path': str(prepared), + 'num_spikes': manifest['bounded_num_spikes'], + 'num_units': len(manifest['unit_ids']), + 'waveform_coverage': manifest['waveform_coverage'], + 'budgets': manifest['budgets'], + 'output_bytes': sum(p.stat().st_size for p in prepared.rglob('*') if p.is_file()), + } + except Exception as error: + report['failures'].append(_failure(error)) + if not report['failures']: + report['status'] = 'passed' + report['timing_seconds']['total'] = time.perf_counter() - started + return report + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('params', type=Path, help='AIND sorting params.py') + parser.add_argument('--phy-revision', required=True) + parser.add_argument('--exporter-revision', required=True) + parser.add_argument( + '--output-dir', type=Path, help='Optional fresh bounded package destination' + ) + parser.add_argument('--max-spikes', type=int, default=2_000_000) + parser.add_argument('--max-bytes', type=int, default=536_870_912) + parser.add_argument('--batch-size', type=int, default=100_000) + parser.add_argument( + '--report', type=Path, help='Write JSON report to this path (default stdout)' + ) + args = parser.parse_args(argv) + if args.report: + source_root = args.params.resolve().parent + report_path = args.report.resolve() + protected_roots = [source_root] + if args.output_dir is not None: + protected_roots.append(args.output_dir.resolve()) + if any(report_path == root or root in report_path.parents for root in protected_roots): + failure = ValueError( + 'Report path must be outside the immutable source and prepared output directories.' + ) + elif args.report.exists() or args.report.is_symlink(): + failure = ValueError(f'Report path must be fresh; already exists: {args.report}.') + else: + failure = None + if failure is not None: + return _cli_failure(failure, args) + report = validate_export( + args.params, + phy_revision=args.phy_revision, + exporter_revision=args.exporter_revision, + output_dir=args.output_dir, + max_spikes=args.max_spikes, + max_bytes=args.max_bytes, + batch_size=args.batch_size, + ) + payload = json.dumps(report, indent=2, sort_keys=True) + '\n' + if args.report: + try: + with args.report.open('x', encoding='utf-8') as stream: + stream.write(payload) + except FileExistsError: + return _cli_failure( + FileExistsError(f'Report path must be fresh; already exists: {args.report}.'), + args, + ) + else: + sys.stdout.write(payload) + return 0 if report['status'] == 'passed' else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/tools/verify_feedback_replay.py b/tools/verify_feedback_replay.py new file mode 100644 index 000000000..32c0613d4 --- /dev/null +++ b/tools/verify_feedback_replay.py @@ -0,0 +1,59 @@ +"""Independently check a demonstrated merge followed by an amplitude split. + +Reads only NumPy arrays, without Phy's journal/projection implementation. The +two children are the finite-below-threshold selection and the remainder. All +source units outside the supplied parent union must remain unchanged. +""" + +import argparse +import json +from collections import Counter +from pathlib import Path + +import numpy as np + + +def verify(args): + labels = np.load(args.source / 'spike_clusters.npy', mmap_mode='r').reshape(-1) + amplitudes = np.load(args.source / 'amplitudes.npy', mmap_mode='r').reshape(-1) + outputs = [ + np.load(path / 'spike_clusters.npy', mmap_mode='r').reshape(-1) for path in args.outputs + ] + assert len(amplitudes) == len(labels) + assert all(len(output) == len(labels) for output in outputs) + counts = Counter() + for start in range(0, len(labels), args.batch_size): + stop = min(start + args.batch_size, len(labels)) + original = labels[start:stop] + values = amplitudes[start:stop] + parent = np.isin(original, args.parents) + selected = np.isfinite(values) & (values < args.threshold) + expected = original.copy() + expected[parent & selected] = args.children[0] + expected[parent & ~selected] = args.children[1] + for output in outputs: + np.testing.assert_array_equal(output[start:stop], expected) + ids, frequencies = np.unique(expected, return_counts=True) + counts.update(dict(zip(map(int, ids), map(int, frequencies)))) + result = { + 'rows_checked_per_output': len(labels), + 'outputs': len(outputs), + 'assignments_exact': True, + 'active_units': len(counts), + 'children': {str(unit): counts[unit] for unit in args.children}, + } + print(json.dumps(result, indent=2)) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, required=True) + parser.add_argument('--outputs', type=Path, nargs='+', required=True) + parser.add_argument('--parents', type=int, nargs='+', required=True) + parser.add_argument('--children', type=int, nargs=2, required=True) + parser.add_argument('--threshold', type=float, required=True) + parser.add_argument('--batch-size', type=int, default=1_000_000) + args = parser.parse_args() + if args.batch_size < 1 or not np.isfinite(args.threshold): + parser.error('Use a positive batch size and a finite threshold.') + verify(args) diff --git a/tools/verify_parent_restore_replay.py b/tools/verify_parent_restore_replay.py new file mode 100644 index 000000000..4dc6ece48 --- /dev/null +++ b/tools/verify_parent_restore_replay.py @@ -0,0 +1,74 @@ +"""Independently verify a split/merge/restore/remerge against original source rows. + +The scenario records user-visible operands and resulting IDs, not production +membership expressions. Expected assignments use only original labels and raw +finite amplitude comparisons; no Phy journal/projector is imported. + +Optional ``included_originals`` identifies whole source units added through +nested merges and retained in the final combination. Omitting it preserves the +original immediate-parent scenario contract. +""" + +import argparse +import json +from collections import Counter +from pathlib import Path + +import numpy as np + + +def verify(source, outputs, scenario, batch_size=1_000_000): + labels = np.load(source / 'spike_clusters.npy', mmap_mode='r').reshape(-1) + amplitudes = np.load(source / 'amplitudes.npy', mmap_mode='r').reshape(-1) + actual = [np.load(path / 'spike_clusters.npy', mmap_mode='r').reshape(-1) for path in outputs] + assert len(labels) == len(amplitudes) + assert all(len(values) == len(labels) for values in actual) + assert np.isfinite(scenario['threshold']) and batch_size > 0 + counts = Counter() + changed = 0 + for start in range(0, len(labels), batch_size): + stop = min(start + batch_size, len(labels)) + original = labels[start:stop] + values = amplitudes[start:stop] + family = np.isin(original, scenario['initial_parents']) + below = np.isfinite(values) & (values < scenario['threshold']) + expected = original.copy() + expected[family & ~below] = scenario['split_remainder'] + expected[family & below] = scenario['final_merged'] + expected[np.isin(original, scenario.get('included_originals', []))] = scenario[ + 'final_merged' + ] + expected[original == scenario['excluded_original']] = scenario['excluded_live'] + expected[original == scenario['new_candidate']] = scenario['final_merged'] + expected[np.isin(original, scenario['unrelated_inputs'])] = scenario['unrelated_result'] + for output in actual: + np.testing.assert_array_equal(output[start:stop], expected) + ids, frequencies = np.unique(expected, return_counts=True) + counts.update(dict(zip(map(int, ids), map(int, frequencies)))) + changed += int(np.count_nonzero(expected != original)) + return { + 'rows_checked_per_output': len(labels), + 'outputs': len(outputs), + 'assignments_exact': True, + 'changed_rows': changed, + 'active_units': len(counts), + 'counts': dict(sorted(counts.items())), + 'oracle': 'Original source labels plus raw finite amplitude < threshold; no Phy imports', + } + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source', type=Path, required=True) + parser.add_argument('--outputs', type=Path, nargs='+', required=True) + parser.add_argument('--scenario', type=Path, required=True) + parser.add_argument('--report', type=Path, required=True) + parser.add_argument('--batch-size', type=int, default=1_000_000) + args = parser.parse_args() + if args.batch_size < 1: + parser.error('--batch-size must be positive.') + result = verify( + args.source, args.outputs, json.loads(args.scenario.read_text()), args.batch_size + ) + args.report.write_text(json.dumps(result, indent=2) + '\n') + print(json.dumps({k: v for k, v in result.items() if k != 'counts'}, indent=2)) diff --git a/uv.lock b/uv.lock index 1c8e4d103..6021fdf09 100644 --- a/uv.lock +++ b/uv.lock @@ -1466,6 +1466,7 @@ dependencies = [ { name = "pip" }, { name = "pyopengl" }, { name = "pyqt5" }, + { name = "pyqt5-sip" }, { name = "qtconsole" }, { name = "requests" }, { name = "responses" }, @@ -1525,6 +1526,7 @@ requires-dist = [ { name = "pyopengl", specifier = ">=3.1.9" }, { name = "pyqt5", specifier = ">=5.15.11,<5.16" }, { name = "pyqt5", marker = "extra == 'dev'", specifier = ">=5.15.11,<5.16" }, + { name = "pyqt5-sip", specifier = ">=12.20.1,<13" }, { name = "pytest", marker = "extra == 'dev'" }, { name = "pytest-cov", marker = "extra == 'dev'" }, { name = "pytest-qt", marker = "extra == 'dev'" }, @@ -1823,26 +1825,34 @@ wheels = [ [[package]] name = "pyqt5-sip" -version = "12.17.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/01/79/086b50414bafa71df494398ad277d72e58229a3d1c1b1c766d12b14c2e6d/pyqt5_sip-12.17.0.tar.gz", hash = "sha256:682dadcdbd2239af9fdc0c0628e2776b820e128bec88b49b8d692fe682f90b4f", size = 104042, upload-time = "2025-02-02T17:13:11.268Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/23/1da570b7e143b6d216728c919cae2976f7dbff65db94e3d9f5b62df37ba5/PyQt5_sip-12.17.0-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:ec47914cc751608e587c1c2fdabeaf4af7fdc28b9f62796c583bea01c1a1aa3e", size = 122696, upload-time = "2025-02-02T17:12:35.786Z" }, - { url = "https://files.pythonhosted.org/packages/61/d5/506b1c3ad06268c601276572f1cde1c0dffd074b44e023f4d80f5ea49265/PyQt5_sip-12.17.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:2f2a8dcc7626fe0da73a0918e05ce2460c7a14ddc946049310e6e35052105434", size = 270932, upload-time = "2025-02-02T17:12:38.175Z" }, - { url = "https://files.pythonhosted.org/packages/0b/9b/46159d8038374b076244a1930ead460e723453ec73f9b0330390ddfdd0ea/PyQt5_sip-12.17.0-cp310-cp310-win32.whl", hash = "sha256:0c75d28b8282be3c1d7dbc76950d6e6eba1e334783224e9b9835ce1a9c64f482", size = 49085, upload-time = "2025-02-02T17:12:40.146Z" }, - { url = "https://files.pythonhosted.org/packages/fe/66/b3eb937a620ce2a5db5c377beeca870d60fafd87aecc1bcca6921bbcf553/PyQt5_sip-12.17.0-cp310-cp310-win_amd64.whl", hash = "sha256:8c4bc535bae0dfa764e8534e893619fe843ce5a2e25f901c439bcb960114f686", size = 59040, upload-time = "2025-02-02T17:12:41.962Z" }, - { url = "https://files.pythonhosted.org/packages/52/fd/7d6e3deca5ce37413956faf4e933ce6beb87ac0cc7b26d934b5ed998f88a/PyQt5_sip-12.17.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2c912807dd638644168ea8c7a447bfd9d85a19471b98c2c588c4d2e911c09b0a", size = 122748, upload-time = "2025-02-02T17:12:43.831Z" }, - { url = "https://files.pythonhosted.org/packages/29/4d/e5981cde03b091fd83a1ef4ef6a4ca99ce6921d61b80c0222fc8eafdc99a/PyQt5_sip-12.17.0-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:71514a7d43b44faa1d65a74ad2c5da92c03a251bdc749f009c313f06cceacc9a", size = 276401, upload-time = "2025-02-02T17:12:45.705Z" }, - { url = "https://files.pythonhosted.org/packages/5f/30/4c282896b1e8841639cf2aca59acf57d8b261ed834ae976c959f25fa4a35/PyQt5_sip-12.17.0-cp311-cp311-win32.whl", hash = "sha256:023466ae96f72fbb8419b44c3f97475de6642fa5632520d0f50fc1a52a3e8200", size = 49091, upload-time = "2025-02-02T17:12:47.688Z" }, - { url = "https://files.pythonhosted.org/packages/24/c1/50fc7301aa39a50f451fc1b6b219e778c540a823fe9533a57b4793c859fd/PyQt5_sip-12.17.0-cp311-cp311-win_amd64.whl", hash = "sha256:fb565469d08dcb0a427def0c45e722323beb62db79454260482b6948bfd52d47", size = 59036, upload-time = "2025-02-02T17:12:49.535Z" }, - { url = "https://files.pythonhosted.org/packages/a3/e6/e51367c28d69b5a462f38987f6024e766fd8205f121fe2f4d8ba2a6886b9/PyQt5_sip-12.17.0-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:ea08341c8a5da00c81df0d689ecd4ee47a95e1ecad9e362581c92513f2068005", size = 124650, upload-time = "2025-02-02T17:12:50.595Z" }, - { url = "https://files.pythonhosted.org/packages/64/3b/e6d1f772b41d8445d6faf86cc9da65910484ebd9f7df83abc5d4955437d0/PyQt5_sip-12.17.0-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:4a92478d6808040fbe614bb61500fbb3f19f72714b99369ec28d26a7e3494115", size = 281893, upload-time = "2025-02-02T17:12:51.966Z" }, - { url = "https://files.pythonhosted.org/packages/ed/c5/d17fc2ddb9156a593710c88afd98abcf4055a2224b772f8bec2c6eea879c/PyQt5_sip-12.17.0-cp312-cp312-win32.whl", hash = "sha256:b0ff280b28813e9bfd3a4de99490739fc29b776dc48f1c849caca7239a10fc8b", size = 49438, upload-time = "2025-02-02T17:12:54.426Z" }, - { url = "https://files.pythonhosted.org/packages/fe/c5/1174988d52c732d07033cf9a5067142b01d76be7731c6394a64d5c3ef65c/PyQt5_sip-12.17.0-cp312-cp312-win_amd64.whl", hash = "sha256:54c31de7706d8a9a8c0fc3ea2c70468aba54b027d4974803f8eace9c22aad41c", size = 58017, upload-time = "2025-02-02T17:12:56.31Z" }, - { url = "https://files.pythonhosted.org/packages/fd/5d/f234e505af1a85189310521447ebc6052ebb697efded850d0f2b2555f7aa/PyQt5_sip-12.17.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:c7a7ff355e369616b6bcb41d45b742327c104b2bf1674ec79b8d67f8f2fa9543", size = 124580, upload-time = "2025-02-02T17:12:58.158Z" }, - { url = "https://files.pythonhosted.org/packages/cd/cb/3b2050e9644d0021bdf25ddf7e4c3526e1edd0198879e76ba308e5d44faf/PyQt5_sip-12.17.0-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:419b9027e92b0b707632c370cfc6dc1f3b43c6313242fc4db57a537029bd179c", size = 281563, upload-time = "2025-02-02T17:12:59.421Z" }, - { url = "https://files.pythonhosted.org/packages/51/61/b8ebde7e0b32d0de44c521a0ace31439885b0423d7d45d010a2f7d92808c/PyQt5_sip-12.17.0-cp313-cp313-win32.whl", hash = "sha256:351beab964a19f5671b2a3e816ecf4d3543a99a7e0650f88a947fea251a7589f", size = 49383, upload-time = "2025-02-02T17:13:00.597Z" }, - { url = "https://files.pythonhosted.org/packages/15/ed/ff94d6b2910e7627380cb1fc9a518ff966e6d78285c8e54c9422b68305db/PyQt5_sip-12.17.0-cp313-cp313-win_amd64.whl", hash = "sha256:672c209d05661fab8e17607c193bf43991d268a1eefbc2c4551fbf30fd8bb2ca", size = 58022, upload-time = "2025-02-02T17:13:01.738Z" }, +version = "12.20.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/5d/778b6bb5d65c32e40ab8bd2b40e218108a31e323c5e8c026895da7833444/pyqt5_sip-12.20.1.tar.gz", hash = "sha256:b94f0c7cf8f6335adb90aab1981756c94e1250854dbcc209271ba8c058c4ddbb", size = 107025, upload-time = "2026-11-11T12:32:21.133Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3c/5d/0c8b9209e51a77a23ba1d95fcd329f4cf7f456a38718fe484e6894a493d9/pyqt5_sip-12.20.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:c02e4a62433e6a3d98e669b2f373a9809f69e6648c639b09647d36b5fc0c1961", size = 124342, upload-time = "2026-11-11T12:31:50.263Z" }, + { url = "https://files.pythonhosted.org/packages/2a/31/667e0b7aa1df7bf2c7f40247070d19f69d5ecbdcdcb711274f018b038dc3/pyqt5_sip-12.20.1-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:9e32a1970bb5040ae81053a5b1b2cf6b97cb49924b3031b933fde1bdb4959de2", size = 273419, upload-time = "2026-11-11T12:31:51.567Z" }, + { url = "https://files.pythonhosted.org/packages/52/e7/7324654308c78dc242cd85541f4748f25df4907690652f3794e6897cc767/pyqt5_sip-12.20.1-cp310-cp310-win32.whl", hash = "sha256:91a7aa4e98f7ac318869be9b7d0e87df7fd0ab3bab561f173c2948a991e90de1", size = 49234, upload-time = "2026-11-11T12:31:53.678Z" }, + { url = "https://files.pythonhosted.org/packages/d8/e7/2838666dbff15d71c6217731c1451d955deaa8b9d52d8f7d0bd85b475250/pyqt5_sip-12.20.1-cp310-cp310-win_amd64.whl", hash = "sha256:948088ac5f05e09ce313b7a5b8f3e585ee6e6bca27961445302d230be62c2db4", size = 59171, upload-time = "2026-11-11T12:31:52.657Z" }, + { url = "https://files.pythonhosted.org/packages/62/b4/1c9730583ee899996fcff1ae35eb5f1653dcb333a9bcc321921d1338927c/pyqt5_sip-12.20.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:7be2c759917fc9be925f001c1ad0d0532f8ea4131016ef3f31087e86113489fa", size = 124348, upload-time = "2026-11-11T12:31:54.622Z" }, + { url = "https://files.pythonhosted.org/packages/b5/e0/e4778da58166e77f2cbb86d756a72a28dbd399b86e33725986826d2b9261/pyqt5_sip-12.20.1-cp311-cp311-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:36212154c64f91c4d1584ea1792e5e71a7502f53a10a3b52659f660243e461eb", size = 277583, upload-time = "2026-11-11T12:31:56.108Z" }, + { url = "https://files.pythonhosted.org/packages/be/35/2415f61e7020874fc0f501a7d2ad9ea243e5258c2f19e2fe433d0c15f237/pyqt5_sip-12.20.1-cp311-cp311-win32.whl", hash = "sha256:9851d4417a348d573318853acb0a7deec36a42f8f992dbd71dba50c40657a806", size = 49240, upload-time = "2026-11-11T12:31:58.928Z" }, + { url = "https://files.pythonhosted.org/packages/64/69/9b6dfb55483cafe49fc2ae16493a84bc71623ba53525cfe1cbfeab176693/pyqt5_sip-12.20.1-cp311-cp311-win_amd64.whl", hash = "sha256:7723028416fdf4f06539ef7bd85652fdf0896bb808529d0c78c87d3d926c5bc4", size = 59179, upload-time = "2026-11-11T12:31:57.752Z" }, + { url = "https://files.pythonhosted.org/packages/98/94/3b3c8476d173fc1fbdd836d4fa73c7c3a072512d44b9bf137a64c9580401/pyqt5_sip-12.20.1-cp312-cp312-macosx_10_9_universal2.whl", hash = "sha256:9f5c9571c09ad76818797f5a478e2822f4cbff856d784e43932d066ecfaa010e", size = 125601, upload-time = "2026-11-11T12:32:00.072Z" }, + { url = "https://files.pythonhosted.org/packages/00/57/1e3d1c73662fb67ac50c02aa42d27600ce9adcd13a036e4283a705db8f6d/pyqt5_sip-12.20.1-cp312-cp312-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:b3df856ad5cb8399c52997ec67074e0295d7bcd2b35199fa0e6387f7c609e08a", size = 282881, upload-time = "2026-11-11T12:32:01.483Z" }, + { url = "https://files.pythonhosted.org/packages/7f/e8/6d937bfecb183b0c46dd9132052955a6b500646006f13c0e384fdaed5000/pyqt5_sip-12.20.1-cp312-cp312-win32.whl", hash = "sha256:62e3e2ce307c7879c8b02867ecb84d3501a022e915ed3c97374069fa303d6982", size = 49707, upload-time = "2026-11-11T12:32:03.744Z" }, + { url = "https://files.pythonhosted.org/packages/03/e8/3a9e98a9bde1d4d18a3f9c13e136d78145ad0b2b88b6378806fd24474ffa/pyqt5_sip-12.20.1-cp312-cp312-win_amd64.whl", hash = "sha256:c3f05d231d3a57d3fda6ed7edd83c376d0d42ec5d5f1f1558be26a86e1343440", size = 58368, upload-time = "2026-11-11T12:32:02.838Z" }, + { url = "https://files.pythonhosted.org/packages/21/2e/63a3632ba8ede2e1c627c518cbad248e52267ce3b37b1c1c0aa4c3981e79/pyqt5_sip-12.20.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:49f6b284220aa9cad3901f24b964a7e722ec62dd3d9df9ede97dc436c7edd5f2", size = 125558, upload-time = "2026-11-11T12:32:04.799Z" }, + { url = "https://files.pythonhosted.org/packages/02/d4/5b7d5ce8577faf7811209494cbae43ed0844a69cc9b8ff7562c24cab15d0/pyqt5_sip-12.20.1-cp313-cp313-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:f0a9f1eeae6ffe25f29b4e58bbd0cd77dfadbcc08de0fdab74f2f089c51a05b1", size = 282846, upload-time = "2026-11-11T12:32:06.064Z" }, + { url = "https://files.pythonhosted.org/packages/e8/e5/ba6065d16cb9e7702389445b0e032df1b90694d6c78cd315b7b6cc2894a2/pyqt5_sip-12.20.1-cp313-cp313-win32.whl", hash = "sha256:056c141ffc479697f2dfd67198bc461c5a107c9fed4d0c283e0387c83ece5b26", size = 49673, upload-time = "2026-11-11T12:32:08.891Z" }, + { url = "https://files.pythonhosted.org/packages/b6/e9/3fba752019e4068be2cb4c4d7614f95c5a4c11148b1f8800c259b5cf39c2/pyqt5_sip-12.20.1-cp313-cp313-win_amd64.whl", hash = "sha256:fe8129359f904934bc1be1ef0be29bae96bb35bfc57fa6bb28b71f0cb918e47f", size = 58408, upload-time = "2026-11-11T12:32:07.613Z" }, + { url = "https://files.pythonhosted.org/packages/cb/e4/6a3606c7fcacdf7c5457b42fd946d38e38582402d1317bce1ebcc9fb188c/pyqt5_sip-12.20.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:b822f36f3665f59c7856f1fbf88a3ce7a4046c20e3eb03cd13b4203117e7a1ce", size = 125813, upload-time = "2026-11-11T12:32:11.588Z" }, + { url = "https://files.pythonhosted.org/packages/87/6e/caea55c1039d5189c43d03799a3fd781f9959d8e540363bdada64c1f82db/pyqt5_sip-12.20.1-cp314-cp314-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:d815b444fba57024a5f051905286c048792ded4edc89ea5de40a8c5f2f8fcd21", size = 283524, upload-time = "2026-11-11T12:32:12.729Z" }, + { url = "https://files.pythonhosted.org/packages/47/b2/b6a12595adfa5010b8ff057a897ee8dda21bf824601e3d7d6420135b539e/pyqt5_sip-12.20.1-cp314-cp314-win32.whl", hash = "sha256:d6f3aefdc344d91a6c4a50c3a0d85cc6b28435180792decf968a5c947839cd0a", size = 50943, upload-time = "2026-11-11T12:32:14.946Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/b675f823fdc9b4922140c7f44304d985761cf4bb4e290064302a552eb874/pyqt5_sip-12.20.1-cp314-cp314-win_amd64.whl", hash = "sha256:6b086f44af4a01241f7941b846b05367385988a448608d28a97305aee8c43c36", size = 59929, upload-time = "2026-11-11T12:32:14.018Z" }, + { url = "https://files.pythonhosted.org/packages/a5/94/6914d7850ed49487890c3bd41e815fd8134aaad27cca7de26f175ca2f55d/pyqt5_sip-12.20.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:e510433fccd10adffb1e32752da8410b1a568fcdc9d5cc4a30ab5d3bb10640f7", size = 126140, upload-time = "2026-11-11T12:32:15.883Z" }, + { url = "https://files.pythonhosted.org/packages/80/21/44ddd086ce2b8aa6026440ec194116083d6fafc93f59ceb574905c7bbe6d/pyqt5_sip-12.20.1-cp315-cp315-manylinux_2_5_x86_64.manylinux1_x86_64.whl", hash = "sha256:462040f2d3450d3fc6ebd4e30cdaee7e30db8bb02544f367d9120437fb77d025", size = 286596, upload-time = "2026-11-11T12:32:17.176Z" }, + { url = "https://files.pythonhosted.org/packages/89/ed/d4717a379ffaf0ae0ee15e9587441989c75e6304f12d647da9b25323bedb/pyqt5_sip-12.20.1-cp315-cp315-win32.whl", hash = "sha256:08e5a1c77fd362d8fc8f5f5f0e92c0123a719da04ffe916c8eafef8d3aaa8a87", size = 51016, upload-time = "2026-11-11T12:32:19.998Z" }, + { url = "https://files.pythonhosted.org/packages/ea/83/8a7428cfef62c08a0c262e9e5a8b6ef2101661eef62c3f8c7d3c8bc28996/pyqt5_sip-12.20.1-cp315-cp315-win_amd64.whl", hash = "sha256:77ed5391e746d531d9a292e19ad5ce8540e56ebec33c74f6ca0a74be7f63fff6", size = 60056, upload-time = "2026-11-11T12:32:18.901Z" }, ] [[package]]