# Conservative SDOF - Harmonic Balance (2)

- Good for strongly and weakly NL systems
- Requires significant knowledge about system studied
- Similar to Galerkin method, but in time

## Overview

Assume an harmonic expansion for $x(t)$

$$
\begin{gather*}
     x(t) = \sum^N_{m = 0} A_m \cos\left( m\omega t + m \beta_0\right)
\end{gather*}
$$

substitute this into the EOM and enforce zero projected residual, i.e. taking the inner product with orthogonal assumption.

$$
\begin{gather*}
    \left< EOM_{LHS},\phantom{-} \cos\left(m\omega t + m\beta_0\right) \right> = 0\\
    m = 0, 1, 2, \cdots, N
\end{gather*}
$$

which is

$$
\begin{gather*}
    \int_0^{\frac{2\pi}{\omega} } \left( EOM_{LHS}\bullet \cos\left(m\omega t + m\beta_0\right) \right)dt
\end{gather*}
$$

Then we solve for $A_0, A_2, A_3, \cdots, A_n$ and $\omega$ in terms of $A_1$ and other system parameters. In this example we solve the following equation

$$
\begin{gather*}
    \ddot{x} + \omega_0^2 x + \alpha_2 x^2 + \alpha_3 x^3 = 0.
\end{gather*}
$$

## Assumed Harmonic Expansion - up to and including $\cos\left(2\left(\omega t + \beta \right)\right)$ and $\alpha_2 = 0$ no spurious solutions

Assume a harmonic expansion for $x(t)$ - will use this to satisfy the cubic equation, so include harmonic terms at twice the linear natrual frequency

Note: phi = omega * t + beta0

```python
import sympy as sp
from sympy.simplify.fu import TR4, TR7, TR8, TR11
import numpy as np
from itertools import combinations_with_replacement
from math import factorial
```

```python
M = 2  # order of harmonic expansion
Ai = sp.symbols('A_(0:' + str(M+1) + ')', real=True)  # coefficient A
t, w, w0 = sp.symbols('t omega omega_0', real=True, positive=True)
b0 = sp.Symbol('beta_0')

# harmonic expansion of x(t)
phi = sp.Symbol('phi')
xh = sp.Function('x_h')(phi)
xh = sum([Ai[i] * sp.cos(i * phi) for i in range(M+1)])
xh
```

$\displaystyle A_{0} + A_{1} \cos{\left(\phi \right)} + A_{2} \cos{\left(2 \phi \right)}$

```python
# Defining the EOM
N = 3  # order of powered terms of alpha
ai = sp.symbols('alpha_(2:' + str(N+1) + ')')
x = sp.Function('x')(phi)

# EOM
EOM = w**2 * sp.diff(x, phi, 2) + w0**2 * x + sum([ai[i-2] * x**i for i in range(2, N+1)])
EOM = sp.Eq(EOM, 0)
EOM = EOM.subs(ai[0], 0)  #! set alpha_2 = 0
EOM
```

$\displaystyle \alpha_{3} x^{3}{\left(\phi \right)} + \omega^{2} \frac{d^{2}}{d \phi^{2}} x{\left(\phi \right)} + \omega_{0}^{2} x{\left(\phi \right)} = 0$

```python
# Substitute x(t) for the harmonic expansion of x(t) into EOM
err = EOM.lhs.subs(x, xh).doit().expand()
err = TR7(err).expand()
err = TR8(err).expand()
err
```

$\displaystyle A_{0}^{3} \alpha_{3} + 3 A_{0}^{2} A_{1} \alpha_{3} \cos{\left(\phi \right)} + 3 A_{0}^{2} A_{2} \alpha_{3} \cos{\left(2 \phi \right)} + \frac{3 A_{0} A_{1}^{2} \alpha_{3} \cos{\left(2 \phi \right)}}{2} + \frac{3 A_{0} A_{1}^{2} \alpha_{3}}{2} + 3 A_{0} A_{1} A_{2} \alpha_{3} \cos{\left(\phi \right)} + 3 A_{0} A_{1} A_{2} \alpha_{3} \cos{\left(3 \phi \right)} + \frac{3 A_{0} A_{2}^{2} \alpha_{3} \cos{\left(4 \phi \right)}}{2} + \frac{3 A_{0} A_{2}^{2} \alpha_{3}}{2} + A_{0} \omega_{0}^{2} + \frac{3 A_{1}^{3} \alpha_{3} \cos{\left(\phi \right)}}{4} + \frac{A_{1}^{3} \alpha_{3} \cos{\left(3 \phi \right)}}{4} + \frac{3 A_{1}^{2} A_{2} \alpha_{3} \cos{\left(2 \phi \right)}}{2} + \frac{3 A_{1}^{2} A_{2} \alpha_{3} \cos{\left(4 \phi \right)}}{4} + \frac{3 A_{1}^{2} A_{2} \alpha_{3}}{4} + \frac{3 A_{1} A_{2}^{2} \alpha_{3} \cos{\left(\phi \right)}}{2} + \frac{3 A_{1} A_{2}^{2} \alpha_{3} \cos{\left(3 \phi \right)}}{4} + \frac{3 A_{1} A_{2}^{2} \alpha_{3} \cos{\left(5 \phi \right)}}{4} - A_{1} \omega^{2} \cos{\left(\phi \right)} + A_{1} \omega_{0}^{2} \cos{\left(\phi \right)} + \frac{3 A_{2}^{3} \alpha_{3} \cos{\left(2 \phi \right)}}{4} + \frac{A_{2}^{3} \alpha_{3} \cos{\left(6 \phi \right)}}{4} - 4 A_{2} \omega^{2} \cos{\left(2 \phi \right)} + A_{2} \omega_{0}^{2} \cos{\left(2 \phi \right)}$

Note there are terms with frequency content as high as $6\phi$

To find $A_0$, $\omega$, $A_2$, we project the error back on the assumed expansion and set the projections to zero

Note: same as setting the coefficients in front of each $\cos(n\phi)$ to zero for $n = 0, 1, 2$

```python
proj_eqn = {}
for i in range(M+1):
    proj_eqn['eq'+str(i)] = sp.integrate(sp.expand_trig(err * sp.cos(i * phi)), (phi, 0, 2*sp.pi))
```

```python
proj_eqn['eq0']
```

$\displaystyle 2 \pi A_{0}^{3} \alpha_{3} + 3 \pi A_{0} A_{1}^{2} \alpha_{3} + 3 \pi A_{0} A_{2}^{2} \alpha_{3} + 2 \pi A_{0} \omega_{0}^{2} + \frac{3 \pi A_{1}^{2} A_{2} \alpha_{3}}{2}$

```python
proj_eqn['eq1']
```

$\displaystyle 3 \pi A_{0}^{2} A_{1} \alpha_{3} + 3 \pi A_{0} A_{1} A_{2} \alpha_{3} + \frac{3 \pi A_{1}^{3} \alpha_{3}}{4} + \frac{3 \pi A_{1} A_{2}^{2} \alpha_{3}}{2} - \pi A_{1} \omega^{2} + \pi A_{1} \omega_{0}^{2}$

```python
proj_eqn['eq2']
```

$\displaystyle 3 \pi A_{0}^{2} A_{2} \alpha_{3} + \frac{3 \pi A_{0} A_{1}^{2} \alpha_{3}}{2} + \frac{3 \pi A_{1}^{2} A_{2} \alpha_{3}}{2} + \frac{3 \pi A_{2}^{3} \alpha_{3}}{4} - 4 \pi A_{2} \omega^{2} + \pi A_{2} \omega_{0}^{2}$

if $A_1$ is small neglect terms with $A_0^2, A_2^2, A_0A_2, A_1^2A_0, A_0^3, A_1^2A_2, \cdots$

This is because there is the assumption of
$$
\begin{gather*}
    A_1 > A_i \phantom{---} i = 0, 2, 3, \cdots
\end{gather*}
$$

equation 0 tells us that $A_0$ is proportional to $A_1$ squared - We have a constant term multiplying $A_0$ (in addition to others) and no $A_1$ terms but only $A_1^2$ terms.

```python
deglist = list(map(int, sp.degree_list(proj_eqn['eq0'], gens=Ai)))
A1_deg = deglist[1]
removing_combos = []
Ai_ = tuple(filter(lambda A: A != Ai[1], Ai))

# A1 ** n -> n can be up to O(A1**4) which is square of A1**2
keep_terms = []
for i in range(A1_deg+1, A1_deg**2+1):
    temp = []
    for j in range(i):
        temp.append(Ai[1])
    keep_terms.append(tuple(temp))

temp = list(combinations_with_replacement(Ai_, A1_deg))
for t in temp:
    if t not in keep_terms:
        removing_combos.append(t)

for i in range(A1_deg+1, max(deglist)+1):
    temp = list(combinations_with_replacement(Ai, i))
    for t in temp:
        if t not in keep_terms:
            removing_combos.append(t)

eq_copy = proj_eqn['eq0']
for term in removing_combos:
    eq_copy = eq_copy.subs(np.prod(term), 0)

eq_copy = sp.Eq(eq_copy, 0)

eq0_new = eq_copy
eq0_ordered = eq0_new
epsilon = sp.Symbol('epsilon')
for A in Ai_:
    eq0_ordered = eq0_ordered.subs(A, epsilon**A1_deg * A)
eq0_ordered = sp.collect(eq0_ordered.subs(Ai[1], epsilon * Ai[1]).lhs, epsilon)
eq0_ordered = sp.Eq(eq0_ordered, 0)

eq_copy = sp.Eq(Ai[0], sp.solve(eq_copy, Ai[0])[0])
eq_copy
```

$\displaystyle A_{0} = 0$

equation 2 tells $A_2$ is also proportional to $A_1$ squared

```python
deglist = list(map(int, sp.degree_list(proj_eqn['eq2'], gens=Ai)))
A1_deg = deglist[1]
Ai_ = tuple(filter(lambda A: A != Ai[1], Ai))

for i in range(A1_deg+1, max(deglist)+1):
    temp = list(combinations_with_replacement(Ai, i))
    for t in temp:
        if t not in removing_combos:
            if t not in keep_terms:
                removing_combos.append(t)

eq_copy = proj_eqn['eq2']
for term in removing_combos:
    eq_copy = eq_copy.subs(np.prod(term), 0)

eq_copy = sp.Eq(eq_copy, 0)

eq2_new = eq_copy
eq2_ordered = eq2_new
for A in Ai_:
    eq2_ordered = eq2_ordered.subs(A, epsilon**A1_deg * A)
eq2_ordered = sp.collect(eq2_ordered.subs(Ai[1], epsilon * Ai[1]).lhs, epsilon)
eq2_ordered = sp.Eq(eq2_ordered, 0)

eq_copy = sp.Eq(Ai[2], sp.solve(eq_copy, Ai[2])[0])
eq_copy
```

$\displaystyle A_{2} = 0$

```python
eq_copy = proj_eqn['eq1']
for term in removing_combos:
    eq_copy = eq_copy.subs(np.prod(term), 0)

eq_copy = sp.Eq(eq_copy, 0)
eq1_new = eq_copy
eq1_ordered = eq1_new
for A in Ai_:
    eq1_ordered = eq1_ordered.subs(A, epsilon**A1_deg * A)
eq1_ordered = sp.collect(eq1_ordered.subs(Ai[1], epsilon * Ai[1]).lhs, epsilon)
eq1_ordered = sp.Eq(eq1_ordered, 0)
```

To facilitate the solution, we order the coefficients using epsilon and then ignore all terms quadratic and higher in $A_0$ and $A_2$ - this means we keep terms up to tand including $O(\epsilon^3)$ -> small amplitude assumption

$A_1$ is ordered at $\epsilon$ and $A_0$ and $A_2$ are order at $\epsilon^2$

