## First Assignment

#### 1) Apply the appropriate string methods to the **x** variable (as '.upper') to change it exactly to: "$Dichlorodiphenyltrichloroethane$".

```python
x = "DiClOrod  IFeNi  lTRicLOr oETaNo  DiChlorod iPHeny lTrichL oroEThaNe"
```

```python
x.replace(' ','').capitalize().replace("c","ch").replace("feni","pheny").replace("anodichhlorodiphenyltrichhloroethane","hane")
```

    'Dichlorodiphenyltrichloroethane'

#### 2) Assign respectively the values: 'word', 15, 3.14 and 'list' to variables A, B, C and D in a single line of code. Then, print them in that same order on a single line separated by a space, using only one print statement.

```python
A, B, C, D = "word", 15, 3.15, "list"
print("A: {} B: {} C: {} D:{}".format(A, B, C, D))
```

    A: word B: 15 C: 3.15 D:list

#### 3) Use the **input()** function to receive an input in the form **'68.4 1.71'**, that is, two floating point numbers in a line separated by space. Then, assign these numbers to the variables **w** and **h** respectively, which represent an individual's weight and height (hint: take a look at the '.split()' method). With this data, calculate the individual's Body Mass Index (BMI) from the following relationship:

\begin{equation}
BMI = \dfrac{weight}{height^2}
\end{equation}

```python
w, h = input().split()
print("w = ",w,",h = ",h)
BMI = ((float(w))/((float(h)/100)**2))/10000
print(BMI)
```

#### This value can also be classified according to ranges of values, following to the table below. Use conditional structures to classify and print the classification assigned to the individual.

<\center>

(source: https://healthtravelguide.com/bmi-calculator/)

```python
w, h = input().split()
print("w = ",w,",h = ",h)
BMI = ((float(w))/((float(h)/100)**2))/10000
if BMI < 18.5:
    print("Underweight")
elif 18.5 < BMI < 24.9:
    print("Normal weight")
elif 25 < BMI < 29.9:
    print("Pre-obesity")
elif 30 < BMI < 34.9:
    print("Obesity class I")
elif 35 < BMI < 39.9:
    print("Obesity class II")
elif BMI > 40:
    print("Obesity class III")
```

#### 4) Receive an integer as an input and, using a loop, calculate the factorial of this number, that is, the product of all the integers from one to the number provided.

```python
x = int(input())
fac = 1

for i in range(1, x + 1):
    fac = fac * i

print("factorial of " + str(x) + " is " + str(fac))
```

    23
    factorial of 23 is 25852016738884976640000

#### 5) Using a while loop and the input function, read an indefinite number of integers until the number read is -1. Present the sum of all these numbers in the form of a print, excluding the -1 read at the end.

```python
sum = 0
minus = int(input())

while minus != -1:
    sum = sum + minus
    minus = int(input())

if minus == -1:
    print("The sum is: " + str(sum))
else: print("oops")
```

    2
    4
    -2
    -1
    The sum is: 4

#### 6) Read the **first name** of an employee, his **amount of hours worked** and the **salary per hour** in a single line separated by commas. Next, calculate the **total salary** for this employee and show it to two decimal places.

```python
employee = {"name": "Walter", "hours": 35, "sph": 12.62}
salary = (employee["hours"] * employee["sph"])*4
print("{:.2f}".format(salary))
```

    1766.80

#### 7) Read three floating point values **A**, **B** and **C** respectively. Then calculate itens a, b, c, d and e:

```python
A = float(input())
B = float(input())
C = float(input())
```

    2
    3
    6

    a) the area of the triangle rectangle with A as the base and C as the height.

```python
a = (A*B)/2
print a
```

    3.0

    b) the area of the circle of radius C. (pi = 3.14159)

```python
b = (C*C)*3.14159
print b
```

    113.09724

    c) the area of the trapezoid that has A and B for bases and C for height.

```python
c = ((A+B)*C)/2
print c
```

    15.0

    d) the area of the square that has side B.

```python
d = B*B
print d
```

    9.0

    e) the area of the rectangle that has sides A and B.

```python
e = A*B
print e
```

    6.0

#### 8) Read **the values a, b and c** and calculate the **roots of the second degree equation** $ax^{2}+bx+c=0$ using [this formula](https://en.wikipedia.org/wiki/Quadratic_equation). If it is not possible to calculate the roots, display the message **“There are no real roots”**.

```python
x = ((-b) +- 2 ** (b*b - 4*a*c)) / 2*a
if (((a*x)*(a*x))+b*x+c) == 0:
    print x
else: print("There are no real roots.")
```

#### 9) Read four floating point numerical values corresponding to the coordinates of two geographical coordinates in the cartesian plane. Each point will come in a line with its coordinates separated by space. Then calculate and show the distance between these two points.

(obs: $d=\sqrt{(x_1-x_2)^2 + (y_1-y_2)^2}$)

```python
import math
from math import sqrt

x1 = int(input("x1: "))
y1 = int(input("y1: "))
x2 = int(input("x2: "))
y2 = int(input("y2: "))

# x1, y1 = int(input("x1 & y1: ")).split()
# x2, y2 = int(input("x2 & y2: ")).split()

diff = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
print(round(diff,3))
```

    x1: 2
    y1: 5
    x2: -9
    y2: 17
    16.279

#### 10) Read **two floating point numbers** on a line that represent **coordinates of a cartesian point**. With this, use **conditional structures** to determine if you are at the origin, printing the message **'origin'**; in one of the axes, printing **'x axis'** or **'y axis'**; or in one of the four quadrants, printing **'q1'**, **'q2**', **'q3'** or **'q4'**.

```python
x = int(input("x: "))
y = int(input("y: "))

if (x > 0):
    if (y > 0):
        print("q1")
    elif (y < 0):
        print("q4")
elif (x < 0):
    if (y > 0):
        print("q2")
    elif (y < 0):
        print("q3")
elif (x == 0):
    if (y != 0):
        print("x axis")
    elif (y == 0):
        print("origin")
elif (y == 0):
    if (x != 0):
        print("y axis")
else: print("oops")
```

    x: 9
    y: 9
    9
    9
    q1

#### 11) Read an integer that represents a phone code for international dialing.
#### Then, inform to which country the code belongs to, considering the generated table below:
(You just need to consider the first 10 entries)

```python
import pandas as pd
df = pd.read_html('https://en.wikipedia.org/wiki/Telephone_numbers_in_Europe')[1]
df = df.iloc[:,:2]
df.head(20)
```

      0
      1

      0
      Country
      Country calling code

      1
      Austria
      43

      2
      Belgium
      32

      3
      Bulgaria
      359

      4
      Croatia
      385

      5
      Cyprus
      357

      6
      Czech Republic
      420

      7
      Denmark
      45

      8
      Estonia
      372

      9
      Finland
      358

      10
      France
      33

      11
      Germany
      49

      12
      Greece
      30

      13
      Hungary
      36

      14
      Iceland
      354

      15
      Ireland
      353

      16
      Italy
      39

      17
      Latvia
      371

      18
      Liechtenstein
      423

      19
      Lithuania
      370

```python
phone = str(input())
if phone.startswith("43"):
    print("Austria"),
elif phone.startswith("32"):
    print("Belgium")
elif phone.startswith("359"):
    print("Bulgaria")
elif phone.startswith("385"):
    print("Croatia")
elif phone.startswith("357"):
    print("Cyprus")
elif phone.startswith("420"):
    print("Czech Republic")
elif phone.startswith("45"):
    print("Denmark")
elif phone.startswith("372"):
    print("Estonia")
elif phone.startswith("358"):
    print("Finnland")
elif phone.startswith("33"):
    print("France")
else: print("Country not detected")
```

    35888
    Finnland

#### 12) Write a piece of code that reads 6 numbers in a row. Next, show the number of positive values entered. On the next line, print the average of the values to one decimal place.

```python
sixnum = list(map(int, input().split()))
pos = 0
for num in sixnum:
    if(num % 2 == 0):
        pos = pos + 1
print(pos)
avg = len(sixnum)/pos
print (round(avg,2))
```

#### 13) Read an integer **N**. Then print the **square of each of the even values**, from 1 to N, including N, if applicable, arranged one per line.

```python
N = int(input())

for number in range(1, N+1):
    if(number % 2 == 0):
        print ("{0}".format(number))
```

    8
    2
    4
    6
    8

#### 14) Using **input()**, read an integer and print its classification as **'even / odd'** and **'positive / negative'** . The two classes for the number must be printed on the same line separated by a space. In the case of zero, print only **'null'**.

```python
x = int(input())

if (x % 2 == 0) & x > 0:
    print ("even positive")
elif (x % 2 == 0) & x < 0:
    print ("even negative")
elif (x % 2 != 0) & x > 0:
    print ("odd positive")
elif (x % 2 != 0) & x < 0:
    print ("odd negative")
elif x == 0:
    print("null")
```

    789
    odd positive

## Challenge
#### 15) Ordering problems are recurrent in the history of programming. Over time, several algorithms have been developed to fulfill this function. The simplest of these algorithms is the [**Bubble Sort**](https://en.wikipedia.org/wiki/Bubble_sort), which is based on comparisons of elements two by two in a loop of passes through the elements. Your mission, if you decide to accept it, will be to input six whole numbers ramdonly ordered. Then implement the **Bubble Sort** principle to order these six numbers **using only loops and conditionals**.
#### At the end, print the six numbers in ascending order on a single line separated by spaces.

```python

```


# PHY321: Conservative Forces, Momentum and Angular Momentum conservation

**[Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/)**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA and Department of Physics, University of Oslo, Norway

Date: **Feb 19, 2021**

