{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from scipy import signal\n",
    "import matplotlib.pyplot as plt\n",
    "import dautil as dl\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fs = 365\n",
    "rain = dl.data.Weather.load()['RAIN'].dropna()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('periodograms')\n",
    "lr = dl.nb.LatexRenderer(chapter=6, context=context)\n",
    "lr.render(r'S(f)=\\frac{\\Delta t}{N} \\left| \\sum_{n=0}^{N-1} x_n e^{-i2\\pi n f} \\right|^2, \\qquad -\\frac{1}{2\\Delta t} < f \\le \\frac{1}{2\\Delta t}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def plot_periodogram(arr, ax):\n",
    "    f, Pxx_den = signal.periodogram(arr, fs)\n",
    "    ax.set_xlabel('Frequency (Hz)')\n",
    "    ax.set_ylabel('PSD')\n",
    "    ax.semilogy(f, Pxx_den)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "dl.options.mimic_seaborn()\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.label()\n",
    "plot_periodogram(rain, sp.ax)\n",
    "sp.label(advance=True)\n",
    "plot_periodogram(np.diff(rain, 2), sp.ax)\n",
    "sp.label(advance=True)\n",
    "plot_periodogram(pd.rolling_sum(rain, fs).dropna(), sp.ax)\n",
    "sp.label(advance=True)\n",
    "plot_periodogram(pd.rolling_mean(rain, fs).dropna(), sp.ax)\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
}
