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 / tools / estimation / est4.c

731 lines · 40030 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 v4 tool (protocol docs/estimation/protocols/est-v4.md).
18 *
19 * est4 fit --raw <D1>/machine-state.ndjson --marks <D1>/machine-state-marks.txt
20 * --out <params.txt> [--synthetic-test [--grid-stride N]]
21 * Protocol section 5: two-stage grid fit of G1, G2, G3 on D1, the v3 F1
22 * grid and the E0 histogram, in-sample screen (v3 section 6 rules,
23 * c3_judge), selection, PHASE_A verdict. Binding mode refuses: a dirty
24 * tree (build time and run time), a compiled protocol SHA that differs
25 * from the doc on disk, no compiled D1 identity, inputs whose SHA-256
26 * differs from it or whose path lacks the D1 tag, an existing output.
27 * Every mode refuses a held-out path (v4 or v3 tag) before opening
28 * anything.
29 * est4 precheck --dir <D>
30 * v3 section 7 pre-check (c3_precheck; never reads thermal values).
31 * est4 recorded --dir <D2> --params <params.txt> --outdir <receipts/est-v4>
32 * [--synthetic-test]
33 * The single scored run: S, F1 and E0 on D2 with D1-frozen parameters.
34 * est4 make-synthetic <dir> [--seed N] [--lines N]
35 * Synthetic run folder (tests only), c3_synth_write.
36 */
37#include <dirent.h>
38#include <errno.h>
39#include <limits.h>
40#include <math.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44
45#include "est3c_common.h"
46#include "est_v4.h"
47#include "sha256.h"
48
49#ifndef TOOL_COMMIT
50#define TOOL_COMMIT "unknown"
51#endif
52#ifndef TOOL_DIRTY
53#define TOOL_DIRTY 1
54#endif
55#ifndef E4_PROTOCOL_SHA
56#define E4_PROTOCOL_SHA "unknown"
57#endif
58#ifndef E4_D1_RAW_SHA
59#define E4_D1_RAW_SHA "absent"
60#endif
61#ifndef E4_D1_MARKS_SHA
62#define E4_D1_MARKS_SHA "absent"
63#endif
64#ifndef E4_D2_RAW_SHA
65#define E4_D2_RAW_SHA "absent"
66#endif
67#ifndef E4_D2_MARKS_SHA
68#define E4_D2_MARKS_SHA "absent"
69#endif
70#ifndef E4_D2_SCHED_SHA
71#define E4_D2_SCHED_SHA "absent"
72#endif
73#ifndef E4_PARAMS_SHA
74#define E4_PARAMS_SHA "absent"
75#endif
76#ifndef E4_REPO_ROOT
77#define E4_REPO_ROOT "unknown"
78#endif
79
80#define E4_PROTOCOL_DOC "docs/estimation/protocols/est-v4.md"
81#define E4_RECEIPT_SUBDIR "docs/estimation/receipts/est-v4"
82#define E4_FIT_TAG "-est4-fit-"
83#define E4_HELDOUT_TAG "-est4-heldout-"
84#define E4_AGREE 1e-6 /* fast vs pmf mean log score, nats/step */
85
86static const char *envor(const char *name, const char *dflt)
87{
88#ifdef E4_TEST_BUILD
89 const char *e = getenv(name); if (e) return e;
90#else
91 (void)name;
92#endif
93 return dflt;
94}
95
96static int tool_dirty(void)
97{
98 static int cached = -1;
99#ifdef E4_TEST_BUILD
100 const char *e = getenv("E4_TEST_DIRTY"); if (e && *e) return atoi(e);
101#endif
102 if (cached < 0) cached = TOOL_DIRTY ? TOOL_DIRTY : c3_tree_dirty_now();
103 return cached;
104}
105
106/* held-out: the v4 tag or the v3 tag, on the path as given or resolved */
107static int e4_heldout(const char *path)
108{
109 char rp[PATH_MAX];
110 if (strstr(path, E4_HELDOUT_TAG) || strstr(path, C3_HELDOUT_TAG)) return 1;
111 if (realpath(path, rp) && (strstr(rp, E4_HELDOUT_TAG) || strstr(rp, C3_HELDOUT_TAG))) return 1;
112 return 0;
113}
114
115/* ------------------------------------------------------------ grids (s5) */
116static const double G1_TAU[] = { 0.5, 1, 2, 4, 10, 30 };
117static const double G2_RHO[] = { 0, 0.2, 0.4, 0.6, 0.8, 0.9 };
118static const double G3_TAU[] = { 0.5, 1, 2, 4, 10 };
119#define NQ4 9 /* q = 10^(2 + 0.5 i) */
120static const double LAM4[] = { 0.1, 0.2, 0.3, 0.5, 0.7, 0.9 };
121static const double NU4[] = { 0.8, 1, 1.25, 1.5, 2, 3, 5 };
122#define NC4 21 /* c = 0.20 + 0.05 i */
123static const double PHI4[] = { 1, 0.95, 0.9, 0.8, 0.6 };
124static const double NUH4[] = { 0.5, 0.6, 0.7, 0.8, 1, 1.25, 1.5, 2, 3, 5 };
125#define NCH4 31 /* c_h = 0.10 + 0.05 i */
126#define N_(a) ((int)(sizeof(a) / sizeof((a)[0])))
127static double gq4(int i) { return pow(10.0, 2.0 + 0.5 * (double)i); }
128static double gc4(int i) { return (double)(20 + 5 * i) / 100.0; }
129static double gch4(int i) { return (double)(10 + 5 * i) / 100.0; }
130#define NQ1 25
131#define NR1 17
132static double gq1(int i) { return pow(10.0, 1.0 + 0.25 * (double)i); }
133static double gr1(int j) { return pow(10.0, 2.0 + 0.25 * (double)j); }
134
135static const char *gname(int id) { return id == 1 ? "G1" : id == 2 ? "G2" : id == 3 ? "G3" : "none"; }
136
137/* ------------------------------------------------- tick walk (both paths) */
138static est_obs_class e4_classify(const c3_tick *t, est_pobs *ob)
139{
140 est_assumption a; c3_assumption_base(&a, EST_FAM_STUDENT_T);
141 a.nparam = 2; a.param[0] = 5; a.param[1] = 100;
142 if (est_pobs_classify(&a, t->value, t->present, &t->ev, ob) != EST_OK) return EST_OBS_CLASSES_;
143 return ob->cls;
144}
145
146/* Fast-path trace for one dynamic setting (dyn, q, lam): the scale-free parts
147 * of every scored one-step and ten-step predictive. */
148typedef struct {
149 size_t n1, n10, unscorable, cap;
150 double *y1, *m1, *b1, *a1; /* outcome, location, sqrt(g V_1), anchor */
151 double *y10, *m10, *v10, *g10, *gl10, *a10;
152} e4_trace;
153
154static int trace_alloc(e4_trace *tr, size_t n)
155{
156 memset(tr, 0, sizeof *tr);
157 tr->cap = n ? n : 1;
158 double **f[10] = { &tr->y1, &tr->m1, &tr->b1, &tr->a1, &tr->y10, &tr->m10, &tr->v10, &tr->g10, &tr->gl10, &tr->a10 };
159 for (int i = 0; i < 10; i++) if (!(*f[i] = malloc(tr->cap * sizeof(double)))) return 1;
160 return 0;
161}
162static void trace_free(e4_trace *tr)
163{
164 free(tr->y1); free(tr->m1); free(tr->b1); free(tr->a1); free(tr->a10); free(tr->y10); free(tr->m10); free(tr->v10); free(tr->g10); free(tr->gl10);
165 memset(tr, 0, sizeof *tr);
166}
167
168typedef struct { int ok; double m, v, g, gl, a; } e4_origin;
169
170static int trace_run(const c3_ticks *tk, const est4_params *p, e4_trace *tr)
171{
172 est4_state s;
173 if (est4_init(p, &s) != EST_OK) return 1;
174 e4_origin ring[C3_TEN];
175 memset(ring, 0, sizeof ring);
176 tr->n1 = tr->n10 = tr->unscorable = 0;
177 long first = -1;
178 for (size_t t = 0; t < tk->n; t++) {
179 est_pobs ob;
180 est_obs_class cls = e4_classify(&tk->t[t], &ob);
181 if (cls == EST_OBS_CLASSES_) return 1;
182 int ok = cls == EST_OBS_OK;
183 if (ok && first < 0) first = (long)t;
184 int scored = first >= 0 && (long)t - first >= (long)C3_BURN_IN;
185 e4_origin *o = &ring[t % C3_TEN];
186 if (o->ok) {
187 o->ok = 0;
188 if (ok && tr->n10 < tr->cap) {
189 size_t k = tr->n10++;
190 tr->y10[k] = ob.value; tr->m10[k] = o->m; tr->v10[k] = o->v; tr->g10[k] = o->g; tr->gl10[k] = o->gl; tr->a10[k] = o->a;
191 }
192 }
193 if (ok && scored) {
194 if ((uint64_t)s.gap + 1u > EST_PRED_MAX_H) tr->unscorable++;
195 else {
196 double m, v;
197 if (est4_moments(&s, 1, &m, &v) != EST_OK) return 1;
198 if (tr->n1 < tr->cap) { size_t k = tr->n1++; tr->y1[k] = ob.value; tr->m1[k] = m; tr->b1[k] = sqrt(s.g * v); tr->a1[k] = s.anchor; }
199 }
200 }
201 if (est4_update(&s, ok, ok ? ob.value : NAN) != EST_OK) return 1;
202 if (ok && scored) {
203 double m, v;
204 if (est4_moments(&s, C3_TEN, &m, &v) != EST_OK) return 1;
205 o->ok = 1; o->m = m; o->v = v; o->g = s.g; o->gl = s.gl; o->a = s.anchor;
206 }
207 }
208 return 0;
209}
210
211static double fast_ls1(const e4_trace *tr, double nu, double c)
212{
213 double sum = 0.0;
214 for (size_t i = 0; i < tr->n1; i++) {
215 est4_pred pr = { 1u, tr->m1[i], c * tr->b1[i], nu };
216 sum += est4_fast_logp(&pr, C3_QUANTUM, tr->a1[i], tr->y1[i], NULL, NULL);
217 }
218 return tr->n1 ? sum / (double)tr->n1 : -INFINITY;
219}
220
221static double fast_ls10(const e4_trace *tr, double phi, double nuh, double ch)
222{
223 double sum = 0.0;
224 for (size_t i = 0; i < tr->n10; i++) {
225 double gb = est4_gbar(tr->g10[i], tr->gl10[i], phi, C3_TEN);
226 est4_pred pr = { C3_TEN, tr->m10[i], ch * sqrt(gb * tr->v10[i]), nuh };
227 sum += est4_fast_logp(&pr, C3_QUANTUM, tr->a10[i], tr->y10[i], NULL, NULL);
228 }
229 return tr->n10 ? sum / (double)tr->n10 : -INFINITY;
230}
231
232/* Full path: discrete pmf predictives scored by est_dpred_score, statistics
233 * by c3_judge (v3 section 6), plus the ten-step mean log score. Mirrors
234 * c3_score tick for tick. */
235static int e4_score(const c3_ticks *tk, const c3_marks *mk, const est4_params *p, c3_stats *st, double *ls10)
236{
237 memset(st, 0, sizeof *st);
238 est_calib_init(&st->c);
239 st->first_fail = -1;
240 st->cap = tk->n ? tk->n : 1;
241 st->cov95_step = malloc(st->cap * sizeof(double));
242 st->width_step = malloc(st->cap * sizeof(double));
243 st->regime_step = malloc(st->cap);
244 est_dpred *ring = malloc(C3_TEN * sizeof *ring), *dp = malloc(sizeof *dp);
245 int ring_ok[C3_TEN];
246 memset(ring_ok, 0, sizeof ring_ok);
247 double l10 = 0.0;
248 int rc = 0;
249 est4_state s;
250 if (!st->cov95_step || !st->width_step || !st->regime_step || !ring || !dp) { rc = 1; snprintf(st->errmsg, sizeof st->errmsg, "out of memory"); goto done; }
251 if (est4_init(p, &s) != EST_OK) { rc = 1; snprintf(st->errmsg, sizeof st->errmsg, "params"); goto done; }
252 long first = -1;
253 for (size_t t = 0; t < tk->n && !rc; t++) {
254 const c3_tick *tc = &tk->t[t];
255 est_pobs ob; est_pinnov iv; est_status r;
256 est_obs_class cls = e4_classify(tc, &ob);
257 if (cls == EST_OBS_CLASSES_) { rc = 1; break; }
258 int ok = cls == EST_OBS_OK;
259 if (ok && first < 0) first = (long)t;
260 int scored = first >= 0 && (long)t - first >= (long)C3_BURN_IN;
261 if (ring_ok[t % C3_TEN]) {
262 ring_ok[t % C3_TEN] = 0;
263 if (ok) {
264 if ((r = est_dpred_score(&ring[t % C3_TEN], &ob, &iv)) != EST_OK) { rc = 1; break; }
265 if (iv.valid) { st->ten_cov += est_frac_cover(iv.F_lo, iv.F_hi, 0.95); st->ten_n++; l10 += iv.logp; }
266 }
267 }
268 if (ok && scored) {
269 if ((uint64_t)s.gap + 1u > EST_PRED_MAX_H) st->unscorable++;
270 else {
271 est4_pred pr;
272 if (est4_predict(&s, 1, &pr) != EST_OK || est4_dpred(&s, &pr, dp) != EST_OK) { rc = 1; break; }
273 if ((r = est_dpred_score(dp, &ob, &iv)) != EST_OK) { rc = 1; break; }
274 if (iv.valid) {
275 st->logsum += iv.logp; st->n++;
276 if (est_calib_add(&st->c, dp, &iv) != EST_OK) { rc = 1; break; }
277 size_t k = st->n - 1;
278 st->cov95_step[k] = est_frac_cover(iv.F_lo, iv.F_hi, 0.95);
279 double w = NAN;
280 if (est_dpred_width80(dp, &w) != EST_OK) { rc = 1; break; }
281 st->width_step[k] = w;
282 st->regime_step[k] = (unsigned char)c3_in_trial(mk, tc->wall_ns);
283 }
284 }
285 }
286 if (est4_update(&s, ok, ok ? ob.value : NAN) != EST_OK) { rc = 1; break; }
287 if (ok && scored) {
288 est4_pred pr;
289 if (est4_predict(&s, C3_TEN, &pr) != EST_OK || est4_dpred(&s, &pr, &ring[t % C3_TEN]) != EST_OK) { rc = 1; break; }
290 ring_ok[t % C3_TEN] = 1;
291 }
292 }
293 if (rc && !st->errmsg[0]) snprintf(st->errmsg, sizeof st->errmsg, "v4 scoring error");
294 st->error = rc;
295 st->logscore = st->n ? st->logsum / (double)st->n : -INFINITY;
296 *ls10 = st->ten_n ? l10 / (double)st->ten_n : -INFINITY;
297 if (!rc) c3_judge(st);
298done:
299 free(ring); free(dp);
300 return rc;
301}
302
303/* ------------------------------------------------------------- the fit */
304typedef struct {
305 int have;
306 est4_params p;
307 double fast1, fast10, full1, full10;
308 size_t points1, points2, n1, n10, skipped; /* skipped: (dyn, q, lam) points whose filter failed */
309 int edge[8]; /* chosen value on a grid edge: dyn q lam nu c phi nu_h c_h */
310} g_fit;
311
312static int edge_of(double v, const double *g, int n) { return v == g[0] || v == g[n - 1]; }
313
314static int fit_family(const c3_ticks *tk, int id, int stride, g_fit *gf)
315{
316 const double *dyn = id == 1 ? G1_TAU : id == 2 ? G2_RHO : G3_TAU;
317 int nd = id == 1 ? N_(G1_TAU) : id == 2 ? N_(G2_RHO) : N_(G3_TAU);
318 e4_trace tr;
319 if (trace_alloc(&tr, tk->n)) { trace_free(&tr); return 1; }
320 memset(gf, 0, sizeof *gf);
321 double best = -INFINITY;
322 est4_params p;
323 memset(&p, 0, sizeof p);
324 p.family = (est4_family)id; p.quantum = C3_QUANTUM;
325 p.phi = 1.0; p.nu_h = 1.0; p.c_h = 1.0; p.nu = 1.0; p.c = 1.0;
326 /* stage 1: one-step score over dyn, q, lam, nu, c */
327 for (int a = 0; a < nd; a += stride)
328 for (int b = 0; b < NQ4; b += stride)
329 for (int l = 0; l < N_(LAM4); l += stride) {
330 p.dyn = dyn[a]; p.q = gq4(b); p.lam = LAM4[l];
331 if (trace_run(tk, &p, &tr)) { gf->skipped++; continue; }
332 for (int u = 0; u < N_(NU4); u += stride)
333 for (int c = 0; c < NC4; c += stride) {
334 double ls = fast_ls1(&tr, NU4[u], gc4(c));
335 gf->points1++;
336 if (isfinite(ls) && c3_grid_take(gf->have, ls, best)) {
337 gf->have = 1; best = ls;
338 gf->p = p; gf->p.nu = NU4[u]; gf->p.c = gc4(c);
339 }
340 }
341 }
342 if (!gf->have) { trace_free(&tr); return 0; }
343 gf->fast1 = best;
344 /* stage 2: ten-step score over phi, nu_h, c_h with stage 1 frozen */
345 if (trace_run(tk, &gf->p, &tr)) { trace_free(&tr); gf->have = 0; return 0; }
346 int have2 = 0; double best2 = -INFINITY;
347 for (int a = 0; a < N_(PHI4); a += stride)
348 for (int u = 0; u < N_(NUH4); u += stride)
349 for (int c = 0; c < NCH4; c += stride) {
350 double ls = fast_ls10(&tr, PHI4[a], NUH4[u], gch4(c));
351 gf->points2++;
352 if (isfinite(ls) && c3_grid_take(have2, ls, best2)) {
353 have2 = 1; best2 = ls;
354 gf->p.phi = PHI4[a]; gf->p.nu_h = NUH4[u]; gf->p.c_h = gch4(c);
355 }
356 }
357 if (!have2) { trace_free(&tr); gf->have = 0; return 0; }
358 gf->fast10 = best2;
359 gf->n1 = tr.n1; gf->n10 = tr.n10;
360 double cg[NC4], chg[NCH4], qg[NQ4];
361 for (int i = 0; i < NC4; i++) cg[i] = gc4(i);
362 for (int i = 0; i < NCH4; i++) chg[i] = gch4(i);
363 for (int i = 0; i < NQ4; i++) qg[i] = gq4(i);
364 gf->edge[0] = edge_of(gf->p.dyn, dyn, nd); gf->edge[1] = edge_of(gf->p.q, qg, NQ4);
365 gf->edge[2] = edge_of(gf->p.lam, LAM4, N_(LAM4)); gf->edge[3] = edge_of(gf->p.nu, NU4, N_(NU4));
366 gf->edge[4] = edge_of(gf->p.c, cg, NC4); gf->edge[5] = edge_of(gf->p.phi, PHI4, N_(PHI4));
367 gf->edge[6] = edge_of(gf->p.nu_h, NUH4, N_(NUH4)); gf->edge[7] = edge_of(gf->p.c_h, chg, NCH4);
368 trace_free(&tr);
369 return 0;
370}
371
372static void put_screen(FILE *fp, const char *name, const c3_stats *st, double ls10)
373{
374 for (int i = 0; i < C3_ST_COUNT; i++)
375 fprintf(fp, "screen %s %s value %.17g band %.17g %.17g n %zu gated %d pass %d\n", name, c3_stat_name(i),
376 st->value[i], st->band_lo[i], st->band_hi[i],
377 (i >= C3_ST_Q0 && i <= C3_ST_TEN) ? st->sub_n[i] : st->n, st->gated[i], st->pass[i]);
378 fprintf(fp, "screen_sharpness %s width80_mean_mc %.17g width80_median_mc %.17g unscorable %zu ten_logscore %.17g\n",
379 name, st->width_mean, st->width_median, st->unscorable, ls10);
380 fprintf(fp, "screen_result %s pass %d first_fail %s n %zu logscore %.17g\n", name, st->calibrated,
381 st->calibrated ? "none" : c3_stat_name(st->first_fail), st->n, st->logscore);
382}
383
384static int cmd_fit(int argc, char **argv)
385{
386 const char *raw = NULL, *mkp = NULL, *out = NULL;
387 int synth = 0, stride = 1;
388 for (int i = 0; i < argc; i++) {
389 if (!strcmp(argv[i], "--raw") && i + 1 < argc) raw = argv[++i];
390 else if (!strcmp(argv[i], "--marks") && i + 1 < argc) mkp = argv[++i];
391 else if (!strcmp(argv[i], "--out") && i + 1 < argc) out = argv[++i];
392 else if (!strcmp(argv[i], "--synthetic-test")) synth = 1;
393 else if (!strcmp(argv[i], "--grid-stride") && i + 1 < argc) stride = atoi(argv[++i]);
394 else { fprintf(stderr, "usage: est4 fit --raw R --marks M --out P [--synthetic-test [--grid-stride N]]\n"); return 2; }
395 }
396 if (!raw || !mkp || !out) { fprintf(stderr, "est4 fit: --raw, --marks and --out are required\n"); return 2; }
397 /* held-out guard first, before any file is opened, in every mode */
398 if (e4_heldout(raw) || e4_heldout(mkp) || e4_heldout(out)) { fprintf(stderr, "refuse: a held-out path; fitting on it is not allowed\n"); return 2; }
399 if (stride < 1 || (stride != 1 && !synth)) { fprintf(stderr, "refuse: --grid-stride only with --synthetic-test\n"); return 2; }
400 const char *proto = envor("E4_TEST_PROTOCOL_SHA", E4_PROTOCOL_SHA);
401 const char *d1raw = envor("E4_TEST_D1_RAW_SHA", E4_D1_RAW_SHA), *d1mk = envor("E4_TEST_D1_MARKS_SHA", E4_D1_MARKS_SHA);
402 if (!synth) {
403 if (tool_dirty()) { fprintf(stderr, "refuse: the binding fit needs a clean tree (dirty=%d)\n", tool_dirty()); return 2; }
404 char doc[65] = "";
405 if (!strcmp(proto, "unknown") || est_sha_file_hex(E4_PROTOCOL_DOC, doc) || strcmp(doc, proto)) {
406 fprintf(stderr, "refuse: compiled protocol SHA %s differs from %s on disk (%s)\n", proto, E4_PROTOCOL_DOC, doc[0] ? doc : "unreadable"); return 2; }
407 if (!strcmp(d1raw, "absent") || !strcmp(d1mk, "absent")) { fprintf(stderr, "refuse: no D1 identity compiled in (receipts/est-v4/d1.sha256)\n"); return 2; }
408 if (!strstr(raw, E4_FIT_TAG) || !strstr(mkp, E4_FIT_TAG)) { fprintf(stderr, "refuse: the binding fit opens only a %s run\n", E4_FIT_TAG); return 2; }
409 }
410 char err[512];
411 est_file f;
412 if (est_file_load(raw, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 1; }
413 static c3_marks mk;
414 if (c3_marks_load(mkp, 1, &mk, err, sizeof err)) { fprintf(stderr, "refuse: marks: %s\n", err); est_file_free(&f); return 1; }
415 if (!synth && (strcmp(f.sha_hex, d1raw) || strcmp(mk.sha, d1mk))) {
416 fprintf(stderr, "refuse: input SHA-256 differs from the compiled D1 identity\n"); est_file_free(&f); return 2; }
417 FILE *fp = fopen(out, "wbx");
418 if (!fp) { fprintf(stderr, "refuse: cannot create %s (%s); outputs are never overwritten\n", out, strerror(errno)); est_file_free(&f); return 1; }
419 c3_ticks tk;
420 if (c3_ticks_build(&f, &tk, err, sizeof err)) { fprintf(stderr, "ticks: %s\n", err); fclose(fp); est_file_free(&f); return 1; }
421
422 static g_fit gf[4];
423 static c3_stats st[4];
424 double full10[4] = { 0 };
425 int agree[4] = { 0 };
426 for (int id = 1; id <= 3; id++) {
427 if (fit_family(&tk, id, stride, &gf[id])) { fprintf(stderr, "out of memory\n"); fclose(fp); return 1; }
428 fprintf(stderr, "est4 fit: %s done (%zu + %zu points)\n", gname(id), gf[id].points1, gf[id].points2);
429 if (!gf[id].have) continue;
430 if (e4_score(&tk, &mk, &gf[id].p, &st[id], &full10[id])) { fprintf(stderr, "screen %s: %s\n", gname(id), st[id].errmsg); gf[id].have = 0; continue; }
431 gf[id].full1 = st[id].logscore; gf[id].full10 = full10[id];
432 agree[id] = fabs(gf[id].full1 - gf[id].fast1) <= E4_AGREE && fabs(gf[id].full10 - gf[id].fast10) <= E4_AGREE &&
433 st[id].n == gf[id].n1 && st[id].ten_n == gf[id].n10;
434 if (!agree[id]) { fprintf(stderr, "est4 fit: %s fast and pmf scores disagree; family unavailable\n", gname(id)); gf[id].have = 0; }
435 }
436 /* baselines (v3 definitions): F1 grid and E0 histogram on D1 */
437 int f1have = 0; double f1ls = -INFINITY; c3_model m, f1m;
438 memset(&f1m, 0, sizeof f1m);
439 for (int i = 0; i < NQ1; i += stride)
440 for (int j = 0; j < NR1; j += stride) {
441 c3_stats s1;
442 c3_make_f1(&m, gq1(i), gr1(j));
443 if (c3_score(&tk, NULL, &m, 0, &s1)) continue;
444 if (isfinite(s1.logscore) && c3_grid_take(f1have, s1.logscore, f1ls)) { f1have = 1; f1ls = s1.logscore; f1m = m; }
445 }
446 double *e = malloc((tk.n + 1) * sizeof *e);
447 uint32_t *e0c = calloc(EST_PRED_N, sizeof *e0c);
448 if (!e || !e0c) { fprintf(stderr, "out of memory\n"); fclose(fp); return 1; }
449 size_t ne = c3_h1_changes(&tk, e, tk.n + 1);
450 c3_e0_counts(e, ne, e0c);
451
452 int av[6] = { 0 }, ps[6] = { 0 }; double lsv[6] = { 0 };
453 for (int id = 1; id <= 3; id++) { av[id] = gf[id].have; ps[id] = gf[id].have && st[id].calibrated; lsv[id] = gf[id].have ? gf[id].full1 : -INFINITY; }
454 int sel = c3_select(av, ps, lsv);
455
456 char doc_hex[65] = "unavailable";
457 est_sha_file_hex(E4_PROTOCOL_DOC, doc_hex);
458 fprintf(fp, "est4_params v4\n");
459 fprintf(fp, "protocol %s\nprotocol_doc_sha256 %s\nprotocol_doc_sha256_on_disk %s\n", E4_PROTOCOL_DOC, proto, doc_hex);
460 fprintf(fp, "tool_commit %s\ntool_dirty %d\nsynthetic_test %d\ngrid_stride %d\n", TOOL_COMMIT, tool_dirty(), synth, stride);
461 fprintf(fp, "fit_raw_path %s\nfit_raw_sha256 %s\nfit_marks_path %s\nfit_marks_sha256 %s\nfit_lines %zu\n", raw, f.sha_hex, mkp, mk.sha, f.nlines);
462 fprintf(fp, "d1_identity_compiled raw %s marks %s\n", d1raw, d1mk);
463 fprintf(fp, "ticks total %zu inserted %zu gaps_capped %zu bad_t %zu absent_value %zu unparsable_value %zu\n",
464 tk.n, tk.inserted, tk.gaps_capped, tk.bad_t, tk.absent_value, tk.unparsable_value);
465 fprintf(fp, "marks pairs %zu begins %zu ends %zu unclosed %zu\n", mk.n, mk.begins, mk.ends, mk.unclosed);
466 fprintf(fp, "rule stage1 maximise fast one-step mean log score over dyn q lam nu c (phi nu_h c_h unused)\n");
467 fprintf(fp, "rule stage2 maximise fast ten-step mean log score over phi nu_h c_h with stage 1 frozen\n");
468 fprintf(fp, "rule agreement fast vs pmf mean log score within %g nats, same step counts\n", E4_AGREE);
469 for (int id = 1; id <= 3; id++) {
470 const g_fit *g = &gf[id];
471 fprintf(fp, "family %s available %d dyn %.17g q %.17g lam %.17g nu %.17g c %.17g phi %.17g nu_h %.17g c_h %.17g"
472 " logscore %.17g ten_logscore %.17g fast1 %.17g fast10 %.17g points1 %zu points2 %zu skipped %zu agree %d\n",
473 gname(id), g->have, g->p.dyn, g->p.q, g->p.lam, g->p.nu, g->p.c, g->p.phi, g->p.nu_h, g->p.c_h,
474 g->have ? g->full1 : -INFINITY, g->have ? g->full10 : -INFINITY, g->fast1, g->fast10, g->points1, g->points2, g->skipped, agree[id]);
475 fprintf(fp, "grid_edge %s dyn %d q %d lam %d nu %d c %d phi %d nu_h %d c_h %d\n", gname(id),
476 g->edge[0], g->edge[1], g->edge[2], g->edge[3], g->edge[4], g->edge[5], g->edge[6], g->edge[7]);
477 }
478 fprintf(fp, "baseline F1 available %d q_proc %.17g r %.17g logscore %.17g\n", f1have, f1m.a.param[0], f1m.a.param[1], f1ls);
479 for (int id = 1; id <= 3; id++) {
480 if (!gf[id].have) { fprintf(fp, "screen_result %s pass 0 first_fail unavailable n 0\n", gname(id)); continue; }
481 put_screen(fp, gname(id), &st[id], full10[id]);
482 }
483 fprintf(fp, "e0_changes %zu\n", ne);
484 for (int i = 0; i < EST_PRED_N; i++) if (e0c[i]) fprintf(fp, "e0_count %d %u\n", i - EST_PRED_K, e0c[i]);
485 fprintf(fp, "selection_rule best D1 one-step log score among screen-passers; earlier of G1 < G2 < G3 within %.2f nats preferred\n", C3_TIE_NATS);
486 if (sel) fprintf(fp, "selected %s\nphase_a PASS\n", gname(sel));
487 else {
488 fprintf(fp, "selected none\nphase_a PHASE_A_FAIL\n");
489 for (int id = 1; id <= 3; id++) {
490 fprintf(fp, "phase_a_fail %s", gname(id));
491 if (!gf[id].have) fprintf(fp, " unavailable");
492 else for (int i = 0; i < C3_ST_COUNT; i++)
493 if (st[id].gated[i] && !st[id].pass[i]) fprintf(fp, " %s=%.6g", c3_stat_name(i), st[id].value[i]);
494 fprintf(fp, "\n");
495 }
496 }
497 int bad = ferror(fp) != 0;
498 if (fclose(fp) != 0) bad = 1;
499 if (bad) {
500 /* never leave a partial params file behind: it would block a rerun (wbx) */
501 remove(out);
502 fprintf(stderr, "est4 fit: writing %s failed; partial file removed\n", out);
503 for (int id = 1; id <= 3; id++) if (gf[id].have) c3_stats_free(&st[id]);
504 free(e); free(e0c); c3_ticks_free(&tk); est_file_free(&f);
505 return 1;
506 }
507 char ph[65] = "unavailable";
508 est_sha_file_hex(out, ph);
509 printf("EST4_FIT selected=%s phase_a=%s params_sha256=%s synthetic_test=%d\n", gname(sel), sel ? "PASS" : "PHASE_A_FAIL", ph, synth);
510 for (int id = 1; id <= 3; id++) if (gf[id].have) c3_stats_free(&st[id]);
511 free(e); free(e0c); c3_ticks_free(&tk); est_file_free(&f);
512 return bad ? 1 : 0;
513}
514
515/* ------------------------------------------------------ params reader */
516typedef struct {
517 int phase_a_pass, selected, synthetic, tool_dirty;
518 int have[4], pass[4];
519 est4_params g[4];
520 double ls[4];
521 double f1q, f1r; int f1have;
522 uint64_t e0_n; uint32_t e0[EST_PRED_N];
523 char protocol_sha[65], fit_raw_sha[65], fit_marks_sha[65], fit_raw_path[1024];
524} e4_params_file;
525
526/* the whole key including its trailing space: no prefix of a longer key matches */
527static int key(const char *line, const char *k) { return !strncmp(line, k, strlen(k)); }
528
529static int gid(const char *s) { return !strcmp(s, "G1") ? 1 : !strcmp(s, "G2") ? 2 : !strcmp(s, "G3") ? 3 : 0; }
530
531static int params_read(const char *path, e4_params_file *P, char *err, size_t cap)
532{
533 memset(P, 0, sizeof *P);
534 FILE *fp = fopen(path, "rb");
535 if (!fp) { snprintf(err, cap, "cannot open %s", path); return 1; }
536 char line[4096], a[64], b[1100];
537 int magic = 0, have_phase = 0, have_sel = 0;
538 P->selected = -1;
539 while (fgets(line, sizeof line, fp)) {
540 if (!strncmp(line, "est4_params v4", 14)) magic = 1;
541 else if (key(line, "protocol_doc_sha256 ") && sscanf(line + 20, "%64s", P->protocol_sha) == 1) {}
542 else if (key(line, "fit_raw_sha256 ") && sscanf(line + 15, "%64s", P->fit_raw_sha) == 1) {}
543 else if (key(line, "fit_marks_sha256 ") && sscanf(line + 17, "%64s", P->fit_marks_sha) == 1) {}
544 else if (key(line, "fit_raw_path ")) { size_t L = strcspn(line + 13, "\n"); if (L >= sizeof P->fit_raw_path) L = sizeof P->fit_raw_path - 1; memcpy(P->fit_raw_path, line + 13, L); P->fit_raw_path[L] = 0; }
545 else if (key(line, "synthetic_test ") && sscanf(line + 15, "%d", &P->synthetic) == 1) {}
546 else if (key(line, "tool_dirty ") && sscanf(line + 11, "%d", &P->tool_dirty) == 1) {}
547 else if (!strncmp(line, "family ", 7)) {
548 est4_params g; int av; double ls;
549 memset(&g, 0, sizeof g);
550 if (sscanf(line, "family %63s available %d dyn %lf q %lf lam %lf nu %lf c %lf phi %lf nu_h %lf c_h %lf logscore %lf",
551 a, &av, &g.dyn, &g.q, &g.lam, &g.nu, &g.c, &g.phi, &g.nu_h, &g.c_h, &ls) != 11 || !gid(a)) {
552 snprintf(err, cap, "bad family line"); fclose(fp); return 1; }
553 int id = gid(a);
554 g.family = (est4_family)id; g.quantum = C3_QUANTUM;
555 P->have[id] = av; P->g[id] = g; P->ls[id] = av ? ls : -INFINITY;
556 } else if (!strncmp(line, "baseline F1 ", 12)) {
557 if (sscanf(line, "baseline F1 available %d q_proc %lf r %lf", &P->f1have, &P->f1q, &P->f1r) != 3) { snprintf(err, cap, "bad F1 line"); fclose(fp); return 1; }
558 } else if (!strncmp(line, "screen_result ", 14)) {
559 int ps;
560 if (sscanf(line, "screen_result %63s pass %d", a, &ps) != 2 || !gid(a)) { snprintf(err, cap, "bad screen_result"); fclose(fp); return 1; }
561 P->pass[gid(a)] = ps;
562 } else if (!strncmp(line, "e0_count ", 9)) {
563 int k; unsigned c;
564 if (sscanf(line, "e0_count %d %u", &k, &c) != 2 || k < -EST_PRED_K || k > EST_PRED_K) { snprintf(err, cap, "bad e0_count"); fclose(fp); return 1; }
565 P->e0[k + EST_PRED_K] = c; P->e0_n += c;
566 } else if (!strncmp(line, "selected ", 9) && sscanf(line + 9, "%63s", a) == 1) { have_sel = 1; P->selected = gid(a); }
567 else if (!strncmp(line, "phase_a ", 8) && sscanf(line + 8, "%1099s", b) == 1) { have_phase = 1; P->phase_a_pass = !strcmp(b, "PASS"); }
568 }
569 fclose(fp);
570 if (!magic || !have_phase || !have_sel) { snprintf(err, cap, "not a v4 params file"); return 1; }
571 for (int id = 1; id <= 3; id++) if (P->have[id] && est4_params_check(&P->g[id]) != EST_OK) { snprintf(err, cap, "%s params invalid", gname(id)); return 1; }
572 return 0;
573}
574
575/* ------------------------------------------------------ eval */
576static int has_receipt(const char *dir)
577{
578 DIR *d = opendir(dir);
579 if (!d) return -1;
580 struct dirent *e; int found = 0;
581 while ((e = readdir(d))) if (!strncmp(e->d_name, "receipt-", 8)) found = 1;
582 closedir(d);
583 return found;
584}
585
586static int cmd_recorded(int argc, char **argv)
587{
588 const char *dir = NULL, *ppath = NULL, *outdir = NULL;
589 int synth = 0;
590 for (int i = 0; i < argc; i++) {
591 if (!strcmp(argv[i], "--dir") && i + 1 < argc) dir = argv[++i];
592 else if (!strcmp(argv[i], "--params") && i + 1 < argc) ppath = argv[++i];
593 else if (!strcmp(argv[i], "--outdir") && i + 1 < argc) outdir = argv[++i];
594 else if (!strcmp(argv[i], "--synthetic-test")) synth = 1;
595 else { fprintf(stderr, "usage: est4 recorded --dir D2 --params P --outdir O [--synthetic-test]\n"); return 2; }
596 }
597 if (!dir || !ppath || !outdir) { fprintf(stderr, "est4 recorded: --dir, --params and --outdir are required\n"); return 2; }
598 char err[512];
599 const char *proto = envor("E4_TEST_PROTOCOL_SHA", E4_PROTOCOL_SHA);
600 const char *d2r = envor("E4_TEST_D2_RAW_SHA", E4_D2_RAW_SHA), *d2m = envor("E4_TEST_D2_MARKS_SHA", E4_D2_MARKS_SHA),
601 *d2s = envor("E4_TEST_D2_SCHED_SHA", E4_D2_SCHED_SHA), *psha = envor("E4_TEST_PARAMS_SHA", E4_PARAMS_SHA);
602 if (!synth) {
603 if (tool_dirty()) { fprintf(stderr, "refuse: recorded needs a clean tree (dirty=%d)\n", tool_dirty()); return 2; }
604 if (!strcmp(d2r, "absent") || !strcmp(d2m, "absent") || !strcmp(d2s, "absent")) { fprintf(stderr, "refuse: no D2 identity compiled in (receipts/est-v4/d2.sha256)\n"); return 2; }
605 char doc[65] = "";
606 if (est_sha_file_hex(E4_PROTOCOL_DOC, doc) || strcmp(doc, proto)) { fprintf(stderr, "refuse: protocol doc on disk differs from the compiled SHA\n"); return 2; }
607 char ph0[65] = "";
608 if (!strcmp(psha, "absent") || est_sha_file_hex(ppath, ph0) || strcmp(ph0, psha)) { fprintf(stderr, "refuse: params SHA-256 differs from the compiled params SHA\n"); return 2; }
609 char want[PATH_MAX + 64], rw[PATH_MAX], ro[PATH_MAX];
610 const char *root = envor("E4_TEST_REPO_ROOT", E4_REPO_ROOT);
611 if (!strcmp(root, "unknown")) { fprintf(stderr, "refuse: no repo root compiled in\n"); return 2; }
612 snprintf(want, sizeof want, "%s/%s", root, E4_RECEIPT_SUBDIR);
613 if (!realpath(want, rw) || !realpath(outdir, ro) || strcmp(rw, ro)) { fprintf(stderr, "refuse: a recorded receipt goes only to <repo>/%s\n", E4_RECEIPT_SUBDIR); return 2; }
614 if (!strstr(dir, E4_HELDOUT_TAG)) { fprintf(stderr, "refuse: the recorded run scores only a %s run\n", E4_HELDOUT_TAG); return 2; }
615 } else if (e4_heldout(dir) || strstr(dir, E4_FIT_TAG) || strstr(dir, C3_D1_ID)) {
616 fprintf(stderr, "refuse: --synthetic-test never runs on D1 or a held-out run\n"); return 2;
617 }
618 static e4_params_file P;
619 if (params_read(ppath, &P, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; }
620 if (!P.phase_a_pass) { fprintf(stderr, "refuse: params say PHASE_A_FAIL; D2 is NOT_RUN\n"); return 2; }
621 int av[6] = { 0 }, ps[6] = { 0 }; double lsv[6] = { 0 };
622 for (int id = 1; id <= 3; id++) { av[id] = P.have[id]; ps[id] = P.pass[id]; lsv[id] = P.ls[id]; }
623 int resel = c3_select(av, ps, lsv);
624 if (resel != P.selected || P.selected < 1) { fprintf(stderr, "refuse: params selected %s but the rule gives %s\n", gname(P.selected), gname(resel)); return 2; }
625 if (!P.f1have) { fprintf(stderr, "refuse: params carry no F1 baseline\n"); return 2; }
626 if (!synth) {
627 if (P.synthetic || P.tool_dirty) { fprintf(stderr, "refuse: params are not a binding fit\n"); return 2; }
628 if (strcmp(P.protocol_sha, proto)) { fprintf(stderr, "refuse: params fitted under another protocol SHA\n"); return 2; }
629 if (strcmp(P.fit_raw_sha, envor("E4_TEST_D1_RAW_SHA", E4_D1_RAW_SHA)) || strcmp(P.fit_marks_sha, envor("E4_TEST_D1_MARKS_SHA", E4_D1_MARKS_SHA)) || !strstr(P.fit_raw_path, E4_FIT_TAG)) {
630 fprintf(stderr, "refuse: params are not a fit on the compiled D1\n"); return 2; }
631 }
632 int hr = has_receipt(outdir);
633 if (hr < 0) { fprintf(stderr, "refuse: outdir %s is not a readable directory\n", outdir); return 2; }
634 if (hr > 0) { fprintf(stderr, "refuse: %s already holds a receipt; a second scored run is a new protocol version\n", outdir); return 2; }
635 c3_pre pre;
636 if (c3_precheck(dir, &pre, err, sizeof err)) { fprintf(stderr, "refuse: precheck: %s\n", err); return 2; }
637 printf("precheck %s: %s\n", pre.valid ? "VALID" : "INCONCLUSIVE", pre.why);
638 if (!pre.valid) { fprintf(stderr, "refuse: the pre-check is INCONCLUSIVE; D2 is not scored\n"); return 3; }
639 if (!synth && (strcmp(pre.raw_sha, d2r) || strcmp(pre.marks_sha, d2m) || strcmp(pre.sched_sha, d2s))) {
640 fprintf(stderr, "refuse: D2 data SHA-256 differs from the compiled D2 identity\n"); return 2; }
641 char path[1200];
642 est_file f;
643 snprintf(path, sizeof path, "%s/machine-state.ndjson", dir);
644 if (est_file_load(path, &f, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; }
645 /* the scored bytes are the identified bytes (the pre-check hashed a separate read) */
646 if (!synth && strcmp(f.sha_hex, d2r)) { fprintf(stderr, "refuse: scored D2 bytes differ from the compiled D2 identity\n"); est_file_free(&f); return 2; }
647 if (synth && strcmp(d2r, "absent") && !strcmp(f.sha_hex, d2r)) { fprintf(stderr, "refuse: --synthetic-test never runs on D1 or a held-out run (D2 bytes)\n"); est_file_free(&f); return 2; }
648 c3_ticks tk;
649 if (c3_ticks_build(&f, &tk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); est_file_free(&f); return 2; }
650 static c3_marks mk;
651 snprintf(path, sizeof path, "%s/machine-state-marks.txt", dir);
652 if (c3_marks_load(path, 1, &mk, err, sizeof err)) { fprintf(stderr, "refuse: %s\n", err); return 2; }
653 static c3_stats sS, s1, s0;
654 static c3_model m1, m0;
655 double l10S = -INFINITY;
656 c3_make_f1(&m1, P.f1q, P.f1r);
657 c3_make_e0(&m0, P.e0, P.e0_n);
658 if (e4_score(&tk, &mk, &P.g[P.selected], &sS, &l10S) || c3_score(&tk, &mk, &m1, 1, &s1) || c3_score(&tk, &mk, &m0, 1, &s0)) {
659 fprintf(stderr, "scoring error: %s %s %s\n", sS.errmsg, s1.errmsg, s0.errmsg); return 1; }
660 int same = sS.n == s1.n && sS.n == s0.n && sS.unscorable == s1.unscorable && sS.unscorable == s0.unscorable;
661 int beat1 = sS.logscore >= s1.logscore - C3_TIE_NATS, beat0 = sS.logscore >= s0.logscore - C3_TIE_NATS;
662 /* est-json-1: a non-finite measured value is recorded as invalid and can never pass */
663 size_t inv = c3_stats_invalid(&sS, C3_TEN_MEASURED, l10S) + c3_stats_invalid(&s1, C3_TEN_UNAVAILABLE, NAN) + c3_stats_invalid(&s0, C3_TEN_UNAVAILABLE, NAN);
664 int pass = inv == 0 && same && sS.calibrated && beat1 && beat0;
665 const char *verdict = pass ? "PASS" : "HELD_OUT_FAIL";
666 const char *reason = inv ? "non-finite measured value (marked invalid in the receipt)" : !same ? "S, F1 and E0 were not scored on the same steps" : !sS.calibrated ? "S not calibrated"
667 : (!beat1 || !beat0) ? "calibrated but not better than a baseline" : "calibrated and no worse than F1 and E0";
668 char *buf = NULL; size_t blen = 0;
669 FILE *o = open_memstream(&buf, &blen);
670 if (!o) { fprintf(stderr, "out of memory\n"); return 1; }
671 char pdisk[65] = "unavailable";
672 est_sha_file_hex(ppath, pdisk);
673 fprintf(o, "{\n \"receipt\": \"est4 v4 sealed held-out run\",\n \"verdict\": \"%s\",\n \"reason\": \"%s\",\n", verdict, reason);
674 fprintf(o, " \"synthetic_test\": %s,\n \"tool_commit\": \"%s\",\n \"tool_dirty\": %d,\n \"protocol_sha256\": \"%s\",\n \"params_sha256\": \"%s\",\n",
675 synth ? "true" : "false", TOOL_COMMIT, tool_dirty(), proto, pdisk);
676 fprintf(o, " \"d2\": {\"dir\": "); c3_json_str(o, dir);
677 fprintf(o, ", \"raw_sha256\": \"%s\", \"marks_sha256\": \"%s\", \"schedule_sha256\": \"%s\", \"lines\": %zu},\n", pre.raw_sha, pre.marks_sha, pre.sched_sha, pre.lines);
678 fprintf(o, " \"selected\": \"%s\",\n \"comparisons\": {\"same_steps\": %s, \"no_worse_than_F1\": %s, \"no_worse_than_E0\": %s, \"tie_nats\": %.2f},\n",
679 gname(P.selected), same ? "true" : "false", beat1 ? "true" : "false", beat0 ? "true" : "false", C3_TIE_NATS);
680 fprintf(o, " \"json_rules\": \"est-json-1\",\n \"invalid_measurements\": %zu,\n", inv);
681 fprintf(o, " \"scores\": {\n");
682 c3_json_stats(o, gname(P.selected), &sS, C3_TEN_MEASURED, l10S); fprintf(o, ",\n");
683 c3_json_stats(o, "F1", &s1, C3_TEN_UNAVAILABLE, NAN); fprintf(o, ",\n");
684 c3_json_stats(o, "E0", &s0, C3_TEN_UNAVAILABLE, NAN); fprintf(o, "\n }\n}\n");
685 fclose(o);
686 uint8_t dg[32]; char hex[65];
687 sha256_ctx c; sha256_init(&c); sha256_update(&c, (const uint8_t *)buf, blen); sha256_final(&c, dg);
688 est_hex(dg, 32, hex);
689 snprintf(path, sizeof path, "%s/receipt-%s.json", outdir, hex);
690 FILE *w = fopen(path, "wbx");
691 if (!w || fwrite(buf, 1, blen, w) != blen || fclose(w)) { fprintf(stderr, "cannot write %s\n", path); free(buf); return 1; }
692 free(buf);
693 printf("EST4_RECORDED verdict=%s selected=%s receipt=%s reason=%s\n", verdict, gname(P.selected), path, reason);
694 c3_stats_free(&sS); c3_stats_free(&s1); c3_stats_free(&s0); c3_ticks_free(&tk); est_file_free(&f);
695 return 0;
696}
697
698static int cmd_precheck(int argc, char **argv)
699{
700 if (argc != 2 || strcmp(argv[0], "--dir")) { fprintf(stderr, "usage: est4 precheck --dir D\n"); return 2; }
701 char err[512]; c3_pre pre;
702 if (c3_precheck(argv[1], &pre, err, sizeof err)) { fprintf(stderr, "precheck: %s\n", err); return 2; }
703 printf("precheck lines %zu gaps_big %zu/%zu marks %s foreign_mean %.4f over3 %.4f unmeasured %zu\n",
704 pre.lines, pre.gaps_big, pre.gaps, pre.ok_marks ? "ok" : pre.marks_why, pre.foreign_mean, pre.foreign_over3_frac, pre.foreign_unmeasured);
705 printf("%s: %s\n", pre.valid ? "VALID" : "INCONCLUSIVE", pre.why);
706 return pre.valid ? 0 : 3;
707}
708
709static int cmd_synth(int argc, char **argv)
710{
711 if (argc < 1) { fprintf(stderr, "usage: est4 make-synthetic DIR [--seed N] [--lines N]\n"); return 2; }
712 c3_synth sy; memset(&sy, 0, sizeof sy);
713 sy.seed = 1; sy.lines = 2400;
714 for (int i = 1; i < argc; i++) {
715 if (!strcmp(argv[i], "--seed") && i + 1 < argc) sy.seed = strtoull(argv[++i], NULL, 0);
716 else if (!strcmp(argv[i], "--lines") && i + 1 < argc) sy.lines = (size_t)strtoull(argv[++i], NULL, 0);
717 else return 2;
718 }
719 return c3_synth_write(argv[0], &sy) ? 1 : 0;
720}
721
722int main(int argc, char **argv)
723{
724 if (argc < 2) { fprintf(stderr, "usage: est4 fit|precheck|recorded|make-synthetic ...\n"); return 2; }
725 if (!strcmp(argv[1], "fit")) return cmd_fit(argc - 2, argv + 2);
726 if (!strcmp(argv[1], "recorded")) return cmd_recorded(argc - 2, argv + 2);
727 if (!strcmp(argv[1], "precheck")) return cmd_precheck(argc - 2, argv + 2);
728 if (!strcmp(argv[1], "make-synthetic")) return cmd_synth(argc - 2, argv + 2);
729 fprintf(stderr, "est4: unknown command %s\n", argv[1]);
730 return 2;
731}