gdp-wired 0.25.0 → 0.27.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 +20 -1
  3. package/dist/core/accel.js +797 -220
  4. package/dist/core/bmc.d.ts +12 -1
  5. package/dist/core/bmc.js +275 -106
  6. package/dist/core/cycles.d.ts +2 -3
  7. package/dist/core/cycles.js +35 -131
  8. package/dist/core/cyclic.d.ts +4 -1
  9. package/dist/core/cyclic.js +103 -74
  10. package/dist/core/data.d.ts +1 -1
  11. package/dist/core/data.js +89 -118
  12. package/dist/core/discover.js +65 -27
  13. package/dist/core/dsl.d.ts +3 -2
  14. package/dist/core/dsl.js +29 -25
  15. package/dist/core/exists.js +7 -14
  16. package/dist/core/extract-check.d.ts +55 -4
  17. package/dist/core/extract-check.js +248 -122
  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 +98 -4
  21. package/dist/core/extract-read.js +306 -43
  22. package/dist/core/extract-shapes.d.ts +14 -0
  23. package/dist/core/extract-shapes.js +609 -79
  24. package/dist/core/extract-xstate.d.ts +5 -1
  25. package/dist/core/extract-xstate.js +618 -184
  26. package/dist/core/extract.d.ts +1 -0
  27. package/dist/core/extract.js +81 -30
  28. package/dist/core/infer.d.ts +1 -0
  29. package/dist/core/infer.js +126 -64
  30. package/dist/core/machine.d.ts +6 -0
  31. package/dist/core/machine.js +35 -4
  32. package/dist/core/nonterm.d.ts +5 -1
  33. package/dist/core/nonterm.js +133 -45
  34. package/dist/core/q.d.ts +1 -0
  35. package/dist/core/q.js +2 -2
  36. package/dist/core/relation.d.ts +1 -0
  37. package/dist/core/relation.js +20 -36
  38. package/dist/core/solver.d.ts +33 -0
  39. package/dist/core/solver.js +84 -30
  40. package/dist/core/transfer.js +22 -13
  41. package/dist/core/translate.d.ts +1 -1
  42. package/dist/core/translate.js +88 -65
  43. package/dist/core/xstate.d.ts +6 -1
  44. package/dist/core/xstate.js +336 -55
  45. package/dist/kernel/cdcl.js +212 -79
  46. package/dist/kernel/prove.d.ts +36 -5
  47. package/dist/kernel/prove.js +212 -104
  48. package/dist/kernel/reader.d.ts +75 -5
  49. package/dist/kernel/reader.js +533 -76
  50. package/dist/kernel/simplex.d.ts +27 -2
  51. package/dist/kernel/simplex.js +160 -14
  52. package/package.json +3 -2
@@ -2,12 +2,40 @@
2
2
  // - interpret / compileJs: the runtime, as an interpreter and as generated JavaScript
3
3
  // - prove: each law by induction (holds at the start, one step preserves it), with every case decided by solver.ts
4
4
  // - search: real counterexample traces from the start, by bounded enumeration of short request sequences
5
- // - strengthen (invariant.ts): candidate invariants dropped until the rest are inductive (Houdini)
6
5
  // Arithmetic is linear: +, −, × by a constant, min, max, if. Maps are naturals indexed by naturals, every cell starting
7
6
  // 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
7
  // every other key the step reads).
9
8
  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";
9
+ import { add, env, eq, k, le, lt, nat, scale, show, solve, sub, v } from "./solver.js";
10
+ export const seeded = (seed) => { let x = seed; return k => { x = (x * 1103515245 + 12345) % 2 ** 31; return Math.floor(x / 2 ** 31 * k); }; };
11
+ // Every object in a term, the term first.
12
+ export const walk = (t, f) => {
13
+ if (Array.isArray(t)) {
14
+ for (const x of t)
15
+ walk(x, f);
16
+ return;
17
+ }
18
+ if (!t || typeof t !== 'object')
19
+ return;
20
+ const o = t;
21
+ f(o);
22
+ for (const x of Object.values(o))
23
+ walk(x, f);
24
+ };
25
+ // Every object in a term once (arrays too), a part shared by several uses read at its first: a witness read at each of
26
+ // its uses in a goal is one object, and a walk of the goal written out would read it at each.
27
+ export const walkOnce = (t, f) => {
28
+ const seen = new Set();
29
+ const go = (x) => {
30
+ if (!x || typeof x !== 'object' || seen.has(x))
31
+ return;
32
+ seen.add(x);
33
+ f(x);
34
+ for (const y of Object.values(x))
35
+ go(y);
36
+ };
37
+ go(t);
38
+ };
11
39
  // A write at one key, for the parts that take no write at every key (the symbolic prover, the GPU synthesizers, the
