# Introduction to PyCBC Inference 2: Analyzing a gravitational wave
### Collin Capano and Alex Nitz

In this tutorial we show how to set up a run for a gravitation wave, in this case, GW150914.

### Prerequisites

We will need the most recent version of pycbc installed for this tutorial.

```python
import sys
!{sys.executable} -m pip install pycbc lalsuite ligo-common --no-cache-dir

# This is needed to access the executables on sciserver. On a personal machine this should be ignore.
path = %env PATH
%env PATH=$path:/home/idies/miniconda3/envs/py37/bin
```

```python
import os
from IPython.display import Image
from IPython.core.display import HTML
```

## BBH example

To analyze a gravitational wave, we need to provide a prior, a model, and data settings in our configuration file. These settings can all be put into a single file, or split up into multiple files, all of which are provided via the `--config-file` option. In this example, we split the configuration up into 3 files:
  * [gw150914_like.ini](gw150914_like.ini): specifies the model we will use, and the parameters that will be varied and their priors. This is the configuration file you would use to analyze signals like GW150914.
  * [emcee_pt-gw150914_like.ini](emcee_pt-gw150914_like.ini): specifies sampler settings. In this case, we are using the `emcee_pt` sampler.
  * [data.ini](data.ini): specifies the settings for loading the gravitational-wave data.

In the following sections, we look at the various sections of thes configuration files in detail.

## The model

