# PHY321: Introduction to Classical Mechanics and plans for Spring 2021

**[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

 **Scott Pratt**, Department of Physics and Astronomy and Facility for Rare Ion Beams (FRIB), Michigan State University, USA

Date: **Jan 20, 2021**

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

## Aims and Overview

The first week starts on Monday January 11. This week is dedicated to a
review of learning material and reminder on programming aspects,
useful tools, where to find information and much more. There are no lectures during this week and the material here on vectors and Python programming will also be discussed during the week which begins with January 18. Feel free to look at the notes here before our first lecture on the 20th.

* Introduction to the course and reminder  on vectors, space, time and motion.

* Python programming reminder, elements from [CMSE 201 INTRODUCTION TO COMPUTATIONAL MODELING](https://cmse.msu.edu/academics/undergraduate-program/undergraduate-courses/cmse-201-introduction-to-computational-modeling/) and how they are used in this course. Installing software (anaconda). .

* Introduction to Git and GitHub. [Overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).

**Recommended reading**: John R. Taylor, Classical Mechanics (Univ. Sci. Books 2005), <https://www.uscibooks.com/taylor2.htm>, see also <https://github.com/mhjensen/Physics321/tree/master/doc/Literature>. Chapters 1.2 and 1.3 of Taylor.

## Introduction to the course and where to find material

[Overview video](https://mediaspace.msu.edu/media/t/1_zzl90pfu)

## Classical mechanics

Classical mechanics is a topic which has been taught intensively over
several centuries. It is, with its many variants and ways of
presenting the educational material, normally the first **real** physics
course many of us meet and it lays the foundation for further physics
studies. Many of the equations and ways of reasoning about the
underlying laws of motion and pertinent forces, shape our approaches and understanding
of the scientific method and discourse, as well as the way we develop our insights
and deeper understanding about physical systems.

## From Continuous to Discretized Approaches

There is a wealth of
well-tested (from both a physics point of view and a pedagogical
standpoint) exercises and problems which can be solved
analytically. However, many of these problems represent idealized and
less realistic situations.  The large majority of these problems are
solved by paper and pencil and are traditionally aimed
at what we normally refer to as continuous models from which we may find an analytical solution.  As a consequence,
when teaching mechanics, it implies that we can seldomly venture beyond an idealized case
in order to develop our understandings and insights about the
underlying forces and laws of motion.

We aim at changing this here by introducing throughout the course what
we will call a **computational path**, where with computations we mean
solving scientific problems with all possible tools and means, from
plain paper an pencil exercises, via symbolic calculations to writing
a code and running a program to solve a specific
problem. Mathematically this normally means that we move from a
continuous problem to a discretized one. This appproach enables us to
solve a much broader class of problems.
In mechanics this means, since we often rephrase the physical problems in terms of differential equations, that we can in most settings reuse the same program with some minimal changes.

## Space, Time, Motion, Reference Frames  and Reminder on vectors and other mathematical quantities

Our studies will start with the motion of different types of objects
such as a falling ball, a runner, a bicycle etc etc. It means that an
object's position in space varies with time.
In order to study such systems we need to define

* choice of origin

* choice of the direction of the axes

* choice of positive direction (left-handed or right-handed system of reference)

* choice of units and dimensions

These choices lead to some important questions such as

* is the  physics of a system independent of the origin of the axes?

* is the  physics independent of the directions of the axes, that is are there privileged axes?

* is the physics independent of the orientation of system?

* is the physics independent of the scale of the length?

## Dimension, units and labels

Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass
one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s$^2$ and for energy 1 Joule 1kgm$^2$s$^{-2}$.

We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):
* position $\boldsymbol{r}$, in one dimention we will normally just use $x$,

* mass $m$,

* time $t$,

* velocity $\boldsymbol{v}$ or just $v$ in one dimension,

* acceleration $\boldsymbol{a}$ or just $a$ in one dimension,

* momentum $\boldsymbol{p}$ or just $p$ in one dimension,

* kinetic energy $K$,

* potential energy $V$ and

* frequency $\omega$.

More variables will be defined as we need them.

## Dimensions and Units

It is also important to keep track of dimensionalities. Don't mix this
up with a chosen unit for a given variable. We mark the dimensionality
in these lectures as $[a]$, where $a$ is the quantity we are
interested in. Thus

* $[\boldsymbol{r}]=$ length

* $[m]=$ mass

* $[K]=$ energy

* $[t]=$ time

* $[\boldsymbol{v}]=$ length over time

* $[\boldsymbol{a}]=$ length over time squared

* $[\boldsymbol{p}]=$ mass times length over time

* $[\omega]=$ 1/time

## Scalars, Vectors and Matrices

A scalar is something with a value that is independent of coordinate
system. Examples are mass, or the relative time between events. A
vector has magnitude and direction. Under rotation, the magnitude
stays the same but the direction changes. Scalars have no spatial
index, whereas a three-dimensional vector has 3 indices, e.g. the
position $\boldsymbol{r}$ has components $r_1,r_2,r_3$, which are often
referred to as $x,y,z$.

There are several categories of changes of coordinate system. The
observer can translate the origin, might move with a different
velocity, or might rotate her/his coordinate axes. For instance, a
particle's position vector changes when the origin is translated, but
its velocity does not. When you study relativity you will find that
quantities you thought of as scalars, such as time or an electric
potential, are actually parts of four-dimensional vectors and that
changes of the velocity of the reference frame act in a similar way to
rotations.

In addition to vectors and scalars, there are matrices, which have two
indices. One also has objects with 3 or four indices. These are called
tensors of rank $n$, where $n$ is the number of indices. A matrix is a
rank-two tensor. The Levi-Civita symbol, $\epsilon_{ijk}$ used for
cross products of vectors, is a tensor of rank three.

## Definitions  of Vectors

In these lectures we will use boldfaced lower-case letters to label a
vector. A vector $\boldsymbol{a}$ in three dimensions is thus defined as

$$
\boldsymbol{a} =(a_x,a_y, a_z),
$$

and using the unit vectors (see below) in a cartesian system we have

$$
\boldsymbol{a} = a_x\boldsymbol{e}_1+a_y\boldsymbol{e}_2+a_z\boldsymbol{e}_3,
$$

where the unit vectors have magnitude $\vert\boldsymbol{e}_i\vert = 1$ with
$i=1=x$, $i=2=y$ and $i=3=z$. Some authors use letters
$\boldsymbol{i}=\boldsymbol{e}_1$, $\boldsymbol{j}=\boldsymbol{e}_2$ and $\boldsymbol{k}=\boldsymbol{e}_3$.

## Other ways to define a Vector

Alternatively, you may also encounter the above vector as

$$
\boldsymbol{a} = a_1\boldsymbol{e}_1+a_2\boldsymbol{e}_2+a_3\boldsymbol{e}_3.
$$

Here we have used that $a_1=a_x$, $a_2=a_y$ and $a_3=a_z$. Such a
notation is sometimes more convenient if we wish to represent vector
operations in a mathematically more compact way, see below here. We may also find this useful if  we want the different
components to represent other coordinate systems that the Cartesian one. A typical example would be going from a Cartesian representation to a spherical basis. We will encounter such cases many times in this course.

We use lower-case letters for vectors and upper-case letters for matrices. Vectors and matrices are always boldfaced.

## Polar Coordinates

As an example, consider a two-dimensional Cartesian system with a vector $\boldsymbol{r}=(x,y)$.
Our vector is then written as

$$
\boldsymbol{r} = x\boldsymbol{e}_1+y\boldsymbol{e}_2.
$$

Transforming to polar coordinates with the radius $\rho\in [0,\infty)$
and the angle $\phi \in [0,2\pi]$ we have the familiar transformations

$$
x = \rho \cos{\phi} \hspace{0.5cm}   y = \rho \sin{\phi},
$$

and the inverse relations

$$
\rho =\sqrt{x^2+y^2} \hspace{0.5cm}   \phi = \mathrm{arctan}(\frac{y}{x}).
$$

We can rewrite the vector $\boldsymbol{a}$ in terms of $\rho$ and $\phi$ as

$$
\boldsymbol{a} = \rho \cos{\phi}\boldsymbol{e}_1+\rho \sin{\phi}\boldsymbol{e}_2,
$$

and we define the new unit vectors as $\boldsymbol{e}'_1=\cos{\phi}\boldsymbol{e}_1$ and $\boldsymbol{e}'_2=\sin{\phi}\boldsymbol{e}_2$, we have

$$
\boldsymbol{a}' = \rho\boldsymbol{e}'_1+\rho \boldsymbol{e}'_2.
$$

Below we will show that the norms of this vector in a Cartesian basis and a Polar basis are equal.

## Unit Vectors

Also known as basis vectors, unit vectors point in the direction of
the coordinate axes, have unit norm, and are orthogonal to one
another. Sometimes this is referred to as an orthonormal basis,

$$
\begin{equation}
\boldsymbol{e}_i\cdot\boldsymbol{e}_j=\delta_{ij}=\begin{bmatrix}
1 & 0 & 0\\
0& 1 & 0\\
0 & 0 & 1
\end{bmatrix}.
\label{_auto1} \tag{1}
\end{equation}
$$

Here, $\delta_{ij}$ is unity when $i=j$ and is zero otherwise. This is
called the unit matrix, because you can multiply it with any other
matrix and not change the matrix. The **dot** denotes the dot product,
$\boldsymbol{a}\cdot\boldsymbol{b}=a_1b_1+a_2b_2+a_3b_3=|a||b|\cos\theta_{ab}$. Sometimes
the unit vectors are called $\hat{x}$, $\hat{y}$ and
$\hat{z}$.

## Our definition of unit vectors

Vectors can be decomposed in terms of unit vectors,

$$
\begin{equation}
\boldsymbol{r}=r_1\hat{e}_1+r_2\hat{e}_2+r_3\hat{e}_3.
\label{_auto2} \tag{2}
\end{equation}
$$

The vector components $r_1$, $r_2$ and $r_3$ might be
called $x$, $y$ and $z$ for a displacement. Another way to write this is to define the vector $\boldsymbol{r}=(x,y,z)$.

Similarly, for the velocity we will use in this course the components  $\boldsymbol{v}=(v_x, v_y,v_z$. The accelaration is then given by $\boldsymbol{a}=(a_x,a_y,a_z)$.

## More definitions, repeated indices

As mentioned above, repeated indices infer sums.
This means that when you encounter an expression like the one on the left-hand side here, it stands actually for a sum (right-hand side)

$$
x_iy_i=\sum_i x_iy_i=\boldsymbol{x}\cdot\boldsymbol{y}.
$$

We will in our lectures seldom use this notation and rather spell out the summations.  This inferred summation over indices is normally called [Einstein summation convention](https://en.wikipedia.org/wiki/Einstein_notation).

## Vector Operations, Scalar Product (or dot product)

For two vectors $\boldsymbol{a}$ and $\boldsymbol{b}$ we have

$$
\begin{eqnarray*}
\boldsymbol{a}\cdot\boldsymbol{b}&=&\sum_ia_ib_i=|a||b|\cos\theta_{ab},\\
|a|&\equiv& \sqrt{\boldsymbol{a}\cdot\boldsymbol{a}},
\end{eqnarray*}
$$

or with a norm-2 notation

$$
|a|\equiv \vert\vert \boldsymbol{a}\vert\vert_2=\sqrt{\sum_i a_i^2}.
$$

Not of all of you are familiar with linear algebra. Numerically we will always deal with arrays and the dot product vector is given by the product of the transposed vector multiplied with the other vector, that is we have

$$
\boldsymbol{a}^T\boldsymbol{b}=\sum_i a_ib_i=|a||b|\cos\theta_{ab}.
$$

The superscript $T$ represents the transposition operations.

## Digression, Linear Algebra Notation for Vectors

As an example, consider a three-dimensional velocity defined by a vector $\boldsymbol{v}=(v_x,v_y,v_z)$. For those of you familiar with linear algebra, we would write this quantity as

$$
\boldsymbol{v}=\begin{bmatrix} v_x\\ v_y \\ v_z \end{bmatrix},
$$

and the transpose as

$$
\boldsymbol{v}^T=\begin{bmatrix} v_x & v_y &v_z \end{bmatrix}.
$$

The norm is

$$
\boldsymbol{v}^T\boldsymbol{v}=v_x^2+v_y^2+v_z^2,
$$

as it should.

Since we will use Python as a programming language throughout this course, the above vector, using the package **numpy** (see discussions below), can be written as

```python
import numpy as np
# Define the values of vx, vy and vz
vx = 0.0
vy = 1.0
vz = 0.0
v = np.array([vx, vy, vz])
print(v)
# The print the transpose of v
print(v.T)
```

Try to figure out how to calculate the norm with **numpy**.
We will come back to **numpy** in the examples below.

## Norm of a transformed Vector

As an example, consider our transformation of a two-dimensional Cartesian vector $\boldsymbol{r}$ to polar coordinates.
We had

$$
\boldsymbol{r} = x\boldsymbol{e}_1+y\boldsymbol{e}_2.
$$

Transforming to polar coordinates with the radius $\rho\in [0,\infty)$
and the angle $\phi \in [0,2\pi]$ we have

$$
x = \rho \cos{\phi} \hspace{0.5cm}   y = \rho \sin{\phi}.
$$

We can write this

$$
\boldsymbol{r} = \begin{bmatrix} x \\ y \end{bmatrix}= \begin{bmatrix} \rho \cos{\phi}  \\ \rho \sin{\phi}  \end{bmatrix}.
$$

The norm in Cartesian coordinates is $\boldsymbol{r}\cdot\boldsymbol{r}=x^2+y^2$ and
using Polar coordinates we have
$\rho^2(\cos{\phi})^2+\rho^2(\cos{\phi})^2=\rho^2$, which shows that
the norm is conserved since we have $\rho = \sqrt{x^2+y^2}$. A
transformation to a new basis should not change the norm.

## Vector Product (or cross product) of vectors $\boldsymbol{a}$ and $\boldsymbol{b}$

$$
\begin{eqnarray*}
\boldsymbol{c}&=&\boldsymbol{a}\times\boldsymbol{b},\\
c_i&=&\epsilon_{ijk}a_jb_k.
\end{eqnarray*}
$$

Here $\epsilon$ is the third-rank anti-symmetric tensor, also known as
the Levi-Civita symbol. It is $\pm 1$ only if all three indices are
different, and is zero otherwise. The choice of $\pm 1$ depends on
whether the indices are an even or odd permutation of the original
symbols. The permutation $xyz$ or $123$ is considered to be $+1$. Its elements are

$$
\begin{eqnarray}
\epsilon_{ijk}&=&-\epsilon_{ikj}=-\epsilon_{jik}=-\epsilon_{kji}\\
\nonumber
\epsilon_{123}&=&\epsilon_{231}=\epsilon_{312}=1,\\
\nonumber
\epsilon_{213}&=&\epsilon_{132}=\epsilon_{321}=-1,\\
\nonumber
\epsilon_{iij}&=&\epsilon_{iji}=\epsilon_{jii}=0.
\end{eqnarray}
$$

## More on cross-products

You may have met cross-products when studying magnetic
fields. Because the matrix is anti-symmetric, switching the $x$ and
$y$ axes (or any two axes) flips the sign. If the coordinate system is
right-handed, meaning the $xyz$ axes satisfy
$\hat{x}\times\hat{y}=\hat{z}$, where you can point along the $x$ axis
with your extended right index finger, the $y$ axis with your
contracted middle finger and the $z$ axis with your extended
thumb. Switching to a left-handed system flips the sign of the vector
$\boldsymbol{c}=\boldsymbol{a}\times\boldsymbol{b}$.

Note that
$\boldsymbol{a}\times\boldsymbol{b}=-\boldsymbol{b}\times\boldsymbol{a}$. The vector $\boldsymbol{c}$ is
perpendicular to both $\boldsymbol{a}$ and $\boldsymbol{b}$ and the magnitude of
$\boldsymbol{c}$ is given by

$$
|c|=|a||b|\sin{\theta_{ab}}.
$$

## Pseudo-vectors

Vectors obtained by the cross product of two real vectors are called
pseudo-vectors because the assignment of their direction can be
arbitrarily flipped by defining the Levi-Civita symbol to be based on
left-handed rules. Examples are the magnetic field and angular
momentum. If the direction of a real vector prefers the right-handed
over the left-handed direction, that constitutes a violation of
parity. For instance, one can polarize the spins (angular momentum) of
nuclei with a magnetic field so that the spins preferentially point
along the direction of the magnetic field. This does not violate
parity because both are pseudo-vectors. Now assume these polarized
nuclei decay and that electrons are one of the products. If these
electrons prefer to exit the decay parallel vs. antiparallel to the
polarizing magnetic field, this constitutes parity violation because
the direction of the outgoing electron momenta are a real vector. This
is precisely what is observed in weak decays.

## Differentiation of a vector with respect to a scalar

For example, the
acceleration $\boldsymbol{a}$ is given by the change in velocity per unit time, $\boldsymbol{a}=d\boldsymbol{v}/dt$
with components

$$
a_i = (d\boldsymbol{v}/dt)_i=\frac{dv_i}{dt}.
$$

Here $i=x,y,z$ or $i=1,2,3$ if we are in three dimensions.

## Gradient operator $\nabla$

This represents  the derivatives $\partial/\partial
x$, $\partial/\partial y$ and $\partial/\partial z$. An often used shorthand is  $\partial_x=\partial/\partial_x$.

The gradient of a scalar function of position and time
$\Phi(x,y,z)=\Phi(\boldsymbol{r},t)$ is given by

$$
\boldsymbol{\nabla}~\Phi,
$$

with components $i$

$$
(\nabla\Phi(x,y,z,t))_i=\partial/\partial r_i\Phi(\boldsymbol{r},t)=\partial_i\Phi(\boldsymbol{r},t).
$$

Note that the gradient is a vector.

Taking the dot product of the gradient with a vector, normally called the divergence,
we have

$$
\mathrm{div} \boldsymbol{a}, \nabla\cdot\boldsymbol{a}=\sum_i \partial_i a_i.
$$

Note that the divergence is a scalar.

## The curl

The **curl** of a vector is defined as
$\nabla\times\boldsymbol{a}$,

$$
{\rm\bf curl}~\boldsymbol{a},
$$

with components

$$
(\boldsymbol{\nabla}\times\boldsymbol{a})_i=\epsilon_{ijk}\partial_j a_k(\boldsymbol{r},t).
$$

## The Laplacian

The Laplacian is referred to as $\nabla^2$ and is defined as

$$
\boldsymbol{\nabla}^2=\boldsymbol{\nabla}\cdot\boldsymbol{\nabla}=\frac{\partial^2}{\partial x^2}+\frac{\partial^2}{\partial y^2}+\frac{\partial^2}{\partial z^2}.
$$

Question: is the Laplacian a scalar or a vector?

## Some identities

Here we simply state these, but you may wish to prove a few. They are useful for this class and will be essential when you study electromagnetism.

$$
\begin{eqnarray}
\boldsymbol{a}\cdot(\boldsymbol{b}\times\boldsymbol{c})&=&\boldsymbol{b}\cdot(\boldsymbol{c}\times\boldsymbol{a})=\boldsymbol{c}\cdot(\boldsymbol{a}\times\boldsymbol{b})\\
\nonumber
\boldsymbol{a}\times(\boldsymbol{b}\times\boldsymbol{c})&=&(\boldsymbol{a}\cdot\boldsymbol{c})\boldsymbol{b}-(\boldsymbol{a}\cdot\boldsymbol{b})\boldsymbol{c}\\
\nonumber
(\boldsymbol{a}\times\boldsymbol{b})\cdot(\boldsymbol{c}\times\boldsymbol{d})&=&(\boldsymbol{a}\cdot\boldsymbol{c})(\boldsymbol{b}\cdot\boldsymbol{d})
-(\boldsymbol{a}\cdot\boldsymbol{d})(\boldsymbol{b}\cdot\boldsymbol{c})
\end{eqnarray}
$$

## More useful relations

Using the fact that multiplication of reals is distributive we can show that

$$
\boldsymbol{a}(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\boldsymbol{b}+\boldsymbol{a}\boldsymbol{c},
$$

Similarly we can also show that (using product rule for differentiating reals)

$$
\frac{d}{dt}(\boldsymbol{a}\boldsymbol{b})=\boldsymbol{a}\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\frac{d\boldsymbol{a}}{dt}.
$$

We can repeat these operations for the cross products and show that they are distribuitive

$$
\boldsymbol{a}\times(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\times\boldsymbol{b}+\boldsymbol{a}\times\boldsymbol{c}.
$$

We have also that

$$
\frac{d}{dt}(\boldsymbol{a}\times\boldsymbol{b})=\boldsymbol{a}\times\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\times\frac{d\boldsymbol{a}}{dt}.
$$

## Gauss's Theorem

For an integral over a volume $V$ confined by a surface $S$, Gauss's theorem gives

$$
\int_V dv~\nabla\cdot\boldsymbol{A}=\int_Sd\boldsymbol{S}\cdot\boldsymbol{A}.
$$

For a closed path $C$ which carves out some area $S$,

$$
\int_C d\boldsymbol{\ell}\cdot\boldsymbol{A}=\int_Sd\boldsymbol{s} \cdot(\nabla\times\boldsymbol{A})
$$

## and Stokes's Theorem

Stoke's law can be understood by considering a small rectangle,
$-\Delta x<x<\Delta x$, $-\Delta y<y<\Delta y$. The path integral
around the edges is

$$
\begin{eqnarray}
\int_C d\boldsymbol{\ell}\cdot\boldsymbol{A}&=&2\Delta y[A_y(\Delta x,0)-A_y(-\Delta x,0)]-2\Delta x[A_x(0,\Delta y)-A_x(0,-\Delta y)]\\
\nonumber
&=&4\Delta x\Delta y\left\{
\frac{A_y(\Delta x,0)-A_y(-\Delta x,0)}{2\Delta x}-\frac{A_x(0,\Delta y)-A_x(0,-\Delta y)}{2\Delta y}\right\}\\
\nonumber
&=&4\Delta x\Delta y\left\{\frac{\partial A_y}{\partial x}-\frac{\partial A_x}{\partial y}\right\}\\
&=&\Delta S \cdot \nabla\times\boldsymbol{A}.
\end{eqnarray}
$$

Here $\Delta S$ is the area of the surface element.

## Basic Matrix Features

**Note**: The material on matrices is optional and will not be used much
(except for illustrations at the very end on garmonic oscillations)
since most of you have not yet taken a course on linear algebra. The
material is however included here for the sake of completeness.

$$
\mathbf{A} =
      \begin{bmatrix} a_{11} & a_{12} & a_{13} & a_{14} \\
                                 a_{21} & a_{22} & a_{23} & a_{24} \\
                                   a_{31} & a_{32} & a_{33} & a_{34} \\
                                  a_{41} & a_{42} & a_{43} & a_{44}
             \end{bmatrix}\qquad
\mathbf{I} =
      \begin{bmatrix} 1 & 0 & 0 & 0 \\
                                 0 & 1 & 0 & 0 \\
                                 0 & 0 & 1 & 0 \\
                                 0 & 0 & 0 & 1
             \end{bmatrix}
$$

## Inverse of a Matrix

The inverse of a matrix is defined by

$$
\mathbf{A}^{-1} \cdot \mathbf{A} = I
$$

              Relations               	       Name     	                             matrix elements

   $A = A^{T}$                               	    symmetric          	    $a_{ij} = a_{ji}$

   $A = \left (A^{T} \right )^{-1}$          	    real orthogonal    	    $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$

   $A = A^{ * }$                             	    real matrix        	    $a_{ij} = a_{ij}^{ * }$

   $A = A^{\dagger}$                         	    hermitian          	    $a_{ij} = a_{ji}^{ * }$

   $A = \left (A^{\dagger} \right )^{-1}$    	    unitary            	    $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$

## Some famous Matrices

  * Diagonal if $a_{ij}=0$ for $i\ne j$

  * Upper triangular if $a_{ij}=0$ for $i > j$

  * Lower triangular if $a_{ij}=0$ for $i < j$

  * Upper Hessenberg if $a_{ij}=0$ for $i > j+1$

  * Lower Hessenberg if $a_{ij}=0$ for $i < j+1$

  * Tridiagonal if $a_{ij}=0$ for $|i -j| > 1$

  * Lower banded with bandwidth $p$: $a_{ij}=0$ for $i > j+p$

  * Upper banded with bandwidth $p$: $a_{ij}=0$ for $i < j+p$

  * Banded, block upper triangular, block lower triangular....

## More Basic Matrix Features

**Some Equivalent Statements.**

For an $N\times N$ matrix  $\mathbf{A}$ the following properties are all equivalent

  * If the inverse of $\mathbf{A}$ exists, $\mathbf{A}$ is nonsingular.

  * The equation $\mathbf{Ax}=0$ implies $\mathbf{x}=0$.

  * The rows of $\mathbf{A}$ form a basis of $R^N$.

  * The columns of $\mathbf{A}$ form a basis of $R^N$.

  * $\mathbf{A}$ is a product of elementary matrices.

  * $0$ is not eigenvalue of $\mathbf{A}$.

## Rotations

Here, we use rotations as an example of matrices and their operations. One can consider a different orthonormal basis $\hat{e}'_1$, $\hat{e}'_2$ and $\hat{e}'_3$. The same vector $\boldsymbol{r}$ mentioned above can also be expressed in the new basis,

$$
\begin{equation}
\boldsymbol{r}=r'_1\hat{e}'_1+r'_2\hat{e}'_2+r'_3\hat{e}'_3.
\label{_auto3} \tag{3}
\end{equation}
$$

Even though it is the same vector, the components have changed. Each
new unit vector $\hat{e}'_i$ can be expressed as a linear sum of the
previous vectors,

$$
\begin{equation}
\hat{e}'_i=\sum_j U_{ij}\hat{e}_j,
\label{_auto4} \tag{4}
\end{equation}
$$

and the matrix $U$ can be found by taking the dot product of both sides with $\hat{e}_k$,

$$
\begin{eqnarray}
\nonumber
\hat{e}_k\cdot\hat{e}'_i&=&\sum_jU_{ij}\hat{e}_k\cdot\hat{e}_j\\
\label{eq:lambda_angles} \tag{5}
\hat{e}_k\cdot\hat{e}'_i&=&\sum_jU_{ij}\delta_{jk}=U_{ik}.
\end{eqnarray}
$$

## More on the matrix $U$

Thus, the matrix lambda has components $U_{ij}$ that are equal to the
cosine of the angle between new unit vector $\hat{e}'_i$ and the old
unit vector $\hat{e}_j$.

$$
\begin{equation}
U = \begin{bmatrix}
\hat{e}'_1\cdot\hat{e}_1& \hat{e}'_1\cdot\hat{e}_2& \hat{e}'_1\cdot\hat{e}_3\\
\hat{e}'_2\cdot\hat{e}_1& \hat{e}'_2\cdot\hat{e}_2& \hat{e}'_2\cdot\hat{e}_3\\
\hat{e}'_3\cdot\hat{e}_1& \hat{e}'_3\cdot\hat{e}_2& \hat{e}'_3\cdot\hat{e}_3
\end{bmatrix},~~~~~U_{ij}=\hat{e}'_i\cdot\hat{e}_j=\cos\theta_{ij}.
\label{_auto5} \tag{6}
\end{equation}
$$

## Properties of the matrix $U$

Note that the matrix is not symmetric, $U_{ij}\ne U_{ji}$. One can also look at the inverse transformation, by switching the primed and unprimed coordinates,

$$
\begin{eqnarray}
\label{eq:inverseU} \tag{7}
\hat{e}_i&=&\sum_jU^{-1}_{ij}\hat{e}'_j,\\
\nonumber
U^{-1}_{ij}&=&\hat{e}_i\cdot\hat{e}'_j=U_{ji}.
\end{eqnarray}
$$

The definition of transpose of a matrix, $M^{t}_{ij}=M_{ji}$, allows one to state this as

$$
\begin{eqnarray}
\label{eq:transposedef} \tag{8}
U^{-1}&=&U^{t}.
\end{eqnarray}
$$

## Tensors

A tensor obeying Eq. ([8](#eq:transposedef)) defines what is known as
a unitary, or orthogonal, transformation.

The matrix $U$ can be used to transform any vector to the new basis. Consider a vector

$$
\begin{eqnarray}
\boldsymbol{r}&=&r_1\hat{e}_1+r_2\hat{e}_2+r_3\hat{e}_3\\
\nonumber
&=&r'_1\hat{e}'_1+r'_2\hat{e}'_2+r'_3\hat{e}'_3.
\end{eqnarray}
$$

This is the same vector expressed as a sum over two different sets of
basis vectors. The coefficients $r_i$ and $r'_i$ represent components
of the same vector. The relation between them can be found by taking
the dot product of each side with one of the unit vectors,
$\hat{e}_i$, which gives

$$
\begin{eqnarray}
r_i&=&\sum_j \hat{e}_i\cdot\hat{e}'_j~r'_j.
\end{eqnarray}
$$

Using Eq. ([7](#eq:inverseU)) one can see that the transformation of $r$ can be also written in terms of $U$,

$$
\begin{eqnarray}
\label{eq:rotateR} \tag{9}
r_i&=&\sum_jU^{-1}_{ij}~r'_j.
\end{eqnarray}
$$

Thus, the matrix that transforms the coordinates of the unit vectors,
Eq. ([7](#eq:inverseU)) is the same one that transforms the
coordinates of a vector, Eq. ([9](#eq:rotateR)).

## Rotation matrix

As a small exercise, find the rotation matrix $U$ for finding the
components in the primed coordinate system given from those in the
unprimed system, given that the unit vectors in the new system are
found by rotating the coordinate system by and angle $\phi$ about the
$z$ axis.

In this case

$$
\begin{eqnarray*}
\hat{e}'_1&=&\cos\phi \hat{e}_1-\sin\phi\hat{e}_2,\\
\hat{e}'_2&=&\sin\phi\hat{e}_1+\cos\phi\hat{e}_2,\\
\hat{e}'_3&=&\hat{e}_3.
\end{eqnarray*}
$$

By inspecting Eq. ([5](#eq:lambda_angles)), we get

$$
U=\left(\begin{array}{ccc}
\cos\phi&-\sin\phi&0\\
\sin\phi&\cos\phi&0\\
0&0&1\end{array}\right).
$$

## Unitary Transformations

Under a unitary transformation $U$ (or basis transformation) scalars
are unchanged, whereas vectors $\boldsymbol{r}$ and matrices $M$ change as

$$
\begin{eqnarray}
r'_i&=&U_{ij}~ r_j, ~~({\rm sum~inferred})\\
\nonumber
M'_{ij}&=&U_{ik}M_{km}U^{-1}_{mj}.
\end{eqnarray}
$$

Physical quantities with no spatial indices are scalars (or
pseudoscalars if they depend on right-handed vs. left-handed
coordinate systems), and are unchanged by unitary
transformations. This includes quantities like the trace of a matrix,
the matrix itself had indices but none remain after performing the
trace.

$$
\begin{eqnarray}
{\rm Tr} M&\equiv& M_{ii}.
\end{eqnarray}
$$

Because there are no remaining indices, one expects it to be a scalar. Indeed one can see this,

$$
\begin{eqnarray}
{\rm Tr} M'&=&U_{ij}M_{jm}U^{-1}_{mi}\\
\nonumber
&=&M_{jm}U^{-1}_{mi}U_{ij}\\
\nonumber
&=&M_{jm}\delta_{mj}\\
\nonumber
&=&M_{jj}={\rm Tr} M.
\end{eqnarray}
$$

A similar example is the determinant of a matrix, which is also a scalar.

## Numerical Elements

Numerical algorithms call for approximate discrete models and much of
the development of methods for continuous models are nowadays being
replaced by methods for discrete models in science and industry,
simply because **much larger classes of problems can be addressed** with
discrete models, often by simpler and more generic methodologies.

As we will see throughout this course, when properly scaling the equations at hand,
discrete models open up for more advanced abstractions and the possibility to
study  real life systems, with the added bonus that we can explore and
deepen our basic understanding of various physical systems

Analytical solutions are as important as before. In addition, such
solutions provide us with invaluable benchmarks and tests for our
discrete models. Such benchmarks, as we will see below, allow us
to discuss possible sources of errors and their behaviors.  And
finally, since most of our models are based on various algorithms from
numerical mathematics, we have a unique oppotunity to gain a deeper
understanding of the mathematical approaches we are using.

With computing and data science as important elements in essentially
all aspects of a modern society, we could  then try to define Computing as
**solving scientific problems using all possible tools, including
symbolic computing, computers and numerical algorithms, and analytical
paper and pencil solutions**.
Computing provides us with the tools to develope our own understanding of the scientific method by enhancing algorithmic thinking.

## Computations and the Scientific Method

The way we will teach this course reflects this definition of
computing. The course contains both classical paper and pencil
exercises as well as computational projects and exercises. The hope is
that this will allow you to explore the physics of systems governed by
the degrees of freedom of classical mechanics at a deeper level, and
that these insights about the scientific method will help you to
develop a better understanding of how the underlying forces and
equations of motion and how they impact a given system.

Furthermore,
by introducing various numerical methods via computational projects
and exercises, we aim at developing your competences and skills about
these topics.

## Computational Competences

These competences will enable you to

* understand how algorithms are used to solve mathematical problems,

* derive, verify, and implement algorithms,

* understand what can go wrong with algorithms,

* use these algorithms to construct reproducible scientific outcomes and to engage in science in ethical ways, and

* think algorithmically for the purposes of gaining deeper insights about scientific problems.

All these elements are central for maturing and gaining a better understanding of the modern scientific process *per se*.

The power of the scientific method lies in identifying a given problem
as a special case of an abstract class of problems, identifying
general solution methods for this class of problems, and applying a
general method to the specific problem (applying means, in the case of
computing, calculations by pen and paper, symbolic computing, or
numerical computing by ready-made and/or self-written software). This
generic view on problems and methods is particularly important for
understanding how to apply available, generic software to solve a
particular problem.

*However, verification of algorithms and understanding their limitations requires much of the classical knowledge about continuous models.*

## A well-known example to illustrate many of the above concepts

Before we venture into a reminder on Python and mechanics relevant applications, let us briefly outline some of the
abovementioned topics using an example many of you may have seen before in for example CMSE201.
A simple algorithm for integration is the Trapezoidal rule.
Integration of a function $f(x)$ by the Trapezoidal Rule is given by following algorithm for an interval $x \in [a,b]$

$$
\int_a^b(f(x) dx = \frac{1}{2}\left [f(a)+2f(a+h)+\dots+2f(b-h)+f(b)\right] +O(h^2),
$$

where $h$ is the so-called stepsize defined by the number of integration points $N$ as $h=(b-a)/(n)$.
Python offers an  extremely versatile programming  environment, allowing for
the inclusion of analytical studies in a numerical program. Here we show an
example code with the **trapezoidal rule**. We use also **SymPy** to evaluate the exact value of the integral and compute the absolute error
with respect to the numerically evaluated one of the integral
$\int_0^1 dx x^2 = 1/3$.
The following code for  the trapezoidal rule allows you  to plot the relative error by comparing with the exact result. By increasing to $10^8$ points one arrives at a region where numerical errors start to accumulate.

```python
%matplotlib inline

from math import log10
import numpy as np
from sympy import Symbol, integrate
import matplotlib.pyplot as plt
# function for the trapezoidal rule
def Trapez(a,b,f,n):
   h = (b-a)/float(n)
   s = 0
   x = a
   for i in range(1,n,1):
       x = x+h
       s = s+ f(x)
   s = 0.5*(f(a)+f(b)) +s
   return h*s
#  function to compute pi
def function(x):
    return x*x
# define integration limits
a = 0.0;  b = 1.0;
# find result from sympy
# define x as a symbol to be used by sympy
x = Symbol('x')
exact = integrate(function(x), (x, a, b))
# set up the arrays for plotting the relative error
n = np.zeros(9); y = np.zeros(9);
# find the relative error as function of integration points
for i in range(1, 8, 1):
    npts = 10**i
    result = Trapez(a,b,function,npts)
    RelativeError = abs((exact-result)/exact)
    n[i] = log10(npts); y[i] = log10(RelativeError);
plt.plot(n,y, 'ro')
plt.xlabel('n')
plt.ylabel('Relative error')
plt.show()
```

## Analyzing the above example

This example shows the potential of combining numerical algorithms
with symbolic calculations, allowing us to

* Validate and verify  their  algorithms.

* Including concepts like unit testing, one has the possibility to test and test several or all parts of the code.

* Validation and verification are then included *naturally* and one can develop a better attitude to what is meant with an ethically sound scientific approach.

* The above example allows the student to also test the mathematical error of the algorithm for the trapezoidal rule by changing the number of integration points. The students get **trained from day one to think error analysis**.

* With a Jupyter notebook you can keep exploring similar examples and turn them in as your own notebooks.

## Python practicalities, Software and needed installations

We will make extensive use of Python as programming language and its
myriad of available libraries.  You will find
Jupyter notebooks invaluable in your work.

If you have Python installed (we strongly recommend Python3) and you feel
pretty familiar with installing different packages, we recommend that
you install the following Python packages via **pip** as

1. pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow

For Python3, replace **pip** with **pip3**.

For OSX users we recommend, after having installed Xcode, to
install **brew**. Brew allows for a seamless installation of additional
software via for example

1. brew install python3

For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
you can use **pip** as well and simply install Python as

1. sudo apt-get install python3  (or python for pyhton2.7)

etc etc.

## Python installers

If you don't want to perform these operations separately and venture
into the hassle of exploring how to set up dependencies and paths, we
recommend two widely used distrubutions which set up all relevant
dependencies for Python, namely

* [Anaconda](https://docs.anaconda.com/),

which is an open source
distribution of the Python and R programming languages for large-scale
data processing, predictive analytics, and scientific computing, that
aims to simplify package management and deployment. Package versions
are managed by the package management system **conda**.

* [Enthought canopy](https://www.enthought.com/product/canopy/)

is a Python
distribution for scientific and analytic computing distribution and
analysis environment, available for free and under a commercial
license.

Furthermore, [Google's Colab](https://colab.research.google.com/notebooks/welcome.ipynb) is a free Jupyter notebook environment that requires
no setup and runs entirely in the cloud. Try it out!

## Useful Python libraries
Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)

* [NumPy](https://www.numpy.org/) is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays

* [The pandas](https://pandas.pydata.org/) library provides high-performance, easy-to-use data structures and data analysis tools

* [Xarray](http://xarray.pydata.org/en/stable/) is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!

* [Scipy](https://www.scipy.org/) (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.

* [Matplotlib](https://matplotlib.org/) is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

* [Autograd](https://github.com/HIPS/autograd) can automatically differentiate native Python and Numpy code. It can handle a large subset of Python's features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives

* [SymPy](https://www.sympy.org/en/index.html) is a Python library for symbolic mathematics.

* [scikit-learn](https://scikit-learn.org/stable/) has simple and efficient tools for machine learning, data mining and data analysis

* [TensorFlow](https://www.tensorflow.org/) is a Python library for fast numerical computing created and released by Google

* [Keras](https://keras.io/) is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano

* And many more such as [pytorch](https://pytorch.org/),  [Theano](https://pypi.org/project/Theano/) etc

Your jupyter notebook can easily be
converted into a nicely rendered **PDF** file or a Latex file for
further processing. For example, convert to latex as

        pycod jupyter nbconvert filename.ipynb --to latex

And to add more versatility, the Python package [SymPy](http://www.sympy.org/en/index.html) is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS)  and is entirely written in Python.

## Numpy examples and Important Matrix and vector handling packages

There are several central software libraries for linear algebra and eigenvalue problems. Several of the more
popular ones have been wrapped into ofter software packages like those from the widely used text **Numerical Recipes**. The original source codes in many of the available packages are often taken from the widely used
software package LAPACK, which follows two other popular packages
developed in the 1970s, namely EISPACK and LINPACK.  We describe them shortly here.

  * LINPACK: package for linear equations and least square problems.

  * LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACK's website <http://www.netlib.org> it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.

  * BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from <http://www.netlib.org>.

## Numpy and arrays

[Numpy](http://www.numpy.org/) provides an easy way to handle arrays in Python. The standard way to import this library is as

```python
import numpy as np
```

Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,

```python
n = 10
x = np.random.normal(size=n)
print(x)
```

    [ 0.0894565   1.94971919 -1.00217137  1.04531722  1.65047376 -0.39492747
      0.07211386 -0.43060307 -0.44633089  0.74168775]

We defined a vector $x$ with $n=10$ elements with its values given by the Normal distribution $N(0,1)$.
Another alternative is to declare a vector as follows

```python
import numpy as np
vx = 0.0
vy = 1.0
vz = 0.0
v = np.array([vx, vy, vz])
print(v)
```

    [0. 1. 0.]

Here we have defined a vector with three elements, with $x_0=1$, $x_1=2$ and $x_2=3$. Note that both Python and C++
start numbering array elements from $0$ and on. This means that a vector with $n$ elements has a sequence of entities $x_0, x_1, x_2, \dots, x_{n-1}$. We could also let (recommended) Numpy to compute the logarithms of a specific array as

```python
import numpy as np
x = np.log(np.array([4, 7, 8]))
print(x)
```

    [1.38629436 1.94591015 2.07944154]

In the last example we used Numpy's unary function $np.log$. This function is
highly tuned to compute array elements since the code is vectorized
and does not require looping. We normaly recommend that you use the
Numpy intrinsic functions instead of the corresponding **log** function
from Python's **math** module. The looping is done explicitely by the
**np.log** function. The alternative, and slower way to compute the
logarithms of a vector would be to write

```python
import numpy as np
from math import log
x = np.array([4, 7, 8])
for i in range(0, len(x)):
    x[i] = log(x[i])
print(x)
```

We note that our code is much longer already and we need to import the **log** function from the **math** module.
The attentive reader will also notice that the output is $[1, 1, 2]$. Python interprets automagically our numbers as integers (like the **automatic** keyword in C++). To change this we could define our array elements to be double precision numbers as

```python
import numpy as np
x = np.log(np.array([4, 7, 8], dtype = np.float64))
print(x)
```

or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is

```python
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x)
```

To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the **itemsize** functionality (the array $x$ is actually an object which inherits the functionalities defined in Numpy) as

```python
import numpy as np
x = np.log(np.array([4.0, 7.0, 8.0])
print(x.itemsize)
```

## Matrices in Python

Having defined vectors, we are now ready to try out matrices. We can
define a $3 \times 3 $ real matrix $\hat{A}$ as (recall that we user
lowercase letters for vectors and uppercase letters for matrices)

```python
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
print(A)
```

If we use the **shape** function we would get $(3, 3)$ as output, that is verifying that our matrix is a $3\times 3$ matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as

```python
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[:,0])
```

We can continue this was by printing out other columns or rows. The example here prints out the second column

```python
import numpy as np
A = np.log(np.array([ [4.0, 7.0, 8.0], [3.0, 10.0, 11.0], [4.0, 5.0, 7.0] ]))
# print the first column, row-major order and elements start with 0
print(A[1,:])
```

Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the [Numpy website for more details](http://www.numpy.org/). Useful functions when defining a matrix are the **np.zeros** function which declares a matrix of a given dimension and sets all elements to zero

```python
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to zero
A = np.zeros( (n, n) )
print(A)
```

or initializing all elements to

```python
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to one
A = np.ones( (n, n) )
print(A)
```

or as unitarily distributed random numbers (see the material on random number generators in the statistics part)

```python
import numpy as np
n = 10
# define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]
A = np.random.rand(n, n)
print(A)
```

## Meet the Pandas

Another useful Python package is
[pandas](https://pandas.pydata.org/), which is an open source library
providing high-performance, easy-to-use data structures and data
analysis tools for Python. **pandas** stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.

**pandas** has two major classes, the **DataFrame** class with
two-dimensional data objects and tabular data organized in columns and
the class **Series** with a focus on one-dimensional data objects. Both
classes allow you to index data easily as we will see in the examples
below.  **pandas** allows you also to perform mathematical operations on
the data, spanning from simple reshapings of vectors and matrices to
statistical operations.

The following simple example shows how we can, in an easy way make
tables of our data. Here we define a data set which includes names,
place of birth and date of birth, and displays the data in an easy to
read way. We will see repeated use of **pandas**, in particular in
connection with classification of data.

```python
import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
        'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
        'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
        'Date of Birth T.A.': [2968, 2890, 2931, 2980]
        }
data_pandas = pd.DataFrame(data)
display(data_pandas)
```

      First Name
      Last Name
      Place of birth
      Date of Birth T.A.

      0
      Frodo
      Baggins
      Shire
      2968

      1
      Bilbo
      Baggins
      Shire
      2890

      2
      Aragorn II
      Elessar
      Eriador
      2931

      3
      Samwise
      Gamgee
      Shire
      2980

In the above we have imported **pandas** with the shorthand **pd**, the latter has become the standard way we import **pandas**. We make then a list of various variables
and reorganize the above lists into a **DataFrame** and then print out  a neat table with specific column labels as *Name*, *place of birth* and *date of birth*.
Displaying these results, we see that the indices are given by the default numbers from zero to three.
**pandas** is extremely flexible and we can easily change the above indices by defining a new type of indexing as

```python
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)
```

      First Name
      Last Name
      Place of birth
      Date of Birth T.A.

      Frodo
      Frodo
      Baggins
      Shire
      2968

      Bilbo
      Bilbo
      Baggins
      Shire
      2890

      Aragorn
      Aragorn II
      Elessar
      Eriador
      2931

      Sam
      Samwise
      Gamgee
      Shire
      2980

Thereafter we display the content of the row which begins with the index **Aragorn**

```python
display(data_pandas.loc['Aragorn'])
```

    First Name            Aragorn II
    Last Name                Elessar
    Place of birth           Eriador
    Date of Birth T.A.          2931
    Name: Aragorn, dtype: object

We can easily append data to this, for example

```python
new_hobbit = {'First Name': ["Peregrin"],
              'Last Name': ["Took"],
              'Place of birth': ["Shire"],
              'Date of Birth T.A.': [2990]
              }
data_pandas=data_pandas.append(pd.DataFrame(new_hobbit, index=['Pippin']))
display(data_pandas)
```

      First Name
      Last Name
      Place of birth
      Date of Birth T.A.

      Frodo
      Frodo
      Baggins
      Shire
      2968

      Bilbo
      Bilbo
      Baggins
      Shire
      2890

      Aragorn
      Aragorn II
      Elessar
      Eriador
      2931

      Sam
      Samwise
      Gamgee
      Shire
      2980

      Pippin
      Peregrin
      Took
      Shire
      2990

Here are other examples where we use the **DataFrame** functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix
of dimensionality $10\times 5$ and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.

```python
import numpy as np
import pandas as pd
from IPython.display import display
np.random.seed(100)
# setting up a 10 x 5 matrix
rows = 10
cols = 5
a = np.random.randn(rows,cols)
df = pd.DataFrame(a)
display(df)
print(df.mean())
print(df.std())
display(df**2)
```

      0
      1
      2
      3
      4

      0
      -1.749765
      0.342680
      1.153036
      -0.252436
      0.981321

      1
      0.514219
      0.221180
      -1.070043
      -0.189496
      0.255001

      2
      -0.458027
      0.435163
      -0.583595
      0.816847
      0.672721

      3
      -0.104411
      -0.531280
      1.029733
      -0.438136
      -1.118318

      4
      1.618982
      1.541605
      -0.251879
      -0.842436
      0.184519

      5
      0.937082
      0.731000
      1.361556
      -0.326238
      0.055676

      6
      0.222400
      -1.443217
      -0.756352
      0.816454
      0.750445

      7
      -0.455947
      1.189622
      -1.690617
      -1.356399
      -1.232435

      8
      -0.544439
      -0.668172
      0.007315
      -0.612939
      1.299748

      9
      -1.733096
      -0.983310
      0.357508
      -1.613579
      1.470714

    0   -0.175300
    1    0.083527
    2   -0.044334
    3   -0.399836
    4    0.331939
    dtype: float64
    0    1.069584
    1    0.965548
    2    1.018232
    3    0.793167
    4    0.918992
    dtype: float64

      0
      1
      2
      3
      4

      0
      3.061679
      0.117430
      1.329492
      0.063724
      0.962990

      1
      0.264421
      0.048920
      1.144993
      0.035909
      0.065026

      2
      0.209789
      0.189367
      0.340583
      0.667239
      0.452553

      3
      0.010902
      0.282259
      1.060349
      0.191963
      1.250636

      4
      2.621102
      2.376547
      0.063443
      0.709698
      0.034047

      5
      0.878123
      0.534362
      1.853835
      0.106431
      0.003100

      6
      0.049462
      2.082875
      0.572069
      0.666597
      0.563167

      7
      0.207888
      1.415201
      2.858185
      1.839818
      1.518895

      8
      0.296414
      0.446453
      0.000054
      0.375694
      1.689345

      9
      3.003620
      0.966899
      0.127812
      2.603636
      2.162999

Thereafter we can select specific columns only and plot final results

```python
df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
df.index = np.arange(10)

display(df)
print(df['Second'].mean() )
print(df.info())
print(df.describe())

from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'

df.cumsum().plot(lw=2.0, figsize=(10,6))
plt.show()

df.plot.bar(figsize=(10,6), rot=15)
plt.show()
```

We can produce a $4\times 4$ matrix

```python
b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)
```

and many other operations.

The **Series** class is another important class included in
**pandas**. You can view it as a specialization of **DataFrame** but where
we have just a single column of data. It shares many of the same
features as **DataFrame**. As with **DataFrame**, most operations are
vectorized, achieving thereby a high performance when dealing with
computations of arrays, in particular labeled arrays.  As we will see
below it leads also to a very concice code close to the mathematical
operations we may be interested in.  For multidimensional arrays, we
recommend strongly
[xarray](http://xarray.pydata.org/en/stable/). **xarray** has much of
the same flexibility as **pandas**, but allows for the extension to
higher dimensions than two.

## Introduction to Git and GitHub/GitLab and similar

[Git](https://git-scm.com/) is a distributed version-control system
for tracking changes in any set of files, originally designed for
coordinating work among programmers cooperating on source code during
software development.

The [reference document and videos here](https://git-scm.com/doc)
give you an excellent introduction to the **git**.

We believe you will find version-control software very useful in your work.

## GitHub, GitLab and many other

[GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), [Bitbucket](https://bitbucket.org/product?&aceid=&adposition=&adgroup=92266806717&campaign=1407243017&creative=414608923671&device=c&keyword=bitbucket&matchtype=e&network=g&placement=&ds_kids=p51241248597&ds_e=GOOGLE&ds_eid=700000001551985&ds_e1=GOOGLE&gclid=Cj0KCQiA6Or_BRC_ARIsAPzuer_yrxzs-R8KDVdF0-DduJR9hTBYcjdE8L9_CkA9eyz8XT7-3bFGOpQaAqe2EALw_wcB&gclsrc=aw.ds) and other are code hosting platforms for
version control and collaboration. They let you and others work
together on projects from anywhere.

All teaching material related to this course is open and freely
available via the GitHub site of the course. The video here gives a
short intro to
[GitHub](https://www.youtube.com/watch/w3jLJU7DT5E?reload=9).

See also the [overview video on Git and GitHub](https://mediaspace.msu.edu/media/t/1_8mgx3cyf).

## Useful Git and GitHub links

These are a couple references that we have found useful (git commands, markdown, GitPages):
* <https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet>

* <https://education.github.com/git-cheat-sheet-education.pdf>

* <https://guides.github.com/features/pages/>

## Useful IDEs and text editors

When dealing with homeworks, at some point you would need to use an
editor, or an integrated development envinroment (IDE). As an IDE, we
would like to recommend **anaconda** since we end up using
jupyter-notebooks.  **anaconda** runs on all known operating systems.

If you prefer editing **Python** codes, there are several excellent cross-platform editors.
If you are in a Windows environment, **word** is the classical text editor.

There is however a wealth of text editors and/ord IDEs that run on all operating
systems and functions well with Python.  Some of the more popular ones  are

* [Atom](https://atom.io/)

* [Sublime](https://www.sublimetext.com/)


# Customer Segmentation: Estimate Individualized Responses to Incentives

Nowadays, business decision makers rely on estimating the causal effect of interventions to answer what-if questions about shifts in strategy, such as promoting specific product with discount, adding new features to a website or increasing investment from a sales team. However, rather than learning whether to take action for a specific intervention for all users, people are increasingly interested in understanding the different responses from different users to the two alternatives. Identifying the characteristics of users having the strongest response for the intervention could help make rules to segment the future users into different groups. This can help optimize the policy to use the least resources and get the most profit.

In this case study, we will use a personalized pricing example to explain how the [EconML](https://aka.ms/econml) and [DoWhy](https://github.com/microsoft/dowhy) libraries could fit into this problem and provide robust and reliable causal solutions.

### Summary

1. [Background](#background)
2. [Data](#data)
3. [Create Causal Model and Identify Causal Effect with DoWhy](#identify)
4. [Get Causal Effects with EconML](#estimate)
5. [Test Estimate Robustness with DoWhy](#robustness)
    1. [Add Random Common Cause](#random-common-cause)
    2. [Add Unobserved Common Cause](#unobserved-common-cause)
    3. [Replace Treatment with a Random (Placebo) Variable](#placebo-variable)
    4. [Remove a Random Subset of the Data](#subset)
6. [Understand Treatment Effects with EconML](#interpret)
7. [Make Policy Decisions with EconML](#policy)
8. [Conclusions](#conclusion)

# Background

The global online media market is growing fast over the years. Media companies are always interested in attracting more users into the market and encouraging them to buy more songs or become members. In this example, we'll consider a scenario where one experiment a media company is running is to give small discount (10%, 20% or 0) to their current users based on their income level in order to boost the likelihood of their purchase. The goal is to understand the **heterogeneous price elasticity of demand** for people with different income level, learning which users would respond most strongly to a small discount. Furthermore, their end goal is to make sure that despite decreasing the price for some consumers, the demand is raised enough to boost the overall revenue.

The EconML and DoWhy libraries complement each other in implementing this solution. On one hand, the DoWhy library can help [build a causal model, indentify the causal effect](#identify) and [test causal assumptions](#robustness). On the other hand, EconML’s `DML` based estimators can be used to take the discount variation in existing data, along with a rich set of user features, to [estimate heterogeneous price sensitivities](#estimate) that vary with multiple customer features. Then, the `SingleTreeCateInterpreter` provides a [presentation-ready summary](#interpret) of the key features that explain the biggest differences in responsiveness to a discount, and the `SingleTreePolicyInterpreter` recommends a [policy](#policy) on who should receive a discount in order to increase revenue (not only demand), which could help the company to set an optimal price for those users in the future.

```python
# Some imports to get us started
import warnings
warnings.simplefilter('ignore')

# Utilities
import os
import urllib.request
import numpy as np
import pandas as pd
from networkx.drawing.nx_pydot import to_pydot
from IPython.display import Image, display

# Generic ML imports
from sklearn.preprocessing import PolynomialFeatures
from sklearn.ensemble import GradientBoostingRegressor

# EconML imports
from econml.dml import LinearDML, CausalForestDML
from econml.cate_interpreter import SingleTreeCateInterpreter, SingleTreePolicyInterpreter

import matplotlib.pyplot as plt

%matplotlib inline
```

# Data

The dataset* has ~10,000 observations and includes 9 continuous and categorical variables that represent user's characteristics and online behaviour history such as age, log income, previous purchase, previous online time per week, etc.

We define the following variables:

Feature Name|Type|Details
:--- |:---|:---
**account_age** |W| user's account age
**age** |W|user's age
**avg_hours** |W| the average hours user was online per week in the past
**days_visited** |W| the average number of days user visited the website per week in the past
**friend_count** |W| number of friends user connected in the account
**has_membership** |W| whether the user had membership
**is_US** |W| whether the user accesses the website from the US
**songs_purchased** |W| the average songs user purchased per week in the past
**income** |X| user's income
**price** |T| the price user was exposed during the discount season (baseline price * small discount)
**demand** |Y| songs user purchased during the discount season

**To protect the privacy of the company, we use the simulated data as an example here. The data is synthetically generated and the feature distributions don't correspond to real distributions. However, the feature names have preserved their names and meaning.*

The treatment and outcome are generated using the following functions:
$$
T =
\begin{cases}
  1 & \text{with } p=0.2,  \\
  0.9 & \text{with }p=0.3, & \text{if income}<1 \\
  0.8 & \text{with }p=0.5, \\
  \\
    1 & \text{with }p=0.7, \\
  0.9 & \text{with }p=0.2, & \text{if income}\ge1 \\
  0.8 & \text{with }p=0.1, \\
\end{cases}
$$

\begin{align}
\gamma(X) & = -3 - 14 \cdot \{\text{income}<1\} \\
\beta(X,W) & = 20 + 0.5 \cdot \text{avg_hours} + 5 \cdot \{\text{days_visited}>4\} \\
Y &= \gamma(X) \cdot T + \beta(X,W)
\end{align}

```python
# Import the sample pricing data
file_url = "https://msalicedatapublic.blob.core.windows.net/datasets/Pricing/pricing_sample.csv"
train_data = pd.read_csv(file_url)
```

```python
# Data sample
train_data.head()
```

      account_age
      age
      avg_hours
      days_visited
      friends_count
      has_membership
      is_US
      songs_purchased
      income
      price
      demand

      0
      3
      53
      1.834234
      2
      8
      1
      1
      4.903237
      0.960863
      1.0
      3.917117

      1
      5
      54
      7.171411
      7
      9
      0
      1
      3.330161
      0.732487
      1.0
      11.585706

      2
      3
      33
      5.351920
      6
      9
      0
      1
      3.036203
      1.130937
      1.0
      24.675960

      3
      2
      34
      6.723551
      0
      8
      0
      1
      7.911926
      0.929197
      1.0
      6.361776

      4
      4
      30
      2.448247
      5
      8
      1
      0
      7.148967
      0.533527
      0.8
      12.624123

```python
# Define estimator inputs
train_data["log_demand"] = np.log(train_data["demand"])
train_data["log_price"] = np.log(train_data["price"])

Y = train_data["log_demand"].values
T = train_data["log_price"].values
X = train_data[["income"]].values  # features
confounder_names = ["account_age", "age", "avg_hours", "days_visited", "friends_count", "has_membership", "is_US", "songs_purchased"]
W = train_data[confounder_names].values
```

```python
# Get test data
X_test = np.linspace(0, 5, 100).reshape(-1, 1)
X_test_data = pd.DataFrame(X_test, columns=["income"])
```

# Create Causal Model and Identify Causal Effect with DoWhy

We define the causal assumptions with DoWhy. For example, we can include features we believe as confounders and features we think will influence the heterogeneity of the effect. With these assumptions defined, DoWhy can generate a causal graph for us, and use that graph to first identify the causal effect.

```python
# initiate an EconML cate estimator
est = LinearDML(model_y=GradientBoostingRegressor(), model_t=GradientBoostingRegressor(),
              featurizer=PolynomialFeatures(degree=2, include_bias=False))
```

```python
# fit through dowhy
est_dw = est.dowhy.fit(Y, T, X=X, W=W, outcome_names=["log_demand"], treatment_names=["log_price"], feature_names=["income"],
               confounder_names=confounder_names, inference="statsmodels")
```

    WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs.
    INFO:dowhy.causal_graph:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named "Unobserved Confounders" to reflect this.
    INFO:dowhy.causal_model:Model to find the causal effect of treatment ['log_price'] on outcome ['log_demand']
    WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.
    INFO:dowhy.causal_identifier:Continuing by ignoring these unobserved confounders because proceed_when_unidentifiable flag is True.
    INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:[]
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income

```python
# Visualize causal graph
try:
    # Try pretty printing the graph. Requires pydot and pygraphviz
    display(
        Image(to_pydot(est_dw._graph._graph).create_png())
    )
except:
    # Fall back on default graph view
    est_dw.view_model()
```

```python
identified_estimand = est_dw.identified_estimand_
print(identified_estimand)
```

    Estimand type: nonparametric-ate

    ### Estimand : 1
    Estimand name: backdoor1 (Default)
    Estimand expression:
         d
    ────────────(Expectation(log_demand|is_US,has_membership,days_visited,age,inco
    d[log_price]

    me,account_age,avg_hours,songs_purchased,friends_count))

    Estimand assumption 1, Unconfoundedness: If U→{log_price} and U→log_demand then P(log_demand|log_price,is_US,has_membership,days_visited,age,income,account_age,avg_hours,songs_purchased,friends_count,U) = P(log_demand|log_price,is_US,has_membership,days_visited,age,income,account_age,avg_hours,songs_purchased,friends_count)

    ### Estimand : 2
    Estimand name: iv
    No such variable found!

# Get Causal Effects with EconML

Based on the identified causal effect above, we fit the model as follows using EconML:

\begin{align}
log(Y) & = \theta(X) \cdot log(T) + f(X,W) + \epsilon \\
log(T) & = g(X,W) + \eta
\end{align}

where $\epsilon, \eta$ are uncorrelated error terms.

The models we fit here aren't an exact match for the data generation function above, but if they are a good approximation, they will allow us to create a good discount policy.  Although the model is misspecified, we hope to see that our `DML` based estimators can still capture the right trend of $\theta(X)$ and that the recommended policy beats other baseline policies (such as always giving a discount) on revenue.  Because of the mismatch between the data generating process and the model we're fitting, there isn't a single true $\theta(X)$ (the true elasticity varies with not only X but also T and W), but given how we generate the data above, we can still calculate the range of true $\theta(X)$ to compare against.

```python
# Define underlying treatment effect function given DGP
def gamma_fn(X):
    return -3 - 14 * (X["income"] < 1)

def beta_fn(X):
    return 20 + 0.5 * (X["avg_hours"]) + 5 * (X["days_visited"] > 4)

def demand_fn(data, T):
    Y = gamma_fn(data) * T + beta_fn(data)
    return Y

def true_te(x, n, stats):
    if x < 1:
        subdata = train_data[train_data["income"] < 1].sample(n=n, replace=True)
    else:
        subdata = train_data[train_data["income"] >= 1].sample(n=n, replace=True)
    te_array = subdata["price"] * gamma_fn(subdata) / (subdata["demand"])
    if stats == "mean":
        return np.mean(te_array)
    elif stats == "median":
        return np.median(te_array)
    elif isinstance(stats, int):
        return np.percentile(te_array, stats)
```

```python
# Get the estimate and range of true treatment effect
truth_te_estimate = np.apply_along_axis(true_te, 1, X_test, 1000, "mean")  # estimate
truth_te_upper = np.apply_along_axis(true_te, 1, X_test, 1000, 95)  # upper level
truth_te_lower = np.apply_along_axis(true_te, 1, X_test, 1000, 5)  # lower level
```

## Parametric heterogeneity
First of all, we can try to learn a **linear projection of the treatment effect** assuming a polynomial form of $\theta(X)$. We use the `LinearDML` estimator. Since we don't have any priors on these models, we use a generic gradient boosting tree estimators to learn the expected price and demand from the data.

```python
lineardml_estimate = est_dw.estimate_
print(lineardml_estimate)
```

    *** Causal Estimate ***

    ## Identified estimand
    Estimand type: nonparametric-ate

    ## Realized estimand
    b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    Target units: ate

    ## Estimate
    Mean value: -0.9956103906192235

```python
# Get treatment effect and its confidence interval
te_pred = est_dw.effect(X_test).flatten()
te_pred_interval = est_dw.effect_interval(X_test)
```

```python
# Compare the estimate and the truth
plt.figure(figsize=(10, 6))
plt.plot(X_test.flatten(), te_pred, label="Sales Elasticity Prediction")
plt.plot(X_test.flatten(), truth_te_estimate, "--", label="True Elasticity")
plt.fill_between(
    X_test.flatten(),
    te_pred_interval[0].flatten(),
    te_pred_interval[1].flatten(),
    alpha=0.2,
    label="95% Confidence Interval",
)
plt.fill_between(
    X_test.flatten(),
    truth_te_lower,
    truth_te_upper,
    alpha=0.2,
    label="True Elasticity Range",
)
plt.xlabel("Income")
plt.ylabel("Songs Sales Elasticity")
plt.title("Songs Sales Elasticity vs Income")
plt.legend(loc="lower right")
```

From the plot above, it's clear to see that the true treatment effect is a **nonlinear** function of income, with elasticity around -1.75 when income is smaller than 1 and a small negative value when income is larger than 1. The model fits a quadratic treatment effect, which is not a great fit. But it still captures the overall trend: the elasticity is negative and people are less sensitive to the price change if they have higher income.

```python
# Get the final coefficient and intercept summary
est_dw.summary(feature_names=["income"])
```

Coefficient Results

      	     point_estimate	 stderr	  zstat	  pvalue	 ci_lower	 ci_upper

  income	        2.386	      0.081	 29.485	    0.0	    2.227	    2.545

  income^2	      -0.42	      0.028	 -15.185	   0.0	   -0.474	   -0.366

CATE Intercept Results

         	        point_estimate	 stderr	  zstat	  pvalue	 ci_lower	 ci_upper

  cate_intercept	     -3.003	      0.049	 -60.738	   0.0	    -3.1	    -2.906

A linear parametric conditional average treatment effect (CATE) model was fitted:
$Y = \Theta(X)\cdot T + g(X, W) + \epsilon$
where for every outcome $i$ and treatment $j$ the CATE $\Theta_{ij}(X)$ has the form:
$\Theta_{ij}(X) = \phi(X)' coef_{ij} + cate\_intercept_{ij}$
where $\phi(X)$ is the output of the `featurizer` or $X$ if `featurizer`=None. Coefficient Results table portrays the $coef_{ij}$ parameter vector for each outcome $i$ and treatment $j$. Intercept Results table portrays the $cate\_intercept_{ij}$ parameter.

`LinearDML` estimator can also return the summary of the coefficients and intercept for the final model, including point estimates, p-values and confidence intervals. From the table above, we notice that $income$ has positive effect and ${income}^2$ has negative effect, and both of them are statistically significant.

## Nonparametric Heterogeneity
Since we already know the true treatment effect function is nonlinear, let us fit another model using `CausalForestDML`, which assumes a fully **nonparametric estimation of the treatment effect**.

```python
# initiate an EconML cate estimator
est_nonparam = CausalForestDML(model_y=GradientBoostingRegressor(), model_t=GradientBoostingRegressor())
# fit through dowhy
est_nonparam_dw = est_nonparam.dowhy.fit(Y, T, X=X, W=W, outcome_names=["log_demand"], treatment_names=["log_price"],
                                         feature_names=["income"], confounder_names=confounder_names, inference="blb")
```

    WARNING:dowhy.causal_model:Causal Graph not provided. DoWhy will construct a graph based on data inputs.
    INFO:dowhy.causal_graph:If this is observed data (not from a randomized experiment), there might always be missing confounders. Adding a node named "Unobserved Confounders" to reflect this.
    INFO:dowhy.causal_model:Model to find the causal effect of treatment ['log_price'] on outcome ['log_demand']
    WARNING:dowhy.causal_identifier:If this is observed data (not from a randomized experiment), there might always be missing confounders. Causal effect cannot be identified perfectly.
    INFO:dowhy.causal_identifier:Continuing by ignoring these unobserved confounders because proceed_when_unidentifiable flag is True.
    INFO:dowhy.causal_identifier:Instrumental variables for treatment and outcome:[]
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income

```python
# Get treatment effect and its confidence interval
te_pred = est_nonparam_dw.effect(X_test).flatten()
te_pred_interval = est_nonparam_dw.effect_interval(X_test)
```

```python
# Compare the estimate and the truth
plt.figure(figsize=(10, 6))
plt.plot(X_test.flatten(), te_pred, label="Sales Elasticity Prediction")
plt.plot(X_test.flatten(), truth_te_estimate, "--", label="True Elasticity")
plt.fill_between(
    X_test.flatten(),
    te_pred_interval[0].flatten(),
    te_pred_interval[1].flatten(),
    alpha=0.2,
    label="95% Confidence Interval",
)
plt.fill_between(
    X_test.flatten(),
    truth_te_lower,
    truth_te_upper,
    alpha=0.2,
    label="True Elasticity Range",
)
plt.xlabel("Income")
plt.ylabel("Songs Sales Elasticity")
plt.title("Songs Sales Elasticity vs Income")
plt.legend(loc="lower right")
```

We notice that this model fits much better than the `LinearDML`, the 95% confidence interval correctly covers the true treatment effect estimate and captures the variation when income is around 1. Overall, the model shows that people with low income are much more sensitive to the price changes than higher income people.

# Test Estimate Robustness with DoWhy

### Add Random Common Cause

How robust are our estimates to adding another confounder? We use DoWhy to test this!

```python
res_random = est_nonparam_dw.refute_estimate(method_name="random_common_cause", num_simulations=5)
print(res_random)
```

    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count+w_random | income

    Refute: Add a Random Common Cause
    Estimated effect:-0.9594204479199662
    New effect:-0.9574777656374094

### Add Unobserved Common Cause

How robust are our estimates to unobserved confounders? Since we assume the model is under unconfoundedness, adding an unobserved confounder might bias the estimates. We use DoWhy to test this!

```python
res_unobserved = est_nonparam_dw.refute_estimate(
    method_name="add_unobserved_common_cause",
    confounders_effect_on_treatment="linear",
    confounders_effect_on_outcome="linear",
    effect_strength_on_treatment=0.1,
    effect_strength_on_outcome=0.1,
)
print(res_unobserved)
```

    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income

    Refute: Add an Unobserved Common Cause
    Estimated effect:-0.9594204479199662
    New effect:0.20029340691678463

### Replace Treatment with a Random (Placebo) Variable

What happens our estimates if we replace the treatment variable with noise? Ideally, the average effect would be wildly different than our original estimate. We use DoWhy to investigate!

```python
res_placebo = est_nonparam_dw.refute_estimate(
    method_name="placebo_treatment_refuter", placebo_type="permute",
    num_simulations=3
)
print(res_placebo)
```

    INFO:dowhy.causal_refuters.placebo_treatment_refuter:Refutation over 3 simulated datasets of permute treatment
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~placebo+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~placebo+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~placebo+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    WARNING:dowhy.causal_refuters.placebo_treatment_refuter:We assume a Normal Distribution as the sample has less than 100 examples.
                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.

    Refute: Use a Placebo Treatment
    Estimated effect:-0.9594204479199662
    New effect:-0.0009044538846515711
    p value:0.4246571154416484

### Remove a Random Subset of the Data

Do we recover similar estimates on subsets of the data? This speaks to the ability of our chosen estimator to generalize well. We use DoWhy to investigate this!

```python
res_subset = est_nonparam_dw.refute_estimate(
    method_name="data_subset_refuter", subset_fraction=0.8,
    num_simulations=3)
print(res_subset)
```

    INFO:dowhy.causal_refuters.data_subset_refuter:Refutation over 0.8 simulated datasets of size 8000.0 each
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    INFO:dowhy.causal_estimator:INFO: Using EconML Estimator
    INFO:dowhy.causal_estimator:b: log_demand~log_price+is_US+has_membership+days_visited+age+income+account_age+avg_hours+songs_purchased+friends_count | income
    WARNING:dowhy.causal_refuters.data_subset_refuter:We assume a Normal Distribution as the sample has less than 100 examples.
                     Note: The underlying distribution may not be Normal. We assume that it approaches normal with the increase in sample size.

    Refute: Use a subset of data
    Estimated effect:-0.9594204479199662
    New effect:-0.9571011772201145
    p value:0.19397906736405435

# Understand Treatment Effects with EconML
EconML includes interpretability tools to better understand treatment effects. Treatment effects can be complex, but oftentimes we are interested in simple rules that can differentiate between users who respond positively, users who remain neutral and users who respond negatively to the proposed changes.

The EconML `SingleTreeCateInterpreter` provides interperetability by training a single decision tree on the treatment effects outputted by the any of the EconML estimators. In the figure below we can see in dark red users respond strongly to the discount and the in white users respond lightly to the discount.

```python
intrp = SingleTreeCateInterpreter(include_model_uncertainty=True, max_depth=2, min_samples_leaf=10)
intrp.interpret(est_nonparam_dw, X_test)
plt.figure(figsize=(25, 5))
intrp.plot(feature_names=["income"], fontsize=12)
```

# Make Policy Decision with EconML
We want to make policy decisions to maximum the **revenue** instead of the demand. In this scenario,

\begin{align}
Rev & = Y \cdot T \\
    & = \exp^{log(Y)} \cdot T\\
    & = \exp^{(\theta(X) \cdot log(T) + f(X,W) + \epsilon)} \cdot T \\
    & = \exp^{(f(X,W) + \epsilon)} \cdot T^{(\theta(X)+1)}
\end{align}

With the decrease of price, revenue will increase only if $\theta(X)+1<0$. Thus, we set `sample_treatment_cast=-1` here to learn **what kinds of customers we should give a small discount to maximum the revenue**.

The EconML library includes policy interpretability tools such as `SingleTreePolicyInterpreter` that take in a treatment cost and the treatment effects to learn simple rules about which customers to target profitably. In the figure below we can see the model recommends to give discount for people with income less than $0.985$ and give original price for the others.

```python
intrp = SingleTreePolicyInterpreter(risk_level=0.05, max_depth=2, min_samples_leaf=1, min_impurity_decrease=0.001)
intrp.interpret(est_nonparam_dw, X_test, sample_treatment_costs=-1)
plt.figure(figsize=(25, 5))
intrp.plot(feature_names=["income"], treatment_names=["Discount", "No-Discount"], fontsize=12)
```

Now, let us compare our policy with other baseline policies! Our model says which customers to give a small discount to, and for this experiment, we will set a discount level of 10% for those users. Because the model is misspecified we would not expect good results with large discounts. Here, because we know the ground truth, we can evaluate the value of this policy.

```python
# define function to compute revenue
def revenue_fn(data, discount_level1, discount_level2, baseline_T, policy):
    policy_price = baseline_T * (1 - discount_level1) * policy + baseline_T * (1 - discount_level2) * (1 - policy)
    demand = demand_fn(data, policy_price)
    rev = demand * policy_price
    return rev
```

```python
policy_dic = {}
# our policy above
policy = intrp.treat(X)
policy_dic["Our Policy"] = np.mean(revenue_fn(train_data, 0, 0.1, 1, policy))

## previous strategy
policy_dic["Previous Strategy"] = np.mean(train_data["price"] * train_data["demand"])

## give everyone discount
policy_dic["Give Everyone Discount"] = np.mean(revenue_fn(train_data, 0.1, 0, 1, np.ones(len(X))))

## don't give discount
policy_dic["Give No One Discount"] = np.mean(revenue_fn(train_data, 0, 0.1, 1, np.ones(len(X))))

## follow our policy, but give -10% discount for the group doesn't recommend to give discount
policy_dic["Our Policy + Give Negative Discount for No-Discount Group"] = np.mean(revenue_fn(train_data, -0.1, 0.1, 1, policy))

## give everyone -10% discount
policy_dic["Give Everyone Negative Discount"] = np.mean(revenue_fn(train_data, -0.1, 0, 1, np.ones(len(X))))
```

```python
# get policy summary table
res = pd.DataFrame.from_dict(policy_dic, orient="index", columns=["Revenue"])
res["Rank"] = res["Revenue"].rank(ascending=False)
res
```

      Revenue
      Rank

      Our Policy
      14.686241
      2.0

      Previous Strategy
      14.349342
      4.0

      Give Everyone Discount
      13.774469
      6.0

      Give No One Discount
      14.294606
      5.0

      Our Policy + Give Negative Discount for No-Discount Group
      15.564411
      1.0

      Give Everyone Negative Discount
      14.612670
      3.0

**We beat the baseline policies!** Our policy gets the highest revenue except for the one raising the price for the No-Discount group. That means our currently baseline price is low, but the way we segment the user does help increase the revenue!

# Conclusions

In this notebook, we have demonstrated the power of using EconML and DoWhy to:

* Estimate the treatment effect correctly even the model is misspecified
* Test causal assumptions and investigate the robustness of the resulting estimates
* Interpret the resulting individual-level treatment effects
* Make the policy decision beats the previous and baseline policies

To learn more about what EconML can do for you, visit our [website](https://aka.ms/econml), our [GitHub page](https://github.com/microsoft/EconML) or our [docummentation](https://econml.azurewebsites.net/).

To learn more about what DoWhy can do for you, visit the [GitHub page](https://github.com/microsoft/dowhy) or [documentation](https://microsoft.github.io/dowhy/index.html).

notebooks/CustomerScenarios/Case Study - Customer Segmentation at An Online Media Company - EconML + DoWhy.ipynb


```python
# %load /Users/facai/Study/book_notes/preconfig.py
%matplotlib inline

import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)
sns.set(font='SimHei')
plt.rcParams['axes.grid'] = False

from IPython.display import SVG

def show_image(filename, figsize=None):
    if figsize:
        plt.figure(figsize=figsize)

    plt.imshow(plt.imread(filename))
```

xgboost的基本原理与实现简介
========================

xgboost是个很棒的工具，其优点很多：运行速度，支持正则，直接用损失函数指导树的生成等等，不一而足。相较spark自带的gbdt，xgboost更适合工程应用。

本文参照论文 Tianqi Chen and Carlos Guestrin. XGBoost: A Scalable Tree Boosting System，介绍下xgboost对原始gbdt的改进地方，并说明下具体的实现细节。

代码版本信息：

```bash
~/W/xgboost ❯❯❯ git log -n 1
commit 74db1e8867eb9ecfacf07311131c2724dbc3fdbd
Author: Nan Zhu <CodingCat@users.noreply.github.com>
Date:   Sun Aug 28 21:25:49 2016 -0400

    [jvm-packages] remove APIs with DMatrix from xgboost-spark  (#1519)

    * test consistency of prediction functions between DMatrix and RDD

    * remove APIs with DMatrix from xgboost-spark

    * fix compilation error in xgboost4j-example

    * fix test cases
```

### 0. 大纲

xgboost的贡献，既有理论上的拓展，也有工程上的性能优化。本文只关心在其在理论上的改进，主要是将正则（Regularized）引入损失函数，并且用损失函数直接指导树的生成。我们用传统GBDT做引，一步步走到xgboost。

这里假设读者已经了解决策树和GBDT的原理，不会过多铺垫。

### 1. GBDT框架

为了便于后续讲解，首先会引入公式描述决策树和GBDT模型，涉及的数学知识是比较简易的，不要恐慌。

对于一个$J$颗叶子的决策树（CART），可以表示为加法模型[1]：

\begin{equation}
    f(x) = h \left (x; \{b_j, R_j\}^J_1 \right ) = \displaystyle \sum_{j=1}^J b_j \mathbf{1}(x \in R_j)
\end{equation}

其中$R_j$是叶子，$b_j$是叶子对应的值。

对于一个tree ensemble model，就是$K$颗树的结果叠加：

\begin{equation}
    \hat{y}_i = \phi(x_i) = \displaystyle \sum_{k=1}^K f_k(x_i)
\end{equation}

具体到传统的GBDT，其可描述成最优问题：

\begin{align}
    f_m &= \displaystyle \operatorname{arg \, min}_f \sum_{i=1}^n L \left ( y_i, \hat{y}_i + f(x_i) \right ) \\
        &= \operatorname{arg \, min} \mathcal{L}(f)
\end{align}

传统的思路，便是借用最速下降的想法，认定损失函数中$f(x_i)$是关于梯度的一个函数。而xgboost正是在这里做了新的文章，引入正则，泰勒展开，再揉进树模型里。

[1]:  Friedman - Greedy function approximation: A gradient boosting machine

### 2. xgboost

#### 2.0 正则

xgboost将正则 $\Omega(f)$ 引入进损失函数 $\mathcal{L}(f)$，控制了树的叶子数$\|R_j\|$和叶子值$b_j$，表示如下：

\begin{align}
    \mathcal{L}(f) &= \displaystyle \sum_{i=1}^{n} L(y_i, \hat{y}_i + f(x_i)) + \Omega(f) \\
    \Omega(f) &= \gamma \|R_j\| + \frac{1}{2} \lambda \|b_j\|^2
\end{align}

但这样纯理论的公式是无法应用到工程上的，要用它指导树模型的生成，必须将它的这两个加法项$\sum L(f)$和$\Omega(f)$整合，才可以直接指导模型生成。要整合，重点有两个，一是打开$\sum L(f)$，放出$f$；二是将$\mathcal{L}(f)$转换成指导树生长的函数。

#### 2.1 泰勒展开

对于第一个问题，打开 $\sum L(f)$，xgboost的方法是利用[泰勒展开](https://zh.wikipedia.org/wiki/泰勒公式)成二阶多项式:

\begin{align}
    \mathcal{L} &\approx \sum_{i=1}^n \left [ L(y_i, \hat{y}_i) + g_i f(x_i) + \frac{1}{2} h_i f^2(x_i) \right ] + \Omega(f) \\
    g_i &= \frac{\partial \, L(y_i, \hat{y}_i)}{\partial \hat{y}_i} \\
    h_i &= \frac{\partial^2 \, L(y_i, \hat{y}_i)}{\partial \hat{y}^2_i} \\
\end{align}

为了便于理解，我将推导过程细致说下：

利用泰勒公式，我们在单点可将一个函数$f(x)$展开为高阶导数的叠加：
\begin{equation}
    \sum _{n=0}^{\infty }{\frac {f^{(n)}(a)}{n!}}(x-a)^{n}
\end{equation}

具体到二阶导数为
\begin{equation}
f(x) \approx f(a)+{\frac  {f'(a)}{1!}}(x-a)+{\frac  {f''(a)}{2!}}(x-a)^{2}
\end{equation}

我们做点变形以利于理解，令$t = \hat{y}_i + f(x_i)$，则
\begin{align}
    L(y_i, \hat{y}_i + f(x_i)) &= L(y_i, t)\\
                               &= L(t) \quad \text{给定$x_i$，则$y_i$是定值，即常数}
\end{align}

接着利用泰勒将$L(t)$在$\hat{y}_i$点展开：

\begin{align}
L(t) &\approx L(\hat{y}_i) + {\frac  {L'(\hat{y}_i)}{1!}}(t-\hat{y}_i)+{\frac  {f''(\hat{y}_i)}{2!}}(t-\hat{y}_i)^{2} \\
     &= L(\hat{y}_i) + L'(\hat{y}_i) f(x_i) + \frac{1}{2}f''(\hat{y}_i) f^{2}(x_i) \\
     &= L(y_i, \hat{y}_i) + L'(\hat{y}_i) f(x_i) + \frac{1}{2}f''(\hat{y}_i) f^{2}(x_i) \\
     &= L(y_i, \hat{y}_i) + g_i f(x_i) + \frac{1}{2} h_i f^2(x_i)
\end{align}

#### 2.2 引入树模型

泰勒解决了第一个问题，打开$L(f)$，得到：

\begin{equation}
    \mathcal{L} \approx \sum_{i=1}^n \left [ L(y_i, \hat{y}_i) + g_i f(x_i) + \frac{1}{2} h_i f^2(x_i) \right ] + \Omega(f)
\end{equation}

接着需要回答第二个问题，在这之前，我们先做点预处理。

对于损失函数$\mathcal{L}$，常数项$L(y_i, \hat{y}_i)$是可以直接舍掉的，记为：

\begin{equation}
    \mathcal{L} = \sum_{i=1}^n \left [ g_i f(x_i) + \frac{1}{2} h_i f^2(x_i) \right ] + \Omega(f)
\end{equation}

如何用这个外部的损失函数指导树模型呢？

在论文Friedman - Greedy function approximation: A gradient boosting machine里推导TreeBoost方法时给了个套路：

1. 将决策树的数学模型$f(x)$代入外部损失函数$\mathcal{L}$。
2. 固定$J$，得到最优的$b_j$解析式。
3. 反代$b_j$回$\mathcal{L}$，将它作为树生成的评价函数（内部损失函数）。

这个套路的思想是，对于树模型来说，主要有两个参数：叶子数、叶子值。通过固定叶子数，就可以利用外部损失函数$\mathcal{L}(f)$寻优到最佳的叶子值计算解析式。将参数反代，外部损失函数就变成只和$x$相关$\mathcal{L}(x)$，这时它就可以作为树生长的评价函数。这个思路挺巧妙的，可能有点绕。

##### 2.2.0 代入树模型

我们就将树模型$f(x)$的数学代入，

\begin{align}
    \mathcal{L} &= \sum_{i=1}^n \left [ g_i f(x_i) + \frac{1}{2} h_i f^2(x_i) \right ] + \Omega(f) \\
                &= \sum_{i=1}^n \left [ g_i \sum_{j=1}^J b_j \mathbf{1}(x_i \in R_j) + \frac{1}{2} h_i (\sum_{j=1}^J \color{red}{b_j} \mathbf{1}(x_i \in R_j))^{\color{red}{2}} \right ] + \Omega(f) \\
                &= \sum_{i=1}^n \left [ g_i \sum_{j=1}^J b_j \mathbf{1}(x_i \in R_j) + \frac{1}{2} h_i \sum_{j=1}^J \color{red}{b_j^2} \mathbf{1}(x_i \in R_j) \right ] + \Omega(f) \quad \text{因为$x_i$只属于一个$R_j$} \\
                &= \sum_{j=1}^J \color{blue}{\sum_{i=1}^n \mathbf{1}(x_i \in R_j)} g_i b_j + \frac{1}{2} \color{blue}{\sum_{j=1}^J \sum_{i=1}^n \mathbf{1}(x_i \in R_j)} h_i b_j^2 + \Omega(f) \quad \text{乘法交换} \\
                &\text{令} I_j = \{ i \, | \, x_i \in R_j \} \quad \text{即属于$R_j$的全部下标$i$} \\
                &= \sum_{j=1}^J \color{blue}{\sum_{i \in I_j}} g_i b_j + \frac{1}{2} \sum_{j=1}^J \color{blue}{\sum_{i \in I_j}} h_i b_j^2 + \Omega(f) \\
                &= \sum_{j=1}^J ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} \sum_{j=1}^J (\sum_{i \in I_j} h_i) b_j^2 + \Omega(f) \quad \text{乘法分配律}\\
                &= \sum_{j=1}^J ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} \sum_{j=1}^J (\sum_{i \in I_j} h_i) b_j^2 + \gamma \|R_j\| + \frac{1}{2} \lambda \|b_j\|^2 \quad \text{代入正则$\Omega(f)$}\\
                &= \sum_{j=1}^J ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} \sum_{j=1}^J (\sum_{i \in I_j} h_i) b_j^2 + \gamma \|R_j\| + \frac{1}{2} \lambda \sum_{j=1}^J b_j^2 \\
                &= \sum_{j=1}^J \left ( ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} (\sum_{i \in I_j} h_i) b_j^2 + \frac{1}{2} \lambda b_j^2 \right ) + \gamma \|R_j\|  \\
                &= \sum_{j=1}^J \left ( ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} (\sum_{i \in I_j} h_i + \lambda) b_j^2 \right ) + \gamma \|R_j\|  \\
\end{align}

##### 2.2.1 $b_j$最优解析式

\begin{align}
    b_j &= \operatorname{arg \, min}_{b_j} \mathcal{L} \\
        &= \operatorname{arg \, min}_{b_j} \sum_{j=1}^J \left ( ( \sum_{i \in I_j} g_i ) b_j + \frac{1}{2} (\sum_{i \in I_j} h_i + \lambda) b_j^2 \right ) + \gamma \|R_j\|  \\
        &\approx \sum_{j=1}^J \operatorname{arg \, min}_{b_j} \left ( ( \sum_{i \in I_j} g_i ) \color{red}{b_j} + \frac{1}{2} (\sum_{i \in I_j} h_i + \lambda) \color{red}{b_j^2} \right ) + \gamma \|R_j\|
\end{align}

全局最优不好求，我们转而求局部最优。注意到每个局部项是一个二项式，它的最小点可用公式直接套出：

\begin{align}
    b^*_j &= - \frac{\sum_{i \in I_j} g_i}{\sum_{i \in I_j} h_i + \lambda} \\
\end{align}

##### 2.2.2 树生长的评价函数

将$b_j$重代回$\mathcal{L}$得到评价函数：

\begin{align}
    \mathcal{L} &= - \frac{1}{2} \sum_{j=1}^J \frac{(\sum_{i \in I_j} g_i)^2}{\sum_{i \in I_j} h_i + \lambda} + \gamma \|R_j\| \\
                &= - \frac{1}{2} H + \gamma T
\end{align}

于是得到树生成的分割依据：

\begin{align}
    \mathcal{L}_{\text{split}} &= \mathcal{L} - \mathcal{L}_L - \mathcal{L}_R \\
                              &= \frac{1}{2} (H_L + H_R - H) + \gamma (T - T_L - T_R) \\
                              &= \frac{1}{2} (H_L + H_R - H) - \gamma \\
\end{align}

#### 2.3 小结

至此，xgboost对GBDT框架的主要改进就说明完了。我们梳理下，对于一个损失函数 $L$，用它解出老模型的输出 $\hat{y}_i$ 的一阶导 $g_i$ 和二阶导 $h_i$。有了这两阶导数，就可以做为评价函数直接指导决策树的生长，同时算出叶子的值，于是就得到了新树，再加回老模型得到新模型。

我们可以看到，原始的GBDT只是将Gradient Boost框架中的学习模型指定是决策树，这时还是一个通用框架。而TreeBoost和xbgoost，则更进一步，将决策树的数学模型代入Gradeint Boost，从而解出直接指导决策树生长的解析式。也就说，把外部的损失函数，引入到了决策树的建立过程中，这其实就是从通用到定制的过程。所以，可以说，TreeBoost和xgboost的本质，就是对树模型进行定制优化的Gradient Boost。

### 3 工程实现

#### 3.0 训练

正如前面小结所言，xgboost的训练主要是三步：

1. 老模型的预测值$\hat{y}_i$；
2. 计算出两阶导数$g_i$和$h_i$；
3. 将导数信息传入，指导决策树生长。

主体代码位于 `src/learner.cc`，如下：

```C++
288   void UpdateOneIter(int iter, DMatrix* train) override {
289     CHECK(ModelInitialized())
290         << "Always call InitModel or LoadModel before update";
291     if (tparam.seed_per_iteration || rabit::IsDistributed()) {
292       common::GlobalRandom().seed(tparam.seed * kRandSeedMagic + iter);
293     }
294     this->LazyInitDMatrix(train);
295     this->PredictRaw(train, &preds_);
296     obj_->GetGradient(preds_, train->info(), iter, &gpair_);
297     gbm_->DoBoost(train, this->FindBufferOffset(train), &gpair_);
298   }
```

理论比工程好讲，工程实现会有大量细节，相当繁琐。现在时间不多，没有心力面面俱到，不再准备细写了。

我画了简版的UML图，可能不准确，感兴趣的朋友可以参考它，自行从这个入口去追一遍。

```python
SVG("./res/Main.svg")
```

```python

```