<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[BusWatching - Medium]]></title>
        <description><![CDATA[Bus Watching covers ongoing work at Cornell Tech’s Urban Tech Hub to develop tools for tracking, analyzing, modeling and visualizing bus transit systems all over the world. - Medium]]></description>
        <link>https://medium.com/bus-watching?source=rss----47bb28ebbc---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>BusWatching - Medium</title>
            <link>https://medium.com/bus-watching?source=rss----47bb28ebbc---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 00:40:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/bus-watching" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Announcing the Bus Observatory API]]></title>
            <link>https://medium.com/bus-watching/announcing-the-bus-observatory-api-71f3e2df090d?source=rss----47bb28ebbc---4</link>
            <guid isPermaLink="false">https://medium.com/p/71f3e2df090d</guid>
            <category><![CDATA[transit]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[urban-planning]]></category>
            <dc:creator><![CDATA[Anthony Townsend]]></dc:creator>
            <pubDate>Fri, 12 Aug 2022 00:45:21 GMT</pubDate>
            <atom:updated>2022-09-05T18:48:53.707Z</atom:updated>
            <content:encoded><![CDATA[<p>As transit systems recover from the pandemic, buses are leading the way. As <em>Th</em>e <em>Economist</em> <a href="https://www.economist.com/united-states/2022/07/21/american-public-transport-faces-a-post-pandemic-reckoning">reported recently</a>:</p><blockquote>Before the pandemic, bus use had fallen in America for decades, as cars became more affordable for the relatively poorer people who most often travelled by bus. Networks were neglected. By contrast light-rail projects and subway systems thrived, as more white-collar workers commuted to city centres. But since the pandemic they have suffered as those workers have stayed at home, and mostly poorer folk are again filling buses. Bus passenger numbers fell the least among transport systems, and are now closest to pre-pandemic levels. This divergence is creating “existential questions” for public-transport providers…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L1llNBk6c5t9-zxgdkldA.jpeg" /><figcaption>A bus in Nantes, France. (Flickr: <a href="https://www.flickr.com/photos/st3f4n/156630529/in/photolist-eQLNn-M6sro-beHujT-pXQh1h-akVNto-9Ke8kA-6Tyza3-2ABEv-ae2moS-qEdxW-8tmX65-ej5AAZ-4P5hAd-7UGp66-bxJ6o2-C9dJx-8tnakm-4vek7Q-7CUFWN-cwjwpS-wZ5eoo-828m3c-7RZDyc-cNSgzq-6gpYZe-7dW8Zn-4P5hJJ-4Uy2n-beHudR-o77gM-SnyAh7-8Nwhm-53Je6K-5d7MWL-7AdTbM-4bcwWj-8ddCfh-bjPdps-fhtDcQ-SYFVwi-21FWzn7-bm1S9j-8QwzXZ-6g1L4Z-BRSJAu-8NiGqP-kTKZXx-26gJ1-hMiJZE-bJPUEH">DocChewbacca</a>)</figcaption></figure><h3><strong>We think better data about buses can help us better understand how bus systems work. That can help us improve them.</strong></h3><p>That’s why over the last two years, Cornell Tech’s Jacobs Urban Tech Hub has been tooling up to collect and use real-time data from bus systems in the New York region.</p><p>As we explained in a series of posts last year, we <a href="https://medium.com/bus-watching/can-better-data-unlock-a-brighter-future-for-buses-1f1bcea7092d">started scraping real-time data</a> from the New York City Transit and NJTransit bus systems in 2020–1. We <a href="https://medium.com/bus-watching/the-bigness-of-bus-data-a65a276ba2e1">struggled with the technical challenges</a> of collecting, storing, and distributing this big, streaming urban data. Our initial solutions to these challenges enabled some <a href="https://medium.com/bus-watching/from-sensing-to-sensemaking-analyzing-visualizing-and-modeling-new-york-citys-buses-896bb42cf39f">tantalizing student research projects</a> that applied machine learning and web visualization techniques to make sense of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6tJCpI1Wxw19gnqMvUXUg.png" /><figcaption>An 2021 visualization by Cornell Tech student Jamie Geng revealed the “pheromone trails” of urban buses.</figcaption></figure><p>Along the way, our vision and ambitions grew. We wanted to rebuild our data infrastructure to make it more powerful, more cost-effective, and more scalable. The goal was creating a repository of longitudinal data, encompassing multiple geographies, that others could use to help improve our understanding of urban bus systems and improve them. The idea of a <a href="https://medium.com/bus-watching/towards-a-global-bus-observatory-822111845e54">global “bus observatory” was born</a>.</p><p>I’m delighted to announce that this facility, the <a href="https://api.busobservatory.org/">Bus Observatory API</a>, is now available. Feel free to <a href="https://api.busobservatory.org/">jump right in</a>, or continue reading below to learn more about the data and how we’re delivering it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5j8oi-JyTEc7AUlaDWLPXg.png" /><figcaption>The <a href="https://api.busobservatory.org/">Bus Observatory API</a> is now live.</figcaption></figure><h4>The Data</h4><p>Our first data set focuses on New York City Transit MTA Bus services. The <a href="https://api.busobservatory.org/nyct">New York City Transit feed</a> is our flagship data set, tracking bus movements citywide since October 15, 2020. Drawn from the system’s SIRI API, this is a rich feed which includes passenger count data from May 2021 onwards.</p><p>There are 5 ways to get data, which is distributed in batches of a single route’s vehicle movements for a single hour. All of this is discussed in depth in the API <a href="https://api.busobservatory.org/#quickstart">quickstart guide</a>, but here’s a quick summary:</p><ol><li>Download one of several sample data sets, covering a variety of New York City Transit routes and time periods</li><li><a href="https://api.busobservatory.org/docs">Run a query </a>using the Swagger API documentation app.</li><li>Directly query the API using an endpoint. For instance, <a href="https://api.busobservatory.org/buses/bulk/nyct_mta_bus_siri/M1/2022/7/4/21">all of the positions recorded from the New York City MTA Buses SIRI feed between 9pm and 10pm on July 4, 2022</a>.</li><li>Get the data directly from a command line interface with curl, for instance:</li></ol><pre>curl -X &#39;GET&#39; https://api.busobservatory.org/buses/bulk/nyct_mta_bus_siri/M1/2022/7/4/21&#39; -H &#39;accept: application/json&#39;</pre><p>5. Get more data with a script.</p><p>For example, the following Python function takes a system_id, a route, and (start and end time in ISO8501 format) as arguments; generates a list of dates and hours within this interval; retrieves the bulk data for each our from the Bus Observatory API; and combines these responses into a single Pandas dataframe.</p><pre>import pandas as pd<br>import requests</pre><pre>def get_buses(system_id, route, start, end):</pre><pre>    df = pd.DataFrame()</pre><pre>    times = (<br>        pd.date_range(start=pd.Timestamp(start), \<br>            end=pd.Timestamp(end), freq=&quot;1H&quot;)<br>            .to_pydatetime()<br>            .tolist()<br>        )</pre><pre>    for t in times:</pre><pre>        print(t)<br>        url = f&quot;https://api.busobservatory.org/buses/bulk/{system_id}/{route}/{t.year}/{t.month}/{t.day}/{t.hour}&quot;<br>        print(url)<br>        r = requests.get(url).json()<br>        print(r[&quot;query&quot;])<br>        newdata = pd.DataFrame.from_dict(r[&quot;result&quot;])<br>        df = pd.concat([df, newdata], ignore_index=True, sort=False)</pre><pre>    return df</pre><p>Grabbing a whole day’s data for a single route, and writing it to a single parquet file from the results is as simple as:</p><pre>get_buses(<br>    &#39;nyct_mta_bus_siri&#39;, <br>    &#39;M1&#39;, <br>    &#39;2022-07-21T00:00:00&#39;,<br>    &#39;2022-07-22T00:00:00&#39;<br>    ).to_parquet(&#39;buses.parquet&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*2BWJY9rtuJtVl-wE8mzmjA.png" /><figcaption>A typical response from the BusObservatory API re-stating the query and results. Each record indicates and observation of a vehicle position, which are sampled every 60 seconds, 24 hours a day, 365 days a week.</figcaption></figure><h4>Use Cases</h4><p>What is all this data good for?</p><p>Our students <a href="https://medium.com/bus-watching/from-sensing-to-sensemaking-analyzing-visualizing-and-modeling-new-york-citys-buses-896bb42cf39f">explored many of the possibilites in 2021</a>, from mapping tools that let us “play back” historical data of bus movements to machine learning models that can link disruptions on the subway system to spikes in bus crowding nearby.</p><p>But the possibilities for exploration are endless. How do different route designs, street configurations, and signal prioritization technologies impact bus speed, bunching, and crowding? What can we learn from benchmarking detailed metrics <em>across</em> cities? What new measures of service, like travel time reliability can we create (e.g. “this flight is 70% on-time” but for buses)?</p><p>These are interesting enough, but as we mash long-term bus data up with other environmental and infrastructure data sets, even bigger possibilities emerge. How does severe heat and precipitation impact bus ridership? And how does that correlate with the location and quality of bus shelters? We already <a href="https://data.cityofnewyork.us/Transportation/Bus-Stop-Shelters/qafz-7myz">have that data</a>. If we’re looking to buses as a tool for reducing transportation-related emissions, we need to make sure climate change itself isn’t undermining the appeal of this option.</p><h4>How It Works</h4><p>One of the biggest achievements of this project is delivering this service in a simple, scalable, and cost-effective manner. I worried a lot about cost and performance, as well as the amount of time we’d need to spend maintaining this service. Solving all those constraints led me us to modern serverless frameworks to scrape, store, query and serve the data. The key pieces are:</p><p><strong>Serverless functions.</strong> We use AWS Lambda functions to run small Python scripts that fetch data from transit operators’ APIs (Katie Bell’s <a href="https://archive.org/details/lca2018-Is_the_370_the_worst_bus_route_in_Sydney">amazing 2018 talk</a> about tracking buses in Sydney was inspiring here). Some are simple, simply fetching a single endpoint and writing it out to our data lake. Others, like the New York City Transit SIRI feed require a more sophisticated approach to process in the 60-second window we have. (For that we grab all 200+ routes individually with a flurry of asynchronous requests). Lambda is flexible enough to accommodate all these needs, we don’t have to administer any Linux servers, it scales out on its own as demand grows, and the cost is negligible. We even run the API handler and public webserver itself as another Lambda function using the <a href="https://fastapi.tiangolo.com/">FastAPI framework</a>.</p><p><strong>Data lakes. </strong>There’s no database behind the Bus Observatory. Our Lambda functions write out their results to files stored in Amazon’s S3 object storage system, using the Parquet format (think of it like a much more structured kind of CSV). The AWS Lake Formation service provides a ton of housekeeping services, combining these files and “partitioning” them over time to optimize speed and flexibility for data retrieval.</p><p><strong>Serverless query tools.</strong> Every time you make a request to the API, our FastAPI Lambda function is invoked. That function turns your request into an SQL query, which is executed on the data lake using the AWS Athena serverless interactive query service.</p><pre>SELECT * <br>FROM nyct_mta_bus_siri <br>WHERE route = ‘M5’ <br>AND <br>(<br>timestamp &gt;= from_iso8601_timestamp(‘2022–07–07T21:00:00’) <br>AND <br>timestamp &lt; from_iso8601_timestamp(‘2022–07–07T22:00:00’)<br>)</pre><p>One way to think about this is that Athena provides a database-like interface that turns a collection of structured tabular data in parquet files into a relational database. (If you like this idea, check out <a href="https://duckdb.org/">duckdb</a> which will blow your mind. Thx to Arnauld Sahuguet for the tip.) While we do give up a bit of speed using Athena versus a dedicated database, its still fairly snappy, and likely to improve as our LakeFormation optimizes the underlying file structure over time. And not having to maintain a database server saves hundreds of hours of time. The cost is about 1 cent per query. Amazing.</p><p><strong>API gateway service.</strong> Our FastAPI Lambda function sits behind an AWS API Gateway which provides a variety of caching, logging, rate limiting, and other features that mean we don’t have to manage the details and have better performance and more peace of mind.</p><p>Overall, I’m stunned by the simplicity of all of this, even though the serverless ecosystem is still fairly immature (many of these AWS services have only been around for the last 5 years). I’ll likely never deploy any kind of web service using a dedicated server again.</p><p>Check out the GitHub code repositories for the <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/BusObservatory-API">grabber</a> and <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/BusObservatory-API">API</a>.</p><h4>What’s Next?</h4><p>We’ll be inviting a new cohort of urban tech master’s students at Cornell Tech to explore new investigations and use cases for the data.</p><p>We’re also already planning a number of updates and improvements, which include:</p><ul><li>Adding a <a href="https://api.busobservatory.org/nj">NJTransit feed</a> covering bus transit operations throughout an entire state. As of writing, this data set contains more than 320 million minute-to-minute observations capturing all bus movements since April 6, 2021. We’re working on figuring out how to standardize the API interface for interacting with what is a radically different data set.</li><li>Adding a second feed for New York City Transit, based on the system’s more modern, standard GTFS-RT feed. We’ve been scraping this data all summer, and are preparing it for publication in the fall of 2022.</li><li>Adding more cities. Please help us identify interesting transit data feeds via <a href="https://docs.google.com/forms/d/e/1FAIpQLSdrK5JtKSo9cPozkTueqxAfV63dsHIdrDqzekcc-BPw6s590Q/viewform">this suggestion form</a>.</li><li>Backfilling the New York City Transit SIRI data feed. Transit Center, which pioneered similar efforts in 2016, maintains a <a href="https://github.com/Bus-Data-NYC/mta-bus-archive">deep archive of SIRI data stretching back to 2017</a>. We’ve grabbed this and are working on merging it with our data.</li><li>Securing the API. For now, the complexity of deploying and supporting an authentication and authorization scheme was too daunting. That may change if traffic grows too quickly.</li><li>Debugging. Please share any issues you have <a href="https://forms.gle/pmhWFpx5FyRrKS7a7">here</a>.</li></ul><p>If you have any other ideas, enhancements, or questions, please feel free to reach out to <a href="/service/mailto:urbantech@cornell.edu">urbantech@cornell.edu</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f3e2df090d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bus-watching/announcing-the-bus-observatory-api-71f3e2df090d">Announcing the Bus Observatory API</a> was originally published in <a href="https://medium.com/bus-watching">BusWatching</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards A Global Bus Observatory]]></title>
            <link>https://medium.com/bus-watching/towards-a-global-bus-observatory-822111845e54?source=rss----47bb28ebbc---4</link>
            <guid isPermaLink="false">https://medium.com/p/822111845e54</guid>
            <category><![CDATA[new-york-city]]></category>
            <category><![CDATA[urbantech]]></category>
            <category><![CDATA[cornell-tech]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[transit]]></category>
            <dc:creator><![CDATA[Anthony Townsend]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 13:37:06 GMT</pubDate>
            <atom:updated>2022-08-12T13:10:12.851Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth and final post in a series describing ongoing work at Cornell Tech’s Urban Tech Hub with big, streaming data generated by bus transit.</p><p>As you can see from the first three articles in this series, we learned a lot this year. Our <a href="https://medium.com/bus-watching/can-better-data-unlock-a-brighter-future-for-buses-1f1bcea7092d">initial hunch</a> was to start scraping data from the New York City bus system. Like so many exercises in big urban data, this was easy to prototype, but <a href="https://medium.com/bus-watching/the-bigness-of-bus-data-a65a276ba2e1">much harder to sustain and scale</a>. That hunch proved out though, as our students cooked up a variety of <a href="https://medium.com/bus-watching/from-sensing-to-sensemaking-analyzing-visualizing-and-modeling-new-york-citys-buses-896bb42cf39f">amazing tools for analyzing, visualizing, and modeling</a> interesting phenomena with the data.</p><p>But where do we go from here?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69IpNzw9aNtdoFTXHYYfbQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jeremybezanger?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jeremy Bezanger</a> on <a href="https://unsplash.com/s/photos/buses?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As I’ve noted before, we’re not the first or only group to stockpile this data. The <a href="https://github.com/Bus-Data-NYC">Bus Data Working Group</a>, put together to support Transit Center’s Bus Turnaround work in 2015, has tons of tools and a repository of historical data stretching back several years. It’s still being maintained, although there are some gaps in the data, most regrettably during the first six months of the pandemic. James Fennel’s more recent <a href="https://github.com/jamespfennell/hoard"><em>hoard</em></a> package is an amazingly robust tool for building data lakes, and was designed to scrape the New York City subway system. It’s easily adapted for bus data, too, simply by swapping data source feeds. Andrew Dickinson’s <a href="https://github.com/Andrew-Dickinson/nyct-gtfs"><em>nyct-gtfs</em></a> is another package that makes it easy to scrape subway data and can easily be adapted for BusTime feeds too.</p><p>I think what makes our work at Cornell Tech unique and valuable is our focus on the whole stack—data acquisition, warehousing, dissemination, and application. There are five pieces to that stack, which all have big room for improvement:</p><ul><li>The scraper or <strong>grabber</strong> is a set of Python scripts and object models that poll the BusTime SIRI VehicleMonitoring API once per minute, 365 days a year, parse the data, and dump it to disk. Our v1 grabber parsed a few fields from these JSON responses into a mysql table and dropped the rest. The v2 scraper improved on this by making a tarball of the full payload of those API responses (for later reprocessing), and then parsed a similar but expanded set of fields into a cache, which was bundled up every hour into one JSON file per route, for distribution by the API. For the most part, this layer works pretty good. But its hard-coded for New York City’s system, which operates on the rather obscure SIRI standard, and our specific data store implementation. The grabber needs to be refactored so we can add parsers for different kinds of feeds, and be able to push them to a variety of places.</li><li>I was never satisfied with our solution to the<strong> data storage and retrieval layer</strong>. The v1 solution, a mysql process running in a docker container on an Amazon EC2 instance, was labor-intensive and started creating all kinds of performance problems and risks as it grew. The v2 solution, storing all the data in static JSON files was primitive and made it impossible to query. It was optimized for one purpose—shipping bulk data to users. It needs to be replaced by something that can scale, is backed up regularly, and has high-performance query capability.</li><li>We never built the third layer, a <strong>data dashboard</strong>, to tell us what the data store contained. I had to resort to the database shell and SQL queries, or browsing through the file system to take an inventory and look for gaps. This will be a crucial tool we need to build going forward.</li><li>Our <strong>API</strong> solutions were also an exercise in rapid but ultimately unsatisfying prototyping. The first version, coded in Flask, provided lots of flexibility, allowing users to specify a route, a date range (in ISO format), and an output format (json or geojson, with a planned but abandoned hook to generate a table suitable for use in <em>Kepler.gl</em>). But I never did the indexing and query optimization, nor did i provide the needed resources to make it scale. By the time the database hit about 200 million rows (mid-spring, after about 5 months of scraping), it more or less stopped working. The v2 solution, implemented in FastAPI, was limited by the data store. All it really could do was parse a URL for route and date arguments and fetch a static file to return. In that it shined. But students had to write their own loops to iterate over date ranges to get all the data they needed for experiments. What we need is an API with a wider range of query options hooked up to a fast database that can dynamically generate results users need.</li><li>Finally, we need more <strong>exploratory analysis tools</strong> to work with huge slices of the data. Our machine learning efforts suffered because they focused on relatively rare events, and relied on data from passenger occupancy count sensors, which are installed in only about 40 percent of the fleet. Improving these models will mean being able to quickly query and analyze multiple months of data interactively. For that we need a modern big data layer, such as Apache Spark, that can parallelize datasets and speed up explorations.</li></ul><p>This is our agenda going into 2022, where the focus of work by a new group of students—Preksha Agarwal, Eesha Khanna, and Sarang Pramode—will be on helping us regroup and rebuild our core infrastructure. We’re going to look at several alternatives for the data warehouse, from cloud-hosted databases to serverless interactive query services like Amazon Athena. Along the way, we’ll likely explore serverless architectures for scraping too, such as Amazon’s Lambda. We’re going to engineer this pipeline for high performance, big scale, and low cost.</p><p>It’s an exciting set of challenges, and ones that our students don’t often encounter in coursework, where faculty are focused on teaching the latest theories and techniques, but rarely go beyond data sets that are static, clean, and small. Here, our students need to build a production service that deals with real-world challenges like latency, disk failures, time-sensitive torrents and dirty data feeds.</p><p>I also expect to throw them some curveballs along the way too, like figuring out where and what kind of geospatial functionality to embed. Right now we just ship coordinate pairs and expect users to make all the maps. But we <em>can</em> embed geoprocessing all the way down in our database, and expose those capabilities through our API. But should we? And if so, at what cost and complexity? Should we meter access to our API?</p><p>My list of to-dos for this project goes on for pages. But amidst all that planning, a new vision has emerged. What we are building isn’t just for tracking buses in New York City, it’s a <strong>“bus observatory” </strong>— a scalable scraper and stockpile of data on the operations of every bus system on the planet , openly available for anyone that wants to use it.</p><p>Arriving at that that vision, and all the work we’ve done to get here, has really helped clarify the meaning of “urban tech” for me.</p><p>Over the last year and a half, since we launched the Urban Tech Hub at Cornell Tech, many people have asked me, “What is urban tech?” So many, in fact, I wrote a <a href="https://www.starcitygroup.us/wp-content/uploads/2021/01/What-is-urban-tech-Definitions-aims-and-ethical-tensions.pdf">white paper</a> to try to define it, and explain its aims and ethical tensions.</p><p>But as I contemplate what we’re doing here, my notion of what urban tech is becomes far more concrete. Because what we’re doing is building a new kind of scientific instrument.</p><p>It’s like a telescope hoisted to the top of a mountain, but rather than gazing out at the stars, it is aimed back down to our human-made earth, our remarkable urban settlements. Much as modern astronomers seek to collect and share massive, streaming data widely for many eyes to study — we aim to deliver raw information for scholars, students, and amateur urbanists to discover patterns in the workings of urban transit.</p><p>There are already lots of private companies pulling this kind of data every day, from big ones like Google to smaller ones like Transit. And there’s even been some <a href="https://www.businessinsider.com/real-time-transit-map-2017-6">cool</a> <a href="https://mobility.portal.geops.io/world.geops.transit?baselayers=world.geops.travic,ch.sbb.netzkarte,ch.sbb.netzkarte.dark&amp;lang=en&amp;layers=paerke,strassennamen,haltekanten,haltestellen,pois,world.geops.traviclive&amp;x=-8235743.5&amp;y=4971840.95&amp;z=14">efforts</a> to do something like this, but the underlying data has always been held back. And there’s no community to help researchers and students use it.</p><p>That’s the difference here. I see this bus observatory as a shared research facility for urban scholars and engineers and transit stakeholders. While our primary focus is on archival and exploration, we want this work to be relevant to those working inside and outside government to improve bus services day-to-day. We will step up our efforts to be relevant and impactful to these stakeholders.</p><p>While I don’t know exactly what this data will be used for, that’s the same situation I was in back in October 2020 when I started collecting it. But my hunch them panned out, and I think this one will as well.</p><h4>Further Reading</h4><p>This series of four articles documents the thinking and work of our bus data working group at Cornell Tech throughout 2020–2021, and lays out a roadmap for 2022.</p><ol><li>The first article, <a href="https://medium.com/p/1f1bcea7092d"><strong>“Can Better Data Unlock A Bright Future for Buses?”</strong></a>, provides background on the project — its inspiration, its aims, and its importance.</li><li>The second article, <a href="https://medium.com/p/a65a276ba2e1"><strong>“The Bigness of Bus Data”</strong></a>, digs into the techniques we developed to retrieve, store, and distribute data on the operations of New York City buses. We’ll show you some code, and show you where you can fetch slices of the data we’ve culled, as well as the raw original responses we parsed it from (and why you’d ever want to do that in the first place.)</li><li>Article three, <a href="https://medium.com/p/896bb42cf39f"><strong>“From Sensing to Sensemaking: Models, Analytics, and Visualizations”</strong></a>, explores student work in modeling, analytics, and visualization built on top of this data. These demonstrate the potential of what easy access to longitudinal data about buses can unlock — these include: <br>- a <em>diff</em>-style <strong>data analysis tool</strong> for comparing performance of bus service by route and period developed by Jeremy Shaffer; <br>- a <strong>predictive model</strong> created by Lars Kouwenhoven for understanding the impact of service disruptions on nearby subway lines on bus crowding; <br>- a <strong>predictive model </strong>exploring interactions between severe heat and rainfall, inadequate shelters at bus stops, and ridership — a harbinger of structural challenges to come that could limit the system’s utility as a tool for carbon emission reductions — put together by Alexander Amy and Sanket Shah; and, <br>- an <strong>interactive map-based data visualization</strong> of the entire New York City bus system designed by Jamie (Hao) Geng, with channels for switching between a real-time view of what’s happening right now, and “playback” of historical observations.</li><li>Finally, article four, <a href="https://medium.com/p/822111845e54"><strong>“Towards A Global Bus Observatory”</strong></a> lays out our vision and plan for 2022, and the opportunities and technical challenges we anticipate in the year ahead.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822111845e54" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bus-watching/towards-a-global-bus-observatory-822111845e54">Towards A Global Bus Observatory</a> was originally published in <a href="https://medium.com/bus-watching">BusWatching</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Sensing to Sensemaking: Analyzing, Visualizing, and Modeling New York City’s Buses]]></title>
            <link>https://medium.com/bus-watching/from-sensing-to-sensemaking-analyzing-visualizing-and-modeling-new-york-citys-buses-896bb42cf39f?source=rss----47bb28ebbc---4</link>
            <guid isPermaLink="false">https://medium.com/p/896bb42cf39f</guid>
            <category><![CDATA[urbantech]]></category>
            <category><![CDATA[cornell-tech]]></category>
            <category><![CDATA[transit]]></category>
            <category><![CDATA[new-york-city]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anthony Townsend]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 02:05:12 GMT</pubDate>
            <atom:updated>2022-08-12T13:10:38.052Z</atom:updated>
            <content:encoded><![CDATA[<p>This article, the third in a series, highlights the work of students in Cornell Tech’s Urban Tech master’s program leveraging high-frequency bus journey tracking data scraped from the New York MTA’s BusTime API. This was carried out during year-long small group &amp; independent study projects in 2021.</p><p>Big data is the new oil!</p><p>No it’s not. I hate that metaphor more than most.</p><p>But streams of high-frequency sensor data, like the data I started scraping from the NY MTA’s BusTime API in October 2022, are a vital raw material for sensemaking.</p><p>Soon after I <a href="https://medium.com/bus-watching/can-better-data-unlock-a-brighter-future-for-buses-1f1bcea7092d">started scraping</a> the BusTime API, to track the status of every bus in New York City every 60 seconds, I found an opportunity to share the data with our students at Cornell Tech as part of a unique year-long degree requirement, the “Specialization” course. This course, which spans students’ first and second year, puts students into small groups to pursue independent research projects in close consultation with an advisor. Students begin their work in the spring with a 3-credit commitment that focuses on exploring their research topic, homing in on a question, and collecting the tools and techniques they’ll need to carry out the work in the fall, when the commitment doubles to 6 credit-hours.</p><p>This bus data is rich. By the fall, we’d accumulated nearly a half-billion observations of up to 2,000 buses operating on more than 250 routes over nearly a full year. During that time, the bus system had seen the city start to bounce back from the public health crisis and economic slump of the pandemic, severe weather events including heat emergencies and historic, torrential downpours, and more. There was so much to explore in this data.</p><p>Below we take a quick look at the projects Cornell Tech’s urban tech graduate students carried out to analyze, visualize, and model the New York City bus system during 2021.</p><h3>A <em>diff</em> Tool for Big Bus Data</h3><p>While I’d built an API for delivering bulk data to student researchers, it wasn’t simple to turn that raw data—essentially a pile of breadcrumbs—into useful information. For instance, computing basic service metrics like travel speed required multiple steps of fetching data, transforming it into a clean dataframe, and computing summary statistics. What’s more, comparing different time periods or different routes added more complexity.</p><p><em>diff </em>is a old Unix command-line tool used to compare the contents of two files. <a href="https://www.diffchecker.com/">Online versions of this trusty tool</a> make it easy to see the differences between versions of a file, and <em>diff</em> is the backbone of version control systems like <em>git. </em>Could we use this approach to provide a simple web-based tool for comparing different slices of the bus data archive?</p><p>That was the thinking behind an interactive query and comparison tool developed by Jeremy Shaffer. With this tool data seekers can construct a two queries, with different filters for route and time period, and compute summary statistics comparing across them. This allows for comparisons on the same route at different times, or between different routes at the same time (or different routes at different times, though this is probably less useful).</p><p>Highlights of Jeremy’s work include:</p><ul><li>Dynamic retrieval of data from our API</li><li>Computation of average travel speed and bunching, taking into account the unique geography of each route via published GTFS geometries</li><li>An elegant, performant interactive dashboard implemented in <a href="https://streamlit.io/">Streamlit</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*WUNF1jlcBYiYAL7FZc-0Bw.png" /><figcaption>A diff tool for big bus data highlights the differences in two filters and then computes comparative statistics. Shown here: the Bx19 is a lot slower on weekdays—1.24 miles per hour less than the already tortoise-like pace of 5.29 mph for Saturday morning. (Jeremy Shaffer)</figcaption></figure><h3>Maps for Playback and Real-Time</h3><p>While most of our students were enrolled in the Urban Tech master’s specialization, Jamie (Hao) Geng joined our group from Cornell Tech’s Connective Media program. Jamie’s work zeroed in on developing a way to grapple visually with the mass of data contained in our system. Naturally, this quickly led to the development of a map-based tool, with two “channels”:</p><ul><li>a <a href="https://master.dy7qfkm3y63du.amplifyapp.com/#">“history” view</a>* for playing back the hourly bulk data files provided by our API</li><li>a <a href="https://master.dy7qfkm3y63du.amplifyapp.com/real">“live” view</a>* for fetching and viewing a weather-radar-style loop of the last 5 minutes of bus movements citywide (which we felt provided a more compelling visual experience than the snail-like pace of the animation on the <a href="https://map.mta.info/">MTA’s new interactive subway map</a>)</li></ul><p>We’re already thinking about how to further refine the “live” map as a public-facing visualization, and perhaps as a public display in the Bloomberg Center at Cornell Tech.</p><p>Highlights of Jamie’s work include:</p><ul><li>A performant React-based map leveraging deck.gl for rendering big, animated data sets — including a variety of options for viewing high-frequency urban data and derived metrics in summary and in detail</li><li>A clever “loop” animation to show “real-time” bus movements in a more informative, and visually appealing method than actual real-time.</li><li>A serverless (AWS Lambda) backend to retrieve and parse the latest bus positions from the BusTime API</li></ul><p><em>*n.b. Because of some idiosyncrasies in the way Cornell’s campus network routes IP addresses for Amazon web services, some of these maps may not work well for Cornell users. It’s suggested to use an external network or personal hotspot for now, until we can resolve the routing issues.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZcOM7WxNpsIhcIT2Grq7A.png" /><figcaption><a href="https://www.youtube.com/watch?v=jQE66WA2s-A">All your bus are belong to us</a>. (Jamie Geng)</figcaption></figure><h3><strong>Predicting the Impact of Subway Disruptions on Bus Crowding</strong></h3><p>By far the most interesting development in bus data in 2020 was the introduction of passenger counts. This data was quickly exploited by the MTA and a variety of app provides to broadcast information on levels of crowding aboard buses during the pandemic. But Lars Kouwenhoven wondered whether the data could reveal other patterns in the bus system. As we explored the possibilities, Lars zeroed in on an important question—what happens to ridership on buses when service on nearby subway lines is disrupted, and can we predict that surge in crowding reliably?</p><p>Lars spent the spring developing a robust machine learning model to predict the number of passengers on future trips, as well as trips on buses without occupancy sensors. But work on the larger project of predicting the impacts of subway disruptions continues. The relative rareness of these events—just 1/2 of 1 percent of bus observations were flagged as being effected by a subway disruption—as well as the complexity of relationships between the two network topologies limited. More data, and more refinement are expected to improve the effectiveness of the model.</p><p>Highlights of Lars’ work include:</p><ul><li>Implementation and evaluation of an XGBoost-based machine learning pipeline to predict the number of passengers on buses in the future, as well as the 60 percent of buses without occupancy sensors. (Though the model had some shortcomings, the mean average error was 4.09, and there was potential for future improvement).</li><li>Grabbing, parsing, and merging data from the MTA service alert feed to determine the period of subway disruptions and affected bus lines.</li><li>Use of a cyclical time transformation to improve the model’s understanding of relationships between late night and early morning travel.</li><li>Identification of interesting transit rider behaviors around subway disruptions, notably a surge in riders onto nearby buses <em>just before</em> the issuance of an unplanned subway disruption alert, indicating real-time reactions to the service change.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nR0h0_rZqVwHVVfIVdNCA.png" /><figcaption>AI can’t help you now — but New York City buses can. Riders from the IRT 2/3 subway head over to the M7 bus at 3 different stops during an unplanned disruption late on the evening of October 28, 2021. The data shows ridership shifting to the buses even before an official alert hits the wires at 11:15pm. (Lars Kouwenhoven)</figcaption></figure><h3>Buswatcher-Insights: A Public Codebase for Machine Learning</h3><p>Normally, the Specialization project spans a Spring semester and the following Fall semester. It’s kind of a cool setup, because students go off in the summer and come back with new ideas and sometimes big leaps from tinkering and noodling they’ve done in between stints in internships or on the beach.</p><p>Alexander Amy and Sanket Shah took a different path, pivoting away from a different Specialization project they’d worked on in the Spring and joining the bus data group in September for a crash course in transit tracking. Like Lars Kouwenhoven (see above), their intention was to exploit the bus data to do an in-depth machine learning project.</p><p>As we explored possible experiments, a series of extreme weather events that had occurred in New York City over the summer were fresh on my mind—torrential downpours caused by the remnants of Hurricane Ida, and a series of historic heat waves. Buses are one of our best tools for shifting people from cars and taxis to a lower-emission form of travel. But was anyone thinking about climate-proofing the bus network itself? A quick survey of relevant literature revealed a good body of work on how precipitation can drive people from buses, but heat was less studied.</p><p>This project brought together 3 sets of data:</p><ul><li>the bus positions provided by <a href="http://api.buswatcher.org/docs">our API</a>,</li><li>a data set containing the locations of <a href="https://data.cityofnewyork.us/Transportation/Bus-Stop-Shelters/qafz-7myz">bus shelters</a> published by the city,</li><li>weather data indicating heat, humidity, and rainfall for the city.</li></ul><p>Alex and Sanket worked hard to build out <a href="https://cornell-tech-urban-tech-hub.github.io/buswatcher-insights/">a prototype model</a>. However, the complexity of phenomena they were trying to model ultimately proved too great to definitively answer in one semester. Rather than leaving the project there, however, the team regrouped and embarked on a different, and highly constructive effort—to clean up and compile their <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/buswatcher-insights/">codebase</a> to hand off to future students, and put their experiments online in an <a href="https://cornell-tech-urban-tech-hub.github.io/buswatcher-insights/">interactive Streamlit application</a> that allows us to view and interact with their data, models, and evaluation metrics.</p><p>Highlights of Alex and Sanket’s work include:</p><ul><li>Creation of an effective, generalized, and extensively documented set of methods and tools to accelerate the work of future students and researchers working with New York City bus data</li><li>Creation of a interactive web app that “shows” instead of “tells” the implications of different model and feature choices made during the experiments.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*B1Ye7oUo9nalYmnwXy3DqQ.png" /><figcaption>Students who build tools for other students are my heroes. (Alexander Amy and Sanket Shah)</figcaption></figure><p>In the final post, we look to 2022 and the opportunities and challenges facing the next group of student researchers digging into New York City’s bus system.</p><h4>Further Reading</h4><p>This series of four articles documents the thinking and work of our bus data working group at Cornell Tech throughout 2020–2021, and lays out a roadmap for 2022.</p><ol><li>The first article, <a href="https://medium.com/p/1f1bcea7092d"><strong>“Can Better Data Unlock A Bright Future for Buses?”</strong></a>, provides background on the project — its inspiration, its aims, and its importance.</li><li>The second article, <a href="https://medium.com/p/a65a276ba2e1"><strong>“The Bigness of Bus Data”</strong></a>, digs into the techniques we developed to retrieve, store, and distribute data on the operations of New York City buses. We’ll show you some code, and show you where you can fetch slices of the data we’ve culled, as well as the raw original responses we parsed it from (and why you’d ever want to do that in the first place.)</li><li>Article three, <a href="https://medium.com/p/896bb42cf39f"><strong>“From Sensing to Sensemaking: Models, Analytics, and Visualizations”</strong></a>, explores student work in modeling, analytics, and visualization built on top of this data. These demonstrate the potential of what easy access to longitudinal data about buses can unlock — these include: <br>- a <em>diff</em>-style <strong>data analysis tool</strong> for comparing performance of bus service by route and period developed by Jeremy Shaffer; <br>- a <strong>predictive model</strong> created by Lars Kouwenhoven for understanding the impact of service disruptions on nearby subway lines on bus crowding; <br>- a <strong>predictive model </strong>exploring interactions between severe heat and rainfall, inadequate shelters at bus stops, and ridership — a harbinger of structural challenges to come that could limit the system’s utility as a tool for carbon emission reductions — put together by Alexander Amy and Sanket Shah; and, <br>- an <strong>interactive map-based data visualization</strong> of the entire New York City bus system designed by Jamie (Hao) Geng, with channels for switching between a real-time view of what’s happening right now, and “playback” of historical observations.</li><li>Finally, article four, <a href="https://medium.com/p/822111845e54"><strong>“Towards A Global Bus Observatory”</strong></a> lays out our vision and plan for 2022, and the opportunities and technical challenges we anticipate in the year ahead.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=896bb42cf39f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bus-watching/from-sensing-to-sensemaking-analyzing-visualizing-and-modeling-new-york-citys-buses-896bb42cf39f">From Sensing to Sensemaking: Analyzing, Visualizing, and Modeling New York City’s Buses</a> was originally published in <a href="https://medium.com/bus-watching">BusWatching</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bigness of Bus Data]]></title>
            <link>https://medium.com/bus-watching/the-bigness-of-bus-data-a65a276ba2e1?source=rss----47bb28ebbc---4</link>
            <guid isPermaLink="false">https://medium.com/p/a65a276ba2e1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[urbantech]]></category>
            <category><![CDATA[cornell-tech]]></category>
            <category><![CDATA[transit]]></category>
            <category><![CDATA[new-york-city]]></category>
            <dc:creator><![CDATA[Anthony Townsend]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 01:57:41 GMT</pubDate>
            <atom:updated>2022-08-12T13:10:48.756Z</atom:updated>
            <content:encoded><![CDATA[<p>As I described in the first post in this series, as the pandemic-induced transit shakeup evolved into outright fiscal meltdown over the summer of 2020, I threw together <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/nycbuswatcher/tree/e2954a1addd351d6bb3770507ef782e84a650bfd">some code</a> that scraped the positions and status of all the buses in the New York City Transit system once a minute, day-in and day-out.</p><p>I was excited. While others were already scraping the data and making it available publicly, there were lots of issues with using those repositories (more on that below), and having our own copy ready at hand would provide total control and flexibility.</p><p>Keeping this system running, however, quickly proved to be a multi-faceted engineering challenge.</p><p>This post looks at five challenges we encountered and the approaches we used to overcome them. While we learned a ton and produced a working data platform, our work is nowhere near done. (In the <a href="https://medium.com/p/822111845e54">final article</a>, I lay out some of the thinking in how we will tear all this down and put it back together again in 2022.)</p><h3>Challenge 1. Handling high-frequency data</h3><p>Scraping a data set once is one thing. Scraping it every minute, day in, day out, is another.</p><p>Vehicle positions are ephemeral. I mean, that’s obvious right? So obtaining a fresh fix for each bus on the road is important. But how often is often enough? Given the relative slowness of city buses (under 10 mph on average in New York), and after some experimentation, we settled on once per minute. In that interval a bus going at 10 miles per hour will travel about 900 feet, or about 3 blocks—right around the interval between stops. That seemed right for a first go, since ideally we’d be able to get a position around each and every stop, at a minimum.</p><p><strong>Breaking down our API requests. </strong>The first challenge this creates is getting the data, and processing it in under a minute—otherwise, our workload would back up and we’d either miss the next fetch or our workload would back up. This proved to be very hard, because the MTA BusTime API couldn’t reliably respond to requests for the entire system status at once, and would often take 2 to 3 minutes to respond or even timeout during rush hour when the responses grew close to 100 megabytes in size. FWIW, this use is discouraged by the MTA anyways.</p><p>My first solution to this problem was to break down that single bulk request for the entire system into requests for individual routes, which required first making a request to another API endpoint (the MTA’s OneBusAway API) to get a list of active routes, and then iterating over that list to construct URLs to get each route’s vehicle monitoring data. This worked brilliantly, but the system had to wait for each request to be fulfilled before moving onto the next. Often we’d miss that 60 second deadline and things would start backing up.</p><p>That’s when I stumbled onto some kind code.</p><p><strong>Getting asynchronous. </strong>Asynchronous web requests in python are not as straightforward as Javascript, but I was able to make use of a nice technique I found on StackOverflow based on the <em>trio</em> package (much of the workings are contained in other functions not shown, but the code below illustrations how the dispatching of the parallel asynchronous grabber jobs work):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*4nIbhN3SQdN7UqjwoJdbjA.png" /><figcaption>Nom nom bus data.</figcaption></figure><p>What this does, then, is to send lots of requests to the API separately, and then parse them as they come back without any request being held up by any other. The number of simultaneous requests is configurable, and I settled on a number around 50.</p><p>The results were incredible. A process that previously took a minimum of 25–30 seconds (and often longer, if there were network latency issues, as one request would hold up all the others behind it), usually completed in less than 10 seconds, leaving plenty of time to any housekeeping tasks to prepare for the next minute’s cycle to start.</p><p><strong>Persisting the scraper. </strong>After we’d solved the problem of how to fetch the BusTime feeds quickly, the challenge became deploying this scraper in a persistent, reliable fashion. This wasn’t something you could run on a laptop and leave in a corner. It had to be going around the clock, and be able to recover from errors and crashes. Here, we did two things:</p><ol><li><strong>Containerization. </strong>The grabber and the database were both staged as docker containers (as the API would also later), and the whole stack was deployed on an Amazon Web Services EC2 instance. Surprisingly, we were able to get by for a while on a free tier micro-sized instance. This would change when time came to deploy the API and we needed more memory and CPU to be able to execute queries on the growing database.</li><li><strong>Testing</strong>. I’m not a software engineer, so rather than develop formal tests, I spent a lot of time checking logs and trapping errors that would cause the grabber to choke or crash. If you’re interested, most of these are documented in the commit logs of the code. After a few weeks, the whole system had become very reliable.</li></ol><h3>Challenge 2. Handling a lot of data</h3><p>It was clear early on that we were accumulating <strong>a lot of data</strong>. Certainly more than I had ever worked with before. After a few days of scraping I checked our database with the first query everyone learns in SQL:</p><pre>SELECT COUNT(*) FROM buses;</pre><p>A variation on that provided a bit more information, namely how many records we were accumulating each day:</p><pre>SELECT service_date, COUNT(*) FROM buses GROUP BY service_date;</pre><p>I was somewhat taken aback to discover the database growing by 1.5 to 2 million records a day, or 60 million records monthly. A quick check verified that it made sense (an average of 1,5000 to 2,000 buses rolling at any given time, streaming 60 observations per hour, for 24 hours).</p><p>By today’s standards, you have to be in the terabyte range to qualify as “<a href="https://towardsdatascience.com/how-big-is-big-data-3fb14d5351ba">big data</a>”. At the rate we were going, we’d get there in about a year. Maybe not that big, but for me, big enough. Certainly big enough to cause a lot of problems.</p><p>I dreaded (and still do) the inevitable task of database optimization that now loomed, and scaling our computing resources, that laid ahead—the thankless work of the big data era.</p><p>But I had already bigger problems. My students were clamoring for more. A few months in, they discovered the scalar passenger count value embedded in a part of the SIRI response JSON nested five levels deep. This was valuable information, and easy enough to update our code to parse out once I knew where to look, but it raised two new problems:</p><ol><li><strong>Database migration. </strong>I’d need to design and implement a database migration to add the new fields to our table, something I had never done on a live database, and certainly not at this scale.</li><li><strong>Preserving the raw response data. </strong>What other potentially valuable information were we throwing away by parsing the MTA API responses selectively and discarding the rest? This was potentially a big headache.</li><li><strong>Reprocessing old responses to update the database.</strong> So what happens if we decide to start parsing another field into our main data table? Simply deploy the new parser and then migrate the database. But what about going back and extracting those new fields from the raw responses we’ve been stockpiling? I think of that as reprocessing, and it’s a nasty, complex task.</li></ol><p>To make things worse, as we accumulate more data, all of these tasks take longer and longer to execute during development. At some point, you can’t work on a copy of the database, but need an excerpt of it, adding yet another complexity.</p><p>We’ll pick up both of these challenges below, because they were instrumental in a decision to completely rebuild the platform 8 months in, and the architecture I chose. But for now, I’ll simply say that even without the raw responses, the database was growing by about 2 gigabytes a day, and that was just the fields we were parsing out.</p><h3>Challenge 3. Distributing Data</h3><p>The other challenge of collecting and storing so much data was distributing it. After all, the entire point of building this system was to make a big, live data set from a real-world urban system readily available to our Urban Tech students, and potentially researchers as well.</p><p>This immediately became a problem. As my students started exploring the data, and building models, they would make frequent requests for ever-more-expansive slices of the data. This wasn’t just time consuming, since it required me to jump through three hoops just to generate the tables requested (well three really: ssh-ing into the EC2 instance, and then exec-ing into the database docker container, and then dumping the tables from the mysql client), then I had to figure out how to dump and move the data from the docker container back to the students. Of course there are ways to streamline all of this, but in practice, getting that set up was often more work than the tedious but simpler manual methods.</p><p>Rather than invest time in automating that process, I jumped to another solution—providing an API. That <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/nycbuswatcher/blob/e2954a1addd351d6bb3770507ef782e84a650bfd/api-www.py">first API</a> including a bunch of endpoints, including one powering a nifty livemap of the system.</p><p>And so, that code provided a variety of endpoints:</p><pre>All observations for the entire system during a specific interval (in this case the one-hour period between 11 am and 12 noon on August 11, 2020):</pre><pre>api/v1/nyc/buses?start=2020-08-11T11:00:00+00:00&amp;end=2020-08-11T15:12:00+00:00</pre><pre>All observations for a single trip:</pre><pre>/api/v1/nyc/trips?service_date=2020-08-11&amp;trip_id=NYCT_20110102EA_087800_B63_0002_B63_19</pre><p>These endpoints triggered SQL queries built up from the parsed arguments in the URL, and results of the would be spit out in JSON over the web. This was all pretty easy to build using the Flask framework. I even added another optional argument:</p><pre>&amp;output=geojson</pre><p>That would wrap the whole response in GeoJSON, making it instantly mappable.</p><h3>The Big Rewrite(s)</h3><p>By this point, I was very pleased with myself. I had only started learning Python in 2016, and now I was able to take an idea about scraping big urban data, and in about 100 hours, turn it into a reliable, persistent platform . I’d run into a dozen serious challenges, and managed to overcome them, with style even.</p><p>Of course, that’s when the problems started.</p><p>Almost as soon as I rolled it out, the API started choking because of high demands each request placed on the database — my queries were complex and badly designed, I hadn’t done a good job indexing the data, I wasn’t caching any responses, and since I was trying to keep costs down had not provisioned enough computing resources. The API soon became pretty useless.</p><p>And over the summer of 2021, as I prepared for my students to return, and turn the ideas they’d explored during the spring into full-fledged models and visualizations, I realized I needed to streamline things.</p><p>And so I threw the database out the window, and rebuilt the entire stack as a data lake of static files.</p><h4>From Database to Data Lake…</h4><p>The idea behind my new architecture was to simply stream those minute by minute data ingestions to a series of static files and have the API dish those out, eliminating the database entirely. My thinking was this:</p><ol><li><strong>API users wanted bulk data, so I limited the flexibility of queries and preprocessed the responses. </strong>The first version of the API was designed to allow fetching of any defined period, but since 1 route-hours worth of data was usually just a few megabytes, it seemed like a good chunk. I dubbed this unit of data a “shipment”, and rewrote the grabber to pickle (a python method of serializing objects) each route’s observations into a temporary folder, and then once an hour bundle those up in a single JSON file, which could easily and quickly be served as a static response to an API request. (and in one of the easiest and most fun parts of the project, I rewrote the API using the amazing <a href="https://fastapi.tiangolo.com/">FastAPI</a> framework).</li><li><strong>The raw data was enormous, so I compressed it. </strong>Another copy of the raw API responses went into cold storage, with a similar scheme, bundled up into hourly .tar.gz route-hour packages. I created an endpoint that would allow anyone that wanted to do their own reprocessing to extract features we’d passed over, to retrive these bundles (which I called “glaciers”) programmatically as well.</li></ol><p>As intended, the students quickly figured out how to iterate over a list of routes and date intervals to pull the bulk data they needed into geopandas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*HO1BChkKmiNvzsLCJTSSJw.png" /><figcaption>Students write better code than you can dream of. (<a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/buswatcher-insights/blob/main/data_pipeline/data_downloader.py">buswatcher-insights</a>)</figcaption></figure><p>For our purposes—scraping, parsing, aggregating, and distributing big streaming data for student work—this bespoke architecture performed well.</p><h4>…and back again?</h4><p>I soon realized though that I’d once again painted myself into a corner. More on this in the fourth article, but by the end of the 2021, this bespoke data lake approach was showing its limits, most notably the inability to do any kinds of queries across the whole data set—a showstopper when I started to think about scaling horizontally to scrape other cities. I’m now looking to move back to a more structured data store.</p><h4>Lessons</h4><p>As long as this post is, it’s not even half the story. There were many feautures and experiments that we pursued but abandoned. But the key lessons were these:</p><ol><li>Know your data source’s limits. Be respectful, be aware of its weak spots. The asynchronous part of this code is the least intuitive, but highest-performing part of this project and it solved a show-stopping problem.</li><li>Doing ongoing data collection means becoming at least a little bit of a Linux sys admin.</li><li>Save everything you fetch. Storage is cheap and gzip is fast.</li><li>A full-on relational databases is not always the best way to persist data, especially if you don’t plan lots of different, complex queries.</li><li>Share your data programmatically. Wrapping a fast, full-featured REST API around any dataset is trivially easy with python frameworks like Flask or FastAPI.</li></ol><h4>Further Reading</h4><p>This series of four articles documents the thinking and work of our bus data working group at Cornell Tech throughout 2020–2021, and lays out a roadmap for 2022.</p><ol><li>The first article, <a href="https://medium.com/p/1f1bcea7092d"><strong>“Can Better Data Unlock A Bright Future for Buses?”</strong></a>, provides background on the project — its inspiration, its aims, and its importance.</li><li>The second article, <a href="https://medium.com/p/a65a276ba2e1"><strong>“The Bigness of Bus Data”</strong></a>, digs into the techniques we developed to retrieve, store, and distribute data on the operations of New York City buses. We’ll show you some code, and show you where you can fetch slices of the data we’ve culled, as well as the raw original responses we parsed it from (and why you’d ever want to do that in the first place.)</li><li>Article three, <a href="https://medium.com/p/896bb42cf39f"><strong>“From Sensing to Sensemaking: Models, Analytics, and Visualizations”</strong></a>, explores student work in modeling, analytics, and visualization built on top of this data. These demonstrate the potential of what easy access to longitudinal data about buses can unlock — these include: <br>- a <em>diff</em>-style <strong>data analysis tool</strong> for comparing performance of bus service by route and period developed by Jeremy Shaffer; <br>- a <strong>predictive model</strong> created by Lars Kouwenhoven for understanding the impact of service disruptions on nearby subway lines on bus crowding; <br>- a <strong>predictive model </strong>exploring interactions between severe heat and rainfall, inadequate shelters at bus stops, and ridership — a harbinger of structural challenges to come that could limit the system’s utility as a tool for carbon emission reductions — put together by Alexander Amy and Sanket Shah; and, <br>- an <strong>interactive map-based data visualization</strong> of the entire New York City bus system designed by Jamie (Hao) Geng, with channels for switching between a real-time view of what’s happening right now, and “playback” of historical observations.</li><li>Finally, article four, <a href="https://medium.com/p/822111845e54"><strong>“Towards A Global Bus Observatory”</strong></a> lays out our vision and plan for 2022, and the opportunities and technical challenges we anticipate in the year ahead.</li></ol><h4>Even Further Reading</h4><p>If you haven’t dorked out enough yet on processing bus data, you can watch Katie Bell <a href="https://www.youtube.com/watch?v=O7jqU39wvKk">explain the ins and outs</a> of doing more or less the same thing (with much more elegance) in Sydney, and her code is <a href="https://github.com/katharosada/bus-shaming">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a65a276ba2e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bus-watching/the-bigness-of-bus-data-a65a276ba2e1">The Bigness of Bus Data</a> was originally published in <a href="https://medium.com/bus-watching">BusWatching</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Can Better Data Unlock A Brighter Future for Buses?]]></title>
            <link>https://medium.com/bus-watching/can-better-data-unlock-a-brighter-future-for-buses-1f1bcea7092d?source=rss----47bb28ebbc---4</link>
            <guid isPermaLink="false">https://medium.com/p/1f1bcea7092d</guid>
            <category><![CDATA[urbantech]]></category>
            <category><![CDATA[new-york-city]]></category>
            <category><![CDATA[cornell-tech]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[transit]]></category>
            <dc:creator><![CDATA[Anthony Townsend]]></dc:creator>
            <pubDate>Thu, 16 Dec 2021 23:29:17 GMT</pubDate>
            <atom:updated>2022-08-12T13:11:01.898Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“A man who, beyond the age of 26, finds himself on a bus can count himself as a failure.”</blockquote><blockquote>—Margaret Thatcher</blockquote><p>It’s <a href="https://www.theguardian.com/Columnists/Column/0,5673,1560453,00.html">doubtful</a> that Thatcher ever actually said this. But then, Captain Kirk never actually said “Beam me up, Scotty!” and Sherlock Holmes never quipped “Elementary, my dear Watson.” Apocryphal, all of them are.</p><p>Still, that Thatcherite snub has a whiff of truth even here on the other side of the pond. Bus ridership in the United States has <a href="https://www.nytimes.com/interactive/2020/03/13/upshot/mystery-of-missing-bus-riders.html">plummeted over the last decade</a>. In New York City, it dropped 15 percent between 2010 and 2020. And that was <em>before</em> the pandemic, which <a href="https://new.mta.info/coronavirus/ridership">slashed average daily ridership again by about <strong>one-third</strong></a>. Buses are the mobility choice of last resort, and many who can, have chosen to abandon them altogether.</p><p>Do not count me among them. At 48, nearly twice the age of Thatcher’s proverbial failure, I consider myself something of a success. And I ride the bus all the time.</p><p>In fact, I prefer buses to trains. Who wouldn’t rather sit, iPad in hand with a good e-book, enjoying the cheap pleasure of connected transit?</p><p>Or what about the front-row view of the city, scrolling by outside? The fleeting moments when, at a stop the door opens onto some sidewalk drama or comedy. And then with a whoosh we’re off again to the next scene. It all feels so much more connected to the life of the city than rocketing through a tunnel on a train.</p><p>Plus, buses are still the best motorized means of getting around the city without sending a lot of carbon dioxide into the atmosphere.</p><p>Take that, Uber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*XHkdNo_KQEI8sh5K1oruGA.jpeg" /><figcaption>Milana Vinn for <a href="https://citylimits.org/2016/09/07/slow-late-or-crowded-buses-are-the-jugular-of-the-bronx/">City Limits</a></figcaption></figure><h4>The Pandemic 1–2 Hits Buses</h4><p>Here’s another quote, from Mike Tyson, which I think he actually said:</p><blockquote>“Everybody has a plan until they get punched in the mouth.“</blockquote><blockquote>—Mike Tyson</blockquote><p>The pandemic dealt a one-two punch to transit systems all over the world, buses in particular.</p><p>First, they became death traps. In New York City, 33 transit workers died in the first month of the pandemic. <a href="https://www.businessinsider.com/new-york-city-bus-drivers-most-deaths-covid-19-mta-2020-4">Most were bus drivers</a>. Countless New Yorkers presumably contracted COVID on buses before masks were widely available and enforced by mandate.</p><p>Then the financial toll of far fewer riders took hold. In August, MTA officials released a “doomsday budget” which threatened a<a href="https://nyc.streetsblog.org/2020/08/26/mta-40-service-cuts-will-happen-without-federal-aid/">40 percent service cut to fill a multi-billion dollar hole</a>. It was a not-so-subtle plea for federal assistance. (And despite the increased bus ridership, buses would see the same level of cuts as subway service.)</p><p>This was more than bureaucratic scare-mongering. The Trump administration was unraveling under the pressure of a pandemic <em>and</em> a re-election campaign. The slow emergency of the bus system’s decline seemed to be snowballing. Would it collapse altogether?</p><h4>When Every Bus Is A Lifeline, and Every Lane A Bus Lane</h4><p>Unthinkable before, the thought of letting the bus system collapse during the pandemic was absurd.</p><p>That’s because buses had quickly became the city’s most vital lifelines. With passengers afraid to pack into train cars, NYC Transit buses <a href="https://www.nytimes.com/2020/07/06/nyregion/mta-buses-nyc-coronavirus.html">carried more passengers than the subways</a> in April and May 2020 for the first time ever. Then, when overnight subway service was suspended or more than a year — from May 6, 2020 to May 17, 2021 — buses filled in the gaps.</p><p>Those front-line workers we all cheered? The bus was the only thing between having well-staffed, functional hospitals and distribution centers, and total societal collapse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiycgPZU1SQPcu6FcTtIPA.png" /></figure><p>Bus service also got noticeably quicker during the pandemic because there were fewer cars and trucks clogging the streets. <a href="https://www.nydailynews.com/coronavirus/ny-coronavirus-mta-bus-speeds-20200517-tbnem4wrbjdaramxkfu54y3twm-story.html">Bus speeds improved by nearly 20 percent</a>, in a natural experiment that validated arguments bus advocates had been making for years about our priorities around road space. Any bus route could be bus rapid transit (BRT), it turned out. We just needed to unleash the system’s potential by making more room on the road.</p><h4>Documenting Transit Doomsday</h4><p>As budget negotiations dragged on in the fall of 2020, I waited along with everyone else for a bailout from Washington. I too wrote letters, and called my members of Congress.</p><p>But I realized there was also something else I could do. I could <strong>preserve a record of the bus system’s collapse for posterity. </strong>Maybe, I thought, having the data showing the system’s death throes would useful down the road. Hopefully, to restore service. At worst, to make sure such things didn’t happen again.</p><p>So I got coding. The work was straightforward. I knew that the MTA had a <a href="https://bustime.mta.info/wiki/Developers/Index">robust API providing real-time data on bus operations</a>. I knew it would be relatively easy to scrape this data say, once per minute, and store the location and trip info for every bus in the system, 24/7. I’d build <a href="https://github.com/Cornell-Tech-Urban-Tech-Hub/njbuswatcher">just such a system</a> to monitor NJTransit’s bus routes a few years earlier.</p><p>A few hours later, I had some scripts and was scraping the location of every bus in the entire city, every 60 seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sjJLoaoFyKFVt6Tfb6er5g.jpeg" /><figcaption>With a flurry of keyboarding, the scraping of New York City’s bus network begins.</figcaption></figure><p><strong>I let my program run for a few weeks, but still didn’t have a very clear idea what this data would be useful for. </strong>My initial hunch—that it would enable some kind of forensic retrospective of a pandemic-induced transit meltdown—was still speculation. In fact, I didn’t actually want it be used for that, because I didn’t want the meltdown to happen!</p><p>What’s more, others had already built tools. For instance, the folks at Transit Center has been running a similar <a href="https://github.com/Bus-Data-NYC">scraping</a> scheme for years to create <a href="http://busturnaround.nyc/report-cards/">report cards</a> analyzing the quality of service on every New York City bus route. I wasn’t interested in repeating this work.</p><p>But I suspect there was still an opportunity to do new things with New York City’s bus data. As with Transit Center’s pioneering work, most data science experiments around bus data were limited to basic service metrics like travel speed and service frequency. (One of our favorites was this <a href="https://bunching.github.io/">heat map of bus bunching in Pittsburgh</a>). These were fascinating and useful, but what else could we learn from big bus data?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*KXpRoZMqZNBaVEmPpYXdsg.png" /><figcaption>Mark Egge’s 2016 bunching heat map of Pittsburgh’s buses. (<a href="https://bunching.github.io/">link</a>)</figcaption></figure><p>Then I had an idea—let students have at it!</p><p>At Cornell Tech, we’d just launched a new master’s degree in “urban tech”, an <a href="https://tech.cornell.edu/programs/masters-programs/jacobs-technion-cornell-dual-ms-urban-tech/">urban-focused graduate program in applied information science and information systems engineering</a>. I was slated to supervise a small group of students enrolled in a unique year-long “specialization” course, a sort of small-group independent study.</p><p>It didn’t take long for some remarkable possibilities to surface.</p><p>The first thing they keyed in on was the availability of passenger count data, thanks to the deployment of Automated Passenger Counter (APC) systems on about 40 percent of the fleet during the summer of 2020. <a href="https://www.govtech.com/fs/transportation/new-york-mta-app-now-features-bus-passenger-counts.html#:~:text=The%20real%2Dtime%20passenger%20numbers,the%20number%20of%20passengers%20onboard.">Combining infrared and camera-based computer vision techniques</a>, the sensors provided accurate counts of passengers onboard. I initially missed it, but the students found this field, encapsulated a half-dozen levels deep inside a nested data structure within the BusTime data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*FlLB_-HePN6GgrG0_AtqtQ.jpeg" /><figcaption>I see you, sucker. Most Automated Passenger Counter systems use computer vision to count individuals as they board a transit vehicle. (Image: <a href="https://gpstrackit.com/wp-content/uploads/2019/04/On-Boarding-Cameras.jpg">GPSTrackit</a>)</figcaption></figure><p>My students’ explorations of the data would soon reveal other secrets.</p><p>One put on a planner’s hat and started looking at the problem from the other way around. The MTA had taken advantage of light traffic to speed construction on long-planned capital improvements to bus routes intended to reduce and eliminate bottlenecks—bus lanes and priority traffic signaling foremost. Zeroing in on one of the city’s most congested busways, along East 149th Street in the Bronx, this student set out to measure the results.</p><p>The group also brought new methods and data science tools to bus data to deepen and expand the kinds of questions one could ask of it. Most important were machine learning approaches aimed at predicting passenger counts based on a whole host of factors. Students developed experiments to model and predict the impacts of severe weather on ridership, taking into account the poor state of the city’s network of bus passenger shelters. Another decided to look at the impact of subway disruptions on crowding along intersecting bus lines. Could this type of system stress be predicted better?</p><p>Another student also made this super-cool map that shows the entire system in action, in real-time. More on that later in another post.</p><p>Frankly, <strong>I was surprised to find so much potential in bus data.</strong></p><p>When we started, it had been a nearly decade since BusTime came online in <a href="https://www.programmableweb.com/api/mta-bus-time">2012–2013</a>. During those first few years, app developers, transit advocates, and researchers had generated immeasurable public and private value through bright uses of the data. It was, in every sense of the world, a public information utility, leveraging the city’s ongoing investment in transit by making bus service more convenient and more satisfying to use. And it still has lots more to give.</p><p>And that’s why this work at Cornell Tech, which started in the summer of 2020 will continues through the end of 2022 and beyond.</p><p>Along the way, we have come to better understand the challenges of collecting such vast urban data—and these challenges have scaled faster than we thought. We’ve already taken one pause, in the summer of 2021, to tear apart our data collection and storage platform and rebuild it from the ground up. It served us well, but has reached its limits, and in 2022 we’re going to focus on scaling our efforts in a third version — vertically, in terms of preserving as comprehensive a record of bus system operations as possible (rather than just parsing a few fields of interest and tossing the rest); and horizontally, by generalizing our infrastructure to be able to scrape bus feeds from multiple cities. In so doing, we’ll make a slight shift from focusing on data science to data engineering — but since our Cornell Tech students are earning dual degrees in <a href="https://tech.cornell.edu/programs/masters-programs/jacobs-technion-cornell-dual-ms-urban-tech/">applied information science and information systems engineering</a> its a perfect fit.</p><h4>Further Reading</h4><p>This series of four articles documents the thinking and work of our bus data working group at Cornell Tech throughout 2020–2021, and lays out a roadmap for 2022.</p><ol><li>The first article, <a href="https://medium.com/p/1f1bcea7092d"><strong>“Can Better Data Unlock A Bright Future for Buses?”</strong></a>, provides background on the project — its inspiration, its aims, and its importance.</li><li>The second article, <a href="https://medium.com/p/a65a276ba2e1"><strong>“The Bigness of Bus Data”</strong></a>, digs into the techniques we developed to retrieve, store, and distribute data on the operations of New York City buses. We’ll show you some code, and show you where you can fetch slices of the data we’ve culled, as well as the raw original responses we parsed it from (and why you’d ever want to do that in the first place.)</li><li>Article three, <a href="https://medium.com/p/896bb42cf39f"><strong>“From Sensing to Sensemaking: Models, Analytics, and Visualizations”</strong></a>, explores student work in modeling, analytics, and visualization built on top of this data. These demonstrate the potential of what easy access to longitudinal data about buses can unlock — these include: <br>- a <em>diff</em>-style <strong>data analysis tool</strong> for comparing performance of bus service by route and period developed by Jeremy Shaffer; <br>- a <strong>predictive model</strong> created by Lars Kouwenhoven for understanding the impact of service disruptions on nearby subway lines on bus crowding; <br>- a <strong>predictive model </strong>exploring interactions between severe heat and rainfall, inadequate shelters at bus stops, and ridership — a harbinger of structural challenges to come that could limit the system’s utility as a tool for carbon emission reductions — put together by Alexander Amy and Sanket Shah; and, <br>- an <strong>interactive map-based data visualization</strong> of the entire New York City bus system designed by Jamie (Hao) Geng, with channels for switching between a real-time view of what’s happening right now, and “playback” of historical observations.</li><li>Finally, article four, <a href="https://medium.com/p/822111845e54"><strong>“Towards A Global Bus Observatory”</strong></a> lays out our vision and plan for 2022, and the opportunities and technical challenges we anticipate in the year ahead.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f1bcea7092d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bus-watching/can-better-data-unlock-a-brighter-future-for-buses-1f1bcea7092d">Can Better Data Unlock A Brighter Future for Buses?</a> was originally published in <a href="https://medium.com/bus-watching">BusWatching</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>