"""
Build S43 v3: 7-panel harmonic-scale generalization across critical attributes.
4×2 grid (last cell empty).
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path

OUT = Path("/sessions/kind-brave-babbage/mnt/Wavelet/harmonic_synthesis_2026-05-01")

WONG = {'blue':'#0072B2','vermil':'#D55E00','green':'#009E73',
        'gold':'#E69F00','sky':'#56B4E9','pink':'#CC79A7','grey':'#999999'}

# Load 7-attribute summary
df = pd.read_csv(OUT / "test8_seven_attributes_harmonic_summary.csv")
print(df[['label','n','M0_R2_pop','M1_R2_pop','M2_R2_pop','F_M0_M1','p_M0_M1','F_M1_M2','p_M1_M2']].to_string(index=False))

# Group by domain — 4-column layout fits 7 attributes nicely (1 empty cell)
labels_short = {
    'TSA-seq (radial geometry)': ('a', 'TSA-seq (radial geometry)'),
    'Repli-seq (RT)':              ('b', 'Repli-seq (RT — mechanism)'),
    'log gene density':            ('c', 'Gene density (function)'),
    'PCAWG pan-cancer mutation density': ('d', 'PCAWG mutation density (cancer mut. landscape)'),
    'log CNV breakpoint density':  ('e', 'ClinVar pathogenic CNV breakpoints (rare disease)'),
    'gnomAD-SV breakpoint density':('f', 'gnomAD-SV breakpoints (population variation)'),
    'PCAWG TRA breakpoint density':('g', 'PCAWG translocations (cancer somatic SVs)'),
}

# Order: continuous on top row + d, discrete on bottom
order = [
    'TSA-seq (radial geometry)',
    'Repli-seq (RT)',
    'log gene density',
    'PCAWG pan-cancer mutation density',
    'log CNV breakpoint density',
    'gnomAD-SV breakpoint density',
    'PCAWG TRA breakpoint density',
]

fig, axes = plt.subplots(2, 4, figsize=(18, 9))
axes_flat = axes.flatten()
for ax, lbl in zip(axes_flat, order):
    r = df[df['label']==lbl].iloc[0]
    short_letter, short_title = labels_short[lbl]
    xs = [0, 1, 2]
    R2_pop = [r['M0_R2_pop'], r['M1_R2_pop'], r['M2_R2_pop']]
    R2_oct = [r['M0_R2_oct'], r['M1_R2_oct'], r['M2_R2_oct']]
    w = 0.35
    ax.bar([x-w/2 for x in xs], R2_pop, w, color=WONG['blue'], label='R² pop')
    ax.bar([x+w/2 for x in xs], R2_oct, w, color=WONG['gold'], label='R² oct')
    for i, x in enumerate(xs):
        ax.text(x-w/2, R2_pop[i] + 0.012*np.sign(R2_pop[i]+0.001),
                f"{R2_pop[i]:+.3f}", ha='center', fontsize=8)
        ax.text(x+w/2, R2_oct[i] + 0.012*np.sign(R2_oct[i]+0.001),
                f"{R2_oct[i]:+.3f}", ha='center', fontsize=8)
    ax.annotate(f"F = {r['F_M0_M1']:.1f}\np = {r['p_M0_M1']:.2g}",
                xy=(0.5, max(R2_oct[0], R2_oct[1])+0.06), ha='center',
                fontsize=8, color=WONG['vermil'])
    ax.annotate(f"F = {r['F_M1_M2']:.1f}\np = {r['p_M1_M2']:.2g}",
                xy=(1.5, max(R2_oct[1], R2_oct[2])+0.06), ha='center',
                fontsize=8, color=WONG['vermil'])
    ax.set_xticks(xs); ax.set_xticklabels(['M0\nrank-1','M1\n+T₁/3','M2\n+T₁/5'], fontsize=8.5)
    ax.set_ylabel('R²', fontsize=9.5)
    ax.set_title(f"{short_letter}    {short_title}\n(n = {int(r['n']):,})",
                 fontsize=9.5, loc='left')
    y_low = min(0, min(R2_pop)*1.2 - 0.05)
    y_high = max(1.05, max(R2_oct)*1.15)
    ax.set_ylim(y_low, y_high)
    ax.axhline(0, color='black', lw=0.5)
    ax.grid(alpha=0.3, axis='y')

# Hide last empty panel
axes_flat[-1].set_visible(False)
axes_flat[0].legend(fontsize=9, loc='upper left')

plt.suptitle('Phase at the rank-2 GWS scale ($T_1/3$) generalises across 7 critical attribute domains.\n'
             'Continuous biological signals (a–d) refine further at $T_1/5$; sparse breakpoint events (e, g) saturate at $T_1/3$.',
             fontsize=11, y=1.005)
plt.tight_layout()
plt.savefig(OUT / "s43_v3_seven_attributes.png", dpi=200, bbox_inches='tight')
plt.savefig(OUT / "s43_v3_seven_attributes.svg", bbox_inches='tight')
plt.close(fig)
print("Saved: s43_v3_seven_attributes.png/svg")
