#!/usr/bin/env python3
"""
Computation 78 -- Structural derivation candidates for beta and the residual direction
========================================================================================
Third hard-research push in the Option B sequence.  Comp 77 found that the
dynamical Boltzmann mechanism can reproduce the SM up-type Yukawa hierarchy
with beta ~ 28.24 and (p_1, p_2, p_3) ~ (0.52, 0.35, 0.13) -- but those two
inputs are unmotivated.  This computation tests specific structural
candidates for each.

STRUCTURAL CANDIDATES FOR beta
-------------------------------
  (1) beta = dim(SO(8)) = 28.  Numerically VERY close to Comp 77's best-fit
      28.24.  Discrepancy ~0.85%, possibly within fitting noise.
      Motivation: Spin(8) is the rotation group of O = R^8; triality permutes
      three 8-dim reps; PST has three generations.

  (2) beta = dim(G_2) = 14.  G_2 = Aut(O) preserves the V_7 directional
      structure.  Numerically too small.

  (3) beta = 4 * dim(V_7) = 28.  Same as (1) numerically, different motivation:
      a 'V_7 inverse-temperature' that scales with V_7 dim and the spacetime
      KO-dim 4.  Coincides with (1).

  (4) beta = log 2 * |D| at matched scaling.  Depends on |D|; not D-independent.

  (5) beta = max-entropy Lagrange multiplier at the modal-threshold constraint.
      Computable from Comp 75's Cramer rate function I'(alpha) at the
      relevant alpha.

STRUCTURAL CANDIDATES FOR (p_1, p_2, p_3)
-----------------------------------------
  (A) Cartan-decomposition pattern under SU(3)_c -> T^2 breaking.
      The Cartan torus T^2 of SU(3) has two specific Cartan directions;
      the residual direction projects onto them with computable angles.

  (B) Specific T(C) direction at the modal sublimation extremum.
      If modal sublimation selects T(C) at a specific point of the threshold
      surface |T(C)| = tau, the residual direction is determined.

  (C) Fano-plane angle pattern.  The three Q_k correspond to three Fano
      lines through tau-hat.  The angles between these and an arbitrary
      direction give specific p_k values.

THIS COMPUTATION
----------------
Tests each candidate concretely and checks against Comp 77's best-fit values
(beta = 28.24, (p_1, p_2, p_3) = (0.52, 0.35, 0.13)).
"""

from __future__ import annotations
import math
import numpy as np


def candidate_betas():
    """Returns dict of structural beta candidates."""
    return {
        "dim(SO(8))": 28,
        "dim(SO(8)) = 8*7/2": 8 * 7 / 2,
        "dim(G_2)": 14,
        "dim(Spin(8))": 28,
        "4 * dim(V_7) = 4*7": 4 * 7,
        "dim(SU(3))^2 = 64 / something": 64 / 28 * 28,  # to be tested
        "Comp 77 best fit": 28.24,
    }


def comp77_target_yukawas():
    """SM up-type Yukawas (normalised to top)."""
    return np.array([1.0, 0.0076, 1.3e-5])


def comp77_p_target():
    """Comp 77 best-fit (p_1, p_2, p_3)."""
    return np.array([0.5237, 0.3509, 0.1254])


def yukawa_hierarchy_from(beta: float, p: np.ndarray) -> np.ndarray:
    """Compute the Yukawa hierarchy from (beta, p)."""
    rates = np.exp(-beta * (1 - p))
    return rates / rates.max()


def check_beta_candidate(beta_name: str, beta_val: float) -> dict:
    """Check whether a candidate beta with Comp 77's p-vector reproduces SM."""
    p = comp77_p_target()
    yukawas = yukawa_hierarchy_from(beta_val, p)
    target = comp77_target_yukawas()
    log_yukawas = np.log10(yukawas + 1e-30)
    log_target = np.log10(target + 1e-30)
    log_diff = log_yukawas - log_target
    return {
        "beta_name": beta_name,
        "beta_val": beta_val,
        "yukawas": yukawas.tolist(),
        "log_diff": log_diff.tolist(),
        "max_log_err": float(np.max(np.abs(log_diff))),
    }


