# Hydrogen storage tank

A hydrogen-powered vehicle is storing fuel using three onboard cylindrical tanks, each with height 65 cm and diameter 28 cm. To refuel, the tanks are connected to a reservoir of hydrogen, supplied at 300 bar and ambient temperature; a fill valve connects the reservoir to the tanks. Initially, the storage tanks have hydrogen at 60 bar and ambient temperature. The ambient temperature is 25°C.

The mass flow rate through the valve is given by
\begin{equation}
\dot{m} = C_{\text{valve}} \sqrt{ P_{\text{supply}} - P } \;,
\end{equation}
where $C_{\text{valve}} = 2.68 \cdot 10^{-6} \, \frac{\text{kg}}{\text{s Pa}^{0.5}}$ is the valve coefficient.
The heat transfer rate from the tank walls to the hydrogen is given by
\begin{equation}
\dot{Q} = h_{\text{conv}} A_s \left( T_{\text{wall}} - T \right) \;,
\end{equation}
where $h_{\text{conv}} = 40 \frac{\text{W}}{\text{K m}^2}$ is the convection heat transfer coefficient.

The tanks are connected for filling for three minutes.

**Problem:** Determine the pressure and temperature of the hydrogen in the storage tanks as a function of time. Determine the mass of fuel added as a function of time.

```python
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
import cantera as ct

from pint import UnitRegistry
ureg = UnitRegistry()
Q_ = ureg.Quantity

from scipy.integrate import solve_ivp
```

First, let's specify the thermodynamic states of the supply and hydrogen in the tank (initially):

```python
temp_ambient = Q_(25, 'degC')

# supply of hydrogen has constant conditions
supply = ct.Hydrogen()
supply.TP = (
    temp_ambient.to('K').magnitude,
    Q_(300, 'bar').to('Pa').magnitude
    )

# tank properties
tank = {'number': 3,
        'height': Q_(65, 'cm'),
        'diameter': Q_(28, 'cm')
        }

volume_tank = np.pi * tank['height'] * tank['diameter']**2 / 4.0

# initial state in the tanks, fixed by temperature and pressure
temp_initial = temp_ambient
pres_initial = Q_(60, 'bar')
hydrogen = ct.Hydrogen()
hydrogen.TP = temp_initial.to('K').magnitude, pres_initial.to('Pa').magnitude
```

To figure out how the system changes with time, we can do a mass balance and energy balance for the control volume. The mass balance gives
\begin{equation}
\frac{dm}{dt} = \dot{m} = C_{\text{valve}} \sqrt{ P_{\text{supply}} - P(t) }
\end{equation}
and the energy balance gives
\begin{equation}
\dot{m} h_{\text{supply}} + \dot{Q} = \frac{dU}{dt} \;,
\end{equation}
which provide the governing equations for how this system evolves.

We can use mass ($m$) and total internal energy ($U$) as our state variables, and construct an ODE system for these variables. We need to be able to convert between internal system properties and these:
\begin{align}
m &= \frac{ N_{\text{tank}} V_{\text{tank}} }{v} \\
U &= u \, m \;.
\end{align}

We need to define a function that evaluates the time derivative system:

```python
def tank_rates(t, y, supply, tank, temp_ambient):
    '''Evaluates time derivatives for mass and internal energy (dm/dt and dU/dt)
    '''
    mass = Q_(y[0], 'kg')
    internal_energy = Q_(y[1], 'J')

    surface_area_tank = tank['number'] * (
        2 * np.pi*tank['diameter']**2 / 4.0 +
        np.pi*tank['diameter']*tank['height']
        )
    volume_tank = np.pi * tank['height'] * tank['diameter']**2 / 4.0

    # specify state based on mass and internal_energy
    specific_volume = (tank['number'] * volume_tank) / mass
    specific_internal_energy = internal_energy / mass
    f = ct.Hydrogen()
    f.UV = (
        specific_internal_energy.to('J/kg').magnitude,
        specific_volume.to('m^3/kg').magnitude
        )

    # evaluate dm/dt
    C_valve = Q_(2.68e-6, 'kg/(s*Pa**0.5)')
    mdot = C_valve * np.sqrt(Q_(supply.P, 'Pa') - Q_(f.P, 'Pa'))
    dmdt = mdot

    # evaluate dU/dt
    h_conv = Q_(40, 'W/(m**2 K)')
    Qdot = h_conv * surface_area_tank * (temp_ambient - Q_(f.T, 'K'))
    dUdt = (mdot * Q_(supply.h, 'J/kg')) + Qdot

    return [dmdt.to('kg/s').magnitude, dUdt.to('J/s').magnitude]
```