12
40
  // hand-written shader, the first Lean export): they refuse one by name.
13
41
  export const pointWrite = (w, where) => { if ('each' in w)
@@ -227,7 +255,10 @@ const callOf = (fn) => {
227
255
  }
228
256
  return f;
229
257
  };
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.
258
+ // A key of several arguments: their pairing, left-nested, ((a, b), c)..., each pair (s)² + b with s = a + b.
259
+ export const pairE = (a, b) => { const s = plus(a, b); return plus(prod(s, s), b); };
260
+ export const argsKey = (args) => args.slice(1).reduce(pairE, args[0]);
261
+ // The n arguments a key pairs (argsKey's), if it is their pairing.
231
262
  const paired = new WeakMap();
232
263
  export function pairedArgs(key, n) {
233
264
  let byN = paired.get(key);
@@ -649,7 +680,7 @@ function symC(c, s, truth) {
649
680
  }
650
681
  }
651
682
  // 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;
683
+ const proveDebug = !!env.PROVE_DEBUG;
653
684
  const debug = (label, n) => { if (proveDebug)
654
685
  console.error(`[prove] ${label}: ${n} (${Math.round(performance.now())} ms)`); };
655
686
  // 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;
@@ -7,6 +7,7 @@ export type NeverEndsOptions = {
7
7
  lassos?: boolean;
8
8
  counted?: number;
9
9
  accel?: number;
10
+ extend?: number;
10
11
  };
11
12
  export type NeverEndsVerdict = {
12
13
  proven: boolean;
@@ -31,7 +32,10 @@ export type NeverEndsVerdict = {
31
32
  accelClosed: number;
32
33
  };
33
34
  };
35
+ export declare const isT: (c: C) => boolean;
36
+ export declare const isF: (c: C) => boolean;
34
37
  export declare const simpE: (e: E) => E;
35
38
  export declare const simpC: (c: C) => C;
36
39
  export declare function goalSize(x: unknown): number;
40
+ export declare const dagSize: (x: unknown) => number;
37
41
  export declare function findNeverEnds(l: Loop, opts?: NeverEndsOptions): NeverEndsVerdict;
@@ -1,15 +1,37 @@
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";
1
25
  import { checkRecur, loopMachine, recurGoal, substC, trueC } from "../kernel/kernel.js";
2
- import { clock, counted, grow } from "../kernel/prove.js";
26
+ import { clock, counted, grow, realModels } from "../kernel/prove.js";
3
27
  import { work } from "./solver.js";
4
28
  import { accelerated, stemsTo } from "./accel.js";
5
29
  import { findBoundedRun } from "./bmc.js";
6
- const K = (value) => ({ op: 'const', value }), V = (name) => ({ op: 'var', name });
7
30
  const T = trueC, F = { op: '<', a: K(0), b: K(0) };
8
- const isT = (c) => c.op === '<=' && c.a.op === 'const' && c.b.op === 'const' && c.a.value <= c.b.value;
9
- 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);
10
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 }; };
11
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 }; };
12
- const eq = (a, b) => ({ op: '=', a, b });
13
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 });
14
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 });
15
37
  const times = (k, a) => (k === 0 ? K(0) : k === 1 ? a : a.op === 'const' ? K(k * a.value) : { op: 'mul', k, a });
@@ -79,10 +101,12 @@ export function goalSize(x) {
79
101
  return n;
80
102
  }
81
103
  const GOAL_MAX = 300_000;
