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

Computation 127 -- P2's irreducible primitive is non-balance of v, independent of magnitude positivity
========================================================================================
Backs the open_research.md Sec 7.2 verdict (P2 reducibility, partial).  Almost all of
P2's operative content reduces to P1 + magnitude positivity, but ONE non-degeneracy commitment
survives: the NON-BALANCE of the elementary directions, |Sum_{a in D} v(a)| > 0 (the
assignment v: D -> V_7 is not antipodally cancelling).  magnitude positivity secures only the
edge-COUNT magnitude; the V_7-vector bias |Sum v| can vanish on a balanced assignment
even with the edge count maximal.  So the vector T(D) != 0 (hence hat-tau = T(D)/|T(D)|)
rests on non-balance, NOT on magnitude positivity -- vindicating complement asymmetry as a logically independent,
separately-adopted constraint (and vindicating keeping P2 for the vector).

CHECKS
------
  (1) NON-BALANCE is independent of magnitude positivity.  A balanced assignment v: D -> V_7 with
      Sum v = 0 has a maximal/positive edge count (magnitude positivity) yet |Sum v| = 0,
      so the vector bias T(D) and hat-tau are undefined.  magnitude positivity does not secure it.
  (2) G_2 PRESERVES BALANCE (refutes the Hurwitz/G_2 reduction).  G_2 is a subgroup of
      SO(7) acting LINEARLY on V_7 = Im(O), so g(Sum v) = Sum g(v(a)); a balanced set
      stays balanced and a non-balanced set keeps its norm, under every g.  The algebra
      neither forbids nor forces balance.  Demonstrated with random SO(7) maps (which
      contain the G_2 action); the load-bearing fact is linearity, which G_2 has.
  (3) NON-BALANCE is GENERIC but NOT FORCED.  The balanced locus {v : Sum v = 0} is
      codimension 7 (seven scalar constraints in V_7): a continuous random v has
      |Sum v| > 0 with probability one, balanced assignments are measure zero.  Yet PST
      fixes NO measure over v: D -> V_7 (a fixed structural datum), so "generic" has no
      substrate referent and non-balance is adopted, not derived.

A "pass": (1) balanced |Sum v| ~ 0 while edge count > 0; (2) balance drift and
norm-deviation ~ machine zero over many SO(7) maps; (3) random v never hits the
measure-zero balanced locus.
"""

from __future__ import annotations
from itertools import combinations
import numpy as np


def edge_count(D):
    """magnitude positivity on the maximal config for an all-distinct delta: C(|D|,2)."""
    return len(list(combinations(range(D), 2)))


def random_so7(rng):
    """A random SO(7) rotation (QR of a Gaussian matrix; determinant fixed to +1)."""
    A = rng.normal(size=(7, 7))
    Q, R = np.linalg.qr(A)
    Q = Q * np.sign(np.diag(R))
    if np.linalg.det(Q) < 0:
        Q[:, 0] = -Q[:, 0]
    return Q


def main():
    print("=" * 100)
    print("  Computation 127 -- P2's irreducible primitive is non-balance of v, independent of magnitude positivity")
    print("=" * 100)
    print()
    rng = np.random.default_rng(20260627)
    D = 6

    # ---- (1) non-balance independent of magnitude positivity ------------------------------
    print("  (1) NON-BALANCE vs magnitude positivity : a balanced v has maximal edge count but ZERO vector bias")
    u = rng.normal(size=(3, 7)); u /= np.linalg.norm(u, axis=1, keepdims=True)
    v_bal = np.vstack([u, -u])                         # 6 unit V_7 vectors summing to 0
    w = rng.normal(size=(6, 7)); w /= np.linalg.norm(w, axis=1, keepdims=True)   # generic
    bal_norm = np.linalg.norm(v_bal.sum(0))
    gen_norm = np.linalg.norm(w.sum(0))
    print(f"      |D| = {D},  edge count C(|D|,2) = {edge_count(D)}   (magnitude positivity: maximal, > 0)")
    print(f"      balanced v: |Sum v| = {bal_norm:.2e}   -> vector bias T(D) = 0, hat-tau UNDEFINED")
    print(f"      generic  w: |Sum w| = {gen_norm:.4f}    -> vector bias T(D) != 0, hat-tau defined")
    nonbalance_indep = (bal_norm < 1e-12) and (edge_count(D) > 0)
    print(f"      -> magnitude positivity (count > 0) does NOT secure the vector bias: {nonbalance_indep}")
    print()

    # ---- (2) G_2 / linear maps preserve balance -----------------------------
    print("  (2) G_2 subset SO(7) acts LINEARLY -> preserves balance (refutes the Hurwitz/G_2 reduction)")
    max_bal_drift = 0.0
    max_norm_dev = 0.0
    for _ in range(2000):
        g = random_so7(rng)
        max_bal_drift = max(max_bal_drift, np.linalg.norm((g @ v_bal.T).sum(1)))
        lhs = np.linalg.norm((g @ w.T).sum(1)); rhs = gen_norm
        max_norm_dev = max(max_norm_dev, abs(lhs / rhs - 1.0))
    print(f"      over 2000 random SO(7) maps:")
    print(f"        max |g.(Sum v)| for the balanced set   = {max_bal_drift:.2e}   (stays balanced)")
    print(f"        max | |Sum g.w| / |Sum w| - 1 |        = {max_norm_dev:.2e}   (norm preserved, stays non-balanced)")
    g2_preserves = (max_bal_drift < 1e-10) and (max_norm_dev < 1e-10)
    print(f"      -> the algebra maps balanced->balanced, non-balanced->non-balanced: {g2_preserves}")
    print()

    # ---- (3) non-balance generic (codim 7) but not forced -------------------
    print("  (3) NON-BALANCE is GENERIC (balanced locus codim 7, measure zero) but NOT forced")
    trials = 200_000
    V = rng.normal(size=(trials, D, 7)); V /= np.linalg.norm(V, axis=2, keepdims=True)
    norms = np.linalg.norm(V.sum(1), axis=1)
    print(f"      {trials} random unit v-assignments (|D|={D}): min |Sum v| = {norms.min():.4f}, "
          f"fraction with |Sum v| < 1e-3 = {np.mean(norms < 1e-3):.0e}")
    print(f"      the balanced locus {{v : Sum v = 0}} is {7} scalar constraints in V_7 -> codimension 7,")
    print(f"      measure zero.  But a balanced v is explicitly constructible (check 1), and PST fixes NO")
    print(f"      measure over v: D -> V_7 (a fixed structural datum), so non-balance is ADOPTED, not derived.")
    generic_not_forced = norms.min() > 1e-6
    print()

    # ---- assessment ---------------------------------------------------------
    print("=" * 100)
    print("  ASSESSMENT")
    print("=" * 100)
    print(f"  (1) non-balance independent of magnitude positivity (balanced v: count>0 but |Sum v|=0) : {nonbalance_indep}")
    print(f"  (2) G_2 / linear maps preserve balance (Hurwitz/G_2 reduction refuted)    : {g2_preserves}")
    print(f"  (3) non-balance generic (codim 7) yet constructible / unforced            : {generic_not_forced}")
    print()
    ok = nonbalance_indep and g2_preserves and generic_not_forced
    print(f"  RESULT: {'CONFIRMS Sec 7.2 -- P2 reduces to P1+magnitude positivity EXCEPT the irreducible non-balance |Sum v|>0' if ok else 'MISMATCH -- revise'}")


if __name__ == "__main__":
    main()