**Choice of method:** Here we use the `'BDF'` for the `method` argument, which tells the `solve_ivp()` function to use an implicit integration method based on backward differentiation formula. Other methods [are available](https://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.solve_ivp.html) and may be more efficient for some problems, but this is fairly accurate and can handle stiffness in the ODE system.

Finally, we can calcluate the initial mass and internal energy, then integrate over the filling time:

```python
# initial system mass and (total) internal energy
mass_initial = (tank['number'] * volume_tank) / Q_(hydrogen.v, 'm^3/kg')
int_energy_initial = mass_initial * Q_(hydrogen.u, 'J/kg')

# Integrate over 3 minutes,
# using backward differentiation formula (BDF) method
sol = solve_ivp(
    tank_rates, [0, 60*3],
    [mass_initial.to('kg').magnitude, int_energy_initial.to('J').magnitude],
    args=(supply, tank, temp_ambient,),
    method='BDF'
    )
```

The integration was successful (it did not report an error), so now plot temperature and pressure of the tank as a function of time.

We have the system mass and internal energy as a function of time, and we'll need to use those to specify the system at each state to obtain its properties as a function of time.

```python
pressures = np.zeros(len(sol.y[0]))
temperatures = np.zeros(len(sol.y[0]))

for idx in range(len(sol.y[0])):
    mass = Q_(sol.y[0][idx], 'kg')
    internal_energy = Q_(sol.y[1][idx], 'J')

    volume_tank = np.pi * tank['height'] * tank['diameter']**2 / 4.0

    # calculate specific volume and specific internal energy
    # based on mass and (total) internal energys
    specific_volume = (tank['number'] * volume_tank) / mass
    specific_internal_energy = internal_energy / mass
    f = ct.Hydrogen()
    f.UV = (
        specific_internal_energy.to('J/kg').magnitude,
        specific_volume.to('m^3/kg').magnitude
        )

    pressures[idx] = f.P
    temperatures[idx] = f.T

pressures *= ureg.Pa
temperatures *= ureg.K

fig, ax1 = plt.subplots(figsize=(5, 3))

color = 'red'
ax1.set_xlabel('Time (s)')
ax1.set_ylabel('Pressure (bar)', color=color)
ax1.plot(sol.t, pressures.to('bar').magnitude, color=color)
ax1.tick_params(axis='y', labelcolor=color)
ax1.axis([0, 180, 50, 300])
ax1.grid(True)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'blue'
# we already handled the x-label with ax1
ax2.set_ylabel('Temperature (°C)', color=color)
ax2.plot(sol.t, temperatures.to('degC').magnitude, color=color)
ax2.tick_params(axis='y', labelcolor=color)
ax2.axis([0, 180, 20, 120])
ax2.grid(True)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()
```

    <IPython.core.display.Javascript object>

Now plot the mass of fuel added as a function of time:

```python
mass_added = sol.y[0] - mass_initial.to('kg').magnitude
fig, ax = plt.subplots(figsize=(5, 3))
ax.plot(sol.t, mass_added)
plt.xlabel('Time (s)')
plt.axis([0, 180, 0, 1.6])
plt.ylabel('Fuel added (kg)')
plt.grid(True)
fig.tight_layout()
plt.show()
```

    <IPython.core.display.Javascript object>


Reference: This is made after SEIR_COVID19 https://github.com/alsnhll/SEIR_COVID19

## Model

### Equations

\begin{equation}
\begin{split}
\dot{S} &= -\beta_1 I_1 S -\beta_2 I_2 S - \beta_3 I_3 S\\
\dot{E} &=\beta_1 I_1 S +\beta_2 I_2 S + \beta_3 I_3 S - a E \\
\dot{I_1} &= a E - \gamma_1 I_1 - p_1 I_1 \\
\dot{I_2} &= p_1 I_1 -\gamma_2 I_2 - p_2 I_2 \\
\dot{I_3} & = p_2 I_2 -\gamma_3 I_3 - \mu I_3 \\
\dot{R} & = \gamma_1 I_1 + \gamma_2 I_2 + \gamma_3 I_3 \\
\dot{D} & = \mu I_3
\end{split}
\end{equation}

### Variables
* $S$: Susceptible individuals
* $E$: Exposed individuals - infected but not yet infectious or symptomatic
* $I_i$: Infected individuals in severity class $i$. Severity increaes with $i$ and we assume individuals must pass through all previous classes
  * $I_1$: Mild infection (hospitalization not required)
  * $I_2$: Severe infection (hospitalization required)
  * $I_3$: Critical infection (ICU required)
* $R$: individuals who have recovered from disease and are now immune
* $D$: Dead individuals
* $N=S+E+I_1+I_2+I_3+R+D$ Total population size (constant)

### Parameters
* $\beta_i$ rate at which infected individuals in class $I_i$ contact susceptibles and infect them
* $a$ rate of progression from the exposed to infected class
* $\gamma_i$ rate at which infected individuals in class $I_i$ recover from disease and become immune
* $p_i$ rate at which infected individuals in class $I_i$ progress to class $I_{I+1}$
* $\mu$ death rate for individuals in the most severe stage of disease

### Basic reproductive ratio

Idea: $R_0$ is the sum of
1. the average number of secondary infections generated from an individual in stage $I_1$
2. the probability that an infected individual progresses to $I_2$ multiplied by the average number of secondary infections generated from an individual in stage $I_2$
3.  the probability that an infected individual progresses to $I_3$ multiplied by the average number of secondary infections generated from an individual in stage $I_3$

\begin{equation}
\begin{split}
R_0 & = N\frac{\beta_1}{p_1+\gamma_1} + \frac{p_1}{p_1 + \gamma_1} \left( \frac{N \beta_2}{p_2+\gamma_2} + \frac{p_2}{p_2 + \gamma_2} \frac{N \beta_3}{\mu+\gamma_3}\right)\\
&= N\frac{\beta_1}{p_1+\gamma_1} \left(1 + \frac{p_1}{p_2 + \gamma_2}\frac{\beta_2}{\beta_1} \left( 1 + \frac{p_2}{\mu + \gamma_3} \frac{\beta_3}{\beta_2} \right) \right)
\end{split}
\end{equation}

```
from google.colab import drive
drive.mount('/content/drive')
```

    Mounted at /content/drive

```
cd /content/drive/My Drive/DMC20_Data/c3ai
```

    /content/drive/My Drive/DMC20_Data/c3ai

```
import numpy as np
# !pip install -q bokeh==2.2.3
from bokeh.layouts import row, column
from bokeh.models import CustomJS, Slider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.embed import components

x = np.linspace(0, 10, 500)
y = np.sin(x)

source = ColumnDataSource(data=dict(x=x, y=y))

plot = figure(y_range=(-10, 10), plot_width=400, plot_height=400)

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

amp_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Amplitude")
freq_slider = Slider(start=0.1, end=10, value=1, step=.1, title="Frequency")
phase_slider = Slider(start=0, end=6.4, value=0, step=.1, title="Phase")
offset_slider = Slider(start=-5, end=5, value=0, step=.1, title="Offset")

callback = CustomJS(args=dict(source=source, amp=amp_slider, freq=freq_slider, phase=phase_slider, offset=offset_slider),
                    code="""
    const data = source.data;
    const A = amp.value;
    const k = freq.value;
    const phi = phase.value;
    const B = offset.value;
    const x = data['x']
    const y = data['y']
    for (var i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }
    source.change.emit();
""")

amp_slider.js_on_change('value', callback)
freq_slider.js_on_change('value', callback)
phase_slider.js_on_change('value', callback)
offset_slider.js_on_change('value', callback)

layout = row(
    plot,
    column(amp_slider, freq_slider, phase_slider, offset_slider),
)

output_file("slider.html", title="slider.py example")

show(layout)

```

```
script, div = components(layout)
```

```
import numpy as np, matplotlib.pyplot as plt
from scipy.integrate import odeint
```

```
#Defining the differential equations

#Don't track S because all variables must add up to 1
#include blank first entry in vector for beta, gamma, p so that indices align in equations and code.
#In the future could include recovery or infection from the exposed class (asymptomatics)

def seir(y,t,b,a,g,p,u,N):
    dy=[0,0,0,0,0,0]
    S=N-sum(y);
    dy[0]=np.dot(b[1:3],y[1:3])*S-a*y[0] # E
    dy[1]= a*y[0]-(g[1]+p[1])*y[1] #I1
    dy[2]= p[1]*y[1] -(g[2]+p[2])*y[2] #I2
    dy[3]= p[2]*y[2] -(g[3]+u)*y[3] #I3
    dy[4]= np.dot(g[1:3],y[1:3]) #R
    dy[5]=u*y[3] #D

    return dy
```

```
# Define parameters based on clinical observations

#I will add sources soon
# https://github.com/midas-network/COVID-19/tree/master/parameter_estimates/2019_novel_coronavirus

IncubPeriod=5  #Incubation period, days
DurMildInf=10 #Duration of mild infections, days
FracMild=0.8  #Fraction of infections that are mild
FracSevere=0.15 #Fraction of infections that are severe
FracCritical=0.05 #Fraction of infections that are critical
CFR=0.02 #Case fatality rate (fraction of infections resulting in death)
TimeICUDeath=7 #Time from ICU admission to death, days
DurHosp=11 #Duration of hospitalization, days

```

```
# Define parameters and run ODE

N=1000
b=np.zeros(4) #beta
g=np.zeros(4) #gamma
p=np.zeros(3)

a=1/IncubPeriod

u=(1/TimeICUDeath)*(CFR/FracCritical)
g[3]=(1/TimeICUDeath)-u

p[2]=(1/DurHosp)*(FracCritical/(FracCritical+FracSevere))
g[2]=(1/DurHosp)-p[2]

g[1]=(1/DurMildInf)*FracMild
p[1]=(1/DurMildInf)-g[1]

#b=2e-4*np.ones(4) # all stages transmit equally
b=2.5e-4*np.array([0,1,0,0]) # hospitalized cases don't transmit

#Calculate basic reproductive ratio
R0=N*((b[1]/(p[1]+g[1]))+(p[1]/(p[1]+g[1]))*(b[2]/(p[2]+g[2])+ (p[2]/(p[2]+g[2]))*(b[3]/(u+g[3]))))
print("R0 = {0:4.1f}".format(R0))
```

    R0 =  2.5

```
print(b)
print(a)
print(g)
print(p)
print(u)
```

    [0.      0.00025 0.      0.     ]
    0.2
    [0.         0.08       0.06818182 0.08571429]
    [0.         0.02       0.02272727]
    0.057142857142857134

```
tmax=365
tvec=np.arange(0,tmax,0.1)
ic=np.zeros(6)
ic[0]=1

soln=odeint(seir,ic,tvec,args=(b,a,g,p,u,N))
soln=np.hstack((N-np.sum(soln,axis=1,keepdims=True),soln))

plt.figure(figsize=(13,5))
plt.subplot(1,2,1)
plt.plot(tvec,soln)
plt.xlabel("Time (days)")
plt.ylabel("Number per 1000 People")
plt.legend(("S","E","I1","I2","I3","R","D"))
plt.ylim([0,1000])

#Same plot but on log scale
plt.subplot(1,2,2)
plt.plot(tvec,soln)
plt.semilogy()
plt.xlabel("Time (days)")
plt.ylabel("Number per 1000 People")
plt.legend(("S","E","I1","I2","I3","R","D"))
plt.ylim([1,1000])
#plt.tight_layout()
```

```
import numpy as np
# !pip install -q bokeh==2.2.3
from bokeh.layouts import row, column
from bokeh.models import CustomJS, Slider
from bokeh.plotting import figure, output_file, show, ColumnDataSource
from bokeh.embed import components

# x = np.linspace(0, 10, 500)
tvec=np.arange(0,tmax,0.1)
# y = np.sin(x)
soln=odeint(seir,ic,tvec,args=(b,a,g,p,u,N))
soln=np.hstack((N-np.sum(soln,axis=1,keepdims=True),soln))

source = ColumnDataSource(data=dict(x=tvec, y=soln))

plot = figure(plot_width=400, plot_height=400)

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

IncubPeriod_slider = Slider(start=0.1, end=10, value=1, step=.1, title="IncubPeriod")
DurMildInf_slider = Slider(start=0.1, end=10, value=1, step=.1, title="DurMildInf")
FracMild_slider = Slider(start=0, end=6.4, value=0, step=.1, title="FracMild")
TimeICUDeath_slider = Slider(start=-5, end=5, value=0, step=.1, title="TimeICUDeath")

# IncubPeriod=5  #Incubation period, days
# DurMildInf=10 #Duration of mild infections, days
# FracMild=0.8  #Fraction of infections that are mild
# FracSevere=0.15 #Fraction of infections that are severe
# FracCritical=0.05 #Fraction of infections that are critical
# CFR=0.02 #Case fatality rate (fraction of infections resulting in death)
# TimeICUDeath=7 #Time from ICU admission to death, days
# DurHosp=11 #Duration of hospitalization, days

callback = CustomJS(args=dict(source=source, IncubPeriod=IncubPeriod_slider, DurMildInf=DurMildInf_slider,
                              FracMild=FracMild_slider, TimeICUDeath=TimeICUDeath_slider),
                    code="""
    const data = source.data;
    const A = amp.value;
    const k = freq.value;
    const phi = phase.value;
    const B = offset.value;
    const x = data['x']
    const y = data['y']
    for (var i = 0; i < x.length; i++) {
        y[i] = B + A*Math.sin(k*x[i]+phi);
    }

    N=1000
    b=np.zeros(4)
    g=np.zeros(4)
    p=np.zeros(3)

    a=1/IncubPeriod

    u=(1/TimeICUDeath)*(CFR/FracCritical)
    g[3]=(1/TimeICUDeath)-u

    p[2]=(1/DurHosp)*(FracCritical/(FracCritical+FracSevere))
    g[2]=(1/DurHosp)-p[2]

    g[1]=(1/DurMildInf)*FracMild
    p[1]=(1/DurMildInf)-g[1]

    b=2.5e-4*np.array([0,1,0,0]) # hospitalized cases don't transmit

    tvec=np.arange(0,tmax,0.1)
    soln=odeint(seir,ic,tvec,args=(b,a,g,p,u,N))
    soln=np.hstack((N-np.sum(soln,axis=1,keepdims=True),soln))

    source.change.emit();
""")

IncubPeriod_slider.js_on_change('value', callback)
DurMildInf_slider.js_on_change('value', callback)
FracMild_slider.js_on_change('value', callback)
TimeICUDeath_slider.js_on_change('value', callback)

layout = row(
    plot,
    column(IncubPeriod_slider, DurMildInf_slider, FracMild_slider, TimeICUDeath_slider),
)

output_file("slider.html", title="slider.py example")

show(layout)

```

```
# !pip install pscript
```

    Collecting pscript
      Downloading https://files.pythonhosted.org/packages/c5/bc/be9b0c7a26cdf95065a957bf7124426db96ed54269fd53d31de75a55eb8e/pscript-0.7.4-py3-none-any.whl (126kB)
         |████████████████████████████████| 133kB 5.1MB/s
    Installing collected packages: pscript
    Successfully installed pscript-0.7.4

```
# Set up the plots and their data source
source = ColumnDataSource(data=dict(T=[], S=[], I=[], R=[]))

SIR_plot = figure(plot_width=400, plot_height=400)
SIR_plot.line('T', 'S', source=source, legend_label="S", line_width=3, line_alpha=0.6, color='blue')
SIR_plot.line('T', 'I', source=source, legend_label="I", line_width=3, line_alpha=0.6, color='orange')
SIR_plot.line('T', 'R', source=source, legend_label="R", line_width=3, line_alpha=0.6, color='green')

I_plot = figure(plot_width=400, plot_height=400)
I_plot.line('T', 'I', source=source, line_width=3, line_alpha=0.6, color='orange')
# I_plot.xlabel('test')
I_plot.xaxis.axis_label = 'New xlabel'

# declare the interactive interface elements
trans_rate = Slider(start=0.01, end=0.4, value=0.3, step=.01, title="transmission rate ")
recov_rate = Slider(start=0.01, end=0.4, value=0.1, step=.01, title="recovery rate")

I_init = Slider(start=0.01, end=0.1, value=0.05, step=.002, title="initial infected [proportion] ")
max_time = Slider(start=10, end=200, value=50, step=1, title="time range [days] ")

callback = CustomJS(args=dict(source=source, I_init=I_init, max_time=max_time,
                              trans_rate=trans_rate, recov_rate=recov_rate),
                    code="""\
    let i = I_init.value;
    let s = 1-i;
    let r = 0;
    const bet = trans_rate.value;
    const gam = recov_rate.value;
    let tf = max_time.value;
    const dt = 0.1;
    const tlst = source.data.T = [0];
    const slst = source.data.S = [s];
    const ilst = source.data.I = [i];
    const rlst = source.data.R = [r];

    function odefunc(t,sir) {
        let tr = bet*sir[0]*sir[1];
        let rc = gam*sir[1];
        return [-tr, tr-rc, rc];
    }
    let sir = [s,i,r];
    for (let t = 0; t < tf; t+=dt) {
        sir = RK4Step(t,sir,dt);
        tlst.push(t+dt);
        slst.push(sir[0]);
        ilst.push(sir[1]);
        rlst.push(sir[2]);
    }
    source.change.emit();

    function axpy(a,x,y) {
        // returns a*x+y for arrays x,y of the same length
        var k = y.length >>> 0;
        var res = new Array(k);
        while(k-->0) { res[k] = y[k] + a*x[k]; }
        return res;
    }

    function RK4Step(t,y,h) {
        var k0 = odefunc(t      ,               y );
        var k1 = odefunc(t+0.5*h, axpy(0.5*h,k0,y));
        var k2 = odefunc(t+0.5*h, axpy(0.5*h,k1,y));
        var k3 = odefunc(t+    h, axpy(    h,k2,y));
        // ynext = y+h/6*(k0+2*k1+2*k2+k3);
        return axpy(h/6,axpy(1,k0,axpy(2,k1,axpy(2,k2,k3))),y);
    }

""")
trans_rate.js_on_change('value', callback)
recov_rate.js_on_change('value', callback)

I_init.js_on_change('value', callback)
max_time.js_on_change('value', callback)

# generate the layout

parameters_panel = column(trans_rate, recov_rate)
initials_panel = column(I_init,max_time)

plots = row(SIR_plot, I_plot)
inputs = row(parameters_panel, initials_panel)

simulation = column(plots, inputs)

output_file("slider2.html", title="slider.py example")
show(simulation)

```

```
script, div = components(simulation)
```

```
script
```

    '\n'

```
# get observed growth rate r (and doubling time) for a particular variable between selected time points
#(all infected classes eventually grow at same rate during early infection)

#Don't have a simple analytic formula for r for this model due to the complexity of the stages

def growth_rate(tvec,soln,t1,t2,i):
  i1=np.where(tvec==t1)[0][0]
  i2=np.where(tvec==t2)[0][0]
  r=(np.log(soln[i2,1])-np.log(soln[i1,1]))/(t2-t1)
  DoublingTime=np.log(2)/r

  return r, DoublingTime
```

```
(r,DoublingTime)=growth_rate(tvec,soln,10,20,1)
print("The epidemic growth rate is = {0:4.2f} per day and the doubling time {1:4.1f} days ".format(r,DoublingTime))
```

    The epidemic growth rate is = 0.08 per day and the doubling time  9.0 days

### Repeat but with a social distancing measure that reduces transmission rate

```
bSlow=0.6*b
R0Slow=N*((bSlow[1]/(p[1]+g[1]))+(p[1]/(p[1]+g[1]))*(bSlow[2]/(p[2]+g[2])+ (p[2]/(p[2]+g[2]))*(bSlow[3]/(u+g[3]))))

solnSlow=odeint(seir,ic,tvec,args=(bSlow,a,g,p,u,N))
solnSlow=np.hstack((N-np.sum(solnSlow,axis=1,keepdims=True),solnSlow))

plt.figure(figsize=(13,5))
plt.subplot(1,2,1)
plt.plot(tvec,solnSlow)
plt.xlabel("Time (days)")
plt.ylabel("Number per 1000 People")
plt.legend(("S","E","I1","I2","I3","R","D"))
plt.ylim([0,1000])

#Same plot but on log scale
plt.subplot(1,2,2)
plt.plot(tvec,solnSlow)
plt.semilogy()
plt.xlabel("Time (days)")
plt.ylabel("Number per 1000 People")
plt.legend(("S","E","I1","I2","I3","R","D"))
plt.ylim([1,1000])

(rSlow,DoublingTimeSlow)=growth_rate(tvec,solnSlow,30,40,1)

plt.show()
print("R0 under intervention = {0:4.1f}".format(R0Slow))
print("The epidemic growth rate is = {0:4.2f} per day and the doubling time {1:4.1f} days ".format(rSlow,DoublingTimeSlow))
```

#### Compare epidemic growth with and without intervention

```
### All infectious cases (not exposed)

plt.figure(figsize=(13,5))
plt.subplot(1,2,1)
plt.plot(tvec,np.sum(soln[:,2:5],axis=1,keepdims=True))
plt.plot(tvec,np.sum(solnSlow[:,2:5],axis=1,keepdims=True))
plt.xlabel("Time (days)")
plt.ylabel("Number per 1000 People")
plt.legend(("No intervention","Intervention"))
plt.ylim([0,1000])
plt.title('All infectious cases')
```

## COVID19 Cases vs Hospital Capacity

Depending on the severity ($I_i$) stage of COVID-19 infection, patients need different level of medical care.

Individuals in $I_1$ have "mild" infection, meaning they have cough/fever/other flu-like symptoms and may also have mild pneumonia. Mild pneumonia does not require hospitalization, although in many outbreak locations like China and South Korea all symptomatic patients are being hospitalized. This is likely to reduce spread and to monitor these patients in case they rapidly progress to worse outcome. However, it is a huge burden on the health care system.

Individuals in $I_2$ have "severe" infection, which is categorized medically as having any of the following: "dyspnea, respiratory frequency 30/min, blood oxygen saturation 93%, partial pressure of arterial oxygen to fraction of inspired oxygen ratio $<$300, lung infiltrates $>$50% within 24 to 48 hours". These individuals require hospitalization but can be treated on regular wards. They may require supplemental oxygen.

Individuals in $I_3$ have "critical" infection, which is categorized as having any of the following: "respiratory failure, septic shock, and/or multiple organ dysfunction or failure".
They require ICU-level care, generally because they need mechanical ventilation.

We consider different scenarios for care requirements. One variation between scenarios is whether we include hospitalization for all individuals or only those with severe or critical infection. Another is the care of critical patients. If ICUs are full, hospitals have protocols developed for pandemic influenza to provide mechanical ventilation outside regular ICU facility and staffing requirements. Compared to "conventional" ventilation protocols, there are "contingency" and "crisis" protocols that can be adopted to increase patient loads. These protocols involve increasing patient:staff ratios, using non-ICU beds, and involving non-critical care specialists in patient care.

```
#Parameter sources: https://docs.google.com/spreadsheets/d/1zZKKnZ47lqfmUGYDQuWNnzKnh-IDMy15LBaRmrBcjqE

# All values are adjusted for increased occupancy due to flu season

AvailHospBeds=2.6*(1-0.66*1.1) #Available hospital beds per 1000 ppl in US based on total beds and occupancy
AvailICUBeds=0.26*(1-0.68*1.07) #Available ICU beds per 1000 ppl in US, based on total beds and occupancy. Only counts adult not neonatal/pediatric beds
ConvVentCap=0.062 #Estimated excess # of patients who could be ventilated in US (per 1000 ppl) using conventional protocols
ContVentCap=0.15 #Estimated excess # of patients who could be ventilated in US (per 1000 ppl) using contingency protocols
CrisisVentCap=0.42 #Estimated excess # of patients who could be ventilated in US (per 1000 ppl) using crisis protocols

```

### Assumptions 1
* Only severe or critical cases go to the hospital
* All critical cases require ICU care and mechanical ventilation

```
NumHosp=soln[:,3]+soln[:,4]
NumICU=soln[:,4]

plt.figure(figsize=(13,4.8))
plt.subplot(1,2,1)
plt.plot(tvec,NumHosp)
plt.plot(np.array((0, tmax)),AvailHospBeds*np.ones(2),color='C0',linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing Hospitalization","Available Hospital Beds"))
ipeakHosp=np.argmax(NumHosp) #find peak
peakHosp=10*np.ceil(NumHosp[ipeakHosp]/10)#find time at peak
plt.ylim([0,peakHosp])

plt.subplot(1,2,2)
plt.plot(tvec,NumICU,color='C1')
plt.plot(np.array((0, tmax)),AvailICUBeds*np.ones(2),color='C1',linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing ICU","Available ICU Beds"))
ipeakICU=np.argmax(NumICU) #find peak
peakICU=10*np.ceil(NumICU[ipeakICU]/10)#find time at peak
plt.ylim([0,peakICU])
plt.ylim([0,10])

#Find time when hospitalized cases = capacity
icross=np.argmin(np.abs(NumHosp[0:ipeakHosp]-AvailHospBeds)) #find intersection before peak
TimeFillBeds=tvec[icross]

#Find time when ICU cases = capacity
icross=np.argmin(np.abs(NumICU[0:ipeakICU]-AvailICUBeds)) #find intersection before peak
TimeFillICU=tvec[icross]

plt.show()
print("Hospital and ICU beds are filled by COVID19 patients after {0:4.1f} and {1:4.1f} days".format(TimeFillBeds,TimeFillICU))
```

Note that we have not taken into account the limited capacity in the model itself. If hospitals are at capacity, then the death rate will increase, since individuals with severe and critical infection will often die without medical care. The transmission rate will probably also increase, since any informal home-care for these patients will likely not include the level of isolation/precautions used in a hospital.

#### Allow for mechanical ventilation outside of ICUs using contingency or crisis capacity

```
plt.plot(tvec,NumICU)
plt.plot(np.array((0, tmax)),ConvVentCap*np.ones(2),linestyle=":")
plt.plot(np.array((0, tmax)),ContVentCap*np.ones(2),linestyle=":")
plt.plot(np.array((0, tmax)),CrisisVentCap*np.ones(2),linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing Mechanical Ventilation","Conventional Capacity","Contingency Capacity","Crisis Capacity"))
plt.ylim([0,peakICU])
plt.ylim([0,10])

#Find time when ICU cases = conventional capacity
icrossConv=np.argmin(np.abs(NumICU[0:ipeakICU]-ConvVentCap)) #find intersection before peak
TimeConvCap=tvec[icrossConv]
icrossCont=np.argmin(np.abs(NumICU[0:ipeakICU]-ContVentCap)) #find intersection before peak
TimeContCap=tvec[icrossCont]
icrossCrisis=np.argmin(np.abs(NumICU[0:ipeakICU]-CrisisVentCap)) #find intersection before peak
TimeCrisisCap=tvec[icrossCrisis]

plt.show()
print("Capacity for mechanical ventilation is filled by COVID19 patients after {0:4.1f} (conventional), {1:4.1f} (contingency) and {2:4.1f} (crisis) days".format(TimeConvCap,TimeContCap,TimeCrisisCap))
```

Compare to the case with intervention

```
NumHospSlow=solnSlow[:,3]+solnSlow[:,4]
NumICUSlow=solnSlow[:,4]

plt.figure(figsize=(13,4.8))
plt.subplot(1,2,1)
plt.plot(tvec,NumHosp)
plt.plot(tvec,NumHospSlow,color='C0',linestyle="--")
plt.plot(np.array((0, tmax)),AvailHospBeds*np.ones(2),color='C0',linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing Hospitalization","Cases Needing Hospitalization (Intervetion)","Available Hospital Beds"))
plt.ylim([0,peakHosp])

plt.subplot(1,2,2)
plt.plot(tvec,NumICU,color='C1')
plt.plot(tvec,NumICUSlow,color='C1',linestyle="--")
plt.plot(np.array((0, tmax)),AvailICUBeds*np.ones(2),color='C1',linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing ICU","Cases Needing ICU (Intervetion)","Available ICU Beds"))
plt.ylim([0,peakICU])

#Find time when hospitalized cases = capacity
ipeakHospSlow=np.argmax(NumHospSlow) #find peak
icross=np.argmin(np.abs(NumHospSlow[0:ipeakHospSlow]-AvailHospBeds)) #find intersection before peak
TimeFillBedsSlow=tvec[icross]

#Find time when ICU cases = capacity
ipeakICUSlow=np.argmax(NumICUSlow) #find peak
icross=np.argmin(np.abs(NumICUSlow[0:ipeakICU]-AvailICUBeds)) #find intersection before peak
TimeFillICUSlow=tvec[icross]

plt.show()
print("With intervention, hospital and ICU beds are filled by COVID19 patients after {0:4.1f} and {1:4.1f} days".format(TimeFillBedsSlow,TimeFillICUSlow))
```

And for expanded mechanical ventilation capacity

```
plt.plot(tvec,NumICU)
plt.plot(tvec,NumICUSlow)
plt.plot(np.array((0, tmax)),ConvVentCap*np.ones(2),linestyle=":")
plt.plot(np.array((0, tmax)),ContVentCap*np.ones(2),linestyle=":")
plt.plot(np.array((0, tmax)),CrisisVentCap*np.ones(2),linestyle=":")
plt.xlabel("Time (days)")
plt.ylabel("Number Per 1000 People")
plt.legend(("Cases Needing Mechanical Ventilation","Cases Needing Mechanical Ventilation (Intervention)","Conventional Capacity","Contingency Capacity","Crisis Capacity"))
plt.ylim([0,peakICU])

#Find time when ICU cases = conventional capacity (with intervention)
icrossConvSlow=np.argmin(np.abs(NumICUSlow[0:ipeakICUSlow]-ConvVentCap)) #find intersection before peak
TimeConvCapSlow=tvec[icrossConvSlow]
icrossContSlow=np.argmin(np.abs(NumICUSlow[0:ipeakICUSlow]-ContVentCap)) #find intersection before peak
TimeContCapSlow=tvec[icrossContSlow]
icrossCrisisSlow=np.argmin(np.abs(NumICUSlow[0:ipeakICUSlow]-CrisisVentCap)) #find intersection before peak
TimeCrisisCapSlow=tvec[icrossCrisisSlow]

plt.show()
print("Capacity for mechanical ventilation is filled by COVID19 patients after {0:4.1f} (conventional), {1:4.1f} (contingency) and {2:4.1f} (crisis) days".format(TimeConvCapSlow,TimeContCapSlow,TimeCrisisCapSlow))
```

Interpretation: While interventions that reduce infectiousness do "flatten the curve", cases are still WAY over hospital capacity. There is no way to get anywhere close to staying under hospital bed capacity or mechanical ventilation capacity without reducing $R_0<1$.

### Assumptions 2
* All cases go to the hospital
* All critical cases require ICU care and mechanical ventilation

Note: No point running this scenario because it would be even more extreme than Assumption 1 (mild cases stayed home) and Assumption 1 already lead to rapid overlow of hospital resources

### Assumptions 3
* Only severe or critical cases go to the hospital
* All critical cases require ICU care and mechanical ventilation
* When hospital capacity is exceed, individual dies

Note: Could be used to simulate expected increases in death if capacity exceeded

## Alternative Models

To be continued, including
* Assuming ~30% of cases are asymptomatic (as seen on Diamond Princess) (This would lead to a re-interpretation of the reported rates of severe and critical infection, so the prevalence of these stages would decrease)
* A parallel instead of series model of disease course (because it is unclear if it is realistic that individuals who pass through the mild stage on the way to a severe state spend as long in the mild stage as individuals who never progress)
* Including pre-symptomatic transmission (for about last ~2 days of exposed period, as estimated in some studies)


```python
# HIDDEN
from datascience import *
from prob140 import *
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
%matplotlib inline
import math
from scipy import stats
from sympy import *
init_printing()
```

## Conditioning and Independence ##

The key to recognizing that a density is a multivariate normal density is spotting that the function in the exponent is a quadratic.

This observation leads to an important result: If $\mathbf{X}$ is multivariate normal then the conditional distribution of any subset of elements given any other subset of elements is also multivariate normal.

You can see this by examining the exponents in the densities.

To calculate the conditional density, we have to divide the joint density by the density of the given variables.
- The numerator has a quadratic in the exponent.
- The denominator has a quadratic in the exponent.
- In the exponent of the quotient there is the difference between the quadratics, which is also a quadratic.

Therefore, the conditional density is multivariate normal.

In the next chapter, we will develop a way of identifying the parameters of the resulting multivariate normal distribution. For now, you can use `SymPy` to find the density numerically. Here is an example in two dimensions.

### Conditional Density by `SymPy`##
Let $\mathbf{X} = [X_1, X_2]^T$ be bivariate normal with mean $\mathbf{0}$ and covariance matrix $\boldsymbol{\Sigma}$ given below. You can assume $\boldsymbol{\Sigma}$ is positive definite – in the next chapter you will see how to check.

```python
# A covariance matrix

Sigma = Matrix([[4, 3.6], [3.6, 9]])
Sigma
```

Then $X_1$ is normal $(0, 2^2)$, $X_2$ is normal $(0, 3^2)$, and $Cov(X_1, X_2) = 3.6$. In the cells below we have defined the density of $\mathbf{X}$ in the `SymPy` function `f_X`.

```python
# Centered multivariate normal density function
# with covariance matrix Sigma

declare('x_1')
declare('x_2')
x = Matrix([x_1, x_2])

f_X = (1/((2*pi) * (Sigma.det()**0.5))) * exp(-0.5 * (x.T * Sigma.inv() * x))
```

```python
f_X
```

Note the quadratic in the exponent.

Now suppose we want to find the conditional density of $X_2$ given $X_1 = x_1$. The density of $X_1$ at $x_1$ is

```python
1/(((2 * pi) ** 0.5) * 2) * exp(-0.5 * (x_1 ** 2)/(2**2))
```

You can double check this by using `SymPy` to integrate the joint density. As in lab, we have used the `rearrange_1` function to simplify the expression. You can see that it is exactly the same as the normal density above.

```python
f_X_1 = Integral(f_X, (x_2, -oo, oo)).doit()
rearrange_1(f_X_1)
```

```python
def divide(a, b):
    return a * (b ** -1)
```

```python
simplify(divide(f_X, f_X_2))
```

### Independence and the Covariance Matrix ###
If the elements of $\mathbf{X}$ are mutually independent then $Cov(X_i, X_j) = 0$ for all $i \ne j$ and hence the covariance matrix $\boldsymbol{\Sigma}$ is a diagonal matrix and the $i$th diagonal element is $Var(X_i)$.

In the other direction, for general joint distributions zero covariance doesn't imply independence, and pairwise independence doesn't imply mutual independence. But the multivariate normal is a wonderful distribution:

If $\mathbf{X}$ is multivariate normal and its elements are pairwise uncorrelated – that is, $Cov(X_i, X_j) = 0$ for all
$i \ne j$ – then the elements of $\mathbf{X}$ are mutually independent.

That is, **for the multivariate normal distribution, pairwise uncorrelatedness is the same as mutual independence.**

This is easy to see from the form of the density of $\mathbf{X}$. If $\boldsymbol{\Sigma}$ is a diagonal matrix then so is $\boldsymbol{\Sigma}^{-1}$. The $i$th diagonal element of $\boldsymbol{\Sigma}^{-1}$ is $1/\sigma_i^2$ where $\sigma_i^2 = Var(X_i)$. So

$$
(\mathbf{x} - \boldsymbol{\mu})\boldsymbol{\Sigma}^{-1} (\mathbf{x} - \boldsymbol{\mu}) ~ = ~ \sum_{i=1}^n \frac{(x_i - \boldsymbol{\mu}(i))^2}{\sigma_i^2}
$$
and therefore
$$
\exp\big{(} -\frac{1}{2} (\mathbf{x} - \boldsymbol{\mu})\boldsymbol{\Sigma}^{-1} (\mathbf{x} - \boldsymbol{\mu}) \big{)} ~ = ~ \prod_{i=1}^n \exp\big{(}-\frac{1}{2} \big{(}\frac{x_i - \boldsymbol{\mu}(i)}{\sigma_i}\big{)}^2\big{)}
$$

In the constant of integration, $\det(\boldsymbol{\Sigma}) = \sigma_1^2 \sigma_2^2 \cdots \sigma_n^2$.

Therefore the density of $\mathbf{X}$ is the product of the marginal normal densities.

### Indepedence of Sum and Difference ###
Let $\mathbf{X} = [X_1, X_2]^T$ have a bivariate normal distribution. Let $S = X_1 + X_2$ and $D = X_1 - X_2$. We know that $S$ and $D$ have a bivariate normal distribution and that

$$
Cov(S, D) ~ = ~ Var(X_1) - Var(X_2)
$$

If $X_1$ and $X_2$ have the same variance then $S$ and $D$ are uncorrelated, and hence also independent by what we have just proved.

```python

```


# HW 5

## Imports

```python
import numpy
import sympy
from astropy import units, constants
```

## Theory A

### Quadratic Geometric Quantities

```python
alpha, beta = sympy.symbols('alpha beta')
```

```python
def g(mu: sympy.Symbol, nu: sympy.Symbol):
    return sympy.Symbol('g_{}_{}'.format(mu.name, nu.name))

def christoffel(mu, nu, lam):
    sympy.Derivative()
```

```python

```

```python

```

```python

```

## Problem C

### C1

Radius of orbit of binary: (7.144)

$$\omega = \bigg(\frac{GM}{4R^3}\bigg)^2 \implies R(\omega) = \left(\frac{GM}{4\omega^2}\right)^{1/3}$$

```python
def rad(omega, mass):
    return (constants.G * mass / (4 * omega ** 2)) ** (1/3)
```

```python
M1 = 36 * constants.M_sun
M2 = 29 * constants.M_sun
M_avg = (M1 + M2) / 2.0

omega = 350 * (1 / units.second) #* (2 * numpy.pi)
```

```python
r = rad(omega, M_avg)
r
```

$206474.44 \; \mathrm{m}$

```python
R_s = 2 * constants.G * M_avg / constants.c ** 2
R_s
```

$95980.627 \; \mathrm{m}$

```python
r / R_s
```

$2.1512096 \; \mathrm{}$

### C2

Distance

$$\LARGE\bar{h}_{ij} = \frac{2G}{r} \ddot{Q}_{ij}(t - r)$$

$$\LARGE \ddot{Q}_{ij} = 2Mr^2\omega^2 \begin{vmatrix}-\cos{2\omega(t-d)} & -\sin{2\omega(t-d)} & 0 \\ -\sin{2\omega(t-d)} & \cos{2\omega(t-d)} & 0 \\ 0 & 0 & 0 \end{vmatrix}$$

$$\LARGE\bar{h}_{ij} =  \frac{4GMr^2 \omega^2}{d} \begin{vmatrix}-\cos{2\omega(t-d)} & -\sin{2\omega(t-d)} & 0 \\ -\sin{2\omega(t-d)} & \cos{2\omega(t-d)} & 0 \\ 0 & 0 & 0 \end{vmatrix}$$

$$\max \bar{h}_{ij} = 4GMr^2 \omega^2 / d$$

```python
d = (410 * units.Mpc).to(units.meter)
omega_max = 350 * (1 / units.second) #* (2 * numpy.pi)
r_min = rad(omega_max, M_avg)
```

```python
h_ij_max = 4 * constants.G * M_avg * (r_min ** 2) * (omega_max ** 2) / (d * (constants.c ** 4))
h_ij_max
```

$8.8167083 \times 10^{-22} \; \mathrm{}$

### C3

$$P \sim G \dddot{Q}^2 \sim P_o \frac{r_s}{r}$$

```python
constants.G
```

$6.6743 \times 10^{-11} \; \mathrm{\frac{m^{3}}{kg\,s^{2}}}$

```python
P_o = (constants.c ** 5 / constants.G).to(units.Watt)
P_o
```

$3.6282549 \times 10^{52} \; \mathrm{W}$

```python
constants.L_sun
```

$3.828 \times 10^{26} \; \mathrm{W}$

```python
P_o / constants.L_sun
```

$9.4781999 \times 10^{25} \; \mathrm{}$

```python
P_sun_mass = (constants.M_sun * (constants.c ** 2) / (1 * units.second)).to(units.Watt)
P_sun_mass
```

$1.7870937 \times 10^{47} \; \mathrm{W}$

```python
P_o / P_sun_mass
```

$203025.45 \; \mathrm{}$

### C4

$$P(r) =  \frac{2}{5c^5} \frac{G^4 M^5}{R^5}$$

$$R(\omega) = \left(\frac{GM}{4\omega^2}\right)^{1/3}$$

$$\LARGE P(\omega) =  \frac{2}{5c^5} \frac{1}{G} \left(2GM\right)^{10/3} \omega^{10/3}$$

$$\LARGE E \equiv \int_{0}^{t_f} P(\omega(t)) dt =  \frac{2}{5c^5} \frac{1}{G} \left(2GM\right)^{10/3} \int_{0}^{t_f} \omega^{10/3}(t) dt$$

Assumption:

$$\LARGE \omega(t) = \frac{t}{t_f}\omega_f + \frac{(t_f - t)}{t_f}\omega_o = \frac{\omega_f - \omega_o}{t_f} t + \omega_o$$

$$\LARGE E = \frac{2}{5c^5} \frac{1}{G} \left(2GM\right)^{10/3} \frac{3}{13} \frac{t_f}{\omega_f - \omega_o} (\omega_f^{13/3} - \omega_o^{13/3})$$

```python
omega_init = 35 * (1 / units.second) #* (2 * numpy.pi)
omega_fin = 350 * (1 / units.second) #* (2 * numpy.pi)
```

```python
P_units = constants.G ** 4 * units.kg ** 5 / (units.m ** 5) / (constants.c ** 5)
P_units
```

$8.1944419 \times 10^{-84} \; \mathrm{\frac{m^{2}\,kg}{s^{3}}}$

```python
P_units = (1 / constants.c ** 5) * (1 / constants.G) * (constants.G * units.kg) ** (10/3) * (1 / units.second) ** (10/3)
P_units
```

$7.4617926 \times 10^{-67} \; \mathrm{\frac{m^{2}\,kg}{s^{3}}}$

```python
delta_t = 0.2 * units.second
```

```python
E = ( (2 / (5 * constants.c ** 5))
     * (1 / constants.G) * (2 * constants.G * M_avg) ** (10/3)
     * (omega_fin ** (13/3) - omega_init ** (13/3)) * (delta_t / (omega_fin - omega_init)) * (3 / 13)
)
E
```

$5.0482335 \times 10^{47} \; \mathrm{\frac{m^{2}\,kg}{s^{2}}}$

```python
E / (constants.M_sun * constants.c ** 2)
```

$2.8248287 \; \mathrm{}$

```python

```

```python

```


```python
import sympy as sy
sy.init_printing(use_unicode=False)
```

```python
x1,x2,x3,x4=sy.symbols('x(1:5)')
y1,y2,y3,y4=sy.symbols('y(1:5)')
```

```python
xs=[x1,x2,x3,x4]
ys=[y1,y2,y3,y4]
```

```python
b1x,b2x,b3x,b4x=sy.symbols('b_{(1:5)x}')
b1y,b2y,b3y,b4y=sy.symbols('b_{(1:5)y}')
e1x,e2x,e3x,e4x=sy.symbols('e_{(1:5)x}')
e1y,e2y,e3y,e4y=sy.symbols('e_{(1:5)y}')
```

```python
b1 = [b1x,b1y]
e1 = [e1x,e1y]

b2 = [b2x,b2y]
e2 = [e2x,e2y]

b3 = [b3x,b3y]
e3 = [e3x,e3y]

b4 = [b4x,b4y]
e4 = [e4x,e4y]
```

```python
#example
B1 = [1, -1]
E1 = [-1, 1]

B2 = [-1, 2]
E2 = [1, 4]

B3 = [2, 4]
E3 = [4, 2]

B4 = [4, 1]
E4 = [2, -1]
```

```python
def on_segment(b,e,x,y):
    return (e[0]-b[0])*(y-b[1])-(e[1]-b[1])*(x-b[0])

def orthogonal(lx, ly, cx, cy, rx, ry):
    return (lx-cx)*(rx-cx)+(ly-cy)*(ry-cy)
```

```python
f1=orthogonal(x1, y1, x2, y2, x3, y3)
f2=orthogonal(x2, y2, x3, y3, x4, y4)
f3=orthogonal(x3, y3, x4, y4, x1, y1)
f4=orthogonal(x4, y4, x1, y1, x2, y2)
fs=[f1,f2,f3,f4]
fs
```

```python
g1=on_segment(b1,e1,x1,y1)
g2=on_segment(b2,e2,x2,y2)
g3=on_segment(b3,e3,x3,y3)
g4=on_segment(b4,e4,x4,y4)
gs=[g1,g2,g3,g4]
gs
```

```python
lf1,lf2,lf3,lf4=sy.symbols('\lambda_{f_(1:5)}')
lfs=[lf1,lf2,lf3,lf4]
lfs
```

```python
lg1,lg2,lg3,lg4=sy.symbols('\lambda_{g_(1:5)}')
lgs=[lg1,lg2,lg3,lg4]
lgs
```

```python
area=(x4-x1)*(y2-y1)-(x2-x1)*(y4-y1)
```

```python
area
```

```python
Phi=area-sy.Matrix(lfs).dot(sy.Matrix(fs))-sy.Matrix(lgs).dot(sy.Matrix(gs))
Phi
```

```python
[sy.diff(Phi,x1),
sy.diff(Phi,y1),
sy.diff(Phi,x2),
sy.diff(Phi,y2),
sy.diff(Phi,x3),
sy.diff(Phi,y3),
sy.diff(Phi,x4),
sy.diff(Phi,y4)]
```

```python
[sy.diff(Phi,lf1),
sy.diff(Phi,lf2),
sy.diff(Phi,lf3),
sy.diff(Phi,lf4),
sy.diff(Phi,lg1),
sy.diff(Phi,lg2),
sy.diff(Phi,lg3),
sy.diff(Phi,lg4)]
```

```python

```


```python
from sympy.physics.mechanics import *
import sympy as sp
mechanics_printing(pretty_print=True)
```

```python
m1, m2, m3, m4, l1, l2, l3, l4 = sp.symbols(r'm_1 m_2 m_3 m_4 l_1 l_2 l_3 l_4')
t, g, h = sp.symbols('t g h')
v1, v2, v3, v4 = dynamicsymbols(r'\theta_1 \theta_2 \theta_3 \theta_4')
dv1, dv2, dv3, dv4 = dynamicsymbols(r'\theta_1 \theta_2 \theta_3 \theta_4', 1)
ddv1, ddv2, ddv3, ddv4 = dynamicsymbols(r'\theta_1 \theta_2 \theta_3 \theta_4', 2)
```

```python
x1 = l1 * sp.sin(v1)
y1 = -l1 * sp.cos(v1)
x2 = x1 + l2 * sp.sin(v2)
y2 = y1 + -l2 * sp.cos(v2)
x3 = x2 + l3 * sp.sin(v3)
y3 = y2 + -l3 * sp.cos(v3)
x4 = x3 + l4 * sp.sin(v4)
y4 = y3 + -l4 * sp.cos(v4)

dx1 = x1.diff(t)
dy1 = y1.diff(t)
dx2 = x2.diff(t)
dy2 = y2.diff(t)
dx3 = x3.diff(t)
dy3 = y3.diff(t)
dx4 = x4.diff(t)
dy4 = y4.diff(t)
```

```python
V = (m1 * g * y1) + (m2 * g * y2) + (m3 * g * y3) + (m4 * g * y4)
T = (sp.Rational(1, 2) * m1 * (dx1**2 + dy1**2)) + (sp.Rational(1, 2) * m2 * (dx2**2+dy2**2)) + (sp.Rational(1, 2) * m3 * (dx3**2 + dy3**2)) + (sp.Rational(1, 2) * m4 * (dx4**2 + dy4**2))
L = T - V
```

```python
LM = LagrangesMethod(L, [v1, v2, v3, v4])
```

```python
soln = LM.form_lagranges_equations()
```

```python
sp.latex(soln)
```

    ⎡
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢g⋅l₁⋅m₁⋅sin(\theta₁(t)) + g⋅l₁⋅m₂⋅sin(\theta₁(t)) + g⋅l₁⋅m₃⋅sin(\theta₁(t)) +
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢                                                        g⋅l₂⋅m₂⋅sin(\theta₂(t
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎢
    ⎣

                                  ⎛                         2
                                  ⎜    2    2              d                    2
                               m₁⋅⎜2⋅l₁ ⋅sin (\theta₁(t))⋅───(\theta₁(t)) + 2⋅l₁ ⋅
                                  ⎜                         2
                                  ⎝                       dt
     g⋅l₁⋅m₄⋅sin(\theta₁(t)) + ───────────────────────────────────────────────────
                                                                        2

                                                                ⎛     ⎛
                                                             m₂⋅⎜2⋅l₂⋅⎜l₁⋅sin(\the
                                                                ⎝     ⎝
    )) + g⋅l₂⋅m₃⋅sin(\theta₂(t)) + g⋅l₂⋅m₄⋅sin(\theta₂(t)) - ─────────────────────

                       2            ⎞
       2              d             ⎟
    cos (\theta₁(t))⋅───(\theta₁(t))⎟      ⎛     ⎛                   d
                       2            ⎟   m₂⋅⎜2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta₁(t)
                     dt             ⎠      ⎝     ⎝                   dt
    ───────────────────────────────── - ──────────────────────────────────────────

            d                                   d             ⎞                 d
    ta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟⋅cos(\theta₂(t))⋅──
            dt                                  dt            ⎠                 dt
    ──────────────────────────────────────────────────────────────────────────────

                           d             ⎞                 d                     ⎛
    ) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟⋅cos(\theta₁(t))⋅──(\theta₁(t)) - 2⋅l₁⋅⎜
                           dt            ⎠                 dt                    ⎝
    ──────────────────────────────────────────────────────────────────────────────
                                                                        2

                        ⎛                   d                                   d
    (\theta₂(t)) - 2⋅l₂⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──
                        ⎝                   dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────
               2

                       d                                   d             ⎞
    l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t))⎟⋅sin(\th
                       dt                                  dt            ⎠
    ──────────────────────────────────────────────────────────────────────────────

                                                       ⎛
                                                       ⎜     ⎛                   d
                ⎞                 d             ⎞   m₂⋅⎜2⋅l₂⋅⎜l₁⋅sin(\theta₁(t))⋅─
    (\theta₂(t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟      ⎜     ⎝                   d
                ⎠                 dt            ⎠      ⎝
    ───────────────────────────────────────────── + ──────────────────────────────

                                  ⎛
                                  ⎜     ⎛                   d
             d             ⎞   m₂⋅⎜2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅si
    eta₁(t))⋅──(\theta₁(t))⎟      ⎜     ⎝                   dt
             dt            ⎠      ⎝
    ──────────────────────── + ───────────────────────────────────────────────────

                                       d             ⎞                 d
    ─(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟⋅cos(\theta₂(t))⋅──(\theta₂(
    t                                  dt            ⎠                 dt

    ──────────────────────────────────────────────────────────────────────────────

                  d             ⎞                 d                     ⎛
    n(\theta₂(t))⋅──(\theta₂(t))⎟⋅cos(\theta₁(t))⋅──(\theta₁(t)) - 2⋅l₁⋅⎜l₁⋅cos(\t
                  dt            ⎠                 dt                    ⎝

    ──────────────────────────────────────────────────────────────────────────────

               ⎛                   d                                   d
    t)) - 2⋅l₂⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(
               ⎝                   dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                                                              ⎛     ⎛
                                                           m₃⋅⎜2⋅l₃⋅⎜l₁⋅sin(\theta
                                                              ⎝     ⎝
       g⋅l₃⋅m₃⋅sin(\theta₃(t)) + g⋅l₃⋅m₄⋅sin(\theta₃(t)) - ───────────────────────

              d                                   d             ⎞
    heta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t))⎟⋅sin(\theta₁(t))⋅
              dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                                               ⎛
       ⎞                 d                     ⎜                     ⎛d
    t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t)) + 2⋅l₂⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t
       ⎠                 dt                    ⎜                     ⎝dt
                                               ⎝
    ──────────────────────────────────────────────────────────────────────────────

          d                                   d
    ₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅
          dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                          ⎛                                     2
    d                     ⎜                     ⎛d             ⎞
    ──(\theta₁(t)) + 2⋅l₁⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅cos(\theta₁
    dt                    ⎜                     ⎝dt            ⎠
                          ⎝
    ──────────────────────────────────────────────────────────────────────────────

       2                        2
      ⎞                        d                                   ⎛d
    ))⎟  + l₁⋅cos(\theta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))
      ⎠                         2                                  ⎝dt
                              dt
    ──────────────────────────────────────────────────────────────────────────────
                          2

    d             ⎞                 d                     ⎛                   d
    ──(\theta₃(t))⎟⋅cos(\theta₃(t))⋅──(\theta₃(t)) - 2⋅l₃⋅⎜l₁⋅cos(\theta₁(t))⋅──(\
    dt            ⎠                 dt                    ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────
                                                 2

           2                                                  2
          d                                   ⎛d             ⎞
    (t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos(\theta₂(t
           2                                  ⎝dt            ⎠
         dt
    ──────────────────────────────────────────────────────────────────────────────
     2

     2                        2            ⎞                        ⎛
    ⎞                        d             ⎟                        ⎜
    ⎟  + l₂⋅cos(\theta₂(t))⋅───(\theta₂(t))⎟⋅cos(\theta₂(t)) + 2⋅l₂⋅⎜l₁⋅sin(\theta
    ⎠                         2            ⎟                        ⎜
                            dt             ⎠                        ⎝
    ──────────────────────────────────────────────────────────────────────────────

                                    d                                   d
    theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃
                                    dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

         2            ⎞                        ⎛                     2
        d             ⎟                        ⎜                    d
    ))⋅───(\theta₂(t))⎟⋅cos(\theta₁(t)) + 2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅───(\theta₁(t))
         2            ⎟                        ⎜                     2
       dt             ⎠                        ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

            2                                                  2
           d                                   ⎛d             ⎞
    ₁(t))⋅───(\theta₁(t)) + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(
            2                                  ⎝dt            ⎠
          dt
    ──────────────────────────────────────────────────────────────────────────────

                                               ⎛
                                               ⎜     ⎛                   d
        ⎞                 d             ⎞   m₃⋅⎜2⋅l₃⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta
    (t))⎟⋅sin(\theta₃(t))⋅──(\theta₃(t))⎟      ⎜     ⎝                   dt
        ⎠                 dt            ⎠      ⎝
    ───────────────────────────────────── + ──────────────────────────────────────

                                          2                        2
                          ⎛d             ⎞                        d
     + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\theta₂(t)) +
                          ⎝dt            ⎠                         2
                                                                 dt
    ──────────────────────────────────────────────────────────────────────────────

          2                                                  2⎞                ⎞
         d                                   ⎛d             ⎞ ⎟                ⎟
    t))⋅───(\theta₂(t)) + l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟ ⎟⋅sin(\theta₂(t))⎟
          2                                  ⎝dt            ⎠ ⎟                ⎟
        dt                                                    ⎠                ⎠
    ──────────────────────────────────────────────────────────────────────────── -

                               d                                   d             ⎞
    ₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t))⎟
                               dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                                        2⎞                ⎞
                        ⎛d             ⎞ ⎟                ⎟
     l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟ ⎟⋅sin(\theta₁(t))⎟      ⎛     ⎛
                        ⎝dt            ⎠ ⎟                ⎟   m₃⋅⎜2⋅l₁⋅⎜l₁⋅sin(\th
                                         ⎠                ⎠      ⎝     ⎝
    ─────────────────────────────────────────────────────── - ────────────────────

        ⎛     ⎛                   d                                   d
     m₃⋅⎜2⋅l₂⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t
        ⎝     ⎝                   dt                                  dt
     ─────────────────────────────────────────────────────────────────────────────

                     d                     ⎛                   d
    ⋅cos(\theta₃(t))⋅──(\theta₃(t)) - 2⋅l₃⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂
                     dt                    ⎝                   dt

    ──────────────────────────────────────────────────────────────────────────────

             d                                   d
    eta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t
             dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                            d             ⎞                 d
    )) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t))⎟⋅cos(\theta₂(t))⋅──(\theta₂(t)) - 2⋅l₂⋅
                            dt            ⎠                 dt
    ──────────────────────────────────────────────────────────────────────────────
                                                                         2

                     d                                   d             ⎞
    ⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t))⎟⋅sin(\thet
                     dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                                                    ⎛     ⎛                   d
                                                 m₄⋅⎜2⋅l₄⋅⎜l₁⋅sin(\theta₁(t))⋅──(\
                                                    ⎝     ⎝                   dt
                       g⋅l₄⋅m₄⋅sin(\theta₄(t)) - ─────────────────────────────────

       d             ⎞                 d                     ⎛                   d
    ))⋅──(\theta₃(t))⎟⋅cos(\theta₁(t))⋅──(\theta₁(t)) - 2⋅l₁⋅⎜l₁⋅cos(\theta₁(t))⋅─
       dt            ⎠                 dt                    ⎝                   d
    ──────────────────────────────────────────────────────────────────────────────
                                                    2

    ⎛                   d                                   d
    ⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅co
    ⎝                   dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                 ⎛                                     2
           d                     ⎜                     ⎛d             ⎞
    a₃(t))⋅──(\theta₃(t)) + 2⋅l₃⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅cos(
           dt                    ⎜                     ⎝dt            ⎠
                                 ⎝
    ──────────────────────────────────────────────────────────────────────────────

                                    d                                   d
    theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃
                                    dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                       d                                   d
    ─(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\the
    t                                  dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                                                       ⎛
                                                                       ⎜     ⎛
                  d             ⎞                 d             ⎞   m₃⋅⎜2⋅l₂⋅⎜l₁⋅s
    s(\theta₃(t))⋅──(\theta₃(t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟      ⎜     ⎝
                  dt            ⎠                 dt            ⎠      ⎝
    ───────────────────────────────────────────────────────────── + ──────────────

                  2                                                  2
                 d                                   ⎛d             ⎞
    \theta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos(\t
                  2                                  ⎝dt            ⎠
                dt
    ──────────────────────────────────────────────────────────────────────────────
                                                    2

                              d             ⎞                 d
    (t)) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₄(t))⋅──(\theta₄(t)) - 2⋅l
                              dt            ⎠                 dt
    ──────────────────────────────────────────────────────────────────────────────
                                                                           2

                                                  ⎛
                                                  ⎜     ⎛                   d
           ⎞                 d             ⎞   m₃⋅⎜2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅──(\th
    ta₃(t))⎟⋅sin(\theta₁(t))⋅──(\theta₁(t))⎟      ⎜     ⎝                   dt
           ⎠                 dt            ⎠      ⎝
    ──────────────────────────────────────── + ───────────────────────────────────

                   d                                   d
    in(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\th
                   dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                2                                                  2
               d                                   ⎛d             ⎞
    heta₂(t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₃⋅cos(\the
                2                                  ⎝dt            ⎠
              dt
    ──────────────────────────────────────────────────────────────────────────────

      ⎛                   d                                   d
    ₄⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅
      ⎝                   dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                  d                                   d
    eta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t
                                  dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

             d             ⎞                 d                     ⎛
    eta₃(t))⋅──(\theta₃(t))⎟⋅cos(\theta₂(t))⋅──(\theta₂(t)) - 2⋅l₂⋅⎜l₁⋅cos(\theta₁
             dt            ⎠                 dt                    ⎝

    ──────────────────────────────────────────────────────────────────────────────

              2            ⎞                        ⎛                     2
             d             ⎟                        ⎜                    d
    ta₃(t))⋅───(\theta₃(t))⎟⋅cos(\theta₃(t)) + 2⋅l₃⋅⎜l₁⋅sin(\theta₁(t))⋅───(\theta
              2            ⎟                        ⎜                     2
            dt             ⎠                        ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

                    d                                   d             ⎞
    cos(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\theta₄(t))⎟⋅sin(\theta
                    dt                                  dt            ⎠
    ──────────────────────────────────────────────────────────────────────────────

      ⎞                 d                     ⎛                   d
    ))⎟⋅cos(\theta₁(t))⋅──(\theta₁(t)) - 2⋅l₁⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) +
      ⎠                 dt                    ⎝                   dt

    ──────────────────────────────────────────────────────────────────────────────

         d                                   d                                   d
    (t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅─
         dt                                  dt                                  d

    ──────────────────────────────────────────────────────────────────────────────

                                               2                        2
                               ⎛d             ⎞                        d
    ₁(t)) + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\theta₂(
                               ⎝dt            ⎠                         2
                                                                      dt
    ──────────────────────────────────────────────────────────────────────────────

                               ⎛
                               ⎜     ⎛                   d
          d             ⎞   m₄⋅⎜2⋅l₄⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\
    ₄(t))⋅──(\theta₄(t))⎟      ⎜     ⎝                   dt
          dt            ⎠      ⎝
    ───────────────────── + ──────────────────────────────────────────────────────

                        d                                   d             ⎞
     l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t))⎟⋅sin(\t
                        dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                                                         ⎛
                 ⎞                 d                     ⎜                     ⎛d
    ─(\theta₃(t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t)) + 2⋅l₂⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──
    t            ⎠                 dt                    ⎜                     ⎝dt
                                                         ⎝
    ──────────────────────────────────────────────────────────────────────────────

                                             2                        2
                             ⎛d             ⎞                        d
    t)) + l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t))⋅───(\theta₃(t)
                             ⎝dt            ⎠                         2
                                                                    dt
    ──────────────────────────────────────────────────────────────────────────────

               d                                   d
    theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅sin(\theta₄
               dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                                    ⎛                                     2
              d                     ⎜                     ⎛d             ⎞
    heta₁(t))⋅──(\theta₁(t)) + 2⋅l₁⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅c
              dt                    ⎜                     ⎝dt            ⎠
                                    ⎝
    ──────────────────────────────────────────────────────────────────────────────

                 2                        2
                ⎞                        d                                   ⎛d
    (\theta₁(t))⎟  + l₁⋅cos(\theta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\
                ⎠                         2                                  ⎝dt
                                        dt
    ──────────────────────────────────────────────────────────────────────────────
                                                                            2

                                           2⎞                ⎞
                           ⎛d             ⎞ ⎟                ⎟
    ) + l₃⋅cos(\theta₃(t))⋅⎜──(\theta₃(t))⎟ ⎟⋅sin(\theta₃(t))⎟      ⎛     ⎛
                           ⎝dt            ⎠ ⎟                ⎟   m₄⋅⎜2⋅l₃⋅⎜l₁⋅sin(
                                            ⎠                ⎠      ⎝     ⎝
    ────────────────────────────────────────────────────────── - ─────────────────

         d             ⎞                 d                     ⎛
    (t))⋅──(\theta₄(t))⎟⋅cos(\theta₄(t))⋅──(\theta₄(t)) - 2⋅l₄⋅⎜l₁⋅cos(\theta₁(t))
         dt            ⎠                 dt                    ⎝

    ──────────────────────────────────────────────────────────────────────────────

                     2                                                  2
                    d                                   ⎛d             ⎞
    os(\theta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos
                     2                                  ⎝dt            ⎠
                   dt
    ──────────────────────────────────────────────────────────────────────────────
                                                       2

               2                        2
              ⎞                        d                                   ⎛d
    theta₂(t))⎟  + l₂⋅cos(\theta₂(t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\th
              ⎠                         2                                  ⎝dt
                                      dt
    ──────────────────────────────────────────────────────────────────────────────

                d                                   d
    \theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta
                dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

     d                                   d                                   d
    ⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\t
     dt                                  dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                   2                                                  2
                  d                                   ⎛d             ⎞
    (\theta₂(t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₃⋅cos(\
                   2                                  ⎝dt            ⎠
                 dt
    ──────────────────────────────────────────────────────────────────────────────

             2                        2            ⎞                        ⎛
            ⎞                        d             ⎟                        ⎜
    eta₃(t))⎟  + l₃⋅cos(\theta₃(t))⋅───(\theta₃(t))⎟⋅cos(\theta₂(t)) + 2⋅l₂⋅⎜l₁⋅si
            ⎠                         2            ⎟                        ⎜
                                    dt             ⎠                        ⎝
    ──────────────────────────────────────────────────────────────────────────────

          d                                   d             ⎞                 d
    ₃(t))⋅──(\theta₃(t)) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₃(t))⋅──(\
          dt                                  dt            ⎠                 dt
    ──────────────────────────────────────────────────────────────────────────────

                                   d             ⎞                 d
    heta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\theta₄(t))⎟⋅sin(\theta₄(t))⋅──(\theta₄(t))
                                   dt            ⎠                 dt

    ──────────────────────────────────────────────────────────────────────────────

                 2            ⎞                        ⎛                     2
                d             ⎟                        ⎜                    d
    theta₃(t))⋅───(\theta₃(t))⎟⋅cos(\theta₁(t)) + 2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅───(\th
                 2            ⎟                        ⎜                     2
               dt             ⎠                        ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

                    2                                                  2
                   d                                   ⎛d             ⎞
    n(\theta₁(t))⋅───(\theta₁(t)) + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(
                    2                                  ⎝dt            ⎠
                  dt
    ──────────────────────────────────────────────────────────────────────────────

                      ⎛                   d                                   d
    theta₃(t)) - 2⋅l₃⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\
                      ⎝                   dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────
             2

           ⎛                                     2                        2
           ⎜                     ⎛d             ⎞                        d
    + 2⋅l₄⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅cos(\theta₁(t))⋅───(\theta
           ⎜                     ⎝dt            ⎠                         2
           ⎝                                                            dt
    ──────────────────────────────────────────────────────────────────────────────

                                                  2                        2
                                  ⎛d             ⎞                        d
    eta₁(t)) + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\thet
                                  ⎝dt            ⎠                         2
                                                                         dt
    ──────────────────────────────────────────────────────────────────────────────

                  2                                                  2
                 d                                   ⎛d             ⎞
    \theta₂(t))⋅───(\theta₂(t)) + l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\t
                  2                                  ⎝dt            ⎠
                dt
    ──────────────────────────────────────────────────────────────────────────────

                                    d                                   d
    theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\theta₄
                                    dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                               2                        2
                               ⎛d             ⎞                        d
    ₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos(\theta₂(t))⋅───(\theta₂(
                               ⎝dt            ⎠                         2
                                                                      dt
    ──────────────────────────────────────────────────────────────────────────────
                                                                      2

                                                2                        2
                                ⎛d             ⎞                        d
    a₂(t)) + l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t))⋅───(\theta₃
                                ⎝dt            ⎠                         2
                                                                       dt
    ──────────────────────────────────────────────────────────────────────────────

                2                                                  2⎞
               d                                   ⎛d             ⎞ ⎟
    heta₃(t))⋅───(\theta₃(t)) + l₃⋅cos(\theta₃(t))⋅⎜──(\theta₃(t))⎟ ⎟⋅sin(\theta₂(
                2                                  ⎝dt            ⎠ ⎟
              dt                                                    ⎠
    ──────────────────────────────────────────────────────────────────────────────

                                               ⎛
                                               ⎜     ⎛                   d
        ⎞                 d             ⎞   m₄⋅⎜2⋅l₃⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta
    (t))⎟⋅sin(\theta₃(t))⋅──(\theta₃(t))⎟      ⎜     ⎝                   dt
        ⎠                 dt            ⎠      ⎝
    ───────────────────────────────────── + ──────────────────────────────────────

                                             2                        2
                             ⎛d             ⎞                        d
    t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₃⋅cos(\theta₃(t))⋅───(\theta₃(t)
                             ⎝dt            ⎠                         2
                                                                    dt
    ──────────────────────────────────────────────────────────────────────────────

                                              2⎞                ⎞
                              ⎛d             ⎞ ⎟                ⎟
    (t)) + l₃⋅cos(\theta₃(t))⋅⎜──(\theta₃(t))⎟ ⎟⋅sin(\theta₁(t))⎟      ⎛     ⎛
                              ⎝dt            ⎠ ⎟                ⎟   m₄⋅⎜2⋅l₁⋅⎜l₁⋅s
                                               ⎠                ⎠      ⎝     ⎝
    ───────────────────────────────────────────────────────────── - ──────────────

       ⎞
       ⎟
    t))⎟      ⎛     ⎛                   d                                   d
       ⎟   m₄⋅⎜2⋅l₂⋅⎜l₁⋅sin(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\th
       ⎠      ⎝     ⎝                   dt                                  dt
    ──── - ───────────────────────────────────────────────────────────────────────

                               d                                   d
    ₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t))
                               dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                                           2                        2            ⎞
                           ⎛d             ⎞                        d             ⎟
    ) - l₄⋅sin(\theta₄(t))⋅⎜──(\theta₄(t))⎟  + l₄⋅cos(\theta₄(t))⋅───(\theta₄(t))⎟
                           ⎝dt            ⎠                         2            ⎟
                                                                  dt             ⎠
    ──────────────────────────────────────────────────────────────────────────────

                   d                                   d
    in(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\th
                   dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                  d                                   d
    eta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t
                                  dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                         d             ⎞                 d                     ⎛
    + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₃(t))⋅──(\theta₃(t)) - 2⋅l₃⋅⎜l₁
                         dt            ⎠                 dt                    ⎝

    ──────────────────────────────────────────────────────────────────────────────

                            ⎛                     2
                            ⎜                    d
    ⋅cos(\theta₄(t)) + 2⋅l₄⋅⎜l₁⋅sin(\theta₁(t))⋅───(\theta₁(t)) + l₁⋅cos(\theta₁(t
                            ⎜                     2
                            ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

             d                                   d             ⎞                 d
    eta₃(t))⋅──(\theta₃(t)) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₁(t))⋅─
             dt                                  dt            ⎠                 d
    ──────────────────────────────────────────────────────────────────────────────

      ⎞                 d                     ⎛                   d
    ))⎟⋅cos(\theta₂(t))⋅──(\theta₂(t)) - 2⋅l₂⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) +
      ⎠                 dt                    ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────
                                     2

                     d                                   d
    ⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\
                     dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                       2                        2
       ⎛d             ⎞                        d
    ))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\theta₂(t)) + l₂⋅cos(\theta₂(t))
       ⎝dt            ⎠                         2
                                              dt
    ──────────────────────────────────────────────────────────────────────────────

                         ⎛                   d                                   d
    ─(\theta₁(t)) - 2⋅l₁⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅─
    t                    ⎝                   dt                                  d
    ──────────────────────────────────────────────────────────────────────────────
                2

                        d                                   d
     l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅co
                        dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

               d                                   d             ⎞
    theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\theta₄(t))⎟⋅sin(\theta₃(t))
               dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                     2                        2
     ⎛d             ⎞                        d                                   ⎛
    ⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t))⋅───(\theta₃(t)) + l₃⋅cos(\theta₃(t))⋅⎜
     ⎝dt            ⎠                         2                                  ⎝
                                            dt
    ──────────────────────────────────────────────────────────────────────────────

                                       d                                   d
    ─(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\the
    t                                  dt                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                                                       ⎛
                                                                       ⎜     ⎛
                  d             ⎞                 d             ⎞   m₄⋅⎜2⋅l₂⋅⎜l₁⋅s
    s(\theta₄(t))⋅──(\theta₄(t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t))⎟      ⎜     ⎝
                  dt            ⎠                 dt            ⎠      ⎝
    ───────────────────────────────────────────────────────────── + ──────────────

                           ⎛                                     2
     d                     ⎜                     ⎛d             ⎞
    ⋅──(\theta₃(t)) + 2⋅l₃⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅cos(\theta
     dt                    ⎜                     ⎝dt            ⎠
                           ⎝
    ──────────────────────────────────────────────────────────────────────────────

                   2                        2
    d             ⎞                        d                                   ⎛d
    ──(\theta₃(t))⎟  + l₄⋅sin(\theta₄(t))⋅───(\theta₄(t)) + l₄⋅cos(\theta₄(t))⋅⎜──
    dt            ⎠                         2                                  ⎝dt
                                          dt
    ──────────────────────────────────────────────────────────────────────────────

                                                  ⎛
                                                  ⎜     ⎛                   d
           ⎞                 d             ⎞   m₄⋅⎜2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅──(\th
    ta₄(t))⎟⋅sin(\theta₁(t))⋅──(\theta₁(t))⎟      ⎜     ⎝                   dt
           ⎠                 dt            ⎠      ⎝
    ──────────────────────────────────────── + ───────────────────────────────────

                   d                                   d
    in(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\th
                   dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

            2                                                  2
           d                                   ⎛d             ⎞
    ₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos(\theta₂(
            2                                  ⎝dt            ⎠
          dt
    ──────────────────────────────────────────────────────────────────────────────

                 2⎞                ⎞
                ⎞ ⎟                ⎟
    (\theta₄(t))⎟ ⎟⋅sin(\theta₄(t))⎟
                ⎠ ⎟                ⎟
                  ⎠                ⎠
    ────────────────────────────────

                                  d                                   d
    eta₁(t)) + l₂⋅sin(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅sin(\theta₃(t))⋅──(\theta₃(t
                                  dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

             d                                   d             ⎞                 d
    eta₃(t))⋅──(\theta₃(t)) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₂(t))⋅─
             dt                                  dt            ⎠                 d

    ──────────────────────────────────────────────────────────────────────────────

          2                                                  2
         d                                   ⎛d             ⎞
    t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₃⋅cos(\theta₃(t)
          2                                  ⎝dt            ⎠
        dt
    ──────────────────────────────────────────────────────────────────────────────
        2

                            d             ⎞                 d
    )) + l₄⋅sin(\theta₄(t))⋅──(\theta₄(t))⎟⋅cos(\theta₁(t))⋅──(\theta₁(t)) - 2⋅l₁⋅
                            dt            ⎠                 dt

    ──────────────────────────────────────────────────────────────────────────────

                         ⎛                   d                                   d
    ─(\theta₂(t)) - 2⋅l₂⋅⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅─
    t                    ⎝                   dt                                  d

    ──────────────────────────────────────────────────────────────────────────────

        2                                                  2
       d                                   ⎛d             ⎞
    )⋅───(\theta₃(t)) - l₄⋅sin(\theta₄(t))⋅⎜──(\theta₄(t))⎟  + l₄⋅cos(\theta₄(t))⋅
        2                                  ⎝dt            ⎠
      dt
    ──────────────────────────────────────────────────────────────────────────────

    ⎛                   d                                   d
    ⎜l₁⋅cos(\theta₁(t))⋅──(\theta₁(t)) + l₂⋅cos(\theta₂(t))⋅──(\theta₂(t)) + l₃⋅co
    ⎝                   dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

                                       d                                   d
    ─(\theta₂(t)) + l₃⋅cos(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\the
    t                                  dt                                  dt

    ──────────────────────────────────────────────────────────────────────────────

      2            ⎞                        ⎛                     2
     d             ⎟                        ⎜                    d
    ───(\theta₄(t))⎟⋅cos(\theta₃(t)) + 2⋅l₃⋅⎜l₁⋅sin(\theta₁(t))⋅───(\theta₁(t)) +
      2            ⎟                        ⎜                     2
    dt             ⎠                        ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

                  d                                   d             ⎞
    s(\theta₃(t))⋅──(\theta₃(t)) + l₄⋅cos(\theta₄(t))⋅──(\theta₄(t))⎟⋅sin(\theta₁(
                  dt                                  dt            ⎠

    ──────────────────────────────────────────────────────────────────────────────

                                                   ⎛
           ⎞                 d                     ⎜                     ⎛d
    ta₄(t))⎟⋅sin(\theta₂(t))⋅──(\theta₂(t)) + 2⋅l₂⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\thet
           ⎠                 dt                    ⎜                     ⎝dt
                                                   ⎝
    ──────────────────────────────────────────────────────────────────────────────

                                       2                        2
                       ⎛d             ⎞                        d
    l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\theta₂(t)) + l₂
                       ⎝dt            ⎠                         2
                                                              dt
    ──────────────────────────────────────────────────────────────────────────────

                              ⎛                                     2
        d                     ⎜                     ⎛d             ⎞
    t))⋅──(\theta₁(t)) + 2⋅l₁⋅⎜- l₁⋅sin(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₁⋅cos(\th
        dt                    ⎜                     ⎝dt            ⎠
                              ⎝
    ──────────────────────────────────────────────────────────────────────────────

           2                        2
          ⎞                        d                                   ⎛d
    a₁(t))⎟  + l₁⋅cos(\theta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂
          ⎠                         2                                  ⎝dt
                                  dt
    ──────────────────────────────────────────────────────────────────────────────

                                     2                        2
                     ⎛d             ⎞                        d
    ⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t))⋅───(\theta₃(t)) + l₃⋅c
                     ⎝dt            ⎠                         2
                                                            dt
    ──────────────────────────────────────────────────────────────────────────────

               2                                                  2
              d                                   ⎛d             ⎞
    eta₁(t))⋅───(\theta₁(t)) - l₂⋅sin(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₂⋅cos(\thet
               2                                  ⎝dt            ⎠
             dt
    ──────────────────────────────────────────────────────────────────────────────

         2                        2
        ⎞                        d                                   ⎛d
    (t))⎟  + l₂⋅cos(\theta₂(t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t
        ⎠                         2                                  ⎝dt
                                dt
    ──────────────────────────────────────────────────────────────────────────────
                                2

                                   2                        2
                   ⎛d             ⎞                        d
    os(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₄⋅sin(\theta₄(t))⋅───(\theta₄(t)) + l₄⋅cos
                   ⎝dt            ⎠                         2
                                                          dt
    ──────────────────────────────────────────────────────────────────────────────

             2                                                  2
            d                                   ⎛d             ⎞
    a₂(t))⋅───(\theta₂(t)) - l₃⋅sin(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₃⋅cos(\theta₃
             2                                  ⎝dt            ⎠
           dt
    ──────────────────────────────────────────────────────────────────────────────
           2

       2                        2
      ⎞                        d                                   ⎛d
    ))⎟  + l₃⋅cos(\theta₃(t))⋅───(\theta₃(t)) - l₄⋅sin(\theta₄(t))⋅⎜──(\theta₄(t))
      ⎠                         2                                  ⎝dt
                              dt
    ──────────────────────────────────────────────────────────────────────────────

                                 2⎞                ⎞
                 ⎛d             ⎞ ⎟                ⎟
    (\theta₄(t))⋅⎜──(\theta₄(t))⎟ ⎟⋅sin(\theta₃(t))⎟
                 ⎝dt            ⎠ ⎟                ⎟
                                  ⎠                ⎠
    ────────────────────────────────────────────────

           2                                                  2
          d                                   ⎛d             ⎞
    (t))⋅───(\theta₃(t)) - l₄⋅sin(\theta₄(t))⋅⎜──(\theta₄(t))⎟  + l₄⋅cos(\theta₄(t
           2                                  ⎝dt            ⎠
         dt
    ──────────────────────────────────────────────────────────────────────────────

     2                        2            ⎞                        ⎛
    ⎞                        d             ⎟                        ⎜
    ⎟  + l₄⋅cos(\theta₄(t))⋅───(\theta₄(t))⎟⋅cos(\theta₂(t)) + 2⋅l₂⋅⎜l₁⋅sin(\theta
    ⎠                         2            ⎟                        ⎜
                            dt             ⎠                        ⎝
    ──────────────────────────────────────────────────────────────────────────────

         2            ⎞                        ⎛                     2
        d             ⎟                        ⎜                    d
    ))⋅───(\theta₄(t))⎟⋅cos(\theta₁(t)) + 2⋅l₁⋅⎜l₁⋅sin(\theta₁(t))⋅───(\theta₁(t))
         2            ⎟                        ⎜                     2
       dt             ⎠                        ⎝                   dt
    ──────────────────────────────────────────────────────────────────────────────

            2                                                  2
           d                                   ⎛d             ⎞
    ₁(t))⋅───(\theta₁(t)) + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(
            2                                  ⎝dt            ⎠
          dt
    ──────────────────────────────────────────────────────────────────────────────

                                          2                        2
                          ⎛d             ⎞                        d
     + l₁⋅cos(\theta₁(t))⋅⎜──(\theta₁(t))⎟  + l₂⋅sin(\theta₂(t))⋅───(\theta₂(t)) +
                          ⎝dt            ⎠                         2
                                                                 dt
    ──────────────────────────────────────────────────────────────────────────────

          2                                                  2
         d                                   ⎛d             ⎞
    t))⋅───(\theta₂(t)) + l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t)
          2                                  ⎝dt            ⎠
        dt
    ──────────────────────────────────────────────────────────────────────────────

                                        2                        2
                        ⎛d             ⎞                        d
     l₂⋅cos(\theta₂(t))⋅⎜──(\theta₂(t))⎟  + l₃⋅sin(\theta₃(t))⋅───(\theta₃(t)) + l
                        ⎝dt            ⎠                         2
                                                               dt
    ──────────────────────────────────────────────────────────────────────────────

        2                                                  2
       d                                   ⎛d             ⎞
    )⋅───(\theta₃(t)) + l₃⋅cos(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₄⋅sin(\theta₄(t))⋅
        2                                  ⎝dt            ⎠
      dt
    ──────────────────────────────────────────────────────────────────────────────

                                      2                        2
                      ⎛d             ⎞                        d
    ₃⋅cos(\theta₃(t))⋅⎜──(\theta₃(t))⎟  + l₄⋅sin(\theta₄(t))⋅───(\theta₄(t)) + l₄⋅
                      ⎝dt            ⎠                         2
                                                             dt
    ──────────────────────────────────────────────────────────────────────────────

      2                                                  2⎞                ⎞
     d                                   ⎛d             ⎞ ⎟                ⎟
    ───(\theta₄(t)) + l₄⋅cos(\theta₄(t))⋅⎜──(\theta₄(t))⎟ ⎟⋅sin(\theta₂(t))⎟
      2                                  ⎝dt            ⎠ ⎟                ⎟
    dt                                                    ⎠                ⎠
    ────────────────────────────────────────────────────────────────────────

                                    2⎞                ⎞⎤
                    ⎛d             ⎞ ⎟                ⎟⎥
    cos(\theta₄(t))⋅⎜──(\theta₄(t))⎟ ⎟⋅sin(\theta₁(t))⎟⎥
                    ⎝dt            ⎠ ⎟                ⎟⎥
                                     ⎠                ⎠⎥
    ───────────────────────────────────────────────────⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎥
                                                       ⎦

```python
soln1 = sp.simplify(soln[0])
soln2 = sp.simplify(soln[1])
soln3 = sp.simplify(soln[2])
soln4 = sp.simplify(soln[3])
```

```python
solution = sp.solve([soln1, soln2, soln3, soln4], (ddv1, ddv2, ddv3, ddv4))
```

```python
sp.latex(solution)
```

```python

```