import sys; sys.path[:0] = [".", ".."]
import numpy as np, json
from figstyle import *
O=json.load(open('out.json')); lc,lr=O['lost_cap'],O['lost_rent']
r=np.linspace(0.001,0.012,200); E=r*8760*1000  # kWh per MW-yr
def batt(frac,h): capex=(241*h+372)*1000*frac; return capex*(0.08/(1-1.08**-15)+0.04)
fig,ax=plt.subplots(figsize=(5.6,3.3))
ax.fill_between(r*100,E*lc/1e3,E*lr/1e3,color=RED,alpha=0.25,lw=0,label='Value of compute lost to curtailment')
ax.plot(r*100,E*lc/1e3,color=RED,lw=1); ax.plot(r*100,E*lr/1e3,color=RED,lw=1)
for (f,h),ls in [((0.5,2),'--'),((1.0,4),':')]:
    ax.axhline(batt(f,h)/1e3,color=BLUE,ls=ls,lw=1.3,label=f'Battery covering {f:.0%} of load for {h} h')
for x in [0.25,0.5,1.0]: ax.axvline(x,color='0.82',lw=0.7,zorder=0)
ax.set_xlabel('Annual curtailment, percent of maximum uptime'); ax.set_ylabel('Thousand USD per MW-year')
ax.set_xlim(0.1,1.2); ax.set_ylim(0,220)
fig.canvas.draw()
for k,lab,dy,va in [(lr,'lost-rent bound',2,'bottom'),(lc,'idle-capital bound',-4,'top')]:
    x0,x1=0.70,0.80; y0,y1=x0/100*8760*1000*k/1e3,x1/100*8760*1000*k/1e3
    p0,p1=ax.transData.transform([(x0,y0),(x1,y1)]); ang=np.degrees(np.arctan2(p1[1]-p0[1],p1[0]-p0[0]))
    ax.text(x0,y0+dy,lab,rotation=ang,rotation_mode='anchor',ha='left',va=va,fontsize=7,color=RED)
ax.legend(loc='upper center',bbox_to_anchor=(0.5,-0.2),ncol=2,fontsize=7.5)
save(fig,'fig_curtail.pdf')

gpus=100e6/(132e3/72); capJ=65*gpus
per=np.logspace(-1,2,100)  # swing period s
fig,ax=plt.subplots(figsize=(5.6,3.2))
for dP,c in [(10,GREEN),(30,ORANGE),(50,PURPLE)]:
    ax.plot(per,dP*1e6*per/2/3.6e6,color=c,lw=1.4,label=f'{dP} MW swing')
ax.axhline(capJ/3.6e6,color=NAVY,ls='--',lw=1,label='Storage in GB300 power supplies, 100 MW of racks')
ax.set_xscale('log'); ax.set_yscale('log'); ax.set_xticks([0.1,1,10,100]); ax.set_xticklabels(['0.1','1','10','100']); ax.set_yticks([0.1,1,10,100,1000]); ax.set_yticklabels(['0.1','1','10','100','1,000']); ax.set_xlabel('Period of the power swing (s)'); ax.set_ylabel('Energy to absorb half a cycle (kWh)')
ax.legend(loc='upper left',fontsize=7.5)
save(fig,'fig_swing.pdf')
