```python
#increase page width
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:100% !important; }</style>"))
#create a button to run all following cells
HTML(''' <form action="javascript:IPython.notebook.execute_cells_below()"><input type="submit" id="toggleButton" value="Run all cells below"></form>''')
```

# Modes of the new model (1D)

As shown in the notes, the computation of the modes leads to the following stability matrix
\begin{align}
  Tr(M) &= -K k^2 - \left( 1+\alpha  \frac{\overline{m}}{r} \right) \tau_{v}^{-1} - \frac{r}{\overline{m}\tau_{m}} + \overline{X}r \tau_m - D_mk^2 \label{eq:Tr_remodel-adim}\\
    det(M) &= k^4 K D_m + k^2 \left( \frac{K r}{\overline{m}\tau_m} + (1+\alpha \frac{\overline{m}}{r}) \tau_v^{-1} D_m \right)  +(1+\alpha \frac{\overline{m}}{r}) \tau_v^{-1} \left( \frac{r}{\overline{m}\tau_m}-\overline{X} r \tau_m \right)  \label{eq:Det_remodel-adim}
\end{align}

Where we recall the definition $\overline{X}=  \chi (1-\overline{m})$
The higest higenvalue is then given by :
\begin{equation}
\lambda_+ = \text{Tr} - \sqrt{\text{Tr}^2 - 4 \text{Det}}
\end{equation}
Next we plot $\lambda_+(k)$, namely the dispersion relation of our 1D system.

```python
import numpy as np

from numpy import linalg as LA
import math
from numpy.lib import scimath
from precompute_fp import fp_myo
import bz2
import pickle
import os
import sys

%matplotlib widget
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.dpi']= 150 #sets ploted image dpi (for the inline backend)
matplotlib.rcParams['savefig.dpi'] = 150 #dpi for the notebook backend

from ipywidgets import interactive,fixed,FloatSlider,HBox, Layout,VBox
import ipywidgets as widgets
# nb :
# M(Tbar,Bbar)

# feng parameters :      tbar =1.7731898882334818
#                        bbar=4.6437261959339562
#bbar = 4.64373
#tbar = 2.47669
# 1(stable upper) branch mbar = 0.92598269226757346
#                        xbar = 0.3437161108695741
#
#----------------

class modes() :

     def __init__(self,K=1.0,tau_v=30,koff=0.14,kon=0.14,alpha=10,Dm=1.0):
          self.Ks=np.linspace(0,1,100) #frequency range
          self.myofp = fp_myo() #load the myosin fixed points
          self.Bbars,self.Tbars,self.M0,self.M1,self.M2 = self.myofp.Bbars,self.myofp.Tbars,self.myofp.M0,self.myofp.M1,self.myofp.M2
          self.Tgrid,self.Bgrid = np.meshgrid(self.Tbars,self.Bbars,indexing='ij')

     def stabmat(self,k,mbar,bbar,K,tau_v,r,alpha,Dm,tau_m) : # tau_m and k0 are not relevant for the eigenvalues so we assume = 1
         with np.errstate(divide='ignore', invalid='ignore'): #ignore divide by zero
             T = - k**2*K* - Dm*k**2  - (1+alpha*mbar/r)/tau_v  - r/(mbar*tau_m) + bbar*(1-mbar)*r*tau_m
             D = k**4*K*Dm + k**2*((K*r/(mbar) + (1+alpha*mbar/r)*Dm/tau_v)) + (1+alpha*mbar/r)/tau_v*(r/(mbar*tau_m)-bbar*(1-mbar)*r)
             Delta = T - 4*D
             L1 =   0.5*(T+ np.lib.scimath.sqrt(Delta)) #most unstable wavelength in all case
         return L1

     def compute_modes(self,k,m,b,K,tau_v,r,alpha,Dm,tau_m) :
          if m == np.NaN :
               return np.NaN*np.ones(len(k))
          return self.stabmat(k,m,b,K,tau_v,r,alpha,Dm,tau_m)

modes=modes()
k = np.linspace(0,1,100)

init = 0

def plot_modes(k,K,r,tau_v,xstar,bbar,alpha,Dm,tau_m) :
    global p0,p1,p2,fig1,ax1,lgd,init
    #compute mbar branches
    tbar = xstar*bbar
    i = np.abs(modes.Tbars-tbar).argmin()#find closest value in precomputed data
    j = np.abs(modes.Bbars-bbar).argmin()#find closest value in precomputed data
    mbars = [modes.M0[i][j],modes.M1[i][j],modes.M2[i][j]]
    lam = [modes.compute_modes(k,mbar,bbar,K,tau_v,r,alpha,Dm,tau_m).real for mbar in mbars]
    p0.set_ydata(lam[0].real)
    p1.set_ydata(lam[1].real)
    p2.set_ydata(lam[2].real)
    [lgd.get_texts()[i].set_text(r'Re($\lambda_{%d+}, m=%f$)'%(i,mbars[i])) for i in range(len(lam))]
    fig1.canvas.draw()
    fig1.canvas.flush_events()

interactive_modes = interactive(plot_modes,
                               bbar=FloatSlider(value=4.0,min=min(modes.Bbars), max=max(modes.Bbars),step=0.05, continuous_update=True),
                               K=FloatSlider(value=1.0,min=0, max=1e1, continuous_update=True),
                               tau_v=FloatSlider(value=30.0,min=0.0, max=1e2, step=1.0, continuous_update=True),
                               tau_m=FloatSlider(value=1,min=0, max=10, step=0.01, continuous_update=True),
                               r=FloatSlider(value=1.0,min=1e-2, max=1e2, step=0.01, continuous_update=True),
                               xstar=FloatSlider(value=0.5,min=min(modes.Tbars)/max(modes.Bbars),max=max(modes.Tbars)/min(modes.Bbars),step=0.01,continuous_update=True),
                               Dm=FloatSlider(value=0.0,min=0.0, max=2, step=0.01, continuous_update=True),
                               alpha=FloatSlider(value=0.0,min=0.0, max=10, step=0.01, continuous_update=True),
                               k=fixed(k)
)

#dummy plot
plt.ioff()
plt.clf()
fig1,ax1 =plt.subplots()

ax1.set_xlim(0,1)
ax1.set_ylim(-1,1)
ax1.set_xlabel(r"$k$")
ax1.set_ylabel(r"$\omega$")
p0, = ax1.plot(k**2,np.zeros_like(k),label=" ")
p1, = ax1.plot(k**2,np.zeros_like(k),label=" ")
p2, = ax1.plot(k**2,np.zeros_like(k),label=" ")
lgd = ax1.legend()

controls = VBox(interactive_modes.children[:-1], layout = Layout(flex_flow='column wrap'))
display(HBox([controls, fig1.canvas], layout = Layout(align_items='center')))
fig1.canvas.layout.min_height = '800px'
fig1.canvas.toolbar_position="top"
fig1.canvas.toolbar_visible=False

```

# Nullclines (and dynamics) of a single junction
Let's now see how the nullclines are affected by the terms.
The $\lambda$ nullcine is modified whereas the $m$ one isn't  :
\begin{align}
0 &=  - \beta m -   \left( K+\tau_{v}^{-1}\left(1+\alpha m_\lambda \right) \right) \lambda + F \nonumber \\
0 &= 1+ m f(T) \nonumber
\end{align}
We end up with the final form :

\begin{align}
\lambda_{\lambda}(m) &=  - \frac{\beta}{K+\tau_{v}^{-1}\left(1+\alpha m_\lambda \right)} m  + \frac{F}{K+\tau_{v}^{-1}\left(1+\alpha m_\lambda \right)}\label{eq:nullcline_lamba2} \\
\lambda_m(m) &= \frac{1}{K} \left( - \frac{\log( \frac{1}{r\,m} -1)}{k_0} - \beta m + T^{*} \right)  \label{eq:nullcline_m2}
\end{align}

```python
#capturing widget
out = widgets.Output(layout={'border': '1px solid black'})
#@out.capture(clear_output=True) #to put just before the function definition to catch the return/errors
```

```python
class nullclines_0d_remodel() :
    def __init__(self) :
        self.ll = lambda  m,beta,K,tau_v,r,tstar,alpha,Dm,F,k0 :  -beta*m/((K+tau_v**(-1))*(1+alpha*m)) + F/(K+tau_v**(-1)*(1+alpha*m))
        self.lm = lambda  m,beta,K,tau_v,r,tstar,alpha,Dm,F,k0 :  1/K* (-np.log(1/(r*m)-1)/k0 - beta*m + tstar)

        self.k0=4.0 #set k0 to an arbitrary value
        self.ms = np.linspace(0,1,100)
        debug_view = widgets.Output(layout={'border': '1px solid black'})

        self.interactive_nullclines = interactive(self.plot_nullclines,
                                       beta=FloatSlider(value=1.0,min=0, max=10,step=0.01, continuous_update=True),
                                       K=FloatSlider(value=1.0,min=0, max=1e1,step=0.01, continuous_update=True),
                                       F=FloatSlider(value=1.0,min=0, max=10,step=0.01, continuous_update=True),
                                       tau_v=FloatSlider(value=30,min=0, max=1e2, step=0.01, continuous_update=True),
                                       r=FloatSlider(value=1.0,min=1e-2, max=1e2, step=0.01, continuous_update=True),
                                       tstar=FloatSlider(value=0.5,min=0, max=10,step=0.01, continuous_update=True),
                                       Dm=FloatSlider(value=0,min=0, max=2, step=0.01, continuous_update=True),
                                       alpha=FloatSlider(value=0,min=0, max=10, step=0.01, continuous_update=True),
                                       m=fixed(self.ms)
                                      )

        #plt.ioff()
        #plt.clf()

        self.fig2,self.ax = plt.subplots()
        self.ax.set_xlim(0,1)
        self.ax.set_ylim(-1,1)
        self.p0, = self.ax.plot(self.ms,np.zeros_like(self.ms),label=r"$\lambda$ nullcline ")
        self.p1, = self.ax.plot(self.ms,np.zeros_like(self.ms),label=r"$m$ nullcline")
        self.lgd = self.ax.legend()
        #self.interactive_nullclines
        self.controls = VBox(self.interactive_nullclines.children[:-1], layout = Layout(flex_flow='column wrap'))

        display(HBox([self.controls, self.fig2.canvas], layout = Layout(align_items='center')))
        self.fig2.canvas.layout.min_height = '800px'
        self.fig2.canvas.toolbar_position="top"
        self.fig2.canvas.toolbar_visible=False

    def plot_nullclines(self,m,beta,F,K,tau_v,r,tstar,alpha,Dm) :
        self.p0.set_ydata(self.ll(m,beta,K,tau_v,r,tstar,alpha,Dm,F,self.k0))
        self.p1.set_ydata(self.lm(m,beta,K,tau_v,r,tstar,alpha,Dm,F,self.k0))
        self.fig2.canvas.draw()
        self.fig2.canvas.flush_events()
        print(self.lm(m,beta,K,tau_v,r,tstar,alpha,Dm,F,self.k0))

nc = nullclines_0d_remodel()

```

# Dynamics in adimensional form
Since we are working with adimensional units we need to write the dynamics of the system in these units as well.
We end up with the following system :
\begin{align}
  \frac{d\overline{m}}{dt} &= \tau_m^{-1} r \left( 1 - \overline{m} \left( 1+ e^{-\chi \left(\overline{m} + \frac{K}{\beta}\lambda - x^{*}\right)} \right) \right) \\
                             \frac{d\lambda}{dt} &= -K \lambda -\frac{\beta}{r}\overline{m}-\tau_v^{-1} \left( 1+\alpha \frac{\overline{m}}{r} \right)
\end{align}

<!-- nb: we absorb $\tau_m$ by rescaling time (and therefore K,$\beta$,etc.) -->

