<!-- dom:TITLE: Week 48: Support Vector Machines and Summary of course -->
# Week 48: Support Vector Machines and Summary of course
<!-- dom:AUTHOR: Morten Hjorth-Jensen at Department of Physics, University of Oslo & Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University -->
<!-- Author: -->
**Morten Hjorth-Jensen**, Department of Physics, University of Oslo and Department of Physics and Astronomy and National Superconducting Cyclotron Laboratory, Michigan State University

Date: **Nov 26, 2020**

Copyright 1999-2020, Morten Hjorth-Jensen. Released under CC Attribution-NonCommercial 4.0 license

## Overview of week 48

* **Thursday**: Support Vector Machines: Kernels, Classification and Regression

* **Friday**: Summary of course with perspectives for future studies

Geron's chapter 5. Chapter 12 (sections 12.1-12.3 are the most relevant ones)  of Hastie et al contains also a good discussion.

## Thursday

We finalize our discussion on Support Vector Machines with an emphasis on kernel transformations and applications to regression. The following [video attempts at giving an overview on this part](https://www.youtube.com/watch?v=Toet3EiSFcM&ab_channel=StatQuestwithJoshStarmer). See also the [follow-up video](https://www.youtube.com/watch?v=Qc5IyLW_hns&ab_channel=StatQuestwithJoshStarmer).

## Friday

Friday's lecture is split in two parts. It starts with a summary of
what we have done this semester and continues with perspectives for future studies and
modern research projects in machine learning.

## Support Vector Machines, overarching aims

As discussed last week,
a Support Vector Machine (SVM) is a very powerful and versatile
Machine Learning method, capable of performing linear or nonlinear
classification, regression, and even outlier detection. It is one of
the most popular models in Machine Learning, and anyone interested in
Machine Learning should have it in their toolbox. SVMs are
particularly well suited for classification of complex but small-sized or
medium-sized datasets.

The case with two well-separated classes only can be understood in an
intuitive way in terms of lines in a two-dimensional space separating
the two classes.

The basic mathematics behind the SVM is however less familiar to most of us.
It relies on the definition of hyperplanes and the
definition of a **margin** which separates classes (in case of
classification problems) of variables. It is also used for regression
problems.  I recommend you take a look at the lectures from last week on the binary classification problem.

## Kernels and non-linearity

The cases we studied last week  were all characterized by two classes
with a close to linear separability. The classifiers we have described
so far find linear boundaries in our input feature space. It is
possible to make our procedure more flexible by exploring the feature
space using other basis expansions such as higher-order polynomials,
wavelets, splines etc.

If our feature space is not easy to separate, as shown in the figure
here generated by the code below (see also Figures 12.2 and 12.3 of [Hastie et al.](https://www.springer.com/gp/book/9780387848570)), we can achieve a better separation by introducing more complex
basis functions. The ideal would be (see Figures 12.2 and 12.3) to, via a specific transformation to
obtain a separation between the classes which is almost linear.

The change of basis, from $x\rightarrow z=\phi(x)$ leads to the same type of equations to be solved, except that
we need to introduce, for example, a polynomial transformation to a two-dimensional training set.

```python
%matplotlib inline

import numpy as np
import os

np.random.seed(42)

# To plot pretty figures
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

from sklearn.svm import SVC
from sklearn import datasets

X1D = np.linspace(-4, 4, 9).reshape(-1, 1)
X2D = np.c_[X1D, X1D**2]
y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])

plt.figure(figsize=(11, 4))

plt.subplot(121)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.plot(X1D[:, 0][y==0], np.zeros(4), "bs")
plt.plot(X1D[:, 0][y==1], np.zeros(5), "g^")
plt.gca().get_yaxis().set_ticks([])
plt.xlabel(r"$x_1$", fontsize=20)
plt.axis([-4.5, 4.5, -0.2, 0.2])

plt.subplot(122)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs")
plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^")
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"$x_2$", fontsize=20, rotation=0)
plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16])
plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3)
plt.axis([-4.5, 4.5, -1, 17])
plt.subplots_adjust(right=1)
plt.show()
```

## The equations

Suppose we define a polynomial transformation of degree two only. We define a vector $\boldsymbol{x}_i=[x_i,y_i]$ and have

$$
\boldsymbol{z}_i^T = \phi(\boldsymbol{x}_i)^T =\left[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i\right].
$$

With our new basis, the equations we solved earlier are basically the same, that is we have now (without the slack option for simplicity)

$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{z}_i^T\boldsymbol{z}_j,
$$

subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$, and for the support vectors

$$
y_i(\boldsymbol{z}_i^T\boldsymbol{w}+b)= 1 \hspace{0.1cm}\forall i,
$$

from which we also find $b$.
To compute $\boldsymbol{z}_i^T\boldsymbol{z}_j$ we define the kernel $K(\boldsymbol{x}_i,\boldsymbol{x}_j)$ as

$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\boldsymbol{z}_i^T\boldsymbol{z}_j= \phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j).
$$

For the above example, the kernel reads

$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[1, \sqrt{2}x_i, \sqrt{2}y_i, x_i^2, y_i^2, \sqrt{2}x_iy_i]\begin{bmatrix} 1\\ \sqrt{2}x_j \\ \sqrt{2}y_j \\ x_j^2\\ y_i^2\\ \sqrt{2}x_jy_j \end{bmatrix}=1+2x_ix_j+2y_iy_j+(x_ix_j)^2+(y_iy_j)^2+2x_ix_jy_iy_j.
$$

We note that this dot product can be rewritten as

$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=[1+\boldsymbol{x}_i^T\boldsymbol{x}_j]^d,
$$

where $d=2$ in our case and $\boldsymbol{x}_i=[x_i,y_i]$ and $\boldsymbol{x}_j=[x_j,y_j]$.
To compute the last equation is however inefficient from a computational stand.
Instead of computing the last equation for the kernel, we simply compute
the dot product $(\boldsymbol{x}_i^T\boldsymbol{x}_j)^2$.
This leads to the so-called
kernel trick.

## The problem to solve

Using our definition of the kernel, we can rewrite again the Lagrangian

$$
{\cal L}=\sum_i\lambda_i-\frac{1}{2}\sum_{ij}^n\lambda_i\lambda_jy_iy_j\boldsymbol{x}_i^T\boldsymbol{z}_j,
$$

subject to the constraints $\lambda_i\geq 0$, $\sum_i\lambda_iy_i=0$ in terms of a convex optimization problem

$$
\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\
y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\
\end{bmatrix}\boldsymbol{\lambda}-\mathbb{1}\boldsymbol{\lambda},
$$

subject to $\boldsymbol{y}^T\boldsymbol{\lambda}=0$. Here we defined the vectors $\boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
$\boldsymbol{y}=[y_1,y_2,\dots,y_n]$.
If we add the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.

## Tailoring the equations to the usage of CVXOPT

We can rewrite this (see the solutions below) in terms of a convex optimization problem of the type

$$
\begin{align*}
    &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber
    &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \hspace{0.2cm} \wedge \boldsymbol{A}\boldsymbol{\lambda}=f.
\end{align*}
$$

Below we discuss how to solve these equations. Here we note that the matrix $\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j)$.
Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up. The constraint $\boldsymbol{y}^T\boldsymbol{\lambda}=0$ leads to $f=0$ and $\boldsymbol{A}=\boldsymbol{y}$. How to set up the matrix $\boldsymbol{G}$ is discussed later. Here note that the inequalities $0\leq \lambda_i \leq C$ can be split up into
$0\leq \lambda_i$ and $\lambda_i \leq C$. These two inequalities define then the matrix $\boldsymbol{G}$ and the vector $\boldsymbol{h}$.

## Different kernels and Mercer's theorem

There are several popular kernels being used. These are
1. Linear: $K(\boldsymbol{x},\boldsymbol{y})=\boldsymbol{x}^T\boldsymbol{y}$,

2. Polynomial: $K(\boldsymbol{x},\boldsymbol{y})=(\boldsymbol{x}^T\boldsymbol{y}+\gamma)^d$,

3. Gaussian Radial Basis Function: $K(\boldsymbol{x},\boldsymbol{y})=\exp{\left(-\gamma\vert\vert\boldsymbol{x}-\boldsymbol{y}\vert\vert^2\right)}$,

4. Tanh: $K(\boldsymbol{x},\boldsymbol{y})=\tanh{(\boldsymbol{x}^T\boldsymbol{y}+\gamma)}$,

and many other ones.

An important theorem for us is [Mercer's
theorem](https://en.wikipedia.org/wiki/Mercer%27s_theorem).  The
theorem states that if a kernel function $K$ is symmetric, continuous
and leads to a positive semi-definite matrix $\boldsymbol{P}$ then there
exists a function $\phi$ that maps $\boldsymbol{x}_i$ and $\boldsymbol{x}_j$ into
another space (possibly with much higher dimensions) such that

$$
K(\boldsymbol{x}_i,\boldsymbol{x}_j)=\phi(\boldsymbol{x}_i)^T\phi(\boldsymbol{x}_j).
$$

So you can use $K$ as a kernel since you know $\phi$ exists, even if
you don’t know what $\phi$ is.

Note that some frequently used kernels (such as the Sigmoid kernel)
don’t respect all of Mercer’s conditions, yet they generally work well
in practice.

## The moons example ([Adapted from Geron, chapter 5](https://www.oreilly.com/library/view/hands-on-machine-learning/9781492032632/))

```python
from __future__ import division, print_function, unicode_literals

import numpy as np
np.random.seed(42)

import matplotlib
import matplotlib.pyplot as plt
plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

from sklearn.svm import SVC
from sklearn import datasets

from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import LinearSVC

from sklearn.datasets import make_moons
X, y = make_moons(n_samples=100, noise=0.15, random_state=42)

def plot_dataset(X, y, axes):
    plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
    plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
    plt.axis(axes)
    plt.grid(True, which='both')
    plt.xlabel(r"$x_1$", fontsize=20)
    plt.ylabel(r"$x_2$", fontsize=20, rotation=0)

plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.show()

from sklearn.datasets import make_moons
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures

polynomial_svm_clf = Pipeline([
        ("poly_features", PolynomialFeatures(degree=3)),
        ("scaler", StandardScaler()),
        ("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42))
    ])

polynomial_svm_clf.fit(X, y)

def plot_predictions(clf, axes):
    x0s = np.linspace(axes[0], axes[1], 100)
    x1s = np.linspace(axes[2], axes[3], 100)
    x0, x1 = np.meshgrid(x0s, x1s)
    X = np.c_[x0.ravel(), x1.ravel()]
    y_pred = clf.predict(X).reshape(x0.shape)
    y_decision = clf.decision_function(X).reshape(x0.shape)
    plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)
    plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)

plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])

plt.show()

from sklearn.svm import SVC

poly_kernel_svm_clf = Pipeline([
        ("scaler", StandardScaler()),
        ("svm_clf", SVC(kernel="poly", degree=3, coef0=1, C=5))
    ])
poly_kernel_svm_clf.fit(X, y)

poly100_kernel_svm_clf = Pipeline([
        ("scaler", StandardScaler()),
        ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5))
    ])
poly100_kernel_svm_clf.fit(X, y)

plt.figure(figsize=(11, 4))

plt.subplot(121)
plot_predictions(poly_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.title(r"$d=3, r=1, C=5$", fontsize=18)

plt.subplot(122)
plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.5, -1, 1.5])
plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
plt.title(r"$d=10, r=100, C=5$", fontsize=18)

plt.show()

def gaussian_rbf(x, landmark, gamma):
    return np.exp(-gamma * np.linalg.norm(x - landmark, axis=1)**2)

gamma = 0.3

x1s = np.linspace(-4.5, 4.5, 200).reshape(-1, 1)
x2s = gaussian_rbf(x1s, -2, gamma)
x3s = gaussian_rbf(x1s, 1, gamma)

XK = np.c_[gaussian_rbf(X1D, -2, gamma), gaussian_rbf(X1D, 1, gamma)]
yk = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0])

plt.figure(figsize=(11, 4))

plt.subplot(121)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.scatter(x=[-2, 1], y=[0, 0], s=150, alpha=0.5, c="red")
plt.plot(X1D[:, 0][yk==0], np.zeros(4), "bs")
plt.plot(X1D[:, 0][yk==1], np.zeros(5), "g^")
plt.plot(x1s, x2s, "g--")
plt.plot(x1s, x3s, "b:")
plt.gca().get_yaxis().set_ticks([0, 0.25, 0.5, 0.75, 1])
plt.xlabel(r"$x_1$", fontsize=20)
plt.ylabel(r"Similarity", fontsize=14)
plt.annotate(r'$\mathbf{x}$',
             xy=(X1D[3, 0], 0),
             xytext=(-0.5, 0.20),
             ha="center",
             arrowprops=dict(facecolor='black', shrink=0.1),
             fontsize=18,
            )
plt.text(-2, 0.9, "$x_2$", ha="center", fontsize=20)
plt.text(1, 0.9, "$x_3$", ha="center", fontsize=20)
plt.axis([-4.5, 4.5, -0.1, 1.1])

plt.subplot(122)
plt.grid(True, which='both')
plt.axhline(y=0, color='k')
plt.axvline(x=0, color='k')
plt.plot(XK[:, 0][yk==0], XK[:, 1][yk==0], "bs")
plt.plot(XK[:, 0][yk==1], XK[:, 1][yk==1], "g^")
plt.xlabel(r"$x_2$", fontsize=20)
plt.ylabel(r"$x_3$  ", fontsize=20, rotation=0)
plt.annotate(r'$\phi\left(\mathbf{x}\right)$',
             xy=(XK[3, 0], XK[3, 1]),
             xytext=(0.65, 0.50),
             ha="center",
             arrowprops=dict(facecolor='black', shrink=0.1),
             fontsize=18,
            )
plt.plot([-0.1, 1.1], [0.57, -0.1], "r--", linewidth=3)
plt.axis([-0.1, 1.1, -0.1, 1.1])

plt.subplots_adjust(right=1)

plt.show()

x1_example = X1D[3, 0]
for landmark in (-2, 1):
    k = gaussian_rbf(np.array([[x1_example]]), np.array([[landmark]]), gamma)
    print("Phi({}, {}) = {}".format(x1_example, landmark, k))

rbf_kernel_svm_clf = Pipeline([
        ("scaler", StandardScaler()),
        ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001))
    ])
rbf_kernel_svm_clf.fit(X, y)

from sklearn.svm import SVC

gamma1, gamma2 = 0.1, 5
C1, C2 = 0.001, 1000
hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2)

svm_clfs = []
for gamma, C in hyperparams:
    rbf_kernel_svm_clf = Pipeline([
            ("scaler", StandardScaler()),
            ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C))
        ])
    rbf_kernel_svm_clf.fit(X, y)
    svm_clfs.append(rbf_kernel_svm_clf)

plt.figure(figsize=(11, 7))

for i, svm_clf in enumerate(svm_clfs):
    plt.subplot(221 + i)
    plot_predictions(svm_clf, [-1.5, 2.5, -1, 1.5])
    plot_dataset(X, y, [-1.5, 2.5, -1, 1.5])
    gamma, C = hyperparams[i]
    plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16)

plt.show()
```

## Mathematical optimization of convex functions

A mathematical (quadratic) optimization problem, or just optimization problem, has the form

$$
\begin{align*}
    &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber
    &\mathrm{subject\hspace{0.1cm}to} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge  \boldsymbol{A}\boldsymbol{\lambda}=f.
\end{align*}
$$

subject to some constraints for say a selected set $i=1,2,\dots, n$.
In our case we are optimizing with respect to the Lagrangian multipliers $\lambda_i$, and the
vector $\boldsymbol{\lambda}=[\lambda_1, \lambda_2,\dots, \lambda_n]$ is the optimization variable we are dealing with.

In our case we are particularly interested in a class of optimization problems called convex optmization problems.
In our discussion on gradient descent methods we discussed at length the definition of a convex function.

Convex optimization problems play a central role in applied mathematics and we recommend strongly [Boyd and Vandenberghe's text on the topics](http://web.stanford.edu/~boyd/cvxbook/).

## How do we solve these problems?

If we use Python as programming language and wish to venture beyond
**scikit-learn**, **tensorflow** and similar software which makes our
lives so much easier, we need to dive into the wonderful world of
quadratic programming. We can, if we wish, solve the minimization
problem using say standard gradient methods or conjugate gradient
methods. However, these methods tend to exhibit a rather slow
converge. So, welcome to the promised land of quadratic programming.

The functions we need are contained in the quadratic programming package **CVXOPT** and we need to import it together with **numpy** as

```python
import numpy
import cvxopt
```

This will make our life much easier. You don't need to write your own optimizer.

## A simple example

We remind ourselves about the general problem we want to solve

$$
\begin{align*}
    &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}\boldsymbol{x}^T\boldsymbol{P}\boldsymbol{x}+\boldsymbol{q}^T\boldsymbol{x},\\ \nonumber
    &\mathrm{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{x} \preceq \boldsymbol{h} \wedge  \boldsymbol{A}\boldsymbol{x}=f.
\end{align*}
$$

Note: we use **s.t.** for subject to.
Let us show how to perform the optmization using a simple case. Assume we want to optimize the following problem

$$
\begin{align*}
    &\mathrm{min}_{x}\hspace{0.2cm} \frac{1}{2}x^2+5x+3y \\ \nonumber
    &\mathrm{subject to} \\ \nonumber
    &x, y \geq 0 \\ \nonumber
    &x+3y  \geq 15 \\ \nonumber
    &2x+5y  \leq  100 \\ \nonumber
    &3x+4y  \leq  80.  \\ \nonumber
\end{align*}
$$

The minimization problem can be rewritten in terms of vectors and matrices as (with $x$ and $y$ being the unknowns)

$$
\frac{1}{2}\begin{bmatrix} x\\ y \end{bmatrix}^T   \begin{bmatrix} 1 & 0\\ 0 & 0  \end{bmatrix}  \begin{bmatrix} x \\ y \end{bmatrix}  + \begin{bmatrix}3\\ 4  \end{bmatrix}^T \begin{bmatrix}x \\ y  \end{bmatrix}.
$$

Similarly, we can now set up the inequalities (we need to change $\geq$ to $\leq$ by multiplying with $-1$ on bot sides) as the following matrix-vector equation

$$
\begin{bmatrix} -1 & 0 \\ 0 & -1 \\ -1 & -3 \\ 2 & 5 \\ 3 & 4\end{bmatrix}\begin{bmatrix} x \\ y\end{bmatrix} \preceq \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
$$

We have collapsed all the inequalities into a single matrix $\boldsymbol{G}$. We see also that our matrix

$$
\boldsymbol{P} =\begin{bmatrix} 1 & 0\\ 0 & 0  \end{bmatrix}
$$

is clearly positive semi-definite (all eigenvalues larger or equal zero).
Finally, the vector $\boldsymbol{h}$ is defined as

$$
\boldsymbol{h} = \begin{bmatrix}0 \\ 0\\ -15 \\ 100 \\ 80\end{bmatrix}.
$$

Since we don't have any equalities the matrix $\boldsymbol{A}$ is set to zero
The following code solves the equations for us

```python
# Import the necessary packages
import numpy
from cvxopt import matrix
from cvxopt import solvers
P = matrix(numpy.diag([1,0]), tc='d')
q = matrix(numpy.array([3,4]), tc='d')
G = matrix(numpy.array([[-1,0],[0,-1],[-1,-3],[2,5],[3,4]]), tc='d')
h = matrix(numpy.array([0,0,-15,100,80]), tc='d')
# Construct the QP, invoke solver
sol = solvers.qp(P,q,G,h)
# Extract optimal value and solution
sol['x']
sol['primal objective']
```

## Back to the more realistic cases

We are now ready to return to our setup of the optmization problem for a more realistic case. Introducing the **slack** parameter $C$ we have

$$
\frac{1}{2} \boldsymbol{\lambda}^T\begin{bmatrix} y_1y_1K(\boldsymbol{x}_1,\boldsymbol{x}_1) & y_1y_2K(\boldsymbol{x}_1,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_1,\boldsymbol{x}_n) \\
y_2y_1K(\boldsymbol{x}_2,\boldsymbol{x}_1) & y_2y_2K(\boldsymbol{x}_2,\boldsymbol{x}_2) & \dots & \dots & y_1y_nK(\boldsymbol{x}_2,\boldsymbol{x}_n) \\
\dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots \\
y_ny_1K(\boldsymbol{x}_n,\boldsymbol{x}_1) & y_ny_2K(\boldsymbol{x}_n\boldsymbol{x}_2) & \dots & \dots & y_ny_nK(\boldsymbol{x}_n,\boldsymbol{x}_n) \\
\end{bmatrix}\boldsymbol{\lambda}-\mathbb{I}\boldsymbol{\lambda},
$$

subject to $\boldsymbol{y}^T\boldsymbol{\lambda}=0$. Here we defined the vectors $\boldsymbol{\lambda} =[\lambda_1,\lambda_2,\dots,\lambda_n]$ and
$\boldsymbol{y}=[y_1,y_2,\dots,y_n]$.
With  the slack constants this leads to the additional constraint $0\leq \lambda_i \leq C$.

## Setting up the matrices and the problem

We have the general problem

$$
\begin{align*}
    &\mathrm{min}_{\lambda}\hspace{0.2cm} \frac{1}{2}\boldsymbol{\lambda}^T\boldsymbol{P}\boldsymbol{\lambda}+\boldsymbol{q}^T\boldsymbol{\lambda},\\ \nonumber
    &\mathrm{s.t.} \hspace{0.2cm} \boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h} \wedge  \boldsymbol{A}\boldsymbol{\lambda}=f.
\end{align*}
$$

1. With a given kernel we can thus define the matrix $\boldsymbol{P}$.

2. The matrix $\boldsymbol{P}$ has matrix elements $p_{ij}=y_iy_jK(\boldsymbol{x}_i,\boldsymbol{x}_j)$. Given a kernel $K$ and the targets $y_i$ this matrix is easy to set up.

3. The vector $\boldsymbol{q}$ is zero.

4. The constraint $\boldsymbol{y}^T\boldsymbol{\lambda}=0$ leads to $f=0$ and $\boldsymbol{A}=\boldsymbol{y}$.

5. To set up the matrix $\boldsymbol{G}$ we note that the inequalities $0\leq \lambda_i \leq C$ can be split up into $0\leq \lambda_i$ and $\lambda_i \leq C$. These two inequalities define then the matrix $\boldsymbol{G}$ and the vector $\boldsymbol{h}$.

## Setting up $\boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h}$

We have two constraints, $0\le \lambda_i$ and $\lambda_i \le C$. To do this we multiply the ones with the contraint
$\ge$ with $-1$ in order to get $\le$. It means that the problem $\boldsymbol{G}\boldsymbol{\lambda} \preceq \boldsymbol{h}$
can be written as

$$
\begin{bmatrix} -1& 0 & 0 & \dots & 0 \\
0& -1 & 0 & \dots & 0 \\
0& 0 & -1 & \dots & 0 \\
\dots& \dots & \dots  & \dots & \dots \\
0& 0 & 0 & \dots & -1 \\
1 & 0 & 0 & \dots & 0 \\
0& 1 & 0 & \dots & 0 \\
0& 0 & 1 & \dots & 0 \\
\dots& \dots & \dots  & \dots & \dots \\
0& 0 & 0 & \dots & 1 \\
\end{bmatrix}
\begin{bmatrix} \lambda_1 \\
\lambda_2 \\
\lambda_3 \\
\dots \\
\lambda_n \\
\end{bmatrix}=
\begin{bmatrix} 0 \\
0 \\
0 \\
\dots \\
0 \\
C \\
C \\
C \\
\dots \\
C \\
\end{bmatrix}.
$$

And then we are ready to go.

## SVMs and Regression and multiclass classification

[See handwritten lectures from lecture November 26.](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesNovember26.pdf). More text will be added here. See also [Hastie et al.](https://www.springer.com/gp/book/9780387848570) section 12.3.

## Summary of course

## What? Me worry? No final exam in this course!
<!-- dom:FIGURE: [figures/exam1.jpeg, width=500 frac=0.6] -->
<!-- begin figure -->

<p></p>

<!-- end figure -->

## Topics we have covered this year

The course has two central parts

1. Statistical analysis and optimization of data

2. Machine learning

## Statistical analysis and optimization of data

The following topics  be covered
1. Basic concepts, expectation values, variance, covariance, correlation functions and errors;

2. Simpler models, binomial distribution, the Poisson distribution, simple and multivariate normal distributions;

3. Central elements from linear algebra

4. Gradient methods for data optimization

5. Estimation of errors using cross-validation, bootstrapping and jackknife methods;

6. Practical optimization using Singular-value decomposition and least squares for parameterizing data.

7. Principal Component Analysis.

## Machine learning

The following topics will be covered
1. Linear methods for regression and classification:

a. Ordinary Least Squares

b. Ridge regression

c. Lasso regression

d. Logistic regression

5. Neural networks and deep learning:

a. Feed Forward Neural Networks

b. Convolutional Neural Networks

c. Recurrent Neural Networks

4. Decisions trees and ensemble methods:

a. Decision trees

b. Bagging and voting

c. Random forests

d. Boosting and gradient boosting

5. Support vector machines

a. Binary classification and multiclass classification

b. Kernel methods

c. Regression

## Learning outcomes and overarching aims of this course

The course introduces a variety of central algorithms and methods
essential for studies of data analysis and machine learning. The
course is project based and through the various projects, normally
three, you will be exposed to fundamental research problems
in these fields, with the aim to reproduce state of the art scientific
results. The students will learn to develop and structure large codes
for studying these systems, get acquainted with computing facilities
and learn to handle large scientific projects. A good scientific and
ethical conduct is emphasized throughout the course.

* Understand linear methods for regression and classification;

* Learn about neural network;

* Learn about baggin, boosting and trees

* Support vector machines

* Learn about basic data analysis;

* Be capable of extending the acquired knowledge to other systems and cases;

* Have an understanding of central algorithms used in data analysis and machine learning;

* Work on numerical projects to illustrate the theory. The projects play a central role and you are expected to know modern programming languages like Python or C++.

## Perspective on Machine Learning

1. Rapidly emerging application area

2. Experiment AND theory are evolving in many many fields. Still many low-hanging fruits.

3. Requires education/retraining for more widespread adoption

4. A lot of “word-of-mouth” development methods

Huge amounts of data sets require automation, classical analysis tools often inadequate.
High energy physics hit this wall in the 90’s.
In 2009 single top quark production was determined via [Boosted decision trees, Bayesian
Neural Networks, etc.](https://arxiv.org/pdf/0903.0850.pdf)

## Machine Learning Research

Where to find recent results:
1. Conference proceedings, arXiv and blog posts!

2. **NIPS**: [Neural Information Processing Systems](https://papers.nips.cc)

3. **ICLR**: [International Conference on Learning Representations](https://openreview.net/group?id=ICLR.cc/2018/Conference#accepted-oral-papers)

4. **ICML**: International Conference on Machine Learning

5. [Journal of Machine Learning Research](http://www.jmlr.org/papers/v19/)

## Starting your Machine Learning Project

1. Identify problem type: classification, generation, regression

2. Consider your data carefully

3. Choose a simple model that fits 1. and 2.

4. Consider your data carefully again… data representation

5. Based on results, feedback loop to earliest possible point

## Choose a Model and Algorithm

1. Supervised?

2. Start with the simplest model that fits your problem

3. Start with minimal processing of data

## Preparing Your Data

1. Shuffle your data

2. Mean center your data

  * Why?

3. Normalize the variance

  * Why?

4. **Whitening**

  * Decorrelates data

  * Can be hit or miss

5. When to do train/test split?

## Which Activation and Weights to Choose in Neural Networks

1. RELU? ELU?

2. Sigmoid or Tanh?

3. Set all weights to 0?

  * Terrible idea

4. Set all weights to random values?

  * Small random values

## Optimization Methods and Hyperparameters
1. Stochastic gradient descent

a. Stochastic gradient descent + momentum

2. State-of-the-art approaches:

  * RMSProp

  * Adam

Which regularization and hyperparameters? $L_1$ or $L_2$, soft classifiers, depths of trees and many other. Need to explore a large set of hyperparameters and regularization methods.

## Resampling

When do we resample?

1. Bootstrap

2. Cross-validation

3. Jackknife and many other

## Other courses on Data science and Machine Learning  at UiO

The link here <https://www.mn.uio.no/english/research/about/centre-focus/innovation/data-science/studies/>  gives an excellent overview of courses on Machine learning at UiO.

1. [STK2100 Machine learning and statistical methods for prediction and classification](http://www.uio.no/studier/emner/matnat/math/STK2100/index-eng.html).

2. [IN3050/IN4050 Introduction to Artificial Intelligence and Machine Learning](https://www.uio.no/studier/emner/matnat/ifi/IN3050/index-eng.html). Introductory course in machine learning and AI with an algorithmic approach.

3. [STK-INF3000/4000 Selected Topics in Data Science](http://www.uio.no/studier/emner/matnat/math/STK-INF3000/index-eng.html). The course provides insight into selected contemporary relevant topics within Data Science.

4. [IN4080 Natural Language Processing](https://www.uio.no/studier/emner/matnat/ifi/IN4080/index.html). Probabilistic and machine learning techniques applied to natural language processing.

5. [STK-IN4300 – Statistical learning methods in Data Science](https://www.uio.no/studier/emner/matnat/math/STK-IN4300/index-eng.html). An advanced introduction to statistical and machine learning. For students with a good mathematics and statistics background.

6. [IN-STK5000  Adaptive Methods for Data-Based Decision Making](https://www.uio.no/studier/emner/matnat/ifi/IN-STK5000/index-eng.html). Methods for adaptive collection and processing of data based on machine learning techniques.

7. [IN5400/INF5860 – Machine Learning for Image Analysis](https://www.uio.no/studier/emner/matnat/ifi/IN5400/). An introduction to deep learning with particular emphasis on applications within Image analysis, but useful for other application areas too.

8. [TEK5040 – Dyp læring for autonome systemer](https://www.uio.no/studier/emner/matnat/its/TEK5040/). The course addresses advanced algorithms and architectures for deep learning with neural networks. The course provides an introduction to how deep-learning techniques can be used in the construction of key parts of advanced autonomous systems that exist in physical environments and cyber environments.

## Additional courses of interest

1. [STK4051 Computational Statistics](https://www.uio.no/studier/emner/matnat/math/STK4051/index-eng.html)

2. [STK4021 Applied Bayesian Analysis and Numerical Methods](https://www.uio.no/studier/emner/matnat/math/STK4021/index-eng.html)

## What's the future like?

Based on multi-layer nonlinear neural networks, deep learning can
learn directly from raw data, automatically extract and abstract
features from layer to layer, and then achieve the goal of regression,
classification, or ranking. Deep learning has made breakthroughs in
computer vision, speech processing and natural language, and reached
or even surpassed human level. The success of deep learning is mainly
due to the three factors: big data, big model, and big computing.

In the past few decades, many different architectures of deep neural
networks have been proposed, such as
1. Convolutional neural networks, which are mostly used in image and video data processing, and have also been applied to sequential data such as text processing;

2. Recurrent neural networks, which can process sequential data of variable length and have been widely used in natural language understanding and speech processing;

3. Encoder-decoder framework, which is mostly used for image or sequence generation, such as machine translation, text summarization, and image captioning.

## Types of Machine Learning, a repetition

The approaches to machine learning are many, but are often split into two main categories.
In *supervised learning* we know the answer to a problem,
and let the computer deduce the logic behind it. On the other hand, *unsupervised learning*
is a method for finding patterns and relationship in data sets without any prior knowledge of the system.
Some authours also operate with a third category, namely *reinforcement learning*. This is a paradigm
of learning inspired by behavioural psychology, where learning is achieved by trial-and-error,
solely from rewards and punishment.

Another way to categorize machine learning tasks is to consider the desired output of a system.
Some of the most common tasks are:

  * Classification: Outputs are divided into two or more classes. The goal is to   produce a model that assigns inputs into one of these classes. An example is to identify  digits based on pictures of hand-written ones. Classification is typically supervised learning.

  * Regression: Finding a functional relationship between an input data set and a reference data set.   The goal is to construct a function that maps input data to continuous output values.

  * Clustering: Data are divided into groups with certain common traits, without knowing the different groups beforehand.  It is thus a form of unsupervised learning.

  * Other unsupervised learning algortihms like **Boltzmann machines**

## Why Boltzmann machines?

What is known as restricted Boltzmann Machines (RMB) have received a lot of attention lately.
One of the major reasons is that they can be stacked layer-wise to build deep neural networks that capture complicated statistics.

The original RBMs had just one visible layer and a hidden layer, but recently so-called Gaussian-binary RBMs have gained quite some popularity in imaging since they are capable of modeling continuous data that are common to natural images.

Furthermore, they have been used to solve complicated [quantum mechanical many-particle problems or classical statistical physics problems like the Ising and Potts classes of models](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002).

## Boltzmann Machines

Why use a generative model rather than the more well known discriminative deep neural networks (DNN)?

* Discriminitave methods have several limitations: They are mainly supervised learning methods, thus requiring labeled data. And there are tasks they cannot accomplish, like drawing new examples from an unknown probability distribution.

* A generative model can learn to represent and sample from a probability distribution. The core idea is to learn a parametric model of the probability distribution from which the training data was drawn. As an example

a. A model for images could learn to draw new examples of cats and dogs, given a training dataset of images of cats and dogs.

b. Generate a sample of an ordered or disordered phase, having been given samples of such phases.

c. Model the trial function for [Monte Carlo calculations](https://journals.aps.org/rmp/abstract/10.1103/RevModPhys.91.045002).

## Some similarities and differences from DNNs

1. Both use gradient-descent based learning procedures for minimizing cost functions

2. Energy based models don't use backpropagation and automatic differentiation for computing gradients, instead turning to Markov Chain Monte Carlo methods.

3. DNNs often have several hidden layers. A restricted Boltzmann machine has only one hidden layer, however several RBMs can be stacked to make up Deep Belief Networks, of which they constitute the building blocks.

History: The RBM was developed by amongst others [Geoffrey Hinton](https://en.wikipedia.org/wiki/Geoffrey_Hinton), called by some the "Godfather of Deep Learning", working with the University of Toronto and Google.

## Boltzmann machines (BM)

A BM is what we would call an undirected probabilistic graphical model
with stochastic continuous or discrete units.

It is interpreted as a stochastic recurrent neural network where the
state of each unit(neurons/nodes) depends on the units it is connected
to. The weights in the network represent thus the strength of the
interaction between various units/nodes.

It turns into a Hopfield network if we choose deterministic rather
than stochastic units. In contrast to a Hopfield network, a BM is a
so-called generative model. It allows us to generate new samples from
the learned distribution.

## A standard BM setup

A standard BM network is divided into a set of observable and visible units $\hat{x}$ and a set of unknown hidden units/nodes $\hat{h}$.

Additionally there can be bias nodes for the hidden and visible layers. These biases are normally set to $1$.

BMs are stackable, meaning they cwe can train a BM which serves as input to another BM. We can construct deep networks for learning complex PDFs. The layers can be trained one after another, a feature which makes them popular in deep learning

However, they are often hard to train. This leads to the introduction of so-called restricted BMs, or RBMS.
Here we take away all lateral connections between nodes in the visible layer as well as connections between nodes in the hidden layer. The network is illustrated in the figure below.

## The structure of the RBM network

<!-- dom:FIGURE: [figures/RBM.png, width=800 frac=1.0] -->
<!-- begin figure -->

<p></p>

<!-- end figure -->

## The network

**The network layers**:
1. A function $\mathbf{x}$ that represents the visible layer, a vector of $M$ elements (nodes). This layer represents both what the RBM might be given as training input, and what we want it to be able to reconstruct. This might for example be given by the pixels of an image or coefficients representing speech, or the coordinates of a quantum mechanical state function.

2. The function $\mathbf{h}$ represents the hidden, or latent, layer. A vector of $N$ elements (nodes). Also called "feature detectors".

## Goals

The goal of the hidden layer is to increase the model's expressive
power. We encode complex interactions between visible variables by
introducing additional, hidden variables that interact with visible
degrees of freedom in a simple manner, yet still reproduce the complex
correlations between visible degrees in the data once marginalized
over (integrated out).

**The network parameters, to be optimized/learned**:
1. $\mathbf{a}$ represents the visible bias, a vector of same length as $\mathbf{x}$.

2. $\mathbf{b}$ represents the hidden bias, a vector of same lenght as $\mathbf{h}$.

3. $W$ represents the interaction weights, a matrix of size $M\times N$.

## Joint distribution

The restricted Boltzmann machine is described by a Bolztmann distribution

<!-- Equation labels as ordinary links -->
<div id="_auto1"></div>

$$
\begin{equation}
	P_{rbm}(\mathbf{x},\mathbf{h}) = \frac{1}{Z} e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})},
\label{_auto1} \tag{1}
\end{equation}
$$

where $Z$ is the normalization constant or partition function, defined as

<!-- Equation labels as ordinary links -->
<div id="_auto2"></div>

$$
\begin{equation}
	Z = \int \int e^{-\frac{1}{T_0}E(\mathbf{x},\mathbf{h})} d\mathbf{x} d\mathbf{h}.
\label{_auto2} \tag{2}
\end{equation}
$$

It is common to ignore $T_0$ by setting it to one.

## Network Elements, the energy function

The function $E(\mathbf{x},\mathbf{h})$ gives the **energy** of a
configuration (pair of vectors) $(\mathbf{x}, \mathbf{h})$. The lower
the energy of a configuration, the higher the probability of it. This
function also depends on the parameters $\mathbf{a}$, $\mathbf{b}$ and
$W$. Thus, when we adjust them during the learning procedure, we are
adjusting the energy function to best fit our problem.

An expression for the energy function is

$$
E(\hat{x},\hat{h}) = -\sum_{ia}^{NA}b_i^a \alpha_i^a(x_i)-\sum_{jd}^{MD}c_j^d \beta_j^d(h_j)-\sum_{ijad}^{NAMD}b_i^a \alpha_i^a(x_i)c_j^d \beta_j^d(h_j)w_{ij}^{ad}.
$$

Here $\beta_j^d(h_j)$ and $\alpha_i^a(x_j)$ are so-called transfer functions that map a given input value to a desired feature value. The labels $a$ and $d$ denote that there can be multiple transfer functions per variable. The first sum depends only on the visible units. The second on the hidden ones. **Note** that there is no connection between nodes in a layer.

The quantities $b$ and $c$ can be interpreted as the visible and hidden biases, respectively.

The connection between the nodes in the two layers is given by the weights $w_{ij}$.

## Defining different types of RBMs
There are different variants of RBMs, and the differences lie in the types of visible and hidden units we choose as well as in the implementation of the energy function $E(\mathbf{x},\mathbf{h})$.

**Binary-Binary RBM:**

RBMs were first developed using binary units in both the visible and hidden layer. The corresponding energy function is defined as follows:

<!-- Equation labels as ordinary links -->
<div id="_auto3"></div>

$$
\begin{equation}
	E(\mathbf{x}, \mathbf{h}) = - \sum_i^M x_i a_i- \sum_j^N b_j h_j - \sum_{i,j}^{M,N} x_i w_{ij} h_j,
\label{_auto3} \tag{3}
\end{equation}
$$

where the binary values taken on by the nodes are most commonly 0 and 1.

**Gaussian-Binary RBM:**

Another varient is the RBM where the visible units are Gaussian while the hidden units remain binary:

<!-- Equation labels as ordinary links -->
<div id="_auto4"></div>

$$
\begin{equation}
	E(\mathbf{x}, \mathbf{h}) = \sum_i^M \frac{(x_i - a_i)^2}{2\sigma_i^2} - \sum_j^N b_j h_j - \sum_{i,j}^{M,N} \frac{x_i w_{ij} h_j}{\sigma_i^2}.
\label{_auto4} \tag{4}
\end{equation}
$$

## More about RBMs
1. Useful when we model continuous data (i.e., we wish $\mathbf{x}$ to be continuous)

2. Requires a smaller learning rate, since there's no upper bound to the value a component might take in the reconstruction

Other types of units include:
1. Softmax and multinomial units

2. Gaussian visible and hidden units

3. Binomial units

4. Rectified linear units

## Autoencoders: Overarching view

Autoencoders are artificial neural networks capable of learning
efficient representations of the input data (these representations are called codings)  without
any supervision (i.e., the training set is unlabeled). These codings
typically have a much lower dimensionality than the input data, making
autoencoders useful for dimensionality reduction.

More importantly, autoencoders act as powerful feature detectors, and
they can be used for unsupervised pretraining of deep neural networks.

Lastly, they are capable of randomly generating new data that looks
very similar to the training data; this is called a generative
model. For example, you could train an autoencoder on pictures of
faces, and it would then be able to generate new faces.  Surprisingly,
autoencoders work by simply learning to copy their inputs to their
outputs. This may sound like a trivial task, but we will see that
constraining the network in various ways can make it rather
difficult. For example, you can limit the size of the internal
representation, or you can add noise to the inputs and train the
network to recover the original inputs. These constraints prevent the
autoencoder from trivially copying the inputs directly to the outputs,
which forces it to learn efficient ways of representing the data. In
short, the codings are byproducts of the autoencoder’s attempt to
learn the identity function under some constraints.

[Video on autoencoders](https://www.coursera.org/lecture/building-deep-learning-models-with-tensorflow/autoencoders-1U4L3)

See also A. Geron's textbook, chapter 15.

## Bayesian Machine Learning

This is an important topic if we aim at extracting a probability
distribution. This gives us also a confidence interval and error
estimates.

Bayesian machine learning allows us to encode our prior beliefs about
what those models should look like, independent of what the data tells
us. This is especially useful when we don’t have a ton of data to
confidently learn our model.

[Video on Bayesian deep learning](https://www.youtube.com/watch?v=E1qhGw8QxqY&ab_channel=AndrewGordonWilson)

See also the [slides here](https://github.com/CompPhysics/MachineLearning/blob/master/doc/Articles/lec03.pdf).

## Reinforcement Learning

Reinforcement Learning (RL) is one of the most exciting fields of
Machine Learning today, and also one of the oldest. It has been around
since the 1950s, producing many interesting applications over the
years.

It studies
how agents take actions based on trial and error, so as to maximize
some notion of cumulative reward in a dynamic system or
environment. Due to its generality, the problem has also been studied
in many other disciplines, such as game theory, control theory,
operations research, information theory, multi-agent systems, swarm
intelligence, statistics, and genetic algorithms.

In March 2016, AlphaGo, a computer program that plays the board game
Go, beat Lee Sedol in a five-game match. This was the first time a
computer Go program had beaten a 9-dan (highest rank) professional
without handicaps. AlphaGo is based on deep convolutional neural
networks and reinforcement learning. AlphaGo’s victory was a major
milestone in artificial intelligence and it has also made
reinforcement learning a hot research area in the field of machine
learning.

[Lecture on Reinforcement Learning](https://www.youtube.com/watch?v=FgzM3zpZ55o&ab_channel=stanfordonline).

See also A. Geron's textbook, chapter 16.
## Transfer learning

The goal of transfer learning is to transfer the model or knowledge
obtained from a source task to the target task, in order to resolve
the issues of insufficient training data in the target task. The
rationality of doing so lies in that usually the source and target
tasks have inter-correlations, and therefore either the features,
samples, or models in the source task might provide useful information
for us to better solve the target task. Transfer learning is a hot
research topic in recent years, with many problems still waiting to be studied.

[Lecture on transfer learning](https://www.ias.edu/video/machinelearning/2020/0331-SamoryKpotufe).

## Adversarial learning

The conventional deep generative model has a potential problem: the
model tends to generate extreme instances to maximize the
probabilistic likelihood, which will hurt its performance. Adversarial
learning utilizes the adversarial behaviors (e.g., generating
adversarial instances or training an adversarial model) to enhance the
robustness of the model and improve the quality of the generated
data. In recent years, one of the most promising unsupervised learning
technologies, generative adversarial networks (GAN), has already been
successfully applied to image, speech, and text.

[Lecture on adversial learning](https://www.youtube.com/watch?v=CIfsB_EYsVI&ab_channel=StanfordUniversitySchoolofEngineering).

## Dual learning

Dual learning is a new learning paradigm, the basic idea of which is
to use the primal-dual structure between machine learning tasks to
obtain effective feedback/regularization, and guide and strengthen the
learning process, thus reducing the requirement of large-scale labeled
data for deep learning. The idea of dual learning has been applied to
many problems in machine learning, including machine translation,
image style conversion, question answering and generation, image
classification and generation, text classification and generation,
image-to-text, and text-to-image.

## Distributed machine learning

Distributed computation will speed up machine learning algorithms,
significantly improve their efficiency, and thus enlarge their
application. When distributed meets machine learning, more than just
implementing the machine learning algorithms in parallel is required.

## Meta learning

Meta learning is an emerging research direction in machine
learning. Roughly speaking, meta learning concerns learning how to
learn, and focuses on the understanding and adaptation of the learning
itself, instead of just completing a specific learning task. That is,
a meta learner needs to be able to evaluate its own learning methods
and adjust its own learning methods according to specific learning
tasks.

## The Challenges Facing Machine Learning

While there has been much progress in machine learning, there are also challenges.

For example, the mainstream machine learning technologies are
black-box approaches, making us concerned about their potential
risks. To tackle this challenge, we may want to make machine learning
more explainable and controllable. As another example, the
computational complexity of machine learning algorithms is usually
very high and we may want to invent lightweight algorithms or
implementations. Furthermore, in many domains such as physics,
chemistry, biology, and social sciences, people usually seek elegantly
simple equations (e.g., the Schrödinger equation) to uncover the
underlying laws behind various phenomena. In the field of machine
learning, can we reveal simple laws instead of designing more complex
models for data fitting? Although there are many challenges, we are
still very optimistic about the future of machine learning. As we look
forward to the future, here are what we think the research hotspots in
the next ten years will be.

## Explainable machine learning

Machine learning, especially deep learning, evolves rapidly. The
ability gap between machine and human on many complex cognitive tasks
becomes narrower and narrower. However, we are still in the very early
stage in terms of explaining why those effective models work and how
they work.

**What is missing: the gap between correlation and causation**. Standard Machine Learning is based on what e have called a frequentist approach.

Most
machine learning techniques, especially the statistical ones, depend
highly on correlations in data sets to make predictions and analyses. In
contrast, rational humans tend to reply on clear and trustworthy
causality relations obtained via logical reasoning on real and clear
facts. It is one of the core goals of explainable machine learning to
transition from solving problems by data correlation to solving
problems by logical reasoning. Bayesian Machine Learning is one of the exciting research directions in this field.

## Quantum machine learning

Quantum machine learning is an emerging interdisciplinary research
area at the intersection of quantum computing and machine learning.

Quantum computers use effects such as quantum coherence and quantum
entanglement to process information, which is fundamentally different
from classical computers. Quantum algorithms have surpassed the best
classical algorithms in several problems (e.g., searching for an
unsorted database, inverting a sparse matrix), which we call quantum
acceleration.

When quantum computing meets machine learning, it can be a mutually
beneficial and reinforcing process, as it allows us to take advantage
of quantum computing to improve the performance of classical machine
learning algorithms. In addition, we can also use the machine learning
algorithms (on classic computers) to analyze and improve quantum
computing systems.

[Lecture on Quantum ML](https://www.youtube.com/watch?v=Xh9pUu3-WxM&ab_channel=InstituteforPure%26AppliedMathematics%28IPAM%29).

[Read interview with Maria Schuld on her work on Quantum Machine Learning](https://physics.aps.org/articles/v13/179?utm_campaign=weekly&utm_medium=email&utm_source=emailalert). See also [her recent textbook](https://www.springer.com/gp/book/9783319964232).

## Quantum machine learning algorithms based on linear algebra

Many quantum machine learning algorithms are based on variants of
quantum algorithms for solving linear equations, which can efficiently
solve N-variable linear equations with complexity of O(log2 N) under
certain conditions. The quantum matrix inversion algorithm can
accelerate many machine learning methods, such as least square linear
regression, least square version of support vector machine, Gaussian
process, and more. The training of these algorithms can be simplified
to solve linear equations. The key bottleneck of this type of quantum
machine learning algorithms is data input—that is, how to initialize
the quantum system with the entire data set. Although efficient
data-input algorithms exist for certain situations, how to efficiently
input data into a quantum system is as yet unknown for most cases.

## Quantum reinforcement learning

In quantum reinforcement learning, a quantum agent interacts with the
classical environment to obtain rewards from the environment, so as to
adjust and improve its behavioral strategies. In some cases, it
achieves quantum acceleration by the quantum processing capabilities
of the agent or the possibility of exploring the environment through
quantum superposition. Such algorithms have been proposed in
superconducting circuits and systems of trapped ions.

## Quantum deep learning

Dedicated quantum information processors, such as quantum annealers
and programmable photonic circuits, are well suited for building deep
quantum networks. The simplest deep quantum network is the Boltzmann
machine. The classical Boltzmann machine consists of bits with tunable
interactions and is trained by adjusting the interaction of these bits
so that the distribution of its expression conforms to the statistics
of the data. To quantize the Boltzmann machine, the neural network can
simply be represented as a set of interacting quantum spins that
correspond to an adjustable Ising model. Then, by initializing the
input neurons in the Boltzmann machine to a fixed state and allowing
the system to heat up, we can read out the output qubits to get the
result.

## Social machine learning

Machine learning aims to imitate how humans
learn. While we have developed successful machine learning algorithms,
until now we have ignored one important fact: humans are social. Each
of us is one part of the total society and it is difficult for us to
live, learn, and improve ourselves, alone and isolated. Therefore, we
should design machines with social properties. Can we let machines
evolve by imitating human society so as to achieve more effective,
intelligent, interpretable “social machine learning”?

And much more.

## The last words?

Early computer scientist Alan Kay said, **The best way to predict the
future is to create it**. Therefore, all machine learning
practitioners, whether scholars or engineers, professors or students,
need to work together to advance these important research
topics. Together, we will not just predict the future, but create it.

## Best wishes to you all and thanks so much for your heroic efforts this semester

<!-- dom:FIGURE: [figures/Nebbdyr2.png, width=500 frac=0.6] -->
<!-- begin figure -->

<p></p>

<!-- end figure -->


# Heat transfer for Extended surfaces

Fins are widely used to increase heat transfer through an increase of the surface area exposed to convection and radiation heat transfer. The following shows the comparison between theory and (an almost realistic) simulation of a rectangular fin subjected to a convection flow, with characteristics $h$ and $T_\infty$. The fin material has a conductivity of $k$ assumed to be constant for the range of temperature of our problem

The theory starts with the geometry of the fin. Here we consider the simplest case, a rectangular thin. The cross-sectional area is $A_c=wt$, where $w$ is the width and $t$ the tickness. The perimeter of this area is $P=2(w+t)$. The length is $L$.

A control volume between $x$ and $x+\Delta x$ and bounded from the whole of cross sectional area $A_c$. If one assumes on any cross-sectional area temperature variation to be negligible, the problem reduces to the following ODE (derived in great details in your book).
$$
\frac{d^2T}{dx^2}-\frac{hP}{kA_c}\left(T(x)-T_\infty\right)=0
$$
and by operating the variable transformation $\theta(x)=\left(T(x)-T_\infty\right)$:
$$
\frac{d^2\theta}{dx^2}-m^2\theta=0 \text{ with }m^2=\frac{hP}{kA_c}
$$
The general solution is
$$
\theta(x)=C_1e^{+mx}+C_2e^{-mx}
$$
The constants are determined by the boundary conditions at

 $x=0$. Here we assume constant base temperature $T_b$ or $\theta_b=T_b-T_\infty$
$$
\theta_b=C_1+C_2
$$

 $x=L$. The solution for this boundary depends on the approximation we think we can make:

 Convection flow
$$
h\theta(L)=-k\left.\frac{d\theta}{dx}\right\vert_{x=L}
$$

 Adiabatic
$$
\left.\frac{d\theta}{dx}\right\vert_{x=L}=0
$$

 Constant temperature
$$
\theta(L)=T_L-T_\infty
$$

 Infinite fin ($L/t\gg 1$?)
$$
\theta(L)=0
$$

```python
%matplotlib inline

from IPython.display import clear_output

import schemdraw as schem
import schemdraw.elements as e

import matplotlib.pyplot as plt
import numpy as np
import math
import scipy.constants as sc

import sympy as sym

```

## Discretized heat equation for steady, pure conduction

Under the assumption of constant thermodynamic properties, the heat transport equation can be derived as:
$$
\rho C_p\left(\frac{\partial T}{\partial t}+\mathbf{u}.\boldsymbol{\nabla}T\right)=k\nabla^2T
$$
For a pure conduction (velocity vector $\mathbf{u}=\mathbf{0}$) and steady state $\partial T/\partial t=0$, the temperature field is the solution of:
$$
\nabla^2 T=0\Leftrightarrow \frac{\partial^2 T}{\partial x^2}+\frac{\partial^2 T}{\partial y^2}+\frac{\partial^2 T}{\partial z^2}=0
$$

This equation can be derived by using a 2D control volume of dimensions $\Delta x\times\Delta y$ and applying the conservation of energy and Fourier's law on the surface of the control volume.

Show that:

$$
\frac{k\Delta y}{\Delta x}\left(T_{i,j}-T_{i-1,j}\right)
-\frac{k\Delta y}{\Delta x}\left(T_{i+1,j}-T_{i,j}\right)
+\frac{k\Delta x}{\Delta y}\left(T_{i,j}-T_{i,j-1}\right)
-\frac{k\Delta x}{\Delta y}\left(T_{i,j+1}-T_{i,j}\right)=0
$$

Using Taylor series expansion, show that:
$$
\frac{\partial^2 T}{\partial x^2}=\frac{T_{i+1,j} - 2T_{i,j} + T_{i-1,j}}{\Delta x^2}
$$
and then show
$$
-\frac{k\Delta x}{\Delta y}T_{i,j-1}
-\frac{k\Delta x}{\Delta y}T_{i-1,j}
+\left(2\frac{k\Delta x}{\Delta y}+2\frac{k\Delta y}{\Delta x}\right)T_{i,j}
-\frac{k\Delta x}{\Delta y}T_{i+1,j}
-\frac{k\Delta x}{\Delta y}T_{i,j+1}=0
$$
$$
\Leftrightarrow\frac{\partial^2 T}{\partial x^2}+\frac{\partial^2 T}{\partial y^2}=0
$$

```python
def build_matrix(n,A,b,nx,ny,dx,dy,k_cond,h,alpha,beta,T_infty,Tiso):
    for j in range (1,ny-1):
        for i in range (1,nx-1):
            k = i + j * nx
            kim = k - 1
            kip = k + 1
            kjm = k - nx
            kjp = k + nx
            A[k, k] = k_cond*(2.*dx/dy+2.*dy/dx)
            A[k, kim] = -k_cond*dy/dx
            A[k, kip] = -k_cond*dy/dx
            A[k, kjm] = -k_cond*dx/dy
            A[k, kjp] = -k_cond*dx/dy

    i = 0
    j = 0
    k = i + j * nx
    kip = 1
    kjp = nx
    A[k,k] = 3.*k_cond*dy/dx+k_cond*dx/dy+alpha*h*dx
    A[k,kip] = -k_cond*dy/dx
    A[k,kjp] = -k_cond*dx/dy+beta*h*dx
    b[k] = 2.*k_cond*dy/dx*T_iso+h*dx*T_infty

    i = 0
    j = ny-1
    k = i + j * nx
    kim = k - 1
    kip = k + 1
    kjm = k - nx
    kjp = k + nx

    A[k,kjm] = -k_cond*dx/dy + beta*h*dx
    A[k,k] = 3.*k_cond*dy/dx+k_cond*dx/dy + alpha*h*dx
    A[k,kip] = -k_cond*dy/dx
    b[k] = 2.*k_cond*dy/dx*T_iso + h*dx*T_infty

    i = 0
    for j in range (1,ny-1):
        k = i + j * nx
        kim = k - 1
        kip = k + 1
        kjm = k - nx
        kjp = k + nx
        A[k,kjm] = -k_cond*dx/dy
        A[k,k] = 3.*k_cond*dy/dx+2.*k_cond*dx/dy
        A[k,kip] = -k_cond*dy/dx
        A[k,kjp] = -k_cond*dx/dy
        b[k] = 2.*k_cond*dy/dx*T_iso

    i = nx-1
    j = 0
    k = i + j * nx
    kim = k - 1
    kip = k + 1
    kjm = k - nx
    kjp = k + nx
    A[k,kim] = -k_cond*dy/dx+beta*h*dy
    A[k,k] = k_cond*dy/dx+k_cond*dx/dy+alpha*h*dy
    A[k,kjp] = -k_cond*dx/dy
    b[k] = +h*dy*T_infty

    i = nx-1
    j = ny-1
    k = i + j * nx
    kim = k - 1
    kip = k + 1
    kjm = k - nx
    kjp = k + nx
    A[k,kjm] = -k_cond*dx/dy
    A[k,kim] = -k_cond*dy/dx+beta*h*dy
    A[k,k] = k_cond*dy/dx+k_cond*dx/dy+alpha*h*dy
    b[k] = h*dy*T_infty

    i = nx-1
    for j in range (1,ny-1):
        k = i + j * nx
        kim = k - 1
        kip = k + 1
        kjm = k - nx
        kjp = k + nx
        A[k,kjm] = -k_cond*dx/dy
        A[k,kim] = -k_cond*dy/dx + beta*h*dy
        A[k,k] = k_cond*dy/dx+2.*k_cond*dx/dy + alpha*h*dy
        A[k,kjp] = -k_cond*dx/dy
        b[k] = h*dy*T_infty

    j = 0
    for i in range (1,nx-1):
        k = i + j * nx
        kim = k - 1
        kip = k + 1
        kjm = k - nx
        kjp = k + nx
        A[k,kim] = -k_cond*dy/dx
        A[k,k] = 2.*k_cond*dy/dx+k_cond*dx/dy + alpha*h*dx
        A[k,kip] = -k_cond*dy/dx
        A[k,kjp] = -k_cond*dx/dy + beta*h*dx
        b[k] = h*dx*T_infty

    j = ny-1
    for i in range (1,nx-1):
        k = i + j * nx
        kim = k - 1
        kip = k + 1
        kjm = k - nx
        kjp = k + nx
        A[k,kjm] = -k_cond*dx/dy+beta*h*dx
        A[k,kim] = -k_cond*dy/dx
        A[k,k] = 2.*k_cond*dy/dx+k_cond*dx/dy+alpha*h*dx
        A[k,kip] = -k_cond*dy/dx
        b[k] = h*dx*T_infty

```

A major difficulty of this code resides in the rearrangement of the matrix $T_{i,j}$ into the vector $T_k$ with $k=i+j.nx$. The matrix is now pentadiagonal with its two furthest diagonal at $\pm nx$ from the main diagonal

Boundary condition: Isothermal at the base, convection everywhere else.
$i=0,j=0$:
$$
k\frac{T_{0,0}-T_a}{\Delta x/2}\Delta y-k\frac{T_{1,0}-T_{0,0}}{\Delta x}\Delta y+h\Delta x\left(\alpha T_{0,0}+\beta T_{0,1}-T\infty\right)-k\frac{T_{0,1}-T_{0,0}}{\Delta y}\Delta x = 0
$$

$$\left(3\frac{k\Delta y}{\Delta x}+k\frac{\Delta x}{\Delta y}+\alpha h \Delta x\right)T_{0,0}
-\frac{k\Delta y}{\Delta x}T_{1,0}
+\left(-\frac{k\Delta x}{\Delta y}+\beta h \Delta x\right)T_{0,1}
=2\frac{k\Delta y}{\Delta x}T_a+h\Delta x T_\infty
$$

$i=0,j=ny-1$:
$$
k\frac{T_{0,ny-1}-T_a}{\Delta x/2}\Delta y-k\frac{T_{1,ny-1}-T_{0,ny-1}}{\Delta x}\Delta y +k\frac{T_{0,ny-1}-T_{0,ny-2}}{\Delta y}\Delta x +h\Delta x\left(\alpha T_{0,ny-1}+\beta T_{0,ny-2}-T_\infty\right) = 0
$$

$$
\left(-\frac{k\Delta x}{\Delta y}+\beta h\Delta x\right)T_{0,ny-2}+\left(3\frac{k\Delta y}{\Delta x}T+\frac{k\Delta x}{\Delta y}+\alpha h\Delta x\right)T_{0,ny-1}-\frac{k\Delta y}{\Delta x}T_{1,ny-1}=2\frac{k\Delta y}{\Delta x}T_a + h\Delta x T_\infty
$$

$i=0,j\in\left]0,ny-1\right[$:
$$
k\frac{T_{0,j}-T_a}{\Delta x/2}\Delta y-k\frac{T_{1,j}-T_{0,j}}{\Delta x}\Delta y +k\frac{T_{0,j}-T_{0,j-1}}{\Delta y}\Delta x -k\frac{T_{0,j+1}-T_{0,j}}{\Delta y}\Delta x = 0
$$

$$
-\frac{k\Delta x}{\Delta y}T_{0,j-1}
+\left(3\frac{k\Delta y}{\Delta x}+2\frac{k\Delta x}{\Delta y}\right)T_{0,j}
-\frac{k\Delta y}{\Delta x}T_{1,j}
-\frac{k\Delta x}{\Delta y}T_{0,j+1}=2\frac{k\Delta y}{\Delta x}T_a
$$

$i=nx-1,j=0$:
$$
k\frac{T_{nx-1,0}-T_{nx-2,0}}{\Delta x}\Delta y-h\Delta y\left(\alpha T_{nx-1,0}+\beta T_{nx-2,0}-T_\infty\right)-k\frac{T_{nx-1,1}-T_{nx-1,0}}{\Delta y}\Delta x = 0
$$

$$
\left(-\frac{k\Delta y}{\Delta x}-\beta h \Delta y\right)T_{nx-2,0}+
\left(\frac{k\Delta y}{\Delta x}+k\frac{\Delta x}{\Delta y}-\alpha h \Delta y\right)T_{nx-1,0}-\frac{k\Delta x}{\Delta y}T_{nx-1,1}=-h\Delta y T_\infty
$$

$i=nx-1,j=ny-1$:
$$
k\frac{T_{nx-1,ny-1}-T_{nx-2,ny-1}}{\Delta x}\Delta y+h\Delta y\left(\alpha T_{nx-1,ny-1}+\beta T_{nx-2,ny-1}-T_\infty\right)+k\frac{T_{nx-1,ny-1}-T_{nx-1,ny-2}}{\Delta y}\Delta x = 0
$$

$$
-\frac{k\Delta x}{\Delta y}T_{nx-1,ny-2}
+\left(-\frac{k\Delta y}{\Delta x}+\beta h\Delta y\right)T_{nx-2,ny-1}+
\left(\frac{k\Delta y}{\Delta x}+k\frac{\Delta x}{\Delta y}+\alpha h \Delta y\right)T_{nx-1,ny-1}
=h\Delta yT_\infty
$$

$i=nx-1,j\in\left]0,ny-1\right[$:
$$
k\frac{T_{nx-1,j}-T_{nx-2,j}}{\Delta x}\Delta y+h\Delta y\left(\alpha T_{nx-1,j}+\beta T_{nx-2,j}-T_\infty\right)
+k\frac{T_{nx-1,j}-T_{nx-1,j-1}}{\Delta y}\Delta x-k\frac{T_{nx-1,j+1}-T_{nx-1,j}}{\Delta y}\Delta x = 0
$$

$$
-\frac{k\Delta x}{\Delta y}T_{nx-1,j-1}
+\left(-\frac{k\Delta y}{\Delta x}+\beta h \Delta y\right)T_{nx-2,j}+
\left(\frac{k\Delta y}{\Delta x}+2k\frac{\Delta x}{\Delta y}+\alpha h \Delta y\right)T_{nx-1,j}-\frac{k\Delta x}{\Delta y}T_{nx-1,j+1}=h\Delta y T_\infty
$$

$0<i<nx-1,j=0$:
$$
k\frac{T_{i,0}-T_{i-1,0}}{\Delta x}\Delta y-k\frac{T_{i+1,0}-T_{i,0}}{\Delta x}\Delta y
+h\Delta x\left(\alpha T_{i,0}+\beta T_{i,1}-T_\infty\right)-k\frac{T_{i,1}-T_{i,0}}{\Delta y}\Delta x = 0
$$

$$
-\frac{k\Delta y}{\Delta x}T_{i-1,0}+\left(2\frac{k\Delta y}{\Delta x}+\frac{k\Delta x}{\Delta y}+\alpha h \Delta x\right)T_{i,0}
-\frac{k\Delta y}{\Delta x}T_{i+1,0}
+\left(-\frac{k\Delta x}{\Delta y}+\beta h\Delta x\right)T_{i,1} = h\Delta x T_\infty
$$

$0<i<nx-1,j=ny-1$:
$$
k\frac{T_{i,ny-1}-T_{i-1,ny-1}}{\Delta x}\Delta y-k\frac{T_{i+1,ny-1}-T_{i,ny-1}}{\Delta x}\Delta y +k\frac{T_{i,ny-1}-T_{i,ny-2}}{\Delta y}\Delta x +h\Delta x\left(\alpha T_{i,ny-1}+\beta T_{i,ny-2}-T_\infty\right) = 0
$$

$$
\left(-\frac{k\Delta x}{\Delta y}+\beta h\Delta x\right)T_{i,ny-2}-\frac{k\Delta y}{\Delta x}T_{i-1,ny-1}+\left(2\frac{k\Delta y}{\Delta x}+\frac{k\Delta x}{\Delta y}+\alpha h \Delta x\right)T_{i,ny-1}-\frac{k\Delta y}{\Delta x}T_{i+1,ny-1} = h\Delta x T_\infty
$$

```python
def fin(k_cond,T_iso,T_infty,h,lx,ly,nx,ny):

    dx = lx/(nx)
    dy = ly/(ny)
    n = nx*ny
    alpha = 3./2.
    beta = -1./2.
    t = ly
    w = 1 #m
    A_c = t*w
    P = 2.*(t+w)
    m = np.sqrt(h*P/(k_cond*A_c))
    L = lx
    theta_b = T_iso - T_infty

    A = np.zeros((n,n), dtype = np.float)
    b = np.zeros((n,1), dtype = np.float)
    Tn = np.zeros((nx,ny), dtype = np.float)
    theta_comp = np.zeros((nx,ny))
    theta_conv = np.zeros(nx)
    theta_inf = np.zeros(nx)
    Xn = np.zeros((nx,ny), dtype = np.float)
    Yn = np.zeros((nx,ny), dtype = np.float)

    x = np.array([(i+0.5)*dx for i in range(nx)])
    y = np.array([(j+0.5)*dy for j in range(ny)])

    for j in range (ny):
        for i in range (nx):
            Xn[i,j] = x[i]
            Yn[i,j] = y[j]

    build_matrix(n,A,b,nx,ny,dx,dy,k_cond,h,alpha,beta,T_infty,T_iso)

    T = np.linalg.solve(A, b)

    i = 0
    j = 0
    for k in range (n):
        i = k - j*nx
        if (i > nx-1):
            j += 1
            i = 0
        Tn[i,j] = T[k]
        theta_comp[i,j] = Tn[i,j] - T_infty

    for i in range (nx):
        # Temperature distribution for an infinite fin
        theta_inf[i] = np.exp(-m*x[i])
        # Temperature for convection boundary condition at the tip
        theta_conv[i] = (np.cosh(m*(L-x[i]))+(h/(m*k_cond))*np.sinh(m*(L-x[i]))) \
                        /(np.cosh(m*L)+(h/(m*k_cond))*np.sinh(m*L))
    theta_conv *= theta_b
    theta_inf *= theta_b
    return x,y,dx,dy,Xn,Yn,Tn,theta_comp,theta_conv,theta_inf,m*L
```

```python
import numpy as np
##############################
#        Parameters          #
##############################
k_cond = 180.
nx = 100
ny = 20

lx = 0.01
ly = 0.005

n = nx*ny

T_iso = 100.
T_infty = 25.
h = 100. #W/m^2.K

x,y,dx,dy,Xn,Yn,Tn,theta_comp,theta_conv,theta_inf,mL = \
        fin(k_cond,T_iso,T_infty,h,lx,ly,nx,ny)

```

```python
fig = plt.figure(num=None, figsize=(6, 4), dpi=160, facecolor='w', edgecolor='k')
ax = fig.add_subplot(211)
im = ax.contourf(Xn, Yn, Tn, 20, cmap='jet')
ax.set_aspect('equal')
#ax.set_xlabel('$x$ (m)')
ax.set_ylabel('$y$ (m)')
fig.colorbar(im, ax = ax, orientation = 'horizontal')
bx = fig.add_subplot(212)
bx.plot(x, theta_comp[:,0], label='Computed at $y=0$')
bx.plot(x, theta_comp[:,ny//2], label='Computed at $y=t/2$')
bx.plot(x, theta_conv,'--', label='tip convection b.c.')
bx.plot(x, theta_inf,'-', label='Infinite fin sol.')
bx.set_xlabel('$x$ (m)')
bx.set_ylabel(r'$\theta$ ($^\circ$C)')
bx.legend(loc='upper center', bbox_to_anchor=(0.5, -0.5),
          fancybox=True, shadow=True, ncol=5)

heat_rate = 0.

heat_rate = np.sum(-k_cond*(Tn[0,:]-T_iso)/(dx/2.)*dy)
print('heat rate= %4.1f W/m' %heat_rate)
print('mL= %2.3f' %mL)
```

```python
print('error:',np.mean(theta_comp[-1,:])/T_infty)
```

    error: 0.09950832845317478

```python

```

```python

```


# Free Body Diagram for particles

Renato Naville Watanabe

```python
import numpy as np
import matplotlib.pyplot as plt

%matplotlib notebook
```

### Steps to draw a free-body diagram

1 - Draw separately each object considered in the problem. How you separate depends on what questions you want to answer.

2 - Identify the forces acting on each object. If you are analyzing more than one object, remember the third Newton law (action and reaction), and identify where the reaction of a force is being applied.

3 - Draw all the identified forces, representing them as vectors. The vectors should be represented with the origin in the object. In the case of particles, the origin should be in the center of the particle.

4 - If necessary, you should represent the reference frame in the free-body diagram.

5 - After this, you can solve the problem using the Second Newton Law (see, e.g,  [Newton Laws](https://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/Notebooks/newtonLawForParticles.ipynb)) to find the motion of the particle.

## Basic element and forces

### Spring

Is an element used to represent a force proportional to some length or displacement. It produces a force in the same direction of the vector linking the spring extremities and opposite to its length or displacement from an equilibrium length. Frequently it has a linear relation, but it could be nonlinear as well. The force exerted by the spring in one of the extremities is:

\begin{equation}
\vec{\bf{F}} = - k(||\vec{\bf{r}}||-l_0)\frac{\vec{\bf{r}}}{||\vec{\bf{r}}||} = -k\vec{\bf{r}} +kl_0\frac{\vec{\bf{r}}}{||\vec{\bf{r}}||} = -k\left(1-\frac{l_0}{||\vec{\bf{r}}||}\right)\vec{\bf{r}}
\end{equation}

where $\vec{\bf{r}}$ is the vector linking the extremity applying the force to the other extremity and $l_0$ is the equilibrium length of the spring.

Since the spring element is a massless element, the force in  both extremities have the same absolute value and opposite directions.

### Damping

Is an element used to represent a force proportional to the velocity of displacement.  It produces a force in the opposite direction of its velocity.

Frequently it has a linear relation, but it could be nonlinear as well. The force exerted by the damping element in one of its extremities is:

\begin{equation}
\vec{\bf{F}} = - b||\vec{\bf{v}}||\frac{\vec{\bf{v}}}{||\vec{\bf{v}}||} = -b\vec{\bf{v}} = -b\frac{d\vec{\bf{r}}}{dt}
\end{equation}

where $\vec{\bf{r}}$ is the vector linking the extremity applying the force to the other extremity.

For the same reason of the spring, the force in  both extremities have the same absolute value and opposite directions.

### Gravity

The gravity force acts on two masses, each one atracting each other:

\begin{equation}
\vec{{\bf{F}}} = - G\frac{m_1m_2}{||\vec{\bf{r}}||^2}\frac{\vec{\bf{r}}}{||\vec{\bf{r}}||}
\end{equation}

where  $G = 6.67.10^{−11} Nm^2/kg^2$ and $\vec{\bf{r}}$ is a vector with length equal to the distance between the masses and directing towards the other mass. Note the forces acting on each mass have the same absolute value.

Since the mass of the Earth is $m_1=5.9736×10^{24}kg$ and its radius is 6.371×10$^6$ m (see [this notebook](https://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/Notebooks/KineticsFundamentalConcepts.ipynb), for details), the gravity force on Earth is:

\begin{equation}
\vec{{\bf{F}}} = m\vec{\bf{g}}
\end{equation}

with the absolute value of $\vec{\bf{g}}$ approximately equal to 9.81 $m/s^2$,  and point towards the center of Earth.

## Examples of free-body diagram

Below, will be shown some examples of how to draw the free-body diagram and obtain the motion equations to solve the problems.

### 1) No force acting on the particle

The most trivial situation is a particle with no force acting on it.

The free-body diagram is below, with no force vectors acting on the particle.

<figure>

In this situation, the resultant force is:

\begin{equation}
\vec{\bf{F}} = \vec{\bf{0}}
\end{equation}

And the second Newton law for this particle is:

\begin{equation}
m\frac{d^2\vec{\bf{r}}}{dt^2} = \vec{\bf{0}} \rightarrow \frac{d^2\vec{\bf{r}}}{dt^2} = \vec{\bf{0}}
\end{equation}

The motion of of the particle can be found by integrating twice both times, getting the following:

\begin{equation}
\vec{\bf{r}} = \vec{\bf{v_0}}t + \vec{\bf{r0}}
\end{equation}

The particle continues to change its position with the same velocity it was at the beginning of the analysis. This could be predicted by the first Newton law.

### 2) Gravity force acting on the particle

Now, we will consider a ball with the gravity force acting on it. The free-body diagram is depicted below.

<figure>

The only force acting on the ball is the gravitational force:

\begin{equation}
\hat{\bf{F_g}} = - mg \hat{\bf{j}}
\end{equation}

So, we write the Second Newton Law:

\begin{equation}
\hat{\bf{F_g}} = m \frac{d^2\vec{\bf{r}}}{dt^2} \rightarrow - mg \hat{\bf{j}} = m \frac{d^2\vec{\bf{r}}}{dt^2} \rightarrow - g \hat{\bf{j}} =\frac{d^2\vec{\bf{r}}}{dt^2}
\end{equation}

Now, we can separate the equation in two components (x and y):

\begin{equation}
0 = \frac{d^2x}{dt^2}
\end{equation}

and

\begin{equation}
- g = \frac{d^2y}{dt^2}
\end{equation}

These equations were solved in detail in [this Notebook about Newton laws](https://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/Notebooks/newtonLawForParticles.ipynb).

### 3) Ground reaction force

Now, we will analyze the situation of a particle in contact with the ground. To simplify the analysis, only the vertical movement will be considered.

<figure>

The forces acting on the particle are the ground reaction force (often called as normal force) and the gravity force. The free-body diagram of the particle is below:

<figure>

So, the resultant force in the particle is:

\begin{equation}
    \vec{\bf{F}} = \overrightarrow{\bf{GRF}} + m\vec{\bf{g}} = \overrightarrow{\bf{GRF}} - mg\hat{\bf{j}}
\end{equation}

Considering only the y direction:

\begin{equation}
    F = GRF - mg
\end{equation}

Applying the second Newton law to the particle:

\begin{equation}
    m \frac{d^2y}{dt^2} = GRF - mg
\end{equation}

Note that since we have no information about how the force GRF varies along time, we cannot solve this equation. To find the position of the particle along time, one would have to measure the ground reaction force. See [the notebook on Vertical jump](http://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/notebooks/VerticalJump.ipynb) for an application of this model.

## 4) Linear spring in horizontal movement

The example below is mass attached to a spring. The other extremity of the spring is fixed.

<figure>

The only force force acting on the mass is from the spring. Below is the free-body diagram from the mass.

<figure>

Since the movement is horizontal, we can neglect the gravity force.

\begin{equation}
    \vec{\bf{F}} = -k\left(1-\frac{l_0}{||\vec{\bf{r}}||}\right)\vec{\bf{r}}
\end{equation}

Applying the second Newton law to the mass:

\begin{equation}
    m\frac{d^2\vec{\bf{r}}}{dt^2} = -k\left(1-\frac{l_0}{||\vec{\bf{r}}||}\right)\vec{\bf{r}} \rightarrow \frac{d^2\vec{\bf{r}}}{dt^2} = -\frac{k}{m}\left(1-\frac{l_0}{||\vec{\bf{r}}||}\right)\vec{\bf{r}}
\end{equation}

Since the movement is unidimensional, we can deal with it scalarly:

\begin{equation}
    \frac{d^2x}{dt^2} = -\frac{k}{m}\left(1-\frac{l_0}{x}\right)x = -\frac{k}{m}(x-l_0)
\end{equation}

To solve this equation numerically, we must break the equations into two first-order differential equation:

\begin{equation}
    \frac{dv_x}{dt} =  -\frac{k}{m}(x-l_0)
\end{equation}

\begin{equation}
    \frac{dx}{dt} =  v_x
\end{equation}

In the numerical solution below, we will use $k = 40 N/m$, $m = 2 kg$, $l_0 = 0.5 m$ and the mass starts from the position $x = 0.8m$ and at rest.

```python
k = 40
m = 2
l0 = 0.5
x0 = 0.8
v0 = 0

x = x0
v = v0

dt = 0.001
t = np.arange(0, 3, dt)

r = np.array([x])

for i in t[1:]:
    dxdt = v
    dvxdt = -k/m*(x-l0)
    x = x + dt*dxdt
    v = v + dt*dvxdt
    r = np.vstack((r,np.array([x])))

plt.figure()
plt.plot(t,r)
plt.xlabel('t(s)')
plt.ylabel('x(m)')
plt.title('Spring displacement')
plt.show()
```

### 5) Linear spring in bidimensional movement in horizontal plane

This example has two masses attached to the spring. To solve the motion of both masses, we must draw a free-body diagram for each one of the masses.

<figure>

The only force acting on each mass is the force due to the spring. Since the movement is happening in the horizontal plane, the gravity force can be neglected.

<figure>

So, the forces acting on mass 1 is:

\begin{equation}
    \vec{\bf{F_1}} = k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}
\end{equation}

and the forces acting on mass 2 is:

\begin{equation}
    \vec{\bf{F_2}} =k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}
\end{equation}

Applying the second Newton law for the masses:

\begin{equation}
     m_1\frac{d^2\vec{\bf{r_1}}}{dt^2} = k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||} \rightarrow \frac{d^2\vec{\bf{r_1}}}{dt^2} = -\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_1}}+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_2}} \rightarrow \frac{d^2x_1\hat{\bf{i}}}{dt^2}+\frac{d^2y_1\hat{\bf{j}}}{dt^2} = -\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_1\hat{\bf{i}}+y_1\hat{\bf{j}})+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_2\hat{\bf{i}}+y_2\hat{\bf{j}})
\end{equation}

\begin{equation}
     m_2\frac{d^2\vec{\bf{r_2}}}{dt^2} = k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||} \rightarrow \frac{d^2\vec{\bf{r_2}}}{dt^2} = -\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_2}}+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_1}} \rightarrow \frac{d^2x_2\hat{\bf{i}}}{dt^2}+\frac{d^2y_2\hat{\bf{j}}}{dt^2} = -\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_2\hat{\bf{i}}+y_2\hat{\bf{j}})+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_1\hat{\bf{i}}+y_1\hat{\bf{j}})
\end{equation}

Now, we can separate the equations for each of the coordinates:

\begin{equation}
    \frac{d^2x_1}{dt^2} = -\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)x_1+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)x_2=-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_1-x_2)
\end{equation}

\begin{equation}
    \frac{d^2y_1}{dt^2} = -\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)y_1+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)y_2=-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_1-y_2)
\end{equation}

\begin{equation}
    \frac{d^2x_2}{dt^2} = -\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)x_2+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)x_1=-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_2-x_1)
\end{equation}

\begin{equation}
    \frac{d^2y_2}{dt^2} = -\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)y_2+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)y_1=-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_2-y_1)
\end{equation}

To solve these equations numerically, you must break these equations into first-order  equations:

\begin{equation}
    \frac{dv_{x_1}}{dt} = -\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_1-x_2)
\end{equation}

\begin{equation}
    \frac{dv_{y_1}}{dt} = -\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_1-y_2)
