{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from scipy.stats.distributions import poisson\n",
    "import matplotlib.pyplot as plt\n",
    "import dautil as dl\n",
    "from scipy.optimize import minimize\n",
    "from IPython.html.widgets.interaction import interactive\n",
    "from IPython.core.display import display\n",
    "from IPython.core.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "lr = dl.nb.LatexRenderer(chapter=3, start=5)\n",
    "lr.render(r'\\!f(k; \\lambda)= \\Pr(X{=}k)= \\frac{\\lambda^k e^{-\\lambda}}{k!}')\n",
    "lr.render(r'\\lambda=\\operatorname{E}(X)=\\operatorname{Var}(X)')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def log_likelihood(k, mu):\n",
    "    return poisson.logpmf(k, mu).sum()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def count_rain_days(month):\n",
    "    rain = dl.data.Weather.load()['RAIN']\n",
    "    rain = (rain > 0).resample('M', how='sum')\n",
    "    rain = dl.ts.groupby_month(rain)\n",
    "    rain = rain.get_group(month)\n",
    "    \n",
    "    return rain"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def plot(rain, dist, params, month):\n",
    "    fig, ax = plt.subplots()\n",
    "    plt.title('Fitting to the Poisson distribution ({})'.format(dl.ts.short_month(month)))\n",
    "\n",
    "    # Limiting the x-asis for a better plot\n",
    "    plt.xlim([0, 15])\n",
    "    plt.figtext(0.5, 0.7, 'rate {:.3f}'.format(params.x[0]), alpha=0.7,\n",
    "                fontsize=14)\n",
    "    plt.xlabel('# Rainy days in a month')\n",
    "    plt.ylabel('Probability')\n",
    "    ax.hist(dist.train, bins=dist.nbins, normed=True, label='Data')\n",
    "    ax.plot(dist.x, poisson.pmf(dist.x, params.x))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def fit_poisson(month):\n",
    "    month_index = dl.ts.month_index(month)\n",
    "    rain = count_rain_days(month_index)\n",
    "    \n",
    "    dist = dl.stats.Distribution(rain, poisson, range=[-0.5, 19.5])\n",
    "    params = minimize(log_likelihood, x0=rain.mean(), args=(rain,))\n",
    "    plot(rain, dist, params, month_index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\n",
    "context = dl.nb.Context('fitting_poisson')\n",
    "dl.nb.RcWidget(context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "display(interactive(fit_poisson, month=dl.nb.create_month_widget(month='May')))\n",
    "HTML(dl.report.HTMLBuilder().watermark())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.4.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
