1/**
2 * Persistence. Small structured state lives in localStorage: event types
3 * with their clips' onset lists, algorithm sources, and the benchmark
4 * configuration. Bulk audio lives in IndexedDB: clip audio, and the last
5 * benchmark's synthesized recordings so the explorer can reopen them
6 * after a reload. The stores can drift only in harmless directions: a
7 * clip whose audio is missing simply stops contributing snippets.
8 */
9import type { AlgorithmDef, RunResult, SynthConfig } from './bench/types.ts';
11export interface ClipMeta {
12 id: string;
13 sens: number; // the sensitivity the onsets were detected with
14 onsets: number[]; // seconds
15 excluded: number[]; // indices into onsets
16}
18export interface EventType {
19 id: string;
20 name: string;
21 color: string;
22 clips: ClipMeta[];
23}
25export interface BenchConfig extends SynthConfig {
26 preMs: number;
27 postMs: number;
28 runs: number;
29 toleranceMs: number;
30}
32export const DEFAULT_CONFIG: BenchConfig = {
33 durationS: 30,
34 eventsPerType: 30,
35 gainMinDb: 0,
36 overlap: 0.2,
37 trainFraction: 0.3,
38 seed: 1,
39 preMs: 20,
40 postMs: 180,
41 runs: 5,
42 toleranceMs: 20,
43};
45const KEY = 'audio-spike-sorting/v1';
47interface Doc {
48 types: EventType[];
49 config: BenchConfig;
50 algorithms: AlgorithmDef[];
51}
53export function loadDoc(): Doc {
54 try {
55 const raw = localStorage.getItem(KEY);
56 if (raw) {
57 const d = JSON.parse(raw) as Doc;
58 d.config = { ...DEFAULT_CONFIG, ...d.config };
59 return d;
60 }
61 } catch { /* fall through */ }
62 return { types: [], config: { ...DEFAULT_CONFIG }, algorithms: [] };
63}
65export function saveDoc(doc: Doc): void {
66 localStorage.setItem(KEY, JSON.stringify(doc));
67}
69// ---- bulk data in IndexedDB -------------------------------------------------
71const STORES = ['clips', 'bench'] as const;
73let dbPromise: Promise<IDBDatabase> | null = null;
74function db(): Promise<IDBDatabase> {
75 return (dbPromise ??= new Promise((resolve, reject) => {
76 const req = indexedDB.open('audio-spike-sorting', 1);
77 req.onupgradeneeded = () => {
78 for (const s of STORES) {
79 if (!req.result.objectStoreNames.contains(s)) req.result.createObjectStore(s);
80 }
81 };
82 req.onsuccess = () => resolve(req.result);
83 req.onerror = () => reject(req.error);
84 }));
85}
87function op<T>(store: string, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest<T>): Promise<T> {
88 return db().then((d) => new Promise<T>((resolve, reject) => {
89 const req = fn(d.transaction(store, mode).objectStore(store));
90 req.onsuccess = () => resolve(req.result);
91 req.onerror = () => reject(req.error);
92 }));
93}
95export function putClipAudio(id: string, samples: Float32Array, sr: number): Promise<unknown> {
96 return op('clips', 'readwrite', (s) => s.put({ samples, sr }, id));
97}
98export function getClipAudio(id: string): Promise<{ samples: Float32Array; sr: number } | null> {
99 return op<{ samples: Float32Array; sr: number } | undefined>('clips', 'readonly', (s) => s.get(id))
100 .then((r) => r ?? null);
101}
102export function deleteClipAudio(id: string): Promise<unknown> {
103 return op('clips', 'readwrite', (s) => s.delete(id));
104}
106/** The last completed benchmark, everything the explorer and the results
107 * tables need to come back after a reload. */
108export interface StoredBenchmark {
109 when: number;
110 names: string[];
111 colors: string[];
112 algos: { id: string; name: string }[];
113 config: BenchConfig;
114 runs: {
115 seed: number;
116 x: Float32Array;
117 truth: { t: number; typeIndex: number; gain: number }[];
118 }[];
119 results: RunResult[];
120}
122export function putBenchmark(b: StoredBenchmark): Promise<unknown> {
123 return op('bench', 'readwrite', (s) => s.put(b, 'last'));
124}
125export function getBenchmark(): Promise<StoredBenchmark | null> {
126 return op<StoredBenchmark | undefined>('bench', 'readonly', (s) => s.get('last')).then((r) => r ?? null);
127}
129export async function clearAll(): Promise<void> {
130 localStorage.removeItem(KEY);
131 for (const s of STORES) await op(s, 'readwrite', (st) => st.clear());
132}