Download Collapse-Descent/integral-collapse-solver.py from perrabyte/higher-accuracy-integrals: direct link, hf CLI and curl.
- Browser
- Download file 10.5 kB
-
https://huggingface.co/datasets/perrabyte/higher-accuracy-integrals/resolve/main/Collapse-Descent/integral-collapse-solver.py
- Command line
-
hf download hf://datasets/perrabyte/higher-accuracy-integrals/Collapse-Descent/integral-collapse-solver.py
-
curl -L -o integral-collapse-solver.py https://huggingface.co/datasets/perrabyte/higher-accuracy-integrals/resolve/main/Collapse-Descent/integral-collapse-solver.py
10.5 kB
| """ | |
| 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) | |
| 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 |