```python
# Eq0
eq0_ordered
```

$\displaystyle 2 \pi A_{0} \epsilon^{2} \omega_{0}^{2} = 0$

```python
# Eq1
eq1_ordered
```

$\displaystyle \frac{3 \pi A_{1}^{3} \alpha_{3} \epsilon^{3}}{4} + \epsilon \left(- \pi A_{1} \omega^{2} + \pi A_{1} \omega_{0}^{2}\right) = 0$

```python
# Eq2
eq2_ordered
```

$\displaystyle \epsilon^{2} \left(- 4 \pi A_{2} \omega^{2} + \pi A_{2} \omega_{0}^{2}\right) = 0$

```python
A0_sol = sp.solve(eq0_ordered, Ai[0])[0]
A0_sol
```

$\displaystyle 0$

```python
A2_sol = sp.solve(eq2_ordered, Ai[2])[0]
A2_sol
```

$\displaystyle 0$

```python
eq1_ordered_update = eq1_ordered.subs([
    (Ai[0], A0_sol), (Ai[2], A2_sol)
])
omegaSol = sp.solve(eq1_ordered_update, w)
```

```python
omegaSol[0]
```

$\displaystyle - \frac{\sqrt{3 A_{1}^{2} \alpha_{3} \epsilon^{2} + 4 \omega_{0}^{2}}}{2}$

```python
omegaSol[1]
```

$\displaystyle \frac{\sqrt{3 A_{1}^{2} \alpha_{3} \epsilon^{2} + 4 \omega_{0}^{2}}}{2}$

We are keeping up to $O(\epsilon^4)$ only - use this to get our final expression for $\omega$

```python
# The built in sympy series command takes forever (bad algorithm) so we just implement our original Taylor series function
def taylor(expr, var, upto):
    res = expr.subs(var, 0)
    dexpr = sp.diff(expr, var)
    for n in range(1,upto+1):
        res += dexpr.subs(var, 0) / factorial(n) * var**n
        dexpr = sp.diff(dexpr, var)
    return res + sp.O(var**upto)
```

```python
omega1 = taylor(omegaSol[0], epsilon, 4)
omega1
```

$\displaystyle - \omega_{0} - \frac{3 A_{1}^{2} \alpha_{3} \epsilon^{2}}{8 \omega_{0}} + O\left(\epsilon^{4}\right)$

```python
omega2 = taylor(omegaSol[1], epsilon, 4)
omega2
```

$\displaystyle \omega_{0} + \frac{3 A_{1}^{2} \alpha_{3} \epsilon^{2}}{8 \omega_{0}} + O\left(\epsilon^{4}\right)$

```python
omega = sp.simplify(omega2)
omega
```

$\displaystyle \omega_{0} + \frac{3 A_{1}^{2} \alpha_{3} \epsilon^{2}}{8 \omega_{0}} + O\left(\epsilon^{4}\right)$

```python
t = sp.Symbol('t')
phi_temp = omega.removeO() * t
phi_temp
```

$\displaystyle t \left(\frac{3 A_{1}^{2} \alpha_{3} \epsilon^{2}}{8 \omega_{0}} + \omega_{0}\right)$

```python
x = xh.subs([
    (Ai[0], A0_sol), (Ai[2], A2_sol), (phi, omega.removeO()*t)
])
x = x.subs(w, omega.removeO())
x
```

$\displaystyle A_{1} \cos{\left(t \left(\frac{3 A_{1}^{2} \alpha_{3} \epsilon^{2}}{8 \omega_{0}} + \omega_{0}\right) \right)}$

```python
initial_amplitude = sp.simplify(x.subs([
    (t, 0), (epsilon, 1)
]))
initial_amplitude
```

$\displaystyle A_{1}$

```python
ic = float(sp.simplify(initial_amplitude.subs([
    (Ai[1], 1)
])))
ic
```

    1.0

```python
# We plot the phase plane of this system

import matplotlib.pyplot as plt
from scipy.integrate import solve_ivp, DOP853
from typing import List
```

```python
# System
def sys(t, x):
    return [x[1], -x[0] - x[0]**3]

def solve_diffeq(func, t, tspan, ic, parameters={}, algorithm='DOP853', stepsize=np.inf):
    return solve_ivp(fun=func, t_span=tspan, t_eval=t, y0=ic, method=algorithm,
                     args=tuple(parameters.values()), atol=1e-8, rtol=1e-5, max_step=stepsize)

def phasePlane(x1, x2, func, params):
    X1, X2 = np.meshgrid(x1, x2)  # create grid
    u, v = np.zeros(X1.shape), np.zeros(X2.shape)
    NI, NJ = X1.shape
    for i in range(NI):
        for j in range(NJ):
            x = X1[i, j]
            y = X2[i, j]
            dx = func(0, (x, y), *params.values())  # compute values on grid
            u[i, j] = dx[0]
            v[i, j] = dx[1]
    M = np.hypot(u, v)
    u /= M
    v /= M
    return X1, X2, u, v, M

def DEplot(sys: object, tspan: tuple, x0: List[List[float]],
           x: np.ndarray, y: np.ndarray, params: dict):
    if len(tspan) != 3:
        raise Exception('tspan should be tuple of size 3: (min, max, number of points).')
    # Set up the figure the way we want it to look
    plt.figure(figsize=(12, 9))

    X1, X2, dx1, dx2, M = phasePlane(
        x, y, sys, params
    )

    # Quiver plot
    plt.quiver(X1, X2, dx1, dx2, M, scale=None, pivot='mid')
    plt.grid()

    if tspan[0] < 0:
        t1 = np.linspace(0, tspan[0], tspan[2])
        t2 = np.linspace(0, tspan[1], tspan[2])
        if min(tspan) < 0:
            t_span1 = (np.max(t1), np.min(t1))
        else:
            t_span1 = (np.min(t1), np.max(t1))
        t_span2 = (np.min(t2), np.max(t2))
        for x0i in x0:
            sol1 = solve_diffeq(sys, t1, t_span1, x0i, params)
            plt.plot(sol1.y[0, :], sol1.y[1, :], '-r')
            sol2 = solve_diffeq(sys, t2, t_span2, x0i, params)
            plt.plot(sol2.y[0, :], sol2.y[1, :], '-r')
    else:
        t = np.linspace(tspan[0], tspan[1], tspan[2])
        t_span = (np.min(t), np.max(t))
        for x0i in x0:
            sol = solve_diffeq(sys, t, t_span, x0i, params)
            plt.plot(sol.y[0, :], sol.y[1, :], '-r')

    plt.xlim([np.min(x), np.max(x)])
    plt.ylim([np.min(y), np.max(y)])
    plt.show()
```

Using the initial condition found, we get response with period $2\pi$ not $4\pi$

```python
x0 = [[0.1, 0.0]]

x1 = np.linspace(-1, 1, 20)
x2 = np.linspace(-1, 1, 20)

DEplot(sys, (0, 2*np.pi, 1000), x0, x1, x2, {})
```

An attempt to use a much bigger initial condition

```python
x0 = [[3.0, 0.0]]

x1 = np.linspace(-18, 18, 20)
x2 = np.linspace(-18, 18, 20)

DEplot(sys, (0, 2*np.pi, 1000), x0, x1, x2, {})
```


# Symbolic Mathematics in Python

There are times when you need to solve a difficult problem symbollically or analytically. If you have ever used Wolfram Alpha, then you have already done this. Sympy is a python library that allows you to do symbolic mathematics in python.

```python
import sympy as sym
```

## 1. Introduction

### Example 1.1

If you try to write the follwing in python by itself, you will get an error telling you x is undefined:
$$x-x$$

```python
x-x
```

(The error above is on purpose). Variables in python need to be defined before you can say something specific about them

```python
x=102
x-x
```

If you are trying to show that $x-x=0$ is true for any $x$, the above answer would not be valid. Instead you can use a symbolic expression to show that it is true

**First we define the variable as a symmbolic expression**

```python
x = sym.symbols('x')
```

**Now we can use the variable in a symbolic expression**

```python
x-x
```

### Example 1.2

Sympy can be used to perform algebreic operations (among other things). Consider the following expression: $$(3a-4b)^3$$

We can use symppy to expand the expression algebraically.

**First we need to define the variables as symbolic expressions**

```python
a,b = sym.symbols('a,b')
```

**Side note** Notice that the left hand side of the epression has two variables being defined. Python can define more than one variable at a time:

```python
x1,y1 =10,20
print(x1)
print(y1)
```

    10
    20

**Back to the expression** We can define an expression using the variables $a$ and $b$.

```python
expr = (3*a-4*b)**3
print(expr)
```

    (3*a - 4*b)**3

We can also make it look nicer in our notebook. This doesn't affect the math, but it makes our notebook more readable.

```python
sym.init_printing()
```

```python
expr
```

**Now we expand the function algebreically**

```python
expr.expand()
```

Sympy can also factor the equation

```python
sym.factor(26*a**3-108*a**2*b+144*a*b**2-64*b**3)
```

If you want to copy and paste a result, you print the result.

```python
print(sym.factor(26*a**3-108*a**2*b+144*a*b**2-64*b**3))
```

    2*(a - 2*b)*(13*a**2 - 28*a*b + 16*b**2)

You can also chain together functions

```python
expr.expand().factor()
```

### Exercise 1.1

Show that the following two expressions are true.
$$(2w-3z)(2w+3z)=4w^2-9z^2$$
$$(2w-3z)^2\ne4w^2-9z^2$$

```python
w,z = sym.symbols('w,z')
expr = (2*w-3*z)*(2*w+3*z)
```

```python
expr
```

```python
sym.expand(expr).factor(expr)
```

```python
print("this shows that they are equal")
```

    this shows that they are equal

```python
expr1 = (2*w-3*z)**2
```

```python
expr1
```

```python
sym.expand(expr1).factor(expr1)
```

```python
print("this shows that they are not equal")
```

    this shows that they are not equal

## 2. Solving Equations

Sympy can be used to symbolilically solve equations. As before, you need to define which variables are symbols

### Example 2.1

Use sympy to solve the following equation
$$ax^3+bx^2+cx+d=0$$

```python
# Define the variables
a,b,c,d,x = sym.symbols('a,b,c,d,x')
```

```python
# Define the expression
expr=a*x**3+b*x**2+c*x+d
expr
```

We can use the `solvset` function to solve this equation

```python
solutions=sym.solveset(expr,x)
```

```python
print(solutions)
```

    {-(-3*c/a + b**2/a**2)/(3*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)) - (sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)/3 - b/(3*a), -(-3*c/a + b**2/a**2)/(3*(-1/2 - sqrt(3)*I/2)*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)) - (-1/2 - sqrt(3)*I/2)*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)/3 - b/(3*a), -(-3*c/a + b**2/a**2)/(3*(-1/2 + sqrt(3)*I/2)*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)) - (-1/2 + sqrt(3)*I/2)*(sqrt(-4*(-3*c/a + b**2/a**2)**3 + (27*d/a - 9*b*c/a**2 + 2*b**3/a**3)**2)/2 + 27*d/(2*a) - 9*b*c/(2*a**2) + b**3/a**3)**(1/3)/3 - b/(3*a)}

```python
solutions
```

What if I need help. You can do this with any python function. `function?`

```python
# Run this command to see a help box
sym.solveset?
```

### Exercise 2.1

Use the `solveset` function to solve the following chemical problem.

Phosgene gas, $\text{COCl}_2$, dissociates at high temperatures according to the following equilibrium:

$$ \text{COCl}_2 \rightleftharpoons  \text{CO} + \text{Cl}_2 $$

At $\text{400 C}$, the equilibrium constant $K_c=8.05$.

If you start with a  $\text{0.250 M}$ phosgene sample at $\text{400 C}$, determine the concentrations of all species at equilibrium.

