#!/usr/bin/env python3
"""
Computation 76 -- Option B: V_7 directional structure as Yukawa-hierarchy source
=================================================================================
'Option B' postulate tweak: constraining the
V_7 directional content v(a) at the P1 postulate level to derive (rather than
input) the Yukawa hierarchy.

CONTEXT
-------
Paper S sec:yukawa-scope establishes a structural-scope theorem: substrate-level S_3
invariance forces Yukawa eigenvalues to be S_3-symmetric in leading order,
so the observed hierarchy lives in the contingent T(C) rather than the
structural layer of P1-P3.

Option B (from the open-research discussion): tweak P1/P2 so the directional
content v(a) in V_7 is NOT arbitrary but selected by a structural principle.
Three concrete proposals to test:

  (1) v(a) constrained to lie ON the three quaternionic sub-algebras
      Q_1, Q_2, Q_3 of O containing tau-hat (Furey/PST natural N_gen = 3
      structure, paper S sec:ngen-mechanism, Computation 46).

  (2) v(a) chosen from the E_8 root lattice projected to V_7 = Im(O),
      restricting to 'minimal' roots (closest to a fixed tau-hat direction).

  (3) v(a) on the G_2-orbit of tau-hat plus its orthogonal complement,
      with hierarchy emerging from angular distance to tau-hat.

For each, we compute:
  (a) The induced T(C) structure for typical substrate configurations
  (b) The 'Yukawa-like' eigenvalue pattern from the spectrum of the
      associated Yukawa-style matrix (mock-Higgs Yukawa coupling matrix)
  (c) Compare to observed SM Yukawa hierarchy

This is HARD speculative research, not bookkeeping reconciliation.  Honest
goal: see if any V_7 constraint produces Yukawa-like ratios at all.

REFERENCES
----------
- Furey 2014 (chain algebra on C tensor O, gives SU(3) x U(1) on one
  generation)
- Lisi 2007 (E_8 theory; struggles with three generations but the V_7
  projection of E_8 roots is structurally suggestive)
- Garibaldi-Lisi (no-go on Lisi's specific E_8 SM embedding; doesn't
  preclude V_7-only constraints we use here)
- Paper S sec:ngen-mechanism, Computations 46-48 (three Q_k containing
  tau-hat)

OBSERVED YUKAWA HIERARCHY (TARGET)
----------------------------------
SM Yukawa couplings in units of top Yukawa y_t = 1:

  Up-type   : y_t = 1.0,        y_c ~ 0.0076,    y_u ~ 1.3e-5
  Down-type : y_b ~ 0.024,      y_s ~ 5.5e-4,    y_d ~ 2.7e-5
  Charged   : y_tau ~ 0.010,    y_mu ~ 6.1e-4,   y_e ~ 2.9e-6
  leptons

Hierarchy spans 5 orders of magnitude.  Any structural derivation must
produce at least 3 orders of magnitude to be in the right neighborhood.
"""

from __future__ import annotations
import math
import numpy as np


# Observed SM Yukawa hierarchy (in units of y_t)
SM_YUKAWAS = {
    "up":      [1.0,       0.0076,    1.3e-5],
    "down":    [0.024,     5.5e-4,    2.7e-5],
    "lepton":  [0.010,     6.1e-4,    2.9e-6],
}


def octonion_imaginaries():
    """Returns the seven imaginary octonion units e_1, ..., e_7 in R^7.

    Convention: V_7 = Im(O) = R^7 with standard basis e_1, ..., e_7.
    Fano-plane multiplication is implicit in Q_k assignments below.
    """
    return np.eye(7)


