/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / CompareView.tsx
528 lines · 20.4 KBBlameHistoryRaw
1import { useCallback, useEffect, useMemo, useState } from "react";
2import { CanvasPlot, drawLine, drawMarker, readTheme, type MarkerShape, type PointerInfo, type Scales, type Theme } from "./CanvasPlot.tsx";
3import { smoothLog, type Analysis, type AnalysisSettings } from "../analysis/analyze.ts";
4import type { RecordingMeta } from "../storage/db.ts";
5import { colorFor, db10, download, fmtHz, fmtSec, getAnalysis, groupOrder, groupStyle, linearFit } from "../model.ts";
7interface Props {
8 recs: RecordingMeta[]; // recordings included in the comparison
9 all: RecordingMeta[];
10 settings: AnalysisSettings;
11 onOpen: (id: string) => void;
14interface Row {
15 meta: RecordingMeta;
16 a: Analysis;
19type Metric = "median" | "centroid" | "power";
20const METRICS: Record<Metric, { label: string; axis: string; get: (a: Analysis) => number; fmt: (v: number) => string; log: boolean }> = {
21 median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, log: false },
22 centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, log: false },
23 power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, log: false },
24};
26export function CompareView({ recs, all, settings, onOpen }: Props) {
27 const [rows, setRows] = useState<Row[]>([]);
28 const [progress, setProgress] = useState<[number, number]>([0, 0]);
29 const [metric, setMetric] = useState<Metric>("median");
30 const [specMode, setSpecMode] = useState<"group" | "each">("group");
31 const [normalize, setNormalize] = useState(false);
32 const [smoothing, setSmoothing] = useState(1 / 6);
34 useEffect(() => {
35 let live = true;
36 (async () => {
37 const out: Row[] = [];
38 setProgress([0, recs.length]);
39 for (let i = 0; i < recs.length; i++) {
40 const a = await getAnalysis(recs[i], settings);
41 if (!live) return;
42 if (a && a.energy > 0) out.push({ meta: recs[i], a });
43 setProgress([i + 1, recs.length]);
44 await new Promise((r) => setTimeout(r, 0));
45 }
46 if (live) setRows(out);
47 })();
48 return () => {
49 live = false;
50 };
51 }, [recs, settings]);
53 const groups = useMemo(() => groupOrder(rows.map((r) => r.meta)), [rows]);
54 const style = useCallback((label: string) => groupStyle(label, all), [all]);
56 const skipped = recs.length - rows.length;
57 const loading = progress[0] < progress[1];
59 if (!recs.length) return <div className="card empty">No recordings are included in the comparison. Tick some in the list on the left.</div>;
61 return (
62 <div className="compare">
63 {loading && (
64 <div className="card muted">
65 Analysing {progress[0]} / {progress[1]}…
66 </div>
67 )}
68 {!loading && skipped > 0 && (
69 <div className="card warn">
70 {skipped} recording{skipped > 1 ? "s have" : " has"} no tear segment or no energy above the background and {skipped > 1 ? "are" : "is"} left out.
71 </div>
72 )}
73 <Summary rows={rows} groups={groups} />
75 <div className="grid2">
76 <section className="card">
77 <h3>Total sound energy vs tear duration</h3>
78 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
79 <Scatter rows={rows} y={(a) => db10(a.energy)} yFmt={(v) => `${v.toFixed(1)} dB`} yLabel="energy (dB re FS²·s)" style={style} onOpen={onOpen} fitUnit="dB" minSpan={10} />
80 </section>
81 <section className="card">
82 <div className="plot-head">
83 <h3>{METRICS[metric].label} vs tear duration</h3>
84 <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Metric">
85 {(Object.keys(METRICS) as Metric[]).map((k) => (
86 <option key={k} value={k}>
87 {METRICS[k].label}
88 </option>
89 ))}
90 </select>
91 </div>
92 <p className="caption">
93 {metric === "power"
94 ? "Same energy packed into less time means power rises 10 dB for every 10× shorter tear."
95 : "If the clicks are the same at every speed, this should not depend on duration."}
96 </p>
97 <Scatter
98 rows={rows}
99 y={METRICS[metric].get}
100 yFmt={METRICS[metric].fmt}
101 yLabel={METRICS[metric].axis}
102 style={style}
103 onOpen={onOpen}
104 fitUnit={metric === "power" ? "dB" : "Hz"}
105 minSpan={metric === "power" ? 10 : 4000}
106 />
107 </section>
108 </div>
110 <section className="card">
111 <div className="plot-head">
112 <h3>Frequency makeup</h3>
113 <div className="toolbar">
114 <select value={specMode} onChange={(e) => setSpecMode(e.target.value as "group" | "each")} aria-label="Lines">
115 <option value="group">average per label</option>
116 <option value="each">each recording</option>
117 </select>
118 <label>
119 <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> shape only (scale each to equal energy)
120 </label>
121 <label>
122 smoothing
123 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
124 <option value={1 / 12}>1/12 octave</option>
125 <option value={1 / 6}>1/6 octave</option>
126 <option value={1 / 3}>1/3 octave</option>
127 </select>
128 </label>
129 </div>
130 </div>
131 <p className="caption">
132 Energy spectral density of each tear with the background removed.
133 {normalize
134 ? " Each curve is divided by its total energy in the band, so only the shape is compared."
135 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
136 </p>
137 <SpectraOverlay rows={rows} groups={groups} mode={specMode} normalize={normalize} smoothing={smoothing} settings={settings} style={style} />
138 </section>
140 <section className="card">
141 <div className="plot-head">
142 <h3>All recordings</h3>
143 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
144 Download CSV
145 </button>
146 </div>
147 <Table rows={rows} groups={groups} style={style} onOpen={onOpen} />
148 </section>
149 </div>
150 );
153// ---------- summary ----------
155function Summary({ rows, groups }: { rows: Row[]; groups: string[] }) {
156 if (rows.length < 3) return <div className="card muted">Add at least three recordings (ideally at a few different speeds) to see trends.</div>;
157 const lx = rows.map((r) => Math.log10(r.a.duration));
158 const fe = linearFit(lx, rows.map((r) => db10(r.a.energy)));
159 const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
160 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
161 return (
162 <section className="card summary">
163 <h3>The two questions</h3>
164 <div className="q">
165 <div className="q-title">Same total energy at every speed?</div>
166 {fe && (
167 <div>
168 Energy changes by <b>{fmtSigned(fe.b)} ± {fe.seB.toFixed(2)} dB</b> for each 10× longer tear (straight-line fit, ± one standard error, {fe.n} recordings).
169 {" "}
170 {verdict(fe.b, fe.seB)}
171 </div>
172 )}
173 </div>
174 <div className="q">
175 <div className="q-title">Same frequency makeup at every speed?</div>
176 {fm && (
177 <div>
178 Median frequency changes by <b>{fmtSigned(fm.b, 0)} ± {fm.seB.toFixed(0)} Hz</b> for each 10× longer tear. Compare the curve shapes below (tick “shape only”).
179 {" "}
180 {verdict(fm.b, fm.seB)}
181 </div>
182 )}
183 </div>
184 <p className="caption">
185 Durations span {span.toFixed(1)}× across {groups.length} label{groups.length === 1 ? "" : "s"}.
186 {span < 3 ? " That is a narrow range; trends will be hard to see." : ""} The fit uses measured durations, not labels. A trend within about two standard errors of zero is not distinguishable from no trend. Run-to-run scatter at the same speed tells you how much a single comparison can be trusted.
187 </p>
188 </section>
189 );
192function fmtSigned(v: number, digits = 2) {
193 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
196function verdict(b: number, se: number) {
197 if (!Number.isFinite(se)) return null;
198 return Math.abs(b) < 2 * se ? <span className="muted">(not clearly different from zero)</span> : <span className="muted">(clearly different from zero)</span>;
201// ---------- scatter ----------
203function Scatter({
204 rows,
205 y,
206 yFmt,
207 yLabel,
208 style,
209 onOpen,
210 fitUnit,
211 minSpan,
212}: {
213 minSpan: number;
214 rows: Row[];
215 y: (a: Analysis) => number;
216 yFmt: (v: number) => string;
217 yLabel: string;
218 style: (l: string) => { slot: number | null; shape: MarkerShape };
219 onOpen: (id: string) => void;
220 fitUnit: string;
221}) {
222 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
223 const xr = useMemo<[number, number]>(() => {
224 if (!pts.length) return [0.1, 20];
225 const lo = Math.min(...pts.map((p) => p.x));
226 const hi = Math.max(...pts.map((p) => p.x));
227 return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
228 }, [pts]);
229 const yr = useMemo<[number, number]>(() => {
230 if (!pts.length) return [0, 1];
231 const lo = Math.min(...pts.map((p) => p.y));
232 const hi = Math.max(...pts.map((p) => p.y));
233 // keep a minimum span so tiny differences are not blown up to fill the plot
234 const mid = (lo + hi) / 2;
235 const half = Math.max((hi - lo) * 0.6, minSpan / 2);
236 return [mid - half, mid + half];
237 }, [pts, minSpan]);
238 const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
240 const draw = useCallback(
241 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
242 if (fit) {
243 drawLine(ctx, s, [xr[0], xr[1]], [fit.a + fit.b * Math.log10(xr[0]), fit.a + fit.b * Math.log10(xr[1])], th.muted, 1.5, [6, 4]);
244 }
245 for (const p of pts) {
246 const st = style(p.r.meta.label);
247 drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 5);
248 }
249 },
250 [pts, fit, xr, style],
251 );
253 const near = (p: PointerInfo) => {
254 let best: (typeof pts)[number] | null = null;
255 let bd = 14 * 14;
256 for (const q of pts) {
257 const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
258 if (d < bd) {
259 bd = d;
260 best = q;
261 }
262 }
263 return best;
264 };
266 return (
267 <>
268 <CanvasPlot
269 height={280}
270 xRange={xr}
271 xLog
272 yRange={yr}
273 xLabel="tear duration (s)"
274 yLabel={yLabel}
275 draw={draw}
276 hover={(p) => {
277 const q = near(p);
278 if (!q) return null;
279 return { lines: [q.r.meta.label, `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
280 }}
281 onClick={(p) => {
282 const q = near(p);
283 if (q) onOpen(q.r.meta.id);
284 }}
285 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
286 ariaLabel={`${yLabel} against tear duration`}
287 />
288 <Legend labels={groupOrder(rows.map((r) => r.meta))} style={style} extra={fit ? `dashed: straight-line fit, slope ${fmtSigned(fit.b, fitUnit === "Hz" ? 0 : 2)} ${fitUnit} per 10× duration` : undefined} />
289 </>
290 );
293// ---------- spectra overlay ----------
295function SpectraOverlay({
296 rows,
297 groups,
298 mode,
299 normalize,
300 smoothing,
301 settings,
302 style,
303}: {
304 rows: Row[];
305 groups: string[];
306 mode: "group" | "each";
307 normalize: boolean;
308 smoothing: number;
309 settings: AnalysisSettings;
310 style: (l: string) => { slot: number | null; shape: MarkerShape };
311}) {
312 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
313 const fLo = Math.max(20, settings.bandLow);
314 const fHi = Math.min(settings.bandHigh, fsMin / 2);
316 const lines = useMemo(() => {
317 const per = rows.map((r) => {
318 const scale = normalize ? 1 / r.a.energy : 1;
319 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
320 return { label: r.meta.label, name: r.meta.label, f: sm.f, v: sm.v };
321 });
322 if (mode === "each") return per.map((p) => ({ ...p, db: p.v.map(db10Floor) }));
323 return groups
324 .map((g) => {
325 const members = per.filter((p) => p.label === g);
326 if (!members.length) return null;
327 const f = members[0].f;
328 const v = f.map((_, i) => members.reduce((s, m) => s + (m.v[i] ?? 0), 0) / members.length);
329 return { label: g, name: `${g} (n=${members.length})`, f, v, db: v.map(db10Floor) };
330 })
331 .filter((x): x is NonNullable<typeof x> => !!x);
332 }, [rows, groups, mode, normalize, smoothing, fLo, fHi]);
334 const yr = useMemo<[number, number]>(() => {
335 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
336 if (!all.length) return [-100, 0];
337 const top = Math.max(...all);
338 return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
339 }, [lines]);
341 const draw = useCallback(
342 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
343 for (const l of lines) {
344 const st = style(l.label);
345 drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), mode === "each" ? 1.5 : 2);
346 }
347 },
348 [lines, style, mode],
349 );
351 return (
352 <>
353 <CanvasPlot
354 height={340}
355 xRange={[fLo, fHi]}
356 xLog
357 yRange={yr}
358 xLabel="frequency (Hz)"
359 yLabel={normalize ? "relative density (dB re 1/Hz)" : "energy density (dB re FS²·s/Hz)"}
360 draw={draw}
361 hover={(p) => {
362 if (!lines.length) return null;
363 const f = lines[0].f;
364 let i = 0;
365 for (let k = 1; k < f.length; k++) if (Math.abs(Math.log(f[k] / p.xv)) < Math.abs(Math.log(f[i] / p.xv))) i = k;
366 const vals = lines.slice(0, 10).map((l) => `${l.name}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`);
367 if (lines.length > 10) vals.push(`… ${lines.length - 10} more`);
368 return { lines: [fmtHz(f[i]), ...vals], x: f[i] };
369 }}
370 ariaLabel="Energy spectral density of tears, overlaid"
371 />
372 <Legend labels={groups} style={style} lines />
373 </>
374 );
377function db10Floor(v: number) {
378 return v > 0 ? 10 * Math.log10(v) : NaN;
381// ---------- legend & table ----------
383function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
384 if (line) return <svg width="18" height="10" aria-hidden><line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" /></svg>;
385 const d: Record<MarkerShape, string> = {
386 circle: "M9,4 a5,5 0 1,0 0.01,0",
387 square: "M4.5,4.5 h9 v9 h-9 z",
388 triangle: "M9,3.5 L14.2,13 L3.8,13 z",
389 diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z",
390 cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z",
391 };
392 return (
393 <svg width="18" height="18" aria-hidden>
394 <path d={d[shape]} fill={color} />
395 </svg>
396 );
399function Legend({ labels, style, lines, extra }: { labels: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; lines?: boolean; extra?: string }) {
400 const th = readTheme(document.documentElement);
401 return (
402 <div className="legend">
403 {labels.map((l) => {
404 const st = style(l);
405 return (
406 <span key={l}>
407 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {l}
408 </span>
409 );
410 })}
411 {extra && <span className="muted">{extra}</span>}
412 </div>
413 );
416function Table({ rows, groups, style, onOpen }: { rows: Row[]; groups: string[]; style: (l: string) => { slot: number | null; shape: MarkerShape }; onOpen: (id: string) => void }) {
417 const th = readTheme(document.documentElement);
418 const sorted = [...rows].sort((a, b) => groups.indexOf(a.meta.label) - groups.indexOf(b.meta.label) || b.a.duration - a.a.duration);
419 const groupStats = groups.map((g) => {
420 const rs = rows.filter((r) => r.meta.label === g);
421 const e = rs.map((r) => db10(r.a.energy));
422 const mean = e.reduce((s, v) => s + v, 0) / e.length;
423 const sd = e.length > 1 ? Math.sqrt(e.reduce((s, v) => s + (v - mean) ** 2, 0) / (e.length - 1)) : NaN;
424 return {
425 g,
426 n: rs.length,
427 dur: rs.reduce((s, r) => s + r.a.duration, 0) / rs.length,
428 mean,
429 sd,
430 med: rs.reduce((s, r) => s + r.a.medianFreq, 0) / rs.length,
431 };
432 });
433 return (
434 <div className="table-wrap">
435 <table>
436 <thead>
437 <tr>
438 <th>Label</th>
439 <th>n</th>
440 <th className="num">Mean duration</th>
441 <th className="num">Energy (dB), mean ± sd</th>
442 <th className="num">Median freq, mean</th>
443 </tr>
444 </thead>
445 <tbody>
446 {groupStats.map((s) => {
447 const st = style(s.g);
448 return (
449 <tr key={s.g}>
450 <td>
451 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {s.g}
452 </td>
453 <td>{s.n}</td>
454 <td className="num">{fmtSec(s.dur)}</td>
455 <td className="num">
456 {s.mean.toFixed(1)}
457 {Number.isFinite(s.sd) ? ` ± ${s.sd.toFixed(1)}` : ""}
458 </td>
459 <td className="num">{fmtHz(s.med)}</td>
460 </tr>
461 );
462 })}
463 </tbody>
464 </table>
465 <table>
466 <thead>
467 <tr>
468 <th>Label</th>
469 <th className="num">Duration</th>
470 <th className="num">Speed (in/s)</th>
471 <th className="num">Energy (dB)</th>
472 <th className="num">Above bg (dB)</th>
473 <th className="num">Median freq</th>
474 <th className="num">Centroid</th>
475 <th className="num">Peak (dBFS)</th>
476 <th></th>
477 </tr>
478 </thead>
479 <tbody>
480 {sorted.map(({ meta, a }) => {
481 const st = style(meta.label);
482 return (
483 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)}>
484 <td>
485 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {meta.label}
486 </td>
487 <td className="num">{fmtSec(a.duration)}</td>
488 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
489 <td className="num">{db10(a.energy).toFixed(1)}</td>
490 <td className="num">{Number.isFinite(a.snrDb) ? a.snrDb.toFixed(1) : "–"}</td>
491 <td className="num">{fmtHz(a.medianFreq)}</td>
492 <td className="num">{fmtHz(a.centroid)}</td>
493 <td className="num">{a.peakDbfs.toFixed(1)}</td>
494 <td>{a.nearClip > 0 ? <span className="warn-inline">⚠ clipped</span> : meta.source !== "mic" ? <span className={`badge ${meta.source}`}>{meta.source}</span> : null}</td>
495 </tr>
496 );
497 })}
498 </tbody>
499 </table>
500 </div>
501 );
504function exportCsv(rows: Row[], settings: AnalysisSettings) {
505 const head = [
506 "id", "created", "label", "source", "notes", "sample_rate", "tear_start_s", "tear_end_s", "segment_manual", "duration_s", "speed_in_per_s",
507 "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
508 "band_low_hz", "band_high_hz", "sheet_length_in",
509 ];
510 const q = (v: unknown) => {
511 const s = String(v ?? "");
512 return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
513 };
514 const lines = [head.join(",")];
515 for (const { meta: m, a } of rows) {
516 lines.push(
517 [
518 m.id, new Date(m.createdAt).toISOString(), m.label, m.source, m.notes, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
519 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
520 a.snrDb.toFixed(2), a.medianFreq.toFixed(1), a.centroid.toFixed(1), a.f10.toFixed(1), a.f90.toFixed(1), a.peakDbfs.toFixed(2), a.nearClip,
521 settings.bandLow, settings.bandHigh, settings.sheetLengthIn,
522 ]
523 .map(q)
524 .join(","),
525 );
526 }
527 download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
↑↓ move↵openescclose