"""Host memory and swap during the protocol-007 full run, from the retained 15 s samples
(receipts/resources.csv) and the call times in run-summary.json. Measurements only; no neural
activity. Writes figures/run-memory.png (1920 x 1200) and .svg.
"""
import csv, json
from pathlib import Path
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT = Path(__file__).resolve().parent
summary = json.loads((ROOT / 'run-summary.json').read_text())
host = json.loads((ROOT / 'receipts/launch.json').read_text())['host']
GIB = 2 ** 30
rows = []
with (ROOT / 'receipts/resources.csv').open() as fh:
    for r in csv.DictReader(fh):
        rows.append((float(r['epoch']), (host['memory_total_bytes'] - float(r['memavailable_kb']) * 1024) / GIB,
                     (host['swap_total_bytes'] - float(r['swapfree_kb']) * 1024) / GIB))
calls = summary['run_calls']
t0 = calls[0]['start_epoch'] - summary['phases_hours']['construction'] * 3600
hours = [(t - t0) / 3600 for t, _, _ in rows]

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': MUTED})
f = plt.figure(figsize=(12.8, 8), dpi=150, facecolor=PAPER)
f.text(.065, .94, 'felisyn  /  research note 15', color=VIOLET, fontsize=15)
f.text(.065, .869, 'Fifteen hours on an 8 GB server', fontsize=29)
f.text(.065, .817, 'Host memory and swap during the full run: build, 40.32 s of spontaneous activity, retrieval and saving.',
       color=MUTED, fontsize=15)
ax = f.add_axes([.085, .25, .83, .48], facecolor=PAPER)
main = calls[1]
x0, x1 = (main['start_epoch'] - t0) / 3600, (main['end_epoch'] - t0) / 3600
ax.axvspan(x0, x1, color=LIGHT, alpha=.25, linewidth=0)
ax.fill_between(hours, [s for _, _, s in rows], color=LIGHT, alpha=.55, linewidth=0)
ax.plot(hours, [s for _, _, s in rows], color=VIOLET, linewidth=2, label='Swap in use')
ax.plot(hours, [m for _, m, _ in rows], color=INK, linewidth=1.6, label='Memory in use')
ram = host['memory_total_bytes'] / GIB
ax.axhline(ram, color=MUTED, linewidth=1, linestyle=(0, (4, 3)))
ax.text(hours[-1], ram + .5, f'physical memory {ram:.1f} GiB', ha='right', va='bottom', fontsize=12, color=MUTED)
top = max(s for _, _, s in rows) * 1.22
ax.text((x0 + x1) / 2, top * .89, f"main segment, 40.32 s of model time: {main['wall_s'] / 3600:.1f} h", ha='center', va='top', fontsize=13, color=VIOLET)
built = summary['phases_hours']['construction']
ax.axvline(built, color=VIOLET, linewidth=1, linestyle=(0, (2, 2)))
ax.text(built, top * .965, '  network built', ha='left', va='top', fontsize=12.5, color=VIOLET)
saved = summary['phases_hours']
end = sum(saved.values())
ax.axvline(end, color=VIOLET, linewidth=1, linestyle=(0, (2, 2)))
ax.text(end, top * .88, 'data saved ', ha='right', va='top', fontsize=12.5, color=VIOLET)
ax.set_ylim(0, top)
ax.set_xlim(0, hours[-1])
ax.set_xlabel('Hours since start', fontsize=13, color=MUTED)
ax.set_ylabel('GiB', fontsize=13, color=MUTED)
for side in ['top', 'right']:
    ax.spines[side].set_visible(False)
ax.legend(loc='upper left', frameon=False, fontsize=13)
w = summary['resources']['whole_run']
elapsed = json.loads((ROOT / 'receipts/launch.json').read_text())['elapsed_s']
notes = [f"Built in {saved['construction']:.1f} h; NEST simulated the 40.32 s segment at {main['loop_seconds_per_simulated_second']:.0f} s per simulated second; "
         f"{round(elapsed / 60) // 60} h {round(elapsed / 60) % 60} min in total.",
         f"Peaks: {w['peak_memory_in_use_gib']:.1f} GiB memory, {w['peak_swap_in_use_gib']:.1f} GiB swap. 15 s host samples (receipts/resources.csv); "
         '1 MPI rank × 16 threads on 4 vCPUs.',
         'Model: Antolík et al. 2024, LSV1M v1.0 (MIT). Measurements of our own run; no neural activity is shown.']
for i, line in enumerate(notes):
    f.text(.065, .15 - i * .042, line, fontsize=15 if i == 0 else 13, color=INK if i == 0 else MUTED)
for ext in ['png', 'svg']:
    f.savefig(ROOT / f'figures/run-memory.{ext}', facecolor=PAPER)
print('ok')