\end{equation}

\begin{equation}
    \frac{dv_{x_2}}{dt} = -\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_2-x_1)
\end{equation}

\begin{equation}
    \frac{dv_{y_2}}{dt} = -\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_2-y_1)
\end{equation}

\begin{equation}
    \frac{dx_1}{dt} = v_{x_1}
\end{equation}

\begin{equation}
    \frac{dy_1}{dt} = v_{y_1}
\end{equation}

\begin{equation}
    \frac{dx_2}{dt} = v_{x_2}
\end{equation}

\begin{equation}
    \frac{dy_2}{dt} = v_{y_2}
\end{equation}

Note that if you did not wanted to know the details about the motion of each mass, but only the motion of the center of mass of the masses-spring system, you could have modeled the whole system as a single particle.

To solve the equations numerically, we will use the $m_1=1 kg$, $m_2 = 2 kg$, $l_0 = 0.5 m$, $k = 90 N/m$ and $x_{1_0} = 0 m$, $x_{2_0} = 0 m$, $y_{1_0} = 1 m$, $y_{2_0} = -1 m$, $v_{x1_0} = -2 m/s$, $v_{x2_0} = 0 m/s$, $v_{y1_0} = 0 m/s$, $v_{y2_0} = 0 m/s$.

```python
x01 = 0
y01= 0.5
x02 = 0
y02 = -0.5
vx01 = 0.1
vy01 = 0
vx02 = -0.1
vy02 = 0

x1= x01
y1 = y01
x2= x02
y2 = y02
vx1= vx01
vy1 = vy01
vx2= vx02
vy2 = vy02
r1 = np.array([x1,y1])
r2 = np.array([x2,y2])

k = 30
m1 = 1
m2 = 1
l0 = 0.5

dt = 0.0001
t = np.arange(0,5,dt)

for i in t[1:]:

    dvx1dt = -k/m1*(x1-x2)*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))
    dvx2dt = -k/m2*(x2-x1)*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))
    dvy1dt = -k/m1*(y1-y2)*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))
    dvy2dt = -k/m2*(y2-y1)*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))

    dx1dt = vx1
    dx2dt = vx2
    dy1dt = vy1
    dy2dt = vy2

    x1 = x1 + dt*dx1dt
    x2 = x2 + dt*dx2dt
    y1 = y1 + dt*dy1dt
    y2 = y2 + dt*dy2dt

    vx1 = vx1 + dt*dvx1dt
    vx2 = vx2 + dt*dvx2dt
    vy1 = vy1 + dt*dvy1dt
    vy2 = vy2 + dt*dvy2dt

    r1 = np.vstack((r1,np.array([x1,y1])))
    r2 = np.vstack((r2,np.array([x2,y2])))

springLength = np.sqrt((r1[:,0]-r2[:,0])**2+(r1[:,1]-r2[:,1])**2)
plt.figure()
plt.plot(t, springLength)
plt.xlabel('t(s)')
plt.ylabel('Spring length (m)')
plt.show()

```

