# Introduction to zfit

In this notebook, we will have a walk through the main components of zfit and their features. Especially the extensive model building part will be discussed separately.
zfit consists of 5 mostly independent parts. Other libraries can rely on this parts to do plotting or statistical inference, such as hepstats does. Therefore we will discuss two libraries in this tutorial: zfit to build models, data and a loss, minimize it and get a fit result and hepstats, to use the loss we built here and do inference.

## Data

This component in general plays a minor role in zfit: it is mostly to provide a unified interface for data.

Preprocessing is therefore not part of zfit and should be done beforehand. Python offers many great possibilities to do so (e.g. Pandas).

zfit `Data` can load data from various sources, most notably from Numpy, Pandas DataFrame, TensorFlow Tensor and ROOT (using uproot). It is also possible, for convenience, to convert it directly `to_pandas`. The constructors are named `from_numpy`, `from_root` etc.

```python
import zfit
from zfit import z
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
```

A `Data` needs not only the data itself but also the observables: the human readable string identifiers of the axes (corresponding to "columns" of a Pandas DataFrame). It is convenient to define the `Space` not only with the observable but also with a limit: this can directly be re-used as the normalization range in the PDF.

First, let's define our observables

```python
obs = zfit.Space('obs1', (-5, 10))
```

This `Space` has limits. Next to the effect of handling the observables, we can also play with the limits: multiple `Spaces` can be added to provide disconnected ranges. More importantly, `Space` offers functionality:
- limit1d: return the lower and upper limit in the 1 dimensional case (raises an error otherwise)
- rect_limits: return the n dimensional limits
- area(): calculate the area (e.g. distance between upper and lower)
- inside(): return a boolean Tensor corresponding to whether the value is _inside_ the `Space`
- filter(): filter the input values to only return the one inside

```python
size_normal = 10000
data_normal_np = np.random.normal(size=size_normal, scale=2)

data_normal = zfit.Data.from_numpy(obs=obs, array=data_normal_np)
```

The main functionality is
- nevents: attribute that returns the number of events in the object
- data_range: a `Space` that defines the limits of the data; if outside, the data will be cut
- n_obs: defines the number of dimensions in the dataset
- with_obs: returns a subset of the dataset with only the given obs
- weights: event based weights

Furthermore, `value` returns a Tensor with shape `(nevents, n_obs)`.

To retrieve values, in general `z.unstack_x(data)` should be used; this returns a single Tensor with shape (nevents) or a list of tensors if `n_obs` is larger then 1.

```python
print(f"We have {data_normal.nevents} events in our dataset with the minimum of {np.min(data_normal.unstack_x())}")  # remember! The obs cut out some of the data
```

    We have 9946 events in our dataset with the minimum of -4.978826801974078

```python
data_normal.n_obs
```

    1

## Model

Building models is by far the largest part of zfit. We will therefore cover an essential part, the possibility to build custom models, in an extra chapter. Let's start out with the idea that you define your parameters and your observable space; the latter is the expected input data.

There are two types of models in zfit:
- functions, which are rather simple and "underdeveloped"; their usage is often not required.
- PDF that are function which are normalized (over a specified range); this is the main model and is what we gonna use throughout the tutorials.

A PDF is defined by

\begin{align}
\mathrm{PDF}_{f(x)}(x; \theta) = \frac{f(x; \theta)}{\int_{a}^{b} f(x; \theta)}
\end{align}

where a and b define the normalization range (`norm_range`), over which (by inserting into the above definition) the integral of the PDF is unity.

zfit has a modular approach to things and this is also true for models. While the normalization itself (e.g. what are parameters, what is normalized data) will already be pre-defined in the model, models are composed of functions that are transparently called inside. For example, a Gaussian would usually be implemented by writing a Python function `def gauss(x, mu, sigma)`, which does not care about the normalization and then be wrapped in a PDF, where the normalization and what is a parameter is defined.