The model we will use is set by the `[model]` section. By setting the `name = gaussian_noise`, we tell `pycbc_inference` that we want to use the [GaussianNoise](https://pycbc.org/pycbc/latest/html/pycbc.inference.models.html#pycbc.inference.models.gaussian_noise.GaussianNoise) model. This means that we will be analyzing data $d$ from one or more detectors, which is sampled at some constant sample rate $1/\Delta t$ for a period of time $T$, yielding $N = T/\Delta t$ samples (more on how to load data below).

This model assumes that the data consists of stationary Gaussian noise plus a signal $h$. The signal is modeled by a waveform model, which depends on several parameters. Which model to use is determined by the `approximant` parameter, which is set in the `static_params` section (see below).

When this model is given a set of parameter values $\vec{\vartheta}$, it generates a frequency-domain waveform $\tilde{h}(\vec{\vartheta})$ using the waveform model. It then calculates the log likelihood:
\begin{equation}
\log p(d|\vec{\vartheta}, h) =  -\frac{1}{2} \sum_i \left< h_i(\vec{\vartheta}) - d_i,\, h_i(\vec{\vartheta}) - d_i \right>,
\end{equation}
where the sum is over the number of detectors. The inner product is given by:
\begin{equation}
\left<a_i, \, b_i\right> = 4 \Re \sum_{k=k_0}^{N/2} \frac{\tilde{a}_i^{*}(k \Delta f) \tilde{b}_i(k \Delta f)}{S^{(i)}_n(k\Delta f)} \Delta f.
\end{equation}
Here, $S_n^{(i)}$ is the power spectral density of the noise in the $i$th detector and $\Delta f = 1/T$ is the frequency resolution. This is the discrete form of the matched filter.

As we see, the model requires a lower frequency cutoff for the inner product $f_0 = k_0 \Delta f$. This is set with the `low-frequency-cutoff` option, which we have set to 20.

*Tip:* By setting the `low-frequency-cutoff` to a single value, we will use the same cutoff for all detectors. If you would like to use a different cutoff for each detector, set `low-frequency-cutoff = {DET1}:{F1} {DET2}:{F2} [...]`, where `{DETn}` is the name of the `n`-th detector (e.g., `H1`) and `{Fn}` is the frequency to use for detector `n`.

## The variable and static params

As with the Normal 2D example, we see that there is a `[variable_params]` section. This lists the names of all of the parameters we will be varying in the run. Now we see that there is also a `[static_params]` section. These are parameters that will be kept fixed throughout the run. In this example we have:
 * `approximant = IMRPhenomPv2`: this means that the waveform model we use will be IMRPhenomPv2
 * `f_lower = 20`: this sets the starting frequency for the waveform generation to 20Hz. *This is separate from the low frequency cutoff of the inner product, which is set in the `[model]` section. Generally, this number should be less-than-or-equal-to the `low-frequency-cutoff` in the `[model]` section.*
 * `f_ref = 20`: the "reference" frequency of the waveform.

The `approximant` argument determines what type of waveform we will be generating. Since it is set to `IMRPhenomPv2`, we will be generating a CBC waveform.

## Setting the prior

**Every parameter listed in the `[variable_params]` section must have a prior specified in the file.** This is done by adding sections named `[prior-{params}]` to the file, where `{param}` is the name of the parameter that the section sets a prior for; e.g., `[prior-mass1]`. A section may provide a distribution for multiple parameters. In that case, all of the parameters must be listed in the header as a `+` separated list. For example, `[prior-ra+dec]`. The order that the parameters are provided does not matter.

Each prior section must also have a `name` set. This specifies the name of the distribution to use for that parameter. Distributions are defined in PyCBC's [distributions package](https://pycbc.org/pycbc/latest/html/pycbc.distributions.html); several are available for use. For the complete list, see the table [here](https://pycbc.org/pycbc/latest/html/inference.html#configuring-the-prior).

The rest of the settings in the `[prior]` sections depend on the distribution being used. For example, the `uniform` distribution requires minimum and maximum bounds to be provided for each parameter:
```
[prior-mass1]
name = uniform
min-mass1 = 10.
max-mass1 = 80.
```
Some distributions require no options, since they are predefined in the code. For example, the `uniform_sky` distribution provides the appropriate distributions for right ascension and declination, which it expects to be called `ra` and `dec`, respectively. This is why that section is simply:
```
[prior-ra+dec]
name = uniform_sky
```

### Challenge:
 * The configuration file is missing a prior for the mass of the second object, `mass2`. Set a prior on `mass2` that is uniform in $[10,80)\,\mathrm{M}_\odot$. The solution can be found [here](http://pycbc.org/pycbc/latest/html/inference/examples/bbh.html#setup-the-configuration-files).

## The sampler

The sampler settings are in [emcee_pt-gw150914_like.ini](emcee_pt-gw150914_like.ini). Here we are using the `emcee_pt` sampler. This is a parallel tempered sampler, so it requires a number of temperatures to be set. Note a few other differences from the analytic example here:
  * The `burn-in-test` is set to `nacl & max_posterior`.
  * Instead of an `niterations` option, we have `effective-nsamples = 1000`.
  * A checkpoint interval is set: `checkpoint-interval = 2000`
  * There is a `max-samples-per-chain` option.

These are all options specific to MCMC samplers like `emcee_pt`. Details:

#### The burn in option
Multiple burn in tests may be combined using standard boolean operators like `&` and `|`. In this example, we will consider the sampler to be burned in when it has passed the `nacl` test *and* the `max_posterior` test. This means:

 * `nacl`: The second half of the chain must be longer than 5 times the ACL. If so, the samlper is considered burned-in at the halfway point.
 * `max_posterior`: All of the walkers must find a point that has a log posterior greater than `maxP - ndim/2`, where `maxP` is the maximum posterior value found over all the walkers and `ndim` is the number of variable parameters. The first iteration for which all the walkers pass this test is the burn in iteration.

By doing `&`, we take the larger iteration of these two tests. This combination of tests has worked well for `emcee_pt`.

#### Checkpointing
When a `checkpoint-interval` is set, `pycbc_inference` will dump the results to a checkpoint file after every `checkpoint-interval` iterations. The checkpoint file has the same name as the output, but with `.checkpoint` added on to it.

While ``pycbc_inference`` is running it will create a checkpoint file which
is named ``{output-file}.checkpoint``, where ``{output-file}`` was the name
of the file you specified with the ``--output-file`` command. If a `checkpoint-interval` is set, `pycbc_inference` will checkpoint after the given number of iterations. For `emcee_pt`, this means that it will dump the current samples to this file; when finished, the file is
renamed to ``{output-file}``.

A ``{output-file}.bkup`` is also created, which is a copy of the checkpoint file. This is kept in case the checkpoint file gets corrupted during writing. The ``.bkup`` file is deleted at the end of the run, unless ``--save-backup`` is turned on.

If `pycbc_inference` is terminated while running (either by error, or by a system interrupt), the checkpoint and bkup files remain. When `pycbc_inference` is restarted, it will check for those files. If they are found, it will resume from where it last left off.

#### Termination condition
By setting `effective-nsamples` we tell the `pycbc_inference` until it has an effective number of samples greater than or equal to the specified value. Effective samples are the number of independent samples of the posterior we have. This is given by number of samples that remain after burn-in and thinned by the autocorelation time.

The number of effective samples are counted at each checkpoint. For this reason, a checkpoint-interval must be provided if `effective-nsamples` is set.

#### Max samples per chain
If `max-samples-per-chain` is provided, `pycbc_inference` will ensure that no more than the given number of samples per chain are stored in the output file. Samples will be thinned on disk and in memory when a checkpoint happens to ensure this. This is important for keeping file size down. Without it, a GW run with `200` walkers and `20` temps can result in a file that is over 100GB, since every sample will be saved. With `max-samples-per-chain = 1000`, the maximum file size is capped to ~1GB.

### Samping and waveform transforms
You'll note a `waveform_transforms` and `sampling_transforms` sections. Those are described in more detail in the next tutorial.

## Data settings

The settings for loading the data are in [data.ini](data.ini). This contains a `[data]` section, which is read by the GaussianNoise model to figure out what data to load, and how to condition. Here is what each of the settings that we have does:
 * `instruments`: This tells the code what detectors to analyze. Here, we've set it to `H1` and `L1`.
 * `trigger-time`, `analysis-start-time` and `analysis-end-time`: The `analysis-(start|end)-time` options determine the time that will be analyzed. Notice that the start-time is `-8` and the end time is `2`. This is because these times are measured with respect to the `trigger-time` option. Here, we put an estimate of the GPS time when the binary black hole merger occurred (in a Geocentric reference frame). With these settings, our analyzed time will start 8 seconds before the merger time and end 2 seconds after.
 * `psd-estimation`: This determines how we will estimate the PSD. By setting it to `median-mean`, the PSD will be analyzed from the data using a Welch-like method. Basically, the data is chopped up into semi-overlapping segments, an FFT is taken in each block, then the median is taken over all odd-numbered segments. The same process is repeated for the even-numbered segments. The two sets are then averaged to give the PSD.
 * `psd-start-time` and `psd-end-time`: This defines the analysis block that is used for estimating the PSD. To get a good estimate, you generally want to use ~512s of data. Here, we use 512s centered on the trigger time.
 * `psd-segment-length` and `psd-segment-stride`: These determine the size of each segment when doing the median-mean method, and how much each segment overlaps.
 * `psd-inverse-length`: This truncates the inverse PSD in the time domain to be 4s long.
 * `frame-files`: Specifies the gravitational-wave data ("frame") files to use.
 * `channel-name`: The name of the channels in the frame files containing the gravitational-wave data to analyze.
 * `sample-rate`: The sample rate we will use for the analysis. You want this to be atleast twice the maximum frequency of any possible waveform that will be generated by your prior. For BBH, 2048Hz is generally ok.
 * `strain-high-pass`: Causes a high-pass filter to be applied to the data when it is first loaded, with the cutoff frequency (here) set to 15Hz. This is just to remove the large amplitude low-frequency noise, so as not to cause numerical overflow issues when calculating the likelihood. Generally, you want this to be a few Hz lower than the low-frequency-cutoff used in the model.
 * `pad-data`: Adds an extra few seconds on to the data when loading. This is to avoid corruption issues from the `strain-high-pass` filter. The padded data are removed after the high-pass filter is applied, and before any FFTs are done.

### Determining analysis time duration

Why did we use -8 and +2 for the analysis times? The discrete inner product treats the data as if it were cyclic. If we try to filter a model waveform that is longer (starting from the low-frequency-cutoff) than the analysis duration, it will wrap around to the beginning. For example, if we used an analysis time of 4s, but a waveform is 5s long, the last second of the waveform will wrap around to lay on top of the first second of the segment. To avoid this, we need to analyze a segment that is longer than the longest possible waveform admitted by our prior plus our uncertainty in the trigger time ($\pm 0.1\,$s). In this case, our longest waveform is $m_1 = m_2 = 10\,\mathrm{M}_\odot$. We can check the duration of this waveform using `get_waveform_filter_length_in_time`:

```python
from pycbc import waveform
```

```python
waveform.get_waveform_filter_length_in_time(approximant='IMRPhenomPv2', mass1=10., mass2=10.,
                                            spin1z=0.99, spin2z=0.99, f_lower=20.)
```

Since the `trigger-time` is near the merger time, using ~8s before and ~2s after sufficiently encompasses the longest waveform we might sample.

### Challenge:

What analysis-time settings would you use if your prior on mass1 and mass2 was uniform in $[5, 40)\,\mathrm{M}_\odot$, and you were starting from 20Hz? What if you start from 15Hz?

## Run it

Before we can run, we need to download frame files from [GWOSC](https://www.gw-openscience.org/about/). These contain the LIGO data that we will analyze.

```python
if not os.path.exists('H-H1_GWOSC_4KHZ_R1-1126257415-4096.gwf'):
    !wget https://www.gw-openscience.org/catalog/GWTC-1-confident/data/GW150914/H-H1_GWOSC_4KHZ_R1-1126257415-4096.gwf
if not os.path.exists('L-L1_GWOSC_4KHZ_R1-1126257415-4096.gwf'):
    !wget https://www.gw-openscience.org/catalog/GWTC-1-confident/data/GW150914/L-L1_GWOSC_4KHZ_R1-1126257415-4096.gwf
```

To run this example, we will just run the bash script. Running this example to completion will take several hours. Instead, we'll just run for a couple of checkpoints, kill it, then start it again to see how checkpointing works.

First, do the following:
 * Set the checkpoint interval in the config file to 4.

Now run the script. Watch the output. After it checkpoints (it will say "Running sampler for 4 to 8 iterations"), interrupt the kernel by hitting the stop button above.

```python
!bash run.sh
```

Now run `ls` to see the files in the diretory. You should see a `bbh_results.hdf.checkpoint` and `bbh_results.hdf.bkup`. These are your checkpoint and backup files:

```python
!ls
```

Run the script again. Watch the messages. You should see it say that it is starting from iteration 4. Stop it after it has gotten to another checkpoint.

```python
!bash run.sh
```

We can replace `effective-nsamples` by `niterations` in the sampler config file to get this to complete now. Remove or comment out the `effective-nsamples` option, and replace it with: `niterations = 12`. Now re-run. You should see `pycbc_inference` start up from the last checkpoint, but stop as soon as it gets to 12 iterations.

```python
!bash run.sh
```

Note that the checkpoint file has been renamed to `bbh_results.hdf`, and the backup file is deleted.

```python
!ls
```

Since we ran for such a short period of time, the samples in `bbh_results.hdf` will look nothing like the posterior. In the next tutorial, we will take a look at a completed result file which has been run for the full time.


# Transformadores lineales
__UNLZ - Facultad de Ingeniería__
__Electrotecnia__
__Alumno:__ Daniel Antonio Lorenzo

Un transformador es por lo general un dispositivo de cuatro terminales que comprende dos (o más) bobinas magnéticamente acopladas.

## Ejemplo 13.4
En el circuito de la figura, calcule la impedancia de entrada y la corriente $I_1$. Considere $Z_1 = 60 - j100 \, \Omega$, $Z_2 = 30 + j40 \, \Omega$ y $Z_L = 80 + j60 \, \Omega$.

### Solución

```python
import numpy as np
import cmath
```

```python
# Datos:
Z1 = 60 - 100j # Ohm
Z2 = 30 + 40j # Ohm
ZL = 80 + 60j # Ohm
XL1 = 20j # Ohm
XL2 = 40j # Ohm
M = 5j # Ohm
Vs = cmath.rect(50 , np.deg2rad(60) ) # V
w = 1 # rad/s
```

A partir de la ecuación
$$ Z_{ent} = Z_1 + X_{L1} + \frac{\omega^2 M^2}{Z_2 + X_{L2} + Z_L} $$

```python
Zent = Z1 + XL1 + (w**2 * M**2)/(Z2 + XL2 + ZL)
```

```python
print('Zent = (%.0f < %.2f°) Ohm'%(abs(Zent) , np.rad2deg( cmath.phase(Zent) ) ))
```

    Zent = (100 < -53.13°) Ohm

Así
$$ I_1 = \frac{V}{Z_{ent}} $$

```python
I1 = Vs/Zent
```

```python
print('I1 = (%.2f < %.2f°) A'%(abs(I1) , np.rad2deg( cmath.phase(I1) )))
```

    I1 = (0.50 < 113.13°) A

__Simulación en qucs:__

```python
%reset -s -f
```

## Problema de práctica 13.4
Halle la impedancia de entrada del circuito de la figura y la corriente procedente de la fuente de tensión.

### Solución

```python
import numpy as np
import cmath
```

```python
# Datos:
Z1 = 4 # Ohm
XL1 = 8j # Ohm
XL2 = 10j # Ohm
M = 3j # Ohm
Z2 = -6j # Ohm
ZL = 6 + 4j # Ohm
Vs = 20 # V
w = 1 # rad/s
```

A partir de la ecuación
$$ Z_{ent} = Z_1 + X_{L1} - \frac{\omega^2 M^2}{Z_2 + X_{L2} + Z_L} $$

```python
Zent = Z1 + XL1 - (w**2 * M**2)/(Z2 + XL2 + ZL)
```

```python
print('Zent = (%.2f < %.2f°) Ohm'%(abs(Zent) , np.rad2deg( cmath.phase(Zent) ) ))
```

    Zent = (8.58 < 58.05°) Ohm

Así
$$ I_1 = \frac{V}{Z_{ent}} $$

```python
I1 = Vs/Zent
```

```python
print('I1 = (%.2f < %.2f°) A'%(abs(I1) , np.rad2deg( cmath.phase(I1) )))
```

    I1 = (2.33 < -58.05°) A

__Simulación en qucs:__

```python
%reset -s -f
```

## Ejemplo 13.5
Determine el circuito T equivalente del transformador lineal de la figura.

(a) transformador lineal
(b) circuito T equivalente

### Solución
Dado que $L_1 = 10$, $L_2 = 4$ y $M = 2$, la red equivalente tiene los siguientes parámetros:

$$ L_a = L_1 - M = 10 -2 = 8 \, \mathrm{H} $$

$$ L_b = L_2 - M = 4 - 2 = 2 \, \mathrm{H} $$

$$ L_c = M = 2 \, \mathrm{H} $$

Se ha supuesto que las direcciones de referencia de las corrientes y las polaridades de las tensiones en los devanados de referencia de las corrientes y las polaridades de las tensiones en los devanados primario y secundario se ajustan a las de la figura. De lo contrario, podría ser necesario reemplazar $M$ por $-M$.

## Problema de práctica 13.5
En relación con el transformador lineal de la figura, halle la red $\Pi$ equivalente.

### Solución

$$ L_A = \frac{L_1 L_2 - M^2}{L_2 - M} \quad ; \quad L_B = \frac{L_1 L_2 - M^2}{L_1 - M} \quad ; \quad L_C = \frac{L_1 L_2 - M^2}{M} $$

```python
# Datos:
L1 = 10 # H
L2 = 4 # H
M = 2 # H
```

```python
LA = (L1*L2 - M**2)/(L2 - M)
LB = (L1*L2 - M**2)/(L1 - M)
LC = (L1*L2 - M**2)/(M)
```

```python
print('LA = %.1f H'%LA)
print('LB = %.1f H'%LB)
print('LC = %.1f H'%LC)
```

    LA = 18.0 H
    LB = 4.5 H
    LC = 18.0 H

## Ejemplo 13.6
Determine $I_1$, $I_2$ y $V_0$ en la figura usando el circuito T equivalente del transformador lineal.

### Solución
Las bobinas acopladas magnéticamente deben reemplazarse por el circuito T equivalente.

$$\begin{array}{l}
L_a = L_1 - (-M) \\
L_b = L_2 - (-M) \\
L_c = -M
\end{array}$$

```python
import cmath
import numpy as np
```

```python
# Datos:
L1 = 8j # Ohm
L2 = 5j # Ohm
M = 1j # Ohm
R1 = 4 # Ohm
R2 = 10 # Ohm
Vs = cmath.rect(60 , np.deg2rad(90) )
```

```python
La = L1 - (-M)
Lb = L2 - (-M)
Lc = -M
```

```python
print('La = {:.1f} H'.format(La))
print('Lb = {:.1f} H'.format(Lb))
print('Lc = {:.1f} H'.format(Lc))
```

    La = 0.0+9.0j H
    Lb = 0.0+6.0j H
    Lc = -0.0-1.0j H

Así, el circuito T equivalente de la figura (b) en reemplazo de las dos bobinas de la figura (a)

El circuito equivalente de la figura (b) puede resolverse aplicando el análisis nodal o el de mallas. De la aplicación del análisis de mallas se obtiene

Malla 1:
$$ j6 = I_1 (4 + j9 - j1) + I_2 (-j1) $$

$$ (4 + 8j) I_1 - (j1)I_2 = j6  \tag{1} $$

Malla 2:
$$ 0 = I_1 (-j1) + I_2 (10 + j6 - j1) $$

$$ (-j1) I_1 + (10 + j5)I_2 = 0 \tag{2} $$

```python
A = np.array([[4+8j , -1j],[-1j , 10+5j]  ])
B = np.array([[6j],[0]])
```

```python
I = np.dot( np.linalg.inv(A) , B )
```

```python
print('I1 = (%.3f < %.2f°) A'%(abs(I[0]) , np.rad2deg( cmath.phase(I[0]) ) ))
print('I2 = (%.3f < %.2f°) A'%(abs(I[1]) , np.rad2deg( cmath.phase(I[1]) ) ))
```

    I1 = (0.671 < 27.14°) A
    I2 = (0.060 < 90.57°) A

$$ V_0 = -I_2 R_2 $$

```python
I1 = I[0]
I2 = I[1]

Vo = -I2*R2
```

```python
print('Vo = (%.2f < %.2f°) V'%(abs(Vo) , np.rad2deg( cmath.phase(Vo) )))
```

    Vo = (0.60 < -89.43°) V

```python
%reset -s -f
```

## Problema de práctica 13.6
Resuelva el problema del ejemplo 13.1 usando el modelo T equivalente de las bobinas acopladas magnéticamente.

### Solución

$$\begin{align}
L_a &= L_1 - M \\
L_b &= L_2 - M \\
L_c &= M
\end{align}$$

```python
# Datos:
L1 = 5j # Ohm
L2 = 6j # Ohm
M = 3j # Ohm
C1 = -4j # Ohm
R1 = 12 # Ohm
Vs = 12 # V
```

```python
La = L1 - M
Lb = L2 - M
Lc = M
```

```python
print('La = {:.2f} Ohm'.format(La))
print('Lb = {:.2f} Ohm'.format(Lb))
print('Lc = {:.2f} Ohm'.format(Lc))
```

    La = 0.00+2.00j Ohm
    Lb = 0.00+3.00j Ohm
    Lc = 0.00+3.00j Ohm

```python
import numpy as np
import cmath
```

```python
A = np.array([[1j,-3j],[-3j,12+6j]])
B = np.array([[12],[0]])
```

```python
I = np.dot( np.linalg.inv(A) , B )
```

```python
print('I1 = (%.2f < %.2f°) A'%(abs(I[0]) , np.rad2deg( cmath.phase(I[0]) ) ))
print('I2 = (%.2f < %.2f°) A'%(abs(I[1]) , np.rad2deg( cmath.phase(I[1]) ) ))
```

    I1 = (13.02 < -49.40°) A
    I2 = (2.91 < 14.04°) A

__Simulación en qucs:__


Finally, we write the code file itself.  Most of the text below will appear literally in the file.  Statements in single curly braces will be substituted by the `format` statement at the end of the string; double curly braces will just appear as literal braces in the output.

```python
# Always run this first
# NOTE: Do not define new basic variables in this notebook;
#       define them in Variables_Q.ipynb.  Use this notebook
#       to define new expressions built from those variables.

from __future__ import division # This needs to be here, even though it's in Variables.py
import sys
sys.path.insert(0, '..') # Look for modules in directory above this one
execfile('../Utilities/ExecNotebook.ipy')
UseQuaternions = False
from sympy import N
from sympy import Rational as frac # Rename for similarity to latex
```

```python
with open('PNApproximants.ipp', 'w') as f :
    f.write("""// File produced automatically by OrbitalEvolutionCodeGen.ipynb""")

    for PNOrbitalEvolutionOrder in [frac(n,2) for n in range(0,13)]:
        print("Working on {0} PN...".format(PNOrbitalEvolutionOrder))
        PNOrbitalEvolutionOrderString = str(N(PNOrbitalEvolutionOrder,2)).replace('.','p')
        %cd -q ../PNTerms
        execnotebook('OrbitalEvolution.ipynb')
        ExpressionsForMemberFunctions = CodeOutput.CodeConstructor(PNVariables, PrecessionVelocities)
        execnotebook('AngularMomentum.ipynb')
        %cd -q -
        PrecessionVelocities.AddDerivedVariable('OrbitalAngularMomentum',
            AngularMomentumExpression(PNOrder=PNOrbitalEvolutionOrder),
            datatype=ellHat.datatype)
        CodeConstructor.AddDependencies(PrecessionVelocities)
        # Start the class, write the declarations, initializations, etc.
        f.write("""

class TaylorTn_{PNOrbitalEvolutionOrderString}PN : public TaylorTn {{
private:
{Declarations}
  double Phi, gamma;

public:
  TaylorTn_{PNOrbitalEvolutionOrderString}PN({InputArguments}) :
{Initializations}, Phi(0.0), gamma(0.0)
  {{
    ellHat[0] = ellHat_x;
    ellHat[1] = ellHat_y;
    ellHat[2] = ellHat_z;
    nHat[0] = nHat_x;
    nHat[1] = nHat_y;
    nHat[2] = nHat_z;
  }}

  void Recalculate(double t, const double* y) {{
    v = y[0];
    chi1_x = y[1];
    chi1_y = y[2];
    chi1_z = y[3];
    chi2_x = y[4];
    chi2_y = y[5];
    chi2_z = y[6];
    ellHat_x = y[7];
    ellHat_y = y[8];
    ellHat_z = y[9];
    Phi = y[10];
    gamma = y[11];

    const Quaternion Rax =
        sqrtOfRotor(-normalized(Quaternion(0., ellHat_x, ellHat_y, ellHat_z))*zHat);
    const Quaternion R = Rax * exp(((gamma+Phi)/2.)*zHat);
    const Quaternion nHatQ = R*xHat*R.conjugate();
    nHat_x = nHatQ[1];
    nHat_y = nHatQ[2];
    nHat_z = nHatQ[3];

{Evaluations}
  }}

{MemberFunctions}
""".format(PNOrbitalEvolutionOrderString=PNOrbitalEvolutionOrderString,
           InputArguments=CodeConstructor.CppInputArguments(17),
           Declarations=CodeConstructor.CppDeclarations(2),
           Initializations=CodeConstructor.CppInitializations(4),
           Evaluations=CodeConstructor.CppEvaluations(4),
           MemberFunctions=ExpressionsForMemberFunctions.CppExpressionsAsFunctions(2)))

        # Write the external interfaces to the ODE stepper
        for n,Expressions in zip([1,4,5], [T1Expressions,T4Expressions,T5Expressions]) :
            f.write("""
  int TaylorT{n}(double t, const double* y, double* dydt) {{
    Recalculate(t, y);
    if(v>=1.0) {{ return GSL_EDOM; }} // Beyond domain of PN validity
{Computations}
    if(dvdt_T{n}<1.0e-12) {{ return GSL_EDIVERGE; }} // v is decreasing
    return CommonRHS(dvdt_T{n}, y, dydt);
  }}
""".format(n=n,
           Computations=CodeOutput.CodeConstructor(PNVariables, Expressions).CppEvaluateExpressions() ))

        # Finish up, writing the common RHS function and closing the class
        f.write("""
  int CommonRHS(const double dvdt, const double* y, double* dydt) {{
    const std::vector<double> Omega1 = OmegaVec_chiVec_1();
    const std::vector<double> Omega2 = OmegaVec_chiVec_2();
    const std::vector<double> Omega  = OmegaVec_ellHat();
    dydt[0] = dvdt;
    cross(&Omega1[0], &y[1], &dydt[1]);
    cross(&Omega2[0], &y[4], &dydt[4]);
    cross(&Omega[0],  &y[7], &dydt[7]);
    dydt[10] = v*v*v/m;
    const Quaternion adot(0., dydt[7], dydt[8], dydt[9]);
    const Quaternion Rax =
        sqrtOfRotor(-Quaternion(0., ellHat_x, ellHat_y, ellHat_z).normalized()*zHat);
    const Quaternion Raxdot = ( (-1.0/std::sqrt(2+2*y[9]))*adot*zHat - (dydt[9]/(2+2*y[9]))*Rax );
    dydt[11] = -2*(Rax.conjugate() * Raxdot)[3];

    return GSL_SUCCESS; // GSL expects this if everything went well
  }}
}}; // class TaylorTn_{PNOrbitalEvolutionOrderString}PN : public TaylorTn
""".format(PNOrbitalEvolutionOrderString=PNOrbitalEvolutionOrderString))
print("All done")
```

    Working on 0 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 1/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 1 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 3/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 5/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 3 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 7/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 4 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 9/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 5 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 11/2 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    Working on 6 PN...
    WARNING: Absorption term in EnergyAbsorption.ipynb temporarily disabled.
    All done


## 1-2. 量子ビットに対する基本演算

量子ビットについて理解が深まったところで、次に量子ビットに対する演算がどのように表されるかについて見ていこう。
これには、量子力学の性質が深く関わっている。

1. 線型性：
詳しくは第4章で学ぶのだが、量子力学では状態（量子ビット）の時間変化はつねに（状態の重ね合わせに対して）線型になっている。つまり、**量子コンピュータ上で許された操作は状態ベクトルに対する線型変換**ということになる
。１つの量子ビットの量子状態は規格化された２次元複素ベクトルとして表現されるのだったから、
１つの量子ビットに対する操作＝線型演算は$2 \times 2$の**複素行列**によって表現される。

2. ユニタリ性：
さらに、確率の合計は常に1であるという規格化条件から、量子操作に表す線型演算（量子演算）に対してさらなる制限を導くことができる。まず、各測定結果を得る確率は複素確率振幅の絶対値の2乗で与えられるので、その合計は状態ベクトルの（自分自身との）内積と一致することに注目する:

$$
|\alpha|^2 + |\beta|^2 =
(\alpha^*, \beta^*)
\left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right) = 1.
$$

（アスタリスク $^*$ は複素共役を表す）
 量子コンピュータで操作した後の状態は、量子演算に対応する線型変換(行列)を$U$とすると、

$$
U
\left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right)
$$

と書ける。この状態についても上記の規格化条件が成り立つ必要があるので、

$$
(\alpha^*, \beta^*)
U^\dagger U
\left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right) = 1
$$

