gdp-wired 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +14 -9
  2. package/dist/core/accel.d.ts +44 -0
  3. package/dist/core/accel.js +955 -0
  4. package/dist/core/bmc.d.ts +8 -0
  5. package/dist/core/bmc.js +263 -97
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +409 -174
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +86 -64
  10. package/dist/core/data.d.ts +9 -1
  11. package/dist/core/data.js +872 -168
  12. package/dist/core/discover.js +2 -3
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +21 -18
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +3 -2
  17. package/dist/core/extract-check.js +137 -50
  18. package/dist/core/extract-print.d.ts +1 -0
  19. package/dist/core/extract-print.js +26 -3
  20. package/dist/core/extract-read.d.ts +85 -4
  21. package/dist/core/extract-read.js +295 -34
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +608 -78
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.js +73 -27
  27. package/dist/core/infer.d.ts +1 -0
  28. package/dist/core/infer.js +364 -40
  29. package/dist/core/machine.d.ts +6 -0
  30. package/dist/core/machine.js +35 -3
  31. package/dist/core/nonterm.d.ts +9 -2
  32. package/dist/core/nonterm.js +173 -9
  33. package/dist/core/q.d.ts +1 -0
  34. package/dist/core/q.js +2 -2
  35. package/dist/core/relation.d.ts +1 -0
  36. package/dist/core/relation.js +95 -39
  37. package/dist/core/solver.d.ts +12 -0
  38. package/dist/core/solver.js +76 -30
  39. package/dist/core/transfer.js +23 -14
  40. package/dist/core/translate.d.ts +1 -1
  41. package/dist/core/translate.js +22 -49
  42. package/dist/core/xstate.d.ts +6 -1
  43. package/dist/core/xstate.js +336 -55
  44. package/dist/kernel/cdcl.d.ts +5 -0
  45. package/dist/kernel/cdcl.js +44 -8
  46. package/dist/kernel/prove.d.ts +6 -1
  47. package/dist/kernel/prove.js +101 -85
  48. package/dist/kernel/reader.d.ts +1 -0
  49. package/dist/kernel/reader.js +4 -3
  50. package/dist/kernel/simplex.d.ts +1 -1
  51. package/dist/kernel/simplex.js +13 -1
  52. package/package.json +3 -2
@@ -7,7 +7,36 @@
7
7
  // at the same value; a law about a map holds for every key x, and is proven at one arbitrary x (with the law assumed at
8
8
  // every other key the step reads).
9
9
  import { boundOf, crossFree, historyMachine, keyTerm, plainKey, scope } from "../kernel/kernel.js";
