{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from statsmodels import datasets\n",
    "import matplotlib.pyplot as plt\n",
    "import pywt\n",
    "import pandas as pd\n",
    "import dautil as dl\n",
    "import numpy as np\n",
    "import seaborn as sns\n",
    "import warnings\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "warnings.filterwarnings(action='ignore',\n",
    "                        message='.*Mean of empty slice.*')\n",
    "warnings.filterwarnings(action='ignore',\n",
    "                        message='.*Degrees of freedom <= 0 for slice.*')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('discrete_wavelet')\n",
    "lr = dl.nb.LatexRenderer(chapter=6, start=12, context=context)\n",
    "lr.render(r'Y_t=X_{t}-m \\text{  for } t=1,2, \\dots ,n')\n",
    "lr.render(r'Z_t= \\sum_{i=1}^{t} Y_{i}  \\text{  for }  t=1,2, \\dots ,n')\n",
    "lr.render(r'R_t = \\max\\left (Z_1, Z_2, \\dots, Z_t  \\right )- \\min\\left (Z_1, Z_2, \\dots, Z_t  \\right ) \\text{  for } t=1,2, \\dots, n')\n",
    "lr.render(r'S_{t}= \\sqrt{\\frac{1}{t} \\sum_{i=1}^{t}\\left ( X_{i} - m(t) \\right )^{2}}  \\text{  for } t=1,2, \\dots ,n')\n",
    "lr.render(r'\\left ( R/S \\right )_{t} = \\frac{R_{t}}{S_{t}} \\text{  for } t=1,2, \\dots, n')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def calc_rescaled_range(X):\n",
    "    N = len(X)\n",
    "\n",
    "    # 1. Mean\n",
    "    mean = X.mean()\n",
    "\n",
    "    # 2. Y mean adjusted\n",
    "    Y = X - mean\n",
    "\n",
    "    # 3. Z cumulative deviates\n",
    "    Z = np.array([Y[:i].sum() for i in range(N)])\n",
    "\n",
    "    # 4. Range R\n",
    "    R = np.array([0] + [np.ptp(Z[:i]) for i in range(1, N)])\n",
    "\n",
    "    # 5. Standard deviation S\n",
    "    S = np.array([X[:i].std() for i in range(N)])\n",
    "\n",
    "    # 6. Average partial R/S\n",
    "    return [np.nanmean(R[:i]/S[:i]) for i in range(N)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "data = datasets.get_rdataset('Nile', cache=True).data\n",
    "cA, cD = pywt.dwt(data['Nile'].values, 'haar')\n",
    "coeff = pd.DataFrame({'cA': cA, 'cD': cD})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.nb.RcWidget(context)\n",
    "dl.nb.LabelWidget(2, 2, context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "sp = dl.plotting.Subplotter(2, 2, context)\n",
    "sp.ax.plot(data['time'], data['Nile'])\n",
    "sp.label()\n",
    "\n",
    "cp = dl.plotting.CyclePlotter(sp.next_ax())\n",
    "cp.plot(range(len(cA)), cA, label='Approximation coefficients')\n",
    "cp.plot(range(len(cD)), cD, label='Detail coefficients')\n",
    "sp.label()\n",
    "\n",
    "sp.next_ax().loglog(range(len(cA)), calc_rescaled_range(cA), \n",
    "                    label='Approximation coefficients')\n",
    "sp.ax.loglog(range(len(cD)), calc_rescaled_range(cD), \n",
    "             label='Detail coefficients')\n",
    "sp.label()\n",
    "\n",
    "range_df = pd.DataFrame(data={'Year': data.index,\n",
    "                              'Rescaled range':\n",
    "                              calc_rescaled_range(data['Nile'])})\n",
    "sp.next_ax().set(xscale=\"log\", yscale=\"log\")\n",
    "sns.regplot('Year', 'Rescaled range', range_df, ax=sp.ax, order=1,\n",
    "            scatter_kws={\"s\": 100})\n",
    "sp.label()\n",
    "HTML(sp.exit())"
   ]
  },
  {
   "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
}