```python
# import numpy as np

# from numpy import linalg as LA
# import math
# from numpy.lib import scimath

# import bz2
# import pickle
# import os
# import sys

# %matplotlib widget
# import matplotlib
# import matplotlib.pyplot as plt
# matplotlib.rcParams['figure.dpi']= 200 #sets ploted image dpi (for the inline backend)
# matplotlib.rcParams['savefig.dpi'] = 200 #dpi for the notebook backend

# from ipywidgets import interactive,fixed,FloatSlider,HBox, Layout,VBox
# import ipywidgets as widgets

#Add the actual dynamics
ll = lambda  mbar,bbar,xstar,K,tau_v,r,alpha,F :  -bbar*mbar/((K+tau_v**(-1))*(1+alpha*mbar/r)) + F/(K+tau_v**(-1)*(1+alpha*mbar/r))
lm = lambda  mbar,bbar,xstar,K,tau_v,r,alpha,F :  1/K* (-np.log(1/mbar-1) - bbar*mbar + xstar*bbar)

def plot_nullclines(bbar,xstar,K,tau_v,r,alpha,F) :
    global p0,p1,fig,ax,lgd,mbars
    p0.set_ydata(ll(mbars,bbar,xstar,K,tau_v,r,alpha,F))
    p1.set_ydata(lm(mbars,bbar,xstar,K,tau_v,r,alpha,F))
    fig.canvas.draw()
    fig.canvas.flush_events()

#------------- integration
from scipy.integrate import odeint

def integration_domain(dt,tmax) :
    global tdom
    tdom = np.arange(0,tmax,dt)

def dmdt(lam,mb,beta,K,bbar,xstar,tau_v,r,alpha,F) :
    tb =  mb + K*r/beta*lam
    return r*(1-mb*(1+np.exp(-bbar*(tb-xstar))))

def dlamdt(lam,mb,beta,K,bbar,xstar,tau_v,r,alpha,F) :
    return -K*lam - beta*mb/r - tau_v**(-1)*(1+alpha*mb/r) + F

def sys(y,t,beta,bbar,xstar,K,tau_v,r,alpha,F):
    lam,m = y
    return [dlamdt(lam,m,beta,bbar,xstar,K,tau_v,r,alpha,F),dmdt(lam,m,beta,bbar,xstar,K,tau_v,r,alpha,F)]

def simulate(b):
    global fig,ax,lgd,tdom,lamt,mt
    #need to retrieve variables
    beta = slider_beta.value
    bbar = slider_bbar.value
    xstar = slider_xstar.value
    K = slider_K.value
    tau_v = slider_tau_v.value
    r = slider_r.value
    alpha = slider_alpha.value
    F = slider_F.value
    y0 = [slider_lam0.value,slider_m0.value]
    dt=slider_dt.value
    lamt,mt =odeint(sys, y0, tdom,args=(beta,bbar,xstar,K,tau_v,r,alpha,F)).T #transpose the result
    y = np.zeros((len(tdom),2))
    y[0] = y0
    for i,time in enumerate(tdom[1:],start=1) :
        y[i] = y[i-1]+dt*np.array(sys(y[i-1],time,beta,bbar,xstar,K,tau_v,r,alpha,F))
    lamt,mt = y.T
    p2.set_xdata(mt)
    p2.set_ydata(lamt)
    ax2.cla()
    ax2.plot(tdom,mt,label="m(t)")
    ax2.plot(tdom,lamt,label=r"$\lambda(t)$")
    ax2.legend(loc="upper center",prop={'size': 5})
    fig.canvas.draw()
    fig.canvas.flush_events()

#-------- sliders,buttons

slider_beta=FloatSlider(value=1.0,min=0, max=10,step=0.01, continuous_update=False,description="beta")
slider_bbar=FloatSlider(value=4.0,min=0, max=10,step=0.01, continuous_update=False,description="bbar")
slider_xstar=FloatSlider(value=0.5,min=0, max=1,step=0.01, continuous_update=False,description="xstar")
slider_K=FloatSlider(value=1.0,min=0, max=1e1,step=0.01, continuous_update=False,description="K")
slider_tau_v=FloatSlider(value=30,min=0, max=1e2, step=0.01, continuous_update=False,description="tau_v")
slider_r=FloatSlider(value=1.0,min=1e-2, max=1e2, step=0.01, continuous_update=False,description="r")
slider_alpha=FloatSlider(value=0,min=0, max=10, step=0.01, continuous_update=False,description="alpha")
slider_F=FloatSlider(value=2.0,min=0, max=10, step=0.01, continuous_update=False,description="F")
slider_m0 = FloatSlider(value=0.5,min=0, max=1, step=0.01, continuous_update=False,description="m_0")
slider_lam0 = FloatSlider(value=0.0,min=0, max=1, step=0.01, continuous_update=False,description="lam_0")

interactive_nullclines = widgets.interactive_output(plot_nullclines,{ 'bbar':slider_bbar,
                                                      'xstar':slider_xstar,
                                                      'K':slider_K,
                                                      'tau_v':slider_tau_v,
                                                      'r':slider_r,
                                                      'alpha':slider_alpha,
                                                      'F':slider_F,
                                                     }
                                    )

slider_dt = widgets.FloatLogSlider(
    value=1e-2,
    base=10,
    min=-5, # max exponent of base
    max=1, # min exponent of base
    step=1, # exponent step
    description='dt(log scale)'
)

slider_tmax = widgets.FloatLogSlider(
    value=1e2,
    base=10,
    min=2, # max exponent of base
    max=6, # min exponent of base
    step=1, # exponent step
    description='tmax(log scale)'
)

widgets.interactive_output(integration_domain,{"dt":slider_dt,"tmax":slider_tmax})

button = widgets.Button(description="Simulate ")
button.on_click(simulate)

#-------- parameters
beta=1.0
bbar=4.0
xstar=0.5
K=1.0
tau_v=30
r=1.0
alpha=0
F=2.0

#---- integration and nullclines
#y0 = [0.5,0.0]
mbars = np.linspace(0,0.99,100) #nullclines range

#-------- plot the interface,including the figure
controls_integ = VBox([button,slider_dt,slider_tmax,slider_lam0,slider_m0],layout = Layout(flex_flow='column wrap',border="solid"))
controls = VBox([controls_integ,slider_beta, slider_bbar, slider_xstar,slider_K,slider_tau_v,slider_r,slider_alpha,slider_F],layout = Layout(flex_flow='column wrap'))
#plt.ioff()
#plt.clf()
fig=plt.figure()
ax=fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax.set_xlim(0,1)
ax.set_ylim(-1,1)
ax.set_xlabel(r"$m$")
ax.set_ylabel(r"$\lambda$")

p0, = ax.plot(mbars,ll(mbars,bbar,xstar,K,tau_v,r,alpha,F),label=r"$\lambda$ nullcline ")
p1, = ax.plot(mbars,lm(mbars,bbar,xstar,K,tau_v,r,alpha,F),label=r"$m$ nullcline")
p2, = ax.plot(np.zeros_like(tdom),np.zeros_like(tdom),'r',label="simulation")
lgd = ax.legend(loc="upper center",prop={'size': 5})
p3, = ax2.plot(np.zeros_like(tdom),np.zeros_like(tdom),label="m(t)")
p4, = ax2.plot(np.zeros_like(tdom),np.zeros_like(tdom),label=r"$\lambda(t)$")

display(HBox([controls, fig.canvas], layout = Layout(align_items='center')))
# fig.canvas.layout.min_height = '800px'
fig.canvas.toolbar_position="top"
#fig.canvas.toolbar_visible=False

```

# Dynamics in the original units

```python
#the same in original units
import numpy as np
from numpy import linalg as LA
import math
from numpy.lib import scimath

import bz2
import pickle
import os
import sys

%matplotlib widget
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['figure.dpi']= 150 #sets ploted image dpi (for the inline backend)
matplotlib.rcParams['savefig.dpi'] = 150 #dpi for the notebook backend

from ipywidgets import interactive,fixed,FloatSlider,HBox, Layout,VBox
import ipywidgets as widgets
from scipy.integrate import odeint

#Add the actual dynamics
ll = lambda  m,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F :  (-beta*m+F)/(K+tau_v**(-1)*(1+alpha*m))
lm = lambda  m,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F:  1/K* (-np.log(1/(r*m)-1)/k0 - beta*m + Tstar)

def plot_nullclines(beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F) :
    global p0,p1,fig,ax,lgd,ms
    p0.set_ydata(ll(ms,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F))
    p1.set_ydata(lm(ms,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F))
    fig.canvas.draw()
    fig.canvas.flush_events()

#------------- integration

def integration_domain(dt,tmax) :
    global tdom
    tdom = np.arange(0,tmax,dt)

def dydt(y,t,beta,K,k0,Tstar,tau_m,tau_v,r,alpha,F):
    lam,m = y
    T = beta*m + K*lam
    dlamdt= -T -lam*(1+alpha*m)/tau_v + F
    dmdt = 1/tau_m-m/tau_m*r*(1+np.exp(-k0*(T-Tstar)))
    return [dlamdt,dmdt]

def euler(func,y0,tdom,args):
    dt = tdom[1]
    y = np.zeros((len(tdom),2))
    y[0] = y0
    for i,time in enumerate(tdom[:-1]):
        y[i+1] = y[i]+dt*np.array(func(y[i],time,*args))
    lamt,mt = y.T
    return lamt,mt

def simulate(xxxx):
    beta = slider_beta.value
    Tstar = slider_Tstar.value
    k0 = slider_k0.value
    K = slider_K.value
    tau_m = slider_tau_m.value
    tau_v = slider_tau_v.value
    r = slider_r.value
    alpha = slider_alpha.value
    F = slider_F.value
    y0 = [slider_lam0.value,slider_m0.value]

    lamt_scp,mt_scp = odeint(dydt, y0, tdom,args=(beta,K,k0,Tstar,tau_m,tau_v,r,alpha,F)).T #transpose the result
    p2.set_data(mt_scp,lamt_scp)

    ax2.clear()
    ax2_twin.clear()

    ax2.plot(tdom,mt_scp,'r',label='m(t)')
    ax2_twin.plot(tdom,lamt_scp,'b',label=r'$\lambda(t)$')

    ax2.legend(loc='upper center',prop={'size': 5})
    ax2_twin.legend(loc='upper right',prop={'size':5})
    ax2.set_xlabel('t')
    ax2.set_ylabel('m',color='red')
    ax2.tick_params(axis='y', colors='red')
    ax2_twin.set_ylabel(r'$\lambda$',color='blue')
    ax2_twin.tick_params(axis='y', colors='blue')

    fig.canvas.draw()
    fig.canvas.flush_events()

#-------- parameters beta,K,k0,Tstar,tau_m,tau_v,r,alpha,F
beta=2.3
K=1.0
k0=4.0
Tstar=1.15
tau_m=2.0
tau_v=20
r=1.0
alpha=10.0
F=1.15

#-------- sliders,buttons

slider_beta=FloatSlider(value=beta,min=0, max=10,step=0.01, continuous_update=False,description='beta')
slider_k0=FloatSlider(value=k0,min=0, max=10,step=0.01, continuous_update=False,description='k0')
slider_Tstar=FloatSlider(value=Tstar,min=0, max=10,step=0.01, continuous_update=False,description='Tstar')
slider_K=FloatSlider(value=K,min=0, max=1e1,step=0.01, continuous_update=False,description='K')
slider_tau_m=FloatSlider(value=tau_m,min=0, max=1e1,step=0.01, continuous_update=False,description='tau_m')
slider_tau_v=FloatSlider(value=tau_v,min=0, max=1e4, step=1.0, continuous_update=False,description='tau_v')
slider_r=FloatSlider(value=r,min=1e-2, max=1e2, step=0.01, continuous_update=False,description='r')
slider_alpha=FloatSlider(value=alpha,min=0.0, max=10, step=0.01, continuous_update=False,description='alpha')
slider_F=FloatSlider(value=F,min=0, max=10, step=0.01, continuous_update=False,description='F')
slider_m0 = FloatSlider(value=0.55,min=0, max=1, step=0.01, continuous_update=False,description='m_0')
slider_lam0 = FloatSlider(value=0.0,min=0, max=1, step=0.01, continuous_update=False,description='lam_0')

interactive_nullclines = widgets.interactive_output(plot_nullclines,{ 'k0':slider_k0,
                                                                     'beta':slider_beta,
                                                                     'Tstar':slider_Tstar,
                                                                     'K':slider_K,
                                                                     'tau_m':slider_tau_m,
                                                                     'tau_v':slider_tau_v,
                                                                     'r':slider_r,
                                                                     'alpha':slider_alpha,
                                                                     'F':slider_F,
                                                                     }
                                                    )

slider_dt = widgets.FloatLogSlider(
    value=1e-2,
    base=10,
    min=-5, # max exponent of base
    max=1, # min exponent of base
    step=1, # exponent step
    description='dt(log scale)'
)

slider_tmax = widgets.FloatLogSlider(
    value=5e1,
    base=10,
    min=-1, # max exponent of base
    max=6, # min exponent of base
    step=1, # exponent step
    description='tmax(log scale)'
)

widgets.interactive_output(integration_domain,{'dt':slider_dt,'tmax':slider_tmax})

button = widgets.Button(description='Simulate')
button.on_click(simulate)

#---- integration and nullclines
ms = np.linspace(0,0.99,100) #nullclines range

#-------- plot the interface,including the figure
controls_integ = VBox([button,slider_dt,slider_tmax,slider_lam0,slider_m0],layout = Layout(flex_flow='column wrap',border='solid'))
controls = VBox([controls_integ,slider_beta, slider_K, slider_k0,slider_Tstar,slider_tau_m,slider_tau_v,slider_r,slider_alpha,slider_F],layout = Layout(flex_flow='column wrap'))
plt.ioff()
plt.clf()
fig=plt.figure()
ax=fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax2_twin = ax2.twinx()

ax.set_xlim(0,1)
ax.set_ylim(-1,1)
ax.set_xlabel(r'$m$')
ax.set_ylabel(r'$\lambda$')

p0, = ax.plot(ms,ll(ms,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F),label=r'$\lambda$ nullcline')
p1, = ax.plot(ms,lm(ms,beta,Tstar,k0,K,tau_m,tau_v,r,alpha,F),label=r'$m$ nullcline')
p2, = ax.plot(np.zeros_like(tdom),np.zeros_like(tdom),'r',label='simulation')
lgd = ax.legend(loc='upper center',prop={'size': 5})
p3, = ax2.plot(np.zeros_like(tdom),np.zeros_like(tdom),label='m(t)')
p4, = ax2.plot(np.zeros_like(tdom),np.zeros_like(tdom),label=r'$\lambda(t)$')

display(HBox([controls, fig.canvas], layout = Layout(align_items='center')))
fig.canvas.layout.min_height = '1000px'
fig.canvas.toolbar_position='top'
#fig.canvas.toolbar_visible=False

```