In principle, we can go far by using simply functions (e.g. [TensorFlowAnalysis/AmpliTF](https://github.com/apoluekt/AmpliTF) by Anton Poluektov uses this approach quite successfully for Amplitude Analysis), but this design has limitations for a more general fitting library such as zfit (or even [TensorWaves](https://github.com/ComPWA/tensorwaves), being built on top of AmpliTF).
The main thing is to keep track of the different ordering of the data and parameters, especially the dependencies.

Let's create a simple Gaussian PDF. We already defined the `Space` for the data before, now we only need the parameters. This are a different object than a `Space`.

### Parameter
A `Parameter` (there are different kinds actually, more on that later) takes the following arguments as input:
`Parameter(human readable name, initial value[, lower limit, upper limit])` where the limits are recommended but not mandatory. Furthermore, `step_size` can be given (which is useful to be around the given uncertainty, e.g. for large yields or small values it can help a lot to set this). Also, a `floating` argument is supported, indicating whether the parameter is allowed to float in the fit or not (just omitting the limits does _not_ make a parameter constant).

Parameters have a unique name. This is served as the identifier for e.g. fit results. However, a parameter _cannot_ be retrieved by its string identifier (its name) but the object itself should be used. In places where a parameter maps to something, the object itself is needed, not its name.

```python
mu = zfit.Parameter('mu', 1, -3, 3, step_size=0.2)
sigma_num = zfit.Parameter('sigma42', 1, 0.1, 10, floating=False)
```

These attributes can be changed:

```python
print(f"sigma is float: {sigma_num.floating}")
sigma_num.floating = True
print(f"sigma is float: {sigma_num.floating}")
```

    sigma is float: False
    sigma is float: True

*PITFALL NOTEBOOKS: since the parameters have a unique name, a second parameter with the same name cannot be created; the behavior is undefined and therefore it raises an error.
While this does not pose a problem in a normal Python script, it does in a Jupyter-like notebook, since it is an often practice to "rerun" a cell as an attempt to "reset" things. Bear in mind that this does not make sense, from a logic point of view. The parameter already exists. Best practice: write a small wrapper, do not rerun the parameter creation cell or simply rerun the notebook (restart kernel & run all). For further details, have a look at the discussion and arguments [here](https://github.com/zfit/zfit/issues/186)*

Now we have everything to create a Gaussian PDF:

```python
gauss = zfit.pdf.Gauss(obs=obs, mu=mu, sigma=sigma_num)
```

Since this holds all the parameters and the observables are well defined, we can retrieve them

```python
gauss.n_obs  # dimensions
```

    1

```python
gauss.obs
```

    ('obs1',)

```python
gauss.space
```

    <zfit Space obs=('obs1',), axes=(0,), limits=(array([[-5.]]), array([[10.]]))>

```python
gauss.norm_range
```

    <zfit Space obs=('obs1',), axes=(0,), limits=(array([[-5.]]), array([[10.]]))>

As we've seen, the `obs` we defined is the `space` of Gauss: this acts as the default limits whenever needed (e.g. for sampling). `gauss` also has a `norm_range`, which equals by default as well to the `obs` given, however, we can explicitly change that with `set_norm_range`.

We can also access the parameters of the PDF in two ways, depending on our intention:
either by _name_ (the parameterization name, e.g. `mu` and `sigma`, as defined in the `Gauss`), which is useful if we are interested in the parameter that _describes_ the shape

```python
gauss.params
```

    OrderedDict([('mu', <zfit.Parameter 'mu' floating=True value=1>),
                 ('sigma', <zfit.Parameter 'sigma42' floating=True value=1>)])

or to retrieve all the parameters that the PDF depends on. As this now may sounds trivial, we will see later that models can depend on other models (e.g. sums) and parameters on other parameters. There is one function that automatically retrieves _all_ dependencies, `get_params`. It takes three arguments to filter:
- floating: whether to filter only floating parameters, only non-floating or don't discriminate
- is_yield: if it is a yield, or not a yield, or both
- extract_independent: whether to recursively collect all parameters. This, and the explanation for why independent, can be found later on in the `Simultaneous` tutorial.

Usually, the default is exactly what we want if we look for _all free parameters that this PDF depends on_.

```python
gauss.get_params()
```

    OrderedSet([<zfit.Parameter 'mu' floating=True value=1>, <zfit.Parameter 'sigma42' floating=True value=1>])

The difference will also be clear if we e.g. use the same parameter twice:

```python
gauss_only_mu = zfit.pdf.Gauss(obs=obs, mu=mu, sigma=mu)
print(f"params={gauss_only_mu.params}")
print(f"get_params={gauss_only_mu.get_params()}")
```

    params=OrderedDict([('mu', <zfit.Parameter 'mu' floating=True value=1>), ('sigma', <zfit.Parameter 'mu' floating=True value=1>)])
    get_params=OrderedSet([<zfit.Parameter 'mu' floating=True value=1>])

## Functionality

PDFs provide a few useful methods. The main features of a zfit PDF are:

- `pdf`: the normalized value of the PDF. It takes an argument `norm_range` that can be set to `False`, in which case we retrieve the unnormalized value
- `integrate`: given a certain range, the PDF is integrated. As `pdf`, it takes a `norm_range` argument that integrates over the unnormalized `pdf` if set to `False`
- `sample`: samples from the pdf and returns a `Data` object

```python
integral = gauss.integrate(limits=(-1, 3))  # corresponds to 2 sigma integral
integral
```

    <tf.Tensor: shape=(1,), dtype=float64, numpy=array([0.95449974])>

### Tensors

As we see, many zfit functions return Tensors. This is however no magical thing! If we're outside of models, than we can always safely convert them to a numpy array by calling `zfit.run(...)` on it (or any structure containing potentially multiple Tensors). However, this may not even be required often! They can be added just like numpy arrays and interact well with Python and Numpy:

```python
np.sqrt(integral)
```

    array([0.97698502])

They also have shapes, dtypes, can be slices etc. So do not convert them except you need it. More on this can be seen in the talk later on about zfit and TensorFlow 2.0.

```python
sample = gauss.sample(n=1000)  # default space taken as limits
sample
```

    <zfit.core.data.SampleData at 0x7f90f5f2e278>

```python
sample.unstack_x()[:10]
```

    <tf.Tensor: shape=(10,), dtype=float64, numpy=
    array([3.53428249, 2.21623497, 0.74033309, 0.94986531, 1.16898151,
           1.3350581 , 0.2433266 , 1.68229119, 1.81464923, 1.35160915])>

```python
sample.n_obs
```

    1

```python
sample.obs
```

    ('obs1',)

We see that sample returns also a zfit `Data` object with the same space as it was sampled in. This can directly be used e.g.

```python
probs = gauss.pdf(sample)
probs[:10]
```

    <tf.Tensor: shape=(10,), dtype=float64, numpy=
    array([0.01607914, 0.19041445, 0.38571675, 0.39844123, 0.3932869 ,
           0.37716576, 0.29962732, 0.31609921, 0.28628564, 0.37502859])>

**NOTE**: In case you want to do this repeatedly (e.g. for toy studies), there is a way more efficient way (see later on)

## Plotting

so far, we have a dataset and a PDF. Before we go for fitting, we can make a plot. This functionality is not _directly_ provided in zfit (but can be added to [zfit-physics](https://github.com/zfit/zfit-physics)). It is however simple enough to do it:

```python
def plot_model(model, data, scale=1, plot_data=True):  # we will use scale later on

    nbins = 50

    lower, upper = data.data_range.limit1d
    x = tf.linspace(lower, upper, num=1000)  # np.linspace also works
    y = model.pdf(x) * size_normal / nbins * data.data_range.area()
    y *= scale
    plt.plot(x, y)
    data_plot = zfit.run(z.unstack_x(data))  # we could also use the `to_pandas` method
    if plot_data:
        plt.hist(data_plot, bins=nbins)
```

```python
plot_model(gauss, data_normal)
```

We can of course do better (and will see that later on, continuously improve the plots), but this is quite simple and gives us the full power of matplotlib.

### Different models

zfit offers a selection of predefined models (and extends with models from zfit-physics that contain physics specific models such as ARGUS shaped models).

```python
print(zfit.pdf.__all__)
```

    ['BasePDF', 'BaseFunctor', 'Exponential', 'CrystalBall', 'DoubleCB', 'Gauss', 'Uniform', 'TruncatedGauss', 'WrapDistribution', 'Cauchy', 'Chebyshev', 'Legendre', 'Chebyshev2', 'Hermite', 'Laguerre', 'RecursivePolynomial', 'ProductPDF', 'SumPDF', 'GaussianKDE1DimV1', 'ZPDF', 'SimplePDF', 'SimpleFunctorPDF']

To create a more realistic model, we can build some components for a mass fit with a
- signal component: CrystalBall
- combinatorial background: Exponential
- partial reconstructed background on the left: Kernel Density Estimation

```python
mass_obs = zfit.Space('mass', (0, 1000))
```

```python
# Signal component

mu_sig = zfit.Parameter('mu_sig', 400, 100, 600)
sigma_sig = zfit.Parameter('sigma_sig', 50, 1, 100)
alpha_sig = zfit.Parameter('alpha_sig', 300, 100, 400)
n_sig = zfit.Parameter('n sig', 4, 0.1, 30)
signal = zfit.pdf.CrystalBall(obs=mass_obs, mu=mu_sig, sigma=sigma_sig, alpha=alpha_sig, n=n_sig)
```

```python
# combinatorial background

lam = zfit.Parameter('lambda', -0.01, -0.05, -0.001)
comb_bkg = zfit.pdf.Exponential(lam, obs=mass_obs)
```

```python
part_reco_data = np.random.normal(loc=200, scale=150, size=700)
part_reco_data = zfit.Data.from_numpy(obs=mass_obs, array=part_reco_data)  # we don't need to do this but now we're sure it's inside the limits

part_reco = zfit.pdf.GaussianKDE1DimV1(obs=mass_obs, data=part_reco_data, bandwidth='adaptive')
```

## Composing models

We can also compose multiple models together. Here we'll stick to one dimensional models, the extension to multiple dimensions is explained in the "custom models tutorial".

Here we will use a `SumPDF`. This takes pdfs and fractions. If we provide n pdfs and:
- n - 1 fracs: the nth fraction will be 1 - sum(fracs)
- n fracs: no normalization attempt is done by `SumPDf`. If the fracs are not implicitly normalized, this can lead to bad fitting
  behavior if there is a degree of freedom too much

```python
sig_frac = zfit.Parameter('sig_frac', 0.3, 0, 1)
comb_bkg_frac = zfit.Parameter('comb_bkg_frac', 0.25, 0, 1)
model = zfit.pdf.SumPDF([signal, comb_bkg, part_reco], [sig_frac, comb_bkg_frac])
```

In order to have a corresponding data sample, we can just create one. Since we want to fit to this dataset later on, we will create it with slightly different values. Therefore, we can use the ability of a parameter to be set temporarily to a certain value with

```python
print(f"before: {sig_frac}")
with sig_frac.set_value(0.25):
    print(f"new value: {sig_frac}")
print(f"after 'with': {sig_frac}")
```

    before: <zfit.Parameter 'sig_frac' floating=True value=0.3>
    new value: <zfit.Parameter 'sig_frac' floating=True value=0.25>
    after 'with': <zfit.Parameter 'sig_frac' floating=True value=0.3>

While this is useful, it does not fully scale up. We can use the `zfit.param.set_values` helper therefore.
(_Sidenote: instead of a list of values, we can also use a `FitResult`, the given parameters then take the value from the result_)

```python
with zfit.param.set_values([mu_sig, sigma_sig, sig_frac, comb_bkg_frac, lam], [370, 34, 0.18, 0.15, -0.006]):
    data = model.sample(n=10000)
```

```python
plot_model(model, data);
```

Plotting the components is not difficult now: we can either just plot the pdfs separately (as we still can access them) or in a generalized manner by accessing the `pdfs` attribute:

```python
def plot_comp_model(model, data):
    for mod, frac in zip(model.pdfs, model.params.values()):
        plot_model(mod, data, scale=frac, plot_data=False)
    plot_model(model, data)
```

```python
plot_comp_model(model, data)
```

Now we can add legends etc. Btw, did you notice that actually, the `frac` params are zfit `Parameters`? But we just used them as if they were Python scalars and it works.

```python
print(model.params)
```

    OrderedDict([('frac_0', <zfit.Parameter 'sig_frac' floating=True value=0.3>), ('frac_1', <zfit.Parameter 'comb_bkg_frac' floating=True value=0.25>), ('frac_2', <zfit.ComposedParameter 'Composed_autoparam_2' params=OrderedDict([('param_0', <zfit.Parameter 'sig_frac' floating=True value=0.3>), ('param_1', <zfit.Parameter 'comb_bkg_frac' floating=True value=0.25>)]) value=0.45>)])

### Extended PDFs

So far, we have only looked at normalized PDFs that do contain information about the shape but not about the _absolute_ scale. We can make a PDF extended by adding a yield to it.

The behavior of the new, extended PDF does **NOT change**, any methods we called before will act the same. Only exception, some may require an argument _less_ now. All the methods we used so far will return the same values. What changes is that the flag `model.is_extended` now returns `True`. Furthermore, we have now a few more methods that we can use which would have raised an error before:
- `get_yield`: return the yield parameter (notice that the yield is _not_ added to the shape parameters `params`)
- `ext_{pdf,integrate}`: these methods return the same as the versions used before, however, multiplied by the yield
- `sample` is still the same, but does not _require_ the argument `n` anymore. By default, this will now equal to a _poissonian sampled_ n around the yield.

The `SumPDF` now does not strictly need `fracs` anymore: if _all_ input PDFs are extended, the sum will be as well and use the (normalized) yields as fracs

The preferred way to create an extended PDf is to use `PDF.create_extended(yield)`. However, since this relies on copying the PDF (which may does not work for different reasons), there is also a `set_yield(yield)` method that sets the yield in-place. This won't lead to ambiguities, as everything is supposed to work the same.

```python
yield_model = zfit.Parameter('yield_model', 10000, 0, 20000, step_size=10)
model_ext = model.create_extended(yield_model)
```

alternatively, we can create the models as extended and sum them up

```python
sig_yield = zfit.Parameter('sig_yield', 2000, 0, 10000, step_size=1)
sig_ext = signal.create_extended(sig_yield)

comb_bkg_yield = zfit.Parameter('comb_bkg_yield', 6000, 0, 10000, step_size=1)
comb_bkg_ext = comb_bkg.create_extended(comb_bkg_yield)

part_reco_yield = zfit.Parameter('part_reco_yield', 2000, 0, 10000, step_size=1)
part_reco.set_yield(part_reco_yield)  # unfortunately, `create_extended` does not work here. But no problem, it won't change anyting.
part_reco_ext = part_reco
```

```python
model_ext_sum = zfit.pdf.SumPDF([sig_ext, comb_bkg_ext, part_reco_ext])
```

# Loss

A loss combines the model and the data, for example to build a likelihood. Furthermore, it can contain constraints, additions to the likelihood. Currently, if the `Data` has weights, these are automatically taken into account.

```python
nll_gauss = zfit.loss.UnbinnedNLL(gauss, data_normal)
```

The loss has several attributes to be transparent to higher level libraries. We can calculate the value of it using `value`.

```python
nll_gauss.value()
```

    <tf.Tensor: shape=(), dtype=float64, numpy=33016.127669195615>

Notice that due to graph building, this will take significantly longer on the first run. Rerun the cell above and it will be way faster.

Furthermore, the loss also provides a possibility to calculate the gradients or, often used, the value and the gradients.

We can access the data and models (and possible constraints)

```python
nll_gauss.model
```

    [<zfit.Gauss  params=[mu, sigma42] dtype=float64>0]

```python
nll_gauss.data
```

    [<zfit.core.data.Data at 0x7f91d4f5ed30>]

```python
nll_gauss.constraints
```

    []

Similar to the models, we can also get the parameters via `get_params`.

```python
nll_gauss.get_params()
```

    OrderedSet([<zfit.Parameter 'mu' floating=True value=1>, <zfit.Parameter 'sigma42' floating=True value=1>])

### Extended loss

More interestingly, we can now build a loss for our composite sum model using the sampled data. Since we created an extended model, we can now also create an extended likelihood, taking into account a Poisson term to match the yield to the number of events.

```python
nll = zfit.loss.ExtendedUnbinnedNLL(model_ext_sum, data)
```

```python
nll.get_params()
```

    OrderedSet([<zfit.Parameter 'sig_yield' floating=True value=2000>, <zfit.Parameter 'comb_bkg_yield' floating=True value=6000>, <zfit.Parameter 'part_reco_yield' floating=True value=2000>, <zfit.Parameter 'alpha_sig' floating=True value=300>, <zfit.Parameter 'mu_sig' floating=True value=400>, <zfit.Parameter 'n sig' floating=True value=4>, <zfit.Parameter 'sigma_sig' floating=True value=50>, <zfit.Parameter 'lambda' floating=True value=-0.01>])

# Minimization

While a loss is interesting, we usually want to minimize it. Therefore we can use the minimizers in zfit, most notably `Minuit`, a wrapper around the [iminuit minimizer](https://github.com/scikit-hep/iminuit).

The philosophy is to create a minimizer instance that is mostly _stateless_, e.g. does not remember the position (there are considerations to make it possible to have a state, in case you feel interested, [contact us](https://github.com/zfit/zfit#contact))

Given that iminuit provides us with a very reliable and stable minimizer, it is usually recommended to use this. Others are implemented as well and could easily be wrapped, however, the convergence is usually not as stable.

Minuit has a few options:
- `tolerance`: the Estimated Distance to Minimum (EDM) criteria for convergence (default 1e-3)
- `verbosity`: between 0 and 10, 5 is normal, 7 is verbose, 10 is maximum
- `use_minuit_grad`: if True, uses the Minuit numerical gradient instead of the TensorFlow gradient. This is usually more stable for smaller fits; furthermore the TensorFlow gradient _can_ (experience based) sometimes be wrong.

```python
minimizer = zfit.minimize.Minuit(use_minuit_grad=True)
```

For the minimization, we can call `minimize`, which takes a
- loss as we created above
- optionally: the parameters to minimize

By default, `minimize` uses all the free floating parameters (obtained with `get_params`). We can also explicitly specify which ones to use by giving them (or better, objects that depend on them) to `minimize`; note however that non-floating parameters, even if given explicitly to `minimize` won 't be minimized.

## Pre-fit parts of the PDF

Before we want to fit the whole PDF however, it can be useful to pre-fit it. A way can be to fix the combinatorial background by fitting the exponential to the right tail.

Therefore we create a new data object with an additional cut and furthermore, set the normalization range of the background pdf to the range we are interested in.

```python
values = z.unstack_x(data)
obs_right_tail = zfit.Space('mass', (700, 1000))
data_tail = zfit.Data.from_tensor(obs=obs_right_tail, tensor=values)
with comb_bkg.set_norm_range(obs_right_tail):
    nll_tail = zfit.loss.UnbinnedNLL(comb_bkg, data_tail)
    minimizer.minimize(nll_tail)
```

    ------------------------------------------------------------------
    | FCN = 313                     |      Ncalls=17 (17 total)      |
    | EDM = 1.65e-08 (Goal: 0.001)  |            up = 0.5            |
    ------------------------------------------------------------------
    |  Valid Min.   | Valid Param.  | Above EDM | Reached call limit |
    ------------------------------------------------------------------
    |     True      |     True      |   False   |       False        |
    ------------------------------------------------------------------
    | Hesse failed  |   Has cov.    | Accurate  | Pos. def. | Forced |
    ------------------------------------------------------------------
    |     False     |     True      |   True    |   True    | False  |
    ------------------------------------------------------------------

Since we now fit the lambda parameter of the exponential, we can fix it.

```python
lam.floating = False
lam
```

    <zfit.Parameter 'lambda' floating=False value=-0.008049>

```python
result = minimizer.minimize(nll)
```

    ------------------------------------------------------------------
    | FCN = -1.954e+04              |     Ncalls=167 (167 total)     |
    | EDM = 0.000128 (Goal: 0.001)  |            up = 0.5            |
    ------------------------------------------------------------------
    |  Valid Min.   | Valid Param.  | Above EDM | Reached call limit |
    ------------------------------------------------------------------
    |     True      |     True      |   False   |       False        |
    ------------------------------------------------------------------
    | Hesse failed  |   Has cov.    | Accurate  | Pos. def. | Forced |
    ------------------------------------------------------------------
    |     False     |     True      |   True    |   True    | False  |
    ------------------------------------------------------------------

```python
plot_comp_model(model_ext_sum, data)
```

# Fit result

The result of every minimization is stored in a `FitResult`. This is the last stage of the zfit workflow and serves as the interface to other libraries. Its main purpose is to store the values of the fit, to reference to the objects that have been used and to perform (simple) uncertainty estimation.

```python
print(result)
```

    FitResult of
    <ExtendedUnbinnedNLL model=[<zfit.SumPDF  params=[Composed_autoparam_5, Composed_autoparam_6, Composed_autoparam_7] dtype=float64>0] data=[<zfit.core.data.SampleData object at 0x7f90f5454438>] constraints=[]>
    with
    <Minuit strategy=PushbackStrategy tolerance=0.001>

    ╒═════════╤═════════════╤══════════════════╤═════════╤═════════════╕
    │ valid   │ converged   │ param at limit   │ edm     │ min value   │
    ╞═════════╪═════════════╪══════════════════╪═════════╪═════════════╡
    │ True    │ True        │ False            │ 0.00013 │ -1.954e+04  │
    ╘═════════╧═════════════╧══════════════════╧═════════╧═════════════╛

    Parameters
    name               value    at limit
    ---------------  -------  ----------
    sig_yield           1851       False
    comb_bkg_yield      1131       False
    part_reco_yield     7018       False
    alpha_sig            300       False
    mu_sig             369.7       False
    n sig                  4       False
    sigma_sig          34.09       False

This gives an overview over the whole result. Often we're mostly interested in the parameters and their values, which we can access with a `params` attribute.

```python
print(result.params)
```

    name               value    at limit
    ---------------  -------  ----------
    sig_yield           1851       False
    comb_bkg_yield      1131       False
    part_reco_yield     7018       False
    alpha_sig            300       False
    mu_sig             369.7       False
    n sig                  4       False
    sigma_sig          34.09       False

This is a `dict` which stores any knowledge about the parameters and can be accessed by the parameter (object) itself:

```python
result.params[mu_sig]
```

    {'value': 369.7337120757637}

'value' is the value at the minimum. To obtain other information about the minimization process, `result` contains more attributes:
- fmin: the function minimum
- edm: estimated distance to minimum
- info: contains a lot of information, especially the original information returned by a specific minimizer
- converged: if the fit converged

```python
result.fmin
```

    -19539.388894488584

## Estimating uncertainties

The `FitResult` has mainly two methods to estimate the uncertainty:
- a profile likelihood method (like MINOS)
- Hessian approximation of the likelihood (like HESSE)

When using `Minuit`, this uses (currently) it's own implementation. However, zfit has its own implementation, which are likely to become the standard and can be invoked by changing the method name.

Hesse is also [on the way to implement](https://github.com/zfit/zfit/pull/244) the [corrections for weights](https://inspirehep.net/literature/1762842).

We can explicitly specify which parameters to calculate, by default it does for all.

```python
result.hesse()
```

    OrderedDict([(<zfit.Parameter 'sig_yield' floating=True value=1850>,
                  {'error': 73.52924652265973}),
                 (<zfit.Parameter 'comb_bkg_yield' floating=True value=1130>,
                  {'error': 79.49051306516832}),
                 (<zfit.Parameter 'part_reco_yield' floating=True value=7020>,
                  {'error': 136.98379193128127}),
                 (<zfit.Parameter 'alpha_sig' floating=True value=300>,
                  {'error': 141.4213562373095}),
                 (<zfit.Parameter 'mu_sig' floating=True value=369.7>,
                  {'error': 1.3913704142629884}),
                 (<zfit.Parameter 'n sig' floating=True value=4>,
                  {'error': 10.069756698215553}),
                 (<zfit.Parameter 'sigma_sig' floating=True value=34.09>,
                  {'error': 1.3407261987832484})])

```python
# result.hesse(method='hesse_np')
```

We get the result directly returned. This is also added to `result.params` for each parameter and is nicely displayed with an added column

```python
print(result.params)
```

    name               value    minuit_hesse    at limit
    ---------------  -------  --------------  ----------
    sig_yield           1851     +/-      69       False
    comb_bkg_yield      1131     +/-      75       False
    part_reco_yield     7018     +/- 1.2e+02       False
    alpha_sig            300     +/- 1.4e+02       False
    mu_sig             369.7     +/-     1.4       False
    n sig                  4     +/-      10       False
    sigma_sig          34.09     +/-     1.3       False

```python
errors, new_result = result.errors(params=[sig_yield, part_reco_yield, mu_sig])  # just using three for speed reasons
```

    /home/user/.local/lib/python3.6/site-packages/zfit/minimizers/fitresult.py:359: FutureWarning: 'minuit_minos' will be changed as the default errors method to a custom implementationwith the same functionality. If you want to make sure that 'minuit_minos' will be used in the future, add it explicitly as in `errors(method='minuit_minos')`
      "in the future, add it explicitly as in `errors(method='minuit_minos')`", FutureWarning)

```python
# errors, new_result = result.errors(params=[yield_model, sig_frac, mu_sig], method='zfit_error')
```

```python
print(errors)
```

    OrderedDict([(<zfit.Parameter 'sig_yield' floating=True value=1851>, MError(name='sig_yield', is_valid=True, lower=-73.19610573010954, upper=73.2494131480733, lower_valid=True, upper_valid=True, at_lower_limit=False, at_upper_limit=False, at_lower_max_fcn=False, at_upper_max_fcn=False, lower_new_min=False, upper_new_min=False, nfcn=208, min=1850.6452612293656)), (<zfit.Parameter 'part_reco_yield' floating=True value=7018>, MError(name='part_reco_yield', is_valid=True, lower=-134.46090913541406, upper=138.70099174669127, lower_valid=True, upper_valid=True, at_lower_limit=False, at_upper_limit=False, at_lower_max_fcn=False, at_upper_max_fcn=False, lower_new_min=False, upper_new_min=False, nfcn=204, min=7017.782731457284)), (<zfit.Parameter 'mu_sig' floating=True value=369.7>, MError(name='mu_sig', is_valid=True, lower=-1.3846589189505978, upper=1.391857347531778, lower_valid=True, upper_valid=True, at_lower_limit=False, at_upper_limit=False, at_lower_max_fcn=False, at_upper_max_fcn=False, lower_new_min=False, upper_new_min=False, nfcn=131, min=369.7337120757637))])

```python
print(result.params)
```

    name               value    minuit_hesse         minuit_minos    at limit
    ---------------  -------  --------------  -------------------  ----------
    sig_yield           1851     +/-      69  -     73   +     73       False
    comb_bkg_yield      1131     +/-      75                            False
    part_reco_yield     7018     +/- 1.2e+02  -1.3e+02   +1.4e+02       False
    alpha_sig            300     +/- 1.4e+02                            False
    mu_sig             369.7     +/-     1.4  -    1.4   +    1.4       False
    n sig                  4     +/-      10                            False
    sigma_sig          34.09     +/-     1.3                            False

#### What is 'new_result'?

When profiling a likelihood, such as done in the algorithm used in `errors`, a new minimum can be found. If this is the case, this new minimum will be returned, otherwise `new_result` is `None`. Furthermore, the current `result` would be rendered invalid by setting the flag `valid` to `False`. _Note_: this behavior only applies to the zfit internal error estimator.

### A simple profile

There is no default function (yet) for simple profiling plot. However, again, we're in Python and it's simple enough to do that for a parameter. Let's do it for `sig_yield`

```python
x = np.linspace(1600, 2000, num=50)
y = []
sig_yield.floating = False
for val in x:
    sig_yield.set_value(val)
    y.append(nll.value())

sig_yield.floating = True
zfit.param.set_values(nll.get_params(), result)
```

```python
plt.plot(x, y)
```

We can also access the covariance matrix of the parameters

```python
result.covariance()
```

    array([[ 4.80313887e+03,  1.02095082e+03, -3.43531769e+03,
             0.00000000e+00, -2.08964215e+01,  0.00000000e+00,
             4.67706435e+01],
           [ 1.02095082e+03,  5.63159948e+03, -5.91552419e+03,
             0.00000000e+00, -7.87129146e+00,  0.00000000e+00,
             1.77558437e+01],
           [-3.43531769e+03, -5.91552419e+03,  1.46369813e+04,
             0.00000000e+00,  3.07633305e+01,  0.00000000e+00,
            -6.37418378e+01],
           [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
             2.00000000e+04,  0.00000000e+00,  0.00000000e+00,
             0.00000000e+00],
           [-2.08964215e+01, -7.87129146e+00,  3.07633305e+01,
             0.00000000e+00,  1.93158341e+00,  0.00000000e+00,
            -4.28578345e-01],
           [ 0.00000000e+00,  0.00000000e+00,  0.00000000e+00,
             0.00000000e+00,  0.00000000e+00,  1.01400000e+02,
             0.00000000e+00],
           [ 4.67706435e+01,  1.77558437e+01, -6.37418378e+01,
             0.00000000e+00, -4.28578345e-01,  0.00000000e+00,
             1.74205276e+00]])

# End of zfit

This is where zfit finishes and other libraries take over.

# Beginning of hepstats

`hepstats` is a library containing statistical tools and utilities for high energy physics. In particular you do statistical inferences using the models and likelhoods function constructed in `zfit`.

Short example: let's compute for instance a confidence interval at 68 % confidence level on the mean of the gaussian defined above.

```python
from hepstats.hypotests.parameters import POIarray
from hepstats.hypotests.calculators import AsymptoticCalculator
from hepstats.hypotests import ConfidenceInterval
```

```python
calculator = AsymptoticCalculator(input=result, minimizer=minimizer)
```

```python
value = result.params[mu_sig]["value"]
error = result.params[mu_sig]["minuit_hesse"]["error"]

mean_scan = POIarray(mu_sig, np.linspace(value - 1.5*error, value + 1.5*error, 10))
```

```python
ci = ConfidenceInterval(calculator, mean_scan)
```

```python
ci.interval()
```

    Confidence interval on mu_sig:
    	368.3536149718213 < mu_sig < 371.12167557864825 at 68.0% C.L.

    {'observed': 369.7420306479183,
     'upper': 371.12167557864825,
     'lower': 368.3536149718213}

```python
from utils import one_minus_cl_plot

ax = one_minus_cl_plot(ci)
ax.set_xlabel("mean")
```

There will be more of `hepstats` later.


```python
# Tested on python 3.6.4
%matplotlib inline

import numpy as np # 1.13.3
from scipy.integrate import odeint # 1.0.0
import scipy.optimize as op
import scipy.stats as stats
import matplotlib.pyplot as plt # 2.1.1
from matplotlib.ticker import AutoMinorLocator
from matplotlib.ticker import MaxNLocator

import pandas as pd # 0.22.0
import emcee # 2.2.1
import corner # 2.0.1
import progressbar # 3.34.3
import seaborn as sns # 0.8.1
from cycler import cycler # 0.10.0

print('emcee version', emcee.__version__)

# Directories defined here
DIR_DATA = './data/'
DIR_PLOTS = './plots/'
DIR_OUT = './output/'
```

    emcee version 2.2.1

This jupyter notebook analyses TXTL dynamics from the 2018 Swank et al. paper. The code in this notebook requires the following data files, which are located in `DIR_DATA`:

    dynamics_chip.csv
    dynamics_PR.csv

The results are used to generate Supplementary Figure S3. Plots are written into `DIR_PLOTS`.

```python
def plotlin(data,name,DIR_PLOTS):

    plt.close("all")

    my_dpi=150

    figure_options={'figsize':(8.27,5.83)} #figure size in inches. A4=11.7x8.3. A5=8.27,5.83
    font_options={'size':'28','family':'sans-serif','sans-serif':'Arial'}
    plt.rc('figure', **figure_options)
    plt.rc('font', **font_options)

    current_palette=sns.color_palette("deep", 4)
    plt.rc('axes',prop_cycle=(cycler('color',current_palette)))
    f, axarr=plt.subplots()
    plt.subplots_adjust(left=0.25,bottom=0.2,right=0.95,top=0.95)

    # Plot data
    sns.regplot(x='init',y='fin',data=data,ci=95);
    formatplot(axarr,'Initial rate (RFU/h)','Final level (RFU)', xlim=False,ylim=False)
    plt.savefig(DIR_PLOTS+name+'.pdf',dpi=my_dpi,transparent=True)

def plotlinPR(data,name,DIR_PLOTS):

    plt.close("all")

    my_dpi=150

    figure_options={'figsize':(8.27,5.83)} #figure size in inches. A4=11.7x8.3. A5=8.27,5.83
    font_options={'size':'28','family':'sans-serif','sans-serif':'Arial'}
    plt.rc('figure', **figure_options)
    plt.rc('font', **font_options)

    current_palette=sns.color_palette("deep", 4)
    plt.rc('axes',prop_cycle=(cycler('color',current_palette)))
    f, axarr=plt.subplots()
    plt.subplots_adjust(left=0.25,bottom=0.2,right=0.95,top=0.95)

    # Plot data
    sns.regplot(x='Initial Rate',y='Final Level',data=df2,ci=95);
    formatplot(axarr,'Initial rate (RFU/h)','Final level (RFU)', xlim=False,ylim=False)
    plt.savefig(DIR_PLOTS+name+'.pdf',dpi=my_dpi,transparent=True)

def formatplot(ax,xlabel,ylabel,xlim,ylim,logx=False,logy=False,logxy=False,symlogx=False):

    ######### SET TITLES AND LABLES #########

    #ax.set_title('Plot title')
    if xlabel!=False:
        ax.set_xlabel(xlabel, labelpad=12)
    if ylabel!=False:
        ax.set_ylabel(ylabel, labelpad=12)

    ######### SET AXES LIMITS #########

    if xlim!=False:
        ax.set_xlim(xlim)
    if ylim!=False:
        ax.set_ylim(ylim)

    ######### SET TICK VALUES #########

    #ax.set_xticks([0,0.5,1])
    #	ax.set_yticks([0,2,4,6,8])

    ######### SET LINE THICKNESSES #########

    #ax.xaxis.set_major_formatter(mpl.ticker.FormatStrFormatter("%1.e"))
    #ax.axhline(linewidth=2, color='k')
    #ax.axvline(linewidth=2, color='k')
    ax.spines['bottom'].set_linewidth(2)
    ax.spines['top'].set_linewidth(2)
    ax.spines['left'].set_linewidth(2)
    ax.spines['right'].set_linewidth(2)

    ######### SET TICKS #########

    if logx==True:

        ax.set_xscale("log")

    elif logy==True:

        ax.set_yscale("log")

    elif logxy==True:

        ax.set_xscale("log")
        ax.set_yscale("log")

    elif symlogx==True:

        ax.set_xscale("symlog",linthreshx=1e-4)
        ax.set_yscale("log")

    else:
        minorLocatorx=AutoMinorLocator(2) # Number of minor intervals per major interval
        minorLocatory=AutoMinorLocator(2)
        ax.xaxis.set_minor_locator(minorLocatorx)
        ax.yaxis.set_minor_locator(minorLocatory)

    ax.tick_params(which='major', width=2, length=8, pad=9,direction='in',top='on',right='on')
    ax.tick_params(which='minor', width=2, length=4, pad=9,direction='in',top='on',right='on')
```

Our thermodynamic models calculate RNAP occupancies, and the validity of their comparisons with experiments relies on the proportionality between occupancy, transcription rate, and translation rate:

\begin{equation}
y=Ap_{bound}.
\end{equation}

In our experiments we measure dynamic GFP production, but generally report only the final level. We can check to ensure that the final level (whose value is determined by cell-free exhaustion) is related to the initial GFP production rate (which is proportional to translation rate). A linear relationship between the two quantities would validate our use of final levels (and fold repressions calculated from those quantities) as a proxy to measure translation rate.

```python
# Load timecourse data
df=pd.read_csv('data/dynamics_chip.csv',delimiter=',')

# Plot timecourse data
init=np.zeros(df.shape[0]*(df.shape[1]-1))
fin=np.zeros(df.shape[0]*(df.shape[1]-1))

d={'init': init, 'fin': fin}
dataF=pd.DataFrame(data=d)
i=0
for k in range((df.shape[1]-1)):
    dataF['init'].iloc[i]=df.iloc[1,k+1]/df.iloc[1,0]*60
    dataF['fin'].iloc[i]=df.iloc[-1,k+1]
    i+=1

# Uncomment this to look at time courses
#f,ax=plt.subplots()
#i=0
#for k in range((df.shape[1]-1)):
#    ax.plot(df.iloc[:,0],df.iloc[:,k+1],'o-');
#    dataF['init'].iloc[i]=df.iloc[1,k+1]/df.iloc[1,0]*60
#    dataF['fin'].iloc[i]=df.iloc[-1,k+1]
#    i+=1
#plt.show()

plotlin(dataF,'rates_timecoursechip',DIR_PLOTS)
```

```python
# Load and plot plate reader ZF data (orthogonality matrix)
df2=pd.read_csv(DIR_DATA+'dynamics_PR.csv',delimiter=',')
plotlinPR(df2,'rates_PR',DIR_PLOTS)
```

We observe a linear relationship between initial rates and final levels both on the plate reader as well as on chip, thus validating our use of the final level as a proxy for translation rate.

```python

```


# Tutorial 3: Dimensionality Reduction & Reconstruction
**Week 1, Day 5: Dimensionality Reduction**

**By Neuromatch Academy**

__Content creators:__ Alex Cayco Gajic, John Murray

__Content reviewers:__ Roozbeh Farhoudi, Matt Krause, Spiros Chavlis, Richard Gao, Michael Waskom,  Siddharth Suresh, Natalie Schaworonkow, Ella Batty

**Our 2021 Sponsors, including Presenting Sponsor Facebook Reality Labs**

---
# Tutorial Objectives

*Estimated timing of tutorial: 50 minutes*

In this notebook we'll learn to apply PCA for dimensionality reduction, using a classic dataset that is often used to benchmark machine learning algorithms: MNIST. We'll also learn how to use PCA for reconstruction and denoising.

Overview:
- Perform PCA on MNIST
- Calculate the variance explained
- Reconstruct data with different numbers of PCs
- (Bonus) Examine denoising using PCA

You can learn more about MNIST dataset [here](https://en.wikipedia.org/wiki/MNIST_database).

```python
# @title Tutorial slides

# @markdown These are the slides for the videos in all tutorials today
from IPython.display import IFrame
IFrame(src=f"https://mfr.ca-1.osf.io/render?url=https://osf.io/kaq2x/?direct%26mode=render%26action=download%26mode=render", width=854, height=480)
```

```python
# @title Video 1: PCA for dimensionality reduction
from ipywidgets import widgets

out2 = widgets.Output()
with out2:
  from IPython.display import IFrame
  class BiliVideo(IFrame):
      def __init__(self, id, page=1, width=400, height=300, **kwargs):
          self.id=id
          src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)
          super(BiliVideo, self).__init__(src, width, height, **kwargs)

  video = BiliVideo(id="BV1up4y1S7xs", width=854, height=480, fs=1)
  print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))
  display(video)

out1 = widgets.Output()
with out1:
  from IPython.display import YouTubeVideo
  video = YouTubeVideo(id="oO0bbInoO_0", width=854, height=480, fs=1, rel=0)
  print('Video available at https://youtube.com/watch?v=' + video.id)
  display(video)

out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')

display(out)
```

    Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})

---
# Setup

```python
# Imports

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

```python
# @title Figure Settings
import ipywidgets as widgets   # interactive display
%config InlineBackend.figure_format = 'retina'
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
```

```python
# @title Plotting Functions

def plot_variance_explained(variance_explained):
  """
  Plots eigenvalues.

  Args:
    variance_explained (numpy array of floats) : Vector of variance explained
                                                 for each PC

  Returns:
    Nothing.

  """

  plt.figure()
  plt.plot(np.arange(1, len(variance_explained) + 1), variance_explained,
           '--k')
  plt.xlabel('Number of components')
  plt.ylabel('Variance explained')
  plt.show()

def plot_MNIST_reconstruction(X, X_reconstructed):
  """
  Plots 9 images in the MNIST dataset side-by-side with the reconstructed
  images.

  Args:
    X (numpy array of floats)               : Data matrix each column
                                              corresponds to a different
                                              random variable
    X_reconstructed (numpy array of floats) : Data matrix each column
                                              corresponds to a different
                                              random variable

  Returns:
    Nothing.
  """

  plt.figure()
  ax = plt.subplot(121)
  k = 0
  for k1 in range(3):
    for k2 in range(3):
      k = k + 1
      plt.imshow(np.reshape(X[k, :], (28, 28)),
                 extent=[(k1 + 1) * 28, k1 * 28, (k2 + 1) * 28, k2 * 28],
                 vmin=0, vmax=255)
  plt.xlim((3 * 28, 0))
  plt.ylim((3 * 28, 0))
  plt.tick_params(axis='both', which='both', bottom=False, top=False,
                  labelbottom=False)
  ax.set_xticks([])
  ax.set_yticks([])
  plt.title('Data')
  plt.clim([0, 250])
  ax = plt.subplot(122)
  k = 0
  for k1 in range(3):
    for k2 in range(3):
      k = k + 1
      plt.imshow(np.reshape(np.real(X_reconstructed[k, :]), (28, 28)),
                 extent=[(k1 + 1) * 28, k1 * 28, (k2 + 1) * 28, k2 * 28],
                 vmin=0, vmax=255)
  plt.xlim((3 * 28, 0))
  plt.ylim((3 * 28, 0))
  plt.tick_params(axis='both', which='both', bottom=False, top=False,
                  labelbottom=False)
  ax.set_xticks([])
  ax.set_yticks([])
  plt.clim([0, 250])
  plt.title('Reconstructed')
  plt.tight_layout()

def plot_MNIST_sample(X):
  """
  Plots 9 images in the MNIST dataset.

  Args:
     X (numpy array of floats) : Data matrix each column corresponds to a
                                 different random variable

  Returns:
    Nothing.

  """

  fig, ax = plt.subplots()
  k = 0
  for k1 in range(3):
    for k2 in range(3):
      k = k + 1
      plt.imshow(np.reshape(X[k, :], (28, 28)),
                 extent=[(k1 + 1) * 28, k1 * 28, (k2+1) * 28, k2 * 28],
                 vmin=0, vmax=255)
  plt.xlim((3 * 28, 0))
  plt.ylim((3 * 28, 0))
  plt.tick_params(axis='both', which='both', bottom=False, top=False,
                  labelbottom=False)
  plt.clim([0, 250])
  ax.set_xticks([])
  ax.set_yticks([])
  plt.show()

def plot_MNIST_weights(weights):
  """
  Visualize PCA basis vector weights for MNIST. Red = positive weights,
  blue = negative weights, white = zero weight.

  Args:
     weights (numpy array of floats) : PCA basis vector

  Returns:
     Nothing.
  """

  fig, ax = plt.subplots()
  cmap = plt.cm.get_cmap('seismic')
  plt.imshow(np.real(np.reshape(weights, (28, 28))), cmap=cmap)
  plt.tick_params(axis='both', which='both', bottom=False, top=False,
                  labelbottom=False)
  plt.clim(-.15, .15)
  plt.colorbar(ticks=[-.15, -.1, -.05, 0, .05, .1, .15])
  ax.set_xticks([])
  ax.set_yticks([])
  plt.show()

def plot_eigenvalues(evals, limit=True):
  """
  Plots eigenvalues.

  Args:
     (numpy array of floats) : Vector of eigenvalues

  Returns:
    Nothing.

  """

  plt.figure()
  plt.plot(np.arange(1, len(evals) + 1), evals, 'o-k')
  plt.xlabel('Component')
  plt.ylabel('Eigenvalue')
  plt.title('Scree plot')
  if limit:
    plt.show()
```

```python
# @title Helper Functions

def add_noise(X, frac_noisy_pixels):
  """
  Randomly corrupts a fraction of the pixels by setting them to random values.

  Args:
     X (numpy array of floats)  : Data matrix
     frac_noisy_pixels (scalar) : Fraction of noisy pixels

  Returns:
     (numpy array of floats)    : Data matrix + noise

  """

  X_noisy = np.reshape(X, (X.shape[0] * X.shape[1]))
  N_noise_ixs = int(X_noisy.shape[0] * frac_noisy_pixels)
  noise_ixs = np.random.choice(X_noisy.shape[0], size=N_noise_ixs,
                               replace=False)
  X_noisy[noise_ixs] = np.random.uniform(0, 255, noise_ixs.shape)
  X_noisy = np.reshape(X_noisy, (X.shape[0], X.shape[1]))

  return X_noisy

def change_of_basis(X, W):
  """
  Projects data onto a new basis.

  Args:
    X (numpy array of floats) : Data matrix each column corresponding to a
                                different random variable
    W (numpy array of floats) : new orthonormal basis columns correspond to
                                basis vectors

  Returns:
    (numpy array of floats)   : Data matrix expressed in new basis
  """

  Y = np.matmul(X, W)

  return Y

def get_sample_cov_matrix(X):
  """
  Returns the sample covariance matrix of data X.

  Args:
    X (numpy array of floats) : Data matrix each column corresponds to a
                                different random variable

  Returns:
    (numpy array of floats)   : Covariance matrix
"""

  X = X - np.mean(X, 0)
  cov_matrix = 1 / X.shape[0] * np.matmul(X.T, X)
  return cov_matrix

def sort_evals_descending(evals, evectors):
  """
  Sorts eigenvalues and eigenvectors in decreasing order. Also aligns first two
  eigenvectors to be in first two quadrants (if 2D).

  Args:
    evals (numpy array of floats)    :   Vector of eigenvalues
    evectors (numpy array of floats) :   Corresponding matrix of eigenvectors
                                         each column corresponds to a different
                                         eigenvalue

  Returns:
    (numpy array of floats)          : Vector of eigenvalues after sorting
    (numpy array of floats)          : Matrix of eigenvectors after sorting
  """

  index = np.flip(np.argsort(evals))
  evals = evals[index]
  evectors = evectors[:, index]
  if evals.shape[0] == 2:
    if np.arccos(np.matmul(evectors[:, 0],
                           1 / np.sqrt(2) * np.array([1, 1]))) > np.pi / 2:
      evectors[:, 0] = -evectors[:, 0]
    if np.arccos(np.matmul(evectors[:, 1],
                           1 / np.sqrt(2)*np.array([-1, 1]))) > np.pi / 2:
      evectors[:, 1] = -evectors[:, 1]

  return evals, evectors

def pca(X):
  """
  Performs PCA on multivariate data. Eigenvalues are sorted in decreasing order

  Args:
     X (numpy array of floats) :   Data matrix each column corresponds to a
                                   different random variable

  Returns:
    (numpy array of floats)    : Data projected onto the new basis
    (numpy array of floats)    : Vector of eigenvalues
    (numpy array of floats)    : Corresponding matrix of eigenvectors

  """

  X = X - np.mean(X, 0)
  cov_matrix = get_sample_cov_matrix(X)
  evals, evectors = np.linalg.eigh(cov_matrix)
  evals, evectors = sort_evals_descending(evals, evectors)
  score = change_of_basis(X, evectors)

  return score, evectors, evals
```

---
# Section 1: Perform PCA on MNIST

The MNIST dataset consists of a 70,000 images of individual handwritten digits. Each image is a 28x28 pixel grayscale image. For convenience, each 28x28 pixel image is often unravelled into a single 784 (=28*28) element vector, so that the whole dataset is represented as a 70,000 x 784 matrix. Each row represents a different image, and each column represents a different pixel.

Enter the following cell to load the MNIST dataset and plot the first nine images. It may take a few minutes to load.

```python
from sklearn.datasets import fetch_openml

# GET mnist data
mnist = fetch_openml(name='mnist_784', as_frame = False)
X = mnist.data

# Visualize
plot_MNIST_sample(X)
```

The MNIST dataset has an extrinsic dimensionality of 784, much higher than the 2-dimensional examples used in the previous tutorials! To make sense of this data, we'll use dimensionality reduction. But first, we need to determine the intrinsic dimensionality $K$ of the data. One way to do this is to look for an "elbow" in the scree plot, to determine which eigenvalues are signficant.

## Coding Exercise 1: Scree plot of MNIST

In this exercise you will examine the scree plot in the MNIST dataset.

**Steps:**
- Perform PCA on the dataset using our function `pca` from tutorial 2 (already loaded in) and examine the scree plot.
- When do the eigenvalues appear (by eye) to reach zero? (**Hint:** use `plt.xlim` to zoom into a section of the plot).

```python
help(pca)
```

    Help on function pca in module __main__:

    pca(X)
        Performs PCA on multivariate data. Eigenvalues are sorted in decreasing order

        Args:
           X (numpy array of floats) :   Data matrix each column corresponds to a
                                         different random variable

        Returns:
          (numpy array of floats)    : Data projected onto the new basis
          (numpy array of floats)    : Vector of eigenvalues
          (numpy array of floats)    : Corresponding matrix of eigenvectors

```python
#################################################
## TODO for students
# Fill out function and remove
# raise NotImplementedError("Student excercise: perform PCA and visualize scree plot")
#################################################

# Perform PCA
score, evectors, evals = pca(X)

# Plot the eigenvalues
plot_eigenvalues(evals, limit=False)
plt.xlim([0, 100])  # limit x-axis up to 100 for zooming
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_d8411e54.py)

*Example output:*

---
# Section 2: Calculate the variance explained

*Estimated timing to here from start of tutorial: 15 min*

The scree plot suggests that most of the eigenvalues are near zero, with fewer than 100 having large values. Another common way to determine the intrinsic dimensionality is by considering the variance explained. This can be examined with a cumulative plot of the fraction of the total variance explained by the top $K$ components, i.e.,

\begin{align}
\text{var explained} = \frac{\sum_{i=1}^K \lambda_i}{\sum_{i=1}^N \lambda_i}
\end{align}

where $\lambda_i$ is the $i^{th}$ eigenvalue and $N$ is the total number of components (the original number of dimensions in the data).

The intrinsic dimensionality is often quantified by the $K$ necessary to explain a large proportion of the total variance of the data (often a defined threshold, e.g., 90%).

## Coding Exercise 2: Plot the explained variance

In this exercise you will plot the explained variance.

**Steps:**
- Fill in the function below to calculate the fraction variance explained as a function of the number of principal componenets. **Hint:** use `np.cumsum`.
- Plot the variance explained using `plot_variance_explained`.

**Questions:**
- How many principal components are required to explain 90% of the variance?
- How does the intrinsic dimensionality of this dataset compare to its extrinsic dimensionality?

```python
def get_variance_explained(evals):
  """
  Calculates variance explained from the eigenvalues.

  Args:
    evals (numpy array of floats) : Vector of eigenvalues

  Returns:
    (numpy array of floats)       : Vector of variance explained

  """

  #################################################
  ## TO DO for students: calculate the explained variance using the equation
  ## from Section 2.
  # Comment once you've filled in the function
  # raise NotImplementedError("Student excercise: calculate explaine variance!")
  #################################################

  # Cumulatively sum the eigenvalues
  csum = np.cumsum(evals)

  # Normalize by the sum of eigenvalues
  variance_explained = csum / np.sum(evals)

  return variance_explained

# Calculate the variance explained
variance_explained = get_variance_explained(evals)

# Visualize
plot_variance_explained(variance_explained)
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_a4ac4c9c.py)

*Example output:*

---
# Section 3: Reconstruct data with different numbers of PCs

*Estimated timing to here from start of tutorial: 25 min*

```python
# @title Video 2: Data Reconstruction
from ipywidgets import widgets

out2 = widgets.Output()
with out2:
  from IPython.display import IFrame
  class BiliVideo(IFrame):
      def __init__(self, id, page=1, width=400, height=300, **kwargs):
          self.id=id
          src = 'https://player.bilibili.com/player.html?bvid={0}&page={1}'.format(id, page)
          super(BiliVideo, self).__init__(src, width, height, **kwargs)

  video = BiliVideo(id="BV1XK4y1s7KF", width=854, height=480, fs=1)
  print('Video available at https://www.bilibili.com/video/{0}'.format(video.id))
  display(video)

out1 = widgets.Output()
with out1:
  from IPython.display import YouTubeVideo
  video = YouTubeVideo(id="ZCUhW26AdBQ", width=854, height=480, fs=1, rel=0)
  print('Video available at https://youtube.com/watch?v=' + video.id)
  display(video)

out = widgets.Tab([out1, out2])
out.set_title(0, 'Youtube')
out.set_title(1, 'Bilibili')

display(out)
```

    Tab(children=(Output(), Output()), _titles={'0': 'Youtube', '1': 'Bilibili'})

Now we have seen that the top 100 or so principal components of the data can explain most of the variance. We can use this fact to perform *dimensionality reduction*, i.e., by storing the data using only 100 components rather than the samples of all 784 pixels. Remarkably, we will be able to reconstruct much of the structure of the data using only the top 100 components. To see this, recall that to perform PCA we projected the data $\bf X$ onto the eigenvectors of the covariance matrix:
\begin{align}
\bf S = X W
\end{align}
Since $\bf W$ is an orthogonal matrix, ${\bf W}^{-1} = {\bf W}^T$. So by multiplying by ${\bf W}^T$ on each side we can rewrite this equation as
\begin{align}
{\bf X = S W}^T.
\end{align}
This now gives us a way to reconstruct the data matrix from the scores and loadings. To reconstruct the data from a low-dimensional approximation, we just have to truncate these matrices.  Let's denote ${\bf S}_{1:K}$ and ${\bf W}_{1:K}$ the matrices with only the first $K$ columns of $\bf S$ and $\bf W$, respectively. Then our reconstruction is:
\begin{align}
{\bf \hat X = S}_{1:K} ({\bf W}_{1:K})^T.
\end{align}

## Coding Exercise 3: Data reconstruction

Fill in the function below to reconstruct the data using different numbers of principal components.

**Steps:**

* Fill in the following function to reconstruct the data based on the weights and scores. Don't forget to add the mean!
* Make sure your function works by reconstructing the data with all $K=784$ components. The two images should look identical.

```python
evectors[0:100,0:100].shape
```

    (100, 100)

```python
X_mean.shape
```

    (784,)

```python
score.shape
```

    (70000, 784)

```python
784*784
```

    614656

```python
def reconstruct_data(score, evectors, X_mean, K):
  """
  Reconstruct the data based on the top K components.

  Args:
    score (numpy array of floats)    : Score matrix
    evectors (numpy array of floats) : Matrix of eigenvectors
    X_mean (numpy array of floats)   : Vector corresponding to data mean
    K (scalar)                       : Number of components to include

  Returns:
    (numpy array of floats)          : Matrix of reconstructed data

  """

  #################################################
  ## TO DO for students: Reconstruct the original data in X_reconstructed
  # Comment once you've filled in the function
  # raise NotImplementedError("Student excercise: reconstructing data function!")
  #################################################

  # Reconstruct the data from the score and eigenvectors
  # Don't forget to add the mean!!
  # Grab all rows and 0th-Kth columns in both score and w.T
  # and multiply those together, then add back the mean we sutracted out earlier
  X_reconstructed = np.matmul(score[:, :K], evectors[:, :K].T) + X_mean

  return X_reconstructed

# K = 100
K = 784

# Reconstruct the data based on all components
X_mean = np.mean(X, 0)
X_reconstructed = reconstruct_data(score, evectors, X_mean, K)

# Plot the data and reconstruction
plot_MNIST_reconstruction(X, X_reconstructed)
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_e3395916.py)

*Example output:*

## Interactive Demo 3: Reconstruct the data matrix using different numbers of PCs

Now run the code below and experiment with the slider to reconstruct the data matrix using different numbers of principal components.

1.  How many principal components are necessary to reconstruct the numbers (by eye)? How does this relate to the intrinsic dimensionality of the data?
2.  Do you see any information in the data with only a single principal component?

```python
# @title

# @markdown Make sure you execute this cell to enable the widget!

def refresh(K=100):
  X_reconstructed = reconstruct_data(score, evectors, X_mean, K)
  plot_MNIST_reconstruction(X, X_reconstructed)
  plt.title('Reconstructed, K={}'.format(K))

_ = widgets.interact(refresh, K=(1, 784, 10))
```

    interactive(children=(IntSlider(value=100, description='K', max=784, min=1, step=10), Output()), _dom_classes=…

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_f659a785.py)

---
# Section 4: Visualize PCA components

*Estimated timing to here from start of tutorial: 40 min*

## Coding Exercise 4: Visualization of the weights

Next, let's take a closer look at the first principal component by visualizing its corresponding weights.

**Steps:**

* Enter `plot_MNIST_weights` to visualize the weights of the first basis vector.
* What structure do you see? Which pixels have a strong positive weighting? Which have a strong negative weighting? What kinds of images would this basis vector differentiate (hint: think about the last demo with 1 component)?
* Try visualizing the second and third basis vectors. Do you see any structure? What about the 100th basis vector? 500th? 700th?

```python
help(plot_MNIST_weights)
```

    Help on function plot_MNIST_weights in module __main__:

    plot_MNIST_weights(weights)
        Visualize PCA basis vector weights for MNIST. Red = positive weights,
        blue = negative weights, white = zero weight.

        Args:
           weights (numpy array of floats) : PCA basis vector

        Returns:
           Nothing.

```python
################################################################
# Comment once you've filled in the function
# raise NotImplementedError("Student excercise: visualize PCA components")
################################################################

# Plot the weights of the first principal component

plot_MNIST_weights(evectors[:,0])

# pixels with strong weighting are differentiating features for that number/shape
# pixels with strong neg weighting are negative spaces

```

```python
plot_MNIST_weights(np.sum(evectors[:,0:4],1))
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_d27990ad.py)

*Example output:*

---
# Summary

*Estimated timing of tutorial: 50 minutes*

* In this tutorial, we learned how to use PCA for dimensionality reduction by selecting the top principal components. This can be useful as the intrinsic dimensionality ($K$) is often less than the extrinsic dimensionality ($N$) in neural data. $K$ can be inferred by choosing the number of eigenvalues necessary to capture some fraction of the variance.
* We also learned how to reconstruct an approximation of the original data using the top $K$ principal components. In fact, an alternate formulation of PCA is to find the $K$ dimensional space that minimizes the reconstruction error.
* Noise tends to inflate the apparent intrinsic dimensionality, however the higher components reflect noise rather than new structure in the data. PCA can be used for denoising data by removing noisy higher components.
* In MNIST, the weights corresponding to the first principal component appear to discriminate between a 0 and 1. We will discuss the implications of this for data visualization in the following tutorial.

---
# Notation

\begin{align}
K &\quad \text{selected number of principal components}\\
N &\quad \text{total number of principal components}\\
\bf W &\quad \text{weights, loadings matrix}\\
{\bf X} &\quad \text{original data matrix}\\
\bf S &\quad \text{projected matrix, scores}\\
{\bf S}_{1:K} &\quad \text{first K columns of score matrix } \bf S\\
{\bf W}_{1:K} &\quad \text{first K columns of weight matrix } \bf W\\
\end{align}

---
# Bonus

---
## Bonus Section 1: Examine denoising using PCA

In this lecture, we saw that PCA finds an optimal low-dimensional basis to minimize the reconstruction error. Because of this property, PCA can be useful for denoising corrupted samples of the data.

### Bonus Coding Exercise 1: Add noise to the data
In this exercise you will add salt-and-pepper noise to the original data and see how that affects the eigenvalues.

**Steps:**
- Use the function `add_noise` to add noise to 20% of the pixels.
- Then, perform PCA and plot the variance explained. How many principal components are required to explain 90% of the variance? How does this compare to the original data?

```python
help(add_noise)
```

    Help on function add_noise in module __main__:

    add_noise(X, frac_noisy_pixels)
        Randomly corrupts a fraction of the pixels by setting them to random values.

        Args:
           X (numpy array of floats)  : Data matrix
           frac_noisy_pixels (scalar) : Fraction of noisy pixels

        Returns:
           (numpy array of floats)    : Data matrix + noise

```python
#################################################
## TO DO for students
# Comment once you've filled in the function
# raise NotImplementedError("Student excercise: make MNIST noisy and compute PCA!")
#################################################

np.random.seed(2020)  # set random seed

# Add noise to data
X_noisy = ...

# Perform PCA on noisy data
score_noisy, evectors_noisy, evals_noisy = ...

# Compute variance explained
variance_explained_noisy = ...

# Visualize
plot_MNIST_sample(X_noisy)
plot_variance_explained(variance_explained_noisy)
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_9615a6cd.py)

*Example output:*

### Bonus Coding Exercise 2: Denoising

Next, use PCA to perform denoising by projecting the noise-corrupted data onto the basis vectors found from the original dataset. By taking the top K components of this projection, we can reduce noise in dimensions orthogonal to the K-dimensional latent space.

**Steps:**
- Subtract the mean of the noise-corrupted data.
- Project the data onto the basis found with the original dataset (`evectors`, not `evectors_noisy`) and take the top $K$ components.
- Reconstruct the data as normal, using the top 50 components.
- Play around with the amount of noise and K to build intuition.

```python
#################################################
## TO DO for students
# Comment once you've filled in the function
raise NotImplementedError("Student excercise: reconstruct noisy data from PCA")
#################################################

# Compute mean of noise-corrupted data
X_noisy_mean = ...

# Project onto the original basis vectors
projX_noisy = ...

# Reconstruct the data using the top 50 components
X_reconstructed = ...

# Visualize
plot_MNIST_reconstruction(X_noisy, X_reconstructed)
```

[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W1D5_DimensionalityReduction/solutions/W1D5_Tutorial3_Solution_4c4115fa.py)

*Example output:*