"""Reproduce the constructed reduced-height / normalized-pressure comparison."""
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
particles = [10, 5, 3, 1]
colors = ['#748694', '#2775b6', '#00897b', '#a63658']
u = np.linspace(.1, 6, 300)
rows = []
for dp in particles:
    for velocity in sorted(set(u.tolist() + [5/dp])):
        nu = velocity*dp/2.5
        rows.append(dict(particle_um=dp, u_mm_s=velocity, reduced_velocity=nu,
                         H_um=dp*(1+1/nu+.25*nu), pressure_relative_to_5um_optimum=velocity*(5/dp)**2,
                         optimum=velocity == 5/dp))
with (root/'data/particle-size-kinetics-pressure.csv').open('w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0]))
    writer.writeheader(); writer.writerows(rows)
plt.rcParams.update({'font.family':'DejaVu Sans', 'font.size':14, 'text.color':'#16344b',
                     'axes.labelcolor':'#16344b', 'axes.spines.top':False, 'axes.spines.right':False})
fig, axes = plt.subplots(1, 2, figsize=(16, 9), dpi=240)
fig.subplots_adjust(left=.075, right=.97, top=.76, bottom=.23, wspace=.25)
fig.text(.075,.93,'Smaller particles buy efficiency at a steep pressure cost',fontsize=25,weight='bold')
fig.text(.075,.87,'Equal column length • constant viscosity • common reduced-height and permeability models',fontsize=15)
for dp, color in zip(particles, colors):
    data = [r for r in rows if r['particle_um'] == dp]
    x = [r['u_mm_s'] for r in data]
    axes[0].plot(x,[r['H_um'] for r in data],color=color,lw=2.6,label=f'{dp:g} µm')
    opt = next(r for r in data if r['optimum'])
    axes[0].scatter([opt['u_mm_s']],[opt['H_um']],s=65,color=color,edgecolor='white',zorder=5)
axes[0].set(xlim=(0,6), xlabel='Linear velocity, u (mm/s)',
            title='A  ·  Smaller particles lower the Van Deemter curve',
            ylabel='Plate height, H (µm)',ylim=(0,80))
# Place dimensions directly beside the curves, inside the plot boundary.
for dp, color in zip(particles, colors):
    label_u = 5.4
    nu = label_u*dp/2.5
    label_h = dp*(1+1/nu+.25*nu)
    axes[0].annotate(f'{dp:g} µm', xy=(label_u,label_h), xytext=(7,7),
                     textcoords='offset points', color=color, fontsize=15, weight='bold',
                     bbox=dict(facecolor='white',edgecolor='none',alpha=.85,pad=1.5))
diameters = np.linspace(.5,5,451)
pressure_rows = [dict(particle_um=float(d), optimum_u_mm_s=5/d,
                     pressure_at_optimum_relative_to_1_5um=(1.5/d)**3,
                     pressure_at_fixed_u_relative_to_1_5um=(1.5/d)**2) for d in diameters]
with (root/'data/pressure-vs-particle-size.csv').open('w',newline='') as f:
    writer=csv.DictWriter(f,fieldnames=list(pressure_rows[0]))
    writer.writeheader();writer.writerows(pressure_rows)
axes[1].axvspan(.5,1.5,color='#a63658',alpha=.07)
axes[1].plot(diameters,(1.5/diameters)**3,color='#a63658',lw=3,label='At each efficiency optimum (1/dp³)')
axes[1].plot(diameters,(1.5/diameters)**2,color='#748694',lw=2,ls='--',label='At fixed linear velocity (1/dp²)')
for d, color in zip(particles,colors):
    axes[1].scatter([d],[(1.5/d)**3],color=color,s=65,edgecolor='white',zorder=5)
axes[1].axvline(1.5,color='#b46719',ls=':',lw=1.5)
axes[1].set(xlim=(5,.5),ylim=(0,18),xticks=[5,4,3,2,1.5,1,.5],
            xlabel='Particle diameter, dp (µm)  →  smaller particles',
            ylabel='Relative pressure (1.5 µm = 1 for each curve)',
            title='B  ·  Pressure required to drive the flow')
axes[1].legend(loc='upper left',fontsize=11,frameon=False)
axes[1].annotate('1 µm: 3.375×',xy=(1,3.375),xytext=(2.9,5.5),fontsize=13,color='#a63658',
                 arrowprops={'arrowstyle':'->','color':'#a63658'})
axes[1].annotate('Continues upward as dp → 0',xy=(.57,17),xytext=(3.5,12),fontsize=13,color='#a63658',
                 arrowprops={'arrowstyle':'->','color':'#a63658'})
for ax in axes:
    ax.grid(alpha=.18);ax.set_axisbelow(True)
fig.text(.075,.13,'Following the efficiency optimum: uₒₚₜ ∝ 1/dp  →  ΔPₒₚₜ ∝ 1/dp³',fontsize=18,weight='bold')
fig.text(.075,.08,'1.5 → 1 µm: 3.375× optimum pressure for 1.5× plates and ≈1.22× resolution (fixed k and α).',fontsize=15)
fig.text(.075,.035,'Illustrative model, not product data. h = 1 + 1/ν + 0.25ν; ν = u dp/Dm; Dm = 2.5 × 10⁻⁹ m²/s.',fontsize=12,color='#526879')
fig.savefig(root/'images/hardware/particle-size-kinetics-pressure.png',dpi=240)
plt.close(fig)
