#!/usr/bin/env python3
"""
SCOPE NOTE, 2026-10-11 (comp 202).  Where this file quotes lambda_SM(M_*) ~ 0.0927
(Buttazzo et al. 2013), the 0.8 percent agreement, the one-sigma Higgs match or comp 176's
0.4 sigma, that is the anchor of its day and is kept as found.  comp 202 computes the number
at three loops on current inputs: 0.0932 +- 0.0008, 1.6 sigma from e^-1/4, which is what the
book states from v32.137.  Nothing here is re-run; the substrate side is unaffected.

PROVENANCE: NUMERICAL

Computation 107 -- Full-SM extension of the M_* boson-fermion cancellation:
                   the SECTOR-BLINDNESS argument (WITHDRAWN as a closure)
                   (open-research item 1.3, REOPENED v26.09)
=========================================================================
UPDATE (v26.27+): open-research item 1.3 was subsequently SETTLED in the
NEGATIVE by Comp 120 -- the full-SM extension does not exist within PST.
The withdrawal recorded here stands; Comp 120 is the terminus, and M_* is
irreducibly a scalar-sector result.  The "REOPENED" status below is
historical.

STATUS (v26.09): the closure claim of this computation is WITHDRAWN.
The sector-blindness fact is correct, but its use to close the full-SM
extension of the M_* boson-fermion cancellation does not hold.  Open-
research item 1.3 is REOPENED.  See "WHY THE CLOSURE FAILS" below.

The open foundational item this computation addressed:

  1.3 Full-SM extension of boson-fermion cancellation at M_*
     (i)   Configuration-to-particle map (substrate -> top, W, Z, ...)
     (ii)  Cross-sector coupling universality at M_*
     (iii) Inner-fluctuation sign assignment for gauge modes

The computation established that the substrate-level cancellation
N_B = N_F = 2^{D-1} is SECTOR-BLIND (invariant under any partition of
the Walsh modes into hypothetical SM sectors), and argued that this
transfers the cancellation to the SM top/W/Z sectors.

WHY THE CLOSURE FAILS (referee finding, v26.08 review, accepted)
================================================================
The transfer does NOT hold, for two independent reasons:

(1) LAYER DISJOINTNESS.  Comp 105 establishes that the substrate
    cancellation operates in the UV shell [M_*, sqrt(D)], while the
    physical top, W, Z, and Higgs loops that determine the observed
    delta m_h^2 run in the emergent EFT shell BELOW M_*, where the
    theory is exactly the Standard Model (Proposition F4).  By the very
    disjointness Comp 105 uses to defuse double-counting, the substrate
    cancellation cannot reach the EFT-layer loops.  Keeping the Higgs
    seagull (C_H) while discarding the top/W/Z loops at the same layer
    is selective diagram accounting, not a cancellation.

(2) UNIVERSALITY PREMISE FALSE.  "Coupling universality at M_*"
    (c_S = 1 for every Walsh mode) is contradicted by the observed
    Yukawa hierarchy (y_t/y_e ~ 3e5), which cannot be generated by SM
    RGE running over ln(M_*/m_t) ~ 2.  The paper itself assigns the
    hierarchy to T(C)-contingency (sec:yukawa-scope), so the Yukawas at
    M_* are contingent and hierarchical, not universal.

The empirical Veltman residual at M_* is ~ -3 (top-dominated, negative),
not the +m_h^2 that a clean cancellation would leave.

WHAT SURVIVES: the sector-blindness of the substrate binomial count is
a correct fact.  The scalar-sector self-mass relation
m_h^2 = (3/2) M_*^2/(16 pi^2) (Higgs self-loop in isolation) stands.
The full-SM extension is an OPEN PROBLEM.

THE STRUCTURAL OBSERVATION
===========================
PST's substrate-side cancellation argument (paper sec:renorm,
the boson-fermion pairing cancellation) is

  delta m_h^2 |_{PST scalar} = (M_*^2 / 16 pi^2) . (N_B - N_F) = 0

where N_B and N_F count substrate-level Walsh eigenmodes of the Boolean
Laplacian L^B with even and odd |S| respectively, |S| ranging over
non-empty subsets of [D].

The Walsh basis on P(D) is COMPLETE. Every substrate field configuration
psi : P(D) -> R decomposes uniquely as

  psi = sum_{S subset [D]} c_S chi_S         (1)

with chi_S the Walsh basis. The Mosco-limit projection Pi sends psi to
a field on M = R x S^3, and the CC inner-fluctuation lift assigns each
M-side field to an irreducible representation of A_F = C + H + M_3(C).
The composition

  substrate Walsh mode chi_S --Pi--> field on M --inner-fluct--> SM particle

is by construction SURJECTIVE onto the SM particle content at M_*
(otherwise the substrate would be incomplete relative to its EFT below
M_*, contradicting paper the effective-action expansion).

KEY POINT: which SM particle a given substrate Walsh mode chi_S becomes
under this projection chain DOES NOT AFFECT the substrate-level count
of bosonic vs fermionic modes. The substrate-level Boolean grading
|S| mod 2 is intrinsic; the SM-side sector identity (top, W, Z, ...) is
EMERGENT via Pi + inner fluctuations.

In particular:
  - bosonic substrate modes (|S| even) project to SM-side bosons:
    Higgs scalars (4 dof from A_F inner fluctuations on the C + H part),
    EW gauge bosons (W^+, W^-, Z, photon from the H factor of A_F),
    gluons (8 from the M_3(C) factor of A_F).
  - fermionic substrate modes (|S| odd) project to SM-side fermions:
    quarks (3 colours from M_3(C), 2 weak iso from H, 3 generations
    from the Furey/Dixon Cl(0,6) decomposition) and leptons
    (similar but no colour, see paper sec:ngen-mechanism, Comp 46-48).

The Walsh-mode partition |S|-even / |S|-odd induces an automatic
boson/fermion split on the SM side via the spin-statistics correspondence
that the CAR realisation of Boolean configurations enforces (paper
sec:car-fermions).

SECTOR-BLIND CANCELLATION
==========================
Substrate-side delta m_h^2 in the Walsh basis is

  delta m_h^2 |_{substrate} = (M_*^2 / 16 pi^2) sum_{S != emptyset}
                              (-1)^|S| . c_S          (2)

where c_S = 1 is the universal LG-quartic coefficient (sec:renorm,
"every non-zero eigenmode... universal coupling coefficient c_k = 1").

The IDENTIFICATION of chi_S as a specific SM particle (top, W, gluon, ...)
attaches a SM-side LABEL but does not change the value of c_S or the
sign (-1)^|S|. The substrate sum (2) is by construction:

  sum_{S != emptyset} (-1)^|S| = -1 + sum_{S subset [D]} (-1)^|S|
                              = -1 + 0 = -1

But the paper's the boson-fermion pairing cancellation writes this as N_B - N_F where N_B
and N_F count NON-ZERO Walsh modes by even/odd |S|. For D >= 1:

  N_B = sum_{S != emptyset, |S| even} 1 = 2^{D-1} - 1   (excluding S = emptyset)
  N_F = sum_{S != emptyset, |S| odd}  1 = 2^{D-1}

so N_B - N_F = -1. This residual -1 (from excluding S = emptyset) is
EXACTLY the order-parameter zero mode that gets added back via the
emergent C_H = 6 lambda_PST = 3/2 inner-fluctuation coefficient (Comp 93,
97 substrate-vs-emergent distinction):

  delta m_h^2 |_{total} = (M_*^2 / 16 pi^2) [C_H + (N_B - N_F)]
                       = (M_*^2 / 16 pi^2) [1 + (-1)] ... NO WAIT

Hmm. Let me re-read the paper's prescription. The paper says (paragraph
around the boson-fermion pairing cancellation, line 5520-5533) "Every non-zero eigenmode...
universal coupling c_k = 1 for all k != 0. ... N_B = N_F = 2^{D-1}".

So the paper's reading INCLUDES |S| = 0 in the bosonic count but EXCLUDES
it from the substrate sum (treats it as the order parameter / Higgs).
Under that reading:

  N_B^{paper} = sum_{|S| even, S != emptyset, but include sum reaching 2^{D-1}}

Actually re-reading more carefully: "N_B = N_F = 2^{D-1}" is the FULL
binomial identity sum_{|S| even} = sum_{|S| odd} = 2^{D-1} (including
S = emptyset on the even side). Then "the Higgs zero mode (S = emptyset)
is excluded because it is the order parameter."

So the paper's bookkeeping is:
  Walsh modes (full):     N_B^{full} = 2^{D-1}, N_F^{full} = 2^{D-1}
  Excluding S = emptyset: N_B^{nonzero} = 2^{D-1} - 1, N_F^{nonzero} = 2^{D-1}
  Difference (substrate): N_B^{nonzero} - N_F^{nonzero} = -1
  Add back emergent C_H = 3/2: total contribution = -1 + 1 = 0 ?

That's NOT what the boson-fermion pairing cancellation says. It writes N_B - N_F = 0 and
treats this as the SCALAR-SECTOR cancellation, separate from C_H. Let
me re-check Comp 67's analysis:

Comp 67: "Including the zero mode in the bosonic count gives N_B - N_F = 0
exactly. Excluding the zero mode... gives N_B^{nonzero} - N_F = -1 ...
contributing a residual -M_*^2/(16 pi^2) to the boson-fermion pairing cancellation rather
than 0. Added to the self-loop +M_*^2/(16 pi^2) of the exact scalar-loop shift, this
gives total delta m_h^2 = 0, conflicting with the predicted m_h = M_*/(4pi)."

So Comp 67 found the off-by-one: excluding zero mode gives total
delta m_h^2 = 0, NOT M_*^2/(16 pi^2).

Comp 93/97 closed it via the substrate-vs-emergent distinction: the
substrate-side zero mode chi_emptyset is NOT the emergent SM Higgs
doublet (C_H = 6 lambda = 3/2 from inner fluctuations on A_F). Under
that distinction:
  - substrate sum N_B - N_F = 0 (include zero mode on bosonic side)
  - emergent C_H = 3/2 (added separately)
  - total: delta m_h^2 = (M_*^2/16 pi^2)(0 + 1) = M_*^2/(16 pi^2). OK.

CONCLUSION FOR (i) and (ii):
=============================
Under the substrate-vs-emergent distinction of Comp 93/97:

(i) The configuration-to-particle map is the projection chain
    Pi : substrate Walsh modes -> SM particles via Mosco-limit field
    + A_F inner fluctuations. This chain is by construction SURJECTIVE
    onto SM at M_* (paper the effective-action expansion). The EXPLICIT map (which chi_S maps
    to top vs W vs Z) is encoded in the Cl(0,6) Furey decomposition
    (sec:ngen-mechanism, Comp 46-48) and the A_F inner-fluctuation
    structure (sec:gauge-sm). What matters for the M_* cancellation
    is that the map exists and is surjective; the COUNTING is sector-
    blind on the substrate side.

(ii) Cross-sector coupling universality at M_* holds STRUCTURALLY at
     the substrate level: every Walsh mode chi_S (|S| >= 1) carries
     the SAME coupling coefficient c_S = 1 to the order parameter,
     inherited from the single LG quartic lambda_PST = 1/4 (paper
     sec:renorm). The IR Yukawa hierarchy (y_t ~ 1, y_e ~ 3e-6) is
     generated by RGE running from M_* down to the EW scale, not by
     substrate-level coupling differentiation. At M_*, the substrate
     sees ONE coupling.

(iii) Inner-fluctuation sign assignment: deferred to Comp 108. The
      question is whether the boson/fermion sign assignment from
      |S|-parity carries through to A_F inner-fluctuation gauge bosons
      that are not directly Walsh modes. Tentative resolution: the
      gauge bosons enter the cancellation via their CONTRIBUTION TO C_H
      (via the unimodular unitary lift on A_F), not as separate Walsh-
      mode contributors. Under the substrate-vs-emergent distinction,
      gauge contributions to delta m_h^2 fold into C_H = 3/2, and the
      substrate-side N_B - N_F = 0 already accounts for everything.

NUMERICAL VERIFICATION
=======================
We verify (i) the substrate-level binomial identity for D ranging over
{4, 6, 8, ..., 20}; and (ii) the sector-blind property by partitioning
the Walsh modes into hypothetical SM-side sectors (Higgs, gauge, top,
W/Z, leptons, light quarks, ...) and showing that the substrate-level
identity holds REGARDLESS of how we slice the sectors. The substrate
cancellation is a binomial identity, not a coupling-dependent claim.
"""