が要請される。（ダガー $^\dagger$ は行列の転置と複素共役を両方適用したものを表し、エルミート共役という）

 この関係式が任意の$\alpha$, $\beta$について成り立つ必要があるので、量子演算$U$は以下の条件を満たす**ユニタリー行列**に対応する:
$$
U^{\dagger} U = U U^{\dagger} = I.
$$

すなわち、**量子ビットに対する操作は、ユニタリー行列で表される**のである。

ここで、用語を整理しておく。量子力学では、状態ベクトルに対する線型変換のことを**演算子** (operator) と呼ぶ。単に演算子という場合は、ユニタリーとは限らない任意の線型変換を指す。それに対して、上記のユニタリー性を満たす線型変換のことを**量子演算** (quantum gate) と呼ぶ。量子演算は、量子状態に対する演算子のうち、（少なくとも理論的には）**物理的に実現可能なもの**と考えることができる。

### １量子ビット演算の例：パウリ演算子
１つの量子ビットに作用する基本的な量子演算として**パウリ演算子**を導入する。
これは量子コンピュータを学んでいく上で最も重要な演算子であるので、定義を体に染み込ませておこう。

$$
\begin{eqnarray}
I&=&
\left(\begin{array}{cc}
1 & 0
\\
0 & 1
\end{array}
\right),\;\;\;
X=
\left(\begin{array}{cc}
0 & 1
\\
1 & 0
\end{array}
\right),\;\;\;
Y &=&
\left(\begin{array}{cc}
0 & -i
\\
i & 0
\end{array}
\right),\;\;\;
Z=
\left(\begin{array}{cc}
1 & 0
\\
0 & -1
\end{array}
\right).
\end{eqnarray}
$$

各演算子のイメージを説明する。

まず、$I$は恒等演算子で、要するに「何もしない」ことを表す。

$X$は古典ビットの反転（NOT）に対応し

$$X|0\rangle = |1\rangle, \;\;
X|1\rangle = |0\rangle
$$

のように作用する。（※ブラケット表記を用いた。下記コラムも参照。）

$Z$演算子は$|0\rangle$と$|1\rangle$の位相を反転させる操作で、

$$
Z|0\rangle = |0\rangle, \;\;
Z|1\rangle = -|1\rangle
$$

と作用する。
これは$|0\rangle$と$|1\rangle$の重ね合わせの「位相」という情報を保持できる量子コンピュータ特有の演算である。
例えば、

$$
Z \frac{1}{\sqrt{2}} ( |0\rangle + |1\rangle ) = \frac{1}{\sqrt{2}} ( |0\rangle - |1\rangle )
$$

となる。

$Y$演算子は$Y=iXZ$と書け、
位相の反転とビットの反転を組み合わせたもの（全体にかかる複素数$i$を除いて）であると考えることができる。

(詳細は Nielsen-Chuang の `1.3.1 Single qubit gates` を参照)

### SymPyを用いた一量子ビット演算
SymPyではよく使う基本演算はあらかじめ定義されている。

```python
from IPython.display import Image, display_png
from sympy import *
from sympy.physics.quantum import *
from sympy.physics.quantum.qubit import Qubit,QubitBra
init_printing() # ベクトルや行列を綺麗に表示するため
```

```python
# Google Colaboratory上でのみ実行してください
from IPython.display import HTML
def setup_mathjax():
    display(HTML('''

    '''))
get_ipython().events.register('pre_run_cell', setup_mathjax)
```

```python
from sympy.physics.quantum.gate import X,Y,Z,H,S,T,CNOT,SWAP, CPHASE
```

演算子は何番目の量子ビットに作用するか、
というのを指定して `X(0)` のように定義する。
また、これを行列表示するときには、いくつの量子ビットの空間で表現するか
`nqubits`というのを指定する必要がある。
まだ、量子ビットは１つしかいないので、
`X(0)`、`nqubits=1`としておこう。

```python
X(0)
```

```python
represent(X(0),nqubits=1)  # パウリX
```

同様に、`Y`, `Z`なども利用することができる。それに加え、アダマール演算 `H` や、位相演算 `S`、そして$\pi/4$の位相演算 `T` も利用することができる（これらもよく出てくる演算で、定義は各行列を見てほしい）：

```python
represent(H(0),nqubits=1)
```

```python
represent(S(0),nqubits=1)
```

```python
represent(T(0),nqubits=1)
```

これらの演算を状態に作用させるのは、

```python
ket0 = Qubit('0')
S(0)*Y(0)*X(0)*H(0)*ket0
```

のように `*`で書くことができる。実際に計算をする場合は `qapply()`を利用する。

```python
qapply(S(0)*Y(0)*X(0)*H(0)*ket0)
```

この列ベクトル表示が必要な場合は、

```python
represent(qapply(S(0)*Y(0)*X(0)*H(0)*ket0))
```

のような感じで、SymPyは簡単な行列の計算はすべて自動的にやってくれる。

---

### コラム：ブラケット記法
ここで一旦、量子力学でよく用いられるブラケット記法というものについて整理しておく。ブラケット記法に慣れると非常に簡単に見通しよく計算を行うことができる。

列ベクトルは

$$
|\psi \rangle = \left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right)
$$

とかくのであった。これを**ケット**と呼ぶ。同様に、行ベクトルは

$$
\langle \psi | = ( |\psi \rangle ) ^{\dagger} = ( \alpha ^* , \beta ^*)
$$

とかき、これを**ブラ**と呼ぶ。${\dagger}$マークは転置と複素共役を取る操作で、列ベクトルを行ベクトルへと移す。

２つのベクトル、

$$
|\psi \rangle = \left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right), \;\;\;
|\phi \rangle = \left(
\begin{array}{c}
\gamma
\\
\delta
\end{array}
\right)
$$

があったとする。ブラとケットを抱き合わせると

$$
\langle \phi | \psi \rangle = (\gamma ^* , \delta ^* ) \left(
\begin{array}{c}
\alpha
\\
\beta
\end{array}
\right) = \gamma ^* \alpha + \delta ^* \beta
$$

となり、**内積**に対応する。行ベクトルと列ベクトルをそれぞれブラ・ケットと呼ぶのは、このように並べて内積を取ると「ブラケット」になるからである。

逆に、背中合わせにすると

$$
|\phi \rangle \langle \psi | = \left(
\begin{array}{c}
\gamma
\\
\delta
\end{array}
\right) (\alpha ^* , \beta ^*) = \left(
\begin{array}{cc}
\gamma \alpha ^*  & \gamma \beta ^*
\\
\delta \alpha ^*   & \delta \beta ^*
\end{array}
\right)
$$

となり、演算子となる。例えば、$X$演算子は

$$
X= \left(
\begin{array}{cc}
0 & 1
\\
1 & 0
\end{array}
\right)
=
|0\rangle \langle 1 | + |1\rangle \langle 0|
$$

のように書ける。このことを覚えておけば

$$
\langle 0| 0\rangle = \langle 1 | 1\rangle = 1, \;\;\; \langle 0 | 1 \rangle = \langle 1 | 0 \rangle = 0
$$

から

$$
X |0\rangle = |1\rangle
$$

を行列を書かずに計算できるようになる。
**量子情報の解析計算においては、実際にベクトルの要素を書き下して計算をすることはほとんどなく、このようにブラケットを使って形式的に書いて計算してしまう場合が多い**（古典計算機上で量子コンピュータをシミュレーションする場合はベクトルをすべて書き下すことになる）。

同様に、

$$
I = |0\rangle \langle 0 | + |1\rangle \langle 1| , \;\;\; Z = |0\rangle \langle 0| - |1\rangle \langle 1|
$$

も覚えておくと便利である。


# Data Analysis and Machine Learning: Logistic Regression

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

Date: **Sep 19, 2020**

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

