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

Computation 134 -- Computation 133's void bias is a dropped-metric-factor artifact: the
metric-covariant defect is void-blind; the genuine A6 residual is the fixed-g rate (open_research §1 A6)
=================================================================================
Corrects and re-scopes Computation 133 after the no-P4 analysis. Comp 133 built a bulk void as a
pure DIFFEOMORPHISM of the emergent 1D manifold (x' = CDF^{-1}(x), geodesics preserved to 1e-16,
metric g_2 = n(x')^2) and reported that it biases the uniform-weight node-quadrature c_u by ~0.10,
concluding (A2-vol) is an "irreducible bulk-density axiom". That c_u used FLAT weights |u'|^2 against
a FLAT integral, dropping the g^{-1} and sqrt(g) the void chart's own metric demands. The intrinsic
(metric-covariant) discrete defect is identically zero under a diffeomorphism: a void and its
co-transforming metric are ONE gauge orbit, so the bias was a coordinate artifact, not a density axiom.

This script shows:
  (1) FLAT c_u in the void chart (Comp 133's quantity): biased ~0.10 -- gauge-VARIANT, the wrong defect.
  (2) METRIC-COVARIANT c_u (intrinsic gradient |u'|^2/g_2 and volume sqrt(g_2)dx' = n dx'): -> 1 to
      high precision -- VOID-BLIND, confirming the bias is purely the dropped metric factors.
  (3) The GENUINE residual A6 must exclude is a FIXED-METRIC density modulation (nodes of density n on
      g = 1, NOT a diffeomorphism): there the metric-covariant c_u IS biased. This is the diffeo-
      invariant leading-coefficient / weak-discrepancy inequality eta_{K,R} < d_0^2/4, open and verified
      only for the i.i.d. surrogate -- NOT a coordinate-density gauge freedom.

A "pass": (1) flat void c_u biased; (2) metric-covariant void c_u ~ 1 (|c_u-1| < 1e-2); (3) fixed-g
modulation c_u biased. Then Comp 133 measured the wrong (coordinate) defect, while a genuine fixed-g
rate residual remains.
"""

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):
    raw = 1.0 - amp * np.exp(-((GRID - x0) / w) ** 2)
    return raw / np.trapezoid(raw, GRID)


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 gradu2(x):
    return 4 * np.pi ** 2 * np.cos(2 * np.pi * x) ** 2     # |u'|^2, u = sin 2pi x


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


def main():
    print("=" * 100)
    print("  Computation 134 -- Comp 133's void bias is a dropped-metric artifact; the genuine residual is the fixed-g rate")
    print("=" * 100)
    print()
    N = 4000
    amp = 0.85
    n = density_n(amp)
    cdf = cdf_of(n)
    u = (np.arange(N) + 0.5) / N
    xvoid = np.interp(u, cdf, GRID)                 # void-chart node positions, coordinate density n
    n_at = np.interp(xvoid, GRID, n)               # the void metric factor g_2 = n^2 at each node

    # ---- (1) FLAT c_u in the void chart (Comp 133's quantity) ----------------
    cu_flat = gradu2(xvoid).mean() / CONT_FLAT
    print("  (1) FLAT c_u in the void chart (Comp 133): drops the metric factors")
    print(f"      c_u_flat = mean|u'(x'_a)|^2 / int|u'|^2 dx  = {cu_flat:.4f}   (|c_u-1| = {abs(cu_flat-1):.4f}, biased)")
    p1 = abs(cu_flat - 1) > 0.05
    print()

    # ---- (2) METRIC-COVARIANT c_u in the void chart -------------------------
    # intrinsic |grad u|^2_{g2} = |u'|^2 / g2 = |u'|^2 / n^2 ; dvol_{g2} = sqrt(g2) dx' = n dx'
    # uniform-weight node-average of f -> int f * n dx' (nodes have density n) = int f dvol_{g2}
    num = (gradu2(xvoid) / n_at ** 2).mean()                       # node-avg of intrinsic |grad u|^2
    fg = gradu2(GRID) / n ** 2
    den = np.trapezoid(fg * n, GRID) / np.trapezoid(n, GRID)       # intrinsic average over dvol_{g2}
    cu_cov = num / den
    print("  (2) METRIC-COVARIANT c_u (intrinsic gradient |u'|^2/g_2, volume sqrt(g_2)dx' = n dx'):")
    print(f"      c_u_cov = {cu_cov:.5f}   (|c_u-1| = {abs(cu_cov-1):.5f})   <- VOID-BLIND")
    p2 = abs(cu_cov - 1) < 1e-2
    print(f"      -> the 0.10 flat bias is purely the dropped g^{{-1}}, sqrt(g) factors; a diffeomorphic void")
    print(f"         and its co-transforming metric are one gauge orbit (no density axiom): {p2}")
    print()

    # ---- (3) the GENUINE residual: a FIXED-g density modulation -------------
    # same node density n but on the FIXED Euclidean metric g = 1 (NOT a diffeomorphism):
    # metric-covariant c_u == flat c_u here (g=1), and it IS biased -> the real defect A6 must exclude
    xfix = xvoid                                                   # nodes of density n, on g = 1
    cu_fixedg = gradu2(xfix).mean() / CONT_FLAT
    print("  (3) GENUINE residual -- a FIXED-metric density modulation (nodes density n on g = 1, not a diffeo):")
    print(f"      metric-covariant c_u (= flat, since g=1) = {cu_fixedg:.4f}   (|c_u-1| = {abs(cu_fixedg-1):.4f}, biased)")
    p3 = abs(cu_fixedg - 1) > 0.05
    print(f"      -> a real (non-gauge) density modulation DOES bias the diffeo-invariant defect: this is the")
    print(f"         open leading-coefficient / weak-discrepancy rate eta_{{K,R}} < d_0^2/4, not a gauge axiom.")
    print()

    print("=" * 100)
    print("  ASSESSMENT")
    print("=" * 100)
    print(f"  (1) flat void c_u biased (the quantity Comp 133 measured)        : {p1}")
    print(f"  (2) metric-covariant void c_u -> 1 (void-blind; bias was artifact): {p2}")
    print(f"  (3) fixed-g density modulation biases the covariant c_u (genuine) : {p3}")
    ok = p1 and p2 and p3
    print()
    msg = ("CONFIRMS the no-P4 correction -- Comp 133's void bias is a dropped-metric coordinate artifact (the "
           "metric-covariant defect is void-blind), so there is no irreducible bulk-density axiom; the genuine "
           "A6 residual is the diffeo-invariant fixed-g equidistribution rate eta_{K,R} < d_0^2/4") if ok else "MISMATCH -- revise"
    print("  RESULT: " + msg)


if __name__ == "__main__":
    main()