10
- import { add, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
+ import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
11
+ export const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
12
+ // Every object in a term, the term first.
13
+ export const walk = (t, f) => {
14
+ if (Array.isArray(t)) {
15
+ for (const x of t)
16
+ walk(x, f);
17
+ return;
18
+ }
19
+ if (!t || typeof t !== 'object')
20
+ return;
21
+ const o = t;
22
+ f(o);
23
+ for (const x of Object.values(o))
24
+ walk(x, f);
25
+ };
26
+ // Every object in a term once (arrays too), a part shared by several uses read at its first: a witness read at each of
27
+ // its uses in a goal is one object, and a walk of the goal written out would read it at each.
28
+ export const walkOnce = (t, f) => {
29
+ const seen = new Set();
30
+ const go = (x) => {
31
+ if (!x || typeof x !== 'object' || seen.has(x))
32
+ return;
33
+ seen.add(x);
34
+ f(x);
35
+ for (const y of Object.values(x))
36
+ go(y);
37
+ };
38
+ go(t);
39
+ };
11
40
  // A write at one key, for the parts that take no write at every key (the symbolic prover, the GPU synthesizers, the
12
41
  // hand-written shader, the first Lean export): they refuse one by name.
13
42
  export const pointWrite = (w, where) => { if ('each' in w)
@@ -227,7 +256,10 @@ const callOf = (fn) => {
227
256
  }
228
257
  return f;
229
258
  };
230
- // The n arguments a key pairs (left-nested, ((a, b), c)..., each pair (s)² + b with s = a + b), if it is their pairing.
259
+ // A key of several arguments: their pairing, left-nested, ((a, b), c)..., each pair (s)² + b with s = a + b.
260
+ export const pairE = (a, b) => { const s = plus(a, b); return plus(prod(s, s), b); };
261
+ export const argsKey = (args) => args.slice(1).reduce(pairE, args[0]);
262
+ // The n arguments a key pairs (argsKey's), if it is their pairing.
231
263
  const paired = new WeakMap();
232
264
  export function pairedArgs(key, n) {
233
265
  let byN = paired.get(key);
@@ -649,7 +681,7 @@ function symC(c, s, truth) {
649
681
  }
650
682
  }
651
683
  // PROVE_DEBUG=1 logs the case counts to stderr; read through globalThis so the module also loads where there is no process.
652
- const proveDebug = !!globalThis.process?.env?.PROVE_DEBUG;
684
+ const proveDebug = !!env.PROVE_DEBUG;
653
685
  const debug = (label, n) => { if (proveDebug)
654
686
  console.error(`[prove] ${label}: ${n} (${Math.round(performance.now())} ms)`); };
655
687
  // Drops the cases whose path is already impossible, so impossible branches don't multiply.
@@ -1,4 +1,4 @@
1
- import type { C, E } from './machine.js';
1
+ import { type C, type E } from './machine.js';
2
2
  import { type Loop, type Recur } from '../kernel/kernel.js';
3
3
  export type NeverEndsOptions = {
4
4
  ms?: number;
@@ -6,12 +6,14 @@ export type NeverEndsOptions = {
6
6
  maxTurns?: number;
7
7
  lassos?: boolean;
8
8
  counted?: number;
9
+ accel?: number;
10
+ extend?: number;
9
11
  };
10
12
  export type NeverEndsVerdict = {
11
13
  proven: boolean;
12
14
  checked: boolean;
13
15
  recur?: Recur;
14
- by?: 'lasso' | 'policy lasso' | 'recurrent set';
16
+ by?: 'lasso' | 'policy lasso' | 'recurrent set' | 'accelerated';
15
17
  why?: string;
16
18
  lasso?: {
17
19
  params: Record<string, number>;
@@ -26,9 +28,14 @@ export type NeverEndsVerdict = {
26
28
  ms: number;
27
29
  lassoTried: number;
28
30
  goalSize: number;
31
+ accel: number;
32
+ accelClosed: number;
29
33
  };
30
34
  };
35
+ export declare const isT: (c: C) => boolean;
36
+ export declare const isF: (c: C) => boolean;
31
37
  export declare const simpE: (e: E) => E;
32
38
  export declare const simpC: (c: C) => C;
33
39
  export declare function goalSize(x: unknown): number;
40
+ export declare const dagSize: (x: unknown) => number;
34
41
  export declare function findNeverEnds(l: Loop, opts?: NeverEndsOptions): NeverEndsVerdict;
@@ -1,13 +1,37 @@
1
- import { checkRecur, recurGoal, substC, trueC } from "../kernel/kernel.js";
2
- import { clock, counted, grow } from "../kernel/prove.js";
1
+ // Runs that never end, found: the search behind `proveNeverEnds`. Untrusted, like prove.ts: what it finds is a closed
2
+ // recurrent set with its successor given (kernel.ts's Recur), checked by kernel.ts's checkRecur and, exported, by
3
+ // NonTerm.lean's never_ends_of.
4
+ //
5
+ // - Runs. Random runs of the loop: params small or near the constants its conditions compare with, each turn's inputs
6
+ // small or a value the state holds. Each run keeps its turns' inputs, so any state it reached has a stem.
7
+ // - Lassos. A run back at a state it was in (the params and the state; the inputs are read afresh each turn): the set is
8
+ // the cycle's states, each turn's inputs given at its state by an if over the states (`lassoRecur`).
9
+ // - Policies. From a state a run reached, a run whose inputs are terms over the state and params: in each mode (the
10
+ // values of the state variables the loop compares with constants, its locations), the first allowed of a few
11
+ // assignments, each input a term from a pool (0, 1, ±1, the constants it is compared with, each state and param value,
12
+ // those ± 1); an assignment is added, drawn from the pools, where the run would stop. The policy is the set's witness.
13
+ // A policy run that comes back is a lasso; one that goes on is the set's sample.
14
+ // - The set. Per mode, atoms over the integer values (a pair x, x$n or x$neg is the integer x − x$n; a natural is
15
+ // itself): bounds of one value, of the sum and the difference of two, equalities, each true on the policy run. Those
16
+ // constant along it go in first; then each counterexample the prover's model gives (a state of the set whose
17
+ // witnessed turn fails or leaves the set) is excluded by one more atom false there, the steadiest and simplest first
18
+ // (its slack along the run never shrinking), until the closure goal is proven: kernel/prove.ts's grow, which tries
19
+ // kernel/cdcl.ts's CDCL on a linear goal first. Linear loops' geometric runs (a value doubling, two growing apart) are
20
+ // among these sets: their bounds and differences grow along the run.
21
+ // - Accelerated cycles, between the runs and the policies (core/accel.ts): a set from a cycle of the loop's relation,
22
+ // the cycle's n-fold run read in closed form (an atom's differences along it), and a stem from a reached state or a
23
+ // run with its loops accelerated, checked as the rest are.
24
+ import { n as K, same as eq, seeded, walkOnce, x as V } from "./machine.js";
25
+ import { checkRecur, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
26
+ import { clock, counted, grow, realModels } from "../kernel/prove.js";
3
27
  import { work } from "./solver.js";
4
- const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
28
+ import { accelerated, stemsTo } from "./accel.js";
29
+ import { findBoundedRun } from "./bmc.js";
5
30
  const T = trueC, F = { op: '<', a: K(0), b: K(0) };
6
- const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
7
- const isF = (c) => (c.op === '<' && c.a.op === 'const' && c.b.op === 'const' && c.a.value >= c.b.value) || (c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value > c.b.value);
31
+ export const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
32
+ export const isF = (c) => (c.op === '<' && c.a.op === 'const' && c.b.op === 'const' && c.a.value >= c.b.value) || (c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value > c.b.value);
8
33
  const and = (xs) => { const ys = xs.flatMap(x => (x.op === 'and' ? x.xs : [x])).filter(x => !isT(x)); return ys.some(isF) ? F : ys.length === 0 ? T : ys.length === 1 ? ys[0] : { op: 'and', xs: ys }; };
9
34
  const or = (xs) => { const ys = xs.flatMap(x => (x.op === 'or' ? x.xs : [x])).filter(x => !isF(x)); return ys.some(isT) ? T : ys.length === 0 ? F : ys.length === 1 ? ys[0] : { op: 'or', xs: ys }; };
10
- const eq = (a, b) => ({ op: '=', a, b });
11
35
  const plus = (a, b) => (a.op === 'const' && a.value === 0 ? b : b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? K(a.value + b.value) : { op: 'add', a, b });
12
36
  const minus = (a, b) => (b.op === 'const' && b.value === 0 ? a : a.op === 'const' && b.op === 'const' ? K(Math.max(0, a.value - b.value)) : { op: 'sub', a, b });
13
37
  const times = (k, a) => (k === 0 ? K(0) : k === 1 ? a : a.op === 'const' ? K(k * a.value) : { op: 'mul', k, a });
@@ -77,6 +101,12 @@ export function goalSize(x) {
77
101
  return n;
78
102
  }
79
103
  const GOAL_MAX = 300_000;
104
+ // An accelerated set's goal: the witness reads the location (and, where the cycle comes back to one, an atom that tells
105
+ // the parts there apart), so its ifs multiply the body's less; and the kernel reads a term shared in the goal once per
106
+ // case, so its size here is its distinct terms (TermComp's s1: 23 million nodes written out, 707,064 distinct, proven in
107
+ // 11 s; tqli: 720,729 written out, proven in 22 s).
108
+ export const dagSize = (x) => { let n = 0; walkOnce(x, () => { n++; }); return n; };
109
+ const ACCEL_DAG_MAX = 1_500_000;
80
110
  // --- running the loop ---------------------------------------------------------------------------------------------------
81
111
  class Overflow extends Error {
82
112
  }
@@ -229,9 +259,8 @@ export function findNeverEnds(l, opts = {}) {
229
259
  }
230
260
  function search(l, opts) {
231
261
  const wall0 = performance.now(), now = clock, t0 = now(), until = t0 + (opts.ms ?? 10_000), maxTurns = opts.maxTurns ?? 400;
232
- let seed = opts.seed ?? 7;
233
- const rand = (k) => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return Math.floor(seed / 2 ** 31 * k); };
234
- const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0 };
262
+ const rand = seeded(opts.seed ?? 7);
263
+ const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0, accel: 0, accelClosed: 0 };
235
264
  const done = (v) => ({ ...v, stats: { ...stats, ms: Math.round(performance.now() - wall0) } });
236
265
  const stateNames = Object.keys(l.state), kept = [...l.params, ...stateNames];
237
266
  const allObs = observables(kept), inObs = observables(l.inputs);
@@ -378,6 +407,141 @@ function search(l, opts) {
378
407
  }
379
408
  if (opts.lassos)
380
409
  return done({ proven: false, checked: false, why: `no lasso in ${stats.runs} runs` });
410
+ // 1b. Accelerated cycles (core/accel.ts): a set from a cycle of the relation, a stem into it, its closure proven.
411
+ if ((opts.accel ?? 0.4) > 0) {
412
+ const accelUntil = Math.min(until, now() + (until - now()) * (opts.accel ?? 0.4)), m = loopMachine(l), longUntil = Math.max(until, t0 + (opts.extend ?? 0));
413
+ try {
414
+ // (the random runs, the longest 20, for the cycles they take)
415
+ const ends = new Map();
416
+ for (const v of visits)
417
+ if (v.run && (ends.get(v.run)?.at ?? -1) < v.at)
418
+ ends.set(v.run, v);
419
+ const runs = [...ends.values()].sort((a, b) => b.at - a.at).slice(0, 20).map(v => ({ params: v.params, inputs: stemOf(v) }));
420
+ // A set's closure (`budget`: when it stops), then, where no stem is known, a bounded run (core/bmc.ts: the kernel's
421
+ // k-step goal's model, the set's complement as the law it breaks), then the kernel's check of each stem; `late`
422
+ // where the closure ran out of time.
423
+ const attempt = (a, goal, stems, cut, budget) => {
424
+ // (a model of the CDCL search whose products don't multiply out goes on to the plain search, which multiplies rows)
425
+ const was = realModels.on;
426
+ realModels.on = true;
427
+ let out;
428
+ try {
429
+ out = grow(goal, new Map(), { nodes: 0, until: budget });
430
+ }
431
+ finally {
432
+ realModels.on = was;
433
+ }
434
+ if (!('tree' in out))
435
+ return out.stuck === 'unknown' && out.why !== undefined ? 'late' : undefined;
436
+ stats.accelClosed++;
437
+ if (!stems.length && now() < until) {
438
+ const left = Math.min(until - now(), 2000);
439
+ const run = findBoundedRun(m, [{ name: 'outside the set', holds: { op: 'not', x: a.set } }], { ms: left, depth: 24, ...(opts.counted ? {} : { wall: performance.now() + left }) });
440
+ const c = run && cut({ params: run.params, stem: run.trace.map(r => Object.fromEntries(l.inputs.map(n => [n, Number(r[n] ?? 0)]))) });
441
+ if (c)
442
+ stems.push(c);
443
+ }
444
+ for (const t of stems) {
445
+ const recur = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit, tree: out.tree };
446
+ let ok = false;
447
+ try {
448
+ ok = checkRecur(l, recur);
449
+ }
450
+ catch {
451
+ ok = false;
452
+ }
453
+ if (ok)
454
+ return done({ proven: true, checked: true, recur, by: 'accelerated' });
455
+ }
456
+ return undefined;
457
+ };
458
+ // (sets with a small goal that the accelerated runs' search, run to its end, doesn't reach: after the rest, their
459
+ // closures and bounded runs, in the time the search has left)
460
+ const later = [];
461
+ const again = [];
462
+ for (const a of accelerated(l, { now, until: accelUntil, runs, io: { start, turn } })) {
463
+ stats.accel++;
464
+ const goal = recurGoal(l, a);
465
+ stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
466
+ if (dagSize(goal.hyps) > ACCEL_DAG_MAX)
467
+ continue;
468
+ const inSet = cC(a.set);
469
+ // A stem into the set, cut where it first enters it (every turn allowed): from a state a random run reached (the
470
+ // shortest), else an accelerated run (cheap: tried before the closure, which is not tried for a set no stem
471
+ // reaches), else, once the set is closed, a bounded run.
472
+ const cut = (t) => {
473
+ let st = start(t.params);
474
+ for (let j = 0; j <= t.stem.length; j++) {
475
+ if (inSet(st))
476
+ return { params: t.params, stem: t.stem.slice(0, j) };
477
+ if (j === t.stem.length)
478
+ return undefined;
479
+ const nx = turn(st, t.stem[j]);
480
+ if (!nx)
481
+ return undefined;
482
+ st = nx;
483
+ }
484
+ return undefined;
485
+ };
486
+ const stems = [], report = { exhausted: false };
487
+ let best;
488
+ for (const v of visits)
489
+ if ((!best || v.at < best.at) && inSet(v.st))
490
+ best = v;
491
+ if (best)
492
+ stems.push({ params: best.params, stem: stemOf(best) });
493
+ else {
494
+ // (a set's stem has time of its own, past the stage's if need be, within the search's)
495
+ let n = 0;
496
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(longUntil, now() + 1000), report })) {
497
+ const c = cut(t);
498
+ if (c) {
499
+ stems.push(c);
500
+ break;
501
+ }
502
+ if (++n >= 4)
503
+ break;
504
+ }
505
+ }
506
+ // (a set the accelerated runs' search, run to its end, doesn't reach is left: the time goes to sets a run
507
+ // reaches; a small one is tried after them)
508
+ if (!stems.length && report.exhausted) {
509
+ if (dagSize(goal.hyps) <= 50_000 && later.length < 8)
510
+ later.push({ a, goal, cut });
511
+ continue;
512
+ }
513
+ // (a set with a stem is likely: its closure may take most of what is left, past the stage's share; one without,
514
+ // the stage's share and at most 4 s)
515
+ const v = attempt(a, goal, stems, cut, stems.length ? Math.min(until, now() + Math.max(4000, (until - now()) * 0.6)) : Math.min(accelUntil, now() + 4000));
516
+ if (v && v !== 'late')
517
+ return v;
518
+ if (v === 'late' && stems.length && longUntil > until && again.length < 3)
519
+ again.push({ a, goal, stems, cut });
520
+ }
521
+ // (the small sets no stem reaches: a closure and a bounded run each, in what is left of the search's time)
522
+ for (const { a, goal, cut } of later) {
523
+ if (now() >= until)
524
+ break;
525
+ const v = attempt(a, goal, [], cut, Math.min(until, now() + 2000));
526
+ if (v && v !== 'late')
527
+ return v;
528
+ }
529
+ // (a set with a stem whose closure ran out of time: again, with the time `extend` gives, shared, the smaller goal
530
+ // first)
531
+ again.sort((x, y) => dagSize(x.goal.hyps) - dagSize(y.goal.hyps));
532
+ for (const [k, { a, goal, stems, cut }] of again.entries()) {
533
+ if (now() >= longUntil - 1000)
534
+ break;
535
+ const v = attempt(a, goal, stems, cut, Math.min(longUntil, now() + Math.max(4000, (longUntil - now()) * 0.9 / (again.length - k))));
536
+ if (v && v !== 'late')
537
+ return v;
538
+ }
539
+ }
540
+ catch (e) {
541
+ if (!(e instanceof Overflow))
542
+ throw e;
543
+ }
544
+ }
381
545
  // 2. Policies from the states reached.