## Plans for week 38

* Thursday: Summary of regression methods and discussion of project 1. We revisit also cross-validation and bootstrap as resampling techniques with examples. Recommended reading: [Hastie et al](https://www.springer.com/gp/book/9780387848570) chapters 3 and 7.1-7.6 and 7.10-7.12.

* Friday: Logistic Regression. Recommended reading: [Hastie et al](https://www.springer.com/gp/book/9780387848570) chapters 4.1-4.4 and [Murphy](https://mitpress.mit.edu/books/machine-learning-1) chapter 8.1-8.2

## Thursday September 17

[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK4155/h20/forelesningsvideoer/LectureSeptember17.mp4?vrtx=view-as-webpage) and [link to handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember17.pdf).

## Ridge and LASSO Regression, reminder

The expression for the standard Mean Squared Error (MSE) which we used to define our cost function and the equations for the ordinary least squares (OLS) method, that is
our optimization problem is

$$
{\displaystyle \min_{\boldsymbol{\beta}\in {\mathbb{R}}^{p}}}\frac{1}{n}\left\{\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)^T\left(\boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\right)\right\}.
$$

or we can state it as

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\sum_{i=0}^{n-1}\left(y_i-\tilde{y}_i\right)^2=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2,
$$

where we have used the definition of  a norm-2 vector, that is

$$
\vert\vert \boldsymbol{x}\vert\vert_2 = \sqrt{\sum_i x_i^2}.
$$

By minimizing the above equation with respect to the parameters
$\boldsymbol{\beta}$ we could then obtain an analytical expression for the
parameters $\boldsymbol{\beta}$.  We can add a regularization parameter $\lambda$ by
defining a new cost function to be optimized, that is

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_2^2
$$

which leads to the Ridge regression minimization problem where we
require that $\vert\vert \boldsymbol{\beta}\vert\vert_2^2\le t$, where $t$ is
a finite number larger than zero. By defining

$$
C(\boldsymbol{X},\boldsymbol{\beta})=\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1,
$$

we have a new optimization equation

$$
{\displaystyle \min_{\boldsymbol{\beta}\in
{\mathbb{R}}^{p}}}\frac{1}{n}\vert\vert \boldsymbol{y}-\boldsymbol{X}\boldsymbol{\beta}\vert\vert_2^2+\lambda\vert\vert \boldsymbol{\beta}\vert\vert_1
$$

which leads to Lasso regression. Lasso stands for least absolute shrinkage and selection operator.

Here we have defined the norm-1 as

$$
\vert\vert \boldsymbol{x}\vert\vert_1 = \sum_i \vert x_i\vert.
$$

## Various steps in cross-validation

When the repetitive splitting of the data set is done randomly,
samples may accidently end up in a fast majority of the splits in
either training or test set. Such samples may have an unbalanced
influence on either model building or prediction evaluation. To avoid
this $k$-fold cross-validation structures the data splitting. The
samples are divided into $k$ more or less equally sized exhaustive and
mutually exclusive subsets. In turn (at each split) one of these
subsets plays the role of the test set while the union of the
remaining subsets constitutes the training set. Such a splitting
warrants a balanced representation of each sample in both training and
test set over the splits. Still the division into the $k$ subsets
involves a degree of randomness. This may be fully excluded when
choosing $k=n$. This particular case is referred to as leave-one-out
cross-validation (LOOCV).

## How to set up the cross-validation for Ridge and/or Lasso

* Define a range of interest for the penalty parameter.

* Divide the data set into training and test set comprising samples $\{1, \ldots, n\} \setminus i$ and $\{ i \}$, respectively.

* Fit the linear regression model by means of ridge estimation  for each $\lambda$ in the grid using the training set, and the corresponding estimate of the error variance $\boldsymbol{\sigma}_{-i}^2(\lambda)$, as

$$
\begin{align*}
\boldsymbol{\beta}_{-i}(\lambda) & =  ( \boldsymbol{X}_{-i, \ast}^{T}
\boldsymbol{X}_{-i, \ast} + \lambda \boldsymbol{I}_{pp})^{-1}
\boldsymbol{X}_{-i, \ast}^{T} \boldsymbol{y}_{-i}
\end{align*}
$$

* Evaluate the prediction performance of these models on the test set by $\log\{L[y_i, \boldsymbol{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}$. Or, by the prediction error $|y_i - \boldsymbol{X}_{i, \ast} \boldsymbol{\beta}_{-i}(\lambda)|$, the relative error, the error squared or the R2 score function.

* Repeat the first three steps  such that each sample plays the role of the test set once.

* Average the prediction performances of the test sets at each grid point of the penalty bias/parameter. It is an estimate of the prediction performance of the model corresponding to this value of the penalty parameter on novel data. It is defined as

$$
\begin{align*}
\frac{1}{n} \sum_{i = 1}^n \log\{L[y_i, \mathbf{X}_{i, \ast}; \boldsymbol{\beta}_{-i}(\lambda), \boldsymbol{\sigma}_{-i}^2(\lambda)]\}.
\end{align*}
$$

## Cross-validation in brief

For the various values of $k$

1. shuffle the dataset randomly.

2. Split the dataset into $k$ groups.

3. For each unique group:

a. Decide which group to use as set for test data

b. Take the remaining groups as a training data set

c. Fit a model on the training set and evaluate it on the test set

d. Retain the evaluation score and discard the model

5. Summarize the model using the sample of model evaluation scores

## Code Example for Cross-validation and $k$-fold Cross-validation

The code here uses Ridge regression with cross-validation (CV)  resampling and $k$-fold CV in order to fit a specific polynomial.

```python
%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import PolynomialFeatures

# A seed just to ensure that the random numbers are the same for every run.
# Useful for eventual debugging.
np.random.seed(3155)

# Generate the data.
nsamples = 100
x = np.random.randn(nsamples)
y = 3*x**2 + np.random.randn(nsamples)

## Cross-validation on Ridge regression using KFold only

# Decide degree on polynomial to fit
poly = PolynomialFeatures(degree = 6)

# Decide which values of lambda to use
nlambdas = 500
lambdas = np.logspace(-3, 5, nlambdas)

# Initialize a KFold instance
k = 5
kfold = KFold(n_splits = k)

# Perform the cross-validation to estimate MSE
scores_KFold = np.zeros((nlambdas, k))

i = 0
for lmb in lambdas:
    ridge = Ridge(alpha = lmb)
    j = 0
    for train_inds, test_inds in kfold.split(x):
        xtrain = x[train_inds]
        ytrain = y[train_inds]

        xtest = x[test_inds]
        ytest = y[test_inds]

        Xtrain = poly.fit_transform(xtrain[:, np.newaxis])
        ridge.fit(Xtrain, ytrain[:, np.newaxis])

        Xtest = poly.fit_transform(xtest[:, np.newaxis])
        ypred = ridge.predict(Xtest)

        scores_KFold[i,j] = np.sum((ypred - ytest[:, np.newaxis])**2)/np.size(ypred)

        j += 1
    i += 1

estimated_mse_KFold = np.mean(scores_KFold, axis = 1)

## Cross-validation using cross_val_score from sklearn along with KFold

# kfold is an instance initialized above as:
# kfold = KFold(n_splits = k)

estimated_mse_sklearn = np.zeros(nlambdas)
i = 0
for lmb in lambdas:
    ridge = Ridge(alpha = lmb)

    X = poly.fit_transform(x[:, np.newaxis])
    estimated_mse_folds = cross_val_score(ridge, X, y[:, np.newaxis], scoring='neg_mean_squared_error', cv=kfold)

    # cross_val_score return an array containing the estimated negative mse for every fold.
    # we have to the the mean of every array in order to get an estimate of the mse of the model
    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)

    i += 1

## Plot and compare the slightly different ways to perform cross-validation

plt.figure()

plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
plt.plot(np.log10(lambdas), estimated_mse_KFold, 'r--', label = 'KFold')

plt.xlabel('log10(lambda)')
plt.ylabel('mse')

plt.legend()

plt.show()
```

## Bias-Variance tradeoff with Bootstrap

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.utils import resample

np.random.seed(2018)

n = 40
n_boostraps = 100
maxdegree = 14

# Make data set.
x = np.linspace(-3, 3, n).reshape(-1, 1)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
error = np.zeros(maxdegree)
bias = np.zeros(maxdegree)
variance = np.zeros(maxdegree)
polydegree = np.zeros(maxdegree)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

for degree in range(maxdegree):
    model = make_pipeline(PolynomialFeatures(degree=degree), LinearRegression(fit_intercept=False))
    y_pred = np.empty((y_test.shape[0], n_boostraps))
    for i in range(n_boostraps):
        x_, y_ = resample(x_train, y_train)
        y_pred[:, i] = model.fit(x_, y_).predict(x_test).ravel()

    polydegree[degree] = degree
    error[degree] = np.mean( np.mean((y_test - y_pred)**2, axis=1, keepdims=True) )
    bias[degree] = np.mean( (y_test - np.mean(y_pred, axis=1, keepdims=True))**2 )
    variance[degree] = np.mean( np.var(y_pred, axis=1, keepdims=True) )
    print('Polynomial degree:', degree)
    print('Error:', error[degree])
    print('Bias^2:', bias[degree])
    print('Var:', variance[degree])
    print('{} >= {} + {} = {}'.format(error[degree], bias[degree], variance[degree], bias[degree]+variance[degree]))

plt.plot(polydegree, error, label='Error')
plt.plot(polydegree, bias, label='bias')
plt.plot(polydegree, variance, label='Variance')
plt.legend()
plt.show()
```

## Another Example from Scikit-Learn's Repository

```python
"""
============================
Underfitting vs. Overfitting
============================

This example demonstrates the problems of underfitting and overfitting and
how we can use linear regression with polynomial features to approximate
nonlinear functions. The plot shows the function that we want to approximate,
which is a part of the cosine function. In addition, the samples from the
real function and the approximations of different models are displayed. The
models have polynomial features of different degrees. We can see that a
linear function (polynomial with degree 1) is not sufficient to fit the
training samples. This is called **underfitting**. A polynomial of degree 4
approximates the true function almost perfectly. However, for higher degrees
the model will **overfit** the training data, i.e. it learns the noise of the
training data.
We evaluate quantitatively **overfitting** / **underfitting** by using
cross-validation. We calculate the mean squared error (MSE) on the validation
set, the higher, the less likely the model generalizes correctly from the
training data.
"""

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score

def true_fun(X):
    return np.cos(1.5 * np.pi * X)

np.random.seed(0)

n_samples = 30
degrees = [1, 4, 15]

X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1

plt.figure(figsize=(14, 5))
for i in range(len(degrees)):
    ax = plt.subplot(1, len(degrees), i + 1)
    plt.setp(ax, xticks=(), yticks=())

    polynomial_features = PolynomialFeatures(degree=degrees[i],
                                             include_bias=False)
    linear_regression = LinearRegression()
    pipeline = Pipeline([("polynomial_features", polynomial_features),
                         ("linear_regression", linear_regression)])
    pipeline.fit(X[:, np.newaxis], y)

    # Evaluate the models using crossvalidation
    scores = cross_val_score(pipeline, X[:, np.newaxis], y,
                             scoring="neg_mean_squared_error", cv=10)

    X_test = np.linspace(0, 1, 100)
    plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
    plt.plot(X_test, true_fun(X_test), label="True function")
    plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.xlim((0, 1))
    plt.ylim((-2, 2))
    plt.legend(loc="best")
    plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
        degrees[i], -scores.mean(), scores.std()))
plt.show()
```

## Cross-validation with Ridge

```python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import PolynomialFeatures

# A seed just to ensure that the random numbers are the same for every run.
np.random.seed(3155)
# Generate the data.
n = 100
x = np.linspace(-3, 3, n).reshape(-1, 1)
y = np.exp(-x**2) + 1.5 * np.exp(-(x-2)**2)+ np.random.normal(0, 0.1, x.shape)
# Decide degree on polynomial to fit
poly = PolynomialFeatures(degree = 10)

# Decide which values of lambda to use
nlambdas = 500
lambdas = np.logspace(-3, 5, nlambdas)
# Initialize a KFold instance
k = 5
kfold = KFold(n_splits = k)
estimated_mse_sklearn = np.zeros(nlambdas)
i = 0
for lmb in lambdas:
    ridge = Ridge(alpha = lmb)
    estimated_mse_folds = cross_val_score(ridge, x, y, scoring='neg_mean_squared_error', cv=kfold)
    estimated_mse_sklearn[i] = np.mean(-estimated_mse_folds)
    i += 1
plt.figure()
plt.plot(np.log10(lambdas), estimated_mse_sklearn, label = 'cross_val_score')
plt.xlabel('log10(lambda)')
plt.ylabel('MSE')
plt.legend()
plt.show()
```

## The Ising model

The one-dimensional Ising model with nearest neighbor interaction, no
external field and a constant coupling constant $J$ is given by

$$
\begin{equation}
    H = -J \sum_{k}^L s_k s_{k + 1},
\label{_auto1} \tag{1}
\end{equation}
$$

where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins
in the system is determined by $L$. For the one-dimensional system
there is no phase transition.

We will look at a system of $L = 40$ spins with a coupling constant of
$J = 1$. To get enough training data we will generate 10000 states
with their respective energies.

```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
import scipy.linalg as scl
from sklearn.model_selection import train_test_split
import tqdm
sns.set(color_codes=True)
cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')

L = 40
n = int(1e4)

spins = np.random.choice([-1, 1], size=(n, L))
J = 1.0

energies = np.zeros(n)

for i in range(n):
    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
```

Here we use ordinary least squares
regression to predict the energy for the nearest neighbor
one-dimensional Ising model on a ring, i.e., the endpoints wrap
around. We will use linear regression to fit a value for
the coupling constant to achieve this.

## Reformulating the problem to suit regression

A more general form for the one-dimensional Ising model is

$$
\begin{equation}
    H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
\label{_auto2} \tag{2}
\end{equation}
$$

Here we allow for interactions beyond the nearest neighbors and a state dependent
coupling constant. This latter expression can be formulated as
a matrix-product

$$
\begin{equation}
    \boldsymbol{H} = \boldsymbol{X} J,
\label{_auto3} \tag{3}
\end{equation}
$$

where $X_{jk} = s_j s_k$ and $J$ is a matrix which consists of the
elements $-J_{jk}$. This form of writing the energy fits perfectly
with the form utilized in linear regression, that is

$$
\begin{equation}
    \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon},
\label{_auto4} \tag{4}
\end{equation}
$$

We split the data in training and test data as discussed in the previous example

```python
X = np.zeros((n, L ** 2))
for i in range(n):
    X[i] = np.outer(spins[i], spins[i]).ravel()
y = energies
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```

## Linear regression

In the ordinary least squares method we choose the cost function

$$
\begin{equation}
    C(\boldsymbol{X}, \boldsymbol{\beta})= \frac{1}{n}\left\{(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})\right\}.
\label{_auto5} \tag{5}
\end{equation}
$$

We then find the extremal point of $C$ by taking the derivative with respect to $\boldsymbol{\beta}$ as discussed above.
This yields the expression for $\boldsymbol{\beta}$ to be

$$
\boldsymbol{\beta} = \frac{\boldsymbol{X}^T \boldsymbol{y}}{\boldsymbol{X}^T \boldsymbol{X}},
$$

which immediately imposes some requirements on $\boldsymbol{X}$ as there must exist
an inverse of $\boldsymbol{X}^T \boldsymbol{X}$. If the expression we are modeling contains an
intercept, i.e., a constant term, we must make sure that the
first column of $\boldsymbol{X}$ consists of $1$. We do this here

```python
X_train_own = np.concatenate(
    (np.ones(len(X_train))[:, np.newaxis], X_train),
    axis=1
)
X_test_own = np.concatenate(
    (np.ones(len(X_test))[:, np.newaxis], X_test),
    axis=1
)
```

```python
def ols_inv(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    return scl.inv(x.T @ x) @ (x.T @ y)
beta = ols_inv(X_train_own, y_train)
```

## Singular Value decomposition

Doing the inversion directly turns out to be a bad idea since the matrix
$\boldsymbol{X}^T\boldsymbol{X}$ is singular. An alternative approach is to use the **singular
value decomposition**. Using the definition of the Moore-Penrose
pseudoinverse we can write the equation for $\boldsymbol{\beta}$ as

$$
\boldsymbol{\beta} = \boldsymbol{X}^{+}\boldsymbol{y},
$$

where the pseudoinverse of $\boldsymbol{X}$ is given by

$$
\boldsymbol{X}^{+} = \frac{\boldsymbol{X}^T}{\boldsymbol{X}^T\boldsymbol{X}}.
$$

Using singular value decomposition we can decompose the matrix  $\boldsymbol{X} = \boldsymbol{U}\boldsymbol{\Sigma} \boldsymbol{V}^T$,
where $\boldsymbol{U}$ and $\boldsymbol{V}$ are orthogonal(unitary) matrices and $\boldsymbol{\Sigma}$ contains the singular values (more details below).
where $X^{+} = V\Sigma^{+} U^T$. This reduces the equation for
$\omega$ to

$$
\begin{equation}
    \boldsymbol{\beta} = \boldsymbol{V}\boldsymbol{\Sigma}^{+} \boldsymbol{U}^T \boldsymbol{y}.
\label{_auto6} \tag{6}
\end{equation}
$$

Note that solving this equation by actually doing the pseudoinverse
(which is what we will do) is not a good idea as this operation scales
as $\mathcal{O}(n^3)$, where $n$ is the number of elements in a
general matrix. Instead, doing $QR$-factorization and solving the
linear system as an equation would reduce this down to
$\mathcal{O}(n^2)$ operations.

```python
def ols_svd(x: np.ndarray, y: np.ndarray) -> np.ndarray:
    u, s, v = scl.svd(x)
    return v.T @ scl.pinv(scl.diagsvd(s, u.shape[0], v.shape[0])) @ u.T @ y
```

```python
beta = ols_svd(X_train_own,y_train)
```

When extracting the $J$-matrix  we need to make sure that we remove the intercept, as is done here

```python
J = beta[1:].reshape(L, L)
```

A way of looking at the coefficients in $J$ is to plot the matrices as images.

```python
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J, **cmap_args)
plt.title("OLS", fontsize=18)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
cb = fig.colorbar(im)
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
plt.show()
```

It is interesting to note that OLS
considers both $J_{j, j + 1} = -0.5$ and $J_{j, j - 1} = -0.5$ as
valid matrix elements for $J$.
In our discussion below on hyperparameters and Ridge and Lasso regression we will see that
this problem can be removed, partly and only with Lasso regression.

In this case our matrix inversion was actually possible. The obvious question now is what is the mathematics behind the SVD?

## The one-dimensional Ising model

Let us bring back the Ising model again, but now with an additional
focus on Ridge and Lasso regression as well. We repeat some of the
basic parts of the Ising model and the setup of the training and test
data.  The one-dimensional Ising model with nearest neighbor
interaction, no external field and a constant coupling constant $J$ is
given by

$$
\begin{equation}
    H = -J \sum_{k}^L s_k s_{k + 1},
\label{_auto7} \tag{7}
\end{equation}
$$

where $s_i \in \{-1, 1\}$ and $s_{N + 1} = s_1$. The number of spins in the system is determined by $L$. For the one-dimensional system there is no phase transition.

We will look at a system of $L = 40$ spins with a coupling constant of $J = 1$. To get enough training data we will generate 10000 states with their respective energies.

```python
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
import scipy.linalg as scl
from sklearn.model_selection import train_test_split
import sklearn.linear_model as skl
import tqdm
sns.set(color_codes=True)
cmap_args=dict(vmin=-1., vmax=1., cmap='seismic')

L = 40
n = int(1e4)

spins = np.random.choice([-1, 1], size=(n, L))
J = 1.0

energies = np.zeros(n)

for i in range(n):
    energies[i] = - J * np.dot(spins[i], np.roll(spins[i], 1))
```

A more general form for the one-dimensional Ising model is

$$
\begin{equation}
    H = - \sum_j^L \sum_k^L s_j s_k J_{jk}.
\label{_auto8} \tag{8}
\end{equation}
$$

Here we allow for interactions beyond the nearest neighbors and a more
adaptive coupling matrix. This latter expression can be formulated as
a matrix-product on the form

$$
\begin{equation}
    H = X J,
\label{_auto9} \tag{9}
\end{equation}
$$

where $X_{jk} = s_j s_k$ and $J$ is the matrix consisting of the
elements $-J_{jk}$. This form of writing the energy fits perfectly
with the form utilized in linear regression, viz.

$$
\begin{equation}
    \boldsymbol{y} = \boldsymbol{X}\boldsymbol{\beta} + \boldsymbol{\epsilon}.
\label{_auto10} \tag{10}
\end{equation}
$$

We organize the data as we did above

```python
X = np.zeros((n, L ** 2))
for i in range(n):
    X[i] = np.outer(spins[i], spins[i]).ravel()
y = energies
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.96)

