# Insurance Benefits
## Summary
Formulae for the valuation of traditional insurance benefits, for whole life, term and endowment. For a basic review, $T_x$ is the future life time continuous random variable for life $(x)$, and $K_x$ is the curtate future life time. And a new random variable is $K_{x}^{(m)}$ as the benefits which depends on the number of complete period of length $\displaystyle \frac{1} {m}$ years the insured person $(x)$ lived.

## Intro
Assume that the interest rate is a constant. Assume a continuous benefit, like $\$1$ per year would be rather paid in infinitesimal unit of $\$\mathrm{d}t$ in every interval $(t,t + \mathrm{d}t)$.

## Assumption
$Def$

**Basis**: set of assumptions used in life insurance or pension calculations

And in this chapter we use the *Standard Ultimate Survival Model*: **Makeham’s law** with $A = 0.00022$, $B = 2.7 \times 10^{− 6}$, $c = 1.124$, an **ultimate basis**.

We assume a constant interest rate, the mortality model of the *ultimate basis*.

- The **effective annual rate of interst**, $i$, *Compound Interest*
- **annual accumulation factor**, $\newcommand{\ffrac} {\displaystyle \frac} 1+i$
- **discount factor**, $\boxed{ \upsilon = \ffrac{1} {1+i} }$
- **force of interest** (instantameous rate of growth of value), $\boxed{ \delta = \log(1+i) }$
- **nominal annual rate of interest compounded $p$ times per year**, $\boxed{ i^{\,(p)} = p\left( \left( 1+i \right)^{1/p} -1 \right) \Leftrightarrow 1+i = \left( 1+ \ffrac{i^{\,(p)}} {p} \right)^p }$
- **periodic rate**, $\ffrac{i^{\,(p)}} {p}$
- **The effective rate of discount per year**: $\boxed{ d = 1 - \upsilon = i\upsilon = 1 - e^{-\delta} }$
- **the nominal rate of discount compounded $p$ times per year**: $\boxed{ d^{\,(p)} = p\left( 1 - \upsilon^{1/p} \right) \Leftrightarrow \left( 1 - \ffrac{d^{\,(p)}} {p} \right)^p = \upsilon }$

The payment is contingent of the death of insured.

## Valuation of insurance benefits

### Whole life insurance: the continuous case, $\bar{A}_x$
$Def$

**Whole life insurance**: insurance contract that pays benefit IMMEDIATELY upon **death** of the insured, no matter how far in the future.

But the present value of that future payment, which is ONE DOLLAR, depends on payment date, or the date of death, which is *UNKNOWN*, thus it is an $r.v.$.

$$\boxed{ Z = \upsilon^{T_x}=e^{-\delta T_x} = \frac{1} {(1+i)^{T_x}} }$$

**EPV**: the expected present value, or the actuarial present value:

$$\boxed{ \bar{A}_x = E[Z] = E[e^{-\delta T_x}] = \int_{0} ^{\infty} e^{-\delta t} {_{t}}p_x \mu_{x+t} \, \mathrm{d}t }$$

$\dagger$ The bar upon $A$ means that the one dollar benefit is paid right on death. $\ddagger$

$\dagger$ And the EPV is the integral, of the product of the following
- presnet value of $1$ dollar: $1 \cdot e^{-\delta t}$
- probability of payting that at time $t$: ${_{t}}p_{x}\mu_{x+t}\mathrm{d}t$ $\ddagger$
***
$$\boxed{ E[Z^2] = E[e^{-2\delta T_x}]= \int_{0} ^{\infty} e^{-2\delta t} {_{t}}p_x \mu_{x+t} \, \mathrm{d}t = {^2}{\bar{A}_x} }$$

$\odot$ the $2$ on the left upper side of $\bar{A}$ meaning that calculation is at force of interest $2 \delta$, which is equivalent, at a rate of interest $j$, where $1 + j = e^{2\delta} = (1+i)^2$. $\triangleleft$

Then if the death benefit is $S$ then we have

$$E[SZ]=\int_{0} ^{\infty} Se^{-\delta t} {_{t}}p_x \mu_{x+t} \, \mathrm{d}t = S\bar{A}_x \\
Var[SZ]:=V[SZ] = S^2 \left( {^2}{\bar{A}_x} - \left( \bar{A}_x \right)^2 \right)$$

$\odot$ Low values of $Z$ are associated with high values of $T_x$. $\triangleleft$

### Whole life insurance: the annual case, $A_x$
Suppose now that the benefit of $1$ dollar is payable at the end of the year of death of $(x)$, rather than immediately on death. Since we use $K_x$ to denote curtate future life time, the time to the end of the year of death of $(x)$ is $K_x + 1$. So that now

$$\boxed{ Z = \upsilon^{K_x + 1} } \\
\begin{align}
A_x &= E[\upsilon^{K_x + 1}] = \boxed{ \sum_{k = 0}^{\infty} \upsilon^{k+1} \cdot {_{k \mid}}q_{x} } \\
&= \upsilon \cdot q_x + \upsilon^2 \cdot {_{1 \mid}}q_{x} + \upsilon^3 \cdot {_{2 \mid}}q_{x} + \cdots
\end{align}$$

Each term represents the EPV of a death benefit of a dollar paid at time $k$ conditional on the death of $(x)$ in $(k-1,k]$.

And for the second moment, we have ${^2}A_x = E[\upsilon^{2(K_x + 1)}] = \boxed{ \sum_{k = 0}^{\infty} \upsilon^{2(k+1)} \cdot {_{k \mid}}q_{x} }$. And the variance is $S^2\left( {^2}A_x - \left( A_x \right)^2 \right)$

### Whole life insurance: the $1 /m \text{thly}$ case, $A_x^{(m)}$
$Def$

$K_x^{(m)}$, $r.v.$, where $m > 1$, as the future life time of $(x)$ in years rounded to lower $\ffrac{1} {m} \text{th}$ of a year. Commonly $m = 2,4,12$.

$$\boxed{ K_x^{(m)} = \frac{1} {m} \left \lfloor mT_x \right \rfloor }$$

For example:

$$\begin{array}{ccccc} \hline
T_x & K_x & K_x^{(2)} & K_x^{(4)} & K_x^{(12)} \\ \hline
23.675 & 23 & 23.5 & 23.5& {23\frac{8}{12}} \\
\upsilon^{T_x} & \upsilon^{K_{x}+1} & \upsilon^{K_{x}^{(2)} \, +1/2} & \upsilon^{K_{x}^{(4)} \, +1/4} & \upsilon^{K_{x}^{(12)} \, +1/12} \\ \hline
\end{array}$$
And for the probability:

$$Pr[K_x^{(m)} = k] = Pr[k \leq T_x < k + \frac{1} {m}] = {_{k \mid \frac{1} {m}}}q_x$$

For the expected value:

$$E[Z] = \boxed{ A_x ^{(m)} = \sum_{k=0}^{\infty} \upsilon^{\frac{k+1} {m}} {_{\frac{k} {m} \mid \frac{1} {m}}}q_x} = \upsilon^{1/m} {_{\frac{1} {m}}}q_x + \upsilon^{2/m} {_{{\frac{1} {m}} \mid {\frac{1} {m}}}}q_x + \upsilon^{3/m} {_{{\frac{2} {m}} \mid {\frac{1} {m}}}}q_x + \cdots $$

### Recursions
Although paying the death benefit at the year end, but sometimes we have to deal with the annual life tables. We can use **backwards recursion** to find the $A_x$.

Let the highest age in the table be $\omega$, so that we can assume that all lives expire by age $\omega$, expecially that $q_{\omega - 1} = 1$. Or if there's not a highest age, just choose one so that $q_{\omega - 1}$ is close enough to $1$.

And in that case, $K_{\omega - 1} = 0$

$$\boxed{ A_{\omega - 1} = E\left[ \upsilon ^{1+K_{\omega - 1}} \;\right] = \upsilon }$$

So that

$$\begin{align}
A_x &= \sum_{k=1}^{\omega -x-1} \upsilon ^{k+1} \cdot {_{k}}p_x \cdot q_{x+k} \\
&= \upsilon \cdot q_x + \upsilon^2 \cdot p_x \cdot q_{x+1} + \upsilon^3 \cdot {_{2}}p_{x} \cdot q_{x+2} + \upsilon^4 \cdot {_{3}}p_{x} \cdot q_{x+3} + \cdots \\
&= \upsilon \cdot q_x + \upsilon \cdot p_x \left( \upsilon \cdot q_{x+1} + \upsilon^2 \cdot p_{x+1} \cdot q_{x+2} + \upsilon^3 \cdot {_{2}}p_{x+1} \cdot q_{x+3} + \cdots \right) \\
&= \boxed{\upsilon \cdot q_x + \upsilon \cdot p_x \cdot A_{x+1}}
\end{align}$$

And with this formula we can calculate $A_{x_{_0}}$ of the minimum age, backwards from $A_{\omega - 1} = \upsilon$.

And more terms backward are
0. $q_{\omega - 1} = 1$
1. $A_{\omega}$ not exists
2. $A_{\omega - 1} = v$
3. $A_{\omega - 2} = v q_{\omega - 2} + v \cdot p_{\omega - 2} \cdot v$
4. $A_{\omega - 3} = v q_{\omega - 3} + v^2 \cdot p_{\omega - 3} q_{\omega - 2} + v^3 p_{\omega - 3} p_{\omega - 2}$
5. $A_{\omega - i} = v \cdot q_{w-i} + \displaystyle \sum_{j=2}^i \left( v^j \left( \prod_{k=i-j+2}^{i} p_{\omega - k} \right) q_{\omega - (i-j+1)}\right) $
***
And for monthly benefits, the similar formula can be derived like:

$$\begin{align}
A_{x}^{(m)} &= \upsilon^{1/m}\cdot{_{\frac{1} {m}}}q_x + \upsilon^{2/m} \cdot {_{\frac{1} {m}}}p_x \cdot {_{\frac{1} {m}}} q_{x+\frac{1} {m}} + \upsilon^{3/m} \cdot {_{\frac{2} {m}}}p_x \cdot {_{\frac{1} {m}}} q_{x+\frac{2} {m}} + \cdots \\
&= \upsilon^{1/m} \cdot {_{\frac{1} {m}}}q_x + \upsilon^{1/m} \cdot {_{\frac{1} {m}}}p_x \left( \upsilon^{1/m} \cdot {_{\frac{1} {m}}}q_{x+\frac{1} {m}} + \upsilon^{2/m} \cdot {_{\frac{1} {m}}}p_{x+\frac{1} {m}} \cdot {_{\frac{1} {m}}}q_{x+\frac{2} {m}} + \cdots \right) \\
&= \boxed{\upsilon^{1/m} \cdot {_{\frac{1} {m}}}q_x + \upsilon^{1/m} \cdot {_{\frac{1} {m}}}p_x \cdot A^{(m)}_{x + \frac{1} {m}}}
\end{align}$$

>**e.g.**
>
> Using the Standard Ultimate Survival Model, and an interest rate of $5\%$ per year effective, calculate the mean and standard deviation of the present value of a benefit of $100000$ dollar payable $(\text{a})$ immediately on death, $(\text{b})$ at the end of the month of death, $(\text{c})$ at the end of the year of death for lives aged $20$, $40$, $60$, $80$ and $100$, and comment on the results.
>
> $(\text{a})$ Mean: $100000\bar{A}_{x}$; Standard Deviation: $100000 \sqrt{\sideset{^2}{_x}{\bar{A}} - \left( \bar{A}_{x} \right)^2}$; for $x = 20, 40, 60, 80$, with the effective rate of interest $j = (1+i)^2 - 1 = 10.25\%$
>
> $(\text{b})$ and  $(\text{c})$ just replace each $\bar{A}$ to $A^{(12)}$ and $A_{x}$.

### Term insurance
#### The continuous case $\bar {A}_{{x:\overline {n}|}}^{1}$

Now the death benefit is payable only if the policyholder dies *within* a fixed term of $n$ years. So now the present value, of a benefit of $1$ dollar, is

$$Z = \begin{cases}
\upsilon^{T_x} = e^{-\delta T_x} & \text{ if } T_x \leq n \\
0 & \text{ if } T_x > n
\end{cases}$$

And here the EPV is

$$\boxed{ E[Z] = \bar {A}_{{x:\overline {n}|}}^{1} = \int_{0} ^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \,}$$

And similarly, the expected value of the square of the present value is

