"""Figures for protocol 021's probe phase, from the retained probe analyses only.
  1. OUT_STEM-timing.png/.svg: the share of decoded steps clipped or wrapped, per condition and step length, against
     the declared 10 % limit of the timing rule (the plain lesion's share decided both outcomes).
  2. OUT_STEM-kernels.png/.svg: each condition's response kernel |h(t)| in 10 ms bins, scaled to its peak, with the
     decoding window the declared latency rule gave it, for both step lengths.

  python3 draw_probe.py PROBE_70.json PROBE_105.json OUT_STEM      (1920 x 1200 each)
"""
import json, sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

PAPER, INK, MUTED, LINE = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf'
COLOUR = {'intact': '#6240ab', 'lesion': '#b26a00', 'matched': '#0b6e99'}   # validated together (dataviz validator)
LABEL = {'intact': 'intact', 'lesion': 'plain lesion', 'matched': 'matched lesion'}
NOTE = {'intact': 'published connectivity', 'lesion': 'intracortical connections off',
        'matched': 'connections off, input scaled to the intact rate'}
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': MUTED})
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        'Simulation only: no token, wallet or real order.')

p70, p105, stem = json.load(open(sys.argv[1])), json.load(open(sys.argv[2])), sys.argv[3]
probes = [('70 ms steps', p70), ('105 ms steps', p105)]


def header(f, title, sub):
    f.text(.055, .94, 'felisyn  /  research note, protocol 021', color=COLOUR['intact'], fontsize=15)
    f.text(.055, .872, title, fontsize=28)
    f.text(.055, .823, sub, color=MUTED, fontsize=14)
    f.text(.055, .025, FOOT, fontsize=11, color=MUTED)


def save(f, name):
    f.savefig(f'{stem}-{name}.png', dpi=150, facecolor=PAPER)
    f.savefig(f'{stem}-{name}.svg', facecolor=PAPER)
    plt.close(f)


# ---------------------------------------------------------------- figure 1: the timing rule
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
header(f, 'The timing check stopped the test twice',
       'Share of decoded steps clipped or wrapped, 120 probe steps each. The declared rule allowed at most 10 % in '
       'intact and plain lesion.')
ax = f.add_axes([.30, .17, .52, .58], facecolor=PAPER)
rows = []
for cond in ('intact', 'lesion', 'matched'):
    for timing, pa in probes:
        if cond in pa['conditions']:
            rows.append((cond, timing, pa['conditions'][cond]['clip_or_wrap_share']))
ordered = list(reversed(rows))
for y, (cond, timing, share) in enumerate(ordered):
    ax.plot([0, share * 100], [y, y], color=LINE, lw=2, solid_capstyle='butt', zorder=1)
    ax.plot(share * 100, y, 'o', ms=10, color=COLOUR[cond], mec=PAPER, mew=2, zorder=3)
    ax.text(share * 100 + 1.0, y, f'{share * 100:.1f} %', va='center', fontsize=14, color=INK)
ax.axvline(10, color=INK, lw=1.2, ls=(0, (4, 3)), zorder=2)
ax.text(10.4, len(rows) - 0.45, 'limit 10 %', fontsize=13, color=INK)
ax.set_xlim(0, 35)
ax.set_ylim(-0.7, len(rows) - 0.3)
ax.set_yticks(range(len(ordered)), [f'{LABEL[c]}, {t}' for c, t, _ in ordered], fontsize=15, color=INK)
ax.tick_params(axis='y', length=0, pad=14, labelcolor=INK)
ax.set_xlabel('decoded steps clipped or wrapped (%)', color=MUTED)
ax.grid(axis='x', color=LINE, lw=0.6, alpha=0.6)
ax.set_axisbelow(True)
for side in ('top', 'right', 'left'):
    ax.spines[side].set_visible(False)
f.text(.30, .085, 'The matched lesion was not part of this rule; it is shown for completeness.', fontsize=12, color=MUTED)
f.text(.30, .06, 'Clipped or wrapped: the decoded orientation falls outside the encoder\'s 45° to 135° range.', fontsize=12, color=MUTED)
save(f, 'timing')

# ---------------------------------------------------------------- figure 2: kernels and windows
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
header(f, 'How each network answers one step',
       'Response kernel |h(t)| of the layer 4 population code in 10 ms bins, each scaled to its own peak; bars: the '
       'decoding window from the declared latency rule.')
for k, (timing, pa) in enumerate(probes):
    ax = f.add_axes([.07 + k * .47, .17, .40, .55], facecolor=PAPER)
    conds = [c for c in ('intact', 'lesion', 'matched') if c in pa['conditions']]
    for j, cond in enumerate(conds):
        c = pa['conditions'][cond]
        h = c['kernel_abs']
        peak = max(h)
        t = [10 * i + 5 for i in range(len(h))]
        ax.plot(t, [v / peak for v in h], color=COLOUR[cond], lw=2, zorder=3)
        w0, w1 = c['window_ms']
        y = 1.13 + 0.09 * j
        ax.plot([w0, w1], [y, y], color=COLOUR[cond], lw=5, solid_capstyle='butt', zorder=3)
        ax.text(w1 + 6, y, f'{LABEL[cond]} {w0:.0f} to {w1:.0f} ms', va='center', fontsize=11, color=INK)
    step = 70 if timing.startswith('70') else 105
    for n in range(1, 4):
        ax.axvline(n * step, color=LINE, lw=1, zorder=1)
    ax.set_xlim(0, 350)
    ax.set_ylim(0, 1.45)
    ax.set_yticks([0, 0.5, 1])
    ax.set_xlabel(f'time after a step begins (ms); thin lines: the next steps begin ({timing})', color=MUTED, fontsize=12)
    ax.text(0, 1.52, timing, fontsize=17, color=INK, transform=ax.transData)
    for side in ('top', 'right'):
        ax.spines[side].set_visible(False)
    if k == 0:
        ax.set_ylabel('scaled to each peak', color=MUTED)
    missing = [c for c in ('intact', 'lesion', 'matched') if c not in pa['conditions']]
    if missing:
        ax.text(5, 1.13 + 0.09 * len(conds), 'matched lesion: not yet probed at this step length', va='center', fontsize=11, color=MUTED)
save(f, 'kernels')
print('wrote', f'{stem}-timing.png', f'{stem}-kernels.png')
