File size: 12,905 Bytes
e215d3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// Dochia v1 — JavaScript (Node) reference implementation.
// Mirrors python/dochia.py. No dependencies.

const SQRT2 = Math.sqrt(2);
const SQRT2PI = Math.sqrt(2 * Math.PI);

function erf(x) {
  // Abramowitz & Stegun 7.1.26
  const sign = x < 0 ? -1 : 1;
  const ax = Math.abs(x);
  const a1 = 0.254829592, a2 = -0.284496736, a3 = 1.421413741;
  const a4 = -1.453152027, a5 = 1.061405429, p = 0.3275911;
  const t = 1 / (1 + p * ax);
  const y = 1 - (((((a5 * t + a4) * t + a3) * t + a2) * t + a1) * t) * Math.exp(-ax * ax);
  return sign * y;
}

export const normCdf = (z) => 0.5 * (1 + erf(z / SQRT2));
export const normPdf = (z) => Math.exp(-0.5 * z * z) / SQRT2PI;

export function normPpf(p) {
  if (p <= 0) return -Infinity;
  if (p >= 1) return Infinity;
  let lo = -12, hi = 12;
  for (let i = 0; i < 200; i++) {
    const mid = 0.5 * (lo + hi);
    if (normCdf(mid) < p) lo = mid; else hi = mid;
  }
  return 0.5 * (lo + hi);
}

export function lognormalParams(mean, sd) {
  mean = Math.max(mean, 1e-6); sd = Math.max(sd, 1e-6);
  const s2 = Math.log1p((sd * sd) / (mean * mean));
  const s = Math.sqrt(s2);
  return { m: Math.log(mean) - 0.5 * s2, s };
}

export function mixtureFromMoments(mean, sd, pi, tailShift, tailSdMult, momentMatch = false) {
  pi = Math.min(Math.max(pi, 0), 0.45); mean = Math.max(mean, 1); sd = Math.max(sd, 0.2);
  if (pi <= 1e-9) {
    const main = lognormalParams(mean, sd);
    return { mean, sd, tailProb: 0, w: [1], m: [main.m], s: [main.s] };
  }
  if (!momentMatch) {
    const main = lognormalParams(mean, sd);
    const tail = lognormalParams(Math.max(mean + tailShift, mean * 1.02), Math.max(sd * tailSdMult, 0.3));
    return { mean, sd, tailProb: pi, w: [1 - pi, pi], m: [main.m, tail.m], s: [main.s, tail.s] };
  }
  const tailMean = Math.max(mean + tailShift, mean * 1.02);
  const tailSd = Math.max(sd * tailSdMult, 0.3);
  const mainMean = (mean - pi * tailMean) / (1 - pi);
  const mainVar = ((sd * sd + mean * mean - pi * (tailSd * tailSd + tailMean * tailMean)) / (1 - pi)) - mainMean * mainMean;
  if (mainMean <= 0.5 || mainVar <= 0.04) {
    const main = lognormalParams(mean, sd);
    return { mean, sd, tailProb: 0, w: [1], m: [main.m], s: [main.s] };
  }
  const main = lognormalParams(mainMean, Math.sqrt(mainVar));
  const tail = lognormalParams(tailMean, tailSd);
  return { mean, sd, tailProb: pi, w: [1 - pi, pi], m: [main.m, tail.m], s: [main.s, tail.s] };
}

export function mixCdf(mix, x) {
  if (x <= 0) return 0;
  let total = 0;
  for (let i = 0; i < mix.w.length; i++) total += mix.w[i] * normCdf((Math.log(x) - mix.m[i]) / mix.s[i]);
  return Math.min(Math.max(total, 0), 1);
}

export function mixPdf(mix, x) {
  if (x <= 0) return 0;
  let total = 0;
  for (let i = 0; i < mix.w.length; i++) {
    const z = (Math.log(x) - mix.m[i]) / mix.s[i];
    total += mix.w[i] * normPdf(z) / (x * mix.s[i]);
  }
  return total;
}

