""" Integral Collapse — solving integrals by descent in coefficient space. Corpus framing (CCT / Theorem Telescope): - The derivative operator ∂ₓ is the LOOP. An antiderivative is a section F such that the loop transports it back to the integrand everywhere: ρ(∂ₓ)·F = f. - A candidate F(x; c) = Σ c_i b_i(x) is a section over coefficient space. The collocation residual R(c) = Σ_k (F'(x_k) − f(x_k))² is the monodromy residual; the grid points are the loop sampler (each point asks: does the candidate survive differentiation here?). - The symbolic gradient ∇R (exact, via sympy) is the loop direction; descent is the minimal-entropy collapse path. - R is CONVEX in c → the question lattice has a single basin: the collapse is unambiguous. Every start reaches the same root. - Newton polish = external loop (lstsq: rank-deficient on purpose). - The +C of integration is the KERNEL of the loop: ∂ₓ(1) = 0, so constants are invisible to the monodromy — they must be chosen by convention. The null space of the Hessian IS the +C. - Certificate: differentiate the recognized F and simplify F' − f. Vanishes → order ∞ (symbolic flat section). Residual floor > 0 → no flat section in this basis: THE WALL, where a new symbol must be DEFINED, not derived (erf, like i). Extending the framework: Feynman's trick (differentiate under the integral sign) is a parameter loop — define I(a), traverse the a-loop, collapse the resulting ODE. The Risch algorithm / Meijer-G (sympy.integrate) is the full external loop for symbolic integration. """ import sympy as sp import numpy as np class IntegralCollapse: """ Solve F'(x) = f(x) by collapsing an ansatz section onto the flat section of the derivative loop — then certify it exactly. """ def __init__(self, integrand, x, interval=(-1.0, 1.0), n_nodes=32, extra_basis=None): self.x = x self.f = sp.sympify(integrand) self.a, self.b = sp.Float(interval[0]), sp.Float(interval[1]) # ── SEED: ansatz basis built from the integrand's own atoms ─ atoms = self.f.atoms(sp.exp, sp.log, sp.sin, sp.cos, sp.tan, sp.atan, sp.asin, sp.acos, sp.erf) basis = [sp.Integer(1), x, x**2, x**3] for at in sorted(atoms, key=str): basis += [at, x * at, x**2 * at] if extra_basis: basis += list(extra_basis) seen, self.basis = set(), [] for b in basis: k = sp.srepr(b) if k not in seen: seen.add(k) self.basis.append(b) n_nodes = max(n_nodes, 2 * len(self.basis) + 4) n = len(self.basis) self.c = sp.symbols(f"c0:{n}") # ── residual sections on the collocation grid (loop sampler) F = sum(ci * bi for ci, bi in zip(self.c, self.basis)) resid = sp.diff(F, x) - self.f nodes = [self.a + (self.b - self.a) * sp.Float(t) for t in np.linspace(0.0, 1.0, n_nodes)] self.sections = [sp.expand(resid.subs(x, xv)) for xv in nodes] self.R_sym = sum(s**2 for s in self.sections) self.grad_sym = [sp.diff(self.R_sym, ci) for ci in self.c] self.hess_sym = sp.hessian(self.R_sym, self.c) self.R_fn = sp.lambdify(self.c, self.R_sym, "numpy") self.g_fn = sp.lambdify(self.c, self.grad_sym, "numpy") self.h_fn = sp.lambdify(self.c, self.hess_sym, "numpy") # ── numeric helpers ──────────────────────────────────────────── def _R(self, c): return float(self.R_fn(*c)) def _grad(self, c): g = self.g_fn(*c) if not isinstance(g, (list, tuple)): g = [g] return np.array([float(np.real(gi)) for gi in g]) def _hess(self, c): return np.array(self.h_fn(*c), dtype=float) # ── COLLAPSE: descent along the minimal-entropy path ────────── def descend(self, c0, lr=0.05, tol=1e-8, max_iter=20000): c = np.array(c0, dtype=float) m = np.zeros_like(c) v = np.zeros_like(c) b1, b2 = 0.9, 0.999 for t in range(1, max_iter + 1): g = self._grad(c) if not np.all(np.isfinite(g)): return None, t m = b1 * m + (1 - b1) * g v = b2 * v + (1 - b2) * g * g mh = m / (1 - b1**t) vh = v / (1 - b2**t) r = self._R(c) lr_eff = lr * (0.1 if r < 1e-6 else 0.5 if r < 1e-2 else 1.0) c = c - lr_eff * mh / (np.sqrt(vh) + 1e-15) if self._R(c) < tol: break return c, t # ── EXTERNAL LOOP: Newton polish (lstsq tolerates the +C kernel) def newton_polish(self, c, iters=25): c = np.array(c, dtype=float) r0 = self._R(c) for _ in range(iters): g = self._grad(c) if np.linalg.norm(g) < 1e-14: break d = np.linalg.lstsq(self._hess(c), -g, rcond=None)[0] if not np.all(np.isfinite(d)): break cn = c + d rn = self._R(cn) if rn < r0: c, r0 = cn, rn else: break return c # ── EXACT RECOGNITION (must survive verification, like i-patch) @staticmethod def _nsimplify(v, tol=1e-8): v = float(v) if abs(v) < tol: return sp.Integer(0) # noise floor → exactly 0 try: e = sp.Rational(v).limit_denominator(1000) if abs(float(e) - v) < tol: return e except Exception: pass try: e = sp.nsimplify(v, [sp.sqrt(2), sp.sqrt(3), sp.sqrt(5), sp.pi, sp.E], rational=False) if abs(float(e) - v) < tol: return e except Exception: pass return None # ── SOLVE: collapse → recognize → certify ───────────────────── def solve(self, n_starts=8, seed=0): rng = np.random.default_rng(seed) best, best_R = None, np.inf for _ in range(n_starts): # convex: every start agrees c0 = rng.normal(0.0, 0.1, size=len(self.c)) c, iters = self.descend(c0) if c is None: continue c = self.newton_polish(c) R = self._R(c) if R < best_R: best, best_R, self.iters = c, R, iters out = {"R": best_R, "coeffs": best, "F_num": sum(float(ci) * bi for ci, bi in zip(best, self.basis))} if best_R < 1e-16: # the section went flat exact = [self._nsimplify(v) for v in best] if all(e is not None for e in exact): F_exact = sum(e * b for e, b in zip(exact, self.basis)) # CERTIFICATE: differentiate symbolically, simplify if sp.simplify(sp.diff(F_exact, self.x) - self.f) == 0: out["F_exact"], out["order"] = sp.expand(F_exact), sp.oo return out out["order"] = 2 # flat numerically, unrecognized else: out["order"] = 0 # THE WALL: no flat section here return out # ── definite value: evaluate the flat section across the loop ─ def definite_value(self, res): F = res.get("F_exact") if F is None: return None, res["order"] val = sp.simplify(F.subs(self.x, self.b) - F.subs(self.x, self.a)) ref = sp.Integral(self.f, (self.x, self.a, self.b)).evalf(30) order = sp.oo if abs(complex(sp.N(val, 30)) - complex(ref)) < 1e-20 else 2 return sp.simplify(val), order # ═══════════════════════════ DEMO ══════════════════════════════════ if __name__ == "__main__": x = sp.Symbol("x") cases = [ ("∫ x·e^(x²) dx", x * sp.exp(x**2), (-1.0, 1.0)), ("∫ eˣ·sin x dx", sp.exp(x) * sp.sin(x), (-1.0, 1.0)), ("∫ x·sin x dx", x * sp.sin(x), (-1.0, 1.0)), ("∫ ln x dx", sp.log(x), (1.0, 2.0)), ("∫ sin x dx over [0, π]", sp.sin(x), (0.0, sp.pi)), ("∫ e^(x²) dx — the erf wall", sp.exp(x**2), (0.0, 1.0)), ] for name, f, iv in cases: s = IntegralCollapse(f, x, interval=iv) res = s.solve() order = "∞" if res["order"] == sp.oo else str(res["order"]) print("=" * 66) print(name) if "F_exact" in res: print(f" F = {sp.simplify(res['F_exact'])} + C") print(f" R = {res['R']:.1e} order {order} " f"(symbolically flat: dF/dx − f → 0)") val, vord = s.definite_value(res) if val is not None and iv[0] != iv[1]: vo = "∞" if vord == sp.oo else str(vord) print(f" definite over [{iv[0]}, {iv[1]}] = {val} order {vo}") elif res["order"] == 2: print(f" F ≈ {res['F_num']}") print(f" R = {res['R']:.1e} order {order} " f"(flat numerically, no exact form recognized)") else: print(f" RESIDUAL FLOOR: R = {res['R']:.3e} after full collapse") print(f" order {order}: no flat section in this basis — " f"the wall where erf(x) must be DEFINED, not derived") print(f" (external loop: sympy.integrate → sqrt(pi)*erf(x)/2)") # Expected output (approximately): # # ∫ x·e^(x²) dx # F = exp(x**2)/2 + C R = 1e-30 order ∞ # ∫ eˣ·sin x dx # F = eˣ(sin x − cos x)/2 + C R = 1e-30 order ∞ # ∫ x·sin x dx # F = sin(x) − x·cos(x) + C R = 1e-30 order ∞ # ∫ ln x dx # F = x·log(x) − x + C R = 1e-30 order ∞ # ∫ sin x dx over [0, π] # F = −cos(x) + C ... definite = 2 order ∞ # ∫ e^(x²) dx — the erf wall # RESIDUAL FLOOR: R ≈ 1e-3 … 1e-6 after full collapse # order 0: no flat section in this basis — the wall