Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 71 additions & 0 deletions backend/fabric.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
"""fabric -- the instance's initial state as a woven tapestry, not a medium.

Where `scout` reads the viscosity medium as a field to move through, `fabric`
reads the instance as a FABRIC: a tapestry of qualities threaded together, giving a
holistic view of the initial state before any solving. Each thread is a chart of
instance-space with its own natural coordinate and its own decidability fold
(measured to be a Fisher-Rao metric singularity in that coordinate):

parity thread -- GF(2) rank-deficiency of the recovered XORs (fold ~0.05)
orbit thread -- symmetry coarseness / isotropy (fold ~0.9; sharper)
gyration thread -- hyperbolic depth in the Poincare mesh (distance to ∂∞)
counting thread -- at-most-one / cardinality signal
implication thread -- binary-clause fraction
shape thread -- clause/variable ratio

The fabric is the coordinate of an instance in the "cosmo manifold"; the families
occupy distinct regions of it (a distributional ledger, `scripts/fabric_ledger.py`),
and the two Fisher folds (`scripts/fisher_fold.py`) are where the metric of the
predictive field diverges.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict

from .cnf_utils import CNFFormula
from .orbifold import hyperbolic_depth, symmetry_partition
from .scout import scout, xor_rank_deficiency


@dataclass
class Fabric:
parity_kind: str # 'consistent'|'inconsistent'|'nostruct'
rank_deficiency: float # parity thread: 0 determined ... 1 free (fold ~0.05)
orbit_coarseness: float # orbit thread: 0 rigid ... 1 highly symmetric (fold ~0.9)
gyration: float # hyperbolic depth (distance to the boundary ∂∞)
counting_signal: float # at-most-one fraction (cardinality thread)
implication_signal: float # binary-clause fraction
ratio: float # clauses / variables
region: str # scout's verdict: island | tunnel | fold
predicted_frame: str

def as_dict(self) -> Dict[str, float]:
return {"rank_def": self.rank_deficiency, "orbit": self.orbit_coarseness,
"gyration": self.gyration, "counting": self.counting_signal,
"implication": self.implication_signal, "ratio": self.ratio}


def fabric(formula: CNFFormula) -> Fabric:
"""Weave the instance's initial-state tapestry -- the holistic multi-quality
coordinate of `formula` in the cosmo manifold."""
n = max(formula.num_vars, 1)
m = max(len(formula.clauses), 1)
kind, defic = xor_rank_deficiency(formula)
orbit = 1.0 - len(symmetry_partition(formula)) / n
amo = sum(1 for c in formula.clauses
if len(c) == 2 and all(l < 0 for l in c)) / m
binf = sum(1 for c in formula.clauses if len(c) == 2) / m
r = scout(formula)
return Fabric(
parity_kind=kind,
rank_deficiency=defic,
orbit_coarseness=orbit,
gyration=hyperbolic_depth(formula),
counting_signal=amo,
implication_signal=binf,
ratio=m / n,
region=r.region,
predicted_frame=r.predicted_frame,
)
16 changes: 14 additions & 2 deletions backend/frame_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ class BreathTrace:
amplitude: int # deepest single-round intake
settled: bool # reached a fixpoint/conflict (resonant rest)
verdict: str # 'SAT' | 'UNSAT' | 'CDCL_NEEDED'
entailed: Dict[int, bool] = None # the literals the coupling ENTAILED (sound)


def coupling_breath(formula: CNFFormula, max_rounds: int = 64) -> BreathTrace:
Expand All @@ -334,7 +335,7 @@ def coupling_breath(formula: CNFFormula, max_rounds: int = 64) -> BreathTrace:
of cross-frame exchange breathes visibly before settling."""
base = frame_solve(formula)
if base.status != 'CDCL_NEEDED':
return BreathTrace([], 0, 0, True, base.status)
return BreathTrace([], 0, 0, True, base.status, {})

n = formula.num_vars
le2 = [c for c in formula.clauses if len(c) <= 2]
Expand Down Expand Up @@ -386,4 +387,15 @@ def coupling_breath(formula: CNFFormula, max_rounds: int = 64) -> BreathTrace:
verdict = 'SAT'
amplitude = max((breath[i] - (breath[i - 1] if i else 0)
for i in range(len(breath))), default=0)
return BreathTrace(breath, rounds, amplitude, settled, verdict)
return BreathTrace(breath, rounds, amplitude, settled, verdict, dict(fixed))


def coupled_entailments(formula: CNFFormula):
"""The sound literals the coupling ENTAILS, even when it does not fully decide
-- GRD's escape field made concrete: carry the accumulated moving-frame
structure into the CDCL fallback instead of discarding it. Returns
(entailed: {var: bool}, verdict). Every entailed literal is implied by the
formula (2-SAT unit / weight-1 GF(2) row), so appending them as units is
satisfiability-preserving -- a sound warm-start."""
bt = coupling_breath(formula)
return (bt.entailed or {}), bt.verdict
118 changes: 118 additions & 0 deletions backend/scout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""scout -- the omni viscosity medium as a predictive field over instance-space.

