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

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 project's [homepage](https://camdavidsonpilon.github.io/Probabilistic-Programming-and-Bayesian-Methods-for-Hackers/). We hope you enjoy the book, and we encourage any contributions!

#### Looking for a printed version of Bayesian Methods for Hackers?

_Bayesian Methods for Hackers_ is now a published book by Addison-Wesley, available on [Amazon](http://www.amazon.com/Bayesian-Methods-Hackers-Probabilistic-Addison-Wesley/dp/0133902838)!

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, assumes 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 computationally-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).

```python
"""
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, matplotlib
        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!
%matplotlib inline
from IPython.core.pylabtools import figsize
import numpy as np
from matplotlib import pyplot as plt
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 = plt.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$ pass. 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 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]$?

```python
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("Is my code bug-free?")
```

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.

```python
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.ylim(0,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.

#### Expected Value
Expected value (EV) is one of the most important concepts in probability. The EV for a given probability distribution can be described as "the mean value in the long run for many repeated samples from that distribution." To borrow a metaphor from physics, a distribution's EV acts like its "center of mass." Imagine repeating the same experiment many times over, and taking the average over each outcome. The more you repeat the experiment, the closer this average will become to the distributions EV. (side note: as the number of repeated experiments goes to infinity, the difference between the average outcome and the EV becomes arbitrarily small.)

### 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 \in \mathbb{R}_{>0} $$

$\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.

```python
figsize(12.5, 4)

import scipy.stats as stats
a = np.arange(16)
poi = stats.poisson
lambda_ = [1.5, 4.25]
colours = ["#348ABD", "#A60628"]

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}$$

```python
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.ylim(0, 1.2)
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.)

```python
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:

```python
import pymc as pm

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

tau = pm.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.

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

    Random output: 64 5 12

```python
@pm.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.

`@pm.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. Deterministic functions will be covered in Chapter 2.

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

model = pm.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* (MCMC), 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.

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

     [-----------------100%-----------------] 40000 of 40000 complete in 6.5 sec

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

```python
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}$.

```python
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 received")
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$?

```python
# 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()`.

```python
# 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`.)

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

### References