export function mixQuantile(mix, p) {
  if (p <= 0) return 0;
  if (p >= 1) return 1000;
  let lo = 1, hi = 400;
  if (mixCdf(mix, lo) >= p) return lo;
  if (mixCdf(mix, hi) <= p) return hi;
  for (let i = 0; i < 40; i++) {
    const mid = 0.5 * (lo + hi);
    if (mixCdf(mix, mid) < p) lo = mid; else hi = mid;
  }
  return 0.5 * (lo + hi);
}

export function calibrated(mix, params) {
  return {
    mix,
    anchorLow: params.tailAnchorLow,
    anchorHigh: params.tailAnchorHigh,
    scaleLow: Math.max(params.tailScaleLow, 1e-6),
    scaleHigh: Math.max(params.tailScaleHigh, 1e-6),
    qLow: mixQuantile(mix, params.tailAnchorLow),
    qHigh: mixQuantile(mix, params.tailAnchorHigh),
  };
}

export function calQuantile(cal, p) {
  if (p <= 0) return 0;
  if (p >= 1) return 1000;
  if (p <= cal.anchorLow) return cal.qLow + (mixQuantile(cal.mix, p) - cal.qLow) * cal.scaleLow;
  if (p >= cal.anchorHigh) return cal.qHigh + (mixQuantile(cal.mix, p) - cal.qHigh) * cal.scaleHigh;
  return mixQuantile(cal.mix, p);
}

export function calCdf(cal, x) {
  if (x <= cal.qLow) {
    const y = cal.qLow + (x - cal.qLow) / cal.scaleLow;
    return Math.min(Math.max(mixCdf(cal.mix, y), 0), 1);
  }
  if (x >= cal.qHigh) {
    const y = cal.qHigh + (x - cal.qHigh) / cal.scaleHigh;
    return Math.min(Math.max(mixCdf(cal.mix, y), 0), 1);
  }
  return mixCdf(cal.mix, x);
}

export function calPdf(cal, x) {
  if (x <= 0) return 0;
  if (x < cal.qLow) return mixPdf(cal.mix, cal.qLow + (x - cal.qLow) / cal.scaleLow) / cal.scaleLow;
  if (x > cal.qHigh) return mixPdf(cal.mix, cal.qHigh + (x - cal.qHigh) / cal.scaleHigh) / cal.scaleHigh;
  return mixPdf(cal.mix, x);
}

function median(values) {
  const s = [...values].sort((a, b) => a - b);
  const n = s.length;
  if (n === 0) return 0;
  return n % 2 === 1 ? s[(n - 1) / 2] : 0.5 * (s[n / 2 - 1] + s[n / 2]);
}