$$\boxed{ E[Z^2] = \sideset{^2}{_{{x:\overline {n}|}}^{1}}{\bar{A}} = \int_{0} ^{n} e^{-2\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \,}$$

#### The annual case ${A}_{{x:\overline {n}|}}^{1}$

Now the death benefit is payable at the *end* of the year of death, provided that the policyholder dies *within* a fixed term of $n$ years. So now the present value, of a benefit of $1$ dollar, is

$$Z = \begin{cases}
\upsilon^{K_x + 1} & \text{ if } K_x \leq n - 1 \\
0 & \text{ if } K_x \geq n
\end{cases}$$

And here the EPV is

$$\boxed{ E[Z] = {A}_{{x:\overline {n}|}}^{1} = \sum_{k = 0} ^{n-1} \upsilon^{k + 1} {_{k \mid}}q_{x} }$$

And similarly, the expected value of the square of the present value is

$$\boxed{E[Z^2] = {^2}{A}_{{x:\overline {n}|}}^{1} = \sum_{k = 0} ^{n-1} \upsilon^{2( k + 1)} {_{k \mid}}q_{x} }$$

#### The $1 /m \text{thly}$ case, ${A^{(m)}}{_{x:\overline {n}|}^{1}}$
Now the death benefit is payable at the *end* of the $1 /m \text{thly}$ year of death, provided that the policyholder dies *within* a fixed term of $n$ years. So now the present value, of a benefit of $1$ dollar, is

$$Z = \begin{cases}
\upsilon^{K_x^{(m)} \; +  \frac{1} {m}} & \text{ if } K_x^{(m)} \leq n - \frac{1} {m} \\
0 & \text{ if } K_x^{(m)} \geq n
\end{cases}$$

And here the EPV is

$$\boxed{ E[Z] = {A^{(m)}}{_{x:\overline {n}|}^{1}} = \sum_{k = 0} ^{mn-1} \upsilon^{(k + 1)/m} {_{\frac{k} {m} \mid \frac{1} {m}}}q_{x} }$$

And similarly, the expected value of the square of the present value is

$$\boxed{ E[Z^2] = {^2}{A^{(m)}}{_{{x:\overline {n}|}}^{1}} = \sum_{k = 0} ^{n-1} \upsilon^{2( k + 1 )/m} {_{k \mid}}q_{x} }$$

### Pure Endowment
$\odot$ "Pure Endowment" is a term. And "Endowment" normally means "Endowment Insurance". $\triangleleft$

$Def$

A $n\text{-year}$ pure endowment with sum insured $100000$ dollars, issued to $(x)$, will pay $100000$ dollars in $n$ years if $(x)$ is still alive at that time

So now the present value, of a benefit of $1$ dollar, is

$$Z = \begin{cases}
0 & \text{ if } T_x < n & P = 1 - {_{n}}p_{x}\\
\upsilon^{T_x} & \text{ if } T_x \geq n & P = {_{n}}p_{x}
\end{cases}$$

So that the EPV is

$${_n}E_{x}:= \boxed{ E[Z] = {A}{_{{x:\overline {n}|}}^{\;\;1}} = \upsilon^n \cdot {_{n}}p_{x}  }$$

### Endowment insurance
It's a combination of a *term insurance* and a *pure endowment*. The sum insured is payable on the death of $(x)$ should $(x)$ die within a fixed term, say $n$ years, but if $(x)$ survives for $n$ years, the sum insured is payable at the end of the $n$th year.

So the present value is

$$\begin{align}
Z &= \begin{cases}
\upsilon^{T_x} = e^{-\delta T_x} & \text{ if } T_x < n \\
\upsilon^n & \text{ if } T_x \geq n
\end{cases} \\
&= \upsilon^{\min{(T_x \, , \, n)}} \\
&= e^{-\delta \min{(T_x \, , \, n)}}
\end{align}
$$

Then the EPV should be

$$\begin{align}
E[Z] &= \int_{0} ^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t &+ &\int_{n} ^{\infty} e^{-\delta n} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \int_{0} ^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t &+ &e^{-\delta n} {_{n}}p_{x} \\
&= \bar {A}_{{x:\overline {n}|}}^{1} &+ &{A}{_{{x:\overline {n}|}}^{\;\;1}}
\end{align}$$

In complete actuarial notation, it would be like

$$\boxed{ \bar {A}_{{x:\overline {n}|}} = \bar{A}_{{x:\overline {n}|}}^{1} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \, }$$

And similarly, the expected value of the squared present value of the benefit is

$$\boxed{ {^{2}}\bar{A}_{{x:\overline {n}|}} = \int_{0} ^{n} e^{-2\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t + e^{-2\delta n} {_{n}}p_{x} = {^{2}}\bar{A}_{{x:\overline {n}|}}^{1} + {^{2}}{A}{_{{x:\overline {n}|}}^{\;\;1}} \, }$$

***

And if the benefit is paid at the end of the year of death, then the present value would be like

$$\begin{align}
Z &= \begin{cases}
\upsilon^{K_x + 1} & \text{ if } K_x \leq n - 1 \\
\upsilon^n & \text{ if } K_x \geq n
\end{cases} \\
&= \upsilon^{\min{(K_x + 1,n)}}
\end{align}$$

So that the EPV is like

$$\boxed{ \sum_{k=0} ^{n-1} \upsilon^{k+1} {_{k\mid}}q_{x} + \upsilon^n  P[K_x \geq n] = {A}_{{x:\overline {n}|}}^{1} + \upsilon^n {_{n}}p_{x} \, }$$

And in complete actuarial notation, it will be like

$$\boxed{ {A}_{{x:\overline {n}|}} = {A}_{{x:\overline {n}|}}^{1} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \, }$$

Similarly, the expected value of the squared present value of the benefit is

$$\boxed{ {^{2}}{A}_{{x:\overline {n}|}} = \sum_{k=0} ^{n-1} \upsilon^{2(k+1)} {_{k\mid}}q_{x} + \upsilon^{2n} {_{n}}p_{x} = {^{2}}{A}_{{x:\overline {n}|}}^{1} + {^{2}}{A}{_{{x:\overline {n}|}}^{\;\;1}} \, }$$

***

Finally if the death benefit is payable at the end of the $1 /m \text{th}$ year of death, then the present value of the benefit is

$$\begin{align}
Z &= \begin{cases}
\upsilon^{K_x^{(m)} \; +  \frac{1} {m}} & \text{ if } K_x^{(m)} \leq n - \frac{1} {m} \\
\upsilon^n & \text{ if } K_x^{(m)} \geq n
\end{cases}\\
&= \upsilon^{\min{(K_x^{(m)} \; +  \frac{1} {m}\:,\: n)}}
\end{align}$$

Here the EPV of the benefit is

$$\sum_{k = 0} ^{mn-1} \upsilon^{(k + 1)/m} {_{\frac{k} {m} \mid \frac{1} {m}}}q_{x} + \upsilon^n P[K_x^{(m)} \geq n] = {A^{(m)}}{_{x:\overline {n}|}^{1}} + \upsilon^n {_{n}}p_{x}$$

And in complete actuarial notation we have

$$\boxed{ A^{(m)}_{x:\overline {n}|} = {A^{(m)}}{_{x:\overline {n}|}^{1}} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \, }$$

### Deferred insurance benefits
Deferred insurance refers to insurance which does not begin to offer death benefit cover until the end of a deferred period.

For example, a death benefit will be paid immediately on the death of $(x)$, provided that $(x)$ dies between ages $x+u$ and $x + u + n$. So in this condition, the present value random variable ($p.v.\;r.v.$ later) is

$$Z = \begin{cases}
0 & \text{ if } T_x < u \text{ or } T_x \geq u+n \\
e^{-\delta T_x} & \text{ if } u \leq T_x < u+n
\end{cases}$$

And the actuarial notation for the EPV of the deferred term insurance benefit is

$$\begin{align}
{_{u\mid}}\bar{A}_{{x:\overline {n}|}}^{1} &= \int_{u} ^{u+n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&\stackrel{s = t - u}= \int_{0} ^{n} e^{-\delta(s+u)} {_{s+u}}p_{x} \mu_{x+s+u} \, \mathrm{d}s \\
&= \boxed{ e^{-\delta u} {_{u}}p_{x} \int_{0} ^{n} e^{-\delta s} {_{s}}p_{x+u} \mu_{x+s+u} \, \mathrm{d}s \, }\\
&= \boxed{ e^{-\delta u} {_{u}}p_{x} \bar{A}_{x+u:\overline {n}|}^{1} \,} \\
&= \boxed{ {_{u}}E_{x}\bar{A}_{x+u:\overline {n}|}^{1} \,}
\end{align}$$

Another fomula is

$$\begin{align}
{_{u\mid}}\bar{A}_{{x:\overline {n}|}}^{1} &= \int_{u} ^{u+n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \int_{0} ^{u+n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t - \int_{0} ^{u} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \boxed{ \bar{A}_{{x:\overline {u+n}\displaystyle{|}}}^{1} - \bar{A}_{{x:\overline {u}|}}^{1}}
\end{align}$$

$\odot$ Thus, the EPV of a deferred term insurance benefit can be found by differencing the EPVs of term insurance benefits for terms $u + n$ and $u$. $\triangleleft$

Then we can use deffered term insurance polices to decompose the $n\text{-year}$ term insurance

$$\begin{align}
\bar {A}_{{x:\overline {n}|}}^{1} &= \int_{0}^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \sum_{r=0} ^{n-1} \int_{r}^{r+1} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \boxed{ \sum_{r=0} ^{n-1} {_{r\mid}}\bar{A}_{{x:\overline {1}|}}^{1}}
\end{align}$$

and similarly for whole life insurance policy.

$$\begin{align}
\bar {A}_{x} &= \int_{0}^{\infty} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \sum_{r=0} ^{\infty} \int_{r}^{r+1} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\
&= \sum_{r=0} ^{\infty} {_{r\mid}}\bar{A}_{{x:\overline {1}\displaystyle{|}}}^{1}
\end{align}$$

In particular, we should note that

$$\begin{align}
A_x &= \boxed{{A}_{{x:\overline {n}|}}^{1} + {_{n\mid}}A_x }  \\
{A}_{{x:\overline {n}|}}^{1} &= A_x - {_{n\mid}}A_x  \\
&= A_x - \upsilon^n {_{n}}p_{x} A_{x+n}
\end{align}$$

And we can also get that

$$\begin{align}
{_{n\mid}}A_x &= A_x - {A}_{{x:\overline {n}|}}^{1}\\
&= \sum_{k=0}^{\infty} \upsilon^{k+1} {_{k\mid}}q_{x} - \sum_{k=0}^{n-1} \upsilon^{k+1} {_{k\mid}}q_{x} \\
&= \sum_{k=n}^{\infty} \upsilon^{k+1} {_{k\mid}}q_{x} \\
&= \upsilon^{n} \cdot {_{n}}p_{x} \cdot A_{x+n}
\end{align}$$

>**e.g.** Given $F_0(t) = 1 - \left( 1 - \ffrac{t} {10} \right)^{(1/2)}$, $t \in [0,10]$, find the $A_x$ using recursion, using $i=0.07$.
>
> First we need to find $\upsilon = \ffrac{1} {1+0.07} = 0.935$; then
>
>$${_{t}}p_{x}= S_x(t)= \frac{S_0(x+t)} {S_0(x)}=\frac{\left( 1-(x+t)/10 \right)^{1/2} } {\left( 1 - x/10 \right)^{1/2}}= \left( \frac{10-(t+x)} {10-x} \right)^{1/2}$$
>
>$$p_{x} = \left( \frac{9-x} {10-x} \right)^{1/2}, q_{x} = 1-p_{x}$$
>
>Then using the regression: $A_x = \upsilon q_{x} + \upsilon p_{x} A_{x+1} $, from the initial condition: $q_{\omega-1}=1,A_{\omega-1}=\upsilon$
>
>$$\begin{array}{cccc}\hline
x & p_x & q_x & A_x \\\hline
0 & 0.948683 & 0.051317 & 0.630980951 \\
1 & 0.942809 & 0.057191 & 0.657577631 \\
2 & 0.935414 & 0.064586 & 0.685628879 \\
3 & 0.925820 & 0.074180 & 0.715230902 \\
4 & 0.912871 & 0.087129 & 0.746491857 \\
5 & 0.894427 & 0.105573 & 0.779537603 \\
6 & 0.866025 & 0.133975 & 0.814524014 \\
7 & 0.816497 & 0.183503 & 0.851667972 \\
8 & 0.707107 & 0.292893 & 0.891346428 \\
9 & 0        & 1        & 0.934579439 \\\hline
\end{array}$$
>
>Or use the definition: $A_0 = \displaystyle \sum_{k=0}^{9} \upsilon^{k+1} \cdot {_{k}}p_{0} \cdot q_{k},\dots, \boxed{ A_x = \sum_{k=0}^{\omega-1-x} \upsilon^{k+1} \cdot {_{k}}p_{x} \cdot q_{x+k}\,},A_9 = \sum_{k=0}^{0} \upsilon^{k+1} \cdot {_{k}}p_{9} \cdot q_{9+k}$

>**e.g.** Exercise 4.1
>
>Given $i = 6\%$ and the following table
>
>$$\begin{array}{ccc} \hline
x & l_x & A_x \\ \hline
35 & 100000.00 & 0.151375 \\
36 &  99737.15 & 0.158245 \\
37 &  99455.91 & 0.165386 \\
38 &  99154.72 & 0.172804 \\
39 &  98831.91 & 0.180505 \\
40 &  98485.68 & 0.188492 \\ \hline
\end{array}$$
>
>($\text{a}$) ${_{5}}E_{35}$
>
>>First we cauculate $\upsilon = \ffrac{1} {1+0.06} = 0.943396$

>>${_5}p_{35} = \ffrac{l_{35+5}} {l_{35}} = 0.984857$

>>${_5}E_{35} = \upsilon^5 \cdot {_5}p_{35} = 0.7359423$

> ($\text{b}$) ${A}_{{35:\overline {5}\displaystyle{|}}}^{1}$

>> $$\begin{align}
{A}_{{35:\overline {5}|}}^{1} &= \sum_{k=0}^{5-1} \upsilon^{k+1} \cdot {_{k\mid}}p_{35} \\
&= \upsilon^1 \cdot \frac{l_{35} - l_{36}} {l_{35}} + \upsilon^2 \cdot \frac{l_{36} - l_{37}} {l_{35}} + \upsilon^3 \cdot \frac{l_{35} - l_{35}} {l_{35}} + \upsilon^4 \cdot \frac{l_{35} - l_{35}} {l_{35}} + \upsilon^5 \cdot \frac{l_{35} - l_{35}} {l_{35}} \\
&= 0.012656
\end{align}$$

> ($\text{c}$) ${_{5\mid}}A_{35}$

>>$$\begin{align}
{_{5\mid}}A_{35} &= \upsilon^5 \cdot {_{5}}p_{35} \cdot A_{40} \\
&= A_{35} - {A}_{{35:\overline {5}\displaystyle{|}}}^{1} \\
&= 0.151375 - 0.012656 = 0.138719
\end{align}$$

>**e.g.** Exercise 4.5
>
>Show that
>
>$${A}_{{x:\overline {n}|}} = \sum_{k=0}^{n-2} \upsilon^{k+1} {_{k}}q_{x} + \upsilon^n \cdot {_{n-1}}p_{x}$$
>
>$$\begin{align}
{A}_{{x:\overline {n}|}} &= {A}{_{{x:\overline {n}|}}^{1}} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \\
&= \left( \sum_{k=0}^{n-1} \upsilon^{k+1} \cdot {_{k\mid}}q_{x}\right) + \upsilon^n \cdot {_{n}}p_{x} \\
&= \sum_{k=0}^{n-2} \upsilon^{k+1} {_{k}}q_{x} + \upsilon^{n-1+1} {_{n-1\mid}}q_{x} + \upsilon^n \cdot {_{n}}p_{x} \\
&= \sum_{k=0}^{n-2} \upsilon^{k+1} {_{k}}q_{x} + \upsilon^n \cdot {_{n-1}}p_{x}
\end{align}$$

>**e.g.** Exercise 4.11
>
>- Under an endowment insurance issued to a life aged $x$, let $X$ denote the present value of a unit sum insured, payable at the moment of death or at the end of the $n\text{-year}$ term.
>- Under a term insurance issued to a life aged $x$, let $Y$ denote the present value of a unit sum insured, payable at the moment of death within the $n\text{-year}$ term.
>
>Given that $V [ X ] = 0.0052, \upsilon^n = 0.3, {_{n}}p_{x} = 0.8, E [ Y ] = 0.04$, calculate $V [ Y ]$.
>
>>So far we already know that
>>
>>$$\begin{array}{cc}
X = \begin{cases}
\upsilon^{T_{x}} & \text{ if } T_{x} \leq n \\
\upsilon^{n} & \text{ if } T_{x} > n
\end{cases} & Y = \begin{cases}
\upsilon^{T_{x}} & \text{ if } T_{x} \leq n \\
0 & \text{ if } T_{x} > n
\end{cases}
\end{array}$$
>>
>>Obviously we need to construct a Intermediate variable to connect them
>>
>>$$Z = X-Y = \begin{cases}
0 & \text{ if } T_{x} \leq n \\
\upsilon^{n} & \text{ if } T_{x} > n
\end{cases}$$
>>
>>A pure endowment! So that now
>>
>>$$\begin{align}
V[Y] &= V[X] + V[Z] - 2Cov[X,Z] \\
&= V[X] + E[Z^2] - \left( E[Z] \right)^2 - 2\left( E[XZ] - E[X] \cdot E[Z] \right)\\
&= V[X] + \upsilon^{2n} \cdot {_{n}}p_{x} - \left( \upsilon^{n} \cdot {_{n}}p_{x} \right)^2 - 2\left( E[Z^2] - \left( E[Y] + \upsilon^n \cdot {_{n}}p_{x} \right) \cdot E[Z] \right)\\
&= 0.0052 + 0.3^2 \times 0.8 -\left( 0.3 \times 0.8 \right)^2 \\
&\;\;\;\;-2 \times \left( 0.3^2 \times 0.8 - \left( 0.04 + 0.3 \times 0.8 \right) \times 0.3 \times 0.8 \right)\\
&= 0.01
\end{align}$$

## Relating $\bar{A}_x$, $A_x$, and $A_{x}^{(m)}$
### UDD
$${_{s}}q_{y} \overset{\mathrm{UDD}}{ = } s\cdot q_{y} \Rightarrow \frac{\mathrm{d}} {\mathrm{d}s}\left({_{s}}q_{y}\right) = q_{y} \\
f_{y}(s) = {_{s}}p_{y} \cdot \mu_{y+s}$$
$$\Rightarrow {_{s}}p_{y} \cdot \mu_{y+s} \overset{\mathrm{UDD}}{ = } \:q_y$$

Then we have

$$\begin{align}
\bar{A}_x &= \int_{0}^{\infty} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \; \mathrm{d}t = \sum_{k=0} ^{\infty} \int_{k}^{k+1} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \; \mathrm{d}t \\
&\overset{t=k+s}{ = } \sum_{k=0} ^{\infty} \int_{0}^{1} e^{\delta}e^{-\delta s}e^{-\delta}e^{-\delta k} {_{k+s}}p_{x} \mu_{x+k+s} \; \mathrm{d}(k+s) \\
&= \sum_{k=0} ^{\infty} \int_{0}^{1}e^{(1-s)\delta}e^{-(1+k)\delta} {_{k}}p_{x}\cdot {_{s}}p_{x+k} \mu_{x+k+s} \mathrm{d}s \\
&= \sum_{k=0} ^{\infty} {_{k}}p_{x} \upsilon^{k+1} \int_{0}^{1}e^{(1-s)\delta} {_{s}}p_{x+k} \mu_{x+k+s} \mathrm{d}s \\
&\overset{\mathrm{UDD}}{ = }  \sum_{k=0} ^{\infty} {_{k}}p_{x} \cdot q_{x+k} \upsilon^{k+1} \int_{0}^{1}e^{(1-s)\delta} \mathrm{d}s =A_x \frac{e^{\delta} - 1} {\delta}
\end{align}$$

So finally since $e^{\delta} = 1 + i$, so that

$$\boxed{\bar{A}_x \approx \frac{i} {\delta}A_x}$$

Similarly, we have a table

$$\begin{array}{ccc} \hline
&\text{UDD Method} & \text{Similar idea} \\ \hline
\text{Whole life} & \bar{A}_x \approx \frac{i} {\delta}A_x & A_x^{(m)} = \frac{i} {i^{(m)}} \; A_x \\
n\text{-year term} &  \bar {A}_{{x:\overline {n}|}}^{1} \approx \frac{i} {\delta}{A}_{{x:\overline {n}|}}^{1} & {A^{(m)}}{_{x:\overline {n}|}^{1}} = \frac{i} {i^{(m)}} \; {A}_{{x:\overline {n}|}}^{1} \\
\text{Endowment} & \bar {A}_{{x:\overline {n}|}}\approx \frac{i} {\delta} \bar {A}_{{x:\overline {n}|}}^{1} + \upsilon^n {_{n}}p_{x} & A^{(m)}_{x:\overline {n}|} = \frac{i} {i^{(m)}} \; {A}_{{x:\overline {n}|}}^{1} + \upsilon^n {_{n}}p_{x} \\ \hline
\end{array}$$

And the deferred one: ${_{n|}}\bar{A}_x \approx \ffrac{i} {\delta} {_{n|}}{A}_x$

$\dagger$ The $i^{(m)}$ is defined by

$$1+i = \left( 1+ \frac{i^{(m)}} {m} \right)^m$$

### Using the claims acceleration approach
>**e.g.** From the relation of $A_x$ and $A_x^{(4)}$
>
>From year $K_x$ to $K_x + 1$, four different payment may happen for $A_x^{(4)}$, which are $K_x + 1/4$, $K_x + 2/4$, $K_x + 3/4$, $K_x + 4/4$. So that if we assume that the deaths occur evenly over the year, then the average payment time is

>$$\frac{1} {4} \left( K_x + 1/4 + K_x + 2/4 + K_x + 3/4 + K_x + 4/4\right) = K_x + \frac{5} {8}$$
>
>NOT $\ffrac{2} {4}$

$Conclusion$

For $K_{x}^{(m)}$, we have the average is

$$\frac{1} {m} \left( K_x + 1/m + K_x + 2/m + \cdots + K_x + m/m\right) = K_x + \frac{m+1} {2m}$$

So that in general, for an $m-\text{thly}$ death benefit, assuming deaths are uniformly distributed over the year of age, the average time of payment of the death benefit is $( m + 1 )/ 2m$ in the year of death. So we have the approximation

$$\begin{align}
A_x^{(m)} &\approx q_x \cdot \upsilon^{\frac{m+1} {2m}} + {_{1|}}q_x \cdot \upsilon^{1+ \frac{m+1} {2m}} + {_{2|}}q_x \cdot \upsilon^{2+ \frac{m+1} {2m}} + \cdots \\
&= \sum_{k=0}^{\infty} {_{k|}}q_x \cdot \upsilon^{k+ \frac{m+1} {2m}} \\
&= \left( 1+i \right)^{\frac{m-1} {2m}} \sum_{k=0}^{\infty} {_{k|}}q_x \cdot \upsilon^{k+1}
\end{align}$$

That is

$$\boxed{ A_x^{(m)} \approx \left( 1+i \right)^{\frac{m-1} {2m}} A_x }$$

$\dagger$ Note that

$$A_x^{(m)} = \sum_{k=0}^{\infty} {_{\frac{k} {m}|\frac{1} {m}}}q_x \cdot \upsilon^{(k+1)/m} \neq \sum_{k=0}^{\infty} {_{k|}}q_x \cdot \upsilon^{k+ \frac{m+1} {2m}}$$ $\ddagger$

And for the continuous benefit EPV, $\bar{A}_x$, we can just let $m \to \infty$ so that

$$\boxed{ \bar{A}_x \approx \left( 1+i \right)^{1/2} A_x }$$

This implies that assume that lives die uniformly through the year, the benefit paid immediately on death on average is half a year ealier than the benefit valued by $A_x$.

Similarly for the endowment

$$\boxed{ \bar{A}_{x:\overline{n}|} \approx (1+i)^{1/2} A^1_{x:\overline{n}|} + \upsilon^n \cdot {_{n}}p_x}$$

$$\boxed{ {A}_{x:\overline{n}|}^{(m)} \approx (1+i)^{1/2} {A^{(m)}}{_{x:\overline {n}|}^{1}} + \upsilon^n \cdot {_{n}}p_x}$$

## Variable insurance benefits
Consider an event $E$, then the indicator random variables is defined as

$$I(E) = \begin{cases}
1 & \text{ if } E \text{ is true} \\
0 & \text{ if } E \text{ is not true}
\end{cases}$$

Now we can see that we use the expectation of this variable to replace the probability of the event.

$$\newcommand{\EE}{\mathbb{E}}\EE[I(E)] = \Pr[E]$$

However in continuous condition, the indicator variable is defined as $I(t < T_x \leq t + \mathrm{d}t)$, so that

$$\begin{align}
\EE[I(t < T_x \leq t + \mathrm{d}t)] &= \Pr[t < T_x \leq t + \mathrm{d}t] \\
&= \Pr[t < T_x] \cdot \Pr[T_x \leq t + \mathrm{d}t | t < T_x] \\
&\approx {_{t}}p_{x} \cdot \mu_{x+t} \mathrm{d} t
\end{align}$$

>**e.g.**
>
>For a discrete case, PV: $Z = 1000 \cdot I\left( T_x \leq 10 \right) \upsilon^{10} + 2000 \cdot I\left( 10 < T_x \leq 20 \right) \upsilon^{20}$. Then we have the EPV
>
>$$1000 \cdot {_{10}}q_{x} \upsilon^{10} + 2000 \cdot {_{10|10}}q_{x} \upsilon^{20}$$
>***
>An **increasing insurance** policy with a death benefit of $T_x$ payable at the moment of death. That is, the benefit is the number of years lived by an insured life from age $x$ to his or her death. So it's not hard to find the EPV
>
>$$\int_{0}^{\infty} t e^{-\delta t}{_{t}}p_{x} \cdot \mu_{x+t} \; \mathrm{d} t:=\left( \bar{I}\bar{A}\right)_x$$
>
>Here's how to use indicator to find this value
>
>$$\begin{align}
\left( \bar{I}\bar{A}\right)_x &= \EE\left[\lim_{\mathrm{d}t \to 0} \sum_{i=1}^{\infty} t_i\upsilon^{t_i} I\left( t_i < T_x \leq t_i + \mathrm{d}t \right)\right] \\
&= \lim_{\mathrm{d}t \to 0} \sum_{i=1}^{\infty} t_i\upsilon^{t_i} \EE\left[ I\left( t_i < T_x \leq t_i + \mathrm{d}t \right) \right] \\
&=\int_{0}^{\infty} t \cdot \upsilon^{t} \cdot {_{t}}p_{x} \cdot \mu_{x+t} \mathrm{d} t \\
\end{align}$$
>
>First we define the present value, PV: $Z = T_x e^{-\delta T_x}$
>
>$$\EE[Z^k] = \int_{0}^{\infty} \left( t e^{-\delta t} \right)^k {_{t}}p_{x} \cdot \mu_{x+t} \; \mathrm{d} t$$
>
>And if the policy ceases after $n$ years, we have
>
>$$\left( \bar{I}\bar{A}\right)^{1}_{x:\overline{n}|} = \int_{0}^{n} t e^{-\delta t}{_{t}}p_{x} \cdot \mu_{x+t} \; \mathrm{d} t$$
>
>Another common one policy is with geometrically increasing benefit. One form is to return the profits on the premium back to the insurer. Another is like
>
>>Benefit would be $(1+j)^k$ if death happens in $(x+k,x+k+1]$. So that the EPV would be
>>
>>$$\sum_{k=0}^{n-1} (1+j)^k \upsilon^{k+1} {_{k|}}q_{x} = \frac{1} {1+j} \sum_{k=0}^{n-1} \left(\frac{1+j} {1+i} \right)^{k+1} {_{k}}p_{x} q_{x+k}$$
>>
>>So that we can define $v^* = \ffrac{1+j} {1+i}$, and $i^* = \ffrac{1} {v^*} - 1 = \ffrac{i-j} {1+j}$, and finally the EPV would be, under the assumption $j<i$
>>
>>$$\frac{1} {1+j} \sum_{k=0}^{n-1} \left(v^* \right)^{k+1} {_{k|}}p_{x} q_{x+k}:= A^{1}_{x:\overline{n}|i^*}$$

>**e.g.** Example 4.6
>
>$n\text{-year}$ term insurance policy issued to $(x)$, under which the death benefit is $k+1$ if death occurs between ages $x+k$ and $x+k+1$, for $k = 1, 2, \dots, n-1$
>
>We can directly write out the EPV of this death benefit:
>
>$$\left( IA \right)^{1}_{x:\overline{n}|}:=\sum_{k=0}^{n-1} \upsilon^{k+1} \cdot (k+1) {_{k|}}q_{x}$$
>
>And by the way if the term $n$ is infinite, we can denote that as
>
>$$\left( IA \right)_{x}:=\sum_{k=0}^{\infty} \upsilon^{k+1} \cdot (k+1) {_{k|}}q_{x}$$

>However to find the variance
>
>$$Z = \begin{cases}
\left( K_x + 1\right) \upsilon^{K_x + 1} & \text{ if } K_x \leq n \\
0 & \text{ if } K_x > n
\end{cases}$$
>
>$$E[Z^2] = \sum_{k=0}^{n-1} \upsilon^{2(k+1)} (l+k)^2 {_{k|}}q_{x}$$
>
>So that the variance is just $V[Z] = \displaystyle \sum_{k=0}^{n-1} \upsilon^{2(k+1)} (l+k)^2 {_{k|}}q_{x} - \left( \left( IA \right)^{1}_{x:\overline{n}|} \right)^2$

<center> **Summary Table** </center>

Before everything...

- The **effective annual rate of interst**, $i$, *Compound Interest*
- **discount factor**, $\upsilon = \ffrac{1} {1+i}$
- **force of interest**, $\delta = \log(1+i)$
- **The effective rate of discount per year**, $d = 1 - \upsilon = i\upsilon = 1 - e^{-\delta}$

<center> Insurance </center>

$$\begin{array}{ccc} \hline
& \text{Whole life} & \text{Term} \\ \hline
\text{Continuous} & \bar{A}_x = \displaystyle \int_{0} ^{\infty} e^{-\delta t} {_{t}}p_x \mu_{x+t} \, \mathrm{d}t & \bar {A}_{{x:\overline {n}|}}^{1} = \displaystyle \int_{0} ^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t \\[1em]
\text{Annual} & A_x = \displaystyle \sum_{k = 0}^{\infty} \upsilon^{k+1} \cdot {_{k \mid}}q_{x} & {A}_{{x:\overline {n}|}}^{1} = \displaystyle \sum_{k = 0} ^{n-1} \upsilon^{k + 1} {_{k \mid}}q_{x} \\[1em]
m\text{thly} & A_x ^{(m)} = \displaystyle \sum_{k=0}^{\infty} \upsilon^{(k + 1)/m} {_{\frac{k} {m} \mid \frac{1} {m}}}q_x & {A^{(m)}}{_{x:\overline {n}|}^{1}} = \displaystyle \sum_{k = 0} ^{mn-1} \upsilon^{(k + 1)/m} {_{\frac{k} {m} \mid \frac{1} {m}}}q_{x} \\[1em] \hline
\end{array}
$$
***

<center> Recursion </center>

$$\boxed{ A_x = \sum_{k=0}^{\omega-1-x} \upsilon^{k+1} \cdot {_{k}}p_{x} \cdot q_{x+k} = \upsilon \cdot q_{x} + \upsilon \cdot p_{x} \cdot A_{x+1}}$$

$$A_{x}^{(m)} = \upsilon^{1/m} \cdot {_{\frac{1} {m}}}q_{x} + \upsilon^{1/m} \cdot {_{\frac{1} {m}}}p_{x} \cdot A_{x + \frac{1} {m}}^{(m)} $$
***

<center> Endowment </center>

$$\begin{array}{cc} \hline
\text{Pure Endowment} & \text{Endowment} \\ \hline
{_n}E_{x} = {A}{_{{x:\overline {n}|}}^{\;\;1}} = \upsilon^n \cdot {_{n}}p_{x}  &
\begin{array}{rc}
\text{Continuous} & \bar {A}_{{x:\overline {n}|}} = \bar{A}_{{x:\overline {n}|}}^{1} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \\[1em]
\text{Annual} & {A}_{{x:\overline {n}|}} = {A}_{{x:\overline {n}|}}^{1}+{A}{_{{x:\overline {n}|}}^{\;\;1}} \\[1em]
m\text{thly} & A^{(m)}_{x:\overline {n}|} = {A^{(m)}}{_{x:\overline {n}|}^{1}} + {A}{_{{x:\overline {n}|}}^{\;\;1}} \\[1em]
\end{array} \\ \hline
\end{array}
$$
***

<center> Deferred Insurance </center>

$$\begin{align}
{_{u\mid}}\bar{A}_{{x:\overline {n}|}}^{1} &= {_{u}}E_{x} \cdot \bar{A}_{x+u:\overline {n}|}^{1} \\
&= {A}{_{{x:\overline {n}|}}^{\;\;1}} \cdot \bar{A}_{x+u:\overline {n}|}^{1} \\
&= \boxed{ \bar{A}_{{x:\overline {u+n}\displaystyle{|}}}^{1} - \bar{A}_{{x:\overline {u}|}}^{1}}
\end{align}$$

- Decomposition of $n\text{-year}$ term insurance
$$
\bar{A}_{{x:\overline {n}|}}^{1} = \int_{0}^{n} e^{-\delta t} {_{t}}p_{x} \mu_{x+t} \, \mathrm{d}t = \sum_{r=0} ^{n-1} {_{r\mid}}\bar{A}_{{x:\overline {1}\displaystyle{|}}}^{1}
$$
- Decomposition of whole life insurance
$$\bar{A}_{x} = \sum_{r=0} ^{\infty} {_{r\mid}}\bar{A}_{{x:\overline {1}\displaystyle{|}}}^{1}$$
- One last formula!

$$\begin{align}
{_{n|}}A_x &= {_{n}}E_x \cdot A_{x+n} = \boxed{ \upsilon^n \cdot {_{n}}p_{x} A_{x+n} } \\
&= A_x - A^1_{x:\overline{n}|}
\end{align}$$

$$\boxed{A_x = {A}_{{x:\overline {n}|}}^{1} + {_{n\mid}}A_x }$$

## Questions from quizs

- The **expected present value** of a policy issued to a life aged $x$ with a $1$ *dollar* death benefit payable *at the end of the* **month** ($m=12$) of death (regardless of when that death occurs).

$$A^{(12)}_x = \sum_{k=0}^{\infty} \upsilon^{(k + 1)/12} {_{\frac{k} {12} \mid \frac{1} {12}}}q_x$$

- The **expected present value** of a policy issued to a life aged $x$ a $1$ *dollar* death benefit payable *right after death* given the insurer doesn't suvive $n$ term year.

$$\bar{A}^1_{x:\overline{n}|}$$

- ${_{4}}E_{35}$ comes first, then ${_{4|}}A_{35} = {_{4}}E_{35} A_{35+4}$ comes next, then the $A^{1}_{35:\overline{4}\displaystyle{|}} = \sum\limits_{k=0}^{3} \upsilon^{k+1} {_{k|}}q_{35} = A_{35} - {_{4|}}A_{35}$. And finally $A_{35:\overline{4}\displaystyle{|}} = A^{1}_{35:\overline{4}\displaystyle{|}} + A^{\;\;\;1}_{35:\overline{4}\displaystyle{|}} = A^{1}_{35:\overline{4}\displaystyle{|}} + {_{4}}E_{35}$


```python
import numpy as np
#from sympy import *
from matplotlib import pyplot as plt
from scipy import signal
import control
```

# Trabajo practico N°1

## Ejercicio 1

i) $$\begin{equation} \frac{Y(s)}{X(s)} = \frac{125}{s^2+10s+25}\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = \frac{125}{(s+5)^2}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 10\frac{dy(t)}{dt} + 25y(t) = 125x(t)\end{equation}$$

#### Polos y ceros

```python
num1 = np.array([0, 0, 125])
den1 = np.array([1, 10, 25])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 5[1-e^{-5t}(1+5t)]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 5 * (1 - np.exp(-5 * t) * (1 + 5 * t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

ii) $$\begin{equation} \frac{Y(s)}{X(s)} = \frac{10}{s^2+2s+5}\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = \frac{10}{s^2+2s+5}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 2\frac{dy(t)}{dt} + 5y(t) = 10x(t)\end{equation}$$

#### Polos y ceros

```python
num = np.array([0, 0, 10])
den = np.array([1, 2, 5])

tf = control.tf(num, den)
control.pzmap(tf);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 2[1-(cos(2t)+\frac{1}{2}sin(2t)) e^{-t}]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 2 * (1 - (np.cos(2*t)+0.5*np.sin(2*t))*np.exp(-t))*u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

iii) $$\begin{equation} \frac{Y(s)}{X(s)} = \frac{60}{s^3+5s^2+16s+30}\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = \frac{60}{(s+3)(s^2+2s+10)}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^3y(t)}{dt^3} + 5\frac{d^2y(t)}{dt^2} + 16\frac{dy(t)}{dt} + 30y(t) = 60x(t)\end{equation}$$

#### Polos y ceros

```python
num1 = np.array([0, 0, 0, 60])
den1 = np.array([1, 5, 16, 30])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 2[1-\frac{1}{13}(10e^{-2t}+3cos(3t)+11sen(3t))e^{-t}]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 2*(1 - (10*np.exp(-2*t) + 3*np.cos(3*t) + 11*np.sin(3*t))*np.exp(-t)/13)*u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

iv) $$\begin{equation} \frac{Y(s)}{X(s)} = \frac{3s^2+18s+24}{s^2+4s+3}\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = 3\frac{(s+2)(s+4)}{(s+1)(s+3)}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 4\frac{dy(t)}{dt} + 3y(t) = 3\frac{d^2x(t)}{dt^2} + 18\frac{dx(t)}{dt} + 24x(t)\end{equation}$$

#### Polos y ceros

```python
num1 = 3 * np.array([1, 6, 8])
den1 = np.array([1, 4, 3])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = [8-\frac{1}{2}(9 + e^{-2t})e^{-t}]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = (8 - 0.5 * (9 + np.exp(-2*t))*np.exp(-t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

v) $$\begin{equation} \frac{d^2y(t)}{dt^2} + 4y(t) = 8x(t)\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = \frac{8}{s^2+4}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 4y(t) = 8x(t)\end{equation}$$

#### Polos y ceros

```python
num1 = 8 * np.array([0, 0, 1])
den1 = np.array([1, 0, 4])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 2(1-cos(2t))u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 2 * (1 - np.cos(2 * t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

vi)$$\begin{equation} y(t) = 8x(t) + 6\int_0^t x(\tau)d\tau + 2 \frac{dx(t)}{dt}\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = 2\frac{s^2+4s+3}{s}=2\frac{(s+1)(s+3)}{s}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{dy(t)}{dt} = 2\frac{d^2x(t)}{dt^2} + 8\frac{dx(t)}{dt} + 6x(t)\end{equation}$$

#### El problema es que el sistema tiene mas ceros que polos por lo cual no es realizable

vii) $$\begin{equation} \frac{dy(t)}{dt} + y(t) = 2x(t-2)\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = 2\frac{1}{s+1}e^{-2s}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{dy(t)}{dt} + y(t) = 2x(t-2)\end{equation}$$

#### Polos y ceros

```python
num1 = 2 * np.array([0, 1])
den1 = np.array([1, 1])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 2[1-e^{-(t-2)}]u(t-2)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 2 * (1 - np.exp(-(t))) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

viii) $$\begin{equation} 2\frac{dy(t)}{dt} - 2y(t) = 6x(t)\end{equation}$$

#### Transferencia

$$\begin{equation} H(s) = 3\frac{1}{s-1}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{dy(t)}{dt} - y(t) = 3x(t)\end{equation}$$

#### Polos y ceros

```python
num1 = 3 * np.array([0, 1])
den1 = np.array([1, -1])

tf1 = control.tf(num1, den1)
control.pzmap(tf1);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf1)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 3[e^{t}-1]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = 3* (np.exp(t) - 1 ) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

ix)

#### Transferencia

$$\begin{equation} H(s) = \frac{60}{(s+1)(s+2)(s+3)}=\frac{60}{s^3+6s^2+11s+6}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^3y(t)}{dt^3} + 6\frac{d^2y(t)}{dt^2} + 11\frac{dy(t)}{dt} + 6y(t) = 60x(t) \end{equation}$$

#### Polos y ceros

```python
num = np.array([0, 0, 0, 60])
den = np.array([1, 6, 11, 6])

tf = control.tf(num, den)
control.pzmap(tf);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 10[1-3e^{-t}+3e^{-2t}-e^{-3t}]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)

y = 10 * (1 - 3*np.exp(-t) + 3*np.exp(-2*t) - np.exp(-3*t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

x)

#### Transferencia

$$\begin{equation} H(s) = 5\frac{s+4}{s^2+4s+5}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 4\frac{dy(t)}{dt} + 5y(t) = 5\frac{dx(t)}{dt} + 20x(t) \end{equation}$$

#### Polos y ceros

```python
num = 5 * np.array([0, 1, 4])
den = np.array([1, 4, 5])

tf = control.tf(num, den)
control.pzmap(tf);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = 4[1-(cos(t)+\frac{3}{4}sin(t))e^{-2t}]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)

y = 4 * (1 - (np.cos(t) + (3/4) * np.sin(t)) * np.exp(-2*t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

xi)

#### Transferencia

$$\begin{equation} H(s) = \frac{s+2}{2(s+4)}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation}\frac{d^2y(t)}{dt^2} + 4\frac{dy(t)}{dt} = \frac{dx(t)}{dt} + 2x(t) \end{equation}$$

#### Polos y ceros

```python
num = np.array([0, 0, 1, 2])
den = np.array([1, 4, 0, 0])

tf = control.tf(num, den)
control.pzmap(tf);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = (\frac{3}{40} + \frac{1}{2}t - \frac{1}{8}e^{-4t})u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)

y = (3/40 + 0.5 * t - (1/8) * np.exp(-4*t)) * u

fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

xii)

