"""Milestone-1 figure from retained data only: decoded against presented orientation for the decoder
chosen by the pre-written selection rule (probe-decoding.json from analyze_probe.py).

  python3 draw_probe.py PROBE_DECODING.json OUT_STEM
writes OUT_STEM.png and OUT_STEM.svg (1920 x 1200).
"""
import json, sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

PAPER, INK, MUTED, LINE = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf'
HIGH, LOW = '#6240ab', '#b26a00'              # validated pair (CVD dE 27.7), both pass contrast on PAPER
BAND = '#efe9f6'
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': INK})

res = json.load(open(sys.argv[1]))
ch = res['selection']['chosen']
v = next(x for x in res['variants'] if x['layer'] == ch['layer'] and x['window_ms'] == ch['window_ms'] and x['decoder'] == ch['decoder'])
rows = v['per_step']
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.055, .94, 'felisyn  /  controller, milestone 1', color=HIGH, fontsize=15)
f.text(.055, .872, 'Reading grating orientation from the 2 mm model', fontsize=28)
f.text(.055, .823, f"{len(rows)} probe gratings, 210 ms each. Decoder chosen by the pre-written rule: {ch['layer']}, "
                   f"{ch['decoder']} population vector, {ch['window_ms'][0]:.0f}-{ch['window_ms'][1]:.0f} ms after onset.",
       color=MUTED, fontsize=14.5)
ax = f.add_axes([.09, .13, .5, .62], facecolor=PAPER)
ax.axvspan(45, 135, color=BAND, lw=0, zorder=0)
ax.text(90, -16, 'orientations the encoder uses', ha='center', va='top', fontsize=12, color=MUTED)
ax.plot([-10, 190], [-10, 190], color=LINE, lw=1.4, zorder=1)
rng = np.random.default_rng(3)
for contrast, colour, marker in ((30.0, LOW, 'o'), (100.0, HIGH, 's')):
    pts = [r for r in rows if r['contrast'] == contrast]
    x = np.degrees([r['orientation'] for r in pts]) + rng.uniform(-2.2, 2.2, len(pts))
    y = np.degrees([r['orientation'] for r in pts]) + np.array([r['error_deg'] for r in pts])
    ax.scatter(x, y, s=64, marker=marker, facecolors=colour, edgecolors=PAPER, linewidths=2, zorder=3,
               label=f'{contrast:.0f} % contrast')
ax.set_xlim(-12, 192)
ax.set_ylim(-30, 210)
ax.set_xticks(range(0, 181, 45))
ax.set_yticks(range(0, 181, 45))
ax.set_xlabel('presented orientation (degrees)', color=MUTED)
ax.set_ylabel('decoded orientation (degrees)', color=MUTED)
for s in ('top', 'right'):
    ax.spines[s].set_visible(False)
ax.grid(color=LINE, lw=.6, alpha=.6)
ax.legend(loc='upper left', frameon=False, fontsize=13)
bc = ch['median_abs_error_in_range_by_contrast_deg']
lines = [('Median error, 45-135 degrees', f"{ch['median_abs_error_in_range_deg']:.1f} deg"),
         ('  at 30 % contrast', f"{bc['30']:.1f} deg"), ('  at 100 % contrast', f"{bc['100']:.1f} deg"),
         ('Error SD, 45-135 degrees', f"{ch['error_sd_in_range_deg']:.1f} deg"),
         ('Neurons decoded', f"{v['neurons_used']:,}"),
         ('Spikes per neuron per window', f"{v['mean_spikes_per_neuron_per_step']:.2f}")]
for k, (label, value) in enumerate(lines):
    f.text(.65, .70 - k * .062, label, fontsize=15, color=INK if not label.startswith('  ') else MUTED)
    f.text(.95, .70 - k * .062, value, fontsize=15, ha='right')
f.text(.65, .25, 'Exploratory calibration. It set the decoder for the\npre-declared test (protocol 017); it is not a test itself.',
       fontsize=12.5, color=MUTED, va='top')
f.text(.055, .035, 'Data: Felisyn probe run of the 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0). Simulation only.',
       fontsize=11.5, color=MUTED)
for ext in ('png', 'svg'):
    f.savefig(f'{sys.argv[2]}.{ext}', facecolor=PAPER)