```python
sym.symbols('x')
expr2=x**2-((8.05*0.250)-(8.05*x))
solutions=sym.solveset(expr2,x)
```

```python
solutions
```

Why did you pick your answer?

## 3. Calculus

We can use also Sympy to differentiate and integrate. Let us experiment with differentiating the following expression:

$$x ^ 2 - \cos(x)$$

```python
sym.diff(x ** 2 - sym.cos(x), x)
```

Similarly we can integrate:

```python
sym.integrate(x ** 2 - sym.cos(x), x)
```

We can also carry out definite integrals:

```python
sym.integrate(x ** 2 - sym.cos(x), (x, 0, 5))
```

### Exercise 3.1

Use Sympy to calculate the following:

1. $\frac{d(x ^2 + xy - \ln(y))}{dy}$
1. $\int_0^5 e^{2x}\;dx$

```python
y=sym.symbols('y')
sym.diff(x**2 + x*y -sym.log(y), y)
```

```python
x=sym.symbols('x')
sym.integrate(sym.E**(2*x), (x, 0, 5))
```

### Exercise 3.2
Solve the following definate integral
$$\int\limits_{ - \infty }^\infty  {\frac{1}{{\sigma \sqrt {2\pi } }}{e^{ - \frac{1}{2}{{\left( {\frac{{x - \mu }}{\sigma }} \right)}^2}}}}$$

Hint, the sympy symbol for infinity is `oo`

```python
x,s,u=sym.symbols('x,s,u')
sym.integrate((1/(s*sym.sqrt(2*sym.pi)))*sym.E**(-0.5*((x-u)/s)**2), (x, -sym.oo, sym.oo ))
```

