interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / research / atemporal / at0 / model / at0_exact.c

387 lines · 17142 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/* Exact arithmetic for AT-0: reduced rationals (64-bit fields, 128-bit
18 * intermediates, limits of AT0_CASE_V1 section 2), scaled decimals, canonical
19 * token parsing/printing, and an exact comparison of a binary64 value against
20 * scaled-decimal bounds using a small fixed-size unsigned bignum. */
21#include "at0_model.h"
22
23#include <ctype.h>
24#include <math.h>
25#include <string.h>
26
27static const char *const status_names[] = {
28 "OK", "CASE_PARSE_ERROR", "CASE_NONCANONICAL", "CASE_UNSUPPORTED_VERSION",
29 "CASE_INVALID_PARAMETER", "CASE_IRRATIONAL_SPECTRUM", "CASE_ID_MISMATCH",
30 "ERR_ARGUMENT", "ERR_OVERFLOW", "ERR_NONFINITE", "ERR_IO", "ERR_INTERNAL"
31};
32
33const char *at0_status_name(at0_status s)
34{
35 if ((int)s < 0 || (size_t)s >= sizeof status_names / sizeof status_names[0]) return "ERR_UNKNOWN";
36 return status_names[s];
37}
38
39int at0_status_is_refusal(at0_status s)
40{
41 return s >= AT0_CASE_PARSE_ERROR && s <= AT0_CASE_ID_MISMATCH;
42}
43
44/* ---- 128-bit helpers ------------------------------------------------------ */
45static at0_i128 i128_abs(at0_i128 x) { return x < 0 ? -x : x; }
46
47static at0_i128 i128_gcd(at0_i128 a, at0_i128 b)
48{
49 a = i128_abs(a); b = i128_abs(b);
50 while (b != 0) { at0_i128 t = a % b; a = b; b = t; }
51 return a;
52}
53
54/* reduce n/d (d != 0) and check the contract limits */
55static at0_status rat_from_i128(at0_i128 n, at0_i128 d, at0_rat *out)
56{
57 /* reduce; the only limit here is representability (|n|, d < 2^62) so that every further
58 * product of two rationals fits in 128 bits. The contract limit 2^20 applies to tokens
59 * written in a case file and is enforced by validity rule 3 (at0_rat_in_limits). */
60 if (!out || d == 0) return AT0_ERR_ARGUMENT;
61 if (d < 0) { n = -n; d = -d; }
62 at0_i128 g = i128_gcd(n, d);
63 if (g > 1) { n /= g; d /= g; }
64 if (i128_abs(n) > AT0_RAT_REPR_LIMIT || d > AT0_RAT_REPR_LIMIT) return AT0_ERR_OVERFLOW;
65 out->n = (int64_t)n; out->d = (int64_t)d;
66 return AT0_OK;
67}
68
69at0_status at0_rat_make(int64_t n, int64_t d, at0_rat *out) { return rat_from_i128(n, d, out); }
70int 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; }
71int at0_scaled_in_limits(at0_scaled s) { return s.k >= 0 && s.k <= AT0_SCALED_K_MAX && s.n < (uint64_t)AT0_INT_SATURATED; }
72
73at0_status at0_rat_add(at0_rat a, at0_rat b, at0_rat *out)
74{
75 return rat_from_i128((at0_i128)a.n * b.d + (at0_i128)b.n * a.d, (at0_i128)a.d * b.d, out);
76}
77at0_status at0_rat_sub(at0_rat a, at0_rat b, at0_rat *out)
78{
79 return rat_from_i128((at0_i128)a.n * b.d - (at0_i128)b.n * a.d, (at0_i128)a.d * b.d, out);
80}
81at0_status at0_rat_mul(at0_rat a, at0_rat b, at0_rat *out)
82{
83 return rat_from_i128((at0_i128)a.n * b.n, (at0_i128)a.d * b.d, out);
84}
85int at0_rat_cmp(at0_rat a, at0_rat b)
86{
87 at0_i128 l = (at0_i128)a.n * b.d, r = (at0_i128)b.n * a.d;
88 return l < r ? -1 : (l > r ? 1 : 0);
89}
90int at0_rat_is_zero(at0_rat a) { return a.n == 0; }
91double at0_rat_to_double(at0_rat a) { return (double)a.n / (double)a.d; }
92
93/* integer square root of a nonnegative 128-bit value, exact test */
94static int i128_is_square(at0_i128 x, at0_i128 *root)
95{
96 if (x < 0) return 0;
97 if (x == 0) { *root = 0; return 1; }
98 at0_i128 r = (at0_i128)sqrtl((long double)x);
99 if (r < 0) r = 0;
100 while (r > 0 && r * r > x) r--;
101 while ((r + 1) * (r + 1) <= x) r++;
102 *root = r;
103 return r * r == x;
104}
105
106at0_status at0_rat_sqrt_exact(at0_rat a, at0_rat *root, int *is_square)
107{
108 if (!root || !is_square) return AT0_ERR_ARGUMENT;
109 *is_square = 0;
110 if (a.n < 0) return AT0_OK;
111 at0_i128 rn, rd;
112 if (!i128_is_square((at0_i128)a.n, &rn)) return AT0_OK;
113 if (!i128_is_square((at0_i128)a.d, &rd)) return AT0_OK;
114 at0_status st = rat_from_i128(rn, rd, root);
115 if (st != AT0_OK) return st;
116 *is_square = 1;
117 return AT0_OK;
118}
119
120at0_status at0_rat_reduce_turn(at0_rat x, at0_rat *out)
121{
122 /* x - round(x) with round half up, result in [-1/2, 1/2) */
123 if (!out) return AT0_ERR_ARGUMENT;
124 at0_i128 n = x.n, d = x.d;
125 at0_i128 twice = 2 * n + d; /* 2x + 1 numerator over 2d */
126 at0_i128 q = twice / (2 * d); /* floor for nonnegative */
127 if (twice < 0 && twice % (2 * d) != 0) q -= 1;
128 return rat_from_i128(n - q * d, d, out);
129}
130
131/* ---- canonical integer token -------------------------------------------- */
132/* Returns 1 for a canonical integer, 0 for a shape error (rule 1: empty, non-digit, "+",
133 * too long) and -1 for a well-formed but noncanonical one (rule 2: leading zeros, "-0").
134 * A canonical digit string longer than 18 digits cannot fit the contract limits; it is
135 * parsed as the saturation value AT0_INT_SATURATED (above every limit, not divisible by 10)
136 * so that rule 3 refuses it as CASE_INVALID_PARAMETER after the version check, and no
137 * int64 arithmetic can overflow. */
138static int parse_canonical_int(const char *s, size_t len, int64_t *out)
139{
140 if (len == 0 || len > 64) return 0;
141 size_t i = 0; int neg = 0;
142 if (s[0] == '-') { neg = 1; i = 1; if (len == 1) return 0; }
143 for (size_t j = i; j < len; j++) if (!isdigit((unsigned char)s[j])) return 0;
144 int canonical = 1;
145 if (s[i] == '0' && len - i > 1) canonical = 0; /* leading zero */
146 if (neg && s[i] == '0') canonical = 0; /* "-0" (and "-0..." ) */
147 int64_t v = 0;
148 size_t digits = len - i;
149 for (; i < len; i++) if (digits <= 18) v = v * 10 + (s[i] - '0');
150 if (digits > 18) v = AT0_INT_SATURATED;
151 *out = neg ? -v : v;
152 return canonical ? 1 : -1;
153}
154
155at0_status at0_rat_parse(const char *tok, at0_rat *out)
156{
157 if (!tok || !out) return AT0_ERR_ARGUMENT;
158 const char *slash = strchr(tok, '/');
159 if (!slash) return AT0_CASE_PARSE_ERROR;
160 int64_t n, d;
161 int cn = parse_canonical_int(tok, (size_t)(slash - tok), &n);
162 int cd = parse_canonical_int(slash + 1, strlen(slash + 1), &d);
163 if (cn == 0 || cd == 0) return AT0_CASE_PARSE_ERROR; /* shape first (rule 1) */
164 if (cn < 0 || cd < 0) return AT0_CASE_NONCANONICAL; /* then canonicality (rule 2) */
165 if (d < 1) return AT0_CASE_NONCANONICAL;
166 int saturated = n == AT0_INT_SATURATED || n == -AT0_INT_SATURATED || d == AT0_INT_SATURATED;
167 if (!saturated && i128_gcd(n, d) != 1) return AT0_CASE_NONCANONICAL; /* covers 0/5 and 2/4; limits are rule 3 */
168 out->n = n; out->d = d;
169 return AT0_OK;
170}
171
172at0_status at0_crat_parse(const char *tok, at0_crat *out)
173{
174 if (!tok || !out) return AT0_ERR_ARGUMENT;
175 size_t len = strlen(tok);
176 if (len < 7 || tok[0] != '(' || tok[len - 1] != ')') return AT0_CASE_PARSE_ERROR;
177 const char *semi = strchr(tok, ';');
178 if (!semi) return AT0_CASE_PARSE_ERROR;
179 char a[64], b[64];
180 size_t la = (size_t)(semi - tok - 1), lb = len - 2 - la - 1;
181 if (la == 0 || lb == 0 || la >= sizeof a || lb >= sizeof b) return AT0_CASE_PARSE_ERROR;
182 memcpy(a, tok + 1, la); a[la] = 0;
183 memcpy(b, semi + 1, lb); b[lb] = 0;
184 at0_status sa = at0_rat_parse(a, &out->re), sb = at0_rat_parse(b, &out->im);
185 if (sa == AT0_CASE_PARSE_ERROR || sb == AT0_CASE_PARSE_ERROR) return AT0_CASE_PARSE_ERROR;
186 if (sa != AT0_OK) return sa;
187 return sb;
188}
189
190at0_status at0_scaled_parse(const char *tok, at0_scaled *out)
191{
192 if (!tok || !out) return AT0_ERR_ARGUMENT;
193 const char *at = strchr(tok, '@');
194 if (!at) return AT0_CASE_PARSE_ERROR;
195 int64_t n, k;
196 int cn = parse_canonical_int(tok, (size_t)(at - tok), &n);
197 int ck = parse_canonical_int(at + 1, strlen(at + 1), &k);
198 if (cn == 0 || ck == 0) return AT0_CASE_PARSE_ERROR;
199 if (cn < 0 || ck < 0) return AT0_CASE_NONCANONICAL;
200 if (n < 0 || k < 0) return AT0_CASE_NONCANONICAL;
201 if (k > 1000) k = 1000; /* above every limit; rule 3 refuses it */
202 if (n == 0 && k != 0) return AT0_CASE_NONCANONICAL;
203 if (n != 0 && k != 0 && n % 10 == 0) return AT0_CASE_NONCANONICAL;
204 out->n = (uint64_t)n; out->k = (int)k;
205 return AT0_OK;
206}
207
208int at0_rat_format(at0_rat a, char *buf, size_t cap)
209{
210 return snprintf(buf, cap, "%lld/%lld", (long long)a.n, (long long)a.d);
211}
212int at0_crat_format(at0_crat a, char *buf, size_t cap)
213{
214 return snprintf(buf, cap, "(%lld/%lld;%lld/%lld)", (long long)a.re.n, (long long)a.re.d,
215 (long long)a.im.n, (long long)a.im.d);
216}
217int at0_scaled_format(at0_scaled s, char *buf, size_t cap)
218{
219 return snprintf(buf, cap, "%llu@%d", (unsigned long long)s.n, s.k);
220}
221
222/* ---- fixed-size unsigned bignum for exact comparisons -------------------- */
223/* 2^1074 (smallest subnormal scale) * 2^53 * 10^40 * 10^40 < 2^1400 ; 48 limbs = 1536 bits */
224#define BN_LIMBS 48
225typedef struct { uint32_t l[BN_LIMBS]; } bn_t;
226
227static void bn_zero(bn_t *x) { memset(x, 0, sizeof *x); }
228static 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); }
229static int bn_mul_small(bn_t *x, uint32_t m)
230{
231 uint64_t carry = 0;
232 for (int i = 0; i < BN_LIMBS; i++) {
233 uint64_t t = (uint64_t)x->l[i] * m + carry;
234 x->l[i] = (uint32_t)t; carry = t >> 32;
235 }
236 return carry == 0;
237}
238static int bn_shl(bn_t *x, int bits)
239{
240 while (bits >= 32) {
241 if (x->l[BN_LIMBS - 1] != 0) return 0;
242 for (int i = BN_LIMBS - 1; i > 0; i--) x->l[i] = x->l[i - 1];
243 x->l[0] = 0; bits -= 32;
244 }
245 if (bits == 0) return 1;
246 if (x->l[BN_LIMBS - 1] >> (32 - bits)) return 0;
247 for (int i = BN_LIMBS - 1; i > 0; i--) x->l[i] = (x->l[i] << bits) | (x->l[i - 1] >> (32 - bits));
248 x->l[0] <<= bits;
249 return 1;
250}
251static 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; }
252static int bn_add(bn_t *x, const bn_t *y)
253{
254 uint64_t carry = 0;
255 for (int i = 0; i < BN_LIMBS; i++) {
256 uint64_t t = (uint64_t)x->l[i] + y->l[i] + carry;
257 x->l[i] = (uint32_t)t; carry = t >> 32;
258 }
259 return carry == 0;
260}
261static int bn_cmp(const bn_t *a, const bn_t *b)
262{
263 for (int i = BN_LIMBS - 1; i >= 0; i--) {
264 if (a->l[i] != b->l[i]) return a->l[i] < b->l[i] ? -1 : 1;
265 }
266 return 0;
267}
268
269at0_status at0_exact_prob_status(double p, at0_scaled b, at0_scaled tol, int *le, int *gt)
270{
271 if (!le || !gt) return AT0_ERR_ARGUMENT;
272 if (!isfinite(p) || p < 0) return AT0_ERR_ARGUMENT;
273 if (b.k > AT0_SCALED_K_MAX || tol.k > AT0_SCALED_K_MAX || b.k < 0 || tol.k < 0) return AT0_ERR_ARGUMENT;
274 /* p = m * 2^e exactly, m integer < 2^53 */
275 int e = 0; uint64_t m = 0;
276 if (p != 0.0) {
277 int ex; double fr = frexp(p, &ex); /* p = fr * 2^ex, fr in [0.5,1) */
278 m = (uint64_t)ldexp(fr, 53); /* exact integer */
279 e = ex - 53;
280 }
281 int s = e < 0 ? -e : 0; /* scale by 2^s so p's exponent is >= 0 */
282 int K = b.k > tol.k ? b.k : tol.k;
283 bn_t P, B, T;
284 bn_from_u64(&P, m);
285 if (!bn_shl(&P, s + e) || !bn_pow10_mul(&P, K)) return AT0_ERR_OVERFLOW;
286 bn_from_u64(&B, b.n);
287 if (!bn_shl(&B, s) || !bn_pow10_mul(&B, K - b.k)) return AT0_ERR_OVERFLOW;
288 bn_from_u64(&T, tol.n);
289 if (!bn_shl(&T, s) || !bn_pow10_mul(&T, K - tol.k)) return AT0_ERR_OVERFLOW;
290 bn_t PB = P; if (!bn_add(&PB, &B)) return AT0_ERR_OVERFLOW; /* p + b */
291 bn_t TB = T; if (!bn_add(&TB, &B)) return AT0_ERR_OVERFLOW; /* tol + b */
292 *le = bn_cmp(&PB, &T) <= 0; /* p + b <= tol */
293 *gt = bn_cmp(&P, &TB) > 0; /* p - b > tol <=> p > tol + b */
294 return AT0_OK;
295}
296
297at0_status at0_scaled_from_double_ceil(double x, at0_scaled *out)
298{
299 if (!out || !isfinite(x) || x < 0) return AT0_ERR_ARGUMENT;
300 if (x == 0.0) { out->n = 0; out->k = 0; return AT0_OK; }
301 /* pick k so that x * 10^k is in [10^6, 10^7): seven significant digits, round up, then add one unit */
302 int k = 0; long double y = (long double)x;
303 while (y < 1e6L && k < AT0_SCALED_K_MAX) { y *= 10.0L; k++; }
304 while (y >= 1e7L && k > 0) { y /= 10.0L; k--; }
305 if (y >= 1.8e19L) return AT0_ERR_OVERFLOW;
306 uint64_t n = (uint64_t)ceill(y) + 1; /* +1 absorbs the decimal conversion itself */
307 while (k > 0 && n % 10 == 0) { n /= 10; k--; } /* canonical form */
308 out->n = n; out->k = k;
309 return AT0_OK;
310}
311
312/* ---- overflow-free exact tests on in-limit case data ------------------------ */
313/* Every token of a valid case satisfies rule 3 (|n|, d <= 2^20), but values derived from
314 * several tokens with different denominators (|h|, |h| + hz, eigenvector overlaps) have
315 * reduced denominators far beyond 2^62, so they must never pass through at0_rat. The
316 * functions below keep every intermediate as an unreduced 128-bit integer whose bound is
317 * stated at the use site, and verify each product and sum with checked arithmetic:
318 * an exceeded bound is reported as AT0_ERR_OVERFLOW, never wrapped. */
319
320int at0_i128_mul(at0_i128 a, at0_i128 b, at0_i128 *out) { return !__builtin_mul_overflow(a, b, out); }
321int at0_i128_add(at0_i128 a, at0_i128 b, at0_i128 *out) { return !__builtin_add_overflow(a, b, out); }
322
323static int rat_in_token_limits(at0_rat a) { return at0_rat_in_limits(a); }
324
325at0_status at0_rat_norm_exact(at0_rat hx, at0_rat hy, at0_rat hz, at0_rat *norm, int *is_square)
326{
327 /* |h|^2 = (nx^2 (dy dz)^2 + ny^2 (dx dz)^2 + nz^2 (dx dy)^2) / (dx dy dz)^2.
328 * With tokens <= 2^20: each term <= 2^40 * 2^80 = 2^120, the sum <= 3 * 2^120 < 2^122, D = dx dy dz <= 2^60.
329 * The denominator is a perfect square, so |h| is rational iff the numerator is a perfect
330 * square S^2, and then |h| = S / D with S < 2^61 (representable). */
331 if (!norm || !is_square) return AT0_ERR_ARGUMENT;
332 if (!rat_in_token_limits(hx) || !rat_in_token_limits(hy) || !rat_in_token_limits(hz)) return AT0_ERR_OVERFLOW;
333 *is_square = 0;
334 at0_i128 dx = hx.d, dy = hy.d, dz = hz.d, D, t, term, num = 0;
335 if (!at0_i128_mul(dx, dy, &t) || !at0_i128_mul(t, dz, &D)) return AT0_ERR_OVERFLOW;
336 const at0_i128 n[3] = { hx.n, hy.n, hz.n }, other[3] = { dy * dz, dx * dz, dx * dy };
337 for (int i = 0; i < 3; i++) {
338 if (!at0_i128_mul(n[i], other[i], &t)) return AT0_ERR_OVERFLOW; /* n_i * (D / d_i) */
339 if (!at0_i128_mul(t, t, &term)) return AT0_ERR_OVERFLOW;
340 if (!at0_i128_add(num, term, &num)) return AT0_ERR_OVERFLOW;
341 }
342 at0_i128 S;
343 if (!i128_is_square(num, &S)) return AT0_OK;
344 at0_status st = rat_from_i128(S, D, norm);
345 if (st != AT0_OK) return st;
346 *is_square = 1;
347 return AT0_OK;
348}
349
350at0_status at0_exact_norm_plus_hz(at0_rat hx, at0_rat hy, at0_rat hz, at0_rat h_norm,
351 at0_i128 *A, at0_i128 *D)
352{
353 /* a = |h| + hz = (S + nz dx dy) / D with D = dx dy dz and |h| = S / D unreduced:
354 * S <= sqrt3 * 2^60 < 2^61 and |nz dx dy| <= 2^60, so |A| < 2^62. h_norm is the reduced S / D, hence
355 * h_norm.d divides D and S = h_norm.n * (D / h_norm.d). */
356 if (!A || !D) return AT0_ERR_ARGUMENT;
357 if (!rat_in_token_limits(hx) || !rat_in_token_limits(hy) || !rat_in_token_limits(hz)) return AT0_ERR_OVERFLOW;
358 at0_i128 dx = hx.d, dy = hy.d, dz = hz.d, t, d, S, z;
359 if (!at0_i128_mul(dx, dy, &t) || !at0_i128_mul(t, dz, &d)) return AT0_ERR_OVERFLOW;
360 if (h_norm.d < 1 || d % h_norm.d != 0) return AT0_ERR_INTERNAL;
361 if (!at0_i128_mul((at0_i128)h_norm.n, d / h_norm.d, &S)) return AT0_ERR_OVERFLOW;
362 if (!at0_i128_mul((at0_i128)hz.n, dx * dy, &z)) return AT0_ERR_OVERFLOW;
363 if (!at0_i128_add(S, z, A)) return AT0_ERR_OVERFLOW;
364 *D = d;
365 return AT0_OK;
366}
367
368at0_status at0_exact_sum_is_zero(int count, const at0_i128 *num, const at0_i128 *den, int *zero)
369{
370 /* sum_i num[i]/den[i] == 0 <=> sum_i num[i] * prod_{j != i} den[j] == 0.
371 * Terms with a zero numerator are dropped first so that the products only involve the
372 * denominators of the terms that can contribute. The caller states the bound. */
373 if (!num || !den || !zero || count < 0 || count > 4) return AT0_ERR_ARGUMENT;
374 at0_i128 n[4], d[4]; int m = 0;
375 for (int i = 0; i < count; i++) {
376 if (den[i] < 1) return AT0_ERR_ARGUMENT;
377 if (num[i] != 0) { n[m] = num[i]; d[m] = den[i]; m++; }
378 }
379 at0_i128 acc = 0;
380 for (int i = 0; i < m; i++) {
381 at0_i128 t = n[i];
382 for (int j = 0; j < m; j++) if (j != i && !at0_i128_mul(t, d[j], &t)) return AT0_ERR_OVERFLOW;
383 if (!at0_i128_add(acc, t, &acc)) return AT0_ERR_OVERFLOW;
384 }
385 *zero = acc == 0;
386 return AT0_OK;
387}