"""Render the lecture curve from its CSV. Requires matplotlib and numpy."""
from pathlib import Path
import csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np

root = Path(__file__).resolve().parent.parent
with (root / 'data/van-deemter-curve.csv').open() as f:
    rows = list(csv.DictReader(f))
def values(key):
    return np.array([float(r[key]) for r in rows])
navy, purple, orange, teal = '#16344b', '#7752a5', '#b95212', '#007f87'
plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 16,
                     'text.color': navy, 'axes.labelcolor': navy,
                     'xtick.color': navy, 'ytick.color': navy})
fig = plt.figure(figsize=(12, 10), facecolor='white')
fig.text(.075, .95, 'Why flow changes efficiency', fontsize=27, weight='bold')
fig.text(.075, .905, 'H = A + B/u + Cu', fontsize=22)
fig.text(.925, .905, 'Lower H → higher efficiency', ha='right', fontsize=16)
ax = fig.add_axes([.105, .275, .845, .565])
ax.set_facecolor('#f7fafc')
u = values('u_mm_s')
for key, color, style, width, label in [
    ('H_mm', navy, '-', 3.7, 'Total H'),
    ('A_mm', purple, '--', 2.6, 'A'),
    ('B_over_u_mm', orange, '-.', 2.6, 'B/u'),
    ('Cu_mm', teal, ':', 3.2, 'Cu')]:
    ax.plot(u, values(key)*1000, color=color, linestyle=style, linewidth=width, label=label)
ax.set(xlim=(.15, 4), ylim=(0, 40), xlabel='Linear velocity, u (mm/s)', ylabel='Plate height, H (μm)')
ax.set_xticks([.5,1,1.5,2,2.5,3,3.5,4])
ax.set_yticks([0,10,20,30,40])
ax.grid(axis='y', color='#dce5eb', linewidth=1)
ax.set_axisbelow(True)
for side in ['top', 'right']:
    ax.spines[side].set_visible(False)
for side in ['left', 'bottom']:
    ax.spines[side].set_color('#9aaeba')
ax.tick_params(labelsize=16, length=5, pad=7)
ax.xaxis.labelpad = 13
ax.yaxis.labelpad = 10
ax.legend(loc='upper right', ncol=2, fontsize=17, frameon=True, facecolor='white', edgecolor='#dce5eb', framealpha=1)
ax.vlines(1, 0, 18, color='#9aaeba', linestyle=(0,(3,4)), linewidth=1.5)
ax.scatter([1], [18], s=100, color=navy, edgecolor='white', linewidth=1.5, zorder=6)
ax.annotate('Minimum H = 18 μm\nat u = 1.00 mm/s', xy=(1,18), xytext=(1.45,29),
            fontsize=17, weight='bold', color=navy,
            arrowprops={'arrowstyle':'->','color':navy,'lw':1.5},
            bbox={'boxstyle':'round,pad=0.6','fc':'white','ec':'#dce5eb'})
for x, color, title, body in [
    (.075, purple, 'A · Multiple paths', 'Constant in this model'),
    (.375, orange, 'B/u · Diffusion', 'Falls as flow increases'),
    (.685, teal, 'Cu · Mass transfer', 'Rises as flow increases')]:
    fig.text(x, .16, title, fontsize=16, weight='bold', color=color)
    fig.text(x, .127, body, fontsize=14)
fig.text(.075, .072, 'Efficiency optimum ≠ best practical flow', fontsize=17, weight='bold')
fig.text(.075, .043, 'Also consider resolution, run time and pressure.', fontsize=14)
fig.savefig(root / 'images/van-deemter/van-deemter-curve.png', dpi=200, facecolor='white')
plt.close(fig)