$\displaystyle \begin{cases} 0.353553390593274 \sqrt{2} \left(2 - \operatorname{erfc}{\left(\frac{0.707106781186548 u}{s} \right)}\right) + 0.353553390593274 \sqrt{2} \operatorname{erfc}{\left(\frac{0.707106781186548 u}{s} \right)} & \text{for}\: \left(\left(2 \left|{\arg{\left(s \right)}}\right| \leq \frac{\pi}{2} \wedge \left|{4 \arg{\left(s \right)} - 2 \arg{\left(u \right)}}\right| < \pi\right) \vee \left(\left|{4 \arg{\left(s \right)} - 2 \arg{\left(u \right)}}\right| \leq \pi \wedge 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \vee \left(\left|{4 \arg{\left(s \right)} - 2 \arg{\left(u \right)}}\right| < \pi \wedge 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \vee 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \wedge \left(\left(2 \left|{\arg{\left(s \right)}}\right| \leq \frac{\pi}{2} \wedge \left|{- 4 \arg{\left(s \right)} + 2 \arg{\left(u \right)} + 2 \pi}\right| < \pi\right) \vee \left(\left|{- 4 \arg{\left(s \right)} + 2 \arg{\left(u \right)} + 2 \pi}\right| \leq \pi \wedge 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \vee \left(\left|{- 4 \arg{\left(s \right)} + 2 \arg{\left(u \right)} + 2 \pi}\right| < \pi \wedge 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \vee 2 \left|{\arg{\left(s \right)}}\right| < \frac{\pi}{2}\right) \\\int\limits_{-\infty}^{\infty} \frac{\sqrt{2} e^{- \frac{0.5 \left(- u + x\right)^{2}}{s^{2}}}}{2 \sqrt{\pi} s}\, dx & \text{otherwise} \end{cases}$

Lookup Gaussian functions: https://en.wikipedia.org/wiki/Gaussian_function
Does your answer maake sense?

## 4. Plotting with Sympy

Finally Sympy can be used to plot functions. Note that this makes use of [matplotlib](http://matplotlib.org/).

Let us plot $x^2$:

```python
expr = x ** 2
p = sym.plot(expr)
```

### Exercise 4.1 Plot the following function:

1. $y=x + cos(x)$
1. ${\frac{1}{{ \sqrt {2\pi } }}{e^{ - \frac{x^2}{2}}}}$

```python
expr1 = x+sym.cos(x)
p = sym.plot(expr1)
```

```python
expr2 = (1/(sym.sqrt(2*sym.pi))) * sym.E ** (-x**2/2)
p = sym.plot(expr2)
```

# Lecture

## L1. Hydrogen Atom

Sympy has built in modules for the eigenfunctions of the hydrogen atom.

```python
import sympy.physics.hydrogen
import numpy as np
```

You can caluclate the eigenvalues ($E$) in Hartrees

`sym.physics.hydrogen.E_nl(n,Z)`

```python
sym.physics.hydrogen.E_nl(1,1)
```

We can use a loop to print out many energies

```python
for n in range(1,5):
    print(sym.physics.hydrogen.E_nl(n,1))
```

    -1/2
    -1/8
    -1/18
    -1/32

We can plot the hydrogen radial wavefunction (1s orbital)

```python
r = sympy.symbols('r')
sympy.physics.hydrogen.R_nl(1, 0, r, 1)
```

```python
sym.plot(sympy.physics.hydrogen.R_nl(1, 0, r, 1),(r,0,10.50))
```

And the probablity distribution function

```python
sympy.symbols('r')
prob_1s=sympy.physics.hydrogen.R_nl(1, 0, r, 1)*sympy.physics.hydrogen.R_nl(1, 0, r, 1)
prob_1s
```

```python
sym.plot(prob_1s,(r,0,10))
```

Plot a 2s orbital

```python
sympy.symbols('r')
prob_2s=sympy.physics.hydrogen.R_nl(2, 0, r, 1)*sympy.physics.hydrogen.R_nl(2, 0, r, 1)
prob_2s
```

```python
sym.plot(prob_2s,(r,0,10))
```

We can change the range to see the node better.

```python
sym.plot(prob_2s,(r,1,8))
```

Notice the node!

### Exercise L1.1

Plot the radial distriubution function for a 2p, 3s, 4s, and 3d orbital.

```python
# 2p orbital
r=sympy.symbols('r')
sympy.physics.hydrogen.R_nl(2, 1, r, 1)

# 2p radial distribution
sym.plot(sympy.physics.hydrogen.R_nl(2, 1, r, 1),(r,0,20))
```

```python
# 2p probability distribution
sympy.symbols('r')
prob_2p=sympy.physics.hydrogen.R_nl(2, 1, r, 1)*sympy.physics.hydrogen.R_nl(2, 1, r, 1)
prob_2p
sym.plot(prob_2p, (r, 0,12))
```

```python
#3s orbital
r=sympy.symbols('r')
sympy.physics.hydrogen.R_nl(3, 0, r, 1)

# 3s radial distribution
sym.plot(sympy.physics.hydrogen.R_nl(3, 0, r, 1),(r,0,25))
```

```python
# 3s probability distribution
sympy.symbols('r')
prob_3s=sympy.physics.hydrogen.R_nl(3, 0, r, 1)*sympy.physics.hydrogen.R_nl(3, 0, r, 1)
prob_3s
sym.plot(prob_3s, (r, 1,19))
```

```python
# 4s orbital
r=sympy.symbols('r')
sympy.physics.hydrogen.R_nl(4, 0, r, 1)

# 4s radial distribution
sym.plot(sympy.physics.hydrogen.R_nl(4, 0, r, 1),(r,0,35))
```

```python
# 4s probability distribution
sympy.symbols('r')
prob_4s=sympy.physics.hydrogen.R_nl(4, 0, r, 1)*sympy.physics.hydrogen.R_nl(4, 0, r, 1)
prob_4s
sym.plot(prob_4s, (r, 1,16))
```

```python
# 3d orbital
r=sympy.symbols('r')
sympy.physics.hydrogen.R_nl(3, 2, r, 1)

# 3d radial distribution
sym.plot(sympy.physics.hydrogen.R_nl(3, 2, r, 1),(r,0,35))
```

```python
# 3d probability distribution
sympy.symbols('r')
prob_3d=sympy.physics.hydrogen.R_nl(3, 2, r, 1)*sympy.physics.hydrogen.R_nl(3, 2, r, 1)
prob_3d
sym.plot(prob_3d, (r, 0,23))
```

```python

```


# Semi-Monocoque Theory: corrective solutions

```python
from pint import UnitRegistry
import sympy
import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import sys
%matplotlib inline
from IPython.display import display
```

Import **Section** class, which contains all calculations

```python
from Section import Section
```

Initialization of **sympy** symbolic tool and **pint** for dimension analysis (not really implemented rn as not directly compatible with sympy)

```python
ureg = UnitRegistry()
sympy.init_printing()
```

Define **sympy** parameters used for geometric description of sections

```python
A, A0, t, t0, a, b, h, L, E, G = sympy.symbols('A A_0 t t_0 a b h L E G', positive=True)
```

We also define numerical values for each **symbol** in order to plot scaled section and perform calculations

```python
values = [(A, 150 * ureg.millimeter**2),(A0, 250  * ureg.millimeter**2),(a, 80 * ureg.millimeter), \
          (b, 20 * ureg.millimeter),(h, 35 * ureg.millimeter),(L, 2000 * ureg.millimeter), \
          (t, 0.8 *ureg.millimeter),(E, 72e3 * ureg.MPa), (G, 27e3 * ureg.MPa)]
datav = [(v[0],v[1].magnitude) for v in values]
```

# Second example: Rectangular section with 6 nodes and 2 loops

Define graph describing the section:

1) **stringers** are **nodes** with parameters:
- **x** coordinate
- **y** coordinate
- **Area**

2) **panels** are **oriented edges** with parameters:
- **thickness**
- **lenght** which is automatically calculated

```python
stringers = {1:[(2*a,h),A],
             2:[(a,h),A],
             3:[(sympy.Integer(0),h),A],
             4:[(sympy.Integer(0),sympy.Integer(0)),A],
             5:[(a,sympy.Integer(0)),A],
             6:[(2*a,sympy.Integer(0)),A]}

panels = {(1,2):t,
          (2,3):t,
          (3,4):t,
          (4,5):t,
          (5,6):t,
          (6,1):t,
          (5,2):t}
```

Define section and perform first calculations

```python
S1 = Section(stringers, panels)
```

```python
S1.cycles
```

## Plot of **S1** section in original reference frame

Define a dictionary of coordinates used by **Networkx** to plot section as a Directed graph.
Note that arrows are actually just thicker stubs

```python
start_pos={ii: [float(S1.g.node[ii]['ip'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }
```

```python
plt.figure(figsize=(12,8),dpi=300)
nx.draw(S1.g,with_labels=True, arrows= True, pos=start_pos)
plt.arrow(0,0,20,0)
plt.arrow(0,0,0,20)
#plt.text(0,0, 'CG', fontsize=24)
plt.axis('equal')
plt.title("Section in starting reference Frame",fontsize=16);
```

## Plot of **S1** section in inertial reference Frame

Section is plotted wrt **center of gravity** and rotated (if necessary) so that *x* and *y* are principal axes.
**Center of Gravity** and **Shear Center** are drawn

```python
positions={ii: [float(S1.g.node[ii]['pos'][i].subs(datav)) for i in range(2)] for ii in S1.g.nodes() }
```

```python
x_ct, y_ct = S1.ct.subs(datav)

plt.figure(figsize=(12,8),dpi=300)
nx.draw(S1.g,with_labels=True, pos=positions)
plt.plot([0],[0],'o',ms=12,label='CG')
plt.plot([x_ct],[y_ct],'^',ms=12, label='SC')
#plt.text(0,0, 'CG', fontsize=24)
#plt.text(x_ct,y_ct, 'SC', fontsize=24)
plt.legend(loc='lower right', shadow=True)
plt.axis('equal')
plt.title("Section in pricipal reference Frame",fontsize=16);
```

Expression of **inertial properties** in *principal reference frame*

```python
sympy.simplify(S1.Ixx), sympy.simplify(S1.Iyy), sympy.simplify(S1.Ixy), sympy.simplify(S1.θ)
```

```python
S1.symmetry
```

    [{'edges': [((1, 2), (2, 3)), ((3, 4), (6, 1)), ((4, 5), (5, 6)), (5, 2)],
      'nodes': [(1, 3), (2, 2), (4, 6), (5, 5)]},
     {'edges': [((1, 2), (5, 6)), ((2, 3), (4, 5)), (3, 4), (5, 2), (6, 1)],
      'nodes': [(1, 6), (2, 5), (3, 4)]}]

Compute **L** matrix: with 6 nodes we expect 3 **dofs**, two with _symmetric load_ and one with _antisymmetric load_

```python
S1.compute_L()
```

```python
S1.L
```

Compute **H** matrix

```python
S1.compute_H()
```

```python
S1.H.subs(datav)
```

Compute $\tilde{K}$ and $\tilde{M}$

```python
S1.compute_KM(A,h,t)
```

```python
S1.Ktilde
```

```python
S1.Mtilde.subs(datav)
```

Compute **eigenvalues** and **eigenvectors**: results are in the form:
- eigenvalue
- multiplicity
- eigenvector

```python
sol_data = (S1.Ktilde.inv()*(S1.Mtilde.subs(datav))).eigenvects()
sol_data
```

Extract eigenvalues

```python
β2 = [sol[0] for sol in sol_data]
β2
```

Extract and normalize eigenvectors

```python
X = [sol[2][0]/sol[2][0].norm() for sol in sol_data]
X
```

Compute numerical value of $\lambda$

```python
λ = [sympy.N(sympy.sqrt(E*A*h/(G*t)*βi).subs(datav)) for βi in β2]
λ
```

```python

```


# Value-at-Risk for Stocks: Historical Simulation

### Lecture Notes by Jakov Ivan S. Dumbrique (jdumbrique@ateneo.edu)

MATH 100.2: Topics in Financial Mathematics II \
First Semester, S.Y. 2021-2022 \
Ateneo de Manila University

```python
import numpy as np # Numerical Computing
import pandas as pd # Data wrangling
```

## Introduction to Historical Simulation

1. The primary basis of the Delta-Normal approach in the computation of the VaR is the assumption that asset price returns (or portfolio returns) are normally distributed.
2. Historical data can also be used to estimate VaR for stock portfolios without assuming a particular parametric distribution for the asset return series. This particular procedure is known as **historical simulation**.

Consider a financial institution with a position of $N$ shares on a stock $E$ with price $S_{0}$ today. Let $S_1$ be the price per share of $E_1$ tomorrow.

Let $R_1 = \ln(S_1/S_0)$ be the continuously compounded return on the asset observed tomorrow.
For sufficiently small $R_1$, we assume that $$\Delta P = P_1-P_0 = N(S_1-S_0) \approx N S_0 R_1.$$

In historical simulation, it is also assumed that $R_1$ is a random variable whose values consist of the one-day asset returns observed historically. However, unlike in Delta-Normal Approach, we don't assume $R_1$ to be normally distributed.

###  Step 1: Generate historical one-day returns $\{R_{1,j}\}$
Consider the time series $\{S_{-t}\}$, $t=0,1,2,\dots,M$, where $S_{-t}$ indicates the stock price $t$ trading days ago and $M+1$ is the length of the time series.

Define
\begin{equation}
R_{1,j} = \ln\left(\frac{S_{-j}}{S_{-(j+1)}}\right), j=0,1,\dots,M-1
\end{equation}
and so the series $\{R_{1,j}\}$ contains all possible values of the random variable $R_1$, with $R_{1,j}$ representing the $j$th scenario for $R_1$.

 Example on Single-Asset Portfolio

Today is February 23, 2018. You are a portfolio risk manager who is assigned to analyze the market risk of a portfolio of 700 PLDT (TEL) shares. Determine the portfolio's one-day 99% VaR using historical simulation approach.

```python
TEL_df = pd.read_csv("https://raw.githubusercontent.com/ateneomathdept/math100.2_2021Sem1/main/data/lectures/TEL_2018.csv")
TEL_df
```

      dt
      close

      0
      2/23/18
      1488.74

      1
      2/22/18
      1510.86

      2
      2/21/18
      1513.72

      3
      2/20/18
      1536.65

      4
      2/16/18
      1476.37

      ...
      ...
      ...

      243
      3/2/17
      1430.29

      244
      3/1/17
      1408.94

      245
      2/28/17
      1394.35

      246
      2/27/17
      1374.93

      247
      2/24/17
      1367.68

248 rows × 2 columns

```python
def get_return(df, d):
    """
    df is the original df

    appends returns series to df
    """
    df["previous"] = df["close"].shift(-d)
    df["return"] = np.log(df["close"]/df["previous"])
    return df
```

```python
TEL_df = get_return(TEL_df, d=1)
TEL_df
```

      dt
      close
      previous
      return

      0
      2/23/18
      1488.74
      1510.86
      -0.014749

      1
      2/22/18
      1510.86
      1513.72
      -0.001891

      2
      2/21/18
      1513.72
      1536.65
      -0.015035

      3
      2/20/18
      1536.65
      1476.37
      0.040018

      4
      2/16/18
      1476.37
      1475.71
      0.000447

      ...
      ...
      ...
      ...
      ...

      243
      3/2/17
      1430.29
      1408.94
      0.015040

      244
      3/1/17
      1408.94
      1394.35
      0.010409

      245
      2/28/17
      1394.35
      1374.93
      0.014026

      246
      2/27/17
      1374.93
      1367.68
      0.005287

      247
      2/24/17
      1367.68
      NaN
      NaN

248 rows × 4 columns

### Step 2: Get historical changes in portfolio values $\{\Delta P_j\}$
In scenario $j$, the stock price tomorrow is approximated as
\begin{equation}
S_{1,j} = S_0 e^{R_{1,j}}.
\end{equation}

Consequently, the change in portfolio value under scenario $j$ is given by the approximation
\begin{equation}
\Delta P_j = N (S_{1,j}-S_0) \approx NS_0 R_{1,j}.
\end{equation}

Like the random variable $R_1$, $\Delta P$ can be represented as a random variable with $M$ possible scenarios denoted by $\{\Delta P_j\}$.

```python
def get_change_in_value_df(df, N):
    """
    df is the output of get_returns_df

    appends change in portfolio value series to df
    """
    S0 = df.loc[0, "close"]
    df["change_in_value"] = N * S0 * df["return"]
    return df
```

```python
TEL_df = get_change_in_value_df(TEL_df, N=700)
TEL_df
```

      dt
      close
      previous
      return
      change_in_value

      0
      2/23/18
      1488.74
      1510.86
      -0.014749
      -15370.094698

      1
      2/22/18
      1510.86
      1513.72
      -0.001891
      -1970.824622

      2
      2/21/18
      1513.72
      1536.65
      -0.015035
      -15667.749059

      3
      2/20/18
      1536.65
      1476.37
      0.040018
      41703.842890

      4
      2/16/18
      1476.37
      1475.71
      0.000447
      465.975103

      ...
      ...
      ...
      ...
      ...
      ...

      243
      3/2/17
      1430.29
      1408.94
      0.015040
      15673.009003

      244
      3/1/17
      1408.94
      1394.35
      0.010409
      10847.710303

      245
      2/28/17
      1394.35
      1374.93
      0.014026
      14616.263663

      246
      2/27/17
      1374.93
      1367.68
      0.005287
      5509.622658

      247
      2/24/17
      1367.68
      NaN
      NaN
      NaN

248 rows × 5 columns

### Step 3: Get the (1-alpha)th percentile of the ordered array of historical changes in portfolio values

The one-day 99\% VaR of the portfolio thus corresponds to the scenario $j^*$, given by $\Delta P_{j^*}$, in the 1st percentile of the scenario space $\{\Delta P_j\}$.

$\Delta P_{j^*}$ represents the worst possible movement in portfolio value with probability 99\%.

If the $\Delta P_j$s are arranged in ascending order, the one-day 99\% VaR for the portfolio is the $\lfloor 0.01M \rfloor$th smallest value in the array.

```python
M = len(TEL_df)-1
M
```

    247

```python
0.01*M
```

    2.47

```python
k = int(np.floor(0.01*M))
k
```

    2

```python
TEL_df["change_in_value"]
```

    0     -15370.094698
    1      -1970.824622
    2     -15667.749059
    3      41703.842890
    4        465.975103
               ...
    243    15673.009003
    244    10847.710303
    245    14616.263663
    246     5509.622658
    247             NaN
    Name: change_in_value, Length: 248, dtype: float64

```python
var = abs(TEL_df["change_in_value"].sort_values(ignore_index=True)[k-1])
var
```

    60730.66451735293

```python
def get_kth_percentile_discrete(df, d, alpha):
    """
    this returns the (1-alpha)th percentile of the ordered array of historical changes in portfolio values
    """
    M = len(df)-d
    k = int(np.floor((1-alpha)*M))
    var = abs(df["change_in_value"].sort_values(ignore_index=True)[k-1])

    return var
```

```python
get_kth_percentile_discrete(TEL_df, d=1, alpha=0.99)
```

    60730.66451735293

```python
def d_day_alpha_percent_VaR_single_stock_historical(
    df, N, d, alpha
):
    """Returns the d-day 100(alpha)% VaR of a single stock using Historical Simulation Approach.

    Parameters
    ----------
    df : pandas.DataFrame
        has two columns: (1) dt [str] and (2) closing price [float]
        assumes the dates are arranged from newest to oldest, and the date today is the date on the first row
    N : int
        number of shares for the sole stock
    d : int
        the value to be used in calculating the d-day VaR (e.g. 1-day, 5-day)
    alpha : float
        the value to be used in calculting the 100(alpha)% VaR (e.g. 0.99, 0.95)

    Returns
    -------
    float (2 decimal places)
        d-day 100(alpha)% VaR of a single stock using Historical Simulation Approach
    """

    # step 1: generate your historical returns
    df = get_return(df, d)
    # Step 2: get your historical changes in portfolio values
    df = get_change_in_value_df(df, N)
    # Step 3: get the (1-p/100)th percentile of the ordered array of historical changes in portfolio values
    var = get_kth_percentile_discrete(df, d, alpha)

    return round(var, 2)
```

```python
TEL_df = pd.read_csv("https://raw.githubusercontent.com/ateneomathdept/math100.2_2021Sem1/main/data/lectures/TEL_2018.csv")
TEL_df
```

      dt
      close

      0
      2/23/18
      1488.74

      1
      2/22/18
      1510.86

      2
      2/21/18
      1513.72

      3
      2/20/18
      1536.65

      4
      2/16/18
      1476.37

      ...
      ...
      ...

      243
      3/2/17
      1430.29

      244
      3/1/17
      1408.94

      245
      2/28/17
      1394.35

      246
      2/27/17
      1374.93

      247
      2/24/17
      1367.68

248 rows × 2 columns

```python
d_day_alpha_percent_VaR_single_stock_historical(df=TEL_df, N=700, d=1, alpha=0.99)
```

    60730.66

 Exercise on N-Asset Portfolio

Today is February 23, 2018. You are a portfolio risk manager who is assigned to analyze the market risk of a portfolio of 700 PLDT (TEL) shares, 300 Ayala Corporation (AC) shares, and 500 URC shares. What is the portfolio's one-day 99% VaR using historical approach?

```python

```


# Writing our first climate model

In class, we discussed Earth's global radiation budget, and we plotted the top-of-atmosphere radiative fluxes.  Now we will use our knowledge of energy balance to write a simple climate model!

The model we are going to create will tell us how much global mean temperature should change for a given change in climate parameters.

First, let's look again at the plot of energy balance we've been studying.  Double-click on the image to see how it was added to the Jupyter notebook as well--this will help you on Assignment 2.

## 1. Finding parameters that fit observations

In class we discussed the Stefan-Boltzmann law of blackbody radiation, and we related the outgoing longwave radiation at the top of the atmosphere to Earth's theoretical surface temperature.  We found that blackbody radiation was not a very good fit to the observed temperature due to the influence of our greenhouse atmosphere.

To account for the atmosphere, we introduced the  **transmissivity**  of the atmosphere, $\tau$, a number less than 1 that represents the greenhouse effect of Earth's atmosphere.

With the transmissivity included, the **OLR** or Outgoing Longwave Radiation to space is:

$$ \text{OLR} = \tau \sigma T_s^4 $$

where $\sigma$ is the Stefan-Boltzmann constant and $T_s$ is the surface temperature.

**Exercise: Find a value for $\tau$ that fits the observations of $OLR$ and $T_s$.**

```python
## your python code here
```

From the plot above, the area-averaged incoming solar radiation or **insolation** is 341.3 W m$^{-2}$.

Let's denote this quantity by $Q$.

```python
Q = 341.3  # the insolation
```

#### Planetary albedo

Some of the incoming radiation is not absorbed at all but simply reflected back to space. Let's call this quantity $F_{reflected}$

From observations we have:

```python
Freflected = 101.9  #  reflected shortwave flux in W/m2
```

The **planetary albedo** is the fraction of $Q$ that is reflected.

We will denote the planetary albedo by $\alpha$.

Then we can compute...

```python
## compute alpha and fill in below statement
```

This means that ....% of solar radiation is reflected back to space.

## 2. Absorbed Shortwave Radiation

The **Absorbed Shortwave Radiation** or ASR is the part of the incoming sunlight that is *not* reflected back to space, i.e. that part that is absorbed somewhere within the Earth system.

Mathematically we write

$$ \text{ASR} = Q - F_{reflected} = (1-\alpha) Q $$

**Exercise: define a new variable (not a function) called ASR_obs.  Compute ASR from the variables you have computed above.**

```python
## your code here
```

What does this value tell you about Earth's global energy balance?  Use what we discussed in class and the information above.

(Your interpretation here)

## 3. Equilibrium temperature

*This is one of the central concepts in climate modeling.*

The Earth system is in **energy balance** when energy in = energy out, i.e. when

$$ \text{ASR} = \text{OLR} $$

Questions we'd like to answer include

- What surface temperature do we need to have this balance?
- By how much would the temperature change in response to other changes in Earth system?
    - Changes in greenhouse gases
    - Changes in cloudiness
    - etc.

The equations above describe a simple climate model.  We can use this model to get an *exact solution* for the **equilibrium temperature**.

**Exercise: Write out the statement of energy balance, replacing ASR and OLR with their formulas we discussed above.**

*(You can write the statement here if you know LaTeX, or you can write it in your notebook)*

**Now: rearrange the statement to solve for the surface temperature, $T_s$.**

*(What expression do you find for $T_s$? You can write it here if you know LaTeX, or write it in your notebook.)*

To produce this expression, we assumed $ASR=OLR$.  Thus, $T_s$ is our equilibrium temperature required for energy balance, $T_{eq}$.  If the Earth had exactly this surface temperature, it would be in radiative balance with the Sun.

**Python implementation: write a reusable function that will compute the equilibrium temperature $T_{eq}$ for any values of albedo, incoming solar flux, and transmissivity.**

```python
## your reusable function here
```

Let's make your function a little bit easier to use.  Add to your function definition so that it has *default values* for each of the parameters.  [Here is a tutorial on default values.](https://www.pythontutorial.net/python-basics/python-default-parameters/)

Choose appropriate default values and assign them below.

```python
## version of your function with default values here
```

Finally, compute the equilibrium temperature with the observed values of each parameter.

```python
## your call to your function
```

How does this compare with the observed global temperature?

*(Your response here)*

## 4. A climate change scenario

Suppose that, due to global warming (changes in atmospheric composition and subsequent changes in cloudiness):

- The longwave transmissitivity decreases to $\tau = 0.57$
- The planetary albedo increases to $\alpha = 0.32$

What is the ***new equilibrium temperature***?

```python
Teq_new = ... ## your computation here
#  we'll show an example of formatted print output, limiting to two or one decimal places
print('The new equilibrium temperature is {:.2f} K.'.format(Teq_new))
print('The equilibrium temperature increased by about {:.1f} K.'.format(Teq_new-Teq_observed))
```

Most climate models are more complicated than this one, and solving directly for the equilibrium temperature will not be possible.

Instead, we will be able to use the model to calculate the terms in the energy budget (ASR and OLR). To prepare for that style of modelling...

**Python exercise:**
- Write reusable functions that will compute ASR and OLR for any values of albedo, transmissivity, solar flux, and temperature.
- Verify the following:
    - With the new parameter values but the old temperature $T = 288$ K, is ASR greater or lesser than OLR?
    - Is the Earth gaining or losing energy?
    - How does your answer change if $T = 295$ K (or any other temperature greater than 291 K)?

```python
## your code here
```

## 5. Simulating changes over time

The above exercise shows us that if some properties of the climate system change in such a way that the **equilibrium temperature goes up**, then the Earth system *receives more energy from the sun than it is losing to space*. The system is **no longer in energy balance**.

The temperature must then increase to get back into balance. The increase will not happen all at once! It will take time for energy to accumulate in the climate system. We want to model this **time-dependent adjustment** of the system.

In fact almost all climate models are **time-dependent**, meaning the model calculates **time derivatives** (rates of change) of climate variables.

### An energy balance **equation**

If the Earth system is no longer in energy balance, then there must be some net change in energy within the system over time.  We will write the **total energy budget** of the Earth system as

$$
\begin{align}
\frac{dE}{dt} &= \text{net energy flux in to system} \\
 &= \text{flux in – flux out} \\
 &= \text{ASR} - \text{OLR}
\end{align}
$$

where $E$ is the **enthalpy** or **heat content** of the total system.

We will express the budget **per unit surface area**, so each term above has units W m$^{-2}$

Note: any internal exchanges of energy between different reservoirs (e.g. between ocean, land, ice, atmosphere) do not appear in this budget – because $E$ is the sum of all reservoirs.

Also note: **This is a generically true statement.** We have just defined some terms, and made the (very good) assumption that the only significant energy sources are radiative exchanges with space.

**This equation is the starting point for _every climate model_.**

But so far, we don’t actually have a MODEL, something that will show us changes in the system over time. We just have a statement of a budget. To use this budget to make a model, we need to relate terms in the budget to state variables of the atmosphere-ocean system.

For now, the state variable we are most interested in is **temperature** – because it is directly connected to the physics of each term above.

### An energy balance **model**

If we now suppose that

$$ E = C T_s $$

where $E$ is the total heat content as above, $T_s$ is the global mean surface temperature, and $C$ is a constant – the **effective heat capacity** of the atmosphere- ocean column.

then we can rewrite our energy budget equation as...

*(Write down the equation here if you know LaTeX, or write it in your notebook.)*

For our purposes here we are going to use a value of C equivalent to heating 100 meters of water:

$$C = c_w \rho_w H$$

where

$c_w = 4 \times 10^3$ J kg$^{-1}$ $^\circ$C$^{-1}$ is the specific heat of water,

$\rho_w = 10^3$ kg m$^{-3}$ is the density of water, and

$H$ is an effective depth of water that is heated or cooled.

```python
c_w = 4E3  #  Specific heat of water in J/kg/K
rho_w = 1E3  #  Density of water in kg/m3
H = 100.   #  Depth of water in m
C = c_w * rho_w * H   #  Heat capacity of the model
print('The effective heat capacity is {:.1e} J/m2/K'.format(C))
```

### Solving the energy balance model

The version of the energy budget equation you rewrote above is a first-order Ordinary Differential Equation (ODE) for $T_s$ as a function of time. It is also **our very first climate model!**

To solve it (i.e. see how $T_s$ evolves from some specified initial condition) we have two choices:

1. Solve it analytically
2. Solve it numerically

Option 1 (analytical) will usually not be possible because the equations will typically be too complex and non-linear. This is why computers are our best friends in the world of climate modeling.

HOWEVER it is often useful and instructive to simplify a model down to something that is analytically solvable when possible. Why? Two reasons:

1. Analysis will often yield a deeper understanding of the behavior of the system
2. Gives us a benchmark against which to test the results of our numerical solutions.

## Sidebar: representing time derivatives on the computer

Recall that the derivative is the **instantaneous rate of change**. It is defined as

$$ \frac{dT}{dt} = \lim_{\Delta t\rightarrow 0} \frac{\Delta T}{\Delta t}$$

- **On the computer there is no such thing as an instantaneous change.**
- We are always dealing with *discrete quantities*.
- So we approximate the derivative with $\Delta T/ \Delta t$.
- So long as we take the time interval $\Delta t$ "small enough", the approximation is valid and useful.
- (The meaning of "small enough" varies widely in practice. Let's not worry about it right now)

So we can write out your model from step 6 as

$$ C  \frac{\Delta T}{\Delta t} \approx \text{ASR} - \text{OLR}$$

where $\Delta T$ is the **change in temperature predicted by our model** over a short time interval $\Delta t$.

We can now use this to make a prediction:

Given a current temperature $T_1$ at time $t_1$, what is the temperature $T_2$ at a future time $t_2$?

We can write

$$ \Delta T = T_2-T_1 $$
$$ \Delta t = t_2-t_1 $$

and so our model says

$$ C  \frac{T_2-T_1}{\Delta t} = \text{ASR} - \text{OLR} $$

Which we can rearrange to **solve for the future temperature**:

$$ T_2 = T_1 + \frac{\Delta t}{C} \left( \text{ASR} - \text{OLR}(T_1) \right)  $$

We now have a formula with which to make our prediction!

Notice that we have written the OLR as a *function of temperature*. We will use the current temperature $T_1$ to compute the OLR, and use that OLR to determine the future temperature.

## 6. Computational solution of our Energy Balance Model

The quantity $\Delta t$ is called a **timestep**. It is the smallest time interval represented in our model.

Let's use a timestep of 1 year:

```python
dt = 60. * 60. * 24. * 365.   # one year expressed in seconds
```

### Try stepping forward one timestep

```python
# Try a single timestep, using your functions for ASR and OLR.  Input the correct parameter values: alpha=0.32, tau=0.57
T1 = 288.
T2 = T1 + dt / C * ( ASR(...) - OLR(T1...) ) ## edit here to call your functions
print(T2)
```

***Did you get a `NameError` here?***

The code above assumes that we have already defined functions `ASR()` and `OLR()`. If you named them something else in the exercise above, then the code won't work as written.  Try again, making sure to call correct function names to compute ASR and OLR.

**What happened when you stepped forward one year?  Why?**

*(Your answer here)*

**Exercise: step forward one more time step, using the T2 you computed above as your starting value.**

```python
T2 = ...
T3 = ...
print(T3)
```

But we don't want to type this out every time.  That's right: it's time to define another function.

**Exercise: define a function that will step forward one year, given an initial temperature $T_i$**

```python
def step_forward(Ti):
    ## work of the function
    return ... ## write what should be returned
```

The most effective way to write this function is to base it on what we've already done, calling other functions and variables we have already defined.

**Why do you think we defined default values of the albedo, solar flux, and transmissivity above?  How does that help us in writing step_forward?**

### Automate the timestepping with a loop

Now let's really harness the power of the computer by **making a loop** (and storing values in arrays):

```python
import numpy as np

numsteps = 20
Tsteps = np.zeros(numsteps+1)
Years = np.zeros(numsteps+1)
Tsteps[0] = 288.
for n in range(numsteps):
    Years[n+1] = n+1
    Tsteps[n+1] = step_forward( Tsteps[n] )
print(Tsteps)
```

What did we just do?

- Created an array of zeros
- set the initial temperature to 288 K
- repeated our time step 20 times.
- Stored the results of each time step into the array.

#### Python fact: the `for` statement executes a statement (or series of statements) a specified number of times (a loop!)

## 7. Make a plot

Let's present our results in a more visually interpretable way, using matplotlib to create a plot.

We can easily make simple graphs with the function `plt.plot(x,y)`, where `x` and `y` are arrays of the same size. But we must import it first.

This uses a graphics library called [matplotlib](https://matplotlib.org). This is the workhorse of scientific plotting in Python, and we will be using it all the time!

When we plan on plotting, our notebooks will usually start with this:
```
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
```
...unless we are going to use xarray plotting only.

```python
# a special instruction for the Jupyter notebook
#   Display all plots inline in the notebook
%matplotlib inline
#  import the plotting package
import matplotlib.pyplot as plt
```

```python
plt.plot(Years, Tsteps)
plt.xlabel('Years')
plt.ylabel('Global mean temperature (K)');
```

**Exercise: Use the matplotlib documentation, or other online resources, to change something about your plot.  Maybe you want to use a different color line, or different line style, or line width?**

```python
## Your revised version of the plot here
```

**Finally: Describe what happens in your simulation over time.**

*(Your answer here)*

This lab draws heavily from Climlab resources by Brian Rose (not linked at top to avoid ruining the surprise!)

```python

```


# Learning from data: Neural networks, from the simple perceptron to deep learning

**Christian Forssén**, Department of Physics, Chalmers University of Technology, Sweden

 **Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: **Oct 15, 2019**

Copyright 2018-2019, Christian Forssén. Released under CC Attribution-NonCommercial 4.0 license

# Neural networks

Artificial neural networks are computational systems that can learn to
perform tasks by considering examples, generally without being
programmed with any task-specific rules. It is supposed to mimic a
biological system, wherein neurons interact by sending signals in the
form of mathematical functions between layers. All layers can contain
an arbitrary number of neurons, and each connection is represented by
a weight variable.

## Terminology

Each time we describe a neural network algorithm we will typically specify three things.

Architecture:
  :
  The architecture specifies what variables are involved in the network and their topological relationships – for example, the variables involved in a neural net might be the weights of the connections between the neurons, along with the activities of the neurons.

Activity rule:
  :
  Most neural network models have short time-scale dynamics: local rules define how the activities of the neurons change in response to each other. Typically the activity rule depends on the weights (the parameters) in the network.

Learning rule:
  :
  The learning rule specifies the way in which the neural network’s weights change with time. This learning is usually viewed as taking place on a longer time scale than the time scale of the dynamics under the activity rule. Usually the learning rule will depend on the activities of the neurons. It may also depend on the values of target values supplied by a teacher and on the current value of the weights.

## Artificial neurons

The field of artificial neural networks has a long history of
development, and is closely connected with the advancement of computer
science and computers in general. A model of artificial neurons was
first developed by McCulloch and Pitts in 1943 to study signal
processing in the brain and has later been refined by others. The
general idea is to mimic neural networks in the human brain, which is
composed of billions of neurons that communicate with each other by
sending electrical signals.  Each neuron accumulates its incoming
signals, which must exceed an activation threshold to yield an
output. If the threshold is not overcome, the neuron remains inactive,
i.e. has zero output.

This behaviour has inspired a simple mathematical model for an artificial neuron.

$$
\begin{equation}
 y = f\left(\sum_{i=1}^n w_jx_j + b \right) = f(z),
\label{artificialNeuron} \tag{1}
\end{equation}
$$

where the bias $b$ is sometimes denoted $w_0$.
Here, the output $y$ of the neuron is the value of its activation function, which have as input
a weighted sum of signals $x_1, \dots ,x_n$ received by $n$ other neurons.

Conceptually, it is helpful to divide neural networks into four
categories:
1. general purpose neural networks, including deep neural networks (DNN) with several hidden layers, for supervised learning,

2. neural networks designed specifically for image processing, the most prominent example of this class being Convolutional Neural Networks (CNNs),

3. neural networks for sequential data such as Recurrent Neural Networks (RNNs), and

4. neural networks for unsupervised learning such as Deep Boltzmann Machines.

In natural science, DNNs and CNNs have already found numerous
applications. In statistical physics, they have been applied to detect
phase transitions in 2D Ising and Potts models, lattice gauge
theories, and different phases of polymers, or solving the
Navier-Stokes equation in weather forecasting.  Deep learning has also
found interesting applications in quantum physics. Various quantum
phase transitions can be detected and studied using DNNs and CNNs:
topological phases, and even non-equilibrium many-body
localization.

In quantum information theory, it has been shown that one can perform
gate decompositions with the help of neural networks.

The applications are not limited to the natural sciences. There is a
plethora of applications in essentially all disciplines, from the
humanities to life science and medicine.

## Neural network types

An artificial neural network (ANN), is a computational model that
consists of layers of connected neurons, or nodes or units.  We will
refer to these interchangeably as units or nodes, and sometimes as
neurons.

It is supposed to mimic a biological nervous system by letting each
neuron interact with other neurons by sending signals in the form of
mathematical functions between layers.  A wide variety of different
ANNs have been developed, but most of them consist of an input layer,
an output layer and eventual layers in-between, called *hidden
layers*. All layers can contain an arbitrary number of nodes, and each
connection between two nodes is associated with a weight variable.

Neural networks (also called neural nets) are neural-inspired
nonlinear models for supervised learning.  As we will see, neural nets
can be viewed as natural, more powerful extensions of supervised
learning methods such as linear and logistic regression and soft-max
methods we discussed earlier.

### Feed-forward neural networks

The feed-forward neural network (FFNN) was the first and simplest type
of ANNs that were devised. In this network, the information moves in
only one direction: forward through the layers.

Nodes are represented by circles, while the arrows display the
connections between the nodes, including the direction of information
flow. Additionally, each arrow corresponds to a weight variable
(figure to come).  We observe that each node in a layer is connected
to *all* nodes in the subsequent layer, making this a so-called
*fully-connected* FFNN.

### Convolutional Neural Network

A different variant of FFNNs are *convolutional neural networks*
(CNNs), which have a connectivity pattern inspired by the animal
visual cortex. Individual neurons in the visual cortex only respond to
stimuli from small sub-regions of the visual field, called a receptive
field. This makes the neurons well-suited to exploit the strong
spatially local correlation present in natural images. The response of
each neuron can be approximated mathematically as a convolution
operation.  (figure to come)

Convolutional neural networks emulate the behaviour of neurons in the
visual cortex by enforcing a *local* connectivity pattern between
nodes of adjacent layers: Each node in a convolutional layer is
connected only to a subset of the nodes in the previous layer, in
contrast to the fully-connected FFNN.  Often, CNNs consist of several
convolutional layers that learn local features of the input, with a
fully-connected layer at the end, which gathers all the local data and
produces the outputs. They have wide applications in image and video
recognition.

### Recurrent neural networks

So far we have only mentioned ANNs where information flows in one
direction: forward. *Recurrent neural networks* on the other hand,
have connections between nodes that form directed *cycles*. This
creates a form of internal memory which are able to capture
information on what has been calculated before; the output is
dependent on the previous computations. Recurrent NNs make use of
sequential information by performing the same task for every element
in a sequence, where each element depends on previous elements. An
example of such information is sentences, making recurrent NNs
especially well-suited for handwriting and speech recognition.

### Other types of networks

There are many other kinds of ANNs that have been developed. One type
that is specifically designed for interpolation in multidimensional
space is the radial basis function (RBF) network. RBFs are typically
made up of three layers: an input layer, a hidden layer with
non-linear radial symmetric activation functions and a linear output
layer (''linear'' here means that each node in the output layer has a
linear activation function). The layers are normally fully-connected
and there are no cycles, thus RBFs can be viewed as a type of
fully-connected FFNN. They are however usually treated as a separate
type of NN due the unusual activation functions.

## Multilayer perceptrons

The *multilayer perceptron* (MLP) is a very popular, and easy to implement approach, to deep learning. It consists of
1. a neural network with one or more layers of nodes between the input and the output nodes.

2. the multilayer network structure, or architecture, or topology, consists of an input layer, one or more hidden layers, and one output layer.

3. the input nodes pass values to the first hidden layer, its nodes pass the information on to the second and so on till we reach the output layer.

As a convention it is normal to call a network with one layer of input units, one layer of hidden units and one layer of output units as  a two-layer network. A network with two layers of hidden units is called a three-layer network etc.

The number of input nodes does not need to equal the number of output
nodes. This applies also to the hidden layers. Each layer may have its
own number of nodes and activation functions.

The hidden layers have their name from the fact that they are not
linked to observables and as we will see below when we define the
so-called activation $\boldsymbol{z}$, we can think of this as a basis
expansion of the original inputs $\boldsymbol{x}$.

### Why multilayer perceptrons?

According to the [universal approximation
theorem](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.441.7873&rep=rep1&type=pdf), a feed-forward
neural network with just a single hidden layer containing a finite
number of neurons can approximate a continuous multidimensional
function to arbitrary accuracy, assuming the activation function for
the hidden layer is a **non-constant, bounded and
monotonically-increasing continuous function**. The theorem thus
states that simple neural networks can represent a wide variety of
interesting functions when given appropriate parameters. It is the
multilayer feedforward architecture itself which gives neural networks
the potential of being universal approximators.

Note that the requirements on the activation function only applies to
the hidden layer, the output nodes are always assumed to be linear, so
as to not restrict the range of output values.

### Mathematical model

The output $y$ is produced via the activation function $f$

$$
y = f\left(\sum_{i=1}^n w_ix_i + b \right) = f(z),
$$

This function receives $x_i$ as inputs.
Here the activation $z=(\sum_{i=1}^n w_ix_i+b)$.
In an FFNN of such neurons, the *inputs* $x_i$ are the *outputs* of
the neurons in the preceding layer. Furthermore, an MLP is
fully-connected, which means that each neuron receives a weighted sum
of the outputs of *all* neurons in the previous layer.

First, for each node $j$ in the first hidden layer, we calculate a weighted sum $z_j^1$ of the input coordinates $x_i$,

$$
\begin{equation} z_j^1 = \sum_{i=1}^{n} w_{ji}^1 x_i + b_j^1
\label{_auto1} \tag{2}
\end{equation}
$$

Here $b_j^1$ is the so-called bias which is normally needed in
case of zero activation weights or inputs. How to fix the biases and
the weights will be discussed below.  The value of $z_j^1$ is the
argument to the activation function $f$ of each node $j$, The
variable $n$ stands for all possible inputs to a given node $j$ in the
first layer.  We define  the output $y_j^1$ of all neurons in layer 1 as

$$
\begin{equation}
 y_j^1 = f(z_j^1) = f\left(\sum_{i=1}^n w_{ji}^1 x_i  + b_j^1\right),
\label{outputLayer1} \tag{3}
\end{equation}
$$

where we assume that all nodes in the same layer have identical
activation functions, hence the notation $f$. In general, we could assume in the more general case that different layers have different activation functions.
In this case we would identify these functions with a superscript $l$ for the $l$-th layer,

$$
\begin{equation}
 y_i^l = f^l(z_i^l) = f^l\left(\sum_{j=1}^{N_{l-1}} w_{ij}^l y_j^{l-1} + b_i^l\right),
\label{generalLayer} \tag{4}
\end{equation}
$$

where $N_{l-1}$ is the number of nodes in layer $l-1$. When the output of
all the nodes in the first hidden layer are computed, the values of
the subsequent layer can be calculated and so forth until the output
is obtained.

The output of neuron $i$ in layer 2 is thus,

$$
\begin{equation}
 y_i^2 = f^2\left(\sum_{j=1}^N w_{ij}^2 y_j^1 + b_i^2\right)
\label{_auto2} \tag{5}
\end{equation}
$$

$$
\begin{equation}
 = f^2\left[\sum_{j=1}^N w_{ij}^2f^1\left(\sum_{k=1}^M w_{jk}^1 x_k + b_j^1\right) + b_i^2\right]
\label{outputLayer2} \tag{6}
\end{equation}
$$

where we have substituted $y_k^1$ with the inputs $x_k$. Finally, the ANN output reads

$$
\begin{equation}
 y_i^3 = f^3\left(\sum_{j=1}^N w_{ij}^3 y_j^2 + b_i^3\right)
\label{_auto3} \tag{7}
\end{equation}
$$

$$
\begin{equation}
 = f^3\left[\sum_{j} w_{ij}^3 f^2\left(\sum_{k} w_{jk}^2 f^1\left(\sum_{m} w_{km}^1 x_m + b_k^1\right) + b_j^2\right)
  + b_1^3\right]
\label{_auto4} \tag{8}
\end{equation}
$$

We can generalize this expression to an MLP with $L$ hidden
layers. The complete functional form is,

$$
\begin{equation}
y^{L+1}_i = f^{L+1}\left[\!\sum_{j=1}^{N_L} w_{ij}^L f^L \left(\sum_{k=1}^{N_{L-1}}w_{jk}^{L-1}\left(\dots f^1\left(\sum_{n=1}^{N_0} w_{mn}^1 x_n+ b_m^1\right)\dots\right)+b_k^{L-1}\right)+b_1^L\right]
\label{completeNN} \tag{9}
\end{equation}
$$

which illustrates a basic property of MLPs: The only independent
variables are the input values $x_n$.

This confirms that an MLP, despite its quite convoluted mathematical
form, is nothing more than an analytic function, specifically a
mapping of real-valued vectors $\boldsymbol{x} \in \mathbb{R}^n \rightarrow
\boldsymbol{y} \in \mathbb{R}^m$.

Furthermore, the flexibility and universality of an MLP can be
illustrated by realizing that the expression is essentially a nested
sum of scaled activation functions of the form

$$
\begin{equation}
 f(x) = c_1 f(c_2 x + c_3) + c_4,
\label{_auto5} \tag{10}
\end{equation}
$$

where the parameters $c_i$ are weights and biases. By adjusting these
parameters, the activation functions can be shifted up and down or
left and right, change slope or be rescaled which is the key to the
flexibility of a neural network.

### Matrix-vector notation

We can introduce a more convenient notation for the activations in an ANN.

Additionally, we can represent the biases and activations
as layer-wise column vectors $\boldsymbol{b}_l$ and $\boldsymbol{y}_l$, so that the $i$-th element of each vector
is the bias $b_i^l$ and activation $y_i^l$ of node $i$ in layer $l$ respectively.

We have that $\boldsymbol{W}_l$ is an $N_{l-1} \times N_l$ matrix, while $\boldsymbol{b}_l$ and $\boldsymbol{y}_l$ are $N_l \times 1$ column vectors.
With this notation, the sum becomes a matrix-vector multiplication, and we can write
the equation for the activations of hidden layer 2 (assuming three nodes for simplicity) as

$$
\begin{equation}
 \boldsymbol{y}_2 = f_2(\boldsymbol{W}_2 \boldsymbol{y}_{1} + \boldsymbol{b}_{2}) =
 f_2\left(\left[\begin{array}{ccc}
    w^2_{11} &w^2_{12} &w^2_{13} \\
    w^2_{21} &w^2_{22} &w^2_{23} \\
    w^2_{31} &w^2_{32} &w^2_{33} \\
    \end{array} \right] \cdot
    \left[\begin{array}{c}
           y^1_1 \\
           y^1_2 \\
           y^1_3 \\
          \end{array}\right] +
    \left[\begin{array}{c}
           b^2_1 \\
           b^2_2 \\
           b^2_3 \\
          \end{array}\right]\right).
\label{_auto6} \tag{11}
\end{equation}
$$

### Matrix-vector notation  and activation

The activation of node $i$ in layer 2 is

$$
\begin{equation}
 y^2_i = f_2\Bigr(w^2_{i1}y^1_1 + w^2_{i2}y^1_2 + w^2_{i3}y^1_3 + b^2_i\Bigr) =
 f_2\left(\sum_{j=1}^3 w^2_{ij} y_j^1 + b^2_i\right).
\label{_auto7} \tag{12}
\end{equation}
$$

This is not just a convenient and compact notation, but also a useful
and intuitive way to think about MLPs: The output is calculated by a
series of matrix-vector multiplications and vector additions that are
used as input to the activation functions. For each operation
$\mathrm{W}_l \boldsymbol{y}_{l-1}$ we move forward one layer.

### Activation functions

A property that characterizes a neural network, other than its
connectivity, is the choice of activation function(s).  The following restrictions are imposed on an activation function for a FFNN to fulfill the universal approximation theorem

  * Non-constant

  * Bounded

  * Monotonically-increasing

  * Continuous

**Logistic and Hyperbolic activation functions**
The second requirement excludes all linear functions. Furthermore, in
a MLP with only linear activation functions, each layer simply
performs a linear transformation of its inputs.

Regardless of the number of layers, the output of the NN will be
nothing but a linear function of the inputs. Thus we need to introduce
some kind of non-linearity to the NN to be able to fit non-linear
functions Typical examples are the logistic *Sigmoid*

$$
f_\mathrm{sigmoid}(z) = \frac{1}{1 + e^{-z}},
$$

and the *hyperbolic tangent* function

$$
f_\mathrm{tanh}(z) = \tanh(z)
$$

**Rectifier activation functions**
The Rectifier Linear Unit (ReLU) uses the following activation function

$$
f_\mathrm{ReLU}(z) = \max(0,z).
$$

To solve a problem of dying ReLU neurons, practitioners often use a  variant of the ReLU
function, such as the leaky ReLU or the so-called
exponential linear unit (ELU) function

$$
f_\mathrm{ELU}(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\  z & z \ge 0.\end{array}\right.
$$

### Relevance

The *sigmoid* function are more biologically plausible because the
output of inactive neurons are zero. Such activation function are
called *one-sided*. However, it has been shown that the hyperbolic
tangent performs better than the sigmoid for training MLPs. It has
become the most popular for *deep neural networks*

## Deriving the back propagation code for a multilayer perceptron model

Note: figures will be inserted later!

As we have seen the final output of a feed-forward network can be expressed in terms of basic matrix-vector multiplications.
The unknowwn quantities are our weights $w_{ij}$ and we need to find an algorithm for changing them so that our errors are as small as possible.
This leads us to the famous [back propagation algorithm](https://www.nature.com/articles/323533a0).

The questions we want to ask are how do changes in the biases and the
weights in our network change the cost function and how can we use the
final output to modify the weights?

To derive these equations let us start with a plain regression problem
and define our cost function as

$$
{\cal C}(\boldsymbol{W})  =  \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2,
$$

where the $t_i$s are our $n$ targets (the values we want to
reproduce), while the outputs of the network after having propagated
all inputs $\boldsymbol{x}$ are given by $y_i$.  Other cost functions can also be considered.

### Definitions

With our definition of the targets $\boldsymbol{t}$, the outputs of the
network $\boldsymbol{y}$ and the inputs $\boldsymbol{x}$ we
define now the activation $z_j^l$ of node/neuron/unit $j$ of the
$l$-th layer as a function of the bias, the weights which add up from
the previous layer $l-1$ and the forward passes/outputs
$\boldsymbol{a}^{l-1}$ from the previous layer as

$$
z_j^l = \sum_{i=1}^{M_{l-1}}w_{ij}^la_i^{l-1}+b_j^l,
$$

where $b_j^l$ are the biases from layer $l$.  Here $M_{l-1}$
represents the total number of nodes/neurons/units of layer $l-1$. The
figure here illustrates this equation.  We can rewrite this in a more
compact form as the matrix-vector products we discussed earlier,

$$
\boldsymbol{z}^l = \left(\boldsymbol{W}^l\right)^T\boldsymbol{a}^{l-1}+\boldsymbol{b}^l.
$$

With the activation values $\boldsymbol{z}^l$ we can in turn define the
output of layer $l$ as $\boldsymbol{a}^l = f(\boldsymbol{z}^l)$ where $f$ is our
activation function. In the examples here we will use the sigmoid
function discussed in the logistic regression lecture. We will also use the same activation function $f$ for all layers
and their nodes.  It means we have

$$
a_j^l = f(z_j^l) = \frac{1}{1+\exp{-(z_j^l)}}.
$$

### Derivatives and the chain rule

From the definition of the activation $z_j^l$ we have

$$
\frac{\partial z_j^l}{\partial w_{ij}^l} = a_i^{l-1},
$$

and

$$
\frac{\partial z_j^l}{\partial a_i^{l-1}} = w_{ji}^l.
$$

With our definition of the activation function we have (note that this function depends only on $z_j^l$)

$$
\frac{\partial a_j^l}{\partial z_j^{l}} = a_j^l(1-a_j^l)=f(z_j^l) \left[ 1-f(z_j^l) \right].
$$

### Derivative of the cost function

With these definitions we can now compute the derivative of the cost function in terms of the weights.

Let us specialize to the output layer $l=L$. Our cost function is

$$
{\cal C}(\boldsymbol{W^L})  =  \frac{1}{2}\sum_{i=1}^n\left(y_i - t_i\right)^2=\frac{1}{2}\sum_{i=1}^n\left(a_i^L - t_i\right)^2,
$$

The derivative of this function with respect to the weights is

$$
\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{jk}^L}  =  \left(a_j^L - t_j\right)\frac{\partial a_j^L}{\partial w_{jk}^{L}},
$$

The last partial derivative can easily be computed and reads (by applying the chain rule)

$$
\frac{\partial a_j^L}{\partial w_{jk}^{L}} = \frac{\partial a_j^L}{\partial z_{j}^{L}}\frac{\partial z_j^L}{\partial w_{jk}^{L}}=a_j^L(1-a_j^L)a_k^{L-1},
$$

### Bringing it together, first back propagation equation

We have thus

$$
\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{jk}^L}  =  \left(a_j^L - t_j\right)a_j^L(1-a_j^L)a_k^{L-1},
$$

Defining

$$
\delta_j^L = a_j^L(1-a_j^L)\left(a_j^L - t_j\right) = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)},
$$

and using the Hadamard product of two vectors we can write this as

$$
\boldsymbol{\delta}^L = f'(\boldsymbol{z}^L)\circ\frac{\partial {\cal C}}{\partial (\boldsymbol{a}^L)}.
$$

This is an important expression. The second term on the right handside
measures how fast the cost function is changing as a function of the $j$th
output activation.  If, for example, the cost function doesn't depend
much on a particular output node $j$, then $\delta_j^L$ will be small,
which is what we would expect. The first term on the right, measures
how fast the activation function $f$ is changing at a given activation
value $z_j^L$.

Notice that everything in the above equations is easily computed.  In
particular, we compute $z_j^L$ while computing the behaviour of the
network, and it is only a small additional overhead to compute
$f'(z^L_j)$.  The exact form of the derivative with respect to the
output depends on the form of the cost function.
However, provided the cost function is known there should be little
trouble in calculating

$$
\frac{\partial {\cal C}}{\partial (a_j^L)}
$$

With the definition of $\delta_j^L$ we have a more compact definition of the derivative of the cost function in terms of the weights, namely

$$
\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{jk}^L}  =  \delta_j^La_k^{L-1}.
$$

### Derivatives in terms of $z_j^L$

It is also easy to see that our previous equation can be written as

$$
\delta_j^L =\frac{\partial {\cal C}}{\partial z_j^L}= \frac{\partial {\cal C}}{\partial a_j^L}\frac{\partial a_j^L}{\partial z_j^L},
$$

which can also be interpreted as the partial derivative of the cost function with respect to the biases $b_j^L$, namely

$$
\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L}\frac{\partial b_j^L}{\partial z_j^L}=\frac{\partial {\cal C}}{\partial b_j^L},
$$

That is, the error $\delta_j^L$ is exactly equal to the rate of change of the cost function as a function of the bias.

We have now three equations that are essential for the computations of the derivatives of the cost function at the output layer. These equations are needed to start the algorithm and they are

**The starting equations.**

$$
\begin{equation}
\frac{\partial{\cal C}(\boldsymbol{W^L})}{\partial w_{jk}^L}  =  \delta_j^La_k^{L-1},
\label{_auto8} \tag{13}
\end{equation}
$$

and

$$
\begin{equation}
\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)},
\label{_auto9} \tag{14}
\end{equation}
$$