import math
import random


def binomial_cancellation(D):
    """N_B - N_F where N_B = sum |S|-even, N_F = sum |S|-odd."""
    n_b = sum(math.comb(D, k) for k in range(0, D + 1, 2))
    n_f = sum(math.comb(D, k) for k in range(1, D + 1, 2))
    return n_b, n_f


def sector_blind_partition_check(D, n_sectors, rng):
    """
    Randomly partition the 2^D Walsh modes into n_sectors hypothetical
    SM-side sectors. Within each sector, sum (-1)^|S| over modes.
    The TOTAL across all sectors must equal N_B - N_F = 0 (for D >= 1).
    The sector-level totals can differ -- that's the IR Yukawa hierarchy
    expressed at substrate level. What matters is that the SUM is zero
    regardless of partition choice.
    """
    all_modes = []
    for S_size in range(D + 1):
        sign = 1 if S_size % 2 == 0 else -1
        count = math.comb(D, S_size)
        for _ in range(count):
            all_modes.append((S_size, sign))

    rng.shuffle(all_modes)
    chunk = len(all_modes) // n_sectors
    sector_totals = []
    for s in range(n_sectors):
        start = s * chunk
        end = (s + 1) * chunk if s < n_sectors - 1 else len(all_modes)
        sector_sum = sum(sign for _, sign in all_modes[start:end])
        sector_totals.append(sector_sum)

    grand_total = sum(sector_totals)
    return sector_totals, grand_total


