"""Figures for protocol 018's results, from the retained results.json only.
  1. OUT_STEM.png/.svg: for each state, the four cats' within-segment shared fluctuation at 100 ms (the primary
     measure) with 95 % bootstrap intervals, and the model's primary value with its interval and its variants.
  2. OUT_STEM-timescale.png/.svg: the primary measure at 10, 50, 100 and 250 ms (a secondary measure) for the
     model and for each cat's desynchronized and synchronized states.

  python3 draw_results.py RESULTS.json OUT_STEM      (1920 x 1200 each; log axes, all values positive)
"""
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'
MODEL, DATA = '#6240ab', '#b26a00'            # validated pair (CVD dE 27.7), both pass contrast on PAPER
MODEL_LIGHT, DATA_LIGHT = '#d9cdee', '#f3dfc0'
plt.rcParams.update({'font.family': 'STIXGeneral', 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                     'axes.edgecolor': LINE, 'xtick.color': MUTED, 'ytick.color': INK})
ROWS = ['desynchronized I', 'desynchronized II', 'synchronized fast', 'synchronized slow I', 'synchronized slow II']

res = json.load(open(sys.argv[1]))
primary_name = res['parameters']['primary_units']
model = res['model'][primary_name]
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.055, .94, 'felisyn  /  research note, protocol 018', color=MODEL, fontsize=15)
f.text(.055, .872, 'Shared spontaneous fluctuations: model and cat area 17', fontsize=28)
f.text(.055, .823, 'Within-second shared fluctuation of firing at 100 ms between recording sites (cat) or neuron pools (model), '
                   '95% bootstrap intervals.', color=MUTED, fontsize=14)
ax = f.add_axes([.27, .17, .66, .58], facecolor=PAPER)
vals = [model['ci95'][0], model['ci95'][1]]
for i, g in enumerate(ROWS):
    y = len(ROWS) - 1 - i
    for k in range(1, 5):
        e = res['data'][f'cat{k}']['groups'][g]
        yy = y + 0.28 - k * 0.11
        ax.plot(e['ci95'], [yy, yy], color=DATA, lw=1.8, solid_capstyle='round', zorder=2)
        ax.scatter([e['value']], [yy], s=40, color=DATA, edgecolors=PAPER, linewidths=1.5, zorder=3)
        vals += e['ci95']
    f.text(.255, .17 + .58 * (y + .5) / len(ROWS), g, ha='right', va='center', fontsize=14)
vals += [v['value'] for v in res['model'].values()]
lo, hi = min(vals), max(vals)
ax.set_xscale('log')
ax.axvspan(model['ci95'][0], model['ci95'][1], color=MODEL_LIGHT, lw=0, zorder=0)
ax.axvline(model['value'], color=MODEL, lw=2, zorder=1)
for name, v in res['model'].items():
    if name != primary_name:
        ax.plot([v['value']], [-0.55], marker='|', color=MODEL, ms=14, mew=1.5)
ax.set_ylim(-0.8, len(ROWS) - 0.4)
ax.set_yticks([])
ax.set_xlim(lo / 1.6, hi * 1.6)
ticks = [x for x in (0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5) if lo / 1.6 <= x <= hi * 1.6]
ax.set_xticks(ticks)
ax.set_xticklabels([f'{x:g}' for x in ticks])
ax.minorticks_off()
ax.set_xlabel('shared fluctuation at 100 ms (normalised covariance of firing between units, within 1 s; log scale)', color=MUTED)
for s in ('top', 'right', 'left'):
    ax.spines[s].set_visible(False)
ax.grid(axis='x', color=LINE, lw=.6, alpha=.6)
r = res['primary_reading']
f.text(.27, .085, f"Model (violet): {model['value']:.3f} [{model['ci95'][0]:.3f}, {model['ci95'][1]:.3f}]; violet ticks below: the five "
                  f"model variants. Amber: cats 1 to 4, top to bottom.", fontsize=12, color=MUTED)
f.text(.27, .055, f"Declared primary reading (desynchronized): {r['text']}.", fontsize=13.5)
f.text(.055, .02, 'Data: Hahn et al. 2017, PLoS Comput Biol, S5 Dataset (CC BY 4.0). Model: run 011 of LSV1M (Antolík et al. 2024, CC BY 4.0).',
       fontsize=11, color=MUTED)
for ext in ('png', 'svg'):
    f.savefig(f'{sys.argv[2]}.{ext}', facecolor=PAPER)
plt.close(f)

# ---------------------------------------------------------------- figure 2: time scale (secondary measure)
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.055, .94, 'felisyn  /  research note, protocol 018 (secondary measure)', color=MODEL, fontsize=15)
f.text(.055, .872, 'Shared fluctuations by time scale', fontsize=28)
f.text(.055, .823, 'The primary measure computed in bins of 10, 50, 100 and 250 ms. Reported as a secondary measure; no declared reading.',
       color=MUTED, fontsize=14)
ax = f.add_axes([.1, .15, .62, .6], facecolor=PAPER)
bins = sorted(float(b) for b in model['curve'])
ms = [b * 1000 for b in bins]
for k in range(1, 5):
    for g, style in (('desynchronized (1-2)', '-'), ('synchronized (3-5)', (0, (4, 3)))):
        curve = res['data'][f'cat{k}']['groups'][g]['curve']
        ax.plot(ms, [curve[str(b)] for b in bins], color=DATA, lw=1.6, ls=style, marker='o', ms=5, alpha=.9)
ax.plot(ms, [model['curve'][str(b)] for b in bins], color=MODEL, lw=2.6, marker='o', ms=8)
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xticks(ms)
ax.set_xticklabels([f'{m:g}' for m in ms])
ax.minorticks_off()
yt = [x for x in (0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5) if ax.get_ylim()[0] <= x <= ax.get_ylim()[1]]
ax.set_yticks(yt)
ax.set_yticklabels([f'{x:g}' for x in yt])
ax.set_xlabel('bin size (ms)', color=MUTED)
ax.set_ylabel('shared fluctuation (log scale)', color=MUTED)
for s in ('top', 'right'):
    ax.spines[s].set_visible(False)
ax.grid(color=LINE, lw=.6, alpha=.6)
f.text(.75, .66, 'Model, primary pools', color=MODEL, fontsize=15)
f.text(.75, .61, 'Cats 1 to 4, desynchronized', color=DATA, fontsize=15)
f.text(.75, .56, 'Cats 1 to 4, synchronized (dashed)', color=DATA, fontsize=15)
f.text(.75, .44, 'Both fall with bin size. The model\nfalls much faster: its shared\nfluctuations are fast.', fontsize=13, color=MUTED, va='top')
f.text(.055, .03, 'Data: Hahn et al. 2017, PLoS Comput Biol, S5 Dataset (CC BY 4.0). Model: run 011 of LSV1M (Antolík et al. 2024, CC BY 4.0).',
       fontsize=11, color=MUTED)
for ext in ('png', 'svg'):
    f.savefig(f'{sys.argv[2]}-timescale.{ext}', facecolor=PAPER)
