#%%
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams.update({'font.size': 13, 'lines.linewidth': 2.5})
from matplotlib.widgets import Slider, Button

#%%
# Explicit equations 
k = 0.23
v0 = 10
def ODEfun(Yfuncvec, V, k, v0): 
    Ca = Yfuncvec[0]
    Cb = Yfuncvec[1]
    # Explicit equations Inline
    ra = -k * Ca
    rb = -ra
    # Differential equations
    dCadV = ra / v0
    dCbdV = rb / v0
    return np.array([dCadV, dCbdV]) 

Vspan = np.linspace(0, 100, 100) # Range for the Volume of the reactor. 
y0 = np.array([10, 0]) # Initial values for the dependent variables Ca and Cb

#%%
fig, (ax1, ax2) = plt.subplots(2,1)
fig.suptitle("""LEP-1-3a: How Large is the Reactor Volume (Irreversible Reaction)""", fontweight='bold', x = 0.25, y=0.98)
plt.subplots_adjust(left=0.4)
fig.subplots_adjust(hspace=0.3)
sol =  odeint(ODEfun, y0, Vspan, (k, v0))
Ca = sol[:, 0]
Cb = sol[:, 1]
p1, p2 = ax1.plot(Vspan, Ca, Vspan, Cb)
ax1.legend([r'$C_{A}$', r'$C_{B}$'], loc='upper right')
ax1.set_xlabel('V $(dm^{3})$', fontsize='medium')
ax1.set_ylabel(r'Concentration $(mol/dm^3)$', fontsize='medium')
ax1.grid()
ax1.set_ylim(0, 10.5)
ax1.set_xlim(0, 100)

ax1.text(-52, -7,'Differential Equations'
         '\n'
         r'$\dfrac{dC_A}{dV} = \dfrac{r_A}{v_0}$'
                  '\n'
         r'$\dfrac{dC_B}{dV} = \dfrac{r_B}{v_0}$'
         '\n'
         '\n'
         'Explicit Equations'
         '\n'
         r'$r_A = -k*C_A$'
                  '\n'
         r'$r_B = -r_A$', ha='left', wrap = True, fontsize=13,
        bbox=dict(facecolor='none', edgecolor='black', pad=10.0), fontweight='bold')

ra = -k*Ca
rb = -ra
p3, p4 = ax2.plot(Vspan, ra, Vspan, rb)
plt.legend([r'$r_{A}$', r'$r_{B}$'], loc='upper right')
ax2.set_xlabel('V $(dm^{3})$', fontsize='medium')
ax2.set_ylabel(r'Reaction Rate $(mol/dm^3.min)$', fontsize='medium')
ax2.grid()
ax2.set_ylim(-10, 10)
ax2.set_xlim(0, 100)



axcolor = 'black'
ax_k = plt.axes([0.1, 0.7, 0.2, 0.02], facecolor=axcolor)
ax_v0 = plt.axes([0.1, 0.65, 0.2, 0.02], facecolor=axcolor)

sk = Slider(ax_k, r'$k$ ($min^{-1}$)', 0, 1, valinit=0.23)
sv0 = Slider(ax_v0, r'$v_{o} (\frac{dm^3}{min}$)', 0, 20, valinit=10)


def update_plot(val):
    k = sk.val
    v0 = sv0.val
    sol =  odeint(ODEfun, y0, Vspan, (k, v0))
    Ca = sol[:, 0]
    Cb = sol[:, 1]
    ra = -k*Ca
    rb = -ra    
    p1.set_ydata(Ca)
    p2.set_ydata(Cb)
    p3.set_ydata(ra)
    p4.set_ydata(rb)    
    fig.canvas.draw_idle()

sk.on_changed(update_plot)
sv0.on_changed(update_plot)

resetax = plt.axes([0.15, 0.75, 0.09, 0.05])
button = Button(resetax, 'Reset Variables', color='cornflowerblue', hovercolor='0.975')


def reset(event):
    sk.reset()
    sv0.reset()
    
button.on_clicked(reset)


plt.show()
