{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import dautil as dl\n",
    "from scipy.fftpack import dct\n",
    "import matplotlib.pyplot as plt\n",
    "import ch6util\n",
    "import seaborn as sns\n",
    "import numpy as np\n",
    "from IPython.display import HTML"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('analyzing_dct')\n",
    "lr = dl.nb.LatexRenderer(chapter=6, start=10, context=context)\n",
    "lr.render(r'm = 1127 \\log\\left(1 + \\frac{f}{700}\\right)')\n",
    "lr.render(r'X_k = \\sum_{n=0}^{N-1} x_n \\cos \\left[\\frac{\\pi}{N} \\left(n+\\frac{1}{2}\\right) k \\right] \\quad \\quad k = 0, \\dots, N-1')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "rate, audio = ch6util.read_wav()\n",
    "transformed = dct(audio)"
   ]
  },
  {
   "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",
    "freqs = np.fft.fftfreq(audio.size, 1./rate)\n",
    "indices = np.where(freqs > 0)[0]\n",
    "sp.ax.semilogy(np.abs(transformed)[indices])\n",
    "sp.label()\n",
    "\n",
    "sns.distplot(np.log(np.abs(transformed)), ax=sp.next_ax())\n",
    "sp.label()\n",
    "\n",
    "sns.distplot(np.angle(transformed), ax=sp.next_ax())\n",
    "sp.label()\n",
    "\n",
    "magnitude = ch6util.amplitude(audio)\n",
    "cepstrum = dl.ts.power(np.fft.ifft(np.log(magnitude ** 2)))\n",
    "mel = 1127 * np.log(1 + freqs[indices]/700)\n",
    "sp.next_ax().plot(mel, ch6util.amplitude(dct(np.log(magnitude[indices] ** 2))))\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
}