X_train_own = np.concatenate(
    (np.ones(len(X_train))[:, np.newaxis], X_train),
    axis=1
)

X_test_own = np.concatenate(
    (np.ones(len(X_test))[:, np.newaxis], X_test),
    axis=1
)
```

We will do all fitting with **Scikit-Learn**,

```python
clf = skl.LinearRegression().fit(X_train, y_train)
```

When  extracting the $J$-matrix we make sure to remove the intercept

```python
J_sk = clf.coef_.reshape(L, L)
```

And then we plot the results

```python
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_sk, **cmap_args)
plt.title("LinearRegression from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
cb = fig.colorbar(im)
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)
plt.show()
```

The results perfectly with our previous discussion where we used our own code.

## Ridge regression

Having explored the ordinary least squares we move on to ridge
regression. In ridge regression we include a **regularizer**. This
involves a new cost function which leads to a new estimate for the
weights $\boldsymbol{\beta}$. This results in a penalized regression problem. The
cost function is given by

2
2

<
<
<
!
!
M
A
T
H
_
B
L
O
C
K

```python
_lambda = 0.1
clf_ridge = skl.Ridge(alpha=_lambda).fit(X_train, y_train)
J_ridge_sk = clf_ridge.coef_.reshape(L, L)
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_ridge_sk, **cmap_args)
plt.title("Ridge from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
cb = fig.colorbar(im)
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)

plt.show()
```

## LASSO regression

In the **Least Absolute Shrinkage and Selection Operator** (LASSO)-method we get a third cost function.

$$
\begin{equation}
    C(\boldsymbol{X}, \boldsymbol{\beta}; \lambda) = (\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y})^T(\boldsymbol{X}\boldsymbol{\beta} - \boldsymbol{y}) + \lambda \sqrt{\boldsymbol{\beta}^T\boldsymbol{\beta}}.
\label{_auto12} \tag{12}
\end{equation}
$$

Finding the extremal point of this cost function is not so straight-forward as in least squares and ridge. We will therefore rely solely on the function ``Lasso`` from **Scikit-Learn**.

```python
clf_lasso = skl.Lasso(alpha=_lambda).fit(X_train, y_train)
J_lasso_sk = clf_lasso.coef_.reshape(L, L)
fig = plt.figure(figsize=(20, 14))
im = plt.imshow(J_lasso_sk, **cmap_args)
plt.title("Lasso from Scikit-learn", fontsize=18)
plt.xticks(fontsize=18)
plt.yticks(fontsize=18)
cb = fig.colorbar(im)
cb.ax.set_yticklabels(cb.ax.get_yticklabels(), fontsize=18)

plt.show()
```

It is quite striking how LASSO breaks the symmetry of the coupling
constant as opposed to ridge and OLS. We get a sparse solution with
$J_{j, j + 1} = -1$.

## Performance as  function of the regularization parameter

We see how the different models perform for a different set of values for $\lambda$.

```python
lambdas = np.logspace(-4, 5, 10)

train_errors = {
    "ols_sk": np.zeros(lambdas.size),
    "ridge_sk": np.zeros(lambdas.size),
    "lasso_sk": np.zeros(lambdas.size)
}

test_errors = {
    "ols_sk": np.zeros(lambdas.size),
    "ridge_sk": np.zeros(lambdas.size),
    "lasso_sk": np.zeros(lambdas.size)
}

plot_counter = 1

fig = plt.figure(figsize=(32, 54))

for i, _lambda in enumerate(tqdm.tqdm(lambdas)):
    for key, method in zip(
        ["ols_sk", "ridge_sk", "lasso_sk"],
        [skl.LinearRegression(), skl.Ridge(alpha=_lambda), skl.Lasso(alpha=_lambda)]
    ):
        method = method.fit(X_train, y_train)

        train_errors[key][i] = method.score(X_train, y_train)
        test_errors[key][i] = method.score(X_test, y_test)

        omega = method.coef_.reshape(L, L)

        plt.subplot(10, 5, plot_counter)
        plt.imshow(omega, **cmap_args)
        plt.title(r"%s, $\lambda = %.4f$" % (key, _lambda))
        plot_counter += 1

plt.show()
```

We see that LASSO reaches a good solution for low
values of $\lambda$, but will "wither" when we increase $\lambda$ too
much. Ridge is more stable over a larger range of values for
$\lambda$, but eventually also fades away.

## Finding the optimal value of $\lambda$

To determine which value of $\lambda$ is best we plot the accuracy of
the models when predicting the training and the testing set. We expect
the accuracy of the training set to be quite good, but if the accuracy
of the testing set is much lower this tells us that we might be
subject to an overfit model. The ideal scenario is an accuracy on the
testing set that is close to the accuracy of the training set.

```python
fig = plt.figure(figsize=(20, 14))

colors = {
    "ols_sk": "r",
    "ridge_sk": "y",
    "lasso_sk": "c"
}

for key in train_errors:
    plt.semilogx(
        lambdas,
        train_errors[key],
        colors[key],
        label="Train {0}".format(key),
        linewidth=4.0
    )