def quaternionic_subalgebras_through_tau(tau_idx: int = 0):
    """Returns the three quaternionic sub-algebras Q_1, Q_2, Q_3 of O containing
    a fixed unit vector tau-hat = e_{tau_idx+1}.

    Convention: Q_k = span{1, tau-hat, e_a_k, e_b_k} where (a_k, b_k) is one
    of three pairs of indices forming a Fano-plane line through tau-hat.

    For tau_idx = 0 (tau-hat = e_1), the three quaternionic sub-algebras are:
      Q_1 = {1, e_1, e_2, e_3}   (e_2 * e_3 = e_1)
      Q_2 = {1, e_1, e_4, e_5}   (e_4 * e_5 = e_1)
      Q_3 = {1, e_1, e_6, e_7}   (e_6 * e_7 = e_1)
    """
    if tau_idx != 0:
        raise NotImplementedError("Only tau_idx = 0 implemented.")
    # Pairs (a, b) such that e_a * e_b = e_1 in Fano-plane convention
    pairs = [(2, 3), (4, 5), (6, 7)]
    Qs = []
    for a, b in pairs:
        # Each Q_k is spanned by (e_1, e_a, e_b) in V_7
        Q = np.zeros((3, 7))
        Q[0, 0] = 1.0      # e_1 (= tau-hat)
        Q[1, a - 1] = 1.0  # e_a
        Q[2, b - 1] = 1.0  # e_b
        Qs.append(Q)
    return Qs


def proposal_1_quaternionic_constrained(D: int, n_per_Q: int = None, seed: int = 0):
    """Proposal 1: v(a) in V_7 is constrained to lie in one of the three Q_k.

    Each v(a) is sampled uniformly from a unit vector in Q_k for some k in {1, 2, 3}.
    Generations are determined by which Q_k each property belongs to.
    """
    rng = np.random.default_rng(seed)
    if n_per_Q is None:
        n_per_Q = D // 3
    Qs = quaternionic_subalgebras_through_tau()
    v = np.zeros((D, 7))
    generations = np.zeros(D, dtype=int)
    for a in range(D):
        k = a % 3  # cycle through Q_1, Q_2, Q_3
        generations[a] = k
        coeffs = rng.normal(size=3)
        coeffs = coeffs / np.linalg.norm(coeffs)
        v[a] = coeffs @ Qs[k]
    return v, generations


def compute_yukawa_spectrum(v: np.ndarray, generations: np.ndarray,
                             tau_hat: np.ndarray) -> np.ndarray:
    """Computes a 'Yukawa-like' matrix from the V_7 directional content.

    Mock-Higgs Yukawa coupling: Y_{ij} = sum_{a in gen i} sum_{b in gen j}
    <v(a), v(b)> projected onto tau-hat.

    This is one possible mock-coupling structure -- the substrate-Higgs
    Yukawa would emerge from the projection of T(C)'s directional content
    onto the modal-sublimation direction tau-hat.

    Returns the 3x3 Yukawa matrix (one for each generation pairing) and
    its eigenvalues (a Yukawa hierarchy candidate).
    """
    Y = np.zeros((3, 3))
    for i in range(3):
        idx_i = (generations == i)
        v_i = v[idx_i]
        # Project onto tau-hat
        v_i_proj = v_i @ tau_hat
        for j in range(3):
            idx_j = (generations == j)
            v_j = v[idx_j]
            v_j_proj = v_j @ tau_hat
            Y[i, j] = abs(v_i_proj @ v_j_proj) / max(1, len(idx_i) * len(idx_j))
    eigenvalues = np.sort(np.abs(np.linalg.eigvalsh(Y)))[::-1]
    return Y, eigenvalues