#### Transferencia

$$\begin{equation} H(s) = -3\frac{s-6}{s^2+6s+18}\end{equation}$$

#### Ecuacion diferencial

$$\begin{equation} \frac{d^2y(t)}{dt^2} + 6\frac{dy(t)}{dt} + 8y(t) = -3\frac{dx(t)}{dt} + 18x(t)\end{equation}$$

#### Polos y ceros

```python
num = -3 * np.array([0, 1, -6])
den = np.array([1, 6, 18])

tf = control.tf(num, den)
control.pzmap(tf);
```

#### Respuesta al escalon

```python
t, y = control.step_response(tf)
#plt.plot(t, y, label= "time");
fig, ax = plt.subplots()
ax.plot(t, y)

ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

##### Analiticamente llegue a la siguiente expresion

$$\begin{equation}y(t) = -[(2sen(3t) + cos(3t))e^{-3t} + 1]u(t)\end{equation}$$

##### Vamos a graficarla

```python
u = np.ones(t.size)
y = ( -(2*np.sin(3*t) + np.cos(3*t)) * np.exp(-3*t) + 1 ) * u
fig, ax = plt.subplots()
ax.plot(t, y)
ax.set(xlabel='time [s]', ylabel='amplitud []', title='Step Response');
```

```python

```


## Diagramas de cortante y momento

Draw the shear and bending-moment diagrams for problem,
the beam and loading shown, and determine the maximum absolute
value (a) of the shear, (b) of the bending moment.

```python
from __future__ import division
from sympy import *
from sympy.plotting import plot
from sympy.physics.continuum_mechanics.beam import Beam
init_printing(use_latex="mathjax")
```

```python
E, I = symbols('E, I')
RA, RC = symbols('Ra, Rc')
L = 3
#E, I = 29e6, 100
b = Beam(L, E, I)
b.apply_load(RA, 0, -1)
b.apply_load(RC, 2, -1)
b.apply_load(-40e3, 3, -1)
b.apply_load(-12e3, 0, 0, end=2)
b.bc_deflection = [(0, 0),(2,0)]
b.solve_for_reaction_loads(RA,RC)
```

```python
S = b.shear_force()
M = b.bending_moment()
```

```python
plot(S, ("x",0,L))
```

```python
plot(M, ("x",0,L))
```

```python