for key in test_errors:
    plt.semilogx(
        lambdas,
        test_errors[key],
        colors[key] + "--",
        label="Test {0}".format(key),
        linewidth=4.0
    )
plt.legend(loc="best", fontsize=18)
plt.xlabel(r"$\lambda$", fontsize=18)
plt.ylabel(r"$R^2$", fontsize=18)
plt.tick_params(labelsize=18)
plt.show()
```

From the above figure we can see that LASSO with $\lambda = 10^{-2}$
achieves a very good accuracy on the test set. This by far surpasses the
other models for all values of $\lambda$.

## Friday September 18: Intro to Logistic Regression

[Video of Lecture](https://www.uio.no/studier/emner/matnat/fys/FYS-STK3155/h20/forelesningsvideoer/LectureSeptember18.mp4?vrtx=view-as-webpage) and [link to handwritten notes](https://github.com/CompPhysics/MachineLearning/blob/master/doc/HandWrittenNotes/NotesSeptember18.pdf).

## Logistic Regression

In linear regression our main interest was centered on learning the
coefficients of a functional fit (say a polynomial) in order to be
able to predict the response of a continuous variable on some unseen
data. The fit to the continuous variable $y_i$ is based on some
independent variables $\hat{x}_i$. Linear regression resulted in
analytical expressions for standard ordinary Least Squares or Ridge
regression (in terms of matrices to invert) for several quantities,
ranging from the variance and thereby the confidence intervals of the
parameters $\hat{\beta}$ to the mean squared error. If we can invert
the product of the design matrices, linear regression gives then a
simple recipe for fitting our data.

## Classification problems

Classification problems, however, are concerned with outcomes taking
the form of discrete variables (i.e. categories). We may for example,
on the basis of DNA sequencing for a number of patients, like to find
out which mutations are important for a certain disease; or based on
scans of various patients' brains, figure out if there is a tumor or
not; or given a specific physical system, we'd like to identify its
state, say whether it is an ordered or disordered system (typical
situation in solid state physics); or classify the status of a
patient, whether she/he has a stroke or not and many other similar
situations.

The most common situation we encounter when we apply logistic
regression is that of two possible outcomes, normally denoted as a
binary outcome, true or false, positive or negative, success or
failure etc.

## Optimization and Deep learning

Logistic regression will also serve as our stepping stone towards
neural network algorithms and supervised deep learning. For logistic
learning, the minimization of the cost function leads to a non-linear
equation in the parameters $\hat{\beta}$. The optimization of the
problem calls therefore for minimization algorithms. This forms the
bottle neck of all machine learning algorithms, namely how to find
reliable minima of a multi-variable function. This leads us to the
family of gradient descent methods. The latter are the working horses
of basically all modern machine learning algorithms.

We note also that many of the topics discussed here on logistic
regression are also commonly used in modern supervised Deep Learning
models, as we will see later.

## Basics

We consider the case where the dependent variables, also called the
responses or the outcomes, $y_i$ are discrete and only take values
from $k=0,\dots,K-1$ (i.e. $K$ classes).

The goal is to predict the
output classes from the design matrix $\hat{X}\in\mathbb{R}^{n\times p}$
made of $n$ samples, each of which carries $p$ features or predictors. The
primary goal is to identify the classes to which new unseen samples
belong.

Let us specialize to the case of two classes only, with outputs
$y_i=0$ and $y_i=1$. Our outcomes could represent the status of a
credit card user that could default or not on her/his credit card
debt. That is

$$
y_i = \begin{bmatrix} 0 & \mathrm{no}\\  1 & \mathrm{yes} \end{bmatrix}.
$$

## Linear classifier

Before moving to the logistic model, let us try to use our linear
regression model to classify these two outcomes. We could for example
fit a linear model to the default case if $y_i > 0.5$ and the no
default case $y_i \leq 0.5$.

We would then have our
weighted linear combination, namely

$$
\begin{equation}
\hat{y} = \hat{X}^T\hat{\beta} +  \hat{\epsilon},
\label{_auto13} \tag{13}
\end{equation}
$$

where $\hat{y}$ is a vector representing the possible outcomes, $\hat{X}$ is our
$n\times p$ design matrix and $\hat{\beta}$ represents our estimators/predictors.

## Some selected properties

The main problem with our function is that it takes values on the
entire real axis. In the case of logistic regression, however, the
labels $y_i$ are discrete variables. A typical example is the credit
card data discussed below here, where we can set the state of
defaulting the debt to $y_i=1$ and not to $y_i=0$ for one the persons
in the data set (see the full example below).

One simple way to get a discrete output is to have sign
functions that map the output of a linear regressor to values $\{0,1\}$,
$f(s_i)=sign(s_i)=1$ if $s_i\ge 0$ and 0 if otherwise.
We will encounter this model in our first demonstration of neural networks. Historically it is called the ``perceptron" model in the machine learning
literature. This model is extremely simple. However, in many cases it is more
favorable to use a ``soft" classifier that outputs
the probability of a given category. This leads us to the logistic function.

## Simple example

The following example on data for coronary heart disease (CHD) as function of age may serve as an illustration. In the code here we read and plot whether a person has had CHD (output = 1) or not (output = 0). This ouput  is plotted the person's against age. Clearly, the figure shows that attempting to make a standard linear regression fit may not be very meaningful.

```python
# Common imports
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.model_selection import train_test_split
from sklearn.utils import resample
from sklearn.metrics import mean_squared_error
from IPython.display import display
from pylab import plt, mpl
plt.style.use('seaborn')
mpl.rcParams['font.family'] = 'serif'

# Where to save the figures and data files
PROJECT_ROOT_DIR = "Results"
FIGURE_ID = "Results/FigureFiles"
DATA_ID = "DataFiles/"

if not os.path.exists(PROJECT_ROOT_DIR):
    os.mkdir(PROJECT_ROOT_DIR)

if not os.path.exists(FIGURE_ID):
    os.makedirs(FIGURE_ID)

if not os.path.exists(DATA_ID):
    os.makedirs(DATA_ID)

def image_path(fig_id):
    return os.path.join(FIGURE_ID, fig_id)

def data_path(dat_id):
    return os.path.join(DATA_ID, dat_id)

def save_fig(fig_id):
    plt.savefig(image_path(fig_id) + ".png", format='png')

infile = open(data_path("chddata.csv"),'r')

# Read the chd data as  csv file and organize the data into arrays with age group, age, and chd
chd = pd.read_csv(infile, names=('ID', 'Age', 'Agegroup', 'CHD'))
chd.columns = ['ID', 'Age', 'Agegroup', 'CHD']
output = chd['CHD']
age = chd['Age']
agegroup = chd['Agegroup']
numberID  = chd['ID']
display(chd)

plt.scatter(age, output, marker='o')
plt.axis([18,70.0,-0.1, 1.2])
plt.xlabel(r'Age')
plt.ylabel(r'CHD')
plt.title(r'Age distribution and Coronary heart disease')
plt.show()
```

## Plotting the mean value for each group

What we could attempt however is to plot the mean value for each group.

```python
agegroupmean = np.array([0.1, 0.133, 0.250, 0.333, 0.462, 0.625, 0.765, 0.800])
group = np.array([1, 2, 3, 4, 5, 6, 7, 8])
plt.plot(group, agegroupmean, "r-")
plt.axis([0,9,0, 1.0])
plt.xlabel(r'Age group')
plt.ylabel(r'CHD mean values')
plt.title(r'Mean values for each age group')
plt.show()
```

We are now trying to find a function $f(y\vert x)$, that is a function which gives us an expected value for the output $y$ with a given input $x$.
In standard linear regression with a linear dependence on $x$, we would write this in terms of our model

$$
f(y_i\vert x_i)=\beta_0+\beta_1 x_i.
$$

This expression implies however that $f(y_i\vert x_i)$ could take any
value from minus infinity to plus infinity. If we however let
$f(y\vert y)$ be represented by the mean value, the above example
shows us that we can constrain the function to take values between
zero and one, that is we have $0 \le f(y_i\vert x_i) \le 1$. Looking
at our last curve we see also that it has an S-shaped form. This leads
us to a very popular model for the function $f$, namely the so-called
Sigmoid function or logistic model. We will consider this function as
representing the probability for finding a value of $y_i$ with a given
$x_i$.

## The logistic function

Another widely studied model, is the so-called
perceptron model, which is an example of a "hard classification" model. We
will encounter this model when we discuss neural networks as
well. Each datapoint is deterministically assigned to a category (i.e
$y_i=0$ or $y_i=1$). In many cases, and the coronary heart disease data forms one of many such examples, it is favorable to have a "soft"
classifier that outputs the probability of a given category rather
than a single value. For example, given $x_i$, the classifier
outputs the probability of being in a category $k$.  Logistic regression
is the most common example of a so-called soft classifier. In logistic
regression, the probability that a data point $x_i$
belongs to a category $y_i=\{0,1\}$ is given by the so-called logit function (or Sigmoid) which is meant to represent the likelihood for a given event,

$$
p(t) = \frac{1}{1+\mathrm \exp{-t}}=\frac{\exp{t}}{1+\mathrm \exp{t}}.
$$

Note that $1-p(t)= p(-t)$.

## Examples of likelihood functions used in logistic regression and nueral networks

The following code plots the logistic function, the step function and other functions we will encounter from here and on.

```python
"""The sigmoid function (or the logistic curve) is a
function that takes any real number, z, and outputs a number (0,1).
It is useful in neural networks for assigning weights on a relative scale.
The value z is the weighted sum of parameters involved in the learning algorithm."""

import numpy
import matplotlib.pyplot as plt
import math as mt

z = numpy.arange(-5, 5, .1)
sigma_fn = numpy.vectorize(lambda z: 1/(1+numpy.exp(-z)))
sigma = sigma_fn(z)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, sigma)
ax.set_ylim([-0.1, 1.1])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('sigmoid function')

plt.show()

"""Step Function"""
z = numpy.arange(-5, 5, .02)
step_fn = numpy.vectorize(lambda z: 1.0 if z >= 0.0 else 0.0)
step = step_fn(z)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, step)
ax.set_ylim([-0.5, 1.5])
ax.set_xlim([-5,5])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('step function')

plt.show()

"""tanh Function"""
z = numpy.arange(-2*mt.pi, 2*mt.pi, 0.1)
t = numpy.tanh(z)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(z, t)
ax.set_ylim([-1.0, 1.0])
ax.set_xlim([-2*mt.pi,2*mt.pi])
ax.grid(True)
ax.set_xlabel('z')
ax.set_title('tanh function')

