# Multibody dynamics of simple biomechanical models

> Marcos Duarte
> Laboratory of Biomechanics and Motor Control ([http://demotu.org/](http://demotu.org/))
> Federal University of ABC, Brazil

The human body is composed of multiple interconnected segments (which can be modeled as rigid or flexible) and each segment may have translational and rotational movement. The part of mechanics for the study of movement and forces of interconnected bodies is called [multibody system](http://en.wikipedia.org/wiki/Multibody_system) or multibody dynamics.

There are different approaches to deduce the kinematics and dynamics of such bodies, the most common are the [Newton-Euler](http://en.wikipedia.org/wiki/Newton%E2%80%93Euler_equations) and the [Langrangian](http://en.wikipedia.org/wiki/Lagrangian_mechanics) formalisms. The Newton-Euler formalism is based on the well known Newton-Euler equations. The Langrangian formalism uses the [principle of least action](http://en.wikipedia.org/wiki/Principle_of_least_action) and describes the movement based on [generalized coordinates](http://en.wikipedia.org/wiki/Generalized_coordinates), a set of parameters (typically, a convenient minimal set) to describe the configuration of the system taking into account its constraints. For a system with multiple bodies and several constraints, e.g., the human body, it is easier to describe the dynamics of such system using the Langrangian formalism.

Next, we will study two simple problems of multibody systems in the context of biomechanics which we can handle well using the Newton-Euler approach. First a planar one-link system (which is not a multibody!), which can represent the movement of one limb of the body or the entire body as a single inverted pendulum. Second, a planar two-link system, which can represent the movement of two segments of the body, e.g., upper arm and forearm. Zajac and Gordon (1989) and Zajac (1993) offer excellent discussions about applying multibody system concepts to understanding human body movement.

## Newton-Euler equations

For a two-dimensional movement in the $XY$ plane, the Newton-Euler equations are:

\begin{equation}
\left\{ \begin{array}{l l}
\sum F_X = m \ddot{x}_{cm} \\
\\
\sum F_Y = m \ddot{y}_{cm} \\
\\
\sum M_Z = I_{cm} \ddot{\alpha}_Z
\end{array} \right.
\label{}
\end{equation}

Where the movement is described around the body center of mass ($cm$). $(F_X,\,F_Y)$ and $M_Z$ are, respectively, the forces and moment of forces (torques) acting on the body, $(\ddot{x}_{cm},\,\ddot{y}_{cm})$ and $\ddot{\alpha}_Z$ are, respectively, the linear and angular accelerations, and $I_{cm}$ is the body moment of inertia around the $Z$ axis passing through the body center of mass.

Let's use Sympy to derive some of the characteristics of the systems.

```python
from sympy import Symbol, symbols, cos, sin, Matrix, simplify
from sympy.physics.mechanics import dynamicsymbols, mlatex, init_vprinting
init_vprinting()
from IPython.display import display, Math
```

## One-link system

Let's study the dynamics of a planar inverted pendulum as a model for the movement of a human body segment with an external force acting on the segment (see Figure 1).

Figure 1. Planar inverted pendulum with joint actuators (muscles) and corresponding free body diagram. See text for notation convention.

The following notation convention will be used for this problem:

 - $L$ is the length of the segment.
 - $d$ is the distance from the joint of the segment to its center of mass position.
 - $m$ is the mass of the segment.
 - $g$ is the gravitational acceleration (+).
 - $\alpha$ is the angular position of the joint w.r.t. horizontal, $\ddot{\alpha_i}$ is the corresponding angular acceleration.
 - $I$ is the moment of inertia of the segment around its center of mass position.
 - $F_{r}$ is the joint reaction force.
 - $F_{e}$ is the external force acting on the segment.
 - $T$ is the joint moment of force (torque).

Muscles responsible for the movement of the segment are represented as a single pair of antagonistic joint actuators (e.g., flexors and extensors). We will consider that all joint torques are generated only by these muscles (we will disregard the torques generated by ligaments and other tissues) and the total or net joint torque will be the sum of the torques generated by the two muscles:

\begin{equation}
T = T_{net} = T_{extension} - T_{flexion}
\label{}
\end{equation}

Where we considered the extensor torque as positive. In what follows, we will determine only the net torque, we will be unable to decompose the net torque in its components.

### Kinetics

From the free body diagram, the Newton-Euler equations for the planar inverted pendulum are (writing the equation for the torques around the center of mass):

\begin{equation}
\begin{array}{l l}
F_{r,x} + F_{e,x} = m\ddot{x} \\
\\
F_{r,y} - mg + F_{e,y} = m\ddot{y} \\
\\
T + dF_{r,x}\sin\alpha - dF_{r,y}\cos\alpha - (L-d)F_{e,x}\sin\alpha + (L-d)F_{e,y}\cos\alpha = I\ddot{\alpha}
\end{array}
\label{}
\end{equation}

However, manually placing the terms in the Newton-Euler equations as we did above where we calculated the signs of the cross products is error prone. We can avoid this manual placing by treating the quantities as vectors and express them in matricial form:

\begin{equation}
\begin{array}{l l}
\mathbf{F}_r + \mathbf{F}_g + \mathbf{F}_e = m\ddot{\mathbf{r}} \\
\\
\mathbf{T} + \mathbf{r}_{cm,j} \times \mathbf{F}_r + \mathbf{r}_{cm,e} \times \mathbf{F}_e = I\ddot{\mathbf{\alpha}}
\end{array}
\label{}
\end{equation}

Where:

\begin{equation}
\begin{bmatrix} F_{rx} \\ F_{ry} \\ 0 \end{bmatrix}  + \begin{bmatrix} 0 \\ -g \\ 0 \end{bmatrix}  + \begin{bmatrix} F_{ex} \\ F_{ey} \\ 0 \end{bmatrix} = m\begin{bmatrix} \ddot{x} \\ \ddot{y} \\ 0 \end{bmatrix} , \quad \begin{bmatrix} \hat{i} \\ \hat{j} \\ \hat{k} \end{bmatrix}
\label{}
\end{equation}

\begin{equation}
\begin{bmatrix} 0 \\ 0 \\ T_z \end{bmatrix}  + \begin{bmatrix} -d\cos\alpha \\ -d\sin\alpha \\ 0 \end{bmatrix}  \times \begin{bmatrix} F_{rx} \\ F_{ry} \\ 0 \end{bmatrix} + \begin{bmatrix} (L-d)\cos\alpha \\ (L-d)\sin\alpha \\ 0 \end{bmatrix}  \times \begin{bmatrix} F_{ex} \\ F_{ey} \\ 0 \end{bmatrix} = I_z\begin{bmatrix} 0 \\ 0 \\ \ddot{\alpha} \end{bmatrix} , \quad \begin{bmatrix} \hat{i} \\ \hat{j} \\ \hat{k} \end{bmatrix}
\label{}
\end{equation}

Note that $\times$ represents the cross product, not matrix multiplication. Then, both in symbolic or numeric manipulation we would use the cross product function to perform part of the calculations. There are different computational tools that can be used for the formulation of the equations of motion. For instance, Sympy has a module, [Classical Mechanics](http://docs.sympy.org/dev/modules/physics/mechanics/), and see [this list](http://real.uwaterloo.ca/~mbody/#Software) for other software. Let's continue with the manual formulation of the equations hence they are not complex.

We can rewrite the equation for the moments of force in a form that doesn't explicitly involve the joint reaction force expressing the moments of force around the joint center:

\begin{equation}
T - mgd\cos\alpha - LF_{e,x}\sin\alpha + LF_{e,y}\cos\alpha = I_o\ddot{\alpha}
\label{}
\end{equation}

Where $I_o$ is the moment of inertia around the joint, $I_o=I_{cm}+md^2$, using the parallel axis theorem.

The torque due to the joint reaction force does not appear on this equation; this torque is null because by the definition the reaction force acts on the joint. If we want to determine the joint torque and we know the kinematics, we perform inverse dynamics:

\begin{equation}
T = I_o\ddot{\alpha} + mgd \cos \alpha + LF_{e,x}\sin\alpha - LF_{e,y}\cos\alpha
\label{}
\end{equation}

If we want to determine the kinematics and we know the joint torque, we perform direct dynamics:

\begin{equation}
\ddot{\alpha} = I_o^{-1}[T - mgd \cos \alpha - LF_{e,x}\sin\alpha + LF_{e,y}\cos\alpha ]
\label{}
\end{equation}

The expression above is a second-order differential equation which typically is solved numerically. So, unless we are explicitly interested in estimating the joint reaction forces, we don't need to use them for calculating the joint torque or simulate movement. Anyway, let's look at the kinematics of this problem to introduce some important concepts which will be needed later.

### Kinematics

A single planar inverted pendulum has one degree of freedom, the rotation movement of the segment around the pin joint. In this case, if the angular position $\alpha(t)$ is known, the coordinates $x(t)$ and $y(t)$ of the center of mass and their derivatives can be readily determined (a process referred as forward kinematics):

```python
t = Symbol('t')
d, L = symbols('d L', positive=True)
a = dynamicsymbols('alpha')
```

```python
x, y = d*cos(a), d*sin(a)
xd, yd = x.diff(t), y.diff(t)
xdd, ydd = xd.diff(t), yd.diff(t)

display(Math(r'x=' + mlatex(x)))
display(Math(r'\dot{x}=' + mlatex(xd)))
display(Math(r'\ddot{x}=' + mlatex(xdd)))
display(Math(r'y=' + mlatex(y)))
display(Math(r'\dot{y}=' + mlatex(yd)))
display(Math(r'\ddot{y}=' + mlatex(ydd)))
```

$$x=d \operatorname{cos}\left(\alpha\right)$$

$$\dot{x}=- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}$$

$$\ddot{x}=- d \operatorname{sin}\left(\alpha\right) \ddot{\alpha} - d \operatorname{cos}\left(\alpha\right) \dot{\alpha}^{2}$$

$$y=d \operatorname{sin}\left(\alpha\right)$$

$$\dot{y}=d \operatorname{cos}\left(\alpha\right) \dot{\alpha}$$

$$\ddot{y}=- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}^{2} + d \operatorname{cos}\left(\alpha\right) \ddot{\alpha}$$

The terms in $\ddot{x}$ and $\ddot{y}$ proportional to $\dot{\alpha}^2$ are components of the centripetal acceleration on the body. As the name suggests, the [centripetal](http://en.wikipedia.org/wiki/Centripetal_force) acceleration is always directed to the center (towards the joint) when the segment is rotating. See the notebook [Kinematic chain](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/KinematicChain.ipynb) for more on that.

As an exercise, let's go back to the Newton-Euler equation for the sum of torques around the center of mass where the torques due to the joint reaction forces are explicit. From the equation for the the sum of forces, hence we have expressions for the linear accelerations, we can isolate the reaction forces and substitute them on the equation for the torques. With a little help from Sympy:

```python
m, I, g = symbols('m I g', positive=True)
Fex, Fey = symbols('F_ex F_ey')
add = a.diff(t, 2)
```

```python
Frx = m*xdd - Fex
Fry = m*ydd + m*g - Fey
display(Math(r'F_{rx}=' + mlatex(Frx)))
display(Math(r'F_{ry}=' + mlatex(Fry)))
```

$$F_{rx}=- F_{ex} + m \left(- d \operatorname{sin}\left(\alpha\right) \ddot{\alpha} - d \operatorname{cos}\left(\alpha\right) \dot{\alpha}^{2}\right)$$

$$F_{ry}=- F_{ey} + g m + m \left(- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}^{2} + d \operatorname{cos}\left(\alpha\right) \ddot{\alpha}\right)$$

```python
T = I*add - d*sin(a)*Frx + d*cos(a)*Fry + (L-d)*sin(a)*Fex - (L-d)*cos(a)*Fey
display(Math(r'T\quad=\quad ' + mlatex(T)))
```

$$T\quad=\quad F_{ex} \left(L - d\right) \operatorname{sin}\left(\alpha\right) - F_{ey} \left(L - d\right) \operatorname{cos}\left(\alpha\right) + I \ddot{\alpha} - d \left(- F_{ex} + m \left(- d \operatorname{sin}\left(\alpha\right) \ddot{\alpha} - d \operatorname{cos}\left(\alpha\right) \dot{\alpha}^{2}\right)\right) \operatorname{sin}\left(\alpha\right) + d \left(- F_{ey} + g m + m \left(- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}^{2} + d \operatorname{cos}\left(\alpha\right) \ddot{\alpha}\right)\right) \operatorname{cos}\left(\alpha\right)$$

This equation for the torques around the center of mass of only one rotating segment seems too complicated. The equation we derived before for the torques around the joint was much simpler. However, if we look at the terms on this last equation, we can simplify most of them. Let's use Sympy to simplify this equation:

```python
T = simplify(T)
display(Math(r'T=' + mlatex(T)))
```

$$T=F_{ex} L \operatorname{sin}\left(\alpha\right) - F_{ey} L \operatorname{cos}\left(\alpha\right) + I \ddot{\alpha} + d^{2} m \ddot{\alpha} + d g m \operatorname{cos}\left(\alpha\right)$$

And we are back to the more simple equation we've seen before. The first two terms on the right side are the torque due to the external force, the third and fourth are the moment of inertia around the joint (use the theorem of parallel axis) times the acceleration, and the last term is the gravitational torque.

But what happened with all the other terms in the equation?

First, the terms proportional to the angular acceleration were just components from each direction of the 'inertial' torque that when summed resulted in $md^2\ddot{\alpha}$.
Second, the terms proportional to $\dot{\alpha}^2$ are components of the torque due to the centripetal force (acceleration). But the centripetal force passes through the joint as well as through the center of mass, i.e., it has zero lever arm and this torque should be zero. Indeed, when summed these terms are canceled out.

### The Jacobian matrix

Another way to deduce the velocity and acceleration of a point at the rotating link is to use the [Jacobian matrix](http://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) (see [Kinematic chain](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/KinematicChain.ipynb)). Remember that in the context of kinematic chains, the Jacobian is a matrix of all first-order partial derivatives of the linear position vector of the endpoint with respect to the angular position vector. For the planar one-link case, this means that the Jacobian matrix is:

\begin{equation}
\mathbf{J}=
\begin{bmatrix}
\dfrac{\partial x}{\partial \alpha} \\
\dfrac{\partial y}{\partial \alpha} \\
\end{bmatrix}
\label{}
\end{equation}

```python
r = Matrix((x, y))
J = r.diff(a)
display(Math(r'\mathbf{J}=' + mlatex(J)))
```

$$\mathbf{J}=\left[\begin{matrix}- d \operatorname{sin}\left(\alpha\right)\\d \operatorname{cos}\left(\alpha\right)\end{matrix}\right]$$

And Sympy has a function to calculate the Jacobian:

```python
J = r.jacobian([a])
display(Math(r'\mathbf{J}=' + mlatex(J)))
```

$$\mathbf{J}=\left[\begin{matrix}- d \operatorname{sin}\left(\alpha\right)\\d \operatorname{cos}\left(\alpha\right)\end{matrix}\right]$$

The linear velocity of a point in the link will be given by the product between the Jacobian of the kinematic link and its angular velocity:

\begin{equation}
\mathbf{v} = \mathbf{J} \dot{\alpha}
\label{}
\end{equation}

Using Sympy:

```python
vel = J*a.diff(t)
display(Math(r'\begin{bmatrix} \dot{x} \\ \dot{y} \end{bmatrix}=' + mlatex(vel)))
```

$$\begin{bmatrix} \dot{x} \\ \dot{y} \end{bmatrix}=\left[\begin{matrix}- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}\\d \operatorname{cos}\left(\alpha\right) \dot{\alpha}\end{matrix}\right]$$

And the linear acceleration will be given by the derivative of this last expression:

\begin{equation}
\mathbf{a} = \dot{\mathbf{J}} \dot{\alpha} + \mathbf{J} \ddot{\alpha}
\label{}
\end{equation}

And using Sympy again:

```python
acc = (J*a.diff(t)).diff(t)
display(Math(r'\begin{bmatrix} \ddot{x} \\ \ddot{y} \end{bmatrix}=' + mlatex(acc)))
```

$$\begin{bmatrix} \ddot{x} \\ \ddot{y} \end{bmatrix}=\left[\begin{matrix}- d \operatorname{sin}\left(\alpha\right) \ddot{\alpha} - d \operatorname{cos}\left(\alpha\right) \dot{\alpha}^{2}\\- d \operatorname{sin}\left(\alpha\right) \dot{\alpha}^{2} + d \operatorname{cos}\left(\alpha\right) \ddot{\alpha}\end{matrix}\right]$$

Same expressions as before.

We can also use the Jacobian matrix to calculate the torque due to a force on the link:

\begin{equation}
T = \mathbf{J}^T \begin{bmatrix} F_{ex} \\ F_{ey} \end{bmatrix}
\label{}
\end{equation}

```python
Te = J.T*Matrix((Fex, Fey))
display(Math(r'T_e=' + mlatex(Te[0])))
```

$$T_e=- F_{ex} d \operatorname{sin}\left(\alpha\right) + F_{ey} d \operatorname{cos}\left(\alpha\right)$$

Now let's study a two-link system which can rotate independently around each joint. We will see that now the torque due to the centripetal force most of the times will not cancel out and a new torque component will appear.

## Two-link system

Let's study the dynamics of a planar double inverted pendulum (see Figure 2) as a model of two interconnected segments in the human body with an external force acting on the distal segment. Once again, we will consider that there are muscles around each joint and they generate torques.

Figure 2. Planar double inverted pendulum  with joint actuators (muscles) and corresponding free body diagrams. See text for notation convention.

The following notation convention will be used for this problem:
 - Subscript $i$ runs 1 or 2 meaning first (most proximal) or second joint when referring to angles, joint moments, or joint reaction forces, or meaning first or second segment when referring to everything else.
 - $L_i$ is the length of segment $i$.
 - $d_i$ is the distance from the proximal joint of segment $i$ to its center of mass position.
 - $m_i$ is the mass of segment $i$.
 - $g$ is the gravitational acceleration (+).
 - $\alpha_i$ is the angular position of joint $i$ in the joint space, $\ddot{\alpha_i}$ is the corresponding angular acceleration.
 - $\theta_i$ is the angular position of joint $i$ in the segmental space w.r.t. horizontal, $\theta_1=\alpha_1$ and $\theta_2=\alpha_1+\alpha_2$.
 - $I_i$ is the moment of inertia of segment $i$ around its center of mass position.
 - $F_{ri}$ is the reaction force of joint $i$.
 - $F_{e}$ is the external force acting on the distal segment.
 - $T_i$ is the moment of force (torque) of joint $i$.

Hence we know we will need the linear accelerations for solving the Newton-Euler equations, let's deduce them first.

### Kinematics

Once again, if the angular positions $\alpha_1(t)$ and $\alpha_2(t)$ are known, the coordinates $(x_1(t), y_1(t))$ and $(x_2(t), y_2(t))$ and their derivatives can be readily determined (by forward kinematics):

#### Link 1

```python
t = Symbol('t')
d1, d2, L1, L2 = symbols('d1, d2, L_1 L_2', positive=True)
a1, a2 = dynamicsymbols('alpha1 alpha2')
a1d, a2d = a1.diff(t), a2.diff(t)
a1dd, a2dd = a1.diff(t, 2), a2.diff(t, 2)
```

```python
x1, y1 = d1*cos(a1), d1*sin(a1)
x1d, y1d = x1.diff(t), y1.diff(t)
x1dd, y1dd = x1d.diff(t), y1d.diff(t)

display(Math(r'x_1=' + mlatex(x1)))
display(Math(r'\dot{x}_1=' + mlatex(x1d)))
display(Math(r'\ddot{x}_1=' + mlatex(x1dd)))
display(Math(r'y_1=' + mlatex(y1)))
display(Math(r'\dot{y}_1=' + mlatex(y1d)))
display(Math(r'\ddot{y}_1=' + mlatex(y1dd)))
```

$$x_1=d_{1} \operatorname{cos}\left(\alpha_{1}\right)$$

$$\dot{x}_1=- d_{1} \operatorname{sin}\left(\alpha_{1}\right) \dot{\alpha}_{1}$$

$$\ddot{x}_1=- d_{1} \operatorname{sin}\left(\alpha_{1}\right) \ddot{\alpha}_{1} - d_{1} \operatorname{cos}\left(\alpha_{1}\right) \dot{\alpha}_{1}^{2}$$

$$y_1=d_{1} \operatorname{sin}\left(\alpha_{1}\right)$$

$$\dot{y}_1=d_{1} \operatorname{cos}\left(\alpha_{1}\right) \dot{\alpha}_{1}$$

$$\ddot{y}_1=- d_{1} \operatorname{sin}\left(\alpha_{1}\right) \dot{\alpha}_{1}^{2} + d_{1} \operatorname{cos}\left(\alpha_{1}\right) \ddot{\alpha}_{1}$$

#### Link 2

```python
x2, y2 = L1*cos(a1) + d2*cos(a1+a2), L1*sin(a1) + d2*sin(a1+a2)
x2d, y2d = x2.diff(t), y2.diff(t)
x2dd, y2dd = x2d.diff(t), y2d.diff(t)

display(Math(r'x_2=' + mlatex(x2)))
display(Math(r'\dot{x}_2=' + mlatex(x2d)))
display(Math(r'\ddot{x}_2=' + mlatex(x2dd)))
display(Math(r'y_2=' + mlatex(y2)))
display(Math(r'\dot{y}_2=' + mlatex(y2d)))
display(Math(r'\ddot{y}_2=' + mlatex(y2dd)))
```

$$x_2=L_{1} \operatorname{cos}\left(\alpha_{1}\right) + d_{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right)$$

$$\dot{x}_2=- L_{1} \operatorname{sin}\left(\alpha_{1}\right) \dot{\alpha}_{1} - d_{2} \left(\dot{\alpha}_{1} + \dot{\alpha}_{2}\right) \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right)$$

$$\ddot{x}_2=- L_{1} \operatorname{sin}\left(\alpha_{1}\right) \ddot{\alpha}_{1} - L_{1} \operatorname{cos}\left(\alpha_{1}\right) \dot{\alpha}_{1}^{2} - d_{2} \left(\dot{\alpha}_{1} + \dot{\alpha}_{2}\right)^{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right) - d_{2} \left(\ddot{\alpha}_{1} + \ddot{\alpha}_{2}\right) \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right)$$

$$y_2=L_{1} \operatorname{sin}\left(\alpha_{1}\right) + d_{2} \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right)$$

