```python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from scipy.stats import linregress
from uncertainties import ufloat
from uncertainties.umath import *  # sin(), etc.

#Viscosidade e densidade da água Pa.s, kg/m^3
mi = 1.002e-3
rho = 1e3

#Dados diâmetros - Incerteza tipo A
D_val = np.array([31.5, 30.8, 29.5, 29.0, 31.6, 32.1, 31.0, 31.7, 31.5, 32])/1000 #m
D = ufloat(D_val.mean(), D_val.std(ddof=1)/np.sqrt(len(D_val)))

#Dados tempo e volumes - Incerteza tipo B
t_val = np.array([43.68, 12.36, 18.56, 20.29, 6.73, 3.30])    #s
V_val = np.array([0.490, 0.495, 1, 0.985, 0.990, 0.820])/1000 #m^3
t, V = [], []
for i in range(len(t_val)):
    t.append(ufloat(t_val[i], 0.01/np.sqrt(3)))
    V.append(ufloat(V_val[i], 0.01/(np.sqrt(3)*1000))) #Convertendo o erro p/ m^3
D
```

    0.031069999999999997+/-0.00033000000000000016

```python
V_bar, Re = [], []
for i in range(len(t_val)):
    NUM = ((V[i])/t[i]) #multipliquei por x1000 pra ficar em ml
    DEM = ((D/2)**2)*np.pi
    V_bar.append(NUM/DEM)
    Re.append(((NUM/DEM)*D*rho)/(mi))
```

```python
df = pd.DataFrame({'D(m)':D, 't(s)':t, 'V(m^3)':V, 'V_bar(m/s)':V_bar, 'Re':Re})
#df.to_excel('dados_1.xlsx')
df

```

      D(m)
      t(s)
      V(m^3)
      V_bar(m/s)
      Re

      0
      0.03107+/-0.00033
      43.680+/-0.006
      0.000490+/-0.000006
      0.0148+/-0.0004
      459+/-7

      1
      0.03107+/-0.00033
      12.360+/-0.006
      0.000495+/-0.000006
      0.0528+/-0.0013
      1638+/-26

      2
      0.03107+/-0.00033
      18.560+/-0.006
      0.001000+/-0.000006
      0.0711+/-0.0016
      2204+/-27

      3
      0.03107+/-0.00033
      20.290+/-0.006
      0.000985+/-0.000006
      0.0640+/-0.0014
      1985+/-24

      4
      0.03107+/-0.00033
      6.730+/-0.006
      0.000990+/-0.000006
      0.194+/-0.004
      (6.02+/-0.07)e+03

      5
      0.03107+/-0.00033
      3.300+/-0.006
      0.000820+/-0.000006
      0.328+/-0.007
      (1.016+/-0.013)e+04

```python
Re_n, v_b = [], []
for i in range(len(Re)):
    Re_n.append(Re[i].n)
    v_b.append(V_bar[i].n)
```

```python
#Figura
fig, ax = plt.subplots()
ax.set(ylabel=r'Velocidade [$m/s$]', xlabel=r'Número de Reynolds [$adm$]')

#Erros de medida e dados
#ax.scatter(x, y, color='red', label='Dados')
erx = np.full_like(np.arange(0, len(Re), dtype=int), fill_value=Re[1].s)
ery = np.full_like(np.arange(0, len(Re), dtype=int), fill_value=V_bar[1].s)

ax.errorbar(Re_n, v_b, xerr=erx, yerr=ery, fmt='o', markeredgecolor='black',
            markerfacecolor='red', label='Dados', markersize=5, capsize=5)
#Regressão linear dos dados
res = linregress(Re_n, v_b)
ax.plot(np.asarray(Re_n), res.intercept + res.slope*np.asarray(Re_n), linestyle='--', color='blue'
        #,label=r'Aproximação $r^2=$' + f'{res.rvalue:.4f}')
        , label='Aproximação')
ax.axvline(x=2400, ls=':', color='red',label=r'Limiar turbulento $R_e=2400$')
ax.axvline(x=2000, ls=':',  label=r'Limiar laminar $R_e=2000$')

ax.grid(ls='dotted')
ax.legend()

fig.savefig('velc_x_Re.pdf', bbox_inches='tight')
```

```python
from sympy import *
from sympy.abc import *
init_printing()

a = -y**3/(32*x**2) + 5*y**2/4 + 25*y*x**2/2 - x
ex = Eq(a, 0)
ex
```


# Frequentist Inference Case Study - Part A

## 1. Learning objectives

Welcome to part A of the Frequentist inference case study! The purpose of this case study is to help you apply the concepts associated with Frequentist inference in Python. Frequentist inference is the process of deriving conclusions about an underlying distribution via the observation of data. In particular, you'll practice writing Python code to apply the following statistical concepts:
* the _z_-statistic
* the _t_-statistic
* the difference and relationship between the two
* the Central Limit Theorem, including its assumptions and consequences
* how to estimate the population mean and standard deviation from a sample
* the concept of a sampling distribution of a test statistic, particularly for the mean
* how to combine these concepts to calculate a confidence interval

## Prerequisites