plt.show()
```

## Two parameters

We assume now that we have two classes with $y_i$ either $0$ or $1$. Furthermore we assume also that we have only two parameters $\beta$ in our fitting of the Sigmoid function, that is we define probabilities

$$
\begin{align*}
p(y_i=1|x_i,\hat{\beta}) &= \frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}},\nonumber\\
p(y_i=0|x_i,\hat{\beta}) &= 1 - p(y_i=1|x_i,\hat{\beta}),
\end{align*}
$$

where $\hat{\beta}$ are the weights we wish to extract from data, in our case $\beta_0$ and $\beta_1$.

Note that we used

$$
p(y_i=0\vert x_i, \hat{\beta}) = 1-p(y_i=1\vert x_i, \hat{\beta}).
$$

## Maximum likelihood

In order to define the total likelihood for all possible outcomes from a
dataset $\mathcal{D}=\{(y_i,x_i)\}$, with the binary labels
$y_i\in\{0,1\}$ and where the data points are drawn independently, we use the so-called [Maximum Likelihood Estimation](https://en.wikipedia.org/wiki/Maximum_likelihood_estimation) (MLE) principle.
We aim thus at maximizing
the probability of seeing the observed data. We can then approximate the
likelihood in terms of the product of the individual probabilities of a specific outcome $y_i$, that is

$$
\begin{align*}
P(\mathcal{D}|\hat{\beta})& = \prod_{i=1}^n \left[p(y_i=1|x_i,\hat{\beta})\right]^{y_i}\left[1-p(y_i=1|x_i,\hat{\beta}))\right]^{1-y_i}\nonumber \\
\end{align*}
$$

from which we obtain the log-likelihood and our **cost/loss** function

$$
\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n \left( y_i\log{p(y_i=1|x_i,\hat{\beta})} + (1-y_i)\log\left[1-p(y_i=1|x_i,\hat{\beta}))\right]\right).
$$

## The cost function rewritten

Reordering the logarithms, we can rewrite the **cost/loss** function as

$$
\mathcal{C}(\hat{\beta}) = \sum_{i=1}^n  \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
$$

The maximum likelihood estimator is defined as the set of parameters that maximize the log-likelihood where we maximize with respect to $\beta$.
Since the cost (error) function is just the negative log-likelihood, for logistic regression we have that

$$
\mathcal{C}(\hat{\beta})=-\sum_{i=1}^n  \left(y_i(\beta_0+\beta_1x_i) -\log{(1+\exp{(\beta_0+\beta_1x_i)})}\right).
$$

This equation is known in statistics as the **cross entropy**. Finally, we note that just as in linear regression,
in practice we often supplement the cross-entropy with additional regularization terms, usually $L_1$ and $L_2$ regularization as we did for Ridge and Lasso regression.

## Minimizing the cross entropy

The cross entropy is a convex function of the weights $\hat{\beta}$ and,
therefore, any local minimizer is a global minimizer.

Minimizing this
cost function with respect to the two parameters $\beta_0$ and $\beta_1$ we obtain

$$
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_0} = -\sum_{i=1}^n  \left(y_i -\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right),
$$

and

$$
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \beta_1} = -\sum_{i=1}^n  \left(y_ix_i -x_i\frac{\exp{(\beta_0+\beta_1x_i)}}{1+\exp{(\beta_0+\beta_1x_i)}}\right).
$$

## A more compact expression

Let us now define a vector $\hat{y}$ with $n$ elements $y_i$, an
$n\times p$ matrix $\hat{X}$ which contains the $x_i$ values and a
vector $\hat{p}$ of fitted probabilities $p(y_i\vert x_i,\hat{\beta})$. We can rewrite in a more compact form the first
derivative of cost function as

$$
\frac{\partial \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}} = -\hat{X}^T\left(\hat{y}-\hat{p}\right).
$$

If we in addition define a diagonal matrix $\hat{W}$ with elements
$p(y_i\vert x_i,\hat{\beta})(1-p(y_i\vert x_i,\hat{\beta})$, we can obtain a compact expression of the second derivative as

$$
\frac{\partial^2 \mathcal{C}(\hat{\beta})}{\partial \hat{\beta}\partial \hat{\beta}^T} = \hat{X}^T\hat{W}\hat{X}.
$$

## Extending to more predictors

Within a binary classification problem, we can easily expand our model to include multiple predictors. Our ratio between likelihoods is then with $p$ predictors

$$
\log{ \frac{p(\hat{\beta}\hat{x})}{1-p(\hat{\beta}\hat{x})}} = \beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p.
$$

Here we defined $\hat{x}=[1,x_1,x_2,\dots,x_p]$ and $\hat{\beta}=[\beta_0, \beta_1, \dots, \beta_p]$ leading to

$$
p(\hat{\beta}\hat{x})=\frac{ \exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}{1+\exp{(\beta_0+\beta_1x_1+\beta_2x_2+\dots+\beta_px_p)}}.
$$

## Including more classes

Till now we have mainly focused on two classes, the so-called binary
system. Suppose we wish to extend to $K$ classes.  Let us for the sake
of simplicity assume we have only two predictors. We have then following model

$$
\log{\frac{p(C=1\vert x)}{p(K\vert x)}} = \beta_{10}+\beta_{11}x_1,
$$

and

$$
\log{\frac{p(C=2\vert x)}{p(K\vert x)}} = \beta_{20}+\beta_{21}x_1,
$$

and so on till the class $C=K-1$ class

$$
\log{\frac{p(C=K-1\vert x)}{p(K\vert x)}} = \beta_{(K-1)0}+\beta_{(K-1)1}x_1,
$$

and the model is specified in term of $K-1$ so-called log-odds or
**logit** transformations.

## More classes

In our discussion of neural networks we will encounter the above again
in terms of a slightly modified function, the so-called **Softmax** function.

The softmax function is used in various multiclass classification
methods, such as multinomial logistic regression (also known as
softmax regression), multiclass linear discriminant analysis, naive
Bayes classifiers, and artificial neural networks.  Specifically, in
multinomial logistic regression and linear discriminant analysis, the
input to the function is the result of $K$ distinct linear functions,
and the predicted probability for the $k$-th class given a sample
vector $\hat{x}$ and a weighting vector $\hat{\beta}$ is (with two
predictors):

$$
p(C=k\vert \mathbf {x} )=\frac{\exp{(\beta_{k0}+\beta_{k1}x_1)}}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}}.
$$

It is easy to extend to more predictors. The final class is

$$
p(C=K\vert \mathbf {x} )=\frac{1}{1+\sum_{l=1}^{K-1}\exp{(\beta_{l0}+\beta_{l1}x_1)}},
$$

and they sum to one. Our earlier discussions were all specialized to
the case with two classes only. It is easy to see from the above that
what we derived earlier is compatible with these equations.

To find the optimal parameters we would typically use a gradient
descent method.  Newton's method and gradient descent methods are
discussed in the material on [optimization
methods](https://compphysics.github.io/MachineLearning/doc/pub/Splines/html/Splines-bs.html).

This will be discussed next week. Before we develop our own codes for logistic regression, we end this lecture by studying the functionality that **Scikit-learn** offers.

## Wisconsin Cancer Data

We show here how we can use a simple regression case on the breast
cancer data using Logistic regression as our algorithm for
classification.

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression

# Load the data
cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
# Logistic Regression
logreg = LogisticRegression(solver='lbfgs')
logreg.fit(X_train, y_train)
print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
#now scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Logistic Regression
logreg.fit(X_train_scaled, y_train)
print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))
```

    (426, 30)
    (143, 30)
    Test set accuracy with Logistic Regression: 0.95
    Test set accuracy Logistic Regression with scaled data: 0.96

    /Users/MortenImac/anaconda3/lib/python3.6/site-packages/sklearn/linear_model/_logistic.py:762: ConvergenceWarning: lbfgs failed to converge (status=1):
    STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

    Increase the number of iterations (max_iter) or scale the data as shown in:
        https://scikit-learn.org/stable/modules/preprocessing.html
    Please also refer to the documentation for alternative solver options:
        https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
      extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG)

## Using the correlation matrix

In addition to the above scores, we could also study the covariance (and the correlation matrix).
We use **Pandas** to compute the correlation matrix.

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
cancer = load_breast_cancer()
import pandas as pd
# Making a data frame
cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)

fig, axes = plt.subplots(15,2,figsize=(10,20))
malignant = cancer.data[cancer.target == 0]
benign = cancer.data[cancer.target == 1]
ax = axes.ravel()

for i in range(30):
    _, bins = np.histogram(cancer.data[:,i], bins =50)
    ax[i].hist(malignant[:,i], bins = bins, alpha = 0.5)
    ax[i].hist(benign[:,i], bins = bins, alpha = 0.5)
    ax[i].set_title(cancer.feature_names[i])
    ax[i].set_yticks(())
ax[0].set_xlabel("Feature magnitude")
ax[0].set_ylabel("Frequency")
ax[0].legend(["Malignant", "Benign"], loc ="best")
fig.tight_layout()
plt.show()

import seaborn as sns
correlation_matrix = cancerpd.corr().round(1)
# use the heatmap function from seaborn to plot the correlation matrix
# annot = True to print the values inside the square
plt.figure(figsize=(15,8))
sns.heatmap(data=correlation_matrix, annot=True)
plt.show()
```

## Discussing the correlation data

In the above example we note two things. In the first plot we display
the overlap of benign and malignant tumors as functions of the various
features in the Wisconsing breast cancer data set. We see that for
some of the features we can distinguish clearly the benign and
malignant cases while for other features we cannot. This can point to
us which features may be of greater interest when we wish to classify
a benign or not benign tumour.

In the second figure we have computed the so-called correlation
matrix, which in our case with thirty features becomes a $30\times 30$
matrix.

We constructed this matrix using **pandas** via the statements

```python
cancerpd = pd.DataFrame(cancer.data, columns=cancer.feature_names)
```

and then

```python
correlation_matrix = cancerpd.corr().round(1)
```

Diagonalizing this matrix we can in turn say something about which
features are of relevance and which are not. This leads  us to
the classical Principal Component Analysis (PCA) theorem with
applications. This will be discussed later this semester ([week 43](https://compphysics.github.io/MachineLearning/doc/pub/week43/html/week43-bs.html)).

## Other measures in classification studies: Cancer Data  again

```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import  train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression

# Load the data
cancer = load_breast_cancer()

X_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)
print(X_train.shape)
print(X_test.shape)
# Logistic Regression
logreg = LogisticRegression(solver='lbfgs')
logreg.fit(X_train, y_train)
print("Test set accuracy with Logistic Regression: {:.2f}".format(logreg.score(X_test,y_test)))
#now scale the data
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)
X_train_scaled = scaler.transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Logistic Regression
logreg.fit(X_train_scaled, y_train)
print("Test set accuracy Logistic Regression with scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))

from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import cross_validate
#Cross validation
accuracy = cross_validate(logreg,X_test_scaled,y_test,cv=10)['test_score']
print(accuracy)
print("Test set accuracy with Logistic Regression  and scaled data: {:.2f}".format(logreg.score(X_test_scaled,y_test)))

import scikitplot as skplt
y_pred = logreg.predict(X_test_scaled)
skplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)
plt.show()
y_probas = logreg.predict_proba(X_test_scaled)
skplt.metrics.plot_roc(y_test, y_probas)
plt.show()
skplt.metrics.plot_cumulative_gain(y_test, y_probas)
plt.show()
```

```python

```


```python
import numpy as np
import matplotlib.pyplot as plt
from trotter import *
```

# Clock Hamiltonian

\begin{equation}
H=J\sum_i \sum_{m=1}^{n-1} \alpha_m \sigma_i^m \sigma_{i+1}^{-m}+g\sum_i \sum_{m=1}^{n-1} \beta_m \tau_i^m
\end{equation}

```python
dim = 3 # order of the clock (n)
g = -0.2; J = float("{0:.5f}".format(-1-g)); theta = np.pi/3; phi = 0;
alpha = np.array([np.exp(1j*theta),np.exp(-1j*theta)])
beta = np.array([np.exp(1j*phi),np.exp(1j*phi)])

chi = 10; delta = 0.01; N = 500
```

#### Construct operators

```python
sigma = np.diag(np.exp(1j*2*np.pi*np.arange(dim)/dim))
tau = np.roll(np.eye(dim), -1, axis = -1)
interactions = list(zip(J*alpha, [sigma**m for m in range(1,dim)], [sigma**(dim-m) for m in range(1,dim)]))
transv_field = list(zip(g*beta, [tau**m for m in range(1,dim)]))
U=ST_step(delta, interactions, transv_field)
```

#### Initialization with random state

```python
GA0 = np.random.rand(dim,chi,chi)
LA0 = np.random.rand(chi)
GB0 = np.random.rand(dim,chi,chi)
LB0 = np.random.rand(chi)
```

#### iTEBD

```python
res={}
res_names = ["Energy", "SigmaA", "SigmaB"]

GA = GA0; LA = LA0; GB = GB0; LB = LB0
discarded_weights = []
for step in range(N):
    GA, LA, GB, dw, norm_sq = iTEDB(dim, chi, GA, LA, GB, LB, U)
    E_sim =-np.log(norm_sq)/delta/2
    discarded_weights.append(dw)
    GB, LB, GA, dw, norm_sq = iTEDB(dim, chi, GB, LB, GA, LA, U)
    E_sim =-np.log(norm_sq)/delta/2
    discarded_weights.append(dw)
res["Energy"] = E_sim
res["SigmaA"] = np.einsum('sab,tab,st,b,a->', GA, np.conj(GA), sigma, LA**2, LB**2)
res["SigmaB"] = np.einsum('sab,tab,st,b,a->', GB, np.conj(GB), sigma, LB**2, LA**2)
#res["SigmaAdagSigmaB"] = np.einsum('sab,tac,st,b,c,vbd,wcd,vw,a,d->',
#                                   GA, np.conj(GA), sigma**2, LA, LA, GB, np.conj(GB), sigma, LB**2, LB**2)

for key in res_names: print(key, res[key])
print(np.exp(1j*theta))
print("Discarder weights", discarded_weights[-10:])
print("Entanglement spectrum", LB**2)
```

    Energy -0.9540523283159128
    SigmaA (0.002106057508052831+0.000620591534160369j)
    SigmaB (0.0013787301648877973+0.0021790014315824j)
    (0.5000000000000001+0.8660254037844386j)
    Discarder weights [2.5578785504938368e-05, 2.5652207317813146e-05, 2.5711023633503407e-05, 2.5784364928780068e-05, 2.5843549794738243e-05, 2.5916815490194277e-05, 2.597636321475859e-05, 2.6049558175828367e-05, 2.6109463114646672e-05, 2.6182592153803667e-05]
    Entanglement spectrum [7.28641367e-01 1.36134701e-01 1.33994304e-01 5.88745928e-04
     2.17939471e-04 2.17230951e-04 1.01950640e-04 1.00357331e-04
     3.35546876e-06 4.85701633e-08]

#### Save to file

```python
# File_code = '{}J_{}g_{}theta_{}phi_{}Chi_{}delta_{}N'.format(J, g, theta, phi, chi, delta,N)
# !mkdir -p {'clock3/data_'+File_code}

# Outfile1 = './clock3/data_{}/Results.dat'.format(File_code)
# Outfile2 = './clock3/data_{}/EntanglementSpectrum.dat'.format(File_code)
# Outfile3 = './clock3/data_{}/DiscardedWeights.dat'.format(File_code)