$$\dot{y}_2=L_{1} \operatorname{cos}\left(\alpha_{1}\right) \dot{\alpha}_{1} + d_{2} \left(\dot{\alpha}_{1} + \dot{\alpha}_{2}\right) \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right)$$

$$\ddot{y}_2=- L_{1} \operatorname{sin}\left(\alpha_{1}\right) \dot{\alpha}_{1}^{2} + L_{1} \operatorname{cos}\left(\alpha_{1}\right) \ddot{\alpha}_{1} - d_{2} \left(\dot{\alpha}_{1} + \dot{\alpha}_{2}\right)^{2} \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right) + d_{2} \left(\ddot{\alpha}_{1} + \ddot{\alpha}_{2}\right) \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right)$$

Inspecting the equations above, we see a new kind of acceleration, proportional to $\dot{\alpha_1}\dot{\alpha_2}$. This acceleration is due to the [Coriolis effect](http://en.wikipedia.org/wiki/Coriolis_effect) and is  present only when there are movement in the two joints.

### Kinetics

From the free body diagrams, the Newton-Euler equations for the planar double inverted pendulum are:

#### Link 2

\begin{equation}
\begin{array}{l l}
F_{r2x} + F_{e,x} = m_2\ddot{x}_{2} \\
\\
F_{r2y} - m_2g + F_{e,y} = m_2\ddot{y}_{2} \\
\\
T_2 + d_2F_{r2x}\sin(\alpha_1+\alpha_2) - d_2F_{r2y}\cos(\alpha_1+\alpha_2) - (L_2-d_2)F_{e,x}\sin(\alpha_1+\alpha_2) - (L_2-d_2)F_{e,y}\cos(\alpha_1+\alpha_2) = I_{2}(\ddot{\alpha}_1+\ddot{\alpha}_2)
\end{array}
\label{}
\end{equation}

#### Link 1

\begin{equation}
\begin{array}{l l}
F_{r1x} - F_{r2x} = m_1\ddot{x}_{1} \\
\\
F_{r1y} - F_{r2y} - m_1g = m_1\ddot{y}_{1} \\
\\
T_1 - T_2 + d_1F_{r1x}\sin\alpha_1 - d_1F_{r1y}\cos\alpha_1 + (L_1-d_1)F_{r2x}\sin\alpha_1 - (L_1-d_1)F_{r2y}\cos\alpha_1 = I_{1}\ddot{\alpha}_1
\end{array}
\label{}
\end{equation}

If we want to determine the joint torques and we know the kinematics of the links, the inverse dynamics approach, we isolate the joint torques in the equations above, start solving for link 2 and then link 1. To determine the kinematics knowing the joint torques, the direct dynamics approach, we isolate the joint angular accelerations in the equations above and solve the ordinary differential equations.

Let's express the equations for the torques substituting the terms we know:

```python
m1, m2, I1, I2, g = symbols('m_1, m_2, I_1 I_2 g', positive=True)
```

```python
# link 2
Fr2x = m2*x2dd - Fex
Fr2y = m2*y2dd + m2*g - Fey
T2 = I2*(a1dd+a2dd) - d2*Fr2x*sin(a1+a2) + d2*Fr2y*cos(a1+a2) + (L2-d2)*Fex*sin(a1+a2) - (L2-d2)*Fey*cos(a1+a2)
T2 = simplify(T2)
# link 1
Fr1x = m1*x1dd + Fr2x
Fr1y = m1*y1dd + Fr2y + m1*g
T1 = I1*a1dd + T2 - d1*Fr1x*sin(a1) + d1*Fr1y*cos(a1) - (L1-d1)*Fr2x*sin(a1) + (L1-d1)*Fr2y*cos(a1)
T1 = simplify(T1)
```

The expressions for the joint moments of force (torques) are:

```python
display(Math(r'T_1\quad = \quad ' + mlatex(T1)))
display(Math(r'T_2\quad = \quad ' + mlatex(T2)))
```

$$T_1\quad = \quad F_{ex} L_{1} \operatorname{sin}\left(\alpha_{1}\right) + F_{ex} L_{2} \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right) - F_{ey} L_{1} \operatorname{cos}\left(\alpha_{1}\right) - F_{ey} L_{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right) + I_{1} \ddot{\alpha}_{1} + I_{2} \ddot{\alpha}_{1} + I_{2} \ddot{\alpha}_{2} + L_{1}^{2} m_{2} \ddot{\alpha}_{1} - 2 L_{1} d_{2} m_{2} \operatorname{sin}\left(\alpha_{2}\right) \dot{\alpha}_{1} \dot{\alpha}_{2} - L_{1} d_{2} m_{2} \operatorname{sin}\left(\alpha_{2}\right) \dot{\alpha}_{2}^{2} + 2 L_{1} d_{2} m_{2} \operatorname{cos}\left(\alpha_{2}\right) \ddot{\alpha}_{1} + L_{1} d_{2} m_{2} \operatorname{cos}\left(\alpha_{2}\right) \ddot{\alpha}_{2} + L_{1} g m_{2} \operatorname{cos}\left(\alpha_{1}\right) + d_{1}^{2} m_{1} \ddot{\alpha}_{1} + d_{1} g m_{1} \operatorname{cos}\left(\alpha_{1}\right) + d_{2}^{2} m_{2} \ddot{\alpha}_{1} + d_{2}^{2} m_{2} \ddot{\alpha}_{2} + d_{2} g m_{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right)$$

