Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ALGORITHMS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |

---
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/src/onehz/registry/group_registry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const GroupRegistry kAnalyticsGroupRegistry = GroupRegistry(1, <GroupDecl>[
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: [
Expand Down
96 changes: 77 additions & 19 deletions lib/src/onehz/util.dart
Original file line number Diff line number Diff line change
Expand Up @@ -434,33 +434,91 @@ LombScargle? lombScargle(List<double> t, List<double> y, List<double> 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<double>.filled(n, 0), s = List<double>.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 <double>[];
final sd = uniform ? [for (final d in dts) math.sin(dw * d)] : const <double>[];
final out = <LsPoint>[];
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);
Expand Down
6 changes: 4 additions & 2 deletions test/algo_version_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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});
});
}
Loading