# with open(Outfile1, 'w') as f1:
#     print('# ', File_code, file=f1)
#     print('# ', *res_names, file=f1)
#     print(*[res[key] for key in res_names], file=f1)
# np.savetxt(Outfile2, LB**2, header=File_code)
# np.savetxt(Outfile3, discarded_weights, header=File_code)
```

# Analysis of the 3-state clock model

\begin{equation}
H=J\sum_i (e^{i\theta}\sigma_i \sigma_{i+1}^\dagger + h.c.)+g\sum_i (e^{i\varphi} \tau_i+h.c.)
\end{equation}

```python
import glob
import re
```

#### Read data files

```python
datalist=[]
for name in glob.glob('clock3/data_*J_*g_*theta_*phi_*Chi_*delta_*N'):
    ES = np.loadtxt('{}/EntanglementSpectrum.dat'.format(name))
    EE = -np.sum(ES*np.log(ES))
    res = np.genfromtxt('{}/Results.dat'.format(name), dtype=(np.float64, np.complex128, np.complex128))
    m = re.match('clock3/data_(.*)J_(.*)g_(.*)theta_(.*)phi_(.*)Chi_(.*)delta_(.*)N', name)
    datalist.append(np.array([(*m.groups(), *res.item(), EE)],\
             dtype=[\
                    ('J', np.float64), ('g', np.float64), ('theta', np.float64),\
                    ('phi', np.float64), ('chi', np.int32), ('delta', np.float64), ('N', np.int32),\
                    ('Energy', np.float64), ('SigmaA', np.complex128), ('SigmaB', np.complex128),\
                    ('EE', np.float64)]))
datalist = sorted(datalist, key= lambda x: (x['phi'], x['J'], x['theta']))
data = np.array(datalist)
data = np.reshape(data, (3,11,11))
```

#### Plot

```python
for dataset in data:
    fig, axes = plt.subplots(1,2, figsize=(12,5))

    c1 = axes[0].pcolor(dataset['theta'], -dataset['g'], np.abs(dataset['SigmaA']))
    c2 = axes[1].pcolor(dataset['theta'], -dataset['g'], np.abs(dataset['EE']))
    axes[0].set_title(r'$|<\sigma>|$')
    axes[1].set_title('Entanglement Entropy')
    for ax in axes:
        ax.set_xlabel(r'$\theta$')
        ax.set_ylabel(r'$g$')
    fig.colorbar(c1, ax=axes[0])
    fig.colorbar(c2, ax=axes[1])
    plt.suptitle(r'$\varphi={}$'.format(dataset['phi'][0,0]))
    plt.show()
```

Results obtained with $\chi = 10$, $\delta = 0.01$, $N = 500$

### Results in literature

*Phase diagram of the
$\mathbb{Z}_3$ parafermionic chain with chiral interactions*
Ye Zhuang, Hitesh J. Changlani, Norm M. Tubman, and Taylor L. Hughes
Phys. Rev. B 92, 035154

# Read new files

```python
def Observable(operator, LB, GA, LA):
    return np.einsum('sab,tab,st,b,a->', GA, np.conj(GA), operator, LA**2, LB**2)

def Correlator(op1, op2, GA, GB, LA, LB, r, chi):
    G, Gn, L, Ln = GA, GB, LA, LB
    r = int(r)
    OR = np.einsum('a,st,sba,tca->bc', L**2, op2, G, np.conj(G))
    L, Ln, G, Gn = Ln, L, Gn, G
    for _ in range(r-1):
        OR = np.einsum('bc,sdb,sec,b,c->de',OR,G,np.conj(G),L,L)
        L, Ln, G, Gn = Ln, L, Gn, G
    return np.einsum('d,sdb,tdc,b,c,bc,st->', Ln**2, G, np.conj(G), L, L, OR, op1)

def String_correlator(op1, op2, opstr, GA, GB, LA, LB, r, chi):
    G, Gn, L, Ln = GA, GB, LA, LB
    r = int(r)
    ORight = np.einsum('a,st,sba,tca->bc', L**2, op2, G, np.conj(G))
    L, Ln, G, Gn = Ln, L, Gn, G
    for _ in range(r-1):
        ORight = np.einsum('bc,sdb,tec,b,c,st->de',OR,G,np.conj(G),L,L,opstr)
        L, Ln, G, Gn = Ln, L, Gn, G
    return np.einsum('d,sdb,tdc,b,c,bc,st->', Ln**2, G, np.conj(G), L, L, ORight, op1)
```

```python
data = []
folders=['phi0','phipi3', 'phitheta']
#folders=['phipi3_largerchi']
for folder in folders:
    datalist=[]
    for name in glob.glob('{}/data_*J_*g_*theta_*phi_*Chi_*delta_*N'.format(folder)):
        m = re.match('{}/data_(.*)J_(.*)g_(.*)theta_(.*)phi_(.*)Chi_(.*)delta_(.*)N'.format(folder), name)
        chi = int(m.groups()[4])
        Energy = np.loadtxt('{}/Energy.dat'.format(name))
        GA = np.loadtxt('{}/GammaA.dat'.format(name)).reshape(3,chi,chi)
        GB = np.loadtxt('{}/GammaB.dat'.format(name)).reshape(3,chi,chi)
        LA = np.loadtxt('{}/LambdaA.dat'.format(name))
        LB = np.loadtxt('{}/LambdaB.dat'.format(name))
        DW = np.loadtxt('{}/DiscardedWeights.dat'.format(name))
        ES = LB**2
        EE = -np.sum(ES*np.log(ES))
        SigmaA=Observable(sigma,LB,GA,LA)
        NNCorr=Correlator(sigma, sigma**2, GA, GB, LA, LB, 1, chi)

        datalist.append(np.array([(*m.groups(), Energy, GA, GB, LA, LB, EE, SigmaA, NNCorr, DW[-1])],\
                 dtype=[\
                        ('J', np.float64), ('g', np.float64), ('theta', np.float64),\
                        ('phi', np.float64), ('chi', np.int32), ('delta', np.float64), ('N', np.int32),\
                        ('Energy', np.float64), ('GammaA', np.complex128, (3,chi,chi)),\
                        ('GammaB', np.complex128, (3,chi,chi)),\
                        ('LambdaA', np.complex128, (chi)), ('LambdaB', np.complex128, (chi)),
                        ('EE', np.float64), ('SigmaA', np.complex128), ('NNCorr', np.complex128),
                        ('DW', np.float64)]))
    datalist = sorted(datalist, key= lambda x: (x['J'], x['theta']))
    data.append(np.array(datalist).reshape(21,21))
```

```python
for dataset in data:
    fig, axes = plt.subplots(1,2, figsize=(12,5))

    c1 = axes[0].pcolor(dataset['theta'], -dataset['g'], np.abs(dataset['NNCorr']))
    c2 = axes[1].pcolor(dataset['theta'], -dataset['g'], np.abs(dataset['EE']))
    axes[0].set_title(r'$|<\sigma_i\sigma_{i+1}^\dagger>|$')
    axes[1].set_title('Entanglement Entropy')
    for ax in axes:
        ax.set_xlabel(r'$\theta$')
        ax.set_ylabel(r'$g$')
    fig.colorbar(c1, ax=axes[0])
    fig.colorbar(c2, ax=axes[1])
    plt.suptitle(r'$\varphi={}$'.format(dataset['phi'][0,0]))
    plt.show()
    #the last one is theta=phi
```

```python
sel = data[0][15,13]
r = np.arange(1, 15)
y=np.array([Correlator(sigma, sigma**2, sel['GammaA'], sel['GammaB'], sel['LambdaA'], sel['LambdaB'], i, sel['chi']) for i in r])

angle=np.angle(y)
print(np.where(np.diff(angle)>0))
for i in np.where(np.diff(angle)>0)[0]:
    angle[i+1:]=angle[i+1:]-2*np.pi
plt.plot(r-1,angle)
plt.plot(np.angle(y), color='red')
plt.plot(r-1, -theta*r)
#plt.ylim(-np.pi, np.pi)
plt.suptitle(r'$\theta={}, g={}$'.format(sel['theta'], sel['g']))
plt.show()
```

```python

```


# Example of outputting results of mvpolyfit to C code

```python
# Setup ipython environment
%load_ext autoreload
%autoreload 2
%matplotlib inline
# Import libs
from positive import *
from matplotlib.pyplot import *
from numpy import *
```

    The autoreload extension is already loaded. To reload it, use:
      %reload_ext autoreload

### Create a fiducial mvpolyfit object. Call it "foo".

```python
x0 = linspace(-0.5,0.5,15)
y0 = array(x0)
u0 = array(x0)

# Set random seed so that we always get the same answers
random.seed( 30 )

x = x0 + 0.08*(random.random( x0.shape )-0.5)
y = y0 + 0.08*(random.random( y0.shape )-0.5)
X,Y = meshgrid(x,y)
zfun = lambda xx,yy: xx**2 + yy**2 + xx*yy + yy*xx**2

Z = zfun(X,Y) + 0.1*(random.random( X.shape )-0.5)

#
domain,scalar_range = ndflatten( [X,Y], Z )

foo = mvpolyfit( domain, scalar_range, basis_symbols=['00','11','01','100'], verbose = True );
foo.plot();

```

### We've printed the resulting fit function in various forms below

```python
alert('Python String',header=True)
print yellow('* IMPORTANT -- make sure that the precision input is consistent with the number of significant figures for your model\n')
print foo.__str_python__(precision=5)
alert('Latex String',header=True)
print yellow('* It can be useful for latex versions to be less precise\n')
print foo.__str_latex__(precision=2).replace(r'\\ \nonumber','').replace('\n','').replace(r'\quad','').replace(r'&','')
```

    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #
    (notebook)>> Python String
    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #

    * IMPORTANT -- make sure that the precision input is consistent with the number of significant figures for your model

    f = lambda x0,x1: 9.91444e-01*(x1*x1) + 9.93282e-01*(x0*x0) + 9.96038e-01*(x0*x1) + 1.03054e+00*(x1*x0*x0)

    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #
    (notebook)>> Latex String
    # -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~ #

    * It can be useful for latex versions to be less precise

    f(\vec{x})  \; = \;  9.91e-01\,{x1}^{2} \; + \; (9.93e-01)\,{x0}^{2}      \; + \; (9.96e-01)\,x0\,x1 \; + \; (1.03e+00)\,x1\,{x0}^{2}

\begin{align}
f(\vec{x})  \; = \;  1.02e+00\,{x1}^{2} \; + \; (9.78e-01)\,{x0}^{2}      \; + \; (9.80e-01)\,x0\,x1 \; + \; (9.27e-01)\,x1\,{x0}^{2}
\end{align}

### Note that the springs can be hacked for other purposes. For example, below I use the python string to construct a C function string.

```python
pystr = foo.__str_python__(precision=8)
# Only take the useful bits of this string
cstr = pystr.split(':')[-1]
print cyan('This will be added to C code: '),cstr
```

    This will be added to C code:   9.91443548e-01*(x1*x1) + 9.93282096e-01*(x0*x0) + 9.96038493e-01*(x0*x1) + 1.03053717e+00*(x1*x0*x0)

```python
C_template = r'''
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// function prototype, also called function declaration
float myfunction ( float x0, float x1 );

// main function, program starts from here
int main( int argc, char** argv )
{
    // function call
    float x0 = atof(argv[1]);
    float x1 = atof(argv[2]);
    float ans = myfunction ( x0,x1 ) ;
    printf ( "humboldt penguin says: %1.13f\n",ans );
}

float myfunction ( float x0, float x1 )   // function definition
{
    float p ;
    p = *MYCODE* ;
    return ( p ) ;
}
'''
```

### Put the fit function in the C Code

```python
C_code = C_template.replace(r'*MYCODE*',cstr)
```

### Write the code to a file

```python
from os.path import expanduser
fo = open(expanduser('~/Desktop/humboldt_penguin.c'),"w")
fo.write(C_code)
fo.close()
```

### Compile the C code and comare its output to the python code

Compile the code with:

```bash
gcc -o ~/Desktop/foo ~/Desktop/humboldt_penguin.c
```

Evalue the code with x0=1.1 and x1 = 3.14:

```bash
~/Desktop/foo 1.1 3.14
```

```bash
%%bash
# Compile
gcc -o ~/Desktop/foo ~/Desktop/humboldt_penguin.c
# Run with sample inputs
~/Desktop/foo 0.25 -0.4
```

    humboldt penguin says: 0.0953438282013

#### Evaluate the python model with the same inputs

```python
pyvalue = foo.eval( array([ [0.25], [-0.4] ]).T )[0]
print 'another humboldt penguin says: ',pyvalue
```

    another humboldt penguin says:  0.09534382004989973

```python
cvalue = 0.0953438282013
```

```python
print 'pyvalue-cvalue = ',pyvalue-cvalue
alert(yellow('This should be tiny!'))
```

    pyvalue-cvalue =  -8.15140026311223e-09
    (notebook)>> This should be tiny!

```bash
%%bash
# Clean up example files
rm ~/Desktop/foo ~/Desktop/humboldt_penguin.c
```