```


# Molecular dynamics

## With OpenMM

```python
import openmm as mm
from openmm import unit
from uibcdf_systems import DoubleWell

molecular_system = DoubleWell(n_particles = 1, mass = 64 * unit.amu,
                              Eo=3.0 * unit.kilocalories_per_mole,
                              a=5.0 * unit.angstroms, b=0.0 * unit.kilocalories_per_mole,
                              k=1.0 * unit.kilocalories_per_mole/unit.angstrom**2)

integrator = mm.LangevinIntegrator(300.0*unit.kelvin, 1.0/unit.picoseconds, 0.1*unit.picoseconds)
platform = Platform.getPlatformByName('CUDA')
simulation = Simulation(molecular_system.topology, molecular_system.system, integrator, platform)

coordinates = np.zeros([1, 3], np.float32) * unit.nanometers
simulation.context.setPositions(coordinates)

velocities = np.zeros([1, 3], np.float32) * unit.nanometers/unit.picoseconds
simulation.context.setVelocities(velocities)

simulation.step(1000)
```

## With this library

```python
import numpy as np
import sympy as sy
import matplotlib.pyplot as plt
from openmm import unit

from uibcdf_systems import DoubleWell
from uibcdf_systems.tools import langevin

molecular_system = DoubleWell(n_particles = 1, mass = 64 * unit.amu,
                              Eo=3.0 * unit.kilocalories_per_mole,
                              a=5.0 * unit.angstroms, b=0.0 * unit.kilocalories_per_mole,
                              k=1.0 * unit.kilocalories_per_mole/unit.angstrom**2)
