/ magland / rip-sound-analyzer
Sign in
magland / rip-sound-analyzer
rip-sound-analyzer / src / components / CompareView.tsx
455 lines · 17.8 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, linearFit, SPEEDS, speedName, speedStyle } from "../model.ts";
7interface Props {
8 recs: RecordingMeta[]; // at most one per speed, in speed order
9 settings: AnalysisSettings;
10 onOpen: (id: string) => void;
13interface Row {
14 meta: RecordingMeta;
15 a: Analysis;
18type Metric = "median" | "centroid" | "power";
19const METRICS: Record<Metric, { label: string; axis: string; get: (a: Analysis) => number; fmt: (v: number) => string; minSpan: number; unit: string }> = {
20 median: { label: "Median frequency", axis: "median frequency (Hz)", get: (a) => a.medianFreq, fmt: fmtHz, minSpan: 4000, unit: "Hz" },
21 centroid: { label: "Spectral centroid", axis: "centroid (Hz)", get: (a) => a.centroid, fmt: fmtHz, minSpan: 4000, unit: "Hz" },
22 power: { label: "Mean power", axis: "mean power (dBFS)", get: (a) => db10(a.energy / a.duration), fmt: (v) => `${v.toFixed(1)} dBFS`, minSpan: 10, unit: "dB" },
23};
25const energyOf = (a: Analysis) => db10(a.energy);
26const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
28export function CompareView({ recs, settings, onOpen }: Props) {
29 const [rows, setRows] = useState<Row[]>([]);
30 const [ready, setReady] = useState(false);
31 const [metric, setMetric] = useState<Metric>("median");
32 const [normalize, setNormalize] = useState(false);
33 const [smoothing, setSmoothing] = useState(1 / 6);
35 useEffect(() => {
36 let live = true;
37 setReady(false);
38 (async () => {
39 const out: Row[] = [];
40 for (const m of recs) {
41 const a = await getAnalysis(m, settings);
42 if (!live) return;
43 if (a && a.energy > 0) out.push({ meta: m, a });
44 await new Promise((r) => setTimeout(r, 0));
45 }
46 if (live) {
47 setRows(out);
48 setReady(true);
49 }
50 })();
51 return () => {
52 live = false;
53 };
54 }, [recs, settings]);
56 const bandLabel = `${+(settings.energyLow / 1000).toFixed(2)}–${+(settings.energyHigh / 1000).toFixed(2)} kHz`;
57 const missing = SPEEDS.filter((s) => !recs.some((r) => r.label === s.id));
58 const unusable = recs.filter((m) => !rows.some((r) => r.meta.id === m.id));
60 if (!recs.length) return <div className="card empty">Nothing to compare yet. Record a tear at two or more speeds on the Record tab.</div>;
61 if (!ready) return <div className="card muted">Analysing…</div>;
63 return (
64 <div className="compare">
65 {(missing.length > 0 || unusable.length > 0) && (
66 <div className="card muted small">
67 {missing.length > 0 && <div>Not recorded yet: {missing.map((s) => s.name.toLowerCase()).join(", ")}.</div>}
68 {unusable.length > 0 && <div>Left out (no tear range or no sound above the background): {unusable.map((m) => speedName(m.label)).join(", ")}.</div>}
69 </div>
70 )}
72 <Summary rows={rows} bandLabel={bandLabel} />
74 <div className="grid2">
75 <section className="card">
76 <h3>Total sound energy ({bandLabel}) vs tear duration</h3>
77 <p className="caption">If every tear contains the same clicks, the points should lie on a flat line.</p>
78 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
79 </section>
80 <section className="card">
81 <div className="plot-head">
82 <h3>{METRICS[metric].label} vs tear duration</h3>
83 <select value={metric} onChange={(e) => setMetric(e.target.value as Metric)} aria-label="Quantity to plot">
84 {(Object.keys(METRICS) as Metric[]).map((k) => (
85 <option key={k} value={k}>
86 {METRICS[k].label}
87 </option>
88 ))}
89 </select>
90 </div>
91 <p className="caption">
92 {metric === "power"
93 ? "The same energy packed into less time: power should rise 10 dB for every 10× shorter tear (slope −10 dB)."
94 : "If the clicks are the same at every speed, this should not depend on duration."}
95 </p>
96 <Scatter rows={rows} y={METRICS[metric].get} yFmt={METRICS[metric].fmt} yLabel={METRICS[metric].axis} onOpen={onOpen} unit={METRICS[metric].unit} minSpan={METRICS[metric].minSpan} />
97 </section>
98 </div>
100 <section className="card">
101 <div className="plot-head">
102 <h3>Frequency makeup</h3>
103 <div className="toolbar">
104 <label>
105 <input type="checkbox" checked={normalize} onChange={(e) => setNormalize(e.target.checked)} /> compare shape only (scale each to the same total energy)
106 </label>
107 <label>
108 smoothing
109 <select value={smoothing} onChange={(e) => setSmoothing(+e.target.value)}>
110 <option value={1 / 12}>1/12 octave</option>
111 <option value={1 / 6}>1/6 octave</option>
112 <option value={1 / 3}>1/3 octave</option>
113 </select>
114 </label>
115 </div>
116 </div>
117 <p className="caption">
118 Energy spectrum of each tear, background removed.
119 {normalize
120 ? " Each curve is divided by its total energy over the plotted range, so only the shape is compared."
121 : " If tears at all speeds contain the same clicks, the curves should lie on top of each other."}
122 </p>
123 <SpectraOverlay rows={rows} normalize={normalize} smoothing={smoothing} settings={settings} />
124 </section>
126 <section className="card">
127 <div className="plot-head">
128 <h3>Numbers</h3>
129 <button onClick={() => exportCsv(rows, settings)} disabled={!rows.length}>
130 Download CSV
131 </button>
132 </div>
133 <Table rows={rows} onOpen={onOpen} />
134 </section>
135 </div>
136 );
139// ---------- summary ----------
141function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
142 if (rows.length < 2) return <div className="card muted">Record at least two speeds to compare them.</div>;
143 const lx = rows.map((r) => Math.log10(r.a.duration));
144 const e = rows.map((r) => db10(r.a.energy));
145 const fe = linearFit(lx, e);
146 const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
147 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
148 const eRange = Math.max(...e) - Math.min(...e);
149 const meds = rows.map((r) => r.a.medianFreq);
150 return (
151 <section className="card summary">
152 <h3>The two questions</h3>
153 <div className="q">
154 <div className="q-title">Same total energy at every speed?</div>
155 <div>
156 Across {rows.length} speeds the energy in {bandLabel} varies over a range of <b>{eRange.toFixed(1)} dB</b>.
157 {fe && (
158 <>
159 {" "}
160 The trend is <b>{fmtSigned(fe.b)} dB</b> per 10× longer tear (straight-line fit, ± {fe.seB.toFixed(2)} dB).
161 </>
162 )}
163 </div>
164 </div>
165 <div className="q">
166 <div className="q-title">Same frequency makeup at every speed?</div>
167 <div>
168 Median frequency ranges from <b>{fmtHz(Math.min(...meds))}</b> to <b>{fmtHz(Math.max(...meds))}</b>.
169 {fm && (
170 <>
171 {" "}
172 The trend is <b>{fmtSigned(fm.b, 0)} Hz</b> per 10× longer tear (± {fm.seB.toFixed(0)} Hz).
173 </>
174 )}{" "}
175 Compare the curve shapes below.
176 </div>
177 </div>
178 <p className="caption">
179 Tear durations span {span.toFixed(1)}×{span < 3 ? ", a narrow range, so trends will be hard to see" : ""}. Trends use measured durations, not the speed names.
180 With one tear per speed there is no way to tell how much two tears at the same speed would differ, so differences of a dB or two may just be
181 ordinary variation from tear to tear.
182 {fe ? "" : " A trend line needs at least three speeds."}
183 </p>
184 </section>
185 );
188function fmtSigned(v: number, digits = 2) {
189 return `${v >= 0 ? "+" : "−"}${Math.abs(v).toFixed(digits)}`;
192// ---------- scatter ----------
194function Scatter({
195 rows,
196 y,
197 yFmt,
198 yLabel,
199 onOpen,
200 unit,
201 minSpan,
202}: {
203 rows: Row[];
204 y: (a: Analysis) => number;
205 yFmt: (v: number) => string;
206 yLabel: string;
207 onOpen: (id: string) => void;
208 unit: string;
209 minSpan: number;
210}) {
211 const pts = useMemo(() => rows.map((r) => ({ r, x: r.a.duration, y: y(r.a) })).filter((p) => Number.isFinite(p.y)), [rows, y]);
212 const xr = useMemo<[number, number]>(() => {
213 if (!pts.length) return [0.1, 20];
214 const lo = Math.min(...pts.map((p) => p.x));
215 const hi = Math.max(...pts.map((p) => p.x));
216 return [Math.min(lo / 1.5, 0.2), Math.max(hi * 1.5, 15)];
217 }, [pts]);
218 const yr = useMemo<[number, number]>(() => {
219 if (!pts.length) return [0, 1];
220 const lo = Math.min(...pts.map((p) => p.y));
221 const hi = Math.max(...pts.map((p) => p.y));
222 // keep a minimum span so tiny differences are not blown up to fill the plot
223 const mid = (lo + hi) / 2;
224 const half = Math.max((hi - lo) * 0.6, minSpan / 2);
225 return [mid - half, mid + half];
226 }, [pts, minSpan]);
227 const fit = useMemo(() => linearFit(pts.map((p) => Math.log10(p.x)), pts.map((p) => p.y)), [pts]);
229 const draw = useCallback(
230 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
231 if (fit) 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]);
232 for (const p of pts) {
233 const st = speedStyle(p.r.meta.label);
234 drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 6);
235 }
236 },
237 [pts, fit, xr],
238 );
240 const near = (p: PointerInfo) => {
241 let best: (typeof pts)[number] | null = null;
242 let bd = 14 * 14;
243 for (const q of pts) {
244 const d = (p.scales.x(q.x) - p.px) ** 2 + (p.scales.y(q.y) - p.py) ** 2;
245 if (d < bd) {
246 bd = d;
247 best = q;
248 }
249 }
250 return best;
251 };
253 return (
254 <>
255 <CanvasPlot
256 height={280}
257 xRange={xr}
258 xLog
259 yRange={yr}
260 xLabel="tear duration (s)"
261 yLabel={yLabel}
262 draw={draw}
263 hover={(p) => {
264 const q = near(p);
265 if (!q) return null;
266 return { lines: [speedName(q.r.meta.label), `${fmtSec(q.x)} · ${yFmt(q.y)}`, "click to open"], x: q.x, y: q.y };
267 }}
268 onClick={(p) => {
269 const q = near(p);
270 if (q) onOpen(q.r.meta.id);
271 }}
272 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
273 ariaLabel={`${yLabel} against tear duration`}
274 />
275 <Legend rows={rows} extra={fit ? `dashed: trend, ${fmtSigned(fit.b, unit === "Hz" ? 0 : 2)} ${unit} per 10× duration` : undefined} />
276 </>
277 );
280// ---------- spectra overlay ----------
282function SpectraOverlay({ rows, normalize, smoothing, settings }: { rows: Row[]; normalize: boolean; smoothing: number; settings: AnalysisSettings }) {
283 const fsMin = rows.length ? Math.min(...rows.map((r) => r.a.fs)) : 48000;
284 const fLo = Math.max(20, settings.shapeLow);
285 const fHi = Math.min(settings.shapeHigh, fsMin / 2);
287 const lines = useMemo(
288 () =>
289 rows.map((r) => {
290 const scale = normalize ? 1 / r.a.shapeEnergy : 1;
291 const sm = smoothLog(r.a.freqs, r.a.netEsd.map((v) => v * scale), fLo, fHi, smoothing);
292 return { label: r.meta.label, f: sm.f, db: sm.v.map((v) => (v > 0 ? 10 * Math.log10(v) : NaN)) };
293 }),
294 [rows, normalize, smoothing, fLo, fHi],
295 );
297 const yr = useMemo<[number, number]>(() => {
298 const all = lines.flatMap((l) => l.db.filter(Number.isFinite));
299 if (!all.length) return [-100, 0];
300 const top = Math.max(...all);
301 return [Math.floor((top - 50) / 10) * 10, Math.ceil((top + 3) / 5) * 5];
302 }, [lines]);
304 const draw = useCallback(
305 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
306 if (!normalize) {
307 // mark the energy band
308 ctx.fillStyle = th.seg;
309 const bl = s.x(Math.max(settings.energyLow, fLo));
310 const bh = s.x(Math.min(settings.energyHigh, fHi));
311 if (bh > bl) ctx.fillRect(bl, s.top, bh - bl, s.bottom - s.top);
312 }
313 for (const l of lines) {
314 const st = speedStyle(l.label);
315 drawLine(ctx, s, l.f, l.db, colorFor(st.slot, th.series, th.muted), 2);
316 }
317 },
318 [lines, normalize, settings, fLo, fHi],
319 );
321 return (
322 <>
323 <CanvasPlot
324 height={340}
325 xRange={[fLo, fHi]}
326 xLog
327 yRange={yr}
328 xLabel="frequency (Hz)"
329 yLabel={normalize ? "relative density (dB re 1/Hz)" : "energy density (dB re FS²·s/Hz)"}
330 draw={draw}
331 hover={(p) => {
332 if (!lines.length) return null;
333 const f = lines[0].f;
334 let i = 0;
335 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;
336 return { lines: [fmtHz(f[i]), ...lines.map((l) => `${speedName(l.label)}: ${Number.isFinite(l.db[i]) ? l.db[i].toFixed(1) : "–"} dB`)], x: f[i] };
337 }}
338 ariaLabel="Energy spectra of the tears, overlaid"
339 />
340 <Legend rows={rows} lines extra={normalize ? undefined : "shaded: energy band"} />
341 </>
342 );
345// ---------- legend & table ----------
347function MarkerIcon({ shape, color, line }: { shape: MarkerShape; color: string; line?: boolean }) {
348 if (line)
349 return (
350 <svg width="18" height="10" aria-hidden>
351 <line x1="1" y1="5" x2="17" y2="5" stroke={color} strokeWidth="2.5" strokeLinecap="round" />
352 </svg>
353 );
354 const d: Record<MarkerShape, string> = {
355 circle: "M9,4 a5,5 0 1,0 0.01,0",
356 square: "M4.5,4.5 h9 v9 h-9 z",
357 triangle: "M9,3.5 L14.2,13 L3.8,13 z",
358 diamond: "M9,2.8 L14.2,9 L9,15.2 L3.8,9 z",
359 cross: "M7,4 h4 v3 h3 v4 h-3 v3 h-4 v-3 h-3 v-4 h3 z",
360 };
361 return (
362 <svg width="18" height="18" aria-hidden>
363 <path d={d[shape]} fill={color} />
364 </svg>
365 );
368function Legend({ rows, lines, extra }: { rows: Row[]; lines?: boolean; extra?: string }) {
369 const th = readTheme(document.documentElement);
370 return (
371 <div className="legend">
372 {rows.map((r) => {
373 const st = speedStyle(r.meta.label);
374 return (
375 <span key={r.meta.id}>
376 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} line={lines} /> {speedName(r.meta.label)}
377 </span>
378 );
379 })}
380 {extra && <span className="muted">{extra}</span>}
381 </div>
382 );
385function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void }) {
386 const th = readTheme(document.documentElement);
387 return (
388 <div className="table-wrap">
389 <table>
390 <thead>
391 <tr>
392 <th>Speed</th>
393 <th className="num">Tear duration</th>
394 <th className="num">Speed (in/s)</th>
395 <th className="num">Energy (dB)</th>
396 <th className="num">Mean power (dBFS)</th>
397 <th className="num">Median freq</th>
398 <th className="num">Centroid</th>
399 <th className="num">Above background</th>
400 <th className="num">Peak (dBFS)</th>
401 </tr>
402 </thead>
403 <tbody>
404 {rows.map(({ meta, a }) => {
405 const st = speedStyle(meta.label);
406 return (
407 <tr key={meta.id} className="clickable" onClick={() => onOpen(meta.id)} title="Open on the Record tab">
408 <td>
409 <MarkerIcon shape={st.shape} color={colorFor(st.slot, th.series, th.muted)} /> {speedName(meta.label)}
410 </td>
411 <td className="num">{fmtSec(a.duration)}</td>
412 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
413 <td className="num">{db10(a.energy).toFixed(1)}</td>
414 <td className="num">{db10(a.energy / a.duration).toFixed(1)}</td>
415 <td className="num">{fmtHz(a.medianFreq)}</td>
416 <td className="num">{fmtHz(a.centroid)}</td>
417 <td className="num">{Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"}</td>
418 <td className="num">
419 {a.peakDbfs.toFixed(1)}
420 {a.nearClip > 0 ? " ⚠ clipped" : ""}
421 </td>
422 </tr>
423 );
424 })}
425 </tbody>
426 </table>
427 </div>
428 );
431function exportCsv(rows: Row[], settings: AnalysisSettings) {
432 const head = [
433 "speed", "recorded", "source", "sample_rate", "tear_start_s", "tear_end_s", "range_set_by_hand", "duration_s", "speed_in_per_s",
434 "energy_db", "energy_raw_db", "background_db", "above_background_db", "median_hz", "centroid_hz", "f10_hz", "f90_hz", "peak_dbfs", "near_clip_samples",
435 "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
436 ];
437 const q = (v: unknown) => {
438 const s = String(v ?? "");
439 return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
440 };
441 const lines = [head.join(",")];
442 for (const { meta: m, a } of rows) {
443 lines.push(
444 [
445 m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
446 a.duration.toFixed(4), a.speedInPerSec.toFixed(4), db10(a.energy).toFixed(3), db10(a.energyRaw).toFixed(3), db10(a.energyNoise).toFixed(3),
447 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,
448 settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
449 ]
450 .map(q)
451 .join(","),
452 );
453 }
454 download(new Blob([lines.join("\n")], { type: "text/csv" }), `rip-sound-summary-${new Date().toISOString().slice(0, 10)}.csv`);
↑↓ move↵openescclose