### 6)Particle with gravity and linear air resistance

Below is the free-body diagram of a particle with the gravity force and a linear drag force due to the air resistance.

<figure>

the forces being applied in the ball are:

\begin{equation}
\vec{\bf{F}} = -mg \hat{\bf{j}} - b\vec{\bf{v}} = -mg \hat{\bf{j}} - b\frac{d\vec{\bf{r}}}{dt} = -mg \hat{\bf{j}} - b\left(\frac{dx}{dt}\hat{\bf{i}}+\frac{dy}{dt}\hat{\bf{j}}\right) = - b\frac{dx}{dt}\hat{\bf{i}} - \left(mg + b\frac{dy}{dt}\right)\hat{\bf{j}}
\end{equation}

Writing down the Second Newton Law:

\begin{equation}
\vec{\bf{F}} = m \frac{d^2\vec{\bf{r}}}{dt^2} \rightarrow - b\frac{dx}{dt}\hat{\bf{i}} - \left(mg + b\frac{dy}{dt}\right)\hat{\bf{j}} = m\left(\frac{d^2x}{dt^2}\hat{\bf{i}}+\frac{d^2y}{dt^2}\hat{\bf{j}}\right)
\end{equation}

Now, we can separate into one equation for each coordinate:

\begin{equation}
- b\frac{dx}{dt} = m\frac{d^2x}{dt^2} -\rightarrow \frac{d^2x}{dt^2} = -\frac{b}{m} \frac{dx}{dt}
\end{equation}