```

### Newtonian dynamics

```python
initial_positions = np.zeros([1, 3], np.float32) * unit.nanometers
initial_positions[0,0] = 0.55 * unit.nanometers

initial_velocities = np.zeros([1, 3], np.float32) * unit.nanometers/unit.picoseconds

molecular_system.set_coordinates(initial_positions)
molecular_system.set_velocities(initial_velocities)

traj_dict = langevin(molecular_system,
                     friction=0.0/unit.picoseconds,
                     temperature=00.0*unit.kelvin,
                     time=20.0*unit.picoseconds,
                     saving_timestep=0.1*unit.picoseconds,
                     integration_timestep=0.02*unit.picoseconds)
```

      0%|          | 0/1000 [00:00<?, ?it/s]

We can now plot the trajectory of the x coordinate:

```python
plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

Now we can wonder, is the period of the oscillations is in agreement with the value calculated before? A shorter run with more points could be enough to say, by inspection, that the calculus is correct.

```python
mass = 64 * unit.amu
Eo=3.0 * unit.kilocalories_per_mole
a=5.0 * unit.angstroms
T = 2*np.pi*np.sqrt((mass*a**2)/(8.0*Eo))

print('The period of the small oscillations around the minimum is',T)
```

    The period of the small oscillations around the minimum is 2.5080627665032216 ps

As we can also check with the method:

```python
molecular_system.get_small_oscillations_time_periods_around_minima()
```

    ([Quantity(value=array([-0.5,  0. ,  0. ]), unit=nanometer),
      Quantity(value=array([0.5, 0. , 0. ]), unit=nanometer)],
     [Quantity(value=array([2.50806277, 2.45738961, 2.45738961]), unit=picosecond),
      Quantity(value=array([2.50806277, 2.45738961, 2.45738961]), unit=picosecond)])

```python
plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])
plt.axvline(T._value, color='gray', linestyle='--') # Period of the harmonic oscillations approximation
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

It seems a good approximation to what is observed graphically in the integrated trajectory. Keep in mind that this is an approximation valid when the particle moves very close the bottom of the basins. In an real harmonic oscillator this period does not change with amplitude, but in this case does it. If the amplitude is large enough the oscillations are far from being well approximated by the cuadratic term of the Taylor expansion. Try to play with larger and shorter initial distances to the minimum to see this effect:

```python
amplitudes = 0.5*unit.nanometers + np.array([0.02, 0.05, 0.07, 0.1, 0.15]) * unit.nanometers
traj_dicts = []

for amplitude in amplitudes:
    initial_positions[0,0] = amplitude
    molecular_system.set_coordinates(initial_positions)
    traj_dict = langevin(molecular_system,
                         friction=0.0/unit.picoseconds,
                         temperature=00.0*unit.kelvin,
                         time = 5*unit.picoseconds,
                         integration_timestep = 0.02 * unit.picoseconds,
                         saving_timestep = 0.1 * unit.picoseconds,
                         tqdm=False)
    traj_dicts.append(traj_dict)

for traj_dict in traj_dicts:
    plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])

plt.axvline(T._value, color='gray', linestyle='--') # Period of the harmonic oscillations approximation
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

The newtonian dynamics can also include damping. This way we can simulate damped oscillations around the minimum.

```python
traj_dict = langevin(molecular_system,
                     friction=0.5/unit.picoseconds,
                     temperature=0.0*unit.kelvin,
                     time=20.0*unit.picoseconds,
                     saving_timestep=0.1*unit.picoseconds,
                     integration_timestep=0.02*unit.picoseconds)
```

      0%|          | 0/1000 [00:00<?, ?it/s]

```python
plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

What would be the friction value needed to enter in the overdamped regime?

```python
traj_dict = langevin(molecular_system,
                     friction=5.0/unit.picoseconds,
                     temperature=0.0*unit.kelvin,
                     time=20.0*unit.picoseconds,
                     saving_timestep=0.1*unit.picoseconds,
                     integration_timestep=0.02*unit.picoseconds)
```

      0%|          | 0/1000 [00:00<?, ?it/s]

```python
plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

And the same can be checked for the asymmetric double well potential. In the case of the period of short oscillations around a minimum, keep in mind that there the minimum is not longer $a$, and $T$ was here calculated with the value of the second derivative (equal, no matter the value of $b$) in $a$. But still is a good approximation.

### Stochastic Dynamics

Thanks to the `tools.langevin` method in this library, a simple newtonian dynamics can be run with few effort:

```python
initial_positions = np.zeros([1, 3], np.float32) * unit.nanometers
initial_positions[0,0] = 0.5 * unit.nanometers

initial_velocities = np.zeros([1, 3], np.float32) * unit.nanometers/unit.picoseconds

molecular_system.set_coordinates(initial_positions)
molecular_system.set_velocities(initial_velocities)

traj_dict = langevin(molecular_system,
                     friction=1.0/unit.picoseconds,
                     temperature=300.0*unit.kelvin,
                     time=10.0*unit.nanoseconds,
                     saving_timestep=1.0*unit.picoseconds,
                     integration_timestep=0.1*unit.picoseconds)
```

      0%|          | 0/100000 [00:00<?, ?it/s]

Let us see the time evolution of the coordinate $x$ of our single particle:

```python
plt.plot(traj_dict['time'], traj_dict['coordinates'][:,0,0])
plt.xlabel('time ({})'.format(traj_dict['time'].unit))
plt.ylabel('X ({})'.format(traj_dict['coordinates'].unit))
plt.show()
```

The trajectory is long enough to observe the system hopping on and off from the initial basin.


    M 391 Differential Equations Final Project

    Due 11/18/20, 5 pm

Problem 1

By first setting $a_0=1$ and $a_1=0$ and then setting $a_0=0$ and $a_1=1$, find a pair of independent solutions to equations (1), (2), and (3) for p=0,1,2,3. $\newline$
Hermite's Equation (1) $$y''-2xy'+2py=0$$

Suppose $y = \sum_{n  = 0}^\infty a_n x^n$ solves (1) Then we have $y' = \sum_{n  = 1}^\infty na_n x^{n-1}$ and $y'' = \sum_{n  = 2}^\infty (n-1)na_n x^{n-2}$.  Plugging these into (1), we get:
\begin{align}
\sum_{n  = 2}^\infty (n-1)na_n x^{n-2} - 2x\sum_{n  = 1}^\infty na_n x^{n-1} + 2p \sum_{n  = 0}^\infty a_n x^n = 0  \\
\sum_{n  = 0}^\infty (n+2)(n+1)a_{n+2} x^{n} - \sum_{n  = 1}^\infty 2na_n x^{n} + \sum_{n  = 0}^\infty 2pa_n x^n = 0
\end{align}
Since the $n=0$ of the $y'$ term is $2*0*a_0*x^0 = 0$, we can write:
\begin{align}
\sum_{n  = 0}^\infty (n+2)(n+1)a_{n+2} x^{n} - \sum_{n  = 0}^\infty 2na_n x^{n} + \sum_{n  = 0}^\infty 2pa_n x^n = 0 \\
\sum_{n  = 0}^\infty ((n+2)(n+1)a_{n+2} - 2na_n + 2pa_n) x^n = 0 \\
(n+2)(n+1)a_{n+2} - 2na_n + 2pa_n = 0, \forall n \in \mathbb{N}
\end{align}
This gives us the recurrence relation:
\begin{align}
a_{n+2} = \frac{2(n-p)}{(n+2)(n+1)}a_n
\end{align}
If we set $a_0=1$ and $a_1=0$, we get $a_1 = a_3 = 0$. Thus we get the following coefficients:
\begin{align}
a_2 = \frac{2(0-p)}{2} \\
a_4 = \frac{2^2(2-p)(0-p)}{4!}\\
\end{align}
These initial conditions give us the independent solution $$g_p = a_0(1 + \frac{2(0-p)}{2}x^2 + \frac{2^2(2-p)(0-p)}{4!}x^4 + ...)$$
For $g_p$ where $p \in \{0,1,2,3\}$, we get the following solutions (see Problem 4 for more details):
\begin{align}
g_0 = 1\\
g_1 = 1 - x^2\\
g_2 = -(1/9)x^10 - (1/7)x^8 - (1/5)x^6 - (1/3)x^4 - x^2 + 1\\
g_3 = (2/7)x^10 + (3/7)x^8 + (4/5)x^6 + 3x^4 - 6x^2 + 1
\end{align}
If we set $a_0=0$ and $a_1=1$, we get $a_0 = a_2 = 0$. Thus, for $p \in \{0,1,2,3\}$ we get the following coefficients:
\begin{align}
a_3 = \frac{2(1-p)}{3!}\\
a_5 = \frac{2^2(3-p)(1-p)}{5!}
\end{align}
These initial conditions give us the independent solution $$h_p = a_1(x + \frac{2(1-p)}{3!}x^3 + \frac{2^2(3-p)(1-p)}{5!}x^5 + ...)$$
For $h_p$ where $p \in \{0,1,2,3\}$, we get the following solutions (see Problem 4 for more details):
\begin{align}
h_0 = (1/11)x^11 + (1/9)x^9 + (1/7)x^7 + (1/5)x^5 + (1/3)x^3 + x\\
h_1 = x\\
h_2 = -(2/33)x^11 - (5/63)x^9 - (4/35)x^7 - (1/5)x^5 - (2/3)x^3 + x\\
h_3 = -(2/3)x^3 + x
\end{align}

Legendre's equation (2) $$(1−x^2)y′′−2xy′+p(p+1)y=0$$
Suppose $y = \sum_{n  = 0}^\infty a_n x^n$ solves (2) Then we have $y' = \sum_{n  = 1}^\infty na_n x^{n-1}$ and $y'' = \sum_{n  = 2}^\infty (n-1)na_n x^{n-2}$.  Plugging these into (1), we get:
\begin{align}
\sum_{n  = 2}^\infty (n-1)na_n x^{n-2} - x^2\sum_{n  = 2}^\infty (n-1)na_n x^{n-2} - 2x\sum_{n  = 1}^\infty na_n x^{n-1} + p(p+1)\sum_{n=0}^\infty a_nx^n = 0 \\
\sum_{n = 0}^\infty (n+1)(n+2)a_{n+2}x^n - \sum_{n=0}^\infty (n-1)na_nx^n - \sum_{n  = 1}^\infty 2na_n x^n + \sum_{n=0}^\infty p(p+1)a_nx^n = 0 \\
\sum_{n=0}^\infty ((n+1)(n+2)a_{n+2} - (n-1)na_n - 2na_n + p(p+1)a_n)x^n = 0 \\
(n+1)(n+2)a_{n+2} - (n-1)na_n - 2na_n + p(p+1)a_n = 0
\end{align}
This gives the recurrence relation: $$a_{n+2} = \frac{n(n+1)-p(p+1)}{(n+1)(n+2)}$$

If we set $a_0=1$ and $a_1=0$, we get $a_1 = a_3 = 0$. Thus we get the following coefficients:
\begin{align}
a_2 = -\frac{p(p+1)}{2} \\
a_4 = \frac{p(p-2)(p+3)(p+1)}{4!}\\
\end{align}
These initial conditions give us the independent solution $$g_p = a_0(1 - \frac{p(p+1)}{2}x^2 + \frac{p(p-2)(p+3)(p+1)}{4!}x^4 - ...) = a_0 \sum_{n=0}^\infty \frac{(-1)^n \prod_{k=1}^n (p -2k +2) \prod_{j=1}^n (p+2j-1)}{(2n)!}x^{2n}$$
For $g_p$ where $p \in \{0,1,2,3\}$, we get the following solutions (see Problem 2 for more details):
\begin{align}
g_0 = 1\\
g_1 = -(1/9)x^10 - (1/7)x^8 - (1/5)x^6 - (1/3)x^4 - x^2 + 1\\
g_2 = -3x^2 + 1\\
g_3 = (2/7)x^10 + (3/7)x^8 + (4/5)x^6 + 3x^4 - 6x^2 + 1
\end{align}
If we set $a_0=0$ and $a_1=1$, we get $a_0 = a_2 = 0$. Thus, for $p \in \{0,1,2,3\}$ we get the following coefficients:
\begin{align}
a_3 = \frac{-(p+2)(p-1)}{3!}\\
a_5 = \frac{(p+4)(p+2)(p-3)(p-1)}{5!}
\end{align}
These initial conditions give us the independent solution $$h_p = a_1(x - \frac{(p+2)(p-1)}{3!}x^3 + \frac{(p+4)(p+2)(p-3)(p-1)}{5!}x^5 - ...) = a_1 \sum_{n=0}^\infty \frac{(-1)^n \prod_{k=1}^n (p -2k + 1) \prod_{j=1}^n (p+2j)}{(2n+1)!}x^{2n+1}$$
For $h_p$ where $p \in \{0,1,2,3\}$, we get the following solutions (see Problem 2 for more details):
\begin{align}
h_0 = (1/11)x^11 + (1/9)x^9 + (1/7)x^7 + (1/5)x^5 + (1/3)x^3 + x\\
h_1 = x\\
h_2 = -(2/33)x^11 - (5/63)x^9 - (4/35)x^7 - (1/5)x^5 - (2/3)x^3 + x\\
h_3 = -(5/3)x^3 + x
\end{align}