$$T_2\quad = \quad F_{ex} L_{2} \operatorname{sin}\left(\alpha_{1} + \alpha_{2}\right) - F_{ey} L_{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right) + I_{2} \ddot{\alpha}_{1} + I_{2} \ddot{\alpha}_{2} + L_{1} d_{2} m_{2} \operatorname{sin}\left(\alpha_{2}\right) \dot{\alpha}_{1}^{2} + L_{1} d_{2} m_{2} \operatorname{cos}\left(\alpha_{2}\right) \ddot{\alpha}_{1} + d_{2}^{2} m_{2} \ddot{\alpha}_{1} + d_{2}^{2} m_{2} \ddot{\alpha}_{2} + d_{2} g m_{2} \operatorname{cos}\left(\alpha_{1} + \alpha_{2}\right)$$

># Next class

There is an elegant form to display the equations for the torques using generalized coordinates, $q=[\alpha_1, \alpha_2]^T$ and grouping the terms proportional to common quantities in matrices, see for example, Craig (2005, page 180), Pandy (2001), and Zatsiorsky (2002, page 383):

\begin{equation}
\begin{array}{l l}
\tau = M(q)\ddot{q} + C(q,\dot{q}) + G(q) + E(q,\dot{q})
\end{array}
\label{}
\end{equation}

Where, for this two-link system, $\tau$ is a matrix (2x1) of joint torques; $M$ is the mass or inertia matrix (2x2); $\ddot{q}$ is a matrix (2x1) of angular accelerations; $C$ is a matrix (2x1) of [centipetal](http://en.wikipedia.org/wiki/Centripetal_force) and [Coriolis](http://en.wikipedia.org/wiki/Coriolis_effect) torques; $G$ is a matrix (2x1) of  gravitational torques; and $E$ is a matrix (2x1) of external torques.

Let's use Sympy to display the equations for the torques in this new form:

```python
T1, T2 = T1.expand(), T2.expand()
q1, q2 = dynamicsymbols('q_1 q_2')
q1d, q2d = q1.diff(t), q2.diff(t)
q1dd, q2dd = q1.diff(t, 2), q2.diff(t, 2)
T1 = T1.subs({a1:q1, a2:q2, a1d:q1d, a2d:q2d, a1dd:q1dd, a2dd:q2dd})
T2 = T2.subs({a1:q1, a2:q2, a1d:q1d, a2d:q2d, a1dd:q1dd, a2dd:q2dd})
```

```python
M = Matrix(((simplify(T1.coeff(q1dd)), simplify(T1.coeff(q2dd))),
            (simplify(T2.coeff(q1dd)), simplify(T2.coeff(q2dd)))))
C = Matrix((simplify(T1.coeff(q1d**2)*q1d**2 + T1.coeff(q2d**2)*q2d**2 + T1.coeff(q1d*q2d)*q1d*q2d),
            simplify(T2.coeff(q1d**2)*q1d**2 + T2.coeff(q2d**2)*q2d**2 + T2.coeff(q1d*q2d)*q1d*q2d)))
G = Matrix((simplify(T1.coeff(g)*g),
            simplify(T2.coeff(g)*g)))
E = Matrix((simplify(T1.coeff(Fex)*Fex + T1.coeff(Fey)*Fey),
            simplify(T2.coeff(Fex)*Fex + T2.coeff(Fey)*Fey)))

display(Math(r'\begin{eqnarray}\tau&=&\begin{bmatrix}\tau_1\\ \tau_2\\ \end{bmatrix} \\' +
             r'M(q)&=&' + mlatex(M) + r'\\' +
             r'\ddot{q}&=&' + mlatex(Matrix((q1dd, q2dd))) + r'\\' +
             r'C(q,\dot{q})&=&' + mlatex(C) + r'\\' +
             r'G(q)&=&' + mlatex(G) + r'\\' +
             r'E(q,\dot{q})&=&' + mlatex(E) + r'\end{eqnarray}'))
```

$$\begin{eqnarray}\tau&=&\begin{bmatrix}\tau_1\\ \tau_2\\ \end{bmatrix} \\M(q)&=&\left[\begin{matrix}I_{1} + I_{2} + L_{1}^{2} m_{2} + 2 L_{1} d_{2} m_{2} \operatorname{cos}\left(q_{2}\right) + d_{1}^{2} m_{1} + d_{2}^{2} m_{2} & I_{2} + L_{1} d_{2} m_{2} \operatorname{cos}\left(q_{2}\right) + d_{2}^{2} m_{2}\\I_{2} + L_{1} d_{2} m_{2} \operatorname{cos}\left(q_{2}\right) + d_{2}^{2} m_{2} & I_{2} + d_{2}^{2} m_{2}\end{matrix}\right]\\\ddot{q}&=&\left[\begin{matrix}\ddot{q}_{1}\\\ddot{q}_{2}\end{matrix}\right]\\C(q,\dot{q})&=&\left[\begin{matrix}- L_{1} d_{2} m_{2} \left(2 \dot{q}_{1} + \dot{q}_{2}\right) \operatorname{sin}\left(q_{2}\right) \dot{q}_{2}\\L_{1} d_{2} m_{2} \operatorname{sin}\left(q_{2}\right) \dot{q}_{1}^{2}\end{matrix}\right]\\G(q)&=&\left[\begin{matrix}g \left(L_{1} m_{2} \operatorname{cos}\left(q_{1}\right) + d_{1} m_{1} \operatorname{cos}\left(q_{1}\right) + d_{2} m_{2} \operatorname{cos}\left(q_{1} + q_{2}\right)\right)\\d_{2} g m_{2} \operatorname{cos}\left(q_{1} + q_{2}\right)\end{matrix}\right]\\E(q,\dot{q})&=&\left[\begin{matrix}F_{ex} \left(L_{1} \operatorname{sin}\left(q_{1}\right) + L_{2} \operatorname{sin}\left(q_{1} + q_{2}\right)\right) - F_{ey} \left(L_{1} \operatorname{cos}\left(q_{1}\right) + L_{2} \operatorname{cos}\left(q_{1} + q_{2}\right)\right)\\L_{2} \left(F_{ex} \operatorname{sin}\left(q_{1} + q_{2}\right) - F_{ey} \operatorname{cos}\left(q_{1} + q_{2}\right)\right)\end{matrix}\right]\end{eqnarray}$$

With this convention, to perform inverse dynamics we would calculate:

\begin{equation}
\tau = M(q)\ddot{q} + C(q,\dot{q}) + G(q) + E(q,\dot{q})
\label{}
\end{equation}

And for direct dynamics we would solve the differential equation:

\begin{equation}
\ddot{q} = M(q)^{-1} \left[\tau - C(q,\dot{q}) - G(q) - E(q,\dot{q}) \right]
\label{}
\end{equation}

The advantage of calculating analytically the derivatives of the position vector as function of the joint angles and using the notation above is that each term that contributes to each joint torque or acceleration can be easily identified.

#### Coupling (or interaction) effects

The two terms off the main diagonal in the inertia matrix (which are the same) and the centripetal and Coriolis terms represent the effects of the movement (nonzero velocity) of one joint over the other. These torques are referred as coupling or interaction effects (see for example Hollerbach and Flash (1982) for an application of this concept in the study of the motor control of the upper limb movement).

#### Planar double pendulum

Using the same equations above, one can represent a planar double pendulum (hanging from the top, not inverted) considering the angles $\alpha_1$ and $\alpha_2$ negative, e.g., at $\alpha_1=-90^o$ and $\alpha_2=0$ the pendulum is hanging vertical.

#### WARNING: $F_r$ is not the actual joint reaction force!

For these two examples, in the Newton-Euler equations based on the free body diagrams we represented the consequences of all possible muscle forces on a joint as a net muscle torque and all forces acting on a joint as a resultant joint reaction force. That is, all forces between segments were represented as a resultant force that doesn't generate torque and a force couple (or free moment) that only generates torque. This is an important principle in mechanics of rigid bodies, see for example [this text](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/FreeBodyDiagram.ipynb). However, this principle creates the unrealistic notion that the sum of forces is applied directly on the joint (which has no further implication for a rigid body), but it is inaccurate for the understanding of the local effects on the joint. So, if we are trying to understand the stress on the joint or mechanisms of joint injury, the forces acting on the joint and on the rest of the segment must be considered individually.

#### Determination of muscle force

The torque $T$ exerted by a muscle is given by the product between the muscle-tendon moment arm $r$ and its force $F$. For the human body, there is more than one muscle crossing a joint and several joints. In such case, the torques due to the muscles are expressed in the following matrix form considering $n$ joints and $m$ muscles:

\begin{eqnarray}
\begin{bmatrix} T_1 \\ \vdots \\ T_n \end{bmatrix} = \begin{bmatrix} r_{11} & \cdots & r_{1m} \\ \vdots & \ddots & \vdots \\ r_{n1} & \cdots & r_{nm} \end{bmatrix} \begin{bmatrix} F_1 \\ \vdots \\ F_m \end{bmatrix}
\label{}
\end{eqnarray}

Where $r_{nm}$ is the moment arm about joint $n$ of the muscle $m$.
In the example of the two-link system, we sketched two uniarticular muscles for each of the two joints, consequently:

\begin{eqnarray}
\begin{bmatrix} T_1 \\ T_2 \end{bmatrix} = \begin{bmatrix} r_{1,ext} & -r_{1,flex} & 0 & 0 \\ 0 & 0 & r_{1,ext} & -r_{1,flex} \end{bmatrix} \begin{bmatrix} F_{1,ext} \\ F_{1,flex} \\ F_{2,ext} \\ F_{2,flex} \end{bmatrix}
\label{}
\end{eqnarray}

Note the opposite signs for the moment arms of the extension and flexion muscles hence they generate opposite torques. We could have represented the opposite signs in the muscle forces instead of in the moment arms.

The moment arm of a muscle varies with the motion of the joints it crosses. In this case, using the [virtual work principle](http://en.wikipedia.org/wiki/Virtual_work) the moment arm can be given by (Sherman et al., 2013; Nigg and Herzog, 2006, page 634):

\begin{equation}
r(q) = \dfrac{\partial L_{MT}(q)}{\partial q}
\label{}
\end{equation}

Where $L_{MT}(q)$ is the length of the muscle-tendon unit expressed as a function of angle $q$.

For the simulation of human movement, muscles can be modeled as [Hill-type muscles](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/MuscleSimulation.ipynb), the torques they generate are given by the matrix above, and this matrix is entered in the ODE for a multibody system dynamics we deduced before:

\begin{equation}
\ddot{q} = M(q)^{-1} \left[R_{MT}(q)F_{MT}(a,L_{MT},\dot{L}_{MT}) - C(q,\dot{q}) - G(q) - E(q,\dot{q}) \right]
\label{}
\end{equation}

Where $R_{MT}$ and $F_{MT}$ are matrices for the moment arms and muscle-tendon forces, respectively.
This ODE is then solved numerically given initial values; but this problem is far from trivial for a simulation with several segments and muscles.

## Numerical simulation

Let's simulate a voluntary movement of the upper limb using the planar two-link system as a model in order to visualize the contribution of each torque term.
We will ignore the muscle dynamics and we will calculate the joint torques necessary to move the upper limb from one point to another under the assumption that the movement is performed with the smoothest trajectory possible. I.e., the movement is performed with a [minimum-jerk trajectory](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/MinimumJerkHypothesis.ipynb), a hypothesis about control of voluntary movements proposed by Flash and Hogan (1985).

Once we determine the desired trajectory, we can calculate the velocity and acceleration of the segments and combine with anthropometric measures to calculate the joint torques necessary to move the segments. This means we will perform inverse dynamics.

Let's simulate a slow (4 s) and a fast (0.5 s) movement of the upper limb starting at the anatomical neutral position (upper limb at the side of the trunk) and ending with the upper arm forward at horizontal and elbow flexed at 90 degrees.

First, let's import the necessary Python libraries and customize the environment:

```python
import numpy as np
%matplotlib inline
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams['lines.linewidth'] = 3
matplotlib.rcParams['font.size'] = 13
matplotlib.rcParams['lines.markersize'] = 5
matplotlib.rc('axes', grid=True, labelsize=14, titlesize=16, ymargin=0.05)
matplotlib.rc('legend', numpoints=1, fontsize=11)
import sys
sys.path.insert(1, r'./../functions')  # add to pythonpath
```

Let's take the anthropometric data from Dempster's model (see [Body segment parameters](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/BodySegmentParameters.ipynb)):

```python
height, mass = 1.70,               70  # m, kg
L1n, L2n     = 0.188*height,       0.253*height
d1n, d2n     = 0.436*L1n,          0.682*L2n
m1n, m2n     = 0.0280*mass,        0.0220*mass
rg1n, rg2n   = 0.322,              0.468
I1n, I2n     = m1n*(rg1n*L1n)**2,  m2n*(rg2n*L2n)**2
```

Considering these lengths, the initial and final positions of the endpoint (finger tip) for the simulated movement will be:

```python
xi, yi = 0, -L1n-L2n
xf, yf = L1n, L2n
gn = 9.81  # gravity acceleration m/s2
```

### Slow movement

```python
duration = 4  # seconds
```

The endpoint minimum jerk trajectory will be (see [Kinematic chain in a plane (2D)](http://nbviewer.ipython.org/github/demotu/BMC/blob/master/notebooks/KinematicChain.ipynb)):

```python
from minjerk import minjerk
```

```python
time, rlin, vlin, alin, jlin = minjerk([xi, yi], [xf, yf], duration=duration)
```

Let's find the joint angles to produce this minimum-jerk trajectory (inverse kinematics):

```python
from invkin2_2d import invkin
```

```python
rang = invkin(time, rlin, L1=L1n, L2=L2n)
```

For the joint torques, we need to calculate the angular velocity and acceleration. Let's do that using numerical differentiation:

```python
def diff_c(ang, duration):
    """Numerical differentiations using the central difference for the angular data.
    """
    # central difference (f(x+h)-f(x-h))/(2*h)
    dt = duration/(ang.shape[0]-1)
    vang = np.empty_like(rang)
    aang = np.empty_like(rang)
    vang[:, 0] = np.gradient(rang[:, 0], dt)
    vang[:, 1] = np.gradient(rang[:, 1], dt)
    aang[:, 0] = np.gradient(vang[:, 0], dt)
    aang[:, 1] = np.gradient(vang[:, 1], dt)

    _, ax = plt.subplots(1, 3, sharex=True, figsize=(10, 3))
    ax[0].plot(time, rang*180/np.pi)
    ax[0].legend(['Ang 1', 'Ang 2'], framealpha=.5, loc='best')
    ax[1].plot(time, vang*180/np.pi)
    ax[2].plot(time, aang*180/np.pi)
    ylabel = [r'Displacement [$\mathrm{^o}$]', r'Velocity [$\mathrm{^o/s}$]', r'Acceleration [$\mathrm{^o/s^2}$]']
    for i, axi in enumerate(ax):
        axi.set_xlabel('Time [$s$]')
        axi.set_ylabel(ylabel[i])
        axi.xaxis.set_major_locator(plt.MaxNLocator(4))
        axi.yaxis.set_major_locator(plt.MaxNLocator(4))
    plt.tight_layout()
    plt.show()

    return vang, aang

vang, aang = diff_c(rang, duration)
```

```python
def dyna(time, L1n, L2n, d1n, d2n, m1n, m2n, gn, I1n, I2n, q1, q2, rang, vang, aang, Fexn, Feyn, M, C, G, E):
    """Numerical calculation and plot for the torques of a planar two-link system.
    """
    from sympy import lambdify, symbols

    Mfun  = lambdify((I1, I2, L1, L2, d1, d2, m1, m2, q1, q2), M, 'numpy')
    Mn    = Mfun(I1n, I2n, L1n, L2n, d1n, d2n, m1n, m2n, rang[:, 0], rang[:, 1])
    M00   = Mn[0, 0]*aang[:, 0]
    M01   = Mn[0, 1]*aang[:, 1]
    M10   = Mn[1, 0]*aang[:, 0]
    M11   = Mn[1, 1]*aang[:, 1]
    Q1d, Q2d = symbols('Q1d Q2d')
    dicti = {q1.diff(t, 1):Q1d, q2.diff(t, 1):Q2d}
    C0fun = lambdify((L1, d2, m2, q2, Q1d, Q2d), C[0].subs(dicti), 'numpy')
    C0    = C0fun(L1n, d2n, m2n, rang[:, 1], vang[:, 0], vang[:, 1])
    C1fun = lambdify((L1, d2, m2, q2, Q1d, Q2d), C[1].subs(dicti), 'numpy')
    C1    = C1fun(L1n, d2n, m2n, rang[:, 1], vang[:, 0], vang[:, 1])
    G0fun = lambdify((L1, d1, d2, m1, m2, g, q1, q2), G[0], 'numpy')
    G0    = G0fun(L1n, d1n, d2n, m1n, m2n, gn, rang[:, 0], rang[:, 1])
    G1fun = lambdify((L1, d1, d2, m1, m2, g, q1, q2), G[1], 'numpy')
    G1    = G1fun(L1n, d1n, d2n, m1n, m2n, gn, rang[:, 0], rang[:, 1])
    E0fun = lambdify((L1, L2, q1, q2, Fex, Fey), E[0], 'numpy')
    E0    = E0fun(L1n, L2n, rang[:, 0], rang[:, 1], 0, 0)
    E1fun = lambdify((L1, L2, q1, q2, Fex, Fey), E[1], 'numpy')
    E1    = E1fun(L1n, L2n, rang[:, 0], rang[:, 1], Fexn, Feyn)

    fig, ax = plt.subplots(1, 2, sharex=True, squeeze=True, figsize=(10, 4))
    ax[0].plot(time, M00+M01)
    ax[0].plot(time, C0)
    ax[0].plot(time, G0)
    ax[0].plot(time, E0)
    ax[0].plot(time, M00+M01+C0+G0, 'k:', linewidth=4)
    ax[0].set_ylabel(r'Torque [Nm]')
    ax[0].set_title('Joint 1')
    ax[1].plot(time, M10+M11, label='Mass/Inertia')
    ax[1].plot(time, C1, label='Centripetal/Coriolis       ')
    ax[1].plot(time, G1, label='Gravitational')
    ax[1].plot(time, E1, label='External')
    ax[1].plot(time, M10+M11+C1+G1, 'k:', linewidth=4, label='Muscular (sum)')
    ax[1].set_title('Joint 2')
    fig.legend(framealpha=.5, bbox_to_anchor=(1.15, 0.95), fontsize=12)
    for i, axi in enumerate(ax):
        axi.set_xlabel('Time [$s$]')
        axi.xaxis.set_major_locator(plt.MaxNLocator(4))
        axi.yaxis.set_major_locator(plt.MaxNLocator(4))
    plt.show()

    return M00, M01, M10, M11, C0, C1, G0, G1, E0, E1
```

```python
Fexn, Feyn = 0, 0
M00, M01, M10, M11, C0, C1, G0, G1, E0, E1 = dyna(time, L1n, L2n, d1n, d2n, m1n, m2n, gn, I1n, I2n,
                                                  q1, q2, rang, vang, aang, Fexn, Feyn, M, C, G, E)
```

The joint torques essentially compensate the gravitational torque.

### Fast movement

Let's see what is changed for a fast movement:

```python
duration = 0.5  # seconds
time, rlin, vlin, alin, jlin = minjerk([xi, yi], [xf, yf], duration=duration)
rang = invkin(time, rlin, L1=L1n, L2=L2n)
vang, aang = diff_c(rang, duration)
M00, M01, M10, M11, C0, C1, G0, G1, E0, E1 = dyna(time, L1n, L2n, d1n, d2n, m1n, m2n, gn, I1n, I2n,
                                                  q1, q2, rang, vang, aang, Fexn, Feyn, M, C, G, E)
```

The interaction torques are larger than the gravitational torques for most part of the movement.

### Fast movement in the horizontal plane

Let's simulate a fast movement in the horizontal plane:

```python
gn = 0  # gravity acceleration m/s2
M00, M01, M10, M11, C0, C1, G0, G1, E0, E1 = dyna(time, L1n, L2n, d1n, d2n, m1n, m2n, gn, I1n, I2n,
                                                  q1, q2, rang, vang, aang, Fexn, Feyn, M, C, G, E)
```

## Exercises

1. Derive the equations of motion for a single pendulum (not inverted).
2. Derive the equations of motion for a double pendulum (not inverted).
3. Consider the double pendulum moving in the horizontal plane and with no external force. Find out the type of movement and which torque terms are changed when:
  a) $\dot{\alpha}_1=0^o$
  b) $\alpha_2=0^o$
  c) $\dot{\alpha}_2=0^o$
  d) $2\alpha_1+\alpha_2=180^o$ (hint: a two-link system with this configuration is called polar manipulator)