382
546
  const pools = inObs.map(o => {
383
547
  const terms = [iConst(0), iConst(1)];
package/dist/core/q.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Rat } from '../kernel/kernel.js';
2
2
  export type { Rat };
3
+ export declare const bgcd: (a: bigint, b: bigint) => bigint;
3
4
  export declare const q: (num: bigint | number, den?: bigint | number) => Rat;
4
5
  export declare const Q0: Rat, Q1: Rat;
5
6
  export declare const qadd: (a: Rat, b: Rat) => Rat;
package/dist/core/q.js CHANGED
@@ -1,4 +1,4 @@
1
- const gcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b)
1
+ export const bgcd = (a, b) => { a = a < 0n ? -a : a; b = b < 0n ? -b : b; while (b)
2
2
  [a, b] = [b, a % b]; return a; };
3
3
  export const q = (num, den = 1n) => {
4
4
  let n = BigInt(num), d = BigInt(den);
@@ -8,7 +8,7 @@ export const q = (num, den = 1n) => {
8
8
  n = -n;
9
9
  d = -d;
10
10
  }
11
- const g = gcd(n, d) || 1n;
11
+ const g = bgcd(n, d) || 1n;
12
12
  return { num: n / g, den: d / g };
13
13
  };
14
14
  export const Q0 = q(0), Q1 = q(1);
