{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from scipy.spatial.distance import pdist\n",
    "from scipy.cluster.hierarchy import linkage\n",
    "from scipy.cluster.hierarchy import dendrogram\n",
    "import dautil as dl\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "context = dl.nb.Context('clustering_hierarchy')\n",
    "lr = dl.nb.LatexRenderer(chapter=9, start=2, context=context)\n",
    "lr.render(r'\\|a-b \\|_2 = \\sqrt{\\sum_i (a_i-b_i)^2}')\n",
    "lr.render(r'\\min \\, \\{\\, d(a,b) : a \\in A,\\, b \\in B \\,\\}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "df = dl.data.Weather.load().resample('A').dropna()\n",
    "dist = pdist(df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "context = dl.nb.Context('clustering_hierarchy')\n",
    "dl.nb.RcWidget(context)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dendrogram(linkage(dist), labels=[d.year for d in df.index],\n",
    "           orientation='right')\n",
    "plt.tick_params(labelsize=8)\n",
    "plt.xlabel('Cluster')\n",
    "plt.ylabel('Year')"
   ]
  },
  {
   "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
}
