Probabilistic Programming
=====
and Bayesian Methods for Hackers
========

#####Version 0.1
Welcome to *Bayesian Methods for Hackers*. The full Github repository is available at [github/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers](https://github.com/CamDavidsonPilon/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers). The other chapters can be found on the projects [homepage](camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!

Chapter 1
======
***

The Philosophy of Bayesian Inference
------

> You are a skilled programmer, but bugs still slip into your code. After a particularly difficult implementation of an algorithm, you decide to test your code on a trivial example. It passes. You test the code on a harder problem. It passes once again. And it passes the next, *even more difficult*, test too! You are starting to believe that there may be no bugs in this code...

If you think this way, then congratulations, you already are thinking Bayesian! Bayesian inference is simply updating your beliefs after considering new evidence. A Bayesian can rarely be certain about a result, but he or she can be very confident. Just like in the example above, we can never be 100% sure that our code is bug-free unless we test it on every possible problem; something rarely possible in practice. Instead, we can test it on a large number of problems, and if it succeeds we can feel more *confident* about our code, but still not certain.  Bayesian inference works identically: we update our beliefs about an outcome; rarely can we be absolutely sure unless we rule out all other alternatives.

###The Bayesian state of mind

Bayesian inference differs from more traditional statistical inference by preserving *uncertainty*. At first, this sounds like a bad statistical technique. Isn't statistics all about deriving *certainty* from randomness? To reconcile this, we need to start thinking like Bayesians.

The Bayesian world-view interprets probability as measure of *believability in an event*, that is, how confident we are in an event occurring. In fact, we will see in a moment that this is the natural interpretation of probability.

For this to be clearer, we consider an alternative interpretation of probability: *Frequentist*, known as the more *classical* version of statistics, assume that probability is the long-run frequency of events (hence the bestowed title). For example, the *probability of plane accidents* under a frequentist philosophy is interpreted as the *long-term frequency of plane accidents*. This makes logical sense for many probabilities of events, but becomes more difficult to understand when events have no long-term frequency of occurrences. Consider: we often assign probabilities to outcomes of presidential elections, but the election itself only happens once! Frequentists get around this by invoking alternative realities and saying across all these realities, the frequency of occurrences defines the probability.

Bayesians, on the other hand, have a more intuitive approach. Bayesians interpret a probability as measure of *belief*, or confidence, of an event occurring. Simply, a probability is a summary of an opinion. An individual who assigns a belief of 0 to an event has no confidence that the event will occur; conversely, assigning a belief of 1 implies that the individual is absolutely certain of an event occurring. Beliefs between 0 and 1 allow for weightings of other outcomes. This definition agrees with the probability of a plane accident example, for having observed the frequency of plane accidents, an individual's belief should be equal to that frequency, excluding any outside information. Similarly, under this definition of probability being equal to beliefs, it is meaningful to speak about probabilities (beliefs) of presidential election outcomes: how confident are you candidate *A* will win?

Notice in the paragraph above, I assigned the belief (probability) measure to an *individual*, not to Nature. This is very interesting, as this definition leaves room for conflicting beliefs between individuals. Again, this is appropriate for what naturally occurs: different individuals have different beliefs of events occurring, because they possess different *information* about the world. The existence of different beliefs does not imply that anyone is wrong. Consider the following examples demonstrating the relationship between individual beliefs and probabilities:

- I flip a coin, and we both guess the result. We would both agree, assuming the coin is fair, that the probability of Heads is 1/2. Assume, then, that I peek at the coin. Now I know for certain what the result is: I assign probability 1.0 to either Heads or Tails (whichever it is). Now what is *your* belief that the coin is Heads? My knowledge of the outcome has not changed the coin's results. Thus we assign different probabilities to the result.

-  Your code either has a bug in it or not, but we do not know for certain which is true, though we have a belief about the presence or absence of a bug.

-  A medical patient is exhibiting symptoms $x$, $y$ and $z$. There are a number of diseases that could be causing all of them, but only a single disease is present. A doctor has beliefs about which disease, but a second doctor may have slightly different beliefs.

This philosophy of treating beliefs as probability is natural to humans. We employ it constantly as we interact with the world and only see partial truths, but gather evidence to form beliefs. Alternatively, you have to be *trained* to think like a frequentist.

To align ourselves with traditional probability notation, we denote our belief about event $A$ as $P(A)$. We call this quantity the *prior probability*.

John Maynard Keynes, a great economist and thinker, said "When the facts change, I change my mind. What do you do, sir?" This quote reflects the way a Bayesian updates his or her beliefs after seeing evidence. Even — especially — if the evidence is counter to what was initially believed, the evidence cannot be ignored. We denote our updated belief as $P(A |X )$, interpreted as the probability of $A$ given the evidence $X$. We call the updated belief the *posterior probability* so as to contrast it with the prior probability. For example, consider the posterior probabilities (read: posterior beliefs) of the above examples, after observing some evidence $X$.:

1\. $P(A): \;\;$ the coin has a 50 percent chance of being Heads. $P(A | X):\;\;$ You look at the coin, observe a Heads has landed, denote this information $X$, and trivially assign probability 1.0 to Heads and 0.0 to Tails.

2\.   $P(A): \;\;$  This big, complex code likely has a bug in it. $P(A | X): \;\;$ The code passed all $X$ tests; there still might be a bug, but its presence is less likely now.

3\.  $P(A):\;\;$ The patient could have any number of diseases. $P(A | X):\;\;$ Performing a blood test generated evidence $X$, ruling out some of the possible diseases from consideration.

It's clear that in each example we did not completely discard the prior belief after seeing new evidence $X$, but we *re-weighted the prior* to incorporate the new evidence (i.e. we put more weight, or confidence, on some beliefs versus others).

By introducing prior uncertainty about events, we are already admitting that any guess we make is potentially very wrong. After observing data, evidence, or other information, we update our beliefs, and our guess becomes *less wrong*. This is the alternative side of the prediction coin, where typically we try to be *more right*.

###Bayesian Inference in Practice

 If frequentist and Bayesian inference were programming functions, with inputs being statistical problems, then the two would be different in what they return to the user. The frequentist inference function would return a number, representing an estimate (typically a summary statistic like the sample average etc.), whereas the Bayesian function would return *probabilities*.

For example, in our debugging problem above, calling the frequentist function with the argument "My code passed all $X$ tests; is my code bug-free?" would return a *YES*. On the other hand, asking our Bayesian function "Often my code has bugs. My code passed all $X$ tests; is my code bug-free?" would return something very different: probabilities of *YES* and *NO*. The function might return:

>    *YES*, with probability 0.8; *NO*, with probability 0.2

This is very different from the answer the frequentist function returned. Notice that the Bayesian function accepted an additional argument:  *"Often my code has bugs"*. This parameter is the *prior*. By including the prior parameter, we are telling the Bayesian function to include our belief about the situation. Technically this parameter in the Bayesian function is optional, but we will see excluding it has its own consequences.

####Incorporating evidence

As we acquire more and more instances of evidence, our prior belief is *washed out* by the new evidence. This is to be expected. For example, if your prior belief is something ridiculous, like "I expect the sun to explode today", and each day you are proved wrong, you would hope that any inference would correct you, or at least align your beliefs better. Bayesian inference will correct this belief.

Denote $N$ as the number of instances of evidence we possess. As we gather an *infinite* amount of evidence, say as $N \rightarrow \infty$, our Bayesian results (often) align with frequentist results. Hence for large $N$, statistical inference is more or less objective. On the other hand, for small $N$, inference is much more *unstable*: frequentist estimates have more variance and larger confidence intervals. This is where Bayesian analysis excels. By introducing a prior, and returning probabilities (instead of a scalar estimate), we *preserve the uncertainty* that reflects the instability of statistical inference of a small $N$ dataset.

One may think that for large $N$, one can be indifferent between the two techniques since they offer similar inference, and might lean towards the computational-simpler, frequentist methods. An individual in this position should consider the following quote by Andrew Gelman (2005)[1], before making such a decision:

> Sample sizes are never large. If $N$ is too small to get a sufficiently-precise estimate, you need to get more data (or make more assumptions). But once $N$ is "large enough," you can start subdividing the data to learn more (for example, in a public opinion poll, once you have a good estimate for the entire country, you can estimate among men and women, northerners and southerners, different age groups, etc.). $N$ is never enough because if it were "enough" you'd already be on to the next problem for which you need more data.

### Are frequentist methods incorrect then?

**No.**

Frequentist methods are still useful or state-of-the-art in many areas. Tools such as least squares linear regression, LASSO regression, and expectation-maximization algorithms are all powerful and fast. Bayesian methods complement these techniques by solving problems that these approaches cannot, or by illuminating the underlying system with more flexible modeling.

#### A note on *Big Data*
Paradoxically, big data's predictive analytic problems are actually solved by relatively simple algorithms [2][4]. Thus we can argue that big data's prediction difficulty does not lie in the algorithm used, but instead on the computational difficulties of storage and execution on big data. (One should also consider Gelman's quote from above and ask "Do I really have big data?" )

The much more difficult analytic problems involve *medium data* and, especially troublesome, *really small data*. Using a similar argument as  Gelman's above, if big data problems are *big enough* to be readily solved, then we should be more interested in the *not-quite-big enough* datasets.

### Our Bayesian framework

We are interested in beliefs, which can be interpreted as probabilities by thinking Bayesian. We have a *prior* belief in event $A$, beliefs formed by previous information, e.g., our prior belief about bugs being in our code before performing tests.

Secondly, we observe our evidence. To continue our buggy-code example: if our code passes $X$ tests, we want to update our belief to incorporate this. We call this new belief the *posterior* probability. Updating our belief is done via the following equation, known as Bayes' Theorem, after its discoverer Thomas Bayes:

\begin{align}
 P( A | X ) = & \frac{ P(X | A) P(A) } {P(X) } \\\\[5pt]
& \propto P(X | A) P(A)\;\; (\propto \text{is proportional to } )
\end{align}

The above formula is not unique to Bayesian inference: it is a mathematical fact with uses outside Bayesian inference. Bayesian inference merely uses it to connect prior probabilities $P(A)$ with an updated posterior probabilities $P(A | X )$.

##### Example: Mandatory coin-flip example

Every statistics text must contain a coin-flipping example, I'll use it here to get it out of the way. Suppose, naively, that you are unsure about the probability of heads in a coin flip (spoiler alert: it's 50%). You believe there is some true underlying ratio, call it $p$, but have no prior opinion on what $p$ might be.

We begin to flip a coin, and record the observations: either $H$ or $T$. This is our observed data. An interesting question to ask is how our inference changes as we observe more and more data? More specifically, what do our posterior probabilities look like when we have little data, versus when we have lots of data.

Below we plot a sequence of updating posterior probabilities as we observe increasing amounts of data (coin flips).

```
"""
The book uses a custom matplotlibrc file, which provides the unique styles for
matplotlib plots. If executing this book, and you wish to use the book's
styling, provided are two options:
    1. Overwrite your own matplotlibrc file with the rc-file provided in the
       book's styles/ dir. See http://matplotlib.org/users/customizing.html
    2. Also in the styles is  bmh_matplotlibrc.json file. This can be used to
       update the styles in only this notebook. Try running the following code:

        import json
        s = json.load( open("../styles/bmh_matplotlibrc.json") )
        matplotlib.rcParams.update(s)

"""

# The code below can be passed over, as it is currently not important, plus it
# uses advanced topics we have not covered yet. LOOK AT PICTURE, MICHAEL!
%pylab inline
figsize(11, 9)

import scipy.stats as stats

dist = stats.beta
n_trials = [0, 1, 2, 3, 4, 5, 8, 15, 50, 500]
data = stats.bernoulli.rvs(0.5, size=n_trials[-1])
x = np.linspace(0, 1, 100)

# For the already prepared, I'm using Binomial's conj. prior.
for k, N in enumerate(n_trials):
    sx = subplot(len(n_trials)/2, 2, k+1)
    plt.xlabel("$p$, probability of heads") \
        if k in [0, len(n_trials)-1] else None
    plt.setp(sx.get_yticklabels(), visible=False)
    heads = data[:N].sum()
    y = dist.pdf(x, 1 + heads, 1 + N - heads)
    plt.plot(x, y, label="observe %d tosses,\n %d heads" % (N, heads))
    plt.fill_between(x, 0, y, color="#348ABD", alpha=0.4)
    plt.vlines(0.5, 0, 4, color="k", linestyles="--", lw=1)

    leg = plt.legend()
    leg.get_frame().set_alpha(0.4)
    plt.autoscale(tight=True)

plt.suptitle("Bayesian updating of posterior probabilities",
             y=1.02,
             fontsize=14)

plt.tight_layout()
```

The posterior probabilities are represented by the curves, and our uncertainty is proportional to the width of the curve. As the plot above shows, as we start to observe data our posterior probabilities start to shift and move around. Eventually, as we observe more and more data (coin-flips), our probabilities will tighten closer and closer around the true value of $p=0.5$ (marked by a dashed line).

Notice that the plots are not always *peaked* at 0.5. There is no reason it should be: recall we assumed we did not have a prior opinion of what $p$ is. In fact, if we observe quite extreme data, say 8 flips and only 1 observed heads, our distribution would look very biased *away* from lumping around 0.5 (with no prior opinion, how confident would you feel betting on a fair coin after observing 8 tails and 1 head). As more data accumulates, we would see more and more probability being assigned at $p=0.5$, though never all of it.

The next example is a simple demonstration of the mathematics of Bayesian inference.

#####Example: Bug, or just sweet, unintended feature?

Let $A$ denote the event that our code has **no bugs** in it. Let $X$ denote the event that the code passes all debugging tests. For now, we will leave the prior probability of no bugs as a variable, i.e. $P(A) = p$.

We are interested in $P(A|X)$, i.e. the probability of no bugs, given our debugging tests $X$. To use the formula above, we need to compute some quantities.

What is $P(X | A)$, i.e., the probability that the code passes $X$ tests *given* there are no bugs? Well, it is equal to 1, for a code with no bugs will pass all tests.

$P(X)$ is a little bit trickier: The event $X$ can be divided into two possibilities, event $X$ occurring even though our code *indeed has* bugs (denoted $\sim A\;$, spoken *not $A$*), or event $X$ without bugs ($A$). $P(X)$ can be represented as:

\begin{align}
P(X ) & = P(X \text{ and } A) + P(X \text{ and } \sim A) \\\\[5pt]
 & = P(X|A)P(A) + P(X | \sim A)P(\sim A)\\\\[5pt]
& = P(X|A)p + P(X | \sim A)(1-p)
\end{align}

We have already computed $P(X|A)$ above. On the other hand, $P(X | \sim A)$ is subjective: our code can pass tests but still have a bug in it, though the probability there is a bug present is reduced. Note this is dependent on the number of tests performed, the degree of complication in the tests, etc. Let's be conservative and assign $P(X|\sim A) = 0.5$. Then

\begin{align}
P(A | X) & = \frac{1\cdot p}{ 1\cdot p +0.5 (1-p) } \\\\
& = \frac{ 2 p}{1+p}
\end{align}
This is the posterior probability. What does it look like as a function of our prior, $p \in [0,1]$?

```
figsize(12.5, 4)
p = np.linspace(0, 1, 50)
plt.plot(p, 2*p/(1+p), color="#348ABD", lw=3)
#plt.fill_between(p, 2*p/(1+p), alpha=.5, facecolor=["#A60628"])
plt.scatter(0.2, 2*(0.2)/1.2, s=140, c="#348ABD")
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel("Prior, $P(A) = p$")
plt.ylabel("Posterior, $P(A|X)$, with $P(A) = p$")
plt.title("Are there bugs in my code?")
```

We can see the biggest gains if we observe the $X$ tests passed when the prior probability, $p$, is low. Let's settle on a specific value for the prior. I'm a strong programmer (I think), so I'm going to give myself a realistic prior of 0.20, that is, there is a 20% chance that I write code bug-free. To be more realistic, this prior should be a function of how complicated and large the code is, but let's pin it at 0.20. Then my updated belief that my code is bug-free is 0.33.

Recall that the prior is a probability: $p$ is the prior probability that there *are no bugs*, so $1-p$ is the prior probability that there *are bugs*.

Similarly, our posterior is also a probability, with $P(A | X)$ the probability there is no bug *given we saw all tests pass*, hence $1-P(A|X)$ is the probability there is a bug *given all tests passed*. What does our posterior probability look like? Below is a chart of both the prior and the posterior probabilities.

```
figsize(12.5, 4)
colours = ["#348ABD", "#A60628"]

prior = [0.20, 0.80]
posterior = [1./3, 2./3]
plt.bar([0, .7], prior, alpha=0.70, width=0.25,
        color=colours[0], label="prior distribution",
        lw="3", edgecolor=colours[0])

plt.bar([0+0.25, .7+0.25], posterior, alpha=0.7,
        width=0.25, color=colours[1],
        label="posterior distribution",
        lw="3", edgecolor=colours[1])

plt.xticks([0.20, .95], ["Bugs Absent", "Bugs Present"])
plt.title("Prior and Posterior probability of bugs present")
plt.ylabel("Probability")
plt.legend(loc="upper left");
```

Notice that after we observed $X$ occur, the probability of bugs being absent increased. By increasing the number of tests, we can approach confidence (probability 1) that there are no bugs present.

This was a very simple example of Bayesian inference and Bayes rule. Unfortunately, the mathematics necessary to perform more complicated Bayesian inference only becomes more difficult, except for artificially constructed cases. We will later see that this type of mathematical analysis is actually unnecessary. First we must broaden our modeling tools. The next section deals with *probability distributions*. If you are already familiar, feel free to skip (or at least skim), but for the less familiar the next section is essential.

_______

##Probability Distributions

**Let's quickly recall what a probability distribution is:** Let $Z$ be some random variable. Then associated with $Z$ is a *probability distribution function* that assigns probabilities to the different outcomes $Z$ can take. Graphically, a probability distribution is a curve where the probability of an outcome is proportional to the height of the curve. You can see examples in the first figure of this chapter.

We can divide random variables into three classifications:

-   **$Z$ is discrete**: Discrete random variables may only assume values on a specified list. Things like populations, movie ratings, and number of votes are all discrete random variables. Discrete random variables become more clear when we contrast them with...

-   **$Z$ is continuous**: Continuous random variable can take on arbitrarily exact values. For example, temperature, speed, time, color are all modeled as continuous variables because you can progressively make the values more and more precise.

- **$Z$ is mixed**: Mixed random variables assign probabilities to both discrete and continuous random variables, i.e. it is a combination of the above two categories.

###Discrete Case
If $Z$ is discrete, then its distribution is called a *probability mass function*, which measures the probability $Z$ takes on the value $k$, denoted $P(Z=k)$. Note that the probability mass function completely describes the random variable $Z$, that is, if we know the mass function, we know how $Z$ should behave. There are popular probability mass functions that consistently appear: we will introduce them as needed, but let's introduce the first very useful probability mass function. We say $Z$ is *Poisson*-distributed if:

$$P(Z = k) =\frac{ \lambda^k e^{-\lambda} }{k!}, \; \; k=0,1,2, \dots $$

$\lambda$ is called a parameter of the distribution, and it controls the distribution's shape. For the Poisson distribution, $\lambda$ can be any positive number. By increasing $\lambda$, we add more probability to larger values, and conversely by decreasing $\lambda$ we add more probability to smaller values. One can describe $\lambda$ as the *intensity* of the Poisson distribution.

Unlike $\lambda$, which can be any positive number, the value $k$ in the above formula must be a non-negative integer, i.e., $k$ must take on values 0,1,2, and so on. This is very important, because if you wanted to model a population you could not make sense of populations with 4.25 or 5.612 members.

If a random variable $Z$ has a Poisson mass distribution, we denote this by writing

$$Z \sim \text{Poi}(\lambda) $$

One useful property of the Poisson distribution is that its expected value is equal to its parameter, i.e.:

$$E\large[ \;Z\; | \; \lambda \;\large] = \lambda $$

We will use this property often, so it's useful to remember. Below, we plot the probability mass distribution for different $\lambda$ values. The first thing to notice is that by increasing $\lambda$, we add more probability of larger values occurring. Second, notice that although the graph ends at 15, the distributions do not. They assign positive probability to every non-negative integer.

```
figsize(12.5, 4)

import scipy.stats as stats
a = np.arange(16)
poi = stats.poisson
lambda_ = [1.5, 4.25]

plt.bar(a, poi.pmf(a, lambda_[0]), color=colours[0],
        label="$\lambda = %.1f$" % lambda_[0], alpha=0.60,
        edgecolor=colours[0], lw="3")

plt.bar(a, poi.pmf(a, lambda_[1]), color=colours[1],
        label="$\lambda = %.1f$" % lambda_[1], alpha=0.60,
        edgecolor=colours[1], lw="3")

plt.xticks(a + 0.4, a)
plt.legend()
plt.ylabel("probability of $k$")
plt.xlabel("$k$")
plt.title("Probability mass function of a Poisson random variable; differing \
$\lambda$ values")
```

###Continuous Case
Instead of a probability mass function, a continuous random variable has a *probability density function*. This might seem like unnecessary nomenclature, but the density function and the mass function are very different creatures. An example of continuous random variable is a random variable with *exponential density*. The density function for an exponential random variable looks like this:

$$f_Z(z | \lambda) = \lambda e^{-\lambda z }, \;\; z\ge 0$$

Like a Poisson random variable, an exponential random variable can take on only non-negative values. But unlike a Poisson variable, the exponential can take on *any* non-negative values, including non-integral values such as 4.25 or 5.612401. This property makes it a poor choice for count data, which must be an integer, but a great choice for time data, temperature data (measured in Kelvins, of course), or any other precise *and positive* variable. The graph below shows two probability density functions with different $\lambda$ values.

When a random variable $Z$ has an exponential distribution with parameter $\lambda$, we say *$Z$ is exponential* and write

$$Z \sim \text{Exp}(\lambda)$$

Given a specific $\lambda$, the expected value of an exponential random variable is equal to the inverse of $\lambda$, that is:

$$E[\; Z \;|\; \lambda \;] = \frac{1}{\lambda}$$

```
a = np.linspace(0, 4, 100)
expo = stats.expon
lambda_ = [0.5, 1]

for l, c in zip(lambda_, colours):
    plt.plot(a, expo.pdf(a, scale=1./l), lw=3,
             color=c, label="$\lambda = %.1f$" % l)
    plt.fill_between(a, expo.pdf(a, scale=1./l), color=c, alpha=.33)

plt.legend()
plt.ylabel("PDF at $z$")
plt.xlabel("$z$")
plt.title("Probability density function of an Exponential random variable;\
 differing $\lambda$")
```

###But what is $\lambda \;$?

**This question is what motivates statistics**. In the real world, $\lambda$ is hidden from us. We see only $Z$, and must go backwards to try and determine $\lambda$. The problem is difficult because there is no one-to-one mapping from $Z$ to $\lambda$. Many different methods have been created to solve the problem of estimating $\lambda$, but since $\lambda$ is never actually observed, no one can say for certain which method is best!

Bayesian inference is concerned with *beliefs* about what $\lambda$ might be. Rather than try to guess $\lambda$ exactly, we can only talk about what $\lambda$ is likely to be by assigning a probability distribution to $\lambda$.

This might seem odd at first. After all, $\lambda$ is fixed; it is not (necessarily) random! How can we assign probabilities to values of a non-random variable? Ah, we have fallen for our old, frequentist way of thinking. Recall that under Bayesian philosophy, we *can* assign probabilities if we interpret them as beliefs. And it is entirely acceptable to have *beliefs* about the parameter $\lambda$.

##### Example: Inferring behaviour from text-message data

Let's try to model a more interesting example, one that concerns the rate at which a user sends and receives text messages:

>  You are given a series of daily text-message counts from a user of your system. The data, plotted over time, appears in the chart below. You are curious to know if the user's text-messaging habits have changed over time, either gradually or suddenly. How can you model this? (This is in fact my own text-message data. Judge my popularity as you wish.)

```
figsize(12.5, 3.5)
count_data = np.loadtxt("data/txtdata.csv")
n_count_data = len(count_data)
plt.bar(np.arange(n_count_data), count_data, color="#348ABD")
plt.xlabel("Time (days)")
plt.ylabel("count of text-msgs received")
plt.title("Did the user's texting habits change over time?")
plt.xlim(0, n_count_data);
```

Before we start modeling, see what you can figure out just by looking at the chart above. Would you say there was a change in behaviour during this time period?

How can we start to model this? Well, as we have conveniently already seen, a Poisson random variable is a very appropriate model for this type of *count* data. Denoting day $i$'s text-message count by $C_i$,

$$ C_i \sim \text{Poisson}(\lambda)  $$

We are not sure what the value of the $\lambda$ parameter really is, however. Looking at the chart above, it appears that the rate might become higher late in the observation period, which is equivalent to saying that $\lambda$ increases at some point during the observations. (Recall that a higher value of $\lambda$ assigns more probability to larger outcomes. That is, there is a higher probability of many text messages having been sent on a given day.)

How can we represent this observation mathematically? Let's assume that on some day during the observation period (call it $\tau$), the parameter $\lambda$ suddenly jumps to a higher value. So we really have two $\lambda$ parameters: one for the period before $\tau$, and one for the rest of the observation period. In the literature, a sudden transition like this would be called a *switchpoint*:

$$
\lambda =
\begin{cases}
\lambda_1  & \text{if } t \lt \tau \cr
\lambda_2 & \text{if } t \ge \tau
\end{cases}
$$

If, in reality, no sudden change occurred and indeed $\lambda_1 = \lambda_2$, then the $\lambda$s posterior distributions should look about equal.

We are interested in inferring the unknown $\lambda$s. To use Bayesian inference, we need to assign prior probabilities to the different possible values of $\lambda$. What would be good prior probability distributions for $\lambda_1$ and $\lambda_2$? Recall that $\lambda$ can be any positive number. As we saw earlier, the *exponential* distribution provides a continuous density function for positive numbers, so it might be a good choice for modeling $\lambda_i$. But recall that the exponential distribution takes a parameter of its own, so we'll need to include that parameter in our model. Let's call that parameter $\alpha$.

\begin{align}
&\lambda_1 \sim \text{Exp}( \alpha ) \\\
&\lambda_2 \sim \text{Exp}( \alpha )
\end{align}

$\alpha$ is called a *hyper-parameter* or *parent variable*. In literal terms, it is a parameter that influences other parameters. Our initial guess at $\alpha$ does not influence the model too strongly, so we have some flexibility in our choice.  A good rule of thumb is to set the exponential parameter equal to the inverse of the average of the count data. Since we're modeling $\lambda$ using an exponential distribution, we can use the expected value identity shown earlier to get:

$$\frac{1}{N}\sum_{i=0}^N \;C_i \approx E[\; \lambda \; |\; \alpha ] = \frac{1}{\alpha}$$

An alternative, and something I encourage the reader to try, would be to have two priors: one for each $\lambda_i$. Creating two exponential distributions with different $\alpha$ values reflects our prior belief that the rate changed at some point during the observations.

What about $\tau$? Because of the noisiness of the data, it's difficult to pick out a priori when $\tau$ might have occurred. Instead, we can assign a *uniform prior belief* to every possible day. This is equivalent to saying

\begin{align}
& \tau \sim \text{DiscreteUniform(1,70) }\\\\
& \Rightarrow P( \tau = k ) = \frac{1}{70}
\end{align}

So after all this, what does our overall prior distribution for the unknown variables look like? Frankly, *it doesn't matter*. What we should understand is that it's an ugly, complicated mess involving symbols only a mathematician could love. And things will only get uglier the more complicated our models become. Regardless, all we really care about is the posterior distribution.

We next turn to PyMC, a Python library for performing Bayesian analysis that is undaunted by the mathematical monster we have created.

Introducing our first hammer: PyMC
-----

PyMC is a Python library for programming Bayesian analysis [3]. It is a fast, well-maintained library. The only unfortunate part is that its documentation is lacking in certain areas, especially those that bridge the gap between beginner and hacker. One of this book's main goals is to solve that problem, and also to demonstrate why PyMC is so cool.

We will model the problem above using PyMC. This type of programming is called *probabilistic programming*, an unfortunate misnomer that invokes ideas of randomly-generated code and has likely confused and frightened users away from this field. The code is not random; it is probabilistic in the sense that we create probability models using programming variables as the model's components. Model components are first-class primitives within the PyMC framework.

B. Cronin [5] has a very motivating description of probabilistic programming:

>   Another way of thinking about this: unlike a traditional program, which only runs in the forward directions, a probabilistic program is run in both the forward and backward direction. It runs forward to compute the consequences of the assumptions it contains about the world (i.e., the model space it represents), but it also runs backward from the data to constrain the possible explanations. In practice, many probabilistic programming systems will cleverly interleave these forward and backward operations to efficiently home in on the best explanations.

Because of the confusion engendered by the term *probabilistic programming*, I'll refrain from using it. Instead, I'll simply say *programming*, since that's what it really is.

PyMC code is easy to read. The only novel thing should be the syntax, and I will interrupt the code to explain individual sections. Simply remember that we are representing the model's components ($\tau, \lambda_1, \lambda_2$ ) as variables:

```
import pymc as mc

alpha = 1.0/count_data.mean()  # Recall count_data is the
                               # variable that holds our txt counts
lambda_1 = mc.Exponential("lambda_1", alpha)
lambda_2 = mc.Exponential("lambda_2", alpha)

tau = mc.DiscreteUniform("tau", lower=0, upper=n_count_data)
```

In the code above, we create the PyMC variables corresponding to $\lambda_1$ and $\lambda_2$. We assign them to PyMC's *stochastic variables*, so-called because they are treated by the back end as random number generators. We can demonstrate this fact by calling their built-in `random()` methods.

```
print "Random output:", tau.random(), tau.random(), tau.random()
```

    Random output: 4 17 67

```
@mc.deterministic
def lambda_(tau=tau, lambda_1=lambda_1, lambda_2=lambda_2):
    out = np.zeros(n_count_data)
    out[:tau] = lambda_1  # lambda before tau is lambda1
    out[tau:] = lambda_2  # lambda after (and including) tau is lambda2
    return out
```

This code creates a new function `lambda_`, but really we can think of it as a random variable: the random variable $\lambda$ from above. Note that because `lambda_1`, `lambda_2` and `tau` are random, `lambda_` will be random. We are **not** fixing any variables yet.

`@mc.deterministic` is a decorator that tells PyMC this is a deterministic function. That is, if the arguments were deterministic (which they are not), the output would be deterministic as well.

```
observation = mc.Poisson("obs", lambda_, value=count_data, observed=True)

model = mc.Model([observation, lambda_1, lambda_2, tau])
```

The variable `observation` combines our data, `count_data`, with our proposed data-generation scheme, given by the variable `lambda_`, through the `value` keyword. We also set `observed = True` to tell PyMC that this should stay fixed in our analysis. Finally, PyMC wants us to collect all the variables of interest and create a `Model` instance out of them. This makes our life easier when we retrieve the results.

The code below will be explained in Chapter 3, but I show it here so you can see where our results come from. One can think of it as a *learning* step. The machinery being employed is called *Markov Chain Monte Carlo*, which I also delay explaining until Chapter 3. This technique returns thousands of random variables from the posterior distributions of $\lambda_1, \lambda_2$ and $\tau$. We can plot a histogram of the random variables to see what the posterior distributions look like. Below, we collect the samples (called *traces* in the MCMC literature) into histograms.

```
### Mysterious code to be explained in Chapter 3.
mcmc = mc.MCMC(model)
mcmc.sample(40000, 10000, 1)
```

    [****************100%******************]  40000 of 40000 complete

```
lambda_1_samples = mcmc.trace('lambda_1')[:]
lambda_2_samples = mcmc.trace('lambda_2')[:]
tau_samples = mcmc.trace('tau')[:]
```

```
figsize(12.5, 10)
#histogram of the samples:

ax = plt.subplot(311)
ax.set_autoscaley_on(False)

plt.hist(lambda_1_samples, histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_1$", color="#A60628", normed=True)
plt.legend(loc="upper left")
plt.title(r"""Posterior distributions of the variables
    $\lambda_1,\;\lambda_2,\;\tau$""")
plt.xlim([15, 30])
plt.xlabel("$\lambda_1$ value")

ax = plt.subplot(312)
ax.set_autoscaley_on(False)
plt.hist(lambda_2_samples, histtype='stepfilled', bins=30, alpha=0.85,
         label="posterior of $\lambda_2$", color="#7A68A6", normed=True)
plt.legend(loc="upper left")
plt.xlim([15, 30])
plt.xlabel("$\lambda_2$ value")

plt.subplot(313)
w = 1.0 / tau_samples.shape[0] * np.ones_like(tau_samples)
plt.hist(tau_samples, bins=n_count_data, alpha=1,
         label=r"posterior of $\tau$",
         color="#467821", weights=w, rwidth=2.)
plt.xticks(np.arange(n_count_data))

plt.legend(loc="upper left")
plt.ylim([0, .75])
plt.xlim([35, len(count_data)-20])
plt.xlabel(r"$\tau$ (in days)")
plt.ylabel("probability");
```

### Interpretation

Recall that Bayesian methodology returns a *distribution*. Hence we now have distributions to describe the unknown $\lambda$s and $\tau$. What have we gained? Immediately, we can see the uncertainty in our estimates: the wider the distribution, the less certain our posterior belief should be. We can also see what the plausible values for the parameters are: $\lambda_1$ is around 18 and $\lambda_2$ is around 23. The posterior distributions of the two $\\lambda$s are clearly distinct, indicating that it is indeed likely that there was a change in the user's text-message behaviour.

What other observations can you make? If you look at the original data again, do these results seem reasonable?

Notice also that the posterior distributions for the $\lambda$s do not look like exponential distributions, even though our priors for these variables were exponential. In fact, the posterior distributions are not really of any form that we recognize from the original model. But that's OK! This is one of the benefits of taking a computational point of view. If we had instead done this analysis using mathematical approaches, we would have been stuck with an analytically intractable (and messy) distribution. Our use of a computational approach makes us indifferent to mathematical tractability.

Our analysis also returned a distribution for $\tau$. Its posterior distribution looks a little different from the other two because it is a discrete random variable, so it doesn't assign probabilities to intervals. We can see that near day 45, there was a 50% chance that the user's behaviour changed. Had no change occurred, or had the change been gradual over time, the posterior distribution of $\tau$ would have been more spread out, reflecting that many days were plausible candidates for $\tau$. By contrast, in the actual results we see that only three or four days make any sense as potential transition points.

###Why would I want samples from the posterior, anyways?

We will deal with this question for the remainder of the book, and it is an understatement to say that it will lead us to some amazing results. For now, let's end this chapter with one more example.

We'll use the posterior samples to answer the following question: what is the expected number of texts at day $t, \; 0 \le t \le 70$ ? Recall that the expected value of a Poisson variable is equal to its parameter $\lambda$. Therefore, the question is equivalent to *what is the expected value of $\lambda$ at time $t$*?

In the code below, let $i$ index samples from the posterior distributions. Given a day $t$, we average over all possible $\lambda_i$ for that day $t$, using $\lambda_i = \lambda_{1,i}$ if $t \lt \tau_i$ (that is, if the behaviour change has not yet occurred), else we use $\lambda_i = \lambda_{2,i}$.

```
figsize(12.5, 5)
# tau_samples, lambda_1_samples, lambda_2_samples contain
# N samples from the corresponding posterior distribution
N = tau_samples.shape[0]
expected_texts_per_day = np.zeros(n_count_data)
for day in range(0, n_count_data):
    # ix is a bool index of all tau samples corresponding to
    # the switchpoint occurring prior to value of 'day'
    ix = day < tau_samples
    # Each posterior sample corresponds to a value for tau.
    # for each day, that value of tau indicates whether we're "before"
    # (in the lambda1 "regime") or
    #  "after" (in the lambda2 "regime") the switchpoint.
    # by taking the posterior sample of lambda1/2 accordingly, we can average
    # over all samples to get an expected value for lambda on that day.
    # As explained, the "message count" random variable is Poisson distributed,
    # and therefore lambda (the poisson parameter) is the expected value of
    # "message count".
    expected_texts_per_day[day] = (lambda_1_samples[ix].sum()
                                   + lambda_2_samples[~ix].sum()) / N

plt.plot(range(n_count_data), expected_texts_per_day, lw=4, color="#E24A33",
         label="expected number of text-messages recieved")
plt.xlim(0, n_count_data)
plt.xlabel("Day")
plt.ylabel("Expected # text-messages")
plt.title("Expected number of text-messages received")
plt.ylim(0, 60)
plt.bar(np.arange(len(count_data)), count_data, color="#348ABD", alpha=0.65,
        label="observed texts per day")

plt.legend(loc="upper left")
```

Our analysis shows strong support for believing the user's behavior did change ($\lambda_1$ would have been close in value to $\lambda_2$ had this not been true), and that the change was sudden rather than gradual (as demonstrated by $\tau$'s strongly peaked posterior distribution). We can speculate what might have caused this: a cheaper text-message rate, a recent weather-to-text subscription, or perhaps a new relationship. (In fact, the 45th day corresponds to Christmas, and I moved away to Toronto the next month, leaving a girlfriend behind.)