4. Derive the equations of motion and the torque terms using angles in the segmental space $(\theta_1,\,\theta_2)$.
5. Run the numerical simulations for the torques with different parameters.

## References

- Craig JJ (2005) [Introduction to Robotics: Mechanics and Control](http://books.google.com.br/books?id=MqMeAQAAIAAJ). 3rd Edition. Prentice Hall.
- Flash T, Hogan N (1985) [The coordination of arm movements: an experimentally confirmed mathematical model](http://www.jneurosci.org/cgi/reprint/5/7/1688.pdf). Journal of Neuroscience, 5, 1688-1703.
- Hollerbach JM, Flash T (1982) [Dynamic interactions between limb segments during planar arm movement](http://link.springer.com/article/10.1007%2FBF00353957). Biological Cybernetics, 44, 67-77.
- Nigg BM and Herzog W (2006) [Biomechanics of the Musculo-skeletal System](https://books.google.com.br/books?id=hOIeAQAAIAAJ&dq=editions:ISBN0470017678). 3rd Edition. Wiley.
- Pandy MG (2001) [Computer modeling and simulation](https://drive.google.com/open?id=0BxbW72zV7WmUbXZBR2VRMnF5UTA&authuser=0). Annu. Rev. Biomed. Eng., 3, 245–73.
- Sherman MA, Seth A, Delp SL (2013) [What is a moment arm? Calculating muscle effectiveness in biomechanical models using generalized coordinates](http://simtk-confluence.stanford.edu:8080/download/attachments/3376330/ShermanSethDelp-2013-WhatIsMuscleMomentArm-Final2-DETC2013-13633.pdf?version=1&modificationDate=1369103515834) in Proc. ASME Int. Design Engineering Technical Conferences (IDETC), Portland, OR, USA.
- Zajac FE (1993) [Muscle coordination of movement: a perspective](http://e.guigon.free.fr/rsc/article/Zajac93.pdf). J Biomech., 26, Suppl 1:109-24.
- Zajac FE, Gordon ME (1989) [Determining muscle's force and action in multi-articular movement](https://drive.google.com/open?id=0BxbW72zV7WmUcC1zSGpEOUxhWXM&authuser=0). Exercise and Sport Sciences Reviews, 17, 187-230.
- Zatsiorsky VM (2002) [Kinetics of human motion](http://books.google.com.br/books?id=wp3zt7oF8a0C). Human Kinetics.


```python
# Método para resolver las energías y eigenfunciones de un sistema cuántico numéricamente por Teoría de Pertubaciones
# Modelado Molecular 2
# By: José Manuel Casillas Martín     22-oct-2017
import numpy as np
from sympy import *
from sympy.physics.qho_1d import E_n, psi_n
from sympy.physics.hydrogen import E_nl, R_nl
from sympy import init_printing; init_printing(use_latex = 'mathjax')
from scipy import integrate
from scipy.constants import hbar, m_e, m_p, e
from mpmath import spherharm
from numpy import inf, array
import numpy as np
import matplotlib.pyplot as plt
import traitlets
from IPython.display import display
from ipywidgets import Layout, Box, Text, Dropdown, Label, IntRangeSlider, IntSlider, RadioButtons
```

Teoría de Perturbaciones

Consiste en resolver un sistema perturbado(se conoce la solución al no perturbado), y donde el interés es conocer la contribución de la parte perturbada $H'$ al nuevo sistema total.

$$ H = H^{0}+H'$$

La resolución adecuada del problema, depende en gran parte, de una correcta elección de $H'$.

```python
form_item_layout = Layout(display='flex',flex_flow='row',justify_content='space-between')

PType=Dropdown(options=['Particle in a one-dimensional box', 'Harmonic oscilator', 'Hydrogen atom (Helium correction)'])
Pert=Text()
Rang=IntRangeSlider(min=0, max=20, step=1, disabled=False, continuous_update=False, orientation='horizontal',\
                    readout=True, readout_format='d')
M=Text()
Correc=Dropdown(options=['1', '2'])
hbarra=Dropdown(options=[1, 1.0545718e-34])

form_items = [
    Box([Label(value='Problem'),PType], layout=form_item_layout),
    Box([Label(value='Perturbation'),Pert], layout=form_item_layout),
    Box([Label(value='Correction order'),Correc], layout=form_item_layout),
    Box([Label(value='n Range'),Rang], layout=form_item_layout),
    Box([Label(value='Mass'),M], layout=form_item_layout),
    Box([Label(value='Hbar'),hbarra], layout=form_item_layout),]

form = Box(form_items, layout=Layout(display='flex',flex_flow='column',border='solid 2px',align_items='stretch',width='40%'))
form
```

En esta caja interactiva llena los datos del problema que deseas resolver.

# Nota 1:
Es recomendable usar unidades atómicas de Hartree para eficientar los cálculos. 1 u.a. (energía)= 27.211eV.

# Nota 2:
Para la partícula en una caja unidimensional es recomendable que n sea mayor o igual a 1.

## Nota 3:
Para la correción a la energía del átomo de Helio sólo es necesario seleccionar el problema, automáticamente se calcula la correción a primer orden y no se corrigen las funciones de onda.

```python
Problem=PType.value
form_item_layout = Layout(display='flex',flex_flow='row',justify_content='space-between')

L=Text()
W=Text()
atomic_number=RadioButtons(options=['1 (Show Hydrogen energies)','2 (Correct Helium first energy)'],disabled=False)

if Problem=='Particle in a one-dimensional box':
    form_items = [Box([Label(value='Large of box'),L], layout=form_item_layout)]

if Problem=='Harmonic oscilator':
    form_items = [Box([Label(value='Angular Fr'),W], layout=form_item_layout)]

if Problem=='Hydrogen atom (Helium correction)':
    form_items = [Box([Label(value='Atomic number'),atomic_number], layout=form_item_layout)]

form = Box(form_items, layout=Layout(display='flex',flex_flow='column',border='solid 2px',align_items='stretch',width='40%'))
form
```

```python
# Variables que se utilizarán
# x=variable de integracion, l=largo del pozo, m=masa del electrón, w=frecuencia angular
# n=número cuántico principal, Z=Número atómico, q=número cuántico angular(l)
var('x theta phi')
var('r1 r2', real=True)
var('l m hbar w n Z', positive=True, real=True)

# Perturbación
if Pert.value!='':
    H_p=sympify(Pert.value)
    h_p=eval(Pert.value)
else:
    H_p=0
    h_p=0

# Constantes
h=hbarra.value
a0=5.2917721067e-11
if M.value!='':
    mass=float(eval(M.value))
else:
    mass=1

# Energías y funciones que se desea corregir
n_inf=min(Rang.value)
n_sup=max(Rang.value)

if Problem=='Particle in a one-dimensional box':
    if L.value=='':
        large=1
    else:
        large=float(eval(L.value))
    omega=0
    # Energías del pozo de potencial infinito
    k=n*pi/l
    En=hbar**2*k**2/(2*m)

    # Funciones de onda del pozo de potencial infinito
    Psin=sqrt(2/l)*sin(n*pi*x/l)

    # Límites del pozo definido de 0 a l para sympy
    li_sympy=0
    ls_sympy=l
    # Mismo limites para scipy
    li_scipy=0
    ls_scipy=large

if Problem=='Harmonic oscilator':
    large=0
    if W.value=='':
        omega=1
    else:
        omega=float(eval(W.value))
    # Energías del oscilador armónico cuántico
    En=E_n(n,w)

    # Funciones de onda del oscilador armónico cuántico
    Psin=psi_n(n,x,m,w)

     # Límites del pozo definido de -oo a oo para sympy
    li_sympy=-oo
    ls_sympy=oo
    # Límites del pozo definido de -oo a oo para scipy
    li_scipy=-inf
    ls_scipy=inf

if Problem=='Hydrogen atom (Helium correction)':
    if atomic_number.value=='1 (Show Hydrogen energies)':
        z=1
    if atomic_number.value=='2 (Correct Helium first energy)':
        z=2
    large=0
    omega=0

    # Energías del átomo hidrogenoide
    En=z*E_nl(n,z)

    # Funciones de onda del átomo de hidrógeno
    # Número cuántico l=0
    q=0 # La variable l ya esta siendo utilizada para el largo de la caja por ello se sustituyo por q
    Psin=(R_nl(n,q,r1,z)*R_nl(n,q,r2,z))

     # Límites del átomo de hidrógeno de 0 a oo para sympy
    li_sympy=0
    ls_sympy=oo
    # Límites del átomo de hidrógeno de 0 a oo para scipy
    li_scipy=0
    ls_scipy=inf
```

Para sistemas no degenerados, la corrección a la energía a primer orden se calcula como

$$ E_{n}^{(1)} = \int\psi_{n}^{(0)*} H' \psi_{n}^{(0)}d\tau$$

** Tarea 1 : Programar esta ecuación si conoces $H^{0}$ y sus soluciones. **

```python
def correcion_1st_order_Energy(E_n,Psi_n,H_p,li,ls):
    E1_n=Integral(Psi_n*(H_p)*Psi_n,(x,li,ls)).doit()
    return(E_n+E1_n)
```

```python
# Correción de la energía a primer orden
E=[]
Eev=[]
Ec1=[]
if Problem=='Particle in a one-dimensional box' or Problem=='Harmonic oscilator':
    for i in range(n_inf,n_sup+1):
        E.append(En.subs({n:i}))
        Eev.append(E[i-n_inf].subs({m:mass, l:large, hbar:h}).evalf())
        Ec1.append(correcion_1st_order_Energy(En.subs({n:i}),Psin.subs({n:i}),H_p,li_sympy,ls_sympy))
if Problem=='Hydrogen atom (Helium correction)':
    for i in range(n_inf,n_sup+1):
        E.append(En.subs({n:i}))
        Eev.append(E[i-n_inf])
    if z==2:
        integral_1=Integral(Integral((16*z**6*r1*r2**2*exp(-2*z*(r1+r2))),(r2,0,r1)),(r1,0,oo)).doit()
        integral_2=Integral(Integral((16*z**6*r1**2*r2*exp(-2*z*(r1+r2))),(r2,r1,oo)),(r1,0,oo)).doit()
        integral_total=(integral_1+integral_2)
        Ec1.append(E[0]+integral_total)
```

Y la corrección a la función de onda, también a primer orden, se obtiene como:

 $$ \psi_{n}^{(1)} = \sum_{m\neq n} \frac{\langle\psi_{m}^{(0)} | H' | \psi_{n}^{(0)} \rangle}{E_{n}^{(0)} - E_{m}^{(0)}} \psi_{m}^{(0)}$$

**Tarea 2: Programar esta ecuación si conoces $H^{0}$ y sus soluciones. **

```python
# Correción de las funciones a primer orden
if Pert.value!='':
    if Problem=='Particle in a one-dimensional box' or Problem=='Harmonic oscilator':
        Psi_c=[]
        integrals=np.zeros((n_sup+1,n_sup+1))
        for i in range(n_inf,n_sup+1):
            a=0
            for j in range(n_inf,n_sup+1):
                if i!=j:
                    integ= lambda x: eval(str(Psin.subs({n:j})*(h_p)*Psin.subs({n:i}))).subs({m:mass,l:large,w:omega,hbar:h})
                    integrals[i,j]=integrate.quad(integ,li_scipy,ls_scipy)[0]
                    cte=integrals[i,j]/(En.subs({n:i,m:mass,l:large})-En.subs({n:j,m:mass,l:large})).evalf()
                    a=a+cte*Psin.subs({n:j})
            Psi_c.append(Psin.subs({n:i})+a)
```

**Tarea 3: Investigue las soluciones a segundo orden y también programe las soluciones. **

Y la corrección a la energía a segundo orden, se obtiene como:

 $$  E_{n}^{(2)} = \sum_{m\neq n} \frac{|\langle\psi_{m}^{(0)} | H' | \psi_{n}^{(0)} \rangle|^{2}}{E_{n}^{(0)} - E_{m}^{(0)}} $$

```python
# Correción a la energía a segundo orden
if Pert.value!='':
    if Problem=='Particle in a one-dimensional box' or Problem=='Harmonic oscilator':
        if Correc.value=='2':
            Ec2=[]
            for i in range(n_inf,n_sup+1):
                a=0
                for j in range(n_inf,n_sup+1):
                    if i!=j:
                        cte=((integrals[i,j])**2)/(En.subs({n:i,m:mass,l:large,hbar:h})-En.subs({n:j,m:mass,l:large,hbar:h})).evalf()
                        a=a+cte
                Ec2.append(Ec1[i-n_inf]+a)
```

**A continuación se muestran algunos de los resultados al problema resuelto**

Las energías sin perturbación son:

```python
E
```

$$\left [ \frac{\hbar w}{2}, \quad \frac{3 w}{2} \hbar, \quad \frac{5 w}{2} \hbar, \quad \frac{7 w}{2} \hbar\right ]$$

La correción a primer orden de las energías son:

```python
Ec1
```

$$\left [ \frac{\hbar w}{2} + \frac{\hbar}{2 m w}, \quad \frac{3 w}{2} \hbar + \frac{3 \hbar}{2 m w}, \quad \frac{5 w}{2} \hbar + \frac{5 \hbar}{2 m w}, \quad \frac{7 w}{2} \hbar + \frac{7 \hbar}{2 m w}\right ]$$

Si seleccionaste en los parámetros iniciales una correción a segundo orden entonces...

Las correciones a la energía a segundo orden son:

```python
Ec2
```

$$\left [ \frac{\hbar w}{2} - \frac{1}{w} 2.37063083491664 \cdot 10^{33} + \frac{\hbar}{2 m w}, \quad \frac{3 w}{2} \hbar - \frac{1}{w} 7.11189250474994 \cdot 10^{33} + \frac{3 \hbar}{2 m w}, \quad \frac{5 w}{2} \hbar + \frac{1}{w} 2.37063083491664 \cdot 10^{33} + \frac{5 \hbar}{2 m w}, \quad \frac{7 w}{2} \hbar + \frac{1}{w} 7.11189250474994 \cdot 10^{33} + \frac{7 \hbar}{2 m w}\right ]$$

Ahora vamos con la función de onda $(\psi)$

```python
form_item_layout = Layout(
    display='flex',
    flex_flow='row',
    justify_content='space-between')

Graph=IntSlider(min=n_inf, max=n_sup, step=1, disabled=False, continuous_update=False, orientation='horizontal',\
                readout=True, readout_format='d')

form_items = [
    Box([Label(value='What function do you want to see?'),
         Graph], layout=form_item_layout)]

form = Box(form_items, layout=Layout(
    display='flex',
    flex_flow='column',
    border='solid 2px',
    align_items='stretch',
    width='40%'))
form
```

La función de onda original es:

```python
Psin.subs({n:Graph.value})
```

$$\frac{\sqrt[4]{m} \sqrt[4]{w}}{\sqrt[4]{\hbar} \sqrt[4]{\pi}} e^{- \frac{m w x^{2}}{2 \hbar}}$$

La correción a primer orden a la función de onda (utilizando todas las funciones en el rango seleccionado) es:

```python
Psi_c[Graph.value-n_inf]
```

$$\frac{\sqrt[4]{m} \sqrt[4]{w}}{\sqrt[4]{\hbar} \sqrt[4]{\pi}} e^{- \frac{m w x^{2}}{2 \hbar}} - \frac{8.38144569529743 \cdot 10^{32} \sqrt{2} \sqrt[4]{m}}{\sqrt[4]{\hbar} \sqrt[4]{\pi} w^{\frac{3}{4}}} \left(\frac{4 m}{\hbar} w x^{2} - 2\right) e^{- \frac{m w x^{2}}{2 \hbar}}$$

Vamos a graficarlas para verlas mejor...

La función de onda original es:

```python
if Problem=='Particle in a one-dimensional box':
    plot(eval(str(Psin)).subs({n:Graph.value,m:mass,l:large,w:omega,hbar:h}),xlim=(li_scipy,ls_scipy),\
         title='$\psi_{%d}$'%Graph.value)
if Problem=='Harmonic oscilator':
    plot(eval(str(Psin)).subs({n:Graph.value,m:mass,l:large,w:omega,hbar:h}),xlim=(-10*h/(mass*omega),10*h/(mass*omega)),\
         title='$\psi_{%d}$'%Graph.value)
if Problem=='Hydrogen atom (Helium correction)':
    print('Densidad de probabilidad para un electrón')
    plot(eval(str((4*pi*x**2*R_nl(Graph.value,q,x,z)**2))),xlim=(0,10),ylim=(0,20/Graph.value), title='$\psi_{%ds}$'%Graph.value)
    print('Tome en cuenta que debido a la dificultad para seleccionar los límites de la gráfica se muestran bien los primeros\n\
3 estados. A partir de ahí visualizar la gráfica se complica.')
```

La corrección a la función de onda es:

```python
if Problem=='Particle in a one-dimensional box':
    if Pert.value!='':
        plot(eval(str(Psi_c[Graph.value-n_inf])).subs({n:Graph.value,m:mass,l:large,w:omega,hbar:h}),\
             xlim=(li_scipy,ls_scipy),title='$\psi_{%d}$'%Graph.value)
    if Pert.value=='':
        print('No se ingreso ninguna perturbación')
if Problem=='Harmonic oscilator':
    if Pert.value!='':
        plot(eval(str(Psi_c[Graph.value-n_inf])).subs({n:Graph.value,m:mass,l:large,w:omega,hbar:h}),\
             xlim=(-10*h/(mass*omega),10*h/(mass*omega)),title='$\psi_{%d}$' %Graph.value)
    if Pert.value=='':
        print('No se ingreso ninguna perturbación')
if Problem=='Hydrogen atom (Helium correction)':
    print('Este programa no corrige las fucniones de un átomo hidrogenoide')
```

**Tarea 4.  Resolver el átomo de helio aplicando los programas anteriores.**

Para el cálculo a las correciones del átomo de Helio se tomó en cuenta lo siguiente...

La función de onda del átomo de Helio puede ser representada como:

$$ \psi_{nlm} = \psi(r1)_{nlm} \psi(r2)_{nlm}$$

Donde, para el estado fundamental:

$$ \psi(r_{1}.r_{2})_{100} = \frac{Z^{3}}{\pi a_{0}^{3}} e^{\frac{-Z}{a_{0}}(r_{1}+r_{2})}$$

Y la perturbación sería el término de repulsión entre los dos electrones, es decir:

$$ H'= \frac{e^{2}}{r_{12}}=\frac{e^{2}}{|r_{1}-r_{2}|}$$

Finalmente la correción a primer orden de la energía sería:

$$ E^{(1)}= \langle\psi_{n}^{(0)} | H' | \psi_{n}^{(0)} \rangle =\frac{Z^{6}e^{2}}{\pi^{2} a_{0}^{6}} \int_{0}^{2\pi}\int_{0}^{2\pi}\int_{0}^{\pi}\int_{0}^{\pi}\int_{0}^{\infty}\int_{0}^{\infty} \frac{e^{\frac{-2Z}{a_{0}}(r_{1}+r_{2})}}{r_{12}} r_{1}^{2}r_{2}^{2}sen{\theta_{1}}sen{\theta_{2}} dr_{2} dr_{1} d\theta_{2} d\theta_{1} d\phi_{2} d\phi_{1}$$

Se utiliza una expansión del termino de repulsión con los armónicos esféricos y se integra la parte angular. Una vez hecho eso, la integral queda expresada de la siguiente manera:

$$ E^{(1)}= \frac{16Z^{6}e^{2}}{a_{0}^{6}} \left[\int_{0}^{\infty} r_{1}^{2} e^{\frac{-2Z}{a_{0}}r_{1}} \left(\int_{0}^{r_{1}} \frac{r_{2}^{2}}{r_{1}} e^{\frac{-2Z}{a_{0}}r_{2}} dr_{2}+\int_{r_{1}}^{\infty}r_{2} e^{\frac{-2Z}{a_{0}}r_{2}}dr_{2}\right) dr_{1} \right]$$

Esta fue la integral que se programó para hacer la correción a la energía del Helio

**Tarea 5: Método variacional-perturbativo. **

Este método nos permite estimar de forma precisa $E^{(2)}$ y correcciones perturbativas de la energía de órdenes más elevados para el estado fundamental del sistema, sin evaluar sumas infinitas. Ver ecuación 9.38 del libro.

$$ \langle u | H^{0} - E_{g}^{(0)} | u \rangle + \langle u | H' - E_{g}^{(1)} | \psi_{g}^{(0)} \rangle +\langle\psi_{g}^{(0)} | H' - E_{g}^{(1)} | u \rangle \geq E_{g}^{(2)} $$

Donde:

u, es cualquier función que se comporte bien y satisfaga condiciones de frontera.

Por lo general, u tiene un parámetro variacional que permite minimizar el lado izquierdo de la ecuación para estimar $E_{g}^{(2)} $. La función u resulta ser una aproximación a $\psi_{g}^{(1)}$, por lo que se puede utilizar está misma función para estimar $E_{g}^{(3)}$ y seguir haciendo iteraciones para hacer correciones de orden superior tanto a la energía como a la función de onda.

Es necesario meter parámetros de optimización a las funciones de prueba para que tenga sentido intentar programar esto. Esto nos limita a usar Sympy para resolver la integral simbólicamente. Entonces, estamos limitados a las capacidades de esta librería para resolver las integrales y a la capacidad de nuestro procesador. Ya corroboramos que un intel I-7 es cerca de 10 veces más rápido que un I-5.

A continuación se muestra un código que, aprovechando los datos introducidos anteriormente, encuentra por medio del método variacional-perturbativo la correción a segundo orden de la energía y a primer orden de la función de onda.

```python
form_item_layout = Layout(display='flex',flex_flow='row',justify_content='space-between')

F_prueba=Text()
Ran_n=IntSlider(min=n_inf, max=n_sup, step=1, disabled=False, continuous_update=False, orientation='horizontal',\
                    readout=True, readout_format='d')
Correcc=RadioButtons(options=[2],disabled=False)

form_items = [
    Box([Label(value='Test function'),F_prueba], layout=form_item_layout),
    Box([Label(value='Correction order'),Correcc], layout=form_item_layout),
    Box([Label(value='Function to correct'),Ran_n], layout=form_item_layout),]

form = Box(form_items, layout=Layout(display='flex',flex_flow='column',border='solid 2px',align_items='stretch',width='40%'))
form
```

Para la función de prueba se espera que el usuario introduzca una función que sea cuadrado-integrable y que sea compatible en las fronteras con el tipo de problema que se esta solucionando. Además, puede intruducir una constante de optimización (utilice "c")

```python
# Variables que se utilizarán
# c y d=constantes de optimización
var('c')#, real=True)

u=eval(F_prueba.value)
order=Correcc.value
n_n=Ran_n.value

if Problem=='Particle in a one-dimensional box':
    V=0

if Problem=='Harmonic oscilator':
    V=(m/2)*w**2*x**2

if Problem=='Particle in a one-dimensional box' or Problem=='Harmonic oscilator':
    integrando_a=(u)*((-hbar**2)/(2*m)*diff(u,x,2))+(u)*V*(u)-(u)*En.subs({n:n_n})*(u)
    integrando_b=(u)*h_p*(Psin.subs({n:n_n}))-(u)*(Ec1[n_n-n_inf]-En.subs({n:n_n}))*(Psin.subs({n:n_n}))
    integral_a=Integral(eval(str(integrando_a)),(x,li_sympy,ls_sympy)).doit()
    integral_b=Integral(eval(str(integrando_b)),(x,li_sympy,ls_sympy)).doit()
    integral_T=integral_a+2*integral_b
    f_opt=diff(integral_T,c,1)
    c2=solve(f_opt,c)
    E_c2=Ec1[n_n-n_inf]+integral_T.subs({c:c2[0]})
    Psi_c1=(Psin.subs({n:n_n})+u.subs({c:c2[0]}))
```

Se considero que para fines de esta tarea que:

 $$\langle u | H' - E_{g}^{(1)} | \psi_{g}^{(0)} \rangle =\langle\psi_{g}^{(0)} | H' - E_{g}^{(1)} | u \rangle$$

Lo cual se cumple cuando $H'$ es una función sin operadores diferenciales, y además, u y $\psi_{g}^{(0)}$ son funciones reales.

Las correciones a la energía son:

```python
E[n_n-n_inf]
```

$$\frac{\hbar w}{2}$$

```python
Ec1[n_n-n_inf]
```

$$\frac{\hbar w}{2} + \frac{\hbar}{2 m w}$$

```python
E_c2
```

$$- \frac{0.375562772232471 \pi^{0.25} \hbar^{1.0}}{m^{2.0} w^{3.0}} + \frac{0.141047395886939 \sqrt{\pi} \hbar}{m^{2} w^{3}} + \frac{\hbar w}{2} + \frac{\hbar}{2 m w}$$

Las correción a la función de onda:

```python
Psin.subs({n:n_n})
```

$$\frac{\sqrt[4]{m} \sqrt[4]{w}}{\sqrt[4]{\hbar} \sqrt[4]{\pi}} e^{- \frac{m w x^{2}}{2 \hbar}}$$

```python
Psi_c1
```

$$\frac{\sqrt[4]{m} \sqrt[4]{w}}{\sqrt[4]{\hbar} \sqrt[4]{\pi}} e^{- \frac{m w x^{2}}{2 \hbar}} - \frac{0.375562772232471 \sqrt[4]{m} x^{2}}{\hbar^{\frac{5}{4}} w^{\frac{3}{4}}} e^{- \frac{m w x^{2}}{2 \hbar}}$$

Veamos ahora las gráficas de estas funciones...

La función de onda original es:

```python
if Problem=='Particle in a one-dimensional box':
    plot(eval(str(Psin)).subs({n:n_n,m:mass,l:large,w:omega,hbar:h}),xlim=(li_scipy,ls_scipy),\
         title='$\psi_{%d}$'%n_n)
if Problem=='Harmonic oscilator':
    plot(eval(str(Psin)).subs({n:n_n,m:mass,l:large,w:omega,hbar:h}),xlim=(-10*h/(mass*omega),10*h/(mass*omega)),\
         title='$\psi_{%d}$'%n_n)
```

Su correción por medio del método variacional-perturbativo es:

```python
if Problem=='Particle in a one-dimensional box':
    if Pert.value!='':
        plot(Psi_c1.subs({m:mass,l:large,w:omega,hbar:h}),\
             xlim=(li_scipy,ls_scipy),ylim=(-1.5,1.5),title='$\psi_{%d}$'%n_n)
    if Pert.value=='':
        print('No se ingreso ninguna perturbación')
if Problem=='Harmonic oscilator':
    if Pert.value!='':
        plot(Psi_c1.subs({m:mass,l:large,w:omega,hbar:h}),\
             xlim=(-10*h/(mass*omega),10*h/(mass*omega)),title='$\psi_{%d}$' %n_n)
```

**Tarea 6. Revisar sección 9.7. **

Inicialmente a mano, y sengunda instancia favor de intentar programar sección del problema, i.e. integral de Coulomb  e integral de intercambio.

Para comenzar a solucionar este problema, es necesario ser capaz de escribir el termino de repulsión que aparece en la fuerza culombiana ($\frac {1} {r_{12} }$) en términos de los armónicos esféricos de la siguiente manera:

$$ \frac {1} {r_{12} } = \sum_{l=0}^{\infty} \sum_{m=-l}^{l} \frac{4\pi}{2l+1} \frac{r_{<}^{l}}{r_{>}^{l+1}}  \left[Y_{l}^{m}(\theta_{1},\phi_{1})  \right]^{*} Y_{l}^{m}(\theta_{2},\phi_{2})  $$

Intentar programar esto se complica, puesto que los armónicos esféricos sólo han sido definido en librerias de python de forma numérica. Si intentamos programar los armónicos de manera simbólica es necesario utilizar las Polinomios asociados de Legendre, que de igual manera, sólo han sido definidos de manera numérica.

Se podría intentar programar las integral de intercambio de forma numérica pero hacerlo de forma simbólica permitiría simplificar mucho los cálculos, porque al integrar los armónicos esféricos aparecen $\delta_{l,l'}$ y $\delta_{m,m'}$, por lo que la mayoría de las integrales se hacen $0$.

Aún cuando se lograra programar todo esto, hace falta verificar que se seleccionaron correctamente los límites de integración radiales para que el término $\frac{r_{<}^{l}}{r_{>}^{l+1}}$ haga sentido.

```python

```


# Models and Pricing of Financial Derivatives HW_03

**11510691 程远星$\DeclareMathOperator*{\argmin}{argmin}
\DeclareMathOperator*{\argmax}{argmax}
\DeclareMathOperator*{\plim}{plim}
\newcommand{\using}[1]{\stackrel{\mathrm{#1}}{=}}
\newcommand{\ffrac}{\displaystyle \frac}
\newcommand{\asim}{\overset{\text{a}}{\sim}}
\newcommand{\space}{\text{ }}
\newcommand{\bspace}{\;\;\;\;}
\newcommand{\QQQ}{\boxed{?\:}}
\newcommand{\void}{\left.\right.}
\newcommand{\Tran}[1]{{#1}^{\mathrm{T}}}
\newcommand{\d}[1]{\displaystyle{#1}}
\newcommand{\CB}[1]{\left\{ #1 \right\}}
\newcommand{\SB}[1]{\left[ #1 \right]}
\newcommand{\P}[1]{\left( #1 \right)}
\newcommand{\abs}[1]{\left| #1 \right|}
\newcommand{\norm}[1]{\left\| #1 \right\|}
\newcommand{\dd}{\mathrm{d}}
\newcommand{\Exp}{\mathrm{E}}
\newcommand{\RR}{\mathbb{R}}
\newcommand{\EE}{\mathbb{E}}
\newcommand{\II}{\mathbb{I}}
\newcommand{\NN}{\mathbb{N}}
\newcommand{\ZZ}{\mathbb{Z}}
\newcommand{\QQ}{\mathbb{Q}}
\newcommand{\PP}{\mathbb{P}}
\newcommand{\AcA}{\mathcal{A}}
\newcommand{\FcF}{\mathcal{F}}
\newcommand{\AsA}{\mathscr{A}}
\newcommand{\FsF}{\mathscr{F}}
\newcommand{\Var}[2][\,\!]{\mathrm{Var}_{#1}\left[#2\right]}
\newcommand{\Avar}[2][\,\!]{\mathrm{Avar}_{#1}\left[#2\right]}
\newcommand{\Cov}[2][\,\!]{\mathrm{Cov}_{#1}\left(#2\right)}
\newcommand{\Corr}[2][\,\!]{\mathrm{Corr}_{#1}\left(#2\right)}
\newcommand{\I}[1]{\mathrm{I}\left( #1 \right)}
\newcommand{\N}[1]{\mathcal{N} \left( #1 \right)}
\newcommand{\ow}{\text{otherwise}}
\newcommand{\FSD}{\text{FSD}}
\void^\dagger$**

## Question 1

$\P{1}$

$\bspace \begin{align}
\dd y &= \dd\P{2S_t}\\
&= \P{0 + \P{\mu S_t}\cdot 2 + \ffrac{1}{2}\P{\sigma S_t}^2  \cdot 0}\dd t + \sigma S_t \cdot 2 \dd z\\
&= 2\mu S_t \dd t + 2\sigma S_t \dd z\\
&= \mu y \dd t + \sigma y\dd z
\end{align}$

$\P{2}$

$\bspace \begin{align}
\dd y &= \dd\P{S_t^2}\\
&= \P{0 + \P{\mu S_t}\cdot S_t + \ffrac{1}{2}\P{\sigma S_t}^2  \cdot 2}\dd t + \P{\sigma S_t} \cdot S_t \dd z\\
&= \P{2\mu S_t^2 + \sigma^2 S_t^2}\dd t + 2\sigma S_t^2 \dd z\\
&= \P{2\mu + \sigma^2}y\dd t + 2\sigma y \dd z
\end{align}$

$\P{3}$

$\bspace \begin{align}
\dd y &= \dd\P{e^{S_t}}\\
&= \P{0 + \P{\mu S_t}\cdot e^{S_t} + \ffrac{1}{2}\P{\sigma S_t}^2  \cdot e^{S_t}}\dd t + \P{\sigma S_t} \cdot e^{S_t} \dd z\\
&= \P{\mu \log y + \ffrac{1}{2} \P{\sigma \log y}^2}y\dd t + \P{\sigma \log y} \cdot y\dd t
\end{align}$

$\P{4}$

$\bspace \begin{align}
\dd y &= \dd\P{\ffrac{e^{r\P{T-t}}}{S_t}}\\
&= \P{\ffrac{-re^{r\P{T-t}}}{S_t} + \P{\mu S_t}\cdot \P{-\ffrac{e^{r\P{T-t}}}{S_t^2}} + \ffrac{1}{2}\P{\sigma S_t}^2  \cdot \ffrac{2e^{r\P{T-t}}}{S_t^3}}\dd t + \P{\sigma S_t} \cdot \P{-\ffrac{e^{r\P{T-t}}}{S_t^2}} \dd z\\
&= \P{-r-\mu-\sigma^2}y\dd t - \sigma y \dd y
\end{align}$

## Question 2

$\bspace$It is a Brownian motion, the four conditions are checked correct below. We first let the drift and volatility of $W_t$ and $\widetilde W_t$ are $\mu,\sigma$ and $\check\mu,\check\sigma$, respectively. Denote $\widehat W_t$ as the standard Brownian motion, then $\forall\; t>s$, we have

$$\begin{align}
X_t - X_s  &= \rho\P{W_t - W_s} + \sqrt{1-\rho^2}\P{\widetilde W_t - \widetilde W_s} \\
&= \rho\P{\mu \P{t-s} + \sigma \P{\widehat W_t-\widehat W_s}} + \sqrt{1-\rho^2}\P{\check\mu \P{t-s} + \check\sigma \P{\widehat W_t - \widehat W_s}}\\
&= \P{\rho \mu + \sqrt{1-\rho^2}\check \mu}\P{t-s} + \P{\rho\sigma + \sqrt{1-\rho^2}\check\sigma}\P{\widehat W_t - \widehat W_s}
\end{align}$$

- Let $\rho \mu + \sqrt{1-\rho^2}\check \mu \equiv \dot \mu$ and $\rho\sigma + \sqrt{1-\rho^2}\check\sigma\equiv\dot\sigma$, then

$$X_t - X_s = \dot\rho\P{t-s} + \dot\sigma\P{W_t-W_s} \sim \N{\dot\rho\P{t-s},\dot\sigma^2 \P{t-s}},\bspace\forall\; t>s$$

- Consider $t$ and $s$ as two adjacent time in the interval $\SB{0,T}$. Then since $\widehat W_t$ has independent increments, so is $X_t - X_s$, judging from its expression.
- $X_0 = \dot\rho t + \dot\sigma \widehat W_t \mid_{t=0} = \widehat W_0 = 0$
- Still, from the expression of $X_t$, $t$ is continuous and the path $\SB{W_t:t\geq 0}$ are also continuous functions, $X_t$ is continuous.

## Question 3

$\P{1}$

$\bspace$It is a $\PP$-Brownian motion.

- $\forall\; t>s$, the increment $\P{-W_t} - \P{-W_s} = W_s - W_t$ also has the normal distribution $\N{0,t-s}$
- The process $-W_t$ has independent increments: for any set of times $0\leq t_1<t_2<\cdots<t_n$, the $r.v.$ $-W_{t_{\void_2}} + W_{t_{\void_1}}$, $-W_{t_{\void_3}} + W_{t_{\void_2}}$, $\dots$, $-W_{t_{\void_{n}}} + W_{t_{\void_{n-1}}}$ are also independent, since their inverse are.
- $-W_0 = 0$
- The sample paths: $\SB{-W_t: t \geq 0}$ are continuous function of $t$ since $\SB{W_t: t \geq 0}$ are.

$\P{2}$

$\bspace$It is a $\PP$-Brownian motion.

- $\forall\; t>s$, the increment $c\P{W_{t/c^{\void_2}}} - c\P{W_{s/c^{\void_2}}}$ also has the normal distribution $\N{0,c^2\P{t/c^2 - s/c^2}} = \N{0,t-s}$
- The process $cW_{t/c^{\void_2}}$ has independent increments: for any set of times $0\leq t_1<t_2<\cdots<t_n$, the $r.v.$ $-W_{t_{\void_2}} + W_{t_{\void_1}}$, $-W_{t_{\void_3}} + W_{t_{\void_2}}$, $\dots$, $-W_{t_{\void_{n}}} + W_{t_{\void_{n-1}}}$ are also independent, since they are a subset of  $r.v.$ with time range from $0$ to $c^2 t_n$
- $-cW_{0/c^{\void_2}} = cW_0 = 0$
- The sample paths: $\SB{-W_{t/c^{\void_2}}: t \geq 0}$ are continuous function of $t$ since $\SB{W_t: t \geq 0}$ are, so that we can multiply a constant and rescale the time axis to its $1/c^2$ while keeping the continuity

$\P{3}$

$\bspace$It's not. We next prove this process doesn't have the independent increments. Here's the covariance if taking the time $0$, $s$, and $t$.

$$\begin{align}
&\Cov{\sqrt{t} W_1 - \sqrt s W_1, \sqrt s W_1}\\
=&\; \P{\sqrt t - \sqrt s}\sqrt s \cdot \Var{W_1}\\
=&\; \P{\sqrt t - \sqrt s}\sqrt s \neq 0
\end{align}$$

$\P{4}$

$\bspace$It's not. Still, let's see the covariance, taking the time $0$, $2s$ and $2t$.

$$\begin{align}
   &\Cov{\P{W_{2t} - W_t}-\P{W_{2s} - W_s}, W_{2s} - W_s}\\
=\;&\Cov{\P{W_{2t} - W_{2s}}-\P{W_t - W_s}, W_{2s} - W_s}\\
=\;&\Cov{W_{2t} - W_{2s},W_{2s}} + \Cov{\P{W_t - W_s}, W_s}\\
\;&\bspace - \Cov{W_{2t} - W_{2s},W_{s}} - \Cov{\P{W_t - W_s},W_{2s}}\\
=\;& 0+2\Cov{W_{2s},W_s} - \Cov{W_{2t},W_s} - \Cov{W_{t},W_{2s}}\\
=\;& 0+2\Cov{W_{2s} - W_s,W_s}+2\Cov{W_s,W_s} - \Cov{W_{2t}-W_s,W_s} + \Cov{W_s,W_s} - \Cov{W_{t},W_{2s}}\\
=\;& \Var{W_s} - \Cov{W_{t},W_{2s}} = s - \Cov{W_{t},W_{2s}}
\end{align}$$

$\bspace$If $t > 2s$, then the preceding equals to $s - \Var{W_{2s}} = -s \neq 0$.

## Question 4

$$\begin{align}
\Exp\SB{e^{\theta X}} &= \int^{\infty}_{-\infty} e^{\theta X}\cdot\ffrac{1}{\sqrt{2\pi}\sigma}\exp\CB{-\ffrac{ \P{x-\mu}^2}{2\sigma^2}}\;\dd x\\
&= \int^{\infty}_{-\infty} e^{\theta X}\cdot\ffrac{1}{\sqrt{2\pi}\sigma}\exp\CB{-\ffrac{ \P{x-\mu+\theta\sigma^2}^2}{2\sigma^2}} \cdot\exp\CB{\ffrac{\theta^2\sigma^2}{2} + \theta\mu}\;\dd x\\
&= \exp\CB{\ffrac{\theta^2\sigma^2}{2} + \theta\mu}
\end{align}$$

$\bspace$And to find $\Exp\SB{X^4} = \left.\ffrac{\dd^4}{\dd \theta^4}\Exp\SB{e^{\theta X}}\right|_{\theta=0}$, we let $f\P{\theta} = \ffrac{\theta^2\sigma^2}{2} + \theta\mu$, then

$$\begin{align}
\ffrac{\dd^4}{\dd \theta^4}\Exp\SB{e^{\theta X}} &= \ffrac{\dd^3}{\dd \theta^3}\P{f' e^f}\\
&= \ffrac{\dd^2}{\dd \theta^2}\P{\P{f'^2 + f''} e^f}\\
&= \ffrac{\dd}{\dd \theta}\P{\P{2f''f' + f^{\P{3}}+f'} e^f}\\
&= \P{\P{2f^{\P{3}}f' + f^{\P{4}}+f'+f''+2\P{f''}^2} e^f}
\end{align}$$

$\bspace$Plug in $\theta=0$ and by $f = 0 = f^{\P{3}} = f^{\P{4}}$, $f' = \mu$, $f'' = \sigma^2$, we have

$$\Exp\SB{X^4} = 2\sigma^4 + \sigma^2 + \mu$$

## Question 5

$\P{1}$

$\bspace$It's not. Since $\Exp\SB{\abs{e^{\sigma W_t}}} = \exp\CB{\ffrac{1}{2}\sigma^2t} < \infty$. Now see the second condition.

$$\begin{align}
\Exp_s\SB{e^{\sigma W_t}} &= \Exp_s\SB{e^{\sigma W_s}\cdot e^{\sigma \P{W_t-W_s}}}\\
&= e^{\sigma W_s} \Exp_s\SB{e^{\sigma \P{W_t-W_s}}} \\
&= e^{\sigma W_s} \Exp\SB{e^{\sigma W_{t-s}}}\\
&= \exp\CB{\sigma W_s +\ffrac{\sigma^2}{2}\P{t-s}} \neq e^{\sigma W_s}
\end{align}$$

$\P{2}$

$\bspace$It is, if only $c\geq 1$ because if not then the process is not even adapted to the filtration. Now suppose $c\geq1$, then $\Exp\SB{\abs{cW_{t/c^{\void_2}}}} \leq \Exp\SB{\ffrac{1+c^2W_{t/c^{\void_2}}^2}{2}} = \ffrac{1+ c^2\cdot t/c^2}{2} = \ffrac{1+t}{2} < \infty$. Now see the second condition.

$$\begin{align}
\Exp_s\SB{cW_{t/c^{\void_2}}} &= cW_{s/c^{\void_2}} + c\Exp_s\SB{W_{t/c^{\void_2}} - W_{s/c^{\void_2}}}\\
&= cW_{s/c^{\void_2}} + \Exp\SB{W_{\P{t-s}/c^{\void_2}}}\\
&= cW_{s/c^{\void_2}} \\
&\surd
\end{align}$$

$\P{3}$

$\bspace$It is. For the first condition,

$$\begin{align}
\Exp\SB{\abs{tW_t - \d{\int_{0}^{t} W_s\;\dd s}}} &\leq  \Exp\SB{\abs{tW_t} + \abs{\d{\int_{0}^{t} W_s\;\dd s}}}\\
&\leq t\cdot\Exp\SB{\ffrac{W_t^2 + 1}{2}} + \int_{0}^{t} \Exp\SB{\abs{W_s}}\;\dd s\\
&\leq t\cdot\ffrac{1+t}{2} + \int_{0}^{t} \ffrac{1+s}{2}\;\dd s\\
&= t + \ffrac{3}{4}t^2 <\infty
\end{align}$$

$\bspace$And then the second one, in the review we have

$$tW_t - \int_{0}^{t} W_s\;\dd s = \int_0^t s\dd W_t$$

$\bspace$It's an Itô's process! Thus it's a martingale.

## Question 6

$\bspace$Following the three conditions that define the martingale, we have

$$\Exp\SB{\abs{f}}<\infty\\
\Exp_s\SB{f\P{t,W_t}} = f\P{s,W_s}$$

$\bspace$And to check this, it fails the second one

$$\Exp\SB{\abs{e^{vt + \sigma W_t}}}= \Exp\SB{{e^{vt + \sigma W_t}}} = \exp\CB{vt + \ffrac{1}{2}\sigma^2 t} < \infty$$

$$\begin{align}
\Exp_s\SB{e^{vt+\sigma W_t}} &= e^{vs+\sigma W_t}\exp\CB{\ffrac{\sigma^2}{2}t}\Exp\SB{e^{\sigma\P{W_t - W_s}}}\\
&= \exp\CB{vt + \ffrac{\sigma^2}{2}\P{t-s}+\sigma W_s}\neq e^{vs + \sigma W_s}
\end{align}$$

## Question 7

$\bspace$Firstly, it's adapted to $\FcF_t$ and likewise we have $\Exp\SB{\abs{I_n}} \leq \Exp\SB{\ffrac{I_n^2+1} {2}}<\infty$. Then,

$$\begin{align}
\Exp_s\SB{I\P{t}} =& I\P{s} + \Exp_s\SB{I\P{t} - I\P{s}} \\[0.6em]
&\bspace \text{partition the interval } \SB{s,t} \text{ in } n \text{ subintervals}\\[0.5em]
=& I\P{s} + \Exp_s\SB{ \lim_{n\to\infty} \sum_{j=0}^{n-1} h\P{t_j, W_{t_{\void_{j}}}}\P{W_{t_{\void_{j+1}}} - W_{t_{\void_{j}}}} }\\[0.6em]
&\bspace \text{assume the summation is exchangable with the expectation } \\[0.5em]
=& I\P{s} + \lim_{n\to\infty} \sum_{j=0}^{n-1} \Exp_s\SB{ h\P{t_j, W_{t_{\void_{j}}}}\P{W_{t_{\void_{j+1}}} - W_{t_{\void_{j}}}} }\\[0.6em]
&\bspace \text{condition on }\FcF_{t_{\void_{j}}}, \Exp\SB{X\mid Y} = \Exp\SB{\Exp\SB{X \mid Y,W} \mid Y} \\[0.5em]
=& I\P{s} + \lim_{n\to\infty} \sum_{j=0}^{n-1} \Exp_s\SB{ \Exp_{t_{\void_{j}}}\SB{ h\P{t_j, W_{t_{\void_{j}}}} \P{W_{t_{\void_{j+1}}} - W_{t_{\void_{j}}}} } }\\
=& I\P{s} + \lim_{n\to\infty} \sum_{j=0}^{n-1} \Exp_s\SB{  h\P{t_j, W_{t_{\void_{j}}}} } \Exp_{t_{\void_{j}}} \SB{{W_{t_{\void_{j+1}}} - W_{t_{\void_{j}}}} }\\[0.5em]
=& I\P{s}
\end{align}$$

## Question 8

$\P{1}$

$\bspace$Let $X_t = W_t$, then

$$\begin{align}\dd Y_t &= \P{0 + 0 \cdot 3X_t^2 + \ffrac{1}{2}\cdot1\cdot6X_t}\dd t + 1\cdot 3 X_t^2 \dd W_t\\
&= 3X_t \dd t + 3X_t^2 \dd W_t\\
&= 3\sqrt[3]{Y_t} \dd t + 3\sqrt[3]{Y_t^2} \dd W_t
\end{align}$$

$\bspace$It's not a martingale since

$$\begin{align}
\Exp_s\SB{W_t^3} &= \Exp_s\SB{\P{W_t - W_s + W_s}^3}\\
&= \Exp_s\SB{\P{W_t - W_s}^3} + \Exp_s\SB{3\P{W_t - W_s}^2W_s} + \Exp_s\SB{3\P{W_t-W_s}W_s} + W_s^3\\
&= W_s^3 + 3W_s\Exp\SB{\P{W_t-W_s}^2}\\
&= W_s^3 + 3W_s\P{t-s} \neq W_s^3
\end{align}$$

$\P{2}$

$\bspace$Still let $X_t = X_t$, then

$$\begin{align}
\dd Y_t &= \dd\P{\exp\CB{-\ffrac{1}{2}\sigma^2 t} e^{\sigma W_t}}\\
&= Y_t\P{-\ffrac{1}{2}\sigma^2 \dd t - \ffrac{1}{2}\sigma^2 \dd t + \sigma\dd W_t + \ffrac{1}{2}\sigma^2 \dd t}\\
&= Y_t\P{-\ffrac{1}{2}\sigma^2 \dd t + \sigma \dd W_t}
\end{align}$$

$\bspace$It's a martingale. We denote $M_t = \exp\CB{\sigma W_t - \ffrac{1} {2} \sigma^2 t}$. For the expectation part:

$$\Exp\SB{\abs{M_t}} = \int_{-\infty}^{\infty} \exp\CB{\sigma W_t - \ffrac{1} {2} \sigma^2 t} \cdot\ffrac{1} {\sqrt{2\pi t}} \exp\CB{-\ffrac{x^2} {2t}}\dd{x} = 1 < \infty$$

$$\Exp_s\SB{M_t} = \Exp_s\SB{M_s\cdot M_{t-s}} = M_s\Exp_s\SB{M_{t-s}} = M_s$$

## Question 9

$\bspace$Here let $X_t = \alpha W_t$ and we obtain

$$\begin{align}
\dd Z_t &= \dd\P{e^{X_t}}\\
&= \P{0 + 0 + \ffrac{1}{2}\alpha^2 e^{X_t}}\dd t + \alpha e^{X_t} \dd W_t\\
&= Z_t\P{\ffrac{1}{2}\alpha^2 \dd t + \alpha \dd W_t}
\end{align}$$

$$\begin{align}
m\P{t} &= \Exp\SB{Z_t} = \Exp\SB{e^{\alpha W_t}}\\
&= \Exp\SB{e^{\alpha W_0} + \int_0^t \alpha e^{\alpha W_s}\;\dd W_s + \int_0^t\ffrac{1}{2}\alpha^2 e^{\alpha W_s}\;\dd s}\\
&= \Exp\SB{1} + \Exp\SB{\int_0^t \alpha e^{\alpha W_s}\;\dd W_s} + \Exp\SB{\int_0^t\ffrac{1}{2}\alpha^2 e^{\alpha W_s}\;\dd s}\\
&= 1 + 0 + \int_0^t\ffrac{1}{2}\alpha^2 \Exp\SB{e^{\alpha W_s}}\;\dd s\\
&= 1 + \ffrac{1}{2}\alpha^2\int_0^tm\P{s}\;\dd s
\end{align}$$

$$\begin{align}\dd m\P{t} &= \ffrac{1}{2}\alpha^2 m\P{t} + C\\
\Longrightarrow m\P{t} &= \exp\CB{\ffrac{1}{2}\alpha^2 t}-\ffrac{2C}{\alpha^2}\\
m\P{0}=1\Rightarrow m\P{t} &= \Exp\SB{e^{\alpha W_t}} = \exp\CB{\ffrac{1}{2}\alpha^2 t}
\end{align}$$

## Question 10

$\bspace$To verify, we first rewrite the equation to $e^{\alpha t}\dd X_t = -\alpha e^{\alpha t}X_t\dd t + e^{\alpha t}\dd W_t$ and this is equivalent to

$$\dd\P{e^{\alpha t}X_t} = e^{\alpha t}\dd W_t \\
\Longrightarrow e^{\alpha t}X_t - 1 \cdot X_0 = \int_0^t e^{\alpha s}\;\dd W_s\\
\Longrightarrow X_t = e^{-\alpha t}x + e^{-\alpha t}\int_0^t e^{\alpha s}\;\dd W_s
$$

$\bspace$And about the mean

$$\begin{align}
\Exp\SB{X_t} &= \Exp\SB{e^{-\alpha t}x + e^{-\alpha t}\int_0^t e^{\alpha s}\;\dd W_s}\\
&= e^{-\alpha t}x + e^{-\alpha t}\Exp\SB{\int_0^t e^{\alpha s}\;\dd W_s}\\
&= e^{-\alpha t}x + e^{-\alpha t} \cdot 0\\
&= e^{-\alpha t}
\end{align}$$

$\bspace$To find the variance, by $\Var{X_t}=\Exp\SB{X_t^2}-\P{\Exp\SB{X_t}}^2$, we first need to apply the Itô's isommetry to find the second moment

$$\begin{align}
\Exp\SB{X_t^2} &= \Exp\SB{e^{-2\alpha t}x^2 + 2e^{-2\alpha t}x\int_0^t e^{\alpha s}\;\dd W_s + e^{-2\alpha t}\P{\int_0^t e^{\alpha s}\;\dd W_s}^2}\\
&= \Exp\SB{e^{-2\alpha t}x^2} + \Exp\SB{ 2e^{-2\alpha t}x\int_0^t e^{\alpha s}\;\dd W_s} + e^{-2\alpha t}\Exp\SB{\P{\int_0^t e^{\alpha s}\;\dd W_s}^2}\\
&= e^{-2\alpha t}x^2 + 0 + e^{-2\alpha t}\int_0^t \Exp\SB{e^{2\alpha s}}\dd s\\
&= e^{-2\alpha t}x^2 + \ffrac{1}{2\alpha}\P{1 - e^{-2\alpha t}}
\end{align}$$

$\bspace$With this, we can compute the final variance

$$
\begin{align}
\Var{X_t}&=\Exp\SB{X_t^2}-\P{\Exp\SB{X_t}}^2\\
&= e^{-2\alpha t}x^2 + \ffrac{1}{2\alpha}\P{1 - e^{-2\alpha t}} - x^2e^{-2\alpha t}\\
&= \ffrac{1}{2\alpha}\P{1-e^{-2\alpha t}}
\end{align}
$$

## Question 11

$\bspace$To make this simple, we write $\dd X_t = \mu \dd t + \sigma_t \dd W_t$ where $W_t$ is the standard Brownian motion under measure $\PP$. Let $\widetilde W_t$ is that under measure $\PP^*$, then we have

$$\dd X_t = \nu \dd t + \sigma_t \dd \widetilde W_t$$

$\bspace$So we can define $\widetilde W_t = W_t + \ffrac{\mu - \nu}{\sigma}t$. Then by Girsanov’s Theorem, we can define the measure $\PP^*$

$$\left.\ffrac{\dd \PP^*}{\dd \PP}\right|_{\FcF_t} = \exp\CB{-\theta W_t - \ffrac{1}{2}\theta^2 t},\bspace \theta = \ffrac{\mu - \nu}{\sigma}$$

## Question 12

$\bspace$By F-K formula, we have the solution of the corresponding stochastic differential equation

$$\dd X_t = \mu_t\dd t + \sigma_t \dd W_t$$

$\bspace$where $\mu_t = 0$, $r = 0$, and $\sigma_t = \sigma$. So that the solution is, in integral form,

$$X_t = \sigma W_t + X_0$$

$\bspace$So that the solution $F\P{t,x}$

$$\begin{align}
F\P{t,x} &= \Exp\SB{e^{-r\P{T-t}} e^{X_T} \mid X_t = x} \\
&= \Exp\SB{e^{-0\P{T-t}} e^{\sigma W_T} \mid W_t = x} \\
&= \Exp\SB{e^{\sigma\P{ W_T - W_t +x}} \mid W_t = x}\\
&= e^{\sigma x}\Exp\SB{e^{\sigma\P{ W_T - W_t}}}\\
&= \exp\CB{\sigma x + \ffrac{\sigma^2}{2}\P{T-t}}
\end{align}$$

***

FinMath/Models and Pricing of Financial Derivatives/HW/HW_03_11510691.ipynb