#!/usr/bin/env python3
"""
PROVENANCE: SURROGATE

Computation 133 -- (A2-vol) is an AXIOM, not a theorem: a metric-preserving bulk void is
explicitly constructible, so the emergence does not pin the density (open_research §1 A6)
=================================================================================
Backs the A6 discriminator verdict (cycle: is (A2-vol) a theorem or an axiom? -> AXIOM).
The tension data T fixes the intrinsic (emergent) metric only up to DIFFEOMORPHISM; the bulk
node density that c_u reads is a SEPARATE diffeomorphism-class quantity T does not fix. This
script constructs the residual the discriminator left open: an EXPLICIT change of coordinates
(a diffeomorphism) that carves a positive-measure central VOID in the node cloud while leaving
the intrinsic geometry -- every pairwise geodesic distance -- identical, yet biases the
coordinate uniform-weight node-quadrature c_u that the A6 bias half requires to go to 1.

Two coordinate charts of the SAME intrinsic 1D manifold, with N geodesically-uniform nodes:
  chart 1 (uniform):  x_a = (a+1/2)/N,  metric g_1 = 1.
  chart 2 (void):     x'_a = CDF^{-1}(x_a) with coordinate density n(x') (a central dip),
                      metric g_2 = n(x')^2, so the SAME nodes are geodesically uniform.
Because both charts are the same intrinsic geometry related by the diffeomorphism phi = CDF^{-1},
all pairwise GEODESIC distances are identical. But A6's c_u is the COORDINATE (Euclidean)
uniform-weight node-quadrature of |grad u|^2 -- a chart-dependent object -- so the void biases it.

CHECKS
------
  (1) GEODESIC distances IDENTICAL between the charts (machine precision): the void chart is the
      same intrinsic geometry, a genuine diffeomorphic representative -- hence T-realizable.
  (2) The coordinate node-quadrature c_u = mean_a |u'(node_a)|^2 / int|u'|^2 is ~1 in the uniform
      chart but BIASED in the void chart (the void sits where |u'|^2 is large for u = sin 2pi x).
  (3) The bias grows with the void depth: the density A6 must control is a free coordinate choice
      the intrinsic geometry does not fix.

A "pass": (1) max geodesic-distance discrepancy < 1e-3; (2) |c_u-1| ~ 0 uniform, clearly != 0
void; (3) void c_u monotone in the dip amplitude. Conclusion: a metric-preserving void exists,
so (A2-vol) is an irreducible axiom -- the bias half does NOT close internally.
"""

from __future__ import annotations
import numpy as np

GRID = np.linspace(0.0, 1.0, 400001)


def density_n(amp, x0=0.5, w=0.07):
    """coordinate density of the void chart: a central dip, normalised to integrate to 1."""
    raw = 1.0 - amp * np.exp(-((GRID - x0) / w) ** 2)
    Z = np.trapezoid(raw, GRID)
    return raw / Z


def cdf_of(n):
    c = np.concatenate([[0.0], np.cumsum((n[1:] + n[:-1]) / 2.0 * np.diff(GRID))])
    return c / c[-1]


def void_nodes(N, amp):
    """x'_a = CDF^{-1}((a+1/2)/N): N nodes with coordinate density n (a central void)."""
    n = density_n(amp)
    cdf = cdf_of(n)
    u = (np.arange(N) + 0.5) / N
    return np.interp(u, cdf, GRID), n, cdf


def gradu2(x):
    return 4 * np.pi ** 2 * np.cos(2 * np.pi * x) ** 2     # |u'|^2 for u = sin(2 pi x)


CONT = 2 * np.pi ** 2                                      # int_0^1 |u'|^2 dx


def c_u_coord(nodes):
    return gradu2(nodes).mean() / CONT


def geodesic_void(a_idx, b_idx, xprime, cdf):
    """geodesic distance in chart 2 between nodes a,b = int_{x'_a}^{x'_b} n dx' = CDF diff."""
    ca = np.interp(xprime[a_idx], GRID, cdf)
    cb = np.interp(xprime[b_idx], GRID, cdf)
    return abs(cb - ca)


