"""Recorded-neuron counts: paper S5 Table versus the released recorder files on the pinned
model realization, from receipts/recorder-counts.json. Counts only; no neural activity.
Writes figures/recorder-counts.png (1920 x 1200) and .svg.
"""
import json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
rc = json.loads((ROOT / 'receipts/recorder-counts.json').read_text())
POPS = [('V1_Exc_L4', 'L4 excitatory'), ('V1_Inh_L4', 'L4 inhibitory'), ('V1_Exc_L2/3', 'L2/3 excitatory'), ('V1_Inh_L2/3', 'L2/3 inhibitory')]
PAPER, INK, VIOLET, MUTED, LINE, LIGHT = '#fcfaf7', '#28222d', '#6240ab', '#776e7d', '#d8cfdf', '#b9a6dc'
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(.065, .94, 'felisyn  /  research note 13', color=VIOLET, fontsize=15)
f.text(.065, .869, 'Two recording sets, matched exactly', fontsize=29)
f.text(.065, .817, "Recorded-neuron counts in the paper's S5 Table and from the released recorder files on our model realization.",
       color=MUTED, fontsize=15)

def panel(left, width, key, title, labels=True):
    ax = f.add_axes([left, .30, width, .40], facecolor=PAPER)
    y = list(range(len(POPS)))[::-1]
    for i, (pop, label) in enumerate(POPS):
        for recipe, colour, dy, s5_label in [('param_spont', VIOLET, .17, 'spontaneous'), ('param', LIGHT, -.17, 'evoked')]:
            c = rc['S5_comparison'][f'{s5_label}|{pop}']
            computed = c['computed_spikes'] if key == 'spikes' else c['computed_analog'][0]
            s5 = c['S5_spikes'] if key == 'spikes' else c['S5_analog']
            ax.barh(y[i] + dy, computed, height=.3, color=colour)
            ax.plot([s5], [y[i] + dy], marker='|', markersize=17, mew=2.4, color=INK)
            ax.text(computed * 1.12, y[i] + dy, f'{computed:,}', va='center', fontsize=12, color=INK)
    ax.set_xscale('log')
    ax.set_xlim(10, 60000 if key == 'spikes' else 3000)
    ax.set_yticks(y, [label for _, label in POPS] if labels else [''] * len(POPS), fontsize=13)
    ax.tick_params(axis='y', length=0)
    for side in ['top', 'right']:
        ax.spines[side].set_visible(False)
    ax.set_xlabel('Neurons (log scale)', fontsize=12.5, color=MUTED)
    f.text(left, .725, title, fontsize=18, color=VIOLET)

panel(.20, .38, 'spikes', 'Spike-recorded neurons')
panel(.66, .27, 'analog', 'Voltage and conductance recorded', labels=False)
f.text(.065, .165, 'Bars: computed with the released files (dark: param_spont, light: param, the frozen protocol-006 choice). Black ticks: S5 Table values.',
       fontsize=13, color=MUTED)
f.text(.065, .112, f"All 16 counts equal. Same 16-rank construction stopped before any connection; seeds PyNN {rc['seeds']['pynn_seed']}, Mozaik {rc['seeds']['mozaik_seed_effective']}.",
       fontsize=16)
f.text(.065, .07, 'Source: Antolík et al. 2024, PLOS Comput Biol, S5 Table (CC BY 4.0). Counts only; no neural activity is shown.', fontsize=12.5, color=MUTED)
(ROOT / 'figures').mkdir(exist_ok=True)
for ext in ['png', 'svg']:
    f.savefig(ROOT / f'figures/recorder-counts.{ext}', facecolor=PAPER)
print('ok')