-  [1] Gelman, Andrew. N.p.. Web. 22 Jan 2013. [N is never large enough](http://andrewgelman.com/2005/07/31/n_is_never_larg/).
-  [2] Norvig, Peter. 2009. [The Unreasonable Effectiveness of Data](http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/35179.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>.

```python
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://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');
    }
    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

```


# Xarray in 45 minutes

In this lesson, we discuss cover the basics of Xarray data structures. By the
end of the lesson, we will be able to:

- Understand the basic data structures in Xarray
- Inspect `DataArray` and `Dataset` objects.
- Read and write netCDF files using Xarray.
- Understand that there are many packages that build on top of xarray

## A practical example

```python
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr

%matplotlib inline
```

```python
# load tutorial dataset
ds = xr.tutorial.load_dataset("air_temperature")
```

## What's in a dataset? many DataArrays

```python
# dataset repr
ds
```

Datasets are dict-like containers of DataArrays i.e. they are a mapping of
variable name to DataArray.

```python
# pull out "air" dataarray with dictionary syntax
ds["air"]
```

You can save some typing by using the "attribute" or "dot" notation. This won't
work for variable names that clash with a built-in method name (like `mean` for
example).

```python
# pull out dataarray using dot notation
ds.air  ## same as ds["air"]
```

## What's in a DataArray? data + (a lot of) metadata

### Named dimensions `.dims`

```python
ds.air.dims
```

### Coordinate variables or "tick labels" (`.coords`)

`.coords` is a simple
[data container](https://xarray.pydata.org/en/stable/data-structures.html#coordinates)
for coordinate variables.

```python
ds.air.coords
```

Coordinates objects support similar indexing notation

```python
# extracting coordinate variables
ds.air.lon
```

```python
# extracting coorindate variables from .coords
ds.coords["lon"]
```

It is useful to think of the values in these coordinate variables as axis
"labels" such as "tick labels" in a figure. These are coordinate locations on a
grid at which you have data.

### Arbitrary attributes (`.attrs`)

`.attrs` is a dictionary that can contain arbitrary python objects. Your only
limitation is that some attributes may not be writeable to a netCDF file

```python
ds.air.attrs
```

```python
# assign your own attribute
ds.air.attrs["who_is_awesome"] = "xarray"
ds.air.attrs
```

### Underlying data (`.data`)

Xarray structures wrap underlying simpler data structures. In this case, the
underlying data is a numpy array which you may be familiar with.

This part of xarray is quite extensible allowing for GPU arrays, sparse arrays,
arrays with units etc. See the demo at the end.

```python
ds.air.data
```

```python
# what is the type of the underlying data
type(ds.air.data)
```

A numpy array!

### Review

Xarray provides two main data structures

- DataArrays that wrap underlying data containers (e.g. numpy arrays) and
  contain associated metadata
- Datasets that are dict-like containers of DataArrays

For more see

- https://xarray.pydata.org/en/stable/data-structures.html#dataset
- https://xarray.pydata.org/en/stable/data-structures.html#dataarray

---

## Why xarray? Use metadata for fun and ~profit~ papers!

### Analysis without xarray: `X(`

```python
# plot the first timestep
lat = ds.air.lat.data  # numpy array
lon = ds.air.lon.data  # numpy array
temp = ds.air.data  # numpy array
plt.figure()
plt.pcolormesh(lon, lat, temp[0, :, :])
```

```python
temp.mean(axis=1)  ## what did I just do? I can't tell by looking at this line.
```

### Analysis with xarray `=)`

How readable is this code?

```python
ds.air.isel(time=1).plot(x="lon")
```

Use dimension names instead of axis numbers

```python
ds.air.mean("time")
```

---

## Extracting data or "indexing" : `.sel`, `.isel`

Xarray supports

- label-based indexing using `.sel`
- position-based indexing using `.isel`

For more see https://xarray.pydata.org/en/stable/indexing.html

### Label-based indexing

Xarray inherits its label-based indexing rules from pandas; this means great
support for dates and times!

```python
# pull out data for all of 2013-May
ds.sel(time="2013-05")
```

```python
# demonstrate slicing
ds.sel(time=slice("2013-05", "2013-07"))
```

```python
# demonstrate "nearest" indexing
ds.sel(lon=240.2, method="nearest")
```

```python
# "nearest indexing at multiple points"
ds.sel(lon=[240.125, 234], lat=[40.3, 50.3], method="nearest")
```

### Position-based indexing

This is similar to your usual numpy `array[0, 2, 3]` but with the power of named
dimensions!

```python
# pull out time index 0 and lat index 0
ds.air.isel(time=0, lat=0)  #  much better than ds.air[0, 0, :]
```

```python
# demonstrate slicing
ds.air.isel(lat=slice(10))
```

---

## Concepts for computation

### Broadcasting: expanding data

Let's try to calculate grid cell area associated with the air temperature data.
We may want this to make a proper area-weighted domain-average for example

A very approximate formula is

\begin{equation} Δlat \times Δlon \times \cos(\text{latitude}) \end{equation}

assuming that $Δlon$ = 111km and $Δlat$ = 111km

```python
dlon = np.cos(ds.air.lat * np.pi / 180) * 111e3
dlon
```

```python
dlat = 111e3 * xr.ones_like(ds.air.lon)
dlat
```

```python
cell_area = dlon * dlat
cell_area
```

The result has two dimensions because xarray realizes that dimensions `lon` and
`lat` are different so it automatically "broadcasts" to get a 2D result. See the
last row in this image from _Jake VanderPlas Python Data Science Handbook_

Because xarray knows about dimension names we avoid having to create unnecessary
size-1 dimensions using `np.newaxis` or `.reshape`. For more, see
https://xarray.pydata.org/en/stable/computation.html#broadcasting-by-dimension-name

---

### Alignment: putting data on the same grid

When doing arithmetic operations xarray automatically "aligns" i.e. puts the
data on the same grid. In this case `cell_area` and `ds.air` are at the same
lat, lon points so things are multiplied as you would expect

```python
(cell_area * ds.air.isel(time=1))
```

Now lets make `cell_area` unaligned i.e. change the coordinate labels

```python
# make a copy of cell_area
# then add 1e-5 to lat
cell_area_bad = cell_area.copy(deep=True)
cell_area_bad["lat"] = cell_area.lat + 1e-5
cell_area_bad
```

```python
cell_area_bad * ds.air.isel(time=1)
```

**Tip:** If you notice extra NaNs or missing points after xarray computation, it
means that your xarray coordinates were not aligned _exactly_.

For more, see
https://xarray.pydata.org/en/stable/computation.html#automatic-alignment

---

## High level computation: `groupby`, `resample`, `rolling`, `coarsen`, `weighted`

Xarray has some very useful high level objects that let you do common
computations:

1. `groupby` :
   [Bin data in to groups and reduce](https://xarray.pydata.org/en/stable/groupby.html)
1. `resample` :
   [Groupby specialized for time axes. Either downsample or upsample your data.](https://xarray.pydata.org/en/stable/time-series.html#resampling-and-grouped-operations)
1. `rolling` :
   [Operate on rolling windows of your data e.g. running mean](https://xarray.pydata.org/en/stable/computation.html#rolling-window-operations)
1. `coarsen` :
   [Downsample your data](https://xarray.pydata.org/en/stable/computation.html#coarsen-large-arrays)
1. `weighted` :
   [Weight your data before reducing](https://xarray.pydata.org/en/stable/computation.html#weighted-array-reductions)

### groupby

```python
# seasonal groups
ds.groupby("time.season")
```

```python
# make a seasonal mean
seasonal_mean = ds.groupby("time.season").mean()
seasonal_mean
```

The seasons are out of order (they are alphabetically sorted). This is a common
annoyance. The solution is to use `.reindex`

```python
seasonal_mean = seasonal_mean.reindex(season=["DJF", "MAM", "JJA", "SON"])
seasonal_mean
```

### resample

```python
# resample to monthly frequency
ds.resample(time="M").mean()
```

### weighted

```python
# weight by cell_area and take mean over (time, lon)
ds.weighted(cell_area).mean(["lon", "time"]).air.plot()
```

---

## Visualization: `.plot`

For more see https://xarray.pydata.org/en/stable/plotting.html and
https://xarray.pydata.org/en/stable/examples/visualization_gallery.html

We have seen very simple plots earlier. Xarray has some support for visualizing
3D and 4D datasets by presenting multiple facets (or panels or subplots) showing
variations across rows and/or columns.

```python
# facet the seasonal_mean
seasonal_mean.air.plot(col="season")
```

```python
# contours
seasonal_mean.air.plot.contour(col="season", levels=20, add_colorbar=True)
```

```python
# line plots too? wut
seasonal_mean.air.mean("lon").plot.line(hue="season", y="lat")
```

---

## Reading and writing to disk

Xarray supports many disk formats. Below is a small example using netCDF. For
more see https://xarray.pydata.org/en/stable/io.html

```python
# write ds to netCDF
ds.to_netcdf("my-example-dataset.nc")
```

```python
# read from disk
fromdisk = xr.open_dataset("my-example-dataset.nc")
fromdisk
```

```python
# check that the two are identical
ds.identical(fromdisk)
```

**Tip:** A common use case to read datasets that are a collection of many netCDF
files. See
https://xarray.pydata.org/en/stable/io.html#reading-multi-file-datasets for how
to handle that

---

## More information

1. A description of common terms used in the xarray documentation:
   https://xarray.pydata.org/en/stable/terminology.html
1. For information on how to create a DataArray from an existing numpy array:
   https://xarray.pydata.org/en/stable/data-structures.html#creating-a-dataarray
1. Answers to common questions on "how to do X" are here:
   https://xarray.pydata.org/en/stable/howdoi.html
1. Our more extensive Scipy 2020 tutorial material:
   https://xarray-contrib.github.io/xarray-tutorial/
1. Ryan Abernathey has a book on data analysis with a chapter on Xarray:
   https://earth-env-data-science.github.io/lectures/xarray/xarray_intro.html

---

## The scientific python / pangeo ecosystem: demo

Xarray ties in to the larger scientific python ecosystem and in turn many
packages build on top of xarray. A long list of such packages is here:
https://xarray.pydata.org/en/stable/related-projects.html.

Now we will demonstrate some cool features.

### Pandas: tabular data structures

You can easily convert between xarray and pandas structures:
https://pandas.pydata.org/

This allows you to conveniently use the extensive pandas ecosystem of packages
(like seaborn) for your work.

See https://xarray.pydata.org/en/stable/pandas.html

```python
# convert to pandas dataframe
df = ds.isel(time=slice(10)).to_dataframe()
df
```

```python
# convert dataframe to xarray
df.to_xarray()
```

### xarray can wrap other array types, not just numpy

**dask** : parallel arrays https://xarray.pydata.org/en/stable/dask.html &
https://docs.dask.org/en/latest/array.html

**pydata/sparse** : sparse arrays http://sparse.pydata.org

**cupy** : GPU arrays http://cupy.chainer.org

**pint** : unit-aware computations https://pint.readthedocs.org &
https://github.com/xarray-contrib/pint-xarray

### Xarray + dask

Dask cuts up NumPy arrays into blocks and parallelizes your analysis code across
these blocks

```python
# make dask cluster; this is for demo purposes
import dask
import distributed

cluster = distributed.LocalCluster()
```

```python
client = distributed.Client(cluster)
client
```

```python
# demonstrate dask dataset
dasky = xr.tutorial.open_dataset(
    "air_temperature",
    chunks={"time": 10},  # 10 time steps in each block
)

dasky.air
```

All computations with dask-backed xarray objects are lazy, allowing you to build
up a complicated chain of analysis steps quickly

```python
# demonstrate lazy mean
dasky.air.mean("lat")
```

To get concrete values, call `.compute` or `.load`

```python
# "compute" the mean
dasky.air.mean("lat").compute()
```

### holoviews: javascript interactive plots

the `hvplot` package is a nice easy way to access
[holoviews](http://holoviews.org/) functionality. It attaches itself to all
xarray objects under the `.hvplot` namespace. So instead of using `.plot` use
`.hvplot`

```python
import hvplot.xarray

ds.air.hvplot(groupby="time", clim=(270, 300))
```

Try the slider!

### cf_xarray : use even more metadata for even more fun and ~profit~ papers

[cf_xarray](https://cf-xarray.readthedocs.io/) is a new project that tries to
let you make use of other CF attributes that xarray ignores. It attaches itself
to all xarray objects under the `.cf` namespace.

Where xarray allows you to specify dimension names for analysis, `cf_xarray`
lets you specify logical names like `"latitude"` or `"longitude"` instead as
long as the appropriate CF attributes are set.

```python
import cf_xarray
```

```python
# describe cf attributes in dataset
ds.air.cf.describe()
```

The following `mean` operation will work with any dataset that has appropriate
attributes set that allow detection of the "latitude" variable (e.g.
`units: "degress_north"` or `standard_name: "latitude"`)

```python
# demonstrate equivalent of .mean("lat")
ds.air.cf.mean("latitude")
```

```python
# demonstrate indexing
ds.air.cf.sel(longitude=242.5, method="nearest")
```

### Other cool packages

- [xgcm](https://xgcm.readthedocs.io/) : grid-aware operations with xarray
  objects
- [xrft](https://xrft.readthedocs.io/) : fourier transforms with xarray
- [xclim](https://xclim.readthedocs.io/) : calculating climate indices with
  xarray objects
- [intake-xarray](https://intake-xarray.readthedocs.io/) : forget about file
  paths
- [rioxarray](https://corteva.github.io/rioxarray/stable/index.html) : raster
  files and xarray
- [xesmf](https://xesmf.readthedocs.io/) : regrid using ESMF
- [MetPy](https://unidata.github.io/MetPy/latest/index.html) : tools for working
  with weather data

More here: https://xarray.pydata.org/en/stable/related-projects.html


```python
import sys
from __future__ import division
```

```python
import numpy as np
from phasor.utilities.ipynb.displays import *
#from YALL.utilities.tabulate import tabulate

import declarative

from declarative.bunch import (
    DeepBunch
)

import phasor.math.dispatched as dmath
#import phasor.math.dispatch_sympy
```

    Populating the interactive namespace from numpy and matplotlib

```python
import phasor.utilities.version as version
print(version.foundations_version())

from phasor.utilities.np import logspaced
from phasor.utilities.ipynb.sympy import *

from phasor import optics
from phasor import base
from phasor import signals
from phasor import system
from phasor import readouts
from phasor import mechanical
```

    b'2017-09-22 09:45:51 -0400 (a76310c5d4476904171a3f1b18117db454719432)'
    Sympy version:  1.0

```python
d = sympy.var('d')
N = sympy.var('N')
l = sympy.var('l')
A = sympy.var('A')
s = sympy.var('s')
k = sympy.var('k')
epsilon = sympy.var('epsilon')
epsilon_0 = sympy.var('epsilon_0')

d_l1 = sympy.var('l_delta_1')
F1 = sympy.var('F_1')
d_l2 = sympy.var('l_delta_2')
F2 = sympy.var('F_2')

C = sympy.var('C')
V1 = sympy.var('V_1')
I1 = sympy.var('I_1')
V2 = sympy.var('V_2')
I2 = sympy.var('I_2')

Z_e = sympy.var('Z_e', real = True)
Z_m = sympy.var('Z_m', real = True)
k_e = sympy.sqrt(1/sympy.re(Z_e))
k_m = sympy.sqrt(1/sympy.im(Z_m))
k_e = sympy.var('k_e', real = True)
k_m = sympy.var('k_m', real = True)
k_e = sympy.sympify(1)
k_m = sympy.sympify(1)

expr1 = d * F1  - I1/s + C * V1
display(expr1)
expr2 = -d_l1 * k + F1 + k * d * V1
display(expr2)

rel = sympy.Matrix([
    [C, -1/s, -C, +1/s, d, 0, -d, 0],
    [d*k, 0, -d*k, 0, 1, -k, -1, +k],
    [0,1,0,1,0,0,0,0],
    [0,0,0,0,0,1,0,1],
])
var = sympy.Matrix([V1, I1, V2, I2, F1, d_l1, F2, d_l2])
rel * var
```

```python
trans = sympy.Matrix([
    [k_e/2, k_e/2 * Z_e            ,  0,     0,                        0,     0,                        0,     0],
    [k_e/2, -k_e/2 * Z_e.conjugate(), 0,     0,                        0,     0,                        0,     0],
    [0,     0,                        k_e/2, k_e/2 * Z_e            ,  0,     0,                        0,     0],
    [0,     0,                        k_e/2, -k_e/2 * Z_e.conjugate(), 0,     0,                        0,     0],
    [0,     0,                        0,     0,                        k_m/2, k_m/2 * Z_m            ,  0,     0],
    [0,     0,                        0,     0,                        k_m/2, -k_m/2 * Z_m.conjugate(), 0,     0],
    [0,     0,                        0,     0,                        0,     0,                        k_m/2, k_m/2 * Z_m             ],
    [0,     0,                        0,     0,                        0,     0,                        k_m/2, -k_m/2 * Z_m.conjugate()],
])
trans * var
```

```python
rel_ab = rel * trans**-1
rel_a = rel_ab[:,::2]
rel_b = rel_ab[:,1::2]

```

```python
rel_b
```

```python
rel_atob = -rel_b**-1 * rel_a
rel_atob.simplify()
rel_atob
```

```python
from sympy.utilities.lambdify import lambdastr
```

```python
e = rel_atob[1,1]
def pyval(expr):
    sym = list(expr.free_symbols)
    return lambdastr(sym, expr).split(':')[1].strip()
```

```python
pyval(rel_atob[0,0])
```

    '((Z_m + k)/(C*Z_e*Z_m*s + C*Z_e*k*s - Z_e*Z_m*d**2*k*s + Z_m + k))'

```python
pyval(rel_atob[1,1])
```

    '((Z_m + k)/(C*Z_e*Z_m*s + C*Z_e*k*s - Z_e*Z_m*d**2*k*s + Z_m + k))'

```python
pyval(rel_atob[0,1])
```

    '(Z_e*s*(-C*Z_m - C*k + Z_m*d**2*k)/(-C*Z_e*Z_m*s - C*Z_e*k*s + Z_e*Z_m*d**2*k*s - Z_m - k))'

```python
pyval(rel_atob[1,0])
```

    '(Z_e*s*(-C*Z_m*k - C + d**2*k)/(-C*Z_e*Z_m*k*s - C*Z_e*s + Z_e*d**2*k*s - Z_m*k - 1))'

```python

```


```python
import sys
from importlib import reload
import sympy
from itertools import product
from collections import defaultdict
```

```python
sys.path.insert(0, '../')
```

```python
import multivector as mv
import examples as ex
import embedding as emb
```

```
t*(x0,x1,x2,y0,y1,y2) = (t^2*x0, t*x1, t*x2, t-2*y0, t^-1*y1, t^-1*y2)

invariants:
x0*y0
x1*y1
x2*y2
x1*y2
x2*y1
x0*y1^2
x0*y1*y2
x0*y2^2
y0*x1^2
y0*x1*x2
y0*x2^2
```

```python
q = sympy.symbols(tuple('q%d' %x for x in range(5)))
a = sympy.symbols(tuple('a%d' %x for x in range(3)))
b = sympy.symbols(tuple('b%d' %x for x in range(3)))
#z = sympy.symbols('z0 z1')

x = sympy.symbols('x0 x1 x2')
y = sympy.symbols('y0 y1 y2')
stdbrac = mv.Mv(x+y, {(x[0],y[0]):1, (x[1],y[1]):1, (x[2],y[2]):1}).brac
```

```python
rmap = {
    q[0]: x[0]*y[0],
    q[1]: x[1]*y[1],
    q[2]: x[2]*y[2],
    q[3]: x[1]*y[2],
    q[4]: x[2]*y[1],
    a[0]: x[0]*(y[1]**2),
    a[1]: x[0]*(y[1]*y[2]),
    a[2]: x[0]*(y[2]**2),
    b[0]: y[0]*(x[1]**2),
    b[1]: y[0]*(x[1]*x[2]),
    b[2]: y[0]*(x[2]**2)
}

embcoords, invariants = list(zip(*rmap.items()))
```

```python
gbK = sympy.polys.groebner([ai-xi for (ai,xi) in rmap.items()])
K = [g for g in gbK if not (set(g.as_poly().gens) - set(embcoords))]
```

```python
{k:(Pi1.brac(q[0], k)/k).simplify() for k in K}
```

    {-a0*b2 + q0*q4**2: 0,
     b0*b2 - b1**2: 2,
     a0*b2*q3 - a1*b1*q4: 0,
     -a2*b2 + q0*q2**2: 0,
     -b1*q4 + b2*q1: 1,
     -a1*b0 + q0*q1*q3: 0,
     -a0*b1 + q0*q1*q4: 0,
     -a1*q3 + a2*q1: -1,
     -a0*b0 + q0*q1**2: 0,
     a0*b1*q3 - a1*b0*q4: 0,
     -a1*b2 + q0*q2*q4: 0,
     b0*q2 - b1*q3: 1,
     -a1*b1 + q0*q3*q4: 0,
     -a2*b1 + q0*q2*q3: 0,
     a0*a2 - a1**2: -2,
     a1*q2 - a2*q4: -1,
     -b0*q4 + b1*q1: 1,
     -a2*b0 + q0*q3**2: 0,
     q1*q2 - q3*q4: 0,
     a1*b2*q3 - a2*b1*q4: 0,
     a0*q2 - a1*q4: -1,
     b1*q2 - b2*q3: 1,
     a1*b1*q3 - a2*b0*q4: 0,
     -a0*q3 + a1*q1: -1}

```python
{k:(Pi1.brac((q[1] - q[2])/2, k)/k).simplify() for k in K}
```

    {-a0*b2 + q0*q4**2: 2,
     b0*b2 - b1**2: 0,
     a0*b2*q3 - a1*b1*q4: 1,
     -a2*b2 + q0*q2**2: 0,
     -b1*q4 + b2*q1: 1,
     -a1*b0 + q0*q1*q3: -1,
     -a0*b1 + q0*q1*q4: 1,
     -a1*q3 + a2*q1: -1,
     -a0*b0 + q0*q1**2: 0,
     a0*b1*q3 - a1*b0*q4: 0,
     -a1*b2 + q0*q2*q4: 1,
     b0*q2 - b1*q3: -1,
     -a1*b1 + q0*q3*q4: 0,
     -a2*b1 + q0*q2*q3: -1,
     a0*a2 - a1**2: 0,
     a1*q2 - a2*q4: 0,
     -b0*q4 + b1*q1: 0,
     -a2*b0 + q0*q3**2: -2,
     q1*q2 - q3*q4: 0,
     a1*b2*q3 - a2*b1*q4: 0,
     a0*q2 - a1*q4: 1,
     b1*q2 - b2*q3: 0,
     a1*b1*q3 - a2*b0*q4: -1,
     -a0*q3 + a1*q1: 0}

```python
Km = [
    q[1]*q[2] - q[3]*q[4],
    -1*a[2]*b[0] + q[0]*q[3]**2,
    -1*a[2]*b[1] + q[0]*q[2]*q[3],
    -1*a[1]*b[0] + q[0]*q[1]*q[3],
    -1*a[2]*b[2] + q[0]*q[2]**2,
    -1*a[1]*b[1] + q[0]*q[3]*q[4],
    -1*a[0]*b[0] + q[0]*q[1]**2,
    -1*a[0]*b[1] + q[0]*q[1]*q[4],
    -1*a[1]*b[2] + q[0]*q[2]*q[4],
    -1*a[0]*b[2] + q[0]*q[4]**2,
    -1*a[1]*q[3] + a[2]*q[1],
    -1*a[0]*q[3] + a[1]*q[1],
    a[1]*q[2] - a[2]*q[4],
    a[0]*q[2] - a[1]*q[4],
    b[0]*q[2] - b[1]*q[3],
    -b[0]*q[4] + b[1]*q[1],
    b[1]*q[2] - b[2]*q[3],
    -b[1]*q[4] + b[2]*q[1],
    a[1]*b[1]*q[3] - a[2]*b[0]*q[4],
    a[0]*b[1]*q[3] - a[1]*b[0]*q[4],
    a[1]*b[2]*q[3] - a[2]*b[1]*q[4],
    a[0]*b[2]*q[3] - a[1]*b[1]*q[4],
    a[0]*a[2] - a[1]**2,
    b[0]*b[2] - b[1]**2
]
```

```python
Kcoords = sympy.symbols(
    ['C'] +
    ['MQ%d' %x for x in range(9)] +
    ['AQ%d' %x for x in range(4)] +
    ['BQ%d' %x for x in range(4)] +
    ['MM%d' %x for x in range(4)] +
    ['AA%d' %x for x in range(1)] +
    ['BB%d' %x for x in range(1)]
)
```

```python
KHom = dict(zip(Kcoords, Km))
kerCoords, kerPolys = list(zip(*KHom.items()))
```

```python

```

```python

```

```python

```

```python
P = {}
for k1, k2 in product(rmap.keys(), rmap.keys()):
    if (k2, k1) not in P.keys():
        P[(k1, k2)] = stdbrac(rmap[k1],rmap[k2])
```

```python
lift = emb.lift(rmap, embcoords, x+y)
```

```python
Pi = mv.Mv(embcoords, P).mapCoeffs(lambda x:lift(x))
```

```python
Pi.mapCoeffs(lambda x:x.simplify())
```

    -a0*dq0*da0 + 2*a0*dq1*da0 + a0*dq4*da1 - a1*dq0*da1 + a1*dq1*da1 + a1*dq2*da1 + 2*a1*dq3*da0 + 2*a1*dq4*da2 - a2*dq0*da2 + 2*a2*dq2*da2 + a2*dq3*da1 - b0*db0*dq0 - 2*b0*dq1*db0 - b0*dq3*db1 + 2*b1*db0*dq4 + b1*dq0*db1 - b1*dq1*db1 - b1*dq2*db1 - 2*b1*dq3*db2 + b2*dq0*db2 - 2*b2*dq2*db2 - b2*dq4*db1 + q1*(4*q0 - q1)*db0*da0 + q2*(-4*q0 + q2)*da2*db2 - q3**2*db0*da2 + q3*(-2*q0 + q2)*da2*db1 + q3*(2*q0 - q1)*db0*da1 - q3*dq1*dq3 + q3*dq2*dq3 - q4**2*db2*da0 + q4*(2*q0 - q1)*db1*da0 + q4*(2*q0 - q2)*db2*da1 + q4*dq1*dq4 - q4*dq2*dq4 + (-q1 + q2)*dq3*dq4 + (q0*q1 + q2*(q0 - q1))*db1*da1

```python
mv.sBr(Pi,Pi).sort().mapCoeffs(lambda x:x.simplify()/2) == 0
```

    False

```python
Jac = mv.sBr(Pi,Pi).sort().mapCoeffs(lambda x:x.simplify()/2)
```

```python

```

```python
Jac.mapCoeffs(liftK)
```

    3*AQ0*da1*da2*db1 + 4*AQ0*da2*db0*da0 + 4*AQ1*da1*db0*da0 - 4*AQ2*db2*da1*da2 - 3*AQ3*da1*db1*da0 + 4*AQ3*db2*da2*da0 - 3*BQ0*da1*db0*db1 - 4*BQ0*db2*da2*db0 + 4*BQ1*db0*db1*da0 - 4*BQ2*db2*da2*db1 + 3*BQ3*db2*da1*db1 - 4*BQ3*db2*db0*da0 - C*da1*dq4*db0 + C*da2*dq4*db1 - C*db2*da1*dq3 + C*dq3*db1*da0 + (2*AQ1 - 2*AQ2)*da2*db1*da0 + (2*BQ1 - 2*BQ2)*db2*da1*db0

```python
Pi_degs = Pi.deg()
```

```python
reload(emb)
liftK = emb.lift(KHom, kerCoords, embcoords)
```

```python
for c in sorted(embcoords, key=lambda x:str(x)):
    print(c,'\t',-1*mv.sBr(Pi, mv.Mv(embcoords, {():c})).sort().mapCoeffs(lambda x:x.simplify()))
```

    a0 	 a0*dq0 - 2*a0*dq1 - 2*a1*dq3 - q1*(4*q0 - q1)*db0 + q4**2*db2 - q4*(2*q0 - q1)*db1
    a1 	 -a0*dq4 + a1*dq0 - a1*dq1 - a1*dq2 - a2*dq3 - q3*(2*q0 - q1)*db0 - q4*(2*q0 - q2)*db2 + (-q0*q1 - q2*(q0 - q1))*db1
    a2 	 -2*a1*dq4 + a2*dq0 - 2*a2*dq2 - q2*(4*q0 - q2)*db2 + q3**2*db0 - q3*(2*q0 - q2)*db1
    b0 	 -b0*dq0 + 2*b0*dq1 + 2*b1*dq4 - q1*(-4*q0 + q1)*da0 - q3**2*da2 - q3*(-2*q0 + q1)*da1
    b1 	 b0*dq3 - b1*dq0 + b1*dq1 + b1*dq2 + b2*dq4 - q3*(-2*q0 + q2)*da2 - q4*(-2*q0 + q1)*da0 + (q0*q1 + q2*(q0 - q1))*da1
    b2 	 2*b1*dq3 - b2*dq0 + 2*b2*dq2 - q2*(-4*q0 + q2)*da2 - q4**2*da0 - q4*(-2*q0 + q2)*da1
    q0 	 -a0*da0 - a1*da1 - a2*da2 + b0*db0 + b1*db1 + b2*db2
    q1 	 2*a0*da0 + a1*da1 - 2*b0*db0 - b1*db1 - q3*dq3 + q4*dq4
    q2 	 a1*da1 + 2*a2*da2 - b1*db1 - 2*b2*db2 + q3*dq3 - q4*dq4
    q3 	 2*a1*da0 + a2*da1 - b0*db1 - 2*b1*db2 + q3*dq1 - q3*dq2 + (-q1 + q2)*dq4
    q4 	 a0*da1 + 2*a1*da2 - 2*b1*db0 - b2*db1 - q4*dq1 + q4*dq2 + (q1 - q2)*dq3

```python
for qk in K:
    print(qk,'\t',-1*mv.sBr(Pi, mv.Mv(embcoords, {():qk})).sort().mapCoeffs(liftK), end='\n\n')
```

    -a0*b0 + q0*q1**2 	 -2*MQ2*dq3 + 2*MQ6*dq4 + (-AQ0*q1 - AQ1*q3)*da2 + (2*AQ1*q0 - AQ1*q1)*da1 + (-2*BQ1*q0 + BQ1*q1)*db1 + (BQ1*q4 + BQ3*q1)*db2

    -a1*b0 + q0*q1*q3 	 AQ0*q0*da1 - AQ0*q3*da2 - MQ0*dq3 + MQ2*dq1 - MQ2*dq2 + (-2*AQ1*q0 + AQ1*q1)*da0 + (BQ0*q0 + BQ1*q3 - C*b0)*db1 + (-BQ0*q4 - 2*BQ1*q0 + BQ3*q3)*db2 + (C*q0 + 2*MQ4 - MQ5)*dq4

    -a0*b1 + q0*q1*q4 	 -BQ3*q0*db1 + BQ3*q4*db2 - MQ6*dq1 + MQ6*dq2 + MQ8*dq4 + (2*BQ1*q0 - BQ1*q1)*db0 + (-AQ0*q4 + 2*AQ1*q0 + AQ3*q3)*da2 + (-AQ1*q4 - AQ3*q0 + C*a0)*da1 + (-C*q0 - 2*MQ4 + MQ5)*dq3

    -a2*b2 + q0*q2**2 	 2*MQ1*dq3 - 2*MQ7*dq4 + (2*AQ2*q0 - AQ2*q2)*da1 + (-AQ2*q4 - AQ3*q2)*da0 + (BQ0*q2 + BQ2*q3)*db0 + (-2*BQ2*q0 + BQ2*q2)*db1

    -a2*b1 + q0*q2*q3 	 -BQ0*q0*db1 + BQ0*q3*db0 + MQ0*dq3 + MQ1*dq1 - MQ1*dq2 + (2*BQ2*q0 - BQ2*q2)*db2 + (-AQ0*q0 - AQ2*q3 + C*a2)*da1 + (AQ0*q4 + 2*AQ2*q0 - AQ3*q3)*da0 + (-C*q0 + MQ3 - 2*MQ4)*dq4

    -a1*b2 + q0*q2*q4 	 AQ3*q0*da1 - AQ3*q4*da0 - MQ7*dq1 + MQ7*dq2 - MQ8*dq4 + (-2*AQ2*q0 + AQ2*q2)*da2 + (BQ0*q4 - 2*BQ2*q0 - BQ3*q3)*db0 + (BQ2*q4 + BQ3*q0 - C*b2)*db1 + (C*q0 - MQ3 + 2*MQ4)*dq3

    -a2*b0 + q0*q3**2 	 AQ0*q3*da1 - BQ0*q3*db1 + 2*MQ0*dq1 - 2*MQ0*dq2 + (2*MQ1 - 2*MQ2)*dq4 + (-4*AQ0*q0 + AQ0*q1 + AQ1*q3)*da0 + (4*BQ0*q0 - BQ0*q2 - BQ2*q3)*db2

    -a1*b1 + q0*q3*q4 	 AQ1*q4*da0 + AQ2*q3*da2 - BQ1*q3*db0 - BQ2*q4*db2 + (-MQ1 + MQ2)*dq3 + (-MQ6 + MQ7)*dq4 + (-AQ1*q0 - AQ2*q0 + C*a1)*da1 + (BQ1*q0 + BQ2*q0 - C*b1)*db1

    -a0*b2 + q0*q4**2 	 AQ3*q4*da1 - BQ3*q4*db1 - 2*MQ8*dq1 + 2*MQ8*dq2 + (2*MQ6 - 2*MQ7)*dq3 + (AQ2*q4 - 4*AQ3*q0 + AQ3*q2)*da2 + (-BQ1*q4 + 4*BQ3*q0 - BQ3*q1)*db0

    q1*q2 - q3*q4 	 2*AQ0*da2 + 2*AQ3*da0 - 2*BQ0*db0 - 2*BQ3*db2 + (AQ1 + AQ2)*da1 + (-BQ1 - BQ2)*db1

    -a0*q3 + a1*q1 	 -AA0*da1 - AQ0*dq3 + AQ1*dq0 - AQ1*dq1 - AQ1*dq2 - AQ3*dq4 + 2*MQ2*db0 + (C*q4 - 2*MQ6)*db2 + (-C*q0 + C*q1 + MQ4 - MQ5)*db1

    -a1*q3 + a2*q1 	 2*AA0*da0 + AQ0*dq0 - 2*AQ0*dq2 + 2*MQ0*db0 + (-AQ1 - AQ2)*dq4 + (MQ1 - MQ2)*db1 + (-4*C*q0 + C*q2 - 2*MQ4)*db2

    -b0*q4 + b1*q1 	 BB0*db1 + BQ0*dq3 - BQ1*dq0 + BQ1*dq1 + BQ1*dq2 + BQ3*dq4 - 2*MQ6*da0 + (-C*q3 + 2*MQ2)*da2 + (C*q0 - C*q1 - MQ4 + MQ5)*da1

    -b1*q4 + b2*q1 	 -2*BB0*db0 - BQ3*dq0 + 2*BQ3*dq2 - 2*MQ8*da0 + (BQ1 + BQ2)*dq3 + (MQ6 - MQ7)*da1 + (4*C*q0 - C*q2 + 2*MQ4)*da2

    a0*q2 - a1*q4 	 2*AA0*da2 + AQ3*dq0 - 2*AQ3*dq1 + 2*MQ8*db2 + (-AQ1 - AQ2)*dq3 + (MQ6 - MQ7)*db1 + (-4*C*q0 + C*q1 - 2*MQ4)*db0

    a1*q2 - a2*q4 	 -AA0*da1 - AQ0*dq3 + AQ2*dq0 - AQ2*dq1 - AQ2*dq2 - AQ3*dq4 + 2*MQ7*db2 + (C*q3 - 2*MQ1)*db0 + (-C*q0 + C*q2 - MQ3 + MQ4)*db1

    b0*q2 - b1*q3 	 -2*BB0*db2 - BQ0*dq0 + 2*BQ0*dq1 - 2*MQ0*da2 + (BQ1 + BQ2)*dq4 + (MQ1 - MQ2)*da1 + (4*C*q0 - C*q1 + 2*MQ4)*da0

    b1*q2 - b2*q3 	 BB0*db1 + BQ0*dq3 - BQ2*dq0 + BQ2*dq1 + BQ2*dq2 + BQ3*dq4 - 2*MQ1*da2 + (-C*q4 + 2*MQ7)*da0 + (C*q0 - C*q2 + MQ3 - MQ4)*da1

    a0*b1*q3 - a1*b0*q4 	 (2*AA0*b0 - AQ3*q3**2 + 2*MQ0*a0)*da2 + (-AQ1*b0 + BQ0*a1 - MM0)*dq3 + (2*BB0*a0 - BQ0*q4**2 + 2*MQ8*b0)*db2 + (-BQ1*a0 + BQ2*a0 + 2*MM3)*dq4 + (AQ1*q1*q4 + 2*MQ4*a0 - 4*MQ6*a1)*da0 + (BQ1*q1*q3 - 4*MQ2*b1 + 2*MQ4*b0)*db0 + (2*AA0*b1 + AQ1*q3*q4 - C*a0*q3 + MQ1*a0 + MQ2*a0 - 2*MQ4*a1)*da1 + (BB0*a1 + BQ0*q0*q4 + BQ1*q3*q4 - C*b0*q4 - MQ4*b1 + MQ6*b0)*db1

    a0*b2*q3 - a1*b1*q4 	 -MM3*dq1 + MM3*dq2 + (AQ1*q4**2 - 2*MQ8*a1)*da0 + (AQ3*b2 - BQ3*a0)*dq4 + (-BQ2*q4**2 + 2*MQ8*b1)*db2 + (4*AA0*b1 - AQ3*q2*q3 + 4*MQ1*a0 - 2*MQ4*a1)*da2 + (-4*BB0*a1 + BQ3*q1*q3 - 4*MQ2*b2 + 2*MQ4*b1)*db0 + (-BQ1*a1 + BQ2*a1 + 2*MM1 - MM2)*dq3 + (AA0*b2 - AQ3*q3*q4 + C*a1*q4 + 2*MQ4*a0 - MQ6*a1 - MQ7*a1)*da1 + (-BB0*a0 + BQ3*q3*q4 - C*b1*q4 - 2*MQ4*b2 + MQ6*b1 + MQ7*b1)*db1

    a1*b1*q3 - a2*b0*q4 	 MM0*dq1 - MM0*dq2 + (-AQ0*b0 + BQ0*a2)*dq3 + (-AQ2*q3**2 + 2*MQ0*a1)*da2 + (BQ1*q3**2 - 2*MQ0*b1)*db0 + (4*BQ0*q0*q4 - BQ0*q2*q4 + 2*MQ4*b1)*db2 + (-4*AA0*b1 + AQ0*q1*q4 + 2*MQ4*a1 - 4*MQ6*a2)*da0 + (-BQ1*a1 + BQ2*a1 - MM1 + 2*MM2)*dq4 + (-AA0*b0 + AQ0*q3*q4 - C*a1*q3 + MQ1*a1 + MQ2*a1 - 2*MQ4*a2)*da1 + (BB0*a2 - BQ0*q3*q4 + C*b1*q3 - MQ1*b1 - MQ2*b1 + 2*MQ4*b0)*db1

    a1*b2*q3 - a2*b1*q4 	 (-2*AA0*b2 + AQ0*q4**2 - 2*MQ8*a2)*da0 + (-AQ0*b1 + BQ2*a2 + MM0)*dq3 + (AQ2*b2 - BQ3*a1 - MM3)*dq4 + (-2*BB0*a2 + BQ3*q3**2 - 2*MQ0*b2)*db0 + (-AQ2*q2*q3 + 4*MQ1*a1 - 2*MQ4*a2)*da2 + (-BQ2*q2*q4 - 2*MQ4*b2 + 4*MQ7*b1)*db2 + (-2*AA0*b1 - AQ2*q3*q4 + C*a2*q4 + 2*MQ4*a1 - MQ6*a2 - MQ7*a2)*da1 + (-2*BB0*a1 - BQ2*q3*q4 + C*b2*q3 - MQ1*b2 - MQ2*b2 + 2*MQ4*b1)*db1

    a0*a2 - a1**2 	 2*AA0*dq0 - 2*AA0*dq1 - 2*AA0*dq2 + (-4*AQ0*q0 + AQ0*q1 - AQ1*q3)*db0 + (-AQ2*q4 - 4*AQ3*q0 + AQ3*q2)*db2 + (AQ0*q4 + 2*AQ1*q0 + 2*AQ2*q0 + AQ3*q3 - 2*C*a1)*db1

    b0*b2 - b1**2 	 -2*BB0*dq0 + 2*BB0*dq1 + 2*BB0*dq2 + (4*BQ0*q0 - BQ0*q2 + BQ2*q3)*da2 + (BQ1*q4 + 4*BQ3*q0 - BQ3*q1)*da0 + (-BQ0*q4 - 2*BQ1*q0 - 2*BQ2*q0 - BQ3*q3 + 2*C*b1)*da1

```python

```

```python

```

```python

```

```python

```

```python

```

```python

```

```python

```


# Surfinpy

#### Tutorial 3 - Pressure

Chemical potential can be converted to pressure values using

\begin{align}
P & = \frac{\mu_O}{k_B T} ,
\end{align}

where P is the pressure, $\mu$ is the chemical potential of oxygen, $k_B$ is the Boltzmnann constant and T is the temperature.

```python
import matplotlib.pyplot as plt
from surfinpy import mu_vs_mu
from surfinpy import utils as ut
from surfinpy import data
```

```python
Oxygen_exp = ut.fit_nist("O2.txt")[298]
Water_exp = ut.fit_nist("H2O.txt")[298]
Oxygen_corrected = (-9.08 + -0.86 + Oxygen_exp) / 2
Water_corrected = -14.84 + 0.55 + Water_exp
```

```python
bulk = data.ReferenceDataSet(cation = 1, anion = 2, energy = -780.0, funits = 4)

pure = data.DataSet(cation = 24, x = 48, y = 0, area = 60.0, energy = -575.0, label = "0.00 $TiO_2$", nspecies = 1)
H2O = data.DataSet(cation = 24, x = 48, y = 2, area = 60.0, energy = -612.0, label = "0.16 $TiO_2$", nspecies = 1)
H2O_2 = data.DataSet(cation = 24, x = 48, y = 4, area = 60.0, energy = -640.0, label = "0.32 $TiO_2$", nspecies = 1)
H2O_3 = data.DataSet(cation = 24, x = 48, y = 8, area = 60.0, energy = -676.0, label = "0.64 $TiO_2$", nspecies = 1)
Vo = data.DataSet(cation = 24, x = 46, y = 0, area = 60.0, energy = -558.0, label = "0.00 $TiO_1.9$", nspecies = 1)
H2O_Vo_1 = data.DataSet(cation = 24, x = 46, y = 2, area = 60.0, energy = -594.0, label = "0.00 $TiO_1.9$", nspecies = 1)
H2O_Vo_2 = data.DataSet(cation = 24, x = 46, y = 4, area = 60.0, energy = -624.0, label = "0.16 $TiO_1.9$", nspecies = 1)
H2O_Vo_3 = data.DataSet(cation = 24, x = 46, y = 6, area = 60.0, energy = -640.0, label = "0.32 $TiO_1.9$", nspecies = 1)
H2O_Vo_4 = data.DataSet(cation = 24, x = 46, y = 8, area = 60.0, energy = -670.0, label = "0.64 $TiO_1.9$", nspecies = 1)

data = [pure, Vo, H2O, H2O_Vo_1, H2O_2, H2O_Vo_2, H2O_3, H2O_Vo_3,  H2O_Vo_4]

```

```python
deltaX = {'Range': [ -12, -6],  'Label': 'O'}
deltaY = {'Range': [ -19, -12], 'Label': 'H_2O'}
```

```python
system =  mu_vs_mu.calculate(data, bulk, deltaX, deltaY, x_energy=Oxygen_corrected, y_energy=Water_corrected)
```

As before we can generate a basic plot of oxygen chemical potential vs water chemical potential at 298 K

```python
ax = system.plot_phase(temperature=298, cbar_title="$H_2O$ $/$ $nm^2$", figsize=(6, 5))
plt.savefig("../../../docs/source/Figures/Surfaces_4.png", dpi=600)
plt.show()
```

We can also generate the same plot but with the $\mu$ values converted to pressure.

```python
system.plot_pressure(temperature=298, cbar_title="$H_2O$ $/$ $nm^2$", figsize=(6, 5))
plt.savefig("../../../docs/source/Figures/Surfaces_5.png", dpi=600)
plt.show()
```

Finally, we can also combine these two plots into one

```python
system.plot_mu_p(temperature=298, cbar_title="$H_2O$ $/$ $nm^2$", figsize=(6, 5))
plt.savefig("../../../docs/source/Figures/Surfaces_6.png", dpi=600)
plt.show()
```


**1. Create the below pattern using nested for loop in Python**
$$
\begin{align}
&*\\
&**\\
&***\\
&****\\
&*****\\
&****\\
&***\\
&**\\
&*
\end{align}
$$

```python
num = 5
for star in range(1,10): #we take range upto 10 because we have to print 9 lines
    if star <= 5: #Stars of less than and equal to 5 have to print in increasing order of numbers
        print('*'*star)
    if star>5: #Stars less than 5 have to print in decreasing order of numbers
        print('*'*(num-1))
        num -= 1
```

    *
    **
    ***
    ****
    *****
    ****
    ***
    **
    *

**2. Write a Python program to reverse a word after accepting the input from the user.**

    Input word: ineuron

    Output word: norueni

```python
user_input = input("Enter the Word: ")
#Let say ineuron has 7 alphabet so, the loop is starting from 6 to -1 at step of -1
#so loops runs 7 times from 6 to -1(excluded) and print in reverse order
for char in range(len(user_input)-1,-1,-1):
    print(user_input[char], end='')
```

    Enter the Word: ineuron
    norueni

Python Assignment/Python Assignment 2.ipynb


```python
import numpy as np
import math
from scipy import optimize
import numba as nb
import scipy.stats as stats

import ps3_functions as func

# For plots:
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('seaborn-whitegrid')
mpl.style.use('seaborn')
prop_cycle = plt.rcParams["axes.prop_cycle"]
colors = prop_cycle.by_key()["color"]
import ipywidgets as widgets
from ipywidgets import interact, interact_manual
```

The formulas from Q1 are still valid. Now note that:

* $c_1^*>c_1^M$ and $c_2^*<c_2^M$: The market allocation over-invests compared to optimal allocation.
* Long-run investment is not 'worth it', discount-factor $(\rho)$ more than offsets productivity $(R)$ $\Rightarrow$ push consumption towards $t=1$.

**Question: Note that $c_1^*>c_1^M$ and $c_2^*<c_2^M$ depends on $(\rho^2 R)<1$ and not $(\rho R)<1$. Why?** (Hint: recall that utility from $t=0$ is concave).

# PS3, part 1: Fire sales and multiple equilibria

The setup for part 1:

* Two period economy, $t=0,1$.
* Single consumption good, $(c)$.
* Continuum of entrepreneurs (E) and financiers (F).
* Fixed amount of capital $(\bar{k})$.
* Let $(q_t)$ denote the price of capital. Assume $q_1=\theta$ be the fixed liquidation price of capital (end of period 1).
* **Entrepreneurs:**
    * Risk-neutral, i.e. $u_E = c_0^e+c_1^e$.
    * At start-of-period $t=0$, $E$ has $b_0$ debt and $k^E_0$ capital.
    * Invests in capital for $t=1$ ($k_1^E$).
    * Due to a *temporary shock to cash flows* entrepreneurs do not receive any return on $k_0^E$.
    * In $t=1$ they apply a linear production technology i.e.
        $$\begin{align}
        f(k_1^E) = a k_1^E.
        \end{align}$$
    * At $t=0$ the entrepreneur either (1) repays his debt (if $b_0\leq q_0k_0)$) or (2) renegotiates the level of debt down to $q_0k_0$.
    * Faces a credit constraint of the *collateralized assets* type for period $t=1$: $b_1\leq \theta k_1$.
* **Financiers:**
    * Risk-neutral, i.e. $u_F = c_0^F+c_1^F$.
    * At the start of period $t=0$, F has capital $k^F_0$ (no debt).
    * Has *large* endowments of the consumption good, of size $(e_0,e_1)$ (we will come back to what *large* refers to).
    * Applies production technology using capital $(k_t^F)$ following
    $$\begin{align}
    G(k_t^F) = k_t^F-\dfrac{1}{2}\left(k_t^F\right)^2.
    \end{align}$$

Before we proceed to the questions, we note that:

* **Efficient allocation** of capital is defined as the level equalizes marginal product of capital across sectors, i.e.
    $$\begin{align}
        G'(k^F_1) = 1-k_1^F = a = f'(k_1^E)
    \end{align}$$
    In other words:
    $$\begin{align}
    k_F^* = 1-a, && k_E^* = \bar{k}+a-1
    \end{align}$$

* This might not be the equilibrium, because of the financial frictions in place (credit-constraint due to e.g. moral hazard).

## Q1: Optimization of entrepreneurs

First task is to translate the information above on E to a maximization problem. The problem includes (1) utility function, (2)-(3) budgets and (4) collateral constraint (credit-constraint). Comment on each one of them.

Next characterize E's demand for capital. Consider what happens in the scenarios:

Note that problem is linear in $k_1$. Thus we have corner solutions in general:

* If $q_0\leq \theta$: $E$ chooses $k_1=$...
* If $q_0\geq \theta+a$: $E$ chooses $k_1=$...
* If $q_0 < b_0/k_0$:
* If:
$$\begin{align}
    \max\left(\theta, \mbox{ }b_0/k_0\right)<q_0<\theta+a \tag{A1}
\end{align}$$

.

.

Assumption $(A1)$ is assumed to hold in the following questions.

## Q2: Capital demand under assumption (A1)

Under $(A1)$ the return to capital $>1$. What does this imply for optimal $c_0$? And for the credit constraint?

.

.

.

You should end up with the demand for capital:
$$\begin{align}
k_1 &= \dfrac{q_0k_0-b_0}{q_0-\theta} \\
 &= k_0+\dfrac{k_0\theta -b_0}{q_0-\theta}.
\end{align}$$

### Q3: Discuss expression for capital demand:

Note that $q_0$ is both the price for new capital $k_1$ purchased at $t=0$ and the value of existing capital $k_0$.

Comment on capital demand and how $q_0$ affects it. You may think of two channels from above as a $\color{red}{\text{price}}$ effect and a $\color{blue}{\text{wealth}}$ effect.

## Q4: The financier problem and the market clearing condition for capital.

**Financier problem:**

Write the introduction text as a mathematical problem.

Similar setup to $E$, except that

* No borrowing (endowments are large enough to finance their optimal level $k_t^F$).
* Concave production function, not linear (and both in $t=0,1$).
* This yields a finite optimal level of $k_t^F$.

Solve for the optimal $k_1^F$.

**Market clearing:**

With a fixed supply of capital the market clearing reads:

$$\begin{align}
    \bar{k} = k_1^F+k_1^E.
\end{align}$$

For convenience we will define the *residual supply curve* that entrepreneurs face, by substitution of $(k_1^F)^*$ into the market clearing condition:

$$\begin{align}
    k_1^E = \min\left(\bar{k}, \mbox{ }\bar{k}-(1+\theta-q_0)\right).
\end{align}$$

## Q5: Show and depict graphically that when $b_0<\theta k_0$ there is a unique equilibrium.

## Q6: Show that when $b_0>\theta k_0$ there can be multiple equilibria: A 'bad' and a 'good' one. Explain.

In both Q5 and Q6 it is important to keep track of different relevant ranges of the price $q_0$:

* When $b_0<\theta k_0$ is demand increasing? In which region of $q_0?$ (remember to take assumption (A1) into account).
* Is supply increasing? What is the minimum/maximum level supply attains (on the relevant range of $q_0$)?

In the figure below, you can quickly investigate how the different parameter values affect the demand and supply of capital.

```python
a, amin, amax = 1, 0.5, 1.5 # gives baseline value a, minimum and maximum in sliders below.
b_0, bmin, bmax =0.6, 0.1, 1 # gives baseline value b, minimum and maximum in sliders below.
k_0, kmin, kmax = 0.9, 0.1, 1 # gives baseline value k_0, minimum and maximum in sliders below.
theta, thetamin, thetamax = 0.5, 0, 1 # gives baseline value theta, minimum and maximum in sliders below.
kbar=0.9 # Fixed level of supply.
q_0 = np.linspace(0, 2, 1000) # range of q to consider.
kplot_max = 1 # Maximum
func.interactive_capdemand(q_0,a,a,amin,amax,b_0,b_0,bmin,bmax,k_0,k_0,kmin,kmax,theta,theta,thetamin,thetamax,kbar,kplot_max)
```

    interactive(children=(FloatSlider(value=0.5, description='$\\theta$', max=1.0, step=0.05), FloatSlider(value=1…

## Q7: How can an appropriate reduction in $b_0$ eliminate the bad equilibrium?

Verify that it is the case in the figure above.

What is the intuition behind this?

## Q8: Suppose there were multiple equilibria and the government stands ready to buy assets at the good equilibrium price. How many assets would it have to buy to implement this policy?

## Q9: Compare costs of Q7 and Q8 as policies for working in the financial crisis. Q7 interpreted as injecting capital into the banking system and Q8 as a plan to buy toxic securities with governnment money. Discuss.

# PS3, part 2: Impatient households and risky investments

The setup is a Diamond-Dybvig (1983) type of model. Specifically:

* Three periods $t=0,1,2$.
* Two storage technologies
    * One period tech. with return $1$.
    * Two period tech. with return $R>1$. Can be prematurely liquidated $L<1$.
* Continuum of agents with unit endowment.
* A fraction $\pi$ will be impatient, $1-\pi$ patient. However, there is uncertainty (at time $0$) about what type the agent'll be. The expected utility is then given by:
    $$\begin{align}
        u = \pi\sqrt{c_1}+(1-\pi)\rho \sqrt{c_2}.
    \end{align}$$
    At time $t=1$ when the type is known the utility is:
    $$\begin{align}
       \text{If impatient}: && u_1^{ip} &= \sqrt{c_1} \\
       \text{If patient}: && u_1^{p} &= \rho\sqrt{c_2}
    \end{align}$$
     where $\rho$ reflects standard discounting of the future.

If you are not familiar with the DD model, you may consult the brief recap in "DD model.pdf".

## Q1: Characterize optimal allocation and market allocation.

We define the market allocation as in Diamond-Dybvig (1983):

* At time $t=0$ households choose long run investment $I$ (and short run investment $(1-I)$).
* At time $t=1$ they recognize their type.
* A bond market is included as follows:
    * Households that turns out to be patient: Use short run investment $1-I$ to purchase bonds at $t=1$, receiving $(1-I)/p$ at $t=2$.
    * Impatient consumers receive $p$ units of income at time $t=1$, for each unit of income they repay at $t=2$.
    * Equilibrium price $p=1/R$.

Write up the $c_1$ and $c_2$ constraints. Show that the market allocation (M) is given by:

$$\begin{align}
    c_1^M = 1, && c_2^M = R.
\end{align}$$

### Social Planner solution (optimal):

A social planner allocates $I$ of the initial endowment to long run investments, and $1-I$ to short run investments. As the planner does not operate under uncertanity, $I$ is naturally chosen such that there is no premature liquidation of long run assets. This means that short run investments are allocated to impatient households (share $\pi$), and return on long run investments are allocated to patient households. Show that this setup implies the planner solution:
$$\begin{align}
    c_1^* = \dfrac{1}{\pi+(1-\pi)\rho^2R}, && c_2^* = \dfrac{(\rho R)^2}{\pi+(1-\pi)\rho^2R}.
\end{align}$$

Comment on the result. Compare to the market outcome.

## Q2, part 1: Is it possible to introduce financial intermediaries, and does this implement the optimal allocation?

(*State-contingent contract: The outcome of the contract depends on the realization of some state (e.g. which type of agent the consumer is at $t=1$)).*

Yes. If the financial intermediaries offer **state-contingent contracts** the market is said to be **complete**, in which case the uncertainty no longer entails inefficiency. Try to outline how such a contract might look like. In particular, include the fact that the contract must be **incentive compatible** and obey the **participation constraint** for the financial intermediary.

## Q2, part 2: Is it possible to have bank runs, and why are they inefficient?

* Assume that a patient household expects all other households to withdraw early. What happens to this household's incentives to withdraw early/keep patient?
* Of the patient households withdraw early, the bank has to liquidate long run investments prematurely. What is the maximum amount of income they can amass in $t=1$? Denote this $BR$.
* Show that a bank run is an equilibrium if $BR<c_1^*$. Why?

## Q3: Assume from now on that $\rho R<1$. Characterize optimal and market allocation.

## Q4: Can intermediaries implement optimal allocation? Bank runs?

Consider in particular:

* An intermediary offering $c_1$ to households if they withdraw early and $c_2$ to households that withdraw at $t=2$.
* what is the incentive compatibility constraint here? (how can we make sure that patients households do not withdraw early?)
* If the contract ensures that the IC constraint holds, then exactly which households will choose to withdraw early (if we do not plan for a bank run)

Show that in the case where $\rho R<1$, the **constrained optimal constract** that takes the IC constraint into account offers the contract:

$$\begin{align}
 c_1 = c_2 = \dfrac{R}{R\pi+(1-\pi)}\geq 1.
\end{align}$$

Discuss how the chances for bank runs have changed, compared to Q2 part 2. Explain why bank run only exists if (same as in Q2 part 2):

$$\begin{align}
    \pi c_1+ (1-\pi c_1)L<c_1.
\end{align}$$

## Q5: Why can commitment to a 'pre-announced suspension of convertibility' eliminate the bank run equilibrium?

Interpret the 'pre-announced...' saying that it will at most pay out $x$ when $t=1$.

## Q6: In absence of commitment, assume the CB can choose a threshold $\pi^B\geq \pi$ of deposits that get paid. What is the optimal ex post policy (threshold)? does it prevent bank runs?

This is a complicated one. Try to re-visit it after the exercise class, and see if you agree with the solution in "PS3.ipynb".