and

$$
\begin{equation}
\delta_j^L = \frac{\partial {\cal C}}{\partial b_j^L},
\label{_auto10} \tag{15}
\end{equation}
$$

An interesting consequence of the above equations is that when the
activation $a_k^{L-1}$ is small, the gradient term, that is the
derivative of the cost function with respect to the weights, will also
tend to be small. We say then that the weight learns slowly, meaning
that it changes slowly when we minimize the weights via say gradient
descent. In this case we say the system learns slowly.

Another interesting feature is that is when the activation function,
represented by the sigmoid function here, is rather flat when we move towards
its end values $0$ and $1$. In these
cases, the derivatives of the activation function will also be close
to zero, meaning again that the gradients will be small and the
network learns slowly again.

We need a fourth equation and we are set. We are going to propagate
backwards in order to determine the weights and biases. In order
to do so we need to represent the error in the layer before the final
one $L-1$ in terms of the errors in the final output layer.

### Final back-propagating equation

We have that (replacing $L$ with a general layer $l$)

$$
\delta_j^l =\frac{\partial {\cal C}}{\partial z_j^l}.
$$

We want to express this in terms of the equations for layer $l+1$. Using the chain rule and summing over all $k$ entries we have

$$
\delta_j^l =\sum_k \frac{\partial {\cal C}}{\partial z_k^{l+1}}\frac{\partial z_k^{l+1}}{\partial z_j^{l}}=\sum_k \delta_k^{l+1}\frac{\partial z_k^{l+1}}{\partial z_j^{l}},
$$

