"""Figures for journal note 26 (protocol 022's declared conductance follow-up), drawn only from the CSVs that
make_conductance_csv.py wrote from this package's results/readings-a.json.

  python3 -B draw_conductance.py CSV_DIR [--font FILE ...]        (each figure 1920 x 1200 PNG, and SVG)

  1. conductance-readings:   the three readings, one panel each: the eight group-and-plaid combinations with their
                             95 % intervals and the pooled estimate, against each reading's reference value.
  2. conductance-conditions: mean conductance onto the 45 degree group per source class, and the group's firing, for
                             the blank, its own grating, the orthogonal grating and their plaid (both at 30 %).

--font takes Latin Modern Roman font files (.ttf or .otf, or .woff if fontTools is installed). Without them the
figures fall back to STIXGeneral. Every plotted number is read from the CSVs. It imports nothing but the standard
library and matplotlib.
"""
import argparse, csv, tempfile
from pathlib import Path

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager

PAPER, INK, MUTED, LINE, TINT = '#fcfaf7', '#28222d', '#776e7d', '#d8cfdf', '#efe9f7'
VIOLET = '#5924d6'   # the site's accent; one series, so no categorical pairing to validate
FOOT = ('Model: 2 mm reduction of LSV1M (Antolík et al. 2024, CC BY 4.0), simulated with Mozaik and NEST. '
        '\nExploratory, one network instance, conductances rebuilt from recorded spikes: not a biological measurement.')


def fonts(paths):
    family = []
    for p in paths:
        p = Path(p)
        if p.suffix.lower() == '.woff':
            from fontTools.ttLib import TTFont   # optional: only to read the site's web font
            t = TTFont(str(p))
            t.flavor = None
            tmp = Path(tempfile.mkdtemp()) / (p.stem + '.ttf')
            t.save(str(tmp))
            p = tmp
        font_manager.fontManager.addfont(str(p))
        family.append(font_manager.FontProperties(fname=str(p)).get_name())
    family = list(dict.fromkeys(family)) + ['STIXGeneral']
    plt.rcParams.update({'font.family': family, 'text.color': INK, 'font.size': 14, 'svg.fonttype': 'none',
                         'svg.hashsalt': 'felisyn-conductance-022', 'axes.edgecolor': LINE, 'axes.linewidth': 1,
                         'xtick.color': MUTED, 'ytick.color': MUTED, 'axes.labelcolor': MUTED})


def header(f, title, sub):
    f.text(.055, .94, 'felisyn  /  research note, protocol 022 follow-up (conductances)', color=VIOLET, fontsize=15)
    f.text(.055, .872, title, fontsize=27)
    f.text(.055, .845, sub, color=MUTED, fontsize=14, va='top', linespacing=1.35)
    f.text(.055, .014, FOOT, fontsize=11, color=MUTED)


def save(f, out, name):
    f.savefig(out / f'{name}.png', dpi=150, facecolor=PAPER)
    f.savefig(out / f'{name}.svg', facecolor=PAPER, metadata={'Date': None})
    plt.close(f)


def quiet(ax, keep=('bottom', 'left')):
    for side in ('top', 'right', 'left', 'bottom'):
        ax.spines[side].set_visible(side in keep)


def signed(x, d=3):
    return ('−' if x < 0 else '+') + f'{abs(x):.{d}f}'


PANELS = [('A_aff', 'Afferent additivity\nplaid drive over the summed singles', (0, 1.1), 1.0, 'sum of the two singles, 1', None),
          ('MM1_m_I', 'Inhibition\nchange when the second grating is added', (-0.8, 0.3), 0.0, 'no change, 0', 0.10),
          ('MM2_m_E', 'Cortical excitation\nchange when the second grating is added', (-0.8, 0.3), 0.0, 'no change, 0', 0.10)]


