"""The 24 Figure 4 means of our full run against the values printed in the paper, from
analysis/printed-reference-comparison.json. Each mean is shown as its signed difference from the
printed value in units of half the last printed digit, so the band from -1 to 1 is the range that
rounds to the printed value. Descriptive only. Writes figures/results-vs-printed.png (1920 x 1200) and .svg.
"""
import json
from decimal import Decimal
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
rows = json.loads((ROOT / 'analysis/printed-reference-comparison.json').read_text())['metrics']
METRICS = [('firing_rate_hz', 'Firing rate (Hz)'), ('isi_cv', 'ISI CV'), ('pairwise_correlation', 'Spike-count correlation'),
           ('voltage_mV', 'Membrane voltage (mV)'), ('exc_conductance_nS', 'Excitatory conductance (nS)'),
           ('inh_conductance_nS', 'Inhibitory conductance (nS)')]
POPS = ['L4 excitatory', 'L4 inhibitory', 'L2/3 excitatory', 'L2/3 inhibitory']
PAPER, INK, VIOLET, MUTED, LINE, LIGHT = '#fcfaf7', '#28222d', '#6240ab', '#776e7d', '#d8cfdf', '#b9a6dc'
STYLE = {'L4 excitatory': dict(marker='o', color=VIOLET, mfc=VIOLET), 'L4 inhibitory': dict(marker='o', color=VIOLET, mfc=PAPER),
         'L2/3 excitatory': dict(marker='s', color=INK, mfc=INK), 'L2/3 inhibitory': dict(marker='s', color=INK, mfc=PAPER)}
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': INK})
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.055, .94, 'felisyn  /  research note 15', color=VIOLET, fontsize=15)
f.text(.055, .869, 'All 24 printed Figure 4 means matched', fontsize=29)
f.text(.055, .817, 'Our mean minus the printed value, scaled so the band edges lie half a unit of the last printed digit either side.',
       color=MUTED, fontsize=15)
ax = f.add_axes([.25, .23, .4, .53], facecolor=PAPER)
ax.axvspan(-1, 1, color=LIGHT, alpha=.35, linewidth=0)
ax.axvline(0, color=LINE, linewidth=1)
lookup = {(r['population'], r['metric']): r for r in rows}
for i, (metric, label) in enumerate(METRICS):
    y = len(METRICS) - 1 - i
    for j, pop in enumerate(POPS):
        r = lookup[(pop, metric)]
        unit = float(Decimal(1).scaleb(Decimal(r['printed_reference']).as_tuple().exponent))
        x = r['signed_difference'] / (unit / 2)
        ax.plot([x], [y + (j - 1.5) * .14], linestyle='none', markersize=9, mew=1.6, **STYLE[pop],
                label=pop if i == 0 else None)
    def shown(p):  # two more decimals than the printed value, so the closeness is visible
        decimals = max(0, -Decimal(lookup[(p, metric)]['printed_reference']).as_tuple().exponent) + 2
        return f"{lookup[(p, metric)]['observed']:.{decimals}f}".replace('-', '−')
    observed = '  ·  '.join(shown(p) for p in POPS)
    printed = '  ·  '.join(lookup[(p, metric)]['printed_reference'].replace('-', '−') for p in POPS)
    f.text(.675, .23 + .53 * (y + .5) / len(METRICS) + .012, observed, fontsize=12.5, va='center')
    f.text(.675, .23 + .53 * (y + .5) / len(METRICS) - .022, 'printed  ' + printed, fontsize=12, color=MUTED, va='center')
ax.set_yticks(range(len(METRICS)), [label for _, label in METRICS][::-1], fontsize=13.5)
ax.set_ylim(-.6, len(METRICS) - .4)
ax.set_xlim(-1.25, 1.25)
ax.set_xticks([-1, 0, 1], ['half a printed unit below', 'printed value', 'half a printed unit above'], fontsize=12)
ax.tick_params(axis='y', length=0)
for side in ['top', 'right', 'left']:
    ax.spines[side].set_visible(False)
f.text(.675, .785, 'Our means (L4 exc · L4 inh · L2/3 exc · L2/3 inh)', fontsize=12.5, color=VIOLET)
ax.legend(loc='upper center', bbox_to_anchor=(.5, -.085), ncol=4, frameon=False, fontsize=12, handletextpad=.3, columnspacing=1.2)
f.text(.055, .078, 'Descriptive only: agreement with the paper\'s printed model values, not biological validation. '
       'All 48 parity checks passed.', fontsize=13)
f.text(.055, .04, 'Printed values: Antolík et al. 2024, Figure 4 (CC BY 4.0), transcribed in benchmark-004. '
       'Our run: protocol 007, 40.32 s of spontaneous activity, 22 Oct 2026.', fontsize=12, color=MUTED)
(ROOT / 'figures').mkdir(exist_ok=True)
for ext in ['png', 'svg']:
    f.savefig(ROOT / f'figures/results-vs-printed.{ext}', facecolor=PAPER)
print('ok')