Chebyshev's equation (3) $$(1−x^2)y′′−xy′+p^2y=0$$
Suppose $y = \sum_{n  = 0}^\infty a_n x^n$ solves (3) Then we have $y' = \sum_{n  = 1}^\infty na_n x^{n-1}$ and $y'' = \sum_{n  = 2}^\infty (n-1)na_n x^{n-2}$.  Plugging these into (1), we get:
\begin{align}
\sum_{n  = 2}^\infty (n-1)na_n x^{n-2} - x^2\sum_{n  = 2}^\infty (n-1)na_n x^{n-2} - x\sum_{n  = 1}^\infty na_n x^{n-1} + p^2 \sum_{n  = 0}^\infty a_n x^n = 0  \\
\sum_{n  = 0}^\infty (n+1)(n+2)a_{n+2} x^{n} - \sum_{n  = 0}^\infty (n-1)na_n x^{n} - \sum_{n  = 1}^\infty na_n x^{n} + \sum_{n  = 0}^\infty p^2a_n x^n = 0 \\
\sum_{n  = 0}^\infty ((n+1)(n+2)a_{n+2} + (n-1)na_n - na_n + p^2a_n)x^n = 0 \\
(n+1)(n+2)a_{n+2} + (n-1)na_n - na_n + p^2a_n = 0
\end{align}
This gives the recurrence relation: $$a_{n+2} = \frac{(n-p)(n+p)}{(n+1)(n+2)}a_n$$
If we set $a_0=1$ and $a_1=0$, we get $a_1 = a_3 = a_5 = 0$. Thus we get the following coefficients:
\begin{align}
a_2 = \frac{p^2}{2!} \\
a_4 = \frac{(2^2 - p^2)p^2}{4!}\\
\end{align}
These initial conditions give us the independent solution $$g_p = a_0(1 + \frac{p^2}{2!}x^2 + \frac{(2^2 - p^2)p^2}{4!}x^4 + ...) = a_0 \sum_{n=0}^\infty \frac{\prod_{k=0}^n (p^2 -(2k)^2){(2n)!}x^{2n}$$

If we set $a_0=0$ and $a_1=1$, we get $a_0 = a_2 = 0$. Thus, for $p \in \{0,1,2,3\}$ we get the following coefficients:
\begin{align}
a_3 = \frac{1^2 - p^2}{3!}\\
a_5 = \frac{(3^2 - p^2)(1^2 - p^2)}{5!}
\end{align}
These initial conditions give us the independent solution $$h_p = a_1(x + \frac{1^2 - p^2}{3!}x^3 + \frac{(3^2 - p^2)(1^2 - p^2)}{5!}x^5 + ...) = a_1 \sum_{n=0}^\infty \frac{\prod_{k=0}^n (p^2 -(2k+1)^2){(2n+1)!}x^{2n+1}$$
The independent polynomial solutions are computed in the code below:

```python
# y_1 is even terms, we get this when a_0 = 1
# y_2 is odd terms, we get this when a_1 = 1
# y = a_0*y_1 + a_1*y_2

import math

x = var('x')

for p in range(0,4):

    g=1

    for n in range(1,3):

        prod1 = 1

        for k in range(0,n+1):

            prod1 = prod1*((2*k)^2 - p^2)

        g=g+((prod1/math.factorial(2*n))*x^(2*n))

    print("At p =",p,",\n","y_1 gives", g)

    h=x

    for n in range(1,3):

        prod2 = 1

        for k in range(0,n+1):

            prod2 = prod2*((2*k + 1)^2 - p^2)

        h=h+((prod2/math.factorial(2*n+1))*x^(2*n+1))

    print(" y_2 gives", h)

    print()
```

    At p = 0 ,
     y_1 gives 1
     y_2 gives 15/8*x^5 + 3/2*x^3 + x

    At p = 1 ,
     y_1 gives -15/8*x^4 - 3/2*x^2 + 1
     y_2 gives x

    At p = 2 ,
     y_1 gives 1
     y_2 gives -21/8*x^5 - 5/2*x^3 + x

    At p = 3 ,
     y_1 gives 105/8*x^4 + 45/2*x^2 + 1
     y_2 gives x

This doesn't look quite right, there must be a bug in my code.  It should be $y_1 = 1$ for $p=0$, $y_2 = x$ for $p = 1$, $y_1 = 2x^2-1$ for $p=2$, and $y_2 = 4x^3 -3x$ for $p=3$.

    Problem 2

Forp=0,1,2,3,4,5,6, find polynomial solutions for equation (2) with y(1)=1. Argue that, for each p there is only one such solution.  These polynomials are called the Legendre polynomials

```python
# y_1 is even terms, we get this when a_0 = 1
# y_2 is odd terms, we get this when a_1 = 1
# y = a_0*y_1 + a_1*y_2

import math

x = var('x')

for p in range(0,7):

    g=1

    for n in range(1,6):

        prod1 = 1

        prod3 = 1

        for k in range(1,n+1):

            prod1 = prod1*(p - 2*k + 2)

        for j in range(1,n+1):

            prod3 = prod3*(p+2*j-1)

        g=g+((-1)^n*(prod1*prod3/math.factorial(2*n))*x^(2*n))

    print("At p =",p,",\n","y_1 gives", g)

    h=x

    for n in range(1,6):

        prod2 = 1

        prod4 = 1

        for k in range(1,n+1):

            prod2 = prod2*(p - 2*k + 1)

        for j in range(1,n+1):

            prod4 = prod4*(p+2*j)

        h=h+((-1)^n*(prod2*prod4/math.factorial(2*n+1))*x^(2*n+1))

    print(" y_2 gives", h)

    print()
```

    At p = 0 ,
     y_1 gives 1
     y_2 gives 1/11*x^11 + 1/9*x^9 + 1/7*x^7 + 1/5*x^5 + 1/3*x^3 + x

    At p = 1 ,
     y_1 gives -1/9*x^10 - 1/7*x^8 - 1/5*x^6 - 1/3*x^4 - x^2 + 1
     y_2 gives x

    At p = 2 ,
     y_1 gives -3*x^2 + 1
     y_2 gives -2/33*x^11 - 5/63*x^9 - 4/35*x^7 - 1/5*x^5 - 2/3*x^3 + x

    At p = 3 ,
     y_1 gives 2/7*x^10 + 3/7*x^8 + 4/5*x^6 + 3*x^4 - 6*x^2 + 1
     y_2 gives -5/3*x^3 + x

    At p = 4 ,
     y_1 gives 35/3*x^4 - 10*x^2 + 1
     y_2 gives 1/11*x^11 + 1/7*x^9 + 2/7*x^7 + 6/5*x^5 - 3*x^3 + x

    At p = 5 ,
     y_1 gives -x^10 - 15/7*x^8 - 10*x^6 + 30*x^4 - 15*x^2 + 1
     y_2 gives 21/5*x^5 - 14/3*x^3 + x

    At p = 6 ,
     y_1 gives -231/5*x^6 + 63*x^4 - 21*x^2 + 1
     y_2 gives -8/33*x^11 - 5/9*x^9 - 20/7*x^7 + 10*x^5 - 20/3*x^3 + x

We can argue that the Legendre Equation has odd solutions for odd values of p and even solutions for even values of p, because we can see above that the degrees of the polynomials don't match up for p values and n that are not both even or both odd.  Thus, there is only one polynomial solution $L_p$ for each value of $p$:
\begin{align}
L_0 = 1 \\
L_1 = x \\
L_2 = -3x^2 + 1 \\
L_3 = -\frac{5}{3}x^3 + x
\end{align}

    Problem 3

Plot the first seven Legendre polynomials on a single plot and conjecture aproperty for these polynomials that depends on whetherpis even or odd.

```python
# plot of the first 7 Legendre polynomials
var('x')
g = Graphics()
g += plot(1, (x,-1,1), ymin=-1,ymax=1,color='blue')
g += plot(x, (x, -1, 1), ymin=-1,ymax=1,color='red')
g += plot((.5*(3*x^2-1)), (x, -1, 1),ymin=-1,ymax=1, color='green')
g += plot((.5*(5*x^3-3*x)), (x,-1,1),ymin=-1,ymax=1, color='yellow')
g += plot(((1/8)*(35*x^3-30*x^2+3)), (x,-1,1), ymin=-1,ymax=1, color='teal')
g += plot(((1/8)*(63*x^5-70*x^3+15*x)), (x,-1,1), ymin=-1,ymax=1, color='pink')
g += plot(((1/16)*(231*x^6-315*x^4+105*x^2-5)), (x,-1,1), ymin=-1,ymax=1, color='purple')
g.show()
```

Based on this graph, it appears that the functions for odd p have odd order graphs and functions with even p have even order graphs.

    Problem 4

Consider Hermite’s equation (1).  For a positive integer p, how should you choose values in $\{0,1\}$ for $a_0$ and $a_1$ so that the cooresponding power series solution $h_p(x)$ is actually a polynomial? Compute $h_p(x)$ for $p \in \{0,1,2,3,4,5,6\}$.

```python
# y_1 is even terms, we get this when a_0 = 1
# y_2 is odd terms, we get this when a_1 = 1
# y = a_0*y_1 + a_1*y_2

import math

x = var('x')

for p in range(0,7):

    g=1

    for n in range(1,7):

        prod1 = 1

        for k in range(1,n+1):

            prod1 = prod1*(2*k -2 - p)

        g=g+((2^n*prod1/math.factorial(2*n))*x^(2*n))

    print("At p =",p,",\n","y_1 gives", g)

    h=x

    for n in range(1,7):

        prod2 = 1

        for k in range(1,n+1):

            prod2 = prod2*(2*k - 1 -p)

        h=h+((2^n*prod2/math.factorial(2*n + 1))*x^(2*n + 1))

    print(" y_2 gives", h)

    print()
```

    At p = 0 ,
     y_1 gives 1
     y_2 gives 1/9360*x^13 + 1/1320*x^11 + 1/216*x^9 + 1/42*x^7 + 1/10*x^5 + 1/3*x^3 + x

    At p = 1 ,
     y_1 gives -1/7920*x^12 - 1/1080*x^10 - 1/168*x^8 - 1/30*x^6 - 1/6*x^4 - x^2 + 1
     y_2 gives x

    At p = 2 ,
     y_1 gives -2*x^2 + 1
     y_2 gives -1/102960*x^13 - 1/11880*x^11 - 1/1512*x^9 - 1/210*x^7 - 1/30*x^5 - 1/3*x^3 + x

    At p = 3 ,
     y_1 gives 1/23760*x^12 + 1/2520*x^10 + 1/280*x^8 + 1/30*x^6 + 1/2*x^4 - 3*x^2 + 1
     y_2 gives -2/3*x^3 + x

    At p = 4 ,
     y_1 gives 4/3*x^4 - 4*x^2 + 1
     y_2 gives 1/308880*x^13 + 1/27720*x^11 + 1/2520*x^9 + 1/210*x^7 + 1/10*x^5 - x^3 + x

    At p = 5 ,
     y_1 gives -1/33264*x^12 - 1/2520*x^10 - 1/168*x^8 - 1/6*x^6 + 5/2*x^4 - 5*x^2 + 1
     y_2 gives 4/15*x^5 - 4/3*x^3 + x

    At p = 6 ,
     y_1 gives -8/15*x^6 + 4*x^4 - 6*x^2 + 1
     y_2 gives -1/432432*x^13 - 1/27720*x^11 - 1/1512*x^9 - 1/42*x^7 + 1/2*x^5 - 5/3*x^3 + x

As you can see above, certain values for $a_0$ and $a_1$ give simpler polynomials.  For $p = 1$ I would choose $a_0 = 1, a_1 = 0$.

    Problem 5

Let $G(x,t)=exp(2xt−t^2)$ and, for a positive integer $j$, define: $H_j(x)=\frac{_∂jG}{∂t^j}$
Show that $\frac{\partial^2G}{\partial x^2}−2x\frac{\partial G}{\partial x}+2(2xt−2t^2)G=0$.
The polynomials $H_n$ are called Hermite polynomials.  Make a conjecture for a formula that gives the scalars relating $h_n$ and $H_n$.
$\partial$

```python
# show that G'' - 2xG' + 2(2xt - 2t^2)G = 0
x,t = var('x,t')

G = e^(2*x*t - t^2)
dG = G.diff(x)
d2G = G.diff(x,2)

de = d2G - 2*x*dG + 2*(2*x*t - 2*t^2)*G
de.full_simplify()
```

    0

```python
# plug in some values of n to make a conjecture for scalars relating hn and Hn
Hlist = []
for n in range(0,7):
    new = G.diff(t,n)
    Hlist.append(new)
    print("H_",n,"=",new)

show(Hlist)
```

    H_ 0 = e^(-t^2 + 2*t*x)
    H_ 1 = -2*(t - x)*e^(-t^2 + 2*t*x)
    H_ 2 = 4*(t - x)^2*e^(-t^2 + 2*t*x) - 2*e^(-t^2 + 2*t*x)
    H_ 3 = -8*(t - x)^3*e^(-t^2 + 2*t*x) + 12*(t - x)*e^(-t^2 + 2*t*x)
    H_ 4 = 16*(t - x)^4*e^(-t^2 + 2*t*x) - 48*(t - x)^2*e^(-t^2 + 2*t*x) + 12*e^(-t^2 + 2*t*x)
    H_ 5 = -32*(t - x)^5*e^(-t^2 + 2*t*x) + 160*(t - x)^3*e^(-t^2 + 2*t*x) - 120*(t - x)*e^(-t^2 + 2*t*x)
    H_ 6 = 64*(t - x)^6*e^(-t^2 + 2*t*x) - 480*(t - x)^4*e^(-t^2 + 2*t*x) + 720*(t - x)^2*e^(-t^2 + 2*t*x) - 120*e^(-t^2 + 2*t*x)

```python
t = 0
H0 = e^(-t^2 + 2*t*x)
H1 = -2*(t - x)*e^(-t^2 + 2*t*x)
H2 = 4*(t - x)^2*e^(-t^2 + 2*t*x) - 2*e^(-t^2 + 2*t*x)
H3 = -8*(t - x)^3*e^(-t^2 + 2*t*x) + 12*(t - x)*e^(-t^2 + 2*t*x)
H4 = 16*(t - x)^4*e^(-t^2 + 2*t*x) - 48*(t - x)^2*e^(-t^2 + 2*t*x) + 12*e^(-t^2 + 2*t*x)
H5 = -32*(t - x)^5*e^(-t^2 + 2*t*x) + 160*(t - x)^3*e^(-t^2 + 2*t*x) - 120*(t - x)*e^(-t^2 + 2*t*x)
H6 = 64*(t - x)^6*e^(-t^2 + 2*t*x) - 480*(t - x)^4*e^(-t^2 + 2*t*x) + 720*(t - x)^2*e^(-t^2 + 2*t*x) - 120*e^(-t^2 + 2*t*x)

show("H_0 = G =",H0)
show("H_1 = dG =",H1)
show("H_2 = d2G =",H2)
show("H_3 = d3G =",H3)
show("H_4 = d4G =",H4)
show("H_5 = d5G =",H5)
show("H_6 = d6G =",H6)
```

From problem 4 we have $$h_0 = 1$$ $$h_1 = x$$ $$h_2 = -2x^2 + 1$$ $$h_3 = -\frac{2}{3}x^3 + x$$ $$\frac{4}{3}*x^4 - 4*x^2 + 1$$  and so on.  Thus, the equations for $h_n$ and $H_n$ both have order $n$ but are off by a coefficient.  I was unable to find a general pattern for to correct for the differences in the coefficients.

    Problem 6

Plot $h_j$ for $j=0,...,4$ on a single plot. Do the same for $H_j$ for $j=0,...,4$.

```python
var('x')
h = Graphics()
h += plot(1, (x,-2,2), ymin=-2,ymax=2,color='green')
h += plot(x, (x,-2,2), ymin=-2,ymax=2,color='red')
h += plot((-2*x^2 + 1), (x,-2,2), ymin=-2,ymax=2, color='blue')
h += plot((-2/3*x^3 + x), (x,-2,2), ymin=-2,ymax=2, color='teal')
h += plot((4/3*x^4 - 4*x^2 + 1), (x,-2,2), ymin=-2,ymax=2, color='magenta')
h.show()
```

```python
var('x')
H = Graphics()
H += plot(1, (x,-2,2), ymin=-2,ymax=2,color='green')
H += plot(2*x, (x, -2, 2), ymin=-2,ymax=2,color='red')
H += plot((4*x^2 - 2), (x, -2, 2),ymin=-2,ymax=2, color='blue')
H += plot((8*x^3 - 12*x), (x,-2,2),ymin=-2,ymax=2, color='teal')
H += plot((16*x^4-48*x^2+12), (x,-2,2), ymin=-2,ymax=2, color='magenta')
H.show()
```

    Problem 7

Show that $F(\alpha,\beta,\gamma,x)$ converges on $(−1,1)$ and is a solution for (5) correspondingto the indical root zero.

Let
\begin{align}
 P_0(x) & = -\alpha \beta, \\
 P_1(x) & = \gamma - (1+\alpha +\beta )x, \\
 P_2(x) & = x(1-x)
\end{align}
Then $$P_2(0) = P_2 (1)=0$$
We can see that x = 0 and x = 1 are singular points.  Let's use the ratio test to check if x = 0 is regular:
\begin{align}
\lim_{x \to a} \frac{(x - a) P_1(x)}{P_2(x)} &=\lim_{x \to 0} \frac{(x - 0)(\gamma - (1 + \alpha + \beta)x)}{x(1 - x)}=\lim_{x \to 0} \frac{x(\gamma - (1 + \alpha + \beta)x)}{x(1 - x)}= \gamma  \\
 \lim_{x \to a} \frac{(x - a)^2 P_0(x)}{P_2(x)} &= \lim_{x \to 0} \frac{(x - 0)^2(-\alpha \beta)}{x(1 - x)} = \lim_{x \to 0} \frac{x^2 (-\alpha \beta)}{x(1 - x)} = 0
\end{align}
Thus, x = 0 is a regular singular point and we can assume a solution of the form $$y = \sum_{n=0}^\infty a_n x^{n+m}$$

Then, $$y' = \sum_{n=0}^\infty a_n(n+m)x^{n+m-1}$$ and $$y'' = \sum_{n=0}^\infty a_n(n+m)(n+m-1)x^{n+m-2}$$ Thus, after subbing these sums into the hypergeometric equation and simplifying we get the indicial equation:   $$a_{0} (m(m - 1) + \gamma m) = 0$$

Since $a_0 \not = 0$, we have the indicial roots $m = 0$ and $m = 1-\gamma$

The other terms give us the recurrence relation: $$a_n = \frac{(n + m + \alpha - 1)(n + m + \beta - 1)}{(n + m)(n + m + \gamma - 1)} a_{n - 1}, \text{ for } n \geq 1$$

After solving for a few terms, we can write the general formula: $$a_n =\frac{(m + \alpha)_n (m + \beta)_n}{(m + 1)_n(m + \gamma)_n} a_0, \text{ for } n \geq 0$$

This means our solution is of the form: $$y = a_0 \sum_{n = 0}^\infty \frac{(m + \alpha)_n (m + \beta)_n}{(m + 1)_n (m + \gamma)_n} x^{n + m}$$

Our formula for $a_n$ converges on(-1,1) by the ration test, the formula for $y$ we computed is a valid solution to the hypergeometric equation.

    Problem 8

Suppose that $\gamma$ is not an integer and express a solution to (5) corresponding to the indical root $1-\gamma$ in terms ofF. Give the general solution to (5) in terms of F.

If we base the particular solution $y_1$ on the indicial root $m = 0$ and $y_2$ on the indicial root $m = 1 - \gamma$, then we get:
\begin{align}
 y_1 &= a_0 \sum_{r = 0}^\infty \frac{(\alpha)_r (\beta)_r}{(1)_r (\gamma)_r} x^r = a_0 \cdot {{}_2 F_1}(\alpha, \beta; \gamma; x) \\
 y_2 &= a_0 \sum_{r = 0}^\infty \frac{(\alpha + 1 - \gamma)_r (\beta + 1 - \gamma)_r}{(1 - \gamma + 1)_r (1 - \gamma + \gamma)_r} x^{r + 1 - \gamma} \\
       &= a_0 x^{1 - \gamma} \sum_{r = 0}^\infty \frac{(\alpha + 1 - \gamma)_r (\beta + 1 - \gamma)_r}{(1)_r (2 - \gamma)_r} x^r \\
       &= a_0 x^{1 - \gamma} {{}_2 F_1}(\alpha - \gamma + 1, \beta - \gamma + 1; 2 - \gamma; x)
\end{align}

Thus our general solution is $y = A'y_1 + B'y_2$.  Also, if we let $A′ a_0 = a$ and $B′ a_0 = B$. Then $y = A_2F_1(\alpha ,\beta ;\gamma ;x) + Bx^{1-\gamma }_2F_1(\alpha -\gamma +1,\beta -\gamma +1;2-\gamma ;x)$

    Problem 9

Use the substitution $\frac{1}{2}(1−x)=t$ to show that a particular solution to Legendre’s equation (2) is given by $$F(p+1,−p,1,12(1−x))$$.

```python
t,x = var('t,x')
t = .5*(1-x)

for p in range(0,9):
    Alpha = p + 1
    Beta = -p
    Gamma = 1
    g=1

    for n in range(1,9):

        prod1 = 1

        prod3 = 1

        for k in range(1,n+1):

            prod1 = prod1*Alpha*Beta

        for j in range(1,n+1):

            prod3 = prod3*1*Gamma

        g=g+((prod1/prod3)*t^(n))

    print("At p =",p,",\n","y_1 gives", g.full_simplify())

    h=x

    for n in range(1,9):

        prod2 = 1

        prod4 = 1

        for k in range(1,n+1):

            prod2 = prod2*(Alpha + 1 - Gamma)*(Beta + 1 - Gamma)

        for j in range(1,n+1):

            prod4 = prod4*1*(2-Gamma)

        h=h+((prod2/prod4)*t^(n+1-Gamma))

    print(" y_2 gives", h.full_simplify())

    print()
```

    At p = 0 ,
     y_1 gives 1
     y_2 gives x

    At p = 1 ,
     y_1 gives 1.0*x^8 - 7.0*x^7 + 22.0*x^6 - 40.0*x^5 + 46.0*x^4 - 34.0*x^3 + 16.0*x^2 - 4.0*x + 1.0
     y_2 gives 1.0*x^8 - 7.0*x^7 + 22.0*x^6 - 40.0*x^5 + 46.0*x^4 - 34.0*x^3 + 16.0*x^2 - 3.0*x

    At p = 2 ,
     y_1 gives 6561.0*x^8 - 50301.0*x^7 + 169128.0*x^6 - 325620.0*x^5 + 392526.0*x^4 - 303318.0*x^3 + 146700.0*x^2 - 40596.0*x + 4921.0
     y_2 gives 6561.0*x^8 - 50301.0*x^7 + 169128.0*x^6 - 325620.0*x^5 + 392526.0*x^4 - 303318.0*x^3 + 146700.0*x^2 - 40595.0*x + 4920.0

    At p = 3 ,
     y_1 gives 1679616.0*x^8 - 13156992.0*x^7 + 45116352.0*x^6 - 88452000.0*x^5 + 108437616.0*x^4 - 85121064.0*x^3 + 41779836.0*x^2 - 11723034.0*x + 1439671.0
     y_2 gives 1679616.0*x^8 - 13156992.0*x^7 + 45116352.0*x^6 - 88452000.0*x^5 + 108437616.0*x^4 - 85121064.0*x^3 + 41779836.0*x^2 - 11723033.0*x + 1439670.0

    At p = 4 ,
     y_1 gives 100000000.0*x^8 - 790000000.0*x^7 + 2731000000.0*x^6 - 5395900000.0*x^5 + 6664510000.0*x^4 - 5269039000.0*x^3 + 2604057100.0*x^2 - 735537190.0*x + 90909091.0
     y_2 gives 100000000.0*x^8 - 790000000.0*x^7 + 2731000000.0*x^6 - 5395900000.0*x^5 + 6664510000.0*x^4 - 5269039000.0*x^3 + 2604057100.0*x^2 - 735537189.0*x + 90909090.0

    At p = 5 ,
     y_1 gives 2562890625.0*x^8 - 20332265625.0*x^7 + 70576312500.0*x^6 - 140001412500.0*x^5 + 173589378750.0*x^4 - 137762214750.0*x^3 + 68336450100.0*x^2 - 19371849060.0*x + 2402709961.0
     y_2 gives 2562890625.0*x^8 - 20332265625.0*x^7 + 70576312500.0*x^6 - 140001412500.0*x^5 + 173589378750.0*x^4 - 137762214750.0*x^3 + 68336450100.0*x^2 - 19371849059.0*x + 2402709960.0

    At p = 6 ,
     y_1 gives 37822859361.0*x^8 - 300781786347.0*x^7 + 1046518208442.0*x^6 - 2080767777480.0*x^5 + 2585828322126.0*x^4 - 2056717275354.0*x^3 + 1022463993096.0*x^2 - 290470182324.0*x + 36103638481.0
     y_2 gives 37822859361.0*x^8 - 300781786347.0*x^7 + 1046518208442.0*x^6 - 2080767777480.0*x^5 + 2585828322126.0*x^4 - 2056717275354.0*x^3 + 1022463993096.0*x^2 - 290470182323.0*x + 36103638480.0

    At p = 7 ,
     y_1 gives 377801998336.0*x^8 - 3008923058176.0*x^7 + 10484487344128.0*x^6 - 20876434539520.0*x^5 + 25981030302976.0*x^4 - 20694127547968.0*x^3 + 10302164328400.0*x^2 - 2930773171396.0*x + 364774343221.0
     y_2 gives 377801998336.0*x^8 - 3008923058176.0*x^7 + 10484487344128.0*x^6 - 20876434539520.0*x^5 + 25981030302976.0*x^4 - 20694127547968.0*x^3 + 10302164328400.0*x^2 - 2930773171395.0*x + 364774343220.0

    At p = 8 ,
     y_1 gives 2821109907456.0*x^8 - 22490515095552.0*x^7 + 78444705042432.0*x^6 - 156349507599360.0*x^5 + 194767298862336.0*x^4 - 155282346730944.0*x^3 + 77377486975056.0*x^2 - 22033095055164.0*x + 2744863693741.0
     y_2 gives 2821109907456.0*x^8 - 22490515095552.0*x^7 + 78444705042432.0*x^6 - 156349507599360.0*x^5 + 194767298862336.0*x^4 - 155282346730944.0*x^3 + 77377486975056.0*x^2 - 22033095055163.0*x + 2744863693740.0

These polynomials resemble the Legendre polynomials.  We already proved that these are solutions to the hypergeometric equation.

    Problem 10: Curiosity Element

I chose to investigate the differential equations associated with the SIR model infectious disease spread from my Systems Ecology Modelling independent study last spring.  We can apply the model to the COVID 19 pandemic.

More info about the model I used can be found here: https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-differential-equation-model, https://www.maa.org/press/periodicals/loci/joma/the-sir-model-for-spread-of-disease-the-contact-number

To model the global spread of COVID-19 I will define 3 differential equations.  To start define  $t$ measured in days, and 3 dependent variables: $S = S(t)$ is the number of susceptible individuals, $I = I(t)$ is the number of infected individuals, and $R = R(t)$ is the number of recovered individuals.  We can define 3 more dependent variables: $s(t) = S(t)/N$ is the proportion of susceptible individuals in a population of $N$ individuals, $i(t) = I(t)/N$ is the proportion of the total population that is infected, and $r(t) = R(t)/N$ is the proportion of the total population that is recovered.  This model assumes that people cannot get Sars-CoV-2 more than once, which is not neccessarily true.  We can now define three ordinary differential equations:
\begin{align}
\frac{ds}{dt} = -bs(t)i(t) \\
\frac{dr}{dt} = ki(t) \\
\frac{di}{dt} = bs(t)i(t) - ki(t)
\end{align}
Where $b$ is a fixed number of contacts per day with infected individuals that applies to every individual, and $k$ is a fixed fraction of the infected group that recovers per day.

We know that a typical COVID patient is infectious for about 14 days, so we can set $k = 1/14$.  Let $b = 1/2$, meaning each person comes in contact with an infectious COVID patient every 2 days.  Now we can try to solve and plot the equations with sage.

```python
# here t was changed to x to check for code errors
from sage.symbolic.integration.integral import indefinite_integral

x = var('x')
s = function('s')(x)
i = function('i')(x)
r = function('r')(x)

sus = desolve(diff(s,x) + (1/3)*i*s,s)
imm = desolve(diff(i,x)-(1/3)*s*i + (1/14)*i,i)
rec = desolve(diff(r,x)-(1/14)*i,r)

print("s = ")
sus.show()
print("i = ")
imm.show()
print("r = ")
rec.show()

rec = (1/14)*indefinite_integral(imm,x)
print("r =")
rec.show()
```

    s =

    i =

    r =

    r =

I am unable to graph the equations because they all depend on each other.  In order to graph I will need to do more research on solving systems of differential equations. This technique may involve the Wronskian and variation of parameters.  I don't have time to try this now, so maybe another time.

```python

```


# Import Required Packages

```python
import textwrap
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from scipy.ndimage import gaussian_filter
from PyEMD import EMD as pyemd0215
import emd as emd040
```

```python
import sys
sys.path.append("..")
import AdvEMDpy
from emd_hilbert import hilbert_spectrum
```

# Synthetic Example: Duffing Equation

\begin{equation} \label{spring}
    \frac{d^2x(t)}{dt^2} + {\omega}x(t) = 0,
\end{equation}

\begin{equation} \label{Duffing_equation}
    \frac{d^2x(t)}{dt^2} + \Big(1 - x^2(t)\Big)x(t) = \frac{1}{10}\text{cos}\bigg(\frac{1}{25}2{\pi}t\bigg),
\end{equation}

# Set-Up of Duffing Equation

```python
def duffing_equation(xy, ts):
    gamma = 0.1
    epsilon = 1
    omega = ((2 * np.pi) / 25)
    return [xy[1], xy[0] - epsilon * xy[0] ** 3 + gamma * np.cos(omega * ts)]

t = np.linspace(0, 150, 1501)
XY0 = [1, 1]
solution = odeint(duffing_equation, XY0, t)
x = solution[:, 0]
dxdt = solution[:, 1]
```

# Plot Displacement and Velocity

```python
x_points = [0, 50, 100, 150]
x_names = {0, 50, 100, 150}
y_points_1 = [-2, 0, 2]
y_points_2 = [-1, 0, 1]

fig, axs = plt.subplots(2, 1)
plt.subplots_adjust(hspace=0.2)
axs[0].plot(t, x)
axs[0].set_title('Duffing Equation Displacement')
axs[0].set_ylim([-2, 2])
axs[0].set_xlim([0, 150])

axs[1].plot(t, dxdt)
axs[1].set_title('Duffing Equation Velocity')
axs[1].set_ylim([-1.5, 1.5])
axs[1].set_xlim([0, 150])

axis = 0
for ax in axs.flat:
    ax.label_outer()
    if axis == 0:
        ax.set_ylabel('x(t)')
        ax.set_yticks(y_points_1)
    if axis == 1:
        ax.set_ylabel(r'$ \dfrac{dx(t)}{dt} $')
        ax.set(xlabel='t')
        ax.set_yticks(y_points_2)
    ax.set_xticks(x_points)
    ax.set_xticklabels(x_names)
    axis += 1
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# PyEMD 0.2.10

```python
pyemd = pyemd0215()
py_emd = pyemd(x)
IP, IF, IA = emd040.spectra.frequency_transform(py_emd.T, 10, 'hilbert')
freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100)
hht = emd040.spectra.hilberthuang(IF, IA, freq_edges)
hht = gaussian_filter(hht, sigma=1)
ax = plt.subplot(111)
plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using PyEMD 0.2.10', 40))
plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))
plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15))
plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15))
plt.xticks([0, 50, 100, 150])
plt.yticks([0, 0.1, 0.2])
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')