```python

```


## PolynomialFeatures使用例
- Boston Housingデータセットを例として使用
- Boston Housingデータセットについては下記サイトを参考にした。
 - 「Boston Housing Prices - Evaluation & Validation」https://www.kaggle.com/samratp/boston-housing-prices-evaluation-validation
 - 「Linear Regression on Boston Housing Dataset」https://towardsdatascience.com/linear-regression-on-boston-housing-dataset-f409b7e4a155
 - 「機械学習とBoston Housing Data（3）」https://kiidax.wordpress.com/2016/09/14/機械学習とboston-housing-data（3）/

## 前処理
### ライブラリインポート

```python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import ElasticNet
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_boston
```

### データセット読み込み

```python
boston = load_boston()
# sklearn.utils.BunchからDataFrame形式へ変換
df_prices = pd.DataFrame(boston.target, columns=["MEDV"])
df_features = pd.DataFrame(boston.data, columns=boston.feature_names)

df_data = pd.concat([df_prices,df_features],axis=1)

# 価格が50以上の場合は50になってしまっているようなので、データを削除
# (「Boston Housing Prices - Evaluation & Validation」https://www.kaggle.com/samratp/boston-housing-prices-evaluation-validation)
df_data = df_data[df_data["MEDV"]<50]
```

### 学習データ、テストデータに振り分け

```python
df_features_ = df_data.drop(["MEDV"],axis=1)
df_prices = df_data["MEDV"]
X_train, X_test, y_train, y_test = train_test_split(df_features_, df_prices, test_size = 0.2, random_state=5)
```

### グリッドサーチ
- 参考「GridSearchCV(scikit-learn)によるチューニング」http://starpentagon.net/analytics/scikit_learn_grid_search_cv/
- パイプライン中の流れ
 - StandardScaler()で標準化する
 - PolynomialFeatures()で多項式カラムを作る
 - ElasticNet()で回帰させる
- グリッドサーチにより、最もスコアが高くなるハイパーパラメータを探索する

```python
alpha_params = np.logspace(-3, 3, 7)
l1_ratio_params = np.arange(0.1, 1.0, 0.1)

steps = [
    ('ss', StandardScaler()),
    ('pf', PolynomialFeatures()),
    ('en', ElasticNet())
]
pipeline = Pipeline(steps=steps)

paramters = {
    'pf__degree': [1,2,3],
    'en__alpha': alpha_params,
    'en__l1_ratio': l1_ratio_params,
    'en__fit_intercept': [False]
}

model_CV = GridSearchCV(
    estimator = pipeline,
    param_grid = paramters,
    cv = 5,
    n_jobs = -1,
)

model_CV.fit(X_train, y_train)

best_param = model_CV.best_params_
best_estimator = model_CV.best_estimator_

pred_train = best_estimator.predict(X_train)
r2score_train = r2_score(y_train, pred_train)
rmse_train = np.sqrt(mean_squared_error(y_train, pred_train))

pred_test = best_estimator.predict(X_test)
r2score_test = r2_score(y_test, pred_test)
rmse_test = np.sqrt(mean_squared_error(y_test, pred_test))

print("結果")
print('RMSE (train) : {:.3f}'.format(rmse_train))
print('RMSE (test) : {:.3f}'.format(rmse_test))
print('R2 score (train): %.3f' % r2score_train)
print('R2 score (test) : %.3f' % r2score_test)
print('clf.best_params_', best_param)
```

    結果
    RMSE (train) : 2.585
    RMSE (test) : 2.798
    R2 score (train): 0.889
    R2 score (test) : 0.885
    clf.best_params_ {'en__alpha': 0.1, 'en__fit_intercept': False, 'en__l1_ratio': 0.9, 'pf__degree': 2}

    /Users/suzuki/anaconda3/lib/python3.7/site-packages/sklearn/model_selection/_search.py:841: DeprecationWarning: The default of the `iid` parameter will change from True to False in version 0.22 and will be removed in 0.24. This will change numeric results when test-set sizes are unequal.
      DeprecationWarning)

### カラム名に対応した係数を出力する
#### 下準備
- 拙ブログ「sklearn.preprocessing.PolynomialFeatures の仕様を調査する」https://company-rapper.hatenablog.jp/entry/2019/08/01/230829より

```python
# 1番目からn番目までの素数をnp.arrayで返す関数
import sympy
def primes(n=0):
    ret_primes = list()
    for i in np.arange(n):
        ret_primes.append(sympy.prime(i+1))
    return ret_primes

# コラム名リストからコラムに対してユニークな素数が割り付けられたデータフレームを返す関数
def generate_df_prime_from_columns(columns_original = np.array(["a","b","c"])):
    data_original = np.array(primes(len(columns_original)))
    return pd.DataFrame(data=data_original[np.newaxis,:],columns=columns_original,index=["original"])

# PolynomialFeatures()の出力に対応したカラムを返す関数
def get_columns_for_PolynomialFeatures(poly=PolynomialFeatures(2),columns_from=["a","b","c"],power=False):
    df_from = generate_df_prime_from_columns(columns_from)
    columns_from = df_from.columns
    data_from = df_from.values
    data_poly = poly.fit_transform(df_from)
    # columnsをもう一度作り直す
    columns_poly = list()
    for i, data_poly_0 in enumerate(data_poly[0]):
        if (data_poly_0 == 1):
            columns_poly.append("bias")
        else:
            prime_dict=sympy.factorint(data_poly_0)
            keys = list(prime_dict.keys())
            columns_str = ""
            if power:
                # 累乗で書ける部分は累乗で書く(例:a^2)
                for j, key in enumerate(keys):
                    columns_str += columns_from[list(data_from[0]).index(key)]
                    if prime_dict[key] > 1:
                        columns_str += "^" + str(prime_dict[key])
                    if (j < len(keys)-1):
                        columns_str += "×"
            else:
                # 単純に×で項目をつなげていく(例:a×a×b)
                for j, key in enumerate(keys):
                    for k in np.arange(prime_dict[key]):
                        columns_str += columns_from[list(data_from[0]).index(key)]
                        if (j < len(keys)-1) | (k < prime_dict[key]-1):
                            columns_str += "×"
            columns_poly.append(columns_str)
    return columns_poly
```

#### 係数が大きい順番に出力

```python
# 係数を出力
best_estimator.named_steps["en"].coef_

columns_for_coef_ = get_columns_for_PolynomialFeatures(poly=PolynomialFeatures(best_estimator.named_steps["pf"].degree),
                                                       columns_from=df_features_.columns)
df_coef = pd.DataFrame(data=best_estimator.named_steps["en"].coef_,index=columns_for_coef_,columns=["coef"])
df_coef["abs coef"] = abs(df_coef["coef"])

# 係数の絶対値が0.1以上のものを絶対値の降順で表示
display(df_coef[df_coef["abs coef"]>0.1].sort_values('abs coef', ascending=False))
```

      coef
      abs coef

      bias
      17.580475
      17.580475

      RM
      2.504036
      2.504036

      LSTAT
      -2.486765
      2.486765

      CRIM
      -2.045977
      2.045977

      TAX
      -0.950377
      0.950377

      INDUS
      -0.923279
      0.923279

      RAD×TAX
      0.919711
      0.919711

      AGE
      -0.775039
      0.775039

      DIS
      -0.767196
      0.767196

      TAX×LSTAT
      -0.734776
      0.734776

      AGE×B
      -0.681036
      0.681036

      TAX×PTRATIO
      0.595062
      0.595062

      B
      0.594885
      0.594885

      PTRATIO
      -0.591576
      0.591576

      RM×LSTAT
      -0.575150
      0.575150

      INDUS×INDUS
      0.559900
      0.559900

      RM×RM
      0.518078
      0.518078

      RM×TAX
      -0.516195
      0.516195

      ZN
      -0.486938
      0.486938

      CHAS×RM
      -0.464449
      0.464449

      NOX
      -0.454374
      0.454374

      ZN×PTRATIO
      0.446274
      0.446274

      NOX×RM
      -0.438023
      0.438023

      TAX×TAX
      0.432392
      0.432392

      RM×PTRATIO
      -0.426034
      0.426034

      NOX×DIS
      0.422305
      0.422305

      CHAS×DIS
      0.409789
      0.409789

      PTRATIO×PTRATIO
      0.392427
      0.392427

      AGE×AGE
      0.374468
      0.374468

      RM×B
      0.212104
      0.212104

      CHAS×NOX
      -0.204649
      0.204649

      CHAS×CHAS
      0.170832
      0.170832

      RM×AGE
      -0.161122
      0.161122

      ZN×ZN
      0.154256
      0.154256

      AGE×DIS
      0.151477
      0.151477

      AGE×LSTAT
      -0.135885
      0.135885

      B×B
      -0.129573
      0.129573

      DIS×DIS
      0.120519
      0.120519

      CRIM×CRIM
      0.118679
      0.118679

      LSTAT×LSTAT
      0.114893
      0.114893

      ZN×RM
      0.110348
      0.110348

      CRIM×B
      -0.102504
      0.102504

```python

```


# Start-to-Finish Example: Evolving Maxwell's Equations with Toriodal Dipole Field Initial Data, in Flat Spacetime and Curvilinear Coordinates

## Following the work of [Knapp, Walker & Baumgarte (2002)](https://arxiv.org/abs/gr-qc/0201051), we numerically implement the second version of Maxwell’s equations - System II (BSSN - like) in curvilinear coordinates.

## Author: Terrence Pierre Jacques and Zachariah Etienne
### Formatting improvements courtesy Brandon Clark

**Notebook Status:**  Validated