export function personalState(lengthsIn, params) {
  const lengths = lengthsIn.filter((y) => y >= params.minLength && y <= params.maxLength).map(Number);
  const n = lengths.length;
  if (n === 0) {
    const withinVar = params.withinSdPrior ** 2;
    const between = params.popBetweenSd ** 2;
    const posterior = (withinVar * between) / Math.max(1e-9, withinVar);
    return {
      mean: params.popMean, withinVar, cycleSd: Math.sqrt(withinVar + posterior), n: 0,
      tailProb: params.tailProbBase, trend: 0, recentSd: 0, recentRange: 0,
      gap: false, abstain: false, confidence: 'new',
    };
  }
  const mean = lengths.reduce((a, b) => a + b, 0) / n;
  let sampleVar = 0;
  if (n > 1) sampleVar = lengths.reduce((a, y) => a + (y - mean) ** 2, 0) / (n - 1);
  const med = median(lengths);
  const mad = median(lengths.map((y) => Math.abs(y - med)));
  const robustVar = (1.4826 * mad) ** 2;
  sampleVar = params.varianceBlend * sampleVar + (1 - params.varianceBlend) * robustVar;

  const priorVar = params.withinSdPrior ** 2;
  let priorWeight = params.priorWeight;
  if (sampleVar > priorVar) priorWeight = Math.max(0.5, (params.priorWeight * priorVar) / sampleVar);
  let withinVar = (n * sampleVar + priorWeight * priorVar) / (n + priorWeight);
  withinVar = Math.min(Math.max(withinVar, params.minWithinVar), params.maxWithinVar);

  const between = params.popBetweenSd ** 2;
  const weight = (n * between) / Math.max(1e-9, n * between + withinVar);
  let shrunk = weight * mean + (1 - weight) * params.popMean;
  shrunk = Math.min(Math.max(shrunk, params.minMean), params.maxMean);

  const recent = lengths.slice(-6);
  let trend = 0;
  if (n >= 4 && recent.length >= 3) {
    const weights = Array.from({ length: recent.length }, (_, k) => (1 - params.trendEwma) ** (recent.length - 1 - k));
    trend = recent.reduce((acc, y, i) => acc + (y - shrunk) * weights[i], 0) / weights.reduce((a, b) => a + b, 0);
    const shift = Math.abs(trend) < params.trendThreshold ? 0 : Math.max(-params.trendMaxShift, Math.min(params.trendMaxShift, trend));
    shrunk = Math.min(Math.max(shrunk + shift, params.minMean), params.maxMean);
  }
  const recentMean = recent.reduce((a, b) => a + b, 0) / recent.length;
  const recentSd = recent.length >= 2
    ? Math.sqrt(recent.reduce((a, y) => a + (y - recentMean) ** 2, 0) / (recent.length - 1))
    : 0;
  const recentRange = Math.max(...recent) - Math.min(...recent);
  const gap = Math.max(...recent) > params.abstainGapDays;

  let pi = params.tailProbBase
    + params.tailProbSdGain * Math.max(0, recentSd - 2)
    + params.tailProbRangeGain * Math.max(0, recentRange - 7);
  if (gap) pi += params.tailProbGapBonus;
  pi = Math.min(Math.max(pi, params.tailProbBase), params.tailProbMax);

  const abstain = gap || recentSd > params.abstainRecentSd || n < params.abstainMinCycles;
  const confidence = abstain ? 'abstain' : n >= 6 ? 'established' : n >= 3 ? 'building' : n >= 1 ? 'learning' : 'new';
  const posterior = (withinVar * between) / Math.max(1e-9, n * between + withinVar);
  return {
    mean: shrunk, withinVar, cycleSd: Math.sqrt(withinVar + posterior), n, tailProb: pi,
    trend, recentSd, recentRange, gap, abstain, confidence,
  };
}

export function predictive(state, params) {
  const mix = mixtureFromMoments(state.mean, state.cycleSd * params.bodyScale, state.tailProb,
    params.tailShiftDays, params.tailSdMultiplier, params.momentMatch);
  return calibrated(mix, params);
}

export function hazardCurve(cal, params) {
  const curve = new Array(params.hazardMaxDay).fill(0);
  let prev = 1;
  for (let day = 1; day <= params.hazardMaxDay; day++) {
    if (prev <= 1e-12) { curve[day - 1] = 1; continue; }
    const f = calCdf(cal, day) - calCdf(cal, day - 1);
    curve[day - 1] = Math.min(Math.max(Math.max(0, f) / prev, 0), 1);
    prev -= Math.max(0, f);
    if (prev < 0) prev = 0;
  }
  return curve;
}

export function onsetProbs(cal, currentDay, params) {
  currentDay = Math.max(1, Math.trunc(currentDay));
  const curve = hazardCurve(cal, params);
  const s0 = Math.max(1e-12, 1 - calCdf(cal, currentDay - 1));
  const within = (k) => {
    const st = Math.max(0, 1 - calCdf(cal, currentDay - 1 + k));
    return Math.min(Math.max(1 - st / s0, 0), 1);
  };
  const curveOut = {};
  for (let d = currentDay; d <= Math.min(params.hazardMaxDay, currentDay + 13); d++) curveOut[d] = curve[d - 1];
  return {
    current_day: currentDay,
    p_today: currentDay <= curve.length ? curve[currentDay - 1] : 0,
    p_within_3: within(3), p_within_7: within(7), p_within_14: within(14),
    late_probability: 1 - calCdf(cal, currentDay - 1),
    curve: curveOut,
  };
}