Instead of one solving stream, treat the whole space as filled with GRD's
viscosity medium and SCOUT it: from cheap algebraic *detectors* (far cheaper than
the *deciders* they forecast), predict where an instance sits relative to the
decidability fold -- on the ISLAND (a frame will decide it), in TUNNEL territory
(no structure, straight to CDCL), or in the FOLD boundary layer (partial
structure, genuinely ambiguous -- run the coupling to find out).

Honest finding baked in (ESCAPE_FIELD_NOTE.md): the *decision* is a sharp
catastrophe fold, but the *predictive field* is smooth enough to scout, EXCEPT in
a boundary layer at partial coverage where whether the coupling decides depends on
the exact GF(2) rank, not a cheap feature. And structure is invisible to
clause-shape (Tseitin and random look identical by clause length) -- you must run
the algebraic detectors (xor recovery, symmetry refinement) to sense the medium.

Payoff: on confident TUNNEL the scout lets the router skip the frame deciders and
go straight to certified CDCL, removing the pre-pass overhead on unstructured
instances; on confident ISLAND it names the frame; only the FOLD band pays for the
full coupling.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict

from .binary_clause_check import check_binary_clauses
from .cardinality_check import pigeonhole_counting_refutation
from .cnf_utils import CNFFormula
from .orbifold import symmetry_partition
from .xor_extraction import _rref_gf2, extract_xors


def xor_rank_deficiency(formula: CNFFormula):
"""The NATURAL fold coordinate: the GF(2) rank-deficiency of the recovered
XOR system -- the actual algebraic content of the sign-patterns, not the crude
coverage fraction. Returns (kind, deficiency):
'nostruct' -- no XOR groups
'inconsistent' -- the XOR system forces 0=1 (a certain UNSAT island)
'consistent' -- deficiency in [0,1]: 0 = Gaussian fully DETERMINES the
spanned variables (island); >0 leaves free variables so the
parity does not pin the solution (tunnel).
The fold lives at deficiency ~ 0.05, where P(decide) drops 0.99 -> 0.12 and the
Fisher-Rao metric of the predictive field spikes (scripts/fisher_fold.py)."""
xr = extract_xors(formula)
n = formula.num_vars
spanned = set()
rows = []
for x in xr.xors:
row = 0
for v in x.variables:
row |= 1 << (v - 1)
spanned.add(v)
if x.rhs:
row |= 1 << n
rows.append(row)
if not spanned:
return "nostruct", 0.0
basis = _rref_gf2(rows, n)
if basis is None:
return "inconsistent", 0.0
return "consistent", (len(spanned) - len(basis)) / len(spanned)

ISLAND = "island" # a sound frame will decide it
TUNNEL = "tunnel" # no exploitable structure -> straight to CDCL
FOLD = "fold" # partial structure -> boundary layer, ambiguous


@dataclass
class ScoutReport:
region: str # ISLAND | TUNNEL | FOLD
predicted_frame: str # '2sat' | 'parity' | 'counting' | 'none'
confidence: float # 0..1, from how deep in the region
features: Dict[str, float]


def scout_features(formula: CNFFormula) -> Dict[str, float]:
"""Cheap detectors -- the medium's sensors. All poly and cheaper than the
Gaussian/coupling/CDCL deciders they forecast."""
n = max(formula.num_vars, 1)
m = max(len(formula.clauses), 1)
xor = extract_xors(formula).xor_clause_fraction
part = symmetry_partition(formula)
return {
"xor": xor,
"binary": sum(1 for c in formula.clauses if len(c) == 2) / m,
"amo": sum(1 for c in formula.clauses
if len(c) == 2 and all(l < 0 for l in c)) / m,
"symmetry": 1.0 - len(part) / n, # 0 rigid ... ->1 highly symmetric
"ratio": m / n,
}


def scout(formula: CNFFormula) -> ScoutReport:
"""Predict the instance's region relative to the decidability fold, from the
cheap detectors -- the viscosity medium scouted, not the trajectory run."""
f = scout_features(formula)
# a 2-SAT contradiction is cheap to confirm and always on the island
if not check_binary_clauses(formula).consistent:
return ScoutReport(ISLAND, "2sat", 1.0, f)
# counting signature: symmetric + at-most-one heavy (PHP-like)
if f["symmetry"] >= 0.6 and f["amo"] >= 0.2 or \
pigeonhole_counting_refutation(formula).refuted:
return ScoutReport(ISLAND, "counting", 0.9, f)
# parity: read the NATURAL coordinate (GF(2) rank-deficiency), not coverage.
kind, defic = xor_rank_deficiency(formula)
if kind == "inconsistent":
return ScoutReport(ISLAND, "parity", 1.0, f) # forced UNSAT
if kind == "consistent":
if defic <= 0.02: # Gaussian determines it
return ScoutReport(ISLAND, "parity", 0.98, f)
if defic <= 0.08: # the thin fold layer
return ScoutReport(FOLD, "parity", 1.0 - defic / 0.08, f)
return ScoutReport(TUNNEL, "none", min(defic, 1.0), f) # free -> tunnel
# no XOR structure at all: tunnel territory
conf = 1.0 - max(f["amo"], f["symmetry"] if f["symmetry"] > 0 else 0.0)
return ScoutReport(TUNNEL, "none", conf, f)
41 changes: 41 additions & 0 deletions backend/tests/test_fabric.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
"""Tests for the fabric (backend/fabric.py): the initial state as a woven tapestry.

Each family occupies a distinct region of the fabric-manifold; the threads read
the qualities that place it there.
"""

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "docs/ladder/scripts"))