@@ -25,4 +25,5 @@ export type Generators = {
25
25
  lines: number[][];
26
26
  };
27
27
  export declare function generators(rows: Lin[], names: string[], nats?: string[], cap?: number, until?: number): Generators | undefined;
28
+ export declare const tightBounds: (cs: Lin[]) => Lin[];
28
29
  export declare function houdini(rel: Relation, cands: Lin[][], locOf: (i: number) => [number, number], until: number): Lin[][] | undefined;
@@ -1,19 +1,9 @@
1
1
  import { clock } from "../kernel/prove.js";
2
- import { solve, work } from "./solver.js";
2
+ import { canon, konst, plus, solve, subst, times, vars, work } from "./solver.js";
3
+ import { bgcd } from "./q.js";
3
4
  class Refused extends Error {
4
5
  }
5
6
  const id = (t) => JSON.stringify(t);
6
- const canon = (l) => id(Object.keys(l).sort().map(x => [x, l[x]]));
7
- const plus = (a, b, f = 1) => { const o = { ...a }; for (const x in b) {
8
- o[x] = (o[x] ?? 0) + f * b[x];
9
- if (!o[x])
10
- delete o[x];
11
- } return o; };
12
- const times = (a, f) => { const o = {}; if (f)
13
- for (const x in a)
14
- o[x] = a[x] * f; return o; };
15
- const konst = (c) => (c ? { 1: c } : {});
16
- const vars = (l) => Object.keys(l).filter(x => x !== '1');
17
7
  const pinned = (l, pins) => {
18
8
  let out;
19
9
  for (const x in l)
@@ -111,21 +101,90 @@ function assert(c, p, positive, n) {
111
101
  // The body's value of a state variable on a path: its ifs decided or split, a truncated difference at the top kept
112
102
  // whole (an integer's part, if it is one).
113
103
  // An if and the ifs of its else branches, one after another (a long chain of rules is no deeper a recursion).
104
+ // (A condition the pins decide alone, pc = 3 and t = 1 on a path that pins both, is read at them first: a chain of a
105
+ // rule per case, for every path, is then a walk, not a split of each case.)
114
106
  function chain(e, p, n, leaf) {
115
107
  const out = [];
116
108
  let cur = e, ps = [p];
117
109
  while (cur.op === 'if' && ps.length) {
118
- const c = cur.c, then = cur.then;
119
- for (const q of ps)
110
+ const c = cur.c, then = cur.then, next = [];
111
+ for (const q of ps) {
112
+ const t = truthAt(c, q.pins);
113
+ if (t === true) {
114
+ out.push(...leaf(then, q, n));
115
+ continue;
116
+ }
117
+ if (t === false) {
118
+ next.push(q);
119
+ continue;
120
+ }
120
121
  for (const r of assert(c, q, true, n))
121
122
  out.push(...leaf(then, r, n));
122
- ps = ps.flatMap(q => assert(c, q, false, n));
123
+ next.push(...assert(c, q, false, n));
124
+ }
125
+ ps = next;
123
126
  cur = cur.else;
124
127
  }
125
128
  for (const q of ps)
126
129
  out.push(...leaf(cur, q, n));
127
130
  return out;
128
131
  }
132
+ // A term's value, and a condition's truth, where the pins decide them (undefined where a name isn't pinned).
133
+ function valueAt(e, pins) {
134
+ switch (e.op) {
135
+ case 'var': return pins[e.name];
136
+ case 'const': return e.value;
137
+ case 'mul': {
138
+ const a = valueAt(e.a, pins);
139
+ return a === undefined ? undefined : e.k * a;
140
+ }
141
+ case 'if': {
142
+ const c = truthAt(e.c, pins);
143
+ return c === undefined ? undefined : valueAt(c ? e.then : e.else, pins);
144
+ }
145
+ case 'add':
146
+ case 'sub':
147
+ case 'min':
148
+ case 'max':
149
+ case 'prod': {
150
+ const a = valueAt(e.a, pins), b = a === undefined ? undefined : valueAt(e.b, pins);
151
+ if (a === undefined || b === undefined)
152
+ return undefined;
153
+ return e.op === 'add' ? a + b : e.op === 'sub' ? Math.max(0, a - b) : e.op === 'min' ? Math.min(a, b) : e.op === 'max' ? Math.max(a, b) : a * b;
154
+ }
155
+ case 'get': return undefined;
156
+ }
157
+ }
158
+ function truthAt(c, pins) {
159
+ switch (c.op) {
160
+ case '<':
161
+ case '<=':
162
+ case '=': {
163
+ const a = valueAt(c.a, pins), b = a === undefined ? undefined : valueAt(c.b, pins);
164
+ if (a === undefined || b === undefined)
165
+ return undefined;
166
+ return c.op === '<' ? a < b : c.op === '<=' ? a <= b : a === b;
167
+ }
168
+ case 'and':
169
+ case 'or': {
170
+ let open = false;
171
+ for (const x of c.xs) {
172
+ const t = truthAt(x, pins);
173
+ if (t === undefined)
174
+ open = true;
175
+ else if (t === (c.op === 'or'))
176
+ return t;
177
+ }
178
+ return open ? undefined : c.op === 'and';
179
+ }
180
+ case 'not': {
181
+ const t = truthAt(c.x, pins);
182
+ return t === undefined ? undefined : !t;
183
+ }
184
+ case 'flag':
185
+ case 'all': return undefined;
186
+ }
187
+ }
129
188
  function valueOf(e, p, n) {
130
189
  if (e.op === 'if')
131
190
  return chain(e, p, n, valueOf);
@@ -343,14 +402,13 @@ const renameC = (c, names, f) => {
343
402
  case 'all': return c;
344
403
  }
345
404
  };
346
- const bgcd = (a, b) => { if (a < 0n)
347
- a = -a; if (b < 0n)
348
- b = -b; while (b)
349
- [a, b] = [b, a % b]; return a; };
350
405
  const norm = (x) => { const g = x.reduce(bgcd, 0n); return g > 1n ? x.map(y => y / g) : x; };
351
406
  const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0n);
352
407
  export function generators(rows, names, nats = [], cap = 600, until = Infinity) {
353
408
  const n = names.length, at = new Map(names.map((x, i) => [x, i]));
409
+ // (a row over a name not given has no place: no generators, rather than its coefficient dropped)
410
+ if (rows.some(r => Object.keys(r).some(x => x !== '1' && !at.has(x))))
411
+ return undefined;
354
412
  const hs = [...rows.map(r => { const h = Array.from({ length: n + 1 }, () => 0n); for (const [x, c] of Object.entries(r)) {
355
413
  if (x === '1')
356
414
  h[n] = BigInt(c);
@@ -403,6 +461,21 @@ export function generators(rows, names, nats = [], cap = 600, until = Infinity)
403
461
  const num = (x) => x.map(Number);
404
462
  return { names, vertices: rays.filter(r => r.v[n] > 0n).map(r => num(r.v)), rays: rays.filter(r => r.v[n] === 0n).map(r => num(r.v)), lines: lines.map(num) };
405
463
  }
464
+ // Of the bounds on one name each way, the tightest (the others follow from it), then the rows of more names.
465
+ export const tightBounds = (cs) => {
466
+ const best = new Map(), rest = [];
467
+ for (const c of cs) {
468
+ const xs = vars(c);
469
+ if (xs.length !== 1) {
470
+ rest.push(c);
471
+ continue;
472
+ }
473
+ const x = xs[0], key = `${x}${Math.sign(c[x])}`, b = (c['1'] ?? 0) / Math.abs(c[x]), was = best.get(key);
474
+ if (!was || b > (was['1'] ?? 0) / Math.abs(was[x]))
475
+ best.set(key, c);
476
+ }
477
+ return [...best.values(), ...rest];
478
+ };
406
479
  // --- invariants: Houdini over the relation --------------------------------------------------------------------------
407
480
  //
408
481
  // Candidate atoms per location (each lin ≤ 0 over the relation's names), those that fail at a start dropped by the
@@ -411,22 +484,6 @@ export function generators(rows, names, nats = [], cap = 600, until = Infinity)
411
484
  // inductive over the relation (so over the loop, where the relation is exact); the kernel proves it again as laws.
412
485
  export function houdini(rel, cands, locOf, until) {
413
486
  const H = cands.map(cs => [...new Map(cs.map(c => [canon(c), c])).values()]);
414
- // A path's rows with the candidates at its start: of the bounds on one name, only the tightest each way (the others
415
- // add no vertex).
416
- const tight = (cs) => {
417
- const best = new Map(), rest = [];
418
- for (const c of cs) {
419
- const xs = vars(c);
420
- if (xs.length !== 1) {
421
- rest.push(c);
422
- continue;
423
- }
424
- const x = xs[0], s = Math.sign(c[x]), key = `${x}${s}`, b = (c['1'] ?? 0) / Math.abs(c[x]), was = best.get(key);
425
- if (!was || b > (was['1'] ?? 0) / Math.abs(was[x]))
426
- best.set(key, c);
427
- }
428
- return [...best.values(), ...rest];
429
- };
430
487
  for (let round = 0, changed = true; changed && round < 50; round++) {
431
488
  changed = false;
432
489
  for (const [i, p] of rel.paths.entries()) {
@@ -435,16 +492,15 @@ export function houdini(rel, cands, locOf, until) {
435
492
  const [a, b] = locOf(i);
436
493
  if (!H[b].length)
437
494
  continue;
438
- const rows = [...p.rows, ...tight(H[a])];
495
+ // (a path's rows with the candidates at its start, the tightest bounds of them: the others add no vertex)
496
+ const rows = [...p.rows, ...tightBounds(H[a])];
439
497
  // (the names the candidates at the target read too: one the path reads nowhere is free there, a line)
440
498
  const ns = [...new Set([...rows.flatMap(vars), ...Object.values(p.post).flatMap(vars), ...H[b].flatMap(vars)])].sort();
441
499
  const g = generators(rows, ns, rel.nats, 600, until);
442
500
  if (!g) {
443
501
  // past the generators' cap: each candidate after the turn refuted by the integer solver, or dropped
444
502
  const nat = rel.nats.filter(x => ns.includes(x)).map((x) => ({ [x]: -1 }));
445
- const through = (c) => { let o = {}; for (const [y, k] of Object.entries(c))
446
- o = plus(o, y !== '1' && p.post[y] ? times(p.post[y], k) : { [y]: k }); return o; };
447
- const keep = H[b].filter(c => clock() < until && solve([...rows, ...nat, plus(konst(1), through(c), -1)].map(lin => ({ lin, label: '' })), 4000).kind === 'refuted');
503
+ const keep = H[b].filter(c => clock() < until && solve([...rows, ...nat, plus(konst(1), subst(c, p.post), -1)].map(lin => ({ lin, label: '' })), 4000).kind === 'refuted');
448
504
  if (keep.length < H[b].length) {
449
505
  H[b] = keep;
450
506
  changed = true;
@@ -1,5 +1,7 @@
1
1
  import { type Rat } from './q.js';
2
+ import type { E } from './machine.js';
2
3
  export type Lin = Record<string, number>;
4
+ export declare const env: Record<string, string | undefined>;
3
5
  export type Constraint = {
4
6
  lin: Lin;
5
7
  label: string;
@@ -53,8 +55,18 @@ export type Verdict = {
53
55
  kind: 'unknown';
54
56
  point?: Record<string, number>;
55
57
  };
58
+ export declare const gcd: (a: number, b: number) => number;
59
+ export declare const vars: (lin: Lin) => string[];
60
+ export declare const plus: (a: Lin, b: Lin, f?: number) => Lin;
61
+ export declare const times: (a: Lin, f: number) => Lin;
62
+ export declare const konst: (c: number) => Lin;
63
+ export declare const linOfE: (e: E) => Lin | undefined;
64
+ export declare const subst: (l: Lin, m: Record<string, Lin>) => Lin;
65
+ export declare const canon: (l: Lin) => string;
56
66
  export declare const work: {
57
67
  n: number;
58
68
  };
59
69
  export declare function solve(constraints: Constraint[], maxRows?: number, integral?: boolean): Verdict;
70
+ export declare const ratioRow: (T: Float64Array[], basis: number[], enter: number, cols: number, eps: number) => [number, number];
71
+ export declare function pivot(T: Float64Array[], z: Float64Array | undefined, basis: number[], leave: number, enter: number, cols: number): void;
60
72
  export declare function refuteFast(constraints: Constraint[], maxRows?: number, integral?: boolean): Verdict | undefined;