interplane.Get Omega
Read in your language

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

branch main Branches Tags History

omega-mv / src / estimation / est_pred.h

269 lines · 13312 bytes Raw Blame History
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: quantization-aware discrete predictive layer.
18 *
19 * Why it exists. Protocol v1 failed on heavy tails and volatility clustering;
20 * protocol v2 failed because about 80 % of 1 Hz thermal one-step changes are
21 * exactly zero on the 100 mC sensor grid, so the central 50 % interval of any
22 * continuous predictive covers every zero change and 50 % coverage cannot pass
23 * (docs/estimation/EST23_PROTOCOL_V2.md). Here every candidate estimator
24 * predicts the NEXT OBSERVATION as a probability mass function over the grid,
25 * and calibration is scored with the fractional (randomized-PIT) rule, which is
26 * exactly calibrated for a correct discrete predictive.
27 *
28 * Typed concepts (distinct C types; none collapses into another):
29 * est_assumption ModelAssumption: family, grid quantum (mC), valid range,
30 * parameter vector, unit. Identity = SHA-256(
31 * "omega.est.assumption.v1" || 0x00 || encoding), encoding
32 * in est_pred.c above est_assumption_digest.
33 * est_pobs Observation: raw value + validity class + evidence digest.
34 * Bad values are classified and treated as missing, counted,
35 * kept raw (never repaired, never silently dropped).
36 * est_bstate BeliefState: candidate internal state. Never an output.
37 * est_dpred Estimate/Uncertainty: pmf of the next observation over
38 * offsets k*quantum from the last valid observation (the
39 * anchor), k in [-EST_PRED_K, +EST_PRED_K]. An estimate is
40 * never an observation: update accepts only est_pobs.
41 * est_pinnov Innovation: where the observation fell in the pmf.
42 * est_calib CalibrationEvidence: accumulator; est_calib_verdict reads
43 * it against est_bands.
44 * Confidence in any of these is data. Nothing here is an authority input.
45 *
46 * Step semantics. One logical step = one sampling tick. est_pred_update
47 * consumes exactly one observation record per tick, whatever its class.
48 * gap = ticks elapsed since the last valid observation (0 right after one).
49 * est_pred_predict(h) forecasts the observation h ticks ahead of NOW, so its
50 * effective horizon (ticks after the anchor) is gap + h; that is what
51 * est_dpred.horizon holds. Effective horizon 1..EST_PRED_MAX_H, else
52 * EST_ERR_TIME. predict changes only the generation (+1). update: generation
53 * +1, evidence_root extended with the observation's evidence digest (every
54 * class, so a bad reading is on the record), class counter +1; a valid value
55 * becomes the new anchor (also after a gap beyond EST_PRED_MAX_H, so the state
56 * never dead-ends), anything else just grows the gap.
57 * Before the first valid observation there is no anchor: predict returns
58 * EST_ERR_STALE.
59 *
60 * Families. A continuous one-step change distribution G is discretized:
61 * p(k) = G((k+0.5)q) - G((k-0.5)q), edge bins take the whole outer tails.
62 * F1 GAUSS_KF random-walk Kalman on the level (q_proc, r, p0);
63 * predictive change ~ N(xhat - anchor, P + H*q_proc + r),
64 * H the effective horizon (closed form, no convolution).
65 * F2 HUBER_KF predictive as F1; the update clips the innovation at
66 * c*sqrt(S) (Huber); params (q_proc, r, p0, c).
67 * F3 STUDENT_T persistence centre, change ~ t_nu(0, s); params (nu, s).
68 * F4 SCALE_MIX persistence centre, change ~ est_mix (k <= 3); params
69 * (k, w0, w1, w2, v0, v1, v2), unused w = v = 0.
70 * F5 ADAPTIVE_T persistence centre, change ~ t_nu(0, c*s_t),
71 * s_t^2 = lambda*s_{t-1}^2 + (1-lambda)*max(d^2, floor), d the
72 * last one-step grid change, updated only on two consecutive
73 * valid observations; params (lambda, nu, c, floor, s0).
74 * F3/F4/F5 H-step pmf = H-fold convolution of the DISCRETE one-step pmf (the
75 * sum of H iid grid changes is exactly the H-step grid change), by repeated
76 * squaring; mass beyond +-EST_PRED_K after each product is folded into the
77 * edge bins (edge bin = "at or beyond the edge"). F4 uses the convolution too,
78 * not the est_mix exact h-sum, so all persistence families share one rule.
79 * Documented approximation: mass in an edge bin ("at or beyond +-EST_PRED_K")
80 * is convolved as if it sat exactly at +-EST_PRED_K, so some tail mass moves
81 * inward on each squaring. Measured edge mass for F3 nu=1.5 s=10 mC: 1.5e-6
82 * at h=1, <= 4.4e-5 at h=64 (no effect on coverage; not exact).
83 * Finally every returned pmf is mixed with EST_PRED_FLOOR of uniform mass and
84 * renormalized: no outcome on the grid has zero probability, and the pmf sums
85 * to 1 within 1e-12.
86 *
87 * Observation classes (checked in this order): MISSING (caller says absent),
88 * NONFINITE, OUT_OF_RANGE (value < lo or > hi), OFF_GRID (|value/q - round|
89 * > EST_PRED_GRID_TOL), else OK. An OK value whose offset from the anchor is
90 * beyond +-EST_PRED_K is scored in the edge bin.
91 *
92 * Calibration (est_calib_verdict). Statistics are checked in this fixed order
93 * and the first failure is named: n, cov50, cov80, cov95, pit[0..9], bias
94 * (mean mid-PIT z), lag1 (lag-1 autocorrelation of z, from streaming sums:
95 * (S_xy/(n-1) - m^2) / (S_xx/n - m^2)).
96 * This library order (n first) is NOT the EST-3c v3 protocol's first-failing-
97 * statistic order (section 6 lists n last). The v3 tools apply the protocol
98 * order themselves (c3_judge in tools/estimation/est3c_common.c) and do not
99 * call est_calib_verdict.
100 *
101 * Bounded (pmf arrays of fixed size), no allocation, no globals; libm only.
102 * Not linked into the runtime; built by mk/estimation_v3.mk only. */
103#ifndef OMEGA_EST_PRED_H
104#define OMEGA_EST_PRED_H
105
106#include <stddef.h>
107#include <stdint.h>
108
109#include "est_types.h"
110#include "est_mix.h"
111
112#define EST_PRED_K 400
113#define EST_PRED_N (2 * EST_PRED_K + 1)
114#define EST_PRED_MAX_H 64u
115#define EST_PRED_NPARAM 8u
116#define EST_PRED_FLOOR 1e-12 /* uniform mass mixed into every pmf */
117#define EST_PRED_GRID_TOL 1e-6 /* in quanta */
118#define EST_DOMAIN_ASSUMPTION "omega.est.assumption.v1"
119
120typedef enum {
121 EST_FAM_GAUSS_KF = 1,
122 EST_FAM_HUBER_KF = 2,
123 EST_FAM_STUDENT_T = 3,
124 EST_FAM_SCALE_MIX = 4,
125 EST_FAM_ADAPTIVE_T = 5
126} est_family;
127
128/* ModelAssumption. nparam must equal the family's count (3, 4, 2, 7, 5);
129 * param[nparam..] must be 0. Variances in mC^2, scales in mC. */
130typedef struct {
131 est_family family;
132 est_unit unit; /* unit of the observed value */
133 double quantum; /* grid quantum, > 0, finite */
134 double lo, hi; /* valid observation range, lo < hi */
135 uint32_t nparam;
136 double param[EST_PRED_NPARAM];
137} est_assumption;
138
139typedef enum {
140 EST_OBS_OK = 0,
141 EST_OBS_MISSING = 1,
142 EST_OBS_NONFINITE = 2,
143 EST_OBS_OFF_GRID = 3,
144 EST_OBS_OUT_OF_RANGE = 4,
145 EST_OBS_CLASSES_ = 5
146} est_obs_class;
147
148/* Observation. value is kept exactly as received (NaN stays NaN). */
149typedef struct {
150 double value;
151 est_obs_class cls;
152 est_digest evidence; /* binds the raw bytes; must be non-zero */
153} est_pobs;
154
155/* BeliefState. Fields are the candidate's internal state; callers read but do
156 * not write them. cache holds a one-step pmf (no floor) reused while the
157 * scale that produced it (cache_key) is unchanged. */
158typedef struct {
159 est_digest assumption;
160 uint32_t has_anchor;
161 double anchor; /* last valid observation */
162 double xhat, P; /* F1/F2 level mean and variance */
163 double s2; /* F5 adaptive scale squared */
164 uint32_t gap; /* ticks since the last valid observation */
165 uint64_t generation; /* +1 per predict and per update */
166 est_digest evidence_root; /* chained over every observation's evidence */
167 uint64_t count[EST_OBS_CLASSES_];
168 uint32_t cache_valid;
169 double cache_key;
170 int32_t cache_lo, cache_hi; /* nonzero support of cache, as offsets */
171 double cache[EST_PRED_N];
172} est_bstate;
173
174/* Estimate: pmf[i] = P(next obs = anchor + (i - EST_PRED_K) * quantum). */
175typedef struct {
176 est_digest assumption;
177 est_family family;
178 uint32_t horizon; /* effective: ticks after the anchor */
179 uint64_t generation; /* state generation after this predict */
180 double anchor;
181 double quantum;
182 double pmf[EST_PRED_N];
183} est_dpred;
184
185/* Innovation. valid = 0 for a non-OK observation (nothing else is filled). */
186typedef struct {
187 uint32_t valid;
188 est_obs_class cls;
189 int32_t k; /* outcome offset, clipped to +-EST_PRED_K */
190 double F_lo, F_hi; /* P(Y < y), P(Y <= y) */
191 double logp; /* log p(y), p floored at 1e-300 */
192 double z; /* Phi^-1((F_lo+F_hi)/2), clipped to [-8,8] */
193} est_pinnov;
194
195typedef struct {
196 uint64_t n;
197 double cov[3]; /* fractional coverage sums: 0.50 0.80 0.95 */
198 double pit[10];
199 double logp_sum;
200 double width_sum; /* central 80 % width, mC */
201 double z_sum, z_sq, z_lag; /* sum z, sum z^2, sum z_t*z_{t-1} */
202 double z_prev;
203} est_calib;
204
205typedef struct {
206 double cov50[2], cov80[2], cov95[2];
207 double pit[2]; /* per-bin fraction band */
208 double bias_max; /* |mean z| */
209 double lag1_max; /* |lag-1 autocorrelation of z| */
210 uint64_t min_n;
211} est_bands;
212
213typedef enum { EST_NOT_CALIBRATED = 0, EST_CALIBRATED = 1 } est_verdict;
214
215/* ---- numerics (exposed for tests) ---- */
216/* regularized incomplete beta I_x(a,b); NaN on bad input or non-convergence */
217double est_betai(double a, double b, double x);
218/* Student-t (location 0, scale 1) CDF and upper tail P(T > t) */
219double est_t_cdf(double t, double nu);
220double est_t_sf(double t, double nu);
221double est_norm_cdf(double x);
222/* Phi^-1(p) by bisection on erfc, clipped to [-8, 8] (p <= 0 -> -8, >= 1 -> 8) */
223double est_norm_ppf(double p);
224
225/* ---- assumption ---- */
226est_status est_assumption_check(const est_assumption *a);
227est_status est_assumption_digest(const est_assumption *a, est_digest *out);
228
229/* ---- observation ---- */
230/* present = 0 means the sample is absent (MISSING); value is stored raw. */
231est_status est_pobs_classify(const est_assumption *a, double value, int present,
232 const est_digest *evidence, est_pobs *out);
233
234/* ---- candidate ---- */
235est_status est_pred_init(const est_assumption *a, est_bstate *b);
236est_status est_pred_predict(const est_assumption *a, est_bstate *b, uint32_t h,
237 est_dpred *out);
238/* Re-classifies obs->value; a record whose class disagrees is EST_ERR_KIND. */
239est_status est_pred_update(const est_assumption *a, est_bstate *b, const est_pobs *obs);
240/* Scores obs against p. p must be the one-tick forecast made from b's current
241 * state: same assumption, p->generation == b->generation and
242 * p->horizon == b->gap + 1, else EST_ERR_STALE. Call before est_pred_update. */
243est_status est_pred_innov(const est_bstate *b, const est_dpred *p, const est_pobs *obs,
244 est_pinnov *out);
245/* Scores obs against ANY estimate p (any horizon), no staleness check: fills
246 * out as est_pred_innov does (valid = 0 for a non-OK observation). Used for
247 * multi-step scoring and for tool-built baseline pmfs. */
248est_status est_dpred_score(const est_dpred *p, const est_pobs *obs, est_pinnov *out);
249/* H-fold convolution of a one-step grid pmf (EST_PRED_N bins, offset index
250 * EST_PRED_K = 0) by repeated squaring with edge folding as for F3/F4/F5; no
251 * uniform floor is applied. h in 1..EST_PRED_MAX_H, else EST_ERR_TIME. */
252est_status est_pmf_conv_pow(const double *one, uint32_t h, double *out);
253/* Mixes EST_PRED_FLOOR uniform mass into pmf and renormalizes (as predict does). */
254void est_pmf_floor(double *pmf);
255/* width in mC of the central 80 % grid interval (k at CDF >= 0.1 .. >= 0.9) */
256est_status est_dpred_width80(const est_dpred *p, double *mc);
257
258/* ---- calibration evidence ---- */
259void est_calib_init(est_calib *c);
260/* Fractional coverage of central alpha interval for one innovation. */
261double est_frac_cover(double F_lo, double F_hi, double alpha);
262/* adds one valid innovation (iv->valid must be 1) and the width of p */
263est_status est_calib_add(est_calib *c, const est_dpred *p, const est_pinnov *iv);
264void est_bands_default(est_bands *b);
265double est_calib_lag1(const est_calib *c);
266est_verdict est_calib_verdict(const est_calib *c, const est_bands *b, char *reason,
267 size_t cap);
268
269#endif /* OMEGA_EST_PRED_H */