##### Exercises

1\.  Using `lambda_1_samples` and `lambda_2_samples`, what is the mean of the posterior distributions of $\lambda_1$ and $\lambda_2$?

```
#type your code here.
```

2\.  What is the expected percentage increase in text-message rates? `hint:` compute the mean of `lambda_1_samples/lambda_2_samples`. Note that this quantity is very different from `lambda_1_samples.mean()/lambda_2_samples.mean()`.

```
#type your code here.
```

3\. What is the mean of $\lambda_1$ **given** that we know $\tau$ is less than 45.  That is, suppose we have been given new information that the change in behaviour occurred prior to day 45. What is the expected value of $\lambda_1$ now? (You do not need to redo the PyMC part. Just consider all instances where `tau_samples < 45`.)

```
#type your code here.
```

### References

-  [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. <http://andrewgelman.com/2005/07/n_is_never_larg/>.
-  [2] Norvig, Peter. 2009. [*The Unreasonable Effectiveness of Data*](http://www.csee.wvu.edu/~gidoretto/courses/2011-fall-cp/reading/TheUnreasonable EffectivenessofData_IEEE_IS2009.pdf).
- [3] Patil, A., D. Huard and C.J. Fonnesbeck. 2010.
PyMC: Bayesian Stochastic Modelling in Python. Journal of Statistical
Software, 35(4), pp. 1-81.
- [4] Jimmy Lin and Alek Kolcz. Large-Scale Machine Learning at Twitter. Proceedings of the 2012 ACM SIGMOD International Conference on Management of Data (SIGMOD 2012), pages 793-804, May 2012, Scottsdale, Arizona.
- [5] Cronin, Beau. "Why Probabilistic Programming Matters." 24 Mar 2013. Google, Online Posting to Google . Web. 24 Mar. 2013. <https://plus.google.com/u/0/107971134877020469960/posts/KpeRdJKR6Z1>.

```
from IPython.core.display import HTML
def css_styling():
    styles = open("../styles/custom.css", "r").read()
    return HTML(styles)
css_styling()
```

<style>
    @font-face {
        font-family: "Computer Modern";
        src: url('http://mirrors.ctan.org/fonts/cm-unicode/fonts/otf/cmunss.otf');
    }
    div.cell{
        width:800px;
        margin-left:16% !important;
        margin-right:auto;
    }
    h1 {
        font-family: Helvetica, serif;
    }
    h4{
        margin-top:12px;
        margin-bottom: 3px;
       }
    div.text_cell_render{
        font-family: Computer Modern, "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
        line-height: 145%;
        font-size: 130%;
        width:800px;
        margin-left:auto;
        margin-right:auto;
    }
    .CodeMirror{
            font-family: "Source Code Pro", source-code-pro,Consolas, monospace;
    }
    .prompt{
        display: None;
    }
    .text_cell_render h5 {
        font-weight: 300;
        font-size: 22pt;
        color: #4057A1;
        font-style: italic;
        margin-bottom: .5em;
        margin-top: 0.5em;
        display: block;
    }

    .warning{
        color: rgb( 240, 20, 20 )
        }
</style>

```

```


```python
%run ../../common/import_all.py

from common.setup_notebook import *
config_ipython()
setup_matplotlib()
set_css_style()
```

<style>

    /* DOWNLOAD COMPUTER MODERN FONT JUST IN CASE */
    @font-face {
        font-family: "Computer Modern";
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunss.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsx.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunsi.otf');
    }
    @font-face {
        font-family: "Computer Modern";
        font-weight: bold;
        font-style: oblique;
        src: url('http://9dbb143991406a7c655e-aa5fcb0a5a4ec34cff238a2d56ca4144.r56.cf5.rackcdn.com/cmunso.otf');
    }

    /* GLOBAL TEXT FONT */
    div#notebook,
    div.output_area pre,
    div.output_wrapper,
    div.prompt {
      font-family: Times new Roman, monospace !important;
    }

    /* CENTER FIGURE */
    .output_png {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }

    /* LINK */
    a {
        color: #FF8000;
    }

    /* H1 */
    h1 {
        font-size: 42px !important;
        text-align: center;
        color: #FF8000;
    }

    /* H2 */
    h2 {
        font-size: 32px !important;
    }

    /* H2 */
    h3 {
        font-size: 24px !important;
    }

    /* H2 */
    h4 {
        font-size: 20px !important;
    }

    /* PARAGRAPH */
    p {
        font-size: 16px !important;
        text-align: center;
    }

    /* LIST ITEM */
    li {
        font-size: 16px !important;
    }

</style>

# <center> Moments of a distribution and summary statistics

In the following, we will use $X$ to represent a random variable living in sample space (the space of all possible values it can assume) $\Omega$.

In the discrete case, the probability of each value $x_i$ will be represented as $p_i$ (probability mass function); in the continuous case $p(x) = P(X=x)$ will be the probability density function. See [the note on probability functions](probfunctions.ipynb).

Let's start with mean and variance and then we'll then give the general definitions. Also, we'll then switch to other quantities beyond moments which help drawing a comprehensive picture of how data is distributed.

## Expected Value

The **expected value**, or **expectation**, or **mean value** is defined, in the *continuous* case as

$$
\mathbb{E}[X] = \int_\Omega \text{d} x \ x p(x) \ ,
$$

Similarly, in the *discrete* case,

$$
\mathbb{E}[X] = \sum_i^N p_i x_i \ ,
$$

The expectation is the average of all the possible values the random variable can assume. It is the arithmetic mean in the case of discrete variables. This is easy to see if the distribution is uniform, that is, all $N$ values have the same probability $\frac{1}{N}$: the expectation becomes $\frac{1}{N}\sum_i x_i$, which is the exact definition of arithmetic mean. When the distribution is not uniform, the probability is not the same for each value, but the end result is still the arithmetic mean as each different value will be weighted with its probability of occurrence, that is, the count of them over the total of values.

The expected value is typically indicated with $\mu$.

### Linearity of the expected value

The expected value is a linear operator:

$$
\mathbb{E}[aX + bY] = a\mathbb{E}[X] + b \mathbb{E}[Y]
$$

*Proof*

We will prove this in the continuous case but it is clearly easily extensible.

$$
\begin{align}
\mathbb{E}[aX + bY] &= \int_{\Omega_X}\limits \int_{\Omega_Y}\limits \text{d} x \ \text{d} y \ (ax + by) p(x, y) \\
&= a \int_{\Omega_X}\limits \int_{\Omega_Y}\limits \text{d} x \ \text{d} y \ x p(x, y) + b \int_{\Omega_X}\limits \int_{\Omega_Y}\limits \text{d} x \ \text{d} y \ y p(x, y) \\
&= a \int_{\Omega_X}\limits \text{d} x \ x p(x) + b \int_{\Omega_Y}\limits \text{d} y \ y p(y) \\
&= a\mathbb{E}[X] + b \mathbb{E}[Y]
\end{align}
$$

This is because $p(x) = \int_{\Omega_Y}\limits\text{d} y \  x p(x, y)$ because we are effectively summing the PDFs over all the possible values of $Y$, hence eliminating the dependency from this random variable. Analogously the other one.

### Expectation over two variables

We have

$$
\mathbb{E}_{x, y}[A] = \mathbb{E}_x[\mathbb{E}_y[A | x]]
$$

*Proof*

By definition

$$
\mathbb{E}_{x, y}[A] = \int \,dx \,dy \, p(x, y) \, A
$$

and from the definition of [conditional and joint probability](joint-marg-conditional-prob.ipynb),

$$
p(x, y) = p(y|x) p(x) \ .
$$

So, we can write

$$
\mathbb{E}_{x, y}[A] = \int \, dx \, dy A \, p(y|x)p(x)
$$

which is exactly the second term in the statement.

## Variance and standard deviation

The variance is the expected value of the squared difference from the expectation:

$$
Var[X] = \mathbb{E}[(X - \mathbb{E}[X])^2] =  \int_{\Omega_X} \text{d} x \ (x - \mathbb{E}[X])^2 p(x)
$$

The variance is the second moment around the mean. It is typically indicated as $\sigma^2$, $\sigma$ being the **standard deviation**, which gives the measure of error of values from the mean.

### Rewriting the variance

We can also write the variance as

$$
Var[X] = \mathbb{E}[X^2] - \big(\mathbb{E}[X]\big)^2
$$

*Proof*

$$
\begin{align}
Var[X] &= \mathbb{E}[(X - \mu)^2] \\
&= \int_{\Omega_X} \text{d}x \ (x^2 - 2 \mu x + \mu^2) p(x) \\
&= \int_{\Omega_X} \text{d}x \ x^2 p(x) -2 \mu \int_{\Omega_X} \text{d}x \ x p(x) + \mu^2 \int_{\Omega_X} \text{d} x p(x) \\
&= \mathbb{E}[X^2] - 2 \mu^2 + \mu^2 \\
&= \mathbb{E}[X^2] - \big(\mathbb{E}[X]\big)^2
\end{align}
$$

### The variance is not linear

In fact, using the linearity of the expectation

$$
\begin{align}
Var[aX] &= \mathbb{E}[(aX)^2] - \big( \mathbb{E}[aX] \big)^2 \\
&= a^2 \mathbb{E}[X^2] - (a^2 \mu^2) \\
&= a^2 (\mathbb{E}[X^2] - \mu^2) \\
&= a^2 Var[X]
\end{align}
$$

and more in general,

$$
\begin{align}
Var[aX + bY] &= \mathbb{E}[(aX + bY)^2] - \big( \mathbb{E}[aX+bY] \big)^2 \\
&= \mathbb{E}[a^2 X^2 + b^2 Y^2 + 2ab XY] - \big( a \mathbb{E}[X] + b \mathbb{E}[Y] \big)^2 \\
&= a^2\mathbb{E}[X^2] + b^2\mathbb{E}[Y^2] + 2ab\mathbb{E}[XY] - a^2(\mathbb{E}[X])^2 - b^2(\mathbb{E}[Y])^2 - 2ab\mathbb{E}[X]\mathbb{E}[Y] \\
&= a^2 Var[X] + b^2 Var[Y] + 2ab \ \text{cov}(X, Y)
\end{align}
$$

($\text{cov}$ is the covariance).

## The unbiased estimator of variance and standard deviation

If we have $n$ data points, extracted from a population (so we have a sample, refer to figure) and we want to calculate its variance (or standard deviation), using $n$ in the denominator would lead to a biased estimation. We would in fact use $n$ in the case we had the full population, in the case of a sample we have to use $n-1$ and this is because the degrees of freedom are $n-1$ as the mean is computed from $n$ data points so there is one less.

For the mean, if $\mu$ is the one computed with the full population and $\bar x$ the one computed with the sample, which is the estimator of $\mu$,

$$
\bar x = \frac{\sum_{i=1}^{i=n} x_i}{n}
$$

For the variance, calling $\sigma^2$ the one computed with the full population and $s^2$ the one computed with the sample, we have

$$
s_n^2 = \frac{\sum_{i=1}^{i=n} (x_i - \bar x)^2}{n}
$$

and

$$
s_{n-1}^2 = \frac{\sum_{i=1}^{i=n} (x_i - \bar x)^2}{n-1}
$$

with subscript $n$ or $n-1$ indicating, respectively, with which denominator they are calculated.

$s_n^2$ is a biased estimator of the population variance (it contains the mean, which itself eats one degree of freedom) and we have $s_n^2 < s_{n-1}^2$. This last one is the correct estimator of the population variance when you have a sample.

## Standard deviation and standard error

Refer again to the above about sample and population. The population follows a certain distribution, of which the distribution of the sample is an "approximation". This is why we have to use the sample mean (the mean of data points in the sample) as an estimate of the (unknown) population mean. The problem is now how to attribute the error to this value.

In general, following definition, what the standard deviation quantifies is the variability of individuals from the mean. Having the sample, the sample standard deviation tells how far away each sample point is from the sample mean.

Now because we're using the sample mean to estimate the mean (expected value) of the population, and because if we had another sample extracted from the same population this sample mean would likely be different, in general this sample mean follows its distribution. The *standard error* (of the mean, as it can be related to other statistics), typically indicated by *SE*, is the standard deviation of these means.

The standard error is usually estimated by the sample standard deviation $s$ divided by the square root of the sample size $n$:

$$
SE = \frac{s}{\sqrt{n}} \ ,
$$

under the assumption of statistical independence of observations in the sample.

In fact, let $x_1, \ldots, x_n$ be the sample points extracted from a population whose mean and standard deviation are, respectively, $\mu$ and $\sigma$, the sample mean is

$$
m = \frac{x_1 + \cdots + x_n}{n} \ .
$$

The variance of this sample mean $m$, telling how far away the sample mean is from the population mean, is

$$
Var[m] = Var \left[\frac{\sum_i x_i}{n}\right] =
\frac{1}{n^2} Var\Big[\sum_i x_i\Big] = \frac{1}{n^2} \sum_i Var[x_i]
= \frac{1}{n^2} n Var[x_1]
= \frac{1}{n} \sigma^2 \ ,
$$

because each point has the same variance and the points are independent. See above for the non-linearity of the variance for the details on this calculation. Following this, the standard deviation of $m$ is then $\frac{\sigma}{\sqrt{n}}$ and we will use $s$ as an estimate for $\sigma$, which is, again, unknown.

### When to use which

The Standard Error tells how far the sample mean is from the population mean so it is the error to attribute to a sample mean. The standard deviation again is about the individual data points and it tells how far away they are from the sample mean.

While the standard error goes to 0 when $n \to \infty$, the standard deviation goes to $\sigma$.

## Moments: general definition

The $n$-th **raw moment** is the expected value of the $n$-th power of the random variable:

$$
\boxed{\mu_n' = \int \text{d} x \ x^n p(x)}
$$

The expected value is then the first raw moment.

The $n$-th **central moment** around the mean is defined as

$$
\boxed{\mu_n = \int \text{d} x (x-\mu)^n p(x)}
$$

The variance is the second central moment around the mean.

Moments get standardises (normalised) by dividing for the appropriate power of the standard deviation. The $n$-th **standardised moment** is the central moment divided by standard deviation with the same order power:

$$
\boxed{\tilde \mu_n = \frac{\mu_n}{\sigma^n}}
$$

## Skeweness

The **skeweness** is the third standardised moment:

$$
\gamma = \frac{\mathbb{E}[(X-\mu)^3]}{\sigma^3}
$$

The skeweness quantifies how symmetrical a distribution is around the mean: it is zero in the case of a perfectly symmetrical shape. It is positive if the distribution is skewed on the right, that is, if the right tail is heavier than the left one; it is negative if it is skewed on the left, meaning the left tail is heavier than the right one.

## Kurtosis

The **kurtosis** is the fourth standardised moment:

$$
\kappa = \frac{\mu_4}{\sigma^4}
$$

It measures how heavy the tail of a distribution is with respect to a gaussian with the same $\sigma$.

## Further results

### Variance of a matrix of constants times a random vector

In general, with a matrix of constants $\mathbf{X}$ and a vector of observations (random variables) $\mathbf{a}$, using the linearity of the expected value so that $\mathbb{E}[\mathbf{X a}] = \mathbf{X} \mathbb{E}[\mathbf{a}]$, we have

$$
\begin{align}
    Var[\mathbf{X a}] &= \mathbb{E}[(\mathbf{X a} - \mathbb{E}[\mathbf{X a}])^2] \\
                      &= \mathbb{E}[(\mathbf{X a} - \mathbb{E}[\mathbf{X a}])(\mathbf{X a} - \mathbb{E}[\mathbf{X a}])^t] \\
                      &= \mathbb{E}[(\mathbf{X a} - \mathbf{X}\mathbb{E}[\mathbf{a}])(\mathbf{X a} - \mathbf{X}\mathbb{E}[\mathbf{a}])^t] \\
                      &= \mathbb{E}[(\mathbf{X a} - \mathbf{X}\mathbb{E}[\mathbf{a}])((\mathbf{X a})^t - (\mathbf{X}\mathbb{E}[\mathbf{a}])^t)] \\
                      &= \mathbb{E}[\mathbf{Xa}\mathbf{a}^t\mathbf{X}^t - \mathbf{Xa} \mathbb{E}[\mathbf{a}]^t \mathbf{X}^t - \mathbf{X} \mathbb{E}[\mathbf{a}]\mathbf{a}^t\mathbf{X}^t + \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}]^t\mathbf{X}^t] \\
                      &=  \mathbf{X} \mathbb{E}[\mathbf{a}\mathbf{a}^t] \mathbf{X}^t - \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}]^t \mathbf{X}^t - \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}^t] \mathbf{X}^t + \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}^t] \mathbf{X}^t \\
                      &= \mathbf{X} \mathbb{E}[\mathbf{a}\mathbf{a}^t] \mathbf{X}^t - 2 \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}]^t \mathbf{X}^t + \mathbf{X} \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}^t] \mathbf{X}^t = \\
                      &= \mathbf{X} (\mathbb{E}[\mathbf{a} \mathbf{a}^t] - \mathbb{E}[\mathbf{a}] \mathbb{E}[\mathbf{a}^t]) \mathbf{X}^t = \\
                      &= \mathbf{X} Var[\mathbf{a}] \mathbf{X}^t