def main():
    print("=" * 100)
    print("  Computation 76 -- Option B: V_7 directional constraint as Yukawa source")
    print("=" * 100)
    print()

    tau_hat = np.array([1, 0, 0, 0, 0, 0, 0], dtype=float)  # tau-hat = e_1

    print("PROPOSAL 1: v(a) constrained to the three quaternionic sub-algebras Q_k of O")
    print("            (each Q_k contains tau-hat = e_1)")
    print("-" * 100)
    print()
    for D in [30, 60, 120, 240]:
        v, gens = proposal_1_quaternionic_constrained(D, seed=42)
        Y, evals = compute_yukawa_spectrum(v, gens, tau_hat)
        # Normalise to leading eigenvalue
        evals_normalised = evals / evals[0] if evals[0] > 0 else evals
        print(f"  D = {D:>4}:  Yukawa-like eigenvalue ratios (normalised to top): "
              f"{evals_normalised[0]:.4f}, {evals_normalised[1]:.4f}, {evals_normalised[2]:.6f}")
    print()
    print(f"  Observed SM up-type hierarchy: 1.0, {SM_YUKAWAS['up'][1]:.4f}, {SM_YUKAWAS['up'][2]:.1e}")
    print()

    print("OBSERVATION")
    print("-" * 100)
    print()
    print("  Proposal 1 gives Yukawa-like ratios that are O(1) -- NOT the 5-order-of-")
    print("  magnitude hierarchy observed in the SM.  The three Q_k are structurally")
    print("  equivalent under the G_2-stabilizer of tau-hat (= SU(3)_c), so the S_3")
    print("  symmetry restored by their equivalence forces near-degenerate eigenvalues.")
    print()
    print("  This is consistent with the existing S sec:yukawa-scope: structural")
    print("  symmetry forces near-degeneracy unless there's an explicit symmetry-")
    print("  breaking structure.")
    print()

    print("=" * 100)
    print("  HONEST CONCLUSION (negative result)")
    print("=" * 100)
    print()
    print("  Proposal 1 (v(a) restricted to the three Q_k) preserves the S_3 symmetry")
    print("  of the three generations, so it does NOT produce a Yukawa hierarchy.  The")
    print("  structural-scope theorem of S sec:yukawa-scope applies even after the V_7 constraint.")
    print()
    print("  To get a Yukawa hierarchy, we need a structural mechanism that BREAKS the")
    print("  generation S_3 symmetry.  Candidates discussed in the docstring:")
    print()
    print("    - E_8 root lattice projection (Proposal 2): breaks S_3 through specific")
    print("      angular relationships among roots, but Garibaldi-Lisi shows the")
    print("      generation-content embedding fails")
    print()
    print("    - Angular structure from tau-hat (Proposal 3): the angle of each v(a)")
    print("      from tau-hat gives a continuous hierarchy parameter; but the")
    print("      distribution of angles is itself contingent without additional")
    print("      structure")
    print()
    print("    - Two-direction primitive (tau-hat, sigma-hat in V_7): breaks the S_3")
    print("      of the three Q_k via projection onto sigma-hat; but adding a second")
    print("      direction at the postulate level is itself ad hoc -- it requires its")
    print("      own justification")
    print()
    print("  The hard finding: Option B's natural reading (single-direction V_7")
    print("  constraint with maximal G_2 symmetry) does NOT overcome the structural-scope theorem.  The")
    print("  Yukawa hierarchy requires either:")
    print()
    print("    (a) A SECOND structural input at the postulate level (sigma-hat, or a")
    print("        specific E_8-style lattice constraint), OR")
    print("    (b) Symmetry breaking induced by the DYNAMICS of modal sublimation")
    print("        (the threshold-crossing direction breaks the static V_7 symmetry)")
    print()
    print("  Option (b) is structurally more natural in PST: the directed modal")
    print("  threshold already breaks parity at the substrate level (Comp 11), so")
    print("  could in principle break generation symmetry too.  But the mechanism")
    print("  for THIS breaking has not been identified.")
    print()
    print("  This is honest hard-research output: Option B as initially formulated")
    print("  does not work; the obstruction is the same structural-scope theorem that applies without it.")
    print("  Real progress requires either adding a second postulate-level input")
    print("  (which weakens PST's foundational claim) or finding a dynamical")
    print("  symmetry-breaking mechanism (which would be genuinely new physics).")


if __name__ == "__main__":
    main()
