omega-mv
Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.
Brought by drakestapleton
omega-mv / src / estimation / est_pred.c
| 1 | /* SPDX-License-Identifier: Apache-2.0 |
| 2 | * Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | /* ESTIMATION-2 (protocol v3) discrete predictive layer. Contract: est_pred.h. |
| 18 | * No allocation, no globals, no I/O; libm only (plus snprintf for the verdict |
| 19 | * reason text). */ |
| 20 | #include "est_pred.h" |
| 21 | #include "sha256.h" |
| 22 | |
| 23 | #include <math.h> |
| 24 | #include <stdio.h> |
| 25 | #include <string.h> |
| 26 | |
| 27 | #define SQRT1_2 0.70710678118654752440 |
| 28 | #define BETACF_MAXIT 20000 |
| 29 | #define BETACF_EPS 1e-15 |
| 30 | #define BETACF_FPMIN 1e-300 |
| 31 | |
| 32 | /* ------------------------------------------------------------- numerics */ |
| 33 | |
| 34 | /* Continued fraction for I_x(a,b) (modified Lentz, Numerical-Recipes form). |
| 35 | * Returns NaN if it does not converge within BETACF_MAXIT. */ |
| 36 | static double betacf(double a, double b, double x) |
| 37 | { |
| 38 | double qab = a + b, qap = a + 1.0, qam = a - 1.0; |
| 39 | double c = 1.0, d = 1.0 - qab * x / qap; |
| 40 | if (fabs(d) < BETACF_FPMIN) d = BETACF_FPMIN; |
| 41 | d = 1.0 / d; |
| 42 | double h = d; |
| 43 | for (int m = 1; m <= BETACF_MAXIT; m++) { |
| 44 | double m2 = 2.0 * m; |
| 45 | double aa = m * (b - m) * x / ((qam + m2) * (a + m2)); |
| 46 | d = 1.0 + aa * d; |
| 47 | if (fabs(d) < BETACF_FPMIN) d = BETACF_FPMIN; |
| 48 | c = 1.0 + aa / c; |
| 49 | if (fabs(c) < BETACF_FPMIN) c = BETACF_FPMIN; |
| 50 | d = 1.0 / d; |
| 51 | h *= d * c; |
| 52 | aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)); |
| 53 | d = 1.0 + aa * d; |
| 54 | if (fabs(d) < BETACF_FPMIN) d = BETACF_FPMIN; |
| 55 | c = 1.0 + aa / c; |
| 56 | if (fabs(c) < BETACF_FPMIN) c = BETACF_FPMIN; |
| 57 | d = 1.0 / d; |
| 58 | double del = d * c; |
| 59 | h *= del; |
| 60 | if (fabs(del - 1.0) <= BETACF_EPS) return h; |
| 61 | } |
| 62 | return NAN; |
| 63 | } |
| 64 | |
| 65 | /* I_x(a,b) with y = 1 - x supplied exactly by the caller (avoids the |
| 66 | * cancellation in 1 - x when x is close to 1). */ |
| 67 | static double betai_xy(double a, double b, double x, double y) |
| 68 | { |
| 69 | if (!(a > 0.0) || !(b > 0.0) || !isfinite(a) || !isfinite(b)) return NAN; |
| 70 | if (!(x >= 0.0 && x <= 1.0) || !(y >= 0.0 && y <= 1.0)) return NAN; |
| 71 | if (x == 0.0) return 0.0; |
| 72 | if (y == 0.0) return 1.0; |
| 73 | double lbt = lgamma(a + b) - lgamma(a) - lgamma(b) + a * log(x) + b * log(y); |
| 74 | double bt = exp(lbt); |
| 75 | if (x < (a + 1.0) / (a + b + 2.0)) { |
| 76 | double cf = betacf(a, b, x); |
| 77 | return bt * cf / a; |
| 78 | } |
| 79 | double cf = betacf(b, a, y); |
| 80 | return 1.0 - bt * cf / b; |
| 81 | } |
| 82 | |
| 83 | double est_betai(double a, double b, double x) |
| 84 | { |
| 85 | if (!(x >= 0.0 && x <= 1.0)) return NAN; |
| 86 | return betai_xy(a, b, x, 1.0 - x); |
| 87 | } |
| 88 | |
| 89 | /* P(T > t) for t >= 0: 0.5 * I_{nu/(nu+t^2)}(nu/2, 1/2). */ |
| 90 | static double t_sf_pos(double t, double nu) |
| 91 | { |
| 92 | if (isinf(t)) return 0.0; |
| 93 | double t2 = t * t, den = nu + t2; |
| 94 | if (!isfinite(den)) return 0.0; |
| 95 | return 0.5 * betai_xy(0.5 * nu, 0.5, nu / den, t2 / den); |
| 96 | } |
| 97 | |
| 98 | double est_t_sf(double t, double nu) |
| 99 | { |
| 100 | if (isnan(t) || isnan(nu) || !(nu > 0.0)) return NAN; |
| 101 | if (t >= 0.0) return t_sf_pos(t, nu); |
| 102 | return 1.0 - t_sf_pos(-t, nu); |
| 103 | } |
| 104 | |
| 105 | double est_t_cdf(double t, double nu) |
| 106 | { |
| 107 | if (isnan(t) || isnan(nu) || !(nu > 0.0)) return NAN; |
| 108 | return est_t_sf(-t, nu); |
| 109 | } |
| 110 | |
| 111 | double est_norm_cdf(double x) { return 0.5 * erfc(-x * SQRT1_2); } |
| 112 | |
| 113 | double est_norm_ppf(double p) |
| 114 | { |
| 115 | if (isnan(p)) return NAN; |
| 116 | if (p <= 0.0) return -8.0; |
| 117 | if (p >= 1.0) return 8.0; |
| 118 | double lo = -8.0, hi = 8.0; |
| 119 | if (est_norm_cdf(lo) >= p) return -8.0; |
| 120 | if (est_norm_cdf(hi) <= p) return 8.0; |
| 121 | for (int i = 0; i < 200; i++) { |
| 122 | double mid = 0.5 * (lo + hi); |
| 123 | if (mid <= lo || mid >= hi) break; |
| 124 | if (est_norm_cdf(mid) < p) lo = mid; else hi = mid; |
| 125 | } |
| 126 | return 0.5 * (lo + hi); |
| 127 | } |
| 128 | |
| 129 | /* ----------------------------------------------------------- assumption */ |
| 130 | |
| 131 | static uint32_t fam_nparam(est_family f) |
| 132 | { |
| 133 | switch (f) { |
| 134 | case EST_FAM_GAUSS_KF: return 3u; |
| 135 | case EST_FAM_HUBER_KF: return 4u; |
| 136 | case EST_FAM_STUDENT_T: return 2u; |
| 137 | case EST_FAM_SCALE_MIX: return 7u; |
| 138 | case EST_FAM_ADAPTIVE_T: return 5u; |
| 139 | } |
| 140 | return 0u; |
| 141 | } |
| 142 | |
| 143 | static int pos_fin(double v) { return isfinite(v) && v > 0.0; } |
| 144 | static int nonneg_fin(double v) { return isfinite(v) && v >= 0.0; } |
| 145 | |
| 146 | /* Builds the F4 shape from the parameter vector (k, w0, w1, w2, v0, v1, v2). */ |
| 147 | static est_status mix_from(const est_assumption *a, est_mix *mx) |
| 148 | { |
| 149 | double kd = a->param[0]; |
| 150 | if (!(kd == 1.0 || kd == 2.0 || kd == 3.0)) return EST_ERR_DIM; |
| 151 | memset(mx, 0, sizeof *mx); |
| 152 | mx->k = (uint32_t)kd; |
| 153 | for (uint32_t j = 0; j < EST_MIX_MAX; j++) { |
| 154 | double w = a->param[1 + j], v = a->param[4 + j]; |
| 155 | if (j >= mx->k) { |
| 156 | if (w != 0.0 || v != 0.0) return EST_ERR_DIM; |
| 157 | continue; |
| 158 | } |
| 159 | mx->w[j] = w; |
| 160 | mx->v[j] = v; |
| 161 | } |
| 162 | return est_mix_check(mx); |
| 163 | } |
| 164 | |
| 165 | /* Status codes: NULL; KIND (unknown family); UNIT (unit outside 1..MAX_-1); |
| 166 | * NONFINITE (NaN/Inf in quantum, lo, hi or any param); NOT_PD (quantum <= 0, |
| 167 | * or a variance/scale/nu/c/floor that must be > 0 is not); DIM (nparam is not |
| 168 | * the family's count, a param beyond nparam is nonzero, F4 k not in {1,2,3} |
| 169 | * or an unused F4 weight/variance nonzero); ENCODING (lo >= hi, F1/F2 |
| 170 | * q_proc + r == 0, F5 lambda outside [0,1], F4 weights not summing to 1). */ |
| 171 | est_status est_assumption_check(const est_assumption *a) |
| 172 | { |
| 173 | if (!a) return EST_ERR_NULL; |
| 174 | uint32_t np = fam_nparam(a->family); |
| 175 | if (np == 0u) return EST_ERR_KIND; |
| 176 | if ((uint32_t)a->unit < 1u || (uint32_t)a->unit >= (uint32_t)EST_UNIT_MAX_) return EST_ERR_UNIT; |
| 177 | if (!isfinite(a->quantum) || !isfinite(a->lo) || !isfinite(a->hi)) return EST_ERR_NONFINITE; |
| 178 | for (uint32_t i = 0; i < EST_PRED_NPARAM; i++) |
| 179 | if (!isfinite(a->param[i])) return EST_ERR_NONFINITE; |
| 180 | if (!(a->quantum > 0.0)) return EST_ERR_NOT_PD; |
| 181 | if (!(a->lo < a->hi)) return EST_ERR_ENCODING; |
| 182 | if (a->nparam != np) return EST_ERR_DIM; |
| 183 | for (uint32_t i = np; i < EST_PRED_NPARAM; i++) |
| 184 | if (a->param[i] != 0.0) return EST_ERR_DIM; |
| 185 | const double *p = a->param; |
| 186 | switch (a->family) { |
| 187 | case EST_FAM_GAUSS_KF: |
| 188 | case EST_FAM_HUBER_KF: |
| 189 | if (!nonneg_fin(p[0]) || !nonneg_fin(p[1]) || !nonneg_fin(p[2])) return EST_ERR_NOT_PD; |
| 190 | if (!(p[0] + p[1] > 0.0)) return EST_ERR_ENCODING; |
| 191 | if (a->family == EST_FAM_HUBER_KF && !pos_fin(p[3])) return EST_ERR_NOT_PD; |
| 192 | return EST_OK; |
| 193 | case EST_FAM_STUDENT_T: |
| 194 | if (!pos_fin(p[0]) || !pos_fin(p[1])) return EST_ERR_NOT_PD; |
| 195 | return EST_OK; |
| 196 | case EST_FAM_SCALE_MIX: { |
| 197 | est_mix mx; |
| 198 | return mix_from(a, &mx); |
| 199 | } |
| 200 | case EST_FAM_ADAPTIVE_T: |
| 201 | if (!(p[0] >= 0.0 && p[0] <= 1.0)) return EST_ERR_ENCODING; |
| 202 | if (!pos_fin(p[1]) || !pos_fin(p[2]) || !pos_fin(p[3]) || !pos_fin(p[4])) return EST_ERR_NOT_PD; |
| 203 | return EST_OK; |
| 204 | } |
| 205 | return EST_ERR_KIND; |
| 206 | } |
| 207 | |
| 208 | /* Assumption encoding (input to est_assumption_digest), little-endian: |
| 209 | * u32 family | u32 unit | f64 quantum | f64 lo | f64 hi | u32 nparam | |
| 210 | * f64 param[0..nparam-1] |
| 211 | * f64 = IEEE-754 binary64 bit pattern, -0.0 canonicalized to +0.0 (NaN/Inf |
| 212 | * are refused by est_assumption_check first). Entries param[nparam..] are |
| 213 | * zero by contract and not encoded. Length = 36 + 8 * nparam bytes. |
| 214 | * Digest = SHA-256("omega.est.assumption.v1" || 0x00 || encoding). */ |
| 215 | static size_t put_u32(uint8_t *b, size_t o, uint32_t v) |
| 216 | { |
| 217 | for (int i = 0; i < 4; i++) b[o + (size_t)i] = (uint8_t)(v >> (8 * i)); |
| 218 | return o + 4u; |
| 219 | } |
| 220 | static size_t put_f64(uint8_t *b, size_t o, double d) |
| 221 | { |
| 222 | if (d == 0.0) d = 0.0; |
| 223 | uint64_t v; |
| 224 | memcpy(&v, &d, sizeof v); |
| 225 | for (int i = 0; i < 8; i++) b[o + (size_t)i] = (uint8_t)(v >> (8 * i)); |
| 226 | return o + 8u; |
| 227 | } |
| 228 | |
| 229 | est_status est_assumption_digest(const est_assumption *a, est_digest *out) |
| 230 | { |
| 231 | if (!a || !out) return EST_ERR_NULL; |
| 232 | est_status st = est_assumption_check(a); |
| 233 | if (st != EST_OK) return st; |
| 234 | uint8_t enc[36u + 8u * EST_PRED_NPARAM]; |
| 235 | size_t o = 0; |
| 236 | o = put_u32(enc, o, (uint32_t)a->family); |
| 237 | o = put_u32(enc, o, (uint32_t)a->unit); |
| 238 | o = put_f64(enc, o, a->quantum); |
| 239 | o = put_f64(enc, o, a->lo); |
| 240 | o = put_f64(enc, o, a->hi); |
| 241 | o = put_u32(enc, o, a->nparam); |
| 242 | for (uint32_t i = 0; i < a->nparam; i++) o = put_f64(enc, o, a->param[i]); |
| 243 | const uint8_t zero = 0; |
| 244 | sha256_ctx c; |
| 245 | sha256_init(&c); |
| 246 | sha256_update(&c, (const uint8_t *)EST_DOMAIN_ASSUMPTION, strlen(EST_DOMAIN_ASSUMPTION)); |
| 247 | sha256_update(&c, &zero, 1); |
| 248 | sha256_update(&c, enc, o); |
| 249 | sha256_final(&c, out->b); |
| 250 | return EST_OK; |
| 251 | } |
| 252 | |
| 253 | /* ---------------------------------------------------------- observation */ |
| 254 | |
| 255 | static est_obs_class classify(const est_assumption *a, double v, int present) |
| 256 | { |
| 257 | if (!present) return EST_OBS_MISSING; |
| 258 | if (!isfinite(v)) return EST_OBS_NONFINITE; |
| 259 | if (v < a->lo || v > a->hi) return EST_OBS_OUT_OF_RANGE; |
| 260 | double u = v / a->quantum; |
| 261 | if (fabs(u - nearbyint(u)) > EST_PRED_GRID_TOL) return EST_OBS_OFF_GRID; |
| 262 | return EST_OBS_OK; |
| 263 | } |
| 264 | |
| 265 | est_status est_pobs_classify(const est_assumption *a, double value, int present, |
| 266 | const est_digest *evidence, est_pobs *out) |
| 267 | { |
| 268 | if (!a || !evidence || !out) return EST_ERR_NULL; |
| 269 | est_status st = est_assumption_check(a); |
| 270 | if (st != EST_OK) return st; |
| 271 | if (est_digest_is_zero(evidence)) return EST_ERR_KIND; |
| 272 | out->value = value; |
| 273 | out->cls = classify(a, value, present); |
| 274 | out->evidence = *evidence; |
| 275 | return EST_OK; |
| 276 | } |
| 277 | |
| 278 | /* ------------------------------------------------- continuous change law */ |
| 279 | |
| 280 | typedef enum { D_GAUSS, D_T, D_MIX } dist_kind; |
| 281 | typedef struct { |
| 282 | dist_kind kind; |
| 283 | double scale; /* sd (gauss) or t scale */ |
| 284 | double nu; |
| 285 | est_mix mx; |
| 286 | } dist; |
| 287 | |
| 288 | /* upper tail P(X > x) for x >= 0 of the zero-centred law */ |
| 289 | static double dist_sf_pos(const dist *d, double x) |
| 290 | { |
| 291 | switch (d->kind) { |
| 292 | case D_GAUSS: return 0.5 * erfc(x / d->scale * SQRT1_2); |
| 293 | case D_T: return t_sf_pos(x / d->scale, d->nu); |
| 294 | case D_MIX: { |
| 295 | double s = 0.0; |
| 296 | for (uint32_t j = 0; j < d->mx.k; j++) |
| 297 | if (d->mx.w[j] > 0.0) s += d->mx.w[j] * 0.5 * erfc(x / sqrt(d->mx.v[j]) * SQRT1_2); |
| 298 | return s; |
| 299 | } |
| 300 | } |
| 301 | return NAN; |
| 302 | } |
| 303 | |
| 304 | /* p(k) = G((k+.5)q - mu) - G((k-.5)q - mu), edge bins take the outer tails. |
| 305 | * S[e] = P(X > |x_e|) at every bin edge x_e; each difference is formed on the |
| 306 | * side of zero where both tails are small (no cancellation). Normalized. */ |
| 307 | static est_status pmf_from_dist(const dist *d, double mu, double q, double *out) |
| 308 | { |
| 309 | double S[EST_PRED_N - 1]; |
| 310 | double x[EST_PRED_N - 1]; |
| 311 | for (int e = 0; e < EST_PRED_N - 1; e++) x[e] = ((double)(e - EST_PRED_K) + 0.5) * q - mu; |
| 312 | if (mu == 0.0) { |
| 313 | for (int e = EST_PRED_K; e < EST_PRED_N - 1; e++) { |
| 314 | S[e] = dist_sf_pos(d, x[e]); |
| 315 | S[EST_PRED_N - 2 - e] = S[e]; |
| 316 | } |
| 317 | } else { |
| 318 | for (int e = 0; e < EST_PRED_N - 1; e++) S[e] = dist_sf_pos(d, fabs(x[e])); |
| 319 | } |
| 320 | for (int e = 0; e < EST_PRED_N - 1; e++) |
| 321 | if (!(S[e] >= 0.0 && S[e] <= 1.0)) return EST_ERR_NONFINITE; |
| 322 | /* lower edge: P(X <= x_0); upper edge: P(X > x_{N-2}) */ |
| 323 | out[0] = x[0] <= 0.0 ? S[0] : 1.0 - S[0]; |
| 324 | out[EST_PRED_N - 1] = x[EST_PRED_N - 2] >= 0.0 ? S[EST_PRED_N - 2] : 1.0 - S[EST_PRED_N - 2]; |
| 325 | for (int i = 1; i < EST_PRED_N - 1; i++) { |
| 326 | double a = x[i - 1], b = x[i], m; |
| 327 | if (a >= 0.0) m = S[i - 1] - S[i]; |
| 328 | else if (b <= 0.0) m = S[i] - S[i - 1]; |
| 329 | else m = 1.0 - S[i - 1] - S[i]; |
| 330 | out[i] = m > 0.0 ? m : 0.0; |
| 331 | } |
| 332 | double s = 0.0; |
| 333 | for (int i = 0; i < EST_PRED_N; i++) s += out[i]; |
| 334 | if (!(s > 0.0) || !isfinite(s)) return EST_ERR_NONFINITE; |
| 335 | for (int i = 0; i < EST_PRED_N; i++) out[i] /= s; |
| 336 | return EST_OK; |
| 337 | } |
| 338 | |
| 339 | /* ------------------------------------------------------- pmf utilities */ |
| 340 | |
| 341 | static void support(const double *p, int32_t *lo, int32_t *hi) |
| 342 | { |
| 343 | int l = 0, h = EST_PRED_N - 1; |
| 344 | while (l < EST_PRED_N - 1 && p[l] == 0.0) l++; |
| 345 | while (h > l && p[h] == 0.0) h--; |
| 346 | *lo = l; |
| 347 | *hi = h; |
| 348 | } |
| 349 | |
| 350 | /* out = a * b with offsets beyond +-K folded into the edge bins. out may not |
| 351 | * alias a or b. The folded mass of row i is a[i] times a cumulative tail of b |
| 352 | * (C summed up from the low end, D down from the high end, so small tails are |
| 353 | * not differences of large numbers); the in-range part is a plain loop. */ |
| 354 | static void conv_fold(const double *a, const double *b, double *out) |
| 355 | { |
| 356 | double C[EST_PRED_N], D[EST_PRED_N]; |
| 357 | int32_t al, ah, bl, bh; |
| 358 | support(a, &al, &ah); |
| 359 | support(b, &bl, &bh); |
| 360 | double s = 0.0; |
| 361 | for (int j = 0; j < EST_PRED_N; j++) { s += b[j]; C[j] = s; } |
| 362 | s = 0.0; |
| 363 | for (int j = EST_PRED_N - 1; j >= 0; j--) { s += b[j]; D[j] = s; } |
| 364 | for (int i = 0; i < EST_PRED_N; i++) out[i] = 0.0; |
| 365 | for (int32_t i = al; i <= ah; i++) { |
| 366 | double ai = a[i]; |
| 367 | if (ai == 0.0) continue; |
| 368 | int32_t m = EST_PRED_K - i - 1; /* j <= m lands below -K */ |
| 369 | if (m >= bl) out[0] += ai * C[m < bh ? m : bh]; |
| 370 | m = EST_PRED_N + EST_PRED_K - i; /* j >= m lands above +K */ |
| 371 | if (m <= bh) out[EST_PRED_N - 1] += ai * D[m > bl ? m : bl]; |
| 372 | int32_t j0 = EST_PRED_K - i, j1 = EST_PRED_N - 1 + EST_PRED_K - i; |
| 373 | if (j0 < bl) j0 = bl; |
| 374 | if (j1 > bh) j1 = bh; |
| 375 | int32_t off = i - EST_PRED_K; |
| 376 | for (int32_t j = j0; j <= j1; j++) out[j + off] += ai * b[j]; |
| 377 | } |
| 378 | } |
| 379 | |
| 380 | est_status est_pmf_conv_pow(const double *one, uint32_t h, double *out) |
| 381 | { |
| 382 | if (!one || !out) return EST_ERR_NULL; |
| 383 | if (h < 1u || h > EST_PRED_MAX_H) return EST_ERR_TIME; |
| 384 | for (int i = 0; i < EST_PRED_N; i++) |
| 385 | if (!isfinite(one[i]) || one[i] < 0.0) return EST_ERR_NONFINITE; |
| 386 | double base[EST_PRED_N], acc[EST_PRED_N], tmp[EST_PRED_N]; |
| 387 | memcpy(base, one, sizeof base); |
| 388 | int have = 0; |
| 389 | for (uint32_t r = h;;) { |
| 390 | if (r & 1u) { |
| 391 | if (!have) { memcpy(acc, base, sizeof acc); have = 1; } |
| 392 | else { conv_fold(acc, base, tmp); memcpy(acc, tmp, sizeof acc); } |
| 393 | } |
| 394 | r >>= 1; |
| 395 | if (!r) break; |
| 396 | conv_fold(base, base, tmp); |
| 397 | memcpy(base, tmp, sizeof base); |
| 398 | } |
| 399 | memcpy(out, acc, sizeof acc); |
| 400 | return EST_OK; |
| 401 | } |
| 402 | |
| 403 | void est_pmf_floor(double *pmf) |
| 404 | { |
| 405 | if (!pmf) return; |
| 406 | double s = 0.0; |
| 407 | for (int i = 0; i < EST_PRED_N; i++) s += pmf[i]; |
| 408 | double u = EST_PRED_FLOOR / (double)EST_PRED_N; |
| 409 | double t = 0.0; |
| 410 | for (int i = 0; i < EST_PRED_N; i++) { |
| 411 | pmf[i] = (1.0 - EST_PRED_FLOOR) * (s > 0.0 ? pmf[i] / s : 0.0) + u; |
| 412 | t += pmf[i]; |
| 413 | } |
| 414 | for (int i = 0; i < EST_PRED_N; i++) pmf[i] /= t; |
| 415 | } |
| 416 | |
| 417 | /* ------------------------------------------------------------ candidate */ |
| 418 | |
| 419 | static est_status bind(const est_assumption *a, const est_bstate *b) |
| 420 | { |
| 421 | est_digest d; |
| 422 | est_status st = est_assumption_digest(a, &d); |
| 423 | if (st != EST_OK) return st; |
| 424 | if (memcmp(d.b, b->assumption.b, EST_DIGEST_SIZE) != 0) return EST_ERR_MODEL; |
| 425 | return EST_OK; |
| 426 | } |
| 427 | |
| 428 | est_status est_pred_init(const est_assumption *a, est_bstate *b) |
| 429 | { |
| 430 | if (!a || !b) return EST_ERR_NULL; |
| 431 | est_digest d; |
| 432 | est_status st = est_assumption_digest(a, &d); |
| 433 | if (st != EST_OK) return st; |
| 434 | memset(b, 0, sizeof *b); |
| 435 | b->assumption = d; |
| 436 | if (a->family == EST_FAM_GAUSS_KF || a->family == EST_FAM_HUBER_KF) b->P = a->param[2]; |
| 437 | if (a->family == EST_FAM_ADAPTIVE_T) b->s2 = a->param[4] * a->param[4]; |
| 438 | return EST_OK; |
| 439 | } |
| 440 | |
| 441 | /* The persistence families' continuous one-step change law and its cache key. */ |
| 442 | static est_status persist_dist(const est_assumption *a, const est_bstate *b, dist *d, double *key) |
| 443 | { |
| 444 | memset(d, 0, sizeof *d); |
| 445 | switch (a->family) { |
| 446 | case EST_FAM_STUDENT_T: |
| 447 | d->kind = D_T; d->nu = a->param[0]; d->scale = a->param[1]; |
| 448 | *key = d->scale; |
| 449 | return EST_OK; |
| 450 | case EST_FAM_ADAPTIVE_T: |
| 451 | d->kind = D_T; d->nu = a->param[1]; d->scale = a->param[2] * sqrt(b->s2); |
| 452 | if (!pos_fin(d->scale)) return EST_ERR_NONFINITE; |
| 453 | *key = d->scale; |
| 454 | return EST_OK; |
| 455 | case EST_FAM_SCALE_MIX: { |
| 456 | d->kind = D_MIX; |
| 457 | est_status st = mix_from(a, &d->mx); |
| 458 | if (st != EST_OK) return st; |
| 459 | *key = est_mix_total_var(&d->mx); |
| 460 | return EST_OK; |
| 461 | } |
| 462 | default: |
| 463 | return EST_ERR_KIND; |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | est_status est_pred_predict(const est_assumption *a, est_bstate *b, uint32_t h, est_dpred *out) |
| 468 | { |
| 469 | if (!a || !b || !out) return EST_ERR_NULL; |
| 470 | est_status st = bind(a, b); |
| 471 | if (st != EST_OK) return st; |
| 472 | if (!b->has_anchor) return EST_ERR_STALE; |
| 473 | uint64_t H = (uint64_t)b->gap + (uint64_t)h; |
| 474 | if (h < 1u || H < 1u || H > EST_PRED_MAX_H) return EST_ERR_TIME; |
| 475 | double q = a->quantum; |
| 476 | |
| 477 | if (a->family == EST_FAM_GAUSS_KF || a->family == EST_FAM_HUBER_KF) { |
| 478 | double var = b->P + (double)H * a->param[0] + a->param[1]; |
| 479 | dist d; |
| 480 | memset(&d, 0, sizeof d); |
| 481 | d.kind = D_GAUSS; |
| 482 | d.scale = sqrt(var); |
| 483 | if (!pos_fin(d.scale)) return EST_ERR_NONFINITE; |
| 484 | st = pmf_from_dist(&d, b->xhat - b->anchor, q, out->pmf); |
| 485 | if (st != EST_OK) return st; |
| 486 | } else { |
| 487 | dist d; |
| 488 | double key = 0.0; |
| 489 | st = persist_dist(a, b, &d, &key); |
| 490 | if (st != EST_OK) return st; |
| 491 | if (!b->cache_valid || b->cache_key != key) { |
| 492 | st = pmf_from_dist(&d, 0.0, q, b->cache); |
| 493 | if (st != EST_OK) { b->cache_valid = 0; return st; } |
| 494 | support(b->cache, &b->cache_lo, &b->cache_hi); |
| 495 | b->cache_lo -= EST_PRED_K; |
| 496 | b->cache_hi -= EST_PRED_K; |
| 497 | b->cache_key = key; |
| 498 | b->cache_valid = 1; |
| 499 | } |
| 500 | st = est_pmf_conv_pow(b->cache, (uint32_t)H, out->pmf); |
| 501 | if (st != EST_OK) return st; |
| 502 | } |
| 503 | est_pmf_floor(out->pmf); |
| 504 | b->generation++; |
| 505 | out->assumption = b->assumption; |
| 506 | out->family = a->family; |
| 507 | out->horizon = (uint32_t)H; |
| 508 | out->generation = b->generation; |
| 509 | out->anchor = b->anchor; |
| 510 | out->quantum = q; |
| 511 | return EST_OK; |
| 512 | } |
| 513 | |
| 514 | est_status est_pred_update(const est_assumption *a, est_bstate *b, const est_pobs *obs) |
| 515 | { |
| 516 | if (!a || !b || !obs) return EST_ERR_NULL; |
| 517 | est_status st = bind(a, b); |
| 518 | if (st != EST_OK) return st; |
| 519 | if (est_digest_is_zero(&obs->evidence)) return EST_ERR_KIND; |
| 520 | if ((uint32_t)obs->cls >= (uint32_t)EST_OBS_CLASSES_) return EST_ERR_KIND; |
| 521 | est_obs_class cls = classify(a, obs->value, obs->cls != EST_OBS_MISSING); |
| 522 | if (cls != obs->cls) return EST_ERR_KIND; |
| 523 | |
| 524 | est_digest root; |
| 525 | st = est_evidence_root_extend(&b->evidence_root, &obs->evidence, &root); |
| 526 | if (st != EST_OK) return st; |
| 527 | |
| 528 | if (cls == EST_OBS_OK) { |
| 529 | double y = obs->value; |
| 530 | if (!b->has_anchor) { |
| 531 | /* First anchor: F1/F2 start at xhat = y with level variance p0 |
| 532 | * (p0 is the variance of the level given that one reading). */ |
| 533 | if (a->family == EST_FAM_GAUSS_KF || a->family == EST_FAM_HUBER_KF) { |
| 534 | b->xhat = y; |
| 535 | b->P = a->param[2]; |
| 536 | } |
| 537 | } else { |
| 538 | if (a->family == EST_FAM_GAUSS_KF || a->family == EST_FAM_HUBER_KF) { |
| 539 | double Pp = b->P + ((double)b->gap + 1.0) * a->param[0]; |
| 540 | double S = Pp + a->param[1]; |
| 541 | double K = Pp / S; |
| 542 | double e = y - b->xhat; |
| 543 | if (a->family == EST_FAM_HUBER_KF) { |
| 544 | double c = a->param[3] * sqrt(S); |
| 545 | if (e > c) e = c; |
| 546 | else if (e < -c) e = -c; |
| 547 | } |
| 548 | b->xhat += K * e; |
| 549 | b->P = (1.0 - K) * Pp; |
| 550 | if (b->P < 0.0) b->P = 0.0; |
| 551 | } else if (a->family == EST_FAM_ADAPTIVE_T && b->gap == 0u) { |
| 552 | double dd = y - b->anchor, lam = a->param[0], fl = a->param[3]; |
| 553 | double d2 = dd * dd; |
| 554 | b->s2 = lam * b->s2 + (1.0 - lam) * (d2 > fl ? d2 : fl); |
| 555 | } |
| 556 | } |
| 557 | b->anchor = y; |
| 558 | b->has_anchor = 1u; |
| 559 | b->gap = 0u; |
| 560 | } else if (b->gap < UINT32_MAX) { |
| 561 | b->gap++; |
| 562 | } |
| 563 | b->generation++; |
| 564 | b->evidence_root = root; |
| 565 | b->count[cls]++; |
| 566 | return EST_OK; |
| 567 | } |
| 568 | |
| 569 | /* -------------------------------------------------------------- scoring */ |
| 570 | |
| 571 | static est_status check_dpred(const est_dpred *p) |
| 572 | { |
| 573 | if (!isfinite(p->anchor) || !pos_fin(p->quantum)) return EST_ERR_NONFINITE; |
| 574 | if (p->horizon < 1u || p->horizon > EST_PRED_MAX_H) return EST_ERR_TIME; |
| 575 | double s = 0.0; |
| 576 | for (int i = 0; i < EST_PRED_N; i++) { |
| 577 | if (!isfinite(p->pmf[i]) || p->pmf[i] < 0.0) return EST_ERR_NONFINITE; |
| 578 | s += p->pmf[i]; |
| 579 | } |
| 580 | if (!(s > 0.0)) return EST_ERR_NONFINITE; |
| 581 | return EST_OK; |
| 582 | } |
| 583 | |
| 584 | est_status est_dpred_score(const est_dpred *p, const est_pobs *obs, est_pinnov *out) |
| 585 | { |
| 586 | if (!p || !obs || !out) return EST_ERR_NULL; |
| 587 | est_status st = check_dpred(p); |
| 588 | if (st != EST_OK) return st; |
| 589 | if ((uint32_t)obs->cls >= (uint32_t)EST_OBS_CLASSES_) return EST_ERR_KIND; |
| 590 | memset(out, 0, sizeof *out); |
| 591 | out->cls = obs->cls; |
| 592 | if (obs->cls != EST_OBS_OK) return EST_OK; |
| 593 | /* an OK record must carry a finite on-grid value */ |
| 594 | if (!isfinite(obs->value)) return EST_ERR_KIND; |
| 595 | double u = obs->value / p->quantum; |
| 596 | if (fabs(u - nearbyint(u)) > EST_PRED_GRID_TOL) return EST_ERR_KIND; |
| 597 | double kd = nearbyint((obs->value - p->anchor) / p->quantum); |
| 598 | if (kd < -(double)EST_PRED_K) kd = -(double)EST_PRED_K; |
| 599 | if (kd > (double)EST_PRED_K) kd = (double)EST_PRED_K; |
| 600 | int32_t k = (int32_t)kd; |
| 601 | int idx = k + EST_PRED_K; |
| 602 | double below = 0.0, above = 0.0; |
| 603 | for (int i = 0; i < idx; i++) below += p->pmf[i]; |
| 604 | for (int i = EST_PRED_N - 1; i > idx; i--) above += p->pmf[i]; |
| 605 | double pk = p->pmf[idx], tot = below + pk + above; |
| 606 | out->valid = 1u; |
| 607 | out->k = k; |
| 608 | out->F_lo = below / tot; |
| 609 | out->F_hi = (below + pk) / tot; |
| 610 | if (out->F_hi > 1.0) out->F_hi = 1.0; |
| 611 | double pr = pk / tot; |
| 612 | out->logp = log(pr > 1e-300 ? pr : 1e-300); |
| 613 | out->z = est_norm_ppf(0.5 * (out->F_lo + out->F_hi)); |
| 614 | return EST_OK; |
| 615 | } |
| 616 | |
| 617 | est_status est_pred_innov(const est_bstate *b, const est_dpred *p, const est_pobs *obs, |
| 618 | est_pinnov *out) |
| 619 | { |
| 620 | if (!b || !p || !obs || !out) return EST_ERR_NULL; |
| 621 | if (memcmp(p->assumption.b, b->assumption.b, EST_DIGEST_SIZE) != 0) return EST_ERR_STALE; |
| 622 | if (!b->has_anchor || p->generation != b->generation || (uint64_t)p->horizon != (uint64_t)b->gap + 1u) |
| 623 | return EST_ERR_STALE; |
| 624 | return est_dpred_score(p, obs, out); |
| 625 | } |
| 626 | |
| 627 | est_status est_dpred_width80(const est_dpred *p, double *mc) |
| 628 | { |
| 629 | if (!p || !mc) return EST_ERR_NULL; |
| 630 | est_status st = check_dpred(p); |
| 631 | if (st != EST_OK) return st; |
| 632 | double tot = 0.0; |
| 633 | for (int i = 0; i < EST_PRED_N; i++) tot += p->pmf[i]; |
| 634 | int lo = -1, hi = -1; |
| 635 | double c = 0.0; |
| 636 | for (int i = 0; i < EST_PRED_N; i++) { |
| 637 | c += p->pmf[i] / tot; |
| 638 | if (lo < 0 && c >= 0.1) lo = i; |
| 639 | if (hi < 0 && c >= 0.9) { hi = i; break; } |
| 640 | } |
| 641 | if (lo < 0) lo = EST_PRED_N - 1; |
| 642 | if (hi < 0) hi = EST_PRED_N - 1; |
| 643 | *mc = (double)(hi - lo) * p->quantum; |
| 644 | return EST_OK; |
| 645 | } |
| 646 | |
| 647 | /* ---------------------------------------------------------- calibration */ |
| 648 | |
| 649 | void est_calib_init(est_calib *c) |
| 650 | { |
| 651 | if (c) memset(c, 0, sizeof *c); |
| 652 | } |
| 653 | |
| 654 | static double overlap(double a0, double a1, double b0, double b1) |
| 655 | { |
| 656 | double lo = a0 > b0 ? a0 : b0, hi = a1 < b1 ? a1 : b1; |
| 657 | return hi > lo ? hi - lo : 0.0; |
| 658 | } |
| 659 | |
| 660 | double est_frac_cover(double F_lo, double F_hi, double alpha) |
| 661 | { |
| 662 | double lo = 0.5 * (1.0 - alpha), hi = 0.5 * (1.0 + alpha); |
| 663 | if (!(F_hi > F_lo)) return (F_lo >= lo && F_lo <= hi) ? 1.0 : 0.0; |
| 664 | return overlap(F_lo, F_hi, lo, hi) / (F_hi - F_lo); |
| 665 | } |
| 666 | |
| 667 | est_status est_calib_add(est_calib *c, const est_dpred *p, const est_pinnov *iv) |
| 668 | { |
| 669 | static const double alpha[3] = { 0.50, 0.80, 0.95 }; |
| 670 | if (!c || !p || !iv) return EST_ERR_NULL; |
| 671 | if (iv->valid != 1u || iv->cls != EST_OBS_OK) return EST_ERR_KIND; |
| 672 | if (!isfinite(iv->F_lo) || !isfinite(iv->F_hi) || !isfinite(iv->z) || !isfinite(iv->logp)) |
| 673 | return EST_ERR_NONFINITE; |
| 674 | if (iv->F_lo < 0.0 || iv->F_hi > 1.0 || iv->F_hi < iv->F_lo) return EST_ERR_ENCODING; |
| 675 | double w; |
| 676 | est_status st = est_dpred_width80(p, &w); |
| 677 | if (st != EST_OK) return st; |
| 678 | for (int i = 0; i < 3; i++) c->cov[i] += est_frac_cover(iv->F_lo, iv->F_hi, alpha[i]); |
| 679 | double span = iv->F_hi - iv->F_lo; |
| 680 | if (span > 0.0) { |
| 681 | for (int j = 0; j < 10; j++) |
| 682 | c->pit[j] += overlap(iv->F_lo, iv->F_hi, j / 10.0, (j + 1) / 10.0) / span; |
| 683 | } else { |
| 684 | int j = (int)floor(iv->F_lo * 10.0); |
| 685 | if (j < 0) j = 0; |
| 686 | if (j > 9) j = 9; |
| 687 | c->pit[j] += 1.0; |
| 688 | } |
| 689 | c->logp_sum += iv->logp; |
| 690 | c->width_sum += w; |
| 691 | c->z_sum += iv->z; |
| 692 | c->z_sq += iv->z * iv->z; |
| 693 | if (c->n > 0) c->z_lag += iv->z * c->z_prev; |
| 694 | c->z_prev = iv->z; |
| 695 | c->n++; |
| 696 | return EST_OK; |
| 697 | } |
| 698 | |
| 699 | void est_bands_default(est_bands *b) |
| 700 | { |
| 701 | if (!b) return; |
| 702 | b->cov50[0] = 0.46; b->cov50[1] = 0.54; |
| 703 | b->cov80[0] = 0.76; b->cov80[1] = 0.84; |
| 704 | b->cov95[0] = 0.93; b->cov95[1] = 0.97; |
| 705 | b->pit[0] = 0.07; b->pit[1] = 0.13; |
| 706 | b->bias_max = 0.10; |
| 707 | b->lag1_max = 0.20; |
| 708 | b->min_n = 2000; |
| 709 | } |
| 710 | |
| 711 | /* (S_xy/(n-1) - m^2) / (S_xx/n - m^2). NaN for n < 2. If z never varied |
| 712 | * (S_xx/n - m^2 <= 0) there is no serial structure to measure: 0. */ |
| 713 | double est_calib_lag1(const est_calib *c) |
| 714 | { |
| 715 | if (!c || c->n < 2) return NAN; |
| 716 | double n = (double)c->n, m = c->z_sum / n; |
| 717 | double den = c->z_sq / n - m * m; |
| 718 | if (!(den > 0.0)) return 0.0; |
| 719 | return (c->z_lag / (n - 1.0) - m * m) / den; |
| 720 | } |
| 721 | |
| 722 | static int in_band(double v, const double *band) { return v >= band[0] && v <= band[1]; } |
| 723 | |
| 724 | /* reason: "calibrated", or "<stat> <value> outside <band>" naming the first |
| 725 | * failing statistic in the order n, cov50, cov80, cov95, pit0..pit9, bias, |
| 726 | * lag1. A NaN statistic fails. */ |
| 727 | est_verdict est_calib_verdict(const est_calib *c, const est_bands *b, char *reason, size_t cap) |
| 728 | { |
| 729 | char dummy[1]; |
| 730 | if (!reason || cap == 0) { reason = dummy; cap = sizeof dummy; } |
| 731 | if (!c || !b) { snprintf(reason, cap, "null"); return EST_NOT_CALIBRATED; } |
| 732 | if (c->n < b->min_n || c->n == 0) { |
| 733 | snprintf(reason, cap, "n %llu below %llu", (unsigned long long)c->n, |
| 734 | (unsigned long long)b->min_n); |
| 735 | return EST_NOT_CALIBRATED; |
| 736 | } |
| 737 | double n = (double)c->n; |
| 738 | static const char *const cn[3] = { "cov50", "cov80", "cov95" }; |
| 739 | const double *cb[3] = { b->cov50, b->cov80, b->cov95 }; |
| 740 | for (int i = 0; i < 3; i++) { |
| 741 | double v = c->cov[i] / n; |
| 742 | if (!in_band(v, cb[i])) { |
| 743 | snprintf(reason, cap, "%s %.4f outside [%.2f,%.2f]", cn[i], v, cb[i][0], cb[i][1]); |
| 744 | return EST_NOT_CALIBRATED; |
| 745 | } |
| 746 | } |
| 747 | for (int j = 0; j < 10; j++) { |
| 748 | double v = c->pit[j] / n; |
| 749 | if (!in_band(v, b->pit)) { |
| 750 | snprintf(reason, cap, "pit%d %.4f outside [%.2f,%.2f]", j, v, b->pit[0], b->pit[1]); |
| 751 | return EST_NOT_CALIBRATED; |
| 752 | } |
| 753 | } |
| 754 | double bias = c->z_sum / n; |
| 755 | if (!(fabs(bias) <= b->bias_max)) { |
| 756 | snprintf(reason, cap, "bias %.4f beyond %.2f", bias, b->bias_max); |
| 757 | return EST_NOT_CALIBRATED; |
| 758 | } |
| 759 | double l1 = est_calib_lag1(c); |
| 760 | if (!(fabs(l1) <= b->lag1_max)) { |
| 761 | snprintf(reason, cap, "lag1 %.4f beyond %.2f", l1, b->lag1_max); |
| 762 | return EST_NOT_CALIBRATED; |
| 763 | } |
| 764 | snprintf(reason, cap, "calibrated"); |
| 765 | return EST_CALIBRATED; |
| 766 | } |