and recalling that

$$
z_j^{l+1} = \sum_{i=1}^{M_{l}}w_{ij}^{l+1}a_i^{l}+b_j^{l+1},
$$

with $M_l$ being the number of nodes in layer $l$, we obtain

$$
\delta_j^l =\sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l),
$$

This is our final equation.

We are now ready to set up the algorithm for back propagation and learning the weights and biases.

## Setting up the back-propagation algorithm

The four equations  provide us with a way of computing the gradient of the cost function. Let us write this out in the form of an algorithm.

**Summary.**

* First, we set up the input data $\boldsymbol{x}$ and the activations $\boldsymbol{z}_1$ of the input layer and compute the activation function and the outputs $\boldsymbol{a}^1$.

* Secondly, perform the feed-forward until we reach the output layer. I.e., compute all activation functions and the pertinent outputs $\boldsymbol{a}^l$ for $l=2,3,\dots,L$.

* Compute the ouput error $\boldsymbol{\delta}^L$ by

$$
\delta_j^L = f'(z_j^L)\frac{\partial {\cal C}}{\partial (a_j^L)}.
$$

* Back-propagate the error for each $l=L-1,L-2,\dots,2$ as

$$
\delta_j^l = \sum_k \delta_k^{l+1}w_{kj}^{l+1}f'(z_j^l).
$$