\begin{equation}
-mg - b\frac{dy}{dt} = m\frac{d^2y}{dt^2} \rightarrow \frac{d^2y}{dt^2} = -\frac{b}{m}\frac{dy}{dt} - g
\end{equation}

These equations were solved  in [this notebook](https://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/Notebooks/newtonLawForParticles.ipynb).

### 7) Particle with gravity and nonlinear air resistance

Below, is the free-body diagram of a particle with the gravity force and a drag force due to the air resistance proportional to the square of the particle velocity.

<figure>

The forces being applied in the ball are:

\begin{equation}
\vec{\bf{F}} = -mg \hat{\bf{j}} - bv^2\hat{\bf{e_t}} = -mg \hat{\bf{j}} - b (v_x^2+v_y^2) \frac{v_x\hat{\bf{i}}+v_y\hat{\bf{j}}}{\sqrt{v_x^2+v_y^2}} =   -mg \hat{\bf{j}} - b \sqrt{v_x^2+v_y^2} \,(v_x\hat{\bf{i}}+v_y\hat{\bf{j}}) =  -mg \hat{\bf{j}} - b \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\left(\frac{dx}{dt} \hat{\bf{i}}+\frac{dy}{dt}\hat{\bf{j}}\right)
\end{equation}

Writing down the Second Newton Law:

\begin{equation}
\vec{\bf{F}} = m \frac{d^2\vec{\bf{r}}}{dt^2} \rightarrow -mg \hat{\bf{j}} - b \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\left(\frac{dx}{dt} \hat{\bf{i}}+\frac{dy}{dt}\hat{\bf{j}}\right) = m\left(\frac{d^2x}{dt^2}\hat{\bf{i}}+\frac{d^2y}{dt^2}\hat{\bf{j}}\right)
\end{equation}

Now, we can separate into one equation for each coordinate:

\begin{equation}
- b \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\frac{dx}{dt} = m\frac{d^2x}{dt^2} \rightarrow \frac{d^2x}{dt^2} = - \frac{b}{m} \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\frac{dx}{dt}
\end{equation}

\begin{equation}
-mg - b \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\frac{dy}{dt} = m\frac{d^2y}{dt^2} \rightarrow \frac{d^2y}{dt^2} = - \frac{b}{m} \sqrt{\left(\frac{dx}{dt} \right)^2+\left(\frac{dy}{dt} \right)^2} \,\frac{dy}{dt} -g
\end{equation}

These equations were solved numerically in [this notebook](https://nbviewer.jupyter.org/github/BMClab/bmc/blob/master/Notebooks/newtonLawForParticles.ipynb).

## 8) Linear spring and damping on bidimensional horizontal  movement

This situation is very similar to the example of horizontal movement with one spring and two masses, with a damper added in parallel to the spring.

<figure>

Now, the forces acting on each mass are the force due to the spring and the force due to the damper.

<figure>

So, the forces acting on mass 1 is:

\begin{equation}
    \vec{\bf{F_1}} = b\frac{d(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{dt} +  k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||} =  b\frac{d(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{dt} +  k\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(\vec{\bf{r_2}}-\vec{\bf{r_1}})
\end{equation}

and the forces acting on mass 2 is:

\begin{equation}
    \vec{\bf{F_2}} = b\frac{d(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{dt} +  k\left(||\vec{\bf{r_2}}-\vec{\bf{r_1}}||-l_0\right)\frac{(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{||\vec{\bf{r_1}}-\vec{\bf{r_2}}||}= b\frac{d(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{dt} +  k\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(\vec{\bf{r_1}}-\vec{\bf{r_2}})
\end{equation}

Applying the second Newton law for the masses:

\begin{equation}
     m_1\frac{d^2\vec{\bf{r_1}}}{dt^2} = b\frac{d(\vec{\bf{r_2}}-\vec{\bf{r_1}})}{dt}+k\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(\vec{\bf{r_2}}-\vec{\bf{r_1}})
    \end{equation}

\begin{equation}
     \frac{d^2\vec{\bf{r_1}}}{dt^2} = -\frac{b}{m_1}\frac{d\vec{\bf{r_1}}}{dt} -\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_1}} + \frac{b}{m_1}\frac{d\vec{\bf{r_2}}}{dt}+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_2}}
\end{equation}

\begin{equation}
     \frac{d^2x_1\hat{\bf{i}}}{dt^2}+\frac{d^2y_1\hat{\bf{j}}}{dt^2} = -\frac{b}{m_1}\left(\frac{dx_1\hat{\bf{i}}}{dt}+\frac{dy_1\hat{\bf{j}}}{dt}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_1\hat{\bf{i}}+y_1\hat{\bf{j}})+\frac{b}{m_1}\left(\frac{dx_2\hat{\bf{i}}}{dt}+\frac{dy_2\hat{\bf{j}}}{dt}\right)+\frac{k}{m_1}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_2\hat{\bf{i}}+y_2\hat{\bf{j}}) = -\frac{b}{m_1}\left(\frac{dx_1\hat{\bf{i}}}{dt}+\frac{dy_1\hat{\bf{j}}}{dt}-\frac{dx_2\hat{\bf{i}}}{dt}-\frac{dy_2\hat{\bf{j}}}{dt}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_1\hat{\bf{i}}+y_1\hat{\bf{j}}-x_2\hat{\bf{i}}-y_2\hat{\bf{j}})
\end{equation}

\begin{equation}
     m_2\frac{d^2\vec{\bf{r_2}}}{dt^2} = b\frac{d(\vec{\bf{r_1}}-\vec{\bf{r_2}})}{dt}+k\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(\vec{\bf{r_1}}-\vec{\bf{r_2}})
\end{equation}

\begin{equation}
     \frac{d^2\vec{\bf{r_2}}}{dt^2} = -\frac{b}{m_2}\frac{d\vec{\bf{r_2}}}{dt} -\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_2}} + \frac{b}{m_2}\frac{d\vec{\bf{r_1}}}{dt}+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)\vec{\bf{r_1}}
\end{equation}

\begin{equation}
    \frac{d^2x_2\hat{\bf{i}}}{dt^2}+\frac{d^2y_2\hat{\bf{j}}}{dt^2} = -\frac{b}{m_2}\left(\frac{dx_2\hat{\bf{i}}}{dt}+\frac{dy_2\hat{\bf{j}}}{dt}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_2\hat{\bf{i}}+y_2\hat{\bf{j}})+\frac{b}{m_2}\left(\frac{dx_1\hat{\bf{i}}}{dt}+\frac{dy_1\hat{\bf{j}}}{dt}\right)+\frac{k}{m_2}\left(1-\frac{l_0}{||\vec{\bf{r_2}}-\vec{\bf{r_1}}||}\right)(x_1\hat{\bf{i}}+y_1\hat{\bf{j}})=-\frac{b}{m_2}\left(\frac{dx_2\hat{\bf{i}}}{dt}+\frac{dy_2\hat{\bf{j}}}{dt}-\frac{dx_1\hat{\bf{i}}}{dt}-\frac{dy_1\hat{\bf{j}}}{dt}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_2\hat{\bf{i}}+y_2\hat{\bf{j}}-x_1\hat{\bf{i}}-y_1\hat{\bf{j}})
\end{equation}

Now, we can separate the equations for each of the coordinates:

\begin{equation}
    \frac{d^2x_1}{dt^2} = -\frac{b}{m_1}\left(\frac{dx_1}{dt}-\frac{dx_2}{dt}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_1-x_2)
\end{equation}

\begin{equation}
    \frac{d^2y_1}{dt^2} = -\frac{b}{m_1}\left(\frac{dy_1}{dt}-\frac{dy_2}{dt}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_1-y_2)
\end{equation}

\begin{equation}
    \frac{d^2x_2}{dt^2} = -\frac{b}{m_2}\left(\frac{dx_2}{dt}-\frac{dx_1}{dt}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_2-x_1)
\end{equation}

\begin{equation}
    \frac{d^2y_2}{dt^2} = -\frac{b}{m_2}\left(\frac{dy_2}{dt}-\frac{dy_1}{dt}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_2-y_1)
\end{equation}

If you want to solve these equations numerically, you must break these equations into first-order  equations:

\begin{equation}
    \frac{dv_{x_1}}{dt} = -\frac{b}{m_1}\left(v_{x_1}-v_{x_2}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_1-x_2)
\end{equation}

\begin{equation}
    \frac{dv_{y_1}}{dt} =  -\frac{b}{m_1}\left(v_{y_1}-v_{y_2}\right)-\frac{k}{m_1}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_1-y_2)
\end{equation}

\begin{equation}
    \frac{dv_{x_2}}{dt} = -\frac{b}{m_2}\left(v_{x_2}-v_{x_1}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(x_2-x_1)
\end{equation}

\begin{equation}
    \frac{dv_{y_2}}{dt} = -\frac{b}{m_2}\left(v_{y_2}-v_{y_1}\right)-\frac{k}{m_2}\left(1-\frac{l_0}{\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}}\right)(y_2-y_1)
\end{equation}

\begin{equation}
    \frac{dx_1}{dt} = v_{x_1}
\end{equation}

\begin{equation}
    \frac{dy_1}{dt} = v_{y_1}
\end{equation}

\begin{equation}
    \frac{dx_2}{dt} = v_{x_2}
\end{equation}

\begin{equation}
    \frac{dy_2}{dt} = v_{y_2}
\end{equation}

To solve the equations numerically, we will use the $m_1=1 kg$, $m_2 = 2 kg$, $l_0 = 0.5 m$, $k = 10 N/m$, $b = 0.6 Ns/m$ and $x_{1_0} = 0 m$, $x_{2_0} = 0 m$, $y_{1_0} = 1 m$, $y_{2_0} = -1 m$, $v_{x1_0} = -2 m/s$, $v_{x2_0} = 1 m/s$, $v_{y1_0} = 0 m/s$, $v_{y2_0} = 0 m/s$.

```python
x01 = 0
y01= 1
x02 = 0
y02 = -1

vx01 = -2
vy01 = 0
vx02 = 1
vy02 = 0

x1= x01
y1 = y01
x2= x02
y2 = y02
vx1= vx01
vy1 = vy01
vx2= vx02
vy2 = vy02
r1 = np.array([x1,y1])
r2 = np.array([x2,y2])

k = 10
m1 = 1
m2 = 2
b = 0.6
l0 = 0.5

dt = 0.001
t = np.arange(0,5,dt)

for i in t[1:]:
    dvx1dt = -b/m1*(vx1-vx2) -k/m1*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))*(x1-x2)
    dvx2dt = -b/m2*(vx2-vx1) -k/m2*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))*(x2-x1)
    dvy1dt = -b/m1*(vy1-vy2) -k/m1*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))*(y1-y2)
    dvy2dt = -b/m2*(vy2-vy1) -k/m2*(1-l0/np.sqrt((x2-x1)**2+(y2-y1)**2))*(y2-y1)
    dx1dt = vx1
    dx2dt = vx2
    dy1dt = vy1
    dy2dt = vy2
    x1 = x1 + dt*dx1dt
    x2 = x2 + dt*dx2dt
    y1 = y1 + dt*dy1dt
    y2 = y2 + dt*dy2dt
    vx1 = vx1 + dt*dvx1dt
    vx2 = vx2 + dt*dvx2dt
    vy1 = vy1 + dt*dvy1dt
    vy2 = vy2 + dt*dvy2dt
    r1 = np.vstack((r1,np.array([x1,y1])))
    r2 = np.vstack((r2,np.array([x2,y2])))

springDampLength = np.sqrt((r1[:,0]-r2[:,0])**2+(r1[:,1]-r2[:,1])**2)

plt.figure()
plt.plot(t, springDampLength)
plt.xlabel('t(s)')
plt.ylabel('Spring length (m)')
plt.show()

plt.figure()
plt.plot(r1[:,0], r1[:,1],'r.')
plt.plot(r2[:,0], r2[:,1],'b.')
plt.plot((m1*r1[:,0]+m2*r2[:,0])/(m1+m2), (m1*r1[:,1]+m2*r2[:,1])/(m1+m2),'g.')
plt.xlim(-2,2)
plt.ylim(-2,2)
plt.xlabel('x(m)')
plt.ylabel('y(m)')
plt.title('Masses position')
plt.legend(('Mass1','Mass 2','Masses center of mass'))
plt.show()
```

### 9) Simple muscle model

The diagram below shows a simple muscle model. The spring in the left represents the tendinous tissues and the spring in the right represents the elastic properties of the muscle fibers. The damping is present to model the viscous properties of the muscle fibers, the element CE is the contractile element (force production) and the mass $m$ is the muscle mass.

The length $L_{MT}$ is the length of the muscle plus the tendon. In our model $L_{MT}$ is constant, but it could be a function of the joint angle.

<figure>

The length of the tendon will be denoted by $l_T(t)$ and the muscle length, by $l_{m}(t)$. Both lengths are related by each other  by the following expression:

\begin{equation}
l_t(t) + l_m(t) = L_{MT}
\end{equation}

The free-body diagram of the muscle mass is depicted below.

<figure>

The resultant force being applied in the muscle mass is:

$\vec{\bf{F}} = -k_T(||\vec{\bf{r_m}}||-l_{t_0})\frac{\vec{\bf{r_m}}}{||\vec{\bf{r_m}}||} + b\frac{d(L_{MT}\hat{\bf{i}} - \vec{\bf{r_{m}}})}{dt} + k_m (||L_{MT}\hat{\bf{i}} - \vec{\bf{r_{m}}}||-l_{m_0})\frac{L_{MT}\hat{\bf{i}} - \vec{\bf{r_{m}}}}{||L_{MT}\hat{\bf{i}} - \vec{\bf{r_{m}}}||} +\vec{\bf{F}}{\bf{_{CE}}}(t)$

where $\vec{\bf{r_m}}$ is the muscle mass position.

Since the model is unidimensional, we can assume that the force $\vec{\bf{F}}\bf{_{CE}}(t)$ is in the x direction, so the analysis will be done only in this direction.

$F = -k_T(l_t-l_{t_0}) + b\frac{d(L_{MT} - l_t)}{dt} + k_m (l_m-l_{m_0}) + F_{CE}(t) = -k_T(l_t-l_{t_0}) -b\frac{dl_t}{dt} + k_m (L_{MT}-l_t-l_{m_0}) + F_{CE}(t) = -b\frac{dl_t}{dt}-(k_T+k_m)l_t+F_{CE}(t)+k_Tl_{t_0}+k_m(L_{MT}-l_{m_0})$

Applying the second Newton law:

$m\frac{d^2l_t}{dt^2} = -b\frac{dl_t}{dt}-(k_T+k_m)l_t+F_{CE}(t)+k_Tl_{t_0}+k_m(L_{MT}-l_{m_0})$

To solve this equation, we must break the equation into two first-order differential equations:

\begin{equation}
\frac{dvt}{dt} = - \frac{b}{m}v_t - \frac{k_T+k_m}{m}l_t +\frac{F_{CE}(t)}{m} + \frac{k_T}{m}l_{t_0}+\frac{k_m}{m}(L_{MT}-l_{m_0})
\end{equation}

\begin{equation}
\frac{d l_t}{dt} = v_t
\end{equation}

Now, we can solve these equations by using some numerical method. To obtain the solution, we will use the damping factor of the muscle as $b = 10\,Ns/m$, the muscle mass is $m = 2 kg$, the stiffness of the tendon as $k_t=1000\,N/m$ and the elastic element of the muscle as $k_m=1500\,N/m$. The tendon-length is $L_{MT} = 0.35\,m$, and the tendon equilibrium length is $l_{t0} = 0.28\,m$ and the muscle fiber equilibrium length is $l_{m0} = 0.07\,m$. Both the tendon and the muscle fiber are at their equilibrium lengths and at rest.

Also, we will model the force of the contractile element as a Heaviside step of $90\,N$ (90 N beginning at $t=0$), but normally it is modeled as a function of $l_m$ and $v_m$ having a neural activation signal as input.

```python
m = 2
b = 10
km = 1500
kt = 1000
lt0 = 0.28
lm0 = 0.07

Lmt = 0.35
vt0 = 0

dt = 0.0001
t = np.arange(0, 10, dt)

Fce = 90

lt = lt0
vt = vt0
ltp = np.array([lt0])
lmp = np.array([lm0])
Ft = np.array([0])
for i in range(1,len(t)):
    dvtdt = -b/m*vt-(kt+km)/m*lt  + Fce/m + kt/m*lt0 +km/m*(Lmt-lm0)
    dltdt = vt
    vt = vt + dt*dvtdt
    lt = lt + dt*dltdt
    Ft = np.vstack((Ft,np.array(kt*(lt-lt0))))
    ltp = np.vstack((ltp,np.array(lt)))
    lmp = np.vstack((lmp,np.array(Lmt - lt)))

plt.figure()
plt.plot(t,Ft)
plt.xlabel('t(s)')
plt.ylabel('Tendon force (N)')
plt.show()
plt.figure()
plt.plot(t,ltp)
plt.plot(t,lmp)
plt.xlabel('t(s)')
plt.ylabel('Length (m)')
plt.legend(('Tendon length', 'Muscle fiber length'))
plt.show()
```

## Problems

Solve the problems 3.3.9, 3.3.20, 10.1.6, 12.1.6(a,b,c,d,f), 12.1.7, 12.1.10 (a,b) from Ruina and Pratap book

## References

- Ruina A, Rudra P (2015) [Introduction to Statics and Dynamics](http://ruina.tam.cornell.edu/Book/index.html). Oxford University Press.
- Nigg & Herzog (2006) [Biomechanics of the Musculo-skeletal System](https://books.google.com.br/books?id=hOIeAQAAIAAJ&dq=editions:ISBN0470017678). 3rd Edition. Wiley.

```python

```