def main():
    print("=" * 100)
    print("  Computation 133 -- a metric-preserving bulk void is constructible: (A2-vol) is an AXIOM, not a theorem")
    print("=" * 100)
    print()
    N = 4000
    amp = 0.85
    x_uni = (np.arange(N) + 0.5) / N
    x_void, n, cdf = void_nodes(N, amp)

    # ---- (1) geodesic distances identical (same intrinsic geometry) ---------
    print("  (1) GEODESIC distances identical between the uniform and void charts (same intrinsic geometry):")
    rng = np.random.default_rng(20260628)
    maxdev = 0.0
    print(f"      {'pair (a,b)':>14} {'uniform |x_a-x_b|':>18} {'void geodesic':>14}")
    for _ in range(6):
        a, b = sorted(rng.integers(0, N, 2))
        gu = abs(x_uni[a] - x_uni[b])
        gv = geodesic_void(a, b, x_void, cdf)
        maxdev = max(maxdev, abs(gu - gv))
        print(f"      {('(%d,%d)'%(a,b)):>14} {gu:>18.6f} {gv:>14.6f}")
    p1 = maxdev < 1e-3
    print(f"      -> max geodesic discrepancy = {maxdev:.2e}: identical => the void chart is a genuine")
    print(f"         diffeomorphic representative of the same intrinsic geometry (T-realizable): {p1}")
    print()

    # ---- (2) coordinate node-quadrature c_u biased by the void --------------
    print("  (2) the COORDINATE uniform-weight node-quadrature c_u (what A6 needs -> 1) sees the void:")
    cu_uni = c_u_coord(x_uni)
    cu_void = c_u_coord(x_void)
    print(f"      uniform chart : |c_u - 1| = {abs(cu_uni-1):.5f}   (c_u = {cu_uni:.4f})")
    print(f"      void chart    : |c_u - 1| = {abs(cu_void-1):.5f}   (c_u = {cu_void:.4f})   <- biased")
    p2 = abs(cu_uni - 1) < 0.01 and abs(cu_void - 1) > 0.05
    print(f"      -> same intrinsic geometry, yet the coordinate c_u is biased by the void: {p2}")
    print()

    # ---- (3) bias grows with void depth -------------------------------------
    print("  (3) the bias grows with the void depth (the density A6 controls is a free coordinate choice):")
    print(f"      {'amp':>6} {'|c_u-1| (void chart)':>20}")
    ds = []
    for a in (0.0, 0.3, 0.6, 0.85):
        xv, _, _ = void_nodes(N, a)
        d = abs(c_u_coord(xv) - 1)
        ds.append(d)
        print(f"      {a:>6.2f} {d:>20.5f}")
    p3 = ds[0] < 0.01 and ds[-1] > 0.05 and all(ds[i] <= ds[i + 1] + 0.005 for i in range(len(ds) - 1))
    print(f"      -> monotone in the void depth: {p3}")
    print()

    print("=" * 100)
    print("  ASSESSMENT")
    print("=" * 100)
    print(f"  (1) geodesic distances identical -> metric-preserving void is T-realizable : {p1}")
    print(f"  (2) coordinate c_u biased by the void (same intrinsic geometry)            : {p2}")
    print(f"  (3) bias grows with void depth (density is a free coordinate choice)        : {p3}")
    ok = p1 and p2 and p3
    print()
    msg = ("CONFIRMS the discriminator -- a positive-measure bulk void preserving every geodesic distance is "
           "explicitly constructible while biasing the coordinate node-quadrature c_u, so the emergence does NOT "
           "pin the bulk density; (A2-vol) is an irreducible axiom and the A6 bias half does not close internally") if ok else "MISMATCH -- revise"
    print("  RESULT: " + msg)


if __name__ == "__main__":
    main()