def draw_readings(csv_dir, out):
    data = {}
    with open(Path(csv_dir) / 'conductance-readings.csv', newline='') as fh:
        for r in csv.DictReader(fh):
            data.setdefault(r['reading'], {'combination': [], 'pooled': []})[r['kind']].append(
                (float(r['value']), float(r['lo95']), float(r['hi95'])))
    f = plt.figure(figsize=(12.8, 8))
    axs = f.subplots(1, 3, gridspec_kw={'left': .075, 'right': .975, 'top': .64, 'bottom': .125, 'wspace': .26})
    xi = [0.12 + 0.085 * k for k in range(8)]
    for ax, (key, title, ylim, ref, reflabel, margin) in zip(axs, PANELS):
        d = data[key]
        assert len(d['combination']) == 8 and len(d['pooled']) == 1
        quiet(ax)
        ax.set_xlim(0, 1.3)
        ax.set_ylim(*ylim)
        ax.grid(axis='y', color=TINT, linewidth=1)
        ax.set_axisbelow(True)
        ax.axhline(ref, color=INK, linewidth=1.2)
        ax.annotate(reflabel, (0.03, ref), textcoords='offset points', xytext=(0, 6), fontsize=12, color=MUTED)
        if margin:
            for s in (-1, 1):
                ax.axhline(s * margin, color=MUTED, linewidth=1.2, linestyle=(0, (5, 4)))
        for (v, lo, hi), x in zip(d['combination'], xi):
            ax.plot([x, x], [lo, hi], color=VIOLET, linewidth=1, alpha=.55, zorder=3, solid_capstyle='butt')
            ax.plot([x], [v], 'o', markersize=5.5, color=VIOLET, zorder=4)
        v, lo, hi = d['pooled'][0]
        ax.plot([1.0, 1.0], [lo, hi], color=INK, linewidth=2.4, zorder=4, solid_capstyle='butt')
        ax.plot([1.0], [v], 'D', markersize=8, color=INK, zorder=5)
        ax.annotate(signed(v) if margin else f'{v:.3f}', (1.0, v), textcoords='offset points', xytext=(9, -4.5),
                    fontsize=13, color=INK)
        ax.set_xticks([0.42, 1.0])
        ax.set_xticklabels(['eight combinations', 'pooled'])
        ax.tick_params(axis='x', length=0, labelsize=12.5)
        ax.set_title(title, fontsize=15, pad=10)
    axs[0].set_ylabel('plaid response / sum of single responses', fontsize=13)
    axs[1].set_ylabel('change, as a share of what the first grating evoked', fontsize=13)
    axs[1].annotate('margin ±0.10', (1.27, 0.10), textcoords='offset points', xytext=(0, 6), fontsize=12,
                    color=MUTED, ha='right')
    header(f, 'The second grating lowered inhibition, and cortical excitation more',
           'Layer 4 excitatory cells tuned to one grating of an orthogonal plaid, conductances rebuilt from the '
           'pilot’s recorded\nspikes. Dots: each cell group and plaid with its 95 % interval; diamond: the pooled '
           'reading with its 95 % interval\n(10,000 step resamplings).')
    save(f, out, 'conductance-readings')


QUANT = [('aff', 'afferent (from the LGN)', 'mean conductance, nS'), ('E', 'cortical excitation', 'mean conductance, nS'),
         ('I', 'inhibition', 'mean conductance, nS'), ('G|L4E', 'the cells’ own firing', 'spikes per cell per step')]
CONDS = ['blank', 'own grating', 'orthogonal grating', 'plaid']
LABELS = ['blank', 'own\ngrating', 'orthogonal\ngrating', 'plaid']


def draw_conditions(csv_dir, out):
    data = {}
    with open(Path(csv_dir) / 'conductance-conditions.csv', newline='') as fh:
        for r in csv.DictReader(fh):
            if r['group_deg'] == '45':
                data[(r['quantity'], r['condition'])] = float(r['value'])
    f = plt.figure(figsize=(12.8, 8))
    axs = f.subplots(1, 4, gridspec_kw={'left': .065, 'right': .985, 'top': .65, 'bottom': .15, 'wspace': .32})
    for ax, (q, title, unit) in zip(axs, QUANT):
        vals = [data[(q, c)] for c in CONDS]
        quiet(ax)
        ax.grid(axis='y', color=TINT, linewidth=1)
        ax.set_axisbelow(True)
        bars = ax.bar(range(4), vals, width=.62, color=[LINE, VIOLET, LINE, INK])
        for b, v in zip(bars, vals):
            ax.annotate(f'{v:.2f}', (b.get_x() + b.get_width() / 2, v), textcoords='offset points', xytext=(0, 5),
                        ha='center', fontsize=12.5, color=INK)
        ax.set_ylim(0, max(vals) * 1.16)
        ax.set_xticks(range(4))
        ax.set_xticklabels(LABELS, fontsize=11.5)
        ax.tick_params(axis='x', length=0)
        ax.set_ylabel(unit, fontsize=12.5)
        ax.set_title(title, fontsize=15, pad=10)
    header(f, 'The mean input from the LGN does not tell the two gratings apart',
           'Cells preferring 45 degrees; both gratings at 30 % contrast; means over the response window of every '
           'step with\nthat stimulus. The afferent mean is nearly the same for the cells’ own grating, the orthogonal '
           'one and the plaid;\nthe cortical conductances and the firing are not.')
    save(f, out, 'conductance-conditions')


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument('csv_dir')
    ap.add_argument('--font', nargs='*', default=[])
    a = ap.parse_args()
    fonts(a.font)
    out = Path(a.csv_dir)
    draw_readings(a.csv_dir, out)
    draw_conditions(a.csv_dir, out)