box_0 = ax.get_position()
ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# emd 0.3.3

```python
emd_sift = emd040.sift.sift(x)
IP, IF, IA = emd040.spectra.frequency_transform(emd_sift, 10, 'hilbert')
freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 0.2, 100)
hht = emd040.spectra.hilberthuang(IF, IA, freq_edges)
hht = gaussian_filter(hht, sigma=1)
ax = plt.subplot(111)
plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using emd 0.3.3', 40))
plt.pcolormesh(t, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))
plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15))
plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15))
plt.xticks([0, 50, 100, 150])
plt.yticks([0, 0.1, 0.2])
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')

box_0 = ax.get_position()
ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# AdvEMDpy

```python
emd_duffing = AdvEMDpy.EMD(time=t, time_series=x)
emd_duff, emd_ht_duff, emd_if_duff, _, _, _, _ = emd_duffing.empirical_mode_decomposition(verbose=False)

fig, axs = plt.subplots(2, 1)
plt.subplots_adjust(hspace=0.3)
axs[0].plot(t, emd_duff[1, :], label='AdvEMDpy')
axs[0].plot(t, py_emd[0, :], '--', label='PyEMD 0.2.10')
axs[0].plot(t, emd_sift[:, 0], '--', label='emd 0.3.3')
axs[0].set_title('IMF 1')
axs[0].set_ylim([-2, 2])
axs[0].set_xlim([0, 150])