To be able to complete this notebook, you are expected to have a basic understanding of:
* what a random variable is (p.400 of Professor Spiegelhalter's *The Art of Statistics, hereinafter AoS*)
* what a population, and a population distribution, are (p. 397 of *AoS*)
* a high-level sense of what the normal distribution is (p. 394 of *AoS*)
* what the t-statistic is (p. 275 of *AoS*)

Happily, these should all be concepts with which you are reasonably familiar after having read ten chapters of Professor Spiegelhalter's book, *The Art of Statistics*.

We'll try to relate the concepts in this case study back to page numbers in *The Art of Statistics* so that you can focus on the Python aspects of this case study. The second part (part B) of this case study will involve another, more real-world application of these tools.

For this notebook, we will use data sampled from a known normal distribution. This allows us to compare our results with theoretical expectations.

## 2. An introduction to sampling from the normal distribution

First, let's explore the ways we can generate the normal distribution. While there's a fair amount of interest in [sklearn](https://scikit-learn.org/stable/) within the machine learning community, you're likely to have heard of [scipy](https://docs.scipy.org/doc/scipy-0.15.1/reference/index.html) if you're coming from the sciences. For this assignment, you'll use [scipy.stats](https://docs.scipy.org/doc/scipy-0.15.1/reference/tutorial/stats.html) to complete your work.

This assignment will require some digging around and getting your hands dirty (your learning is maximized that way)! You should have the research skills and the tenacity to do these tasks independently, but if you struggle, reach out to your immediate community and your mentor for help.

```python
from scipy.stats import norm
from scipy.stats import t
import numpy as np
import pandas as pd
from numpy.random import seed
import matplotlib.pyplot as plt
```

__Q1:__ Call up the documentation for the `norm` function imported above. (Hint: that documentation is [here](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html)). What is the second listed method?

```python
help(norm)
```

    Help on norm_gen in module scipy.stats._continuous_distns object:

    class norm_gen(scipy.stats._distn_infrastructure.rv_continuous)
     |  norm_gen(momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)
     |
     |  A normal continuous random variable.
     |
     |  The location (``loc``) keyword specifies the mean.
     |  The scale (``scale``) keyword specifies the standard deviation.
     |
     |  %(before_notes)s
     |
     |  Notes
     |  -----
     |  The probability density function for `norm` is:
     |
     |  .. math::
     |
     |      f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}}
     |
     |  for a real number :math:`x`.
     |
     |  %(after_notes)s
     |
     |  %(example)s
     |
     |  Method resolution order:
     |      norm_gen
     |      scipy.stats._distn_infrastructure.rv_continuous
     |      scipy.stats._distn_infrastructure.rv_generic
     |      builtins.object
     |
     |  Methods defined here:
     |
     |  fit(self, data, **kwds)
     |      Return MLEs for shape (if applicable), location, and scale
     |      parameters from data.
     |
     |      MLE stands for Maximum Likelihood Estimate.  Starting estimates for
     |      the fit are given by input arguments; for any arguments not provided
     |      with starting estimates, ``self._fitstart(data)`` is called to generate
     |      such.
     |
     |      One can hold some parameters fixed to specific values by passing in
     |      keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
     |      and ``floc`` and ``fscale`` (for location and scale parameters,
     |      respectively).
     |
     |      Parameters
     |      ----------
     |      data : array_like
     |          Data to use in calculating the MLEs.
     |      arg1, arg2, arg3,... : floats, optional
     |          Starting value(s) for any shape-characterizing arguments (those not
     |          provided will be determined by a call to ``_fitstart(data)``).
     |          No default value.
     |      kwds : floats, optional
     |          - `loc`: initial guess of the distribution's location parameter.
     |          - `scale`: initial guess of the distribution's scale parameter.
     |
     |          Special keyword arguments are recognized as holding certain
     |          parameters fixed:
     |
     |          - f0...fn : hold respective shape parameters fixed.
     |            Alternatively, shape parameters to fix can be specified by name.
     |            For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a``
     |            are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
     |            equivalent to ``f1``.
     |
     |          - floc : hold location parameter fixed to specified value.
     |
     |          - fscale : hold scale parameter fixed to specified value.
     |
     |          - optimizer : The optimizer to use.  The optimizer must take ``func``,
     |            and starting position as the first two arguments,
     |            plus ``args`` (for extra arguments to pass to the
     |            function to be optimized) and ``disp=0`` to suppress
     |            output as keyword arguments.
     |
     |      Returns
     |      -------
     |      mle_tuple : tuple of floats
     |          MLEs for any shape parameters (if applicable), followed by those
     |          for location and scale. For most random variables, shape statistics
     |          will be returned, but there are exceptions (e.g. ``norm``).
     |
     |      Notes
     |      -----
     |      This function uses explicit formulas for the maximum likelihood
     |      estimation of the normal distribution parameters, so the
     |      `optimizer` argument is ignored.
     |
     |      Examples
     |      --------
     |
     |      Generate some data to fit: draw random variates from the `beta`
     |      distribution
     |
     |      >>> from scipy.stats import beta
     |      >>> a, b = 1., 2.
     |      >>> x = beta.rvs(a, b, size=1000)
     |
     |      Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``):
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x)
     |
     |      We can also use some prior knowledge about the dataset: let's keep
     |      ``loc`` and ``scale`` fixed:
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
     |      >>> loc1, scale1
     |      (0, 1)
     |
     |      We can also keep shape parameters fixed by using ``f``-keywords. To
     |      keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
     |      equivalently, ``fa=1``:
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
     |      >>> a1
     |      1
     |
     |      Not all distributions return estimates for the shape parameters.
     |      ``norm`` for example just returns estimates for location and scale:
     |
     |      >>> from scipy.stats import norm
     |      >>> x = norm.rvs(a, b, size=1000, random_state=123)
     |      >>> loc1, scale1 = norm.fit(x)
     |      >>> loc1, scale1
     |      (0.92087172783841631, 2.0015750750324668)
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from scipy.stats._distn_infrastructure.rv_continuous:
     |
     |  __getstate__(self)
     |
     |  __init__(self, momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  cdf(self, x, *args, **kwds)
     |      Cumulative distribution function of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      cdf : ndarray
     |          Cumulative distribution function evaluated at `x`
     |
     |  expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)
     |      Calculate expected value of a function with respect to the
     |      distribution by numerical integration.
     |
     |      The expected value of a function ``f(x)`` with respect to a
     |      distribution ``dist`` is defined as::
     |
     |                  ub
     |          E[f(x)] = Integral(f(x) * dist.pdf(x)),
     |                  lb
     |
     |      where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``
     |      distribution. If the bounds ``lb`` and ``ub`` correspond to the
     |      support of the distribution, e.g. ``[-inf, inf]`` in the default
     |      case, then the integral is the unrestricted expectation of ``f(x)``.
     |      Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``
     |      outside a finite interval in which case the expectation is
     |      calculated within the finite range ``[lb, ub]``.
     |
     |      Parameters
     |      ----------
     |      func : callable, optional
     |          Function for which integral is calculated. Takes only one argument.
     |          The default is the identity mapping f(x) = x.
     |      args : tuple, optional
     |          Shape parameters of the distribution.
     |      loc : float, optional
     |          Location parameter (default=0).
     |      scale : float, optional
     |          Scale parameter (default=1).
     |      lb, ub : scalar, optional
     |          Lower and upper bound for integration. Default is set to the
     |          support of the distribution.
     |      conditional : bool, optional
     |          If True, the integral is corrected by the conditional probability
     |          of the integration interval.  The return value is the expectation
     |          of the function, conditional on being in the given interval.
     |          Default is False.
     |
     |      Additional keyword arguments are passed to the integration routine.
     |
     |      Returns
     |      -------
     |      expect : float
     |          The calculated expected value.
     |
     |      Notes
     |      -----
     |      The integration behavior of this function is inherited from
     |      `scipy.integrate.quad`. Neither this function nor
     |      `scipy.integrate.quad` can verify whether the integral exists or is
     |      finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and
     |      ``cauchy(0).expect()`` returns ``0.0``.
     |
     |      The function is not vectorized.
     |
     |      Examples
     |      --------
     |
     |      To understand the effect of the bounds of integration consider
     |
     |      >>> from scipy.stats import expon
     |      >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)
     |      0.6321205588285578
     |
     |      This is close to
     |
     |      >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)
     |      0.6321205588285577
     |
     |      If ``conditional=True``
     |
     |      >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)
     |      1.0000000000000002
     |
     |      The slight deviation from 1 is due to numerical integration.
     |
     |  fit_loc_scale(self, data, *args)
     |      Estimate loc and scale parameters from data using 1st and 2nd moments.
     |
     |      Parameters
     |      ----------
     |      data : array_like
     |          Data to fit.
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |
     |      Returns
     |      -------
     |      Lhat : float
     |          Estimated location parameter for the data.
     |      Shat : float
     |          Estimated scale parameter for the data.
     |
     |  isf(self, q, *args, **kwds)
     |      Inverse survival function (inverse of `sf`) at q of the given RV.
     |
     |      Parameters
     |      ----------
     |      q : array_like
     |          upper tail probability
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      x : ndarray or scalar
     |          Quantile corresponding to the upper tail probability q.
     |
     |  logcdf(self, x, *args, **kwds)
     |      Log of the cumulative distribution function at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logcdf : array_like
     |          Log of the cumulative distribution function evaluated at x
     |
     |  logpdf(self, x, *args, **kwds)
     |      Log of the probability density function at x of the given RV.
     |
     |      This uses a more numerically accurate calculation if available.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logpdf : array_like
     |          Log of the probability density function evaluated at x
     |
     |  logsf(self, x, *args, **kwds)
     |      Log of the survival function of the given RV.
     |
     |      Returns the log of the "survival function," defined as (1 - `cdf`),
     |      evaluated at `x`.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logsf : ndarray
     |          Log of the survival function evaluated at `x`.
     |
     |  nnlf(self, theta, x)
     |      Return negative loglikelihood function.
     |
     |      Notes
     |      -----
     |      This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
     |      parameters (including loc and scale).
     |
     |  pdf(self, x, *args, **kwds)
     |      Probability density function at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      pdf : ndarray
     |          Probability density function evaluated at x
     |
     |  ppf(self, q, *args, **kwds)
     |      Percent point function (inverse of `cdf`) at q of the given RV.
     |
     |      Parameters
     |      ----------
     |      q : array_like
     |          lower tail probability
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      x : array_like
     |          quantile corresponding to the lower tail probability q.
     |
     |  sf(self, x, *args, **kwds)
     |      Survival function (1 - `cdf`) at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      sf : array_like
     |          Survival function evaluated at x
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from scipy.stats._distn_infrastructure.rv_generic:
     |
     |  __call__(self, *args, **kwds)
     |      Freeze the distribution for the given arguments.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution.  Should include all
     |          the non-optional arguments, may include ``loc`` and ``scale``.
     |
     |      Returns
     |      -------
     |      rv_frozen : rv_frozen instance
     |          The frozen distribution.
     |
     |  __setstate__(self, state)
     |
     |  entropy(self, *args, **kwds)
     |      Differential entropy of the RV.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          Location parameter (default=0).
     |      scale : array_like, optional  (continuous distributions only).
     |          Scale parameter (default=1).
     |
     |      Notes
     |      -----
     |      Entropy is defined base `e`:
     |
     |      >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
     |      >>> np.allclose(drv.entropy(), np.log(2.0))
     |      True
     |
     |  freeze(self, *args, **kwds)
     |      Freeze the distribution for the given arguments.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution.  Should include all
     |          the non-optional arguments, may include ``loc`` and ``scale``.
     |
     |      Returns
     |      -------
     |      rv_frozen : rv_frozen instance
     |          The frozen distribution.
     |
     |  interval(self, alpha, *args, **kwds)
     |      Confidence interval with equal areas around the median.
     |
     |      Parameters
     |      ----------
     |      alpha : array_like of float
     |          Probability that an rv will be drawn from the returned range.
     |          Each value should be in the range [0, 1].
     |      arg1, arg2, ... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter, Default is 0.
     |      scale : array_like, optional
     |          scale parameter, Default is 1.
     |
     |      Returns
     |      -------
     |      a, b : ndarray of float
     |          end-points of range that contain ``100 * alpha %`` of the rv's
     |          possible values.
     |
     |  mean(self, *args, **kwds)
     |      Mean of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      mean : float
     |          the mean of the distribution
     |
     |  median(self, *args, **kwds)
     |      Median of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          Location parameter, Default is 0.
     |      scale : array_like, optional
     |          Scale parameter, Default is 1.
     |
     |      Returns
     |      -------
     |      median : float
     |          The median of the distribution.
     |
     |      See Also
     |      --------
     |      rv_discrete.ppf
     |          Inverse of the CDF
     |
     |  moment(self, n, *args, **kwds)
     |      n-th order non-central moment of distribution.
     |
     |      Parameters
     |      ----------
     |      n : int, n >= 1
     |          Order of moment.
     |      arg1, arg2, arg3,... : float
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |  rvs(self, *args, **kwds)
     |      Random variates of given type.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          Location parameter (default=0).
     |      scale : array_like, optional
     |          Scale parameter (default=1).
     |      size : int or tuple of ints, optional
     |          Defining number of random variates (default is 1).
     |      random_state : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional
     |          If `seed` is `None` the `~np.random.RandomState` singleton is used.
     |          If `seed` is an int, a new ``RandomState`` instance is used, seeded
     |          with seed.
     |          If `seed` is already a ``RandomState`` or ``Generator`` instance,
     |          then that object is used.
     |          Default is None.
     |
     |      Returns
     |      -------
     |      rvs : ndarray or scalar
     |          Random variates of given `size`.
     |
     |  stats(self, *args, **kwds)
     |      Some statistics of the given RV.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional (continuous RVs only)
     |          scale parameter (default=1)
     |      moments : str, optional
     |          composed of letters ['mvsk'] defining which moments to compute:
     |          'm' = mean,
     |          'v' = variance,
     |          's' = (Fisher's) skew,
     |          'k' = (Fisher's) kurtosis.
     |          (default is 'mv')
     |
     |      Returns
     |      -------
     |      stats : sequence
     |          of requested moments.
     |
     |  std(self, *args, **kwds)
     |      Standard deviation of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      std : float
     |          standard deviation of the distribution
     |
     |  support(self, *args, **kwargs)
     |      Return the support of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, ... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter, Default is 0.
     |      scale : array_like, optional
     |          scale parameter, Default is 1.
     |      Returns
     |      -------
     |      a, b : float
     |          end-points of the distribution's support.
     |
     |  var(self, *args, **kwds)
     |      Variance of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      var : float
     |          the variance of the distribution
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from scipy.stats._distn_infrastructure.rv_generic:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
     |
     |  random_state
     |      Get or set the RandomState object for generating random variates.
     |
     |      This can be either None, int, a RandomState instance, or a
     |      np.random.Generator instance.
     |
     |      If None (or np.random), use the RandomState singleton used by np.random.
     |      If already a RandomState or Generator instance, use it.
     |      If an int, use a new RandomState instance seeded with seed.

__A:cdf

 |  cdf(self, x, *args, **kwds)
 |      Cumulative distribution function of the given RV.
 |
 |      Parameters
 |      ----------
 |      x : array_like
 |          quantiles
 |      arg1, arg2, arg3,... : array_like
 |          The shape parameter(s) for the distribution (see docstring of the
 |          instance object for more information)
 |      loc : array_like, optional
 |          location parameter (default=0)
 |      scale : array_like, optional
 |          scale parameter (default=1)
 |
 |      Returns
 |      -------
 |      cdf : ndarray
 |          Cumulative distribution function evaluated at `x`

__Q2:__ Use the method that generates random variates to draw five samples from the standard normal distribution.

__A:__

```python
seed(47)
# draw five samples here
std = 1
mean = 0
samples = np.random.normal(mean, std, size=5)
```

__Q3:__ What is the mean of this sample? Is it exactly equal to the value you expected? Hint: the sample was drawn from the standard normal distribution. If you want a reminder of the properties of this distribution, check out p. 85 of *AoS*.

```python
samples.mean()
```

    0.19355593334131074

```python
samples
```

    array([-0.84800948,  1.30590636,  0.92420797,  0.6404118 , -1.05473698])

__A:__ The mean in about .2

```python
# Calculate and print the mean here, hint: use np.mean()
np.mean(samples)
```

    0.19355593334131074

__Q4:__ What is the standard deviation of these numbers? Calculate this manually here as $\sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n}}$ (This is just the definition of **standard deviation** given by Professor Spiegelhalter on p.403 of *AoS*). Hint: np.sqrt() and np.sum() will be useful here and remember that numPy supports [broadcasting](https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html).