* Finally, update the weights and the biases using gradient descent for each $l=L-1,L-2,\dots,2$ and update the weights and biases according to the rules

$$
w_{jk}^l\leftarrow  w_{jk}^l- \eta \delta_j^la_k^{l-1},
$$

$$
b_j^l \leftarrow b_j^l-\eta \frac{\partial {\cal C}}{\partial b_j^l}=b_j^l-\eta \delta_j^l,
$$

The parameter $\eta$ is the learning rate.
Here it is convenient to use stochastic gradient descent with mini-batches and an outer loop that steps through multiple epochs of training.

## Learning challenges

The back-propagation algorithm works by going from
the output layer to the input layer, propagating the error gradient. The learning algorithm uses these
gradients to update each parameter with a Gradient Descent (GD) step.

Unfortunately, the gradients often get smaller and smaller as the
algorithm progresses down to the first hidden layers. As a result, the
GD update step leaves the lower layer connection weights
virtually unchanged, and training never converges to a good
solution. This is known in the literature as
**the vanishing gradients problem**.

In other cases, the opposite can happen, namely that the gradients grow bigger and
bigger. The result is that many of the layers get large updates of the
weights and the learning algorithm diverges. This is the **exploding gradients problem**, which is mostly encountered in recurrent neural networks. More generally, deep neural networks suffer from unstable gradients, different layers may learn at widely different speeds

