"""Host memory and swap during the full-network feasibility probe, from the retained 15 s samples
(receipts/full-1x16-70ms/resources.csv, host.json) and the phase marks in probe-analysis.json.
Measurements only; no neural activity. Writes figures/probe-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
REC = ROOT / 'receipts/full-1x16-70ms'
host = json.loads((REC / 'host.json').read_text())
summary = json.loads((ROOT / 'probe-analysis.json').read_text())
GIB = 2 ** 30
rows = []
with (REC / 'resources.csv').open() as fh:
    for r in csv.DictReader(fh):
        rows.append((float(r['epoch']), (host['MemTotal_kB'] - float(r['memavailable_kb'])) * 1024 / GIB,
                     (host['SwapTotal_kB'] - float(r['swapfree_kb'])) * 1024 / GIB))
t0 = summary['marks_utc_epoch']['start']
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 14', color=VIOLET, fontsize=15)
net = summary['network']
f.text(.065, .869, 'The full network on an 8 GB server', fontsize=29)
f.text(.065, .817, f"Host memory and swap while building and briefly running the full model: {net['neurons']:,} neurons, "
       f"{net['nest_num_connections_after_build'] / 1e6:.1f} million connections.", color=MUTED, fontsize=15)

ax = f.add_axes([.085, .25, .83, .48], facecolor=PAPER)
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['MemTotal_kB'] * 1024 / 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.18
for name, label, align in [('constructed', ' network built', 'left'), ('simulated', '0.52 s run done ', 'right')]:
    if name in summary['marks_utc_epoch']:
        x = (summary['marks_utc_epoch'][name] - t0) / 3600
        ax.axvline(x, color=VIOLET, linewidth=1, linestyle=(0, (2, 2)))
        ax.text(x, top * .97, label, fontsize=12.5, color=VIOLET, va='top', ha=align)
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)
sim = summary['simulation']
notes = [f"Built in {summary['phases_wall_seconds']['construct'] / 3600:.1f} h. The {sim['nest_biological_time_ms'] / 1000:.2f} s run took "
         f"{summary['phases_wall_seconds']['simulate'] / 60:.0f} min; NEST's loop ran at about {sim['nest_loop_wall_seconds_per_simulated_second']:.0f} s "
         f"per simulated second in the last {sim['last_call_ms']:.0f} ms.",
         '15 s host samples (resources.csv). 1 MPI rank × 16 threads on 4 vCPUs, 7.8 GiB RAM, 64 GiB swap file. A feasibility probe, not the experiment.',
         '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)
(ROOT / 'figures').mkdir(exist_ok=True)
for ext in ['png', 'svg']:
    f.savefig(ROOT / f'figures/probe-memory.{ext}', facecolor=PAPER)
print('ok')
