diff --git a/.crumb b/.crumb index 5901f2c2c..2ea9c467f 100644 --- a/.crumb +++ b/.crumb @@ -75,8 +75,8 @@ "purpose": "Directory polyglot. Purpose not yet described by a human." }, { - "digest": "8178197a3e956890d6194e5b4fcc0e0b5c4ec67b0749f0d257f2ed17c8ca7465", - "last_commit": "559f6e5", + "digest": "0edca877e06d54b6be1e1a55ef36c288345b8d860bd07a74c38c736b4bd39ffb", + "last_commit": "547cda8", "name": "research", "purpose": "Directory research. Purpose not yet described by a human." }, @@ -94,7 +94,7 @@ }, { "digest": "6632b2d7fadadd84a7188d5ddefc5029ba0c0492cd29672269dd2b198f787112", - "last_commit": "d2ab554", + "last_commit": "19f73c7", "name": "tests", "purpose": "Directory tests. Purpose not yet described by a human." }, @@ -105,15 +105,15 @@ "purpose": "Directory tools. Purpose not yet described by a human." } ], - "children_root": "sha256:783eef0ebbd8a38a65d7de949d4db683f9249ffab82d976646b308c7c270ead1", - "compiled_at": "2026-10-09T21:50:08Z", + "children_root": "sha256:8e0588da14677e6de9ced1545c791d06096eb1e86f2d3e6a1ddbc9536985fa33", + "compiled_at": "2026-10-09T22:41:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:c829e7912cba7f90007613ec94eb49ed1ca3c4838ee887979777812130876e99", + "digest": "sha256:1447ea246c5527ec792d747b91d5c27f5541904ef04c165ec01b21b8571c3b05", "evidence_files": 4847, "evidence_root": "sha256:8a1e306ee977789a3394c51305afc3121a0ba0d5e1735b29b2cc16ffd12f668a", - "files": 6858, - "generated_at_commit": "d2ab554be81f4f7d7506afab8a6cfc9a0db64a27", - "source_tree": "sha256:ebe1b1d6bcad56600990a87c1a150151c3863929c7c814a23a7503031b7f6c79" + "files": 6876, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:0e6281e4b57b2856f45b9d1ddf5f77fdbfa6bce864b575c783b66eb30f80de33" }, "owner_lane": "", "provenance": { diff --git a/research/.crumb b/research/.crumb index 61c724f3f..48b24fc0b 100644 --- a/research/.crumb +++ b/research/.crumb @@ -20,6 +20,12 @@ "extensions": { "generated": { "children": [ + { + "digest": "fe3abca7c4f63727ca468b2a8deec5056c6efc45557a6d3b3919469a43849204", + "last_commit": "547cda8", + "name": "atemporal", + "purpose": "AT-0 Clock-Free Universe research program: relational (Page-Wootters) quantum models with no ext" + }, { "digest": "7597531ca9a2cdce9e840dda55ce639f86c4237eda3f2e3d1d5b10c599966a33", "last_commit": "458c57f", @@ -27,15 +33,15 @@ "purpose": "Directory research/dirac-oracle. Purpose not yet described by a human." } ], - "children_root": "sha256:1a933756dbe3d8d1d5b73fa0ec35a9bc07e17de29a2675f2e492c27b76d8ed70", - "compiled_at": "2026-10-04T18:19:24Z", + "children_root": "sha256:c2425e92d104ec358aae0d416df92fcb01ea9da33e7a143221a658509d628854", + "compiled_at": "2026-10-09T22:41:51Z", "compiler": "crumb-compile/1", - "digest": "sha256:8178197a3e956890d6194e5b4fcc0e0b5c4ec67b0749f0d257f2ed17c8ca7465", + "digest": "sha256:0edca877e06d54b6be1e1a55ef36c288345b8d860bd07a74c38c736b4bd39ffb", "evidence_files": 0, "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "files": 146, - "generated_at_commit": "cfd67162853eb0c0fbb73758e3dfb9837676e2a2", - "source_tree": "sha256:9552d21f4d776752253b7be8727c8ab716dc1b180f6c5e602b22a98f6d1ae78c" + "files": 164, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:bdcdca5f66f5bc4ad17e95704b536bf9b8e32c5a0a3ceca3c0bdb920e5a90cff" }, "owner_lane": "", "provenance": { diff --git a/research/atemporal/.crumb b/research/atemporal/.crumb new file mode 100644 index 000000000..cc5d1132a --- /dev/null +++ b/research/atemporal/.crumb @@ -0,0 +1,26 @@ +{ + "extensions": { + "generated": { + "children": [ + { + "digest": "ad454f336751fe02900ed1a66172f4ed7a13a454b20d586d9ce6736441022fe5", + "last_commit": "547cda8", + "name": "at0", + "purpose": "AT-0 V1: finite clock plus one qubit under the AT0_CASE_V1 / AT0_RESULT_V1 contracts" + } + ], + "children_root": "sha256:ca3c1b6e303d3574080cd75bbb7f7a55904db335b217b6183d55610877bda5c1", + "compiled_at": "2026-10-09T22:41:51Z", + "compiler": "crumb-compile/1", + "digest": "sha256:fe3abca7c4f63727ca468b2a8deec5056c6efc45557a6d3b3919469a43849204", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 18, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:6cbcb6a090eedd9120d7bc2e3aa818ab6bff80e2eebe7e0e1eceb647ceeff69a" + } + }, + "name": "atemporal", + "purpose": "AT-0 Clock-Free Universe research program: relational (Page-Wootters) quantum models with no external time parameter; contracts live in aien-architecture docs/plans/atemporal", + "schema_version": "1.0.0" +} diff --git a/research/atemporal/at0/.crumb b/research/atemporal/at0/.crumb new file mode 100644 index 000000000..964de4c28 --- /dev/null +++ b/research/atemporal/at0/.crumb @@ -0,0 +1,26 @@ +{ + "extensions": { + "generated": { + "children": [ + { + "digest": "f141e0a1f4d8e0008df9ea042d820f0cf18355a0ed185115ada9c31b2dd58cff", + "last_commit": "547cda8", + "name": "model", + "purpose": "Agent 3 candidate relational quantum engine in portable C11: state, Hamiltonians, constraint ker" + } + ], + "children_root": "sha256:99f8832d532a5420c7f6a480108ac882aca7416cf9d0de28f8f69de3d45eea84", + "compiled_at": "2026-10-09T22:41:51Z", + "compiler": "crumb-compile/1", + "digest": "sha256:ad454f336751fe02900ed1a66172f4ed7a13a454b20d586d9ce6736441022fe5", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 18, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:6cbcb6a090eedd9120d7bc2e3aa818ab6bff80e2eebe7e0e1eceb647ceeff69a" + } + }, + "name": "at0", + "purpose": "AT-0 V1: finite clock plus one qubit under the AT0_CASE_V1 / AT0_RESULT_V1 contracts", + "schema_version": "1.0.0" +} diff --git a/research/atemporal/at0/model/.crumb b/research/atemporal/at0/model/.crumb new file mode 100644 index 000000000..df7ee915e --- /dev/null +++ b/research/atemporal/at0/model/.crumb @@ -0,0 +1,26 @@ +{ + "extensions": { + "generated": { + "children": [ + { + "digest": "e9114c1e9534737dc1a4d49971f6abb3278e4dcf7c5b9c544795c90c8812bccc", + "last_commit": "547cda8", + "name": "tests", + "purpose": "Component tests and case files for the candidate engine" + } + ], + "children_root": "sha256:250f09a76e0e74b7f3921f23346262b006f7b267cf456f5d695a2be3c0fa7a65", + "compiled_at": "2026-10-09T22:41:51Z", + "compiler": "crumb-compile/1", + "digest": "sha256:f141e0a1f4d8e0008df9ea042d820f0cf18355a0ed185115ada9c31b2dd58cff", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 18, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:6cbcb6a090eedd9120d7bc2e3aa818ab6bff80e2eebe7e0e1eceb647ceeff69a" + } + }, + "name": "model", + "purpose": "Agent 3 candidate relational quantum engine in portable C11: state, Hamiltonians, constraint kernel, clock POVM, conditional states, Pauli probabilities, versioned case input and engine output", + "schema_version": "1.0.0" +} diff --git a/research/atemporal/at0/model/.gitignore b/research/atemporal/at0/model/.gitignore new file mode 100644 index 000000000..6b0236f71 --- /dev/null +++ b/research/atemporal/at0/model/.gitignore @@ -0,0 +1,2 @@ +build/ +build-asan/ diff --git a/research/atemporal/at0/model/README.md b/research/atemporal/at0/model/README.md new file mode 100644 index 000000000..101618275 --- /dev/null +++ b/research/atemporal/at0/model/README.md @@ -0,0 +1,141 @@ +# AT-0 candidate relational quantum engine (research model) + +**Status:** candidate implementation, research directory. Not a gate, not evidence, not a contract. +**Program:** AT-0 Clock-Free Universe, tracking issue aien-dev/omega#358. Pinned to: frozen contracts `AT0_CASE_V1` / `AT0_RESULT_V1` at aien-architecture `044c9d1`; charter (ownership, gates) at aien-architecture `d390939`; draft `AT0_SPEC.md` at aien-architecture PR #176 head `0efd1a14` (DRAFT, not merged: the hand tables used by the tests must be re-verified when it merges). +**Built from:** omega `19f73c7`. **Language:** portable C11 (`__int128` via `__extension__` for exact rationals), +`-lm` only, single thread, no GPU, no network, no Python. + +## What it does + +Given an `AT0_CASE_V1` case file, the engine builds a finite Page-Wootters universe (a clock of dimension +N and one qubit), projects the declared reference product state onto the exact kernel of the total +constraint `H_total = H_C (x) I + I (x) H_S`, measures the clock with the covariant discrete POVM +`F_k = w |t_k> (x) |psi_0>)`, residual `||H_total Psi_hat||`, exact decision whether `Psi = 0` | +| Internal clock POVM | `at0_povm.c` | `|t_k> = N^(-1/2) sum_j exp(-2 pi i E_j k tau) |E_j>` with the turn count reduced exactly before `cos`/`sin`; residual `||sum_k F_k - I||_F` | +| Conditional state | `at0_conditional.c` | `phi_k = ( [--reversed]` | + +## Build and test + +``` +cd research/atemporal/at0/model +./build.sh # plain: -std=c11 -Wall -Wextra -Werror -pedantic -O2, into ./build +./build.sh asan # sanitizer: -O1 -g -fsanitize=address,undefined, into ./build-asan +./build/at0-tests tests/cases +./build/at0-model tests/cases/kat-ideal-qubit-n4.case +``` + +Nothing is added to omega's `Makefile` or `mk/`; `make test` is unaffected. `tests/mkcase.sh ` stamps +`case_id` and `acceptance_id` onto a hand-written case body (shell and `sha256sum` only); it reproduces +the published digests of the contract's section 6 example. + +Exit codes of `at0-model`: 0 success (engine text on stdout); 2 case refused (`AT0_CASE_REFUSED ` +on stderr, one line, per AT0_RESULT_V1 section 5); 1 any other error (`AT0_ENGINE_ERROR `). + +## Output format: `OMEGA-AT0-ENGINE v1` + +A private format of this directory (not a contract, not an identity, no digest is defined over it). +Header lines, then the case identities and `case_file_sha256`, then a `numerics` block +(`arithmetic BINARY64`, `bound_kind ESTIMATED`, `threads 1`), then a `values` block that is exactly the +AT0_RESULT_V1 section 1 values block **without** the oracle's `reference` lines. A runner can splice this +block, plus the oracle's reference lines, into a full result. Value tokens follow AT0_RESULT_V1 section 2. + +## Mathematical assumptions + +1. Units hbar = 1; clock energies and `h0, hx, hy, hz` are exact rationals from the case. +2. `|h|^2 = hx^2 + hy^2 + hz^2` is the square of a rational (validated; else `CASE_IRRATIONAL_SPECTRUM`), + so the system eigenvalues `h0 +/- |h|` are rational and the kernel test is exact. +3. Kernel of `H_total` is spanned by `|E_j> (x) |e_s>` with `E_j + e_s = 0`; because energies are strictly + increasing, each system eigenvalue is matched by at most one clock energy. When `|h| = 0` both system + components of a matched energy are in the kernel. +4. Eigenvectors: for `|h| > 0` and `|h| + hz != 0`, `v_- = (-(hx - i hy), |h| + hz) / sqrt(2|h|(|h|+hz))` and + `v_+ = (|h| + hz, hx + i hy) / same`; for `|h| + hz = 0` they are `|0>, |1>`; for `|h| = 0` the + computational basis. The decision whether `Psi = P_0(|t_r> (x) |psi_0>)` is the zero vector is made + exactly in rationals (overlaps `` with the unnormalized rational eigenvectors), never by a + floating-point threshold. +5. Clock phase `exp(-2 pi i E_j k tau)`: the turn count `E_j k tau` is reduced exactly to `[-1/2, 1/2)` in + 128-bit integer arithmetic, converted to binary64 (exact, both numerator and denominator are below 2^53), + then passed to `cos`/`sin`. No lookup table; special angles are not special-cased. +6. The POVM is not assumed to resolve the identity; the residual is measured and reported. +7. Conditional probabilities are Born-rule traces against `rho_k`; purity, pair sums and ranges are + consequences, not inputs. + +Derived consequence used by the tests, not assumed by the engine: when both system eigenvalues are matched, +`phi_k = (1/N) exp(-i H_S (t_k - t_r)) |psi_0>` restricted to the matched eigenspaces, so the conditional +state is the Schrodinger evolution read at `t_k - t_r` with `t_k = 2 pi k tau`, and `p(k) = w / N` for +every label whether or not the POVM is normalized. + +## Error estimates (`bound_kind ESTIMATED`, not a proof) + +With `eps = 2^-53`, N = `clock_dim`, M = `clock_label_count`, `w = povm_weight`, +`Hmax = max_j |E_j| + |h0| + |h|`, each bound is a first-order operation-count estimate with a safety factor, +rounded up to seven significant decimal digits plus one unit: + +| Quantity | Estimate | +|---|---| +| `constraint_residual` | `32 eps N (Hmax + 1)` | +| `povm_residual` | `16 eps N (M w + 1)` | +| `clock_probability k` | `32 eps (N + 4) (p(k) + 1)` | +| `pauli k A s` | `32 eps (N + 8)` | + +Assumes glibc `cos`/`sin`/`sqrt` within 1 ulp on the build target. The tests check that every measured +deviation from the hand table and from the test-side Schrodinger reference lies inside the stated bound. +A `RIGOROUS` bound would need directed-rounding interval arithmetic with enclosures of `cos` and `sin`; it is +not provided here, so a case with `min_bound_kind RIGOROUS` will fail `BOUND_KIND_INSUFFICIENT` by design. + +## Supported and unsupported cases + +**Supported:** every valid `AT0_CASE_V1` case: `2 <= N <= 64`, `1 <= M <= 256`, any rational energies, +field, weight and tau within the contract limits, any nonzero rational reference state, any reference label +(phase offset), any `|h|` (frequency `omega = 2|h|`), degenerate `|h| = 0`, trivial kernel, half-covered +spectrum, non-normalized POVMs, exactly-zero projections. + +**Unsupported / not provided:** clock-system interaction (`interaction NONE` only); system dimension other +than 2; `RIGOROUS` bounds; shot sampling; the oracle's `reference` lines and the full `AT0_RESULT_V1` file +(provenance, verdict, digests belong to the runner/verifier); CI wiring; GPU or parallel execution. + +## Behaviour in corner cases (to be confirmed against Agent 4's hand derivations) + +- Trivial kernel or exactly-zero projection: `constraint_residual undefined 0@0`, every label `UNDEFINED`, + every `clock_probability` and `pauli` value `undefined 0@0`. AT0_RESULT_V1 does not say which label status + to write when `Psi = 0`; `UNDEFINED` is the choice here and is an open contract question for Agent 0. +- Contract limits on written tokens (|n|, d <= 2^20; scaled k <= 40) are judged in rule 3 as `CASE_INVALID_PARAMETER`, + after the shape (rule 1) and version (rule 2) checks. A token longer than 18 digits is parsed as a saturation value + (never an integer overflow) and refused the same way; a scaled numerator above 10^18 - 1 is refused as unsupported. +- Derived exact quantities (`|h|`, `h0 +/- |h|`, kernel sums, exact overlaps) use 128-bit intermediates and must fit + 63-bit numerators and denominators; a case whose derived rationals do not fit stops with `AT0_ENGINE_ERROR ERR_OVERFLOW` + (explicit, never a wrong number). No valid case within the contract limits is known to hit this. +- Trivial kernel ruling (Agent 0, omega#358): `povm_residual` is still computed, nothing is divided, every label is + `UNDEFINED`; this engine already behaves that way. Result files move to `AT0_RESULT_V2`; the `contract` line of the + engine output names it, and the values block is unchanged. +- Independent review (Claude Opus 5.5 over the full diff, 2026-10-09) found five arithmetic-limit defects, all fixed and + covered by `test_review_findings`; it confirmed the eigenvectors, kernel projection, phase reduction, Born rule and + identity hashing. Codex review was unavailable (usage limit). +- `tests/cases/kat-ideal-qubit-n4.case` is the contract's section 6 example byte for byte + (`case_file_sha256 ed16c95c...`). + +## Ownership + +The charter at aien-architecture `d390939` (section 7, aligned with omega#358) places this candidate engine under +`research/atemporal/at0/model/` (Agent 3). The oracle (`at0/oracle/`, Agent 2, Rust, std only) and the evaluator share no +source, object or numerical routine with this directory; the only shared omega source is `src/sha256.c`. diff --git a/research/atemporal/at0/model/at0_case.c b/research/atemporal/at0/model/at0_case.c new file mode 100644 index 000000000..126217703 --- /dev/null +++ b/research/atemporal/at0/model/at0_case.c @@ -0,0 +1,536 @@ +/* AT0_CASE_V1 codec: parse, validate (rules 1..6 in contract order), compute + * identities, emit canonical bytes. The only shared omega source is sha256. */ +#include "at0_model.h" +#include "sha256.h" + +#include +#include +#include + +const char *const at0_failure_codes[AT0_FAILURE_CODE_COUNT] = { + "BOUND_KIND_INSUFFICIENT", "CONDITIONAL_UNDEFINED", "CONSTRAINT_RESIDUAL_EXCEEDED", + "NONFINITE_VALUE", "POVM_NORMALIZATION_EXCEEDED", "PRECISION_INSUFFICIENT", + "PROBABILITY_OUT_OF_RANGE", "PROBABILITY_SUM_EXCEEDED", "SCHRODINGER_DEVIATION_EXCEEDED", + "TRIVIAL_PHYSICAL_STATE" +}; + +#define LINE_CAP 4096 + +typedef struct { + const char *line[LINE_CAP]; + size_t len[LINE_CAP]; + int count; + int pos; +} lines_t; + +/* rule 1: byte shape. Fills line table pointing into a NUL-free copy. */ +static at0_status split_lines(const uint8_t *bytes, size_t len, char *copy, lines_t *L) +{ + if (len == 0 || bytes[len - 1] != '\n') return AT0_CASE_PARSE_ERROR; + memcpy(copy, bytes, len); + L->count = 0; L->pos = 0; + size_t start = 0; + for (size_t i = 0; i < len; i++) { + uint8_t b = bytes[i]; + if (b == '\n') { + size_t n = i - start; + if (n == 0) return AT0_CASE_PARSE_ERROR; /* blank line */ + if (copy[start] == ' ' || copy[i - 1] == ' ') return AT0_CASE_PARSE_ERROR; + for (size_t j = start + 1; j < i; j++) + if (copy[j] == ' ' && copy[j - 1] == ' ') return AT0_CASE_PARSE_ERROR; + if (L->count >= LINE_CAP) return AT0_CASE_PARSE_ERROR; + copy[i] = 0; + L->line[L->count] = copy + start; L->len[L->count] = n; L->count++; + start = i + 1; + } else if (b < 0x20 || b > 0x7E) { + return AT0_CASE_PARSE_ERROR; + } + } + return AT0_OK; +} + +static const char *next_line(lines_t *L) { return L->pos < L->count ? L->line[L->pos++] : NULL; } + +/* " ": returns rest or NULL if key does not match */ +static const char *key_rest(const char *line, const char *key) +{ + size_t k = strlen(key); + if (!line || strncmp(line, key, k) != 0 || line[k] != ' ') return NULL; + return line + k + 1; +} + +static int valid_label(const char *s) +{ + size_t n = strlen(s); + if (n < 1 || n > AT0_LABEL_LEN || !(s[0] >= 'a' && s[0] <= 'z')) return 0; + for (size_t i = 1; i < n; i++) + if (!((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= '0' && s[i] <= '9') || s[i] == '_')) return 0; + return 1; +} +static int valid_name(const char *s) +{ + size_t n = strlen(s); + if (n < 1 || n > AT0_NAME_LEN || !isalnum((unsigned char)s[0])) return 0; + for (size_t i = 1; i < n; i++) + if (!(isalnum((unsigned char)s[i]) || s[i] == '_' || s[i] == '.' || s[i] == '-')) return 0; + return 1; +} +static int valid_digest(const char *s) +{ + if (strlen(s) != AT0_DIGEST_HEX) return 0; + for (int i = 0; i < AT0_DIGEST_HEX; i++) + if (!((s[i] >= '0' && s[i] <= '9') || (s[i] >= 'a' && s[i] <= 'f'))) return 0; + return 1; +} +static int parse_small_int(const char *s, long *out) +{ + /* canonical nonnegative integer token, bounded so counts cannot overflow */ + size_t n = strlen(s); + if (n == 0 || n > 9) return 0; + if (s[0] == '0' && n > 1) return 0; + long v = 0; + for (size_t i = 0; i < n; i++) { if (!isdigit((unsigned char)s[i])) return 0; v = v * 10 + (s[i] - '0'); } + *out = v; return 1; +} + +/* split a comma list in place (no spaces, no empty items, no trailing comma) */ +static int split_list(char *s, char **items, int cap, int *count) +{ + *count = 0; + if (strcmp(s, "none") == 0) return 1; + if (*s == 0) return 0; + char *p = s; + for (;;) { + char *c = strchr(p, ','); + if (c) *c = 0; + if (*p == 0) return 0; + if (*count < cap) items[*count] = p; + (*count)++; + if (!c) break; + p = c + 1; + } + return 1; +} + +typedef struct { + /* raw values that are only judged after the shape pass */ + char header[64], domain[64], contract[64]; + char model_family[64], energy_unit[64], system_dim[16], interaction[32], constraint[32], + physical_state[48], clock_povm[48], observables[64]; + long clock_dim, label_count; + int energies_seen; + int expected_codes_raw_count; + char expected_codes_raw[AT0_FAILURE_CODE_COUNT + 1][48]; + int expected_codes_overflow; +} raw_t; + +static at0_status copy_tok(const char *src, char *dst, size_t cap) +{ + if (!src || strlen(src) >= cap) return AT0_CASE_PARSE_ERROR; + strcpy(dst, src); return AT0_OK; +} + +#define NEED(expr) do { at0_status st_ = (expr); if (st_ != AT0_OK) return st_; } while (0) +#define FIXED(L, text) do { const char *l_ = next_line(L); if (!l_ || strcmp(l_, text) != 0) return AT0_CASE_PARSE_ERROR; } while (0) +#define KEYED(L, key, rest) do { rest = key_rest(next_line(L), key); if (!rest) return AT0_CASE_PARSE_ERROR; } while (0) + +/* rule 1 (shape + token canonicality) for the whole file */ +static at0_status parse_shape(lines_t *L, at0_case *c, raw_t *r) +{ + const char *rest; + char tmp[AT0_LINE_MAX]; + memset(c, 0, sizeof *c); memset(r, 0, sizeof *r); + + KEYED(L, "OMEGA-AT0-CASE", rest); NEED(copy_tok(rest, r->header, sizeof r->header)); + KEYED(L, "domain", rest); NEED(copy_tok(rest, r->domain, sizeof r->domain)); + KEYED(L, "contract", rest); NEED(copy_tok(rest, r->contract, sizeof r->contract)); + KEYED(L, "case_name", rest); + if (!valid_name(rest)) return AT0_CASE_PARSE_ERROR; + strcpy(c->name, rest); + FIXED(L, "begin semantic"); + KEYED(L, "model_family", rest); NEED(copy_tok(rest, r->model_family, sizeof r->model_family)); + KEYED(L, "energy_unit", rest); NEED(copy_tok(rest, r->energy_unit, sizeof r->energy_unit)); + KEYED(L, "clock_dim", rest); if (!parse_small_int(rest, &r->clock_dim)) return AT0_CASE_PARSE_ERROR; + KEYED(L, "clock_energies", rest); + { + if (strlen(rest) >= sizeof tmp) return AT0_CASE_PARSE_ERROR; + strcpy(tmp, rest); + char *items[AT0_CLOCK_DIM_MAX]; int n; + if (!split_list(tmp, items, AT0_CLOCK_DIM_MAX, &n) || n == 0) return AT0_CASE_PARSE_ERROR; + if (n != r->clock_dim) return AT0_CASE_PARSE_ERROR; + for (int i = 0; i < n && i < AT0_CLOCK_DIM_MAX; i++) NEED(at0_rat_parse(items[i], &c->clock_energies[i])); + r->energies_seen = n; + } + KEYED(L, "system_dim", rest); NEED(copy_tok(rest, r->system_dim, sizeof r->system_dim)); + KEYED(L, "system_hamiltonian_pauli", rest); + { + if (strlen(rest) >= sizeof tmp) return AT0_CASE_PARSE_ERROR; + strcpy(tmp, rest); + char *items[4]; int n; + if (!split_list(tmp, items, 4, &n) || n != 4) return AT0_CASE_PARSE_ERROR; + NEED(at0_rat_parse(items[0], &c->h0)); NEED(at0_rat_parse(items[1], &c->hx)); + NEED(at0_rat_parse(items[2], &c->hy)); NEED(at0_rat_parse(items[3], &c->hz)); + } + KEYED(L, "interaction", rest); NEED(copy_tok(rest, r->interaction, sizeof r->interaction)); + KEYED(L, "constraint", rest); NEED(copy_tok(rest, r->constraint, sizeof r->constraint)); + KEYED(L, "physical_state", rest); NEED(copy_tok(rest, r->physical_state, sizeof r->physical_state)); + KEYED(L, "reference_clock_label", rest); + if (!valid_label(rest)) return AT0_CASE_PARSE_ERROR; + strcpy(c->reference_clock_label, rest); + KEYED(L, "reference_system_state", rest); + { + if (strlen(rest) >= sizeof tmp) return AT0_CASE_PARSE_ERROR; + strcpy(tmp, rest); + char *items[2]; int n; + if (!split_list(tmp, items, 2, &n) || n != 2) return AT0_CASE_PARSE_ERROR; + NEED(at0_crat_parse(items[0], &c->psi0[0])); NEED(at0_crat_parse(items[1], &c->psi0[1])); + } + KEYED(L, "clock_povm", rest); NEED(copy_tok(rest, r->clock_povm, sizeof r->clock_povm)); + KEYED(L, "povm_tau_turns", rest); NEED(at0_rat_parse(rest, &c->povm_tau_turns)); + KEYED(L, "povm_weight", rest); NEED(at0_rat_parse(rest, &c->povm_weight)); + KEYED(L, "clock_label_count", rest); if (!parse_small_int(rest, &r->label_count)) return AT0_CASE_PARSE_ERROR; + for (long k = 0; k < r->label_count; k++) { + KEYED(L, "clock_label", rest); + if (strlen(rest) >= sizeof tmp) return AT0_CASE_PARSE_ERROR; + strcpy(tmp, rest); + char *sp = strchr(tmp, ' '); + if (!sp) return AT0_CASE_PARSE_ERROR; + *sp = 0; + long idx; + if (!parse_small_int(tmp, &idx) || idx != k) return AT0_CASE_PARSE_ERROR; + if (!valid_label(sp + 1)) return AT0_CASE_PARSE_ERROR; + if (k < AT0_LABEL_MAX) strcpy(c->labels[k], sp + 1); + } + KEYED(L, "observables", rest); NEED(copy_tok(rest, r->observables, sizeof r->observables)); + FIXED(L, "end semantic"); + FIXED(L, "begin acceptance"); + KEYED(L, "control_kind", rest); + if (strcmp(rest, "POSITIVE") == 0) c->control_kind = AT0_CTRL_POSITIVE; + else if (strcmp(rest, "NEGATIVE") == 0) c->control_kind = AT0_CTRL_NEGATIVE; + else return AT0_CASE_PARSE_ERROR; + KEYED(L, "expected_outcome", rest); + if (strcmp(rest, "PASS") == 0) c->expected_outcome = AT0_EXPECT_PASS; + else if (strcmp(rest, "FAIL") == 0) c->expected_outcome = AT0_EXPECT_FAIL; + else return AT0_CASE_PARSE_ERROR; + KEYED(L, "expected_failure_codes", rest); + { + if (strlen(rest) >= sizeof tmp) return AT0_CASE_PARSE_ERROR; + strcpy(tmp, rest); + char *items[AT0_FAILURE_CODE_COUNT + 1]; int n; + if (!split_list(tmp, items, AT0_FAILURE_CODE_COUNT + 1, &n)) return AT0_CASE_PARSE_ERROR; + r->expected_codes_raw_count = n; + if (n > AT0_FAILURE_CODE_COUNT) r->expected_codes_overflow = 1; + for (int i = 0; i < n && i <= AT0_FAILURE_CODE_COUNT; i++) + NEED(copy_tok(items[i], r->expected_codes_raw[i], sizeof r->expected_codes_raw[i])); + } + KEYED(L, "min_bound_kind", rest); + if (strcmp(rest, "RIGOROUS") == 0) c->min_bound_kind = AT0_BOUND_RIGOROUS; + else if (strcmp(rest, "ESTIMATED") == 0) c->min_bound_kind = AT0_BOUND_ESTIMATED; + else if (strcmp(rest, "NONE") == 0) c->min_bound_kind = AT0_BOUND_NONE; + else return AT0_CASE_PARSE_ERROR; + KEYED(L, "tol_constraint_residual", rest); NEED(at0_scaled_parse(rest, &c->tol_constraint_residual)); + KEYED(L, "tol_povm_residual", rest); NEED(at0_scaled_parse(rest, &c->tol_povm_residual)); + KEYED(L, "tol_probability", rest); NEED(at0_scaled_parse(rest, &c->tol_probability)); + KEYED(L, "tol_zero_probability", rest); NEED(at0_scaled_parse(rest, &c->tol_zero_probability)); + KEYED(L, "tol_schrodinger", rest); NEED(at0_scaled_parse(rest, &c->tol_schrodinger)); + FIXED(L, "end acceptance"); + KEYED(L, "case_id", rest); + if (!valid_digest(rest)) return AT0_CASE_PARSE_ERROR; + strcpy(c->case_id, rest); + KEYED(L, "acceptance_id", rest); + if (!valid_digest(rest)) return AT0_CASE_PARSE_ERROR; + strcpy(c->acceptance_id, rest); + FIXED(L, "end"); + if (L->pos != L->count) return AT0_CASE_PARSE_ERROR; /* trailing lines */ + return AT0_OK; +} + +/* rule 3: ranges and fixed values */ +static at0_status check_parameters(at0_case *c, const raw_t *r) +{ + /* contract limits on written tokens (AT0_CASE_V1 section 2), judged here so that rules 1 and 2 come first */ + for (int j = 0; j < r->energies_seen && j < AT0_CLOCK_DIM_MAX; j++) + if (!at0_rat_in_limits(c->clock_energies[j])) return AT0_CASE_INVALID_PARAMETER; + if (!at0_rat_in_limits(c->h0) || !at0_rat_in_limits(c->hx) || !at0_rat_in_limits(c->hy) || !at0_rat_in_limits(c->hz)) return AT0_CASE_INVALID_PARAMETER; + for (int s = 0; s < AT0_SYSTEM_DIM; s++) + if (!at0_rat_in_limits(c->psi0[s].re) || !at0_rat_in_limits(c->psi0[s].im)) return AT0_CASE_INVALID_PARAMETER; + if (!at0_rat_in_limits(c->povm_tau_turns) || !at0_rat_in_limits(c->povm_weight)) return AT0_CASE_INVALID_PARAMETER; + if (!at0_scaled_in_limits(c->tol_constraint_residual) || !at0_scaled_in_limits(c->tol_povm_residual) || + !at0_scaled_in_limits(c->tol_probability) || !at0_scaled_in_limits(c->tol_zero_probability) || + !at0_scaled_in_limits(c->tol_schrodinger)) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->model_family, "PAGE_WOOTTERS_FINITE_IDEAL") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->energy_unit, "DIMENSIONLESS_HBAR_1") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->system_dim, "2") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->interaction, "NONE") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->constraint, "SUM_HC_HS") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->physical_state, "NULLSPACE_PROJECTION") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->clock_povm, "COVARIANT_DISCRETE") != 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(r->observables, "PAULI_X,PAULI_Y,PAULI_Z") != 0) return AT0_CASE_INVALID_PARAMETER; + if (r->clock_dim < AT0_CLOCK_DIM_MIN || r->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_CASE_INVALID_PARAMETER; + c->clock_dim = (int)r->clock_dim; + for (int j = 1; j < c->clock_dim; j++) + if (at0_rat_cmp(c->clock_energies[j - 1], c->clock_energies[j]) >= 0) return AT0_CASE_INVALID_PARAMETER; + if (at0_rat_is_zero(c->psi0[0].re) && at0_rat_is_zero(c->psi0[0].im) && + at0_rat_is_zero(c->psi0[1].re) && at0_rat_is_zero(c->psi0[1].im)) return AT0_CASE_INVALID_PARAMETER; + if (c->povm_weight.n <= 0) return AT0_CASE_INVALID_PARAMETER; + if (c->povm_tau_turns.n <= 0) return AT0_CASE_INVALID_PARAMETER; + if (r->label_count < 1 || r->label_count > AT0_LABEL_MAX) return AT0_CASE_INVALID_PARAMETER; + c->label_count = (int)r->label_count; + c->reference_index = -1; + for (int k = 0; k < c->label_count; k++) { + for (int l = 0; l < k; l++) + if (strcmp(c->labels[k], c->labels[l]) == 0) return AT0_CASE_INVALID_PARAMETER; + if (strcmp(c->labels[k], c->reference_clock_label) == 0) c->reference_index = k; + } + if (c->reference_index < 0) return AT0_CASE_INVALID_PARAMETER; + return AT0_OK; +} + +/* rule 4: |h|^2 must be the square of a rational */ +static at0_status check_spectrum(at0_case *c) +{ + at0_rat x2, y2, z2, s; + at0_status st; + if ((st = at0_rat_mul(c->hx, c->hx, &x2)) != AT0_OK) return AT0_ERR_OVERFLOW; + if ((st = at0_rat_mul(c->hy, c->hy, &y2)) != AT0_OK) return AT0_ERR_OVERFLOW; + if ((st = at0_rat_mul(c->hz, c->hz, &z2)) != AT0_OK) return AT0_ERR_OVERFLOW; + if ((st = at0_rat_add(x2, y2, &s)) != AT0_OK) return AT0_ERR_OVERFLOW; + if ((st = at0_rat_add(s, z2, &s)) != AT0_OK) return AT0_ERR_OVERFLOW; + int sq; + if ((st = at0_rat_sqrt_exact(s, &c->h_norm, &sq)) != AT0_OK) return AT0_ERR_OVERFLOW; + if (!sq) return AT0_CASE_IRRATIONAL_SPECTRUM; + return AT0_OK; +} + +/* rule 6: expected failure code list */ +static at0_status check_acceptance(at0_case *c, const raw_t *r) +{ + c->expected_failure_count = 0; + if (c->expected_outcome == AT0_EXPECT_PASS) { + return r->expected_codes_raw_count == 0 ? AT0_OK : AT0_CASE_INVALID_PARAMETER; + } + if (r->expected_codes_raw_count == 0 || r->expected_codes_overflow) return AT0_CASE_INVALID_PARAMETER; + int prev = -1; + for (int i = 0; i < r->expected_codes_raw_count; i++) { + int idx = -1; + for (int j = 0; j < AT0_FAILURE_CODE_COUNT; j++) + if (strcmp(r->expected_codes_raw[i], at0_failure_codes[j]) == 0) { idx = j; break; } + if (idx < 0 || idx <= prev) return AT0_CASE_INVALID_PARAMETER; /* unknown, duplicate or unsorted */ + c->expected_failure_idx[i] = idx; prev = idx; + } + c->expected_failure_count = r->expected_codes_raw_count; + return AT0_OK; +} + +/* ---- emission ------------------------------------------------------------ */ +typedef struct { char *buf; size_t cap; size_t len; int overflow; } out_t; + +static void put(out_t *o, const char *s) +{ + size_t n = strlen(s); + if (o->len + n >= o->cap) { o->overflow = 1; return; } + memcpy(o->buf + o->len, s, n); o->len += n; o->buf[o->len] = 0; +} +static void putf_rat(out_t *o, at0_rat r) { char t[64]; at0_rat_format(r, t, sizeof t); put(o, t); } + +static void emit_semantic(const at0_case *c, out_t *o) +{ + char t[128]; + put(o, "begin semantic\n"); + put(o, "model_family PAGE_WOOTTERS_FINITE_IDEAL\n"); + put(o, "energy_unit DIMENSIONLESS_HBAR_1\n"); + snprintf(t, sizeof t, "clock_dim %d\n", c->clock_dim); put(o, t); + put(o, "clock_energies "); + for (int j = 0; j < c->clock_dim; j++) { if (j) put(o, ","); putf_rat(o, c->clock_energies[j]); } + put(o, "\n"); + put(o, "system_dim 2\n"); + put(o, "system_hamiltonian_pauli "); + putf_rat(o, c->h0); put(o, ","); putf_rat(o, c->hx); put(o, ","); putf_rat(o, c->hy); put(o, ","); putf_rat(o, c->hz); + put(o, "\n"); + put(o, "interaction NONE\n"); + put(o, "constraint SUM_HC_HS\n"); + put(o, "physical_state NULLSPACE_PROJECTION\n"); + snprintf(t, sizeof t, "reference_clock_label %s\n", c->reference_clock_label); put(o, t); + put(o, "reference_system_state "); + at0_crat_format(c->psi0[0], t, sizeof t); put(o, t); put(o, ","); + at0_crat_format(c->psi0[1], t, sizeof t); put(o, t); put(o, "\n"); + put(o, "clock_povm COVARIANT_DISCRETE\n"); + put(o, "povm_tau_turns "); putf_rat(o, c->povm_tau_turns); put(o, "\n"); + put(o, "povm_weight "); putf_rat(o, c->povm_weight); put(o, "\n"); + snprintf(t, sizeof t, "clock_label_count %d\n", c->label_count); put(o, t); + for (int k = 0; k < c->label_count; k++) { snprintf(t, sizeof t, "clock_label %d %s\n", k, c->labels[k]); put(o, t); } + put(o, "observables PAULI_X,PAULI_Y,PAULI_Z\n"); + put(o, "end semantic\n"); +} + +static void emit_acceptance(const at0_case *c, out_t *o) +{ + char t[128]; + put(o, "begin acceptance\n"); + put(o, c->control_kind == AT0_CTRL_POSITIVE ? "control_kind POSITIVE\n" : "control_kind NEGATIVE\n"); + put(o, c->expected_outcome == AT0_EXPECT_PASS ? "expected_outcome PASS\n" : "expected_outcome FAIL\n"); + put(o, "expected_failure_codes "); + if (c->expected_failure_count == 0) put(o, "none"); + for (int i = 0; i < c->expected_failure_count; i++) { if (i) put(o, ","); put(o, at0_failure_codes[c->expected_failure_idx[i]]); } + put(o, "\n"); + put(o, c->min_bound_kind == AT0_BOUND_RIGOROUS ? "min_bound_kind RIGOROUS\n" + : c->min_bound_kind == AT0_BOUND_ESTIMATED ? "min_bound_kind ESTIMATED\n" : "min_bound_kind NONE\n"); + at0_scaled_format(c->tol_constraint_residual, t, sizeof t); put(o, "tol_constraint_residual "); put(o, t); put(o, "\n"); + at0_scaled_format(c->tol_povm_residual, t, sizeof t); put(o, "tol_povm_residual "); put(o, t); put(o, "\n"); + at0_scaled_format(c->tol_probability, t, sizeof t); put(o, "tol_probability "); put(o, t); put(o, "\n"); + at0_scaled_format(c->tol_zero_probability, t, sizeof t); put(o, "tol_zero_probability "); put(o, t); put(o, "\n"); + at0_scaled_format(c->tol_schrodinger, t, sizeof t); put(o, "tol_schrodinger "); put(o, t); put(o, "\n"); + put(o, "end acceptance\n"); +} + +long at0_case_emit(const at0_case *c, char *buf, size_t cap) +{ + if (!c || !buf || cap == 0) return -1; + out_t o = { buf, cap, 0, 0 }; + char t[512]; + buf[0] = 0; + put(&o, "OMEGA-AT0-CASE v1\ndomain omega.at0.case.v1\ncontract AT0_CASE_V1\n"); + snprintf(t, sizeof t, "case_name %s\n", c->name); put(&o, t); + emit_semantic(c, &o); + emit_acceptance(c, &o); + snprintf(t, sizeof t, "case_id %s\nacceptance_id %s\nend\n", c->case_id, c->acceptance_id); put(&o, t); + return o.overflow ? -1 : (long)o.len; +} + +static void hex_digest(const uint8_t d[32], char out[AT0_DIGEST_HEX + 1]) +{ + static const char hx[] = "0123456789abcdef"; + for (int i = 0; i < 32; i++) { out[2 * i] = hx[d[i] >> 4]; out[2 * i + 1] = hx[d[i] & 15]; } + out[AT0_DIGEST_HEX] = 0; +} + +static void tagged_digest(const char *tag, const char *text, size_t len, char out[AT0_DIGEST_HEX + 1]) +{ + sha256_ctx ctx; uint8_t d[32]; uint8_t zero = 0; + sha256_init(&ctx); + sha256_update(&ctx, (const uint8_t *)tag, strlen(tag)); + sha256_update(&ctx, &zero, 1); + sha256_update(&ctx, (const uint8_t *)text, len); + sha256_final(&ctx, d); + hex_digest(d, out); +} + +at0_status at0_case_identities(const at0_case *c, char case_id[AT0_DIGEST_HEX + 1], + char acceptance_id[AT0_DIGEST_HEX + 1]) +{ + if (!c || !case_id || !acceptance_id) return AT0_ERR_ARGUMENT; + char *buf = malloc(AT0_LINE_MAX * 4); + if (!buf) return AT0_ERR_INTERNAL; + out_t o = { buf, AT0_LINE_MAX * 4, 0, 0 }; + buf[0] = 0; + emit_semantic(c, &o); + if (o.overflow) { free(buf); return AT0_ERR_INTERNAL; } + tagged_digest("omega.at0.case.v1", buf, o.len, case_id); + o.len = 0; buf[0] = 0; + emit_acceptance(c, &o); + if (o.overflow) { free(buf); return AT0_ERR_INTERNAL; } + tagged_digest("omega.at0.acceptance.v1", buf, o.len, acceptance_id); + free(buf); + return AT0_OK; +} + +at0_status at0_case_parse(const uint8_t *bytes, size_t len, at0_case *out) +{ + if (!bytes || !out) return AT0_ERR_ARGUMENT; + if (len > (size_t)LINE_CAP * 256) return AT0_CASE_PARSE_ERROR; + char *copy = malloc(len + 1); + lines_t *L = malloc(sizeof *L); + raw_t *r = malloc(sizeof *r); + char *re = malloc(len + 1); + at0_status st = AT0_ERR_INTERNAL; + if (!copy || !L || !r || !re) goto done; + + /* rule 1 */ + if ((st = split_lines(bytes, len, copy, L)) != AT0_OK) goto done; + if ((st = parse_shape(L, out, r)) != AT0_OK) goto done; + /* rule 2 */ + if (strcmp(r->header, "v1") != 0 || strcmp(r->domain, "omega.at0.case.v1") != 0 || + strcmp(r->contract, "AT0_CASE_V1") != 0) { st = AT0_CASE_UNSUPPORTED_VERSION; goto done; } + /* rule 3 */ + if ((st = check_parameters(out, r)) != AT0_OK) goto done; + /* canonical-form guard: the parsed case must re-emit byte for byte */ + { + /* the emitted text uses parsed codes; copy raw codes so the guard sees the file's list */ + at0_case tmp = *out; + tmp.expected_failure_count = 0; + int ok = 1; + if (r->expected_codes_raw_count > 0 && !r->expected_codes_overflow) { + for (int i = 0; i < r->expected_codes_raw_count; i++) { + int idx = -1; + for (int j = 0; j < AT0_FAILURE_CODE_COUNT; j++) + if (strcmp(r->expected_codes_raw[i], at0_failure_codes[j]) == 0) idx = j; + if (idx < 0) { ok = 0; break; } + tmp.expected_failure_idx[i] = idx; + } + tmp.expected_failure_count = r->expected_codes_raw_count; + } + if (ok && !r->expected_codes_overflow) { + long n = at0_case_emit(&tmp, re, len + 1); + if (n != (long)len || memcmp(re, bytes, len) != 0) { st = AT0_CASE_NONCANONICAL; goto done; } + } + } + /* rule 4 */ + if ((st = check_spectrum(out)) != AT0_OK) goto done; + /* rule 5 */ + { + char cid[AT0_DIGEST_HEX + 1], aid[AT0_DIGEST_HEX + 1]; + at0_case tmp = *out; + /* acceptance text must be hashed exactly as written; raw codes are canonical only if rule 6 passes, + * so hash the file's own acceptance lines instead of re-emitting them */ + (void)tmp; + size_t a0 = 0, a1 = 0, s0 = 0, s1 = 0; + for (int i = 0; i < L->count; i++) { + if (strcmp(L->line[i], "begin semantic") == 0) s0 = (size_t)(L->line[i] - copy); + if (strcmp(L->line[i], "end semantic") == 0) s1 = (size_t)(L->line[i] - copy) + L->len[i] + 1; + if (strcmp(L->line[i], "begin acceptance") == 0) a0 = (size_t)(L->line[i] - copy); + if (strcmp(L->line[i], "end acceptance") == 0) a1 = (size_t)(L->line[i] - copy) + L->len[i] + 1; + } + tagged_digest("omega.at0.case.v1", (const char *)bytes + s0, s1 - s0, cid); + tagged_digest("omega.at0.acceptance.v1", (const char *)bytes + a0, a1 - a0, aid); + if (strcmp(cid, out->case_id) != 0 || strcmp(aid, out->acceptance_id) != 0) { st = AT0_CASE_ID_MISMATCH; goto done; } + } + /* rule 6 */ + if ((st = check_acceptance(out, r)) != AT0_OK) goto done; + { + sha256_ctx ctx; uint8_t d[32]; + sha256_init(&ctx); sha256_update(&ctx, bytes, len); sha256_final(&ctx, d); + hex_digest(d, out->case_file_sha256); + } + st = AT0_OK; +done: + free(copy); free(L); free(r); free(re); + return st; +} + +at0_status at0_case_read_file(const char *path, at0_case *out) +{ + if (!path || !out) return AT0_ERR_ARGUMENT; + FILE *f = fopen(path, "rb"); + if (!f) return AT0_ERR_IO; + size_t cap = 65536, len = 0; + uint8_t *buf = malloc(cap); + if (!buf) { fclose(f); return AT0_ERR_INTERNAL; } + for (;;) { + size_t n = fread(buf + len, 1, cap - len, f); + len += n; + if (n == 0) break; + if (len == cap) { + if (cap > (size_t)LINE_CAP * 256) { free(buf); fclose(f); return AT0_CASE_PARSE_ERROR; } + cap *= 2; + uint8_t *nb = realloc(buf, cap); + if (!nb) { free(buf); fclose(f); return AT0_ERR_INTERNAL; } + buf = nb; + } + } + int err = ferror(f); + fclose(f); + if (err) { free(buf); return AT0_ERR_IO; } + at0_status st = at0_case_parse(buf, len, out); + free(buf); + return st; +} diff --git a/research/atemporal/at0/model/at0_conditional.c b/research/atemporal/at0/model/at0_conditional.c new file mode 100644 index 000000000..54e8837bd --- /dev/null +++ b/research/atemporal/at0/model/at0_conditional.c @@ -0,0 +1,43 @@ +/* Conditional subsystem state: phi_k = ( +#include + +at0_status at0_conditional_compute(const at0_case *c, const at0_state *psi, double psi_norm2, + int k, at0_conditional *out) +{ + if (!c || !psi || !out || psi->clock_dim != c->clock_dim) return AT0_ERR_ARGUMENT; + if (!(psi_norm2 > 0.0) || !isfinite(psi_norm2)) return AT0_ERR_ARGUMENT; + if (k < 0 || k >= c->label_count) return AT0_ERR_ARGUMENT; + memset(out, 0, sizeof *out); + at0_clock_vec t; + at0_status st = at0_povm_clock_state(c, k, &t); + if (st != AT0_OK) return st; + for (int s = 0; s < AT0_SYSTEM_DIM; s++) { + double complex acc = 0.0; + for (int j = 0; j < c->clock_dim; j++) { + double complex a; + if ((st = at0_state_get(psi, j, s, &a)) != AT0_OK) return st; + acc += conj(t.v[j]) * a; + } + out->phi.v[s] = acc; + } + double n2 = 0.0; + for (int s = 0; s < AT0_SYSTEM_DIM; s++) { + double re = creal(out->phi.v[s]), im = cimag(out->phi.v[s]); + n2 += re * re + im * im; + } + if (!isfinite(n2)) return AT0_ERR_NONFINITE; + out->phi_norm2 = n2; + out->clock_probability = at0_rat_to_double(c->povm_weight) * n2 / psi_norm2; + if (!isfinite(out->clock_probability)) return AT0_ERR_NONFINITE; + out->defined_numeric = n2 > 0.0; + if (out->defined_numeric) { + for (int a = 0; a < AT0_SYSTEM_DIM; a++) + for (int b = 0; b < AT0_SYSTEM_DIM; b++) + out->rho.m[a][b] = out->phi.v[a] * conj(out->phi.v[b]) / n2; + } + return AT0_OK; +} diff --git a/research/atemporal/at0/model/at0_constraint.c b/research/atemporal/at0/model/at0_constraint.c new file mode 100644 index 000000000..9b4f79ea7 --- /dev/null +++ b/research/atemporal/at0/model/at0_constraint.c @@ -0,0 +1,141 @@ +/* Hamiltonian constraint: exact kernel of H_total, nullspace projection of the + * reference product state, and the residual || H_total Psi_hat ||. */ +#include "at0_model.h" +#include +#include + +at0_status at0_constraint_kernel(const at0_case *c, const at0_system_hamiltonian *hs, at0_kernel *out) +{ + if (!c || !hs || !out) return AT0_ERR_ARGUMENT; + memset(out, 0, sizeof *out); + for (int j = 0; j < c->clock_dim; j++) { + for (int s = 0; s < AT0_SYSTEM_DIM; s++) { + at0_rat sum; + at0_status st = at0_rat_add(c->clock_energies[j], hs->eig[s], &sum); + if (st != AT0_OK) return st; + if (at0_rat_is_zero(sum)) { + if (out->kernel_dim >= AT0_TOTAL_DIM_MAX) return AT0_ERR_INTERNAL; + out->match_j[out->kernel_dim] = j; + out->match_s[out->kernel_dim] = s; + out->kernel_dim++; + } + } + } + return AT0_OK; +} + +/* exact test: is zero? uses the unnormalized rational eigenvector + * (-(hx - i hy), |h| + hz) for s = 0 and (|h| + hz, hx + i hy) for s = 1; + * in the degenerate case the eigenvectors are |0>, |1>. */ +static at0_status overlap_is_zero(const at0_case *c, const at0_system_hamiltonian *hs, int s, int *zero) +{ + at0_crat p0 = c->psi0[0], p1 = c->psi0[1]; + if (hs->degenerate) { + at0_crat p = s == 0 ? p0 : p1; + *zero = at0_rat_is_zero(p.re) && at0_rat_is_zero(p.im); + return AT0_OK; + } + at0_rat a, rpz, hx = c->hx, hy = c->hy; + at0_status st = at0_rat_add(c->h_norm, c->hz, &rpz); + if (st != AT0_OK) return st; + if (at0_rat_is_zero(rpz)) { + /* h = (0, 0, -|h|): the eigenvectors are |0> (s = 0) and |1> (s = 1), as in at0_hamiltonian_system */ + at0_crat p = s == 0 ? p0 : p1; + *zero = at0_rat_is_zero(p.re) && at0_rat_is_zero(p.im); + return AT0_OK; + } + /* conj(v_s) . psi0 with v_0 = (-(hx - i hy), a), v_1 = (a, hx + i hy), a = |h| + hz: + * s=0: conj(v_0) = (-(hx + i hy), a) -> -(hx + i hy) p0 + a p1 + * s=1: conj(v_1) = (a, hx - i hy) -> a p0 + (hx - i hy) p1 + * Each is u*p + v*q with u, v complex rationals; test both parts for zero + * with cross-multiplied 128-bit integers (no reduction needed). */ + a = rpz; + at0_crat u, v, p, q; + if (s == 0) { + u.re.n = -hx.n; u.re.d = hx.d; u.im.n = -hy.n; u.im.d = hy.d; /* -(hx + i hy) */ + v.re = a; v.im.n = 0; v.im.d = 1; + p = p0; q = p1; + } else { + u.re = a; u.im.n = 0; u.im.d = 1; + v.re = hx; v.im.n = -hy.n; v.im.d = hy.d; /* hx - i hy */ + p = p0; q = p1; + } + /* (u.re + i u.im)(p.re + i p.im) + (v.re + i v.im)(q.re + i q.im) */ + /* real: u.re p.re - u.im p.im + v.re q.re - v.im q.im ; imag: u.re p.im + u.im p.re + v.re q.im + v.im q.re */ + /* The product test above can overflow for extreme inputs, so decide the zero test with + * the limit-checked rational API instead: each operand is at most 2^20, products are + * at most 2^40 and are reduced after every step; AT0_ERR_OVERFLOW is reported, never wrapped. */ + { + at0_rat r1, r2, r3, r4, re, im, t; + /* real part */ + if ((st = at0_rat_mul(u.re, p.re, &r1)) != AT0_OK) return st; + if ((st = at0_rat_mul(u.im, p.im, &r2)) != AT0_OK) return st; + if ((st = at0_rat_mul(v.re, q.re, &r3)) != AT0_OK) return st; + if ((st = at0_rat_mul(v.im, q.im, &r4)) != AT0_OK) return st; + if ((st = at0_rat_sub(r1, r2, &t)) != AT0_OK) return st; + if ((st = at0_rat_add(t, r3, &t)) != AT0_OK) return st; + if ((st = at0_rat_sub(t, r4, &re)) != AT0_OK) return st; + /* imaginary part */ + if ((st = at0_rat_mul(u.re, p.im, &r1)) != AT0_OK) return st; + if ((st = at0_rat_mul(u.im, p.re, &r2)) != AT0_OK) return st; + if ((st = at0_rat_mul(v.re, q.im, &r3)) != AT0_OK) return st; + if ((st = at0_rat_mul(v.im, q.re, &r4)) != AT0_OK) return st; + if ((st = at0_rat_add(r1, r2, &t)) != AT0_OK) return st; + if ((st = at0_rat_add(t, r3, &t)) != AT0_OK) return st; + if ((st = at0_rat_add(t, r4, &im)) != AT0_OK) return st; + *zero = at0_rat_is_zero(re) && at0_rat_is_zero(im); + } + return AT0_OK; +} + +at0_status at0_constraint_physical_state(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_kernel *k, at0_state *psi) +{ + if (!c || !hs || !k || !psi) return AT0_ERR_ARGUMENT; + at0_status st = at0_state_init(psi, c->clock_dim); + if (st != AT0_OK) return st; + at0_clock_vec tr; + if ((st = at0_povm_clock_state(c, c->reference_index, &tr)) != AT0_OK) return st; + double complex psi0[AT0_SYSTEM_DIM]; + for (int s = 0; s < AT0_SYSTEM_DIM; s++) + psi0[s] = at0_rat_to_double(c->psi0[s].re) + I * at0_rat_to_double(c->psi0[s].im); + /* exact decision whether the projected state is the zero vector */ + int all_zero = 1; + for (int m = 0; m < k->kernel_dim; m++) { + int z; + if ((st = overlap_is_zero(c, hs, k->match_s[m], &z)) != AT0_OK) return st; + if (!z) { all_zero = 0; break; } + } + if (all_zero) return AT0_OK; /* Psi = 0 exactly: leave the zero state */ + for (int m = 0; m < k->kernel_dim; m++) { + int j = k->match_j[m], s = k->match_s[m]; + if (j < 0 || j >= c->clock_dim || s < 0 || s >= AT0_SYSTEM_DIM) return AT0_ERR_ARGUMENT; + const at0_qubit *e = &hs->vec[s]; + double complex overlap = conj(e->v[0]) * psi0[0] + conj(e->v[1]) * psi0[1]; /* */ + double complex coef = tr.v[j] * overlap; /* */ + for (int sp = 0; sp < AT0_SYSTEM_DIM; sp++) { + double complex cur; + if ((st = at0_state_get(psi, j, sp, &cur)) != AT0_OK) return st; + if ((st = at0_state_set(psi, j, sp, cur + coef * e->v[sp])) != AT0_OK) return st; + } + } + return at0_state_check_finite(psi); +} + +at0_status at0_constraint_residual(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_state *psi, double *out) +{ + if (!c || !hs || !psi || !out) return AT0_ERR_ARGUMENT; + double n2; + at0_status st = at0_state_norm2(psi, &n2); + if (st != AT0_OK) return st; + if (!(n2 > 0.0)) return AT0_ERR_ARGUMENT; /* residual of the zero state is undefined */ + at0_state h; + if ((st = at0_hamiltonian_apply_total(c, hs, psi, &h)) != AT0_OK) return st; + double hn2; + if ((st = at0_state_norm2(&h, &hn2)) != AT0_OK) return st; + double r = sqrt(hn2 / n2); + if (!isfinite(r)) return AT0_ERR_NONFINITE; + *out = r; + return AT0_OK; +} diff --git a/research/atemporal/at0/model/at0_engine.c b/research/atemporal/at0/model/at0_engine.c new file mode 100644 index 000000000..2bdfc38fe --- /dev/null +++ b/research/atemporal/at0/model/at0_engine.c @@ -0,0 +1,78 @@ +/* Engine orchestration: builds every quantity of AT0_RESULT_V1 section 3 from + * the case alone, attaches ESTIMATED error bounds (README section "Error + * estimates"), and decides label status with exact integer comparisons. */ +#include "at0_model.h" +#include +#include + +#define EPS 1.1102230246251565e-16 /* 2^-53 */ + +static double fmax_d(double a, double b) { return a > b ? a : b; } + +static at0_status bound_from(double est, at0_scaled *out) +{ + if (!isfinite(est) || est < 0) return AT0_ERR_NONFINITE; + return at0_scaled_from_double_ceil(est, out); +} + +static at0_status run(const at0_case *c, at0_engine_result *out, int reversed) +{ + if (!c || !out) return AT0_ERR_ARGUMENT; + memset(out, 0, sizeof *out); + out->bound_kind = AT0_BOUND_ESTIMATED; + out->label_count = c->label_count; + at0_status st; + + at0_system_hamiltonian hs; + if ((st = at0_hamiltonian_system(c, &hs)) != AT0_OK) return st; + at0_kernel ker; + if ((st = at0_constraint_kernel(c, &hs, &ker)) != AT0_OK) return st; + out->kernel_dim = ker.kernel_dim; + at0_state psi; + if ((st = at0_constraint_physical_state(c, &hs, &ker, &psi)) != AT0_OK) return st; + double psi_norm2; + if ((st = at0_state_norm2(&psi, &psi_norm2)) != AT0_OK) return st; + out->psi_nonzero = psi_norm2 > 0.0; + + double n = (double)c->clock_dim, m = (double)c->label_count; + double w = at0_rat_to_double(c->povm_weight); + double hmax = fmax_d(fabs(at0_rat_to_double(c->clock_energies[0])), + fabs(at0_rat_to_double(c->clock_energies[c->clock_dim - 1]))) + + fabs(at0_rat_to_double(c->h0)) + at0_rat_to_double(c->h_norm); + + if (out->psi_nonzero) { + if ((st = at0_constraint_residual(c, &hs, &psi, &out->constraint_residual)) != AT0_OK) return st; + if ((st = bound_from(32.0 * EPS * n * (hmax + 1.0), &out->constraint_residual_bound)) != AT0_OK) return st; + } else { + out->constraint_residual = 0.0; + out->constraint_residual_bound.n = 0; out->constraint_residual_bound.k = 0; + } + if ((st = at0_povm_residual(c, &out->povm_residual)) != AT0_OK) return st; + if ((st = bound_from(16.0 * EPS * n * (m * w + 1.0), &out->povm_residual_bound)) != AT0_OK) return st; + + for (int i = 0; i < c->label_count; i++) { + int k = reversed ? c->label_count - 1 - i : i; + at0_label_values *lv = &out->label[k]; + memset(lv, 0, sizeof *lv); + if (!out->psi_nonzero) { lv->status = AT0_LABEL_UNDEFINED; continue; } + at0_conditional cond; + if ((st = at0_conditional_compute(c, &psi, psi_norm2, k, &cond)) != AT0_OK) return st; + lv->clock_probability = cond.clock_probability; + if ((st = bound_from(32.0 * EPS * (n + 4.0) * (cond.clock_probability + 1.0), &lv->clock_probability_bound)) != AT0_OK) return st; + int le, gt; + if ((st = at0_exact_prob_status(lv->clock_probability, lv->clock_probability_bound, c->tol_zero_probability, &le, >)) != AT0_OK) return st; + lv->status = le ? AT0_LABEL_UNDEFINED : (gt ? AT0_LABEL_DEFINED : AT0_LABEL_INDETERMINATE); + if (lv->status != AT0_LABEL_DEFINED) continue; + if (!cond.defined_numeric) return AT0_ERR_INTERNAL; /* DEFINED implies ||phi|| > 0 */ + for (int ax = 0; ax < 3; ax++) { + for (int sg = 0; sg < 2; sg++) { + if ((st = at0_observable_probability(&cond.rho, (at0_axis)ax, (at0_sign)sg, &lv->pauli[ax][sg])) != AT0_OK) return st; + if ((st = bound_from(32.0 * EPS * (n + 8.0), &lv->pauli_bound[ax][sg])) != AT0_OK) return st; + } + } + } + return AT0_OK; +} + +at0_status at0_engine_run(const at0_case *c, at0_engine_result *out) { return run(c, out, 0); } +at0_status at0_engine_run_reversed(const at0_case *c, at0_engine_result *out) { return run(c, out, 1); } diff --git a/research/atemporal/at0/model/at0_exact.c b/research/atemporal/at0/model/at0_exact.c new file mode 100644 index 000000000..a364f8461 --- /dev/null +++ b/research/atemporal/at0/model/at0_exact.c @@ -0,0 +1,289 @@ +/* Exact arithmetic for AT-0: reduced rationals (64-bit fields, 128-bit + * intermediates, limits of AT0_CASE_V1 section 2), scaled decimals, canonical + * token parsing/printing, and an exact comparison of a binary64 value against + * scaled-decimal bounds using a small fixed-size unsigned bignum. */ +#include "at0_model.h" + +#include +#include +#include + +static const char *const status_names[] = { + "OK", "CASE_PARSE_ERROR", "CASE_NONCANONICAL", "CASE_UNSUPPORTED_VERSION", + "CASE_INVALID_PARAMETER", "CASE_IRRATIONAL_SPECTRUM", "CASE_ID_MISMATCH", + "ERR_ARGUMENT", "ERR_OVERFLOW", "ERR_NONFINITE", "ERR_IO", "ERR_INTERNAL" +}; + +const char *at0_status_name(at0_status s) +{ + if ((int)s < 0 || (size_t)s >= sizeof status_names / sizeof status_names[0]) return "ERR_UNKNOWN"; + return status_names[s]; +} + +int at0_status_is_refusal(at0_status s) +{ + return s >= AT0_CASE_PARSE_ERROR && s <= AT0_CASE_ID_MISMATCH; +} + +/* ---- 128-bit helpers ------------------------------------------------------ */ +static at0_i128 i128_abs(at0_i128 x) { return x < 0 ? -x : x; } + +static at0_i128 i128_gcd(at0_i128 a, at0_i128 b) +{ + a = i128_abs(a); b = i128_abs(b); + while (b != 0) { at0_i128 t = a % b; a = b; b = t; } + return a; +} + +/* reduce n/d (d != 0) and check the contract limits */ +static at0_status rat_from_i128(at0_i128 n, at0_i128 d, at0_rat *out) +{ + /* reduce; the only limit here is representability (|n|, d < 2^62) so that every further + * product of two rationals fits in 128 bits. The contract limit 2^20 applies to tokens + * written in a case file and is enforced by validity rule 3 (at0_rat_in_limits). */ + if (!out || d == 0) return AT0_ERR_ARGUMENT; + if (d < 0) { n = -n; d = -d; } + at0_i128 g = i128_gcd(n, d); + if (g > 1) { n /= g; d /= g; } + if (i128_abs(n) > AT0_RAT_REPR_LIMIT || d > AT0_RAT_REPR_LIMIT) return AT0_ERR_OVERFLOW; + out->n = (int64_t)n; out->d = (int64_t)d; + return AT0_OK; +} + +at0_status at0_rat_make(int64_t n, int64_t d, at0_rat *out) { return rat_from_i128(n, d, out); } +int at0_rat_in_limits(at0_rat a) { return a.d >= 1 && a.d <= AT0_RATIONAL_LIMIT && a.n <= AT0_RATIONAL_LIMIT && a.n >= -AT0_RATIONAL_LIMIT; } +int at0_scaled_in_limits(at0_scaled s) { return s.k >= 0 && s.k <= AT0_SCALED_K_MAX && s.n < (uint64_t)AT0_INT_SATURATED; } + +at0_status at0_rat_add(at0_rat a, at0_rat b, at0_rat *out) +{ + return rat_from_i128((at0_i128)a.n * b.d + (at0_i128)b.n * a.d, (at0_i128)a.d * b.d, out); +} +at0_status at0_rat_sub(at0_rat a, at0_rat b, at0_rat *out) +{ + return rat_from_i128((at0_i128)a.n * b.d - (at0_i128)b.n * a.d, (at0_i128)a.d * b.d, out); +} +at0_status at0_rat_mul(at0_rat a, at0_rat b, at0_rat *out) +{ + return rat_from_i128((at0_i128)a.n * b.n, (at0_i128)a.d * b.d, out); +} +int at0_rat_cmp(at0_rat a, at0_rat b) +{ + at0_i128 l = (at0_i128)a.n * b.d, r = (at0_i128)b.n * a.d; + return l < r ? -1 : (l > r ? 1 : 0); +} +int at0_rat_is_zero(at0_rat a) { return a.n == 0; } +double at0_rat_to_double(at0_rat a) { return (double)a.n / (double)a.d; } + +/* integer square root of a nonnegative 128-bit value, exact test */ +static int i128_is_square(at0_i128 x, at0_i128 *root) +{ + if (x < 0) return 0; + if (x == 0) { *root = 0; return 1; } + at0_i128 r = (at0_i128)sqrtl((long double)x); + if (r < 0) r = 0; + while (r > 0 && r * r > x) r--; + while ((r + 1) * (r + 1) <= x) r++; + *root = r; + return r * r == x; +} + +at0_status at0_rat_sqrt_exact(at0_rat a, at0_rat *root, int *is_square) +{ + if (!root || !is_square) return AT0_ERR_ARGUMENT; + *is_square = 0; + if (a.n < 0) return AT0_OK; + at0_i128 rn, rd; + if (!i128_is_square((at0_i128)a.n, &rn)) return AT0_OK; + if (!i128_is_square((at0_i128)a.d, &rd)) return AT0_OK; + at0_status st = rat_from_i128(rn, rd, root); + if (st != AT0_OK) return st; + *is_square = 1; + return AT0_OK; +} + +at0_status at0_rat_reduce_turn(at0_rat x, at0_rat *out) +{ + /* x - round(x) with round half up, result in [-1/2, 1/2) */ + if (!out) return AT0_ERR_ARGUMENT; + at0_i128 n = x.n, d = x.d; + at0_i128 twice = 2 * n + d; /* 2x + 1 numerator over 2d */ + at0_i128 q = twice / (2 * d); /* floor for nonnegative */ + if (twice < 0 && twice % (2 * d) != 0) q -= 1; + return rat_from_i128(n - q * d, d, out); +} + +/* ---- canonical integer token -------------------------------------------- */ +/* A canonical digit string longer than 18 digits cannot fit the contract limits; it is + * parsed as the saturation value AT0_INT_SATURATED (above every limit, not divisible by 10) + * so that rule 3 refuses it as CASE_INVALID_PARAMETER after the version check, and no + * int64 arithmetic can overflow. */ +static int parse_canonical_int(const char *s, size_t len, int64_t *out) +{ + /* decimal, optional '-', no leading zeros, no '+', no "-0" */ + if (len == 0 || len > 64) return 0; + size_t i = 0; int neg = 0; + if (s[0] == '-') { neg = 1; i = 1; if (len == 1) return 0; } + if (s[i] == '0' && len - i > 1) return 0; + if (neg && s[i] == '0') return 0; + int64_t v = 0; + size_t digits = len - i; + for (; i < len; i++) { + if (!isdigit((unsigned char)s[i])) return 0; + if (digits <= 18) v = v * 10 + (s[i] - '0'); + } + if (digits > 18) v = AT0_INT_SATURATED; + *out = neg ? -v : v; + return 1; +} + +at0_status at0_rat_parse(const char *tok, at0_rat *out) +{ + if (!tok || !out) return AT0_ERR_ARGUMENT; + const char *slash = strchr(tok, '/'); + if (!slash) return AT0_CASE_PARSE_ERROR; + int64_t n, d; + if (!parse_canonical_int(tok, (size_t)(slash - tok), &n)) return AT0_CASE_PARSE_ERROR; + if (!parse_canonical_int(slash + 1, strlen(slash + 1), &d)) return AT0_CASE_PARSE_ERROR; + if (d < 1) return AT0_CASE_NONCANONICAL; + int saturated = n == AT0_INT_SATURATED || n == -AT0_INT_SATURATED || d == AT0_INT_SATURATED; + if (!saturated && i128_gcd(n, d) != 1) return AT0_CASE_NONCANONICAL; /* covers 0/5 and 2/4; limits are rule 3 */ + out->n = n; out->d = d; + return AT0_OK; +} + +at0_status at0_crat_parse(const char *tok, at0_crat *out) +{ + if (!tok || !out) return AT0_ERR_ARGUMENT; + size_t len = strlen(tok); + if (len < 7 || tok[0] != '(' || tok[len - 1] != ')') return AT0_CASE_PARSE_ERROR; + const char *semi = strchr(tok, ';'); + if (!semi) return AT0_CASE_PARSE_ERROR; + char a[64], b[64]; + size_t la = (size_t)(semi - tok - 1), lb = len - 2 - la - 1; + if (la == 0 || lb == 0 || la >= sizeof a || lb >= sizeof b) return AT0_CASE_PARSE_ERROR; + memcpy(a, tok + 1, la); a[la] = 0; + memcpy(b, semi + 1, lb); b[lb] = 0; + at0_status st = at0_rat_parse(a, &out->re); + if (st != AT0_OK) return st; + return at0_rat_parse(b, &out->im); +} + +at0_status at0_scaled_parse(const char *tok, at0_scaled *out) +{ + if (!tok || !out) return AT0_ERR_ARGUMENT; + const char *at = strchr(tok, '@'); + if (!at) return AT0_CASE_PARSE_ERROR; + int64_t n, k; + if (!parse_canonical_int(tok, (size_t)(at - tok), &n)) return AT0_CASE_PARSE_ERROR; + if (!parse_canonical_int(at + 1, strlen(at + 1), &k)) return AT0_CASE_PARSE_ERROR; + if (n < 0 || k < 0) return AT0_CASE_NONCANONICAL; + if (k > 1000) k = 1000; /* above every limit; rule 3 refuses it */ + if (n == 0 && k != 0) return AT0_CASE_NONCANONICAL; + if (n != 0 && k != 0 && n % 10 == 0) return AT0_CASE_NONCANONICAL; + out->n = (uint64_t)n; out->k = (int)k; + return AT0_OK; +} + +int at0_rat_format(at0_rat a, char *buf, size_t cap) +{ + return snprintf(buf, cap, "%lld/%lld", (long long)a.n, (long long)a.d); +} +int at0_crat_format(at0_crat a, char *buf, size_t cap) +{ + return snprintf(buf, cap, "(%lld/%lld;%lld/%lld)", (long long)a.re.n, (long long)a.re.d, + (long long)a.im.n, (long long)a.im.d); +} +int at0_scaled_format(at0_scaled s, char *buf, size_t cap) +{ + return snprintf(buf, cap, "%llu@%d", (unsigned long long)s.n, s.k); +} + +/* ---- fixed-size unsigned bignum for exact comparisons -------------------- */ +/* 2^1074 (smallest subnormal scale) * 2^53 * 10^40 * 10^40 < 2^1400 ; 48 limbs = 1536 bits */ +#define BN_LIMBS 48 +typedef struct { uint32_t l[BN_LIMBS]; } bn_t; + +static void bn_zero(bn_t *x) { memset(x, 0, sizeof *x); } +static void bn_from_u64(bn_t *x, uint64_t v) { bn_zero(x); x->l[0] = (uint32_t)v; x->l[1] = (uint32_t)(v >> 32); } +static int bn_mul_small(bn_t *x, uint32_t m) +{ + uint64_t carry = 0; + for (int i = 0; i < BN_LIMBS; i++) { + uint64_t t = (uint64_t)x->l[i] * m + carry; + x->l[i] = (uint32_t)t; carry = t >> 32; + } + return carry == 0; +} +static int bn_shl(bn_t *x, int bits) +{ + while (bits >= 32) { + if (x->l[BN_LIMBS - 1] != 0) return 0; + for (int i = BN_LIMBS - 1; i > 0; i--) x->l[i] = x->l[i - 1]; + x->l[0] = 0; bits -= 32; + } + if (bits == 0) return 1; + if (x->l[BN_LIMBS - 1] >> (32 - bits)) return 0; + for (int i = BN_LIMBS - 1; i > 0; i--) x->l[i] = (x->l[i] << bits) | (x->l[i - 1] >> (32 - bits)); + x->l[0] <<= bits; + return 1; +} +static int bn_pow10_mul(bn_t *x, int k) { for (int i = 0; i < k; i++) if (!bn_mul_small(x, 10)) return 0; return 1; } +static int bn_add(bn_t *x, const bn_t *y) +{ + uint64_t carry = 0; + for (int i = 0; i < BN_LIMBS; i++) { + uint64_t t = (uint64_t)x->l[i] + y->l[i] + carry; + x->l[i] = (uint32_t)t; carry = t >> 32; + } + return carry == 0; +} +static int bn_cmp(const bn_t *a, const bn_t *b) +{ + for (int i = BN_LIMBS - 1; i >= 0; i--) { + if (a->l[i] != b->l[i]) return a->l[i] < b->l[i] ? -1 : 1; + } + return 0; +} + +at0_status at0_exact_prob_status(double p, at0_scaled b, at0_scaled tol, int *le, int *gt) +{ + if (!le || !gt) return AT0_ERR_ARGUMENT; + if (!isfinite(p) || p < 0) return AT0_ERR_ARGUMENT; + if (b.k > AT0_SCALED_K_MAX || tol.k > AT0_SCALED_K_MAX || b.k < 0 || tol.k < 0) return AT0_ERR_ARGUMENT; + /* p = m * 2^e exactly, m integer < 2^53 */ + int e = 0; uint64_t m = 0; + if (p != 0.0) { + int ex; double fr = frexp(p, &ex); /* p = fr * 2^ex, fr in [0.5,1) */ + m = (uint64_t)ldexp(fr, 53); /* exact integer */ + e = ex - 53; + } + int s = e < 0 ? -e : 0; /* scale by 2^s so p's exponent is >= 0 */ + int K = b.k > tol.k ? b.k : tol.k; + bn_t P, B, T; + bn_from_u64(&P, m); + if (!bn_shl(&P, s + e) || !bn_pow10_mul(&P, K)) return AT0_ERR_OVERFLOW; + bn_from_u64(&B, b.n); + if (!bn_shl(&B, s) || !bn_pow10_mul(&B, K - b.k)) return AT0_ERR_OVERFLOW; + bn_from_u64(&T, tol.n); + if (!bn_shl(&T, s) || !bn_pow10_mul(&T, K - tol.k)) return AT0_ERR_OVERFLOW; + bn_t PB = P; if (!bn_add(&PB, &B)) return AT0_ERR_OVERFLOW; /* p + b */ + bn_t TB = T; if (!bn_add(&TB, &B)) return AT0_ERR_OVERFLOW; /* tol + b */ + *le = bn_cmp(&PB, &T) <= 0; /* p + b <= tol */ + *gt = bn_cmp(&P, &TB) > 0; /* p - b > tol <=> p > tol + b */ + return AT0_OK; +} + +at0_status at0_scaled_from_double_ceil(double x, at0_scaled *out) +{ + if (!out || !isfinite(x) || x < 0) return AT0_ERR_ARGUMENT; + if (x == 0.0) { out->n = 0; out->k = 0; return AT0_OK; } + /* pick k so that x * 10^k is in [10^6, 10^7): seven significant digits, round up, then add one unit */ + int k = 0; long double y = (long double)x; + while (y < 1e6L && k < AT0_SCALED_K_MAX) { y *= 10.0L; k++; } + while (y >= 1e7L && k > 0) { y /= 10.0L; k--; } + if (y >= 1.8e19L) return AT0_ERR_OVERFLOW; + uint64_t n = (uint64_t)ceill(y) + 1; /* +1 absorbs the decimal conversion itself */ + while (k > 0 && n % 10 == 0) { n /= 10; k--; } /* canonical form */ + out->n = n; out->k = k; + return AT0_OK; +} diff --git a/research/atemporal/at0/model/at0_hamiltonian.c b/research/atemporal/at0/model/at0_hamiltonian.c new file mode 100644 index 000000000..bc246af79 --- /dev/null +++ b/research/atemporal/at0/model/at0_hamiltonian.c @@ -0,0 +1,64 @@ +/* Hamiltonian construction: H_S = h0 I + hx X + hy Y + hz Z with its exact + * rational spectrum h0 +/- |h| and binary64 eigenvectors; H_total applied as + * H_C (x) I + I (x) H_S on the combined state. */ +#include "at0_model.h" +#include +#include + +at0_status at0_hamiltonian_system(const at0_case *c, at0_system_hamiltonian *out) +{ + if (!c || !out) return AT0_ERR_ARGUMENT; + memset(out, 0, sizeof *out); + at0_status st; + if ((st = at0_rat_sub(c->h0, c->h_norm, &out->eig[0])) != AT0_OK) return st; + if ((st = at0_rat_add(c->h0, c->h_norm, &out->eig[1])) != AT0_OK) return st; + double h0 = at0_rat_to_double(c->h0), hx = at0_rat_to_double(c->hx); + double hy = at0_rat_to_double(c->hy), hz = at0_rat_to_double(c->hz); + double r = at0_rat_to_double(c->h_norm); + out->hs.m[0][0] = h0 + hz; out->hs.m[0][1] = hx - I * hy; + out->hs.m[1][0] = hx + I * hy; out->hs.m[1][1] = h0 - hz; + if (at0_rat_is_zero(c->h_norm)) { + /* H_S = h0 I: any basis is an eigenbasis; use the computational one */ + out->degenerate = 1; + out->vec[0].v[0] = 1.0; out->vec[0].v[1] = 0.0; + out->vec[1].v[0] = 0.0; out->vec[1].v[1] = 1.0; + return AT0_OK; + } + at0_rat rpz; + if ((st = at0_rat_add(c->h_norm, c->hz, &rpz)) != AT0_OK) return st; + if (at0_rat_is_zero(rpz)) { + /* h = (0, 0, -|h|): eigenvalue -|h| on |0>, +|h| on |1> */ + out->vec[0].v[0] = 1.0; out->vec[0].v[1] = 0.0; + out->vec[1].v[0] = 0.0; out->vec[1].v[1] = 1.0; + return AT0_OK; + } + double a = r + hz; + double norm = sqrt(2.0 * r * a); /* |(a, hx + i hy)| = sqrt(a^2 + hx^2 + hy^2) = sqrt(2 r a) */ + if (!(norm > 0.0) || !isfinite(norm)) return AT0_ERR_NONFINITE; + /* eigenvalue h0 - |h| */ + out->vec[0].v[0] = -(hx - I * hy) / norm; + out->vec[0].v[1] = a / norm; + /* eigenvalue h0 + |h| */ + out->vec[1].v[0] = a / norm; + out->vec[1].v[1] = (hx + I * hy) / norm; + return AT0_OK; +} + +at0_status at0_hamiltonian_apply_total(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_state *in, at0_state *out) +{ + if (!c || !hs || !in || !out || in->clock_dim != c->clock_dim) return AT0_ERR_ARGUMENT; + at0_status st = at0_state_init(out, c->clock_dim); + if (st != AT0_OK) return st; + for (int j = 0; j < c->clock_dim; j++) { + double ej = at0_rat_to_double(c->clock_energies[j]); + double complex a0, a1; + if ((st = at0_state_get(in, j, 0, &a0)) != AT0_OK) return st; + if ((st = at0_state_get(in, j, 1, &a1)) != AT0_OK) return st; + double complex b0 = ej * a0 + hs->hs.m[0][0] * a0 + hs->hs.m[0][1] * a1; + double complex b1 = ej * a1 + hs->hs.m[1][0] * a0 + hs->hs.m[1][1] * a1; + if ((st = at0_state_set(out, j, 0, b0)) != AT0_OK) return st; + if ((st = at0_state_set(out, j, 1, b1)) != AT0_OK) return st; + } + return at0_state_check_finite(out); +} diff --git a/research/atemporal/at0/model/at0_main.c b/research/atemporal/at0/model/at0_main.c new file mode 100644 index 000000000..5fc21aea0 --- /dev/null +++ b/research/atemporal/at0/model/at0_main.c @@ -0,0 +1,30 @@ +/* at0-model: run one AT0_CASE_V1 case through the candidate engine. + * at0-model [--reversed] + * stdout: OMEGA-AT0-ENGINE v1 text. Refused case: stderr "AT0_CASE_REFUSED ", + * exit 2 (AT0_RESULT_V1 section 5). Other failures: stderr "AT0_ENGINE_ERROR ", exit 1. */ +#include "at0_model.h" +#include +#include + +int main(int argc, char **argv) +{ + if (argc < 2 || argc > 3 || (argc == 3 && strcmp(argv[2], "--reversed") != 0)) { + fprintf(stderr, "usage: at0-model [--reversed]\n"); + return 1; + } + at0_case *c = calloc(1, sizeof *c); + at0_engine_result *r = calloc(1, sizeof *r); + char *buf = malloc(1 << 20); + if (!c || !r || !buf) { fprintf(stderr, "AT0_ENGINE_ERROR ERR_INTERNAL\n"); return 1; } + at0_status st = at0_case_read_file(argv[1], c); + if (at0_status_is_refusal(st)) { fprintf(stderr, "AT0_CASE_REFUSED %s\n", at0_status_name(st)); free(c); free(r); free(buf); return 2; } + if (st != AT0_OK) { fprintf(stderr, "AT0_ENGINE_ERROR %s\n", at0_status_name(st)); free(c); free(r); free(buf); return 1; } + st = argc == 3 ? at0_engine_run_reversed(c, r) : at0_engine_run(c, r); + if (st != AT0_OK) { fprintf(stderr, "AT0_ENGINE_ERROR %s\n", at0_status_name(st)); free(c); free(r); free(buf); return 1; } + long n = at0_engine_emit(c, r, buf, 1 << 20); + if (n < 0) { fprintf(stderr, "AT0_ENGINE_ERROR ERR_INTERNAL\n"); free(c); free(r); free(buf); return 1; } + int rc = fwrite(buf, 1, (size_t)n, stdout) == (size_t)n && fflush(stdout) == 0 ? 0 : 1; + if (rc) fprintf(stderr, "AT0_ENGINE_ERROR ERR_IO\n"); + free(c); free(r); free(buf); + return rc; +} diff --git a/research/atemporal/at0/model/at0_model.h b/research/atemporal/at0/model/at0_model.h new file mode 100644 index 000000000..3dad55683 --- /dev/null +++ b/research/atemporal/at0/model/at0_model.h @@ -0,0 +1,248 @@ +/* AT-0 candidate relational quantum engine (Agent 3, research model). + * + * Implements the finite Page-Wootters universe of AT0_CASE_V1 / AT0_RESULT_V1 + * (aien-architecture docs/plans/atemporal/ at commit 044c9d1): a clock of + * dimension N, one qubit, the constraint H_total = H_C (x) I + I (x) H_S, a + * covariant discrete clock POVM, and conditional qubit statistics read off by + * the Born rule after a clock measurement. + * + * Rules this header enforces by construction: + * - no wall-clock, CPU time, GPU, random or scheduling input anywhere; + * - the clock phase is a declared measurement parameter (label k, tau); + * - no hidden mutable global state: every function takes explicit objects; + * - every failure is an explicit at0_status, never a silent default; + * - every array index is bounds-checked against the case limits below. + * + * Portable C11 (plus __int128 through __extension__ for exact rationals). + */ +#ifndef AT0_MODEL_H +#define AT0_MODEL_H + +#include +#include +#include +#include + +/* ---- contract limits (AT0_CASE_V1 sections 2 and 3) ---------------------- */ +#define AT0_CLOCK_DIM_MIN 2 +#define AT0_CLOCK_DIM_MAX 64 +#define AT0_LABEL_MAX 256 +#define AT0_SYSTEM_DIM 2 +#define AT0_RATIONAL_LIMIT 1048576LL /* contract limit on written tokens */ +#define AT0_RAT_REPR_LIMIT 4611686018427387904LL /* 2^62: representability of derived rationals */ +#define AT0_SCALED_K_MAX 40 +#define AT0_INT_SATURATED 999999999999999999LL /* parsed value of any token longer than 18 digits */ +#define AT0_LABEL_LEN 32 +#define AT0_NAME_LEN 64 +#define AT0_DIGEST_HEX 64 +#define AT0_LINE_MAX 4096 + +/* ---- status codes --------------------------------------------------------- */ +typedef enum { + AT0_OK = 0, + /* case refusal codes, AT0_RESULT_V1 section 5, in contract order */ + AT0_CASE_PARSE_ERROR, + AT0_CASE_NONCANONICAL, + AT0_CASE_UNSUPPORTED_VERSION, + AT0_CASE_INVALID_PARAMETER, + AT0_CASE_IRRATIONAL_SPECTRUM, + AT0_CASE_ID_MISMATCH, + /* engine errors (never silent) */ + AT0_ERR_ARGUMENT, /* NULL pointer, index out of range, bad enum */ + AT0_ERR_OVERFLOW, /* exact arithmetic would overflow its limits */ + AT0_ERR_NONFINITE, /* a computed binary64 is NaN or infinite */ + AT0_ERR_IO, /* read or write failure */ + AT0_ERR_INTERNAL +} at0_status; + +const char *at0_status_name(at0_status s); +int at0_status_is_refusal(at0_status s); + +/* ---- exact arithmetic ----------------------------------------------------- */ +__extension__ typedef __int128 at0_i128; + +typedef struct { int64_t n; int64_t d; } at0_rat; /* reduced, d >= 1 */ +typedef struct { at0_rat re, im; } at0_crat; /* complex rational */ +typedef struct { uint64_t n; int k; } at0_scaled; /* n / 10^k */ + +at0_status at0_rat_make(int64_t n, int64_t d, at0_rat *out); /* reduces, checks limits */ +at0_status at0_rat_add(at0_rat a, at0_rat b, at0_rat *out); +at0_status at0_rat_sub(at0_rat a, at0_rat b, at0_rat *out); +at0_status at0_rat_mul(at0_rat a, at0_rat b, at0_rat *out); +int at0_rat_cmp(at0_rat a, at0_rat b); /* exact sign of a-b */ +int at0_rat_is_zero(at0_rat a); +int at0_rat_in_limits(at0_rat a); /* contract limit |n|, d <= 2^20 */ +int at0_scaled_in_limits(at0_scaled s); /* contract limit k <= 40 */ +double at0_rat_to_double(at0_rat a); /* one correctly-rounded division */ +/* exact test: is a a square of a rational? if yes, *root is the nonnegative root */ +at0_status at0_rat_sqrt_exact(at0_rat a, at0_rat *root, int *is_square); +/* reduce x into [-1/2, 1/2) exactly: x - round(x) */ +at0_status at0_rat_reduce_turn(at0_rat x, at0_rat *out); + +/* parse / print canonical tokens; parsing refuses non-canonical text */ +at0_status at0_rat_parse(const char *tok, at0_rat *out); +at0_status at0_crat_parse(const char *tok, at0_crat *out); +at0_status at0_scaled_parse(const char *tok, at0_scaled *out); +int at0_rat_format(at0_rat a, char *buf, size_t cap); +int at0_crat_format(at0_crat a, char *buf, size_t cap); +int at0_scaled_format(at0_scaled s, char *buf, size_t cap); + +/* exact comparison of a finite nonnegative binary64 p against scaled decimals: + * sets *le = (p + b <= tol), *gt = (p - b > tol), computed with exact integers */ +at0_status at0_exact_prob_status(double p, at0_scaled b, at0_scaled tol, int *le, int *gt); + +/* binary64 -> smallest-ish scaled decimal >= x (x finite, >= 0); ESTIMATED use only */ +at0_status at0_scaled_from_double_ceil(double x, at0_scaled *out); + +/* ---- case (versioned input) ----------------------------------------------- */ +typedef enum { AT0_CTRL_POSITIVE, AT0_CTRL_NEGATIVE } at0_control_kind; +typedef enum { AT0_EXPECT_PASS, AT0_EXPECT_FAIL } at0_expected_outcome; +typedef enum { AT0_BOUND_NONE = 0, AT0_BOUND_ESTIMATED = 1, AT0_BOUND_RIGOROUS = 2 } at0_bound_kind; + +#define AT0_FAILURE_CODE_COUNT 10 +extern const char *const at0_failure_codes[AT0_FAILURE_CODE_COUNT]; /* sorted bytewise */ + +typedef struct { + char name[AT0_NAME_LEN + 1]; + /* semantic block */ + int clock_dim; /* N */ + at0_rat clock_energies[AT0_CLOCK_DIM_MAX]; /* strictly increasing */ + at0_rat h0, hx, hy, hz; + char reference_clock_label[AT0_LABEL_LEN + 1]; + at0_crat psi0[AT0_SYSTEM_DIM]; + at0_rat povm_tau_turns; + at0_rat povm_weight; + int label_count; /* M */ + char labels[AT0_LABEL_MAX][AT0_LABEL_LEN + 1]; + /* acceptance block */ + at0_control_kind control_kind; + at0_expected_outcome expected_outcome; + int expected_failure_count; /* 0 means token "none" */ + int expected_failure_idx[AT0_FAILURE_CODE_COUNT]; + at0_bound_kind min_bound_kind; + at0_scaled tol_constraint_residual, tol_povm_residual, tol_probability, + tol_zero_probability, tol_schrodinger; + /* identities as read from the file, and recomputed */ + char case_id[AT0_DIGEST_HEX + 1]; + char acceptance_id[AT0_DIGEST_HEX + 1]; + char case_file_sha256[AT0_DIGEST_HEX + 1]; + /* derived exact data filled by validation */ + int reference_index; /* index r of reference label */ + at0_rat h_norm; /* |h| rational */ +} at0_case; + +/* Parse and validate AT0_CASE_V1 bytes (rules 1..6 in order). On refusal returns + * the refusal status and leaves *out unspecified. */ +at0_status at0_case_parse(const uint8_t *bytes, size_t len, at0_case *out); +/* Emit the canonical case text (byte-exact round trip). Returns bytes written or -1. */ +long at0_case_emit(const at0_case *c, char *buf, size_t cap); +/* Compute case_id / acceptance_id from a parsed case into 64-hex buffers. */ +at0_status at0_case_identities(const at0_case *c, char case_id[AT0_DIGEST_HEX + 1], + char acceptance_id[AT0_DIGEST_HEX + 1]); +at0_status at0_case_read_file(const char *path, at0_case *out); + +/* ---- quantum state representation ---------------------------------------- */ +/* The combined Hilbert space is C^N (x) C^2 with clock factor first: + * component index (j, s) -> j * 2 + s. */ +#define AT0_TOTAL_DIM_MAX (AT0_CLOCK_DIM_MAX * AT0_SYSTEM_DIM) + +typedef struct { + int clock_dim; + double complex amp[AT0_TOTAL_DIM_MAX]; +} at0_state; + +typedef struct { double complex v[AT0_SYSTEM_DIM]; } at0_qubit; +typedef struct { double complex m[AT0_SYSTEM_DIM][AT0_SYSTEM_DIM]; } at0_qubit_op; +typedef struct { int clock_dim; double complex v[AT0_CLOCK_DIM_MAX]; } at0_clock_vec; + +at0_status at0_state_init(at0_state *s, int clock_dim); /* zero state */ +at0_status at0_state_get(const at0_state *s, int j, int sys, double complex *out); +at0_status at0_state_set(at0_state *s, int j, int sys, double complex val); +at0_status at0_state_norm2(const at0_state *s, double *out); /* */ +at0_status at0_state_inner(const at0_state *a, const at0_state *b, double complex *out); +at0_status at0_state_scale(at0_state *s, double complex z); +at0_status at0_state_check_finite(const at0_state *s); + +/* ---- Hamiltonian construction --------------------------------------------- */ +typedef struct { + at0_rat eig[AT0_SYSTEM_DIM]; /* e_0 = h0 - |h|, e_1 = h0 + |h| (exact) */ + at0_qubit vec[AT0_SYSTEM_DIM]; /* orthonormal eigenvectors (binary64) */ + int degenerate; /* |h| == 0 */ + at0_qubit_op hs; /* H_S matrix in computational basis */ +} at0_system_hamiltonian; + +at0_status at0_hamiltonian_system(const at0_case *c, at0_system_hamiltonian *out); +/* apply H_total = H_C (x) I + I (x) H_S to a state */ +at0_status at0_hamiltonian_apply_total(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_state *in, at0_state *out); + +/* ---- constraint: kernel projection and verification ----------------------- */ +typedef struct { + int kernel_dim; /* exact count of (j, s) with E_j + e_s = 0 */ + int match_j[AT0_TOTAL_DIM_MAX]; /* matched clock index */ + int match_s[AT0_TOTAL_DIM_MAX]; /* matched system eigen index */ +} at0_kernel; + +at0_status at0_constraint_kernel(const at0_case *c, const at0_system_hamiltonian *hs, at0_kernel *out); +/* |Psi> = P_0 (|t_r> (x) |psi_0>) */ +at0_status at0_constraint_physical_state(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_kernel *k, at0_state *psi); +/* || H_total Psi_hat ||_2 ; requires Psi nonzero */ +at0_status at0_constraint_residual(const at0_case *c, const at0_system_hamiltonian *hs, + const at0_state *psi, double *out); + +/* ---- clock POVM ----------------------------------------------------------- */ +/* |t_k> = N^(-1/2) sum_j exp(-2 pi i E_j k tau) |E_j>, phase reduced exactly mod one turn */ +at0_status at0_povm_clock_state(const at0_case *c, int k, at0_clock_vec *out); +/* || sum_k w |t_k> 0 so rho exists numerically */ + at0_qubit_op rho; /* phi phi^dagger / ||phi||^2 when defined */ +} at0_conditional; + +at0_status at0_conditional_compute(const at0_case *c, const at0_state *psi, double psi_norm2, + int k, at0_conditional *out); + +/* ---- observables ---------------------------------------------------------- */ +typedef enum { AT0_AXIS_X = 0, AT0_AXIS_Y = 1, AT0_AXIS_Z = 2 } at0_axis; +typedef enum { AT0_SIGN_PLUS = 0, AT0_SIGN_MINUS = 1 } at0_sign; + +at0_status at0_pauli_matrix(at0_axis axis, at0_qubit_op *out); +/* P(sigma = +/-1) = Tr(rho (I +/- sigma)/2), computed directly, not as 1 - other */ +at0_status at0_observable_probability(const at0_qubit_op *rho, at0_axis axis, at0_sign sign, double *out); + +/* ---- engine run and versioned output -------------------------------------- */ +typedef enum { AT0_LABEL_DEFINED, AT0_LABEL_UNDEFINED, AT0_LABEL_INDETERMINATE } at0_label_status; + +typedef struct { + at0_label_status status; + double clock_probability; at0_scaled clock_probability_bound; + double pauli[3][2]; at0_scaled pauli_bound[3][2]; +} at0_label_values; + +typedef struct { + int kernel_dim; + int psi_nonzero; + double constraint_residual; at0_scaled constraint_residual_bound; + double povm_residual; at0_scaled povm_residual_bound; + int label_count; + at0_label_values label[AT0_LABEL_MAX]; + at0_bound_kind bound_kind; /* always ESTIMATED in this engine */ +} at0_engine_result; + +at0_status at0_engine_run(const at0_case *c, at0_engine_result *out); +/* test-only: evaluate the labels in reverse order; must give bit-identical values */ +at0_status at0_engine_run_reversed(const at0_case *c, at0_engine_result *out); + +/* OMEGA-AT0-ENGINE v1 writer (values block identical to AT0_RESULT_V1 section 1 + * minus the oracle's reference lines). Returns bytes written or -1. */ +long at0_engine_emit(const at0_case *c, const at0_engine_result *r, char *buf, size_t cap); +int at0_f64_format(double x, char *buf, size_t cap); /* f64:<16 hex>, -0 folded, nonfinite */ + +#endif /* AT0_MODEL_H */ diff --git a/research/atemporal/at0/model/at0_observable.c b/research/atemporal/at0/model/at0_observable.c new file mode 100644 index 000000000..141f2e67d --- /dev/null +++ b/research/atemporal/at0/model/at0_observable.c @@ -0,0 +1,37 @@ +/* Observable probabilities: P(sigma = +/-1) = Tr(rho (I +/- sigma)/2), each + * sign computed directly from rho (never as one minus the other). */ +#include "at0_model.h" +#include + +at0_status at0_pauli_matrix(at0_axis axis, at0_qubit_op *out) +{ + if (!out) return AT0_ERR_ARGUMENT; + switch (axis) { + case AT0_AXIS_X: out->m[0][0] = 0; out->m[0][1] = 1; out->m[1][0] = 1; out->m[1][1] = 0; return AT0_OK; + case AT0_AXIS_Y: out->m[0][0] = 0; out->m[0][1] = -I; out->m[1][0] = I; out->m[1][1] = 0; return AT0_OK; + case AT0_AXIS_Z: out->m[0][0] = 1; out->m[0][1] = 0; out->m[1][0] = 0; out->m[1][1] = -1; return AT0_OK; + default: return AT0_ERR_ARGUMENT; + } +} + +at0_status at0_observable_probability(const at0_qubit_op *rho, at0_axis axis, at0_sign sign, double *out) +{ + if (!rho || !out) return AT0_ERR_ARGUMENT; + if (sign != AT0_SIGN_PLUS && sign != AT0_SIGN_MINUS) return AT0_ERR_ARGUMENT; + at0_qubit_op sigma; + at0_status st = at0_pauli_matrix(axis, &sigma); + if (st != AT0_OK) return st; + double sgn = sign == AT0_SIGN_PLUS ? 1.0 : -1.0; + /* projector Pi = (I + sgn * sigma) / 2 ; probability = Tr(rho Pi) = sum_ab rho[a][b] Pi[b][a] */ + double complex tr = 0.0; + for (int a = 0; a < AT0_SYSTEM_DIM; a++) { + for (int b = 0; b < AT0_SYSTEM_DIM; b++) { + double complex pi_ba = 0.5 * ((a == b ? 1.0 : 0.0) + sgn * sigma.m[b][a]); + tr += rho->m[a][b] * pi_ba; + } + } + double p = creal(tr); + if (!isfinite(p)) return AT0_ERR_NONFINITE; + *out = p; + return AT0_OK; +} diff --git a/research/atemporal/at0/model/at0_output.c b/research/atemporal/at0/model/at0_output.c new file mode 100644 index 000000000..dd481e18f --- /dev/null +++ b/research/atemporal/at0/model/at0_output.c @@ -0,0 +1,76 @@ +/* OMEGA-AT0-ENGINE v1: the engine's versioned output. Its values block is the + * AT0_RESULT_V1 section 1 values block without the oracle's reference lines, + * so a runner can splice it into a result. This is a private format of the + * model directory, not a contract and not an identity. */ +#include "at0_model.h" +#include +#include + +int at0_f64_format(double x, char *buf, size_t cap) +{ + if (!isfinite(x)) return snprintf(buf, cap, "nonfinite"); + if (x == 0.0) x = 0.0; /* fold -0.0 to +0.0 */ + uint64_t bits; + memcpy(&bits, &x, sizeof bits); + return snprintf(buf, cap, "f64:%016llx", (unsigned long long)bits); +} + +typedef struct { char *buf; size_t cap; size_t len; int overflow; } out_t; +static void put(out_t *o, const char *s) +{ + size_t n = strlen(s); + if (o->len + n >= o->cap) { o->overflow = 1; return; } + memcpy(o->buf + o->len, s, n); o->len += n; o->buf[o->len] = 0; +} +static void put_value(out_t *o, double v, at0_scaled b) +{ + char t[64]; + at0_f64_format(v, t, sizeof t); put(o, t); put(o, " "); + at0_scaled_format(b, t, sizeof t); put(o, t); +} + +long at0_engine_emit(const at0_case *c, const at0_engine_result *r, char *buf, size_t cap) +{ + if (!c || !r || !buf || cap == 0) return -1; + static const char *axes[3] = { "X", "Y", "Z" }; + static const char *signs[2] = { "PLUS", "MINUS" }; + out_t o = { buf, cap, 0, 0 }; + char t[512]; + buf[0] = 0; + put(&o, "OMEGA-AT0-ENGINE v1\ndomain omega.at0.engine.v1\ncontract AT0_RESULT_V2\n"); + snprintf(t, sizeof t, "case_name %s\ncase_id %s\nacceptance_id %s\ncase_file_sha256 %s\n", + c->name, c->case_id, c->acceptance_id, c->case_file_sha256); put(&o, t); + put(&o, "begin numerics\narithmetic BINARY64\n"); + put(&o, r->bound_kind == AT0_BOUND_ESTIMATED ? "bound_kind ESTIMATED\n" : "bound_kind NONE\n"); + put(&o, "threads 1\nend numerics\nbegin values\n"); + snprintf(t, sizeof t, "physical_state_kernel_dim %d\n", r->kernel_dim); put(&o, t); + put(&o, "constraint_residual "); + if (r->psi_nonzero) put_value(&o, r->constraint_residual, r->constraint_residual_bound); else put(&o, "undefined 0@0"); + put(&o, "\n"); + put(&o, "povm_residual "); put_value(&o, r->povm_residual, r->povm_residual_bound); put(&o, "\n"); + for (int k = 0; k < r->label_count; k++) { + const at0_label_values *lv = &r->label[k]; + const char *status = lv->status == AT0_LABEL_DEFINED ? "DEFINED" + : lv->status == AT0_LABEL_UNDEFINED ? "UNDEFINED" : "INDETERMINATE"; + snprintf(t, sizeof t, "label %d %s %s\n", k, c->labels[k], status); put(&o, t); + } + for (int k = 0; k < r->label_count; k++) { + const at0_label_values *lv = &r->label[k]; + snprintf(t, sizeof t, "clock_probability %d ", k); put(&o, t); + if (r->psi_nonzero) put_value(&o, lv->clock_probability, lv->clock_probability_bound); else put(&o, "undefined 0@0"); + put(&o, "\n"); + } + for (int k = 0; k < r->label_count; k++) { + const at0_label_values *lv = &r->label[k]; + for (int ax = 0; ax < 3; ax++) { + for (int sg = 0; sg < 2; sg++) { + snprintf(t, sizeof t, "pauli %d %s %s ", k, axes[ax], signs[sg]); put(&o, t); + if (lv->status == AT0_LABEL_DEFINED) put_value(&o, lv->pauli[ax][sg], lv->pauli_bound[ax][sg]); + else put(&o, "undefined 0@0"); + put(&o, "\n"); + } + } + } + put(&o, "end values\nend\n"); + return o.overflow ? -1 : (long)o.len; +} diff --git a/research/atemporal/at0/model/at0_povm.c b/research/atemporal/at0/model/at0_povm.c new file mode 100644 index 000000000..1267ffce1 --- /dev/null +++ b/research/atemporal/at0/model/at0_povm.c @@ -0,0 +1,74 @@ +/* Internal clock POVM: covariant discrete clock states and the normalization + * residual. The phase of each component is reduced exactly (rational, mod one + * turn) before cos/sin, so no accumulated angle drift and no lookup table. */ +#include "at0_model.h" +#include +#include + +#define AT0_TWO_PI 6.283185307179586476925286766559 + +/* exp(-2 pi i E_j k tau) with the turn count reduced exactly in 128-bit integers */ +static at0_status clock_phase(const at0_case *c, int j, int k, double complex *out) +{ + if (j < 0 || j >= c->clock_dim || k < 0 || k >= c->label_count) return AT0_ERR_ARGUMENT; + at0_rat e = c->clock_energies[j], tau = c->povm_tau_turns; + at0_i128 n = (at0_i128)e.n * k * tau.n; /* |n| <= 2^20 * 2^8 * 2^20 = 2^48 */ + at0_i128 d = (at0_i128)e.d * tau.d; /* d <= 2^40 */ + /* x = n/d ; reduce to [-1/2, 1/2): x - round_half_up(x) */ + at0_i128 twice = 2 * n + d; + at0_i128 q = twice / (2 * d); + if (twice < 0 && twice % (2 * d) != 0) q -= 1; + at0_i128 rn = n - q * d; /* |rn| <= d */ + double x = (double)(long long)rn / (double)(long long)d; /* both exact in binary64 */ + double theta = -AT0_TWO_PI * x; + double cs = cos(theta), sn = sin(theta); + if (!isfinite(cs) || !isfinite(sn)) return AT0_ERR_NONFINITE; + *out = cs + I * sn; + return AT0_OK; +} + +at0_status at0_povm_clock_state(const at0_case *c, int k, at0_clock_vec *out) +{ + if (!c || !out) return AT0_ERR_ARGUMENT; + if (c->clock_dim < AT0_CLOCK_DIM_MIN || c->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + if (k < 0 || k >= c->label_count) return AT0_ERR_ARGUMENT; + memset(out, 0, sizeof *out); + out->clock_dim = c->clock_dim; + double scale = 1.0 / sqrt((double)c->clock_dim); + for (int j = 0; j < c->clock_dim; j++) { + double complex ph; + at0_status st = clock_phase(c, j, k, &ph); + if (st != AT0_OK) return st; + out->v[j] = scale * ph; + } + return AT0_OK; +} + +at0_status at0_povm_residual(const at0_case *c, double *out) +{ + if (!c || !out) return AT0_ERR_ARGUMENT; + int n = c->clock_dim; + if (n < AT0_CLOCK_DIM_MIN || n > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + double w = at0_rat_to_double(c->povm_weight); + double complex s[AT0_CLOCK_DIM_MAX][AT0_CLOCK_DIM_MAX]; + memset(s, 0, sizeof s); + for (int k = 0; k < c->label_count; k++) { + at0_clock_vec t; + at0_status st = at0_povm_clock_state(c, k, &t); + if (st != AT0_OK) return st; + for (int j = 0; j < n; j++) + for (int l = 0; l < n; l++) + s[j][l] += w * t.v[j] * conj(t.v[l]); + } + double acc = 0.0; + for (int j = 0; j < n; j++) { + for (int l = 0; l < n; l++) { + double complex d = s[j][l] - (j == l ? 1.0 : 0.0); + acc += creal(d) * creal(d) + cimag(d) * cimag(d); + } + } + double r = sqrt(acc); + if (!isfinite(r)) return AT0_ERR_NONFINITE; + *out = r; + return AT0_OK; +} diff --git a/research/atemporal/at0/model/at0_state.c b/research/atemporal/at0/model/at0_state.c new file mode 100644 index 000000000..f610f2b57 --- /dev/null +++ b/research/atemporal/at0/model/at0_state.c @@ -0,0 +1,76 @@ +/* Quantum state representation: a vector in C^N (x) C^2, clock factor first. + * Every accessor checks its indices; nothing here is global. */ +#include "at0_model.h" +#include +#include + +static int index_ok(const at0_state *s, int j, int sys) +{ + return s && s->clock_dim >= AT0_CLOCK_DIM_MIN && s->clock_dim <= AT0_CLOCK_DIM_MAX && + j >= 0 && j < s->clock_dim && sys >= 0 && sys < AT0_SYSTEM_DIM; +} + +at0_status at0_state_init(at0_state *s, int clock_dim) +{ + if (!s || clock_dim < AT0_CLOCK_DIM_MIN || clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + memset(s, 0, sizeof *s); + s->clock_dim = clock_dim; + return AT0_OK; +} + +at0_status at0_state_get(const at0_state *s, int j, int sys, double complex *out) +{ + if (!out || !index_ok(s, j, sys)) return AT0_ERR_ARGUMENT; + *out = s->amp[j * AT0_SYSTEM_DIM + sys]; + return AT0_OK; +} + +at0_status at0_state_set(at0_state *s, int j, int sys, double complex val) +{ + if (!index_ok(s, j, sys)) return AT0_ERR_ARGUMENT; + s->amp[j * AT0_SYSTEM_DIM + sys] = val; + return AT0_OK; +} + +at0_status at0_state_norm2(const at0_state *s, double *out) +{ + if (!s || !out || s->clock_dim < AT0_CLOCK_DIM_MIN || s->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + double acc = 0.0; + int n = s->clock_dim * AT0_SYSTEM_DIM; + for (int i = 0; i < n; i++) { + double re = creal(s->amp[i]), im = cimag(s->amp[i]); + acc += re * re + im * im; + } + if (!isfinite(acc)) return AT0_ERR_NONFINITE; + *out = acc; + return AT0_OK; +} + +at0_status at0_state_inner(const at0_state *a, const at0_state *b, double complex *out) +{ + if (!a || !b || !out || a->clock_dim != b->clock_dim) return AT0_ERR_ARGUMENT; + if (a->clock_dim < AT0_CLOCK_DIM_MIN || a->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + double complex acc = 0.0; + int n = a->clock_dim * AT0_SYSTEM_DIM; + for (int i = 0; i < n; i++) acc += conj(a->amp[i]) * b->amp[i]; + if (!isfinite(creal(acc)) || !isfinite(cimag(acc))) return AT0_ERR_NONFINITE; + *out = acc; + return AT0_OK; +} + +at0_status at0_state_scale(at0_state *s, double complex z) +{ + if (!s || s->clock_dim < AT0_CLOCK_DIM_MIN || s->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + int n = s->clock_dim * AT0_SYSTEM_DIM; + for (int i = 0; i < n; i++) s->amp[i] *= z; + return at0_state_check_finite(s); +} + +at0_status at0_state_check_finite(const at0_state *s) +{ + if (!s || s->clock_dim < AT0_CLOCK_DIM_MIN || s->clock_dim > AT0_CLOCK_DIM_MAX) return AT0_ERR_ARGUMENT; + int n = s->clock_dim * AT0_SYSTEM_DIM; + for (int i = 0; i < n; i++) + if (!isfinite(creal(s->amp[i])) || !isfinite(cimag(s->amp[i]))) return AT0_ERR_NONFINITE; + return AT0_OK; +} diff --git a/research/atemporal/at0/model/build.sh b/research/atemporal/at0/model/build.sh new file mode 100755 index 000000000..3d2a09c41 --- /dev/null +++ b/research/atemporal/at0/model/build.sh @@ -0,0 +1,21 @@ +#!/bin/sh +# Build the AT-0 candidate engine and its tests (plain C11, -lm only). +# ./build.sh plain build into ./build +# ./build.sh asan address + undefined sanitizer build into ./build-asan +# Links omega's src/sha256.c (the only shared source); never touches omega's Makefile. +set -eu +HERE=$(cd "$(dirname "$0")" && pwd) +ROOT=$(cd "$HERE/../../../.." && pwd) +MODE=${1:-plain} +CFLAGS="-std=c11 -Wall -Wextra -Werror -pedantic -D_POSIX_C_SOURCE=200809L -I$HERE -I$ROOT/src" +if [ "$MODE" = asan ]; then OUT="$HERE/build-asan"; CFLAGS="$CFLAGS -O1 -g -fsanitize=address,undefined -fno-sanitize-recover=all" +else OUT="$HERE/build"; CFLAGS="$CFLAGS -O2"; fi +CC=${CC:-gcc} +mkdir -p "$OUT" +LIB="$HERE/at0_exact.c $HERE/at0_case.c $HERE/at0_state.c $HERE/at0_hamiltonian.c $HERE/at0_constraint.c \ + $HERE/at0_povm.c $HERE/at0_conditional.c $HERE/at0_observable.c $HERE/at0_engine.c $HERE/at0_output.c $ROOT/src/sha256.c" +# shellcheck disable=SC2086 +$CC $CFLAGS -o "$OUT/at0-model" $HERE/at0_main.c $LIB -lm +# shellcheck disable=SC2086 +$CC $CFLAGS -o "$OUT/at0-tests" $HERE/tests/test_model.c $LIB -lm +echo "built $OUT/at0-model and $OUT/at0-tests ($MODE)" diff --git a/research/atemporal/at0/model/tests/.crumb b/research/atemporal/at0/model/tests/.crumb new file mode 100644 index 000000000..b10c7868f --- /dev/null +++ b/research/atemporal/at0/model/tests/.crumb @@ -0,0 +1,26 @@ +{ + "extensions": { + "generated": { + "children": [ + { + "digest": "3f458e7cbb850b27968d4de4597067b979707b6230e5259a523d7538006967b6", + "last_commit": "547cda8", + "name": "cases", + "purpose": "AT0_CASE_V1 case files used by the tests; the KAT file is the contract section 6 example byte fo" + } + ], + "children_root": "sha256:4d31598f44679f12de8b915d8daea2f08fe425951cb1f553554349a0718ea56f", + "compiled_at": "2026-10-09T22:41:51Z", + "compiler": "crumb-compile/1", + "digest": "sha256:e9114c1e9534737dc1a4d49971f6abb3278e4dcf7c5b9c544795c90c8812bccc", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 3, + "generated_at_commit": "f5ece3506f5451e4b8e13145a96e758fe0359b86", + "source_tree": "sha256:f33d7951bb98df749c5654eea9169eb06cd808c908b5f8d3c931a118110f90f2" + } + }, + "name": "tests", + "purpose": "Component tests and case files for the candidate engine", + "schema_version": "1.0.0" +} diff --git a/research/atemporal/at0/model/tests/cases/.crumb b/research/atemporal/at0/model/tests/cases/.crumb new file mode 100644 index 000000000..999c6da23 --- /dev/null +++ b/research/atemporal/at0/model/tests/cases/.crumb @@ -0,0 +1,19 @@ +{ + "extensions": { + "generated": { + "children": [], + "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "compiled_at": "2026-10-09T22:33:14Z", + "compiler": "crumb-compile/1", + "digest": "sha256:3f458e7cbb850b27968d4de4597067b979707b6230e5259a523d7538006967b6", + "evidence_files": 0, + "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "files": 1, + "generated_at_commit": "547cda8fefd174045da3b7833972ae5d22496878", + "source_tree": "sha256:e846c823a32f900e5e0cbd6cd17f13ade7d2ff7bf98d17ffeae31c2d3f41d008" + } + }, + "name": "cases", + "purpose": "AT0_CASE_V1 case files used by the tests; the KAT file is the contract section 6 example byte for byte", + "schema_version": "1.0.0" +} diff --git a/research/atemporal/at0/model/tests/cases/kat-ideal-qubit-n4.case b/research/atemporal/at0/model/tests/cases/kat-ideal-qubit-n4.case new file mode 100644 index 000000000..3f4c2c03d --- /dev/null +++ b/research/atemporal/at0/model/tests/cases/kat-ideal-qubit-n4.case @@ -0,0 +1,40 @@ +OMEGA-AT0-CASE v1 +domain omega.at0.case.v1 +contract AT0_CASE_V1 +case_name at0-kat-ideal-qubit-n4 +begin semantic +model_family PAGE_WOOTTERS_FINITE_IDEAL +energy_unit DIMENSIONLESS_HBAR_1 +clock_dim 4 +clock_energies -3/2,-1/2,1/2,3/2 +system_dim 2 +system_hamiltonian_pauli 0/1,0/1,0/1,1/2 +interaction NONE +constraint SUM_HC_HS +physical_state NULLSPACE_PROJECTION +reference_clock_label t0 +reference_system_state (1/1;0/1),(1/1;0/1) +clock_povm COVARIANT_DISCRETE +povm_tau_turns 1/4 +povm_weight 1/1 +clock_label_count 4 +clock_label 0 t0 +clock_label 1 t1 +clock_label 2 t2 +clock_label 3 t3 +observables PAULI_X,PAULI_Y,PAULI_Z +end semantic +begin acceptance +control_kind POSITIVE +expected_outcome PASS +expected_failure_codes none +min_bound_kind ESTIMATED +tol_constraint_residual 1@12 +tol_povm_residual 1@12 +tol_probability 1@12 +tol_zero_probability 1@9 +tol_schrodinger 1@12 +end acceptance +case_id 3cf4ca4f882b5b9691ddcd905e65e15010855adcd2be200e19ebc3184655b44d +acceptance_id a13fb02dd674b8042ef8c0a197f03d58768709f782ba59cd26545eef6d41a228 +end diff --git a/research/atemporal/at0/model/tests/mkcase.sh b/research/atemporal/at0/model/tests/mkcase.sh new file mode 100755 index 000000000..f22e812fe --- /dev/null +++ b/research/atemporal/at0/model/tests/mkcase.sh @@ -0,0 +1,13 @@ +#!/bin/sh +# Stamp AT0_CASE_V1 identities onto a hand-written case body. +# tests/mkcase.sh > +# The body holds every line from "OMEGA-AT0-CASE v1" through "end acceptance". +# Appends case_id, acceptance_id and "end" per AT0_CASE_V1 section 5 +# (SHA-256 of domain tag, one zero byte, then the block lines). No Python. +set -eu +body=$1 +tagged() { { printf '%s' "$1"; printf '\0'; sed -n "/^begin $2\$/,/^end $2\$/p" "$body"; } | sha256sum | cut -c1-64; } +cat "$body" +printf 'case_id %s\n' "$(tagged omega.at0.case.v1 semantic)" +printf 'acceptance_id %s\n' "$(tagged omega.at0.acceptance.v1 acceptance)" +printf 'end\n' diff --git a/research/atemporal/at0/model/tests/test_model.c b/research/atemporal/at0/model/tests/test_model.c new file mode 100644 index 000000000..3e33b9bb9 --- /dev/null +++ b/research/atemporal/at0/model/tests/test_model.c @@ -0,0 +1,521 @@ +/* Component tests for the AT-0 candidate engine. + * at0-tests + * Every test is a plain function returning 0 on pass; failures print the + * test name and the offending value. No randomness, no wall clock. */ +#include "at0_model.h" +#include +#include +#include + +static int failures = 0; +#define CHECK(cond, ...) do { if (!(cond)) { failures++; printf(" FAIL %s:%d: ", __func__, __LINE__); printf(__VA_ARGS__); printf("\n"); return 1; } } while (0) +#define OK(call) CHECK((call) == AT0_OK, "%s returned %s", #call, at0_status_name(call)) + +static const char *cases_dir; +static at0_case kat; /* the AT0_CASE_V1 section 6 example, parsed once */ +static uint8_t kat_bytes[8192]; static size_t kat_len; + +static int load_file(const char *name, uint8_t *buf, size_t cap, size_t *len) +{ + char path[1024]; + snprintf(path, sizeof path, "%s/%s", cases_dir, name); + FILE *f = fopen(path, "rb"); + if (!f) return 0; + *len = fread(buf, 1, cap, f); + fclose(f); + return 1; +} + +/* build a case from a struct: compute ids, emit, parse back through the full validator */ +static at0_status finalize(at0_case *c) +{ + at0_status st = at0_case_identities(c, c->case_id, c->acceptance_id); + if (st != AT0_OK) return st; + static char buf[65536]; + long n = at0_case_emit(c, buf, sizeof buf); + if (n < 0) return AT0_ERR_INTERNAL; + return at0_case_parse((const uint8_t *)buf, (size_t)n, c); +} + +static at0_rat R(int64_t n, int64_t d) { at0_rat r; at0_status st = at0_rat_make(n, d, &r); if (st != AT0_OK) { r.n = 0; r.d = 1; } return r; } +static at0_scaled S(uint64_t n, int k) { at0_scaled s = { n, k }; return s; } + +/* a two-level-clock case in the draft AT0_SPEC mapping: omega = 1, N = 2, M labels, w = 2/M */ +static void spec_two_level(at0_case *c, int m, int ref) +{ + memset(c, 0, sizeof *c); + strcpy(c->name, "spec-two-level"); + c->clock_dim = 2; c->clock_energies[0] = R(-1, 1); c->clock_energies[1] = R(0, 1); + c->h0 = R(1, 2); c->hx = R(0, 1); c->hy = R(0, 1); c->hz = R(-1, 2); + c->psi0[0].re = R(1, 1); c->psi0[0].im = R(0, 1); c->psi0[1].re = R(1, 1); c->psi0[1].im = R(0, 1); + c->povm_tau_turns = R(1, m); c->povm_weight = R(2, m); + c->label_count = m; + for (int k = 0; k < m; k++) snprintf(c->labels[k], sizeof c->labels[k], "t%d", k); + strcpy(c->reference_clock_label, c->labels[ref]); + c->control_kind = AT0_CTRL_POSITIVE; c->expected_outcome = AT0_EXPECT_PASS; + c->min_bound_kind = AT0_BOUND_ESTIMATED; + c->tol_constraint_residual = S(1, 12); c->tol_povm_residual = S(1, 12); c->tol_probability = S(1, 12); + c->tol_zero_probability = S(1, 9); c->tol_schrodinger = S(1, 12); +} + +/* test-side Schrodinger reference (not the AT-0 oracle): U = exp(-i H_S t) via the 2x2 identity + * exp(-i (h0 I + h.sigma) t) = e^{-i h0 t} (cos(|h| t) I - i sin(|h| t) (h.sigma)/|h|) */ +static void schrodinger_probs(const at0_case *c, double t, double out[3][2]) +{ + double h0 = at0_rat_to_double(c->h0), hx = at0_rat_to_double(c->hx), hy = at0_rat_to_double(c->hy), hz = at0_rat_to_double(c->hz); + double r = at0_rat_to_double(c->h_norm); + double complex u[2][2]; + double complex g = cexp(-I * h0 * t); + if (r == 0.0) { u[0][0] = g; u[0][1] = 0; u[1][0] = 0; u[1][1] = g; } + else { + double cs = cos(r * t), sn = sin(r * t); + u[0][0] = g * (cs - I * sn * hz / r); u[0][1] = g * (-I * sn * (hx - I * hy) / r); + u[1][0] = g * (-I * sn * (hx + I * hy) / r); u[1][1] = g * (cs + I * sn * hz / r); + } + double complex p0 = at0_rat_to_double(c->psi0[0].re) + I * at0_rat_to_double(c->psi0[0].im); + double complex p1 = at0_rat_to_double(c->psi0[1].re) + I * at0_rat_to_double(c->psi0[1].im); + double complex v0 = u[0][0] * p0 + u[0][1] * p1, v1 = u[1][0] * p0 + u[1][1] * p1; + double n2 = cabs(v0) * cabs(v0) + cabs(v1) * cabs(v1); + double complex eig[3][2][2] = { + { { 1 / sqrt(2.0), 1 / sqrt(2.0) }, { 1 / sqrt(2.0), -1 / sqrt(2.0) } }, /* X+, X- */ + { { 1 / sqrt(2.0), I / sqrt(2.0) }, { 1 / sqrt(2.0), -I / sqrt(2.0) } }, /* Y+, Y- */ + { { 1, 0 }, { 0, 1 } } }; /* Z+, Z- */ + for (int a = 0; a < 3; a++) for (int s = 0; s < 2; s++) { + double complex ov = conj(eig[a][s][0]) * v0 + conj(eig[a][s][1]) * v1; + out[a][s] = cabs(ov) * cabs(ov) / n2; + } +} + +static double scaled_to_double(at0_scaled s) { return (double)s.n * pow(10.0, -s.k); } + +/* ---- tests ---------------------------------------------------------------- */ +static int test_kat_roundtrip(void) +{ + static char buf[8192]; + long n = at0_case_emit(&kat, buf, sizeof buf); + CHECK(n == (long)kat_len && memcmp(buf, kat_bytes, kat_len) == 0, "re-emitted KAT differs from file"); + CHECK(strcmp(kat.case_id, "3cf4ca4f882b5b9691ddcd905e65e15010855adcd2be200e19ebc3184655b44d") == 0, "case_id"); + CHECK(strcmp(kat.acceptance_id, "a13fb02dd674b8042ef8c0a197f03d58768709f782ba59cd26545eef6d41a228") == 0, "acceptance_id"); + CHECK(strcmp(kat.case_file_sha256, "ed16c95c89bf312b0fbf95a4cd43bc352daa138954fabad78d8a170cd35b4e81") == 0, "case_file_sha256"); + char cid[65], aid[65]; + OK(at0_case_identities(&kat, cid, aid)); + CHECK(strcmp(cid, kat.case_id) == 0 && strcmp(aid, kat.acceptance_id) == 0, "recomputed identities differ"); + CHECK(kat.h_norm.n == 1 && kat.h_norm.d == 2, "|h| = %lld/%lld", (long long)kat.h_norm.n, (long long)kat.h_norm.d); + return 0; +} + +static int test_exact_arithmetic(void) +{ + at0_rat a, b, r; int sq; + OK(at0_rat_make(6, -4, &a)); CHECK(a.n == -3 && a.d == 2, "reduce"); + OK(at0_rat_make(1, 3, &b)); OK(at0_rat_add(a, b, &r)); CHECK(r.n == -7 && r.d == 6, "add"); + OK(at0_rat_sqrt_exact(R(9, 4), &r, &sq)); CHECK(sq && r.n == 3 && r.d == 2, "sqrt 9/4"); + OK(at0_rat_sqrt_exact(R(2, 1), &r, &sq)); CHECK(!sq, "sqrt 2 must not be rational"); + OK(at0_rat_reduce_turn(R(7, 4), &r)); CHECK(r.n == -1 && r.d == 4, "7/4 mod turn -> -1/4, got %lld/%lld", (long long)r.n, (long long)r.d); + OK(at0_rat_reduce_turn(R(-1, 2), &r)); CHECK(r.n == -1 && r.d == 2, "-1/2 stays -1/2"); + OK(at0_rat_reduce_turn(R(1, 2), &r)); CHECK(r.n == -1 && r.d == 2, "1/2 -> -1/2"); + OK(at0_rat_make(AT0_RATIONAL_LIMIT + 1, 1, &r)); CHECK(!at0_rat_in_limits(r), "contract limit is a rule-3 property, not an arithmetic one"); + CHECK(at0_rat_make(INT64_MAX, 1, &r) == AT0_ERR_OVERFLOW, "representability limit"); + OK(at0_rat_make(1000, 1, &r)); OK(at0_rat_mul(r, r, &r)); OK(at0_rat_mul(r, r, &r)); CHECK(r.n == 1000000000000LL, "wide product"); + CHECK(at0_rat_parse("2/4", &r) == AT0_CASE_NONCANONICAL, "2/4"); + CHECK(at0_rat_parse("-0/1", &r) == AT0_CASE_PARSE_ERROR, "-0/1"); + CHECK(at0_rat_parse("+1/1", &r) == AT0_CASE_PARSE_ERROR, "+1/1"); + CHECK(at0_rat_parse("1/0", &r) == AT0_CASE_NONCANONICAL, "1/0"); + at0_scaled s; + CHECK(at0_scaled_parse("10@13", &s) == AT0_CASE_NONCANONICAL, "10@13"); + CHECK(at0_scaled_parse("0@3", &s) == AT0_CASE_NONCANONICAL, "0@3"); + OK(at0_scaled_parse("1@41", &s)); CHECK(!at0_scaled_in_limits(s), "1@41 parses, rule 3 refuses it"); + OK(at0_scaled_parse("25@2", &s)); CHECK(s.n == 25 && s.k == 2, "25@2"); + /* exact comparison: p = 0.25, b = 1e-15, tol = 1e-9 -> defined */ + int le, gt; + OK(at0_exact_prob_status(0.25, S(1, 15), S(1, 9), &le, >)); CHECK(!le && gt, "0.25 defined"); + OK(at0_exact_prob_status(0.0, S(1, 15), S(1, 9), &le, >)); CHECK(le && !gt, "0 undefined"); + OK(at0_exact_prob_status(1e-9, S(0, 0), S(1, 9), &le, >)); CHECK(!le && gt, "binary64 nearest 1e-9 is above 10^-9, so exactly greater"); + OK(at0_exact_prob_status(5e-324, S(0, 0), S(0, 0), &le, >)); CHECK(!le && gt, "subnormal > 0 exactly"); + OK(at0_exact_prob_status(0.5, S(5, 1), S(0, 0), &le, >)); CHECK(!le && !gt, "p - b == tol boundary"); + return 0; +} + +static int test_state_normalization(void) +{ + at0_system_hamiltonian hs; at0_kernel k; at0_state psi; double n2; + OK(at0_hamiltonian_system(&kat, &hs)); + OK(at0_constraint_kernel(&kat, &hs, &k)); + OK(at0_constraint_physical_state(&kat, &hs, &k, &psi)); + OK(at0_state_norm2(&psi, &n2)); + CHECK(n2 > 0.0, "physical state is zero"); + OK(at0_state_scale(&psi, 1.0 / sqrt(n2))); + OK(at0_state_norm2(&psi, &n2)); + CHECK(fabs(n2 - 1.0) < 4e-16, "normalized norm2 = %.17g", n2); + for (int kk = 0; kk < kat.label_count; kk++) { + at0_clock_vec t; double acc = 0; + OK(at0_povm_clock_state(&kat, kk, &t)); + for (int j = 0; j < t.clock_dim; j++) acc += cabs(t.v[j]) * cabs(t.v[j]); + CHECK(fabs(acc - 1.0) < 4e-16, "clock state %d norm2 = %.17g", kk, acc); + } + /* eigenvectors orthonormal for a tilted field */ + at0_case c = kat; c.hx = R(3, 10); c.hz = R(2, 5); c.h0 = R(1, 4); + OK(finalize(&c)); + OK(at0_hamiltonian_system(&c, &hs)); + double complex ov = conj(hs.vec[0].v[0]) * hs.vec[1].v[0] + conj(hs.vec[0].v[1]) * hs.vec[1].v[1]; + CHECK(cabs(ov) < 4e-16, "eigenvectors not orthogonal: %.3g", cabs(ov)); + return 0; +} + +static int test_constraint_satisfaction(void) +{ + at0_system_hamiltonian hs; at0_kernel k; at0_state psi; double r; + OK(at0_hamiltonian_system(&kat, &hs)); + OK(at0_constraint_kernel(&kat, &hs, &k)); + CHECK(k.kernel_dim == 2, "kernel dim %d", k.kernel_dim); + OK(at0_constraint_physical_state(&kat, &hs, &k, &psi)); + OK(at0_constraint_residual(&kat, &hs, &psi, &r)); + CHECK(r <= 1e-15, "residual %.3g", r); + /* stationarity: a kernel vector is invariant under any evolution parameter; here the + * generator annihilates it, so H_total applied twice is zero too */ + at0_state h; double hn; + OK(at0_hamiltonian_apply_total(&kat, &hs, &psi, &h)); OK(at0_state_norm2(&h, &hn)); + CHECK(hn <= 1e-30, "H Psi norm2 %.3g", hn); + /* negative control: a product state outside the kernel */ + at0_state bad; OK(at0_state_init(&bad, kat.clock_dim)); OK(at0_state_set(&bad, 0, 0, 1.0)); + OK(at0_constraint_residual(&kat, &hs, &bad, &r)); + CHECK(fabs(r - 1.0) < 1e-15, "|E_0>|0> residual should be |-3/2 + 1/2| = 1, got %.17g", r); + /* uncovered spectrum: kernel empty, Psi zero */ + at0_case c = kat; for (int j = 0; j < 4; j++) c.clock_energies[j] = R(j + 1, 1); + OK(finalize(&c)); OK(at0_hamiltonian_system(&c, &hs)); OK(at0_constraint_kernel(&c, &hs, &k)); + CHECK(k.kernel_dim == 0, "uncovered kernel dim %d", k.kernel_dim); + OK(at0_constraint_physical_state(&c, &hs, &k, &psi)); double n2; OK(at0_state_norm2(&psi, &n2)); + CHECK(n2 == 0.0, "uncovered Psi must be zero"); + CHECK(at0_constraint_residual(&c, &hs, &psi, &r) == AT0_ERR_ARGUMENT, "residual of zero state must be refused"); + /* exact-zero overlap: psi0 orthogonal to the only matched eigenvector gives Psi = 0 exactly */ + c = kat; c.clock_energies[0] = R(-3, 2); c.clock_energies[1] = R(-1, 2); c.clock_energies[2] = R(3, 2); c.clock_energies[3] = R(5, 2); + c.psi0[0].re = R(0, 1); c.psi0[1].re = R(1, 1); /* only e=+1/2 (|0>) matched by E=-1/2; psi0 = |1> */ + OK(finalize(&c)); OK(at0_hamiltonian_system(&c, &hs)); OK(at0_constraint_kernel(&c, &hs, &k)); + CHECK(k.kernel_dim == 1, "half-covered kernel dim %d", k.kernel_dim); + OK(at0_constraint_physical_state(&c, &hs, &k, &psi)); OK(at0_state_norm2(&psi, &n2)); + CHECK(n2 == 0.0, "orthogonal psi0 must give exactly zero Psi"); + /* degenerate system (|h| = 0): kernel holds both system components of the matched energy */ + c = kat; c.hz = R(0, 1); c.h0 = R(1, 2); OK(finalize(&c)); + OK(at0_hamiltonian_system(&c, &hs)); CHECK(hs.degenerate, "degenerate flag"); + OK(at0_constraint_kernel(&c, &hs, &k)); CHECK(k.kernel_dim == 2, "degenerate kernel dim %d", k.kernel_dim); + return 0; +} + +static int test_povm_normalization(void) +{ + double r; + OK(at0_povm_residual(&kat, &r)); + CHECK(r <= 1e-15, "KAT povm residual %.3g", r); + at0_case c = kat; c.povm_weight = R(1, 2); OK(finalize(&c)); + OK(at0_povm_residual(&c, &r)); + CHECK(fabs(r - 1.0) < 1e-14, "w=1/2 residual should be ||I/2||_F = 1, got %.17g", r); + c = kat; c.label_count = 3; OK(finalize(&c)); + OK(at0_povm_residual(&c, &r)); + CHECK(r > 0.5, "dropped label residual %.3g", r); + c = kat; c.povm_tau_turns = R(1, 3); OK(finalize(&c)); /* broken clock: D tau M not integer */ + OK(at0_povm_residual(&c, &r)); + CHECK(r > 0.1, "broken clock residual %.3g", r); + /* N = 8, M = 8, tau = 1/4 with half-integer gaps: still a resolution of the identity */ + memset(&c, 0, sizeof c); c = kat; c.clock_dim = 8; + for (int j = 0; j < 8; j++) c.clock_energies[j] = R(-3 + 2 * j, 4); + c.label_count = 8; for (int k = 0; k < 8; k++) snprintf(c.labels[k], sizeof c.labels[k], "t%d", k); + OK(finalize(&c)); OK(at0_povm_residual(&c, &r)); + CHECK(r <= 1e-14, "N=8 residual %.3g", r); + return 0; +} + +static int test_conditional_density(void) +{ + at0_system_hamiltonian hs; at0_kernel k; at0_state psi; double n2, psum = 0; + OK(at0_hamiltonian_system(&kat, &hs)); OK(at0_constraint_kernel(&kat, &hs, &k)); + OK(at0_constraint_physical_state(&kat, &hs, &k, &psi)); OK(at0_state_norm2(&psi, &n2)); + for (int kk = 0; kk < kat.label_count; kk++) { + at0_conditional cd; + OK(at0_conditional_compute(&kat, &psi, n2, kk, &cd)); + CHECK(cd.defined_numeric, "label %d undefined", kk); + double tr = creal(cd.rho.m[0][0] + cd.rho.m[1][1]); + CHECK(fabs(tr - 1.0) < 4e-16, "trace %.17g", tr); + CHECK(cabs(cd.rho.m[0][1] - conj(cd.rho.m[1][0])) < 4e-16, "not hermitian"); + /* purity: rho^2 == rho */ + for (int a = 0; a < 2; a++) for (int b = 0; b < 2; b++) { + double complex sq = cd.rho.m[a][0] * cd.rho.m[0][b] + cd.rho.m[a][1] * cd.rho.m[1][b]; + CHECK(cabs(sq - cd.rho.m[a][b]) < 8e-16, "rho^2 != rho at %d%d", a, b); + } + CHECK(fabs(cd.clock_probability - 0.25) < 4e-16, "p(%d) = %.17g", kk, cd.clock_probability); + psum += cd.clock_probability; + } + CHECK(fabs(psum - 1.0) < 8e-16, "sum p = %.17g", psum); + CHECK(at0_conditional_compute(&kat, &psi, n2, 4, (at0_conditional *)&hs) == AT0_ERR_ARGUMENT, "label out of range"); + return 0; +} + +static int test_pauli_probabilities(void) +{ + /* KAT hand table (AT0_CASE_V1 section 6): P(X+), P(Y+), P(Z+) per label */ + static const double table[4][3] = { {1, .5, .5}, {.5, 1, .5}, {0, .5, .5}, {.5, 0, .5} }; + static at0_engine_result res; at0_engine_result *r = &res; memset(r, 0, sizeof *r); + OK(at0_engine_run(&kat, r)); + for (int k = 0; k < 4; k++) { + CHECK(r->label[k].status == AT0_LABEL_DEFINED, "label %d not DEFINED", k); + for (int a = 0; a < 3; a++) { + double plus = r->label[k].pauli[a][0], minus = r->label[k].pauli[a][1]; + CHECK(fabs(plus - table[k][a]) <= 1e-15, "k=%d axis=%d P+ = %.17g", k, a, plus); + CHECK(fabs(plus + minus - 1.0) <= 4e-16, "pair sum k=%d axis=%d", k, a); + CHECK(fabs(plus - table[k][a]) <= scaled_to_double(r->label[k].pauli_bound[a][0]), "deviation exceeds stated bound"); + } + } + /* draft-spec two-level mapping: P(Y+) = (1 - sin theta_k)/2 = 1/2, 0, 1/2, 1 for M = 4 */ + at0_case c; spec_two_level(&c, 4, 0); OK(finalize(&c)); + OK(at0_engine_run(&c, r)); + static const double yplus[4] = { .5, 0, .5, 1 }; + for (int k = 0; k < 4; k++) { + CHECK(fabs(r->label[k].pauli[1][0] - yplus[k]) <= 1e-15, "spec Y+ k=%d = %.17g", k, r->label[k].pauli[1][0]); + CHECK(fabs(r->label[k].clock_probability - 0.25) <= 4e-16, "spec p(k)"); + } + CHECK(r->povm_residual <= 1e-15 && r->constraint_residual <= 1e-15, "spec residuals"); + /* eigenstate control (spec T4): psi0 = |0> is stationary, P(Z+) = 1, P(X+) = P(Y+) = 1/2 */ + c.psi0[1].re = R(0, 1); OK(finalize(&c)); OK(at0_engine_run(&c, r)); + for (int k = 0; k < 4; k++) { + CHECK(fabs(r->label[k].pauli[2][0] - 1.0) <= 1e-15 && fabs(r->label[k].pauli[0][0] - .5) <= 1e-15 && + fabs(r->label[k].pauli[1][0] - .5) <= 1e-15, "eigenstate control k=%d", k); + } + return 0; +} + +/* varying N, phase offset (reference label), omega (|h|) and tilt, against the test-side Schrodinger reference */ +static int test_schrodinger_general(void) +{ + static at0_engine_result res; at0_engine_result *r = &res; memset(r, 0, sizeof *r); + struct { int n, m, ref; at0_rat tau, w, h0, hx, hy, hz, e0, step; at0_crat p0, p1; } tc[] = { + /* N=8 tilted field, h0=1/4, |h|=1/2, reference label 3 (phase offset), tau=1/4 */ + { 8, 8, 3, {1,4}, {1,1}, {1,4}, {3,10}, {0,1}, {2,5}, {-3,4}, {1,2}, {{1,1},{0,1}}, {{1,3},{-2,5}} }, + /* N=4 omega: |h|=1 (hz=1), energies -1,0,1,2 step 1, tau=1/8, M=8, w=1/2 */ + { 4, 8, 5, {1,8}, {1,2}, {0,1}, {0,1}, {0,1}, {1,1}, {-1,1}, {1,1}, {{2,1},{1,1}}, {{-1,1},{1,2}} }, + /* N=3 with hy, |h| = 5/13 from (3/13, 4/13, 0): energies -5/13, 0, 5/13 ; gaps 5/13 and 10/13 need tau M = 13/5: tau = 13/30, M = 6, w = 1/2 */ + { 3, 6, 0, {13,30}, {1,2}, {0,1}, {3,13}, {4,13}, {0,1}, {-5,13}, {5,13}, {{1,1},{0,1}}, {{0,1},{1,1}} }, + /* N=5 with M=7 labels, w = 5/7: not a POVM for these gaps, but conditional states are still Schrodinger */ + { 5, 7, 2, {1,7}, {5,7}, {1,2}, {0,1}, {0,1}, {1,2}, {-1,1}, {1,2}, {{1,1},{1,1}}, {{1,1},{-1,1}} }, + }; + for (size_t i = 0; i < sizeof tc / sizeof tc[0]; i++) { + at0_case c; memset(&c, 0, sizeof c); + snprintf(c.name, sizeof c.name, "general-%zu", i); + c.clock_dim = tc[i].n; + for (int j = 0; j < tc[i].n; j++) { at0_rat e; OK(at0_rat_mul(tc[i].step, R(j, 1), &e)); OK(at0_rat_add(tc[i].e0, e, &c.clock_energies[j])); } + c.h0 = tc[i].h0; c.hx = tc[i].hx; c.hy = tc[i].hy; c.hz = tc[i].hz; + c.psi0[0] = tc[i].p0; c.psi0[1] = tc[i].p1; + c.povm_tau_turns = tc[i].tau; c.povm_weight = tc[i].w; c.label_count = tc[i].m; + for (int k = 0; k < tc[i].m; k++) snprintf(c.labels[k], sizeof c.labels[k], "lab%d", k); + strcpy(c.reference_clock_label, c.labels[tc[i].ref]); + c.expected_outcome = AT0_EXPECT_PASS; c.min_bound_kind = AT0_BOUND_ESTIMATED; + c.tol_constraint_residual = S(1, 12); c.tol_povm_residual = S(1, 12); c.tol_probability = S(1, 12); + c.tol_zero_probability = S(1, 9); c.tol_schrodinger = S(1, 12); + OK(finalize(&c)); + OK(at0_engine_run(&c, r)); + CHECK(r->kernel_dim == 2, "case %zu kernel dim %d", i, r->kernel_dim); + CHECK(r->constraint_residual <= scaled_to_double(r->constraint_residual_bound), "case %zu residual %.3g", i, r->constraint_residual); + double tau = at0_rat_to_double(c.povm_tau_turns); + for (int k = 0; k < c.label_count; k++) { + CHECK(r->label[k].status == AT0_LABEL_DEFINED, "case %zu label %d status", i, k); + double ref[3][2]; + schrodinger_probs(&c, 2 * 3.141592653589793238462643383279 * (k - tc[i].ref) * tau, ref); + for (int a = 0; a < 3; a++) for (int s = 0; s < 2; s++) { + double dev = fabs(r->label[k].pauli[a][s] - ref[a][s]); + CHECK(dev <= 2e-15, "case %zu k=%d axis=%d sign=%d engine %.17g ref %.17g", i, k, a, s, r->label[k].pauli[a][s], ref[a][s]); + CHECK(dev <= scaled_to_double(r->label[k].pauli_bound[a][s]), "case %zu deviation above stated bound", i); + } + double expect_p = at0_rat_to_double(c.povm_weight) / c.clock_dim; + CHECK(fabs(r->label[k].clock_probability - expect_p) <= 4e-16, "case %zu p(k) %.17g", i, r->label[k].clock_probability); + } + if (i == 3) CHECK(r->povm_residual > 0.1, "M=7 labels on N=5 must not resolve the identity"); + else CHECK(r->povm_residual <= scaled_to_double(r->povm_residual_bound), "case %zu povm residual %.3g", i, r->povm_residual); + } + return 0; +} + +static int test_global_phase_invariance(void) +{ + static at0_engine_result ra, rb; at0_engine_result *a = &ra, *b = &rb; memset(a, 0, sizeof *a); memset(b, 0, sizeof *b); + at0_case base = kat; base.psi0[0].re = R(2, 1); base.psi0[1].re = R(1, 1); base.psi0[1].im = R(-1, 2); + base.hx = R(3, 10); base.hz = R(2, 5); base.h0 = R(1, 4); + for (int j = 0; j < 4; j++) base.clock_energies[j] = R(-3 + 2 * j, 4); /* -3/4,-1/4,1/4,3/4 : covers +-1/2 around 1/4 */ + OK(finalize(&base)); OK(at0_engine_run(&base, a)); + CHECK(a->kernel_dim == 2, "kernel"); + at0_crat phases[2] = { {{3,5},{4,5}}, {{0,1},{1,1}} }; /* (3+4i)/5 and i, both unit modulus */ + for (int p = 0; p < 2; p++) { + at0_case c = base; + for (int s = 0; s < 2; s++) { + at0_rat re, im, t1, t2; + OK(at0_rat_mul(phases[p].re, base.psi0[s].re, &t1)); OK(at0_rat_mul(phases[p].im, base.psi0[s].im, &t2)); OK(at0_rat_sub(t1, t2, &re)); + OK(at0_rat_mul(phases[p].re, base.psi0[s].im, &t1)); OK(at0_rat_mul(phases[p].im, base.psi0[s].re, &t2)); OK(at0_rat_add(t1, t2, &im)); + c.psi0[s].re = re; c.psi0[s].im = im; + } + OK(finalize(&c)); OK(at0_engine_run(&c, b)); + CHECK(strcmp(c.case_id, base.case_id) != 0, "phase-multiplied case must be a different question"); + for (int k = 0; k < 4; k++) { + CHECK(fabs(a->label[k].clock_probability - b->label[k].clock_probability) <= 4e-16, "p(k) changed under global phase"); + for (int ax = 0; ax < 3; ax++) for (int sg = 0; sg < 2; sg++) + CHECK(fabs(a->label[k].pauli[ax][sg] - b->label[k].pauli[ax][sg]) <= 8e-16, "pauli changed under global phase %d", p); + } + } + return 0; +} + +static int expect_refusal(const char *name, const char *from, const char *to, at0_status want) +{ + static char text[8192]; at0_case c; + memcpy(text, kat_bytes, kat_len); text[kat_len] = 0; + char *pos = strstr(text, from); + CHECK(pos != NULL, "%s: pattern not found", name); + static char out[8192]; + size_t head = (size_t)(pos - text); + memcpy(out, text, head); out[head] = 0; + strcat(out, to); strcat(out, pos + strlen(from)); + at0_status st = at0_case_parse((const uint8_t *)out, strlen(out), &c); + CHECK(st == want, "%s: got %s, want %s", name, at0_status_name(st), at0_status_name(want)); + return 0; +} + +static int test_invalid_input_refusal(void) +{ + int f = 0; + f |= expect_refusal("noncanonical rational", "-3/2,-1/2", "-6/4,-1/2", AT0_CASE_NONCANONICAL); + f |= expect_refusal("header version", "OMEGA-AT0-CASE v1", "OMEGA-AT0-CASE v2", AT0_CASE_UNSUPPORTED_VERSION); + f |= expect_refusal("domain", "domain omega.at0.case.v1", "domain omega.at0.case.v2", AT0_CASE_UNSUPPORTED_VERSION); + f |= expect_refusal("dimension too small", "clock_dim 4\nclock_energies -3/2,-1/2,1/2,3/2", "clock_dim 1\nclock_energies -3/2", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("energies not increasing", "-3/2,-1/2,1/2,3/2", "-3/2,1/2,-1/2,3/2", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("irrational spectrum", "0/1,0/1,0/1,1/2", "0/1,1/1,0/1,1/1", AT0_CASE_IRRATIONAL_SPECTRUM); + f |= expect_refusal("case_id mismatch", "case_id 3cf4", "case_id 4cf4", AT0_CASE_ID_MISMATCH); + f |= expect_refusal("acceptance_id mismatch", "acceptance_id a13f", "acceptance_id b13f", AT0_CASE_ID_MISMATCH); + f |= expect_refusal("zero tau", "povm_tau_turns 1/4", "povm_tau_turns 0/1", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("negative weight", "povm_weight 1/1", "povm_weight -1/1", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("unknown reference label", "reference_clock_label t0", "reference_clock_label t9", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("duplicate label", "clock_label 3 t3", "clock_label 3 t2", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("zero system state", "(1/1;0/1),(1/1;0/1)", "(0/1;0/1),(0/1;0/1)", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("wrong fixed value", "interaction NONE", "interaction WEAK", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("float text", "tol_probability 1@12", "tol_probability 1e-12", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("noncanonical scaled", "tol_probability 1@12", "tol_probability 10@13", AT0_CASE_NONCANONICAL); + f |= expect_refusal("double space", "clock_dim 4", "clock_dim 4", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("crlf", "clock_dim 4\n", "clock_dim 4\r\n", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("missing final lf", "end\n", "end", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("unknown key", "interaction NONE", "interactions NONE", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("bad label chars", "clock_label 1 t1", "clock_label 1 T1", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("trailing lines", "end\n", "end\nextra\n", AT0_CASE_PARSE_ERROR); + f |= expect_refusal("bad failure code with FAIL", "expected_outcome PASS\nexpected_failure_codes none", "expected_outcome FAIL\nexpected_failure_codes NOT_A_CODE", AT0_CASE_ID_MISMATCH); + /* rule 6 with correct identities: FAIL with "none", unsorted and duplicate code lists */ + at0_case c = kat; c.expected_outcome = AT0_EXPECT_FAIL; c.expected_failure_count = 0; + at0_status st = finalize(&c); + CHECK(st == AT0_CASE_INVALID_PARAMETER, "FAIL with none: %s", at0_status_name(st)); + c = kat; c.expected_outcome = AT0_EXPECT_FAIL; c.expected_failure_count = 2; c.expected_failure_idx[0] = 4; c.expected_failure_idx[1] = 2; + st = finalize(&c); CHECK(st == AT0_CASE_INVALID_PARAMETER, "unsorted codes: %s", at0_status_name(st)); + c = kat; c.expected_outcome = AT0_EXPECT_FAIL; c.expected_failure_count = 2; c.expected_failure_idx[0] = 4; c.expected_failure_idx[1] = 4; + st = finalize(&c); CHECK(st == AT0_CASE_INVALID_PARAMETER, "duplicate codes: %s", at0_status_name(st)); + c = kat; c.expected_outcome = AT0_EXPECT_FAIL; c.expected_failure_count = 2; c.expected_failure_idx[0] = 4; c.expected_failure_idx[1] = 7; + st = finalize(&c); CHECK(st == AT0_OK, "sorted codes should pass: %s", at0_status_name(st)); + /* API argument checking */ + at0_state s; double complex z; + OK(at0_state_init(&s, 4)); + CHECK(at0_state_get(&s, 4, 0, &z) == AT0_ERR_ARGUMENT, "clock index out of range"); + CHECK(at0_state_get(&s, 0, 2, &z) == AT0_ERR_ARGUMENT, "system index out of range"); + CHECK(at0_state_init(&s, 65) == AT0_ERR_ARGUMENT, "dimension above limit"); + CHECK(at0_state_init(NULL, 4) == AT0_ERR_ARGUMENT, "null state"); + CHECK(at0_case_parse(NULL, 0, &c) == AT0_ERR_ARGUMENT, "null bytes"); + CHECK(at0_engine_run(&kat, NULL) == AT0_ERR_ARGUMENT, "null result"); + at0_qubit_op op; CHECK(at0_pauli_matrix((at0_axis)3, &op) == AT0_ERR_ARGUMENT, "bad axis"); + return f; +} + +static int test_repeatability_and_order(void) +{ + static char t1[1 << 16], t2[1 << 16]; + static at0_engine_result ra, rb; at0_engine_result *a = &ra, *b = &rb; memset(a, 0, sizeof *a); memset(b, 0, sizeof *b); + at0_case c = kat; c.hx = R(3, 10); c.hz = R(2, 5); c.h0 = R(1, 4); + for (int j = 0; j < 4; j++) c.clock_energies[j] = R(-3 + 2 * j, 4); + strcpy(c.reference_clock_label, "t2"); + OK(finalize(&c)); + OK(at0_engine_run(&c, a)); long n1 = at0_engine_emit(&c, a, t1, sizeof t1); + OK(at0_engine_run(&c, b)); long n2 = at0_engine_emit(&c, b, t2, sizeof t2); + CHECK(n1 > 0 && n1 == n2 && memcmp(t1, t2, (size_t)n1) == 0, "two runs differ"); + OK(at0_engine_run_reversed(&c, b)); n2 = at0_engine_emit(&c, b, t2, sizeof t2); + CHECK(n1 == n2 && memcmp(t1, t2, (size_t)n1) == 0, "reversed label order changed the values block"); + CHECK(strstr(t1, "OMEGA-AT0-ENGINE v1\ndomain omega.at0.engine.v1\n") == t1, "header"); + CHECK(strstr(t1, "\nthreads 1\n") && strstr(t1, "\nbound_kind ESTIMATED\n"), "numerics block"); + /* f64 token rules */ + char tok[32]; + at0_f64_format(-0.0, tok, sizeof tok); CHECK(strcmp(tok, "f64:0000000000000000") == 0, "-0 folding: %s", tok); + at0_f64_format(1.0, tok, sizeof tok); CHECK(strcmp(tok, "f64:3ff0000000000000") == 0, "1.0: %s", tok); + at0_f64_format(0.0 / 0.0, tok, sizeof tok); CHECK(strcmp(tok, "nonfinite") == 0, "nan: %s", tok); + /* trivial physical state: values undefined, labels UNDEFINED, kernel 0 */ + at0_case u = kat; for (int j = 0; j < 4; j++) u.clock_energies[j] = R(j + 1, 1); + OK(finalize(&u)); OK(at0_engine_run(&u, a)); n1 = at0_engine_emit(&u, a, t1, sizeof t1); + CHECK(n1 > 0 && strstr(t1, "physical_state_kernel_dim 0\nconstraint_residual undefined 0@0\n"), "trivial kernel output"); + CHECK(strstr(t1, "label 0 t0 UNDEFINED\n") && strstr(t1, "pauli 3 Z MINUS undefined 0@0\n"), "trivial labels"); + return 0; +} + +static int test_review_findings(void); +int main(int argc, char **argv) +{ + if (argc != 2) { fprintf(stderr, "usage: at0-tests \n"); return 2; } + cases_dir = argv[1]; + if (!load_file("kat-ideal-qubit-n4.case", kat_bytes, sizeof kat_bytes, &kat_len)) { fprintf(stderr, "cannot read KAT case\n"); return 2; } + at0_status st = at0_case_parse(kat_bytes, kat_len, &kat); + if (st != AT0_OK) { fprintf(stderr, "KAT case refused: %s\n", at0_status_name(st)); return 2; } + struct { const char *name; int (*fn)(void); } tests[] = { + { "kat_roundtrip", test_kat_roundtrip }, + { "exact_arithmetic", test_exact_arithmetic }, + { "state_normalization", test_state_normalization }, + { "constraint_satisfaction", test_constraint_satisfaction }, + { "povm_normalization", test_povm_normalization }, + { "conditional_density_matrices", test_conditional_density }, + { "pauli_probabilities", test_pauli_probabilities }, + { "schrodinger_general_n_phase_omega", test_schrodinger_general }, + { "global_phase_invariance", test_global_phase_invariance }, + { "invalid_input_refusal", test_invalid_input_refusal }, + { "repeatability_and_order", test_repeatability_and_order }, + { "review_findings_f1_f5", test_review_findings }, + }; + int total = (int)(sizeof tests / sizeof tests[0]), passed = 0; + for (int i = 0; i < total; i++) { + int before = failures; + int rc = tests[i].fn(); + int ok = rc == 0 && failures == before; + printf("%s %s\n", ok ? "PASS" : "FAIL", tests[i].name); + if (ok) passed++; + } + printf("at0-tests: %d/%d passed\n", passed, total); + return passed == total ? 0 : 1; +} + +/* regression tests for the independent review of PR omega#360 (findings F1..F5) */ +static int test_review_findings(void) +{ + static at0_engine_result res; at0_engine_result *r = &res; + /* F1: tiny |h| = 1/1025 is a valid rational spectrum */ + at0_case c = kat; c.hz = R(1, 1025); + at0_status st = finalize(&c); CHECK(st == AT0_OK, "F1 refused: %s", at0_status_name(st)); + /* F2: energies and h0 at the contract limit */ + c = kat; c.clock_energies[0] = R(-1048576, 1); c.h0 = R(1048576, 1); + OK(finalize(&c)); OK(at0_engine_run(&c, r)); CHECK(r->kernel_dim == 0, "F2 kernel %d", r->kernel_dim); + /* F3: large overlaps in the exact zero test */ + c = kat; c.clock_energies[0] = R(-1000, 1); c.clock_energies[3] = R(1000, 1); c.hx = R(600, 1); c.hz = R(800, 1); + c.psi0[0].re = R(1000, 1); + OK(finalize(&c)); OK(at0_engine_run(&c, r)); CHECK(r->kernel_dim == 2 && r->psi_nonzero, "F3 run"); + /* F4: 19-digit tokens never overflow and are refused as out of range */ + int f = 0; + f |= expect_refusal("F4 long denominator", "povm_weight 1/1", "povm_weight 1/9999999999999999999", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("F4 long scaled", "tol_probability 1@12", "tol_probability 9999999999999999999@0", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("scaled k above 40", "tol_probability 1@12", "tol_probability 1@41", AT0_CASE_INVALID_PARAMETER); + f |= expect_refusal("rational above limit", "povm_weight 1/1", "povm_weight 2000000/1", AT0_CASE_INVALID_PARAMETER); + /* F5: version check (rule 2) precedes the limit check (rule 3) */ + f |= expect_refusal("F5 version before limit", "OMEGA-AT0-CASE v1\n", "OMEGA-AT0-CASE v2\n", AT0_CASE_UNSUPPORTED_VERSION); + { + static char text[8192]; at0_case d; + memcpy(text, kat_bytes, kat_len); text[kat_len] = 0; + char *p = strstr(text, "OMEGA-AT0-CASE v1"); p[15] = '2'; + char *q = strstr(text, "povm_weight 1/1"); memcpy(q, "povm_weight 2/1", 15); /* same length, over no limit yet */ + at0_status s2 = at0_case_parse((const uint8_t *)text, strlen(text), &d); + CHECK(s2 == AT0_CASE_UNSUPPORTED_VERSION, "F5: %s", at0_status_name(s2)); + } + f |= expect_refusal("F5 noncanonical is rule 1, before the limit", "povm_weight 1/1", "povm_weight 2000000/4000000", AT0_CASE_NONCANONICAL); + return f; +}