def cartan_directions_SU3():
    """Returns the two Cartan directions of SU(3) embedded in R^3.
    These are the lambda_3 and lambda_8 Gell-Mann eigenvectors (diagonal).
    For SU(3) acting on 3 orthogonal 2-planes in R^6, the Cartan T^2 directions
    pick out specific weight patterns.

    Returns the three weight patterns (eigenvalues under T_3, T_8) for the
    SU(3) fundamental representation, which give the (p_1, p_2, p_3) pattern
    under generic breaking T^2 -> identity.
    """
    # Fundamental weights of SU(3): (1, 0, 0), (0, 1, 0), (0, 0, 1) in
    # 3 orthogonal directions
    # Under T^2 they have specific (T_3, T_8) eigenvalues
    T3_weights = [1 / 2, -1 / 2, 0]
    T8_weights = [1 / (2 * math.sqrt(3)), 1 / (2 * math.sqrt(3)), -1 / math.sqrt(3)]
    return T3_weights, T8_weights


def main():
    print("=" * 100)
    print("  Computation 78 -- structural derivation candidates for beta and residual direction")
    print("=" * 100)
    print()

    print("PART 1: STRUCTURAL CANDIDATES FOR beta")
    print("-" * 100)
    print()
    target_p = comp77_p_target()
    print(f"  Using Comp 77's best-fit p = ({target_p[0]:.4f}, {target_p[1]:.4f}, {target_p[2]:.4f})")
    print(f"  Target hierarchy: (1.0, 7.6e-3, 1.3e-5)")
    print()
    print(f"  {'candidate':>35}  {'beta':>10}  {'yukawas':>40}  {'max log err':>14}")

    for name, beta_val in candidate_betas().items():
        result = check_beta_candidate(name, beta_val)
        y = result["yukawas"]
        max_err = result["max_log_err"]
        y_str = f"({y[0]:.2e}, {y[1]:.2e}, {y[2]:.2e})"
        print(f"  {name:>35}  {beta_val:>10.3f}  {y_str:>40}  {max_err:>14.4f}")
    print()

    print("  STRUCTURAL FIT FINDING:")
    print("  - dim(SO(8)) = 28 (and equivalently dim(Spin(8)) = 28, or 4 * dim(V_7) = 28):")
    print("    beta = 28 with Comp 77's p gives yukawas within 0.2 orders of magnitude")
    print("    of the SM hierarchy.")
    print("  - This is suggestive but does NOT uniquely identify the structural origin")
    print("    of beta, since SO(8) and Spin(8) and 4*V_7 are all dim 28.")
    print("  - The most physically motivated reading: Spin(8) triality acts on the three")
    print("    octonion sub-algebras (the three 8-dim representations are permuted by")
    print("    triality), and PST has three generations.")
    print("  - HONEST CAVEAT: 0.85% discrepancy with Comp 77's best fit (28 vs 28.24)")
    print("    might be fitting noise, or might be a real structural correction.")
    print()

    print("PART 2: STRUCTURAL CANDIDATES FOR (p_1, p_2, p_3)")
    print("-" * 100)
    print()
    print("  Comp 77 best-fit: (0.5237, 0.3509, 0.1254)")
    print()

    print("  Candidate A: Cartan T^2 weights of SU(3) under generic breaking")
    print("  ---")
    T3, T8 = cartan_directions_SU3()
    print(f"  T_3 eigenvalues: {T3}")
    print(f"  T_8 eigenvalues: {T8}")
    print("  These are degenerate -- two have the same T_3 eigenvalue.  Don't directly")
    print("  give a three-distinct-p_k pattern.  Doesn't match Comp 77 unless additional")
    print("  breaking parameter is specified.")
    print()

    print("  Candidate B: Cosine-pattern from Fano-plane angles")
    print("  ---")
    # In the Fano plane, the three lines through e_1 contain pairs (e_2, e_3),
    # (e_4, e_5), (e_6, e_7).  An arbitrary direction in tau-hat^perp = R^6 has
    # cos^2 projections onto each pair.
    # Test: specific 'Fano-symmetric' direction with angles based on cubic roots
    # of unity (since three Q_k correspond to Z_3 rotation in some sense)
    angles_candidates = [
        ("e_2 direction", np.array([0, 1, 0, 0, 0, 0, 0])),
        ("e_3 direction", np.array([0, 0, 1, 0, 0, 0, 0])),
        ("Q_1 diagonal (e_2 + e_3) / sqrt(2)",
         np.array([0, 1, 1, 0, 0, 0, 0]) / math.sqrt(2)),
        ("Generic (1, 1, 1, 1, 1, 1) / sqrt(6) in tau-hat^perp",
         np.array([0, 1, 1, 1, 1, 1, 1]) / math.sqrt(6)),
        ("Heavily weighted toward Q_1 (3, 3, 1, 1, 0.5, 0.5)",
         np.array([0, 3, 3, 1, 1, 0.5, 0.5]) / np.linalg.norm(
             np.array([0, 3, 3, 1, 1, 0.5, 0.5]))),
    ]
    print(f"  {'direction':>50}  {'p_1':>10}  {'p_2':>10}  {'p_3':>10}")
    for name, vec in angles_candidates:
        # Projections onto Q_k ∩ tau-hat^perp
        p_1 = vec[1] ** 2 + vec[2] ** 2
        p_2 = vec[3] ** 2 + vec[4] ** 2
        p_3 = vec[5] ** 2 + vec[6] ** 2
        total = p_1 + p_2 + p_3
        if total > 1e-9:
            p_1 /= total
            p_2 /= total
            p_3 /= total
        ps = sorted([p_1, p_2, p_3], reverse=True)
        print(f"  {name:>50}  {ps[0]:>10.4f}  {ps[1]:>10.4f}  {ps[2]:>10.4f}")
    print()

    # Try to find a direction that EXACTLY gives Comp 77's p-vector
    target = comp77_p_target()
    print(f"  Target: ({target[0]:.4f}, {target[1]:.4f}, {target[2]:.4f})")
    print()

    # Direction whose projections give the target
    # p_1 = v_1^2 + v_2^2, p_2 = v_3^2 + v_4^2, p_3 = v_5^2 + v_6^2
    # Choose v_1 = v_2 = sqrt(p_1/2), etc.
    v = np.zeros(7)
    for k in range(3):
        coords = np.sqrt(target[k] / 2)
        v[1 + 2 * k] = coords
        v[2 + 2 * k] = coords
    print(f"  Constructed direction giving exact p match: v = {v}")
    print()

    print("  HONEST FINDING: Comp 77's target (p_1, p_2, p_3) = (0.52, 0.35, 0.13) does")
    print("  not match any structurally privileged direction we can identify (the Cartan")
    print("  directions of SU(3), Fano-plane symmetric directions, or generic axis-")
    print("  aligned directions).  The fit found by Comp 77's random search is a")
    print("  specific point in a 5-dimensional parameter space.")
    print()
    print("  Without identifying a structural principle that selects this specific")
    print("  direction, Option B does NOT close.  Comp 76 ruled out the static")
    print("  approach; Comp 77 showed the dynamical mechanism is viable but needs two")
    print("  structural inputs; Comp 78 tests candidate structural origins for both")
    print("  inputs and finds:")
    print()
    print("    - beta = 28 (Spin(8) triality / 4*V_7) is suggestive at 0.85% level")
    print("      but doesn't uniquely identify the origin.")
    print("    - The residual direction (p_1, p_2, p_3) ~ (0.52, 0.35, 0.13)")
    print("      does NOT correspond to any structurally privileged direction we")
    print("      have identified.")
    print()
    print("  This suggests the dynamical mechanism, while quantitatively viable, may")
    print("  not be the right STRUCTURAL closure of Option B.  The actual mechanism")
    print("  might involve a DIFFERENT functional form (not Boltzmann), or different")
    print("  structural inputs, or it may be that the Yukawa hierarchy is genuinely")
    print("  contingent in T(C) (the structural-scope theorem holds).")
    print()
    print("  Honest verdict after Comps 76, 77, 78: Option B's structural closure")
    print("  remains elusive.  The mechanism is quantitatively viable but the")
    print("  required parameters don't match any clean structural reading.  Either")
    print("  the mechanism is the right type but the parameters need an unanticipated")
    print("  structural origin, or it's the wrong type and a different mechanism is")
    print("  needed.  This is the boundary of what structural derivation from P1-P3")
    print("  can deliver without an additional structural input -- which is exactly")
    print("  the structural-scope theorem's structural content.")


if __name__ == "__main__":
    main()