def veltman_residual_at_Mstar(lambda_sm, y_t, g, g_prime):
    """
    Standard Veltman-style residual coefficient of M_*^2/(16 pi^2)
    in the empirical SM at scale M_*.

    delta m_h^2 / (M_*^2 / 16 pi^2) ~= 6 lambda - 12 y_t^2 + 9 g^2 + 3 g'^2
                                       (Veltman 1981, simplified)
    Sign and coefficient conventions vary; we use the conventional sign
    such that exact cancellation gives 0.
    """
    return 6.0 * lambda_sm - 12.0 * y_t**2 + 9.0 * g**2 + 3.0 * g_prime**2


def main():
    print("=" * 72)
    print("Computation 107: Full-SM extension of M_* boson-fermion cancellation")
    print("=" * 72)
    print()
    print("(i)  Configuration-to-particle map: surjective Pi + A_F inner")
    print("     fluctuations cover SM at M_* (structural).")
    print("(ii) Coupling universality at M_*: substrate has ONE coupling")
    print("     lambda_PST = 1/4; IR Yukawa hierarchy from RGE running.")
    print("(iii) Inner-fluctuation sign assignment: deferred to Comp 108.")
    print()

    print("Substrate-level binomial cancellation N_B - N_F = 0:")
    print()
    print(f"  {'D':>4}  {'N_B':>10}  {'N_F':>10}  {'N_B - N_F':>11}")
    print(f"  {'-'*4}  {'-'*10}  {'-'*10}  {'-'*11}")
    for D in [4, 6, 8, 10, 12, 14, 16, 18, 20]:
        nb, nf = binomial_cancellation(D)
        print(f"  {D:>4}  {nb:>10}  {nf:>10}  {nb - nf:>11}")
    print()
    print("Exact cancellation across all D: structural binomial identity.")
    print()

    print("Sector-blind partition check (D = 12):")
    print("Random partition of 2^D = 4096 Walsh modes into hypothetical")
    print("SM sectors. Per-sector sums vary (IR Yukawa hierarchy expressed)")
    print("but GRAND TOTAL stays zero by binomial identity.")
    print()
    rng = random.Random(107)
    D = 12
    for trial in range(5):
        n_sectors = rng.randint(4, 12)
        sector_totals, grand_total = sector_blind_partition_check(D, n_sectors, rng)
        sample = sector_totals[:min(6, len(sector_totals))]
        more = "..." if len(sector_totals) > 6 else ""
        print(f"  trial {trial + 1}: {n_sectors:>2} sectors  "
              f"per-sector totals = {sample}{more}  "
              f"grand total = {grand_total}")
    print()
    print("Per-sector totals vary widely; grand total always 0.")
    print()

    print("Comparison: empirical SM Veltman residual at M_* = 1.285 TeV")
    print("(using Buttazzo-RGE running of SM couplings to M_*):")
    print()
    lambda_sm_Mstar = 0.0927
    y_t_Mstar = 0.85
    g_Mstar = 0.64
    g_prime_Mstar = 0.36
    veltman = veltman_residual_at_Mstar(lambda_sm_Mstar, y_t_Mstar,
                                          g_Mstar, g_prime_Mstar)
    print(f"  lambda_SM(M_*) ~= {lambda_sm_Mstar}")
    print(f"  y_t(M_*)       ~= {y_t_Mstar}")
    print(f"  g(M_*)         ~= {g_Mstar}")
    print(f"  g'(M_*)        ~= {g_prime_Mstar}")
    print()
    print(f"  Veltman residual coefficient: {veltman:.3f}")
    print(f"  (exact cancellation would give 0; empirical SM does not")
    print(f"  cancel at M_* under naive Veltman.)")
    print()
    print("Reading: the EMPIRICAL SM running of SM couplings does NOT")
    print("deliver Veltman cancellation at M_*. The PST claim is that this")
    print("apparent discrepancy is the IR Yukawa hierarchy expressed at")
    print("M_*. At the SUBSTRATE level (above the Mosco/inner-fluctuation")
    print("projection), the cancellation is binomial and exact. The IR")
    print("running below M_* generates the hierarchy that breaks the naive")
    print("Veltman picture; this does NOT undermine the substrate-level")
    print("argument because the substrate operates on Walsh modes with")
    print("universal coupling lambda_PST = 1/4, before sector-specific")
    print("Yukawa and gauge couplings emerge under RGE running.")

    print()
    print("=" * 72)
    print("Structural closure of 1.3 sub-tasks (i) and (ii):")
    print("=" * 72)
    print()
    print("(i)  The configuration-to-particle map is SURJECTIVE onto SM")
    print("     particle content at M_* by construction (paper the effective-action expansion;")
    print("     A_F = C + H + M_3(C) carries the full SM gauge group via")
    print("     Comp 3, 19, 106; Cl(0,6) Furey decomposition + three Fano")
    print("     sub-algebras through tau-hat carry the three generations,")
    print("     Comp 46-48). The EXPLICIT chi_S -> SM-particle assignment")
    print("     is the standard CC inner-fluctuation construction lifted")
    print("     to the substrate via Pi. For the M_* cancellation argument,")
    print("     it suffices that the map exists and is surjective; the")
    print("     substrate-level COUNTING is sector-blind by the binomial")
    print("     identity verified above.")
    print()
    print("(ii) Coupling universality at M_* is STRUCTURAL at the substrate")
    print("     level: the single LG quartic lambda_PST = 1/4 endows every")
    print("     non-zero Walsh mode with c_k = 1, regardless of SM-side")
    print("     sector identity. The IR Yukawa hierarchy is generated by")
    print("     RGE running BELOW M_* (paper sec:renorm: 'no PST modes")
    print("     propagate below M_*; beta-functions are exactly SM').")
    print("     The empirical SM Veltman residual at M_* expressed in")
    print("     SM-side variables is the IR hierarchy already accounting")
    print("     for the substrate's universality from above. There is no")
    print("     contradiction with the substrate-level cancellation.")
    print()
    print("(iii) Inner-fluctuation sign assignment for gauge modes:")
    print("      DEFERRED to Comp 108 (next step). Question: does the")
    print("      Walsh |S|-parity boson/fermion sign carry to A_F inner-")
    print("      fluctuation gauge bosons that are not directly Walsh modes?")
    print("      Tentative answer: gauge contributions to delta m_h^2 fold")
    print("      into the emergent C_H = 3/2 coefficient (substrate-vs-")
    print("      emergent distinction of Comp 93/97); the substrate Walsh")
    print("      sum N_B - N_F already accounts for everything else. A")
    print("      separate verification is required to confirm this is")
    print("      consistent with the CC inner-fluctuation construction.")


if __name__ == "__main__":
    main()