\end{align}
$$

## Let's see all this on some known distributions!

We will extract $n$ values from several distributions, one at a time, and see what happens to the moments.

```python
n = 100000                                                          # the number of points to extract

g = np.random.normal(size=n)                                           # gaussian
e = np.random.exponential(size=n)                                      # exponential
p = np.random.power(a=0.5, size=n)                                     # power-law x^{0.5}, or a sqrt
z = np.random.zipf(a=2, size=n)                                        # Zipf (power-law) x^{-2}
```

### The gaussian

The gaussian will be the comparison distribution we refer to. Why? Because it's the queen of distributions!

```python
# Use 100 bins
bins = 100

hist = np.histogram(g, bins=bins)
hist_vals, bin_edges = hist[0], hist[1]
bin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)]     # middle point of bin

plt.plot(bin_mids, hist_vals, marker='o')

plt.title('Histogram $10^5$ normally distributed data')
plt.xlabel('Bin mid')
plt.ylabel('Count items')
plt.show();
```

```python
'The mean is %s, the std %s' % (np.mean(g), np.std(g))
'The skeweness is %s, the kurtosis %s' % (stats.skew(g), stats.kurtosis(g))
```

    'The mean is -0.000640742485484, the std 0.999986499155'

    'The skeweness is 0.01838211229141485, the kurtosis -0.025766042470362294'

