diff --git a/ALGORITHMS.md b/ALGORITHMS.md index 7de6b20..3f22f8d 100644 --- a/ALGORITHMS.md +++ b/ALGORITHMS.md @@ -176,7 +176,7 @@ code comments describe parity tests, not universal numerical guarantees. | `hrDipFromDayTotals` | `clinical/nocturnal.dart` | Internal HR-dip band and minimum-sample rule, ESTIMATE with low confidence; sample-order day totals and all-valid-sample night mean | Avram 2019; Dial 2025 support nocturnal RHR only, not HR-dip classification | | `Calories.minuteEnergyPricer / assembleMinuteEnergySeries` | `workout/calories.dart` | Shared dailyEnergy minute billing and ordered assembly | Keytel et al. 2005; Mifflin-St Jeor 1990; Tudor-Locke et al. 2019 | | `slidingMedians` | `util.dart` | Same clipped-window median via maintained sorted values; percentileSorted uses type 7, zero-based rank (n - 1) * p / 100 | Hyndman & Fan 1996 | -| `lombScargle` | `util.dart` | First-sample time origin reduces argument error; mathematically time-shift invariant | Press & Rybicki 1989 | +| `lombScargle` | `util.dart` | First-sample time origin reduces argument error; mathematically time-shift invariant; one pass per frequency via the angle-sum identities, per-point (cos, sin) stepped by rotation on a uniform grid and re-seeded from exact trig every 32 frequencies | Press & Rybicki 1989; Press, Teukolsky, Vetterling & Flannery 2007 | | `Sum / SumOf / SumSq / Moments / Ewma` | `../aggregate/primitives.dart` | Compensated Sum/SumOf and ordinary SumSq; centered moments; affine EWMA composition, algebraically equal to the recurrence: f_y(f_x(c)) = a*a*c + a*lambda*x + lambda*y, a = 1-lambda | Welford 1962 and Chan, Golub & LeVeque 1983 for Moments only; sums are arithmetic, EWMA composition follows algebra | --- @@ -205,6 +205,7 @@ Malik et al. References added for the methods above: +- Press, W. H., Teukolsky, S. A., Vetterling, W. T., Flannery, B. P. (2007). Numerical Recipes: The Art of Scientific Computing, 3rd ed., §13.8 Spectral Analysis of Unevenly Sampled Data. Cambridge University Press. - Welford, B. P. (1962). Note on a method for calculating corrected sums of squares and products. Technometrics 4(3):419-420. - Chan, T. F., Golub, G. H., LeVeque, R. J. (1983). Algorithms for computing the sample variance: analysis and recommendations. The American Statistician 37(3):242-247. - Hyndman, R. J., Fan, Y. (1996). Sample quantiles in statistical packages. The American Statistician 50(4):361-365. diff --git a/CHANGELOG.md b/CHANGELOG.md index 1185ae2..507ab9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -68,6 +68,32 @@ - `Calories.hourlyRollup` — hourly sums of covered minutes with per-hour coverage; an hour with no covered minute is null, not zero. +### Compute Lomb-Scargle in one trig-free pass per frequency + +`lombScargle` made two passes per frequency with four trig calls per point. +It now makes one pass using the angle-sum identities (Numerical Recipes 3rd ed., +§13.8 `period`), and on a uniform frequency grid steps each +point's (cos, sin) by rotation, re-seeding from exact trig every 32 +frequencies; a non-uniform grid uses exact trig at every frequency. Same +spectrum: 13 of the 361 numbers in the output fixtures move, all spectral, by +at most 7.8e-14 relative, and no threshold decision changes. One degenerate +case does change: when every point sits on a node of the sine (evenly sampled +at exactly Nyquist), the sine term is now 0 rather than rounding residue +divided by rounding residue. A basis that is small but real (ω·span ≪ 1) +is summed directly and keeps its power. A grid counts as uniform only when the +recurrence lands on every labelled frequency to 1e-9 rad of phase, and a NaN +or infinite frequency sends the grid to exact trig, where it costs its own bin. +`hrvFreq` on three real 18–23k-beat nights: 872–1,369 ms before, 174–286 ms +after. Sleep staging, respiratory rate and coherence call the same function. +`found.core` moves to counter 3. + +Method: Lomb 1976; Scargle 1982; Press & Rybicki 1989; Press, Teukolsky, +Vetterling & Flannery 2007 (Numerical Recipes 3rd ed., §13.8). The real-night +timings are not reproducible from this repo (the nights are not in it). +`dart run tool/bench_lomb_scargle.dart` is a synthetic stand-in: seeded 18k, +22k and 24k-beat nights, run on main and on this branch to compare timing and +check the band powers agree. + ### Review input and gap validity HRV time, nocturnal and session RMSSD abstain on non-finite NN intervals before diff --git a/lib/src/onehz/registry/group_registry.dart b/lib/src/onehz/registry/group_registry.dart index 52887ea..1a3b098 100644 --- a/lib/src/onehz/registry/group_registry.dart +++ b/lib/src/onehz/registry/group_registry.dart @@ -74,7 +74,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, [ GroupDecl( id: 'found.core', kind: GroupKind.foundation, - counter: 2, + counter: 3, // 3: Lomb-Scargle trig-free recurrence (last-digit drift) members: ['median'], api: ['needBaselineNote'], files: [ diff --git a/lib/src/onehz/util.dart b/lib/src/onehz/util.dart index be00b16..2fa5a3b 100644 --- a/lib/src/onehz/util.dart +++ b/lib/src/onehz/util.dart @@ -434,33 +434,91 @@ LombScargle? lombScargle(List t, List y, List freqsHz) { // One-sided periodogram → density: 2·Δt, with Δt the MEAN sample interval. final psdScale = 2.0 * span / (n - 1); + // Single pass per frequency, two trig-free identities (Press, Teukolsky, + // Vetterling & Flannery, Numerical Recipes 3rd ed. 2007, §13.8 `period`). + // With c = cos ωt', s = sin ωt' (t' = t − t0): + // Σ sin 2ωt' = Σ 2sc, Σ cos 2ωt' = Σ (c² − s²) → τ as before + // Σ y cos ω(t'−τ) = cosωτ·Σyc + sinωτ·Σys (angle subtraction) + // Σ cos² ω(t'−τ) = ½(n + cos2ωτ·Σc2 + sin2ωτ·Σs2), Σ sin² = n − that. + // On a uniform grid (c, s) advance by a per-point rotation, re-seeded from + // exact trig every [reseed] steps so recurrence drift stays at rounding. + final m = freqsHz.length; + final dts = [for (final ti in t) ti - t0]; + final step = m > 1 ? freqsHz[1] - freqsHz[0] : 0.0; + const reseed = 32; + // Uniform means the recurrence lands on every LABELLED frequency: between + // re-seeds it evaluates f[a] + j·step, so each bin's distance from that, + // times the span, bounds its phase error — held to 1e-9 rad, inside the + // repo's 1e-8 relative comparison tolerance. A per-step tolerance alone let + // 31 small errors add up (~1.7e-6 rad over a 30,000 s night). Negated `<=` + // and the isFinite test send NaN or ±∞ anywhere in the grid to exact trig, + // where it costs its own bin and nothing else. + var uniform = m > 1 && step.isFinite; + for (var k = 1; k < m && uniform; k++) { + final a = k - k % reseed; + final drift = (freqsHz[k] - (freqsHz[a] + (k - a) * step)).abs(); + if (!freqsHz[k].isFinite || !(2 * math.pi * drift * span <= 1e-9)) { + uniform = false; + } + } + // A basis denominator this small is computed directly instead of from the + // closed form, whose rounding (~n·ε) would be a visible share of it. + final directBelow = 1e-7 * n; + // Directly summed, a basis whose RMS is under 1e-9 is every point sitting + // on a node (even sampling at Nyquist): rounding, not a component. + final nodeBelow = 1e-18 * n; + final c = List.filled(n, 0), s = List.filled(n, 0); + // The per-point rotation only exists on a uniform grid. + final dw = 2 * math.pi * step; + final cd = uniform ? [for (final d in dts) math.cos(dw * d)] : const []; + final sd = uniform ? [for (final d in dts) math.sin(dw * d)] : const []; final out = []; - for (final fHz in freqsHz) { + for (var k = 0; k < m; k++) { + final fHz = freqsHz[k]; final w = 2 * math.pi * fHz; // angular frequency (rad / time-unit) + if (!uniform || k % reseed == 0) { + for (var i = 0; i < n; i++) { c[i] = math.cos(w * dts[i]); s[i] = math.sin(w * dts[i]); } + } else { + for (var i = 0; i < n; i++) { + final ci = c[i], si = s[i]; + c[i] = ci * cd[i] - si * sd[i]; + s[i] = si * cd[i] + ci * sd[i]; + } + } if (w == 0) { out.add(const LsPoint(0, 0)); continue; } - // τ: phase reference for time-shift invariance. - var sin2 = 0.0, cos2 = 0.0; - for (final ti in t) { - sin2 += math.sin(2 * w * (ti - t0)); - cos2 += math.cos(2 * w * (ti - t0)); - } - final tau = math.atan2(sin2, cos2) / (2 * w); - - var cNum = 0.0, cDen = 0.0, sNum = 0.0, sDen = 0.0; + var s2 = 0.0, c2 = 0.0, yc1 = 0.0, ys1 = 0.0; for (var i = 0; i < n; i++) { - final arg = w * ((t[i] - t0) - tau); - final c = math.cos(arg); - final s = math.sin(arg); - cNum += yc[i] * c; - cDen += c * c; - sNum += yc[i] * s; - sDen += s * s; + final ci = c[i], si = s[i]; + s2 += 2 * si * ci; + c2 += ci * ci - si * si; + yc1 += yc[i] * ci; + ys1 += yc[i] * si; + } + final twoWTau = math.atan2(s2, c2); + final cT = math.cos(twoWTau / 2), sT = math.sin(twoWTau / 2); + final c2T = math.cos(twoWTau), s2T = math.sin(twoWTau); + var cDen = 0.5 * (n + c2T * c2 + s2T * s2); + var sDen = n - cDen; + var cNum = cT * yc1 + sT * ys1; + var sNum = cT * ys1 - sT * yc1; + if (cDen <= directBelow || sDen <= directBelow) { + // Rare (a near-degenerate basis): one more pass, the two-pass form's + // sums at the same τ. A small but real direction (ω·span ≪ 1) keeps its + // power; a node-only one reads as empty below. + cDen = sDen = cNum = sNum = 0; + for (var i = 0; i < n; i++) { + final ca = c[i] * cT + s[i] * sT, sa = s[i] * cT - c[i] * sT; + cDen += ca * ca; + sDen += sa * sa; + cNum += yc[i] * ca; + sNum += yc[i] * sa; + } } - final term1 = cDen == 0 ? 0.0 : (cNum * cNum) / cDen; - final term2 = sDen == 0 ? 0.0 : (sNum * sNum) / sDen; + final term1 = cDen <= nodeBelow ? 0.0 : (cNum * cNum) / cDen; + final term2 = sDen <= nodeBelow ? 0.0 : (sNum * sNum) / sDen; out.add(LsPoint(fHz, 0.5 * (term1 + term2) * psdScale)); } return LombScargle(out); diff --git a/test/algo_version_test.dart b/test/algo_version_test.dart index 1e7d53b..4052ed1 100644 --- a/test/algo_version_test.dart +++ b/test/algo_version_test.dart @@ -4,7 +4,7 @@ import 'package:openstrap_analytics/onehz.dart'; import 'package:test/test.dart'; void main() { - test('PR output changes move their owning groups to counter 2', () { + test('PR output changes move their owning groups past counter 1', () { const changed = { 'found.core', // Lomb-Scargle first-sample origin. 'found.rr_correction', // Artifact-run cap, already bumped. @@ -14,8 +14,10 @@ void main() { 'night.rhythm', // Cosinor/circadian and gap-aware irregular screening. 'activity.load', // TRIMP, CTL/ATL and time-in-zone aggregation. }; + // Moved again since: found.core to 3 (Lomb-Scargle recurrence). + const since = {'found.core': 3}; expect({for (final g in kAnalyticsGroupRegistry.groups) if (g.counter != 1) g.id: g.counter}, - {for (final id in changed) id: 2}); + {for (final id in changed) id: since[id] ?? 2}); }); } diff --git a/test/fixtures/output_batch_parity.json b/test/fixtures/output_batch_parity.json index 9ddfdaf..8c4ee5c 100644 --- a/test/fixtures/output_batch_parity.json +++ b/test/fixtures/output_batch_parity.json @@ -1 +1 @@ -{"source":"580e16733ea6cd0dec81066417d2e89972bdbb54","provenance":"Public batch outputs recorded on the batch-only output commit, before the framework refactor. Inputs are reproductionCases in tool/reproduce_outputs.dart.","cases":[{"rr":[201,0,1],"spectral":2191.9035532963126,"cosinor":[60.20705778058244,1.994548567920997,0.99021822497395,3.584442855968536e-94],"near_singular":false,"hrv":[3.615265234174367,21.52663924532641,1.0673833338741983,21.55214616158443,0.984955296232754],"nonfinite":false,"trimp":10.252064196950478,"ctl":[93.59303565371741,96.28901109956863,-2.695975445851218],"zones":[0.0,50.00499999999995,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,17,0],"spectral":240.47476890807894,"cosinor":[60.20546901353539,1.9944760220371391,0.9906874461342637,3.6450131402730934e-95],"near_singular":false,"hrv":[14.544681533327767,21.511404623818784,0.2902542164251966,21.539302061762694,0.7620460195717869],"nonfinite":false,"trimp":13.023941743036463,"ctl":[94.97450463635269,101.20837984038745,-6.23387520403476],"zones":[0.0,61.00609999999995,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,31,0],"spectral":4.814151167014313,"cosinor":[60.20670784840657,1.9932291959984847,0.9907102525961057,3.252232588931257e-95],"near_singular":false,"hrv":[39.550764408744726,21.5122083009717,0.40991536302833925,21.55029614999938,-0.7370544026973745],"nonfinite":false,"trimp":15.28358496194033,"ctl":[94.92528070209704,96.00888145442389,-1.083600752326845],"zones":[0.0,72.00719999999993,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,32,0],"spectral":358.69230942776977,"cosinor":[60.206138700452115,1.9956478767563555,0.9905970400705738,5.7121975661113537e-95],"near_singular":false,"hrv":[42.09631660353519,21.499141419377167,0.29941934343651677,21.512944620556805,-0.9682323671330902],"nonfinite":false,"trimp":18.40304984916745,"ctl":[96.58887865497881,103.10914807456258,-6.520269419583769],"zones":[0.0,83.00829999999988,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,33,0],"spectral":19.577975582737867,"cosinor":[60.206354166666685,1.99256198692952,0.9903700870164812,1.7315692772094542e-94],"near_singular":false,"hrv":[3.615265234174367,21.52663924532641,1.0673833338741983,21.55214616158443,0.984955296232754],"nonfinite":false,"trimp":20.354197211570078,"ctl":[95.91769269304092,96.02635036170024,-0.10865766865931903],"zones":[0.0,94.00939999999984,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[200,33,0],"spectral":11606.502913565982,"cosinor":[60.2065027398695,1.994982877334022,0.9902341170988117,3.323420791543799e-94],"near_singular":false,"hrv":[14.544681533327767,21.511404623818784,0.2902542164251966,21.539302061762694,0.7620460195717869],"nonfinite":false,"trimp":23.84820212239254,"ctl":[97.91559020097185,105.11939669789578,-7.2038064969239315],"zones":[0.0,105.0104999999998,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[201,0,1],"spectral":179.12281661844955,"cosinor":[60.20613433801807,1.993285411438357,0.9902158539353855,3.625067770914454e-94],"near_singular":false,"hrv":[39.54331943857053,21.508583812826043,0.27113546544007344,21.551316007749993,-0.7371891534838562],"nonfinite":false,"trimp":25.46704673479356,"ctl":[96.68685633705937,96.44160847368228,0.24524786337708804],"zones":[0.0,116.01159999999977,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,17,0],"spectral":527.7181728812988,"cosinor":[60.20664182391473,1.993388211364034,0.990292034354844,2.520360883833827e-94],"near_singular":false,"hrv":[42.11090878105368,21.502568386886722,0.29644031390575065,21.528250446057537,-0.9685070047216077],"nonfinite":false,"trimp":28.750997708819092,"ctl":[98.08372430811947,101.79002204026516,-3.7062977321456856],"zones":[0.0,127.01269999999977,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,31,0],"spectral":21.91751421630071,"cosinor":[60.206102619835434,1.9948632846663268,0.9904511511664523,1.168751936831454e-94],"near_singular":false,"hrv":[3.6114616155271952,21.50300002384371,0.916280807418444,21.477133240134368,0.9853180909453777],"nonfinite":false,"trimp":30.6254910760735,"ctl":[97.31583171818741,97.22062215666931,0.09520956151810367],"zones":[0.0,138.0137999999999,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,32,0],"spectral":94.441233233861,"cosinor":[60.206607219531165,1.9918709847273792,0.9905159686967243,8.514781581412862e-95],"near_singular":false,"hrv":[14.550213162597531,21.50963654798735,0.2980266237242866,21.540300395940907,0.7627458277372915],"nonfinite":false,"trimp":33.68218231936987,"ctl":[98.15600470749584,99.32476832904142,-1.1687636215455797],"zones":[0.0,149.01489999999987,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,33,0],"spectral":12.677409836990822,"cosinor":[60.20622592520504,1.9957534839219526,0.9905696980951562,6.537929637620507e-95],"near_singular":false,"hrv":[39.54331943857053,21.508583812826043,0.27113546544007344,21.551316007749993,-0.7371891534838562],"nonfinite":false,"trimp":35.83311260770479,"ctl":[97.86366868742407,98.31752817052501,-0.45385948310094193],"zones":[0.0,160.01599999999982,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[200,33,0],"spectral":35.03266947297398,"cosinor":[60.20646575449843,1.9913371893547758,0.9904828062401032,1.0015309381130758e-94],"near_singular":false,"hrv":[42.11090878105368,21.502568386886722,0.29644031390575065,21.528250446057537,-0.9685070047216077],"nonfinite":false,"trimp":38.64417150766156,"ctl":[98.18187926518608,97.60954398514504,0.5723352800410453],"zones":[0.0,171.01709999999983,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]}]} +{"source":"580e16733ea6cd0dec81066417d2e89972bdbb54","provenance":"Public batch outputs recorded on the batch-only output commit, before the framework refactor. Inputs are reproductionCases in tool/reproduce_outputs.dart.","cases":[{"rr":[201,0,1],"spectral":2191.903553296312,"cosinor":[60.20705778058244,1.994548567920997,0.99021822497395,3.584442855968536e-94],"near_singular":false,"hrv":[3.615265234174367,21.52663924532641,1.0673833338741983,21.55214616158443,0.984955296232754],"nonfinite":false,"trimp":10.252064196950478,"ctl":[93.59303565371741,96.28901109956863,-2.695975445851218],"zones":[0.0,50.00499999999995,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,17,0],"spectral":240.47476890807957,"cosinor":[60.20546901353539,1.9944760220371391,0.9906874461342637,3.6450131402730934e-95],"near_singular":false,"hrv":[14.544681533327767,21.511404623818784,0.2902542164251966,21.539302061762694,0.7620460195717869],"nonfinite":false,"trimp":13.023941743036463,"ctl":[94.97450463635269,101.20837984038745,-6.23387520403476],"zones":[0.0,61.00609999999995,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,31,0],"spectral":4.81415116701446,"cosinor":[60.20670784840657,1.9932291959984847,0.9907102525961057,3.252232588931257e-95],"near_singular":false,"hrv":[39.550764408744726,21.5122083009717,0.40991536302833925,21.55029614999938,-0.7370544026973745],"nonfinite":false,"trimp":15.28358496194033,"ctl":[94.92528070209704,96.00888145442389,-1.083600752326845],"zones":[0.0,72.00719999999993,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,32,0],"spectral":358.69230942776954,"cosinor":[60.206138700452115,1.9956478767563555,0.9905970400705738,5.7121975661113537e-95],"near_singular":false,"hrv":[42.09631660353519,21.499141419377167,0.29941934343651677,21.512944620556805,-0.9682323671330902],"nonfinite":false,"trimp":18.40304984916745,"ctl":[96.58887865497881,103.10914807456258,-6.520269419583769],"zones":[0.0,83.00829999999988,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,33,0],"spectral":19.577975582738357,"cosinor":[60.206354166666685,1.99256198692952,0.9903700870164812,1.7315692772094542e-94],"near_singular":false,"hrv":[3.615265234174367,21.52663924532641,1.0673833338741983,21.55214616158443,0.984955296232754],"nonfinite":false,"trimp":20.354197211570078,"ctl":[95.91769269304092,96.02635036170024,-0.10865766865931903],"zones":[0.0,94.00939999999984,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[200,33,0],"spectral":11606.502913566024,"cosinor":[60.2065027398695,1.994982877334022,0.9902341170988117,3.323420791543799e-94],"near_singular":false,"hrv":[14.544681533327767,21.511404623818784,0.2902542164251966,21.539302061762694,0.7620460195717869],"nonfinite":false,"trimp":23.84820212239254,"ctl":[97.91559020097185,105.11939669789578,-7.2038064969239315],"zones":[0.0,105.0104999999998,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[201,0,1],"spectral":179.12281661844406,"cosinor":[60.20613433801807,1.993285411438357,0.9902158539353855,3.625067770914454e-94],"near_singular":false,"hrv":[39.54331943857053,21.508583812826043,0.27113546544007344,21.551316007749993,-0.7371891534838562],"nonfinite":false,"trimp":25.46704673479356,"ctl":[96.68685633705937,96.44160847368228,0.24524786337708804],"zones":[0.0,116.01159999999977,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,17,0],"spectral":527.7181728812985,"cosinor":[60.20664182391473,1.993388211364034,0.990292034354844,2.520360883833827e-94],"near_singular":false,"hrv":[42.11090878105368,21.502568386886722,0.29644031390575065,21.528250446057537,-0.9685070047216077],"nonfinite":false,"trimp":28.750997708819092,"ctl":[98.08372430811947,101.79002204026516,-3.7062977321456856],"zones":[0.0,127.01269999999977,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,31,0],"spectral":21.917514216301043,"cosinor":[60.206102619835434,1.9948632846663268,0.9904511511664523,1.168751936831454e-94],"near_singular":false,"hrv":[3.6114616155271952,21.50300002384371,0.916280807418444,21.477133240134368,0.9853180909453777],"nonfinite":false,"trimp":30.6254910760735,"ctl":[97.31583171818741,97.22062215666931,0.09520956151810367],"zones":[0.0,138.0137999999999,0.0,0.0,0.0],"circadian":[1.0,0.02086956521739154,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,32,0],"spectral":94.44123323386093,"cosinor":[60.206607219531165,1.9918709847273792,0.9905159686967243,8.514781581412862e-95],"near_singular":false,"hrv":[14.550213162597531,21.50963654798735,0.2980266237242866,21.540300395940907,0.7627458277372915],"nonfinite":false,"trimp":33.68218231936987,"ctl":[98.15600470749584,99.32476832904142,-1.1687636215455797],"zones":[0.0,149.01489999999987,0.0,0.0,0.0],"circadian":[1.0,0.2553191489361734,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[199,33,0],"spectral":12.677409836989828,"cosinor":[60.20622592520504,1.9957534839219526,0.9905696980951562,6.537929637620507e-95],"near_singular":false,"hrv":[39.54331943857053,21.508583812826043,0.27113546544007344,21.551316007749993,-0.7371891534838562],"nonfinite":false,"trimp":35.83311260770479,"ctl":[97.86366868742407,98.31752817052501,-0.45385948310094193],"zones":[0.0,160.01599999999982,0.0,0.0,0.0],"circadian":[1.0,0.3312676056338072,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]},{"rr":[200,33,0],"spectral":35.03266947297338,"cosinor":[60.20646575449843,1.9913371893547758,0.9904828062401032,1.0015309381130758e-94],"near_singular":false,"hrv":[42.11090878105368,21.502568386886722,0.29644031390575065,21.528250446057537,-0.9685070047216077],"nonfinite":false,"trimp":38.64417150766156,"ctl":[98.18187926518608,97.60954398514504,0.5723352800410453],"zones":[0.0,171.01709999999983,0.0,0.0,0.0],"circadian":[1.0,0.3688421052631628,3.505000000000011,1.3600000000000079,14,0],"irregular_gap":[22.360679774997894,83.33333333333333]}]} diff --git a/test/fixtures/output_changes.json b/test/fixtures/output_changes.json index f3c232f..eec483d 100644 --- a/test/fixtures/output_changes.json +++ b/test/fixtures/output_changes.json @@ -89,7 +89,7 @@ 33, 0 ], - "spectral": 32627.260527635714, + "spectral": 32627.260527635663, "cosinor": [ 60.205914409998044, 1.9937577719142632, diff --git a/test/onehz/lomb_scargle_recurrence_test.dart b/test/onehz/lomb_scargle_recurrence_test.dart new file mode 100644 index 0000000..2ce22ad --- /dev/null +++ b/test/onehz/lomb_scargle_recurrence_test.dart @@ -0,0 +1,195 @@ +// lombScargle computes each frequency in one trig-free pass, stepping the +// per-point (cos, sin) by rotation on a uniform grid. This pins it to the +// textbook two-pass form (explicit τ, then explicit cos/sin of ω(t − τ)) on +// uniform and non-uniform grids, epoch-scale times, long grids that cross many +// re-seeds, and points that sit on a node of the frequency. +import 'dart:math' as math; + +import 'package:openstrap_analytics/onehz.dart'; +import 'package:test/test.dart'; + +/// The previous implementation, kept as the reference. +List _reference(List t, List y, List freqsHz) { + final n = t.length; + final my = y.reduce((a, b) => a + b) / n; + final yc = [for (final v in y) v - my]; + var tMin = t[0], tMax = t[0]; + for (final ti in t) { + tMin = math.min(tMin, ti); + tMax = math.max(tMax, ti); + } + final psdScale = 2.0 * (tMax - tMin) / (n - 1); + final t0 = t[0]; + final out = []; + for (final fHz in freqsHz) { + final w = 2 * math.pi * fHz; + if (w == 0) { + out.add(0); + continue; + } + var sin2 = 0.0, cos2 = 0.0; + for (final ti in t) { + sin2 += math.sin(2 * w * (ti - t0)); + cos2 += math.cos(2 * w * (ti - t0)); + } + final tau = math.atan2(sin2, cos2) / (2 * w); + var cNum = 0.0, cDen = 0.0, sNum = 0.0, sDen = 0.0; + for (var i = 0; i < n; i++) { + final arg = w * ((t[i] - t0) - tau); + final c = math.cos(arg), s = math.sin(arg); + cNum += yc[i] * c; + cDen += c * c; + sNum += yc[i] * s; + sDen += s * s; + } + final term1 = cDen == 0 ? 0.0 : (cNum * cNum) / cDen; + final term2 = sDen == 0 ? 0.0 : (sNum * sNum) / sDen; + out.add(0.5 * (term1 + term2) * psdScale); + } + return out; +} + +/// Beat-like times: an RR series around [rrMs] with breathing and jitter, +/// starting at [t0Sec] (epoch scale when large), in seconds. +({List t, List y}) _beats(int n, int seed, + {double rrMs = 1000, double t0Sec = 0}) { + final r = math.Random(seed); + final t = [], y = []; + var clock = t0Sec; + for (var i = 0; i < n; i++) { + final rr = rrMs + 60 * math.sin(2 * math.pi * i / 4.3) + 25 * (r.nextDouble() - 0.5); + clock += rr / 1000; + t.add(clock); + y.add(rr); + } + return (t: t, y: y); +} + +void _expectClose(List t, List y, List f) { + final got = lombScargle(t, y, f)!.spectrum; + final want = _reference(t, y, f); + expect(got.length, want.length); + final peak = want.reduce(math.max); + for (var k = 0; k < want.length; k++) { + expect(got[k].freqHz, f[k] == 0 ? 0 : f[k]); + // Relative to the bin, with a floor relative to the spectrum's peak so + // bins at rounding level do not demand relative agreement. + expect(got[k].psd, closeTo(want[k], 1e-9 * want[k].abs() + 1e-12 * peak), + reason: 'bin $k at ${f[k]} Hz'); + } +} + +void main() { + final uniform = [for (var k = 1; k <= 1600; k++) k * 0.00025]; // 0.00025..0.4 Hz + final nonUniform = [for (var k = 1; k <= 400; k++) 0.0003 * math.pow(k, 1.3)]; + + test('uniform grid matches the two-pass reference', () { + final b = _beats(3000, 1); + _expectClose(b.t, b.y, uniform); + }); + + test('uniform grid on epoch-scale times', () { + final b = _beats(3000, 2, t0Sec: 1796100000); + _expectClose(b.t, b.y, uniform); + }); + + test('non-uniform grid takes the exact-trig path and matches', () { + final b = _beats(1500, 3, rrMs: 1400); + _expectClose(b.t, b.y, nonUniform); + }); + + test('a grid that starts at 0 Hz keeps the 0 bin and the recurrence', () { + final b = _beats(800, 4); + _expectClose(b.t, b.y, [for (var k = 0; k < 200; k++) k * 0.002]); + }); + + test('a two-point grid and a one-point grid', () { + final b = _beats(300, 5); + _expectClose(b.t, b.y, [0.1, 0.25]); + _expectClose(b.t, b.y, [0.2]); + }); + + test('evenly sampled at Nyquist: the empty sine term is 0, not residue', () { + // t = 0..n-1 s and an alternating ±1 series at f = 0.5 Hz: every + // sin ω(t − τ) is 0 exactly, so only the cosine term exists and the PSD + // is ½·(Σy²)·2Δt = 256. The two-pass form read the sine term as + // residue/residue (~1e-16 per point) and published 292.3; the closed form + // treats a denominator at rounding level as empty. + final t = [for (var i = 0; i < 256; i++) i.toDouble()]; + final y = [for (var i = 0; i < 256; i++) i.isEven ? 1.0 : -1.0]; + final got = lombScargle(t, y, [0.5])!.spectrum.single.psd; + expect(got, closeTo(256, 1e-9)); + expect(_reference(t, y, [0.5]).single, isNot(closeTo(256, 1))); + }); + + test('below Nyquist on the same even grid matches the reference', () { + final t = [for (var i = 0; i < 256; i++) i.toDouble()]; + final y = [for (var i = 0; i < 256; i++) math.sin(i * 0.9) + 0.3 * math.cos(i * 2.1)]; + _expectClose(t, y, [for (var k = 1; k < 120; k++) k / 256]); + }); + + test('incremental agrees with batch at Nyquist: no residue/residue power', () { + final t = [for (var i = 0; i < 256; i++) i.toDouble()]; + final y = [for (var i = 0; i < 256; i++) i.isEven ? 1.0 : -1.0]; + final inc = IncrementalLombScargle([0.5]).sync(t, y)!.spectrum.single.psd; + final batch = lombScargle(t, y, [0.5])!.spectrum.single.psd; + expect(inc, closeTo(batch, 1e-9 * batch)); + }); + + test('a NaN in the grid costs its own bin, not every bin after it', () { + final b = _beats(1500, 5); + final grid = [for (var k = 1; k <= 200; k++) k * 0.002]; + grid[1] = double.nan; + final got = lombScargle(b.t, b.y, grid)!.spectrum; + final want = _reference(b.t, b.y, grid); + expect(got[1].psd.isNaN, isTrue); + for (var k = 0; k < grid.length; k++) { + if (k == 1) continue; + expect(got[k].psd, closeTo(want[k], 1e-9 * want[k].abs() + 1e-12), + reason: 'bin $k'); + } + }); + + test('an infinite frequency fails the uniform check, not inherits a bin', () { + final b = _beats(1500, 6); + // Last, so its own tolerance (1e-12·|f|) is infinite too. + final grid = [for (var k = 1; k <= 40; k++) k * 0.005]..[39] = double.infinity; + final got = lombScargle(b.t, b.y, grid)!.spectrum; + final want = _reference(b.t, b.y, grid); + expect(got[39].psd.isFinite, isFalse); + for (var k = 0; k < grid.length; k++) { + if (k == 39) continue; + expect(got[k].psd, closeTo(want[k], 1e-9 * want[k].abs() + 1e-12), + reason: 'bin $k'); + } + }); + + test('a grid uniform only to 3e-13 Hz still matches at every labelled bin', () { + // Spacing error inside the old per-step tolerance; the recurrence would + // evaluate up to 31 steps of it away from the label (~9e-12 Hz), which + // over 30,000 s is ~1.7e-6 rad of phase. + final t = [for (var i = 0; i <= 30000; i++) i.toDouble()]; + final y = [for (var i = 0; i <= 30000; i++) math.sin(i * 2.2) + 0.5 * math.cos(i * 0.31 + 1)]; + // Every step after the first is 3e-13 Hz long: each passes the per-step + // tolerance, but the drift from the first step adds up between re-seeds. + final grid = [0.33]; + for (var k = 1; k < 64; k++) { + grid.add(grid.last + 0.001 + (k == 1 ? 0 : 3e-13)); + } + final got = lombScargle(t, y, grid)!.spectrum; + final want = _reference(t, y, grid); + for (var k = 0; k < grid.length; k++) { + expect(got[k].psd, closeTo(want[k], 1e-8 * want[k].abs() + 1e-12), + reason: 'bin $k'); + } + }); + + test('a small but real sine direction keeps its power (ω·span ≪ 1)', () { + final t = [0.0, 1.0, 2.0, 3.0]; + final y = [-1.5, -0.5, 0.5, 1.5]; + final got = lombScargle(t, y, [1e-8])!.spectrum.single.psd; + final want = _reference(t, y, [1e-8]).single; + expect(want, greaterThan(1)); + expect(got, closeTo(want, 1e-6 * want)); + }); +} diff --git a/tool/bench_lomb_scargle.dart b/tool/bench_lomb_scargle.dart new file mode 100644 index 0000000..1c0ff2a --- /dev/null +++ b/tool/bench_lomb_scargle.dart @@ -0,0 +1,52 @@ +// Measurement tool: hrvFreq (and so lombScargle) on whole synthetic nights. +// Not a test; no lib/ changes. Seeded, no I/O except print. Run it on main and +// on the branch: the band powers must agree, the times are the point. +// +// dart compile exe tool/bench_lomb_scargle.dart -o /tmp/bench_ls +// /tmp/bench_ls (or: dart run tool/bench_lomb_scargle.dart) +// +// Nights of 18k, 22k and 24k beats (a sleep window at 43–47 bpm), breathing at +// ~14/min, slow wander and jitter, 3 % of beats dropped. Each night: one warm-up, +// then the mean of 3 timed runs. +import 'dart:math' as math; + +import 'package:openstrap_analytics/onehz.dart'; + +double _gauss(math.Random r) => + math.sqrt(-2 * math.log(r.nextDouble() + 1e-12)) * + math.cos(2 * math.pi * r.nextDouble()); + +({List nn, List ts}) _night(int beats, int seed) { + final r = math.Random(seed); + final nn = [], ts = []; + var t = 1796100000000.0, phase = 0.0, lf = 0.0; + const meanRr = 1330.0; + for (var i = 0; nn.length < beats; i++) { + phase += 2 * math.pi * (14 / 60) * (meanRr / 1000); + lf = lf * 0.97 + _gauss(r) * 8; + final v = meanRr + 100 * math.sin(phase) + lf + _gauss(r) * 5; + t += v; + if (r.nextDouble() >= 0.03) { + nn.add(v); + ts.add(t); + } + } + return (nn: nn, ts: ts); +} + +void main() { + for (final (beats, seed) in [(18000, 1), (22000, 2), (24000, 3)]) { + final n = _night(beats, seed); + Metric run() => hrvFreq(n.nn, n.ts, artifactFraction: 0.05); + final warm = run(); + final sw = Stopwatch()..start(); + for (var i = 0; i < 3; i++) { + run(); + } + final ms = sw.elapsedMicroseconds / 3 / 1000; + final v = warm.value; + String f(double? x) => x == null ? 'null' : x.toStringAsPrecision(10); + print('beats=$beats hrvFreq=${ms.toStringAsFixed(0)} ms ' + 'lf=${f(v?.lf)} hf=${f(v?.hf)} vlf=${f(v?.vlf)} lfhf=${f(v?.lfhf)}'); + } +}