diff --git a/.gitignore b/.gitignore index f3d0b61e..4bfcad54 100644 --- a/.gitignore +++ b/.gitignore @@ -16,5 +16,5 @@ output/ # Agent loop state (scripts/agent-loop) .loop/ -# Archived colour research inputs -.cache/colour/ +# Reproducible research output (includes archived colour inputs in .cache/colour/) +.cache/ diff --git a/docs/evidence/mixed-relations/README.md b/docs/evidence/mixed-relations/README.md new file mode 100644 index 00000000..6797fc61 --- /dev/null +++ b/docs/evidence/mixed-relations/README.md @@ -0,0 +1,213 @@ +# Mixed relation research + +This offline research combines difference inequalities with prospective midpoint +and equal-spacing equalities. It adds internal proof searches and independent +checkers, without changing placement callers, public exports, drawings or +acceptance bands. The complete historical reports are preserved on +`archive/mixed-relations-94` at `0d92b63f`; generated reports stay off this branch. +All counts below can be reproduced with the named scripts under +`scripts/mixed-relations/`. Raw historical data for every row is on that archive +branch; current reproductions write to git-ignored `.cache/mixed-relations/`. + +## Corpus and counted patterns + +`catalogue.mjs` builds 136 base axis systems and 260 prospective systems from +23 book maps (authored and benchmark-hint profiles) and 11 example variants +(each with dagre and ELK). Rank and cross axes use 16-unit gaps. Benchmark hints +add a first-node required pin and same-rank groups inferred from hand geometry; +they are research assumptions, not authored requirements. The established +comparison copy of map 2-1 omits its frame-endpoint arrow. Preferred pins remain +preferences; cross-lane widening is outside this model. + +The prospective probes impose a midpoint on the first three source-order boxes +and an equal-spacing chain on the first four, where available. They use leading +edges, not centres, and do not claim to capture the author's intended groups. +The catalogue separately checks 408 output-only derived positions; deriving a +point from one placement does not fix free coordinates of that placement. + +| Pattern or result | Count | Reproduction script | +| ------------------------------------------------- | --------------: | ------------------------------ | +| Book benchmark axis systems / relations | 46 / 890 | `../benchmark-relations.mjs` | +| Base systems / prospective probes | 136 / 260 | `catalogue.mjs` | +| Checked output-only derivations | 408 | `catalogue.mjs` | +| Probes retaining a smaller equality remainder | 46 | `catalogue.mjs` | +| Initial contradictions / missed by substitution | 43 / 35 | `catalogue.mjs`, `certify.mjs` | +| Additional contradictions needing multiple bounds | 8 | `certify-projection.mjs` | +| Feasible prospective systems over rationals | 209 | `variations.mjs` | +| Fixed / moving / undecided coordinate occurrences | 281 / 2,359 / 0 | `moving-coordinates.mjs` | + +The additional contradictions combine two or three source bounds: cross-axis +spacing in book map 4-5 in both profiles, cross-axis spacing in examples `free` +and `free-plain`, and the rank-axis midpoint in `same-rank`, for both engines +(`certify-projection.mjs`). These are conflicts in prospective constraints, +not defects in the existing drawings. + +## Current corpus measure + +`bounded-grid-system.mjs` checks every result against source systems and +independently prepared rows. At 10,000 rows and 10,000 grid nodes per search, +it classifies all 396 systems with 686 independently checked integer points. +Contradictions have rational source-row certificates; determined results have +one integer point and signed fixed-coordinate proofs; underdetermined results +have two distinct integer points. Search failure remains undecided. + +| Profile | Determined | Underdetermined | Contradictory | Undecided | +| --------------------- | ---------: | --------------: | ------------: | --------: | +| Book, authored | 0 | 137 | 1 | 0 | +| Book, benchmark hints | 0 | 104 | 34 | 0 | +| Examples, dagre | 2 | 50 | 8 | 0 | +| Examples, ELK | 2 | 50 | 8 | 0 | +| Total | 4 | 341 | 51 | 0 | + +`bounded-grid.mjs` checks integer witnesses for all 345 rationally feasible +systems: 340 seeds are already integral and five need local search. +`bounded-grid-variation.mjs` checks integer pairs for all 341 underdetermined +systems: 303 existing pairs are integral and 38 need local construction. +These counts describe the corpus, not a general integer-solving guarantee. + +## Reproduction + +Run from the repository root with locked dependencies installed: + +```sh +npm run build +node scripts/benchmark-relations.mjs > /tmp/relations-baseline.json +node scripts/mixed-relations/catalogue.mjs +node scripts/mixed-relations/certify.mjs +node scripts/mixed-relations/feasibility.mjs +node scripts/mixed-relations/variations.mjs +node scripts/mixed-relations/certify-projection.mjs +node scripts/mixed-relations/fixed-coordinates.mjs +node scripts/mixed-relations/moving-coordinates.mjs +node scripts/mixed-relations/classification.mjs +node scripts/mixed-relations/grid-feasibility.mjs +node scripts/mixed-relations/grid-variations.mjs +node scripts/mixed-relations/bounded-certificates.mjs +node scripts/mixed-relations/bounded-fixed.mjs +node scripts/mixed-relations/bounded-classification.mjs +node scripts/mixed-relations/bounded-system.mjs +node scripts/mixed-relations/bounded-feasibility.mjs +node scripts/mixed-relations/bounded-variation.mjs +node scripts/mixed-relations/bounded-grid.mjs +node scripts/mixed-relations/bounded-grid-variation.mjs +node scripts/mixed-relations/bounded-grid-system.mjs +node scripts/mixed-relations/ablate-grid.mjs +node scripts/mixed-relations/ablate-earlier.mjs +node scripts/mixed-relations/ablate-diagnostics.mjs +npm run verify +``` + +The order matters: fixed-coordinate reports read generated variation pairs; +moving-coordinate and bounded-fixed reports also read generated fixed proofs. +Each writer accepts an optional output-directory argument, except the three ablation scripts. +Prerequisite reads always use the default cache directory. For independent +replay, generate prerequisites there first, then pass a separate destination +and compare JSON byte for byte. Reports retain the 500-line limit. + +Focused diagnostic checks are `node scripts/mixed-relations/test.mjs` and +all `test-*.mjs` scripts in that directory. They check original-row certificates, +feasible points, distinct pairs, fixed coordinates and tampering separately from +the proof producers. The archive contains the earlier per-pass summaries and +raw reports; no screenshots or generated proof files belong in this branch. + +## Ablation of late grid fallbacks + +`node scripts/mixed-relations/ablate-grid.mjs` reconstructs the pre-cleanup +modules from commit `7aaa38f1bdd4443b3b1557c1a9c3e987f95d6bd3` in an ignored +copy, disables each fallback separately, and independently checks every +returned source-system result. It also disables all seven together and runs +the current implementation. Output goes to +`.cache/mixed-relations/grid-ablation/summary.json`; no archive branch is changed. +The raw map catalogue remains on `archive/mixed-relations-94` at `0d92b63f`. + +| Disabled mechanism | Determined | Underdetermined | Contradictory | Undecided | Checked integer points | Changed classifications | +| ---------------------------------- | ---------: | --------------: | ------------: | --------: | ---------------------: | ----------------------: | +| None (reference) | 4 | 341 | 51 | 0 | 686 | 0 | +| Primitive seed line | 4 | 341 | 51 | 0 | 686 | 0 | +| Fractional singleton | 4 | 341 | 51 | 0 | 686 | 0 | +| Single-row divisibility | 4 | 341 | 51 | 0 | 686 | 0 | +| Reduced-row divisibility | 4 | 341 | 51 | 0 | 686 | 0 | +| Pairwise divisibility | 4 | 341 | 51 | 0 | 686 | 0 | +| Parity elimination | 4 | 341 | 51 | 0 | 686 | 0 | +| Odd-prime elimination | 4 | 341 | 51 | 0 | 686 | 0 | +| All seven / current implementation | 4 | 341 | 51 | 0 | 686 | 0 | + +All seven mechanisms and their synthetic controls were removed: none meets +the author's minimum of three changed map-corpus classifications. A failed +nearby grid search now stays undecided. This changes internal diagnostic +coverage outside this corpus, with no public export or placement caller. + +## Ablation of rational and nearby-grid searches + +`ablate-earlier.mjs` freezes the implementation at commit `8c800e1` in an +ignored copy and disables each search separately. It checks all returned proofs +against source systems. Its count report is +`.cache/mixed-relations/earlier-ablation/summary.json`; separate +`-changed.json` files list changed case names. Historical raw data is on +`archive/mixed-relations-94` at `0d92b63f`. + +| Disabled mechanism | Determined | Underdetermined | Contradictory | Undecided | Checked integer points | Changed classifications | +| -------------------------------------- | ---------: | --------------: | ------------: | --------: | ---------------------: | ----------------------: | +| None (reference) | 4 | 341 | 51 | 0 | 686 | 0 | +| Rational feasibility | 0 | 0 | 51 | 345 | 0 | 345 | +| Contradiction projection | 0 | 341 | 0 | 55 | 682 | 55 | +| Fixed-coordinate proofs | 0 | 341 | 51 | 4 | 682 | 4 | +| Signed basis lines | 4 | 341 | 51 | 0 | 686 | 0 | +| Coupled motion cones | 4 | 331 | 51 | 10 | 666 | 10 | +| Nearby integer search | 4 | 303 | 51 | 38 | 610 | 38 | +| Search around first integer point | 4 | 341 | 51 | 0 | 686 | 0 | +| Both zero-contribution paths / current | 4 | 341 | 51 | 0 | 686 | 0 | + +Signed basis lines and the extra integer-point seed were removed together with +their synthetic assertions. Their joint removal preserves every corpus status. +It changes the chosen rational motion points, so this is classification equality, +not byte-identical witness output. Outside this corpus, a search can now remain +undecided when those fallbacks previously found a result. + +The same script repeats each retained-search ablation after both removals: + +| Disabled retained mechanism | Determined | Underdetermined | Contradictory | Undecided | Checked integer points | Changed classifications | +| --------------------------- | ---------: | --------------: | ------------: | --------: | ---------------------: | ----------------------: | +| Rational feasibility | 0 | 0 | 51 | 345 | 0 | 345 | +| Contradiction projection | 0 | 341 | 0 | 55 | 682 | 55 | +| Fixed-coordinate proofs | 0 | 341 | 51 | 4 | 682 | 4 | +| Coupled motion cones | 4 | 0 | 51 | 341 | 4 | 341 | +| Nearby integer search | 4 | 275 | 51 | 66 | 554 | 66 | + +Every retained search meets the three-system minimum. Contradiction projection +also supports the four determined systems' fixedness proofs; its contribution +is 51 contradictions plus four determined statuses, with overlapping dependencies. + +## Ablation of diagnostic shortcuts + +`ablate-diagnostics.mjs` restores the diagnostic classifier and shortcuts from +commit `0d92b63fd096df4cd4632115e1f770af609cc2eb` in ignored copies. It classifies +all base systems and real-map probes, checks rational proofs, then constructs +and independently checks integer witnesses using `gridWitness`. It disables +shortcuts individually and together, and repeats with current code. Counts and +changed-case lists go to `.cache/mixed-relations/diagnostic-ablation/`. +Historical raw reports remain on `archive/mixed-relations-94` at `0d92b63f`. + +| Disabled diagnostic mechanism | Determined | Underdetermined | Contradictory | Undecided | Checked integer points | Changed classifications | +| ----------------------------- | ---------: | --------------: | ------------: | --------: | ---------------------: | ----------------------: | +| None (reference) | 4 | 341 | 51 | 0 | 686 | 0 | +| Greedy coordinate retention | 4 | 341 | 51 | 0 | 686 | 0 | +| Nullspace line search | 4 | 341 | 51 | 0 | 686 | 0 | +| Nullspace plane search | 4 | 341 | 51 | 0 | 686 | 0 | +| Equality-conflict shortcut | 4 | 341 | 51 | 0 | 686 | 0 | +| Single-bound conflict search | 4 | 341 | 51 | 0 | 686 | 0 | +| All five / current | 4 | 341 | 51 | 0 | 686 | 0 | + +All five shortcuts and their dedicated controls were removed. Diagnostic +feasibility and contradiction reports now use the retained bounded projection +implementation. Independent certificate checkers remain. The historical split +between initial and additional contradictions is reproduced by the catalogue's +input analysis in `certify-projection.mjs`, rather than a second proof search. +Witness choices can differ from the archive; classifications remain equal. +There is no public export, placement integration or runtime performance claim. + +## Known gaps + +General integer solving, grid-only uniqueness and placement integration are +known gaps. Placement integration belongs to the stated-relations work after +the proposed source format is approved. diff --git a/scripts/mixed-relations/ablate-diagnostics.mjs b/scripts/mixed-relations/ablate-diagnostics.mjs new file mode 100644 index 00000000..3761f826 --- /dev/null +++ b/scripts/mixed-relations/ablate-diagnostics.mjs @@ -0,0 +1,191 @@ +// Run after npm run build. Historical shortcuts run only in ignored copies. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { classifyMixed as currentClassify } from "./classify.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; +import { gridWitness, checkGridWitness } from "./grid.mjs"; +import { checkGridVariationWitness } from "./grid-variation.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const reference = "0d92b63fd096df4cd4632115e1f770af609cc2eb"; +const destination = resolve(".cache/mixed-relations/diagnostic-ablation"); +const historical = {}; +for (const name of [ + "classify", + "feasible", + "certificate", + "line-witness", + "plane-witness", +]) { + const { stdout } = await promisify(execFile)("git", [ + "show", + `${reference}:scripts/mixed-relations/${name}.mjs`, + ]); + historical[`${name}.mjs`] = stdout; +} +function cut(source, startText, endText, replacement = "") { + const start = source.indexOf(startText); + const end = source.indexOf(endText, start); + assert(start >= 0 && end > start, startText); + return source.slice(0, start) + replacement + source.slice(end); +} +const edits = { + greedy: (s) => + cut( + s, + " const compact =", + " const proof =", + " const point = particular;\n", + ), + line: (s) => + cut( + s, + " for (const start of [point, particular]) {", + " for (const start of [point, particular]) {\n for (let i", + ), + plane: (s) => + cut( + s, + " for (const start of [point, particular]) {\n for (let i", + " const projected =", + ), + "equality-conflict": (s) => + cut(s, " const equal = attempt(rows, sources);", " for (const [edge, e]"), + "single-bound": (s) => + cut( + s, + " for (const [edge, e] of graph.edges.entries()) {", + " return null;\n}", + ), +}; +const cases = []; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + for (const probe of [{ name: "base", rows: [] }, ...probes(problem.nodes)]) + cases.push({ + name: `${id}/${axis}-${probe.name}`, + system, + rows: probe.rows, + }); + } +} +assert.equal(cases.length, 396); +const report = { reference, systems: cases.length, variants: {} }; +let baseline; +for (const variant of [ + "baseline", + ...Object.keys(edits), + "all-removed", + "current", +]) { + let classify = currentClassify; + if (variant !== "current") { + const folder = resolve(destination, variant); + mkdirSync(folder, { recursive: true }); + const sources = Object.fromEntries( + readdirSync("scripts/mixed-relations") + .filter((name) => name.endsWith(".mjs")) + .map((name) => [ + name, + readFileSync(resolve("scripts/mixed-relations", name), "utf8"), + ]), + ); + Object.assign(sources, historical); + for (const key of variant === "baseline" + ? [] + : variant === "all-removed" + ? Object.keys(edits) + : [variant]) { + const name = ["single-bound", "equality-conflict"].includes(key) + ? "certificate.mjs" + : "feasible.mjs"; + sources[name] = edits[key](sources[name]); + } + for (const [name, source] of Object.entries(sources)) + writeFileSync( + resolve(folder, name), + source.replaceAll( + '"../../dist/', + `"${pathToFileURL(resolve("dist")).href}/`, + ), + ); + classify = (await import(pathToFileURL(resolve(folder, "classify.mjs")))) + .classifyMixed; + } + const counts = { + determined: 0, + underdetermined: 0, + contradictory: 0, + undecided: 0, + checkedIntegerPoints: 0, + }; + const statuses = []; + for (const { name, system, rows } of cases) { + const result = classify(system, rows); + let status = result?.status ?? "undecided"; + if (result) + assert(checkMixedResult(system, rows, result), `${variant}: ${name}`); + if (status === "determined" || status === "underdetermined") { + const graph = normalizeRelations(system); + const first = gridWitness(graph, rows, result.point ?? result.values[0]); + if (status === "determined") { + if (first) { + assert(checkGridWitness(graph, rows, first)); + counts.checkedIntegerPoints++; + } else status = "undecided"; + } else { + const second = + first && + (gridWitness(graph, rows, result.values[1], first) ?? + gridWitness(graph, rows, first, first)); + if (second) { + assert(checkGridVariationWitness(graph, rows, [first, second])); + counts.checkedIntegerPoints += 2; + } else status = "undecided"; + } + } + counts[status]++; + statuses.push(status); + } + baseline ??= statuses; + const changed = cases.flatMap(({ name }, i) => + statuses[i] === baseline[i] ? [] : [name], + ); + report.variants[variant] = { + ...counts, + changedClassifications: changed.length, + }; + writeFileSync( + resolve(destination, `${variant}-changed.json`), + await format(JSON.stringify(changed), { parser: "json" }), + ); + console.log(variant, report.variants[variant]); +} +const text = await format(JSON.stringify(report), { parser: "json" }); +assert(text.split("\n").length <= 501); +writeFileSync(resolve(destination, "summary.json"), text); + +assert.deepEqual(report.variants.baseline, { + determined: 4, + underdetermined: 341, + contradictory: 51, + undecided: 0, + checkedIntegerPoints: 686, + changedClassifications: 0, +}); +assert.deepEqual(report.variants["all-removed"], report.variants.baseline); +assert.deepEqual(report.variants.current, report.variants.baseline); diff --git a/scripts/mixed-relations/ablate-earlier.mjs b/scripts/mixed-relations/ablate-earlier.mjs new file mode 100644 index 00000000..c938c0eb --- /dev/null +++ b/scripts/mixed-relations/ablate-earlier.mjs @@ -0,0 +1,181 @@ +// Run after npm run build. Restore only historical modules in an ignored copy; +// never change the working source, dist, recorded evidence or archive branch. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { cpSync, mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import ts from "typescript"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { solveMixedGridSystem as currentSolve } from "../../dist/layout/relations/mixed-grid-system.js"; +import { checkMixedGridSystem as currentCheck } from "../../dist/layout/relations/check-mixed-grid-system.js"; + +// Freeze the pre-ablation implementation so later removals remain reproducible. +const reference = "8c800e15e60eb670a26cc5279286be477972b3f1"; +const destination = resolve(".cache/mixed-relations/earlier-ablation"); +const edits = { + feasibility: ["mixed-feasible", "projectMixedFeasible"], + contradiction: ["mixed-contradiction", "projectMixedContradiction"], + fixed: ["mixed-fixed", "projectMixedFixed"], + "signed-basis": ["mixed-variation", "signed-basis"], + "coupled-cones": ["mixed-variation", "coupledDirections"], + "nearby-grid": ["mixed-grid", "nearbyMixedGrid"], + "second-seed-fallback": ["mixed-grid-system", "second-seed-fallback"], +}; +const modules = [...new Set(Object.values(edits).map(([name]) => name))]; +const sources = {}; +for (const name of modules) { + const { stdout } = await promisify(execFile)("git", [ + "show", + `${reference}:src/layout/relations/${name}.ts`, + ]); + sources[name] = stdout; +} +function edit(source, mechanism) { + if (mechanism === "signed-basis") { + const start = source.indexOf(" for (const direction of basis) {"); + const end = source.indexOf(" yield* coupledDirections", start); + assert(start >= 0 && end > start); + return source.slice(0, start) + source.slice(end); + } + if (mechanism === "second-seed-fallback") + return source.replace( + " ??\n nearbyMixedGrid(graph, rows, first, maxNodes, first)", + "", + ); + const file = ts.createSourceFile( + "input.ts", + source, + ts.ScriptTarget.Latest, + true, + ); + const fn = file.statements.find( + (node) => ts.isFunctionDeclaration(node) && node.name?.text === mechanism, + ); + assert(fn?.body, mechanism); + const body = mechanism === "coupledDirections" ? "{}" : "{ return null; }"; + return source.slice(0, fn.body.pos) + body + source.slice(fn.body.end); +} +const cases = []; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + for (const probe of [{ name: "base", rows: [] }, ...probes(problem.nodes)]) + cases.push({ + name: `${id}/${axis}-${probe.name}`, + system, + rows: probe.rows, + }); + } +} +assert.equal(cases.length, 396); +const report = { + reference, + systems: cases.length, + maxRows: 10_000, + maxNodes: 10_000, + variants: {}, +}; +let baseline; +const removed = ["signed-basis", "second-seed-fallback"]; +const retained = Object.keys(edits).filter((key) => !removed.includes(key)); +for (const variant of [ + "baseline", + ...Object.keys(edits), + "both-removed", + ...retained.map((key) => `cleaned-${key}`), + "current", +]) { + let solve = currentSolve; + let check = currentCheck; + if (variant !== "current") { + const folder = resolve(destination, variant); + cpSync("dist/layout/relations", folder, { recursive: true }); + const modified = { ...sources }; + const keys = + variant === "baseline" + ? [] + : variant === "both-removed" + ? removed + : variant.startsWith("cleaned-") + ? [...removed, variant.slice(8)] + : [variant]; + const changes = keys.map((key) => edits[key]); + for (const [name, mechanism] of changes) { + const before = modified[name]; + modified[name] = edit(before, mechanism); + assert.notEqual(modified[name], before, `${variant}: ${name}`); + } + for (const [name, source] of Object.entries(modified)) + writeFileSync( + resolve(folder, `${name}.js`), + ts.transpileModule(source, { + compilerOptions: { + target: ts.ScriptTarget.ES2023, + module: ts.ModuleKind.ESNext, + }, + }).outputText, + ); + solve = ( + await import(pathToFileURL(resolve(folder, "mixed-grid-system.js"))) + ).solveMixedGridSystem; + check = ( + await import(pathToFileURL(resolve(folder, "check-mixed-grid-system.js"))) + ).checkMixedGridSystem; + } + const counts = { + determined: 0, + underdetermined: 0, + contradictory: 0, + undecided: 0, + }; + let checkedIntegerPoints = 0; + const statuses = []; + for (const { name, system, rows } of cases) { + const result = solve(system, rows, report.maxRows, report.maxNodes); + const status = result?.status ?? "undecided"; + if (result) assert(check(system, rows, result), `${variant}: ${name}`); + counts[status]++; + checkedIntegerPoints += + status === "determined" ? 1 : status === "underdetermined" ? 2 : 0; + statuses.push(status); + } + baseline ??= statuses; + const changed = cases.flatMap(({ name }, i) => + statuses[i] === baseline[i] ? [] : [name], + ); + const detail = await format(JSON.stringify(changed), { parser: "json" }); + assert(detail.split("\n").length <= 501); + mkdirSync(destination, { recursive: true }); + writeFileSync(resolve(destination, `${variant}-changed.json`), detail); + report.variants[variant] = { + ...counts, + checkedIntegerPoints, + changedClassifications: changed.length, + }; +} +assert.deepEqual(report.variants.baseline, { + determined: 4, + underdetermined: 341, + contradictory: 51, + undecided: 0, + checkedIntegerPoints: 686, + changedClassifications: 0, +}); +assert.deepEqual(report.variants.current, report.variants.baseline); +assert.deepEqual(report.variants["both-removed"], report.variants.baseline); + +mkdirSync(destination, { recursive: true }); +const text = await format(JSON.stringify(report), { parser: "json" }); +assert(text.split("\n").length <= 501); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/ablate-grid.mjs b/scripts/mixed-relations/ablate-grid.mjs new file mode 100644 index 00000000..2eb27601 --- /dev/null +++ b/scripts/mixed-relations/ablate-grid.mjs @@ -0,0 +1,175 @@ +// Run after npm run build. Restore only historical modules in an ignored copy; +// never change the working source, dist, recorded evidence or archive branch. +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { promisify } from "node:util"; +import { cpSync, mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import ts from "typescript"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { solveMixedGridSystem as currentSolve } from "../../dist/layout/relations/mixed-grid-system.js"; +import { checkMixedGridSystem as currentCheck } from "../../dist/layout/relations/check-mixed-grid-system.js"; + +// Includes the odd-prime change, already present when cleanup was requested. +// The author's raw-data archive remains archive/mixed-relations-94 at 0d92b63f. +const reference = "7aaa38f1bdd4443b3b1557c1a9c3e987f95d6bd3"; +const destination = resolve(".cache/mixed-relations/grid-ablation"); +const modules = [ + "linear", + "mixed-grid-system", + "mixed-grid-result", + "check-mixed-grid-system", + "mixed-grid-line", + "mixed-grid-divisibility", + "check-mixed-grid-divisibility", + "mixed-grid-parity", + "mixed-grid-primes", +]; +const sources = {}; +for (const name of modules) { + const { stdout } = await promisify(execFile)("git", [ + "show", + `${reference}:src/layout/relations/${name}.ts`, + ]); + sources[name] = stdout; +} +const disableFunction = (name) => (source) => { + const pattern = new RegExp( + `(function ${name}\\([\\s\\S]*?\\n?\\)[^{]*\\{)[\\s\\S]*?\\n}`, + "m", + ); + assert(pattern.test(source), name); + return source.replace(pattern, "$1\n return null;\n}"); +}; +const edits = { + "primitive-line": ["mixed-grid-line", disableFunction("mixedGridLine")], + "fractional-singleton": [ + "mixed-grid-system", + (s) => + s.replace( + "result.point.some((v) => v.numerator % v.denominator !== 0n)", + "false", + ), + ], + "single-row-divisibility": [ + "mixed-grid-system", + (s) => s.replace("checkMixedGridDivisibility(graph, rows, i)", "false"), + ], + "reduced-row-divisibility": [ + "mixed-grid-divisibility", + (s) => s.replace("reducedLinearCombinations(graph.variables, rows)", "[]"), + ], + "pairwise-divisibility": [ + "mixed-grid-divisibility", + disableFunction("pairedCombination"), + ], + parity: ["mixed-grid-parity", disableFunction("mixedGridParity")], + "odd-primes": ["mixed-grid-primes", disableFunction("mixedGridOddPrimes")], +}; +const cases = []; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + for (const probe of [{ name: "base", rows: [] }, ...probes(problem.nodes)]) + cases.push({ + name: `${id}/${axis}-${probe.name}`, + system, + rows: probe.rows, + }); + } +} +assert.equal(cases.length, 396); +const report = { + reference, + systems: cases.length, + maxRows: 10_000, + maxNodes: 10_000, + variants: {}, +}; +let baseline; +for (const variant of [ + "baseline", + ...Object.keys(edits), + "all-removed", + "current", +]) { + let solve = currentSolve; + let check = currentCheck; + if (variant !== "current") { + const folder = resolve(destination, variant); + cpSync("dist/layout/relations", folder, { recursive: true }); + const modified = { ...sources }; + const changes = + variant === "all-removed" + ? Object.values(edits) + : variant === "baseline" + ? [] + : [edits[variant]]; + for (const [name, edit] of changes) { + const before = modified[name]; + modified[name] = edit(before); + assert.notEqual(modified[name], before, `${variant}: ${name}`); + } + for (const [name, source] of Object.entries(modified)) + writeFileSync( + resolve(folder, `${name}.js`), + ts.transpileModule(source, { + compilerOptions: { + target: ts.ScriptTarget.ES2023, + module: ts.ModuleKind.ESNext, + }, + }).outputText, + ); + solve = ( + await import(pathToFileURL(resolve(folder, "mixed-grid-system.js"))) + ).solveMixedGridSystem; + check = ( + await import(pathToFileURL(resolve(folder, "check-mixed-grid-system.js"))) + ).checkMixedGridSystem; + } + const counts = { + determined: 0, + underdetermined: 0, + contradictory: 0, + undecided: 0, + }; + let checkedIntegerPoints = 0; + const statuses = []; + for (const { name, system, rows } of cases) { + const result = solve(system, rows, report.maxRows, report.maxNodes); + const status = result?.status ?? "undecided"; + if (result) assert(check(system, rows, result), `${variant}: ${name}`); + counts[status]++; + checkedIntegerPoints += + status === "determined" ? 1 : status === "underdetermined" ? 2 : 0; + statuses.push(status); + } + baseline ??= statuses; + const changed = cases.flatMap(({ name }, i) => + statuses[i] === baseline[i] ? [] : [name], + ); + report.variants[variant] = { ...counts, checkedIntegerPoints, changed }; +} +assert.deepEqual(report.variants.baseline, { + determined: 4, + underdetermined: 341, + contradictory: 51, + undecided: 0, + checkedIntegerPoints: 686, + changed: [], +}); +assert.deepEqual(report.variants.current, report.variants.baseline); +assert.deepEqual(report.variants["all-removed"], report.variants.baseline); +mkdirSync(destination, { recursive: true }); +const text = await format(JSON.stringify(report), { parser: "json" }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-certificates.mjs b/scripts/mixed-relations/bounded-certificates.mjs new file mode 100644 index 00000000..ca21ee72 --- /dev/null +++ b/scripts/mixed-relations/bounded-certificates.mjs @@ -0,0 +1,75 @@ +// Rebuild first. Exercise the bounded core directly, including conflicts that +// the earlier offline classifier can prove without full projection. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { classifyMixed } from "./classify.mjs"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { checkCertificate } from "./certificate.mjs"; +import { projectMixedContradiction } from "../../dist/layout/relations/mixed-contradiction.js"; +import { checkMixedContradiction } from "../../dist/layout/relations/check-mixed-contradiction.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-certificates", +); +const maxRows = 10_000; +const summary = { + maxRows, + contradictory: 0, + checked: 0, + budgetMisses: 0, + cases: [], +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + const result = classifyMixed(system, probe.rows); + assert(result); + if (result.status !== "contradictory") continue; + summary.contradictory++; + const proof = projectMixedContradiction(graph, probe.rows, maxRows); + if (!proof) { + summary.budgetMisses++; + continue; + } + assert(checkMixedContradiction(graph, probe.rows, proof)); + assert( + checkCertificate( + graph, + probe.rows, + projectionCertificate(graph, probe.rows, maxRows), + ), + ); + summary.checked++; + let lower = 0; + let upper = maxRows; + while (lower < upper) { + const middle = Math.floor((lower + upper) / 2); + if (projectMixedContradiction(graph, probe.rows, middle)) + upper = middle; + else lower = middle + 1; + } + summary.cases.push({ + id: `${id}/${axis}-${probe.name}`, + minimumRowBudget: upper, + }); + } + } +} +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-classification.mjs b/scripts/mixed-relations/bounded-classification.mjs new file mode 100644 index 00000000..a3044581 --- /dev/null +++ b/scripts/mixed-relations/bounded-classification.mjs @@ -0,0 +1,103 @@ +// Rebuild first. Exercise complete typed classification, not offline shortcuts. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { classifyMixed as offlineClassify } from "./classify.mjs"; +import { checkMixedResult as offlineCheck } from "./check-classify.mjs"; +import { classifyMixed } from "../../dist/layout/relations/mixed-classify.js"; +import { checkMixedResult } from "../../dist/layout/relations/check-mixed-result.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-classification", +); +const maxRowsPerSearch = 10_000; +const tally = () => ({ determined: 0, underdetermined: 0, contradictory: 0 }); +const summary = { + maxRowsPerSearch, + systems: 0, + checked: 0, + budgetMisses: 0, + statuses: tally(), + profiles: {}, +}; +const packPoint = (point) => + point.map((r) => [String(r.numerator), String(r.denominator)]); +const packWeights = (weights) => + weights.flatMap((r, row) => + r.numerator === 0n + ? [] + : [{ row, weight: [String(r.numerator), String(r.denominator)] }], + ); +const packProof = (proof) => ({ + edges: packWeights(proof.bounds), + probes: packWeights(proof.equalities), +}); +function pack(result) { + switch (result.status) { + case "contradictory": + return { status: result.status, proof: packProof(result.proof) }; + case "underdetermined": + return { status: result.status, values: result.values.map(packPoint) }; + case "determined": + return { + status: result.status, + point: packPoint(result.point), + fixed: result.fixed.map((proofs) => proofs.map(packProof)), + }; + } +} +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const counts = (summary.profiles[profile] ??= tally()); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + const result = classifyMixed(graph, rows, maxRowsPerSearch); + if (!result) { + summary.budgetMisses++; + continue; + } + assert( + checkMixedResult(graph, rows, result), + `${id}/${axis}-${probe.name}`, + ); + assert( + offlineCheck(system, rows, JSON.parse(JSON.stringify(pack(result)))), + ); + assert.equal(result.status, offlineClassify(system, probe.rows)?.status); + summary.checked++; + summary.statuses[result.status]++; + counts[result.status]++; + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.checked, summary.systems); +assert.equal(summary.budgetMisses, 0); +assert.deepEqual(summary.statuses, { + determined: 4, + underdetermined: 341, + contradictory: 51, +}); +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-feasibility.mjs b/scripts/mixed-relations/bounded-feasibility.mjs new file mode 100644 index 00000000..7a8c3d70 --- /dev/null +++ b/scripts/mixed-relations/bounded-feasibility.mjs @@ -0,0 +1,93 @@ +// Rebuild first. Exercise typed feasible-point search over prepared source rows. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { classifyMixed } from "./classify.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { projectMixedFeasible } from "../../dist/layout/relations/mixed-feasible.js"; +import { checkMixedFeasible } from "../../dist/layout/relations/check-mixed-feasible.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-feasibility", +); +const maxRows = 10_000; +const summary = { + maxRows, + systems: 0, + feasible: 0, + checked: 0, + budgetMisses: 0, + contradictoryControls: 0, + largestMinimumRowBudget: 0, + largestBudgetCase: null, + profiles: {}, +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const counts = (summary.profiles[profile] ??= { + checked: 0, + budgetMisses: 0, + }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const status = classifyMixed(system, probe.rows)?.status; + assert(status); + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + const point = projectMixedFeasible(graph, rows, maxRows); + if (status === "contradictory") { + summary.contradictoryControls++; + assert.equal(point, null); + continue; + } + summary.feasible++; + if (!point) { + summary.budgetMisses++; + counts.budgetMisses++; + continue; + } + assert(checkMixedFeasible(graph, rows, point)); + const packed = point.map((v) => [ + String(v.numerator), + String(v.denominator), + ]); + assert( + checkFeasibleWitness(graph, rows, JSON.parse(JSON.stringify(packed))), + ); + summary.checked++; + counts.checked++; + let low = 0; + let high = maxRows; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (projectMixedFeasible(graph, rows, middle)) high = middle; + else low = middle + 1; + } + if (high > summary.largestMinimumRowBudget) { + summary.largestMinimumRowBudget = high; + summary.largestBudgetCase = `${id}/${axis}-${probe.name}`; + } + } + } +} +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-fixed.mjs b/scripts/mixed-relations/bounded-fixed.mjs new file mode 100644 index 00000000..44993ff7 --- /dev/null +++ b/scripts/mixed-relations/bounded-fixed.mjs @@ -0,0 +1,111 @@ +// Rebuild first. Directly exercise bounded typed fixed-coordinate proofs on +// recorded corpus cases, retaining both the typed and offline input checkers. +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; +import { projectMixedFixed } from "../../dist/layout/relations/mixed-fixed.js"; +import { checkMixedFixed } from "../../dist/layout/relations/check-mixed-fixed.js"; +import { ratio } from "../../dist/layout/relations/rational.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-fixed", +); +const maxRowsPerSign = 10_000; +const summary = { + maxRowsPerSign, + fixedCoordinates: 0, + checked: 0, + budgetMisses: 0, + largestMinimumRowBudgetPerSign: 0, + largestBudgetCase: null, + profiles: {}, +}; +const pack = (weights) => + weights.flatMap((w, row) => + w.numerator === 0n + ? [] + : [{ row, weight: [String(w.numerator), String(w.denominator)] }], + ); +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const counts = (summary.profiles[profile] ??= { + checked: 0, + budgetMisses: 0, + }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + for (const coordinate of graph.variables.keys()) { + const name = `${id}/${axis}-${probe.name}/${coordinate}`; + const file = `.cache/mixed-relations/fixed/${name}.json`; + if (!existsSync(file)) continue; + const recorded = JSON.parse(readFileSync(file, "utf8")); + const point = recorded.point.map(([n, d]) => + ratio(BigInt(n), BigInt(d)), + ); + summary.fixedCoordinates++; + const proof = projectMixedFixed( + graph, + probe.rows, + point, + coordinate, + maxRowsPerSign, + ); + if (!proof) { + summary.budgetMisses++; + counts.budgetMisses++; + continue; + } + assert(checkMixedFixed(graph, probe.rows, point, coordinate, proof)); + const packed = proof.map((p) => ({ + edges: pack(p.bounds), + probes: pack(p.equalities), + })); + assert.deepEqual(packed, recorded.proof); + assert( + checkFixedWitness( + graph, + probe.rows, + recorded.point, + coordinate, + packed, + ), + ); + summary.checked++; + counts.checked++; + let low = 0; + let high = maxRowsPerSign; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (projectMixedFixed(graph, probe.rows, point, coordinate, middle)) + high = middle; + else low = middle + 1; + } + if (high > summary.largestMinimumRowBudgetPerSign) { + summary.largestMinimumRowBudgetPerSign = high; + summary.largestBudgetCase = name; + } + } + } + } +} +assert.equal(summary.fixedCoordinates, 281); +assert.equal(summary.checked, summary.fixedCoordinates); +assert.equal(summary.budgetMisses, 0); +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-grid-system.mjs b/scripts/mixed-relations/bounded-grid-system.mjs new file mode 100644 index 00000000..d322547e --- /dev/null +++ b/scripts/mixed-relations/bounded-grid-system.mjs @@ -0,0 +1,108 @@ +// Rebuild first. Check source-system grid statuses against independently prepared rows. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { checkGridWitness } from "./grid.mjs"; +import { checkGridVariationWitness } from "./grid-variation.mjs"; +import { solveMixedGridSystem } from "../../dist/layout/relations/mixed-grid-system.js"; +import { checkMixedGridSystem } from "../../dist/layout/relations/check-mixed-grid-system.js"; +import { solveMixedSystem } from "../../dist/layout/relations/mixed-system.js"; +import { checkMixedResult } from "../../dist/layout/relations/check-mixed-result.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-grid-system", +); +const tally = () => ({ determined: 0, underdetermined: 0, contradictory: 0 }); +const summary = { + maxRowsPerSearch: 10_000, + maxNodesPerSearch: 10_000, + systems: 0, + checkedSourceResults: 0, + checkedPreparedResults: 0, + checkedIntegerPoints: 0, + unchangedRationalProofs: 0, + statuses: tally(), + profiles: {}, + undecided: [], +}; +const encode = (point) => + point.map((v) => [String(v.numerator), String(v.denominator)]); +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const counts = (summary.profiles[profile] ??= tally()); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + const name = `${id}/${axis}-${probe.name}`; + summary.systems++; + const result = solveMixedGridSystem( + system, + probe.rows, + summary.maxRowsPerSearch, + summary.maxNodesPerSearch, + ); + if (!result) { + summary.undecided.push(name); + continue; + } + assert(checkMixedGridSystem(system, probe.rows, result), name); + summary.checkedSourceResults++; + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + assert(checkMixedResult(graph, rows, result), name); + summary.checkedPreparedResults++; + const rational = solveMixedSystem( + system, + probe.rows, + summary.maxRowsPerSearch, + ); + assert.equal(result.status, rational?.status, name); + if (result.status === "underdetermined") { + assert( + checkGridVariationWitness(graph, rows, result.values.map(encode)), + name, + ); + summary.checkedIntegerPoints += 2; + } else { + assert.deepEqual(result, rational, name); + summary.unchangedRationalProofs++; + if (result.status === "determined") { + assert(checkGridWitness(graph, rows, encode(result.point)), name); + summary.checkedIntegerPoints++; + } + } + summary.statuses[result.status]++; + counts[result.status]++; + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.checkedSourceResults, summary.systems); +assert.equal(summary.checkedPreparedResults, summary.systems); +assert.equal(summary.checkedIntegerPoints, 686); +assert.equal(summary.unchangedRationalProofs, 55); +assert.deepEqual(summary.undecided, []); +assert.deepEqual(summary.statuses, { + determined: 4, + underdetermined: 341, + contradictory: 51, +}); +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-grid-variation.mjs b/scripts/mixed-relations/bounded-grid-variation.mjs new file mode 100644 index 00000000..8698e710 --- /dev/null +++ b/scripts/mixed-relations/bounded-grid-variation.mjs @@ -0,0 +1,107 @@ +// Rebuild first. Check bounded distinct integer pairs against the offline reference. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { gridWitness } from "./grid.mjs"; +import { checkGridVariationWitness } from "./grid-variation.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { solveMixedSystem } from "../../dist/layout/relations/mixed-system.js"; +import { checkMixedSystem } from "../../dist/layout/relations/check-mixed-system.js"; +import { nearbyMixedGrid } from "../../dist/layout/relations/mixed-grid.js"; +import { checkMixedGridVariation } from "../../dist/layout/relations/check-mixed-grid.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-grid-variation", +); +const summary = { + maxRowsPerSearch: 10_000, + maxNodesPerSearch: 10_000, + systems: 0, + rationalContradictions: 0, + rationalDetermined: 0, + existingPairs: 0, + constructedPairs: 0, + checked: 0, + identicalToOffline: 0, + undecided: [], +}; +const encode = (point) => + point.map((v) => [String(v.numerator), String(v.denominator)]); +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const result = solveMixedSystem( + system, + probe.rows, + summary.maxRowsPerSearch, + ); + assert(result && checkMixedSystem(system, probe.rows, result)); + if (result.status === "contradictory") { + summary.rationalContradictions++; + continue; + } + // Retain the independently prepared source equality reference. + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + if (result.status === "determined") { + summary.rationalDetermined++; + continue; + } + if (checkMixedGridVariation(graph, rows, result.values)) { + assert( + checkGridVariationWitness(graph, rows, result.values.map(encode)), + ); + summary.existingPairs++; + summary.checked++; + continue; + } + const cap = summary.maxNodesPerSearch; + const first = nearbyMixedGrid(graph, rows, result.values[0], cap); + const second = + first && + (nearbyMixedGrid(graph, rows, result.values[1], cap, first) ?? + nearbyMixedGrid(graph, rows, first, cap, first)); + if (!second) { + summary.undecided.push(`${id}/${axis}-${probe.name}`); + continue; + } + const proof = [first, second]; + assert(checkMixedGridVariation(graph, rows, proof)); + assert(checkGridVariationWitness(graph, rows, proof.map(encode))); + const referenceFirst = gridWitness(graph, rows, encode(result.values[0])); + const referenceSecond = + referenceFirst && + (gridWitness(graph, rows, encode(result.values[1]), referenceFirst) ?? + gridWitness(graph, rows, referenceFirst, referenceFirst)); + assert.deepEqual(proof.map(encode), [referenceFirst, referenceSecond]); + summary.identicalToOffline++; + summary.constructedPairs++; + summary.checked++; + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.rationalContradictions, 51); +assert.equal(summary.rationalDetermined, 4); +assert.equal(summary.checked, 341); +assert.equal(summary.identicalToOffline, summary.constructedPairs); +assert.deepEqual(summary.undecided, []); +const text = await format(JSON.stringify(summary), { parser: "json" }); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-grid.mjs b/scripts/mixed-relations/bounded-grid.mjs new file mode 100644 index 00000000..9ead0b08 --- /dev/null +++ b/scripts/mixed-relations/bounded-grid.mjs @@ -0,0 +1,89 @@ +// Rebuild first. Compare bounded typed grid search with the offline reference. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { gridWitness, checkGridWitness } from "./grid.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { solveMixedSystem } from "../../dist/layout/relations/mixed-system.js"; +import { checkMixedSystem } from "../../dist/layout/relations/check-mixed-system.js"; +import { nearbyMixedGrid } from "../../dist/layout/relations/mixed-grid.js"; +import { checkMixedGrid } from "../../dist/layout/relations/check-mixed-grid.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-grid", +); +const summary = { + maxRowsPerSearch: 10_000, + maxNodesPerSearch: 10_000, + systems: 0, + rationalContradictions: 0, + alreadyIntegral: 0, + constructed: 0, + checked: 0, + identicalToOffline: 0, + undecided: [], +}; +const encode = (point) => + point.map((v) => [String(v.numerator), String(v.denominator)]); +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const result = solveMixedSystem( + system, + probe.rows, + summary.maxRowsPerSearch, + ); + assert(result && checkMixedSystem(system, probe.rows, result)); + if (result.status === "contradictory") { + summary.rationalContradictions++; + continue; + } + // Retain the independently prepared source equality reference. + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + const point = result.point ?? result.values[0]; + const proof = nearbyMixedGrid( + graph, + rows, + point, + summary.maxNodesPerSearch, + ); + if (!proof) { + summary.undecided.push(`${id}/${axis}-${probe.name}`); + continue; + } + summary[ + checkMixedGrid(graph, rows, point) ? "alreadyIntegral" : "constructed" + ]++; + assert(checkMixedGrid(graph, rows, proof)); + assert(checkGridWitness(graph, rows, encode(proof))); + summary.checked++; + assert.deepEqual(encode(proof), gridWitness(graph, rows, encode(point))); + summary.identicalToOffline++; + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.rationalContradictions, 51); +assert.equal(summary.checked, 345); +assert.equal(summary.identicalToOffline, summary.checked); +assert.deepEqual(summary.undecided, []); +const text = await format(JSON.stringify(summary), { parser: "json" }); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-system.mjs b/scripts/mixed-relations/bounded-system.mjs new file mode 100644 index 00000000..8180e5ef --- /dev/null +++ b/scripts/mixed-relations/bounded-system.mjs @@ -0,0 +1,70 @@ +// Rebuild first. Check the source-system boundary against the earlier assembly. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { sourceEqualities } from "./feasible.mjs"; +import { solveMixedSystem } from "../../dist/layout/relations/mixed-system.js"; +import { checkMixedSystem } from "../../dist/layout/relations/check-mixed-system.js"; +import { classifyMixed } from "../../dist/layout/relations/mixed-classify.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-system", +); +const summary = { + maxRowsPerSearch: 10_000, + systems: 0, + checked: 0, + identicalProofs: 0, + statuses: { determined: 0, underdetermined: 0, contradictory: 0 }, +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const result = solveMixedSystem( + system, + probe.rows, + summary.maxRowsPerSearch, + ); + assert(result, `${id}/${axis}-${probe.name}: no conclusion`); + assert(checkMixedSystem(system, probe.rows, result)); + summary.checked++; + // The earlier JS preparation is an independent conversion reference. + const reference = classifyMixed( + graph, + [...sourceEqualities(system, graph), ...probe.rows], + summary.maxRowsPerSearch, + ); + assert.deepEqual(result, reference, `${id}/${axis}-${probe.name}`); + summary.identicalProofs++; + summary.statuses[result.status]++; + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.checked, summary.systems); +assert.equal(summary.identicalProofs, summary.systems); +assert.deepEqual(summary.statuses, { + determined: 4, + underdetermined: 341, + contradictory: 51, +}); +const text = await format(JSON.stringify(summary), { parser: "json" }); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/bounded-variation.mjs b/scripts/mixed-relations/bounded-variation.mjs new file mode 100644 index 00000000..5c9d262d --- /dev/null +++ b/scripts/mixed-relations/bounded-variation.mjs @@ -0,0 +1,97 @@ +// Rebuild first. Measure typed motion on base and prospective corpus systems. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { feasibleWitness, sourceEqualities } from "./feasible.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { projectMixedVariation } from "../../dist/layout/relations/mixed-variation.js"; +import { checkMixedVariation } from "../../dist/layout/relations/check-mixed-variation.js"; +import { ratio } from "../../dist/layout/relations/rational.js"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/bounded-variation", +); +const maxRowsPerSign = 10_000; +const summary = { + maxRowsPerSign, + systems: 0, + checked: 0, + fixedControls: 0, + withoutFeasiblePoint: 0, + budgetMisses: 0, + largestMinimumRowBudgetPerSign: 0, + largestBudgetCase: null, + profiles: {}, +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const counts = (summary.profiles[profile] ??= { checked: 0 }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + summary.systems++; + const first = feasibleWitness(system, graph, probe.rows); + if (!first) { + summary.withoutFeasiblePoint++; + continue; + } + const rows = [...sourceEqualities(system, graph), ...probe.rows]; + const point = first.map(([n, d]) => ratio(BigInt(n), BigInt(d))); + const second = projectMixedVariation(graph, rows, point, maxRowsPerSign); + const fixedControl = + id.endsWith("/sketch-required") && probe.name === "base"; + if (fixedControl) { + assert.equal(second, null); + summary.fixedControls++; + continue; + } + if (!second) { + summary.budgetMisses++; + continue; + } + assert(checkMixedVariation(graph, rows, [point, second])); + const packed = second.map((v) => [ + String(v.numerator), + String(v.denominator), + ]); + assert(checkVariationWitness(graph, probe.rows, [first, packed])); + summary.checked++; + counts.checked++; + let low = 0; + let high = maxRowsPerSign; + while (low < high) { + const middle = Math.floor((low + high) / 2); + if (projectMixedVariation(graph, rows, point, middle)) high = middle; + else low = middle + 1; + } + if (high > summary.largestMinimumRowBudgetPerSign) { + summary.largestMinimumRowBudgetPerSign = high; + summary.largestBudgetCase = `${id}/${axis}-${probe.name}`; + } + } + } +} +assert.equal(summary.systems, 396); +assert.equal(summary.checked, 341); +assert.equal(summary.fixedControls, 4); +assert.equal(summary.withoutFeasiblePoint, 51); +assert.equal(summary.budgetMisses, 0); +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/catalogue.mjs b/scripts/mixed-relations/catalogue.mjs new file mode 100644 index 00000000..b2f81d82 --- /dev/null +++ b/scripts/mixed-relations/catalogue.mjs @@ -0,0 +1,167 @@ +// Run after npm run build. Optional output directory permits independent replay. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes, auditProbe } from "./probes.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { solveRelations } from "../../dist/layout/relations/solve.js"; +import { checkRelations } from "../../dist/layout/relations/check.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; +import { relationBounds } from "../../dist/layout/relations/bounds.js"; +import { derivePositions } from "../../dist/layout/relations/derive.js"; +import { checkDerivedPositions } from "../../dist/layout/relations/check-derived.js"; +import { checkRelationBoundPaths } from "../../dist/layout/relations/check-witness.js"; + +const destination = resolve(process.argv[2] ?? ".cache/mixed-relations"); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = {}; +const cases = []; +const probeCounts = {}; +let derivedCount = 0; +let missedConflicts = 0; +let lostEqualityDimensions = 0; +for await (const { id, problem, resolved, note } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const solution = solveRelations(system); + assert(checkRelations(system, solution)); + const graph = normalizeRelations(system); + const bounds = + solution.status === "contradictory" ? null : relationBounds(graph); + if (bounds) assert(checkRelationBoundPaths(graph, bounds)); + const diagnostics = bounds + ? probes(problem.nodes).map((probe) => auditProbe(system, graph, probe)) + : []; + const requests = + bounds && problem.nodes.length >= 2 + ? [ + [1, 2], + [1, 3], + [2, 3], + ].map(([part, parts]) => ({ + id: `$derived.${part}.${parts}`, + from: problem.nodes[0].id, + to: problem.nodes[1].id, + part, + parts, + })) + : []; + const derived = bounds + ? derivePositions(solution.placements, requests) + : []; + if (bounds) + assert(checkDerivedPositions(system, solution, requests, derived)); + derivedCount += derived.length; + for (const p of diagnostics) { + probeCounts[p.mixedConclusion] = + (probeCounts[p.mixedConclusion] ?? 0) + 1; + if ( + p.currentStatus !== "contradictory" && + p.mixedConclusion === "contradictory" + ) + missedConflicts++; + if ( + p.remainderDimension !== null && + p.equalityDimensions[1] !== null && + p.remainderDimension > p.equalityDimensions[1] + ) + lostEqualityDimensions++; + } + const key = `${id}/${axis}`; + const status = bounds + ? bounds.every((b) => b.determined) + ? "determined" + : "underdetermined" + : "contradictory"; + counts[status] = (counts[status] ?? 0) + 1; + const report = { + id, + axis, + ...(note ? { note } : {}), + constraints: problem.constraints, + variables: system.variables.length, + relations: system.relations.length, + status, + // Tick bounds, not drawing units; origin and lane variables are included. + bounds: bounds?.map((b) => [b.variable, b.lower, b.upper]), + ...(bounds ? {} : { cycle: solution.cycle, sum: solution.sum }), + derived: { requests, placements: derived }, + probes: diagnostics, + }; + await write(key, report); + cases.push({ + case: key, + status, + probes: diagnostics.length, + contradictions: diagnostics.filter( + (p) => p.mixedConclusion === "contradictory", + ).length, + missedConflicts: diagnostics.filter( + (p) => + p.mixedConclusion === "contradictory" && + p.currentStatus !== "contradictory", + ).length, + lostEqualityDimensions: diagnostics.filter( + (p) => + p.remainderDimension !== null && + p.equalityDimensions[1] !== null && + p.remainderDimension > p.equalityDimensions[1], + ).length, + }); + } +} +const summary = { + cases: cases.length, + counts, + probes: cases.reduce((n, row) => n + row.probes, 0), + derivedPositionsChecked: derivedCount, + probeCounts, + missedConflicts, + lostEqualityDimensions, + profiles: Object.fromEntries( + ["book/authored", "book/benchmark", "examples/dagre", "examples/elk"].map( + (prefix) => { + const rows = cases.filter((r) => r.case.startsWith(prefix)); + return [ + prefix, + { + cases: rows.length, + probes: rows.reduce((n, r) => n + r.probes, 0), + contradictions: rows.reduce((n, r) => n + r.contradictions, 0), + missedConflicts: rows.reduce((n, r) => n + r.missedConflicts, 0), + lostEqualityDimensions: rows.reduce( + (n, r) => n + r.lostEqualityDimensions, + 0, + ), + }, + ]; + }, + ), + ), +}; +await write("summary", summary); +// One index per corpus profile keeps each evidence file small. +for (const prefix of [ + "book/authored", + "book/benchmark", + "examples/dagre", + "examples/elk", +]) + await write( + `${prefix}/index`, + cases.filter((row) => row.case.startsWith(prefix)), + ); +console.log(JSON.stringify(summary, null, 2)); diff --git a/scripts/mixed-relations/certificate.mjs b/scripts/mixed-relations/certificate.mjs new file mode 100644 index 00000000..611e73c3 --- /dev/null +++ b/scripts/mixed-relations/certificate.mjs @@ -0,0 +1,58 @@ +import { + add, + multiply, + ratio, + zero, +} from "../../dist/layout/relations/rational.js"; + +const unpack = ([n, d]) => ratio(BigInt(n), BigInt(d)); +const edgeRow = (graph, e) => ({ + kind: "linear", + terms: [ + ...(e.to ? [{ variable: graph.variables[e.to - 1], coefficient: 1 }] : []), + ...(e.from + ? [{ variable: graph.variables[e.from - 1], coefficient: -1 }] + : []), + ], + constant: e.weight, +}); + +// Independent Farkas check: nonnegative input inequalities plus signed input +// equalities must sum to 0 >= a strictly positive rational constant. +// Does not invoke elimination, fixed-coordinate substitution or the producer. +export function checkCertificate(graph, probes, proof) { + try { + if (!proof) return false; + const cells = new Map(graph.variables.map((v) => [v, zero])); + let constant = zero; + const accumulate = (row, weight) => { + for (const { variable, coefficient } of row.terms) { + if (!cells.has(variable)) throw new Error("Unknown proof variable"); + cells.set( + variable, + add( + cells.get(variable), + multiply(weight, ratio(BigInt(coefficient))), + ), + ); + } + constant = add(constant, multiply(weight, ratio(BigInt(row.constant)))); + }; + for (const { row, weight: packed } of proof.edges) { + if (!Number.isInteger(row) || !graph.edges[row]) return false; + const weight = unpack(packed); + if (weight.numerator < 0n) return false; + accumulate(edgeRow(graph, graph.edges[row]), weight); + } + for (const { row, weight } of proof.probes) { + if (!Number.isInteger(row) || !probes[row]) return false; + accumulate(probes[row], unpack(weight)); + } + return ( + constant.numerator > 0n && + [...cells.values()].every((r) => r.numerator === 0n) + ); + } catch { + return false; + } +} diff --git a/scripts/mixed-relations/certify-projection.mjs b/scripts/mixed-relations/certify-projection.mjs new file mode 100644 index 00000000..d5b12c3f --- /dev/null +++ b/scripts/mixed-relations/certify-projection.mjs @@ -0,0 +1,82 @@ +// Run after npm run build; optional output directory supports independent replay. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes, auditProbe } from "./probes.mjs"; +import { checkCertificate } from "./certificate.mjs"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { feasibleWitness } from "./feasible.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/projection-certificates", +); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + probes: 0, + existingContradictions: 0, + feasible: 0, + projectedContradictions: 0, + notDecided: 0, +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + counts.probes++; + // Preserve the historical split using the catalogue, not a second solver. + if ( + auditProbe(system, graph, probe).mixedConclusion === "contradictory" + ) { + const proof = projectionCertificate(graph, probe.rows); + assert(checkCertificate(graph, probe.rows, proof)); + counts.existingContradictions++; + continue; + } + const witness = feasibleWitness(system, graph, probe.rows); + if (witness) { + assert(checkFeasibleWitness(graph, probe.rows, witness)); + counts.feasible++; + continue; + } + const proof = projectionCertificate(graph, probe.rows); + if (!proof) { + counts.notDecided++; + continue; + } + assert( + checkCertificate(graph, probe.rows, proof), + `${id}/${axis}/${probe.name}`, + ); + counts.projectedContradictions++; + // Sparse weights refer to the normalized input graph, rebuilt on replay. + // Include source names and exact bound rows so a reader can inspect them. + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + rows: probe.rows, + proof, + bounds: proof.edges.map(({ row }) => ({ row, ...graph.edges[row] })), + }); + } + } +} +await write("summary", counts); +console.log(JSON.stringify(counts, null, 2)); diff --git a/scripts/mixed-relations/certify.mjs b/scripts/mixed-relations/certify.mjs new file mode 100644 index 00000000..a7338e46 --- /dev/null +++ b/scripts/mixed-relations/certify.mjs @@ -0,0 +1,65 @@ +// Run after npm run build; optional output directory supports independent replay. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { probes, auditProbe } from "./probes.mjs"; +import { checkCertificate } from "./certificate.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/certificates", +); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + probes: 0, + contradictions: 0, + certified: 0, + missedBySubstitution: 0, +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + counts.probes++; + const audit = auditProbe(system, graph, probe); + if (audit.mixedConclusion !== "contradictory") continue; + counts.contradictions++; + const proof = projectionCertificate(graph, probe.rows); + assert( + checkCertificate(graph, probe.rows, proof), + `${id}/${axis}/${probe.name}`, + ); + counts.certified++; + if (audit.currentStatus !== "contradictory") + counts.missedBySubstitution++; + // Sparse weights refer to the normalized input graph, rebuilt on replay. + // Include source names and exact bound rows so a reader can inspect them. + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + rows: probe.rows, + proof, + bounds: proof.edges.map(({ row }) => ({ row, ...graph.edges[row] })), + }); + } + } +} +await write("summary", counts); +console.log(JSON.stringify(counts, null, 2)); diff --git a/scripts/mixed-relations/check-classify.mjs b/scripts/mixed-relations/check-classify.mjs new file mode 100644 index 00000000..ab6811df --- /dev/null +++ b/scripts/mixed-relations/check-classify.mjs @@ -0,0 +1,31 @@ +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; +import { checkCertificate } from "./certificate.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; + +// Check every conclusion against input rows, without any producer/search call. +export function checkMixedResult(system, rows, result) { + try { + const graph = normalizeRelations(system); + switch (result?.status) { + case "contradictory": + return checkCertificate(graph, rows, result.proof); + case "underdetermined": + return checkVariationWitness(graph, rows, result.values); + case "determined": + return ( + checkFeasibleWitness(graph, rows, result.point) && + Array.isArray(result.fixed) && + result.fixed.length === graph.variables.length && + graph.variables.every((_, i) => + checkFixedWitness(graph, rows, result.point, i, result.fixed[i]), + ) + ); + default: + return false; + } + } catch { + return false; + } +} diff --git a/scripts/mixed-relations/check-feasible.mjs b/scripts/mixed-relations/check-feasible.mjs new file mode 100644 index 00000000..4b7409c1 --- /dev/null +++ b/scripts/mixed-relations/check-feasible.mjs @@ -0,0 +1,50 @@ +import { + add, + multiply, + negate, + ratio, + zero, +} from "../../dist/layout/relations/rational.js"; + +function unpack(pair) { + if ( + !Array.isArray(pair) || + pair.length !== 2 || + !pair.every((v) => typeof v === "string" && /^-?\d+$/.test(v)) || + BigInt(pair[1]) <= 0n + ) + throw new Error("Invalid rational"); + return ratio(BigInt(pair[0]), BigInt(pair[1])); +} + +// Independent exact substitution into INPUT rows. No equality solver, compact +// placement, nullspace or producer metadata is needed to accept a witness. +export function checkFeasibleWitness(graph, rows, proof) { + try { + if (!Array.isArray(proof) || proof.length !== graph.variables.length) + return false; + const values = proof.map(unpack); + const vertices = [zero, ...values]; + for (const edge of graph.edges) { + const gap = add(vertices[edge.to], negate(vertices[edge.from])); + if (gap.numerator < BigInt(edge.weight) * gap.denominator) return false; + } + const index = new Map(graph.variables.map((v, i) => [v, i])); + return rows.every((row) => { + const left = row.terms.reduce( + (sum, term) => + add( + sum, + multiply( + ratio(BigInt(term.coefficient)), + values[index.get(term.variable)], + ), + ), + zero, + ); + return left.numerator === BigInt(row.constant) * left.denominator; + }); + } catch { + return false; + } +} diff --git a/scripts/mixed-relations/check-fixed.mjs b/scripts/mixed-relations/check-fixed.mjs new file mode 100644 index 00000000..fc13b990 --- /dev/null +++ b/scripts/mixed-relations/check-fixed.mjs @@ -0,0 +1,51 @@ +import { + add, + negate, + ratio, + zero, +} from "../../dist/layout/relations/rational.js"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { checkCertificate } from "./certificate.mjs"; + +// Reconstruct from input and a checked point, never producer tight-row metadata. +// Every difference of feasible points obeys these homogeneous tight bounds. +export function motionCone(graph, rows, point, coordinate, sign) { + const values = [zero, ...point.map(([n, d]) => ratio(BigInt(n), BigInt(d)))]; + const edges = graph.edges + .filter(({ from, to, weight }) => { + const gap = add(values[to], negate(values[from])); + return gap.numerator === BigInt(weight) * gap.denominator; + }) + .map((edge) => ({ ...edge, weight: 0 })); + edges.push({ + from: sign === 1 ? 0 : coordinate + 1, + to: sign === 1 ? coordinate + 1 : 0, + weight: 1, + }); + return { + graph: { ...graph, edges }, + rows: rows.map((row) => ({ ...row, constant: 0 })), + }; +} + +// Both signs must be impossible. A nonzero coordinate motion can always be +// positively rescaled to magnitude >= 1 in this homogeneous cone. +export function checkFixedWitness(graph, rows, point, coordinate, proof) { + try { + if ( + !Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length || + !Array.isArray(proof) || + proof.length !== 2 || + !checkFeasibleWitness(graph, rows, point) + ) + return false; + return [1, -1].every((sign, i) => { + const cone = motionCone(graph, rows, point, coordinate, sign); + return checkCertificate(cone.graph, cone.rows, proof[i]); + }); + } catch { + return false; + } +} diff --git a/scripts/mixed-relations/check-variation.mjs b/scripts/mixed-relations/check-variation.mjs new file mode 100644 index 00000000..6e79f6ce --- /dev/null +++ b/scripts/mixed-relations/check-variation.mjs @@ -0,0 +1,26 @@ +import { checkFeasibleWitness } from "./check-feasible.mjs"; + +// Two distinct input-feasible points certify a nonzero finite shift. This +// checker needs neither a basis nor any information from the search. +// Supplying a coordinate requires that coordinate itself to differ. +export function checkVariationWitness(graph, rows, proof, coordinate) { + if ( + coordinate !== undefined && + (!Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length) + ) + return false; + if (!Array.isArray(proof) || proof.length !== 2) return false; + const [first, second] = proof; + if ( + !checkFeasibleWitness(graph, rows, first) || + !checkFeasibleWitness(graph, rows, second) + ) + return false; + return first.some( + ([n, d], i) => + (coordinate === undefined || coordinate === i) && + BigInt(n) * BigInt(second[i][1]) !== BigInt(second[i][0]) * BigInt(d), + ); +} diff --git a/scripts/mixed-relations/classification.mjs b/scripts/mixed-relations/classification.mjs new file mode 100644 index 00000000..9f2e660a --- /dev/null +++ b/scripts/mixed-relations/classification.mjs @@ -0,0 +1,66 @@ +// Run after npm run build; all proof searches remain offline. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { classifyMixed } from "./classify.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/classification", +); +const tally = () => ({ + determined: 0, + underdetermined: 0, + contradictory: 0, + undecided: 0, +}); +const summary = { + systems: 0, + base: tally(), + probes: tally(), + profiles: {}, + determinedCases: [], +}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const totals = (summary.profiles[profile] ??= { + base: tally(), + probes: tally(), + }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + for (const { name, rows } of [ + { name: "base", rows: [] }, + ...probes(problem.nodes), + ]) { + const result = classifyMixed(system, rows); + // JSON roundtrip also tests that no BigInt or implicit metadata is needed. + if (result) + assert( + checkMixedResult(system, rows, JSON.parse(JSON.stringify(result))), + ); + const status = result?.status ?? "undecided"; + const group = name === "base" ? "base" : "probes"; + summary.systems++; + summary[group][status]++; + totals[group][status]++; + if (status === "determined") + summary.determinedCases.push(`${id}/${axis}-${name}`); + } + } +} +assert.equal(summary.systems, 396); +const text = await format(JSON.stringify(summary), { parser: "json" }); +assert(text.split("\n").length <= 501); +mkdirSync(destination, { recursive: true }); +writeFileSync(resolve(destination, "summary.json"), text); +console.log(text); diff --git a/scripts/mixed-relations/classify.mjs b/scripts/mixed-relations/classify.mjs new file mode 100644 index 00000000..9c974f44 --- /dev/null +++ b/scripts/mixed-relations/classify.mjs @@ -0,0 +1,30 @@ +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; +import { feasibleWitness } from "./feasible.mjs"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { variationWitness } from "./variation.mjs"; +import { fixedWitness } from "./fixed.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; + +// Offline rational classification: projection may grow exponentially. Null +// means no checked result; failed searches never imply a mathematical status. +export function classifyMixed(system, rows) { + const graph = normalizeRelations(system); + const point = feasibleWitness(system, graph, rows); + let result; + if (!point) { + const proof = projectionCertificate(graph, rows); + result = { status: "contradictory", proof }; + } else { + const second = variationWitness(system, graph, rows, point); + result = second + ? { status: "underdetermined", values: [point, second] } + : { + status: "determined", + point, + fixed: graph.variables.map((_, i) => + fixedWitness(graph, rows, point, i), + ), + }; + } + return checkMixedResult(system, rows, result) ? result : null; +} diff --git a/scripts/mixed-relations/corpus.mjs b/scripts/mixed-relations/corpus.mjs new file mode 100644 index 00000000..deb23d59 --- /dev/null +++ b/scripts/mixed-relations/corpus.mjs @@ -0,0 +1,75 @@ +import { bookMaps, exampleMaps, stripGeometry } from "../comparison/maps.mjs"; +import { buildProblem } from "../../dist/layout/build-problem.js"; +import { measureLabel } from "../../dist/layout/measure.js"; +import { layout } from "../../dist/layout/index.js"; +import { dagreEngine } from "../../dist/layout/dagre.js"; +import { elkEngine } from "../../dist/layout/elk.js"; + +function benchmarkHints(problem, resolved) { + const groups = new Map(); + for (const { id } of problem.nodes) { + const box = resolved.nodes[id].box; + const center = box[1] + box[3] / 2; + groups.set(center, [...(groups.get(center) ?? []), id]); + } + const first = problem.nodes[0].id; + const box = resolved.nodes[first].box; + return [ + { + kind: "pin", + node: first, + position: [box[0] + box[2] / 2, box[1] + box[3] / 2], + strength: "required", + path: "research.pin-first", + }, + ...[...groups.values()] + .filter((nodes) => nodes.length > 1) + .map((nodes, i) => ({ + kind: "sameRank", + nodes, + strength: "required", + path: `research.same-rank[${i}]`, + })), + ]; +} + +export async function* corpus() { + for (const { id, manual, note } of bookMaps()) { + const source = stripGeometry(manual); + const problem = buildProblem(source, measureLabel); + yield { id: `book/authored/${id}`, problem, resolved: manual, note }; + yield { + id: `book/benchmark/${id}`, + problem: { + ...problem, + constraints: [ + ...problem.constraints, + ...benchmarkHints(problem, manual), + ], + }, + resolved: manual, + note, + }; + } + for (const { id, source } of exampleMaps()) + for (const engine of [dagreEngine, elkEngine]) + yield { + id: `examples/${engine.name}/${id}`, + problem: buildProblem(source, measureLabel), + resolved: await layout(source, engine), + }; +} + +export function geometry(resolved) { + return { + nodes: Object.fromEntries( + Object.entries(resolved.nodes).map(([id, node]) => [id, node.box]), + ), + lanes: Object.fromEntries( + Object.entries(resolved.lanes).map(([id, lane]) => [ + id, + [lane.x, lane.y, lane.w, lane.h], + ]), + ), + }; +} diff --git a/scripts/mixed-relations/feasibility.mjs b/scripts/mixed-relations/feasibility.mjs new file mode 100644 index 00000000..2686a441 --- /dev/null +++ b/scripts/mixed-relations/feasibility.mjs @@ -0,0 +1,84 @@ +// Run after npm run build; optional output directory supports independent replay. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes, auditProbe } from "./probes.mjs"; +import { feasibleWitness } from "./feasible.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/feasibility", +); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + probes: 0, + contradictory: 0, + feasible: 0, + fractionalWitnesses: 0, + notDecided: 0, +}; +const profiles = {}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const totals = (profiles[profile] ??= { + contradictory: 0, + feasible: 0, + notDecided: 0, + }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + counts.probes++; + const audit = auditProbe(system, graph, probe); + const proof = feasibleWitness(system, graph, probe.rows); + if (audit.mixedConclusion === "contradictory") { + assert.equal( + proof, + null, + `${id}/${axis}/${probe.name}: conflicting witness`, + ); + counts.contradictory++; + totals.contradictory++; + } else if (proof) { + assert( + checkFeasibleWitness(graph, probe.rows, proof), + `${id}/${axis}/${probe.name}`, + ); + counts.feasible++; + totals.feasible++; + if (proof.some(([, d]) => d !== "1")) counts.fractionalWitnesses++; + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + conclusion: "feasible-over-rationals", + rows: probe.rows, + variables: graph.variables, + values: proof, + }); + } else { + counts.notDecided++; + totals.notDecided++; + } + } + } +} +const summary = { ...counts, profiles }; +await write("summary", summary); +console.log(JSON.stringify(summary, null, 2)); diff --git a/scripts/mixed-relations/feasible.mjs b/scripts/mixed-relations/feasible.mjs new file mode 100644 index 00000000..4d8f175d --- /dev/null +++ b/scripts/mixed-relations/feasible.mjs @@ -0,0 +1,45 @@ +import { solveLinearEqualities } from "../../dist/layout/relations/linear.js"; +import { projectWitness } from "./project-witness.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; + +const pack = (values) => + values.map((r) => [String(r.numerator), String(r.denominator)]); +export function sourceEqualities(system, graph) { + const equalIds = new Set( + system.relations.filter((r) => r.kind === "equal").map((r) => r.id), + ); + return graph.edges + .filter( + (e) => + !e.source.reverse && + (e.source.kind === "anchor" || equalIds.has(e.source.id)), + ) + .map((e) => ({ + kind: "linear", + terms: [ + ...(e.to + ? [{ variable: graph.variables[e.to - 1], coefficient: 1 }] + : []), + ...(e.from + ? [{ variable: graph.variables[e.from - 1], coefficient: -1 }] + : []), + ], + constant: e.weight, + })); +} + +// Exact bounded projection in the source equality nullspace. Null carries no +// infeasibility or uniqueness claim; every returned point is checked separately. +export function feasibleWitness(system, graph, probes) { + const rows = [...sourceEqualities(system, graph), ...probes]; + const result = solveLinearEqualities(graph.variables, rows); + if (result.status === "contradictory") return null; + const basis = result.status === "underdetermined" ? result.basis : []; + const particular = result.values ?? result.particular; + const proof = pack(particular); + if (checkFeasibleWitness(graph, probes, proof)) return proof; + const projected = projectWitness(graph, particular, basis); + return projected && checkFeasibleWitness(graph, probes, projected) + ? projected + : null; +} diff --git a/scripts/mixed-relations/fixed-coordinates.mjs b/scripts/mixed-relations/fixed-coordinates.mjs new file mode 100644 index 00000000..9ba8a3bd --- /dev/null +++ b/scripts/mixed-relations/fixed-coordinates.mjs @@ -0,0 +1,88 @@ +// Run after npm run build. Read existing points; never rewrite earlier evidence. +import assert from "node:assert/strict"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { fixedWitness } from "./fixed.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve(process.argv[2] ?? ".cache/mixed-relations/fixed"); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + systems: 0, + coordinates: 0, + fixed: 0, + moving: 0, + undecided: 0, +}; +const profiles = {}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const totals = (profiles[profile] ??= { fixed: 0, moving: 0, undecided: 0 }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + const name = `${id}/${axis}-${probe.name}`; + let pair; + try { + pair = JSON.parse( + readFileSync( + `.cache/mixed-relations/variations/${name}.json`, + "utf8", + ), + ).values; + } catch (error) { + if (error.code === "ENOENT") continue; // Contradictory: no point pair. + throw error; + } + assert(checkVariationWitness(graph, probe.rows, pair)); + counts.systems++; + for (const [coordinate, variable] of graph.variables.entries()) { + counts.coordinates++; + const moved = + BigInt(pair[0][coordinate][0]) * BigInt(pair[1][coordinate][1]) !== + BigInt(pair[1][coordinate][0]) * BigInt(pair[0][coordinate][1]); + const proof = moved + ? null + : fixedWitness(graph, probe.rows, pair[0], coordinate); + const status = moved ? "moving" : proof ? "fixed" : "undecided"; + counts[status]++; + totals[status]++; + if (!proof) continue; + assert( + checkFixedWitness(graph, probe.rows, pair[0], coordinate, proof), + ); + await write(`${name}/${coordinate}`, { + id, + axis, + probe: probe.name, + variable, + coordinate, + conclusion: "fixed-over-rationals", + point: pair[0], + proof, + }); + } + } + } +} +assert.equal(counts.systems, 209); +await write("summary", { ...counts, profiles }); +console.log(JSON.stringify({ ...counts, profiles }, null, 2)); diff --git a/scripts/mixed-relations/fixed.mjs b/scripts/mixed-relations/fixed.mjs new file mode 100644 index 00000000..326cfd07 --- /dev/null +++ b/scripts/mixed-relations/fixed.mjs @@ -0,0 +1,28 @@ +import { projectMixedFixed } from "../../dist/layout/relations/mixed-fixed.js"; +import { checkMixedFixed } from "../../dist/layout/relations/check-mixed-fixed.js"; +import { ratio } from "../../dist/layout/relations/rational.js"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; + +// Preserve the diagnostic JSON contract; each signed search has its own cap. +// Null means no checked proof, including budget exhaustion, never motion. +export function fixedWitness(graph, rows, point, coordinate, maxRows = 10_000) { + if (!checkFeasibleWitness(graph, rows, point)) return null; + const values = point.map(([n, d]) => ratio(BigInt(n), BigInt(d))); + const proof = projectMixedFixed(graph, rows, values, coordinate, maxRows); + if (!proof || !checkMixedFixed(graph, rows, values, coordinate, proof)) + return null; + const pack = (weights) => + weights.flatMap((w, row) => + w.numerator === 0n + ? [] + : [{ row, weight: [String(w.numerator), String(w.denominator)] }], + ); + const packed = proof.map((p) => ({ + edges: pack(p.bounds), + probes: pack(p.equalities), + })); + return checkFixedWitness(graph, rows, point, coordinate, packed) + ? packed + : null; +} diff --git a/scripts/mixed-relations/grid-feasibility.mjs b/scripts/mixed-relations/grid-feasibility.mjs new file mode 100644 index 00000000..f10590d3 --- /dev/null +++ b/scripts/mixed-relations/grid-feasibility.mjs @@ -0,0 +1,73 @@ +// Rebuild first. Only new integer points are written; older evidence is untouched. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { classifyMixed } from "./classify.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; +import { gridWitness, checkGridWitness } from "./grid.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve(process.argv[2] ?? ".cache/mixed-relations/grid"); +const summary = { + probes: 0, + rationalContradictions: 0, + existingIntegerPoints: 0, + addedIntegerPoints: 0, + gridUndecided: 0, +}; +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + summary.probes++; + const result = classifyMixed(system, probe.rows); + assert(checkMixedResult(system, probe.rows, result)); + if (result.status === "contradictory") { + summary.rationalContradictions++; + continue; + } + const point = result.point ?? result.values[0]; + if (checkGridWitness(graph, probe.rows, point)) { + summary.existingIntegerPoints++; + continue; + } + const proof = gridWitness(graph, probe.rows, point); + if (!proof) { + summary.gridUndecided++; + continue; + } + assert( + checkGridWitness(graph, probe.rows, JSON.parse(JSON.stringify(proof))), + ); + summary.addedIntegerPoints++; + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + conclusion: "feasible-on-integer-ticks", + rows: probe.rows, + variables: graph.variables, + values: proof, + }); + } + } +} +await write("summary", summary); +console.log(JSON.stringify(summary, null, 2)); diff --git a/scripts/mixed-relations/grid-variation.mjs b/scripts/mixed-relations/grid-variation.mjs new file mode 100644 index 00000000..9d780e2b --- /dev/null +++ b/scripts/mixed-relations/grid-variation.mjs @@ -0,0 +1,12 @@ +import { checkGridWitness } from "./grid.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; + +// Independent substitution, integrality and distinctness, without search calls. +export function checkGridVariationWitness(graph, rows, proof) { + return ( + Array.isArray(proof) && + proof.length === 2 && + proof.every((point) => checkGridWitness(graph, rows, point)) && + checkVariationWitness(graph, rows, proof) + ); +} diff --git a/scripts/mixed-relations/grid-variations.mjs b/scripts/mixed-relations/grid-variations.mjs new file mode 100644 index 00000000..b6713728 --- /dev/null +++ b/scripts/mixed-relations/grid-variations.mjs @@ -0,0 +1,82 @@ +// Rebuild first. Record only pairs not already integral in the rational reports. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { classifyMixed } from "./classify.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; +import { gridWitness } from "./grid.mjs"; +import { checkGridVariationWitness } from "./grid-variation.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/grid-variations", +); +const summary = { + probes: 0, + rationalContradictions: 0, + existingGridPairs: 0, + addedGridPairs: 0, + gridVariationUndecided: 0, +}; +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + summary.probes++; + const result = classifyMixed(system, probe.rows); + assert(checkMixedResult(system, probe.rows, result)); + if (result.status === "contradictory") { + summary.rationalContradictions++; + continue; + } + if (checkGridVariationWitness(graph, probe.rows, result.values)) { + summary.existingGridPairs++; + continue; + } + const first = gridWitness( + graph, + probe.rows, + result.point ?? result.values[0], + ); + const second = + first && + (gridWitness(graph, probe.rows, result.values?.[1] ?? first, first) ?? + gridWitness(graph, probe.rows, first, first)); + if (!second) { + summary.gridVariationUndecided++; + continue; + } + const values = JSON.parse(JSON.stringify([first, second])); + assert(checkGridVariationWitness(graph, probe.rows, values)); + summary.addedGridPairs++; + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + conclusion: "two-distinct-integer-tick-solutions", + rows: probe.rows, + variables: graph.variables, + values, + }); + } + } +} +await write("summary", summary); +console.log(JSON.stringify(summary, null, 2)); diff --git a/scripts/mixed-relations/grid.mjs b/scripts/mixed-relations/grid.mjs new file mode 100644 index 00000000..d8e23321 --- /dev/null +++ b/scripts/mixed-relations/grid.mjs @@ -0,0 +1,91 @@ +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; + +// Independent input substitution plus integrality; no search metadata is used. +export function checkGridWitness(graph, rows, point) { + try { + return ( + checkFeasibleWitness(graph, rows, point) && + point.every(([n, d]) => BigInt(n) % BigInt(d) === 0n) + ); + } catch { + return false; + } +} + +function nearbyDomains(point) { + return point.map(([n, d]) => { + const numerator = BigInt(n); + const denominator = BigInt(d); + const quotient = numerator / denominator; + const floor = quotient - (numerator % denominator < 0n ? 1n : 0n); + const ceil = floor + (numerator % denominator !== 0n ? 1n : 0n); + return [...new Set([floor, ceil, floor - 1n, ceil + 1n])]; + }); +} + +function inputConstraints(graph, rows) { + const index = new Map(graph.variables.map((v, i) => [v, i + 1])); + return [ + ...graph.edges.map((e) => ({ + terms: [ + [e.to, 1n], + [e.from, -1n], + ], + constant: BigInt(e.weight), + equality: false, + })), + ...rows.map((r) => ({ + terms: r.terms.map((t) => [index.get(t.variable), BigInt(t.coefficient)]), + constant: BigInt(r.constant), + equality: true, + })), + ]; +} + +function canComplete(constraints, values, ranges) { + return constraints.every(({ terms, constant, equality }) => { + let min = 0n; + let max = 0n; + for (const [i, coefficient] of terms) { + const [low, high] = + values[i] === null ? ranges[i] : [values[i], values[i]]; + min += coefficient * (coefficient >= 0n ? low : high); + max += coefficient * (coefficient >= 0n ? high : low); + } + return max >= constant && (!equality || min <= constant); + }); +} + +// Finite local search only: floor-1 through ceil+1 in integer ticks. Failure +// proves nothing about grid feasibility elsewhere. Cost can be exponential. +// An optional excluded grid point asks for a distinct point in that neighborhood. +export function gridWitness(graph, rows, point, excluded) { + if (!checkFeasibleWitness(graph, rows, point)) return null; + if (excluded !== undefined && !checkGridWitness(graph, rows, excluded)) + return null; + const accept = (proof) => + checkGridWitness(graph, rows, proof) && + (excluded === undefined || + checkVariationWitness(graph, rows, [excluded, proof])); + if (accept(point)) return point; + const domains = nearbyDomains(point); + const constraints = inputConstraints(graph, rows); + const values = [0n, ...graph.variables.map(() => null)]; + const ranges = [[0n, 0n], ...domains.map((d) => [d.at(-2), d.at(-1)])]; + function search(i) { + if (!canComplete(constraints, values, ranges)) return null; + if (i === values.length) { + const proof = values.slice(1).map((n) => [String(n), "1"]); + return accept(proof) ? proof : null; + } + for (const value of domains[i - 1]) { + values[i] = value; + const proof = search(i + 1); + if (proof) return proof; + } + values[i] = null; + return null; + } + return search(1); +} diff --git a/scripts/mixed-relations/moving-coordinates.mjs b/scripts/mixed-relations/moving-coordinates.mjs new file mode 100644 index 00000000..2876dad8 --- /dev/null +++ b/scripts/mixed-relations/moving-coordinates.mjs @@ -0,0 +1,128 @@ +// Run after npm run build. Earlier evidence is read and independently checked. +import assert from "node:assert/strict"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { variationWitness } from "./variation.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve(process.argv[2] ?? ".cache/mixed-relations/moving"); +const previous = ".cache/mixed-relations"; +function read(file) { + try { + return JSON.parse(readFileSync(file, "utf8")); + } catch (error) { + if (error.code === "ENOENT") return null; + throw error; + } +} +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + systems: 0, + coordinates: 0, + fixed: 0, + moving: 0, + undecided: 0, + addedWitnesses: 0, +}; +const profiles = {}; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const totals = (profiles[profile] ??= { fixed: 0, moving: 0, undecided: 0 }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + const name = `${id}/${axis}-${probe.name}`; + const earlier = read(`${previous}/variations/${name}.json`); + if (!earlier) continue; // Contradictory probes have no feasible pair. + const pair = earlier.values; + assert(checkVariationWitness(graph, probe.rows, pair)); + counts.systems++; + const pending = new Set(); + const record = (status) => { + counts[status]++; + totals[status]++; + }; + for (const coordinate of graph.variables.keys()) { + counts.coordinates++; + const fixed = read(`${previous}/fixed/${name}/${coordinate}.json`); + if (fixed) { + assert.equal(fixed.coordinate, coordinate); + assert( + checkFixedWitness( + graph, + probe.rows, + fixed.point, + coordinate, + fixed.proof, + ), + ); + record("fixed"); + } else if (checkVariationWitness(graph, probe.rows, pair, coordinate)) { + record("moving"); + } else pending.add(coordinate); + } + // One checked pair may show motion in several pending coordinates. Save + // it once, listing only coordinates whose motion is independently checked. + for (const coordinate of pending) { + const second = variationWitness( + system, + graph, + probe.rows, + pair[0], + coordinate, + ); + if (!second) { + pending.delete(coordinate); + record("undecided"); + continue; + } + const values = [pair[0], second]; + assert(checkVariationWitness(graph, probe.rows, values, coordinate)); + const coordinates = [...pending].filter((i) => + checkVariationWitness(graph, probe.rows, values, i), + ); + assert(coordinates.includes(coordinate)); + await write(`${name}/${coordinate}`, { + id, + axis, + probe: probe.name, + coordinate, + coordinates, + variables: graph.variables, + conclusion: "moving-over-rationals", + values, + }); + counts.addedWitnesses++; + for (const i of coordinates) { + pending.delete(i); + record("moving"); + } + } + } + } +} +assert.equal(counts.systems, 209); +assert.equal( + counts.coordinates, + counts.fixed + counts.moving + counts.undecided, +); +await write("summary", { ...counts, profiles }); +console.log(JSON.stringify({ ...counts, profiles }, null, 2)); diff --git a/scripts/mixed-relations/probes.mjs b/scripts/mixed-relations/probes.mjs new file mode 100644 index 00000000..f4e8ae2f --- /dev/null +++ b/scripts/mixed-relations/probes.mjs @@ -0,0 +1,123 @@ +import assert from "node:assert/strict"; +import { solveLinearEqualities } from "../../dist/layout/relations/linear.js"; +import { checkLinearEqualities } from "../../dist/layout/relations/check-linear.js"; +import { + solveWithDifferences, + substituteDeterminedLinear, +} from "../../dist/layout/relations/linear-differences.js"; +import { add, multiply, ratio } from "../../dist/layout/relations/rational.js"; + +const equation = (terms, constant = 0) => ({ kind: "linear", terms, constant }); +const term = (variable, coefficient) => ({ variable, coefficient }); + +// These are prospective constraints on existing boxes, NOT authored intent or +// the scalar output-only derivations currently supported by derivePositions. +export function probes(nodes) { + const ids = nodes.map((n) => n.id); + const midpoint = (a, b, c) => equation([term(a, 1), term(b, -2), term(c, 1)]); + return [ + ...(ids.length >= 3 + ? [{ name: "midpoint", rows: [midpoint(...ids.slice(0, 3))] }] + : []), + ...(ids.length >= 4 + ? [ + { + name: "equal-spacing", + rows: [midpoint(...ids.slice(0, 3)), midpoint(...ids.slice(1, 4))], + }, + ] + : []), + ]; +} + +function equalityRows(system, graph) { + return graph.edges + .filter( + (e) => + !e.source.reverse && + (e.source.kind === "anchor" || + system.relations.find((r) => r.id === e.source.id)?.kind === "equal"), + ) + .map((e) => + equation( + [ + ...(e.to ? [term(graph.variables[e.to - 1], 1)] : []), + ...(e.from ? [term(graph.variables[e.from - 1], -1)] : []), + ], + e.weight, + ), + ); +} + +function checkedSolve(variables, rows) { + const result = solveLinearEqualities(variables, rows); + assert(checkLinearEqualities(variables, rows, result)); + return result; +} + +function violates(graph, result) { + if (result.status === "contradictory") return null; + const values = [ratio(0n), ...(result.values ?? result.particular)]; + const basis = (result.basis ?? []).map((v) => [ratio(0n), ...v]); + return graph.edges + .filter((e) => { + // An inequality is impossible if EVERY exact equality solution has + // this same, insufficient gap. A single bad particular is not enough. + const fixedGap = basis.every((v) => { + const gap = add(v[e.to], multiply(ratio(-1n), v[e.from])); + return gap.numerator === 0n; + }); + const gap = add(values[e.to], multiply(ratio(-1n), values[e.from])); + return fixedGap && gap.numerator < BigInt(e.weight) * gap.denominator; + }) + .map((e) => e.source); +} + +export function auditProbe(system, graph, probe) { + const remainder = substituteDeterminedLinear(system, probe.rows); + const current = solveWithDifferences(system, probe.rows); + const equalities = [ + ...equalityRows(system, graph), + ...Object.entries(remainder.fixed).map(([id, ticks]) => + equation([term(id, 1)], ticks), + ), + ]; + const before = checkedSolve(graph.variables, equalities); + const combined = checkedSolve(graph.variables, [ + ...equalities, + ...probe.rows, + ]); + const free = new Set(remainder.variables); + const support = new Set( + probe.rows.flatMap((r) => r.terms.map((t) => t.variable)), + ); + const violations = violates(graph, combined); + return { + name: probe.name, + rows: probe.rows, + freeSupport: [...support].filter((id) => free.has(id)), + coupling: system.relations + .filter((r) => support.has(r.from) || support.has(r.to)) + .map((r) => [r.id, r.kind, r.from, r.to]), + currentStatus: current.status, + remainderStatus: current.certificate.status, + remainderDimension: + current.certificate.status === "contradictory" + ? null + : (current.certificate.basis?.length ?? 0), + withDifferenceEqualities: combined.status, + equalityDimensions: [before, combined].map((r) => + r.status === "contradictory" ? null : (r.basis?.length ?? 0), + ), + // A contradiction in the equality subset proves a mixed contradiction. + // Fixed gaps can refute an inequality even with other coordinates free. + // Absence of such a gap does not prove mixed feasibility. + mixedConclusion: + combined.status === "contradictory" || violations?.length + ? "contradictory" + : combined.status === "determined" + ? "determined-over-rationals" + : "not-decided", + violations, + }; +} diff --git a/scripts/mixed-relations/project-certificate.mjs b/scripts/mixed-relations/project-certificate.mjs new file mode 100644 index 00000000..8d5e3279 --- /dev/null +++ b/scripts/mixed-relations/project-certificate.mjs @@ -0,0 +1,17 @@ +import { projectMixedContradiction } from "../../dist/layout/relations/mixed-contradiction.js"; +import { checkMixedContradiction } from "../../dist/layout/relations/check-mixed-contradiction.js"; + +// Preserve the diagnostic JSON contract while exercising the typed core. +// The cap counts all input and projected rows, before parallel compaction. +// Null means no checked proof, including exhausted budget, never feasibility. +export function projectionCertificate(graph, probes, maxRows = 10_000) { + const result = projectMixedContradiction(graph, probes, maxRows); + if (!result || !checkMixedContradiction(graph, probes, result)) return null; + const pack = (weights) => + weights.flatMap((w, row) => + w.numerator === 0n + ? [] + : [{ row, weight: [String(w.numerator), String(w.denominator)] }], + ); + return { edges: pack(result.bounds), probes: pack(result.equalities) }; +} diff --git a/scripts/mixed-relations/project-witness.mjs b/scripts/mixed-relations/project-witness.mjs new file mode 100644 index 00000000..8072c3ca --- /dev/null +++ b/scripts/mixed-relations/project-witness.mjs @@ -0,0 +1,11 @@ +import { projectAffineFeasible } from "../../dist/layout/relations/mixed-feasible.js"; + +// Preserve the offline affine/JSON contract while exercising the bounded core. +// Null means no point, including exhausted budget; it carries no status. +// Caller checks all input bounds and equalities independently. +export function projectWitness(graph, point, basis, maxRows = 10_000) { + const result = projectAffineFeasible(graph, point, basis, maxRows); + return ( + result?.map((v) => [String(v.numerator), String(v.denominator)]) ?? null + ); +} diff --git a/scripts/mixed-relations/test-classify.mjs b/scripts/mixed-relations/test-classify.mjs new file mode 100644 index 00000000..00466e06 --- /dev/null +++ b/scripts/mixed-relations/test-classify.mjs @@ -0,0 +1,119 @@ +import assert from "node:assert/strict"; +import { classifyMixed } from "./classify.mjs"; +import { checkMixedResult } from "./check-classify.mjs"; + +const system = ( + relations = [], + anchors = [{ id: "a", variable: "a", position: 0 }], + ids = ["a", "b"], +) => ({ + variables: ids.map((id) => ({ id, size: 0 })), + anchors, + relations, +}); +const edge = (from, to, gap = 0) => ({ + id: `${from}-${to}`, + kind: "minimum", + from, + to, + gap: gap / 64, +}); +const pin = (variable, position = 0) => ({ id: variable, variable, position }); +const row = (terms, constant = 0) => ({ + kind: "linear", + terms: terms.map(([variable, coefficient]) => ({ variable, coefficient })), + constant, +}); +// These literal statuses catch mistaking a failed motion search for uniqueness, +// a failed point search for contradiction, or equality rank for mixed rank. +const cases = [ + [system(), [], "underdetermined"], + [system([], [pin("a"), pin("b", 1)]), [], "determined"], + [system([edge("a", "b", 1), edge("b", "a", 1)]), [], "contradictory"], + [system([edge("a", "b")], [pin("a")]), [row([["b", 2]], 1)], "determined"], + [ + system([edge("a", "b")], [pin("a")]), + [row([["b", 2]], -1)], + "contradictory", + ], + // Neither a general equality nor nonnegative bounds alone fix b and c. + [ + system([edge("a", "b"), edge("a", "c")], [pin("a")], ["a", "b", "c"]), + [ + row([ + ["b", 1], + ["c", 2], + ]), + ], + "determined", + ], + [ + system([edge("b", "c"), edge("c", "b")], [pin("a")], ["a", "b", "c"]), + [], + "underdetermined", + ], + [system([], [pin("a")], ["a"]), [], "determined"], + [system(), [row([], 1)], "contradictory"], +]; +for (const [input, rows, status] of cases) { + for (const reversed of [false, true]) { + const source = { + ...input, + relations: reversed ? [...input.relations].reverse() : input.relations, + }; + const result = classifyMixed(source, rows); + assert.equal(result?.status, status); + assert(checkMixedResult(source, rows, JSON.parse(JSON.stringify(result)))); + assert(!checkMixedResult(source, rows, { ...result, status: "unknown" })); + if (status === "determined" && input.variables.length) { + assert( + !checkMixedResult(source, rows, { + ...result, + fixed: result.fixed.slice(1), + }), + ); + assert( + !checkMixedResult(source, rows, { + ...result, + fixed: result.fixed.map(() => null), + }), + ); + const changed = structuredClone(result); + changed.point[0][0] = String(BigInt(changed.point[0][0]) + 1n); + assert(!checkMixedResult(source, rows, changed)); + } + if (status === "underdetermined") { + assert( + !checkMixedResult(source, rows, { + ...result, + values: [result.values[0], result.values[0]], + }), + ); + assert( + !checkMixedResult(source, rows, { + status: "determined", + point: result.values[0], + fixed: source.variables.map(() => null), + }), + ); + } + if (status === "contradictory") { + assert( + !checkMixedResult(source, rows, { + status, + proof: { edges: [], probes: [] }, + }), + ); + } + } +} +const fractional = classifyMixed(cases[3][0], cases[3][1]); +assert.deepEqual(fractional.point, [ + ["0", "1"], + ["1", "2"], +]); +assert(!checkMixedResult(system(), [], fractional)); +assert(!checkMixedResult(system(), [], null)); +assert.throws(() => classifyMixed(system([], []), []), /anchor/); +assert(!checkMixedResult(system([], []), [], fractional)); +console.log(`${cases.length} mixed status cases pass in both source orders`); diff --git a/scripts/mixed-relations/test-coordinate-variation.mjs b/scripts/mixed-relations/test-coordinate-variation.mjs new file mode 100644 index 00000000..086a5626 --- /dev/null +++ b/scripts/mixed-relations/test-coordinate-variation.mjs @@ -0,0 +1,133 @@ +import assert from "node:assert/strict"; +import { variationWitness } from "./variation.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const q = (...values) => values.map((v) => [String(v), "1"]); +const edge = (from, to, gap = 0) => ({ + id: `${from}-${to}`, + kind: "minimum", + from, + to, + gap: gap / 64, +}); +const system = (relations = []) => ({ + variables: ["a", "b", "c", "d"].map((id) => ({ id, size: 0 })), + anchors: [{ id: "pin", variable: "a", position: 0 }], + relations, +}); +const row = (terms, constant = 0) => ({ + kind: "linear", + terms: terms.map(([variable, coefficient]) => ({ variable, coefficient })), + constant, +}); +const input = system(); +const graph = normalizeRelations(input); +const first = q(0, 0, 0, 0); +const pair = [first, q(0, 1, 0, 0)]; +// A valid system-wide shift does not prove motion of the requested coordinate. +assert(!checkVariationWitness(graph, [], pair, 0)); +assert(!checkVariationWitness(graph, [], pair, 2)); +assert(checkVariationWitness(graph, [], pair, 1)); +for (const coordinate of [-1, 4, 0.5, null, "1"]) { + assert(!checkVariationWitness(graph, [], pair, coordinate)); + assert.equal(variationWitness(input, graph, [], first, coordinate), null); +} +assert(!checkVariationWitness(graph, [], [first, q(1, 1, 0, 0)], 1)); +assert(!checkVariationWitness(graph, [], [first], 1)); +assert(!checkVariationWitness(graph, [], null, 1)); +assert(!checkVariationWitness(graph, [], [first, q(0, 0, 0, 0)], 1)); +assert( + !checkVariationWitness( + graph, + [], + [ + first, + [ + ["0", "1"], + ["1", "0"], + ["0", "1"], + ["0", "1"], + ], + ], + 1, + ), +); +// Literal coordinate expectations catch an unrelated direction being returned. +const cases = [ + [input, [], first, [false, true, true, true]], + [ + system([edge("b", "c"), edge("c", "b")]), + [], + first, + [false, true, true, true], + ], + [ + system([edge("b", "c"), edge("c", "b"), edge("b", "a")]), + [], + first, + [false, true, true, true], + ], + [ + system([edge("a", "b"), edge("a", "c")]), + [ + row([ + ["b", 1], + ["c", 2], + ]), + ], + first, + [false, false, false, true], + ], + [ + system([edge("a", "b"), edge("b", "a", -1)]), + [ + row([ + ["b", 1], + ["c", -1], + ]), + ], + [ + ["0", "1"], + ["3", "4"], + ["3", "4"], + ["0", "1"], + ], + [false, true, true, true], + ], + [ + input, + [row([["b", 2]], 1)], + [ + ["0", "1"], + ["1", "2"], + ["0", "1"], + ["0", "1"], + ], + [false, false, true, true], + ], +]; +for (const [source, rows, point, expected] of cases) { + for (const reversed of [false, true]) { + const ordered = { + ...source, + relations: reversed ? [...source.relations].reverse() : source.relations, + }; + const g = normalizeRelations(ordered); + for (const [coordinate, moving] of expected.entries()) { + const second = variationWitness(ordered, g, rows, point, coordinate); + assert.equal(Boolean(second), moving, `coordinate ${coordinate}`); + if (second) { + assert(checkVariationWitness(g, rows, [point, second], coordinate)); + assert.notEqual( + BigInt(point[coordinate][0]) * BigInt(second[coordinate][1]), + BigInt(second[coordinate][0]) * BigInt(point[coordinate][1]), + ); + } + } + } +} +assert.equal(variationWitness(input, graph, [], q(1, 0, 0, 0), 1), null); +console.log( + "Coordinate motion cases, reversed inputs and tampering checks pass", +); diff --git a/scripts/mixed-relations/test-feasible.mjs b/scripts/mixed-relations/test-feasible.mjs new file mode 100644 index 00000000..0d07e14f --- /dev/null +++ b/scripts/mixed-relations/test-feasible.mjs @@ -0,0 +1,95 @@ +import assert from "node:assert/strict"; +import { feasibleWitness } from "./feasible.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const system = { + variables: ["origin", "a", "b"].map((id) => ({ id, size: 0 })), + anchors: [{ id: "pin", variable: "origin", position: 0 }], + relations: [ + { id: "floor", from: "origin", to: "a", kind: "minimum", gap: 10 / 64 }, + { id: "same", from: "a", to: "b", kind: "equal", gap: 0 }, + ], +}; +const graph = normalizeRelations(system); +const fixed = (constant) => ({ + kind: "linear", + terms: [{ variable: "a", coefficient: 2 }], + constant, +}); +const rows = [fixed(21)]; +// Literal tick values: origin=0, a=b=10.5 meet floor=10 and 2a=21. +const proof = [ + ["0", "1"], + ["21", "2"], + ["21", "2"], +]; +assert(checkFeasibleWitness(graph, rows, proof)); +assert.deepEqual(feasibleWitness(system, graph, rows), proof); +// Projection finds a point satisfying the floor. +assert(checkFeasibleWitness(graph, [], feasibleWitness(system, graph, []))); +assert.equal(feasibleWitness(system, graph, [fixed(19)]), null); +assert.equal(feasibleWitness(system, graph, [fixed(21), fixed(22)]), null); +assert(!checkFeasibleWitness(graph, rows, null)); +assert(!checkFeasibleWitness(graph, rows, proof.slice(1))); +assert(!checkFeasibleWitness(graph, [fixed(22)], proof)); +// Reject violated minimum, equality, and anchor bounds independently. +assert( + !checkFeasibleWitness( + graph, + [], + [ + ["0", "1"], + ["9", "1"], + ["9", "1"], + ], + ), +); +assert( + !checkFeasibleWitness(graph, rows, [ + ["0", "1"], + ["21", "2"], + ["11", "1"], + ]), +); +assert( + !checkFeasibleWitness(graph, rows, [ + ["1", "1"], + ["21", "2"], + ["21", "2"], + ]), +); +for (const bad of [ + ["1", "0"], + ["1", "-2"], + ["oops", "1"], + [21, 2], +]) { + const changed = structuredClone(proof); + changed[1] = bad; + assert(!checkFeasibleWitness(graph, rows, changed)); +} +const unknown = [ + { ...fixed(21), terms: [{ variable: "missing", coefficient: 1 }] }, +]; +assert(!checkFeasibleWitness(graph, unknown, proof)); +// Repeated terms add, rather than overwriting an earlier coefficient. +assert( + checkFeasibleWitness( + graph, + [ + { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "a", coefficient: 1 }, + ], + constant: 21, + }, + ], + proof, + ), +); +console.log( + "Mixed feasible witnesses pass, including rational and tampering cases", +); diff --git a/scripts/mixed-relations/test-fixed.mjs b/scripts/mixed-relations/test-fixed.mjs new file mode 100644 index 00000000..03ab7f9a --- /dev/null +++ b/scripts/mixed-relations/test-fixed.mjs @@ -0,0 +1,109 @@ +import assert from "node:assert/strict"; +import { fixedWitness } from "./fixed.mjs"; +import { checkFixedWitness } from "./check-fixed.mjs"; + +const q = (...values) => values.map((n) => [String(n), "1"]); +const graph = (edges, variables = ["a", "b"]) => ({ variables, edges }); +const edge = (from, to, weight = 0) => ({ from, to, weight }); +const row = (terms, constant = 0) => ({ + kind: "linear", + terms: terms.map(([variable, coefficient]) => ({ variable, coefficient })), + constant, +}); +const cases = [ + [graph([edge(0, 1), edge(1, 0)]), [], q(0, 4), [true, false]], + [graph([edge(0, 1)]), [], q(0, 0), [false, false]], + [graph([edge(1, 0)]), [], q(0, 0), [false, false]], + [ + graph([]), + [ + row([ + ["a", 1], + ["b", 1], + ]), + ], + q(0, 0), + [false, false], + ], + // Inequalities and a general equality together fix both coordinates. + [ + graph([edge(0, 1), edge(0, 2)]), + [ + row([ + ["a", 1], + ["b", 2], + ]), + ], + q(0, 0), + [true, true], + ], + [ + graph([]), + [row([["a", 2]], 1)], + [ + ["1", "2"], + ["0", "1"], + ], + [true, false], + ], + [graph([edge(0, 1), edge(1, 2), edge(2, 0)]), [], q(0, 0), [true, true]], + // Slack inequalities are not tight direction constraints. + [graph([edge(0, 1, -1), edge(1, 0, -1)]), [], q(0, 0), [false, false]], + [graph([]), [row([["a", 1]], 2), row([["b", 1]], 3)], q(2, 3), [true, true]], +]; +let checked = 0; +for (const [input, rows, point, expected] of cases) { + for (const reversed of [false, true]) { + const g = reversed + ? { ...input, edges: [...input.edges].reverse() } + : input; + for (const [i, fixed] of expected.entries()) { + const proof = fixedWitness(g, rows, point, i); + assert.equal(Boolean(proof), fixed); + if (proof) { + checked++; + assert(checkFixedWitness(g, rows, point, i, proof)); + assert(!checkFixedWitness(g, rows, point, i, [proof[0]])); + assert( + !checkFixedWitness(g, rows, point, i, [ + proof[0], + { edges: [], probes: [] }, + ]), + ); + } + } + } +} +const g = graph([edge(0, 1), edge(1, 0)]); +const proof = fixedWitness(g, [], q(0, 0), 0); +assert(!checkFixedWitness(g, [], q(1, 0), 0, proof)); +assert(!checkFixedWitness(g, [], q(0, 0), 1, proof)); +assert(!checkFixedWitness(g, [], q(0, 0), -1, proof)); +assert(!checkFixedWitness(g, [], q(0, 0), 0, null)); +assert(!checkFixedWitness(graph([edge(0, 1)]), [], q(0, 0), 0, proof)); +const fractional = graph([]); +const rows = [row([["a", 2]], 1)]; +const point = [ + ["1", "2"], + ["0", "1"], +]; +const fractionalProof = fixedWitness(fractional, rows, point, 0); +assert(!checkFixedWitness(fractional, [], point, 0, fractionalProof)); +assert( + !checkFixedWitness( + fractional, + rows, + [ + ["1", "0"], + ["0", "1"], + ], + 0, + fractionalProof, + ), +); +assert.equal(fixedWitness(g, [], q(1, 0), 0), null); +assert.equal(fixedWitness(g, [], q(0, 0), 2), null); +assert.equal(fixedWitness(graph([], []), [], [], 0), null); +console.log( + `${cases.length} fixed-coordinate cases and ${checked} certificates pass, including reversed inputs and tampering`, +); diff --git a/scripts/mixed-relations/test-grid-variation.mjs b/scripts/mixed-relations/test-grid-variation.mjs new file mode 100644 index 00000000..f47d0ce5 --- /dev/null +++ b/scripts/mixed-relations/test-grid-variation.mjs @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { gridWitness } from "./grid.mjs"; + +const point = (...values) => values.map((n) => [String(n), "1"]); +const graph = { variables: ["a", "b"], edges: [] }; +const equal = (a, b, constant = 0) => ({ + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + constant, +}); +const first = point(0, 0); +const second = gridWitness(graph, [equal(1, -1)], first, first); +assert.notDeepEqual(second, first, "search must exclude the known point"); +const { checkGridVariationWitness } = await import("./grid-variation.mjs"); +assert(checkGridVariationWitness(graph, [equal(1, -1)], [first, second])); + +// A fractional seed needs a coupled integer move; a alone cannot be rounded. +const coupled = gridWitness( + graph, + [equal(1, -2)], + [ + ["1", "1"], + ["1", "2"], + ], + first, +); +assert(checkGridVariationWitness(graph, [equal(1, -2)], [first, coupled])); + +// Rational motion can exist even when the bounded region has one grid point: +// 0 <= a <= 1, a = 2b. A local miss must remain null, never a uniqueness proof. +const bounded = { + ...graph, + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 1, to: 0, weight: -1 }, + ], +}; +assert.equal(gridWitness(bounded, [equal(1, -2)], first, first), null); +// Solutions (10, 1) and (-10, -1) are outside this finite neighborhood. +assert.equal(gridWitness(graph, [equal(1, -10)], first, first), null); +// Exclusion compares values rather than fraction encodings. +const fixed = [equal(1, 0), equal(0, 1)]; +assert.equal( + gridWitness(graph, fixed, first, [ + ["0", "2"], + ["0", "3"], + ]), + null, +); +assert.equal(gridWitness(graph, fixed, first, null), null); +assert.equal( + gridWitness(graph, fixed, first, [ + ["0", "0"], + ["0", "1"], + ]), + null, +); + +assert(!checkGridVariationWitness(graph, [], [first, first])); +assert( + !checkGridVariationWitness( + graph, + [], + [ + first, + [ + ["0", "2"], + ["0", "3"], + ], + ], + ), +); +assert( + !checkGridVariationWitness( + graph, + [], + [ + first, + [ + ["1", "2"], + ["0", "1"], + ], + ], + ), +); +assert(!checkGridVariationWitness(graph, [equal(1, -1)], [first, point(1, 0)])); +assert(!checkGridVariationWitness(bounded, [], [first, point(2, 0)])); +assert( + !checkGridVariationWitness( + graph, + [], + [ + first, + [ + ["1", "0"], + ["0", "1"], + ], + ], + ), +); +assert(!checkGridVariationWitness(graph, [], null)); +assert(!checkGridVariationWitness(graph, [], [first])); +assert( + checkGridVariationWitness( + graph, + [], + [ + first, + [ + ["2", "2"], + ["0", "1"], + ], + ], + ), +); +console.log( + "Seven distinct grid search cases and independent pair tampering pass", +); diff --git a/scripts/mixed-relations/test-grid.mjs b/scripts/mixed-relations/test-grid.mjs new file mode 100644 index 00000000..0ddb28a3 --- /dev/null +++ b/scripts/mixed-relations/test-grid.mjs @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import { gridWitness, checkGridWitness } from "./grid.mjs"; + +const graph = { variables: ["a", "b"], edges: [] }; +const row = (a, b, constant) => ({ + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + constant, +}); +const cases = [ + // Independent rounding fails; an already integral coordinate must move too. + [ + graph, + [row(1, -2, 0)], + [ + ["1", "1"], + ["1", "2"], + ], + true, + ], + [ + graph, + [row(1, -2, 0)], + [ + ["-1", "1"], + ["-1", "2"], + ], + true, + ], + // Rational feasibility does not imply integer feasibility. + [ + graph, + [row(0, 2, 1)], + [ + ["0", "1"], + ["1", "2"], + ], + false, + ], + [ + { ...graph, edges: [{ from: 0, to: 1, weight: 1 }] }, + [row(1, -2, 0)], + [ + ["1", "1"], + ["1", "2"], + ], + true, + ], + // This bounded search must not wander to a distant integral solution. + [ + graph, + [row(1, -10, 0)], + [ + ["5", "1"], + ["1", "2"], + ], + false, + ], +]; +for (const [input, rows, point, expected] of cases) { + const proof = gridWitness(input, rows, point); + assert.equal(proof !== null, expected); + if (proof) assert(checkGridWitness(input, rows, proof)); +} +assert( + !checkGridWitness( + graph, + [], + [ + ["0", "1"], + ["1", "2"], + ], + ), +); +assert( + !checkGridWitness( + graph, + [row(1, -2, 0)], + [ + ["1", "1"], + ["0", "1"], + ], + ), +); +assert( + !checkGridWitness( + graph, + [], + [ + ["0", "0"], + ["1", "1"], + ], + ), +); +assert(!checkGridWitness(graph, [], null)); +assert( + checkGridWitness( + graph, + [], + [ + ["0", "1"], + ["2", "2"], + ], + ), +); +console.log("Five nearby grid cases and independent checker tampering pass"); diff --git a/scripts/mixed-relations/test-project-certificate.mjs b/scripts/mixed-relations/test-project-certificate.mjs new file mode 100644 index 00000000..2c969f14 --- /dev/null +++ b/scripts/mixed-relations/test-project-certificate.mjs @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { checkCertificate } from "./certificate.mjs"; + +// Neither bound alone conflicts with a+b=3. Their combination does. +const graph = { variables: ["a", "b"] }; +graph.edges = [ + { from: 1, to: 0, weight: -1, source: { kind: "minimum", id: "a" } }, + { from: 2, to: 0, weight: -1, source: { kind: "minimum", id: "b" } }, +]; +const row = (constant) => ({ + kind: "linear", + terms: [ + { variable: "a", coefficient: 2 }, + { variable: "b", coefficient: 2 }, + ], + constant, +}); +for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + const proof = projectionCertificate(input, [row(6)]); + assert(checkCertificate(input, [row(6)], proof)); + assert(proof.edges.length === 2); + assert(!checkCertificate(input, [row(4)], proof)); + assert( + !checkCertificate(input, [row(6)], { + ...proof, + edges: proof.edges.slice(1), + }), + ); + assert.equal(projectionCertificate(input, [row(4)]), null); + assert.equal(projectionCertificate(input, [row(0)]), null); +} +// Keeping a weaker parallel row would hide this conflict. +const parallel = { + ...graph, + edges: [...graph.edges, { from: 1, to: 0, weight: -2 }], +}; +assert( + checkCertificate( + parallel, + [row(6)], + projectionCertificate(parallel, [row(6)]), + ), +); +// A source equality is represented by its two input bound directions. +const fixedGraph = { + variables: ["a"], + edges: [ + { from: 0, to: 1, weight: 2 }, + { from: 1, to: 0, weight: -2 }, + ], +}; +const fractionalRow = { + kind: "linear", + terms: [{ variable: "a", coefficient: 3 }], + constant: 7, +}; +const fractionalProof = projectionCertificate(fixedGraph, [fractionalRow]); +assert(checkCertificate(fixedGraph, [fractionalRow], fractionalProof)); +assert( + fractionalProof.probes.some( + ({ weight: [, denominator] }) => denominator !== "1", + ), +); +// Equality-only contradictions require signed weights; one-sided bounds do not. +assert( + checkCertificate( + graph, + [row(0), row(1)], + projectionCertificate(graph, [row(0), row(1)]), + ), +); +assert.equal( + projectionCertificate( + { variables: ["a"], edges: [{ from: 0, to: 1, weight: 10 }] }, + [], + ), + null, +); +assert.equal(projectionCertificate({ variables: [], edges: [] }, []), null); +const constantGraph = { variables: [], edges: [{ from: 0, to: 0, weight: 1 }] }; +assert( + checkCertificate(constantGraph, [], projectionCertificate(constantGraph, [])), +); +// Duplicate terms accumulate; empty and tautological rows survive safely. +const duplicate = { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "a", coefficient: -1 }, + ], + constant: 1, +}; +assert( + checkCertificate( + graph, + [duplicate], + projectionCertificate(graph, [duplicate]), + ), +); +console.log( + "Projection certificates pass coupled bounds, exact weights and tampering checks", +); diff --git a/scripts/mixed-relations/test-project-witness.mjs b/scripts/mixed-relations/test-project-witness.mjs new file mode 100644 index 00000000..b7e8d0dc --- /dev/null +++ b/scripts/mixed-relations/test-project-witness.mjs @@ -0,0 +1,164 @@ +import assert from "node:assert/strict"; +import { feasibleWitness } from "./feasible.mjs"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; +import { ratio } from "../../dist/layout/relations/rational.js"; +import { projectWitness } from "./project-witness.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; + +const q = (...values) => values.map((v) => ratio(BigInt(v))); +// Removing lower/upper pairs, forgetting constant rows, losing the strongest +// duplicate or reconstructing in the wrong variable order breaks these cases. +const cases = [ + // Three directions with a coupled sum: each coordinate <=1 cannot sum to 4. + [ + [ + [1, 0, -1], + [2, 0, -1], + [3, 0, -1], + [0, 4, 4], + ], + q(0, 0, 0, 0), + [q(1, 0, 0, 1), q(0, 1, 0, 1), q(0, 0, 1, 1)], + null, + ], + // Tight positive, negative and fractional parameters, with a dependent value. + [ + [ + [0, 1, 1], + [1, 0, -1], + [0, 2, -3], + [2, 0, 3], + [0, 3, 5], + [3, 0, -5], + ], + q(0, 0, 0, 0), + [q(2, 0, 0, 1), q(0, 1, 0, 0), q(0, 0, 1, 0)], + [ + ["1", "1"], + ["-3", "1"], + ["5", "1"], + ["1", "2"], + ], + ], + // Strongest parallel row survives even if the weaker row appears last. + [ + [ + [0, 1, 5], + [0, 2, 6], + ], + q(0, 0), + [q(1, 2)], + [ + ["5", "1"], + ["10", "1"], + ], + ], + // Constant conditions must survive every elimination. + [[[0, 2, 1]], q(0, 0), [q(1, 0)], null], + // Both one-sided signs and entirely free parameters. + [ + [ + [0, 2, 3], + [3, 0, 2], + ], + q(7, 0, 0), + [q(1, 0, 0), q(0, 1, 0), q(0, 0, 1)], + [ + ["7", "1"], + ["3", "1"], + ["-2", "1"], + ], + ], + [ + [], + q(2, 3), + [q(1, 0), q(0, 1)], + [ + ["2", "1"], + ["3", "1"], + ], + ], + // Zero-dimensional systems still check constant feasibility. + [[[0, 1, 2]], q(2), [], [["2", "1"]]], + [[[0, 1, 3]], q(2), [], null], + // Eliminate the second parameter first (no pairs), then restore its slot. + [ + [ + [0, 1, 2], + [1, 0, -2], + [0, 2, 3], + ], + q(0, 0), + [q(1, 0), q(0, 1)], + [ + ["2", "1"], + ["3", "1"], + ], + ], +]; +for (const [edges, point, basis, expected] of cases) { + const graph = { + variables: point.map((_, i) => `x${i}`), + edges: edges.map(([from, to, weight]) => ({ from, to, weight })), + }; + for (const ordered of [ + graph, + { ...graph, edges: [...graph.edges].reverse() }, + ]) { + const proof = projectWitness(ordered, point, basis); + assert.deepEqual(proof, expected); + if (proof) assert(checkFeasibleWitness(ordered, [], proof)); + } +} +// Integration: projection repairs three independent triples. +const triples = { + variables: ["origin", "a", "b", "c", "d", "e", "f", "g", "h", "i"].map( + (id) => ({ id, size: 0 }), + ), + anchors: [{ id: "pin", variable: "origin", position: 0 }], + relations: ["a", "b", "c", "d", "e", "f", "g", "h", "i"].map((to) => ({ + id: to, + from: "origin", + to, + kind: "minimum", + gap: ["a", "d", "g"].includes(to) ? 10 / 64 : 0, + })), +}; +const threeRows = [ + ["a", "b", "c"], + ["d", "e", "f"], + ["g", "h", "i"], +].map(([a, b, c]) => ({ + kind: "linear", + terms: [ + { variable: a, coefficient: 1 }, + { variable: b, coefficient: -2 }, + { variable: c, coefficient: 1 }, + ], + constant: 0, +})); +const graph = normalizeRelations(triples); +assert( + checkFeasibleWitness(graph, threeRows, [ + ["0", "1"], + ["10", "1"], + ["5", "1"], + ["0", "1"], + ["10", "1"], + ["5", "1"], + ["0", "1"], + ["10", "1"], + ["5", "1"], + ["0", "1"], + ]), +); +assert( + checkFeasibleWitness( + graph, + threeRows, + feasibleWitness(triples, graph, threeRows), + ), +); +console.log( + "Nine exact projection cases and the three-triple integration regression pass", +); diff --git a/scripts/mixed-relations/test-variation.mjs b/scripts/mixed-relations/test-variation.mjs new file mode 100644 index 00000000..f6843f1f --- /dev/null +++ b/scripts/mixed-relations/test-variation.mjs @@ -0,0 +1,170 @@ +import assert from "node:assert/strict"; +import { variationWitness } from "./variation.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const system = (relations = [], anchors = []) => ({ + variables: ["a", "b", "c"].map((id) => ({ id, size: 0 })), + anchors: anchors.length + ? anchors + : [{ id: "pin", variable: "a", position: 0 }], + relations, +}); +const edge = (from, to, gap, kind = "minimum") => ({ + id: `${from}-${to}`, + from, + to, + gap: gap / 64, + kind, +}); +const pin = (variable, ticks) => ({ + id: variable, + variable, + position: ticks / 64, +}); +const midpoint = [ + { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: -2 }, + { variable: "c", coefficient: 1 }, + ], + constant: 0, + }, +]; +const q = (...values) => values.map((v) => [String(v), "1"]); +// A one-sided or fractional interval must allow motion, tight bounds must not. +const cases = [ + [system(), [], q(0, 0, 0), true], + [system([edge("a", "b", 0)], [pin("a", 0)]), midpoint, q(0, 0, 0), true], + [ + system([edge("a", "b", 0), edge("b", "c", 0)], [pin("a", 0), pin("c", 1)]), + midpoint, + [ + ["0", "1"], + ["1", "2"], + ["1", "1"], + ], + false, + ], + [system([], [pin("a", 0), pin("b", 0), pin("c", 0)]), [], q(0, 0, 0), false], + [system([edge("a", "b", 0, "equal")]), [], q(0, 0, 0), true], + [system([edge("a", "b", 1)]), midpoint, q(0, 0, 0), false], + [system([edge("b", "a", 0)], [pin("a", 0)]), midpoint, q(0, 0, 0), true], + [ + system([edge("a", "b", 0), edge("b", "c", 0)], [pin("a", 0), pin("c", 1)]), + [], + [ + ["0", "1"], + ["1", "2"], + ["1", "1"], + ], + true, + ], + // Opposite inequalities fix all coordinates without explicit equal rows. + [ + system( + [ + edge("a", "b", 0), + edge("b", "a", 0), + edge("b", "c", 0), + edge("c", "b", 0), + ], + [pin("a", 0)], + ), + [], + q(0, 0, 0), + false, + ], +]; +for (const [input, rows, point, expected] of cases) { + for (const ordered of [ + input, + { ...input, relations: [...input.relations].reverse() }, + ]) { + const graph = normalizeRelations(ordered); + const second = variationWitness(ordered, graph, rows, point); + assert.equal(second !== null, expected); + if (second) assert(checkVariationWitness(graph, rows, [point, second])); + } +} +const graph = normalizeRelations(system([], [pin("a", 0)])); +const pair = [q(0, 0, 0), q(0, 1, 2)]; +assert(checkVariationWitness(graph, midpoint, pair)); +assert(!checkVariationWitness(graph, midpoint, [pair[0], pair[0]])); +assert( + !checkVariationWitness(graph, midpoint, [ + q(0, 0, 0), + [ + ["0", "2"], + ["0", "3"], + ["0", "4"], + ], + ]), +); +assert(!checkVariationWitness(graph, midpoint, [pair[0], q(0, 1, 3)])); +assert(!checkVariationWitness(graph, midpoint, [pair[0], q(1, 2, 3)])); +assert( + !checkVariationWitness(graph, midpoint, [ + pair[0], + [ + ["0", "1"], + ["1", "0"], + ["2", "1"], + ], + ]), +); +assert(!checkVariationWitness(graph, midpoint, [pair[0]])); +assert(!checkVariationWitness(graph, midpoint, null)); +// Opposite bounds require a coupled move; individual basis lines are blocked. +const coupled = system([edge("b", "c", 0), edge("c", "b", 0)]); +const coupledGraph = normalizeRelations(coupled); +const coupledSecond = variationWitness(coupled, coupledGraph, [], q(0, 0, 0)); +assert(coupledSecond); +assert(checkVariationWitness(coupledGraph, [], [q(0, 0, 0), coupledSecond])); +assert(checkVariationWitness(coupledGraph, [], [q(0, 0, 0), q(0, 1, 1)])); +const lowerGraph = normalizeRelations(system([edge("a", "b", 0)])); +assert( + !checkVariationWitness(lowerGraph, midpoint, [q(0, 0, 0), q(0, -1, -2)]), +); +assert(!checkVariationWitness(graph, midpoint, [q(0, 0, 0), q(0, 1)])); + +// Coupled negative motion is the only option when an upper bound is tight. +// A positive cone direction must also respect slack bounds via a fractional cap. +for (const [bounds, first] of [ + [[edge("b", "a", 0)], q(0, 0, 0)], + [ + [edge("b", "a", -1), edge("a", "b", 0)], + [ + ["0", "1"], + ["3", "4"], + ["3", "4"], + ], + ], +]) { + const input = system([...coupled.relations, ...bounds]); + for (const ordered of [ + input, + { ...input, relations: [...input.relations].reverse() }, + ]) { + const graph = normalizeRelations(ordered); + const second = variationWitness(ordered, graph, [], first); + assert(second); + assert(checkVariationWitness(graph, [], [first, second])); + } +} +// Three tight coordinates require simultaneous motion in three basis directions. +const triple = { + ...coupled, + variables: [...coupled.variables, { id: "d", size: 0 }], + relations: [...coupled.relations, edge("c", "d", 0), edge("d", "c", 0)], +}; +const tripleGraph = normalizeRelations(triple); +const tripleFirst = q(0, 0, 0, 0); +const tripleSecond = variationWitness(triple, tripleGraph, [], tripleFirst); +assert(tripleSecond); +assert(checkVariationWitness(tripleGraph, [], [tripleFirst, tripleSecond])); +console.log( + "Variation cases, coupled shifts, reversed inputs and tampering checks pass", +); diff --git a/scripts/mixed-relations/test.mjs b/scripts/mixed-relations/test.mjs new file mode 100644 index 00000000..3f1445be --- /dev/null +++ b/scripts/mixed-relations/test.mjs @@ -0,0 +1,48 @@ +import assert from "node:assert/strict"; +import { auditProbe } from "./probes.mjs"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const system = { + variables: ["origin", "a", "b"].map((id) => ({ id, size: 0 })), + anchors: [{ id: "pin", variable: "origin", position: 0 }], + relations: [ + { id: "floor", from: "origin", to: "a", kind: "minimum", gap: 10 / 64 }, + ], +}; +const row = (variable, coefficient, constant) => ({ + kind: "linear", + terms: [{ variable, coefficient }], + constant, +}); +function audit(input, rows) { + return auditProbe(input, normalizeRelations(input), { name: "test", rows }); +} + +// A poor equality particular is not proof that all solutions violate the floor. +assert.equal(audit(system, []).mixedConclusion, "not-decided"); +assert.equal(audit(system, [row("a", 1, 20)]).mixedConclusion, "not-decided"); +// Free unrelated b does not prevent a fixed-gap contradiction at a. +const conflict = audit(system, [row("a", 1, 5)]); +assert.equal(conflict.currentStatus, "underdetermined"); +assert.equal(conflict.mixedConclusion, "contradictory"); +assert.deepEqual(conflict.violations, [ + { kind: "relation", id: "floor", reverse: false }, +]); +const equal = { + ...system, + relations: [ + ...system.relations, + { id: "same", from: "a", to: "b", kind: "equal", gap: 0 }, + ], +}; +assert.equal(audit(equal, [row("b", 1, 5)]).mixedConclusion, "contradictory"); +const incompatible = audit(equal, [row("a", 1, 10), row("b", 1, 20)]); +assert.equal(incompatible.withDifferenceEqualities, "contradictory"); +assert.equal(incompatible.mixedConclusion, "contradictory"); +// Rational feasibility is not a claim of a grid solution (a = 10.5 ticks). +const rational = audit(system, [row("a", 2, 21), row("b", 1, 0)]); +assert.equal(rational.mixedConclusion, "determined-over-rationals"); +assert.deepEqual(rational.violations, []); +console.log( + "Six diagnostic cases passed, including free and fractional coordinates", +); diff --git a/scripts/mixed-relations/variation.mjs b/scripts/mixed-relations/variation.mjs new file mode 100644 index 00000000..afcf215b --- /dev/null +++ b/scripts/mixed-relations/variation.mjs @@ -0,0 +1,33 @@ +import { projectMixedVariation } from "../../dist/layout/relations/mixed-variation.js"; +import { ratio } from "../../dist/layout/relations/rational.js"; +import { sourceEqualities } from "./feasible.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; + +// Preserve the offline JSON contract while exercising bounded typed motion. +// Null means no witness, including exhaustion; it never proves uniqueness. +export function variationWitness( + system, + graph, + rows, + first, + coordinate, + maxRows = 10_000, +) { + if (!checkFeasibleWitness(graph, rows, first)) return null; + const second = projectMixedVariation( + graph, + [...sourceEqualities(system, graph), ...rows], + first.map(([n, d]) => ratio(BigInt(n), BigInt(d))), + maxRows, + coordinate, + ); + const packed = second?.map((v) => [ + String(v.numerator), + String(v.denominator), + ]); + return packed && + checkVariationWitness(graph, rows, [first, packed], coordinate) + ? packed + : null; +} diff --git a/scripts/mixed-relations/variations.mjs b/scripts/mixed-relations/variations.mjs new file mode 100644 index 00000000..9ff92f20 --- /dev/null +++ b/scripts/mixed-relations/variations.mjs @@ -0,0 +1,92 @@ +// Run after npm run build; optional destination supports independent replay. +import assert from "node:assert/strict"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { format } from "prettier"; +import { corpus, geometry } from "./corpus.mjs"; +import { probes } from "./probes.mjs"; +import { feasibleWitness } from "./feasible.mjs"; +import { checkFeasibleWitness } from "./check-feasible.mjs"; +import { variationWitness } from "./variation.mjs"; +import { checkVariationWitness } from "./check-variation.mjs"; +import { checkCertificate } from "./certificate.mjs"; +import { projectionCertificate } from "./project-certificate.mjs"; +import { laneRankRelations } from "../../dist/layout/relations/lane-rank.js"; +import { crossRelations } from "../../dist/layout/relations/cross.js"; +import { normalizeRelations } from "../../dist/layout/relations/normalize.js"; + +const destination = resolve( + process.argv[2] ?? ".cache/mixed-relations/variations", +); +async function write(name, data) { + const file = resolve(destination, `${name}.json`); + const text = await format(JSON.stringify(data), { parser: "json" }); + assert(text.split("\n").length <= 501, `Evidence exceeds 500 lines: ${name}`); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, text); +} +const counts = { + probes: 0, + contradictory: 0, + feasible: 0, + underdetermined: 0, + uniquenessNotDecided: 0, +}; +const profiles = {}; +const unresolved = []; +for await (const { id, problem, resolved } of corpus()) { + const original = geometry(resolved); + const profile = id.split("/").slice(0, 2).join("/"); + const totals = (profiles[profile] ??= { + feasible: 0, + underdetermined: 0, + uniquenessNotDecided: 0, + }); + for (const axis of ["rank", "cross"]) { + const system = + axis === "rank" + ? laneRankRelations(problem, original, 16) + : crossRelations(problem, original.nodes, 16); + const graph = normalizeRelations(system); + for (const probe of probes(problem.nodes)) { + counts.probes++; + const first = feasibleWitness(system, graph, probe.rows); + if (!first) { + const proof = projectionCertificate(graph, probe.rows); + assert( + proof && checkCertificate(graph, probe.rows, proof), + `${id}/${axis}/${probe.name}: missing feasibility classification`, + ); + counts.contradictory++; + continue; + } + assert(checkFeasibleWitness(graph, probe.rows, first)); + counts.feasible++; + totals.feasible++; + const second = variationWitness(system, graph, probe.rows, first); + if (!second) { + unresolved.push({ id, axis, probe: probe.name }); + counts.uniquenessNotDecided++; + totals.uniquenessNotDecided++; + continue; + } + assert( + checkVariationWitness(graph, probe.rows, [first, second]), + `${id}/${axis}/${probe.name}`, + ); + counts.underdetermined++; + totals.underdetermined++; + await write(`${id}/${axis}-${probe.name}`, { + id, + axis, + probe: probe.name, + conclusion: "underdetermined-over-rationals", + rows: probe.rows, + variables: graph.variables, + values: [first, second], + }); + } + } +} +await write("summary", { ...counts, profiles, unresolved }); +console.log(JSON.stringify({ ...counts, profiles, unresolved }, null, 2)); diff --git a/src/layout/relations/check-mixed-contradiction.ts b/src/layout/relations/check-mixed-contradiction.ts new file mode 100644 index 00000000..feb5b948 --- /dev/null +++ b/src/layout/relations/check-mixed-contradiction.ts @@ -0,0 +1,68 @@ +import { add, multiply, negate, ratio, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph, MixedFarkasWitness } from "./mixed-rows.js"; + +function integer(value: number | bigint): bigint { + if (typeof value !== "bigint" && !Number.isSafeInteger(value)) + throw new RangeError("Unsafe mixed input"); + return BigInt(value); +} + +function valid(weight: Rational): boolean { + return ( + typeof weight.numerator === "bigint" && + typeof weight.denominator === "bigint" && + weight.denominator > 0n + ); +} + +function validProof( + graph: MixedGraph, + rows: LinearRelation[], + proof: MixedFarkasWitness, +): boolean { + return ( + proof.bounds.length === graph.edges.length && + proof.equalities.length === rows.length && + [...proof.bounds, ...proof.equalities].every(valid) && + proof.bounds.every((w) => w.numerator >= 0n) + ); +} + +/** Check the weighted original rows directly, without projection or elimination. */ +export function checkMixedContradiction( + graph: MixedGraph, + equalities: LinearRelation[], + proof: MixedFarkasWitness, +): boolean { + try { + if (!validProof(graph, equalities, proof)) return false; + const left = graph.variables.map(() => zero); + const index = new Map(graph.variables.map((id, i) => [id, i])); + if (index.size !== graph.variables.length) return false; + let right = zero; + for (const [i, edge] of graph.edges.entries()) { + const weight = proof.bounds[i]; + if (edge.to) left[edge.to - 1] = add(left[edge.to - 1], weight); + if (edge.from) + left[edge.from - 1] = add(left[edge.from - 1], negate(weight)); + right = add(right, multiply(weight, ratio(integer(edge.weight)))); + } + for (const [i, row] of equalities.entries()) { + const weight = proof.equalities[i]; + for (const term of row.terms) { + const at = index.get(term.variable); + if (at === undefined) return false; + left[at] = add( + left[at], + multiply(weight, ratio(integer(term.coefficient))), + ); + } + right = add(right, multiply(weight, ratio(integer(row.constant)))); + } + return right.numerator > 0n && left.every((v) => v.numerator === 0n); + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-feasible.ts b/src/layout/relations/check-mixed-feasible.ts new file mode 100644 index 00000000..028ff637 --- /dev/null +++ b/src/layout/relations/check-mixed-feasible.ts @@ -0,0 +1,63 @@ +import { add, multiply, negate, ratio, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; + +function integer(value: number | bigint): bigint { + if (typeof value !== "bigint" && !Number.isSafeInteger(value)) + throw new RangeError("Unsafe mixed input"); + return BigInt(value); +} + +function valid(graph: MixedGraph, values: Rational[]): boolean { + return ( + values.length === graph.variables.length && + new Set(graph.variables).size === graph.variables.length && + [...values].every( + (v) => + typeof v.numerator === "bigint" && + typeof v.denominator === "bigint" && + v.denominator > 0n, + ) && + graph.edges.every((e) => + [e.from, e.to].every( + (v) => Number.isSafeInteger(v) && v >= 0 && v <= values.length, + ), + ) + ); +} + +function equalitiesHold( + graph: MixedGraph, + rows: LinearRelation[], + values: Rational[], +): boolean { + const index = new Map(graph.variables.map((v, i) => [v, i])); + return rows.every((row) => { + const left = row.terms.reduce((sum, term) => { + const at = index.get(term.variable); + if (at === undefined) throw new Error("Unknown mixed variable"); + return add(sum, multiply(ratio(integer(term.coefficient)), values[at])); + }, zero); + return left.numerator === integer(row.constant) * left.denominator; + }); +} + +/** Direct substitution into original rows, independent of projection/nullspace. */ +export function checkMixedFeasible( + graph: MixedGraph, + rows: LinearRelation[], + values: Rational[], +): boolean { + try { + if (!valid(graph, values)) return false; + const vertices = [zero, ...values]; + for (const edge of graph.edges) { + const gap = add(vertices[edge.to], negate(vertices[edge.from])); + if (gap.numerator < integer(edge.weight) * gap.denominator) return false; + } + return equalitiesHold(graph, rows, values); + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-fixed.ts b/src/layout/relations/check-mixed-fixed.ts new file mode 100644 index 00000000..89ed91e8 --- /dev/null +++ b/src/layout/relations/check-mixed-fixed.ts @@ -0,0 +1,64 @@ +import { add, negate, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph, MixedFarkasWitness } from "./mixed-rows.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; +import { checkMixedContradiction } from "./check-mixed-contradiction.js"; + +function tightBounds( + graph: MixedGraph, + point: Rational[], +): MixedGraph["edges"] { + const vertices = [zero, ...point]; + return graph.edges + .filter((edge) => { + const gap = add(vertices[edge.to], negate(vertices[edge.from])); + return gap.numerator === BigInt(edge.weight) * gap.denominator; + }) + .map((edge) => ({ from: edge.from, to: edge.to, weight: 0 })); +} + +/** Reconstruct tight rows independently from the input and checked point. + * Every feasible displacement obeys these homogeneous rows. A nonzero signed + * displacement rescales to >= 1; contradictions for both signs fix a coordinate. + * No producer cone metadata, elimination or projection code is trusted. + */ +export function checkMixedFixed( + graph: MixedGraph, + rows: LinearRelation[], + point: Rational[], + coordinate: number, + proof: MixedFarkasWitness[], +): boolean { + try { + if ( + !Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length || + !Array.isArray(proof) || + proof.length !== 2 || + !checkMixedFeasible(graph, rows, point) + ) + return false; + const homogeneous = rows.map((row) => ({ ...row, constant: 0 })); + return [1, -1].every((sign, i) => + checkMixedContradiction( + { + variables: graph.variables, + edges: [ + ...tightBounds(graph, point), + { + from: sign > 0 ? 0 : coordinate + 1, + to: sign > 0 ? coordinate + 1 : 0, + weight: 1, + }, + ], + }, + homogeneous, + proof[i], + ), + ); + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-grid-system.ts b/src/layout/relations/check-mixed-grid-system.ts new file mode 100644 index 00000000..505fd125 --- /dev/null +++ b/src/layout/relations/check-mixed-grid-system.ts @@ -0,0 +1,27 @@ +import type { RelationSystem } from "./types.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedResult } from "./mixed-result.js"; +import { mixedInput } from "./mixed-input.js"; +import { checkMixedResult } from "./check-mixed-result.js"; +import { checkMixedGrid, checkMixedGridVariation } from "./check-mixed-grid.js"; + +/** Reconstruct source rows without solving. A rational contradiction excludes + * grid solutions too. Uniqueness needs an integer point and rational fixedness + * proofs for every coordinate; motion needs two distinct integer points. + */ +export function checkMixedGridSystem( + system: RelationSystem, + rows: LinearRelation[], + result: MixedResult, +): boolean { + try { + const input = mixedInput(system, rows); + if (!checkMixedResult(input.graph, input.rows, result)) return false; + if (result.status === "contradictory") return true; + return result.status === "determined" + ? checkMixedGrid(input.graph, input.rows, result.point) + : checkMixedGridVariation(input.graph, input.rows, result.values); + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-grid.ts b/src/layout/relations/check-mixed-grid.ts new file mode 100644 index 00000000..6558f3ef --- /dev/null +++ b/src/layout/relations/check-mixed-grid.ts @@ -0,0 +1,29 @@ +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import { checkMixedVariation } from "./check-mixed-variation.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; + +/** Original-row substitution and integer ticks; no search state is trusted. */ +export function checkMixedGrid( + graph: MixedGraph, + rows: LinearRelation[], + point: Rational[], +): boolean { + return ( + checkMixedFeasible(graph, rows, point) && + point.every((v) => v.numerator % v.denominator === 0n) + ); +} + +/** Original-row feasibility, integer ticks and exact distinctness, without search. */ +export function checkMixedGridVariation( + graph: MixedGraph, + rows: LinearRelation[], + proof: Rational[][], +): boolean { + return ( + checkMixedVariation(graph, rows, proof) && + proof.every((point) => checkMixedGrid(graph, rows, point)) + ); +} diff --git a/src/layout/relations/check-mixed-result.ts b/src/layout/relations/check-mixed-result.ts new file mode 100644 index 00000000..3ae02cd8 --- /dev/null +++ b/src/layout/relations/check-mixed-result.ts @@ -0,0 +1,39 @@ +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import type { MixedResult } from "./mixed-result.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; +import { checkMixedContradiction } from "./check-mixed-contradiction.js"; +import { checkMixedVariation } from "./check-mixed-variation.js"; +import { checkMixedFixed } from "./check-mixed-fixed.js"; + +/** Check original input rows only; no search or elimination is trusted. + * A determined result needs a feasible point and both signed fixedness proofs + * for every variable. In particular, failure to find motion proves nothing. + */ +export function checkMixedResult( + graph: MixedGraph, + rows: LinearRelation[], + result: MixedResult, +): boolean { + try { + switch (result?.status) { + case "contradictory": + return checkMixedContradiction(graph, rows, result.proof); + case "underdetermined": + return checkMixedVariation(graph, rows, result.values); + case "determined": + return ( + checkMixedFeasible(graph, rows, result.point) && + Array.isArray(result.fixed) && + result.fixed.length === graph.variables.length && + graph.variables.every((_, i) => + checkMixedFixed(graph, rows, result.point, i, result.fixed[i]), + ) + ); + default: + return false; + } + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-system.ts b/src/layout/relations/check-mixed-system.ts new file mode 100644 index 00000000..34add3de --- /dev/null +++ b/src/layout/relations/check-mixed-system.ts @@ -0,0 +1,19 @@ +import type { RelationSystem } from "./types.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedResult } from "./mixed-result.js"; +import { mixedInput } from "./mixed-input.js"; +import { checkMixedResult } from "./check-mixed-result.js"; + +/** Reconstruct source rows and check the proof without invoking the solver. */ +export function checkMixedSystem( + system: RelationSystem, + rows: LinearRelation[], + result: MixedResult, +): boolean { + try { + const input = mixedInput(system, rows); + return checkMixedResult(input.graph, input.rows, result); + } catch { + return false; + } +} diff --git a/src/layout/relations/check-mixed-variation.ts b/src/layout/relations/check-mixed-variation.ts new file mode 100644 index 00000000..4e40f135 --- /dev/null +++ b/src/layout/relations/check-mixed-variation.ts @@ -0,0 +1,39 @@ +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; + +/** Two distinct points checked on original inputs prove rational motion. + * No nullspace, cone construction or projection code is trusted. + */ +export function checkMixedVariation( + graph: MixedGraph, + rows: LinearRelation[], + proof: Rational[][], + coordinate?: number, +): boolean { + try { + if ( + coordinate !== undefined && + (!Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length) + ) + return false; + if (!Array.isArray(proof) || proof.length !== 2) return false; + const [first, second] = proof; + if ( + !checkMixedFeasible(graph, rows, first) || + !checkMixedFeasible(graph, rows, second) + ) + return false; + return first.some( + (v, i) => + (coordinate === undefined || coordinate === i) && + v.numerator * second[i].denominator !== + second[i].numerator * v.denominator, + ); + } catch { + return false; + } +} diff --git a/src/layout/relations/mixed-classify.ts b/src/layout/relations/mixed-classify.ts new file mode 100644 index 00000000..070c1285 --- /dev/null +++ b/src/layout/relations/mixed-classify.ts @@ -0,0 +1,50 @@ +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph, MixedFarkasWitness } from "./mixed-rows.js"; +import { projectMixedFeasible } from "./mixed-feasible.js"; +import { projectMixedContradiction } from "./mixed-contradiction.js"; +import { projectMixedVariation } from "./mixed-variation.js"; +import { projectMixedFixed } from "./mixed-fixed.js"; +import type { MixedResult } from "./mixed-result.js"; +import { checkMixedResult } from "./check-mixed-result.js"; + +function determined( + graph: MixedGraph, + rows: LinearRelation[], + point: Rational[], + maxRows: number, +): MixedResult | null { + const fixed: MixedFarkasWitness[][] = []; + for (let coordinate = 0; coordinate < graph.variables.length; coordinate++) { + const proof = projectMixedFixed(graph, rows, point, coordinate, maxRows); + if (!proof) return null; + fixed.push(proof); + } + return { status: "determined", point, fixed }; +} + +/** Classify normalized tick bounds and integer equalities over the rationals. + * maxRows applies to each projection search separately (including each signed + * cone), not the whole call. At most 2 + 4 * variable count searches are made. + * Equality elimination, rational bit size and wall time remain unbounded. + * Null means no checked conclusion, including exhaustion; it is not a status. + * This does not classify integer-grid solutions or round coordinates. + */ +export function classifyMixed( + graph: MixedGraph, + rows: LinearRelation[], + maxRows: number, +): MixedResult | null { + const point = projectMixedFeasible(graph, rows, maxRows); + let result: MixedResult | null; + if (point === null) { + const proof = projectMixedContradiction(graph, rows, maxRows); + result = proof ? { status: "contradictory", proof } : null; + } else { + const second = projectMixedVariation(graph, rows, point, maxRows); + result = second + ? { status: "underdetermined", values: [point, second] } + : determined(graph, rows, point, maxRows); + } + return result && checkMixedResult(graph, rows, result) ? result : null; +} diff --git a/src/layout/relations/mixed-contradiction.ts b/src/layout/relations/mixed-contradiction.ts new file mode 100644 index 00000000..2c489fd8 --- /dev/null +++ b/src/layout/relations/mixed-contradiction.ts @@ -0,0 +1,37 @@ +import type { LinearRelation } from "./linear.js"; +import { mixedRows } from "./mixed-rows.js"; +import type { MixedGraph, MixedFarkasWitness } from "./mixed-rows.js"; +import { compact, leastPairs, project } from "./mixed-projection.js"; + +/** Exact Farkas search on normalized tick bounds and integer equalities. + * maxRows bounds the total input + projected rows, before compaction. Null + * means no proof, including budget exhaustion; it never implies feasibility. + * Rational bit size and input width are not bounded by this row budget. + */ +export function projectMixedContradiction( + graph: MixedGraph, + equalities: LinearRelation[], + maxRows: number, +): MixedFarkasWitness | null { + if (!Number.isSafeInteger(maxRows) || maxRows < 0) + throw new RangeError( + "Mixed projection row budget must be a nonnegative safe integer", + ); + let remaining = maxRows - graph.edges.length - 2 * equalities.length; + if (remaining < 0) return null; + let pending = mixedRows(graph, equalities); + for (let dimension = graph.variables.length; dimension >= 0; dimension--) { + const { rows, conflict } = compact(pending); + if (conflict) + return { + bounds: conflict.weights.slice(0, graph.edges.length), + equalities: conflict.weights.slice(graph.edges.length), + }; + if (dimension === 0 || rows.length === 0) return null; + const next = project(rows, leastPairs(rows, dimension), remaining); + if (!next) return null; + remaining -= next.length; + pending = next; + } + return null; +} diff --git a/src/layout/relations/mixed-feasible.ts b/src/layout/relations/mixed-feasible.ts new file mode 100644 index 00000000..fa1dc8f1 --- /dev/null +++ b/src/layout/relations/mixed-feasible.ts @@ -0,0 +1,150 @@ +import { add, divide, multiply, negate, ratio, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import { solveLinearEqualities } from "./linear.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph, MixedRow } from "./mixed-rows.js"; +import { compact, leastPairs, project } from "./mixed-projection.js"; + +const subtract = (a: Rational, b: Rational): Rational => add(a, negate(b)); + +function budget(maxRows: number): void { + if (!Number.isSafeInteger(maxRows) || maxRows < 0) + throw new RangeError( + "Mixed projection row budget must be a nonnegative safe integer", + ); +} + +function parameterRows( + graph: MixedGraph, + point: Rational[], + basis: Rational[][], +): MixedRow[] { + if ( + point.length !== graph.variables.length || + basis.some((d) => d.length !== point.length) + ) + throw new Error("Mixed affine dimensions must match variables"); + const values = [zero, ...point]; + const directions = basis.map((d) => [zero, ...d]); + return graph.edges.map(({ from, to, weight }) => { + if ( + ![from, to].every( + (v) => Number.isSafeInteger(v) && v >= 0 && v < values.length, + ) || + !Number.isSafeInteger(weight) + ) + throw new RangeError("Invalid normalized mixed bound"); + return { + cells: [ + ...directions.map((d) => subtract(d[to], d[from])), + subtract(ratio(BigInt(weight)), subtract(values[to], values[from])), + ], + weights: [], + }; + }); +} + +function restore( + rows: MixedRow[], + index: number, + values: Rational[], +): Rational[] | null { + let lower: Rational | null = null; + let upper: Rational | null = null; + for (const { cells } of rows) { + if (cells[index].numerator === 0n) continue; + const coefficients = cells.slice(0, -1).filter((_, i) => i !== index); + const used = coefficients.reduce( + (sum, v, i) => add(sum, multiply(v, values[i])), + zero, + ); + const bound = divide(subtract(cells.at(-1)!, used), cells[index]); + if (cells[index].numerator > 0n) { + if (lower === null || subtract(bound, lower).numerator > 0n) + lower = bound; + } else if (upper === null || subtract(bound, upper).numerator < 0n) + upper = bound; + } + if (lower !== null && upper !== null && subtract(lower, upper).numerator > 0n) + return null; + const value = + lower !== null && lower.numerator > 0n + ? lower + : upper !== null && upper.numerator < 0n + ? upper + : zero; + return [...values.slice(0, index), value, ...values.slice(index)]; +} + +function parameters( + pending: MixedRow[], + dimension: number, + remaining: number, +): Rational[] | null { + const frames: { rows: MixedRow[]; index: number }[] = []; + for (let size = dimension; size >= 0; size--) { + const { rows, conflict } = compact(pending); + if (conflict) return null; + if (size === 0) break; + const index = leastPairs(rows, size); + const next = project(rows, index, remaining); + if (!next) return null; + remaining -= next.length; + frames.push({ rows, index }); + pending = next; + } + let values: Rational[] = []; + for (const { rows, index } of frames.reverse()) { + const next = restore(rows, index, values); + if (!next) return null; + values = next; + } + return values; +} + +/** Search an affine space for a point meeting normalized tick bounds. + * Counts input and projected rows before compaction; null carries no status. + * The caller must check equalities and bounds independently. The budget does + * not bound rational bit size, input width, equality elimination or time. + */ +export function projectAffineFeasible( + graph: MixedGraph, + point: Rational[], + basis: Rational[][], + maxRows: number, +): Rational[] | null { + budget(maxRows); + if (graph.edges.length > maxRows) return null; + const result = parameters( + parameterRows(graph, point, basis), + basis.length, + maxRows - graph.edges.length, + ); + if (result === null) return null; + return point.map((value, i) => + result.reduce( + (sum, parameter, j) => add(sum, multiply(parameter, basis[j][i])), + value, + ), + ); +} + +/** Exact rational feasibility search; null means no point, including exhaustion. + * Equalities cost two input rows each, as in the contradiction projection. + * This does not prove grid feasibility, uniqueness or infeasibility. + */ +export function projectMixedFeasible( + graph: MixedGraph, + equalities: LinearRelation[], + maxRows: number, +): Rational[] | null { + budget(maxRows); + const remaining = maxRows - 2 * equalities.length; + if (remaining < graph.edges.length) return null; + const result = solveLinearEqualities(graph.variables, equalities); + if (result.status === "contradictory") return null; + const point = + result.status === "determined" ? result.values : result.particular; + const basis = result.status === "determined" ? [] : result.basis; + return projectAffineFeasible(graph, point, basis, remaining); +} diff --git a/src/layout/relations/mixed-fixed.ts b/src/layout/relations/mixed-fixed.ts new file mode 100644 index 00000000..bab17598 --- /dev/null +++ b/src/layout/relations/mixed-fixed.ts @@ -0,0 +1,65 @@ +import { add, negate, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph, MixedFarkasWitness } from "./mixed-rows.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; +import { projectMixedContradiction } from "./mixed-contradiction.js"; + +function cone( + graph: MixedGraph, + point: Rational[], + coordinate: number, + sign: number, +): MixedGraph { + const values = [zero, ...point]; + const edges = graph.edges + .filter(({ from, to, weight }) => { + const gap = add(values[to], negate(values[from])); + return gap.numerator === BigInt(weight) * gap.denominator; + }) + .map((edge) => ({ ...edge, weight: 0 })); + edges.push({ + from: sign === 1 ? 0 : coordinate + 1, + to: sign === 1 ? coordinate + 1 : 0, + weight: 1, + }); + return { variables: graph.variables, edges }; +} + +/** Prove one rational coordinate fixed at a feasible point using two signed + * tight-cone Farkas vectors. maxRows applies separately to each signed search; + * at most twice that many input/projected rows are generated. It does not + * bound rational bit size, input width, checking cost or wall time. Null means + * no proof (including exhaustion), never motion or a whole-system status. + */ +export function projectMixedFixed( + graph: MixedGraph, + rows: LinearRelation[], + point: Rational[], + coordinate: number, + maxRows: number, +): MixedFarkasWitness[] | null { + if (!Number.isSafeInteger(maxRows) || maxRows < 0) + throw new RangeError( + "Mixed projection row budget must be a nonnegative safe integer", + ); + if ( + !Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length || + !checkMixedFeasible(graph, rows, point) + ) + return null; + const homogeneous = rows.map((row) => ({ ...row, constant: 0 })); + const proof: MixedFarkasWitness[] = []; + for (const sign of [1, -1]) { + const result = projectMixedContradiction( + cone(graph, point, coordinate, sign), + homogeneous, + maxRows, + ); + if (!result) return null; + proof.push(result); + } + return proof; +} diff --git a/src/layout/relations/mixed-grid-system.ts b/src/layout/relations/mixed-grid-system.ts new file mode 100644 index 00000000..6502aa34 --- /dev/null +++ b/src/layout/relations/mixed-grid-system.ts @@ -0,0 +1,55 @@ +import type { RelationSystem } from "./types.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedResult } from "./mixed-result.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import type { Rational } from "./rational.js"; +import { mixedInput } from "./mixed-input.js"; +import { classifyMixed } from "./mixed-classify.js"; +import { nearbyMixedGrid } from "./mixed-grid.js"; +import { checkMixedGridVariation } from "./check-mixed-grid.js"; +import { checkMixedGridSystem } from "./check-mixed-grid-system.js"; + +function gridPair( + graph: MixedGraph, + rows: LinearRelation[], + values: Rational[][], + maxNodes: number, +): Rational[][] | null { + if (checkMixedGridVariation(graph, rows, values)) return values; + const first = nearbyMixedGrid(graph, rows, values[0], maxNodes); + if (!first) return null; + const second = nearbyMixedGrid(graph, rows, values[1], maxNodes, first); + return second ? [first, second] : null; +} + +/** Sufficient checked grid statuses for source bounds plus tick equalities. + * Preserve rational contradiction proofs and integral rational singletons; + * otherwise seek two integer points with nearby searches. Failure remains + * undecided, including fractional rational singletons and grid-only uniqueness. + * maxRows is per rational projection; maxNodes is per nearby search (at most + * two). Both are nonnegative safe integers. These caps do not bound input + * processing, equality elimination, arithmetic bit size or wall time. + * No rounding or general integer infeasibility proof. + */ +export function solveMixedGridSystem( + system: RelationSystem, + rows: LinearRelation[], + maxRows: number, + maxNodes: number, +): MixedResult | null { + if (!Number.isSafeInteger(maxNodes) || maxNodes < 0) + throw new RangeError( + "Mixed grid node budget must be a nonnegative safe integer", + ); + const input = mixedInput(system, rows); + let result: MixedResult | null = classifyMixed( + input.graph, + input.rows, + maxRows, + ); + if (result?.status === "underdetermined") { + const pair = gridPair(input.graph, input.rows, result.values, maxNodes); + result = pair ? { status: "underdetermined", values: pair } : null; + } + return result && checkMixedGridSystem(system, rows, result) ? result : null; +} diff --git a/src/layout/relations/mixed-grid.ts b/src/layout/relations/mixed-grid.ts new file mode 100644 index 00000000..5c3e7006 --- /dev/null +++ b/src/layout/relations/mixed-grid.ts @@ -0,0 +1,143 @@ +import { ratio } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; +import { checkMixedGrid } from "./check-mixed-grid.js"; + +interface Constraint { + terms: [number, bigint][]; + constant: bigint; + equality: boolean; +} + +function nearby(point: Rational[]): bigint[][] { + return point.map(({ numerator: n, denominator: d }) => { + const floor = n / d - (n % d < 0n ? 1n : 0n); + const ceil = floor + (n % d !== 0n ? 1n : 0n); + return [...new Set([floor, ceil, floor - 1n, ceil + 1n])]; + }); +} + +function constraints(graph: MixedGraph, rows: LinearRelation[]): Constraint[] { + const index = new Map(graph.variables.map((v, i) => [v, i + 1])); + return [ + ...graph.edges.map((e): Constraint => ({ + terms: [ + [e.to, 1n], + [e.from, -1n], + ], + constant: BigInt(e.weight), + equality: false, + })), + ...rows.map((r): Constraint => ({ + terms: r.terms.map((t) => [ + index.get(t.variable)!, + BigInt(t.coefficient), + ]), + constant: BigInt(r.constant), + equality: true, + })), + ]; +} + +function canComplete( + input: Constraint[], + values: (bigint | null)[], + ranges: bigint[][], +): boolean { + return input.every(({ terms, constant, equality }) => { + let min = 0n; + let max = 0n; + for (const [i, coefficient] of terms) { + const [low, high] = + values[i] === null ? ranges[i] : [values[i], values[i]]; + min += coefficient * (coefficient >= 0n ? low : high); + max += coefficient * (coefficient >= 0n ? high : low); + } + return max >= constant && (!equality || min <= constant); + }); +} + +function differs(values: (bigint | null)[], excluded?: Rational[]): boolean { + return ( + excluded === undefined || + excluded.some((v, i) => values[i + 1]! * v.denominator !== v.numerator) + ); +} + +// Iterative depth-first search avoids a call-stack limit on wide systems. +function search( + domains: bigint[][], + input: Constraint[], + remaining: number, + excluded?: Rational[], +): Rational[] | null { + const values: (bigint | null)[] = [0n, ...domains.map(() => null)]; + const ranges = [[0n, 0n], ...domains.map((d) => [d.at(-2)!, d.at(-1)!])]; + const choices = domains.map(() => 0); + let depth = 1; + let visit = true; + while (depth > 0) { + if (visit) { + if (remaining-- === 0) return null; + if ( + !canComplete(input, values, ranges) || + (depth === values.length && !differs(values, excluded)) + ) { + depth--; + visit = false; + continue; + } + if (depth === values.length) return values.slice(1).map((n) => ratio(n!)); + choices[depth - 1] = 0; + } + const domain = domains[depth - 1]; + if (choices[depth - 1] < domain.length) { + values[depth] = domain[choices[depth - 1]++]; + depth++; + visit = true; + } else { + values[depth] = null; + depth--; + visit = false; + } + } + return null; +} + +/** Seek integer ticks in floor-1 through ceil+1 around a checked rational point. + * maxNodes charges the root and every partial/complete assignment, including + * pruned ones. An already integral, nonexcluded point needs no search nodes. + * An optional checked grid point is excluded by exact value. Input checks, + * arithmetic bit size and wall time are not bounded by this cap. Null means + * undecided, including exhaustion or absence of a nearby integer solution. + * This is not an integer infeasibility or uniqueness classifier. + */ +export function nearbyMixedGrid( + graph: MixedGraph, + rows: LinearRelation[], + point: Rational[], + maxNodes: number, + excluded?: Rational[], +): Rational[] | null { + if (!Number.isSafeInteger(maxNodes) || maxNodes < 0) + throw new RangeError( + "Mixed grid node budget must be a nonnegative safe integer", + ); + if (!checkMixedFeasible(graph, rows, point)) return null; + if (excluded !== undefined && !checkMixedGrid(graph, rows, excluded)) + return null; + if ( + checkMixedGrid(graph, rows, point) && + differs([0n, ...point.map((v) => v.numerator / v.denominator)], excluded) + ) + return point; + const result = search( + nearby(point), + constraints(graph, rows), + maxNodes, + excluded, + ); + return result && checkMixedGrid(graph, rows, result) ? result : null; +} diff --git a/src/layout/relations/mixed-input.ts b/src/layout/relations/mixed-input.ts new file mode 100644 index 00000000..beceff9a --- /dev/null +++ b/src/layout/relations/mixed-input.ts @@ -0,0 +1,33 @@ +import type { RelationSystem } from "./types.js"; +import type { LinearRelation } from "./linear.js"; +import { normalizeRelations } from "./normalize.js"; + +/** Keep pins and source equalities available to exact equality elimination. + * Bounds still contain both sides; proof equality indices refer to these + * source rows first, followed by caller rows. Constants are integer ticks. + */ +export function mixedInput(system: RelationSystem, rows: LinearRelation[]) { + const graph = normalizeRelations(system); + const equalIds = new Set( + system.relations.filter((r) => r.kind === "equal").map((r) => r.id), + ); + const source: LinearRelation[] = graph.edges + .filter( + (e) => + !e.source.reverse && + (e.source.kind === "anchor" || equalIds.has(e.source.id)), + ) + .map((e) => ({ + kind: "linear", + terms: [ + ...(e.to + ? [{ variable: graph.variables[e.to - 1], coefficient: 1 }] + : []), + ...(e.from + ? [{ variable: graph.variables[e.from - 1], coefficient: -1 }] + : []), + ], + constant: e.weight, + })); + return { graph, rows: [...source, ...rows] }; +} diff --git a/src/layout/relations/mixed-projection.ts b/src/layout/relations/mixed-projection.ts new file mode 100644 index 00000000..e8658b53 --- /dev/null +++ b/src/layout/relations/mixed-projection.ts @@ -0,0 +1,81 @@ +import { add, divide, negate, one } from "./rational.js"; +import { scaleRow } from "./mixed-rows.js"; +import type { MixedRow } from "./mixed-rows.js"; + +export function compact(rows: MixedRow[]): { + rows: MixedRow[]; + conflict?: MixedRow; +} { + const unique = new Map(); + for (const row of rows) { + const pivot = row.cells.slice(0, -1).find((v) => v.numerator !== 0n); + if (!pivot) { + if (row.cells.at(-1)!.numerator > 0n) return { rows: [], conflict: row }; + continue; + } + const normalized = scaleRow( + row, + divide(one, pivot.numerator > 0n ? pivot : negate(pivot)), + ); + const key = normalized.cells + .slice(0, -1) + .map((v) => `${v.numerator};${v.denominator}`) + .join(";"); + const prior = unique.get(key); + if ( + !prior || + add(normalized.cells.at(-1)!, negate(prior.cells.at(-1)!)).numerator > 0n + ) + unique.set(key, normalized); + } + return { rows: [...unique.values()] }; +} + +export function leastPairs(rows: MixedRow[], dimension: number): number { + let index = 0; + let cost = Infinity; + for (let i = 0; i < dimension; i++) { + const lower = rows.filter((r) => r.cells[i].numerator > 0n).length; + const upper = rows.filter((r) => r.cells[i].numerator < 0n).length; + if (lower * upper < cost) { + index = i; + cost = lower * upper; + } + } + return index; +} + +const sumRows = (low: MixedRow, high: MixedRow): MixedRow => ({ + cells: low.cells.map((v, i) => add(v, high.cells[i])), + weights: low.weights.map((v, i) => add(v, high.weights[i])), +}); + +export function project( + rows: MixedRow[], + index: number, + remaining: number, +): MixedRow[] | null { + const lower: MixedRow[] = []; + const upper: MixedRow[] = []; + const next: MixedRow[] = []; + for (const row of rows) { + const coefficient = row.cells[index]; + const rest = { ...row, cells: row.cells.filter((_, i) => i !== index) }; + if (coefficient.numerator === 0n) { + if (next.length >= remaining) return null; + next.push(rest); + } else { + const positive = coefficient.numerator > 0n; + (positive ? lower : upper).push( + scaleRow( + rest, + divide(one, positive ? coefficient : negate(coefficient)), + ), + ); + } + } + if (lower.length * upper.length > remaining - next.length) return null; + for (const low of lower) + for (const high of upper) next.push(sumRows(low, high)); + return next; +} diff --git a/src/layout/relations/mixed-result.ts b/src/layout/relations/mixed-result.ts new file mode 100644 index 00000000..9ad3e44f --- /dev/null +++ b/src/layout/relations/mixed-result.ts @@ -0,0 +1,7 @@ +import type { Rational } from "./rational.js"; +import type { MixedFarkasWitness } from "./mixed-rows.js"; + +export type MixedResult = + | { status: "contradictory"; proof: MixedFarkasWitness } + | { status: "underdetermined"; values: Rational[][] } + | { status: "determined"; point: Rational[]; fixed: MixedFarkasWitness[][] }; diff --git a/src/layout/relations/mixed-rows.ts b/src/layout/relations/mixed-rows.ts new file mode 100644 index 00000000..facab450 --- /dev/null +++ b/src/layout/relations/mixed-rows.ts @@ -0,0 +1,96 @@ +import { add, multiply, negate, one, ratio, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import type { LinearRelation } from "./linear.js"; +import type { RelationGraph, RelationEdge } from "./types.js"; + +export interface MixedGraph { + variables: RelationGraph["variables"]; + edges: Pick[]; +} + +/** Weights refer to original bounds (nonnegative) and equalities (signed). */ +export interface MixedFarkasWitness { + bounds: Rational[]; + equalities: Rational[]; +} + +export interface MixedRow { + cells: Rational[]; + weights: Rational[]; +} + +export const scaleRow = (row: MixedRow, weight: Rational): MixedRow => ({ + cells: row.cells.map((v) => multiply(v, weight)), + weights: row.weights.map((v) => multiply(v, weight)), +}); + +function integer(value: number | bigint): Rational { + if (typeof value !== "bigint" && !Number.isSafeInteger(value)) + throw new RangeError( + "Mixed coefficients and constants must be safe integers", + ); + return ratio(BigInt(value)); +} + +function make( + graph: MixedGraph, + count: number, + terms: [number, Rational][], + constant: Rational, + source: number, +): MixedRow { + const cells = graph.variables.map(() => zero); + for (const [i, coefficient] of terms) cells[i] = add(cells[i], coefficient); + const weights = Array.from({ length: count }, (_, i) => + i === source ? one : zero, + ); + return { cells: [...cells, constant], weights }; +} + +function termsFor( + row: LinearRelation, + indices: Map, +): [number, Rational][] { + return row.terms.map((t) => { + const index = indices.get(t.variable); + if (index === undefined) + throw new Error(`Unknown mixed variable: ${t.variable}`); + return [index, integer(t.coefficient)]; + }); +} + +/** Translate normalized bounds and integer equalities into weighted >= rows. */ +export function mixedRows( + graph: MixedGraph, + equalities: LinearRelation[], +): MixedRow[] { + const indices = new Map(graph.variables.map((id, i) => [id, i])); + if (indices.size !== graph.variables.length) + throw new Error("Duplicate mixed variable"); + const count = graph.edges.length + equalities.length; + const bounds = graph.edges.map((e, i) => + make( + graph, + count, + [ + ...(e.to ? [[e.to - 1, one] as [number, Rational]] : []), + ...(e.from ? [[e.from - 1, negate(one)] as [number, Rational]] : []), + ], + integer(e.weight), + i, + ), + ); + return [ + ...bounds, + ...equalities.flatMap((row, i) => { + const positive = make( + graph, + count, + termsFor(row, indices), + integer(row.constant), + bounds.length + i, + ); + return [positive, scaleRow(positive, negate(one))]; + }), + ]; +} diff --git a/src/layout/relations/mixed-system.ts b/src/layout/relations/mixed-system.ts new file mode 100644 index 00000000..118c3125 --- /dev/null +++ b/src/layout/relations/mixed-system.ts @@ -0,0 +1,19 @@ +import type { RelationSystem } from "./types.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedResult } from "./mixed-result.js"; +import { mixedInput } from "./mixed-input.js"; +import { classifyMixed } from "./mixed-classify.js"; + +/** Solve source difference bounds and caller equalities jointly over rationals. + * Source measurements use drawing units; caller constants and result points use + * 1/64 ticks. No rounding is applied to rational answers. maxRows is per search, + * as in classifyMixed; null is undecided, including budget exhaustion. + */ +export function solveMixedSystem( + system: RelationSystem, + rows: LinearRelation[], + maxRows: number, +): MixedResult | null { + const input = mixedInput(system, rows); + return classifyMixed(input.graph, input.rows, maxRows); +} diff --git a/src/layout/relations/mixed-variation.ts b/src/layout/relations/mixed-variation.ts new file mode 100644 index 00000000..82a61ce1 --- /dev/null +++ b/src/layout/relations/mixed-variation.ts @@ -0,0 +1,111 @@ +import { add, divide, multiply, negate, one, ratio, zero } from "./rational.js"; +import type { Rational } from "./rational.js"; +import { solveLinearEqualities } from "./linear.js"; +import type { LinearRelation } from "./linear.js"; +import type { MixedGraph } from "./mixed-rows.js"; +import { projectAffineFeasible } from "./mixed-feasible.js"; +import { checkMixedFeasible } from "./check-mixed-feasible.js"; +import { checkMixedVariation } from "./check-mixed-variation.js"; + +const subtract = (a: Rational, b: Rational): Rational => add(a, negate(b)); + +// Slack bounds cap a positive step along the homogeneous direction. +function shift( + graph: MixedGraph, + point: Rational[], + direction: Rational[], +): Rational[] | null { + const values = [zero, ...point]; + const steps = [zero, ...direction]; + let parameter = one; + for (const { from, to, weight } of graph.edges) { + const slope = subtract(steps[to], steps[from]); + if (slope.numerator >= 0n) continue; + const slack = subtract( + subtract(values[to], values[from]), + ratio(BigInt(weight)), + ); + const bound = divide(slack, negate(slope)); + if (subtract(bound, parameter).numerator < 0n) parameter = bound; + } + if (parameter.numerator <= 0n) return null; + return point.map((v, i) => add(v, multiply(parameter, direction[i]))); +} + +function* coupledDirections( + graph: MixedGraph, + point: Rational[], + basis: Rational[][], + maxRows: number, + coordinate?: number, +): Generator { + const values = [zero, ...point]; + const tight = graph.edges + .filter( + ({ from, to, weight }) => + subtract(subtract(values[to], values[from]), ratio(BigInt(weight))) + .numerator === 0n, + ) + .map((edge) => ({ ...edge, weight: 0 })); + for (let i = 1; i <= point.length; i++) { + if (coordinate !== undefined && i !== coordinate + 1) continue; + for (const [from, to] of [ + [0, i], + [i, 0], + ]) { + const cone = { + variables: graph.variables, + edges: [...tight, { from, to, weight: 1 }], + }; + const direction = projectAffineFeasible( + cone, + point.map(() => zero), + basis, + maxRows, + ); + if (direction) yield direction; + } + } +} + +/** Return a second rational feasible point, optionally moving one coordinate. + * Project tight-bound motion cones in the equality nullspace. + * maxRows counts input and generated rows per signed affine cone search, with + * at most 2 * variable count searches (two for a requested coordinate). + * It does not bound equality elimination, bit size, checking cost or wall time. + * Null means no witness, including exhaustion, never fixedness or uniqueness. + */ +export function projectMixedVariation( + graph: MixedGraph, + rows: LinearRelation[], + first: Rational[], + maxRows: number, + coordinate?: number, +): Rational[] | null { + if (!Number.isSafeInteger(maxRows) || maxRows < 0) + throw new RangeError( + "Mixed projection row budget must be a nonnegative safe integer", + ); + if ( + coordinate !== undefined && + (!Number.isInteger(coordinate) || + coordinate < 0 || + coordinate >= graph.variables.length) + ) + return null; + if (!checkMixedFeasible(graph, rows, first)) return null; + const result = solveLinearEqualities(graph.variables, rows); + if (result.status !== "underdetermined") return null; + for (const direction of coupledDirections( + graph, + first, + result.basis, + maxRows, + coordinate, + )) { + const second = shift(graph, first, direction); + if (second && checkMixedVariation(graph, rows, [first, second], coordinate)) + return second; + } + return null; +} diff --git a/test/unit/relations/mixed-classify-properties.test.ts b/test/unit/relations/mixed-classify-properties.test.ts new file mode 100644 index 00000000..968ea690 --- /dev/null +++ b/test/unit/relations/mixed-classify-properties.test.ts @@ -0,0 +1,48 @@ +import { expect, it } from "vitest"; +import fc from "fast-check"; +import { classifyMixed } from "../../../src/layout/relations/mixed-classify.js"; +import { checkMixedResult } from "../../../src/layout/relations/check-mixed-result.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +it("classifies positive weighted sums on translated nonnegative quadrants", () => { + fc.assert( + fc.property( + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: 1, max: 9 }), + fc.integer({ min: 1, max: 9 }), + fc.integer({ min: -1, max: 1 }), + (a, b, ca, cb, slack) => { + const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: a }, + { from: 0, to: 2, weight: b }, + ], + }; + const rows: LinearRelation[] = [ + { + kind: "linear", + constant: ca * a + cb * b + slack, + terms: [ + { variable: "a", coefficient: ca }, + { variable: "b", coefficient: cb }, + ], + }, + ]; + // A negative slack is impossible, zero forces both lower endpoints, + // and a positive slack permits a segment between distinct endpoints. + const expected = + slack < 0 + ? "contradictory" + : slack === 0 + ? "determined" + : "underdetermined"; + const result = classifyMixed(graph, rows, 100)!; + expect(result?.status).toBe(expected); + expect(checkMixedResult(graph, rows, result)).toBe(true); + }, + ), + { seed: 9419, numRuns: 500 }, + ); +}); diff --git a/test/unit/relations/mixed-classify.test.ts b/test/unit/relations/mixed-classify.test.ts new file mode 100644 index 00000000..1c7f7d94 --- /dev/null +++ b/test/unit/relations/mixed-classify.test.ts @@ -0,0 +1,109 @@ +import { expect, it } from "vitest"; +import { classifyMixed } from "../../../src/layout/relations/mixed-classify.js"; +import { checkMixedResult } from "../../../src/layout/relations/check-mixed-result.js"; +import { ratio, zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 0, to: 2, weight: 0 }, + ], +}; +const sum = (constant: number): LinearRelation => ({ + kind: "linear", + terms: graph.variables.map((variable) => ({ variable, coefficient: 1 })), + constant, +}); + +it("certifies all three mixed statuses in either input order", () => { + for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + for (const [constant, status] of [ + [0, "determined"], + [1, "underdetermined"], + [-1, "contradictory"], + ] as const) { + const rows = [sum(constant)]; + const result = classifyMixed(input, rows, 100)!; + expect(result.status).toBe(status); + expect(checkMixedResult(input, rows, result)).toBe(true); + expect(checkMixedResult(input, [sum(constant + 2)], result)).toBe(false); + } + } +}); + +it("does not infer uniqueness or contradiction from exhausted searches", () => { + for (const constant of [-1, 0, 1]) + expect(classifyMixed(graph, [sum(constant)], 0)).toBeNull(); + // Feasibility succeeds with four rows; signed fixedness searches need five. + expect(classifyMixed(graph, [sum(0)], 4)).toBeNull(); + for (const budget of [-1, 0.5, Infinity, NaN]) + expect(() => classifyMixed(graph, [], budget)).toThrow(RangeError); +}); + +it("requires every fixed-coordinate proof and rejects changed points", () => { + const result = classifyMixed(graph, [sum(0)], 100)!; + expect(result.status).toBe("determined"); + if (result.status !== "determined") throw new Error("Expected uniqueness"); + expect(result.point).toEqual([zero, zero]); + expect(result.fixed).toHaveLength(2); + expect(checkMixedResult(graph, [sum(0)], { ...result, fixed: [] })).toBe( + false, + ); + expect( + checkMixedResult(graph, [sum(0)], { + ...result, + fixed: [result.fixed[0], result.fixed[0]], + }), + ).toBe(false); + expect( + checkMixedResult(graph, [sum(0)], { ...result, point: [ratio(1n), zero] }), + ).toBe(false); +}); + +it("rejects identical motion points and altered Farkas weights", () => { + const moving = classifyMixed(graph, [sum(1)], 100)!; + if (moving.status !== "underdetermined") throw new Error("Expected motion"); + expect( + checkMixedResult(graph, [sum(1)], { + ...moving, + values: [moving.values[0], moving.values[0]], + }), + ).toBe(false); + const conflict = classifyMixed(graph, [sum(-1)], 100)!; + if (conflict.status !== "contradictory") throw new Error("Expected conflict"); + expect( + checkMixedResult(graph, [sum(-1)], { + ...conflict, + proof: { ...conflict.proof, equalities: [zero] }, + }), + ).toBe(false); + expect(checkMixedResult(graph, [], null!)).toBe(false); + expect(checkMixedResult(graph, [], { status: "unknown" } as never)).toBe( + false, + ); +}); + +it("classifies empty and fractional systems without rounding", () => { + const empty = { variables: [], edges: [] }; + expect(classifyMixed(empty, [], 0)).toEqual({ + status: "determined", + point: [], + fixed: [], + }); + const rows: LinearRelation[] = [ + { + kind: "linear", + terms: [{ variable: "a", coefficient: 2 }], + constant: 1, + }, + ]; + const input = { variables: ["a"], edges: [] }; + const result = classifyMixed(input, rows, 20)!; + expect(result.status).toBe("determined"); + if (result.status === "determined") + expect(result.point).toEqual([ratio(1n, 2n)]); + expect(checkMixedResult(input, rows, result)).toBe(true); +}); diff --git a/test/unit/relations/mixed-contradiction-properties.test.ts b/test/unit/relations/mixed-contradiction-properties.test.ts new file mode 100644 index 00000000..f08b5a56 --- /dev/null +++ b/test/unit/relations/mixed-contradiction-properties.test.ts @@ -0,0 +1,54 @@ +import { expect, it } from "vitest"; +import fc from "fast-check"; +import { projectMixedContradiction } from "../../../src/layout/relations/mixed-contradiction.js"; +import { checkMixedContradiction } from "../../../src/layout/relations/check-mixed-contradiction.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +it("agrees with the exact range of a linear form over a two-variable box", () => { + fc.assert( + fc.property( + fc.tuple( + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: 0, max: 10 }), + ), + fc.tuple( + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: 0, max: 10 }), + ), + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -150, max: 150 }), + ([a, widthA], [b, widthB], x, y, constant) => { + const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: a }, + { from: 1, to: 0, weight: -a - widthA }, + { from: 0, to: 2, weight: b }, + { from: 2, to: 0, weight: -b - widthB }, + ], + }; + const rows: LinearRelation[] = [ + { + kind: "linear", + constant, + terms: [ + { variable: "a", coefficient: x }, + { variable: "b", coefficient: y }, + ], + }, + ]; + const lower = + Math.min(x * a, x * (a + widthA)) + Math.min(y * b, y * (b + widthB)); + const upper = + Math.max(x * a, x * (a + widthA)) + Math.max(y * b, y * (b + widthB)); + const impossible = constant < lower || constant > upper; + const proof = projectMixedContradiction(graph, rows, 1000); + expect(proof !== null).toBe(impossible); + if (proof) + expect(checkMixedContradiction(graph, rows, proof)).toBe(true); + }, + ), + { seed: 9415, numRuns: 500 }, + ); +}); diff --git a/test/unit/relations/mixed-contradiction.test.ts b/test/unit/relations/mixed-contradiction.test.ts new file mode 100644 index 00000000..edf0d15e --- /dev/null +++ b/test/unit/relations/mixed-contradiction.test.ts @@ -0,0 +1,107 @@ +import { expect, it } from "vitest"; +import { projectMixedContradiction } from "../../../src/layout/relations/mixed-contradiction.js"; +import { checkMixedContradiction } from "../../../src/layout/relations/check-mixed-contradiction.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; +import { ratio, zero } from "../../../src/layout/relations/rational.js"; + +const graph = { + variables: ["a", "b"], + edges: [ + { from: 1, to: 0, weight: -1 }, + { from: 2, to: 0, weight: -1 }, + ], +}; +const sum = (constant: number | bigint): LinearRelation => ({ + kind: "linear", + terms: [ + { variable: "a", coefficient: 2 }, + { variable: "b", coefficient: 2 }, + ], + constant, +}); + +it("checks a conflict requiring both bounds and a general equality", () => { + for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + const proof = projectMixedContradiction(input, [sum(6)], 100); + expect(proof).not.toBeNull(); + expect(checkMixedContradiction(input, [sum(6)], proof!)).toBe(true); + expect(proof!.bounds.every((r) => r.numerator > 0n)).toBe(true); + expect(checkMixedContradiction(input, [sum(4)], proof!)).toBe(false); + expect(projectMixedContradiction(input, [sum(4)], 100)).toBeNull(); + expect(projectMixedContradiction(input, [sum(0)], 100)).toBeNull(); + } +}); + +it("stops before exceeding the total input and generated row budget", () => { + // Four input rows fit, but the two opposite equality rows must be projected. + expect(projectMixedContradiction(graph, [sum(6)], 3)).toBeNull(); + expect(projectMixedContradiction(graph, [sum(6)], 4)).toBeNull(); + // Four inputs + three first projections (one carried) + one final pair. + expect(projectMixedContradiction(graph, [sum(6)], 7)).toBeNull(); + expect(projectMixedContradiction(graph, [sum(6)], 8)).not.toBeNull(); + expect(projectMixedContradiction(graph, [sum(6)], 100)).not.toBeNull(); + for (const budget of [-1, 0.5, Infinity, NaN]) + expect(() => projectMixedContradiction(graph, [], budget)).toThrow(); +}); + +it("keeps exact bigint and signed equality weights", () => { + const rows = [sum(18014398509481985n), sum(18014398509481986n)]; + const proof = projectMixedContradiction({ ...graph, edges: [] }, rows, 100); + expect(proof).not.toBeNull(); + expect(checkMixedContradiction({ ...graph, edges: [] }, rows, proof!)).toBe( + true, + ); + expect(proof!.equalities.some((r) => r.numerator < 0n)).toBe(true); +}); + +it("handles empty systems, repeated terms and constant contradictions", () => { + expect( + projectMixedContradiction({ variables: [], edges: [] }, [], 0), + ).toBeNull(); + const rows: LinearRelation[] = [ + { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "a", coefficient: -1 }, + ], + constant: 1, + }, + ]; + const proof = projectMixedContradiction(graph, rows, 10); + expect(checkMixedContradiction(graph, rows, proof!)).toBe(true); + const constant = { variables: [], edges: [{ from: 0, to: 0, weight: 1 }] }; + expect( + checkMixedContradiction( + constant, + [], + projectMixedContradiction(constant, [], 1)!, + ), + ).toBe(true); +}); + +it("rejects malformed or tampered source weights", () => { + const proof = projectMixedContradiction(graph, [sum(6)], 100)!; + for (const changed of [ + { ...proof, bounds: [] }, + { ...proof, equalities: [] }, + { ...proof, bounds: [zero, ...proof.bounds.slice(1)] }, + { ...proof, bounds: [ratio(-1n), ...proof.bounds.slice(1)] }, + { ...proof, equalities: [{ numerator: 1n, denominator: 0n }] }, + { ...proof, equalities: [{ numerator: 1n, denominator: -1n }] }, + ]) + expect(checkMixedContradiction(graph, [sum(6)], changed)).toBe(false); +}); + +it("rejects duplicate, unknown and unsafe linear inputs", () => { + expect(() => + projectMixedContradiction({ ...graph, variables: ["a", "a"] }, [], 100), + ).toThrow(); + for (const row of [ + { ...sum(1), terms: [{ variable: "missing", coefficient: 1 }] }, + sum(Number.MAX_SAFE_INTEGER + 1), + { ...sum(1), terms: [{ variable: "a", coefficient: 0.5 }] }, + ]) + expect(() => projectMixedContradiction(graph, [row], 100)).toThrow(); +}); diff --git a/test/unit/relations/mixed-feasible-properties.test.ts b/test/unit/relations/mixed-feasible-properties.test.ts new file mode 100644 index 00000000..b552300c --- /dev/null +++ b/test/unit/relations/mixed-feasible-properties.test.ts @@ -0,0 +1,53 @@ +import { expect, it } from "vitest"; +import fc from "fast-check"; +import { projectMixedFeasible } from "../../../src/layout/relations/mixed-feasible.js"; +import { checkMixedFeasible } from "../../../src/layout/relations/check-mixed-feasible.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +it("agrees with the exact range of a linear form over a two-variable box", () => { + fc.assert( + fc.property( + fc.tuple( + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: 0, max: 10 }), + ), + fc.tuple( + fc.integer({ min: -10, max: 10 }), + fc.integer({ min: 0, max: 10 }), + ), + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -150, max: 150 }), + ([a, widthA], [b, widthB], x, y, constant) => { + const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: a }, + { from: 1, to: 0, weight: -a - widthA }, + { from: 0, to: 2, weight: b }, + { from: 2, to: 0, weight: -b - widthB }, + ], + }; + const rows: LinearRelation[] = [ + { + kind: "linear", + constant, + terms: [ + { variable: "a", coefficient: x }, + { variable: "b", coefficient: y }, + ], + }, + ]; + const lower = + Math.min(x * a, x * (a + widthA)) + Math.min(y * b, y * (b + widthB)); + const upper = + Math.max(x * a, x * (a + widthA)) + Math.max(y * b, y * (b + widthB)); + const impossible = constant < lower || constant > upper; + const proof = projectMixedFeasible(graph, rows, 1000); + expect(proof !== null).toBe(!impossible); + if (proof) expect(checkMixedFeasible(graph, rows, proof)).toBe(true); + }, + ), + { seed: 9416, numRuns: 500 }, + ); +}); diff --git a/test/unit/relations/mixed-feasible.test.ts b/test/unit/relations/mixed-feasible.test.ts new file mode 100644 index 00000000..289a1683 --- /dev/null +++ b/test/unit/relations/mixed-feasible.test.ts @@ -0,0 +1,142 @@ +import { expect, it } from "vitest"; +import { + projectMixedFeasible, + projectAffineFeasible, +} from "../../../src/layout/relations/mixed-feasible.js"; +import { checkMixedFeasible } from "../../../src/layout/relations/check-mixed-feasible.js"; +import { ratio, zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: 1 }, + { from: 1, to: 0, weight: -1 }, + ], +}; +const row: LinearRelation = { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: 2 }, + ], + constant: 2, +}; + +it("constructs and independently checks fractional mixed points", () => { + for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + const point = projectMixedFeasible(input, [row], 100); + expect(point).toEqual([ratio(1n), ratio(1n, 2n)]); + expect(checkMixedFeasible(input, [row], point!)).toBe(true); + } +}); + +it("charges input and projected rows, even rows carried without elimination", () => { + const input = { + ...graph, + edges: [ + { from: 0, to: 1, weight: 1 }, + { from: 0, to: 2, weight: 2 }, + ], + }; + // Two input bounds, one carried row after eliminating a, zero after b. + expect(projectMixedFeasible(input, [], 2)).toBeNull(); + expect(projectMixedFeasible(input, [], 3)).toEqual([ratio(1n), ratio(2n)]); + // Two input bounds + two oriented equality rows + one projected pair. + expect(projectMixedFeasible(graph, [row], 4)).toBeNull(); + expect(projectMixedFeasible(graph, [row], 5)).toEqual([ + ratio(1n), + ratio(1n, 2n), + ]); + for (const budget of [-1, 0.5, Infinity, NaN]) + expect(() => projectMixedFeasible(graph, [], budget)).toThrow(); +}); + +it("keeps free coordinates, zero dimensions and constant constraints exact", () => { + expect(projectMixedFeasible({ variables: [], edges: [] }, [], 0)).toEqual([]); + expect(projectMixedFeasible({ ...graph, edges: [] }, [], 0)).toEqual([ + zero, + zero, + ]); + const constant = { kind: "linear" as const, terms: [], constant: 1 }; + expect( + projectMixedFeasible({ variables: [], edges: [] }, [constant], 2), + ).toBeNull(); + expect( + projectMixedFeasible( + { ...graph, edges: [{ from: 1, to: 1, weight: 1 }] }, + [], + 1, + ), + ).toBeNull(); + const huge = { + ...row, + terms: [{ variable: "a", coefficient: 2n }], + constant: 18014398509481985n, + }; + const input = { ...graph, edges: [] }; + const point = projectMixedFeasible(input, [huge], 100)!; + expect(point).toEqual([ratio(18014398509481985n, 2n), zero]); + expect(checkMixedFeasible(input, [huge], point)).toBe(true); +}); + +it("restores reordered parameters and coupled affine directions", () => { + const input = { + variables: ["a", "b", "c"], + edges: [ + { from: 0, to: 1, weight: 2 }, + { from: 1, to: 0, weight: -2 }, + { from: 0, to: 2, weight: 3 }, + { from: 0, to: 3, weight: 5 }, + ], + }; + const q = (values: number[]) => values.map((v) => ratio(BigInt(v))); + const point = projectAffineFeasible( + input, + q([0, 0, 0]), + [q([1, 0, 1]), q([0, 1, 1])], + 100, + )!; + expect(point).toEqual(q([2, 3, 5])); + expect(checkMixedFeasible(input, [], point)).toBe(true); +}); + +it("rejects changed values, rows, invalid rationals and malformed inputs", () => { + const point = projectMixedFeasible(graph, [row], 100)!; + expect(checkMixedFeasible(graph, [row], [zero, point[1]])).toBe(false); + expect(checkMixedFeasible(graph, [{ ...row, constant: 3 }], point)).toBe( + false, + ); + expect(checkMixedFeasible(graph, [row], [])).toBe(false); + for (const denominator of [0n, -1n]) + expect( + checkMixedFeasible( + graph, + [row], + [{ numerator: 1n, denominator }, point[1]], + ), + ).toBe(false); + for (const input of [ + { ...graph, variables: ["a", "a"] }, + { ...graph, edges: [{ from: -1, to: 1, weight: 0 }] }, + { ...graph, edges: [{ from: 0, to: 3, weight: 0 }] }, + { ...graph, edges: [{ from: 0.5, to: 1, weight: 0 }] }, + { ...graph, edges: [{ from: 0, to: 1, weight: 0.5 }] }, + ]) { + expect(checkMixedFeasible(input, [row], point)).toBe(false); + expect(() => projectMixedFeasible(input, [row], 100)).toThrow(); + } + for (const changed of [ + { ...row, terms: [{ variable: "missing", coefficient: 1 }] }, + { ...row, terms: [{ variable: "a", coefficient: 0.5 }] }, + { ...row, constant: Number.MAX_SAFE_INTEGER + 1 }, + ]) { + expect(checkMixedFeasible(graph, [changed], point)).toBe(false); + expect(() => projectMixedFeasible(graph, [changed], 100)).toThrow(); + } +}); + +it("rejects missing entries even for unconstrained coordinates", () => { + expect(checkMixedFeasible({ ...graph, edges: [] }, [], Array(2))).toBe(false); +}); diff --git a/test/unit/relations/mixed-fixed-properties.test.ts b/test/unit/relations/mixed-fixed-properties.test.ts new file mode 100644 index 00000000..c217e7e9 --- /dev/null +++ b/test/unit/relations/mixed-fixed-properties.test.ts @@ -0,0 +1,52 @@ +import { expect, it } from "vitest"; +import fc from "fast-check"; +import { projectMixedFixed } from "../../../src/layout/relations/mixed-fixed.js"; +import { checkMixedFixed } from "../../../src/layout/relations/check-mixed-fixed.js"; +import { zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +it("matches fixedness of a signed linear form on the nonnegative quadrant", () => { + fc.assert( + fc.property( + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -5, max: 5 }), + (a, b) => { + const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 0, to: 2, weight: 0 }, + ], + }; + const rows: LinearRelation[] = [ + { + kind: "linear", + constant: 0, + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + }, + ]; + // Same-sign nonzero coefficients force their variables to zero; + // opposite signs allow a ray. A zero coefficient leaves its variable free. + for (const [coordinate, coefficient] of [a, b].entries()) { + const fixed = coefficient !== 0 && a * b >= 0; + const proof = projectMixedFixed( + graph, + rows, + [zero, zero], + coordinate, + 100, + ); + expect(proof !== null).toBe(fixed); + if (proof) + expect( + checkMixedFixed(graph, rows, [zero, zero], coordinate, proof), + ).toBe(true); + } + }, + ), + { seed: 9417, numRuns: 500 }, + ); +}); diff --git a/test/unit/relations/mixed-fixed.test.ts b/test/unit/relations/mixed-fixed.test.ts new file mode 100644 index 00000000..99052102 --- /dev/null +++ b/test/unit/relations/mixed-fixed.test.ts @@ -0,0 +1,117 @@ +import { expect, it } from "vitest"; +import { projectMixedFixed } from "../../../src/layout/relations/mixed-fixed.js"; +import { checkMixedFixed } from "../../../src/layout/relations/check-mixed-fixed.js"; +import { ratio, zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 0, to: 2, weight: 0 }, + ], +}; +const row: LinearRelation = { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: 2 }, + ], + constant: 0, +}; + +it("proves coordinates fixed jointly by inequalities and a general equality", () => { + for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + for (const coordinate of [0, 1]) { + const proof = projectMixedFixed( + input, + [row], + [zero, zero], + coordinate, + 100, + ); + expect(proof).not.toBeNull(); + expect( + checkMixedFixed(input, [row], [zero, zero], coordinate, proof!), + ).toBe(true); + } + } +}); + +it("does not infer fixedness from one blocked sign or from slack bounds", () => { + for (const edges of [ + graph.edges, + [{ from: 1, to: 0, weight: 0 }], + [ + { from: 0, to: 1, weight: -1 }, + { from: 1, to: 0, weight: -1 }, + ], + ]) { + expect( + projectMixedFixed({ ...graph, edges }, [], [zero, zero], 0, 100), + ).toBeNull(); + } + // Both basis lines are blocked but the coupled direction (2, -1) is free. + expect( + projectMixedFixed({ ...graph, edges: [] }, [row], [zero, zero], 0, 100), + ).toBeNull(); +}); + +it("checks fractional fixed points and leaves other coordinates free", () => { + const rows = [ + { ...row, terms: [{ variable: "a", coefficient: 2 }], constant: 1 }, + ]; + const input = { ...graph, edges: [] }; + const point = [ratio(1n, 2n), zero]; + const proof = projectMixedFixed(input, rows, point, 0, 100)!; + expect(proof).not.toBeNull(); + expect(checkMixedFixed(input, rows, point, 0, proof)).toBe(true); + expect(projectMixedFixed(input, rows, point, 1, 100)).toBeNull(); + expect(checkMixedFixed(input, [], point, 0, proof)).toBe(false); +}); + +it("charges each signed search and leaves budget exhaustion undecided", () => { + const input = { + variables: ["a"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 1, to: 0, weight: 0 }, + ], + }; + // Three input rows; parallel compaction leaves one projected pair per sign. + expect(projectMixedFixed(input, [], [zero], 0, 3)).toBeNull(); + const proof = projectMixedFixed(input, [], [zero], 0, 4)!; + expect(proof).not.toBeNull(); + expect(checkMixedFixed(input, [], [zero], 0, proof)).toBe(true); + for (const budget of [-1, 0.5, Infinity, NaN]) + expect(() => projectMixedFixed(input, [], [zero], 0, budget)).toThrow(); +}); + +it("rejects tampered signs, coordinates, input rows and infeasible points", () => { + const proof = projectMixedFixed(graph, [row], [zero, zero], 0, 100)!; + expect( + checkMixedFixed(graph, [row], [zero, zero], 0, [proof[0], proof[0]]), + ).toBe(false); + expect(checkMixedFixed(graph, [], [zero, zero], 0, proof)).toBe(false); + expect( + checkMixedFixed({ ...graph, edges: [] }, [row], [zero, zero], 0, proof), + ).toBe(false); + expect(checkMixedFixed(graph, [row], [ratio(1n), zero], 0, proof)).toBe( + false, + ); + for (const coordinate of [-1, 2, 0.5, NaN]) { + expect(checkMixedFixed(graph, [row], [zero, zero], coordinate, proof)).toBe( + false, + ); + expect( + projectMixedFixed(graph, [row], [zero, zero], coordinate, 100), + ).toBeNull(); + } + expect(projectMixedFixed(graph, [row], [ratio(1n), zero], 0, 100)).toBeNull(); + expect(checkMixedFixed(graph, [row], Array(2), 0, proof)).toBe(false); + expect( + projectMixedFixed({ variables: [], edges: [] }, [], [], 0, 100), + ).toBeNull(); + expect(checkMixedFixed(graph, [row], [zero, zero], 0, [])).toBe(false); +}); diff --git a/test/unit/relations/mixed-grid-system.test.ts b/test/unit/relations/mixed-grid-system.test.ts new file mode 100644 index 00000000..919dac19 --- /dev/null +++ b/test/unit/relations/mixed-grid-system.test.ts @@ -0,0 +1,128 @@ +import { expect, it } from "vitest"; +import { solveMixedGridSystem } from "../../../src/layout/relations/mixed-grid-system.js"; +import { checkMixedGridSystem } from "../../../src/layout/relations/check-mixed-grid-system.js"; +import { solveMixedSystem } from "../../../src/layout/relations/mixed-system.js"; +import { ratio } from "../../../src/layout/relations/rational.js"; +import type { RelationSystem } from "../../../src/layout/relations/types.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const system: RelationSystem = { + variables: ["origin", "a", "b"].map((id) => ({ id, size: 0 })), + anchors: [{ id: "pin", variable: "origin", position: 0 }], + relations: ["a", "b"].map((to) => ({ + id: to, + from: "origin", + to, + kind: "minimum", + gap: 0, + })), +}; +const row = (a: number, b: number, constant: number): LinearRelation => ({ + kind: "linear", + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + constant, +}); +const bounded: RelationSystem = { + ...system, + relations: [ + ...system.relations, + ...["a", "b"].map((from) => ({ + id: `${from}-upper`, + from, + to: "origin", + kind: "minimum" as const, + gap: -1 / 64, + })), + ], +}; + +it("returns checked grid statuses from source bounds and caller equalities", () => { + // Rejecting integral rational uniqueness or trusting mere feasibility fails. + for (const [constant, status] of [ + [0, "determined"], + [1, "underdetermined"], + [-1, "contradictory"], + ] as const) { + const rows = [row(1, 1, constant)]; + const result = solveMixedGridSystem(system, rows, 100, 100)!; + expect(result.status).toBe(status); + expect(checkMixedGridSystem(system, rows, result)).toBe(true); + } +}); + +it("keeps grid-only uniqueness undecided", () => { + // In [0,1]^2, a=2b moves rationally but only (0,0) is integral. + expect(solveMixedGridSystem(bounded, [row(1, -2, 0)], 100, 1000)).toBeNull(); +}); + +it("rejects rational-only proofs, changed source pins and incomplete uniqueness", () => { + const fractionalRows = [row(2, 0, 1), row(0, 1, 0)]; + const fractional = solveMixedSystem(system, fractionalRows, 100)!; + expect(checkMixedGridSystem(system, fractionalRows, fractional)).toBe(false); + const movingRows = [row(1, -2, 0)]; + const rationalPair = solveMixedSystem(bounded, movingRows, 100)!; + expect(checkMixedGridSystem(bounded, movingRows, rationalPair)).toBe(false); + const rows = [row(1, 1, 0)]; + const fixed = solveMixedGridSystem(system, rows, 100, 100)!; + if (fixed.status !== "determined") throw new Error("Expected uniqueness"); + expect(checkMixedGridSystem(system, rows, { ...fixed, fixed: [] })).toBe( + false, + ); + expect( + checkMixedGridSystem( + { ...system, anchors: [{ ...system.anchors[0], position: 1 / 64 }] }, + rows, + fixed, + ), + ).toBe(false); + expect( + checkMixedGridSystem(system, rows, { ...fixed, point: [ratio(1n)] }), + ).toBe(false); + expect(checkMixedGridSystem(system, rows, null!)).toBe(false); + expect( + checkMixedGridSystem(system, rows, { status: "unknown" } as never), + ).toBe(false); +}); + +it("validates both budgets even on branches needing no grid search", () => { + expect(solveMixedGridSystem(system, [row(1, 1, 0)], 0, 100)).toBeNull(); + for (const cap of [-1, 0.5, Infinity, NaN]) { + expect(() => solveMixedGridSystem(system, [], cap, 100)).toThrow( + RangeError, + ); + for (const constant of [-1, 0, 1]) + expect(() => + solveMixedGridSystem(system, [row(1, 1, constant)], 100, cap), + ).toThrow(RangeError); + } + expect(() => + solveMixedGridSystem({ ...system, anchors: [] }, [], 100, 100), + ).toThrow(); + expect( + checkMixedGridSystem({ ...system, anchors: [] }, [], {} as never), + ).toBe(false); +}); + +it("agrees with exhaustive grid enumeration for small bounded coupled systems", () => { + // An unchecked rational pair or a uniqueness claim after local failure fails. + for (const a of [-2, -1, 1, 2]) + for (const b of [-2, -1, 1, 2]) + for (const constant of [-1, 0, 1, 2]) { + const points = []; + for (let x = 0; x <= 1; x++) + for (let y = 0; y <= 1; y++) + if (a * x + b * y === constant) points.push([0, x, y]); + const rows = [row(a, b, constant)]; + const result = solveMixedGridSystem(bounded, rows, 1000, 1000); + if (points.length > 1) expect(result?.status).toBe("underdetermined"); + if (!result) continue; + expect(checkMixedGridSystem(bounded, rows, result)).toBe(true); + if (result.status === "contradictory") expect(points).toHaveLength(0); + if (result.status === "determined") expect(points).toHaveLength(1); + if (result.status === "underdetermined") + expect(points.length).toBeGreaterThan(1); + } +}); diff --git a/test/unit/relations/mixed-grid-variation.test.ts b/test/unit/relations/mixed-grid-variation.test.ts new file mode 100644 index 00000000..8bdf1bd0 --- /dev/null +++ b/test/unit/relations/mixed-grid-variation.test.ts @@ -0,0 +1,60 @@ +import { expect, it } from "vitest"; +import { checkMixedGridVariation } from "../../../src/layout/relations/check-mixed-grid.js"; +import { nearbyMixedGrid } from "../../../src/layout/relations/mixed-grid.js"; +import { ratio } from "../../../src/layout/relations/rational.js"; + +const graph = { variables: ["a", "b"], edges: [{ from: 0, to: 1, weight: 0 }] }; +const rows = [ + { + kind: "linear" as const, + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: -2 }, + ], + constant: 0, + }, +]; + +it("checks distinct integer pairs against every original bound and equality", () => { + const zero = [ratio(0n), ratio(0n)]; + const other = [ratio(2n), ratio(1n)]; + expect(checkMixedGridVariation(graph, rows, [zero, other])).toBe(true); + for (const proof of [ + [zero, zero], + [zero, [{ numerator: 0n, denominator: 2n }, ratio(0n)]], + [zero, [ratio(1n), ratio(1n, 2n)]], + [zero, [ratio(-2n), ratio(-1n)]], + [zero, [ratio(2n), ratio(0n)]], + [zero, Array(2)], + [zero], + null!, + ]) + expect(checkMixedGridVariation(graph, rows, proof)).toBe(false); +}); + +it("agrees with exhaustive integer-pair enumeration on small coupled systems", () => { + // Removing exclusion handling or accepting a fractional/unchanged point fails. + for (const a of [-2, -1, 1, 2]) { + for (const b of [-2, -1, 1, 2]) { + const input = [ + { + kind: "linear" as const, + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + constant: 0, + }, + ]; + const point = [ratio(0n), ratio(0n)]; + let multiple = false; + for (let x = 0; x <= 1; x++) + for (let y = -1; y <= 1; y++) + if ((x !== 0 || y !== 0) && a * x + b * y === 0) multiple = true; + const next = nearbyMixedGrid(graph, input, point, 100, point); + expect(next !== null).toBe(multiple); + if (next) + expect(checkMixedGridVariation(graph, input, [point, next])).toBe(true); + } + } +}); diff --git a/test/unit/relations/mixed-grid.test.ts b/test/unit/relations/mixed-grid.test.ts new file mode 100644 index 00000000..d33d841a --- /dev/null +++ b/test/unit/relations/mixed-grid.test.ts @@ -0,0 +1,176 @@ +import { expect, it } from "vitest"; +import { nearbyMixedGrid } from "../../../src/layout/relations/mixed-grid.js"; +import { checkMixedGrid } from "../../../src/layout/relations/check-mixed-grid.js"; +import { ratio } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const graph = { variables: ["a", "b"], edges: [] }; +const row = ( + a: number | bigint, + b: number | bigint, + constant = 0, +): LinearRelation => ({ + kind: "linear", + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + constant, +}); + +it("moves integral coordinates too, respecting signs, bounds and exact equalities", () => { + for (const sign of [1n, -1n]) { + const input = { + ...graph, + edges: [{ from: 0, to: 1, weight: Number(sign) }], + }; + const rows = [row(1, -2)]; + const point = nearbyMixedGrid( + input, + rows, + [ratio(sign), ratio(sign, 2n)], + 100, + ); + expect(point).toEqual( + sign > 0n ? [ratio(2n), ratio(1n)] : [ratio(0n), ratio(0n)], + ); + expect(checkMixedGrid(input, rows, point!)).toBe(true); + } +}); + +it("charges every partial assignment including rejected branches", () => { + // root, a=1, four rejected b values, a=0, b=0: eight visits. + const point = [ratio(1n), ratio(1n, 2n)]; + expect(nearbyMixedGrid(graph, [row(1, -2)], point, 7)).toBeNull(); + expect(nearbyMixedGrid(graph, [row(1, -2)], point, 8)).toEqual([ + ratio(0n), + ratio(0n), + ]); + expect(nearbyMixedGrid(graph, [], [ratio(1n), ratio(2n)], 0)).toEqual([ + ratio(1n), + ratio(2n), + ]); + for (const cap of [-1, 0.5, Infinity, NaN]) + expect(() => nearbyMixedGrid(graph, [], point, cap)).toThrow(RangeError); +}); + +it("keeps unsuccessful local searches undecided even when a distant integer exists", () => { + expect( + nearbyMixedGrid(graph, [row(0, 2, 1)], [ratio(0n), ratio(1n, 2n)], 100), + ).toBeNull(); + expect( + nearbyMixedGrid(graph, [row(1, -10)], [ratio(5n), ratio(1n, 2n)], 100), + ).toBeNull(); + expect(checkMixedGrid(graph, [row(1, -10)], [ratio(0n), ratio(0n)])).toBe( + true, + ); +}); + +it("checks original input feasibility and integrality independently", () => { + expect(checkMixedGrid(graph, [], [ratio(0n), ratio(1n, 2n)])).toBe(false); + expect(checkMixedGrid(graph, [row(1, -2)], [ratio(1n), ratio(1n)])).toBe( + false, + ); + expect( + checkMixedGrid(graph, [], [{ numerator: 2n, denominator: 2n }, ratio(0n)]), + ).toBe(true); + for (const values of [ + null!, + [], + Array(2), + [ratio(0n), { numerator: 1n, denominator: 0n }], + ]) + expect(checkMixedGrid(graph, [], values)).toBe(false); + expect( + nearbyMixedGrid(graph, [row(1, -2)], [ratio(1n), ratio(1n)], 100), + ).toBeNull(); + expect( + checkMixedGrid( + { ...graph, variables: ["a", "a"] }, + [], + [ratio(0n), ratio(0n)], + ), + ).toBe(false); +}); + +it("retains empty systems and big integer tick values without numeric rounding", () => { + expect(nearbyMixedGrid({ variables: [], edges: [] }, [], [], 0)).toEqual([]); + const huge = 18014398509481985n; + const point = nearbyMixedGrid( + graph, + [row(1n, -2n)], + [ratio(huge), ratio(huge, 2n)], + 100, + ); + expect(point).toEqual([ratio(huge - 1n), ratio((huge - 1n) / 2n)]); + expect(checkMixedGrid(graph, [row(1n, -2n)], point!)).toBe(true); +}); + +it("agrees with exhaustive local enumeration on coupled rows and repeated terms", () => { + // Independent oracle: enumerate all integer pairs in the specified neighborhood. + for (const a of [-3, -1, 1, 3]) { + for (const b of [-3, -1, 1, 3]) { + for (const x of [-2, -1, 1, 2]) { + for (const y of [-2, -1, 1, 2]) { + const constant = (a * x + b * y) / 2; + if (!Number.isInteger(constant)) continue; + const rows = [row(a, b, constant)]; + // Split a coefficient to check conservative pruning of repeated terms. + rows[0].terms = [ + { variable: "a", coefficient: a - 1 }, + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: b }, + ]; + const input = { + ...graph, + edges: [{ from: 1, to: 2, weight: Math.floor((y - x) / 2) }], + }; + let feasible = false; + for (let i = Math.floor(x / 2) - 1; i <= Math.ceil(x / 2) + 1; i++) + for (let j = Math.floor(y / 2) - 1; j <= Math.ceil(y / 2) + 1; j++) + if ( + a * i + b * j === constant && + j - i >= Math.floor((y - x) / 2) + ) + feasible = true; + const result = nearbyMixedGrid( + input, + rows, + [ratio(BigInt(x), 2n), ratio(BigInt(y), 2n)], + 100, + ); + expect(result !== null).toBe(feasible); + if (result) expect(checkMixedGrid(input, rows, result)).toBe(true); + } + } + } + } +}); + +it("excludes equal grid values and charges the rejected complete assignment", () => { + const input = { variables: ["a"], edges: [] }; + const point = [ratio(0n)]; + const excluded = [{ numerator: 0n, denominator: 2n }]; + // Root, excluded a=0, accepted a=-1: three visits. + expect(nearbyMixedGrid(input, [], point, 2, excluded)).toBeNull(); + expect(nearbyMixedGrid(input, [], point, 3, excluded)).toEqual([ratio(-1n)]); + expect(nearbyMixedGrid(input, [], [ratio(1n)], 0, excluded)).toEqual([ + ratio(1n), + ]); +}); + +it("keeps absent second grid solutions undecided and validates the exclusion", () => { + const point = [ratio(0n), ratio(0n)]; + const pinned = [row(1, 0), row(0, 1)]; + expect(nearbyMixedGrid(graph, pinned, point, 100, point)).toBeNull(); + // Rational motion exists on a=2b, but this neighborhood has only (0,0). + expect(nearbyMixedGrid(graph, [row(1, -2)], point, 100, point)).toBeNull(); + for (const excluded of [[], Array(2), [ratio(0n), ratio(1n, 2n)]]) + expect(nearbyMixedGrid(graph, [], point, 100, excluded)).toBeNull(); + expect( + nearbyMixedGrid(graph, pinned, point, 100, [ratio(1n), ratio(0n)]), + ).toBeNull(); + expect( + nearbyMixedGrid({ variables: [], edges: [] }, [], [], 10, []), + ).toBeNull(); +}); diff --git a/test/unit/relations/mixed-system.test.ts b/test/unit/relations/mixed-system.test.ts new file mode 100644 index 00000000..70ed31d8 --- /dev/null +++ b/test/unit/relations/mixed-system.test.ts @@ -0,0 +1,90 @@ +import { expect, it } from "vitest"; +import { solveMixedSystem } from "../../../src/layout/relations/mixed-system.js"; +import { checkMixedSystem } from "../../../src/layout/relations/check-mixed-system.js"; +import { ratio } from "../../../src/layout/relations/rational.js"; +import type { RelationSystem } from "../../../src/layout/relations/types.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const system: RelationSystem = { + variables: [ + { id: "a", size: 0.001 }, + { id: "b", size: 0 }, + ], + anchors: [{ id: "pin", variable: "a", position: 2 / 64 }], + relations: [ + { id: "gap", from: "a", to: "b", kind: "minimum", gap: 0.001, size: "a" }, + ], +}; +const at = (constant: number | bigint): LinearRelation[] => [ + { kind: "linear", terms: [{ variable: "b", coefficient: 1 }], constant }, +]; + +it("combines rounded size and gap bounds with tick equalities", () => { + const result = solveMixedSystem(system, at(4), 100)!; + expect(result.status).toBe("determined"); + if (result.status === "determined") + expect(result.point).toEqual([ratio(2n), ratio(4n)]); + expect(checkMixedSystem(system, at(4), result)).toBe(true); + expect(solveMixedSystem(system, at(3), 100)?.status).toBe("contradictory"); + expect(solveMixedSystem(system, [], 100)?.status).toBe("underdetermined"); +}); + +it("keeps same-rank equalities and pins in the mixed system", () => { + const equal: RelationSystem = { + ...system, + relations: [{ ...system.relations[0], kind: "equal" }], + }; + const result = solveMixedSystem(equal, [], 100)!; + expect(result.status).toBe("determined"); + if (result.status === "determined") + expect(result.point).toEqual([ratio(2n), ratio(4n)]); + expect(checkMixedSystem(equal, [], result)).toBe(true); + expect(checkMixedSystem(system, [], result)).toBe(false); + expect(solveMixedSystem(equal, at(5), 100)?.status).toBe("contradictory"); +}); + +it("rejects proofs after source pins, sizes or extra rows change", () => { + const result = solveMixedSystem(system, at(4), 100)!; + expect( + checkMixedSystem( + { ...system, anchors: [{ ...system.anchors[0], position: 3 / 64 }] }, + at(4), + result, + ), + ).toBe(false); + expect( + checkMixedSystem( + { + ...system, + variables: [{ id: "a", size: 2 / 64 }, system.variables[1]], + }, + at(4), + result, + ), + ).toBe(false); + expect(checkMixedSystem(system, at(5), result)).toBe(false); + expect(checkMixedSystem(system, at(4), null!)).toBe(false); +}); + +it("retains fractional tick answers, big integers and budget exhaustion", () => { + const rows: LinearRelation[] = [ + { + kind: "linear", + terms: [{ variable: "b", coefficient: 2n }], + constant: 9n, + }, + ]; + const result = solveMixedSystem(system, rows, 100)!; + expect(result.status).toBe("determined"); + if (result.status === "determined") + expect(result.point).toEqual([ratio(2n), ratio(9n, 2n)]); + expect(checkMixedSystem(system, rows, result)).toBe(true); + expect(solveMixedSystem(system, rows, 0)).toBeNull(); + expect(() => solveMixedSystem(system, rows, -1)).toThrow(RangeError); +}); + +it("validates source systems rather than certifying malformed input", () => { + const invalid = { ...system, anchors: [] }; + expect(() => solveMixedSystem(invalid, [], 100)).toThrow(); + expect(checkMixedSystem(invalid, [], {} as never)).toBe(false); +}); diff --git a/test/unit/relations/mixed-variation-properties.test.ts b/test/unit/relations/mixed-variation-properties.test.ts new file mode 100644 index 00000000..9c4d9bcb --- /dev/null +++ b/test/unit/relations/mixed-variation-properties.test.ts @@ -0,0 +1,57 @@ +import { expect, it } from "vitest"; +import fc from "fast-check"; +import { projectMixedVariation } from "../../../src/layout/relations/mixed-variation.js"; +import { checkMixedVariation } from "../../../src/layout/relations/check-mixed-variation.js"; +import { zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +it("matches coordinate motion of a signed linear form on the nonnegative quadrant", () => { + fc.assert( + fc.property( + fc.integer({ min: -5, max: 5 }), + fc.integer({ min: -5, max: 5 }), + (a, b) => { + const graph = { + variables: ["a", "b"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 0, to: 2, weight: 0 }, + ], + }; + const rows: LinearRelation[] = [ + { + kind: "linear", + constant: 0, + terms: [ + { variable: "a", coefficient: a }, + { variable: "b", coefficient: b }, + ], + }, + ]; + // Same-sign nonzero coefficients force their variables to zero; + // opposite signs allow a ray. A zero coefficient leaves its variable free. + for (const [coordinate, coefficient] of [a, b].entries()) { + const moving = coefficient === 0 || a * b < 0; + const proof = projectMixedVariation( + graph, + rows, + [zero, zero], + 100, + coordinate, + ); + expect(proof !== null).toBe(moving); + if (proof) + expect( + checkMixedVariation( + graph, + rows, + [[zero, zero], proof], + coordinate, + ), + ).toBe(true); + } + }, + ), + { seed: 9418, numRuns: 500 }, + ); +}); diff --git a/test/unit/relations/mixed-variation.test.ts b/test/unit/relations/mixed-variation.test.ts new file mode 100644 index 00000000..e8eda5c3 --- /dev/null +++ b/test/unit/relations/mixed-variation.test.ts @@ -0,0 +1,84 @@ +import { expect, it } from "vitest"; +import { projectMixedVariation } from "../../../src/layout/relations/mixed-variation.js"; +import { checkMixedVariation } from "../../../src/layout/relations/check-mixed-variation.js"; +import { ratio, zero } from "../../../src/layout/relations/rational.js"; +import type { LinearRelation } from "../../../src/layout/relations/linear.js"; + +const graph = { + variables: ["a", "b", "c"], + edges: [ + { from: 0, to: 1, weight: 0 }, + { from: 0, to: 2, weight: 0 }, + { from: 0, to: 3, weight: 0 }, + ], +}; +const row: LinearRelation = { + kind: "linear", + terms: [ + { variable: "a", coefficient: 1 }, + { variable: "b", coefficient: 1 }, + { variable: "c", coefficient: -1 }, + ], + constant: 0, +}; +const first = [zero, zero, zero]; + +it("finds coupled motion when neither signed basis line is feasible", () => { + const rows = [ + { + ...row, + terms: row.terms.map((t) => ({ ...t, coefficient: -t.coefficient })), + }, + ]; + // a = c - b has basis (-1,1,0), (1,0,1); target b needs both. + for (const edges of [graph.edges, [...graph.edges].reverse()]) { + const input = { ...graph, edges }; + const second = projectMixedVariation(input, rows, first, 100, 1); + expect(second).not.toBeNull(); + expect(second![1].numerator).toBeGreaterThan(0n); + expect(checkMixedVariation(input, rows, [first, second!], 1)).toBe(true); + } +}); + +it("leaves fixedness and budget misses undecided", () => { + expect(projectMixedVariation(graph, [row], first, 0, 1)).toBeNull(); + const fixed = { + ...row, + terms: row.terms.map((t) => ({ ...t, coefficient: 1 })), + }; + expect(projectMixedVariation(graph, [fixed], first, 100)).toBeNull(); + expect( + projectMixedVariation({ variables: [], edges: [] }, [], [], 100), + ).toBeNull(); + for (const budget of [-1, 0.5, Infinity, NaN]) + expect(() => projectMixedVariation(graph, [row], first, budget)).toThrow(); +}); + +it("checks two original feasible points and the requested coordinate", () => { + const second = [ratio(1n), zero, ratio(1n)]; + expect(checkMixedVariation(graph, [row], [first, second])).toBe(true); + expect(checkMixedVariation(graph, [row], [first, second], 1)).toBe(false); + expect(checkMixedVariation(graph, [row], [first, first])).toBe(false); + expect( + checkMixedVariation(graph, [row], [first, [ratio(1n), zero, zero]]), + ).toBe(false); + expect( + checkMixedVariation(graph, [row], [first, [ratio(-1n), zero, ratio(-1n)]]), + ).toBe(false); + expect(checkMixedVariation(graph, [row], [first, Array(3)])).toBe(false); + expect(checkMixedVariation(graph, [row], [first])).toBe(false); + expect( + checkMixedVariation(graph, [], [[ratio(0n, 2n), zero, zero], first]), + ).toBe(false); + for (const coordinate of [-1, 3, 0.5, NaN]) { + expect(checkMixedVariation(graph, [row], [first, second], coordinate)).toBe( + false, + ); + expect( + projectMixedVariation(graph, [row], first, 100, coordinate), + ).toBeNull(); + } + expect( + projectMixedVariation(graph, [row], [ratio(1n), zero, zero], 100), + ).toBeNull(); +});