Copyright 1999-2021, [Morten Hjorth-Jensen](http://mhjgit.github.io/info/doc/web/). Released under CC Attribution-NonCommercial 4.0 license

## Aims and Overarching Motivation

### Monday

Short repetition from last week. Discussion of momentum and angular momentum.
Reading suggestion: Taylor sections 3.1-3.4

### Wednesday

More on angular momentum, Taylor sections 3.4 and 3.5. Discussion of potential energy and conservative forces.
Reading suggestions: Taylor section 4.2

### Friday

Conservative forces and potential energy. Reading suggestion: Taylor sections 4.2-4.4

If you wish to read more about conservative forces or not, Feyman's lectures from 1963 are quite interesting.
He states for example that **All fundamental forces in nature appear to be conservative**.
This statement was made while developing his argument that *there are no nonconservative forces*.
You may enjoy the link to [Feynman's lecture](http://www.feynmanlectures.caltech.edu/I_14.html).

## Work-Energy Theorem and Energy Conservation

Last week (Friday) we observed that energy was conserved for a force which
depends only on the position.
In particular we considered a force acting on a block
attached to a spring with spring
constant $k$. The other end of the spring was attached to the wall.

The force $F_x$ from the spring on the block was defined as

$$
F_x=-kx.
$$

The work done on the block due to a displacement from a position $x_0$ to $x$

$$
W=\int_{x_0}^{x}F_xdx'=\frac{1}{2}kx_0^2-\frac{1}{2}kx^2.
$$

## Conservation of energy
With the definition of the work-energy theorem in terms of the kinetic energy we obtained

$$
W=\frac{1}{2}mv^2(x)-\frac{1}{2}mv_0^2=\frac{1}{2}kx_0^2-\frac{1}{2}kx^2,
$$

which we rewrote as

$$
\frac{1}{2}mv^2(x)+\frac{1}{2}kx^2=\frac{1}{2}mv_0^2+\frac{1}{2}kx_0^2.
$$

The total energy, which is the sum of potential and kinetic energy, is conserved.
We will analyze this interesting result now in more detail when we study energy, momentum and angular momentum conservation.

But before we start with energy conservation, conservative forces and potential energies, we need to revisit our definitions of momentum and angular momentum.

## What is a Conservative Force?

A conservative force is a force whose property is that the total work
done in moving an object between two points is independent of the
taken path. This means that the work on an object under the influence
of a conservative force, is independent on the path of the object. It
depends only on the spatial degrees of freedom and it is possible to
assign a numerical value for the potential at any point. It leads to
conservation of energy. The gravitational force is an example of a
conservative force.

## Two important conditions

First, a conservative force depends only on the spatial degrees of freedom. This is a necessary condition for obtaining a path integral which is independent of path.
The  important condition for the final work to be independent of the path is that the **curl** of the force is zero, that
is

$$
\boldsymbol{\nabla} \times \boldsymbol{F}=0
$$

## Work-energy theorem to show that energy is conserved with a conservative force

The work-energy theorem states that the work done $W$ by a force $\boldsymbol{F}$ that moves an object from a position $\boldsymbol{r}_0$ to a new position $\boldsymbol{r}_1$

$$
W=\int_{\boldsymbol{r}_0}^{\boldsymbol{r}_1}\boldsymbol{F}\boldsymbol{dr}=\frac{1}{2}mv_1^2-\frac{1}{2}mv_0^2,
$$

where $v_1^2$ is the velocity squared at a time $t_1$ and $v_0^2$ the corresponding quantity at a time $t_0$.
The work done is thus the difference in kinetic energies. We can rewrite the above equation as

$$
\frac{1}{2}mv_1^2=\int_{\boldsymbol{r}_0}^{\boldsymbol{r}_1}\boldsymbol{F}\boldsymbol{dr}+\frac{1}{2}mv_0^2,
$$

that is the final kinetic energy is equal to the initial kinetic energy plus the work done by the force over a given path from a  position $\boldsymbol{r}_0$ at time $t_0$ to a final position position $\boldsymbol{r}_1$ at a later time $t_1$.

## Conservation of Momentum

Before we move on however, we need to remind ourselves about important aspects like the linear momentum and angular momentum. After these considerations, we move back to more details about conservatives forces.

Assume we have $N$ objects, each with velocity $\boldsymbol{v}_i$ with
$i=1,2,\dots,N$ and mass $m_i$. The momentum of each object is
$\boldsymbol{p}_i=m\boldsymbol{v}_i$ and the total linear (or mechanical) momentum is
defined as

$$
\boldsymbol{P}=\sum_{i=1}^N\boldsymbol{p}_i=\sum_{i=1}^Nm_i\boldsymbol{v}_i,
$$

## Two objects first

Let us assume we have two objects only that interact with each other and are influenced by an external force.

We define also the total net force acting on object 1 as

$$
\boldsymbol{F}_1^{\mathrm{net}}=\boldsymbol{F}_1^{\mathrm{ext}}+\boldsymbol{F}_{12},
$$

where $\boldsymbol{F}_1^{\mathrm{ext}}$ is the external force
(for example the force due to an electron moving in an electromagnetic field) and $\boldsymbol{F}_{12}$ is the
force between object one and two. Similarly for object 2 we have

$$
\boldsymbol{F}_2^{\mathrm{net}}=\boldsymbol{F}_2^{\mathrm{ext}}+\boldsymbol{F}_{21}.
$$

## Newton's Third Law

Newton's third law which we met earlier states that **for every action there is an equal and opposite reaction**.
It is more accurately stated as

**if two bodies exert forces on each other, these forces are equal in magnitude and opposite in direction**.

This means that for two bodies $i$ and $j$, if the force on $i$ due to $j$ is called $\boldsymbol{F}_{ij}$, then

$$
\begin{equation}
\boldsymbol{F}_{ij}=-\boldsymbol{F}_{ji}.
\label{_auto1} \tag{1}
\end{equation}
$$

For the abovementioned two objects we have thus $\boldsymbol{F}_{12}=-\boldsymbol{F}_{21}$.

## Newton's Second Law and Momentum

With the net forces acting on each object we can now related the momentum to the forces via

$$
\boldsymbol{F}_1^{\mathrm{net}}=m_1\boldsymbol{a}_i=m_1\frac{d\boldsymbol{v}_i}{dt}=\boldsymbol{F}_1^{\mathrm{ext}}+\boldsymbol{F}_{12},
$$

and

$$
\boldsymbol{F}_2^{\mathrm{net}}=m_2\boldsymbol{a}_2=m_1\frac{d\boldsymbol{v}_i}{dt}=\boldsymbol{F}_2^{\mathrm{ext}}+\boldsymbol{F}_{21}.
$$

Recalling our definition for the linear momentum we have then

$$
\frac{d\boldsymbol{p}_1}{dt}=\boldsymbol{F}_1^{\mathrm{ext}}+\boldsymbol{F}_{12},
$$

and

$$
\frac{d\boldsymbol{p}_2}{dt}=\boldsymbol{F}_2^{\mathrm{ext}}+\boldsymbol{F}_{21}.
$$

## The total Momentum

The total momentum $\boldsymbol{P}$ is defined as the sum of the individual momenta, meaning that we can rewrite

$$
\boldsymbol{F}_1^{\mathrm{net}}+\boldsymbol{F}_2^{\mathrm{net}}=\frac{d\boldsymbol{p}_1}{dt}+\frac{d\boldsymbol{p}_2}{dt}=\frac{d\boldsymbol{P}}{dt},
$$

that is the derivate with respect to time of the total momentum. If we now
write the net forces as sums of the external plus internal forces
between the objects we have

$$
\frac{d\boldsymbol{P}}{dt}=\boldsymbol{F}_1^{\mathrm{ext}}+\boldsymbol{F}_{12}+\boldsymbol{F}_2^{\mathrm{ext}}+\boldsymbol{F}_{21}=\boldsymbol{F}_1^{\mathrm{ext}}+\boldsymbol{F}_2^{\mathrm{ext}}.
$$

The derivative of the total momentum is just **the sum of the external
forces**. If we assume that the external forces are zero and that only
internal (here two-body forces) are at play, we obtain the important
result that the derivative of the total momentum is zero. This means
again that the total momentum is a constant of the motion and
conserved quantity. This is a very important result that we will use
in many applications to come.

## Newton's Second Law

Let us now general to several objects $N$ and let us also assume that there are no external forces. We will label such a system as **an isolated system**.

Newton's second law, $\boldsymbol{F}=m\boldsymbol{a}$, can be written for a particle $i$ as

$$
\begin{equation}
\boldsymbol{F}_i=\sum_{j\ne i}^N \boldsymbol{F}_{ij}=m_i\boldsymbol{a}_i,
\label{_auto2} \tag{2}
\end{equation}
$$

where $\boldsymbol{F}_i$ (a single subscript) denotes the net force acting on $i$ from the other objects/particles.
Because the mass of $i$ is fixed and we assume it does not change with time, one can see that

$$
\begin{equation}
\boldsymbol{F}_i=\frac{d}{dt}m_i\boldsymbol{v}_i=\sum_{j\ne i}^N\boldsymbol{F}_{ij}.
\label{_auto3} \tag{3}
\end{equation}
$$

## Summing over all Objects/Particles

Now, one can sum over all the objects/particles and obtain

$$
\frac{d}{dt}\sum_i m_iv_i=\sum_{ij, i\ne j}^N\boldsymbol{F}_{ij}=0.
$$

How did we arrive at the last step?  We rewrote the double sum as

$$
\sum_{ij, i\ne j}^N\boldsymbol{F}_{ij}=\sum_i^N\sum_{j>i}\left(\boldsymbol{F}_{ij}+\boldsymbol{F}_{ji}\right),
$$

and using Newton's third law which states that
$\boldsymbol{F}_{ij}=-\boldsymbol{F}_{ji}$, we obtain that the net sum over all  the two-particle
forces is zero when we only consider so-called **internal forces**.
Stated differently, the last step made use of the fact that for every
term $ij$, there is an equivalent term $ji$ with opposite
force. Because the momentum is defined as $m\boldsymbol{v}$, for a system of
particles, we have thus

$$
\begin{equation}
\frac{d}{dt}\sum_im_i\boldsymbol{v}_i=0,~~{\rm for~isolated~particles}.
\label{_auto4} \tag{4}
\end{equation}
$$

## Conservation of total Momentum

By "isolated" one means that the only force acting on any particle $i$
are those originating from other particles in the sum, i.e. "no
external" forces. Thus, Newton's third law leads to the conservation
of total momentum,

$$
\boldsymbol{P}=\sum_i m_i\boldsymbol{v}_i,
$$

and we have

$$
\frac{d}{dt}\boldsymbol{P}=0.
$$

## Example: Rocket Science

Consider a rocket of mass $M$ moving with velocity $v$. After a
brief instant, the velocity of the rocket is $v+\Delta v$ and the mass
is $M-\Delta M$. Momentum conservation gives

$$
\begin{eqnarray*}
Mv&=&(M-\Delta M)(v+\Delta v)+\Delta M(v-v_e)\\
0&=&-\Delta Mv+M\Delta v+\Delta M(v-v_e),\\
0&=&M\Delta v-\Delta Mv_e.
\end{eqnarray*}
$$

In the second step we ignored the term $\Delta M\Delta v$ because it is doubly small. The last equation gives

$$
\begin{eqnarray}
\Delta v&=&\frac{v_e}{M}\Delta M,\\
\nonumber
\frac{dv}{dt}&=&\frac{v_e}{M}\frac{dM}{dt}.
\end{eqnarray}
$$

## Integrating the Equations

Integrating the expression with lower limits $v_0=0$ and $M_0$, one finds

$$
\begin{eqnarray*}
v&=&v_e\int_{M_0}^M \frac{dM'}{M'}\\
v&=&v_e\ln(M/M_0)\\
&=&v_e\ln[(M_0-\alpha t)/M_0].
\end{eqnarray*}
$$

Because the total momentum of an isolated system is constant, one can
also quickly see that the center of mass of an isolated system is also
constant. The center of mass is the average position of a set of
masses weighted by the mass,

$$
\begin{equation}
\bar{x}=\frac{\sum_im_ix_i}{\sum_i m_i}.
\label{_auto5} \tag{5}
\end{equation}
$$

## Rate of Change

The rate of change of $\bar{x}$ is

$$
\dot{\bar{x}}=\frac{1}{M}\sum_i m_i\dot{x}_i=\frac{1}{M}P_x.
$$

Thus if the total momentum is constant the center of mass moves at a
constant velocity, and if the total momentum is zero the center of
mass is fixed.

## Conservation of Angular Momentum

The angular momentum is defined as

$$
\begin{equation}
\boldsymbol{L}=\boldsymbol{r}\times\boldsymbol{p}=m\boldsymbol{r}\times\boldsymbol{v}.
\label{_auto6} \tag{6}
\end{equation}
$$

It means that the angular momentum is perpendicular to the plane defined by position $\boldsymbol{r}$ and the momentum $\boldsymbol{p}$ via $\boldsymbol{r}\times \boldsymbol{p}$.

## Rate of Change of Angular Momentum

The rate of change of the angular momentum is

$$
\frac{d\boldsymbol{L}}{dt}=m\boldsymbol{v}\times\boldsymbol{v}+m\boldsymbol{r}\times\dot{\boldsymbol{v}}=\boldsymbol{r}\times{\boldsymbol{F}}
$$

The first term is zero because $\boldsymbol{v}$ is parallel to itself, and the
second term defines the so-called torque. If $\boldsymbol{F}$ is parallel to $\boldsymbol{r}$ then the torque is zero and we say that angular momentum is conserved.

If the force is not radial, $\boldsymbol{r}\times\boldsymbol{F}\ne 0$ as above, and angular momentum is no longer conserved,

$$
\begin{equation}
\frac{d\boldsymbol{L}}{dt}=\boldsymbol{r}\times\boldsymbol{F}\equiv\boldsymbol{\tau},
\label{_auto7} \tag{7}
\end{equation}
$$

where $\boldsymbol{\tau}$ is the torque.

## The Torque, Example 1 (hw 4, exercise 4)

Let us assume we have an initial position $\boldsymbol{r}_0=x_0\boldsymbol{e}_1+y_0\boldsymbol{e}_2$ at a time $t_0=0$.
We add now a force in the positive $x$-direction

$$
\boldsymbol{F}=F_x\boldsymbol{e}_1=\frac{d\boldsymbol{p}}{dt},
$$

where we used the force as defined by the time derivative of the momentum.

We can use this force (and its pertinent acceleration) to find the velocity via the relation

$$
\boldsymbol{v}(t)=\boldsymbol{v}_0+\int_{t_0}^t\boldsymbol{a}dt',
$$

and with $\boldsymbol{v}_0=0$ we have

$$
\boldsymbol{v}(t)=\int_{t_0}^t\frac{\boldsymbol{F}}{m}dt',
$$

where $m$ is the mass of the object.

## The Torque, Example 1 (hw 4, exercise 4)

Since the force acts only in the $x$-direction, we have after integration

$$
\boldsymbol{v}(t)=\frac{\boldsymbol{F}}{m}t=\frac{F_x}{m}t\boldsymbol{e}_1=v_x(t)\boldsymbol{e}_1.
$$

The momentum is in turn given by $\boldsymbol{p}=p_x\boldsymbol{e}_1=mv_x\boldsymbol{e}_1=F_xt\boldsymbol{e}_1$.

Integrating over time again we find the final position as (note the force depends only on the $x$-direction)

$$
\boldsymbol{r}(t)=(x_0+\frac{1}{2}\frac{F_x}{m}t^2) \boldsymbol{e}_1+y_0\boldsymbol{e}_2.
$$

There is no change in the position in the $y$-direction since the force acts only in the $x$-direction.

## The Torque, Example 1 (hw 4, exercise 4)

We can now compute the angular momentum given by

$$
\boldsymbol{l}=\boldsymbol{r}\times\boldsymbol{p}=\left[(x_0+\frac{1}{2}\frac{F_x}{m}t^2) \boldsymbol{e}_1+y_0\boldsymbol{e}_2\right]\times F_xt\boldsymbol{e}_1.
$$

Computing the cross product we find

$$
\boldsymbol{l}=-y_0F_xt\boldsymbol{e}_3=-y_0F_xt\boldsymbol{e}_z.
$$

The torque is the time derivative of the angular momentum and we have

$$
\boldsymbol{\tau}=-y_0F_x\boldsymbol{e}_3=-y_0F_x\boldsymbol{e}_z.
$$

The torque is non-zero and angular momentum is not conserved.

## The Torque, Example 2

One can write the torque about a given axis, which we will denote as $\hat{z}$, in polar coordinates, where

$$
\begin{eqnarray}
x&=&r\sin\theta\cos\phi,~~y=r\sin\theta\cos\phi,~~z=r\cos\theta,
\end{eqnarray}
$$

to find the $z$ component of the torque,

$$
\begin{eqnarray}
\tau_z&=&xF_y-yF_x\\
\nonumber
&=&-r\sin\theta\left\{\cos\phi \partial_y-\sin\phi \partial_x\right\}V(x,y,z).
\end{eqnarray}
$$

## Chain Rule and Partial Derivatives

One can use the chain rule to write the partial derivative w.r.t. $\phi$ (keeping $r$ and $\theta$ fixed),

$$
\begin{eqnarray}
\partial_\phi&=&\frac{\partial x}{\partial\phi}\partial_x+\frac{\partial_y}{\partial\phi}\partial_y
+\frac{\partial z}{\partial\phi}\partial_z\\
\nonumber
&=&-r\sin\theta\sin\phi\partial_x+\sin\theta\cos\phi\partial_y.
\end{eqnarray}
$$

Combining the two equations,

$$
\begin{eqnarray}
\tau_z&=&-\partial_\phi V(r,\theta,\phi).
\end{eqnarray}
$$

Thus, if the potential is independent of the azimuthal angle $\phi$,
there is no torque about the $z$ axis and $L_z$ is conserved.

## System of Isolated Particles

For a system of isolated particles, one can write

$$
\begin{eqnarray}
\frac{d}{dt}\sum_i\boldsymbol{L}_i&=&\sum_{i\ne j}\boldsymbol{r}_i\times \boldsymbol{F}_{ij}\\
\nonumber
&=&\frac{1}{2}\sum_{i\ne j} \boldsymbol{r}_i\times \boldsymbol{F}_{ij}+\boldsymbol{r}_j\times\boldsymbol{F}_{ji}\\
\nonumber
&=&\frac{1}{2}\sum_{i\ne j} (\boldsymbol{r}_i-\boldsymbol{r}_j)\times\boldsymbol{F}_{ij}=0,
\end{eqnarray}
$$

where the last step used Newton's third law,
$\boldsymbol{F}_{ij}=-\boldsymbol{F}_{ji}$. If the forces between the particles are
radial, i.e. $\boldsymbol{F}_{ij} ~||~ (\boldsymbol{r}_i-\boldsymbol{r}_j)$, then each term in
the sum is zero and the net angular momentum is fixed. Otherwise, you
could imagine an isolated system that would start spinning
spontaneously.

## Work, Energy, Momentum and Conservation laws

Energy conservation is most convenient as a strategy for addressing
problems where time does not appear. For example, a particle goes
from position $x_0$ with speed $v_0$, to position $x_f$; what is its
new speed? However, it can also be applied to problems where time
does appear, such as in solving for the trajectory $x(t)$, or
equivalently $t(x)$.

## Energy Conservation
Energy is conserved in the case where the potential energy, $V(\boldsymbol{r})$, depends only on position, and not on time. The force is determined by $V$,

$$
\begin{equation}
\boldsymbol{F}(\boldsymbol{r})=-\boldsymbol{\nabla} V(\boldsymbol{r}).
\label{_auto8} \tag{8}
\end{equation}
$$

## Conservative forces

We say a force is conservative if it satisfies the following conditions:
1. The force $\boldsymbol{F}$ acting on an object only depends on the position $\boldsymbol{r}$, that is $\boldsymbol{F}=\boldsymbol{F}(\boldsymbol{r})$.

2. For any two points $\boldsymbol{r}_1$ and $\boldsymbol{r}_2$, the work done by the force $\boldsymbol{F}$ on the displacement between these two points is independent of the path taken.

3. Finally, the **curl** of the force is zero $\boldsymbol{\nabla}\times\boldsymbol{F}=0$.

## Forces and Potentials

The energy $E$ of a given system is defined as the sum of kinetic and potential energies,

$$
E=K+V(\boldsymbol{r}).
$$

We define the potential energy at a point $\boldsymbol{r}$ as the negative work done from a starting point $\boldsymbol{r}_0$ to a final point $\boldsymbol{r}$

$$
V(\boldsymbol{r})=-W(\boldsymbol{r}_0\rightarrow\boldsymbol{r})= -\int_{\boldsymbol{r}_0}^{\boldsymbol{r}}d\boldsymbol{r}'\boldsymbol{F}(\boldsymbol{r}').
$$

If the potential depends on the path taken between these two points there is no unique potential.

## Example (relevant for homework 5)

We study a classical electron which moves in the $x$-direction along a surface. The force from the surface is

$$
\boldsymbol{F}(x)=-F_0\sin{(\frac{2\pi x}{b})}\boldsymbol{e}_1.
$$

The constant $b$ represents the distance between atoms at the surface of the material, $F_0$ is a constant and $x$ is the position of the electron.

This is indeed a conservative force since it depends only on position
and its **curl** is zero, that is $-\boldsymbol{\nabla}\times \boldsymbol{F}=0$. This means that energy is conserved and the
integral over the work done by the force is independent of the path
taken. We will come back to this in more detail next week.

## Example Continues

Using the work-energy theorem we can find the work $W$ done when
moving an electron from a position $x_0$ to a final position $x$
through the integral

$$
W=-\int_{x_0}^x \boldsymbol{F}(x')dx' =  \int_{x_0}^x F_0\sin{(\frac{2\pi x'}{b})} dx',
$$

which results in

$$
W=\frac{F_0b}{2\pi}\left[\cos{(\frac{2\pi x}{b})}-\cos{(\frac{2\pi x_0}{b})}\right].
$$

Since this is related to the change in kinetic energy we have, with $v_0$ being the initial velocity at a  time $t_0$,

$$
v  = \pm\sqrt{\frac{2}{m}\frac{F_0b}{2\pi}\left[\cos{(\frac{2\pi x}{b})}-\cos{(\frac{2\pi x_0}{b})}\right]+v_0^2}.
$$

## The potential energy from this example

The potential energy, due to energy conservation is

$$
V(x)=V(x_0)+\frac{1}{2}mv_0^2-\frac{1}{2}mv^2,
$$

with $v$ given by the velocity from above.

We can now, in order to find a more explicit expression for the
potential energy at a given value $x$, define a zero level value for
the potential. The potential is defined, using the work-energy
theorem, as

$$
V(x)=V(x_0)+\int_{x_0}^x (-F(x'))dx',
$$

and if you recall the definition of the indefinite integral, we can rewrite this as

$$
V(x)=\int (-F(x'))dx'+C,
$$

where $C$ is an undefined constant. The force is defined as the
gradient of the potential, and in that case the undefined constant
vanishes. The constant does not affect the force we derive from the
potential.

We have then

$$
V(x)=V(x_0)-\int_{x_0}^x \boldsymbol{F}(x')dx',
$$

which results in

$$
V(x)=\frac{F_0b}{2\pi}\left[\cos{(\frac{2\pi x}{b})}-\cos{(\frac{2\pi x_0}{b})}\right]+V(x_0).
$$

We can now define

$$
\frac{F_0b}{2\pi}\cos{(\frac{2\pi x_0}{b})}=V(x_0),
$$

which gives

$$
V(x)=\frac{F_0b}{2\pi}\left[\cos{(\frac{2\pi x}{b})}\right].
$$

## Force and Potential

We have defined work as the energy resulting from a net force acting
on an object (or sseveral objects), that is

$$
W(\boldsymbol{r}\rightarrow \boldsymbol{r}+d\boldsymbol{r})= \boldsymbol{F}(\boldsymbol{r})d\boldsymbol{r}.
$$

If we write out this for each component we have

$$
W(\boldsymbol{r}\rightarrow \boldsymbol{r}+d\boldsymbol{r})=\boldsymbol{F}(\boldsymbol{r})d\boldsymbol{r}=F_xdx+F_ydy+F_zdz.
$$

The work done from an initial position to a final one defines also the difference in potential energies

$$
W(\boldsymbol{r}\rightarrow \boldsymbol{r}+d\boldsymbol{r})=-\left[V(\boldsymbol{r}+d\boldsymbol{r})-V(\boldsymbol{r})\right].
$$

## Getting to $\boldsymbol{F}(\boldsymbol{r})=-\boldsymbol{\nabla} V(\boldsymbol{r})$

We can write out the differences in potential energies as

$$
V(\boldsymbol{r}+d\boldsymbol{r})-V(\boldsymbol{r})=V(x+dx,y+dy,z+dz)-V(x,y,z)=dV,
$$

and using the expression the differential of a multi-variable function $f(x,y,z)$

$$
df=\frac{\partial f}{\partial x}dx+\frac{\partial f}{\partial y}dy+\frac{\partial f}{\partial z}dz,
$$

we can write the expression for the work done as

$$
W(\boldsymbol{r}\rightarrow \boldsymbol{r}+d\boldsymbol{r})=-dV=-\left[\frac{\partial V}{\partial x}dx+\frac{\partial V}{\partial y}dy+\frac{\partial V}{\partial z}dz \right].
$$

## Final expression

Comparing the last equation with

$$
W(\boldsymbol{r}\rightarrow \boldsymbol{r}+d\boldsymbol{r})=F_xdx+F_ydy+F_zdz,
$$

we have

$$
F_xdx+F_ydy+F_zdz=-\left[\frac{\partial V}{\partial x}dx+\frac{\partial V}{\partial y}dy+\frac{\partial V}{\partial z}dz \right],
$$

leading to

$$
F_x=-\frac{\partial V}{\partial x},
$$

and

$$
F_y=-\frac{\partial V}{\partial y},
$$

and

$$
F_z=-\frac{\partial V}{\partial z},
$$

or just

$$
\boldsymbol{F}=-\frac{\partial V}{\partial x}\boldsymbol{e}_1-\frac{\partial V}{\partial y}\boldsymbol{e}_2-\frac{\partial V}{\partial z}\boldsymbol{e}_3=-\boldsymbol{\nabla}V(\boldsymbol{r}).
$$

And this connection is the one we wanted to show.


# Tutorial 4 - Pressure vs Temperature

Surfinpy has the functionality to generate phase diagrams as a function of pressure vs temperature based upon the methodology used in Molinari et al. (J. Phys. Chem. C  116, 12, 7073-7082) according to

\begin{align}
\gamma_{adsorbed, T, P} & = \gamma_{bare} + ( C ( E_{ads, T} - RTln(\frac{p}{p^o})
\end{align}

where $\gamma_{adsorbed, T, p}$ is the surface energy of the surface with adsorbed species at temperature (T) and pressure (P), $\gamma_{bare}$ is the suface energy of the bare surface, C is the coverage of adsorbed species, $E_{ads}$ is the adsorption energy,

\begin{align}
E_{ads, T} & =  E_{slab, adsorbant} - (E_{slab, bare} + n_{H_2O} E_{H_2O, T}) / n_{H_2O}
\end{align}

where $E_{slab, adsorbant}$ is the energy of the surface and the adsorbed species, $n_{H_2O}$ is he number of adsorbed species,

\begin{align}
E_{H_2O, (T)} & = E_{H_2O, (g)} - TS_{(T)}
\end{align}

where $S_{(T)}$ is the experimental entropy of gaseous water in the standard state.

So let's look at this in action. The module used is called p_vs_t

```python
from surfinpy import utils as ut
from surfinpy import p_vs_t
```

There are a number of user inputs that are required, the inputs are similiar to mu_vs_mu but with some small differences. First we need the energy from DFT of the adsorbant (eV), the energy of the surface ($j_m^2$) and the data for each surface. For clarity, in the dictionaries for each surface it is always assumed that the adsorbing species is 'Y'.

```python
adsorbant = -14.00
```

```python
SE = 1.40
```

```python
stoich = {'Cation': 24, 'X': 48, 'Y': 0, 'Area': 60.22, 'Energy': -575.00, 'Label': 'Bare'}
H2O =    {'Cation': 24, 'X': 48, 'Y': 2, 'Area': 60.22, 'Energy': -605.00, 'Label': '1 Water'}
H2O_2 =  {'Cation': 24, 'X': 48, 'Y': 8, 'Area': 60.22, 'Energy': -695.00, 'Label': '2 Water'}
data = [H2O, H2O_2]
```

The coverage of the adsorbing species (in this case water) is also needed. surfinpy has a built in function within the utils module to do this for you, it takes the number of adsorbing species and the surface area and calculates the coverage for you.

```python
coverage = ut.calculate_coverage(data)
```

We need the thermochemical data for the adsorbed species in order to make the DFT energy of our adsorbing species a temperature dependent term. This data has been taken directly from the NIST Janaf database and has been cut to just include the temperature and S values within the temperature range that interests us (In this case 0 - 1000 K).

```python
thermochem = ut.read_nist("H2O.txt")
```

Now we can generate our phase diagram .

```python
system = p_vs_t.calculate(stoich, data, SE, adsorbant, thermochem, coverage)
system.plot()
```


# Step 1 の演習問題

本章では Step 1 で扱ったテーマについて演習問題を記します。
本章の演習問題には Step 1 で扱った知識だけで解けるものもあれば、外部の資料を調べる必要があるものもあります。

## "2. Python 入門" の演習問題

### 問2.1 (組み込み関数)

Python には2章で紹介した以外にも数多くの組み込み関数が定義されています。組み込み関数を適切に使うことでコードを簡潔に記せます。`a=[4, 8, 3, 4, 1]` というリストに対して以下の操作を行う組み込み関数を[公式ドキュメント](https://docs.python.org/ja/3/library/functions.html)からそれぞれ探し、適用して下さい。すなわち、以下のコードセル中の `FUNC` の部分を適切な組み込み関数に置き換えてください。

- リスト `a` の長さを求める。
- リスト `a` に含まれる値の最大値を求める。
- リスト `a` に含まれる値の最小値を求める。
- リスト `a` に含まれる値の合計値を求める。
- リスト `a` をソートして、`[1, 3, 4, 4, 8]` というリストを返す。

```python
# 以下の FUNC という部分を組み込み関数に置き換えてください

a = [4, 8, 3, 4, 1]
res = FUNC(a)
print(res)
```

### 問2.2 (演算)

以下の演算や関数をそれぞれ評価したとき、結果の値と型が何になるか予想してください。実際にコードを実行して、結果が予想と合うか確かめてください。型の確認には `type()` 関数を使用しましょう。

- `1.2 + 3.8`
- `10 // 100`
- `1 >= 0`
- `'Hello World' == 'Hello World'`
- `not 'Chainer' != 'Tutorial'`
- `all([True, True, False])`  (`all` の定義は[公式ドキュメントを参照](https://docs.python.org/ja/3/library/functions.html#all))
- `any([True, True, False])`  (`any` の定義は[公式ドキュメントを参照](https://docs.python.org/ja/3/library/functions.html#any))
- `abs(-3)`  (`abs` の定義は[公式ドキュメントを参照](https://docs.python.org/ja/3/library/functions.html#abs))
- `2 // 0`

```python
# ここにコードを書いてください

```

### 問2.3 (リストの基本操作)

機械学習では大量のデータを扱うことが多いため、リストの扱いに慣れておくと便利なことが多いです。
`a=[4, 8, 3, 4, 1]` というリストに対して以下の操作を行うコードを書いて下さい。

- リスト `a` の先頭の要素を取り除いて、`[8, 3, 4, 1]` となるようにして下さい。
- リスト `a` の末尾の要素を取り除いて、`[4, 8, 3, 4]` となるようにして下さい。
- リスト `a` の末尾に `100` という値を追加して、`[4, 8, 3, 4, 1, 100]` となるようにして下さい。

```python
# ここにコードを書いてください

```

### 問2.4 (リスト内包表記)

**リスト内包表記**はリストを生成するための簡潔な手段です。例えば、平方数のリスト `[0, 1, 4, 9, 16, ...]` を構成したいとき、
```python
squares = []
for x in range(10):
    squares.append(x ** 2)
```
と書く代わりに、
```python
squares = [x ** 2 for x in range(10)]
```
と書くことができます。リスト内包表記は一般に `[(式) for (変数) in (iterableオブジェクト)]` という構文を取ります。リスト内包表記の一般的な説明は[公式ドキュメント](https://docs.python.org/ja/3/tutorial/datastructures.html#list-comprehensions)を参照して下さい。リスト内包表記で `in` の後に続く iterable オブジェクトは `range` である必要はなく、例えばリストを指定できます。

```python
a = [4, 8, 3, 4, 1]
squares = [x ** 2 for x in a]
print(squares)  # => [16, 64, 9, 16, 1]
```

以下の問いに答えて下さい。

(1) `a=[4, 8, 3, 4, 1]` というリストに対し、要素が偶数なら `0`, 奇数なら `1` に変換するコードをリスト内包表記を用いて書いて下さい。この結果、このリストは `[0, 0, 1, 0, 1]` に変換されるべきです。

(2) (1) で書いたコードと組み込み関数を組み合わせて、リスト `a` に含まれる奇数の個数を数えるコードを書いて下さい。

(3) リスト内包表記では、`if` 文を用いることで条件を満たす要素だけをリストに残すことができます。例えば
```python
b = [x for x in range(10) if x > 5]
```
と記すと、`b` は要素が `5` より大きいもののみが残り `[6, 7, 8, 9]` となります。

リスト内包表記を使ってリスト `a` から奇数の要素だけを残すコードを書いて下さい。

```python
# ここにコードを書いてください

```

### 問2.5 (文字列)

Python では文字列型に対して便利な組み込み関数が多数定義されています([公式のドキュメント](https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str))。組み込み関数を使って以下の処理を行って下さい。

(1) [str.join()](https://docs.python.org/ja/3/library/stdtypes.html#str.join) を使って、`0` から `99` までの数をスペース区切りで並べた文字列 `"0 1 2 3 4 ... 99"` を構成して下さい。

(2) [str.format()](https://docs.python.org/ja/3/library/stdtypes.html#str.format) を使って `float` の値 `(1.0 / 7.0)` の小数点以下9桁までを表示して下さい。

```python
# ここにコードを書いてください

```

### 問2.6 (クラス)

クラスを実装する練習として、データを管理するクラスを実装してみましょう。
次のメソッドを全て持つクラス `DataManager` を記述して下さい。

* `__init__(self, x, y, z)`: 3つの数 `x`, `y`, `z` をコンストラクタで受け取り、インスタンスの属性でそれぞれの値を記憶する。
* `add_x(self, delta)`: `x` に `delta` だけ足して、値を更新する。
* `add_y(self, delta)`: `y` に `delta` だけ足して、値を更新する。
* `add_z(self, delta)`: `z` に `delta` だけ足して、値を更新する。
* `sum(self)`: `x`, `y`, `z` の3つの数の合計値を返す。

このクラスを使って以下のようなコードが書けるものとします。

```python
data_manager = DataManager(2, 3, 5)
print(data_manager.sum())  # => 10
data_manager.add_x(4)      # => data_manager.x の値が 2 から 6 に更新される
print(data_manager.sum())  # => 14
data_manager.add_y(0)      # => data_manager.y の値が 3 から 3 に更新される
print(data_manager.sum())  # => 14
data_manager.add_z(-9)     # => data_manager.z の値が 5 から -4 に更新される
print(data_manager.sum())  # => 5
```

```python
# ここにコードを書いてください

```

### 問2.7 (関数呼び出し)
以下で定義される関数 `f`, `g` があるとします。

```python
def f(a):
    a = [6, 7, 8]

def g(a):
    a.append(1)
```

これらに対し、次のコードの実行結果がどうなるか予想して下さい。実際にコードを実行して予想と一致しているか確認し、なぜそのような結果になったのか説明して下さい。

```python
def somefunction():
    a0 = [1, 2, 3]
    f(a0)
    print(a0)

    a1 = [1, 2, 3]
    g(a1)
    print(a1)

somefunction()
```

```python
# ここにコードを書いてください

```

### 問2.8 (制御構文)

2以上の整数 `p` が素数であるとは、「どんな `2` 以上 `p-1` 以下の整数 `k` に対しても `p` は `k` で割り切れない」が成り立つことを指します。素数を小さい順から列挙すると、`2`, `3`, `5`, `7`, `11`, `13`, `17`, ... となります。
チュートリアルで学んだ制御構文である `if` や `for` を用いて、`2` から `100` からまでに含まれる素数を列挙して下さい。

```python
# ここにコードを書いてください

```

## "4. 微分の基礎" の演習問題

ここからは、紙と鉛筆を用意してください。

### 問4.1 (導関数)
導関数の定義 $f'(x) = \lim_{h \rightarrow 0} \frac{f(x+h)-f(x)}{h}$ を用いて以下の関数 $f_1(x), f_2(x)$ の導関数 $f^{'}_1(x), f^{'}_2(x)$ をそれぞれ求めて下さい。

* $f_1(x) = x^3$.
* $f_2(x) = \sqrt{x}$. (ヒント: 分母と分子に $(\sqrt{x+h}+\sqrt{x})$ を掛けて式を整理してみて下さい)

### 問4.2 (線形性)
微分の線形性 $\left( cf(x) \right)^{'} = c f'(x)$, $\left( f(x) + g(x) \right)^{'} = f^{'}(x) + g^{'}(x)$ を用いて、以下の関数の導関数を求めて下さい。

* $f_1(x) = 2x^2-5x+1$
* $f_2(x) = \sum_{k=1}^{123} (k^2+1)x^k$

### 問4.3 (積の微分)
積の微分 $\bigl( f(x) \cdot g(x) \bigr)^{'} = f^{'}(x)g(x) + f(x)g^{'}(x)$ を使って以下の関数を微分して下さい。

* $f_1(x) = x \cdot x$.
* $f_2(x) = x \cdot x^2$.
* $f_3(x) = x \cdot x^3$.

これを繰り返していくと、$g(x) = x^{100}$ に対して $g^{'}(x) = 100x^{99}$ などが成り立つことを確かめて下さい。

### 問4.4 (合成関数の微分)
合成関数の微分則 $\frac{d}{dx} f(g(x)) = \frac{df(u)}{du}\frac{du}{dx}$ ($u=g(x)$) を使って以下の関数を微分して下さい。

* $f_1(x) = (x+1)^3$.
* $f_2(x) = (4x)^3$.
* $f_3(x) = \exp(2x-1)$.
* $f_4(x) = \exp(-x^2)$.
* $f_5(x) = 2^x$.  (ヒント: $2^x = \exp(\log(2) x)$ を利用しましょう)

### 問4.5 (合成関数の微分)
$f(x) = x^2 + 1$, $g(x) = f(f(x))$ とします。

(1) $g(x) = x^4 + 2x^2 + 2$ となることを確認して下さい。また、これより $g'(x) = 4x^3 + 4x$ となることを確認して下さい。

(2) 一方で、合成関数の微分則によって $g'(x)$ を計算し、(1) で求めた導関数と一致することを確認して下さい。

(3) $h(x) = f(f(f(x)))$ とします。合成関数の微分によって $h'(x)$ を計算して下さい。(ヒント: $h(x)=f(g(x))$ であることを利用しましょう)

### 問4.6 (指数関数・対数関数)
指数関数 $\exp(x)$ と対数関数 $\log(x)$ の導関数は以下で定まります。

$$
\begin{align}
\exp^{'}(x) &= \exp(x). \\
\log^{'}(x) &= \frac{1}{x}. \\
\end{align}
$$

このことをプログラムを用いた実験によって確認してみましょう。
**数値微分**は導関数を近似的に計算する手法です。導関数の定義

$$f^{'}(x) = \lim_{h \rightarrow 0} \frac{f(x+h)-f(x)}{h}$$

において、極限を取る代わりにある微小な値 $\Delta h$ を $h$ に代入し、

$$
f'(x) \approx \frac{f(x+\Delta h)-f(x)}{\Delta h}
$$

として計算することによって導関数の値を近似する方法が数値微分です。具体的な $x$ の値に対する $\exp(x)$ の微分を数値微分によって計算するコードは以下のようになります。

```python
import math  # exp を呼び出すために math モジュールをインポート

def f(x):
    return math.exp(x)

def dfdx_approx(x):
    dh = 0.0001
    return (f(x + dh) - f(x)) / dh
```

(1) `x=-3,-2,-1,0,1,2,3` に対して数値微分の関数 `dfdx_approx` を呼び出し、その結果得られた値と正確な微分の値($\exp^{'}(-3),\ldots,\exp^{'}(3)$)とを比較して下さい。

(2) 対数関数 $\log(x)$ についても同様の実験を行い、`x=0.25,0.5,1,2,4,8` に対して比較して下さい。Python から対数関数を呼び出す場合、`math.log` を使用しましょう。

```python
# ここにコードを書いてください

```

### 問4.7 (ニューラルネットワークの関数の微分)
ニューラルネットワークのモデルでよく扱われる関数の導関数を計算してみましょう。

* $\mathrm{ReLU}(x) = \max(x, 0)$.
* $\tanh(x) = \frac{e^x - e^{-x}}{e^x + e^{-x}}$.  (注意: 商の微分則 $\bigl(\frac{f(x)}{g(x)}\bigr)^{'}=\frac{f^{'}(x)g(x)-f(x)g^{'}(x)}{g(x)^2}$ を用いましょう)
* $\mathrm{Sigmoid}(x) = \frac{1}{1 + e^{-x}}$.
* $\mathrm{Softplus}(x) = \log(1+e^x)$.

### 問4.8 (偏微分)
(1) 2変数関数 $f(x, y) = |x| + |y|$ に対して偏微分 $\frac{\partial}{\partial x}f(x,y)$, $\frac{\partial}{\partial y}f(x,y)$ を求めて下さい。

(2) 2変数関数 $f(x, y) = |x + y|$ に対して偏微分 $\frac{\partial}{\partial x}f(x,y)$, $\frac{\partial}{\partial y}f(x,y)$ を求めて下さい。

## "5. 線形代数の基礎" の演習問題

### 問5.1 (プログラムにおけるベクトル・行列の計算)

Python コード上でベクトルや行列に関する演算を行うことを考えてみましょう。ベクトルは `float` のリスト、行列は `float` のリストのリストによって表すことができます。例えば、

$$
{\bf x}=\begin{bmatrix}
3 \\
7 \\
2
\end{bmatrix}, \
{\bf A}=\begin{bmatrix}
1 & 2 & 3 \\
4 & 5 & 6
\end{bmatrix}
$$

というベクトルと行列はそれぞれ `[3, 7, 2]` と `[[1, 2, 3], [4, 5, 6]]` と Python コード上で表すことができます。

(1) 2つのベクトル ${\bf x}$, ${\bf y}$ を受け取り、その和 ${\bf x} + {\bf y}$ を返す関数を書いて下さい。コードは例えば以下のようになります。

```python
def vector_sum(x, y):
    # ...

x = [1, 2, 3]
y = [8, 1, 2]
answer = vector_sum(x, y)
print(answer)  # => [9, 3, 5]
```

(2) 2つの行列 ${\bf X}$, ${\bf Y}$ を受け取り、その和 ${\bf X} + {\bf Y}$ を返す関数を書いて下さい。コードは例えば以下のようになります。

```python
def matrix_sum(X, Y):
    # ...

X = [[1, 2, 3],
     [4, 5, 6]]
Y = [[8, 1, 2],
     [-1, 0, -2]]
answer = matrix_sum(X, Y)
print(answer)  # => [[9, 3, 5], [3, 5, 4]]
```

(3) 行列 ${\bf X}$ とベクトル ${\bf y}$ を受け取り、その積 ${\bf X}{\bf y}$ を返す関数を書いて下さい。

```python
def matrix_vector_product(X, y):
    # ...

X = [[1, 2, 3],
     [4, 5, 6]]
y = [8, 1, 2]
answer = matrix_vector_product(X, y)
print(answer)  # => [16, 49]
```

(4) 2つの行列 ${\bf X}$, ${\bf Y}$ を受け取り、その積 ${\bf X}{\bf Y}$ を返す関数を書いて下さい。

```python
def matrix_product(X, Y):
    # ...

X = [[1, 2, 3],
     [4, 5, 6]]
Y = [[8, 1],
     [-1, 0],
     [0, 1]]
answer = matrix_product(X, Y)
print(answer)  # => [[6, 4], [27, 10]]
```

(5) 行列 ${\bf X}$ を受け取り、その転置 ${\bf X}^{\rm T}$ を返す関数を書いて下さい。

```python
def matrix_transpose(X):
    # ...

X = [[1, 2, 3],
     [4, 5, 6]]
answer = matrix_transpose(X)
print(answer)  # => [[1, 4], [2, 5], [3, 6]]
```

```python
# ここにコードを書いてください

```

### 問5.2 (ベクトルの微分)
${\bf x}$ を次元数 $n$ のベクトル、${\bf A}$ を $n \times n$ の正方行列とします。

$$
{\bf x}=\begin{bmatrix}
x_{1} \\
\vdots \\
x_{n}
\end{bmatrix}, \
{\bf A}=\begin{bmatrix}
a_{11} & \ldots & a_{1n} \\
\vdots &        & \vdots \\
a_{n1} & \ldots & a_{nn}
\end{bmatrix}
$$

二次形式に関する微分 $\frac{\partial}{\partial {\bf x}} \left( {\bf x}^{\rm T}{\bf A}{\bf x} \right) = {\bf x}^{\rm T} \left( {\bf A} + {\bf A}^{\rm T} \right)$ を証明してみましょう。

(1) ${\bf x}^{\rm T}{\bf A}{\bf x} = \sum_{i=1}^n \sum_{j=1}^n a_{ij} x_i x_j$ であることを示して下さい。さらに、これより以下を示して下さい。
$$
{\bf x}^{\rm T}{\bf A}{\bf x} = a_{11} x_1^2 + \left( \sum_{i=2}^n (a_{1i} + a_{i1}) x_i \right) x_1 + \sum_{i=2}^n \sum_{j=2}^n x_i x_j a_{ij}.
$$

(2) 偏微分 $\frac{\partial}{\partial x_1} \left( {\bf x}^{\rm T}{\bf A}{\bf x} \right)$ を計算し、$\sum_{i=1}^n (a_{1i} x_i + a_{i1} x_i)$ となることを示して下さい。

(3) 一般に、$k=1,\ldots,n$ に対して $\frac{\partial}{\partial x_k} \left( {\bf x}^{\rm T}{\bf A}{\bf x} \right) = \sum_{i=1}^n (a_{ki} x_i + a_{ik} x_i)$ となることを示して下さい。これによって $\frac{\partial}{\partial {\bf x}} \left( {\bf x}^{\rm T}{\bf A}{\bf x} \right) = {\bf x}^{\rm T} \left( {\bf A} + {\bf A}^{\rm T} \right)$ が成り立つことを確かめて下さい。

### 問5.3 (ベクトルを入力とする関数の微分)

$f, g$ をベクトルを入力とする実数値関数とします。
微分について以下の性質が成り立つことを示して下さい。

* $\frac{\partial}{\partial {\bf x}}(f({\bf x}) + g({\bf x})) = \frac{\partial}{\partial {\bf x}}f({\bf x}) + \frac{\partial}{\partial {\bf x}}g({\bf x})$.
* $c$ を任意の実数とするとき、$\frac{\partial}{\partial {\bf x}}(cf({\bf x})) = c\frac{\partial}{\partial {\bf x}}f({\bf x})$.
* $c$ を任意の実数、${\bf b}$ を任意のベクトルとするとき、$\frac{\partial}{\partial {\bf x}}f(c{\bf x} + {\bf b}) = c\frac{\partial}{\partial {\bf y}}{\bf f}({\bf y})$. (ここで ${\bf y}=c{\bf x}+{\bf a}$ とする。)

### 問5.4 (ベクトルを入力とする関数の微分)

${\bf x}$ を $n$ 次元ベクトルとします。
以下の関数 $f$ に対するベクトルの微分 $\frac{\partial}{\partial {\bf x}}f({\bf x})$ を計算して下さい。

* $f({\bf x}) = \max(x_1, x_2, \ldots, x_n)$.

* $f({\bf x}) = \sqrt{x_1^2 + x_2^2 + \ldots + x_n^2}$.

* $f({\bf x}) = |x_1 + x_2 + \ldots + x_n|$.

### 問5.5 (多変数関数の合成関数の微分)

3次元ベクトルに対するベクトル値関数 ${\bf f}$ を以下によって定義します。
$$
{\bf f}(\begin{bmatrix}
x_{1} \\
x_{2} \\
x_{3}
\end{bmatrix}) = \begin{bmatrix}
x_{2}^2 \\
x_{3}^2 \\
x_{1}^2
\end{bmatrix}.
$$

(1) ${\bf f}({\bf x})$ のヤコビ行列 $\frac{\partial}{\partial {\bf x}}{\bf f}({\bf x})$ を計算して下さい。

(2) ${\bf f}({\bf f}({\bf x}))$ を計算して下さい。

(3) ${\bf f}({\bf f}({\bf x}))$ のヤコビ行列 $\frac{\partial}{\partial {\bf x}}{\bf f}({\bf f}({\bf x}))$ を、(1) の結果を用いて計算して下さい。

(4) $\frac{\partial}{\partial {\bf x}}{\bf f}({\bf f}({\bf x}))$ を合成関数の微分則 $\frac{\partial}{\partial {\bf x}} {\bf f}( {\bf g}({\bf x}))  = \frac{\partial {\bf f}}{\partial {\bf u}}({\bf u}) \frac{\partial {\bf g}}{\partial {\bf x}}({\bf x})$ (${\bf u}={\bf g}({\bf x})$) によって計算し、結果が (3) と一致することを確認して下さい。

### 問5.6 (多変数関数の合成関数の微分)
${\bf A}$, ${\bf B}$ を $n \times n$ 行列とします。$n$ 次元ベクトル ${\bf x}$ に対して ${\bf f}({\bf x})={\bf A}{\bf x}$, ${\bf g}({\bf x})={\bf B}{\bf x}$ とします。

合成関数の微分則を用いて $\frac{\partial}{\partial {\bf x}}{\bf g}({\bf f}({\bf x})) = {\bf B}{\bf A}$ を示して下さい。

### 問5.7 (多変数関数の合成関数の微分)

(1) $f(y, z) = 2y-3z$ とします。このとき、1変数関数 $g(x)$ と $h(x)$ に対して

$$
\frac{d}{dx}f(g(x), h(x)) = 2g^{'}(x)-3h^{'}(x)
$$

であることを確認して下さい。

(2) $f(y, z) = yz$ とします。このとき $\frac{d}{dx}f(g(x), h(x)) = g^{'}(x)h(x) + g(x)h^{'}(x)$ であることを確認して下さい。

(3) 2変数実数値関数 $f(y, z)$ と1変数関数 $g(x), h(x)$ に対し以下が成り立つことを合成関数の微分則 $\frac{\partial}{\partial {\bf x}} {\bf f}( {\bf g}({\bf x}))  = \frac{\partial {\bf f}}{\partial {\bf u}}({\bf u}) \frac{\partial {\bf g}}{\partial {\bf x}}({\bf x})$ (${\bf u}={\bf g}({\bf x})$) を用いて示して下さい。

$$
\frac{d}{dx}f(g(x), h(x)) = \frac{\partial f}{\partial y}(y, z) \cdot g^{'}(x) + \frac{\partial f}{\partial z}(y, z) \cdot h^{'}(x)
$$

ここで、$y=g(x)$, $z=h(x)$ とします。この結果が (1) と (2) の式の一般化になっていることを確かめて下さい。

(4) 平面上を移動する点があり、時刻 $t$ の点の座標 $(x(t), y(t))$ は $x(t)=t^2+t+1, y(t)=t^2-t+1$ であるとします。座標 $(x,y)$ にいるとき、点は $E(x,y)=\exp(\frac{1}{\sqrt{x^2+y^2}})$ のエネルギーを持っているとします。エネルギーの時間に関する微分 $\frac{\partial}{\partial t}E(x(t),y(t))$ を (3) の結果を用いて求めて下さい。

### 問5.8 (多変数関数の合成関数の微分)
ベクトル値関数 ${\bf f}$ を以下で定義します。

$$
{\bf f}(\begin{bmatrix}
z \\
w
\end{bmatrix}) = \begin{bmatrix}
\frac{e^z}{e^{z+w}} \\
\frac{e^w}{e^{z+w}}
\end{bmatrix}.
$$

${\bf X}$ を $2 \times N$ 行列、${\bf y}$ を $N$ 次元ベクトルとします。
偏微分 $\frac{\partial}{\partial x_{ij}}{\bf f}({\bf X}{\bf y})$ を計算して下さい。ここで、$x_{ij}$ は ${\bf X}$ の $(i,j)$ 成分とします。

## "6. 確率・統計の基礎" の演習問題

### 問6.1 (同時分布・周辺確率)

偏りのあるコイン ${\rm A}$ と ${\rm B}$ があります。
コイン ${\rm A}$ を振ったときに表が出る確率は1/4、裏が出る確率は3/4です。コイン ${\rm B}$ を振ったときに表が出る確率は2/3、裏が出る確率は1/3です。

この二つのコインのうちどちらか一つを等しい確率でランダムに選び、選んだ方のコインを振るという試行を考えます。
選んだコインが ${\rm A}$ と ${\rm B}$ どちらだったかを表す確率変数を $X$、コインを振った結果(表裏)を表す確率変数を $Y$ とします。

(1) 同時確率 $p(X={\rm A}, Y=表)$, $p(X={\rm A}, Y=裏)$, $p(X={\rm B}, Y=表)$, $p(X={\rm B}, Y=裏)$ をそれぞれ計算して下さい。

(2) 同時確率を周辺化して、確率 $p(Y=表)$ と $p(Y=裏)$ を計算して下さい。

### 問6.2 (条件付き確率)

問6.1 の試行で条件付き確率 $p(Y=表 \mid X={\rm A})$ を計算して下さい。

### 問6.3 (ベイズの定理)

(1) 問6.1 の試行で事後確率 $p(X={\rm A} \mid Y=表)$, $p(X={\rm B} \mid Y=表)$, $p(X={\rm A} \mid Y=裏)$, $p(X={\rm B} \mid Y=裏)$ をそれぞれ計算して下さい。

(2) 問6.1 の試行を行った後、コインは表が出たとします。この後さらに同じコインを振ったときに再び表が出る確率を計算して下さい。

### 問6.4 (ベイズの定理)

一様な確率で1から6までの数が出るサイコロがあります。
サイコロを何回か連続で振る試行を考えます。サイコロを振った後、直前に出た数より大きい数が出たときに「ラッキーである」と呼ぶことにします。
例えばサイコロを5回振って 2,5,3,4,4 と順に出た場合、2回目と4回目はラッキーですが、それ以外はラッキーではありません。

いま、サイコロを 10 回振って一度もラッキーではなかったとします。このとき、次にサイコロを振ってラッキーになる確率はいくらになるでしょうか。プログラムを使って分析してみて下さい。

```python
# ここにコードを書いてください

```

### 問6.5 (尤度と最尤推定)

偏りのあるサイコロの出る目の確率を推定する問題を考えます。サイコロを振ったときに出る数を表す確率変数を $X$ とします。確率モデルのパラメータを $\theta=(\theta_1, \theta_2, \theta_3, \theta_4, \theta_5, \theta_6)$ として、確率 $p(X=x)$ を

$$
f(x; \theta) = \theta_x
$$

によってモデル化します。ここで、パラメータは $\theta_1, \ldots, \theta_6 \ge 0$ かつ $\theta_1+\ldots+\theta_6=1$ を満たさなくてはならないとします。

いま、サイコロを60回振って、1の目が30回、それ以外の目が6回出たとします。

(1) 観測データに対する対数尤度を求めて下さい。

(2) プログラムを用いて、$\theta=(\theta_1, \ldots, \theta_6)$ に様々な値を入れた場合に対数尤度がどのようになるかを観測して下さい。$\theta$ がどのようなときに対数尤度が大きくなるか予想してください。

```python
# ここにコードを書いてください

```

### 問6.6 (尤度と最尤推定)

ポアソン分布は正の実数 $\lambda>0$ をパラメータとして持つ分布です。$0$ 以上の整数値を取る確率変数 $X$ が以下の確率値に従うとき、$X$ はポアソン分布に従うと言います。

$$p(X=k)=\frac{\lambda^k e^{-\lambda}}{k!} \; \; \; (k=0,1,2,\ldots).$$

いま、ある交差点で特定の時間帯に存在する歩行者の人数のをポアソン分布でモデル化することを考えます。
$X$ を特定の時間帯に存在する歩行者の人数を表す確率変数とします。確率 $p(X=k)$ は上記のポアソン分布に従うとします。

20日間の観測結果によると、$i$ 日目には $10+i$ 人の歩行者を観測したことが分かっているとします。($i=1,2,\ldots,20$)

(1) 観測データに対する対数尤度を求めて下さい。

(2) 対数尤度を最大にする $\lambda$ の値を求めて下さい。

(3) (2) で求めた $\lambda$ をパラメータとして用いたとき、$k=0,1,\ldots,50$ に対して $p(X=k)$ をプログラムを用いて計算して下さい。なお、累乗 $\lambda^k$ の計算には組み込み関数の `pow` を、階乗 $k!$ の計算には `math` モジュールにある `math.factorial` を用いると便利です。

```python
# ここにコードを書いてください

```

### 問6.7 (事後確率最大化推定(MAP推定))

6章の例6.7.1 にあるコイントスの試行で、事前確率 $p(\theta)$ を以下のように変更した場合にどうなるかを考えてみます。

$$
p(\theta)=\begin{cases}
3 & (1/3 \le \theta \le 3/2) \\
0 & (\text{otherwise})
\end{cases}
$$

コインを10回振って9回表が出て1回裏が出たとき、MAP 推定によってパラメータ $\theta$ を推定して下さい。

### 問6.8 (統計量)

生徒が100人いる学校で期末試験をした結果、科目Aと科目Bの点数は以下のような結果になりました。

* 科目A: 20点の生徒が50人、80点の生徒が50人
* 科目B: 0点の生徒が1人、1点の生徒が1人、2点の生徒が1人、…、99点の生徒が1人

この二つの科目について、生徒の点数の平均と標準偏差をそれぞれ計算して下さい。プログラムを用いてもよいです。

この例から分かるように、データのばらつきが非常に異なる性質をもっていても平均や標準偏差が近い値になることがあります。

```python
# プログラムを用いる場合はここにコードを書いてください

```


# Single-qubit geometric gates

In this notebook we create a single-qubit geometric gate between the $|0\rangle$ and $|2\rangle$ state of the transmon. The ideal unitary operator describing the single-qubit geometric gate in the $\{|0\rangle, |2\rangle\}$ basis is
\begin{align}
U_g = \begin{pmatrix}
\cos\theta & e^{i\phi}\sin\theta \\
e^{-i\phi}\sin\theta & -\cos\theta
\end{pmatrix}
\end{align}
where $\theta$ and $\phi$ are controllable rotation angles.
The rotation that a geometric gate implements depends only on the path that the quantum system takes in Hilbert space during the time evolution. This gate is implemented by simultaneously driving a $2\pi$ rotation between the $|0\rangle$ to $|1\rangle$ and the $|1\rangle$ to $|2\rangle$ transitions which differ in frequency by the anharmonicity of the transmon. We therefore require properly calibrated $X$ gates between $|0\rangle$ to $|1\rangle$ and between $|1\rangle$ to $|2\rangle$ which we label $X_{01}$ and $X_{12}$, respectively. The backend provides us with a properly calibrated $X_{01}$ gate. By modulating the pulse that implements $X_{01}$ with the anharmonicity of the transmon and by scaling its amplitude we can implement a calibrated $X_{12}$ gate that has the same duration as $X_{01}$. This modulation requires a bandwidth comparable to the anharmonicity, which is typically -400 ~ -300 MHz for transmon devices. To avoid calibrating $2\pi$ rotations we implement the geometric gate by two back-to-back simultaneously driven $X_{01}$ and $X_{12}$ gates. The pulse envelope of the $X_{01}$ and $X_{12}$ gates are scaled by the complex parameters $a$ and $b$ which control the rotation angles $\theta$ and $\phi$ on the Bloch sphere spanned by $|0\rangle$ and $|2\rangle$ according to
\begin{align}
e^{i\phi}\tan\frac{\theta}{2}=\frac{a}{b}.
\end{align}

To implement the geometric gate we need to do the following steps.
1. Identify the frequency of the $|1\rangle$ to $|2\rangle$ transition using spectroscopy.
2. Identify the amplitude of the $\pi$-pulse between the $|1\rangle$ to $|2\rangle$ transition.
3. Build a discriminator using Qiskit-Ignis to discriminate the $|0\rangle$, $|1\rangle$, and $|2\rangle$.
4. Implement and measure a single-qubit geometric gate.

References:
- Abdumalikov *et al.*, Nature **496**, 482-485 (2013)
- Egger *et al*, Phys. Rev. Applied **11**, 014017 (2019)

```python
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit

import qiskit.pulse as pulse
from qiskit.compiler import assemble

# Qiskit pulse
from qiskit.pulse import (MemorySlot, Acquire, DriveChannel, Schedule, SamplePulse,
                          InstructionScheduleMap, Play, MeasureChannel, AcquireChannel)
from qiskit.pulse.pulse_lib import Gaussian
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.scheduler import measure_all
from qiskit.visualization.pulse.qcstyle import SchedStyle

# Ignis discriminator fitter tools
from sklearn.svm import SVC
from qiskit.ignis.mitigation.measurement import CompleteMeasFitter, MeasurementFilter
from qiskit.ignis.measurement.discriminator.filters import DiscriminationFilter
from qiskit.ignis.measurement.discriminator.iq_discriminators import SklearnIQDiscriminator

%matplotlib inline
```

### Load a high resolution pulse backend

```python
import warnings
warnings.filterwarnings('ignore')
from qiskit.tools.jupyter import *

from qiskit import IBMQ
IBMQ.load_account()
hub='update-here'
group='update-here'
project='update-here'

provider = IBMQ.get_provider(hub=hub, group=group, project=project)
backend = provider.get_backend('ibmq_armonk')
```

```python
backend
```

    VBox(children=(HTML(value="<h1 style='color:#ffffff;background-color:#000000;padding-top: 1%;padding-bottom: 1…

    <IBMQBackend('ibmq_armonk') from IBMQ(hub='ibm-q-internal', group='dev-qiskit', project='pulse-testing')>

```python
config = backend.configuration()
defaults = backend.defaults()
inst_map = defaults.circuit_instruction_map
style = SchedStyle(figsize=(16, 5))  # schedule style plotting
```

Extract the default Xp and measurement pulse for the qubit that we are going to use.

```python
xp = inst_map.get('x', (0,)).instructions[0][1].pulse
d0 = DriveChannel(0)
dt = config.dt
shots = 1024
```

```python
def add_modulation(pulse, freq: float, dt: float, scale: float = 1.) -> SamplePulse:
    """
    Add a modulation to the pulse.

    Args:
        samples: A list of AWG samples to modulate.
        freq: The frequency of the modulation to add to samples.
        dt: The cycle time.
        scale: a factor to scale the samples.

    Returns: SamplePulse with the added modulation.
    """

    if not isinstance(pulse, SamplePulse):
        samples = pulse.get_sample_pulse().samples
    else:
        samples = pulse.samples

    modulated_samples = []
    for i, amp in enumerate(samples):
        modulated_samples.append(scale * amp * np.exp(2.0j*np.pi*freq*i*dt))

    return SamplePulse(modulated_samples)

def get_job_data(job, average: bool, qubit: int, scale_factor=1):
    """Retrieve data from a job that has already run.

    Args:
        job (Job): The job whose data you want.
        average: If True, gets the data assuming data is an average.
                 If False, gets the data assuming it is for single shots.
    Return:
        list: List containing job result data.
    """
    job_results = job.result(timeout=120) # timeout parameter set to 120 s
    result_data = []
    for i in range(len(job_results.results)):
        if average: # get avg data
            result_data.append(job_results.get_memory(i)[qubit]*scale_factor)
        else: # get single data
            result_data.append(job_results.get_memory(i)[:, qubit]*scale_factor)
    return result_data

def lorenz(x, a, q_freq, b, c):
     return (a / np.pi) * (b / ((x - q_freq)**2 + b**2)) + c
```

## Calibration of an X gate between $|1\rangle$ and $|2\rangle$

### Find the $|1\rangle$ to $|2\rangle$ transition

We use spectroscopy to find the transition between $|1\rangle$ and $|2\rangle$.
First, we apply a pi-pulse to the qubit to prepare the $|1\rangle$ state.
Next, we apply a longer and weaker spectroscopic pulse with a frequency detunning $\delta f$ from the $|0\rangle$ to $|1\rangle$ transition and measure.
By repeating this experiment for different values of $\delta f$ we can identify the frequency detunning of the transition between $|1\rangle$ and $|2\rangle$ which is called the anharmonicity $\alpha$.

**Note**: Here we will drive a transition at +400 MHz which corresponds to an image (created by the IQ mixer) of the anharmonicity. Since the LO is +50 MHz above the $|0\rangle$ to $|1\rangle$ transition frequency of the qubit and that the true qubit anharmonicity is approximately -350 MHz the +400 MHz thus corresponds to an image of the anharmonicity. This image transition of the anharmonicity has proven superior at creating a $\pi$-pulse between the $|1\rangle$ and $|2\rangle$ states.

```python
exps = 74

# Frequency range to scan in GHz
# Anharmonicity is around -349 MHz and its image is around +400 MHz.
frequency_offsets = np.linspace(0.396, 0.404, exps)

schedules = []
for freq in frequency_offsets:
    sched = Schedule(name='Frequency %f MHz' % (freq/1e3))

    spec_pulse = add_modulation(Gaussian(3200, 0.1, 800), freq*1e9, dt)
    #spec_pulse = add_modulation(xp, freq*1e9, dt, scale=0.88)

    sched += Play(xp, d0)
    sched += Play(spec_pulse, d0)
    sched += measure_all(backend) << sched.duration

    schedules.append(sched)
```

```python
schedules[32].draw(plot_range=[0, 7500], style=style, channels=[DriveChannel(0), MeasureChannel(0)])
```

```python
qobj = assemble(schedules, backend, meas_level=1,
                meas_return=MeasReturnType.AVERAGE,
                shots=shots)
```

```python
job = backend.run(qobj)
job.job_id()
```

    '5e8af77747a99200182d40cc'

```python
job.status()
```

    <JobStatus.DONE: 'job has successfully run'>

```python
result = get_job_data(job, True, 0, 1e-15)
spec_signal = abs(np.array(result))
spec_signal = np.average(spec_signal) - spec_signal
```

```python
popt, pcov = curve_fit(lorenz, frequency_offsets, spec_signal, [0.015, 0.4, 0.0045, 0.1])
anharmonicity = popt[1]*1e9
```

```python
anharmonicity
```

    399668282.76144534

```python
fig = plt.figure()
plt.rcParams['font.size'] = 20
plt.plot(frequency_offsets, lorenz(frequency_offsets, *popt))
plt.plot(frequency_offsets, spec_signal, 'ok')
plt.xlabel('Frequency detunning (MHz)')
plt.ylabel('Signal (arb units.)')
plt.title('Anharmonicity %.2f MHz' % (anharmonicity/1e6));
```

## Calibrate a $\pi$-pulse between 1 and 2

Since we now know the anharmonicity $\alpha$ of the transmon, we can apply a frequency modulation $e^{i\alpha t}$ to the pulse envelope $\Omega(t)$ that implements an $X$ gate between $|0\rangle$ and $|1\rangle$ to drive the $|1\rangle$ to $|2\rangle$ transition.
However, the resulting pulse will not have the correct amplitude to implement a $\pi$-pulse between $|1\rangle$ and $|2\rangle$.
To calibrate this pulse we scan a scaling factor $\eta$ of the pulse envelope $\eta\,\Omega(t)\,e^{i\alpha t}$ to measure a Rabi oscillation between $|1\rangle$ and $|2\rangle$.

```python
xp12_scales = np.linspace(0., 1.6, 74)

schedules = []
for amp in xp12_scales:
    sched = Schedule(name='Amplitude {:.3f} (\\% AWG output)'.format(amp))

    xp12 = add_modulation(xp, anharmonicity, dt, scale=amp)

    sched += Play(xp, d0)
    sched += Play(xp12, d0)
    sched += measure_all(backend) << sched.duration

    schedules.append(sched)
```

```python
schedules[73].draw(plot_range=[0, 2000], style=style, channels=[d0, MeasureChannel(0)])
```

```python
qobj = assemble(schedules, backend, meas_level=1,
                meas_return=MeasReturnType.AVERAGE,
                shots=1024)
```

```python
job = backend.run(qobj)
job.job_id()
```

    '5e8af8695b8bdd00181fb5c7'

```python
job.status()
```

    <JobStatus.DONE: 'job has successfully run'>

```python
def amp_func(x, a, b, c):
    """Function used to fit the amplitude scan."""
    return a*np.cos(np.pi*x/b)+c
```

```python
signal = np.real(np.array(get_job_data(job, True, 0, 1e-15)))

popt, pcov = curve_fit(amp_func, xp12_scales, signal, [0.8, 2.0, 0.5])
xp12_scale = abs(popt[1])
```

```python
fig = plt.figure()
plt.plot(xp12_scales, amp_func(xp12_scales, *popt))
plt.plot(xp12_scales, signal, 'ok')
plt.plot([xp12_scale]*2, [min(signal), max(signal)])
plt.xlabel('Amplitude of xp12 relative to xp')
plt.ylabel('Signal (arb. units)')
plt.title('Relative amplitude %.2f %%' % (xp12_scale*100));
```

## Create a 0, 1, 2 discriminator with Qiskit Ignis

We should now have a calibrated $\pi$-pulse between the $|1\rangle$ and $|2\rangle$ states.
We check this by preparing calibration schedules to see if we can distinguish between the $|0\rangle$, $|1\rangle$ and $|2\rangle$ states in the IQ plane.
This measurement is then used to build a 0-1-2 discriminator with Qiskit-Ignis.

Note that we also added a small modulation to the readout pulse to improve the efficiency of the 0-1-2 discriminator.

```python
# The measurement pulse may not be setup to distinguish between 0, 1, and 2
# This line of code allows us to adjust the frequency and amplitude
# of the measurement pulse
meas = measure_all(backend).instructions[1][1].pulse
meas_freq_shift = -0.075e6
meas_pulse = add_modulation(meas, meas_freq_shift, dt, scale=0.9)

meas_sched = Schedule(name='meas %f' % meas_freq_shift)
meas_sched += Play(meas_pulse, MeasureChannel(0))
meas_sched += Acquire(len(meas.samples), AcquireChannel(0), MemorySlot(0))

schedules = []

cal0 = Schedule(name='cal_0'.format(amp))
cal0 += meas_sched << cal0.duration
schedules.append(cal0)

cal1 = Schedule(name='cal_1'.format(amp))
cal1 += Play(xp, d0)
cal1 += meas_sched << cal1.duration
schedules.append(cal1)

# Create the calibrated pi-pulse between |1> and |2>
xp12 = add_modulation(xp, anharmonicity, dt, scale=xp12_scale)

cal2 = Schedule(name='cal_2'.format(amp))
cal2 += Play(xp, d0)
cal2 += Play(xp12, d0)
cal2 += meas_sched << cal2.duration
schedules.append(cal2)
```

```python
schedules[2].draw(style=style, channels=[d0, MeasureChannel(0), AcquireChannel(0)])
```

```python
qobj = assemble(schedules, backend, meas_level=1,
                meas_return=MeasReturnType.SINGLE,
                shots=1024)
```

```python
job = backend.run(qobj)
job.job_id()
```

    '5e8af9100f58730019b2191b'

```python
job.status()
```

    <JobStatus.DONE: 'job has successfully run'>

```python
cal_result_disc = job.result(timeout=3600)
```

```python
svc = SVC(C=0.01, kernel="rbf", gamma="scale")

svc_discriminator = SklearnIQDiscriminator(svc, cal_result_disc, [0], ['0', '1', '2'])
filter012 = DiscriminationFilter(svc_discriminator)
```

The data in the figure below should show three clearly seperated clusters in the IQ plan which correspond to $|0\rangle$, $|1\rangle$, and $|2\rangle$. Since the discriminator must discriminate three states we use the support vector machine provided by Scikit learn.

```python
fig, ax = plt.subplots(1, 1, figsize=(8,5))
svc_discriminator.plot(ax, flag_misclassified=False, show_boundary=True);
```

This measurement can also be used to correct for readout errors using a readout error mitigation tools provided by Qiskit Ignis. In the code below the discriminator returns the states encoded in binary, therefore 0, 1, and 2 are represented by the strings '0', '1', and '10', respectively.

```python
cal_counts = filter012.apply(cal_result_disc).get_counts()
cal_matrix = np.array([[cal_counts[0].get('0',0), cal_counts[1].get('0',0), cal_counts[2].get('0',0)],
                       [cal_counts[0].get('1',0), cal_counts[1].get('1',0), cal_counts[2].get('1',0)],
                       [cal_counts[0].get('10',0), cal_counts[1].get('10',0), cal_counts[2].get('10',0)]])/shots
meas_filter = MeasurementFilter(cal_matrix, ['0', '1', '10'])
```

```python
plt.imshow(cal_matrix, cmap='gray')
plt.xlabel('Prepared state')
plt.ylabel('Measured state');
```

## Geometric single-qubit gates

We now have all the tools needed to implement a single-qubit geometric gate between the $|0\rangle$ and $|2\rangle$ states. This is done by *simultaneously* applying two back-to-back $\pi$-pulses (which corresponds to a $2\pi$ rotation) between the $|0\rangle$ and $|1\rangle$ states and the $|1\rangle$ and $|2\rangle$ states. By using two $\pi$-pulses we save ourselves the task of having to calibrate the $2\pi$-pulses. The pulses that implement the single-qubit geometric gate have the envelope

\begin{align}
a\,\Omega(t)+b\,\eta\,\Omega(t)\,e^{i\alpha t}.
\end{align}

The complex scalars $a$ and $b$ define the rotation angle $\theta$ and phase $\phi$ of the unitary gate that will be implemented on the Bloch sphere created by $|0\rangle$ and $|2\rangle$. $\theta$ and $\phi$ are related to $a$ and $b$ by

\begin{align}
e^{i\phi}\tan\frac{\theta}{2}=\frac{a}{b}.
\end{align}

Note that the pulses that create the single-qubit geometric gate cannot be implement with the `SetFrequency` instruction.

```python
def geometric(a: complex, b: complex, xp: SamplePulse, xp12: SamplePulse, name='') -> Schedule:
    """
    Create a single-qubit geometric gate between the 0 and 2 state.
    In principle the geometric gate is built from a 2pi rotation between 0 and
    1 and a 2pi rotation between 1 and 2. Since we have not calibrated the 2pi
    rotations we will emulate them with two pi back-to-back pi rotations.

    The geometric gate creates a rotation on the Bloch Sphere between |0> and |2>.
    The rotation angle theta and phase phi on the (0,2) Bloch sphere are
    given by e^(i*phi)*tan(theta/2)=a/b.

    Args:
        a: Parameter to control the geometric rotation.
        b: Parameter to control the geometric rotation.
        xp: Calibrated X gate between |0> and |1>.
        xp12: Calibrated X gate between |1> and |2>.

    Returns: A schedules with the geometric gate.
    """

    if abs(abs(a)**2 + abs(b)**2 - 1.0) > 1e-4:
        raise ValueError('a and b must satisfy |a|**2+|b|**2')

    geom_samples = a*xp.samples + b*xp12.samples
    geom = SamplePulse(geom_samples)

    sched = Schedule(name='Geometric (%f, %f) ' % (a, b)+name)
    sched += Play(geom, d0)
    sched += Play(geom, d0)
    sched += meas_sched << sched.duration

    return sched
```

```python
schedules = [cal0, cal1, cal2]
angles = np.linspace(0., np.pi, 70)
for angle in angles:
    a = np.sin(angle/2)
    schedules.append(geometric(a, np.sqrt(1.0-a*a), xp, xp12))
```

The schedule below shows the single-qubit geometric gate, implemented as two back-to-back superpositions of $X_{01}$ and $X_{12}$. These pulses can only be implemented on high resolution devices and cannot be implemented with the `SetFrequency` instruction.

```python
schedules[65].draw(plot_range=[0, 1500], style=style, channels=[d0, MeasureChannel(0)])
```

```python
qobj = assemble(schedules, backend, meas_level=1,
                meas_return=MeasReturnType.SINGLE,
                shots=1024)
```

```python
job = backend.run(qobj)
job.job_id()
```

    '5e8afa81d8deff0019b54e4c'

```python
job.status()
```

    <JobStatus.DONE: 'job has successfully run'>

```python
geom_result = job.result(timeout=3600)
```

To analyse the data we first apply the the 012 discriminator that we build with Qiskit-Ignis. Next, we employ our measurement error mitigation filter to correct the readout.

```python
# Apply discriminator
geom_discriminated = filter012.apply(geom_result)

# Mitigate readout errors
geom_mitigated = meas_filter.apply(geom_discriminated)

# Compute the population counts
counts = geom_mitigated.get_counts()
pop0 = [cnt.get('0',0)/shots for cnt in counts[3:]]
pop1 = [cnt.get('1',0)/shots for cnt in counts[3:]]
pop2 = [cnt.get('10',0)/shots for cnt in counts[3:]]
```

```python
fig, ax = plt.subplots(1, 2, figsize=(14,5), tight_layout=True)

svc_discriminator.plot(ax[0], flag_misclassified=False, show_boundary=True, show_fitting_data=False);
for idx in range(len(angles)):
    iqs = geom_result.get_memory(idx+3)
    ax[0].scatter(np.real(iqs), np.imag(iqs), s=3, color='k',alpha=0.05)

ax[0].set_title('')

ax[1].plot(np.linspace(0, np.pi, 100), np.cos(np.linspace(0, np.pi, 100))**2, '--k')
ax[1].plot(np.linspace(0, np.pi, 100), np.sin(np.linspace(0, np.pi, 100))**2, '--k', label='Ideal')
ax[1].plot(angles, pop0, 'oC0', label='$|0\\rangle$')
ax[1].plot(angles, pop1, 'oC2', label='$|1\\rangle$')
ax[1].plot(angles, pop2, 'oC1', label='$|2\\rangle$')
ax[1].set_xlabel('Rotation angle (rad)')
ax[1].set_ylabel('Transmon population')
ax[1].set_xticks([0, np.pi/2, np.pi])
ax[1].set_xticklabels(['0', '$\pi/2$', '$\pi$'])
ax[1].set_ylim([0, 1.3])
ax[1].set_yticks([0, 0.25, 0.50, 0.75, 1.0])
ax[1].legend(ncol=4, loc=1, fontsize=16, columnspacing=0);
```

```python
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
```

Version Information

Qiskit Software	Version

Qiskit	None

Terra	0.13.0.dev0+4bf9fd5

Aer	0.4.1

Ignis	0.3.0.dev0+5400ab2

Aqua	None

IBM Q Provider	0.5.0

System information

Python	3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0]

OS	Linux

CPUs	4

Memory (Gb)	7.775188446044922

Fri Apr 03 15:06:15 2020 CEST

This code is a part of Qiskit

© Copyright IBM 2017, 2020.

This code is licensed under the Apache License, Version 2.0. You may
obtain a copy of this license in the LICENSE.txt file in the root directory
 of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
Any modifications or derivative works of this code must retain this
copyright notice, and modified files need to carry a notice indicating
that they have been altered from the originals.

```python

```


# Applied Stochastic Processes HW_13

**11510691 程远星$\DeclareMathOperator*{\argmin}{argmin}
\DeclareMathOperator*{\argmax}{argmax}
\DeclareMathOperator*{\plim}{plim}
\newcommand{\ffrac}{\displaystyle \frac}
\newcommand{\d}[1]{\displaystyle{#1}}
\newcommand{\space}{\text{ }}
\newcommand{\bspace}{\;\;\;\;}
\newcommand{\bbspace}{\;\;\;\;\;\;\;\;}
\newcommand{\QQQ}{\boxed{?\:}}
\newcommand{\void}{\left.\right.}
\newcommand{\Tran}[1]{{#1}^{\mathrm{T}}}
\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{\given}[1]{\left. #1 \right|}
\newcommand{\using}[1]{\stackrel{\mathrm{#1}}{=}}
\newcommand{\asim}{\overset{\text{a}}{\sim}}
\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{\dd}{\mathrm{d}}
\newcommand{\I}[1]{\mathrm{I}\left( #1 \right)}
\newcommand{\N}[1]{\mathcal{N}\left( #1 \right)}
\newcommand{\Exp}[1]{\mathrm{E}\left[ #1 \right]}
\newcommand{\Var}[1]{\mathrm{Var}\left[ #1 \right]}
\newcommand{\Avar}[1]{\mathrm{Avar}\left[ #1 \right]}
\newcommand{\Cov}[1]{\mathrm{Cov}\left( #1 \right)}
\newcommand{\Corr}[1]{\mathrm{Corr}\left( #1 \right)}
\newcommand{\ExpH}{\mathrm{E}}
\newcommand{\VarH}{\mathrm{Var}}
\newcommand{\AVarH}{\mathrm{Avar}}
\newcommand{\CovH}{\mathrm{Cov}}
\newcommand{\CorrH}{\mathrm{Corr}}
\newcommand{\ow}{\text{otherwise}}
\newcommand{\wp}{\text{with probability }}
\newcommand{\FSD}{\text{FSD}}
\newcommand{\SSD}{\text{SSD}}
\void^\dagger$**

## Question 1

$$P_{ij}\P t = \begin{cases}
e^{-\mu t} \ffrac{\P{\mu t}^{i-j}}{\P{i-j}!},& 0< i<j\\
\sum\limits_{k=i}^\infty e^{-\mu t} \ffrac{\P{\mu t}^k}{k!},& j=0
\end{cases}$$

## Question 2

$$\begin{align}
P_{ij}\P{t+s} &= P\CB{X\P{t+s} = j \mid X\P0 = i}\\
&= \sum_{k=0}^\infty P\CB{X\P{t+s} = j,X\P t = k \mid X\P0 = i}\\
&= \sum_{k=0}^\infty P\CB{X\P{t+s} = j \mid X\P0 = i,X\P t = k}\cdot P\CB{X\P t = k \mid X\P0 = i}\\
&= \sum_{k=0}^\infty P\CB{X\P{t+s} = j \mid X\P t = k}\cdot P\CB{X\P t = k \mid X\P0 = i}\\
&= \sum_{k=0}^\infty P_{kj}\P s \cdot P_{ik}\P t
\end{align}$$

$$\begin{align}
P_{ij}'\P t &= \lim_{h \to 0} \ffrac{P_{ij}\P{t+h} - P_{ij}\P t}{h}\\
&= \lim_{h \to 0} \ffrac{ \P{\sum\limits_{k\neq i} P_{ik}\P h \cdot P_{kj} \P t} - \P{1-P_{ii}\P h} P_{ij}\P t}{h}\\
&= \lim_{h \to 0}\P{ \sum_{k\neq i} \ffrac{P_{ik}\P h}{h}P_{kj} \P t - \P{\ffrac{1-P_{ii}\P h}{h}}P_{ij}\P t }\\
&= \sum_{k\neq i}\P{ \lim_{h \to 0} \ffrac{P_{ik}\P h}{h}}P_{kj} \P t - \lim_{h \to 0}\P{\ffrac{1-P_{ii}\P h}{h}}P_{ij}\P t \\
&= \sum_{k\neq i} q_{ik} P_{kj}\P t - v_i P_{ij}\P t
\end{align}$$

## Question 3

$\bspace$The four stats are $\P{1,1}$, $\P{1,0}$, $\P{0,1}$, and $\P{0,0}$, where $1$ indicates the machine at that position is working and $0$ otherwise. It is a continuous Markov Chain and we denote the four states $A$, $B$, $C$ and $D$ respectively for notation convenience.

$$v_A = \lambda_1 + \lambda_2,v_B = \lambda_1 + \mu_2,v_C = \mu_1 + \lambda_2,v_D = \mu_1 + \mu_2$$

$\bspace$And thus for the first machine, its transition probabilities are

$$
\begin{align}
P_{11}\P t &= \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1}\\
P_{10}\P t &= \ffrac{\lambda_1 - \lambda_1 e^{-\P{\mu_1 + \lambda_1}t}}{\lambda_1 + \mu_1} \\
P_{01}\P t &= \ffrac{\mu_1 - \mu_1 e^{-\P{\mu_1 + \lambda_1}t}}{\lambda_1 + \mu_1} \\
P_{00}\P t &= \ffrac{\mu_1 e^{-\P{\mu_1 + \lambda_1}t} + \lambda_1}{\lambda_1 + \mu_1}\\
\end{align}
$$

$\bspace$Then for two machines, its transition probabilities are

$$
\begin{align}
P_{AA}\P t &= P_{11}\P t P_{11}^{\P2}\P t = \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1}\cdot \ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2}\\
P_{AB}\P t &= P_{11}\P t P_{10}^{\P2}\P t = \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} \cdot\ffrac{\lambda_2 - \lambda_2 e^{-\P{\mu_2 + \lambda_2}t}}{\lambda_2 + \mu_2} \\
&\vdots\\
P_{DD}\P t &= P_{00}\P t P_{00}^{\P2}\P t = \ffrac{\mu_1 e^{-\P{\mu_1 + \lambda_1}t} + \lambda_1}{\lambda_1 + \mu_1}\cdot\ffrac{\mu_2 e^{-\P{\mu_2 + \lambda_2}t} + \lambda_2}{\lambda_2 + \mu_2}\\
\end{align}
$$

$\bspace$Now we check the backward and forward Kolmogorov's Equations for $P_{AA}$.

$$\begin{align}
&q_{AB}P_{BA}\P t + q_{AC}P_{CA}\P t + q_{AD}P_{DA}\P t - v_A P_{AA}\P t - P_{AA}'\\
=\;& \P{\lambda_1 + \lambda_2} \ffrac{\lambda_2}{\lambda_1 + \lambda_2} \cdot \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} \cdot \ffrac{\mu_2 - \mu_2 e^{-\P{\mu_2 + \lambda_2}t}}{\lambda_2 + \mu_2} \\
&+ \P{\lambda_1 + \lambda_2} \ffrac{\lambda_1}{\lambda_1 + \lambda_2}\cdot \ffrac{\lambda_1 - \lambda_1 e^{-\P{\mu_1 + \lambda_1}t}}{\lambda_1 + \mu_1} \cdot \ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2} \\
&+ \P{\lambda_1 + \lambda_2}\cdot 0 \cdot \ffrac{\mu_1 - \mu_1 e^{-\P{\mu_1 + \lambda_1}t}}{\lambda_1 + \mu_1} \cdot \ffrac{\mu_2 - \mu_2 e^{-\P{\mu_2 + \lambda_2}t}}{\lambda_2 + \mu_2} \\
&- \P{\lambda_1 + \lambda_2} \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} \cdot \ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2} \\
&- \P{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}\ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} - \P{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}\ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2}\\
=\;& \cdots = 0
\end{align}$$

$\bspace$Other transitions are similar. Now we turn to the forward equation of $P_{AA}$.

$$\begin{align}
&q_{BA}P_{AB}\P t + q_{CA}P_{AC}\P t + q_{DA}P_{AD}\P t - v_A P_{AA}\P t - P_{AA}'\\
=\;& \P{\lambda_1 + \mu_2} \ffrac{\mu_2}{\lambda_1 + \lambda_2} \cdot \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} \cdot \ffrac{\lambda_2 - \lambda_2 e^{-\P{\mu_2 + \lambda_2}t}}{\lambda_2 + \mu_2} \\
&+ \P{\mu_1 + \lambda_2} \ffrac{\mu_1}{\mu_1 + \lambda_2}\cdot \ffrac{\mu_1 - \mu_1 e^{-\P{\mu_1 + \lambda_1}t}}{\lambda_1 + \mu_1} \cdot \ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2} \\
&- \P{\lambda_1 + \lambda_1} \ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} \cdot \ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2} \\
&- \P{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}\ffrac{\lambda_1 e^{-\P{\mu_1 + \lambda_1}t} + \mu_1}{\lambda_1 + \mu_1} - \P{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}\ffrac{\lambda_2 e^{-\P{\mu_2 + \lambda_2}t} + \mu_2}{\lambda_2 + \mu_2}\\
=\;& \cdots = 0
\end{align}$$

## Question 4

$\P{1}$

$$\mathbf P = \begin{Vmatrix}
1 - \ffrac{3}{v_1}& \ffrac{1}{v_1} & \ffrac{2}{v_1}\\
\ffrac{2}{v_2}& 1- \ffrac{4}{v_2} & \ffrac{2}{v_2}\\
\ffrac{2}{v_3}& \ffrac{1}{v_3} & 1-\ffrac{3}{v_3}
\end{Vmatrix}$$

$\P{2}$

$$\begin{align}
P_2 &= \ffrac{1}{\ffrac{v_2v_3 - 2}{v_3 + 2} + \ffrac{v_2v_1 - 2}{v_1 + 2}+1} = \ffrac{v_1v_3 + 2v_1 + 2v_3 + 4}{2v_1v_2v_3 + 2v_2v_3 + 2v_2v_1 + v_1v_3 -4}\\
P_1 &= \ffrac{v_1v_2v_3 +2v_2v_3 - 2v_1 - 4}{2v_1v_2v_3 + 2v_2v_3 + 2v_2v_1 + v_1v_3 -4}\\
P_3 &= \ffrac{v_1v_2v_3 +2v_2v_1 - 2v_3 - 4}{2v_1v_2v_3 + 2v_2v_3 + 2v_2v_1 + v_1v_3 -4}
\end{align}$$

Probability and Statistics/Applied Random Process/HW/HW_13.ipynb