axs[1].plot(t, emd_duff[2, :], label='AdvEMDpy')
axs[1].plot(t, py_emd[1, :], '--', label='PyEMD 0.2.10')
axs[1].plot(t, emd_sift[:, 1], '--', label='emd 0.3.3')
axs[1].plot(t, 0.1 * np.cos(0.04 * 2 * np.pi * t), '--', label=r'$0.1$cos$(0.08{\pi}t)$')
axs[1].set_title('IMF 2')
axs[1].set_ylim([-0.2, 0.4])
axs[1].set_xlim([0, 150])

axis = 0
for ax in axs.flat:
    ax.label_outer()
    if axis == 0:
        ax.set_ylabel(r'$\gamma_1(t)$')
        ax.set_yticks([-2, 0, 2])
    if axis == 1:
        ax.set_ylabel(r'$\gamma_2(t)$')
        ax.set_yticks([-0.2, 0, 0.2])
    box_0 = ax.get_position()
    ax.set_position([box_0.x0, box_0.y0, box_0.width * 0.85, box_0.height])
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5), fontsize=8)
    ax.set_xticks(x_points)
    ax.set_xticklabels(x_names)
    axis += 1
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# Sum of absolute errors between true underlying driving function and IMF 2 for each package

\begin{equation}
\begin{split}
    \sum_{i=0}^{1500}\bigg|IMF^{emd}_{2}(t_i) - 0.1\text{cos}(0.08\pi(t_i))\bigg| &= 21.434\\
    \sum_{i=0}^{1500}\bigg|IMF^{PyEMD}_{2}(t_i) - 0.1\text{cos}(0.08\pi(t_i))\bigg| &= 20.774\\
    \sum_{i=0}^{1500}\bigg|IMF^{AdvEMDpy}_{2}(t_i) - 0.1\text{cos}(0.08\pi(t_i))\bigg| &= 15.978,
\end{split}
\end{equation}

```python
print(f'emd 0.3.3:    {round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi * t) - emd_sift[:, 1])), 3)}')
print(f'PyEMD 0.2.10: {round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi * t) - py_emd[1, :])), 3)}')
print(f'AdvEMDpy:     {round(sum(abs(0.1 * np.cos(0.04 * 2 * np.pi * t) - emd_duff[2, :])), 3)}')
```

    emd 0.3.3:    21.434
    PyEMD 0.2.10: 20.774
    AdvEMDpy:     15.978

# Hilbert spectrum using AdvEMDpy

```python
hs_ouputs = hilbert_spectrum(t, emd_duff, emd_ht_duff, emd_if_duff, max_frequency=1.3, plot=False)

ax = plt.subplot(111)
plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of Duffing Equation using AdvEMDpy', 40))
x_hs, y, z = hs_ouputs
y = y / (2 * np.pi)
z_min, z_max = 0, np.abs(z).max()
ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max)
plt.plot(t[:-1], 0.124 * np.ones_like(t[:-1]), '--', label=textwrap.fill('Hamiltonian frequency approximation', 15))
plt.plot(t[:-1], 0.04 * np.ones_like(t[:-1]), 'g--', label=textwrap.fill('Driving function frequency', 15))
plt.xticks([0, 50, 100, 150])
plt.yticks([0, 0.1, 0.2])
plt.ylabel('Frequency (Hz)')
plt.xlabel('Time (s)')

box_0 = ax.get_position()
ax.set_position([box_0.x0, box_0.y0 + 0.05, box_0.width * 0.75, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# Real-World Example: Carbon Dioxide Concentration

# Load CO2 data

```python
CO2_data = pd.read_csv('../Data/co2_mm_mlo.csv', header=51)

plt.plot(CO2_data['month'], CO2_data['decimal date'])
plt.title(textwrap.fill('Mean Monthly Concentration of Carbon Dioxide in the Atmosphere', 35))
plt.ylabel('Parts per million')
plt.xlabel('Time (years)')
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()

signal = CO2_data['decimal date']
signal = np.asarray(signal)
time = CO2_data['month']
time = np.asarray(time)
```

# PyEMD 0.2.10

```python
pyemd = pyemd0215()
py_emd = pyemd(signal)
IP, IFpyemd, IA = emd040.spectra.frequency_transform(py_emd[:2, :].T, 12, 'hilbert')
freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100)
hht = emd040.spectra.hilberthuang(IFpyemd, IA, freq_edges)
hht = gaussian_filter(hht, sigma=1)
fig, ax = plt.subplots()
plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using PyEMD 0.2.10', 45))
plt.ylabel('Frequency (year$^{-1}$)')
plt.xlabel('Time (years)')
plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))
plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10))
box_0 = ax.get_position()
ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# emd 0.3.3

```python
emd_sift = emd040.sift.sift(signal)
IP, IFemd, IA = emd040.spectra.frequency_transform(emd_sift[:, :1], 12, 'hilbert')
freq_edges, freq_bins = emd040.spectra.define_hist_bins(0, 2, 100)
hht = emd040.spectra.hilberthuang(IFemd, IA, freq_edges)
hht = gaussian_filter(hht, sigma=1)
fig, ax = plt.subplots()
plt.title(textwrap.fill('Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using emd 0.3.3', 45))
plt.ylabel('Frequency (year$^{-1}$)')
plt.xlabel('Time (years)')
plt.pcolormesh(time, freq_bins, hht, cmap='gist_rainbow', vmin=0, vmax=np.max(np.max(np.abs(hht))))
plt.plot(time, np.ones_like(time), 'k--', label=textwrap.fill('Annual cycle', 10))
box_0 = ax.get_position()
ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# AdvEMDpy

```python
knots = np.linspace(time[0], time[-1], 200)
emd_example = AdvEMDpy.EMD(time=time, time_series=signal)
imfs, hts, ifs, _, _, _, _ = emd_example.empirical_mode_decomposition(knots=knots, knot_time=time, verbose=False)

fig, axs = plt.subplots(2, 2)
plt.subplots_adjust(hspace=0.5)
axs[0, 0].plot(time, signal)
axs[0, 1].plot(time, signal)
axs[0, 1].plot(time, imfs[0, :], label='Smoothed')
axs[0, 1].legend(loc='lower right')
axs[1, 0].plot(time, imfs[1, :])
axs[1, 1].plot(time, imfs[2, :])

axis = 0
for ax in axs.flat:
    if axis == 0:
        ax.set(ylabel=R'C0$_2$ concentration')
    if axis == 1:
        pass
    if axis == 2:
        ax.set(ylabel=R'C0$_2$ concentration')
        ax.set(xlabel='Time (years)')
    if axis == 3:
        ax.set(xlabel='Time (years)')
    axis += 1

plt.gcf().subplots_adjust(bottom=0.15)

axs[0, 0].set_title(r'Original CO$_2$ Concentration')
axs[0, 1].set_title('Smoothed CO$_2$ Concentration')
axs[1, 0].set_title('IMF 1')
axs[1, 1].set_title('Residual')

plt.gcf().subplots_adjust(bottom=0.15)
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

# Sum of absolute errors between annual frequency and instantaneous frequency of IMF 1 for each package

\begin{equation}
\begin{split}
    \sum_{i=0}^{750}\bigg|IF^{PyEMD}_{1}(t_i) - 1\bigg| &= 181.076\\
    \sum_{i=0}^{750}\bigg|IF^{emd}_{1}(t_i) - 1\bigg| &= 174.047\\
    \sum_{i=0}^{750}\bigg|IF^{AdvEMDpy}_{1}(t_i) - 1\bigg| &= 37.616,
\end{split}
\end{equation}

```python
print(f'PyEMD 0.2.10: {round(sum(np.abs(IFpyemd[:, 0] - np.ones_like(IFpyemd[:, 0]))), 3)}')
print(f'emd 0.3.3:    {round(sum(np.abs(IFemd - np.ones_like(IFemd)))[0], 3)}')
print(f'AdvEMDpy:     {round(sum(np.abs(ifs[1, :] / (2 * np.pi) - np.ones_like(ifs[1, :]))), 3)}')
```

    PyEMD 0.2.10: 181.076
    emd 0.3.3:    174.047
    AdvEMDpy:     37.616

# Hilbert spectrum using AdvEMDpy

```python
hs_ouputs = hilbert_spectrum(time, imfs, hts, ifs, max_frequency=10, which_imfs=[1], plot=False)

x_hs, y, z = hs_ouputs
y = y / (2 * np.pi)

z_min, z_max = 0, np.abs(z).max()
fig, ax = plt.subplots()
ax.pcolormesh(x_hs, y, np.abs(z), cmap='gist_rainbow', vmin=z_min, vmax=z_max)
ax.set_title(textwrap.fill(r'Gaussian Filtered Hilbert Spectrum of CO$_{2}$ Concentration using AdvEMDpy', 40))
plt.ylabel('Frequency (year$^{-1}$)')
plt.xlabel('Time (years)')
plt.plot(x_hs[0, :], np.ones_like(x_hs[0, :]), 'k--', label=textwrap.fill('Annual cycle', 10))
ax.axis([x_hs.min(), x_hs.max(), y.min(), y.max()])

box_0 = ax.get_position()
ax.set_position([box_0.x0 + 0.0125, box_0.y0 + 0.075, box_0.width * 0.8, box_0.height * 0.9])
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
plt.rcParams['figure.figsize'] = [15, 12]
plt.show()
```

```python

```