Drop median frequency and centroid
Frequency makeup is compared through the overlaid spectra instead. The
second Compare plot is now loudness (mean power) vs tear duration, with
the -10 dB per 10x line expected if energy is the same at every speed.
7 changed files+43−76
README.mdmodified+3−3View file
@@ -26,12 +26,12 @@ Open the printed localhost URL in Chrome. Everything runs in the browser; record
2626
2727 - **Record**: five fixed speeds (very slow ~10 s to very fast <0.5 s), one tear each. Pick a speed, record it, check it, re-record or delete it. Capture is raw: Chrome's echo cancellation, noise suppression and auto gain are off, and samples come straight from the audio graph via an AudioWorklet at the mic's own sample rate (32-bit float, no compression). For each recording:
2828 - **Tear range**: found automatically; drag across the level plot to mark it again, drag its edges, or type start/end times. Play the tear (with a moving playhead) or the whole recording.
29- - **Results**: duration, speed, energy, median frequency, centroid, mean power, peak/clipping, level above background.
29+ - **Results**: duration, speed, energy, mean power, peak/clipping, level above background.
3030 - **Close-up**: waveform and spectrogram, with zoom buttons, to look for individual clicks.
3131 - **Frequency makeup**: the tear's energy spectrum against the background.
32-- **Compare**: energy vs tear duration, median frequency / centroid / mean power vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
32+- **Compare**: energy vs tear duration, loudness (mean power) vs duration, spectra of all speeds overlaid (optionally shape only), a table and CSV export.
3333
34-Two frequency bands (set under Analysis settings): the **energy band**, default 15–20 kHz, is used for total energy, finding the tear, the level-over-time plot and the background comparison, because lower frequencies carry much more room and handling noise. The **spectrum band**, default 100 Hz–20 kHz, is used for median frequency, centroid and comparing spectrum shapes.
34+Two frequency bands (set under Analysis settings): the **energy band**, default 15–20 kHz, is used for total energy, finding the tear, the level-over-time plot and the background comparison, because lower frequencies carry much more room and handling noise. The **spectrum band**, default 100 Hz–20 kHz, is the range over which spectra are shown and compared.
3535
3636 The “What this can tell you” tab in the app explains the method and its limits.
3737
scripts/check-analysis.tsmodified+8−6View file
@@ -1,5 +1,5 @@
11 // Sanity checks for the analysis, run with `npm test`.
2-import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels } from "../src/analysis/analyze.ts";
2+import { analyze, detectSegment, DEFAULT_SETTINGS, energyBand, bandLevels, smoothLog } from "../src/analysis/analyze.ts";
33 import { syntheticTear } from "../src/audio/synthetic.ts";
44 import { decodeWav, encodeWavFloat32 } from "../src/audio/wav.ts";
55
@@ -44,20 +44,22 @@ const fs = 48000;
4444 }
4545
4646 // Synthetic tears: same clicks at different durations
47-const results: { T: number; energyDb: number; median: number; seg: [number, number] }[] = [];
47+const results: { T: number; energyDb: number; shapeDb: number[] }[] = [];
4848 for (const T of [0.3, 1, 3, 10]) {
4949 const x = syntheticTear({ tearSeconds: T, seed: 3 });
5050 const seg = detectSegment(x, fs, energyBand(DEFAULT_SETTINGS));
5151 check(`detect segment T=${T}`, !!seg && Math.abs(seg.start - 1) < 0.08 && Math.abs(seg.end - (1 + T)) < 0.08, seg ? `${seg.start.toFixed(3)}–${seg.end.toFixed(3)}` : "none");
5252 if (!seg) continue;
5353 const a = analyze(x, fs, seg, DEFAULT_SETTINGS);
54- results.push({ T, energyDb: 10 * Math.log10(a.energy), median: a.medianFreq, seg: [seg.start, seg.end] });
55- console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB median=${a.medianFreq.toFixed(0)} Hz centroid=${a.centroid.toFixed(0)} Hz peak=${a.peakDbfs.toFixed(1)} dBFS`);
54+ const shape = smoothLog(a.freqs, a.netEsd.map((v) => v / a.shapeEnergy), 1000, 20000, 1 / 3).v.map((v) => 10 * Math.log10(v));
55+ results.push({ T, energyDb: 10 * Math.log10(a.energy), shapeDb: shape });
56+ console.log(` T=${T}s energy=${(10 * Math.log10(a.energy)).toFixed(2)} dB snr=${a.snrDb.toFixed(1)} dB peak=${a.peakDbfs.toFixed(1)} dBFS`);
5657 }
5758 const es = results.map((r) => r.energyDb);
5859 check("synthetic energy independent of duration (range < 1 dB)", Math.max(...es) - Math.min(...es) < 1);
59-const ms = results.map((r) => r.median);
60-check("synthetic median frequency independent of duration (range < 10%)", Math.max(...ms) / Math.min(...ms) < 1.1);
60+let worst = 0;
61+for (const r of results) r.shapeDb.forEach((v, i) => (worst = Math.max(worst, Math.abs(v - results[0].shapeDb[i]))));
62+check("synthetic spectrum shape independent of duration (1/3 octave, 1–20 kHz, within 1.5 dB)", worst < 1.5, `worst ${worst.toFixed(2)} dB`);
6163
6264 // WAV round trip
6365 {
src/App.tsxmodified+1−1View file
@@ -291,7 +291,7 @@ function SettingsPanel({ settings, setSettings }: { settings: AnalysisSettings;
291291 <b>Spectrum band</b>
292292 {field("shapeLow", "from", "Hz")}
293293 {field("shapeHigh", "to", "Hz")}
294- <span className="muted small">Used for median frequency, centroid and comparing spectrum shapes.</span>
294+ <span className="muted small">The frequency range shown when comparing spectra.</span>
295295 </div>
296296 <div className="settings-row">
297297 {field("sheetLengthIn", "Tear length", "in")}
src/analysis/analyze.tsmodified+2−22View file
@@ -10,7 +10,7 @@ export interface AnalysisSettings {
1010 // High frequencies, where the tear stands far above room and handling noise.
1111 energyLow: number; // Hz
1212 energyHigh: number; // Hz
13- // Spectrum band: where median frequency and centroid are computed and spectra are compared.
13+ // Spectrum band: the frequency range over which spectra are shown and compared.
1414 shapeLow: number; // Hz
1515 shapeHigh: number; // Hz
1616 sheetLengthIn: number; // length of the tear, inches
@@ -211,10 +211,6 @@ export interface Analysis {
211211 energy: number; // energyRaw - energyNoise
212212 shapeEnergy: number; // background-subtracted energy in the spectrum band (for normalising shapes)
213213 snrDb: number; // 10 log10(energyRaw / energyNoise)
214- centroid: number; // Hz, of net ESD in the spectrum band
215- medianFreq: number;
216- f10: number;
217- f90: number;
218214 peakDbfs: number; // in the segment
219215 nearClip: number; // samples with |x| >= 0.99 in the segment
220216 backgroundDbfs: number | null; // RMS level of background in the energy band
@@ -273,19 +269,7 @@ export function analyze(
273269
274270 const [sLo, sHi] = bins(settings.shapeLow, settings.shapeHigh);
275271 let tot = 0;
276- let mom = 0;
277- for (let k = sLo; k <= sHi; k++) {
278- tot += netEsd[k];
279- mom += netEsd[k] * freqs[k];
280- }
281- const quantile = (q: number) => {
282- let c = 0;
283- for (let k = sLo; k <= sHi; k++) {
284- c += netEsd[k];
285- if (c >= q * tot) return freqs[k];
286- }
287- return freqs[sHi];
288- };
272+ for (let k = sLo; k <= sHi; k++) tot += netEsd[k];
289273
290274 let peak = 0;
291275 let nearClip = 0;
@@ -318,10 +302,6 @@ export function analyze(
318302 energy,
319303 shapeEnergy: tot * df,
320304 snrDb: noiseEsd ? 10 * Math.log10(energyRaw / Math.max(energyNoise, 1e-30)) : Infinity,
321- centroid: tot > 0 ? mom / tot : NaN,
322- medianFreq: tot > 0 ? quantile(0.5) : NaN,
323- f10: tot > 0 ? quantile(0.1) : NaN,
324- f90: tot > 0 ? quantile(0.9) : NaN,
325305 peakDbfs: 20 * Math.log10(Math.max(peak, 1e-10)),
326306 nearClip,
327307 backgroundDbfs,
src/components/About.tsxmodified+2−2View file
@@ -31,8 +31,8 @@ export function About({ settings }: { settings: AnalysisSettings }) {
3131 <li>
3232 <b>Sound energy</b>: the background-subtracted spectrum summed over the <b>energy band</b>, {fmtHz(settings.energyLow)} –{" "}
3333 {fmtHz(settings.energyHigh)}. Lower frequencies carry much more room and handling noise, so energy, the automatic tear range and the level-over-time
34- plot all use only this band. <b>Median frequency</b> and <b>centroid</b> describe where the energy sits within the wider <b>spectrum band</b>,{" "}
35- {fmtHz(settings.shapeLow)} – {fmtHz(settings.shapeHigh)}. Both bands can be changed under Analysis settings.
34+ plot all use only this band. Spectra are shown and compared over the wider <b>spectrum band</b>, {fmtHz(settings.shapeLow)} –{" "}
35+ {fmtHz(settings.shapeHigh)}. Both bands can be changed under Analysis settings.
3636 </li>
3737 </ul>
3838
src/components/CompareView.tsxmodified+27−39View file
@@ -15,12 +15,8 @@ interface Row {
1515 a: Analysis;
1616 }
1717
18-type Metric = "median" | "centroid" | "power";
19-const 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-};
18+const powerOf = (a: Analysis) => db10(a.energy / a.duration);
19+const fmtDbfs = (v: number) => `${v.toFixed(1)} dBFS`;
2420
2521 const energyOf = (a: Analysis) => db10(a.energy);
2622 const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
@@ -28,7 +24,6 @@ const fmtDb = (v: number) => `${v.toFixed(1)} dB`;
2824 export function CompareView({ recs, settings, onOpen }: Props) {
2925 const [rows, setRows] = useState<Row[]>([]);
3026 const [ready, setReady] = useState(false);
31- const [metric, setMetric] = useState<Metric>("median");
3227 const [normalize, setNormalize] = useState(false);
3328 const [smoothing, setSmoothing] = useState(1 / 6);
3429
@@ -78,22 +73,11 @@ export function CompareView({ recs, settings, onOpen }: Props) {
7873 <Scatter rows={rows} y={energyOf} yFmt={fmtDb} yLabel="energy (dB, relative)" onOpen={onOpen} unit="dB" minSpan={10} />
7974 </section>
8075 <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>
76+ <h3>Loudness ({bandLabel}) vs tear duration</h3>
9177 <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."}
78+ Mean power over the tear. The same energy packed into less time should be 10 dB louder for every 10× shorter tear, as the dotted line shows.
9579 </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} />
80+ <Scatter rows={rows} y={powerOf} yFmt={fmtDbfs} yLabel="mean power (dBFS)" onOpen={onOpen} unit="dB" minSpan={10} expectSlope={-10} />
9781 </section>
9882 </div>
9983
@@ -143,10 +127,8 @@ function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
143127 const lx = rows.map((r) => Math.log10(r.a.duration));
144128 const e = rows.map((r) => db10(r.a.energy));
145129 const fe = linearFit(lx, e);
146- const fm = linearFit(lx, rows.map((r) => r.a.medianFreq));
147130 const span = Math.max(...rows.map((r) => r.a.duration)) / Math.min(...rows.map((r) => r.a.duration));
148131 const eRange = Math.max(...e) - Math.min(...e);
149- const meds = rows.map((r) => r.a.medianFreq);
150132 return (
151133 <section className="card summary">
152134 <h3>The two questions</h3>
@@ -165,14 +147,8 @@ function Summary({ rows, bandLabel }: { rows: Row[]; bandLabel: string }) {
165147 <div className="q">
166148 <div className="q-title">Same frequency makeup at every speed?</div>
167149 <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.
150+ See the frequency plot below. If the curves for different speeds have the same shape (tick “compare shape only” to line them up), the
151+ frequency makeup is the same.
176152 </div>
177153 </div>
178154 <p className="caption">
@@ -199,7 +175,9 @@ function Scatter({
199175 onOpen,
200176 unit,
201177 minSpan,
178+ expectSlope,
202179 }: {
180+ expectSlope?: number; // dB per 10× duration: draws the expected trend through the points' mean
203181 rows: Row[];
204182 y: (a: Analysis) => number;
205183 yFmt: (v: number) => string;
@@ -228,13 +206,19 @@ function Scatter({
228206
229207 const draw = useCallback(
230208 (ctx: CanvasRenderingContext2D, s: Scales, th: Theme) => {
209+ if (expectSlope !== undefined && pts.length) {
210+ const mx = pts.reduce((t, p) => t + Math.log10(p.x), 0) / pts.length;
211+ const my = pts.reduce((t, p) => t + p.y, 0) / pts.length;
212+ const yAt = (x: number) => my + expectSlope * (Math.log10(x) - mx);
213+ drawLine(ctx, s, [xr[0], xr[1]], [yAt(xr[0]), yAt(xr[1])], th.ink2, 1.5, [2, 4]);
214+ }
231215 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]);
232216 for (const p of pts) {
233217 const st = speedStyle(p.r.meta.label);
234218 drawMarker(ctx, s.x(p.x), s.y(p.y), st.shape, colorFor(st.slot, th.series, th.muted), th.surface, 6);
235219 }
236220 },
237- [pts, fit, xr],
221+ [pts, fit, xr, expectSlope],
238222 );
239223
240224 const near = (p: PointerInfo) => {
@@ -272,7 +256,15 @@ function Scatter({
272256 cursor={(p) => (near(p) ? "pointer" : "crosshair")}
273257 ariaLabel={`${yLabel} against tear duration`}
274258 />
275- <Legend rows={rows} extra={fit ? `dashed: trend, ${fmtSigned(fit.b, unit === "Hz" ? 0 : 2)} ${unit} per 10× duration` : undefined} />
259+ <Legend
260+ rows={rows}
261+ extra={[
262+ fit ? `dashed: trend, ${fmtSigned(fit.b)} ${unit} per 10× duration` : "",
263+ expectSlope !== undefined ? `dotted: expected if energy is the same (${fmtSigned(expectSlope, 0)} ${unit} per 10×)` : "",
264+ ]
265+ .filter(Boolean)
266+ .join(" · ") || undefined}
267+ />
276268 </>
277269 );
278270 }
@@ -394,8 +386,6 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
394386 <th className="num">Speed (in/s)</th>
395387 <th className="num">Energy (dB)</th>
396388 <th className="num">Mean power (dBFS)</th>
397- <th className="num">Median freq</th>
398- <th className="num">Centroid</th>
399389 <th className="num">Above background</th>
400390 <th className="num">Peak (dBFS)</th>
401391 </tr>
@@ -412,8 +402,6 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
412402 <td className="num">{a.speedInPerSec.toFixed(2)}</td>
413403 <td className="num">{db10(a.energy).toFixed(1)}</td>
414404 <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>
417405 <td className="num">{Number.isFinite(a.snrDb) ? `${a.snrDb.toFixed(1)} dB` : "–"}</td>
418406 <td className="num">
419407 {a.peakDbfs.toFixed(1)}
@@ -431,7 +419,7 @@ function Table({ rows, onOpen }: { rows: Row[]; onOpen: (id: string) => void })
431419 function exportCsv(rows: Row[], settings: AnalysisSettings) {
432420 const head = [
433421 "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",
422+ "energy_db", "energy_raw_db", "background_db", "above_background_db", "peak_dbfs", "near_clip_samples",
435423 "energy_band_low_hz", "energy_band_high_hz", "spectrum_band_low_hz", "spectrum_band_high_hz", "sheet_length_in",
436424 ];
437425 const q = (v: unknown) => {
@@ -444,7 +432,7 @@ function exportCsv(rows: Row[], settings: AnalysisSettings) {
444432 [
445433 m.label, new Date(m.createdAt).toISOString(), m.source, m.sampleRate, a.segment.start.toFixed(4), a.segment.end.toFixed(4), m.segmentManual,
446434 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,
435+ a.snrDb.toFixed(2), a.peakDbfs.toFixed(2), a.nearClip,
448436 settings.energyLow, settings.energyHigh, settings.shapeLow, settings.shapeHigh, settings.sheetLengthIn,
449437 ]
450438 .map(q)
src/components/TearView.tsxmodified+0−3View file
@@ -535,14 +535,11 @@ function fmtKHz(hz: number) {
535535 }
536536
537537 function Stats({ a, settings, bandLabel }: { a: Analysis | null; settings: AnalysisSettings; bandLabel: string }) {
538- const shape = `${fmtHz(settings.shapeLow)}–${fmtHz(settings.shapeHigh)}`;
539538 if (!a) return <p className="muted">No tear range.</p>;
540539 const items: [string, string, string?][] = [
541540 ["Tear duration", fmtSec(a.duration)],
542541 ["Speed", `${a.speedInPerSec.toFixed(2)} in/s`, `${settings.sheetLengthIn} in ÷ duration`],
543542 ["Sound energy", Number.isFinite(db10(a.energy)) && a.energy > 0 ? `${db10(a.energy).toFixed(1)} dB` : "–", `${bandLabel}, background removed (relative units)`],
544- ["Median frequency", fmtHz(a.medianFreq), `half the energy above, half below (${shape})`],
545- ["Centroid", fmtHz(a.centroid), `energy-weighted mean frequency (${shape})`],
546543 ["Mean power", a.energy > 0 ? `${db10(a.energy / a.duration).toFixed(1)} dBFS` : "–", `${bandLabel}, energy ÷ duration`],
547544 ["Peak", `${a.peakDbfs.toFixed(1)} dBFS`, a.nearClip ? `${a.nearClip} samples near clipping` : "no clipping"],
548545 [