### Is the Logistic activation function (Sigmoid) our choice?

Although this unfortunate behavior has been empirically observed for
quite a while (it was one of the reasons why deep neural networks were
mostly abandoned for a long time), it is only around 2010 that
significant progress was made in understanding it.

A paper titled [Understanding the Difficulty of Training Deep
Feedforward Neural Networks by Xavier Glorot and Yoshua Bengio](http://proceedings.mlr.press/v9/glorot10a.html) identified problems with the popular logistic
sigmoid activation function and the weight initialization technique
that was most popular at the time (namely random initialization using
a normal distribution with a mean of 0 and a standard deviation of
1).

They showed that with this activation function and this
initialization scheme, the variance of the outputs of each layer is
much greater than the variance of its inputs. Going forward in the
network, the variance keeps increasing after each layer until the
activation function saturates at the top layers. This is actually made
worse by the fact that the logistic function has a mean of 0.5, not 0
(the hyperbolic tangent function has a mean of 0 and behaves slightly
better than the logistic function in deep networks).

### The derivative of the Logistic funtion

Looking at the logistic activation function, when inputs become large
(negative or positive), the function saturates at 0 or 1, with a
derivative extremely close to 0. Thus when backpropagation kicks in,
it has virtually no gradient to propagate back through the network,
and what little gradient exists keeps getting diluted as
backpropagation progresses down through the top layers, so there is
really nothing left for the lower layers.

In their paper, Glorot and Bengio proposed a way to significantly
alleviate this problem. The signal must flow properly in both
directions: in the forward direction when making predictions, and in
the reverse direction when backpropagating gradients. We don’t want
the signal to die out, nor do we want it to explode and saturate. For
the signal to flow properly, the authors argue that we need the
variance of the outputs of each layer to be equal to the variance of
its inputs, and we also need the gradients to have equal variance
before and after flowing through a layer in the reverse direction.

One of the insights in the 2010 paper by Glorot and Bengio was that
the vanishing/exploding gradients problems were in part due to a poor
choice of activation function. Until then most people had assumed that
if Nature had chosen to use roughly sigmoid activation functions in
biological neurons, they must be an excellent choice. But it turns out
that other activation functions behave much better in deep neural
networks, in particular the ReLU activation function, mostly because
it does not saturate for positive values (and also because it is quite
fast to compute).

### The RELU function family

The Rectifier Linear Unit (ReLU) uses the following activation function

$$
f(z) = \max(0,z).
$$

The ReLU activation function suffers from a problem known as the dying
ReLUs: during training, some neurons effectively die, meaning they
stop outputting anything other than 0.

In some cases, you may find that half of your network’s neurons are
dead, especially if you used a large learning rate. During training,
if a neuron’s weights get updated such that the weighted sum of the
neuron’s inputs is negative, it will start outputting 0. When this
happen, the neuron is unlikely to come back to life since the gradient
of the ReLU function is 0 when its input is negative.

To solve this problem, nowadays practitioners use a  variant of the ReLU
function, such as the leaky ReLU discussed above or the so-called
exponential linear unit (ELU) function

$$
ELU(z) = \left\{\begin{array}{cc} \alpha\left( \exp{(z)}-1\right) & z < 0,\\  z & z \ge 0.\end{array}\right.
$$

### Which activation function should we use?

In general it seems that the ELU activation function is better than
the leaky ReLU function (and its variants), which is better than
ReLU. ReLU performs better than $\tanh$ which in turn performs better
than the logistic function.

If runtime
performance is an issue, then you may opt for the  leaky ReLU function  over the
ELU function If you don’t
want to tweak yet another hyperparameter, you may just use the default
$\alpha$ of $0.01$ for the leaky ReLU, and $1$ for ELU. If you have
spare time and computing power, you can use cross-validation or
bootstrap to evaluate other activation functions.

## A top-down perspective on Neural networks

The first thing we would like to do is divide the data into two or three
parts. A training set, a validation or dev (development) set, and a
test set.
* The training set is used for learning and adjusting the weights.

* The dev/validation set is a subset of the training data. It is used to

check how well we are doing out-of-sample, after training the model on
the training dataset. We use the validation error as a proxy for the
test error in order to make tweaks to our model, e.g. changing hyperparameters such as the learning rate.
* The test set will be used to test the performance of or predictions with the final neural net.

It is crucial that we do not use any of the test data to train the algorithm. This is a cardinal sin in ML. T If the validation and test sets are drawn from the same distributions, then a good performance on the validation set should lead to similarly good performance on the test set.

However, sometimes
the training data and test data differ in subtle ways because, for
example, they are collected using slightly different methods, or
because it is cheaper to collect data in one way versus another. In
this case, there can be a mismatch between the training and test
data. This can lead to the neural network overfitting these small
differences between the test and training sets, and a poor performance
on the test set despite having a good performance on the validation
set. To rectify this, Andrew Ng suggests making two validation or dev
sets, one constructed from the training data and one constructed from
the test data. The difference between the performance of the algorithm
on these two validation sets quantifies the train-test mismatch. This
can serve as another important diagnostic when using DNNs for
supervised learning.

## Limitations of supervised learning with deep networks

Like all statistical methods, supervised learning using neural
networks has important limitations. This is especially important when
one seeks to apply these methods, especially to physics problems. Like
all tools, DNNs are not a universal solution. Often, the same or
better performance on a task can be achieved by using a few
hand-engineered features (or even a collection of random
features).

Here we list some of the important limitations of supervised neural network based models.

* **Need labeled data**. All supervised learning methods, DNNs for supervised learning require labeled data. Often, labeled data is harder to acquire than unlabeled data (e.g. one must pay for human experts to label images).

* **Supervised neural networks are extremely data intensive.** DNNs are data hungry. They perform best when data is plentiful. This is doubly so for supervised methods where the data must also be labeled. The utility of DNNs is extremely limited if data is hard to acquire or the datasets are small (hundreds to a few thousand samples). In this case, the performance of other methods that utilize hand-engineered features can exceed that of DNNs.

* **Homogeneous data.** Almost all DNNs deal with homogeneous data of one type. It is very hard to design architectures that mix and match data types (i.e. some continuous variables, some discrete variables, some time series). In applications beyond images, video, and language, this is often what is required. In contrast, ensemble models like random forests or gradient-boosted trees have no difficulty handling mixed data types.

* **Many problems are not about prediction.** In natural science we are often interested in learning something about the underlying distribution that generates the data. In this case, it is often difficult to cast these ideas in a supervised learning setting. While the problems are related, it is possible to make good predictions with a *wrong* model. The model might or might not be useful for understanding the underlying science.

Some of these remarks are particular to DNNs, others are shared by all supervised learning methods. This motivates the use of unsupervised methods which in part circumvent these problems.