82
- // An accelerated set's goal: the witness reads the location (and the set's parts only where the cycle comes back to one),
83
- // so its ifs multiply the body's less, and such goals of millions of nodes have closed (TermComp's tqli: 720,729 nodes,
84
- // proven in 22 s).
85
- const ACCEL_GOAL_MAX = 5_000_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;
86
110
  // --- running the loop ---------------------------------------------------------------------------------------------------
87
111
  class Overflow extends Error {
88
112
  }
@@ -235,8 +259,7 @@ export function findNeverEnds(l, opts = {}) {
235
259
  }
236
260
  function search(l, opts) {
237
261
  const wall0 = performance.now(), now = clock, t0 = now(), until = t0 + (opts.ms ?? 10_000), maxTurns = opts.maxTurns ?? 400;
238
- let seed = opts.seed ?? 7;
239
- const rand = (k) => { seed = (seed * 1103515245 + 12345) % 2 ** 31; return Math.floor(seed / 2 ** 31 * k); };
262
+ const rand = seeded(opts.seed ?? 7);
240
263
  const stats = { runs: 0, turns: 0, policies: 0, rounds: 0, ms: 0, lassoTried: 0, goalSize: 0, accel: 0, accelClosed: 0 };
241
264
  const done = (v) => ({ ...v, stats: { ...stats, ms: Math.round(performance.now() - wall0) } });
242
265
  const stateNames = Object.keys(l.state), kept = [...l.params, ...stateNames];
@@ -339,9 +362,10 @@ function search(l, opts) {
339
362
  // 1. Random runs: the states they reach, each with its stem; a lasso on the way is tried at once.
340
363
  const visits = [], bounds = [1, 2, 4, 8, 16, 64];
341
364
  try {
342
- // (a fifth of the time, at most 1.5 s, unless only lassos are asked for; at most 4,000 states kept, then only a
343
- // run's last)
344
- while (now() < (opts.lassos ? until : Math.min(t0 + (until - t0) * 0.2, t0 + 1500))) {
365
+ // (a fifth of the time, at most 1.5 s, a run too, unless only lassos are asked for; at most 4,000 states kept, then
366
+ // only a run's last)
367
+ const runsUntil = opts.lassos ? until : Math.min(t0 + (until - t0) * 0.2, t0 + 1500);
368
+ while (now() < runsUntil) {
345
369
  const bound = bounds[stats.runs++ % bounds.length], ps = drawParams(bound);
346
370
  if (!ps)
347
371
  continue;
@@ -349,7 +373,7 @@ function search(l, opts) {
349
373
  const stem = [], seen = new Map(), trail = [], run = { n: 0 };
350
374
  if (visits.length < 4000)
351
375
  visits.push({ params: ps, trail: stem, at: 0, st, run });
352
- for (let n = 0; n < 3000 && now() < until; n++) {
376
+ for (let n = 0; n < 3000 && now() < runsUntil; n++) {
353
377
  const key = keyOf(st), back = seen.get(key);
354
378
  if (back !== undefined) {
355
379
  const cycle = trail.slice(back).map((s, j) => ({ st: s, input: stem[back + j] }));
@@ -386,7 +410,7 @@ function search(l, opts) {
386
410
  return done({ proven: false, checked: false, why: `no lasso in ${stats.runs} runs` });
387
411
  // 1b. Accelerated cycles (core/accel.ts): a set from a cycle of the relation, a stem into it, its closure proven.
388
412
  if ((opts.accel ?? 0.4) > 0) {
389
- const accelUntil = Math.min(until, now() + (until - now()) * (opts.accel ?? 0.4)), m = loopMachine(l);
413
+ const accelUntil = Math.min(until, now() + (until - now()) * (opts.accel ?? 0.4)), m = loopMachine(l), longUntil = Math.max(until, t0 + (opts.extend ?? 0));
390
414
  try {
391
415
  // (the random runs, the longest 20, for the cycles they take)
392
416
  const ends = new Map();
@@ -394,17 +418,68 @@ function search(l, opts) {
394
418
  if (v.run && (ends.get(v.run)?.at ?? -1) < v.at)
395
419
  ends.set(v.run, v);
396
420
  const runs = [...ends.values()].sort((a, b) => b.at - a.at).slice(0, 20).map(v => ({ params: v.params, inputs: stemOf(v) }));
421
+ // A set's closure (`budget`: when it stops), then, where no stem is known, the accelerated runs' search deeper and a
422
+ // bounded run (core/bmc.ts: the kernel's k-step goal's model, the set's complement as the law it breaks), then the
423
+ // kernel's check of each stem; `late` where the closure ran out of time.
424
+ const attempt = (a, goal, stems, cut, budget) => {
425
+ // (a model of the CDCL search whose products don't multiply out goes on to the plain search, which multiplies rows)
426
+ const was = realModels.on;
427
+ realModels.on = true;
428
+ let out;
429
+ try {
430
+ out = grow(goal, new Map(), { nodes: 0, until: budget });
431
+ }
432
+ finally {
433
+ realModels.on = was;
434
+ }
435
+ if (!('tree' in out))
436
+ return out.stuck === 'unknown' && out.why !== undefined ? 'late' : undefined;
437
+ stats.accelClosed++;
438
+ // (the accelerated runs' search again, deeper: fun9's stem of 30 turns)
439
+ if (!stems.length && now() < until)
440
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(until, now() + 1000), deepen: true })) {
441
+ const c = cut(t);
442
+ if (c) {
443
+ stems.push(c);
444
+ break;
445
+ }
446
+ }
447
+ if (!stems.length && now() < until) {
448
+ const left = Math.min(until - now(), 2000);
449
+ const run = findBoundedRun(m, [{ name: 'outside the set', holds: { op: 'not', x: a.set } }], { ms: left, depth: 24, ...(opts.counted ? {} : { wall: performance.now() + left }) });
450
+ const c = run && cut({ params: run.params, stem: run.trace.map(r => Object.fromEntries(l.inputs.map(n => [n, Number(r[n] ?? 0)]))) });
451
+ if (c)
452
+ stems.push(c);
453
+ }
454
+ for (const t of stems) {
455
+ const recur = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit, tree: out.tree };
456
+ let ok = false;
457
+ try {
458
+ ok = checkRecur(l, recur);
459
+ }
460
+ catch {
461
+ ok = false;
462
+ }
463
+ if (ok)
464
+ return done({ proven: true, checked: true, recur, by: 'accelerated' });
465
+ }
466
+ return undefined;
467
+ };
468
+ // (sets with a small goal that the accelerated runs' search, run to its end, doesn't reach: after the rest, their
469
+ // closures and bounded runs, in the time the search has left)
470
+ const later = [];
471
+ let deepened = 0;
472
+ const again = [];
397
473
  for (const a of accelerated(l, { now, until: accelUntil, runs, io: { start, turn } })) {
398
474
  stats.accel++;
399
475
  const goal = recurGoal(l, a);
400
476
  stats.goalSize = Math.max(stats.goalSize, goalSize(goal.hyps));
401
- if (goalSize(goal.hyps) > ACCEL_GOAL_MAX)
477
+ if (dagSize(goal.hyps) > ACCEL_DAG_MAX)
402
478
  continue;
403
479
  const inSet = cC(a.set);
404
480
  // A stem into the set, cut where it first enters it (every turn allowed): from a state a random run reached (the
405
481
  // shortest), else an accelerated run (cheap: tried before the closure, which is not tried for a set no stem
406
- // reaches), else, once the set is closed, a bounded run (core/bmc.ts: the kernel's k-step goal's model, the set's
407
- // complement as the law it breaks).
482
+ // reaches), else, once the set is closed, a bounded run.
408
483
  const cut = (t) => {
409
484
  let st = start(t.params);
410
485
  for (let j = 0; j <= t.stem.length; j++) {
@@ -429,7 +504,7 @@ function search(l, opts) {
429
504
  else {
430
505
  // (a set's stem has time of its own, past the stage's if need be, within the search's)
431
506
  let n = 0;
432
- for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(until, now() + 1000), report })) {
507
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(longUntil, now() + 1000), report })) {
433
508
  const c = cut(t);
434
509
  if (c) {
435
510
  stems.push(c);
@@ -438,35 +513,48 @@ function search(l, opts) {
438
513
  if (++n >= 4)
439
514
  break;
440
515
  }
516
+ // (a set that search, run to its end, doesn't reach: again deeper, at most 500 ms, for the first four)
517
+ if (!stems.length && report.exhausted && deepened++ < 4)
518
+ for (const t of stemsTo(l, a.targets, { start, turn }, { now, until: Math.min(longUntil, now() + 500), deepen: true })) {
519
+ const c = cut(t);
520
+ if (c) {
521
+ stems.push(c);
522
+ break;
523
+ }
524
+ }
441
525
  }
442
- // (a set the accelerated runs' search, run to its end, doesn't reach is left: the time goes to sets a run reaches)
443
- if (!stems.length && report.exhausted)
526
+ // (a set the accelerated runs' search, run to its end, doesn't reach is left: the time goes to sets a run
527
+ // reaches; a small one is tried after them)
528
+ if (!stems.length && report.exhausted) {
529
+ if (dagSize(goal.hyps) <= 50_000 && later.length < 8)
530
+ later.push({ a, goal, cut });
444
531
  continue;
532
+ }
445
533
  // (a set with a stem is likely: its closure may take most of what is left, past the stage's share; one without,
446
534
  // the stage's share and at most 4 s)
447
- const out = grow(goal, new Map(), { nodes: 0, until: stems.length ? Math.min(until, now() + Math.max(4000, (until - now()) * 0.6)) : Math.min(accelUntil, now() + 4000) });
448
- if (!('tree' in out))
449
- continue;
450
- stats.accelClosed++;
451
- if (!stems.length && now() < until) {
452
- const left = Math.min(until - now(), 2000);
453
- const run = findBoundedRun(m, [{ name: 'outside the set', holds: { op: 'not', x: a.set } }], { ms: left, depth: 24, ...(opts.counted ? {} : { wall: performance.now() + left }) });
454
- const c = run && cut({ params: run.params, stem: run.trace.map(r => Object.fromEntries(l.inputs.map(n => [n, Number(r[n] ?? 0)]))) });
455
- if (c)
456
- stems.push(c);
457
- }
458
- for (const t of stems) {
459
- const recur = { start: params(t.params), stem: asStem(t.stem), set: a.set, wit: a.wit, tree: out.tree };
460
- let ok = false;
461
- try {
462
- ok = checkRecur(l, recur);
463
- }
464
- catch {
465
- ok = false;
466
- }
467
- if (ok)
468
- return done({ proven: true, checked: true, recur, by: 'accelerated' });
469
- }
535
+ 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));
536
+ if (v && v !== 'late')
537
+ return v;
538
+ if (v === 'late' && stems.length && longUntil > until && again.length < 3)
539
+ again.push({ a, goal, stems, cut });
540
+ }
541
+ // (the small sets no stem reaches: a closure and a bounded run each, in what is left of the search's time)
542
+ for (const { a, goal, cut } of later) {
543
+ if (now() >= until)
544
+ break;
545
+ const v = attempt(a, goal, [], cut, Math.min(until, now() + 2000));
546
+ if (v && v !== 'late')
547
+ return v;
548
+ }
549
+ // (a set with a stem whose closure ran out of time: again, with the time `extend` gives, shared, the smaller goal
550
+ // first)
551
+ again.sort((x, y) => dagSize(x.goal.hyps) - dagSize(y.goal.hyps));
552
+ for (const [k, { a, goal, stems, cut }] of again.entries()) {
553
+ if (now() >= longUntil - 1000)
554
+ break;
555
+ const v = attempt(a, goal, stems, cut, Math.min(longUntil, now() + Math.max(4000, (longUntil - now()) * 0.9 / (again.length - k))));
556
+ if (v && v !== 'late')
557
+ return v;
470
558
  }
471
559
  }
472
560
  catch (e) {
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)
@@ -412,10 +402,6 @@ const renameC = (c, names, f) => {
412
402
  case 'all': return c;
413
403
  }
414
404
  };
415
- const bgcd = (a, b) => { if (a < 0n)
416
- a = -a; if (b < 0n)
417
- b = -b; while (b)
418
- [a, b] = [b, a % b]; return a; };
419
405
  const norm = (x) => { const g = x.reduce(bgcd, 0n); return g > 1n ? x.map(y => y / g) : x; };
420
406
  const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0n);
421
407
  export function generators(rows, names, nats = [], cap = 600, until = Infinity) {
@@ -475,6 +461,21 @@ export function generators(rows, names, nats = [], cap = 600, until = Infinity)
475
461
  const num = (x) => x.map(Number);
476
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) };
477
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
+ };
478
479
  // --- invariants: Houdini over the relation --------------------------------------------------------------------------
479
480
  //
480
481
  // Candidate atoms per location (each lin ≤ 0 over the relation's names), those that fail at a start dropped by the
@@ -483,22 +484,6 @@ export function generators(rows, names, nats = [], cap = 600, until = Infinity)
483
484
  // inductive over the relation (so over the loop, where the relation is exact); the kernel proves it again as laws.
484
485
  export function houdini(rel, cands, locOf, until) {
485
486
  const H = cands.map(cs => [...new Map(cs.map(c => [canon(c), c])).values()]);
486
- // A path's rows with the candidates at its start: of the bounds on one name, only the tightest each way (the others
487
- // add no vertex).
488
- const tight = (cs) => {
489
- const best = new Map(), rest = [];
490
- for (const c of cs) {
491
- const xs = vars(c);
492
- if (xs.length !== 1) {
493
- rest.push(c);
494
- continue;
495
- }
496
- const x = xs[0], s = Math.sign(c[x]), key = `${x}${s}`, b = (c['1'] ?? 0) / Math.abs(c[x]), was = best.get(key);
497
- if (!was || b > (was['1'] ?? 0) / Math.abs(was[x]))
498
- best.set(key, c);
499
- }
500
- return [...best.values(), ...rest];
501
- };
502
487
  for (let round = 0, changed = true; changed && round < 50; round++) {
503
488
  changed = false;
504
489
  for (const [i, p] of rel.paths.entries()) {
@@ -507,16 +492,15 @@ export function houdini(rel, cands, locOf, until) {
507
492
  const [a, b] = locOf(i);
508
493
  if (!H[b].length)
509
494
  continue;
510
- 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])];
511
497
  // (the names the candidates at the target read too: one the path reads nowhere is free there, a line)
512
498
  const ns = [...new Set([...rows.flatMap(vars), ...Object.values(p.post).flatMap(vars), ...H[b].flatMap(vars)])].sort();
513
499
  const g = generators(rows, ns, rel.nats, 600, until);
514
500
  if (!g) {
515
501
  // past the generators' cap: each candidate after the turn refuted by the integer solver, or dropped
516
502
  const nat = rel.nats.filter(x => ns.includes(x)).map((x) => ({ [x]: -1 }));
517
- const through = (c) => { let o = {}; for (const [y, k] of Object.entries(c))
518
- o = plus(o, y !== '1' && p.post[y] ? times(p.post[y], k) : { [y]: k }); return o; };
519
- 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');
520
504
  if (keep.length < H[b].length) {
521
505
  H[b] = keep;
522
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,39 @@ 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
  };
69
+ export declare const costs: {
70
+ solves: number;
71
+ solveRows: number;
72
+ fm: number;
73
+ fpivots: number;
74
+ fcells: number;
75
+ cdclNodes: number;
76
+ cdclRows: number;
77
+ scan: number;
78
+ pivots: number;
79
+ pivotRows: number;
80
+ plainNodes: number;
81
+ plainRows: number;
82
+ values: number;
83
+ copies: number;
84
+ edges: number;
85
+ unitRows: number;
86
+ unfoldRows: number;
87
+ goalNodes: number;
88
+ translateRows: number;
89
+ };
59
90
  export declare function solve(constraints: Constraint[], maxRows?: number, integral?: boolean): Verdict;
91
+ export declare const ratioRow: (T: Float64Array[], basis: number[], enter: number, cols: number, eps: number) => [number, number];
92
+ export declare function pivot(T: Float64Array[], z: Float64Array | undefined, basis: number[], leave: number, enter: number, cols: number): void;
60
93
  export declare function refuteFast(constraints: Constraint[], maxRows?: number, integral?: boolean): Verdict | undefined;