Clearly, the mean is 0 (we've taken values this way!); the skeweness is also 0 as the data is normally distributed, hence symmetrical, and the kurtosis comes as 0 because Scipy gives, [by default](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.kurtosis.html), the Fisher version of it, which subtracts 3 so that a normal distribution has 0 kurtosis.

### The exponential

Same plot as for the gaussian, except that we will also plot it in semilog scale (on the $y$), where the distribution appears linear.

```python
# Use 100 bins
bins = 100

hist = np.histogram(e, bins=bins)
hist_vals, bin_edges = hist[0], hist[1]
bin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)]     # middle point of bin

# Main plot: in linear scale
plt.plot(bin_mids, hist_vals)
plt.xlabel('Bin mid')
plt.ylabel('Count items')
plt.title('Histogram $10^5$ exponentially distributed data')

# Inset plot: in semilog (on y)
a = plt.axes([.4, .4, .4, .4], facecolor='y')
plt.semilogy(bin_mids, hist_vals)
plt.title('In semilog scale')
plt.ylabel('Count items')
plt.xlabel('Bin mid')

plt.show();
```

```python
'The mean is %s, the std %s' % (np.mean(e), np.std(e))
'The skeweness is %s, the kurtosis %s' % (stats.skew(e), stats.kurtosis(e))
```

    'The mean is 1.00304878455, the std 0.996973171878'

    'The skeweness is 1.9954113378643468, the kurtosis 6.02308754016868'

This time, the distribution is not symmetrical.

### The power law

We chose to extract numbers from a [power law](power-law.ipynb) with exponent $-0.7$ (see the [docs](https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.power.html#numpy.random.power)). Because of this, it is so much better to bin logarithmically, that is, with a bin width growing logarithmically. If we also choose a log-log scale, we get a line. Let's do it.

```python
# Use 100 bins
bins = np.logspace(0, 4, num=100)

hist = np.histogram(z, bins=bins)
hist_vals, bin_edges = hist[0], hist[1]
bin_mids = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges) -1)]     # middle point of bin

# Main plot: in linear scale
plt.plot(bin_mids, hist_vals)
plt.xlabel('Bin mid')
plt.ylabel('Count items')
plt.title('Histogram $10^5$ pow-law distributed data')

# Inset plot: in semilog (on y)
a = plt.axes([.4, .4, .4, .4], facecolor='y')
plt.loglog(bin_mids, hist_vals)
plt.title('In log-log scale')
plt.ylabel('Count items')
plt.xlabel('Bin mid')

plt.show();
```

Clearly because it is a power law, a linear graph is really useless, can't really see anything. The inset shows the linear trend in log-log scale.

```python
'The mean is %s, the std %s' % (np.mean(z), np.std(z))
'The skeweness is %s, the kurtosis %s' % (stats.skew(z), stats.kurtosis(z))
```

    'The mean is 37.28617, the std 7991.95971848'

    'The skeweness is 299.37959397823863, the kurtosis 92083.86568826315'

Now, this is a heavy-tail, and the kurtosis is quite verbal about it.

## Mode

The mode of a distribution is simply its most frequent value.

## Quantiles

Quantiles are the values which divide a probability distribution into equally populated sets, how many, you decide. As special types of quantiles you got

* *deciles*: 10 sets, so the first decile is the value such that 10% of the observations are smaller and the tenth decile is the value such that 90% of the observations are smaller
* *quartiles*: 4 sets, so the first quartile is such that 25% of the observations are smaller
* *percentile*: 100 sets, so the first percentile is such that 1% of the observations are smaller

The second quartile, corresponding to the fifth decile and to the fiftieth percentile, is kind of special and is called the *median*. Note that unlike the mean, the median is a measure of centrality in the data which is non-sensible to outliers.

This all means you can use the percentile everywhere as it's the most fine-grained one, and calculate the other splits from them. This is in fact what Numpy does, for this reason, and we'll see it below.

Quartiles are conveniently displayed all together in a box plot, along with outliers.

### Trying them out

Let's extract 1000 numbers from a given distribution and let's compute the quartiles. We use `numpy.percentile(array, q=[0, 25, 50, 75, 100])`. Note that the quartile 0 and the quartile 100 correspond respectively to the minimum and maximum of the data.

#### On a uniform distribution, between 0 and 1

```python
u = np.random.uniform(size=1000)

np.percentile(u, q=[0, 25 , 50, 75, 100])
min(u), max(u)
```

    array([0.00205504, 0.27189483, 0.52432025, 0.75195201, 0.99904427])

    (0.0020550371300288583, 0.999044272466301)

#### On a standard gaussian (mean 0, std 1)

Note the median is the mean, that is, in this case, 0. It won't be precisely, because of finite size effect. A gaussian is such that median, mean and mode coincide, doesn't this make it great?

```python
g = np.random.normal(size=1000)

np.percentile(g, q=[0, 25 , 50, 75, 100])
```

    array([-3.48444618, -0.61679718,  0.05202165,  0.68962899,  3.38339965])

#### On a power law with exponent -0.3

Can see that they span orders of magnitude.

```python
p = np.random.power(0.7, size=1000)

np.percentile(p, q=[0, 25 , 50, 75, 100])
```

    array([5.58878867e-05, 1.48743304e-01, 3.93775538e-01, 6.76276735e-01,
           9.99854544e-01])

### The inter-quartile range (IQR)

It is the difference between the third and first quartile and gives a measure of dispersion of the data. It is also sometimes called *midspread*. Note that it is a robust measure of dispersion specifically because it works on quartiles.

$$
IQR = Q_3 - Q-1
$$

The IQR can be used to *test the normality of a distribution* at a simple level, because the quartiles of a normal (standardised) distribution are known so calculated ones can be compared to them.

It is also used in *spotting outliers*: the Tukey's range test defines outliers as those points that fall below $Q_1 - 1.5 IQR$ and above $Q_3 + 1.5 IQR$.

```python

```


# Day 1. Introduction to the Notebook and NumPy

* [Navigating the Notebook](#1)
* [Python built-in functions](#2)
* [Storage and manipulation of numerical arrays](#3)
* [Repeated operations and universal functions](#4)

The answers to the exercises are encrypted. Feel free to ask the instructors for the decryption key whenever you need to view the solution.

```python
from IPython.display import IFrame
from IPython.display import YouTubeVideo
```

```python
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
```

```python
from cryptography.fernet import Fernet
import base64
def encrypt(string, key):
    keygen = lambda x : base64.urlsafe_b64encode(x.encode() + b' '*(32 - len(x)))
    cipher = Fernet(keygen(key))
    return cipher.encrypt(string.encode())
def decrypt(string, key):
    keygen = lambda x : base64.urlsafe_b64encode(x.encode() + b' '*(32 - len(x)))
    cipher = Fernet(keygen(key))
    return print(cipher.decrypt(string.encode()).decode())
```

## Familiarize yourself with

* create a new [environment](https://conda.io/docs/user-guide/concepts.html#conda-environments):
  - go to the terminal (or to the anaconda prompt on Windows) and [make sure](https://conda.io/docs/user-guide/tasks/manage-environments.html#determining-your-current-environment) that no environment is acrivated (else [deactivate](https://conda.io/docs/user-guide/tasks/manage-environments.html#deactivating-an-environment) it)
  - decide on the name of your new environment (_i.e._ `[env_name]`)
  - run `conda create -n [env_name]`
* [activate](https://conda.io/docs/user-guide/tasks/manage-environments.html#activating-an-environment) the new environment
* install the following packages in the new environment:
  - python=3.6
  - mdtraj=1.9 from the `conda-forge` channel (`conda install -c conda-forge mdtraj=1.9`)
  - R from the `r` channel (the package is called r-essentials)
* list the packages installed in the environment (`conda list`)
* deactivate the environment
* [export](https://conda.io/docs/user-guide/tasks/manage-environments.html#sharing-an-environment) the environment to a yml file (be careful not to overwrite any yml file in your current directory)
* [view a list](https://conda.io/docs/user-guide/tasks/manage-environments.html#viewing-a-list-of-your-environments) of all your conda environments
* [remove](https://conda.io/docs/user-guide/tasks/manage-environments.html#removing-an-environment) the environment that you have just created

## Use [Binder](https://mybinder.org/) to launch a GitHub repository

* go to mybinder.org and launch a GitHub repository containing Jupyter Notebooks of your choice
* navigate and run a Notebook in the executable environment
* be aware that the repository has to contain a dependency file (_e.g._ the yml file containing the list of packages of a conda environment)
* Binder uses the dependency file to build a Docker [container](https://www.docker.com/resources/what-container) image of the repository
  - "A container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings." (excerpt from docker.com)

# Navigating the Notebook

```python
IFrame(src='https://api.kaltura.nordu.net/p/310/sp/31000/embedIframeJs/uiconf_id/23449977/partner_id/310?iframeembed=true&playerId=kaltura_player&entry_id=0_z85if4is&flashvars[streamerType]=auto&flashvars[localizationCode]=en&flashvars[leadWithHTML5]=true&flashvars[sideBarContainer.plugin]=true&flashvars[sideBarContainer.position]=left&flashvars[sideBarContainer.clickToClose]=true&flashvars[chapters.plugin]=true&flashvars[chapters.layout]=vertical&flashvars[chapters.thumbnailRotator]=false&flashvars[streamSelector.plugin]=true&flashvars[EmbedPlayer.SpinnerTarget]=videoHolder&flashvars[dualScreen.plugin]=true&&wid=0_l2d1egty', width=608, height=402)
```

### Tasks

1. Find and try out the keyboard shortcuts (Help > Keyboard Shortcuts) for
   - Toggling line numbers
   - Setting the cell to _code_
   - Setting the cell to _markdown_
   - Merging two consecutive cells
   - Inserting a cell above
   - Inserting a cell below
   - Deleting a cell
2. Export this notebook as HTML and open it in a web-browser
3. Go back to the Home page (usually a browser tab) and check which notebooks that are currently running

## Output

The result from running a code cell is shown as output directly below it. In particular, the output from the _last_ command will be printed, unless explicitly suppressed by a trailing `;`

Previous output can be retrieved by:
- `_` last output
- `__` last last output
- `_x` where `x` is the cell number.

### Tasks
- Retrieve the output of the following cell
- Suppress the output of the following cell

```python
a = 3
a
```

## Getting help

- `shift`-`tab`-`tab`: access information about python functions (place cursor between brackets)
- `tab`: tab complete functions and objects
- `?command` or `command?`
- The help menu has links to detailed help on Python, Markdown, Matplotlib etc.

### Task

Use the above different ways to explore the arguments for the `print()` function.
What is the `end` argument for?

## Documentation using Markdown

Markdown is a _lightweight_ markup language that

- is intended to be as easy-to-read and easy-to-write as possible
- supports equations ($f(x)=x$), [links](http://), ~~text formatting~~, tables, images etc.

For more information see [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).

### Task 1

Use a Markdown cell to explain Pythagoras' theorem. Your answer should include

- headers and text formatting
- a link to an external web page
- [LaTeX math](https://jupyter-notebook.readthedocs.io/en/stable/examples/Notebook/Typesetting%20Equations.html)

_Hint:_ images need not be local, but can be linked via a URL.

```python
answer = 'gAAAAABcAVG3y9adFC6juLwdCUxdFnKhUDK9gqLlTTrVNfiedLFxfKdZqWayixC54-Anq9BhGQZvoWBm-AzZMyDhmsfFKIWkrhe9KR-9bwwXho5axladf90oUcqO3gBRYcOHt1nixpfl4ExV2z7Fr-xsxLyIpCzz6K2e0BvagxTonkRQNApDU_qZ6PGTVzpjq9VvgIj_xIQkSt0GEvUI0vtOdZUPly8eszQorUXGbGqIgt5aeE4YVQrnwWRAkwErK9_SdSNNqzWUwnraM_GhnjeFDIMFEbrpSxGYZomAy8N5zqWQIYGbi7jJkPePqIGqYdoM2Anceb_9IrZHQEaap18pBwLU6-Mkwx6k1uCc26eQBdKsUbk36zVKcvt-FeHojYSXtCF3CsDb40nE_b7oBBh5we1fI9IWLSaaOv6NlQVUD0uM5qze7w8BegBmLtMbdwlX9lqx2UC1'

```

```python
decrypt(answer,)
```

### Task 2

1. Use a markdown cell to create a table with column labels **Element**, **Symbol**, **Atomic number**, and a single row with **Hydrogen**, **H**, and **1**.
2. In a *code cell*, import the `Markdown` function from `IPython` using
   ```.py
   from IPython.display import Markdown
   ```
   and explore its documentation.
3. Redo subquestion 1 using the `Markdown` command:
    - write the markdown table as a string (use triple quotation marks or write it on a single line using the line escape sequence \n)
    - populate the table using a [formatted Python string](https://pyformat.info)

```python
answer = 'gAAAAABcAVHzAOYjHRhWhK28NdM61aXfc9hOcExm9TdQPvYCRa50Es4vPadouW4usg3AIm5zdbuYycJMkJ8HvGHmp-AOZcKT0W6XrSXMO8yZz44rUNWMYvT-re4ZVFx-om_Vtsj6bcWLAupO2QHKxZdRh2bl5o4sy8s-0yposy8g4CIGMC0OZs18nBru06xRa9DeLQhxBENMu7FqdC4XU9Bs_fIYtR8WJP5U3suk8O8bXX4AQlkfSCWGsCo-0729C0h6K3k2CkVFoMlnZnXCjpxND9pj5okvZNIsAR2-4KU_T6_AyP_8ifI1w4Xloe_hWourVdpagznZ3I16KLjFI9HdAC6kPeV1ao3Pm9-uKWhjq7oZWLj-aOgfBJeq3GKjyNSJ_r2RBa9bWU2hM9az05h-KtazArxp7_zdq3RDijC5NMgL6_Cyhut5G4Q243K6YiGBlrIWPC7lFhmmgsowExlBKWQne5Z6AQgYfHWPnoEteS-grvqN0iwuRT2PS1hv36RG4a6-O65HL0oQ9oslKmzCJCmd9UNoTBp_oMHWxE2kc-2lnZlB7BwrcsHhVXtrkap8tce0tyj_N3RksSJ6XN-CNoRklAA8UwbFjzSGBr20Q6HdL3QJ5o1r6gxvG06bFNx-iJvc_ALTjyIc9ZKXZnsWOoMymG-L_4FCejCKrLqHFonT2lsrn_dOZ5qVu5KQr4MzDwcxhBFlRYpHUcOCtj2wSqEM0f-ycCUZMveuJueC7s2uOKDXQQy0ZjtiZaW0VUoV-tJlwoWzlSjJvtRSLINESXfi9e60Xw=='
```

```python
decrypt(answer,)
```

### Task: Embedded web content

Lund University Publications ([LUP](https://lup.lub.lu.se/search)) allows you to search for publications from specific LU departments or authors. They also provide the possibility to _embed_ the search result. Use `IPython.display.IFrame` to display a search of your choice.

```python
# Here's an example showing a protein - replace with something from LUP!
from IPython.display import IFrame
IFrame(src="http://www.ncbi.nlm.nih.gov/Structure/icn3d/full.html?pdbid=4lzt", width=800, height=400)
```

##  IPython Magic commands
- Line magic (`%`): operates on a single line and can be mixed with other languages
- Cell magic (`%%`): operates on the whole cell
- [More info](http://ipython.readthedocs.io/en/stable/interactive/magics.html)

```python
%lsmagic
```

This is an example of a LaTeX cell

```latex
%%latex

\begin{equation}
    G_O = \int_0^\infty \mathrm{d}r\; 4 \pi r^2 \left [ g_O(r) -1 \right ]
\end{equation}
```

This is an example of an [SVG](https://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html) cell

```python
%%svg

<svg height="100" width="400">
  <style>
    .bold { font: bold 40px sans-serif; }
    .italic { font: italic 30px serif; }
  </style>
  <defs>
    <marker id="arrowS" markerWidth="15" markerHeight="15" refX="0" refY="3"
        orient="180" markerUnits="strokeWidth" viewBox="0 0 20 20">
      <path d="M0,0 L0,6 L9,3 z" fill="black" />
    </marker>
    <marker id="arrowE" markerWidth="15" markerHeight="15" refX="0" refY="3"
        orient="0" markerUnits="strokeWidth" viewBox="0 0 20 20">
      <path d="M0,0 L0,6 L9,3 z" fill="black" />
    </marker>
  </defs>
  <circle cx="50" cy="50" r="40" stroke="blue" stroke-width="6" fill="transparent" />
  <circle cx="300" cy="50" r="40" stroke="red" stroke-width="6" fill="transparent" />
  <text x="38" y="60" fill="blue" class="bold">+</text>
  <text x="294" y="61" fill="red" class="bold">-</text>
  <text x="170" y="43" fill="black" class="italic">r</text>
  <line x1="110" y1="50" x2="240" y2="50" style="stroke:black; stroke-width:2"
    stroke-dasharray="5,2" marker-start="url(#arrowS)" marker-end="url(#arrowE)" />
</svg>
```

### [Shell commands](https://jakevdp.github.io/PythonDataScienceHandbook/01.05-ipython-and-shell-commands.html)

* find the path of the current directory using `%pwd`
* create a new directory using `%mkdir`
* enter the new directory using `%cd`
* find the path of the current directory using `%pwd`
* get back to the parent directory using `%cd`
* view a list of files and folders in the current directory with `%ls`
* use `%cat` to view the environment.yml file of the course repository

Besides the Magic commands, any command that works on your terminal can be run in the Notebook by prepending an exclamation mark! These commands are executed in a temporary subshell, _e.g._, compare the output of the following two cells.

N.B. The command to remove a nonempty folder on Windows is `rmdir /Q /S <dirname>`

```python
%mkdir new_dir
%cd new_dir
%pwd
%ls
%cd ..
%pwd
%rm -r new_dir
```

```python
%mkdir new_dir
!cd new_dir
!ls
!pwd
!cd ..
!pwd
%rm -r new_dir
```

### Task 3
  - Write a script in a Python cell which creates and deletes this directory tree:
    ```bash
    .
    └── new_dir
        ├── dir_1
        ├── dir_2
        ├── dir_3
        └── dir_4
    ```
  - To write your script, translate the following bash shell.

```bash
%%bash

mkdir new_dir
cd new_dir
for i in {1..4}
do
mkdir dir_$i
done
cd ..
rm -r new_dir
```

```python
answer = 'gAAAAABcASqXgQ5RM5983tgSRo4nD-XKkEiKOpq95dvnucHN62hTjGmSZ0IE5zbBooxiuMD72EmfXoY_3pLy89XMf9Wn-sxohva6A15UfPsfAydL7n3Qq628J4kam9LoBpinpVberru5ojcPui6p7VC9VXaE2HcqGTiCjn_GpPNineaXh8EgaMxWASEYpj2cGRfnmPV02nSK'

```

```python
decrypt(answer,)
```

### Task 4
  - Search stackoverflow.com for different ways of saving a string to file in Python
  - Use one of those methods to write a file named dirtree.txt containing the bash script to create the directory tree of the previous task
  - Read the new file using `%cat`
  - Use the `%%writefile` Magic command to save the same string to file

```python
answer = 'gAAAAABcATGAqC3y72nhYgn_E9BXBLx4ASSuSPcL4wLsn7BbprEwqVpW0GdDJfsDZYNMBbCvNjBOUrE1-AtJ4uTehitEyiU22VBerBYe5HGJoT58bBJhJOduZn5pMTQu4_UDf3Tp7TQSbceTB7d3IsGCFg92F1tiuNZkJsbELRJPcHU4NjrjcToYXAHkLRF-bC6jl312p91HpxbWnIflpUXesJqRdUmlzLwxkSYJ4DmRUiRru-BR1dEEio38ciQbs3coLJQY8edUiEyQoyRPEUzJIcxROM0PGrB9iYrsaD5eUs_NQOOaALpQDdiT_pMVmeUjSVlJpiI298l84ahqa5Io6mitG6YnZ0qj2C-BJlQUc55vK1SJvCIIGC4EoPQ9S83C-Q1VekR5ilUM5T0N1FPD4XiSurarcZRJGdMdsGPrK-24vX2Ok9l7QLCOvR03-gLMFnoKRXmBF0i8cQ-8Ms5UAGUHAYLv3AaiOmcLwbAzwwotHUmmTZw='
```

```python
decrypt(answer,)
```

## Cross-language interaction

It is possible to integrate [multiple languages](https://blog.jupyter.org/i-python-you-r-we-julia-baf064ca1fb6) in the same Notebook. For example we can pass variables from Bash to Python and vice versa. We can also define and compile [Cython](https://cython.org/) or Fortran functions in the Notebook and run them in a Python cell (vide infra).

### Task 5
  - Create a Python variable storing the path of the current directory
  - Create a Python variable storing the list of files and folders in the current directory (using `!ls` on Unix and `!dir` on Windows)

```python
answer = 'gAAAAABcAGuDmNC7FPu2tRLRlcnuPGB0ZNGjMJW7dvPic723eZeqR2fueK25CFKrfgPFQ3HzAoludqrlQLAr8d1cWRW7JW-ZGS6DTBZNaRo1ejwWTnRXaexSypoZjH4YFVzwZ3t_CRRg'

```

```python
decrypt(answer,)
```

# Python built-in functions

```python
YouTubeVideo('YpBUiEsTiEA')
```

### Task 6
Find the type of the items of the arrays `np.arange(0,9,1)` and `np.arange(0.,9,1)`.

```python
answer = 'gAAAAABcAXC6ubPFyqGJPj-A6Mf7CUH0yX6Q55wFMDx-WUSVnAd38Ysi4wrkkBGJJAotGDGZ452zkXKoVX1J8G-fFWnvNtPyovGhVxC6sK7yDRbTFo9LolHQ5b2w3cTfZ0m7kAu063tYE8-VmCIQBh6m6zEd5l9Evw=='
```

```python
decrypt(answer,)
```

### Task 7
Use a list comprehension to generate all possible 4-digit codes consisting of 2 alphabetical letters and 2 numbers (from 0 to 9). How many items does the list of contain? Turn the list into a NumPy array and count the number of unique items.

```python
answer = 'gAAAAABcAXUFYR3d2T0gj4i2zvger7rLhjcdCpmHtMJ25cg0I-Cng6cC2w5ZTCvDHRpt1XOKds6fWztIMkMPoihsu-XDusbRCL7S4-BiWICQHyUqyKuHtrNen4TrJXv2UHP_pzPsCv2BM6xUXKocTsgtBuAuYCLSxX-4bnyXyLNVEsOmTt7jw-QeVmBqiGvqXqP-vv4G7ueg1f6vpRWBNaqayso5ZhVlRzUNc6fNcgWX7q3EvOs_RqY1avTku9V46ldfWSbwFxcCyX-N1aEaYGHuVCgpyZy2w6HDSbWzGfx_quF293TLAX94nJOAh2JYS6NGk9IlvQYWa4LUyGW_Xj1V01I_AlSXiA=='

```

```python
decrypt(answer,)
```

### Task 8
Generate the array [9 7 5 3] with `np.linspace(start=0,stop=10,num=11)` and indexing. Convert its elements to strings with 2 trailing zeros using [`format`](https://pyformat.info/).

```python
answer = 'gAAAAABcAXWqJ3EkPOBOFbWCE8-SH72Mxtjk9Vupi0T6fBICvOOaJrbNMdr2prHQGeOfWflKEbtWxCODpVK5HY7Q1PEeg1r7-SVmSIWO9HSk_rdBitN-DnIL2XbfC9AaM2SSurG4O9PYa-7Mq1lVhm1oyV9vdzVbK0W6M5Wup08NvRZliVlkve1Y4OvcsqxoQdrM1VfuM-fDU3yd7Ytk0zNIAaIueLFCOOkOoEgLipGSDRWdCSqbXquMtsd-xQ9sH2emp0k-k5yE'

```

```python
decrypt(answer,)
```

### Task 9
- create a linear sequence of integers from 0 to 7 stepping by 1 with `arange` and `linspace`
- create a linear sequence of floating-point numbers from 0 to 7 stepping by 0.25 with `arange` and `linspace`

```python
answer = 'gAAAAABcAXacH2s6wH7Q02OEFFeRxe9NXtcuBKGUB4UffBOYJnUZVnv8XeoToWcoQ7FGYa3_elbyhsuFj1n7t6ywpNMqfGIHyuSZA80EnCUrhBv-4hRGUEeeH-FFo_Ca2hck89vkCb-rCTXdVB3oKY_Sj5Cl1BbHY3p3lCtvRTrVY47y_GaUaIlnL1ZB1liPGl6t1m0-ejLJQTu9Jir0_-6HSaoQikAmhzZP1qhKnTbFp4-jK-ddpgxpVLjFJs316OcrGMkkk5YCosZRzzRW9QZSzbufN3nuJj13G7qbl9skcdgM2uvGWcQY3UzEmJy-tbqtnD809YrqtO9I7tpkSwBs82oxJ32hJ9FsSwGhy05GaDRhcUve7CI='

```

```python
decrypt(answer,)
```

### Task 10
- Create an uninitialized array of size 0 and populate it, in a for loop, with the 4-digit codes containing the letter "a" and selected from those generated in Task 7.

Hint: use `empty` and `append`.
- Create the same array in a single line using list comprehension.

```python
answer = 'gAAAAABcAX7FytesghVv_mvr9wtxzVRr8OP5di6oAxZuVVELnr2VIbXR8xTdwX7kyt32y2JRd3UiOc1FKIc1IyLOlmFJma2XXQ72wPGOnqlFaPTceiASAQ8dv50fvtwCsd3CkKDPFsL6Qs2Bk7gnCR602ZmQJJJgLuuaIip0N3d_H88olMevcDyBnMUU9hUqruGTaSf3WR3cRtCInw_5ACJgYgZ9FP4FDU20Ba6bN9guR45P1ShCZOwbLf0NKeLv03sl1LWw2nQSAHEmkMvJgdNZ5_Qwupv3_JxscIBFpN8ho7gKCXbbzCF2OB5-RivPv2DulrOe8WfUl_nm-r-sHhuC0doAs2m6-g=='

```

```python
decrypt(answer,)
```

# Storage and manipulation of numerical arrays

```python
YouTubeVideo('2xJsNi3wk-s')
```

### Task 11
Generate a 3x3 zero matrix and turn it into a 3x3 identity matrix by modifying values one by one or by fancy indexing.

```python
answer = 'gAAAAABcAYDE5-H_i0u-50j3_pcGQwGmrLyH-98v5F-kISABJWSIDDiQues0yc1-M6rIQ57o_neV8kpksWCgjJUR-k0N7u2SrqBgz1oxnwSzryRYsfJLWKSxzNhJM0588wVeXPowZ0wjEKTeURn0f9aDhS3rghxDFaYD30qyubR1qXOqY3644FKa1x4YWgaLpN8x9s_Hs7_6MuPgnx0eoP5oDx1IfL4Dmqb51rIsgiGbQbvWT7tnAjI8JL7LCxP6PIG7FITginHriuM1edJ1h__JbxCQq78mdSFZYgsqy2TGoupVvOqNfN23ox91vXHotjp2UE6y_b0rY6d7mydOt4GgvMgKnDl6QCybpV_Td-ySVCvNuqWTADKwsfntWb-wrJwhh8SsFBrH-35h70ruU1U-307PtfjWZUCirkhANhWh4c5tJpzBJVjsTYyQDwoRNYzVgeAcHkmYocODTwhswnirZOZDwCuAgQY4F6Ba_zB47n6gltOsPYy_DUNAQClAIOABK4Zt79_1bMDDLrnVaHT1TqF4CR42PUJ143SF86zuqDoz0H_E1szwUsz_95qyBvcf1ZzO99tDdAFBt-5P4r5EVoy-iQ35kA=='

```

```python
decrypt(answer,)
```

### Task 12
Complete the following lines

```.py
x =
y =
np.savetxt('',np.c_[],fmt='%',header='\t',delimiter='',comments='')
%cat ```

The cell should
- write to file the following table as a tab-separated value file, specifying a header and the format of the numbers

x        | y        |
-------- | -------- |
0        | 0        |
1        | 1        |
2        | 4        |
3        | 9        |
4        | 16       |
5        | 25       |
6        | 36       |
7        | 49       |
8        | 64       |
9        | 81       |

- read the file in the notebook to check that it look as it should.

```python
answer = 'gAAAAABcAoobPB8I2ABv5t6VCQQteRUOEPicO0MQ2Auh8Jw_UjJ3I7zAFTfSmNIdWktMQP1_nGsVTe-aQRcqJXoFtyruJp4Lm23MKpKie_dS_AQEBHfWD0xjqJiQQSmsPNSgNfI2qfO-umzSR0QbkFP9a9SafpfluAwlHliBG3rJfQ_foe5O9JccdsbqzG903DsDyZASaEhQmu0bWiq_0xTI3QR2ORwc8DKrrNNYJqm6IV15G9u66yM9zapPx8dNlrpnNCf5HE6t'

```

```python
decrypt(answer,)
```

### Task 13

Complete the following lines

```.py
x,y = np.loadtxt(,dtype=str,delimiter=,skiprows=,unpack=)
plt.plot(x,y)
plt.show()
x,y = np.loadtxt(,dtype=int,delimiter=,skiprows=,unpack=)
plt.plot(x,y)
plt.show()```

The cell should
- load the text file created in the previous task so that the values are interpreted as strings (each column should be loaded into a separate array)
- plot $y$ vs $x$
- load the text file created in the previous task so that the values are interpreted as integers (each column should be loaded into a separate array)
- plot $y$ vs $x$ and compare with the previous plot.

```python
answer = 'gAAAAABcAos1k2OGaYibgW_3ODaNjTrbU92NNsxSDFCTirW3uEf7DLxBrxNwMln4ZDiMRff3N6ctjB1KZGIE4FsOpG3x2MbteJgrycQJLoiW2atBA_3oXeaE83LPOK7Qcca0cuJPrxxJXY1lbBQPw0tZXe3-0zcytax9eI37TovKhPpNGWq2vxr-f3j22_0QREjMiZGhU2T5g2dXNFO9R5OKHk6gEtDldPf196SkJT9lO_WVxe21bkMXY7ogm6a-Jaxz71eovm_iaGqDg904nCd1sccqvS-oZFxPKZxNA-xzAKNvRfFzCPVnEMfm3YnUoFS7B5gPMnb3BVGkxD5fAYVpIXeI-ByaLGvutV7HvC8-PtJKOtJg-eM='

```

```python
decrypt(answer,)
```

# Repeated operations and universal functions

```python
YouTubeVideo('469ukhzwEPg')
```

### Task 14
Compute and plot the function $z=xy\exp[-(x^2+y^2)]$ on a square grid 100x100 with side lengths ranging from -2 to 2. Complete the following lines:

```.py
y = x[:,np.]
z = * * np.exp( -  - )
plt.imshow(z, extent=, origin=)
plt.colorbar(label=)
plt.xlabel()
plt.ylabel();```

```python
answer = 'gAAAAABcAoMby1Rf-3JRj1ehvYtOVLeVNwYOuGoUFrmbarZifjvZwDnLzdox_J9dSAkRSacDW9DcP5WbF3nCbXp0ByN7u4LiRhIVCCAJAHvQCjgKLJuimG3X-PHcCuvlofloVxMpuaYGY5QtpoFSH3FJRb40kHwFxrlKIgBqFK_yFMCOwOSc5srYCeJVgRydPqalgSqIHK5DTtIvR_DfRRcrA-MDPMM_hPyuPNYC-QYoeXH-scxbW-22kSNG8p-pcVNoySgIPn4C1YFq_T6m-oB8AOKy6pwtFog84--3yS1g63eYy6diu34nMMUOEnZEk9VmdqyhEPym'

```

```python
decrypt(answer,)
```

### Task 15
Use boolean masking to set to 0.18 the $z$ values that are lower than 0.04 in the previous plot.

```python
answer = 'gAAAAABcApILR-KMnBa3VT2u-pmDiqF_LKSym5bvRjZmMm6ndi03WhBvgQEr3oKlJo5rOgM2MbBwwyHoLPnb81YakQFtnsG6PNdX-SR1K9gMPH9L4st8ihBFolIzrRjiuJldtCbLUmrAEx_Dpn1cjRtTlHND2OizxVrzneguu8PuVk1e-GHSUjXROBlACkkIQ--fJA4ypHYADl-rZpJh5aSgLaTF3PzziT2vvXlQBAQIjU4aAMCLFDEfH-iGI_mbxTNd6BEqY-AUfUDRd29YUobAM-MjmN-W1T79sVAY4w16ZRGptj1waz9vhYjB2avawWvW8COMFXATK-LQUH6TwFi_a_8yreMmZg=='

```

```python
decrypt(answer,'Ystad')
```

### Task 16

Define 3 functions that estimate the limiting value of $\sum_1^\infty \frac{\sqrt{n}}{n^3}$:
1. a Python funtion involving a for loop
2. a Python function exploiting universal functions for repeated operations and aggregation functions
3. a Cython function defined with `cpdef` involving a for loop
Cython is a mix of C and Python. With `cpdef` we can define a function as we would in Python (_i.e._ without declarying any types) but we obtain a function that is almost as fast as C generated code.

Here are snippets of code to complete for each of the three subtasks:
1. ```.py
def func1(n):
    result = 0
    for k in range():
        result +=
    return result```
2. ```.py
def func2(n):
    return ( ).sum()```
3. ```.py
%load_ext Cython
%%cython
cdef extern from "math.h":
    double sqrt(int)
cpdef func3(n): # note the 'p' in 'cpdef'
    result = 0
    for k in range():
        result +=
    return result```

Use `%timeit` to compare the speed of `func1`, `func2`, and `func3`.

```python
answer = 'gAAAAABcAqbaIiWIulQgcO267q_p8PFsH41h2jQuTOZt3vnqlEBt29xULPJTQYQTRjYyVqiEIRJXYfQe-4xJ5bUnd2PVD1YClavYu5Dbj8JjpG_Y_D6DZED4DJV6qfTotHSUX8lNn-8m51YRheaWqMrPxcMyRfAw9I8DGMLlr9064KXVpLlIPIO5q95WWnl5E127o_NhRisZp5GsolVTJw7kxoipgZyGMg=='

```

```python
decrypt(answer,)
```

```python
answer = 'gAAAAABcAqcJPTwdzkomK_6f-zDZ7wbvZnch14UFrHEHQTmKcHmobziYV7dkfnBMmjyddE10f9pR9N9ymzPL0xh1X6tYmVoI9EBj2v5ty0soSsMzttDw0f1-UCioiIFTkrKmEyVBjJlUdZWxY1ybiRDeElJuvLpr6VygSgfJYDMIuv1Ho3YQbQznXQrbAQ5EhP4o-fh2XnFI'

```

```python
decrypt(answer,)
```

```python
answer = 'gAAAAABcAqcun5hh9C7geQYhS-uzCeB2-uRhI_9yc6HtVO-di2GNbcmnLVFWRP-vghmxLPT7vNDrI4BepkH1kxrneRCTaP45Js2od2NYvOLME7xc1cIy4xTNsbYl2hwtK0JLHUK2NyDI6X4-cE9vtc7lHXwZt8gX6h1GA81LWjUwmYlEU-bwv1s9iJytNRF4Cs0s4pl6RfyN2wzCovjeCqt4oXHccoenWnlvW2hjhpI6Zpb6MdcsAfhsaoo39oWaL1XYn-lnQLj71gfc48qP9x5paPSX-xXXATSPJoY8bcGaTyK0dbcyuN6Bg0Iipg3MYGmIcozPEeW_FY1YQhrfXm4Fx09YdkvqbA=='

```

```python
decrypt(answer,)
```

```python
answer = 'gAAAAABcAqdTNpsPmdHE8Jrn6mxQGyRjquTtBOOwub9M47tFjCRCWu2xFuj9jH2-86BPouk-L3tZ7z97FaD_7cxi81KtQjHRutnrf8gwusJY9dCwgypzqtMsitla1XoBqeGX7fMXLT_Pz6B8yj8RP2SJLwuCOlXjKQ=='

```

```python
decrypt(answer,)
```