export function ovulationDistribution(cal, params) {
  const sdO = Math.sqrt(Math.max(cal.mix.sd ** 2 - params.lutealSd ** 2, params.ovulationSdFloor ** 2));
  const meanO = cal.mix.mean - params.lutealMean;
  const step = params.ovulationGridStep;
  const edges = [];
  for (let y = 0; y <= 365 + 1e-9; y += step) edges.push(y);
  const cdfEdges = edges.map((e) => calCdf(cal, e));
  const maxDay = params.hazardMaxDay;
  const probs = new Array(maxDay).fill(0);
  let prev = 0;
  for (let day = 1; day <= maxDay; day++) {
    let total = 0;
    for (let i = 0; i < edges.length - 1; i++) {
      const mass = cdfEdges[i + 1] - cdfEdges[i];
      if (mass <= 0) continue;
      const yMid = 0.5 * (edges[i] + edges[i + 1]);
      total += mass * normCdf((day - yMid + params.lutealMean) / params.lutealSd);
    }
    probs[day - 1] = Math.min(Math.max(total - prev, 0), 1);
    prev = total;
  }
  probs[maxDay - 1] += Math.max(0, 1 - prev);
  const fertile = new Array(maxDay).fill(0);
  for (let day = 1; day <= maxDay; day++) {
    let sum = 0;
    const last = Math.min(maxDay, day + params.fertileWindowDays - 1);
    for (let o = day; o <= last; o++) sum += probs[o - 1];
    fertile[day - 1] = Math.min(Math.max(sum, 0), 1);
  }
  const maxP = Math.max(...fertile);
  const peakDays = [];
  const windowDays = [];
  for (let d = 1; d <= maxDay; d++) {
    if (fertile[d - 1] >= Math.max(0.25, 0.5 * maxP)) peakDays.push(d);
    if (fertile[d - 1] >= 0.05) windowDays.push(d);
  }
  return {
    mean_day: meanO, sd_day: sdO,
    fertile_probabilities: Object.fromEntries(fertile.map((p, i) => [i + 1, p])),
    peak_days: peakDays,
    window_start: windowDays.length ? Math.min(...windowDays) : null,
    window_end: windowDays.length ? Math.max(...windowDays) : null,
  };
}

export function forecast(lengths, currentDay = 1, params = literatureParams()) {
  const state = personalState(lengths, params);
  const cal = predictive(state, params);
  const hazard = onsetProbs(cal, currentDay, params);
  const ovulation = ovulationDistribution(cal, params);
  const labels = ['0.025', '0.05', '0.1', '0.25', '0.5', '0.75', '0.9', '0.95', '0.975'];
  const ps = [0.025, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.975];
  const quantiles = Object.fromEntries(labels.map((label, i) => [label, calQuantile(cal, ps[i])]));
  return {
    params_version: params.version,
    mean_length: state.mean,
    sd_length: state.cycleSd * params.bodyScale,
    cycles_used: state.n,
    confidence: state.confidence,
    abstain: state.abstain,
    tail_prob: state.tailProb,
    trend: state.trend,
    quantiles, hazard, ovulation,
  };
}

export function literatureParams() {
  return {
    version: 'dochia-v1-literature',
    popMean: 29.0, popBetweenSd: 3.5, withinSdPrior: 2.0, priorWeight: 4.0,
    minMean: 18.0, maxMean: 90.0, minWithinVar: 1.44, maxWithinVar: 36.0,
    lutealMean: 14.13, lutealSd: 1.41, fertileWindowDays: 6,
    ovulationSdFloor: 0.35, ovulationGridStep: 0.25,
    varianceBlend: 1.0, momentMatch: false,
    tailProbBase: 0.10, tailProbMax: 0.40, tailProbSdGain: 0.06,
    tailProbRangeGain: 0.02, tailProbGapBonus: 0.20,
    tailShiftDays: 3.0, tailSdMultiplier: 2.2,
    trendEwma: 0.4, trendThreshold: 3.0, trendMaxShift: 3.0,
    bodyScale: 1.0, tailScaleLow: 1.0, tailScaleHigh: 1.0,
    tailAnchorLow: 0.10, tailAnchorHigh: 0.90,
    minLength: 15, maxLength: 120, hazardMaxDay: 120,
    abstainGapDays: 90, abstainRecentSd: 6.0, abstainMinCycles: 0,
  };
}