**Validation Notes:** This module has been validated to exhibit convergence to the exact solution for the electric field $E^i$ and vector potential $A^i$ at the expected order, *after a short numerical evolution of the initial data* (see [plots at bottom](#convergence)).

### NRPy+ Source Code for this module:
* [Maxwell/InitialData.py](../edit/Maxwell/InitialData.py); [\[**tutorial**\]](Tutorial-VacuumMaxwell_InitialData.ipynb): Purely toriodal dipole field initial data; sets all electromagnetic variables in the Cartesian basis
* [Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear.py](../edit/Maxwell/VacuumMaxwell_Flat_Evol_Cartesian.py); [\[**tutorial**\]](Tutorial-Tutorial-VacuumMaxwell_Curvilinear_RHS-Rescaling.ipynb): Generates the right-hand sides for Maxwell's equations in curvilinear coordinates

## Introduction:
Here we use NRPy+ to generate the C source code necessary to set up initial data for a purely toriodal dipole field, as defined in [Knapp, Walker & Baumgarte (2002)](https://arxiv.org/abs/gr-qc/0201051). We then evolve the RHSs of Maxwell's equations using the [Method of Lines](https://reference.wolfram.com/language/tutorial/NDSolveMethodOfLines.html) time integration based on an [explicit Runge-Kutta fourth-order scheme](https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods) (RK4 is chosen below, but multiple options exist).

The entire algorithm is outlined as follows, with links to the relevant NRPy+ tutorial notebooks listed at each step:

1. Allocate memory for gridfunctions, including temporary storage for the Method of Lines time integration
    * [**NRPy+ tutorial on Method of Lines algorithm**](Tutorial-Method_of_Lines-C_Code_Generation.ipynb).
1. Set gridfunction values to initial data
    * [**NRPy+ tutorial on purely toriodal dipole field initial data**](Tutorial-VacuumMaxwell_InitialData.ipynb)
1. Next, integrate the initial data forward in time using the Method of Lines coupled to a Runge-Kutta explicit timestepping algorithm:
    1. At the start of each iteration in time, output the divergence constraint violation
        * [**NRPy+ tutorial on Maxwell's equations constraints**](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb)
    1. At each RK time substep, do the following:
        1. Evaluate RHS expressions
            * [**NRPy+ tutorial on Maxwell's equations right-hand sides**](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb)
        1. Apply Sommerfeld boundary conditions in curvilinear coordinates
            * [**NRPy+ tutorial on setting up Sommerfeld boundary conditions**](Tutorial-SommerfeldBoundaryCondition.ipynb)
1. Repeat above steps at two numerical resolutions to confirm convergence to zero.

# Table of Contents
$$\label{toc}$$

This notebook is organized as follows

1. [Step 1](#initializenrpy): Set core NRPy+ parameters for numerical grids and reference metric
    1. [Step 1.a](#cfl) Output needed C code for finding the minimum proper distance between grid points, needed for [CFL](https://en.wikipedia.org/w/index.php?title=Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition&oldid=806430673)-limited timestep
1. [Step 2](#mw): Generate symbolic expressions and output C code for evolving Maxwell's equations
    1. [Step 2.a](#mwid): Generate symbolic expressions for toroidal dipole field initial data
    1. [Step 2.b](#mwevol): Generate symbolic expressions for evolution equations
    1. [Step 2.c](#mwcon): Generate symbolic expressions for constraint equations
    1. [Step 2.d](#mwcart): Generate symbolic expressions for converting $A^i$ and $E^i$ to the Cartesian basis
    1. [Step 2.e](#mwccode): Output C codes for initial data and evolution equations
    1. [Step 2.f](#mwccode_con): Output C code for constraint equations
    1. [Step 2.g](#mwccode_cart): Output C code for converting $A^i$ and $E^i$ to Cartesian coordinates
    1. [Step 2.h](#mwccode_xzloop): Output C code for printing 2D data
    1. [Step 2.i](#cparams_rfm_and_domainsize): Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h`
1. [Step 3](#bc_functs): Set up Sommerfeld boundary condition functions
1. [Step 4](#mainc): `Maxwell_Playground.c`: The Main C Code
1. [Step 5](#compileexec): Compile generated C codes & perform simulation of the propagating toriodal electromagnetic field
1. [Step 6](#visualize): Visualize the output!
    1. [Step 6.a](#installdownload): Install `scipy` and download `ffmpeg` if they are not yet installed/downloaded
    1. [Step 6.b](#genimages): Generate images for visualization animation
    1. [Step 6.c](#genvideo): Generate visualization animation
1. [Step 7](#convergence): Plot the numerical error, and confirm that it converges to zero with increasing numerical resolution (sampling)
1. [Step 8](#div_e): Comparison of Divergence Constrain Violation
1. [Step 9](#latex_pdf_output): Output this notebook to $\LaTeX$-formatted PDF file

# Step 1: Set core NRPy+ parameters for numerical grids and reference metric \[Back to [top](#toc)\]
$$\label{initializenrpy}$$

```python
# Step P1: Import needed NRPy+ core modules:
from outputC import outputC,lhrh,outCfunction # NRPy+: Core C code output module
import finite_difference as fin  # NRPy+: Finite difference C code generation module
import NRPy_param_funcs as par   # NRPy+: Parameter interface
import grid as gri               # NRPy+: Functions having to do with numerical grids
import indexedexp as ixp         # NRPy+: Symbolic indexed expression (e.g., tensors, vectors, etc.) support
import reference_metric as rfm   # NRPy+: Reference metric support
import cmdline_helper as cmd     # NRPy+: Multi-platform Python command-line interface
import shutil, os, sys           # Standard Python modules for multiplatform OS-level functions, benchmarking

# Step P2: Create C code output directory:
Ccodesdir = os.path.join("MaxwellEvolCurvi_Playground_Ccodes/")
# First remove C code output directory if it exists
# Courtesy https://stackoverflow.com/questions/303200/how-do-i-remove-delete-a-folder-that-is-not-empty
shutil.rmtree(Ccodesdir, ignore_errors=True)
# Then create a fresh directory
cmd.mkdir(Ccodesdir)

# Step P3: Create executable output directory:
outdir = os.path.join(Ccodesdir,"output/")
cmd.mkdir(outdir)

# Step 1: Set the spatial dimension parameter
#         to three (BSSN is a 3+1 decomposition
#         of Einstein's equations), and then read
#         the parameter as DIM.
par.set_parval_from_str("grid::DIM",3)
DIM = par.parval_from_str("grid::DIM")

# Step 2: Set some core parameters, including CoordSystem MoL BoundaryCondition timestepping algorithm,
#                                 FD order, floating point precision, and CFL factor:
# Choices are: Spherical, SinhSpherical, SinhSphericalv2, Cylindrical, SinhCylindrical,
#              SymTP, SinhSymTP
CoordSystem     = "SinhCylindrical"

# Step  2.a: Set boundary conditions
# Current choices are QuadraticExtrapolation (quadratic polynomial extrapolation) or Sommerfeld
BoundaryCondition = "Sommerfeld"

# Step 2.b: Set defaults for Coordinate system parameters.
#           These are perhaps the most commonly adjusted parameters,
#           so we enable modifications at this high level.

# domain_size sets the default value for:
#   * Spherical's params.RMAX
#   * SinhSpherical*'s params.AMAX
#   * Cartesians*'s -params.{x,y,z}min & .{x,y,z}max
#   * Cylindrical's -params.ZMIN & .{Z,RHO}MAX
#   * SinhCylindrical's params.AMPL{RHO,Z}
#   * *SymTP's params.AMAX
domain_size     = 10.0 # Needed for all coordinate systems.

# sinh_width sets the default value for:
#   * SinhSpherical's params.SINHW
#   * SinhCylindrical's params.SINHW{RHO,Z}
#   * SinhSymTP's params.SINHWAA
sinh_width      = 0.4 # If Sinh* coordinates chosen

# sinhv2_const_dr sets the default value for:
#   * SinhSphericalv2's params.const_dr
#   * SinhCylindricalv2's params.const_d{rho,z}
sinhv2_const_dr = 0.05 # If Sinh*v2 coordinates chosen

# SymTP_bScale sets the default value for:
#   * SinhSymTP's params.bScale
SymTP_bScale    = 0.5 # If SymTP chosen

# Step 2.c: Set the order of spatial and temporal derivatives;
#           the core data type, and the CFL factor.
# RK_method choices include: Euler, "RK2 Heun", "RK2 MP", "RK2 Ralston", RK3, "RK3 Heun", "RK3 Ralston",
#              SSPRK3, RK4, DP5, DP5alt, CK5, DP6, L6, DP8
RK_method = "RK4"
FD_order  = 4        # Finite difference order: even numbers only, starting with 2. 12 is generally unstable
REAL      = "double" # Best to use double here.
default_CFL_FACTOR= 0.5      # (GETS OVERWRITTEN WHEN EXECUTED.) In pure axisymmetry (symmetry_axes = 2 below) 1.0 works fine. Otherwise 0.5 or lower.

# Step 3: Generate Runge-Kutta-based (RK-based) timestepping code.
#       3.A: Evaluate RHSs (RHS_string)
#       3.B: Apply boundary conditions (RHS_string)
import MoLtimestepping.C_Code_Generation as MoL
from MoLtimestepping.RK_Butcher_Table_Dictionary import Butcher_dict
RK_order  = Butcher_dict[RK_method][1]
cmd.mkdir(os.path.join(Ccodesdir,"MoLtimestepping/"))

RHS_string = "rhs_eval(&rfmstruct, &params, RK_INPUT_GFS, RK_OUTPUT_GFS);"

if BoundaryCondition == "QuadraticExtrapolation":
    # Extrapolation BCs are applied to the evolved gridfunctions themselves after the MoL update
    post_RHS_string = "apply_bcs_curvilinear(&params, &bcstruct, NUM_EVOL_GFS, evol_gf_parity, RK_OUTPUT_GFS);"
elif BoundaryCondition == "Sommerfeld":
    # Sommerfeld BCs are applied to the gridfunction RHSs directly
    RHS_string += "\n apply_bcs_sommerfeld(&params, xx, &bcstruct, NUM_EVOL_GFS, evol_gf_parity, RK_INPUT_GFS, RK_OUTPUT_GFS);"
    post_RHS_string = ""
else:
    print("Invalid choice of boundary condition")
    sys.exit(1)

MoL.MoL_C_Code_Generation(RK_method, RHS_string = RHS_string, post_RHS_string = post_RHS_string,
                          outdir = os.path.join(Ccodesdir,"MoLtimestepping/"))

# Step 4: Set the coordinate system for the numerical grid
par.set_parval_from_str("reference_metric::CoordSystem",CoordSystem)
rfm.reference_metric()

# Step 5: Set the finite differencing order to 4.
par.set_parval_from_str("finite_difference::FD_CENTDERIVS_ORDER",FD_order)

# Step 6: Copy SIMD/SIMD_intrinsics.h to $Ccodesdir/SIMD/SIMD_intrinsics.h
cmd.mkdir(os.path.join(Ccodesdir,"SIMD"))
shutil.copy(os.path.join("SIMD/")+"SIMD_intrinsics.h",os.path.join(Ccodesdir,"SIMD/"))
# par.set_parval_from_str("indexedexp::symmetry_axes","2")
```

    'MaxwellEvolCurvi_Playground_Ccodes/SIMD/SIMD_intrinsics.h'

## Step 1.a: Output needed C code for finding the minimum proper distance between grid points, needed for [CFL](https://en.wikipedia.org/w/index.php?title=Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition&oldid=806430673)-limited timestep \[Back to [top](#toc)\]
$$\label{cfl}$$

In order for our explicit-timestepping numerical solution to Maxwell's equations to be stable, it must satisfy the [CFL](https://en.wikipedia.org/w/index.php?title=Courant%E2%80%93Friedrichs%E2%80%93Lewy_condition&oldid=806430673) condition:
$$
\Delta t \le \frac{\min(ds_i)}{c},
$$
where $c$ is the wavespeed, and
$$ds_i = h_i \Delta x^i$$
is the proper distance between neighboring gridpoints in the $i$th direction (in 3D, there are 3 directions), $h_i$ is the $i$th reference metric scale factor, and $\Delta x^i$ is the uniform grid spacing in the $i$th direction:

```python
# Output the find_timestep() function to a C file.
rfm.out_timestep_func_to_file(os.path.join(Ccodesdir,"find_timestep.h"))
```

# Step 2: Generate symbolic expressions and output C code for evolving Maxwell's equations \[Back to [top](#toc)\]
$$\label{mw}$$

Here we read in the symbolic expressions from the NRPy+ [InitialData](../edit/Maxwell/InitialData.py) and [Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled](../edit/Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled.py) modules to define the initial data, evolution equations, and constraint equations.

## Step 2.a: Generate symbolic expressions for toroidal dipole field initial data \[Back to [top](#toc)\]
$$\label{mwid}$$

Here we use the NRPy+ [InitialData](../edit/Maxwell/InitialData.py) module, described in [this tutorial](Tutorial-VacuumMaxwell_InitialData.ipynb), to write initial data to the grid functions for both systems.

We define the rescaled quantities $a^i$ and $e^i$ in terms of $A^i$ and $E^i$ in curvilinear coordinates within the NRPy+ [InitialData](../edit/Maxwell/InitialData.py) module (see [this tutorial](Tutorial-VacuumMaxwell_formulation_Curvilinear.ipynb) for more detail);

\begin{align}
a^i &= \frac{A^i}{\text{ReU}[i]},\\ \\
e^i &= \frac{E^i}{\text{ReU}[i]}.
\end{align}

```python
import Maxwell.InitialData as mwid

# Set which system to use, which are defined in Maxwell/InitialData.py
par.set_parval_from_str("Maxwell.InitialData::System_to_use","System_II")

mwid.InitialData()
aidU = ixp.zerorank1()
eidU = ixp.zerorank1()
for i in range(DIM):
    aidU[i] = mwid.AidU[i]/rfm.ReU[i]
    eidU[i] = mwid.EidU[i]/rfm.ReU[i]

Maxwell_ID_SymbExpressions = [\
                 lhrh(lhs="*AU0_exact",rhs=aidU[0]),\
                 lhrh(lhs="*AU1_exact",rhs=aidU[1]),\
                 lhrh(lhs="*AU2_exact",rhs=aidU[2]),\
                 lhrh(lhs="*EU0_exact",rhs=eidU[0]),\
                 lhrh(lhs="*EU1_exact",rhs=eidU[1]),\
                 lhrh(lhs="*EU2_exact",rhs=eidU[2]),\
                 lhrh(lhs="*PSI_exact",rhs=mwid.psi_ID),\
                 lhrh(lhs="*GAMMA_exact",rhs=mwid.Gamma_ID)]

Maxwell_ID_CcodeKernel = fin.FD_outputC("returnstring", Maxwell_ID_SymbExpressions)

```

    Currently using System_II initial data

## Step 2.b: Generate symbolic expressions for evolution equations \[Back to [top](#toc)\]
$$\label{mwevol}$$

Here we use the NRPy+ [Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled](../edit/Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled.py) module, described in [this tutorial](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb), to ascribe the evolution equations to the grid functions.

```python
import Maxwell.VacuumMaxwell_Flat_Evol_Curvilinear_rescaled as rhs

# Set which system to use, which are defined in Maxwell/InitialData.py
par.set_parval_from_str("Maxwell.InitialData::System_to_use","System_II")

cmd.mkdir(os.path.join(Ccodesdir,"rfm_files/"))
par.set_parval_from_str("reference_metric::enable_rfm_precompute","True")
par.set_parval_from_str("reference_metric::rfm_precompute_Ccode_outdir",os.path.join(Ccodesdir,"rfm_files/"))

rhs.VacuumMaxwellRHSs_rescaled()

Maxwell_RHSs_SymbExpressions =  [\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","aU0"),rhs=rhs.arhsU[0]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","aU1"),rhs=rhs.arhsU[1]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","aU2"),rhs=rhs.arhsU[2]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","eU0"),rhs=rhs.erhsU[0]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","eU1"),rhs=rhs.erhsU[1]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","eU2"),rhs=rhs.erhsU[2]),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","psi"),rhs=rhs.psi_rhs),\
                  lhrh(lhs=gri.gfaccess("rhs_gfs","Gamma"),rhs=rhs.Gamma_rhs)]

par.set_parval_from_str("reference_metric::enable_rfm_precompute","False") # Reset to False to disable rfm_precompute.
rfm.ref_metric__hatted_quantities()

Maxwell_RHSs_string = fin.FD_outputC("returnstring",
                          Maxwell_RHSs_SymbExpressions,
                          params="SIMD_enable=True").replace("IDX4","IDX4S")

```

## Step 2.c: Generate symbolic expressions for constraint equations \[Back to [top](#toc)\]
$$\label{mwcon}$$

We now use the NRPy+ [Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled](../edit/Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled.py) module, described in [this tutorial](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb), to ascribe the constraint equations.

```python
C = gri.register_gridfunctions("AUX", "C")
G = gri.register_gridfunctions("AUX", "G")

Constraints_string = fin.FD_outputC("returnstring",
                                [lhrh(lhs=gri.gfaccess("aux_gfs", "C"), rhs=rhs.C),
                                 lhrh(lhs=gri.gfaccess("aux_gfs", "G"), rhs=rhs.G)],
                                params="outCverbose=False").replace("IDX4","IDX4S")
```

## Step 2.d: Generate symbolic expressions for converting $A^i$ and $E^i$ to the Cartesian basis \[Back to [top](#toc)\]
$$\label{mwcart}$$

We now use the NRPy+ [Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled](../edit/Maxwell/VacuumMaxwell_Flat_Evol_Curvilinear_rescaled.py) module, described in [this tutorial](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb), to ascribe the coordinate conversion, to make our convergence tests slightly easier.

```python
AUCart = ixp.register_gridfunctions_for_single_rank1("AUX", "AUCart")
EUCart = ixp.register_gridfunctions_for_single_rank1("AUX", "EUCart")

Cartesian_Vectors_string = fin.FD_outputC("returnstring",
                        [lhrh(lhs=gri.gfaccess("aux_gfs", "AUCart0"), rhs=rhs.AU_Cart[0]),
                         lhrh(lhs=gri.gfaccess("aux_gfs", "AUCart1"), rhs=rhs.AU_Cart[1]),
                         lhrh(lhs=gri.gfaccess("aux_gfs", "AUCart2"), rhs=rhs.AU_Cart[2]),
                         lhrh(lhs=gri.gfaccess("aux_gfs", "EUCart0"), rhs=rhs.EU_Cart[0]),
                         lhrh(lhs=gri.gfaccess("aux_gfs", "EUCart1"), rhs=rhs.EU_Cart[1]),
                         lhrh(lhs=gri.gfaccess("aux_gfs", "EUCart2"), rhs=rhs.EU_Cart[2])],
                        params="outCverbose=False").replace("IDX4","IDX4S")
```

## Step 2.e: Output C codes for initial data and evolution equations \[Back to [top](#toc)\]
$$\label{mwccode}$$

Next we write the C codes for the initial data and evolution equations to files, to be used later by our main C code.

```python
# Step 11: Generate all needed C functions
Part_P1_body = Maxwell_ID_CcodeKernel
desc="Part P1: Declare the function for the exact solution at a single point. time==0 corresponds to the initial data."
name="exact_solution_single_point"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   ="const REAL xx0,const REAL xx1,const REAL xx2,const paramstruct *restrict params,\
                                        REAL *EU0_exact, \
                                        REAL *EU1_exact, \
                                        REAL *EU2_exact, \
                                        REAL *AU0_exact, \
                                        REAL *AU1_exact, \
                                        REAL *AU2_exact, \
                                        REAL *PSI_exact,\
                                        REAL *GAMMA_exact",
    body     = Part_P1_body,
    loopopts = "")

desc="Part P2: Declare the function for the exact solution at all points. time==0 corresponds to the initial data."
name="exact_solution_all_points"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   ="const paramstruct *restrict params,REAL *restrict xx[3], REAL *restrict in_gfs",
    body     ="""
REAL xx0 = xx[0][i0]; REAL xx1 = xx[1][i1]; REAL xx2 = xx[2][i2];
exact_solution_single_point(xx0,xx1,xx2,params,&in_gfs[IDX4S(EU0GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(EU1GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(EU2GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(AU0GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(AU1GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(AU2GF,i0,i1,i2)],
                                               &in_gfs[IDX4S(PSIGF,i0,i1,i2)],
                                               &in_gfs[IDX4S(GAMMAGF,i0,i1,i2)]);""",
    loopopts = "AllPoints")

Part_P3_body = Maxwell_RHSs_string

desc="Part P3: Declare the function to evaluate the RHSs of Maxwell's equations"
name="rhs_eval"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   ="""rfm_struct *restrict rfmstruct,const paramstruct *restrict params,
                 const REAL *restrict in_gfs, REAL *restrict rhs_gfs""",
    body     =Part_P3_body,
    loopopts = "InteriorPoints,EnableSIMD,Enable_rfm_precompute")
```

    Output C function exact_solution_single_point() to file MaxwellEvolCurvi_Playground_Ccodes/exact_solution_single_point.h
    Output C function exact_solution_all_points() to file MaxwellEvolCurvi_Playground_Ccodes/exact_solution_all_points.h
    Output C function rhs_eval() to file MaxwellEvolCurvi_Playground_Ccodes/rhs_eval.h

## Step 2.f: Output C code for constraint equations \[Back to [top](#toc)\]
$$\label{mwccode_con}$$

Finally output the C code for evaluating the divergence constraint, described in [this tutorial](Tutorial-VacuumMaxwell_Curvilinear_RHSs.ipynb). In the absence of numerical error, this constraint should evaluate to zero, but due to numerical (typically truncation and roundoff) error it does not. We will therefore measure the divergence constraint violation to gauge the accuracy of our simulation, and ultimately determine whether errors are dominated by numerical finite differencing (truncation) error as expected. Specifically, we take the L2 norm of the constraint violation, via

\begin{align}
    \lVert C \rVert^2 &= \frac{\int C^2 d\mathcal{V}}{\int d\mathcal{V}}.
\end{align}

Numerically approximating this integral, in spherical coordinates for example, then gives us

\begin{align}
    \lVert C \rVert^2   &= \frac{\sum C^2 r^2 \sin^2 (\theta) dr d\theta d\phi}{\sum r^2 \sin^2 (\theta) dr d\theta d\phi}, \\ \\
    &= \frac{\sum C^2 r^2 \sin^2 (\theta)}{\sum r^2 \sin^2 (\theta) } , \\  \\
    &= \frac{\sum C^2 \ \sqrt{\text{det} \ \hat{\gamma}}}{\sum \sqrt{\text{det} \ \hat{\gamma}}},
\end{align}

where $\hat{\gamma}$ is the reference metric. Thus, along with the C code to calculate the constraints, we also print out the code required to evaluate $\sqrt{\text{det} \ \hat{\gamma}}$ at any given point.

```python
# Set up the C function for the calculating the constraints
Part_P4_body = Constraints_string
desc="Evaluate the constraints"
name="Constraints"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   = """rfm_struct *restrict rfmstruct,const paramstruct *restrict params,
                  REAL *restrict in_gfs, REAL *restrict aux_gfs""",
    body     = Part_P4_body,
    loopopts = "InteriorPoints,Enable_rfm_precompute")

# intgrand to be used to calculate the L2 norm of the constraint
diagnostic_integrand_body = outputC(rfm.detgammahat,"*detg",filename='returnstring',
                                    params="includebraces=False")
desc="Evaluate the volume element at a specific point"
name="diagnostic_integrand"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   ="const REAL xx0,const REAL xx1,const REAL xx2,const paramstruct *restrict params, REAL *restrict detg",
    body     = diagnostic_integrand_body,
    loopopts = "")

```

    Output C function Constraints() to file MaxwellEvolCurvi_Playground_Ccodes/Constraints.h
    Output C function diagnostic_integrand() to file MaxwellEvolCurvi_Playground_Ccodes/diagnostic_integrand.h

## Step 2.g: Output C code for converting $A^i$ and $E^i$ to Cartesian coordinates \[Back to [top](#toc)\]
$$\label{mwccode_cart}$$

Here we write the C code for the coordinate transformation to Cartesian coordinates.

```python
desc="Convert EU and AU to Cartesian basis"
name="Cartesian_basis"
outCfunction(
    outfile  = os.path.join(Ccodesdir,name+".h"), desc=desc, name=name,
    params   = """rfm_struct *restrict rfmstruct,const paramstruct *restrict params, REAL *restrict xx[3],
                  REAL *restrict in_gfs, REAL *restrict aux_gfs""",
    body     = "REAL xx0 = xx[0][i0]; REAL xx1 = xx[1][i1]; REAL xx2 = xx[2][i2];\n"+Cartesian_Vectors_string,
    loopopts = "AllPoints, Enable_rfm_precompute")
```

    Output C function Cartesian_basis() to file MaxwellEvolCurvi_Playground_Ccodes/Cartesian_basis.h

## Step 2.h: Output C code for printing 2D data \[Back to [top](#toc)\]
$$\label{mwccode_xzloop}$$

Here we output the neccesary C code to print out a 2D slice of the data in the xz-plane, using the `xz_loop` macro

```python
def xz_loop(CoordSystem):
    ret = """// xz-plane output for """ + CoordSystem + r""" coordinates:
#define LOOP_XZ_PLANE(ii, jj, kk) \
"""
    if "Spherical" in CoordSystem or  "SymTP" in CoordSystem:
        ret += r"""for (int i2 = 0; i2 < Nxx_plus_2NGHOSTS2; i2++) \
  if(i2 == NGHOSTS || i2 == Nxx_plus_2NGHOSTS2/2) \
    for (int i1 = 0; i1 < Nxx_plus_2NGHOSTS1; i1++) \
      for (int i0 = 0; i0 < Nxx_plus_2NGHOSTS0; i0++)
"""
    elif "Cylindrical" in CoordSystem:
        ret += r"""for (int i2 = 0; i2 < Nxx_plus_2NGHOSTS2; i2++) \
  for (int i1 = 0; i1 < Nxx_plus_2NGHOSTS1; i1++) \
    if(i1 == NGHOSTS || i1 == Nxx_plus_2NGHOSTS1/2) \
      for (int i0 = 0; i0 < Nxx_plus_2NGHOSTS0; i0++)
"""
    elif "Cartesian" in CoordSystem:
        ret += r"""for (int i2 = 0; i2 < Nxx_plus_2NGHOSTS2; i2++) \
  for (int i1 = Nxx_plus_2NGHOSTS1/2; i1 < Nxx_plus_2NGHOSTS1/2+1; i1++) \
    for (int i0 = 0; i0 < Nxx_plus_2NGHOSTS0; i0++)
"""
    return ret

with open(os.path.join(Ccodesdir,"xz_loop.h"),"w") as file:
    file.write(xz_loop(CoordSystem))
```

## Step 2.i: Output C codes needed for declaring and setting Cparameters; also set `free_parameters.h` \[Back to [top](#toc)\]
$$\label{cparams_rfm_and_domainsize}$$

Based on declared NRPy+ Cparameters, first we generate `declare_Cparameters_struct.h`, `set_Cparameters_default.h`, and `set_Cparameters[-SIMD].h`.

Then we output `free_parameters.h`, which sets initial data parameters, as well as grid domain & reference metric parameters, applying `domain_size` and `sinh_width`/`SymTP_bScale` (if applicable) as set above

```python
# Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h
par.generate_Cparameters_Ccodes(os.path.join(Ccodesdir))

# Set free_parameters.h
with open(os.path.join(Ccodesdir,"free_parameters.h"),"w") as file:
    file.write("""
// Set free-parameter values.
params.time = 0.0; // Initial simulation time time corresponds to exact solution at time=0.
params.amp = 1.0;
params.lam = 1.0;
params.wavespeed = 1.0;\n""")

# Append to $Ccodesdir/free_parameters.h reference metric parameters based on generic
#    domain_size,sinh_width,sinhv2_const_dr,SymTP_bScale,
#    parameters set above.
rfm.out_default_free_parameters_for_rfm(os.path.join(Ccodesdir,"free_parameters.h"),
                                        domain_size,sinh_width,sinhv2_const_dr,SymTP_bScale)

# Generate set_Nxx_dxx_invdx_params__and__xx.h:
rfm.set_Nxx_dxx_invdx_params__and__xx_h(Ccodesdir, grid_centering="cell")

# Generate xxCart.h, which contains xxCart() for
#  (the mapping from xx->Cartesian) for the chosen CoordSystem:
rfm.xxCart_h("xxCart","./set_Cparameters.h",os.path.join(Ccodesdir,"xxCart.h"))

# Step 3.d.v: Generate declare_Cparameters_struct.h, set_Cparameters_default.h, and set_Cparameters[-SIMD].h
par.generate_Cparameters_Ccodes(os.path.join(Ccodesdir))
```

# Step 3: Set up Sommerfeld boundary condition for Cartesian coordinate system \[Back to [top](#toc)\]
$$\label{bc_functs}$$

Next we output the C code necessary to implement the Sommerfeld boundary condition in Cartesian coordinates, [as documented in the corresponding NRPy+ tutorial notebook](Tutorial-SommerfeldBoundaryCondition.ipynb)

```python
import CurviBoundaryConditions.CurviBoundaryConditions as cbcs
cbcs.Set_up_CurviBoundaryConditions(os.path.join(Ccodesdir,"boundary_conditions/"),
                                   Cparamspath=os.path.join("../"),
                                   BoundaryCondition=BoundaryCondition)

if BoundaryCondition == "Sommerfeld":
    bcs = cbcs.sommerfeld_boundary_condition_class(fd_order=4,
                                             vars_radial_falloff_power_default=3,
                                             vars_speed_default=1.,
                                             vars_at_inf_default=0.)
    bcs.write_sommerfeld_file(Ccodesdir)
```

    Wrote to file "MaxwellEvolCurvi_Playground_Ccodes/boundary_conditions/parity_conditions_symbolic_dot_products.h"
    Evolved parity: ( Gamma:0, aU0:1, aU1:2, aU2:3, eU0:1, eU1:2, eU2:3, psi:0
        )
    Auxiliary parity: ( AUCart0:1, AUCart1:2, AUCart2:3, C:0, EUCart0:1,
        EUCart1:2, EUCart2:3, G:0 )

    Wrote to file "MaxwellEvolCurvi_Playground_Ccodes/boundary_conditions/EigenCoord_Cart_to_xx.h"

    Successfully generated Sommerfeld boundary condition C code

# Step 4: `Maxwell_Playground.c`: The Main C Code \[Back to [top](#toc)\]
$$\label{mainc}$$

```python
# Part P0: Define REAL, set the number of ghost cells NGHOSTS (from NRPy+'s FD_CENTDERIVS_ORDER),
#          and set the CFL_FACTOR (which can be overwritten at the command line)

with open(os.path.join(Ccodesdir,"Maxwell_Playground_REAL__NGHOSTS__CFL_FACTOR.h"), "w") as file:
    file.write("""
// Part P0.a: Set the number of ghost cells, from NRPy+'s FD_CENTDERIVS_ORDER
#define NGHOSTS """+str(int(FD_order/2)+1)+"""
// Part P0.b: Set the numerical precision (REAL) to double, ensuring all floating point
//            numbers are stored to at least ~16 significant digits
#define REAL """+REAL+"""
// Part P0.c: Set the CFL Factor. Can be overwritten at command line.
REAL CFL_FACTOR = """+str(default_CFL_FACTOR)+";")
```

```python
%%writefile $Ccodesdir/Maxwell_Playground.c

// Step P0: Define REAL and NGHOSTS; and declare CFL_FACTOR. This header is generated in NRPy+.
#include "Maxwell_Playground_REAL__NGHOSTS__CFL_FACTOR.h"

#include "rfm_files/rfm_struct__declare.h"

#include "declare_Cparameters_struct.h"

// All SIMD intrinsics used in SIMD-enabled C code loops are defined here:
#include "SIMD/SIMD_intrinsics.h"

// Step P1: Import needed header files
#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include "time.h"
#include "stdint.h" // Needed for Windows GCC 6.x compatibility
#ifndef M_PI
#define M_PI 3.141592653589793238462643383279502884L
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.707106781186547524400844362104849039L
#endif

// Step P2: Declare the IDX4S(gf,i,j,k) macro, which enables us to store 4-dimensions of
//           data in a 1D array. In this case, consecutive values of "i"
//           (all other indices held to a fixed value) are consecutive in memory, where
//           consecutive values of "j" (fixing all other indices) are separated by
//           Nxx_plus_2NGHOSTS0 elements in memory. Similarly, consecutive values of
//           "k" are separated by Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1 in memory, etc.
#define IDX4S(g,i,j,k) \
( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) + Nxx_plus_2NGHOSTS2 * (g) ) ) )
#define IDX4ptS(g,idx) ( (idx) + (Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2) * (g) )
#define IDX3S(i,j,k) ( (i) + Nxx_plus_2NGHOSTS0 * ( (j) + Nxx_plus_2NGHOSTS1 * ( (k) ) ) )
#define LOOP_REGION(i0min,i0max, i1min,i1max, i2min,i2max) \
  for(int i2=i2min;i2<i2max;i2++) for(int i1=i1min;i1<i1max;i1++) for(int i0=i0min;i0<i0max;i0++)
#define LOOP_ALL_GFS_GPS(ii) _Pragma("omp parallel for") \
  for(int (ii)=0;(ii)<Nxx_plus_2NGHOSTS_tot*NUM_EVOL_GFS;(ii)++)

// Step P3: Set UUGF and VVGF macros, as well as xxCart()
#include "boundary_conditions/gridfunction_defines.h"

// Step P4: Defines set_Nxx_dxx_invdx_params__and__xx(const int EigenCoord, const int Nxx[3],
//                                       paramstruct *restrict params, REAL *restrict xx[3]),
//          which sets params Nxx,Nxx_plus_2NGHOSTS,dxx,invdx, and xx[] for
//          the chosen Eigen-CoordSystem if EigenCoord==1, or
//          CoordSystem if EigenCoord==0.
#include "set_Nxx_dxx_invdx_params__and__xx.h"

// Step P5: Include basic functions needed to impose curvilinear
//          parity and boundary conditions.
#include "boundary_conditions/CurviBC_include_Cfunctions.h"

// Step P6: Find the CFL-constrained timestep
#include "find_timestep.h"

// Part P7: Declare the function for the exact solution at a single point. time==0 corresponds to the initial data.
#include "exact_solution_single_point.h"

// Part P8: Declare the function for the exact solution at all points. time==0 corresponds to the initial data.
#include "exact_solution_all_points.h"

// Step P9: Declare function for evaluating constraints (diagnostic)
#include "Constraints.h"

// Step P10: Declare rhs_eval function, which evaluates the RHSs of Maxwells equations
#include "rhs_eval.h"

// Step P11: Declare function to calculate det gamma_hat, used in calculating the L2 norm
#include "diagnostic_integrand.h"

// Step P12: Declare function to transform to the Cartesian basis
#include "Cartesian_basis.h"

// Step P13: Declare macro to print out data along the xz-plane
#include "xz_loop.h"

// main() function:
// Step 0: Read command-line input, set up grid structure, allocate memory for gridfunctions, set up coordinates
// Step 1: Set up initial data to an exact solution
// Step 2: Start the timer, for keeping track of how fast the simulation is progressing.
// Step 3: Integrate the initial data forward in time using the chosen RK-like Method of
//         Lines timestepping algorithm, and output periodic simulation diagnostics
// Step 3.a: Output 2D data file periodically, for visualization
// Step 3.b: Step forward one timestep (t -> t+dt) in time using
//           chosen RK-like MoL timestepping algorithm
// Step 3.c: If t=t_final, output x and y components of evolution variables and the
//           constraint violation to 2D data file
// Step 3.d: Progress indicator printing to stderr
// Step 4: Free all allocated memory
int main(int argc, const char *argv[]) {
    paramstruct params;
#include "set_Cparameters_default.h"

    // Define xxCart(const paramstruct *restrict params,
    //                     REAL *restrict xx[3],
    //                     const int i0,const int i1,const int i2,
    //                     REAL xCart[3]),
    //           which maps xx->Cartesian via
    //    {xx[0][i0],xx[1][i1],xx[2][i2]}->{xCart[0],xCart[1],xCart[2]}
    // Note that xxCart is declared inline, so it must be #include'd here since we call
    //  it from the main() function.
#include "xxCart.h"

    // Step 0a: Read command-line input, error out if nonconformant
    if((argc != 5 && argc != 6) || atoi(argv[1]) < NGHOSTS || atoi(argv[2]) < NGHOSTS || atoi(argv[3]) < 2 /* FIXME; allow for axisymmetric sims */) {
        fprintf(stderr,"Error: Expected three command-line arguments: ./Maxwell_Playground Nx0 Nx1 Nx2,\n");
        fprintf(stderr,"where Nx[0,1,2] is the number of grid points in the 0, 1, and 2 directions.\n");
        fprintf(stderr,"Nx[] MUST BE larger than NGHOSTS (= %d)\n",NGHOSTS);
        exit(1);
    }
    if(argc == 5) {
        CFL_FACTOR = strtod(argv[5],NULL);
        if(CFL_FACTOR > 0.5 && atoi(argv[3])!=2) {
            fprintf(stderr,"WARNING: CFL_FACTOR was set to %e, which is > 0.5.\n",CFL_FACTOR);
            fprintf(stderr,"         This will generally only be stable if the simulation is purely axisymmetric\n");
            fprintf(stderr,"         However, Nx2 was set to %d>2, which implies a non-axisymmetric simulation\n",atoi(argv[3]));
        }
    }
    // Step 0b: Set up numerical grid structure, first in space...
    const int Nxx[3] = { atoi(argv[1]), atoi(argv[2]), atoi(argv[3]) };
    if(Nxx[0]%2 != 0 || Nxx[1]%2 != 0 || Nxx[2]%2 != 0) {
        fprintf(stderr,"Error: Cannot guarantee a proper cell-centered grid if number of grid cells not set to even number.\n");
        fprintf(stderr,"       For example, in case of angular directions, proper symmetry zones will not exist.\n");
        exit(1);
    }

    // Step 0c: Set free parameters, overwriting Cparameters defaults
    //          by hand or with command-line input, as desired.
#include "free_parameters.h"

   // Step 0d: Uniform coordinate grids are stored to *xx[3]
    REAL *xx[3];
    // Step 0d.i: Set bcstruct
    bc_struct bcstruct;
    {
        int EigenCoord = 1;
        // Step 0d.ii: Call set_Nxx_dxx_invdx_params__and__xx(), which sets
        //             params Nxx,Nxx_plus_2NGHOSTS,dxx,invdx, and xx[] for the
        //             chosen Eigen-CoordSystem.
        set_Nxx_dxx_invdx_params__and__xx(EigenCoord, Nxx, &params, xx);
        // Step 0d.iii: Set Nxx_plus_2NGHOSTS_tot
#include "set_Cparameters-nopointer.h"
        const int Nxx_plus_2NGHOSTS_tot = Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2;
        // Step 0e: Find ghostzone mappings; set up bcstruct
#include "boundary_conditions/driver_bcstruct.h"
        // Step 0e.i: Free allocated space for xx[][] array
        for(int i=0;i<3;i++) free(xx[i]);
    }

    // Step 0f: Call set_Nxx_dxx_invdx_params__and__xx(), which sets
    //          params Nxx,Nxx_plus_2NGHOSTS,dxx,invdx, and xx[] for the
    //          chosen (non-Eigen) CoordSystem.
    int EigenCoord = 0;
    set_Nxx_dxx_invdx_params__and__xx(EigenCoord, Nxx, &params, xx);

    // Step 0g: Set all C parameters "blah" for params.blah, including
    //          Nxx_plus_2NGHOSTS0 = params.Nxx_plus_2NGHOSTS0, etc.
#include "set_Cparameters-nopointer.h"
    const int Nxx_plus_2NGHOSTS_tot = Nxx_plus_2NGHOSTS0*Nxx_plus_2NGHOSTS1*Nxx_plus_2NGHOSTS2;

    // Step 0h: Time coordinate parameters
    const REAL t_final = strtod(argv[4],NULL);

    // Step 0i: Set timestep based on smallest proper distance between gridpoints and CFL factor
    REAL dt = find_timestep(&params, xx);
    //fprintf(stderr,"# Timestep set to = %e\n",(double)dt);
    int N_final = (int)(t_final / dt + 0.5); // The number of points in time.
                                             // Add 0.5 to account for C rounding down
                                             // typecasts to integers.
    int output_every_N = (int)((REAL)N_final/800.0);
    if(output_every_N == 0) output_every_N = 1;

    // Step 0j: Error out if the number of auxiliary gridfunctions outnumber evolved gridfunctions.
    //              This is a limitation of the RK method. You are always welcome to declare & allocate
    //              additional gridfunctions by hand.
    if(NUM_AUX_GFS > NUM_EVOL_GFS) {
        fprintf(stderr,"Error: NUM_AUX_GFS > NUM_EVOL_GFS. Either reduce the number of auxiliary gridfunctions,\n");
        fprintf(stderr,"       or allocate (malloc) by hand storage for *diagnostic_output_gfs. \n");
        exit(1);
    }

    // Step 0k: Allocate memory for gridfunctions
#include "MoLtimestepping/RK_Allocate_Memory.h"
    REAL *restrict y_0_gfs = (REAL *)malloc(sizeof(REAL) * NUM_EVOL_GFS * Nxx_plus_2NGHOSTS_tot);
    REAL *restrict diagnostic_output_gfs_0 = (REAL *)malloc(sizeof(REAL) * NUM_AUX_GFS * Nxx_plus_2NGHOSTS_tot);

    // Step 0l: Set up precomputed reference metric arrays
    // Step 0l.i: Allocate space for precomputed reference metric arrays.
#include "rfm_files/rfm_struct__malloc.h"

    // Step 0l.ii: Define precomputed reference metric arrays.
    {
    #include "set_Cparameters-nopointer.h"
    #include "rfm_files/rfm_struct__define.h"
    }

    LOOP_ALL_GFS_GPS(i) {
     y_n_gfs[i] = 0.0/0.0;
}

    // Step 1: Set up initial data to be exact solution at time=0:
    params.time = 0.0;
    exact_solution_all_points(&params, xx, y_n_gfs);

    // Step 2: Start the timer, for keeping track of how fast the simulation is progressing.
#ifdef __linux__ // Use high-precision timer in Linux.
    struct timespec start, end;
    clock_gettime(CLOCK_REALTIME, &start);
#else     // Resort to low-resolution, standards-compliant timer in non-Linux OSs
    // http://www.cplusplus.com/reference/ctime/time/
    time_t start_timer,end_timer;
    time(&start_timer); // Resolution of one second...
#endif

    // Step 3: Integrate the initial data forward in time using the chosen RK-like Method of
    //         Lines timestepping algorithm, and output periodic simulation diagnostics
    for(int n=0;n<=N_final+1;n++) { // Main loop to progress forward in time.

       // At each timestep, set Constraints to NaN in the grid interior
        LOOP_REGION(NGHOSTS,NGHOSTS+Nxx0,
                    NGHOSTS,NGHOSTS+Nxx1,
                    NGHOSTS,NGHOSTS+Nxx2) {
                    const int idx = IDX3S(i0,i1,i2);
                    diagnostic_output_gfs[IDX4ptS(CGF,idx)] = 0.0/0.0;
            }

        // Step 3.a: Output 2D data file periodically, for visualization
        params.time = ((REAL)n)*dt;
        // Evaluate Divergence constraint violation
        Constraints(&rfmstruct, &params, y_n_gfs, diagnostic_output_gfs);
        // log_L2_Norm = log10( sqrt[Integral( [numerical - exact]^2 * dV)] )
        REAL L2Norm_sum_C = 0.;
        int sum = 0;
        LOOP_REGION(NGHOSTS,NGHOSTS+Nxx0,
                    NGHOSTS,NGHOSTS+Nxx1,
                    NGHOSTS,NGHOSTS+Nxx2) {
            const int idx = IDX3S(i0,i1,i2);
            double C = (double)diagnostic_output_gfs[IDX4ptS(CGF,idx)];
            REAL xx0 = xx[0][i0];
            REAL xx1 = xx[1][i1];
            REAL xx2 = xx[2][i2];
            REAL detghat; diagnostic_integrand(xx0, xx1, xx2, &params, &detghat);
            L2Norm_sum_C += C*C*sqrt(detghat);
            sum = sum + sqrt(detghat);
        }
        REAL L2Norm_C = sqrt(L2Norm_sum_C/(sum));
        printf("%e %.15e\n",params.time, L2Norm_C);

    // Step 3.a: Output 2D data file periodically, for visualization
       if(n%20 == 0) {
            exact_solution_all_points(&params, xx, y_0_gfs);
            Cartesian_basis(&rfmstruct, &params, xx, y_n_gfs, diagnostic_output_gfs);
            Cartesian_basis(&rfmstruct, &params, xx, y_0_gfs, diagnostic_output_gfs_0);
            char filename[100];
            sprintf(filename,"out%d-%08d.txt",Nxx[0],n);
            FILE *out2D = fopen(filename, "w");
            LOOP_XZ_PLANE(ii, jj, kk){
            REAL xCart[3];
            xxCart(&params,xx,i0,i1,i2,xCart);
            int idx = IDX3S(i0,i1,i2);
            REAL Ex_num  = (double)diagnostic_output_gfs[IDX4ptS(EUCART0GF,idx)];
            REAL Ey_num  = (double)diagnostic_output_gfs[IDX4ptS(EUCART1GF,idx)];
            REAL Ax_num  = (double)diagnostic_output_gfs[IDX4ptS(AUCART0GF,idx)];
            REAL Ay_num  = (double)diagnostic_output_gfs[IDX4ptS(AUCART1GF,idx)];
            double C = (double)diagnostic_output_gfs[IDX4ptS(CGF,idx)];

            fprintf(out2D,"%e %e %e %.15e %.15e %.15e %.15e %.15e\n", params.time,
                    xCart[0],xCart[2], Ex_num, Ey_num, Ax_num, Ay_num, C);
       }
        fclose(out2D);
    }

      if(n==N_final-1) {
            exact_solution_all_points(&params, xx, y_0_gfs);
            Cartesian_basis(&rfmstruct, &params, xx, y_n_gfs, diagnostic_output_gfs);
            Cartesian_basis(&rfmstruct, &params, xx, y_0_gfs, diagnostic_output_gfs_0);
            char filename[100];
            sprintf(filename,"out%d.txt",Nxx[0]);
            FILE *out2D = fopen(filename, "w");
            LOOP_XZ_PLANE(ii, jj, kk){
            REAL xCart[3];
            xxCart(&params,xx,i0,i1,i2,xCart);
            int idx = IDX3S(i0,i1,i2);
            REAL Ex_num  = (double)diagnostic_output_gfs[IDX4ptS(EUCART0GF,idx)];
            REAL Ey_num  = (double)diagnostic_output_gfs[IDX4ptS(EUCART1GF,idx)];

            REAL Ax_num  = (double)diagnostic_output_gfs[IDX4ptS(AUCART0GF,idx)];
            REAL Ay_num  = (double)diagnostic_output_gfs[IDX4ptS(AUCART1GF,idx)];

            REAL Ex_exact  = (double)diagnostic_output_gfs_0[IDX4ptS(EUCART0GF,idx)];
            REAL Ey_exact  = (double)diagnostic_output_gfs_0[IDX4ptS(EUCART1GF,idx)];

            REAL Ax_exact  = (double)diagnostic_output_gfs_0[IDX4ptS(AUCART0GF,idx)];
            REAL Ay_exact  = (double)diagnostic_output_gfs_0[IDX4ptS(AUCART1GF,idx)];

            REAL Ex__E_rel = log10(fabs(Ex_num - Ex_exact));
            REAL Ey__E_rel = log10(fabs(Ey_num - Ey_exact));
            REAL Ax__E_rel = log10(fabs(Ax_num - Ax_exact));
            REAL Ay__E_rel = log10(fabs(Ay_num - Ay_exact));

            fprintf(out2D,"%e %e %.15e %.15e %.15e %.15e\n",xCart[0],xCart[2],
                     Ex__E_rel, Ey__E_rel, Ax__E_rel, Ay__E_rel);
       }
        fclose(out2D);
    }
        // Step 3.b: Step forward one timestep (t -> t+dt) in time using
        //           chosen RK-like MoL timestepping algorithm
#include "MoLtimestepping/RK_MoL.h"

        // Step 3.d: Progress indicator printing to stderr

        // Step 3.d.i: Measure average time per iteration
#ifdef __linux__ // Use high-precision timer in Linux.
        clock_gettime(CLOCK_REALTIME, &end);
        const long long unsigned int time_in_ns = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
#else     // Resort to low-resolution, standards-compliant timer in non-Linux OSs
        time(&end_timer); // Resolution of one second...
        REAL time_in_ns = difftime(end_timer,start_timer)*1.0e9+0.5; // Round up to avoid divide-by-zero.
#endif
        const REAL s_per_iteration_avg = ((REAL)time_in_ns / (REAL)n) / 1.0e9;

        const int iterations_remaining = N_final - n;
        const REAL time_remaining_in_mins = s_per_iteration_avg * (REAL)iterations_remaining / 60.0;

        const REAL num_RHS_pt_evals = (REAL)(Nxx[0]*Nxx[1]*Nxx[2]) * 4.0 * (REAL)n; // 4 RHS evals per gridpoint for RK4
        const REAL RHS_pt_evals_per_sec = num_RHS_pt_evals / ((REAL)time_in_ns / 1.0e9);

        // Step 3.d.ii: Output simulation progress to stderr
        if(n % 10 == 0) {
            fprintf(stderr,"%c[2K", 27); // Clear the line
            fprintf(stderr,"It: %d t=%.2f dt=%.2e | %.1f%%; ETA %.0f s | t/h %.2f | gp/s %.2e\r",  // \r is carriage return, move cursor to the beginning of the line
                   n, n * (double)dt, (double)dt, (double)(100.0 * (REAL)n / (REAL)N_final),
                   (double)time_remaining_in_mins*60, (double)(dt * 3600.0 / s_per_iteration_avg), (double)RHS_pt_evals_per_sec);
            fflush(stderr); // Flush the stderr buffer
        } // End progress indicator if(n % 10 == 0)

    } // End main loop to progress forward in time.
    fprintf(stderr,"\n"); // Clear the final line of output from progress indicator.

    // Step 4: Free all allocated memory
#include "rfm_files/rfm_struct__freemem.h"
#include "boundary_conditions/bcstruct_freemem.h"
#include "MoLtimestepping/RK_Free_Memory.h"
    free(y_0_gfs);
    free(diagnostic_output_gfs_0);
    for(int i=0;i<3;i++) free(xx[i]);

    return 0;
}
```

    Writing MaxwellEvolCurvi_Playground_Ccodes//Maxwell_Playground.c

# Step 5: Compile generated C codes & perform simulation of the propagating toriodal electromagnetic field \[Back to [top](#toc)\]
$$\label{compileexec}$$

To aid in the cross-platform-compatible (with Windows, MacOS, & Linux) compilation and execution, we make use of `cmdline_helper` [(**Tutorial**)](Tutorial-cmdline_helper.ipynb).

```python
import cmdline_helper as cmd
CFL_FACTOR=0.5
cmd.C_compile(os.path.join(Ccodesdir,"Maxwell_Playground.c"),
              os.path.join(outdir,"Maxwell_Playground"),compile_mode="optimized")
```

    Compiling executable...
    (EXEC): Executing `gcc -Ofast -fopenmp -march=native -funroll-loops MaxwellEvolCurvi_Playground_Ccodes/Maxwell_Playground.c -o MaxwellEvolCurvi_Playground_Ccodes/output/Maxwell_Playground -lm`...
    (BENCH): Finished executing in 2.0446927547454834 seconds.
    Finished compilation.

```python
# Change to output directory
os.chdir(outdir)
```

```python
# Clean up existing output files
cmd.delete_existing_files("out*.txt")
cmd.delete_existing_files("out*.png")
cmd.delete_existing_files("out-*resolution.txt")
```

```python
# Set tme to end simulation
t_final = str(0.5*domain_size) + ' '

# Run executables
if 'Spherical' in CoordSystem  or 'SymTP' in CoordSystem:
    cmd.Execute("Maxwell_Playground", "64 48 4 "+t_final+str(CFL_FACTOR), "out-lowresolution.txt")
    cmd.Execute("Maxwell_Playground", "96 72 4 "+t_final+str(CFL_FACTOR), "out-medresolution.txt")
    Nxx0_low = '64'
    Nxx0_med = '96'

elif 'Cylindrical' in CoordSystem:
    cmd.Execute("Maxwell_Playground", "50 4 100 "+t_final+str(CFL_FACTOR), "out-lowresolution.txt")
    cmd.Execute("Maxwell_Playground", "80 4 160 "+t_final+str(CFL_FACTOR), "out-medresolution.txt")
    Nxx0_low = '50'
    Nxx0_med = '80'

else:
    # Cartesian
    cmd.Execute("Maxwell_Playground", "64 64 64 "+t_final+str(CFL_FACTOR), "out-lowresolution.txt")
    cmd.Execute("Maxwell_Playground", "128 128 128 "+t_final+str(CFL_FACTOR), "out-medresolution.txt")
    Nxx0_low = '64'
    Nxx0_med = '128'
```

    (EXEC): Executing `taskset -c 0,1,2,3,4,5 ./Maxwell_Playground 50 4 100 5.0 0.5`...
    It: 150 t=4.87 dt=3.25e-02 | 97.4%; ETA 0 s | t/h 6963.28 | gp/s 4.77e+06
    (BENCH): Finished executing in 2.613574981689453 seconds.
    (EXEC): Executing `taskset -c 0,1,2,3,4,5 ./Maxwell_Playground 80 4 160 5.0 0.5`...
    It: 240 t=4.87 dt=2.03e-02 | 97.6%; ETA 0 s | t/h 2137.90 | gp/s 6.00e+06
    (BENCH): Finished executing in 8.6272451877594 seconds.

```python
# Return to root directory
os.chdir(os.path.join("../../"))

print("Finished this code cell.")
```

    Finished this code cell.

# Step 6: Visualize the output! \[Back to [top](#toc)\]
$$\label{visualize}$$

In this section we will generate a movie, plotting the x component of the electric field on a 2D grid..

## Step 6.a: Install `scipy` and download `ffmpeg` if they are not yet installed/downloaded \[Back to [top](#toc)\]
$$\label{installdownload}$$

Note that if you are not running this within `mybinder`, but on a Windows system, `ffmpeg` must be installed using a separate package (on [this site](http://ffmpeg.org/)), or if running Jupyter within Anaconda, use the command: `conda install -c conda-forge ffmpeg`.

```python
!pip install scipy > /dev/null

check_for_ffmpeg = !which ffmpeg >/dev/null && echo $?
if check_for_ffmpeg != ['0']:
    print("Couldn't find ffmpeg, so I'll download it.")
    # Courtesy https://johnvansickle.com/ffmpeg/
    !wget http://astro.phys.wvu.edu/zetienne/ffmpeg-static-amd64-johnvansickle.tar.xz
    !tar Jxf ffmpeg-static-amd64-johnvansickle.tar.xz
    print("Copying ffmpeg to ~/.local/bin/. Assumes ~/.local/bin is in the PATH.")
    !mkdir ~/.local/bin/
    !cp ffmpeg-static-amd64-johnvansickle/ffmpeg ~/.local/bin/
    print("If this doesn't work, then install ffmpeg yourself. It should work fine on mybinder.")
```

## Step 6.b: Generate images for visualization animation \[Back to [top](#toc)\]
$$\label{genimages}$$

Here we loop through the data files output by the executable compiled and run in [the previous step](#mainc), generating a [png](https://en.wikipedia.org/wiki/Portable_Network_Graphics) image for each data file.

**Special thanks to Terrence Pierre Jacques. His work with the first versions of these scripts greatly contributed to the scripts as they exist below.**

```python
## VISUALIZATION ANIMATION, PART 1: Generate PNGs, one per frame of movie ##

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
from IPython.display import HTML
import matplotlib.image as mgimg

import glob
import sys
from matplotlib import animation

globby = glob.glob(os.path.join(outdir,'out'+Nxx0_med+'-00*.txt'))
file_list = []
for x in sorted(globby):
    file_list.append(x)

bound = domain_size/2.0
pl_xmin = -bound
pl_xmax = +bound
pl_zmin = -bound
pl_zmax = +bound

for filename in file_list:
    fig = plt.figure()
    t, x, z, Ex, Ey, Ax, Ay, C = np.loadtxt(filename).T #Transposed for easier unpacking

    plotquantity = Ex
    time = np.round(t[0], decimals=3)
    plotdescription = "Numerical Soln."
    plt.title(r"$E_x$ at $t$ = "+str(time))
    plt.xlabel("x")
    plt.ylabel("z")

    grid_x, grid_z = np.mgrid[pl_xmin:pl_xmax:200j, pl_zmin:pl_zmax:200j]
    points = np.zeros((len(x), 2))
    for i in range(len(x)):
        # Zach says: No idea why x and y get flipped...
        points[i][0] = x[i]
        points[i][1] = z[i]

    grid = griddata(points, plotquantity, (grid_x, grid_z), method='nearest')
    gridcub = griddata(points, plotquantity, (grid_x, grid_z), method='cubic')
    im = plt.imshow(gridcub, extent=(pl_xmin,pl_xmax, pl_zmin,pl_zmax))
    ax = plt.colorbar()
    plt.clim(-3,3)
    ax.set_label(plotdescription)
    savefig(os.path.join(filename+".png"),dpi=150)
    plt.close(fig)
    sys.stdout.write("%c[2K" % 27)
    sys.stdout.write("Processing file "+filename+"\r")
    sys.stdout.flush()
```

    Processing file MaxwellEvolCurvi_Playground_Ccodes/output/out80-00000240.txt

## Step 6.c: Generate visualization animation \[Back to [top](#toc)\]
$$\label{genvideo}$$

In the following step, [ffmpeg](http://ffmpeg.org) is used to generate an [mp4](https://en.wikipedia.org/wiki/MPEG-4) video file, which can be played directly from this Jupyter notebook.

```python
## VISUALIZATION ANIMATION, PART 2: Combine PNGs to generate movie ##

# https://stackoverflow.com/questions/14908576/how-to-remove-frame-from-matplotlib-pyplot-figure-vs-matplotlib-figure-frame
# https://stackoverflow.com/questions/23176161/animating-pngs-in-matplotlib-using-artistanimation

fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
ax.axis('off')

myimages = []

for i in range(len(file_list)):
    img = mgimg.imread(file_list[i]+".png")
    imgplot = plt.imshow(img)
    myimages.append([imgplot])

ani = animation.ArtistAnimation(fig, myimages, interval=100,  repeat_delay=1000)
plt.close()
ani.save(os.path.join(outdir,'Maxwell_ToroidalDipole.mp4'), fps=5,dpi=150)
```

```python
## VISUALIZATION ANIMATION, PART 3: Display movie as embedded HTML5 (see next cell) ##

# https://stackoverflow.com/questions/18019477/how-can-i-play-a-local-video-in-my-ipython-notebook
```

```python
# Embed video based on suggestion:
#  https://stackoverflow.com/questions/39900173/jupyter-notebook-html-cell-magic-with-python-variable
HTML("""

""")
```

# Step 7: Plot the numerical error, and confirm that it converges to zero with increasing numerical resolution (sampling) \[Back to [top](#toc)\]
$$\label{convergence}$$

```python
x_med, z_med, Ex__E_rel_med, Ey__E_rel_med, Ax__E_rel_med, Ay__E_rel_med = np.loadtxt(os.path.join(outdir,'out'+Nxx0_med+'.txt')).T #Transposed for easier unpacking

pl_xmin = -domain_size/2.
pl_xmax = +domain_size/2.
pl_ymin = -domain_size/2.
pl_ymax = +domain_size/2.

grid_x, grid_z = np.mgrid[pl_xmin:pl_xmax:100j, pl_ymin:pl_ymax:100j]
points_med = np.zeros((len(x_med), 2))
for i in range(len(x_med)):
    points_med[i][0] = x_med[i]
    points_med[i][1] = z_med[i]

grid_med = griddata(points_med, Ex__E_rel_med, (grid_x, grid_z), method='nearest')
grid_medcub = griddata(points_med, Ex__E_rel_med, (grid_x, grid_z), method='cubic')

plt.clf()
plt.title(r"Nxx0="+Nxx0_med+" Num. Err.: $\log_{10}|Ex|$ at $t$ = "+t_final)
plt.xlabel("x")
plt.ylabel("z")

fig_medcub = plt.imshow(grid_medcub.T, extent=(pl_xmin,pl_xmax, pl_ymin,pl_ymax))
cb = plt.colorbar(fig_medcub)
```

```python
x_low,z_low, EU0__E_rel_low, EU1__E_rel_low, AU0__E_rel_low, AU1__E_rel_low = np.loadtxt(os.path.join(outdir,'out'+Nxx0_low+'.txt')).T #Transposed for easier unpacking

points_low = np.zeros((len(x_low), 2))
for i in range(len(x_low)):
    points_low[i][0] = x_low[i]
    points_low[i][1] = z_low[i]

grid_low = griddata(points_low, EU0__E_rel_low, (grid_x, grid_z), method='nearest')

griddiff__low_minus__med = np.zeros((100,100))
griddiff__low_minus__med_1darray = np.zeros(100*100)
gridx_1darray_yeq0 = np.zeros(100)
grid_low_1darray_yeq0 = np.zeros(100)
grid_med_1darray_yeq0 = np.zeros(100)
count = 0
for i in range(100):
    for j in range(100):
        griddiff__low_minus__med[i][j] = grid_low[i][j] - grid_med[i][j]
        griddiff__low_minus__med_1darray[count] = griddiff__low_minus__med[i][j]
        if j==49:
            gridx_1darray_yeq0[i] = grid_x[i][j]
            grid_low_1darray_yeq0[i] = grid_low[i][j] + np.log10((float(Nxx0_low)/float(Nxx0_med))**4)
            grid_med_1darray_yeq0[i] = grid_med[i][j]
        count = count + 1

fig, ax = plt.subplots()
plt.title(r"4th-order Convergence of $E_x$ at t = "+t_final)
plt.xlabel("x")
plt.ylabel("log10(Absolute error)")

ax.plot(gridx_1darray_yeq0, grid_med_1darray_yeq0, 'k-', label='Nr = '+Nxx0_med)
ax.plot(gridx_1darray_yeq0, grid_low_1darray_yeq0, 'k--', label='Nr = '+Nxx0_low+', mult. by ('+Nxx0_low+'/'+Nxx0_med+')^4')
# ax.set_ylim([-8.5,0.5])

legend = ax.legend(loc='lower right', shadow=True, fontsize='x-large')
legend.get_frame().set_facecolor('C1')
plt.show()
```

# Step 8: Comparison Divergence Constrain Violation  \[Back to [top](#toc)\]
$$\label{div_e}$$

Here we calculate the violation quantity

$$
\mathcal{C} \equiv \nabla^i E_i,
$$

at each point on our grid (excluding the ghost zones) then calculate the normalized L2 norm over the entire volume via

\begin{align}
    \lVert C \rVert &= \left( \frac{\int C^2 d\mathcal{V}}{\int d\mathcal{V}} \right)^{1/2}.
\end{align}

```python
# Plotting the constraint violation
nrpy_div_low = np.loadtxt(os.path.join(outdir,'out-lowresolution.txt')).T
nrpy_div_med = np.loadtxt(os.path.join(outdir,'out-medresolution.txt')).T

plt.plot(nrpy_div_low[0]/domain_size, (nrpy_div_low[1]), 'k-',label='Nxx0 = '+Nxx0_low)
plt.plot(nrpy_div_med[0]/domain_size, (nrpy_div_med[1]), 'k--',label='Nxx0 = '+Nxx0_med)

plt.yscale('log')
plt.xlabel('Light Crossing Times')
plt.ylabel('||C||')
# plt.xlim(0,2.2)
# plt.ylim(1e-4, 1e-5)
plt.title('L2 Norm of the Divergence of E - '+par.parval_from_str("reference_metric::CoordSystem")+' Coordinates')
plt.legend(loc='center right')
plt.show()
```

# Step 9: Output this notebook to $\LaTeX$-formatted PDF file \[Back to [top](#toc)\]
$$\label{latex_pdf_output}$$

The following code cell converts this Jupyter notebook into a proper, clickable $\LaTeX$-formatted PDF file. After the cell is successfully run, the generated PDF may be found in the root NRPy+ tutorial directory, with filename
[Tutorial-Start_to_Finish-Solving_Maxwells_Equations_in_Vacuum-Curvilinear.pdf](Tutorial-Start_to_Finish-Solving_Maxwells_Equations_in_Vacuum-Curvilinear.pdf) (Note that clicking on this link may not work; you may need to open the PDF file through another means.)

```python
import cmdline_helper as cmd    # NRPy+: Multi-platform Python command-line interface
cmd.output_Jupyter_notebook_to_LaTeXed_PDF("Tutorial-Start_to_Finish-Solving_Maxwells_Equations_in_Vacuum-Curvilinear")
```

    Created Tutorial-Start_to_Finish-Solving_Maxwells_Equations_in_Vacuum-
        Curvilinear.tex, and compiled LaTeX file to PDF file Tutorial-
        Start_to_Finish-Solving_Maxwells_Equations_in_Vacuum-Curvilinear.pdf