__A:__

```python
std = np.sqrt((np.sum((samples-np.mean(samples))**2))/len(samples))
std
```

    0.9606195639478641

Here we have calculated the actual standard deviation of a small data set (of size 5). But in this case, this small data set is actually a sample from our larger (infinite) population. In this case, the population is infinite because we could keep drawing our normal random variates until our computers die!

In general, the sample mean we calculate will not be equal to the population mean (as we saw above). A consequence of this is that the sum of squares of the deviations from the _population_ mean will be bigger than the sum of squares of the deviations from the _sample_ mean. In other words, the sum of squares of the deviations from the _sample_ mean is too small to give an unbiased estimate of the _population_ variance. An example of this effect is given [here](https://en.wikipedia.org/wiki/Bessel%27s_correction#Source_of_bias). Scaling our estimate of the variance by the factor $n/(n-1)$ gives an unbiased estimator of the population variance. This factor is known as [Bessel's correction](https://en.wikipedia.org/wiki/Bessel%27s_correction). The consequence of this is that the $n$ in the denominator is replaced by $n-1$.

You can see Bessel's correction reflected in Professor Spiegelhalter's definition of **variance** on p. 405 of *AoS*.

__Q5:__ If all we had to go on was our five samples, what would be our best estimate of the population standard deviation? Use Bessel's correction ($n-1$ in the denominator), thus $\sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n-1}}$.

__A:__

```python
bes_std = np.sqrt(np.sum((samples-np.mean(samples))**2)/(len(samples)-1))
bes_std
```

    1.0740053227518152

__Q6:__ Now use numpy's std function to calculate the standard deviation of our random samples. Which of the above standard deviations did it return?

__A:__

```python
np.std(samples)
```

    0.9606195639478641

__Q7:__ Consult the documentation for np.std() to see how to apply the correction for estimating the population parameter and verify this produces the expected result.

__A:__

```python
help(np.std)
```

    Help on function std in module numpy:

    std(a, axis=None, dtype=None, out=None, ddof=0, keepdims=<no value>, *, where=<no value>)
        Compute the standard deviation along the specified axis.

        Returns the standard deviation, a measure of the spread of a distribution,
        of the array elements. The standard deviation is computed for the
        flattened array by default, otherwise over the specified axis.

        Parameters
        ----------
        a : array_like
            Calculate the standard deviation of these values.
        axis : None or int or tuple of ints, optional
            Axis or axes along which the standard deviation is computed. The
            default is to compute the standard deviation of the flattened array.

            .. versionadded:: 1.7.0

            If this is a tuple of ints, a standard deviation is performed over
            multiple axes, instead of a single axis or all the axes as before.
        dtype : dtype, optional
            Type to use in computing the standard deviation. For arrays of
            integer type the default is float64, for arrays of float types it is
            the same as the array type.
        out : ndarray, optional
            Alternative output array in which to place the result. It must have
            the same shape as the expected output but the type (of the calculated
            values) will be cast if necessary.
        ddof : int, optional
            Means Delta Degrees of Freedom.  The divisor used in calculations
            is ``N - ddof``, where ``N`` represents the number of elements.
            By default `ddof` is zero.
        keepdims : bool, optional
            If this is set to True, the axes which are reduced are left
            in the result as dimensions with size one. With this option,
            the result will broadcast correctly against the input array.

            If the default value is passed, then `keepdims` will not be
            passed through to the `std` method of sub-classes of
            `ndarray`, however any non-default value will be.  If the
            sub-class' method does not implement `keepdims` any
            exceptions will be raised.

        where : array_like of bool, optional
            Elements to include in the standard deviation.
            See `~numpy.ufunc.reduce` for details.

            .. versionadded:: 1.20.0

        Returns
        -------
        standard_deviation : ndarray, see dtype parameter above.
            If `out` is None, return a new array containing the standard deviation,
            otherwise return a reference to the output array.

        See Also
        --------
        var, mean, nanmean, nanstd, nanvar
        :ref:`ufuncs-output-type`

        Notes
        -----
        The standard deviation is the square root of the average of the squared
        deviations from the mean, i.e., ``std = sqrt(mean(x))``, where
        ``x = abs(a - a.mean())**2``.

        The average squared deviation is typically calculated as ``x.sum() / N``,
        where ``N = len(x)``. If, however, `ddof` is specified, the divisor
        ``N - ddof`` is used instead. In standard statistical practice, ``ddof=1``
        provides an unbiased estimator of the variance of the infinite population.
        ``ddof=0`` provides a maximum likelihood estimate of the variance for
        normally distributed variables. The standard deviation computed in this
        function is the square root of the estimated variance, so even with
        ``ddof=1``, it will not be an unbiased estimate of the standard deviation
        per se.

        Note that, for complex numbers, `std` takes the absolute
        value before squaring, so that the result is always real and nonnegative.

        For floating-point input, the *std* is computed using the same
        precision the input has. Depending on the input data, this can cause
        the results to be inaccurate, especially for float32 (see example below).
        Specifying a higher-accuracy accumulator using the `dtype` keyword can
        alleviate this issue.

        Examples
        --------
        >>> a = np.array([[1, 2], [3, 4]])
        >>> np.std(a)
        1.1180339887498949 # may vary
        >>> np.std(a, axis=0)
        array([1.,  1.])
        >>> np.std(a, axis=1)
        array([0.5,  0.5])

        In single precision, std() can be inaccurate:

        >>> a = np.zeros((2, 512*512), dtype=np.float32)
        >>> a[0, :] = 1.0
        >>> a[1, :] = 0.1
        >>> np.std(a)
        0.45000005

        Computing the standard deviation in float64 is more accurate:

        >>> np.std(a, dtype=np.float64)
        0.44999999925494177 # may vary

        Specifying a where argument:

        >>> a = np.array([[14, 8, 11, 10], [7, 9, 10, 11], [10, 15, 5, 10]])
        >>> np.std(a)
        2.614064523559687 # may vary
        >>> np.std(a, where=[[True], [True], [False]])
        2.0

```python
np.std(samples,ddof=1)
```

    1.0740053227518152

### Summary of section

In this section, you've been introduced to the scipy.stats package and used it to draw a small sample from the standard normal distribution. You've calculated the average (the mean) of this sample and seen that this is not exactly equal to the expected population parameter (which we know because we're generating the random variates from a specific, known distribution). You've been introduced to two ways of calculating the standard deviation; one uses $n$ in the denominator and the other uses $n-1$ (Bessel's correction). You've also seen which of these calculations np.std() performs by default and how to get it to generate the other.

You use $n$ as the denominator if you want to calculate the standard deviation of a sequence of numbers. You use $n-1$ if you are using this sequence of numbers to estimate the population parameter. This brings us to some terminology that can be a little confusing.

The population parameter is traditionally written as $\sigma$ and the sample statistic as $s$. Rather unhelpfully, $s$ is also called the sample standard deviation (using $n-1$) whereas the standard deviation of the sample uses $n$. That's right, we have the sample standard deviation and the standard deviation of the sample and they're not the same thing!

The sample standard deviation
\begin{equation}
s = \sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n-1}} \approx \sigma,
\end{equation}
is our best (unbiased) estimate of the population parameter ($\sigma$).

If your dataset _is_ your entire population, you simply want to calculate the population parameter, $\sigma$, via
\begin{equation}
\sigma = \sqrt{\frac{\sum_i(x_i - \bar{x})^2}{n}}
\end{equation}
as you have complete, full knowledge of your population. In other words, your sample _is_ your population. It's worth noting that we're dealing with what Professor Spiegehalter describes on p. 92 of *AoS* as a **metaphorical population**: we have all the data, and we act as if the data-point is taken from a population at random. We can think of this population as an imaginary space of possibilities.

If, however, you have sampled _from_ your population, you only have partial knowledge of the state of your population. In this case, the standard deviation of your sample is not an unbiased estimate of the standard deviation of the population, in which case you seek to estimate that population parameter via the sample standard deviation, which uses the $n-1$ denominator.

Great work so far! Now let's dive deeper.

## 3. Sampling distributions

So far we've been dealing with the concept of taking a sample from a population to infer the population parameters. One statistic we calculated for a sample was the mean. As our samples will be expected to vary from one draw to another, so will our sample statistics. If we were to perform repeat draws of size $n$ and calculate the mean of each, we would expect to obtain a distribution of values. This is the sampling distribution of the mean. **The Central Limit Theorem (CLT)** tells us that such a distribution will approach a normal distribution as $n$ increases (the intuitions behind the CLT are covered in full on p. 236 of *AoS*). For the sampling distribution of the mean, the standard deviation of this distribution is given by

\begin{equation}
\sigma_{mean} = \frac{\sigma}{\sqrt n}
\end{equation}

where $\sigma_{mean}$ is the standard deviation of the sampling distribution of the mean and $\sigma$ is the standard deviation of the population (the population parameter).

This is important because typically we are dealing with samples from populations and all we know about the population is what we see in the sample. From this sample, we want to make inferences about the population. We may do this, for example, by looking at the histogram of the values and by calculating the mean and standard deviation (as estimates of the population parameters), and so we are intrinsically interested in how these quantities vary across samples.

In other words, now that we've taken one sample of size $n$ and made some claims about the general population, what if we were to take another sample of size $n$? Would we get the same result? Would we make the same claims about the general population? This brings us to a fundamental question: _when we make some inference about a population based on our sample, how confident can we be that we've got it 'right'?_

We need to think about **estimates and confidence intervals**: those concepts covered in Chapter 7, p. 189, of *AoS*.

Now, the standard normal distribution (with its variance equal to its standard deviation of one) would not be a great illustration of a key point. Instead, let's imagine we live in a town of 50,000 people and we know the height of everyone in this town. We will have 50,000 numbers that tell us everything about our population. We'll simulate these numbers now and put ourselves in one particular town, called 'town 47', where the population mean height is 172 cm and population standard deviation is 5 cm.

```python
seed(47)
pop_heights = norm.rvs(172, 5, size=50000)
```

```python
_ = plt.hist(pop_heights, bins=30)
_ = plt.xlabel('height (cm)')
_ = plt.ylabel('number of people')
_ = plt.title('Distribution of heights in entire town population')
_ = plt.axvline(172, color='r')
_ = plt.axvline(172+5, color='r', linestyle='--')
_ = plt.axvline(172-5, color='r', linestyle='--')
_ = plt.axvline(172+10, color='r', linestyle='-.')
_ = plt.axvline(172-10, color='r', linestyle='-.')
```

Now, 50,000 people is rather a lot to chase after with a tape measure. If all you want to know is the average height of the townsfolk, then can you just go out and measure a sample to get a pretty good estimate of the average height?

```python
def townsfolk_sampler(n):
    return np.random.choice(pop_heights, n)
```

Let's say you go out one day and randomly sample 10 people to measure.

```python
seed(47)
daily_sample1 = townsfolk_sampler(10)
```

```python
_ = plt.hist(daily_sample1, bins=10)
_ = plt.xlabel('height (cm)')
_ = plt.ylabel('number of people')
_ = plt.title('Distribution of heights in sample size 10')
```

The sample distribution doesn't resemble what we take the population distribution to be. What do we get for the mean?

```python
np.mean(daily_sample1)
```

    173.47911444163503

And if we went out and repeated this experiment?

```python
daily_sample2 = townsfolk_sampler(10)
```

```python
np.mean(daily_sample2)
```

    173.7317666636263

__Q8:__ Simulate performing this random trial every day for a year, calculating the mean of each daily sample of 10, and plot the resultant sampling distribution of the mean.

__A:__

```python
year_means = []
for day in range(365):
    daily_mean = np.mean(townsfolk_sampler(10))
    year_means.append(daily_mean)

year_mean = np.mean(year_means)

```

```python
_ = plt.hist(year_means, bins=40)
_ = plt.xlabel('height (cm)')
_ = plt.ylabel('number of people')
_ = plt.title('Distribution of heights in sample size 10')
```

```python
seed(47)
# take your samples here
year_means = []
for day in range(365):
    daily_mean = np.mean(townsfolk_sampler(10))
    year_means.append(daily_mean)

year_mean = np.mean(year_means)
year_mean
```

    171.8660049358649

The above is the distribution of the means of samples of size 10 taken from our population. The Central Limit Theorem tells us the expected mean of this distribution will be equal to the population mean, and standard deviation will be $\sigma / \sqrt n$, which, in this case, should be approximately 1.58.

__Q9:__ Verify the above results from the CLT.

```python
np.std(year_means)
```

    1.5849461228591897

```python
5/(np.sqrt(10))
```

    1.5811388300841895

__A:__

```python

```

```python

```

Remember, in this instance, we knew our population parameters, that the average height really is 172 cm and the standard deviation is 5 cm, and we see some of our daily estimates of the population mean were as low as around 168 and some as high as 176.

__Q10:__ Repeat the above year's worth of samples but for a sample size of 50 (perhaps you had a bigger budget for conducting surveys that year)! Would you expect your distribution of sample means to be wider (more variable) or narrower (more consistent)? Compare your resultant summary statistics to those predicted by the CLT.

__A:__

```python
seed(47)
# calculate daily means from the larger sample size here
year_means50=[]
for day in range(365):
    daily_mean = np.mean(townsfolk_sampler(50))
    year_means50.append(daily_mean)

mean_50 = np.mean(year_means50)
mean_50

```

    171.94366080916114

```python
np.std(year_means50)
```

    0.6736107539771146

What we've seen so far, then, is that we can estimate population parameters from a sample from the population, and that samples have their own distributions. Furthermore, the larger the sample size, the narrower are those sampling distributions.

### Normally testing time!

All of the above is well and good. We've been sampling from a population we know is normally distributed, we've come to understand when to use $n$ and when to use $n-1$ in the denominator to calculate the spread of a distribution, and we've  seen the Central Limit Theorem in action for a sampling distribution. All seems very well behaved in Frequentist land. But, well, why should we really care?

Remember, we rarely (if ever) actually know our population parameters but we still have to estimate them somehow. If we want to make inferences to conclusions like "this observation is unusual" or "my population mean has changed" then we need to have some idea of what the underlying distribution is so we can calculate relevant probabilities. In frequentist inference, we use the formulae above to deduce these population parameters. Take a moment in the next part of this assignment to refresh your understanding of how these probabilities work.

Recall some basic properties of the standard normal distribution, such as that about 68% of observations are within plus or minus 1 standard deviation of the mean. Check out the precise definition of a normal distribution on p. 394 of *AoS*.

__Q11:__ Using this fact, calculate the probability of observing the value 1 or less in a single observation from the standard normal distribution. Hint: you may find it helpful to sketch the standard normal distribution (the familiar bell shape) and mark the number of standard deviations from the mean on the x-axis and shade the regions of the curve that contain certain percentages of the population.

__A:__

```python
rv = scipy.stats.norm(0,1)
```

```python
rv.pdf(1)
```

    0.24197072451914337

```python
rv.pdf(1)+rv.pdf(-1)
```

    0.48394144903828673

```python
rv.pdf(-1)
```

    0.24197072451914337

```python
import scipy
help(scipy.stats.norm)

```

    Help on norm_gen in module scipy.stats._continuous_distns object:

    class norm_gen(scipy.stats._distn_infrastructure.rv_continuous)
     |  norm_gen(momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)
     |
     |  A normal continuous random variable.
     |
     |  The location (``loc``) keyword specifies the mean.
     |  The scale (``scale``) keyword specifies the standard deviation.
     |
     |  %(before_notes)s
     |
     |  Notes
     |  -----
     |  The probability density function for `norm` is:
     |
     |  .. math::
     |
     |      f(x) = \frac{\exp(-x^2/2)}{\sqrt{2\pi}}
     |
     |  for a real number :math:`x`.
     |
     |  %(after_notes)s
     |
     |  %(example)s
     |
     |  Method resolution order:
     |      norm_gen
     |      scipy.stats._distn_infrastructure.rv_continuous
     |      scipy.stats._distn_infrastructure.rv_generic
     |      builtins.object
     |
     |  Methods defined here:
     |
     |  fit(self, data, **kwds)
     |      Return MLEs for shape (if applicable), location, and scale
     |      parameters from data.
     |
     |      MLE stands for Maximum Likelihood Estimate.  Starting estimates for
     |      the fit are given by input arguments; for any arguments not provided
     |      with starting estimates, ``self._fitstart(data)`` is called to generate
     |      such.
     |
     |      One can hold some parameters fixed to specific values by passing in
     |      keyword arguments ``f0``, ``f1``, ..., ``fn`` (for shape parameters)
     |      and ``floc`` and ``fscale`` (for location and scale parameters,
     |      respectively).
     |
     |      Parameters
     |      ----------
     |      data : array_like
     |          Data to use in calculating the MLEs.
     |      arg1, arg2, arg3,... : floats, optional
     |          Starting value(s) for any shape-characterizing arguments (those not
     |          provided will be determined by a call to ``_fitstart(data)``).
     |          No default value.
     |      kwds : floats, optional
     |          - `loc`: initial guess of the distribution's location parameter.
     |          - `scale`: initial guess of the distribution's scale parameter.
     |
     |          Special keyword arguments are recognized as holding certain
     |          parameters fixed:
     |
     |          - f0...fn : hold respective shape parameters fixed.
     |            Alternatively, shape parameters to fix can be specified by name.
     |            For example, if ``self.shapes == "a, b"``, ``fa`` and ``fix_a``
     |            are equivalent to ``f0``, and ``fb`` and ``fix_b`` are
     |            equivalent to ``f1``.
     |
     |          - floc : hold location parameter fixed to specified value.
     |
     |          - fscale : hold scale parameter fixed to specified value.
     |
     |          - optimizer : The optimizer to use.  The optimizer must take ``func``,
     |            and starting position as the first two arguments,
     |            plus ``args`` (for extra arguments to pass to the
     |            function to be optimized) and ``disp=0`` to suppress
     |            output as keyword arguments.
     |
     |      Returns
     |      -------
     |      mle_tuple : tuple of floats
     |          MLEs for any shape parameters (if applicable), followed by those
     |          for location and scale. For most random variables, shape statistics
     |          will be returned, but there are exceptions (e.g. ``norm``).
     |
     |      Notes
     |      -----
     |      This function uses explicit formulas for the maximum likelihood
     |      estimation of the normal distribution parameters, so the
     |      `optimizer` argument is ignored.
     |
     |      Examples
     |      --------
     |
     |      Generate some data to fit: draw random variates from the `beta`
     |      distribution
     |
     |      >>> from scipy.stats import beta
     |      >>> a, b = 1., 2.
     |      >>> x = beta.rvs(a, b, size=1000)
     |
     |      Now we can fit all four parameters (``a``, ``b``, ``loc`` and ``scale``):
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x)
     |
     |      We can also use some prior knowledge about the dataset: let's keep
     |      ``loc`` and ``scale`` fixed:
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x, floc=0, fscale=1)
     |      >>> loc1, scale1
     |      (0, 1)
     |
     |      We can also keep shape parameters fixed by using ``f``-keywords. To
     |      keep the zero-th shape parameter ``a`` equal 1, use ``f0=1`` or,
     |      equivalently, ``fa=1``:
     |
     |      >>> a1, b1, loc1, scale1 = beta.fit(x, fa=1, floc=0, fscale=1)
     |      >>> a1
     |      1
     |
     |      Not all distributions return estimates for the shape parameters.
     |      ``norm`` for example just returns estimates for location and scale:
     |
     |      >>> from scipy.stats import norm
     |      >>> x = norm.rvs(a, b, size=1000, random_state=123)
     |      >>> loc1, scale1 = norm.fit(x)
     |      >>> loc1, scale1
     |      (0.92087172783841631, 2.0015750750324668)
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from scipy.stats._distn_infrastructure.rv_continuous:
     |
     |  __getstate__(self)
     |
     |  __init__(self, momtype=1, a=None, b=None, xtol=1e-14, badvalue=None, name=None, longname=None, shapes=None, extradoc=None, seed=None)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |
     |  cdf(self, x, *args, **kwds)
     |      Cumulative distribution function of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      cdf : ndarray
     |          Cumulative distribution function evaluated at `x`
     |
     |  expect(self, func=None, args=(), loc=0, scale=1, lb=None, ub=None, conditional=False, **kwds)
     |      Calculate expected value of a function with respect to the
     |      distribution by numerical integration.
     |
     |      The expected value of a function ``f(x)`` with respect to a
     |      distribution ``dist`` is defined as::
     |
     |                  ub
     |          E[f(x)] = Integral(f(x) * dist.pdf(x)),
     |                  lb
     |
     |      where ``ub`` and ``lb`` are arguments and ``x`` has the ``dist.pdf(x)``
     |      distribution. If the bounds ``lb`` and ``ub`` correspond to the
     |      support of the distribution, e.g. ``[-inf, inf]`` in the default
     |      case, then the integral is the unrestricted expectation of ``f(x)``.
     |      Also, the function ``f(x)`` may be defined such that ``f(x)`` is ``0``
     |      outside a finite interval in which case the expectation is
     |      calculated within the finite range ``[lb, ub]``.
     |
     |      Parameters
     |      ----------
     |      func : callable, optional
     |          Function for which integral is calculated. Takes only one argument.
     |          The default is the identity mapping f(x) = x.
     |      args : tuple, optional
     |          Shape parameters of the distribution.
     |      loc : float, optional
     |          Location parameter (default=0).
     |      scale : float, optional
     |          Scale parameter (default=1).
     |      lb, ub : scalar, optional
     |          Lower and upper bound for integration. Default is set to the
     |          support of the distribution.
     |      conditional : bool, optional
     |          If True, the integral is corrected by the conditional probability
     |          of the integration interval.  The return value is the expectation
     |          of the function, conditional on being in the given interval.
     |          Default is False.
     |
     |      Additional keyword arguments are passed to the integration routine.
     |
     |      Returns
     |      -------
     |      expect : float
     |          The calculated expected value.
     |
     |      Notes
     |      -----
     |      The integration behavior of this function is inherited from
     |      `scipy.integrate.quad`. Neither this function nor
     |      `scipy.integrate.quad` can verify whether the integral exists or is
     |      finite. For example ``cauchy(0).mean()`` returns ``np.nan`` and
     |      ``cauchy(0).expect()`` returns ``0.0``.
     |
     |      The function is not vectorized.
     |
     |      Examples
     |      --------
     |
     |      To understand the effect of the bounds of integration consider
     |
     |      >>> from scipy.stats import expon
     |      >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0)
     |      0.6321205588285578
     |
     |      This is close to
     |
     |      >>> expon(1).cdf(2.0) - expon(1).cdf(0.0)
     |      0.6321205588285577
     |
     |      If ``conditional=True``
     |
     |      >>> expon(1).expect(lambda x: 1, lb=0.0, ub=2.0, conditional=True)
     |      1.0000000000000002
     |
     |      The slight deviation from 1 is due to numerical integration.
     |
     |  fit_loc_scale(self, data, *args)
     |      Estimate loc and scale parameters from data using 1st and 2nd moments.
     |
     |      Parameters
     |      ----------
     |      data : array_like
     |          Data to fit.
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |
     |      Returns
     |      -------
     |      Lhat : float
     |          Estimated location parameter for the data.
     |      Shat : float
     |          Estimated scale parameter for the data.
     |
     |  isf(self, q, *args, **kwds)
     |      Inverse survival function (inverse of `sf`) at q of the given RV.
     |
     |      Parameters
     |      ----------
     |      q : array_like
     |          upper tail probability
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      x : ndarray or scalar
     |          Quantile corresponding to the upper tail probability q.
     |
     |  logcdf(self, x, *args, **kwds)
     |      Log of the cumulative distribution function at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logcdf : array_like
     |          Log of the cumulative distribution function evaluated at x
     |
     |  logpdf(self, x, *args, **kwds)
     |      Log of the probability density function at x of the given RV.
     |
     |      This uses a more numerically accurate calculation if available.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logpdf : array_like
     |          Log of the probability density function evaluated at x
     |
     |  logsf(self, x, *args, **kwds)
     |      Log of the survival function of the given RV.
     |
     |      Returns the log of the "survival function," defined as (1 - `cdf`),
     |      evaluated at `x`.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      logsf : ndarray
     |          Log of the survival function evaluated at `x`.
     |
     |  nnlf(self, theta, x)
     |      Return negative loglikelihood function.
     |
     |      Notes
     |      -----
     |      This is ``-sum(log pdf(x, theta), axis=0)`` where `theta` are the
     |      parameters (including loc and scale).
     |
     |  pdf(self, x, *args, **kwds)
     |      Probability density function at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      pdf : ndarray
     |          Probability density function evaluated at x
     |
     |  ppf(self, q, *args, **kwds)
     |      Percent point function (inverse of `cdf`) at q of the given RV.
     |
     |      Parameters
     |      ----------
     |      q : array_like
     |          lower tail probability
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      x : array_like
     |          quantile corresponding to the lower tail probability q.
     |
     |  sf(self, x, *args, **kwds)
     |      Survival function (1 - `cdf`) at x of the given RV.
     |
     |      Parameters
     |      ----------
     |      x : array_like
     |          quantiles
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      sf : array_like
     |          Survival function evaluated at x
     |
     |  ----------------------------------------------------------------------
     |  Methods inherited from scipy.stats._distn_infrastructure.rv_generic:
     |
     |  __call__(self, *args, **kwds)
     |      Freeze the distribution for the given arguments.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution.  Should include all
     |          the non-optional arguments, may include ``loc`` and ``scale``.
     |
     |      Returns
     |      -------
     |      rv_frozen : rv_frozen instance
     |          The frozen distribution.
     |
     |  __setstate__(self, state)
     |
     |  entropy(self, *args, **kwds)
     |      Differential entropy of the RV.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          Location parameter (default=0).
     |      scale : array_like, optional  (continuous distributions only).
     |          Scale parameter (default=1).
     |
     |      Notes
     |      -----
     |      Entropy is defined base `e`:
     |
     |      >>> drv = rv_discrete(values=((0, 1), (0.5, 0.5)))
     |      >>> np.allclose(drv.entropy(), np.log(2.0))
     |      True
     |
     |  freeze(self, *args, **kwds)
     |      Freeze the distribution for the given arguments.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution.  Should include all
     |          the non-optional arguments, may include ``loc`` and ``scale``.
     |
     |      Returns
     |      -------
     |      rv_frozen : rv_frozen instance
     |          The frozen distribution.
     |
     |  interval(self, alpha, *args, **kwds)
     |      Confidence interval with equal areas around the median.
     |
     |      Parameters
     |      ----------
     |      alpha : array_like of float
     |          Probability that an rv will be drawn from the returned range.
     |          Each value should be in the range [0, 1].
     |      arg1, arg2, ... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter, Default is 0.
     |      scale : array_like, optional
     |          scale parameter, Default is 1.
     |
     |      Returns
     |      -------
     |      a, b : ndarray of float
     |          end-points of range that contain ``100 * alpha %`` of the rv's
     |          possible values.
     |
     |  mean(self, *args, **kwds)
     |      Mean of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      mean : float
     |          the mean of the distribution
     |
     |  median(self, *args, **kwds)
     |      Median of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          Location parameter, Default is 0.
     |      scale : array_like, optional
     |          Scale parameter, Default is 1.
     |
     |      Returns
     |      -------
     |      median : float
     |          The median of the distribution.
     |
     |      See Also
     |      --------
     |      rv_discrete.ppf
     |          Inverse of the CDF
     |
     |  moment(self, n, *args, **kwds)
     |      n-th order non-central moment of distribution.
     |
     |      Parameters
     |      ----------
     |      n : int, n >= 1
     |          Order of moment.
     |      arg1, arg2, arg3,... : float
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |  rvs(self, *args, **kwds)
     |      Random variates of given type.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          Location parameter (default=0).
     |      scale : array_like, optional
     |          Scale parameter (default=1).
     |      size : int or tuple of ints, optional
     |          Defining number of random variates (default is 1).
     |      random_state : {None, int, `~np.random.RandomState`, `~np.random.Generator`}, optional
     |          If `seed` is `None` the `~np.random.RandomState` singleton is used.
     |          If `seed` is an int, a new ``RandomState`` instance is used, seeded
     |          with seed.
     |          If `seed` is already a ``RandomState`` or ``Generator`` instance,
     |          then that object is used.
     |          Default is None.
     |
     |      Returns
     |      -------
     |      rvs : ndarray or scalar
     |          Random variates of given `size`.
     |
     |  stats(self, *args, **kwds)
     |      Some statistics of the given RV.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional (continuous RVs only)
     |          scale parameter (default=1)
     |      moments : str, optional
     |          composed of letters ['mvsk'] defining which moments to compute:
     |          'm' = mean,
     |          'v' = variance,
     |          's' = (Fisher's) skew,
     |          'k' = (Fisher's) kurtosis.
     |          (default is 'mv')
     |
     |      Returns
     |      -------
     |      stats : sequence
     |          of requested moments.
     |
     |  std(self, *args, **kwds)
     |      Standard deviation of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      std : float
     |          standard deviation of the distribution
     |
     |  support(self, *args, **kwargs)
     |      Return the support of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, ... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information).
     |      loc : array_like, optional
     |          location parameter, Default is 0.
     |      scale : array_like, optional
     |          scale parameter, Default is 1.
     |      Returns
     |      -------
     |      a, b : float
     |          end-points of the distribution's support.
     |
     |  var(self, *args, **kwds)
     |      Variance of the distribution.
     |
     |      Parameters
     |      ----------
     |      arg1, arg2, arg3,... : array_like
     |          The shape parameter(s) for the distribution (see docstring of the
     |          instance object for more information)
     |      loc : array_like, optional
     |          location parameter (default=0)
     |      scale : array_like, optional
     |          scale parameter (default=1)
     |
     |      Returns
     |      -------
     |      var : float
     |          the variance of the distribution
     |
     |  ----------------------------------------------------------------------
     |  Data descriptors inherited from scipy.stats._distn_infrastructure.rv_generic:
     |
     |  __dict__
     |      dictionary for instance variables (if defined)
     |
     |  __weakref__
     |      list of weak references to the object (if defined)
     |
     |  random_state
     |      Get or set the RandomState object for generating random variates.
     |
     |      This can be either None, int, a RandomState instance, or a
     |      np.random.Generator instance.
     |
     |      If None (or np.random), use the RandomState singleton used by np.random.
     |      If already a RandomState or Generator instance, use it.
     |      If an int, use a new RandomState instance seeded with seed.

```python
norm(0, 1).pdf(68)
```

    0.0

```python
from statistics import NormalDist

NormalDist(mu=0, sigma=1).pdf(1)
```

    0.24197072451914337

```python
from statistics import NormalDist

NormalDist(mu=0, sigma=1).pdf(0)
```

    0.3989422804014327

```python
rv.cdf(1)
```

    0.8413447460685429

Calculating this probability involved calculating the area under the curve from the value of 1 and below. To put it in mathematical terms, we need to *integrate* the probability density function. We could just add together the known areas of chunks (from -Inf to 0 and then 0 to $+\sigma$ in the example above). One way to do this is to look up tables (literally). Fortunately, scipy has this functionality built in with the cdf() function.

__Q12:__ Use the cdf() function to answer the question above again and verify you get the same answer.

__A:__

```python
NormalDist(mu=0, sigma=1).cdf(1)

```

    0.8413447460685429

__Q13:__ Using our knowledge of the population parameters for our townsfolks' heights, what is the probability of selecting one person at random and their height being 177 cm or less? Calculate this using both of the approaches given above.

__A:__

```python
seed(47)
# pop_heights = norm.rvs(172, 5, size=50000)

rv = norm(172,5)
rv.cdf(177)
```

    0.8413447460685429

```python
NormalDist(mu=172,sigma=5).cdf(177)
```

    0.8413447460685429

__Q14:__ Turning this question around — suppose we randomly pick one person and measure their height and find they are 2.00 m tall. How surprised should we be at this result, given what we know about the population distribution? In other words, how likely would it be to obtain a value at least as extreme as this? Express this as a probability.

__A:__

```python
NormalDist(mu=172,sigma=5).pdf(20)
```

    1.671651966784499e-202

What we've just done is calculate the ***p-value*** of the observation of someone 2.00m tall (review *p*-values if you need to on p. 399 of *AoS*). We could calculate this probability by virtue of knowing the population parameters. We were then able to use the known properties of the relevant normal distribution to calculate the probability of observing a value at least as extreme as our test value.

We're about to come to a pinch, though. We've said a couple of times that we rarely, if ever, know the true population parameters; we have to estimate them from our sample and we cannot even begin to estimate the standard deviation from a single observation.

This is very true and usually we have sample sizes larger than one. This means we can calculate the mean of the sample as our best estimate of the population mean and the standard deviation as our best estimate of the population standard deviation.

In other words, we are now coming to deal with the sampling distributions we mentioned above as we are generally concerned with the properties of the sample means we obtain.

Above, we highlighted one result from the CLT, whereby the sampling distribution (of the mean) becomes narrower and narrower with the square root of the sample size. We remind ourselves that another result from the CLT is that _even if the underlying population distribution is not normal, the sampling distribution will tend to become normal with sufficiently large sample size_. (**Check out p. 199 of AoS if you need to revise this**). This is the key driver for us 'requiring' a certain sample size, for example you may frequently see a minimum sample size of 30 stated in many places. In reality this is simply a rule of thumb; if the underlying distribution is approximately normal then your sampling distribution will already be pretty normal, but if the underlying distribution is heavily skewed then you'd want to increase your sample size.

__Q15:__ Let's now start from the position of knowing nothing about the heights of people in our town.
* Use the random seed of 47, to randomly sample the heights of 50 townsfolk
* Estimate the population mean using np.mean
* Estimate the population standard deviation using np.std (remember which denominator to use!)
* Calculate the (95%) [margin of error](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/hypothesis-testing/margin-of-error/#WhatMofE) (use the exact critial z value to 2 decimal places - [look this up](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/find-critical-values/) or use norm.ppf()) Recall that the ***margin of error*** is mentioned on p. 189 of the *AoS* and discussed in depth in that chapter).
* Calculate the 95% Confidence Interval of the mean (***confidence intervals*** are defined on p. 385 of *AoS*)
* Does this interval include the true population mean?

__A:__

```python
import scipy
seed(47)
# take your sample now
sample= np.random.normal(172,5,50)

```

```python
np.mean(sample)

```

    171.09434218281885

```python
## use 1 degree of freedom as we are estimating the population standard devation
np.std(sample,ddof=1)

```

    4.868476091077329

```python
ss2= np.random.choice(pop_heights, 50)

```

```python
sample_mean = np.mean(ss2)
sample_mean

```

    172.89822406473004

```python
sample_std= np.std(ss2,ddof=1)
sample_std

```

    4.205530631644485

```python
z_critical = scipy.stats.norm.ppf(q=0.95)
z_critical

```

    1.6448536269514722

```python
z_critical = scipy.stats.norm.ppf(q=0.95)
z_critical

margin_of_error = z_critical * (np.std(sample)/np.sqrt(50))

margin_of_error

```

    1.12111027785891

```python
confidence_interval = (sample_mean-margin_of_error,sample_mean+margin_of_error)
confidence_interval

```

    (171.77711378687113, 174.01933434258896)

__Q16:__ Above, we calculated the confidence interval using the critical z value. What is the problem with this? What requirement, or requirements, are we (strictly) failing?

__A:__ you need to have the standard deviation of the population to use a z score to create a confidence interval. If you do not have the population std you need to use a t score.

__Q17:__ Calculate the 95% confidence interval for the mean using the _t_ distribution. Is this wider or narrower than that based on the normal distribution above? If you're unsure, you may find this [resource](https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/confidence-interval/) useful. For calculating the critical value, remember how you could calculate this for the normal distribution using norm.ppf().

```python
from scipy import stats

print (stats.t.ppf(1-0.05, 49))
```

    1.6765508919142629

```python
import scipy.stats
margin_of_error_with_t = (scipy.stats.t.ppf(1-0.05, 49)) * sample_mean/np.sqrt(50)
margin_of_error_with_t
```

    40.47687285231234

```python
# ask if this is only for z score calculation
#margin_of_error_with_t= (sample_mean-np.mean(pop_heights))/(sample_std/(np.sqrt(50)))
# margin_of_error_with_t
```

    1.477866489379801

__A:__

```python
t_conf_interval = (sample_mean-margin_of_error_with_t,sample_mean+margin_of_error_with_t)
t_conf_interval
```

    (130.23951525813817, 211.19326096276285)

```python
sample_size = 50

intervals = []
sample_means = []

for sample in range(25):
    sample = np.random.choice(a= pop_heights, size = sample_size)
    sample_mean = np.mean(sample)
    sample_means.append(sample_mean)

    z_critical = scipy.stats.norm.ppf(q = 0.95)  # Get the z-critical value*

    pop_stdev = np.std(pop_heights)  # Get the population standard deviation

    scipy.stats.norm.ppf(q = 0.05)

    margin_of_error = z_critical * (pop_stdev/np.sqrt(sample_size))

    confidence_interval = (sample_mean - margin_of_error,
                           sample_mean + margin_of_error)

    intervals.append(confidence_interval)

```

```python

plt.figure(figsize=(9,9))

plt.errorbar(x=np.arange(0.1, 25, 1),
             y=sample_means,
             yerr=[(top-bot)/2 for top,bot in intervals],
             fmt='o')

plt.hlines(xmin=0, xmax=25,
           y=172,
           linewidth=2.0,
           color="red")
```

This is slightly wider than the previous confidence interval. This reflects the greater uncertainty given that we are estimating population parameters from a sample.

## 4. Learning outcomes

Having completed this project notebook, you now have hands-on experience:
* sampling and calculating probabilities from a normal distribution
* identifying the correct way to estimate the standard deviation of a population (the population parameter) from a sample
* with sampling distribution and now know how the Central Limit Theorem applies
* with how to calculate critical values and confidence intervals

```python

```

Frequentist Case Study/Frequentist Inference Case Study - Part A (3).ipynb


```python
%matplotlib inline
```

```python
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import odeint
```

# In class assignment for the predator-prey model

## Goal for today's assignment
 we probably want to rephrase/update the goals in line with what's written in the intro

After finishing the activity, you will
- understand and be able to implement the fundamentals of solving ordinary differential equations numerically
- be able to use this knowledge and skillset to generally solve for compartmentalized models

## Overview of the activity
Today, you will
- write your own forward Euler to replace ODEint used in initial explorations (20 minutes)
- write and conduct simple tests of your forward Euler implementation
- re-solve the rumor spreading equations from the intro activity and compare with the solution using ODEint (5 minutes)
- implement your chosen model system (20 minutes)
- will solve the model system to answer your question  (15 minutes)

The time behind the is meant as a guidance. The facilitators will help to keep you on time.  We probably need to talk about timing in order to have sufficient time for the jigsaw and synthesis

After you finished the notebook, we will discuss the results together in class.

## Recap: rumor-spreading model

- TODO: need to copy info over from intro notebook
- Philipp: I just put some placeholders using https://services.math.duke.edu/education/postcalc/ode/ode1.html as reference in order to not duplicate efforts as Adam is writing this part for the intro notebook.

```python
def RHS(state,time):
    S = state
    return k*S*(M - S)

M = 1000# population in school
k = .01 # juiciness of rumor
time = np.linspace(0,3,100)
init_S = np.array([2])

y_odeint = odeint(RHS, init_S, time)
```

```python
plt.plot(time,y_odeint,label='odeint')
plt.xlabel('time')
plt.ylabel('S')
plt.legend()
plt.grid()
```

### Please implement your own forward Euler algorithm in the cell below
Make sure that you use the same interface as `odeint` (i.e., the function call with respect to arguments is identical).

```python
### YOUR CODE HERE ####
# def myodeint...
```

### Solve the rumor spread equation using the same parameters as before but with your own implementation

```python
M = 1000# population in school
k = .01 # juiciness of rumor
time = np.linspace(0,3,100)
init_S = np.array([2])

y_myodeint = myodeint(RHS, init_S, time)
```

### Compare the results between `odeint` and your own implementation in the cell below
 We leave the format free and if they ask how, we ask back what options to compare they can think of, e.g., plot both results on one graph, plot the ration between results, just calculate the total deviation with numpy, etc...

```python
# your comparison here
```

## Summary of the model (Lotka-Volterra equations)
- see https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations for reference
- TODO: some more text could potentially be copied from the intro notebook or in class presentation material

### Equations

\begin{equation}
\frac {dx}{dt} = \alpha x-\beta xy  \\
\frac {dy}{dt} =\delta xy-\gamma y
\end{equation}

with
- $x$ prey polpulation
- $y$ predator population
- $\alpha x$ exponential prey growth
- $\beta x y$ predation rate proportional to the rate at which the predators and the prey meet
- $\delta x y$ predator growth
- $\gamma y$  natural loss rate (exponential decay)

### Assumptions

- The prey population finds ample food at all times.
- The food supply of the predator population depends entirely on the size of the prey population.
- The rate of change of population is proportional to its size.
- During the process, the environment does not change in favour of one species, and genetic adaptation is inconsequential.
- Predators have limitless appetite.

### Please enter the question(s) you want to investige in this cell:
< Question(s) >

### Sample model parameters
The following parameters should be used as a starting point for your investigation. Remember, even though they are stated as bare numbers, all model parameters and variables carry units!

- initial populations: 0.9
- $\alpha = 2/3$
- $\beta = 4/3$
- $\gamma = 1$
- $\delta = 1$
- time: linearly spaced between 0 and 20 with steps of 0.2

```python

```

### Implement the right hand sides of the model questions in the cell below:
Again, remember to use the same interface as before.

```python
### YOUR CODE HERE ####
# def RHS...
```

### Use the space below to explore your model
In other words,
- try different parameters
- is there an efficient way to reduce repetative code?
- think about how you can present/visualize the results

### Your model exploration starts here

```python
### your model exploration
### create additional cells as necessary
```

### Your model exploration ends here

## Final questions

### Answer your own original question below. Support your answer with data.

```python
### answer here
```

### How does your result (the answer to the question you investigated) depend on the choice of model parameters?

```python
### answer here
```

### Demonstrate the robustness of your answer with respect to resolution.

```python
### answer here
```

### If you wanted to explore one of the other models, which parts of your code could you reuse and which would need to be modified?

```python
### answer here
```

```python

```

We also have the following question in the TP:

What numerical parameters are needed to specify the model you chose to
explore (for example, the $K_1$, $k_2$, $k_3$ parameters in the
         generic 2-compartment model)?

However, given that we potentially need to provide sample parameters (see above), we implicitly already answer the question in its current phrasing.

```python

```


```python
from sympy import *
from sympy.plotting import plot
from sympy.physics.continuum_mechanics.beam import Beam
init_printing(use_latex="mathjax")
x = symbols("x")
```

```python
E, I = symbols('E, I')
R1, R2 = symbols('R1, R2')
L = 144
E, I = 29e6, 100
b = Beam(L, E, I)
b.apply_load(R1, 0, -1)
b.apply_load(R2, L, -1)
b.apply_load(-15e3, L/2, -1)
b.bc_deflection = [(L, 0),]
#.solve_for_reaction_loads(R1,R2)
```

```python
df = b.deflection()
ss = b.shear_force()
mm = b.bending_moment()
b.reaction_loads
```

$$\left \{ \right \}$$

```python
#plot(ss, ("x",0,L))
```

```python
#plot(mm, ("x",0,L))
```

```python
limit(b.shear_force(), b.variable, b.length)
```

$$R_{1} + R_{2} - 15000.0$$

```python
limit(b.bending_moment(), x, b.length)
```

$$144.0 R_{1} - 1080000.0$$


```python
%matplotlib inline
from sympy import *
init_printing(use_unicode=True)
```

```python
r, u, v, c, r_c, u_c, v_c, E, p, r_p, u_p, v_p, e, a, b, q, b_0, b_1, b_2, b_3, q_0, q_1, q_2, q_3, q_4, q_5, t, g, c_0, c_1, c_2, c_3, c_4, c_5 = symbols('r u v c r_c u_c v_c E p r_p u_p v_p e a b q b_0 b_1 b_2 b_3 q_0 q_1 q_2 q_3 q_4 q_5 t g c_0 c_1 c_2 c_3 c_4 c_5',positive=True)
```

```python
cprm, thetaprm, Pprm, betaprm, rtheta, gammaprm, rhoprm, Eprm, sigmaprm = symbols('cprm thetaprm Pprm betaprm r_theta gammaprm rhoprm Eprm sigmaprm',positive=True)
```

```python
gamma,r_p,u_p,e = symbols('gamma r_p u_p e',positive=True)
```

####$f_{2}(c,p) = \dfrac{1}{2}r_{c}c^{2}+\dfrac{1}{4}u_{c}c^{4}+\dfrac{1}{6}v_{c}c^{6}+\dfrac{1}{2}r_{p}p^{2}+\dfrac{1}{4}u_{p}p^{4}-\gamma cp-\dfrac{1}{2}ec^{2}p^{2}-Ep$

```python
f2 = ((1/2)*r_c*c**2+(1/4)*u_c*c**4+(1/6)*v_c*c**6+(1/2)*r_p*p**2+(1/4)*u_p*p**4-E*p-gamma*c*p-e*c**2*p**2/2)
nsimplify(f2)
```

###Rescaling

```python
P, C, w, rho, beta, tau, Epr = symbols('P C w rho beta tau E^{\prime}')
```

```python
fP = nsimplify(f2.subs(p,w*Pprm))
fP
```

```python
fP = nsimplify(fP.subs(w,sqrt(r_p/u_p)))
fP
```

```python
fP = expand(fP/(r_p**2/u_p),r_p)
fP
```

```python
fP = fP.subs([(E,Epr/sqrt(u_p)*r_p**(3/2)),(c,cprm*sqrt(r_p/e))])
fP
```

```python
fP = fP.subs([(cprm,thetaprm),(r_c,rtheta*e*r_p/u_p),(u_c,gammaprm*e**2/u_p),(v_c,rhoprm*e**3/(u_p*r_p)),(gamma,betaprm*r_p*sqrt(e/u_p))])
fP
```

```python
fhelp = nsimplify((1/2)*rtheta*thetaprm**2+(1/4)*gammaprm*thetaprm**4+(1/6)*rhoprm*thetaprm**6+(1/2)*Pprm**2+(1/4)*Pprm**4
        +(1/6)*sigmaprm*Pprm**6-betaprm*thetaprm*Pprm-(1/2)*Pprm**2*thetaprm**2-Eprm*Pprm)
fhelp
```

```python
Ep = solve(fhelp.diff(Pprm),Eprm)[0]
Ep
```

```python
fhelp.diff(thetaprm)
```

```python
P_min = solve(fhelp.diff(thetaprm),Pprm)[0]
P_min
```

```python
Ep = Ep.subs(Pprm,P_min)
Ep
```

```python
series(Ep,thetaprm,n=7)
```

```python
# Series expansion of $E$ out to $\mathcal{O(\theta^{\prime 7})}$:

# $\beta E = \theta^{\prime}\left(-\beta^{\prime 2} + r_{\theta}^{\prime}\right) + \theta^{\prime 3}\left(\gamma^{\prime} - r_{\theta}^{\prime} + \dfrac{r_{\theta}^{\prime 3}}{\beta^{\prime 2}} - \dfrac{r_{\theta}^{\prime 2}}{\beta^{\prime 2}}\right) + \theta^{\prime 5}\left(-\gamma^{\prime} + \rho^{\prime} + \dfrac{3\gamma^{\prime}r_{\theta}^{\prime 2}}{\beta^{\prime 2}} - \dfrac{2\gamma^{\prime}r_{\theta}}{\beta^{\prime 2}} + \dfrac{r_{\theta}^{\prime 2}}{\beta^{\prime 2}} - \dfrac{3r_{\theta}^{\prime 4}}{\beta^{\prime 4}} + \dfrac{2r_{\theta}^{\prime 3}}{\beta^{\prime 4}}\right)$

# The coefficients of $E$ i.t.o. $a$ where $r_{\theta}^{\prime} = \beta^{\prime 2} + a$:

# $B(a) = \dfrac{a^{3}}{\beta^{\prime 2}} + a^{2}\left(3 - \dfrac{1}{\beta^{\prime 2}}\right) + a(3\beta^{\prime 2} - 3) + \beta^{\prime 4} - 2\beta^{\prime 2} + \gamma^{\prime}$

# $C(a) = -\dfrac{3a^{4}}{\beta^{\prime 4}} + a^{3}\left(\dfrac{2}{\beta^{\prime 4}} - \dfrac{12}{\beta^{\prime 2}}\right) + a^{2}\left(\dfrac{3\gamma^{\prime}}{\beta^{\prime 2}} - 18 + \dfrac{7}{\beta^{\prime 2}}\right) + a\left(6\gamma^{\prime} - 12\beta^{\prime 2} - \dfrac{2\gamma^{\prime}}{\beta^{\prime 2}} + 8\right) - 3\beta^{\prime 4} + 3\beta^{\prime 2}\gamma^{\prime} + 3\beta^{\prime 2} - 3\gamma^{\prime} + \rho^{\prime}$

# $R(a) = B(a)^{2} - \dfrac{20aC(a)}{9}$ (not going to write this one out, it's long)
```

```python
rth = betaprm**2+a*betaprm

B = (gammaprm-rtheta+(rtheta**3-rtheta**2)/betaprm**2)/betaprm

C = (-gammaprm+rhoprm+3*gammaprm*(rtheta/betaprm)**2-2*gammaprm*rtheta/betaprm**2
     +(rtheta/betaprm)**2+rtheta**5*sigmaprm/betaprm**4-3*(rtheta/betaprm)**4+2*rtheta**3/betaprm**4)/betaprm
```

```python
B = collect(expand(B.subs(rtheta,rth)),a)
B
```

```python
C = collect(expand(C.subs(rtheta,rth)),a)
C
```

```python
b0 = betaprm**3-2*betaprm+gammaprm/betaprm
b1 = 3*betaprm**2-3
b2 = 3*betaprm-1/betaprm
b3 = 1

c0 = betaprm**5*sigmaprm-3*betaprm**3+3*betaprm*gammaprm+3*betaprm-3*gammaprm/betaprm+rhoprm/betaprm
c1 = 5*betaprm**4*sigmaprm+6*gammaprm-12*betaprm**2+8-2*gammaprm/betaprm**2
c2 = 10*betaprm**3*sigmaprm+(3*gammaprm+7)/betaprm-18*betaprm
c3 = 10*betaprm**2*sigmaprm-12+2/betaprm**2
c4 = 5*betaprm*sigmaprm-3/betaprm
c5 = sigmaprm
```

```python
gammap = expand(solve(b0-b_0,gammaprm)[0])
sigmap = expand(solve(c0-c_0,sigmaprm)[0])
```

```python
replacements = [(gammaprm,gammap),(sigmaprm,sigmap)]
```

```python
sigmap = simplify(sigmap.subs(gammaprm,gammap))
```

```python
sigmap
```

```python
gammap
```

```python
b0
```

```python
b1
```

```python
b2
```

```python
b3
```

```python
B_a = b3*a**3+b2*a**2+b1*a+b_0
B_a
```

```python
# c0 = c0.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
c0
```

```python
c1 = c1.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
expand(c1)
```

```python
c2 = c2.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
expand(c2)
```

```python
c3 = c3.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
expand(c3)
```

```python
c4 = c4.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
expand(c4)
```

```python
c5 = c5.subs(sigmaprm,sigmap).subs(gammaprm,gammap)
c5
```

```python
C_a = c5*a**5+c4*a**4+c3*a**3+c2*a**2+c1*a+c_0
collect(expand(C_a),a)
```

```python
series(B_a**2-20*a*C_a/9,a,n=7)
```

```python
series(B**2-20*a*C/9,a,n=7)
```

```python
Etrun = a*thetaprm+b*thetaprm**3+c*thetaprm**5
Etrun
```

```python
collect(Etrun.subs([(b,B),(c,C)]),thetaprm)
```

```python
theta_L = solve(Etrun.diff(thetaprm),thetaprm)[1]
theta_U = solve(Etrun.diff(thetaprm),thetaprm)[3]
theta_L,theta_U
```

```python
E_L = simplify(Etrun.subs(thetaprm,theta_U))
E_U = simplify(Etrun.subs(thetaprm,theta_L))
E_L,E_U
```

```python

```