from frame_benchmark import random_3sat, random_xorsat, tseitin # noqa: E402

from backend.eval.generators import pigeonhole # noqa: E402
from backend.fabric import fabric # noqa: E402


class TestFabricThreads:
def test_parity_family_on_the_parity_thread(self):
fb = fabric(random_xorsat(30, 30, 1))
assert fb.rank_deficiency <= 0.02 or fb.parity_kind == "inconsistent"
assert fb.region == "island" and fb.predicted_frame == "parity"

def test_pigeonhole_on_the_orbit_thread(self):
fb = fabric(pigeonhole(7)[0])
assert fb.orbit_coarseness > 0.8 # highly symmetric
assert fb.counting_signal > 0.5 # at-most-one heavy
assert fb.region == "island"

def test_random_at_the_gyration_boundary(self):
fb = fabric(random_3sat(60, round(4.26 * 60), 1))
assert fb.gyration > 5.0 # out toward the boundary ∂∞
assert fb.region == "tunnel"

def test_families_occupy_distinct_regions(self):
# the tapestry separates the families: their thread-vectors are not equal
vecs = {name: tuple(round(v, 2) for v in fabric(f).as_dict().values())
for name, f in [("tseitin", tseitin(20, 1)),
("php", pigeonhole(7)[0]),
("random", random_3sat(60, 250, 1))]}
assert len(set(vecs.values())) == 3 # all distinct
54 changes: 54 additions & 0 deletions backend/tests/test_frame_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from backend.cnf_utils import CNFFormula, verify_model
from backend.eval.generators import pigeonhole
from backend.frame_solver import (
coupled_entailments,
coupling_breath,
frame_solve,
frame_solve_coupled,
Expand Down Expand Up @@ -222,6 +223,28 @@ def test_coupling_breathes_then_settles(self):
assert b.rounds >= 1 and b.amplitude >= 1 and b.settled
assert b.verdict == "UNSAT"

def test_entailed_literals_are_sound_warm_start(self):
# every literal the coupling entails must be IMPLIED: appending them as
# units preserves satisfiability (a sound warm-start for CDCL). Checked
# by brute force on small random instances.
import random
from itertools import product
rng = random.Random(5)
for _ in range(200):
nv = rng.randint(3, 6)
cl = [[rng.choice([-1, 1]) * v
for v in rng.sample(range(1, nv + 1), rng.randint(1, 3))]
for _ in range(rng.randint(2, 12))]
f = CNFFormula(num_vars=nv, clauses=cl)
ent, _ = coupled_entailments(f)

def sat(g):
return any(verify_model(g, {i + 1: b[i] for i in range(g.num_vars)})
for b in product([False, True], repeat=g.num_vars))
warm = CNFFormula(num_vars=nv,
clauses=cl + [[v if b else -v] for v, b in ent.items()])
assert sat(f) == sat(warm) # entailed units preserve SAT/UNSAT

def test_breath_is_monotone_and_bounded(self):
# a finite CNF's coupling is monotone (fixed only grows) and always
# settles -- resonance to rest; no eternal drone here (that is the
Expand All @@ -233,6 +256,37 @@ def test_breath_is_monotone_and_bounded(self):
assert b.settled


class TestDecidabilityFold:
"""The escape field is a catastrophe fold, not a smooth Eikonal field: a
small amount of noise snaps a decided instance across the decidability cliff
to CDCL_NEEDED (U: finite -> infinite), with a near-empty far side."""

def test_escape_field_snaps_at_the_fold(self):
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]
/ "docs/ladder/scripts"))
from frame_benchmark import random_xorsat
from backend.orbifold import hyperbolic_depth
n = 26
core = random_xorsat(n, n, 2).clauses
decided = CNFFormula(num_vars=n, clauses=list(core))
bt0 = coupling_breath(decided)
assert bt0.verdict in ("SAT", "UNSAT") # on the island: decided
assert hyperbolic_depth(decided) < 1.0 # near the center

import random
rng = random.Random(1010)
noisy = CNFFormula(num_vars=n, clauses=list(core) +
[[rng.choice([-1, 1]) * rng.randint(1, n)
for _ in range(3)] for _ in range(20)])
bt1 = coupling_breath(noisy)
assert bt1.verdict == "CDCL_NEEDED" # snapped across the fold
assert hyperbolic_depth(noisy) > 5.0 # jumped toward the boundary
ent, _ = coupled_entailments(noisy)
assert len(ent) < n // 3 # near-empty far side


def _has_model(f: CNFFormula) -> bool:
"""Brute-force satisfiability check for small formulas (test oracle)."""
n = f.num_vars
Expand Down
Loading
Loading