{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Learning Seattle's Work Habits from Bicycle Counts (Updated!)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*This notebook originally appeared as a [post](http://jakevdp.github.io/blog/2015/07/23/learning-seattles-work-habits-from-bicycle-counts/) on the blog [Pythonic Perambulations](http://jakevdp.github.io). The content is BSD licensed.*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "*Update, July 25, 2015: I included some new plots suggested by my colleague Ariel Rokem. Scroll to the end!*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<!-- PELICAN_BEGIN_SUMMARY -->\n",
    "\n",
    "Last year I wrote a [blog post](https://jakevdp.github.io/blog/2014/06/10/is-seattle-really-seeing-an-uptick-in-cycling/) examining trends in Seattle bicycling and how they relate to weather, daylight, day of the week, and other factors.\n",
    "\n",
    "Here I want to revisit the same data from a different perspective: rather than making assumptions in order to build models that might describe the data, I'll instead wipe the slate clean and ask what information we can extract from the data themselves, without reliance on any model assumptions.\n",
    "In other words, where the previous post examined the data using a *supervised machine learning* approach for *data modeling*, this post will examine the data using an *unsupervised learning approach* for *data exploration*.\n",
    "\n",
    "Along the way, we'll see some examples of importing, transforming, visualizing, and analyzing data in the Python language, using mostly [Pandas](http://pandas.pydata.org/), [Matplotlib](http://matplotlib.org/), and [Scikit-learn](http://scikit-learn.org/).\n",
    "We will also see some real-world examples of the use of unsupervised machine learning algorithms, such as Principal Component Analysis and Gaussian Mixture Models, in exploring and extracting meaning from data.\n",
    "\n",
    "To spoil the punchline (and perhaps whet your appetite) what we will find is that from analysis of bicycle counts alone, we can make some definite statements about the aggregate work habits of Seattleites who commute by bicycle.\n",
    "\n",
    "<!-- PELICAN_END_SUMMARY -->"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Data\n",
    "\n",
    "The data we will use here are the hourly bicycle counts on Seattle's [Fremont Bridge](http://www.openstreetmap.org/#map=17/47.64813/-122.34965).\n",
    "These data come from an [automated bicycle counter](http://www.seattle.gov/transportation/bikecounter_fremont.htm), installed in late 2012, which has inductive sensors under the sidewalks on either side of the bridge.\n",
    "The daily or hourly bicycle counts can be downloaded from [http://data.seattle.gov/](http://data.seattle.gov/); here is the [direct link to the hourly dataset](https://data.seattle.gov/Transportation/Fremont-Bridge-Hourly-Bicycle-Counts-by-Month-Octo/65db-xm6k).\n",
    "To download the data directly, you can uncomment the following ``curl`` command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# !curl -o FremontBridge.csv https://data.seattle.gov/api/views/65db-xm6k/rows.csv?accessType=DOWNLOAD"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Once this is downloaded, we can use the [pandas](http://pandas.pydata.org) library to load the data:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Fremont Bridge West Sidewalk</th>\n",
       "      <th>Fremont Bridge East Sidewalk</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2012-10-03 00:00:00</th>\n",
       "      <td>4</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 01:00:00</th>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 02:00:00</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 03:00:00</th>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 04:00:00</th>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     Fremont Bridge West Sidewalk  \\\n",
       "Date                                                \n",
       "2012-10-03 00:00:00                             4   \n",
       "2012-10-03 01:00:00                             4   \n",
       "2012-10-03 02:00:00                             1   \n",
       "2012-10-03 03:00:00                             2   \n",
       "2012-10-03 04:00:00                             6   \n",
       "\n",
       "                     Fremont Bridge East Sidewalk  \n",
       "Date                                               \n",
       "2012-10-03 00:00:00                             9  \n",
       "2012-10-03 01:00:00                             6  \n",
       "2012-10-03 02:00:00                             1  \n",
       "2012-10-03 03:00:00                             3  \n",
       "2012-10-03 04:00:00                             1  "
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import pandas as pd\n",
    "data = pd.read_csv('../DATA/FremontBridge.csv', index_col='Date', parse_dates=True)\n",
    "data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We'll do some quick data cleaning: we'll rename the columns to the shorter \"West\" and \"East\", set any missing values to zero, and add a \"Total\" column:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>West</th>\n",
       "      <th>East</th>\n",
       "      <th>Total</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>Date</th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2012-10-03 00:00:00</th>\n",
       "      <td>4</td>\n",
       "      <td>9</td>\n",
       "      <td>13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 01:00:00</th>\n",
       "      <td>4</td>\n",
       "      <td>6</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 02:00:00</th>\n",
       "      <td>1</td>\n",
       "      <td>1</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 03:00:00</th>\n",
       "      <td>2</td>\n",
       "      <td>3</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2012-10-03 04:00:00</th>\n",
       "      <td>6</td>\n",
       "      <td>1</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                     West  East  Total\n",
       "Date                                  \n",
       "2012-10-03 00:00:00     4     9     13\n",
       "2012-10-03 01:00:00     4     6     10\n",
       "2012-10-03 02:00:00     1     1      2\n",
       "2012-10-03 03:00:00     2     3      5\n",
       "2012-10-03 04:00:00     6     1      7"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.columns = ['West', 'East']\n",
    "data.fillna(0, inplace=True)\n",
    "data['Total'] = data.eval('East + West')\n",
    "data.head()  # JMS"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can get a better idea of the dataset as a whole through a simple visualization; for example, we can resample the data to see the weekly trend in trips over the nearly three-year period:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "ename": "ImportError",
     "evalue": "No module named 'seaborn'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mImportError\u001b[0m                               Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-4-c89c8bfddabf>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[1;32m      2\u001b[0m \u001b[0mget_ipython\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmagic\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'matplotlib inline'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      3\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmatplotlib\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpyplot\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mplt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0;32mimport\u001b[0m \u001b[0mseaborn\u001b[0m\u001b[0;34m;\u001b[0m \u001b[0mseaborn\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mset\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m  \u001b[0;31m# plot styling\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      5\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mnumpy\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      6\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mImportError\u001b[0m: No module named 'seaborn'"
     ]
    }
   ],
   "source": [
    "# first some standard imports\n",
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn; seaborn.set()  # plot styling\n",
    "import numpy as np\n",
    "\n",
    "data.resample('W', how='sum').plot()\n",
    "plt.ylabel('weekly trips');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The counts show both a strong seasonal variation, as well as a local structure that can be [partially accounted for](https://jakevdp.github.io/blog/2014/06/10/is-seattle-really-seeing-an-uptick-in-cycling/) by temperature, time of year, precipitation, and other factors."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": false
   },
   "source": [
    "## Extracting Knowledge from the Data\n",
    "\n",
    "From here, we could do a variety of other visualizations based on our intuition about what might affect bicycle counts.\n",
    "For example, we could look at the effect of the days of the week, the effect of the weather, and other factors [that I explored previously](https://jakevdp.github.io/blog/2014/06/10/is-seattle-really-seeing-an-uptick-in-cycling/).\n",
    "But we could also proceed by letting the dataset speak for itself, and use *unsupervised machine learning* techniques (that is, machine learning without reference to data labels) to learn what the data have to tell us.\n",
    "\n",
    "We will consider each day in the dataset as its own separate entity (or *sample*, in usual machine learning parlance).\n",
    "For each day, we have 48 observations: two observations (east and west sidewalk sensors) for each of the 24 hour-long periods.\n",
    "By examining the days in light of these observations and doing some careful analysis, we should be able to extract meaningful quantitative statements from the data themselves, without the need to lean on any other assumptions."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Transforming the Data\n",
    "\n",
    "The first step in this approach is to transform our data; essentially we will want a two-dimensional matrix, where each row of the matrix corresponds to a day, and each column of the matrix corresponds to one of the 48 observations.\n",
    "We can arrange the data this way using the ``pivot_table()`` function in Pandas.\n",
    "We want the \"East\" and \"West\" column values, indexed by date, and separated by hour of the day.\n",
    "Any missing values we will fill with zero:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "pivoted = data.pivot_table(['East', 'West'],\n",
    "                           index=data.index.date,\n",
    "                           columns=data.index.hour,\n",
    "                           fill_value=0)\n",
    "pivoted.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next we extract the raw values and put them in a matrix:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "X = pivoted.values\n",
    "X.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Our data consists of just over 1000 days, each with the aforementioned 48 measurements."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Visualizing the Data\n",
    "\n",
    "We can think of this data now as representing 1001 distinct objects which live in a *48-dimensional* space: the value of each dimension is the number of bicycle trips measured on a particular side of the bridge at a particular hour.\n",
    "Visualizing 48-dimensional data is quite difficult, so instead we will use a standard *dimensionality reduction* technique to project this to a more manageable size.\n",
    "\n",
    "The technique we'll use is [Principal Component Analysis (PCA)](http://scikit-learn.org/stable/modules/decomposition.html), a fast linear projection which rotates the data such that the projection preserves the maximum variance.\n",
    "We can ask for components preserving 90% of the variance as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "Xpca = PCA(0.9).fit_transform(X)\n",
    "Xpca.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The output has two dimensions, which means that these two projected components describe at least 90% of the total variance in the dataset.\n",
    "While 48-dimensional data is difficult to plot, we certainly know how to plot two-dimensional data: we'll do a simple scatter plot, and for reference we'll color each point according to the total number of trips taken that day:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "total_trips = X.sum(1)\n",
    "plt.scatter(Xpca[:, 0], Xpca[:, 1], c=total_trips,\n",
    "            cmap='cubehelix')\n",
    "plt.colorbar(label='total trips');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that the days lie in two quite distinct groups, and that the total number of trips increases along the length of each projected cluster.\n",
    "Further, the two groups begin to be less distinguishable when the number of trips during the day is very small.\n",
    "\n",
    "I find this extremely interesting: from the raw data, we can determine that there are basically *two primary types of days* for Seattle bicyclists.\n",
    "Let's model these clusters and try to figure out what these types-of-day are."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Unsupervised Clustering\n",
    "\n",
    "When you have groups of data you'd like to automatically separate, but no previously-determined labels for the groups, the type of algorithm you are looking at is a *clustering* algorithm.\n",
    "There are a number of clustering algorithms out there, but for nicely-defined oval-shaped blobs like we see above, [Gaussian Mixture Models](http://scikit-learn.org/stable/modules/mixture.html) are a very good choice.\n",
    "We can compute the Gaussian Mixture Model of the data using, again, scikit-learn, and quickly plot the predicted labels for the points:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from sklearn.mixture import GMM\n",
    "gmm = GMM(2, covariance_type='full', random_state=0)\n",
    "gmm.fit(Xpca)\n",
    "cluster_label = gmm.predict(Xpca)\n",
    "plt.scatter(Xpca[:, 0], Xpca[:, 1], c=cluster_label);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This clustering seems to have done the job, and separated the two groups we are interested in.\n",
    "Let's join these inferred cluster labels to the initial dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "pivoted['Cluster'] = cluster_label\n",
    "data = data.join(pivoted['Cluster'], on=data.index.date)\n",
    "data.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we can find the average trend by cluster and time using a GroupBy within this updated dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "by_hour = data.groupby(['Cluster', data.index.time]).mean()\n",
    "by_hour.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we can plot the average hourly trend among the days within each cluster:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(1, 2, figsize=(14, 5))\n",
    "hourly_ticks = 4 * 60 * 60 * np.arange(6)\n",
    "\n",
    "for i in range(2):\n",
    "    by_hour.ix[i].plot(ax=ax[i], xticks=hourly_ticks)\n",
    "    ax[i].set_title('Cluster {0}'.format(i))\n",
    "    ax[i].set_ylabel('average hourly trips')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These plots give us some insight into the interpretation of the two clusters: the first cluster shows a sharp bimodal traffic pattern, while the second shows a wide unimodal pattern.\n",
    "\n",
    "In the bimodal cluster, we see a peak around 8:00am which is dominated by cyclists on the west sidewalk, and another peak around 5:00pm which is dominated by cyclists on the east sidewalk.\n",
    "This is very clearly a commute pattern, with the majority of cyclists riding toward downtown Seattle in the morning, and away from downtown Seattle in the evening.\n",
    "\n",
    "In the unimodal cluster, we see fairly steady traffic in each direction beginning early in the morning and going until late at night, with a peak around 2:00 in the afternoon.\n",
    "This is very clearly a recreational pattern of use, with people out riding through the entire day.\n",
    "\n",
    "I find this is fascinating: from simple unsupervised dimensionality reduction and clustering, we've discovered two distinct classes of days in the data, and found that these classes have very intuitive explanations."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Seattle's Work Habits\n",
    "\n",
    "Let's go one step deeper and figure out what we can learn about people (well, bicycle commuters) in Seattle from just this hourly commute data.\n",
    "As a rough approximation, you might guess that these two classes of data might be largely reflective of workdays in the first cluster, and non-work days in the second.\n",
    "We can check this intuition by re-plotting our projected data, except labeling them by day of the week:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "dayofweek = pd.to_datetime(pivoted.index).dayofweek\n",
    "plt.scatter(Xpca[:, 0], Xpca[:, 1], c=dayofweek,\n",
    "            cmap=plt.cm.get_cmap('jet', 7))\n",
    "cb = plt.colorbar(ticks=range(7))\n",
    "cb.set_ticklabels(['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'])\n",
    "plt.clim(-0.5, 6.5);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We see that the weekday/weekend intuition holds, but only to a point: in particular, it is clear that **there are a handful of weekdays which follow the typical weekend pattern!**\n",
    "Further, it's interesting to note that Fridays tend to be pulled closer to weekend days in this plot, though as a whole they still fall solidly in the work-day cluster.\n",
    "\n",
    "Let's take a closer look at the \"special\" weekdays that fall in the \"wrong\" cluster.\n",
    "We start by constructing a dataset listing the cluster id and the day of the week for each of the dates in our dataset:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "results = pd.DataFrame({'cluster': cluster_label,\n",
    "                        'is_weekend': (dayofweek > 4),\n",
    "                        'weekday': pivoted.index.map(lambda x: x.strftime('%a'))},\n",
    "                       index=pivoted.index)\n",
    "results.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, let's see how many weekend days fall in the first, commute-oriented cluster"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "weekend_workdays = results.query('cluster == 0 and is_weekend')\n",
    "len(weekend_workdays)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "zero! Apparently, there is not a single weekend during the year where Seattle cyclists as a whole decide to go to work.\n",
    "\n",
    "Similarly, we can see how many weekdays fall in the second, recreation-oriented cluster:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "midweek_holidays = results.query('cluster == 1 and not is_weekend')\n",
    "len(midweek_holidays)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There were 23 weekdays over the past several years in which Seattle cyclists as a whole did not go to work.\n",
    "To label these, let's load the US Federal holiday calendar available in Pandas:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from pandas.tseries.holiday import USFederalHolidayCalendar\n",
    "cal = USFederalHolidayCalendar()\n",
    "holidays = cal.holidays('2012', '2016', return_name=True)\n",
    "holidays.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just for completeness, we will add to the list the day before and day after each of these holidays:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "holidays_all = pd.concat([holidays,\n",
    "                         \"Day Before \" + holidays.shift(-1, 'D'),\n",
    "                         \"Day After \" + holidays.shift(1, 'D')])\n",
    "holidays_all = holidays_all.sort_index()\n",
    "holidays_all.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that these are *observed* holidays, which is why New Years Day 2012 falls on January 2nd.\n",
    "With this ready to go, we can compute the complete list of non-weekend days on which Seattle bicycle commuters as a whole chose to stay home from work:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "holidays_all.name = 'name'  # required for join\n",
    "joined = midweek_holidays.join(holidays_all)\n",
    "set(joined['name'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "On the other side of things, here are the Federally recognized holidays where Seattle bicycle commuters chose to go to work anyway:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "set(holidays) - set(joined.name)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Update: What's up with Fridays?\n",
    "\n",
    "A colleague of mine, Ariel Rokem, saw the first version of this post and noticed something interesting.\n",
    "For the most part, Fridays tend to lie on the upper side of the weekday cluster, closer in this parameter space to the typical weekend pattern.\n",
    "This pattern holds nearly universally for Fridays, all except for three strange outliers which lie far on the other side of the cluster.\n",
    "\n",
    "We can see these more clearly if we highlight the Friday points in the plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "fridays = (dayofweek == 4)\n",
    "plt.scatter(Xpca[:, 0], Xpca[:, 1], c='gray', alpha=0.2)\n",
    "plt.scatter(Xpca[fridays, 0], Xpca[fridays, 1], c='yellow');"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The yellow points in the bottom-left of the plot are unique – they're far different than other Fridays, and they even stand-out in comparison to the other work days!\n",
    "Let's see what they represent:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "weird_fridays = pivoted.index[fridays & (Xpca[:, 0] < -600)]\n",
    "weird_fridays"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "All three of these outlying Fridays fall in the middle of May. Curious!\n",
    "\n",
    "Let's quickly visualize the daily stats for these, along with the mean trend over all days.\n",
    "We can arrange the data this way with a pivot table operation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "all_days = data.pivot_table('Total', index=data.index.time, columns=data.index.date)\n",
    "print all_days.head()\n",
    "print weird_fridays\n",
    "all_days[:, weird_fridays].plot();\n",
    "#all_days.mean(1).plot(color='gray', lw=5, alpha=0.3,\n",
    "#                      xticks=hourly_ticks);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Apparently these three strange Fridays are days with *extreme amounts of bicycle commuting*.\n",
    "But what makes them so special?\n",
    "\n",
    "After some poking-around on the internet, the answer becomes clear: we've discovered Seattle's annual [bike to work day](http://www.cascade.org/f5-bike-work-day).\n",
    "Mystery solved!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Summary\n",
    "\n",
    "We have seen here that by taking a close look at raw bicycle counts and using some basic visualization and unsupervised machine learning, we can make some very definite statements about the overall work habits of people in Seattle who bicycle to work across the Fremont bridge.\n",
    "In summary, this is what we have learned:\n",
    "\n",
    "- Seattle cyclists, as a whole, tend to take off work New Year's Day, Memorial Day, Independence Day, Labor Day, and the days surrounding Thanksgiving and Christmas.\n",
    "- Seattle cyclists, as a whole, tend to head to the office on the more minor US holidays: Columbus Day, Martin Luther King Jr. Day, Presidents Day, and Veterans Day.\n",
    "- Seattle cyclists, as a whole, would never, ever, be caught at work on a weekend.\n",
    "\n",
    "Thanks for reading!\n",
    "\n",
    "<small>\n",
    "This post was written entirely in the IPython notebook.  You can\n",
    "[download](http://jakevdp.github.io/downloads/notebooks/SeattleCycling2.ipynb)\n",
    "this notebook, or see a static view\n",
    "[here](http://nbviewer.ipython.org/url/jakevdp.github.io/downloads/notebooks/SeattleCycling2.ipynb).\n",
    "</small>"
   ]
  }
 ],
 "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
}
