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 / tools / estimation / est_replay.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 | #include "est_replay.h" |
| 18 | |
| 19 | #include <ctype.h> |
| 20 | #include <limits.h> |
| 21 | #include <stdlib.h> |
| 22 | #include <unistd.h> |
| 23 | #include <math.h> |
| 24 | #include <stdlib.h> |
| 25 | #include <string.h> |
| 26 | |
| 27 | #include "sha256.h" |
| 28 | |
| 29 | #define NS 1000000000ll |
| 30 | |
| 31 | void est_hex(const uint8_t *d, size_t n, char *out) |
| 32 | { |
| 33 | static const char h[] = "0123456789abcdef"; |
| 34 | for (size_t i = 0; i < n; i++) { out[2 * i] = h[d[i] >> 4]; out[2 * i + 1] = h[d[i] & 15]; } |
| 35 | out[2 * n] = 0; |
| 36 | } |
| 37 | |
| 38 | int est_sha_file_hex(const char *path, char out[65]) |
| 39 | { |
| 40 | FILE *fp = fopen(path, "rb"); |
| 41 | if (!fp) return 1; |
| 42 | sha256_ctx c; sha256_init(&c); |
| 43 | uint8_t buf[65536]; size_t n; |
| 44 | while ((n = fread(buf, 1, sizeof buf, fp)) > 0) sha256_update(&c, buf, n); |
| 45 | int bad = ferror(fp); |
| 46 | fclose(fp); |
| 47 | if (bad) return 1; |
| 48 | uint8_t d[32]; sha256_final(&c, d); |
| 49 | est_hex(d, 32, out); |
| 50 | return 0; |
| 51 | } |
| 52 | |
| 53 | static void setmsg(char *err, size_t cap, const char *fmt, const char *a, const char *b) |
| 54 | { |
| 55 | if (err && cap) snprintf(err, cap, fmt, a, b); |
| 56 | } |
| 57 | |
| 58 | /* Find "<hex> <name>" in dir/SHA256SUMS. Returns 0 when found. */ |
| 59 | int est_sums_lookup(const char *dir, const char *name, char hex[65]) |
| 60 | { |
| 61 | char p[1100]; |
| 62 | snprintf(p, sizeof p, "%s/SHA256SUMS", dir); |
| 63 | FILE *fp = fopen(p, "r"); |
| 64 | if (!fp) return 1; |
| 65 | char line[1024]; int found = 1; |
| 66 | while (fgets(line, sizeof line, fp)) { |
| 67 | size_t l = strlen(line); |
| 68 | while (l && (line[l - 1] == '\n' || line[l - 1] == '\r')) line[--l] = 0; |
| 69 | if (l > 66 && line[64] == ' ' && line[65] == ' ' && strcmp(line + 66, name) == 0) { |
| 70 | memcpy(hex, line, 64); hex[64] = 0; found = 0; break; |
| 71 | } |
| 72 | } |
| 73 | fclose(fp); |
| 74 | return found; |
| 75 | } |
| 76 | |
| 77 | int est_allow_run_b = 0; |
| 78 | int est_allow_heldout = 0; |
| 79 | |
| 80 | int est_path_is_heldout(const char *path) |
| 81 | { |
| 82 | char rp[PATH_MAX]; |
| 83 | if (strstr(path, EST_V2_HELDOUT_TAG)) return 1; |
| 84 | if (realpath(path, rp) && strstr(rp, EST_V2_HELDOUT_TAG)) return 1; |
| 85 | return 0; |
| 86 | } |
| 87 | |
| 88 | const char *est_run_b_id(void) |
| 89 | { |
| 90 | #ifdef EST_TEST_BUILD |
| 91 | const char *e = getenv("EST_TEST_B_ID"); if (e && *e) return e; |
| 92 | #endif |
| 93 | return EST_RUN_B_ID; |
| 94 | } |
| 95 | const char *est_run_b_raw_sha(void) |
| 96 | { |
| 97 | #ifdef EST_TEST_BUILD |
| 98 | const char *e = getenv("EST_TEST_B_RAW_SHA"); if (e && *e) return e; |
| 99 | #endif |
| 100 | return EST_RUN_B_RAW_SHA_DEFAULT; |
| 101 | } |
| 102 | const char *est_run_b_marks_sha(void) |
| 103 | { |
| 104 | #ifdef EST_TEST_BUILD |
| 105 | const char *e = getenv("EST_TEST_B_MARKS_SHA"); if (e && *e) return e; |
| 106 | #endif |
| 107 | return EST_RUN_B_MARKS_SHA_DEFAULT; |
| 108 | } |
| 109 | |
| 110 | /* Resolve symlinks and relative parts, then look for run B's id in any path |
| 111 | * component. The unresolved string is checked too. A path that cannot be |
| 112 | * resolved is judged on its raw text only (the open then fails anyway). */ |
| 113 | int est_path_is_run_b(const char *path) |
| 114 | { |
| 115 | char rp[PATH_MAX]; |
| 116 | if (strstr(path, est_run_b_id())) return 1; |
| 117 | if (realpath(path, rp) && strstr(rp, est_run_b_id())) return 1; |
| 118 | return 0; |
| 119 | } |
| 120 | |
| 121 | static int hex_is_run_b(const char *hex) |
| 122 | { |
| 123 | return strcmp(hex, est_run_b_raw_sha()) == 0 || strcmp(hex, est_run_b_marks_sha()) == 0; |
| 124 | } |
| 125 | |
| 126 | static int read_index(const char *path, est_file *f, char *err, size_t errcap); |
| 127 | |
| 128 | int est_file_load(const char *path, est_file *f, char *err, size_t errcap) |
| 129 | { |
| 130 | memset(f, 0, sizeof *f); |
| 131 | if (strlen(path) >= sizeof f->path) { setmsg(err, errcap, "%s: path too long%s", path, ""); return 1; } |
| 132 | char dir[1024]; const char *slash = strrchr(path, '/'); |
| 133 | const char *name = slash ? slash + 1 : path; |
| 134 | if (slash) { size_t n = (size_t)(slash - path); memcpy(dir, path, n); dir[n] = 0; } |
| 135 | else snprintf(dir, sizeof dir, "."); |
| 136 | if (!est_allow_heldout && est_path_is_heldout(path)) { |
| 137 | setmsg(err, errcap, "%s: resolves into the held-out run; only est_eval --protocol-v2 --recorded may open it%s", path, ""); |
| 138 | return 1; |
| 139 | } |
| 140 | if (!est_allow_run_b && est_path_is_run_b(path)) { |
| 141 | setmsg(err, errcap, "%s: resolves into run B; only est_eval --recorded may open run B%s", path, ""); |
| 142 | return 1; |
| 143 | } |
| 144 | char want[65]; |
| 145 | if (est_sums_lookup(dir, name, want)) { setmsg(err, errcap, "%s: no SHA256SUMS line for %s", dir, name); return 1; } |
| 146 | if (!est_allow_run_b && hex_is_run_b(want)) { |
| 147 | setmsg(err, errcap, "%s: SHA256SUMS names run B's digest; refused before opening%s", path, ""); |
| 148 | return 1; |
| 149 | } |
| 150 | if (read_index(path, f, err, errcap)) return 1; |
| 151 | if (strcmp(f->sha_hex, want) != 0) { |
| 152 | setmsg(err, errcap, "SHA-256 mismatch for %s (SHA256SUMS says %s)", path, want); |
| 153 | est_file_free(f); |
| 154 | return 1; |
| 155 | } |
| 156 | if (!est_allow_run_b && hex_is_run_b(f->sha_hex)) { |
| 157 | setmsg(err, errcap, "%s: content is run B; refused%s", path, ""); |
| 158 | est_file_free(f); |
| 159 | return 1; |
| 160 | } |
| 161 | return 0; |
| 162 | } |
| 163 | |
| 164 | int est_file_load_raw(const char *path, est_file *f, char *err, size_t errcap) |
| 165 | { |
| 166 | memset(f, 0, sizeof *f); |
| 167 | if (strlen(path) >= sizeof f->path) { setmsg(err, errcap, "%s: path too long%s", path, ""); return 1; } |
| 168 | return read_index(path, f, err, errcap); |
| 169 | } |
| 170 | |
| 171 | static int read_index(const char *path, est_file *f, char *err, size_t errcap) |
| 172 | { |
| 173 | snprintf(f->path, sizeof f->path, "%s", path); |
| 174 | FILE *fp = fopen(path, "rb"); |
| 175 | if (!fp) { setmsg(err, errcap, "cannot open %s%s", path, ""); return 1; } |
| 176 | size_t cap = 1u << 20, len = 0; |
| 177 | uint8_t *buf = malloc(cap); |
| 178 | if (!buf) { fclose(fp); return 1; } |
| 179 | for (;;) { |
| 180 | if (len == cap) { cap *= 2; uint8_t *nb = realloc(buf, cap); if (!nb) { free(buf); fclose(fp); return 1; } buf = nb; } |
| 181 | size_t n = fread(buf + len, 1, cap - len, fp); |
| 182 | if (n == 0) break; |
| 183 | len += n; |
| 184 | } |
| 185 | fclose(fp); |
| 186 | uint8_t d[32]; sha256_hash(buf, len, d); |
| 187 | est_hex(d, 32, f->sha_hex); |
| 188 | f->data = buf; f->len = len; |
| 189 | size_t nl = 0; |
| 190 | for (size_t i = 0; i < len; i++) if (buf[i] == '\n') nl++; |
| 191 | if (len && buf[len - 1] != '\n') nl++; |
| 192 | f->off = malloc((nl + 1) * sizeof(size_t)); f->llen = malloc((nl + 1) * sizeof(size_t)); |
| 193 | if (!f->off || !f->llen) { est_file_free(f); return 1; } |
| 194 | size_t k = 0, start = 0; |
| 195 | for (size_t i = 0; i < len; i++) if (buf[i] == '\n') { f->off[k] = start; f->llen[k] = i - start; k++; start = i + 1; } |
| 196 | if (start < len) { f->off[k] = start; f->llen[k] = len - start; k++; } |
| 197 | f->nlines = k; |
| 198 | return 0; |
| 199 | } |
| 200 | |
| 201 | void est_file_free(est_file *f) |
| 202 | { |
| 203 | free(f->data); free(f->off); free(f->llen); |
| 204 | memset(f, 0, sizeof *f); |
| 205 | } |
| 206 | |
| 207 | int est_parse_time_prefix(const char *s, size_t len, int64_t *t_ns, size_t *used) |
| 208 | { |
| 209 | size_t i = 0; int64_t sec = 0; |
| 210 | while (i < len && s[i] >= '0' && s[i] <= '9') { |
| 211 | if (i >= 10) return 2; /* more than 10 seconds digits */ |
| 212 | sec = sec * 10 + (s[i] - '0'); i++; |
| 213 | } |
| 214 | if (i == 0 || i >= len || s[i] != '.') return 1; |
| 215 | i++; |
| 216 | int64_t frac = 0; |
| 217 | for (int k = 0; k < 9; k++, i++) { |
| 218 | if (i >= len || s[i] < '0' || s[i] > '9') return 1; |
| 219 | frac = frac * 10 + (s[i] - '0'); |
| 220 | } |
| 221 | if (i < len && s[i] >= '0' && s[i] <= '9') return 1; /* more than nine digits */ |
| 222 | if (sec > 9223372035ll) return 2; /* sec * 1e9 must fit int64 */ |
| 223 | *t_ns = sec * NS + frac; |
| 224 | if (used) *used = i; |
| 225 | return 0; |
| 226 | } |
| 227 | |
| 228 | int est_parse_t(const char *line, size_t len, int64_t *t_ns) |
| 229 | { |
| 230 | static const char pre[] = "{\"t\":"; |
| 231 | if (len < sizeof pre - 1 || memcmp(line, pre, sizeof pre - 1) != 0) return 1; |
| 232 | size_t used; |
| 233 | int pr = est_parse_time_prefix(line + 5, len - 5, t_ns, &used); |
| 234 | if (pr) return pr; |
| 235 | size_t e = 5 + used; |
| 236 | if (e >= len || (line[e] != ',' && line[e] != '}')) return 1; |
| 237 | return 0; |
| 238 | } |
| 239 | |
| 240 | int est_parse_thermal0(const char *line, size_t len, double *value) |
| 241 | { |
| 242 | static const char key[] = "\"thermal_mc\":\""; |
| 243 | size_t kl = sizeof key - 1; |
| 244 | if (len < kl) return 1; |
| 245 | size_t at = (size_t)-1; |
| 246 | for (size_t i = 0; i + kl <= len; i++) if (memcmp(line + i, key, kl) == 0) { at = i + kl; break; } |
| 247 | if (at == (size_t)-1) return 1; |
| 248 | char tok[40]; size_t n = 0; |
| 249 | while (at + n < len && line[at + n] != ' ' && line[at + n] != '"') { |
| 250 | char c = line[at + n]; |
| 251 | if (!(isdigit((unsigned char)c) || c == '+' || c == '-' || c == '.' || c == 'e' || c == 'E')) return 1; |
| 252 | if (n >= sizeof tok - 1) return 1; |
| 253 | tok[n] = c; n++; |
| 254 | } |
| 255 | if (n == 0) return 1; |
| 256 | tok[n] = 0; |
| 257 | char *end; double v = strtod(tok, &end); |
| 258 | if (*end != 0 || !isfinite(v)) return 1; |
| 259 | *value = v; |
| 260 | return 0; |
| 261 | } |
| 262 | |
| 263 | double est_grid_q(int i) { return pow(10.0, -3.0 + 0.5 * (double)i); } |
| 264 | double est_grid_r(int j) { return pow(10.0, 0.25 * (double)j); } |
| 265 | |
| 266 | int est_make_model(int model_id, double q, double r, est_model *m) |
| 267 | { |
| 268 | memset(m, 0, sizeof *m); |
| 269 | m->estimator = EST_ESTIMATOR_LINEAR_KALMAN; |
| 270 | m->meaning = EST_UNCERTAINTY_GAUSSIAN_COVARIANCE; |
| 271 | m->step_ns = NS; |
| 272 | m->m = 1; |
| 273 | m->obs_unit[0] = EST_UNIT_MILLI_CELSIUS; |
| 274 | m->state_unit[0] = EST_UNIT_MILLI_CELSIUS; |
| 275 | m->R[0] = r; |
| 276 | if (model_id == 0 || model_id == 2) { /* M2 (protocol v2): M0 structure, r = 1e-12 */ |
| 277 | m->n = 1; m->F[0] = 1.0; m->Q[0] = q; m->H[0] = 1.0; |
| 278 | } else if (model_id == 1) { |
| 279 | m->n = 2; |
| 280 | m->state_unit[1] = EST_UNIT_MILLI_CELSIUS_PER_S; |
| 281 | m->F[0] = 1.0; m->F[1] = 1.0; m->F[2] = 0.0; m->F[3] = 1.0; |
| 282 | m->Q[0] = q / 3.0; m->Q[1] = q / 2.0; m->Q[2] = q / 2.0; m->Q[3] = q; |
| 283 | m->H[0] = 1.0; m->H[1] = 0.0; |
| 284 | } else return 1; |
| 285 | return 0; |
| 286 | } |
| 287 | |
| 288 | static int digest_eq(const est_digest *a, const est_digest *b) { return memcmp(a->b, b->b, EST_DIGEST_SIZE) == 0; } |
| 289 | |
| 290 | static int fail(est_replay *rp, const char *what, size_t line, est_status st) |
| 291 | { |
| 292 | rp->error = 1; |
| 293 | snprintf(rp->errmsg, sizeof rp->errmsg, "%s at line %zu (status %d)", what, line, (int)st); |
| 294 | return 1; |
| 295 | } |
| 296 | |
| 297 | int est_replay_run(const est_file *f, size_t limit, int model_id, double q, double r, est_replay *rp) |
| 298 | { |
| 299 | est_step *keep = rp->steps; size_t cap = rp->cap; |
| 300 | memset(rp, 0, sizeof *rp); |
| 301 | rp->steps = keep; rp->cap = cap; |
| 302 | size_t nl = f->nlines < limit ? f->nlines : limit; |
| 303 | rp->lines_used = nl; |
| 304 | if (est_make_model(model_id, q, r, &rp->model)) return fail(rp, "bad model", 0, EST_ERR_MODEL); |
| 305 | est_status st = est_digest_model(&rp->model, &rp->model_d); |
| 306 | if (st != EST_OK) return fail(rp, "model digest", 0, st); |
| 307 | if (rp->cap < nl + 1) { |
| 308 | est_step *ns = realloc(rp->steps, (nl + 1) * sizeof *ns); |
| 309 | if (!ns) return fail(rp, "out of memory", 0, EST_OK); |
| 310 | rp->steps = ns; rp->cap = nl + 1; |
| 311 | } |
| 312 | uint8_t src[32]; est_digest source; |
| 313 | sha256_hash((const uint8_t *)EST_SOURCE_TEXT, strlen(EST_SOURCE_TEXT), src); |
| 314 | memcpy(source.b, src, 32); |
| 315 | |
| 316 | est_belief bel; int have = 0; |
| 317 | int64_t prev_wall = 0; int prev_ok = 0; |
| 318 | size_t first = 0; |
| 319 | for (size_t li = 0; li < nl; li++) { |
| 320 | const char *ln = (const char *)f->data + f->off[li]; |
| 321 | size_t ll = f->llen[li]; |
| 322 | double z = 0; int64_t wall = 0; |
| 323 | int tr = est_parse_t(ln, ll, &wall); |
| 324 | int t_ok = (tr == 0); |
| 325 | int v_parsed = (est_parse_thermal0(ln, ll, &z) == 0); |
| 326 | /* a line whose t fails to parse is a missing observation even when the value parses */ |
| 327 | int v_ok = v_parsed && t_ok; |
| 328 | if (!t_ok) { rp->bad_t++; if (tr == 2) rp->bad_t_overflow++; } |
| 329 | if (!v_parsed) rp->bad_value++; |
| 330 | uint8_t ev[32]; sha256_hash((const uint8_t *)ln, ll, ev); |
| 331 | if (!have) { |
| 332 | if (!v_ok) { rp->leading_missing++; if (t_ok) { prev_wall = wall; prev_ok = 1; } continue; } |
| 333 | double x0[2] = { z, 0.0 }, P0[4] = { 0 }; |
| 334 | if (model_id != 1) P0[0] = r; else { P0[0] = r; P0[3] = 1e6; } |
| 335 | st = est_kf_prior(&rp->model, x0, P0, 0, &bel); |
| 336 | if (st != EST_OK) return fail(rp, "prior", li, st); |
| 337 | first = li; have = 1; |
| 338 | est_step *s = &rp->steps[rp->nsteps++]; |
| 339 | memset(s, 0, sizeof *s); |
| 340 | s->line = li; s->L = 0; s->prior = 1; s->t_ok = t_ok; s->wall_ns = t_ok ? wall : 0; |
| 341 | s->horizon = 0; s->t_ns = 0; s->z = z; s->post = bel; s->chain_ok = 1; |
| 342 | memcpy(s->evidence.b, ev, 32); |
| 343 | st = est_digest_belief(&bel, &s->belief_d); |
| 344 | if (st != EST_OK) return fail(rp, "belief digest", li, st); |
| 345 | if (t_ok) { prev_wall = wall; prev_ok = 1; } else { prev_ok = 0; } |
| 346 | continue; |
| 347 | } |
| 348 | /* logical-grid horizon from the raw wall gap */ |
| 349 | uint32_t h = 1; |
| 350 | if (t_ok && prev_ok) { |
| 351 | int64_t gap = wall - prev_wall; |
| 352 | if (gap == 0) rp->gap_zero++; |
| 353 | else if (gap < 0) rp->gap_backward++; |
| 354 | if (gap > 0) { |
| 355 | int64_t hr = (gap + NS / 2) / NS; /* round half up */ |
| 356 | if (hr < 1) hr = 1; |
| 357 | if (hr > 1000000) hr = 1000000; |
| 358 | h = (uint32_t)hr; |
| 359 | } |
| 360 | } |
| 361 | if (h > 1) rp->multi_horizon++; |
| 362 | if (t_ok) { prev_wall = wall; prev_ok = 1; } |
| 363 | else if (prev_ok) prev_wall += NS; /* unparsable t: assume one nominal step */ |
| 364 | |
| 365 | est_step *s = &rp->steps[rp->nsteps++]; |
| 366 | memset(s, 0, sizeof *s); |
| 367 | s->line = li; s->L = li - first; s->t_ok = t_ok; s->wall_ns = t_ok ? wall : 0; s->horizon = h; |
| 368 | memcpy(s->evidence.b, ev, 32); |
| 369 | est_prediction pred; |
| 370 | st = est_kf_predict(&rp->model, &bel, NULL, h, &pred); |
| 371 | if (st != EST_OK) return fail(rp, "predict", li, st); |
| 372 | st = est_digest_prediction(&pred, &s->pred_d); |
| 373 | if (st != EST_OK) return fail(rp, "prediction digest", li, st); |
| 374 | s->t_ns = pred.t_ns; |
| 375 | est_belief post; |
| 376 | if (!v_ok) { |
| 377 | s->coast = 1; rp->coasts++; |
| 378 | st = est_kf_coast(&rp->model, &pred, &bel, &post); |
| 379 | if (st != EST_OK) return fail(rp, "coast", li, st); |
| 380 | s->chain_ok = 1; |
| 381 | } else { |
| 382 | est_observation o; memset(&o, 0, sizeof o); |
| 383 | o.m = 1; o.unit[0] = EST_UNIT_MILLI_CELSIUS; o.z[0] = z; o.R[0] = r; |
| 384 | o.t_ns = pred.t_ns; o.seq = (uint64_t)li; o.source = source; |
| 385 | memcpy(o.evidence.b, ev, 32); |
| 386 | est_innovation iv; |
| 387 | st = est_kf_update(&rp->model, &bel, &pred, &o, &post, &iv); |
| 388 | if (st != EST_OK) return fail(rp, "update", li, st); |
| 389 | est_status s1 = est_digest_observation(&o, &s->obs_d); |
| 390 | est_status s2 = est_digest_innovation(&iv, &s->innov_d); |
| 391 | if (s1 != EST_OK || s2 != EST_OK) return fail(rp, "digest", li, s1 != EST_OK ? s1 : s2); |
| 392 | s->z = z; s->y_mean = pred.y_mean[0]; s->S = iv.S[0]; s->nu = iv.nu[0]; s->nis = iv.nis; |
| 393 | s->chain_ok = digest_eq(&iv.prediction, &s->pred_d) && digest_eq(&iv.observation, &s->obs_d) |
| 394 | && digest_eq(&o.evidence, &s->evidence) && (iv.nu[0] == z - pred.y_mean[0]); |
| 395 | } |
| 396 | s->post = post; |
| 397 | st = est_digest_belief(&post, &s->belief_d); |
| 398 | if (st != EST_OK) return fail(rp, "belief digest", li, st); |
| 399 | bel = post; |
| 400 | } |
| 401 | if (!have) return fail(rp, "no valid observation in the file", 0, EST_OK); |
| 402 | return 0; |
| 403 | } |
| 404 | |
| 405 | void est_replay_free(est_replay *rp) { free(rp->steps); memset(rp, 0, sizeof *rp); } |
| 406 | |
| 407 | void est_replay_write_stream(FILE *fp, const est_replay *rp, int model_id) |
| 408 | { |
| 409 | char a[65], b[65], c[65], d[65]; |
| 410 | for (size_t i = 0; i < rp->nsteps; i++) { |
| 411 | const est_step *s = &rp->steps[i]; |
| 412 | est_hex(s->obs_d.b, 32, a); est_hex(s->pred_d.b, 32, b); |
| 413 | est_hex(s->innov_d.b, 32, c); est_hex(s->belief_d.b, 32, d); |
| 414 | fprintf(fp, "M%d line=%zu L=%zu %s t_ns=%lld h=%u z=%.17g y=%.17g S=%.17g nu=%.17g nis=%.17g obs=%s pred=%s innov=%s belief=%s\n", |
| 415 | model_id, s->line, s->L, s->prior ? "prior" : (s->coast ? "coast" : "obs"), |
| 416 | (long long)s->t_ns, s->horizon, s->z, s->y_mean, s->S, s->nu, s->nis, a, b, c, d); |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | int est_params_write(const char *path, const est_params *p) |
| 421 | { |
| 422 | FILE *fp = fopen(path, "wb"); |
| 423 | if (!fp) return 1; |
| 424 | fprintf(fp, "est_params_v1\nprotocol_commit %s\nfit_run_path %s\nfit_file_sha256 %s\nfit_lines %zu\n", |
| 425 | EST_PROTOCOL_COMMIT, p->fit_path, p->fit_sha, p->fit_lines); |
| 426 | for (int m = 0; m < 2; m++) |
| 427 | fprintf(fp, "M%d q %.17g r %.17g loglik %.17g\n", m, p->q[m], p->r[m], p->ll[m]); |
| 428 | return fclose(fp) != 0; |
| 429 | } |
| 430 | |
| 431 | int est_fit_pick(const double ll[EST_NQ][EST_NR], int *bi, int *bj) |
| 432 | { |
| 433 | double best = -INFINITY; int pi = -1, pj = -1; |
| 434 | for (int i = 0; i < EST_NQ; i++) |
| 435 | for (int j = 0; j < EST_NR; j++) { |
| 436 | if (!isfinite(ll[i][j])) continue; |
| 437 | if (ll[i][j] > best) { best = ll[i][j]; pi = i; pj = j; } /* strict: ties keep the earlier */ |
| 438 | } |
| 439 | if (pi < 0) return 1; |
| 440 | *bi = pi; *bj = pj; |
| 441 | return 0; |
| 442 | } |
| 443 | |
| 444 | static int is_hex64(const char *s) |
| 445 | { |
| 446 | if (strlen(s) != 64) return 0; |
| 447 | for (int i = 0; i < 64; i++) if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0; |
| 448 | return 1; |
| 449 | } |
| 450 | |
| 451 | /* Exactly: header, protocol_commit, fit_run_path, fit_file_sha256, fit_lines, |
| 452 | * M0, M1, in that order, nothing else. */ |
| 453 | int est_params_read(const char *path, est_params *p) |
| 454 | { |
| 455 | memset(p, 0, sizeof *p); |
| 456 | FILE *fp = fopen(path, "r"); |
| 457 | if (!fp) return 1; |
| 458 | char line[1300]; int idx = 0, bad = 0; |
| 459 | while (fgets(line, sizeof line, fp)) { |
| 460 | size_t l = strlen(line); |
| 461 | if (l == 0 || line[l - 1] != '\n') { bad = 1; break; } |
| 462 | line[--l] = 0; |
| 463 | switch (idx) { |
| 464 | case 0: if (strcmp(line, "est_params_v1") != 0) bad = 1; break; |
| 465 | case 1: if (strcmp(line, "protocol_commit " EST_PROTOCOL_COMMIT) != 0) bad = 1; break; |
| 466 | case 2: |
| 467 | if (strncmp(line, "fit_run_path ", 13) != 0 || l - 13 == 0 || l - 13 >= sizeof p->fit_path) bad = 1; |
| 468 | else snprintf(p->fit_path, sizeof p->fit_path, "%.1023s", line + 13); |
| 469 | break; |
| 470 | case 3: |
| 471 | if (strncmp(line, "fit_file_sha256 ", 16) != 0 || !is_hex64(line + 16)) bad = 1; |
| 472 | else memcpy(p->fit_sha, line + 16, 65); |
| 473 | break; |
| 474 | case 4: { |
| 475 | char *end; |
| 476 | if (strncmp(line, "fit_lines ", 10) != 0) { bad = 1; break; } |
| 477 | p->fit_lines = (size_t)strtoull(line + 10, &end, 10); |
| 478 | if (*end || end == line + 10) bad = 1; |
| 479 | break; } |
| 480 | case 5: case 6: { |
| 481 | int m = idx - 5, used = 0; |
| 482 | char tag[4]; snprintf(tag, sizeof tag, "M%d", m); |
| 483 | if (strncmp(line, tag, 2) != 0 || |
| 484 | sscanf(line + 2, " q %lf r %lf loglik %lf%n", &p->q[m], &p->r[m], &p->ll[m], &used) != 3 || |
| 485 | line[2 + used] != 0) bad = 1; |
| 486 | break; } |
| 487 | default: bad = 1; |
| 488 | } |
| 489 | if (bad) break; |
| 490 | idx++; |
| 491 | } |
| 492 | fclose(fp); |
| 493 | return (!bad && idx == 7) ? 0 : 1; |
| 494 | } |
| 495 | |
| 496 | int est_params_validate(const est_params *p, char *err, size_t cap) |
| 497 | { |
| 498 | for (int m = 0; m < 2; m++) { |
| 499 | double q = p->q[m], r = p->r[m]; |
| 500 | if (!isfinite(q) || !isfinite(r) || q <= 0 || r <= 0) { snprintf(err, cap, "M%d: q or r not finite and positive", m); return 1; } |
| 501 | int i = (int)floor((log10(q) + 3.0) / 0.5 + 0.5), j = (int)floor(log10(r) / 0.25 + 0.5); |
| 502 | if (i < 0 || i >= EST_NQ || fabs(q - est_grid_q(i)) > 1e-9 * est_grid_q(i)) { snprintf(err, cap, "M%d: q %.17g is not on the protocol grid", m, q); return 1; } |
| 503 | if (j < 0 || j >= EST_NR || fabs(r - est_grid_r(j)) > 1e-9 * est_grid_r(j)) { snprintf(err, cap, "M%d: r %.17g is not on the protocol grid", m, r); return 1; } |
| 504 | } |
| 505 | return 0; |
| 506 | } |
| 507 | |
| 508 | /* ---- protocol v2 ---- */ |
| 509 | size_t est_m2_changes(const est_replay *rp, double *e, size_t cap) |
| 510 | { |
| 511 | size_t n = 0; double prev = 0; int have = 0; |
| 512 | for (size_t i = 0; i < rp->nsteps; i++) { |
| 513 | const est_step *s = &rp->steps[i]; |
| 514 | if (s->coast) continue; |
| 515 | if (!s->prior && have && memcmp(&s->y_mean, &prev, sizeof prev) != 0 && s->L >= EST_BURN_IN) return (size_t)-1; |
| 516 | if (!s->prior && s->L >= EST_BURN_IN && s->horizon == 1 && n < cap) e[n++] = s->nu; |
| 517 | prev = s->z; have = 1; |
| 518 | } |
| 519 | return n; |
| 520 | } |
| 521 | |
| 522 | int est_params2_write(const char *path, const est_params2 *p) |
| 523 | { |
| 524 | FILE *fp = fopen(path, "wb"); |
| 525 | if (!fp) return 1; |
| 526 | fprintf(fp, "est_params_v2\nv1_params_path %s\nv1_params_sha256 %s\nfit_run_path %s\nfit_file_sha256 %s\nfit_lines %zu\nfit_changes %zu\n", |
| 527 | p->v1_params_path, p->v1_params_sha, p->fit_path, p->fit_sha, p->fit_lines, p->fit_n); |
| 528 | fprintf(fp, "M2 q %.17g r %.17g k %u loglik %.17g\n", p->q, p->r, p->mix.k, p->ll); |
| 529 | for (uint32_t j = 0; j < p->mix.k; j++) fprintf(fp, "c%u w %.17g v %.17g\n", j, p->mix.w[j], p->mix.v[j]); |
| 530 | return fclose(fp) != 0; |
| 531 | } |
| 532 | |
| 533 | static int str_field(const char *line, const char *key, char *dst, size_t cap) |
| 534 | { |
| 535 | size_t kl = strlen(key), l = strlen(line); |
| 536 | if (strncmp(line, key, kl) != 0 || line[kl] != ' ' || l - kl - 1 == 0 || l - kl - 1 >= cap) return 1; |
| 537 | memcpy(dst, line + kl + 1, l - kl); /* includes the terminator */ |
| 538 | return 0; |
| 539 | } |
| 540 | static int size_field(const char *line, const char *key, size_t *out) |
| 541 | { |
| 542 | size_t kl = strlen(key); char *end; |
| 543 | if (strncmp(line, key, kl) != 0 || line[kl] != ' ' || !line[kl + 1]) return 1; |
| 544 | *out = (size_t)strtoull(line + kl + 1, &end, 10); |
| 545 | return *end != 0; |
| 546 | } |
| 547 | |
| 548 | int est_params2_read(const char *path, est_params2 *p) |
| 549 | { |
| 550 | memset(p, 0, sizeof *p); |
| 551 | FILE *fp = fopen(path, "r"); |
| 552 | if (!fp) return 1; |
| 553 | char line[1300]; int idx = 0, bad = 0, total = 8; |
| 554 | while (fgets(line, sizeof line, fp)) { |
| 555 | size_t l = strlen(line); |
| 556 | if (l == 0 || line[l - 1] != '\n') { bad = 1; break; } |
| 557 | line[--l] = 0; |
| 558 | int used = 0; |
| 559 | switch (idx) { |
| 560 | case 0: bad = strcmp(line, "est_params_v2") != 0; break; |
| 561 | case 1: bad = str_field(line, "v1_params_path", p->v1_params_path, sizeof p->v1_params_path); break; |
| 562 | case 2: bad = str_field(line, "v1_params_sha256", p->v1_params_sha, sizeof p->v1_params_sha) || !is_hex64(p->v1_params_sha); break; |
| 563 | case 3: bad = str_field(line, "fit_run_path", p->fit_path, sizeof p->fit_path); break; |
| 564 | case 4: bad = str_field(line, "fit_file_sha256", p->fit_sha, sizeof p->fit_sha) || !is_hex64(p->fit_sha); break; |
| 565 | case 5: bad = size_field(line, "fit_lines", &p->fit_lines); break; |
| 566 | case 6: bad = size_field(line, "fit_changes", &p->fit_n); break; |
| 567 | case 7: |
| 568 | if (sscanf(line, "M2 q %lf r %lf k %u loglik %lf%n", &p->q, &p->r, &p->mix.k, &p->ll, &used) != 4 || line[used] != 0 |
| 569 | || p->mix.k < 1 || p->mix.k > EST_MIX_MAX) bad = 1; |
| 570 | else total = 8 + (int)p->mix.k; |
| 571 | break; |
| 572 | default: { |
| 573 | unsigned j; |
| 574 | if (idx >= total || sscanf(line, "c%u w %lf v %lf%n", &j, &p->mix.w[idx - 8], &p->mix.v[idx - 8], &used) != 3 |
| 575 | || line[used] != 0 || j != (unsigned)(idx - 8)) bad = 1; |
| 576 | break; } |
| 577 | } |
| 578 | if (bad) break; |
| 579 | idx++; |
| 580 | } |
| 581 | fclose(fp); |
| 582 | return (!bad && idx == total && idx > 8) ? 0 : 1; |
| 583 | } |
| 584 | |
| 585 | #ifdef EST_REPLAY_MAIN |
| 586 | /* est_replay <model 0|1|2> <q> <r> <machine-state.ndjson> |
| 587 | * Prints the full observation/prediction/innovation stream, one line per step. |
| 588 | * Never opens run B (est_eval --recorded writes run B's streams itself). */ |
| 589 | int main(int argc, char **argv) |
| 590 | { |
| 591 | if (argc != 5) { fprintf(stderr, "usage: est_replay model q r file\n"); return 2; } |
| 592 | char *e1, *e2, *e3; |
| 593 | long mid = strtol(argv[1], &e1, 10); |
| 594 | double q = strtod(argv[2], &e2), r = strtod(argv[3], &e3); |
| 595 | if (*e1 || *e2 || *e3 || (mid < 0 || mid > 2)) { fprintf(stderr, "bad model, q or r\n"); return 2; } |
| 596 | est_file f; char err[300]; |
| 597 | if (est_file_load(argv[4], &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; } |
| 598 | static est_replay rp; |
| 599 | if (est_replay_run(&f, (size_t)-1, (int)mid, q, r, &rp)) { |
| 600 | fprintf(stderr, "replay failed: %s\n", rp.errmsg); return 1; |
| 601 | } |
| 602 | est_replay_write_stream(stdout, &rp, (int)mid); |
| 603 | fprintf(stderr, "steps=%zu coasts=%zu leading_missing=%zu bad_value=%zu bad_t=%zu\n", |
| 604 | rp.nsteps, rp.coasts, rp.leading_missing, rp.bad_value, rp.bad_t); |
| 605 | return 0; |
| 606 | } |
| 607 | #endif |