Data-Driven Decisions for Where to Park in SF
Tags: aws, showdev, serverless
Published: 2019-08-19 16:53:50

---
title: Data-Driven Decisions for Where to Park in SF
published: true
tags: aws, showdev, serverless
canonical_url: https://rockset.com/blog/data-driven-decisions-realtime-parking-risk-score
---

Have you ever felt uncertain parking in a shady area? In particular, have you ever parked in San Francisco and wondered, if I measured the average inverse square distance to every vehicle incident recorded by the SFPD in the last year, at what percentile would my current location fall?

If so, we built [an app for that](https://rockset.com/sf-parking). In this post we’ll explain our methodology and its implementation.

## Parking in San Francisco

Vehicle-related break-ins and thefts are [notoriously common in San Francisco](https://www.nbcbayarea.com/news/local/Breaking-Point-475109113.html). Just last week, items worth half a million dollars were stolen in a [high-profile car burglary](https://abc7news.com/sf-community-reacts-to-police-response-over-car-burglary-with-celebrity-victim/5465666/). There’s even a [Twitter account](https://twitter.com/sfcarbreakins) tracking incidents.

The San Francisco Police Department maintains an ongoing [dataset of all incidents](https://data.sfgov.org/Public-Safety/Police-Department-Incident-Reports-2018-to-Present/wg3w-h783) since January 1, 2018 (there is [another one](https://data.sfgov.org/Public-Safety/Police-Department-Incident-Reports-Historical-2003/tmnf-yvry) for 2003-2018).The San Francisco Chronicle has created a [great map visualization](https://projects.sfchronicle.com/trackers/sf-car-breakins/) from this to track break-ins. We wanted to make this data even more actionable, to help asses the security of parking in a particular location in real-time.

Hence, the motivating question: if I am looking to park in SF, how can I get a sense of how safe my current spot is?

## Defining a Risk Score

Of course, the risk of a parking spot can be measured in many different qualitative and quantitative ways. We chose a quantitative measure, admittedly quite arbitrary, as the average inverse square of the distance between the parking location and every break-in location in the past year.

![image (1)](https://images.ctfassets.net/1d31s1aajogl/14z48ECo5RdF3LyTAQEwGp/16cfc8376d86c9b662f00d8447c7cea1/image__1_.png)

This just gives a numerical score. We then evaluate this score across a representative sample of parking spots across SF, and place the current parking spot at a percentile within that sample. The higher the score, the closer the spot is to historical incidents (inverse of distance), the higher the risk.

We’ll wrap this all in a simple mobile web app, so in you can open it from your car, press a button, and get a percentile of how secure your parking spot is.

![image (2)](https://images.ctfassets.net/1d31s1aajogl/4pyylPmgECB4tuLmN7F4TR/c5aef2c4c61066159aae6789b16cc57f/image__2_.png)

Now, we just have to use the data to compute the risk score percentile. For this task, we’ll load the SFPD data into a Rockset collection and query it upon a user clicking the button.

## Loading the Data

To get started quickly, we’ll simply download the data as a CSV and upload the file into a new collection.

![image (3)](https://images.ctfassets.net/1d31s1aajogl/6eQ5jGFJl65exKhbi3KV5O/98e2be05a8c7da7cc85e1a392489458c/image__3_.png)

Later, we can set up a periodic job to forward the dataset into the collection via the API, so that it always stays up to date.

## Filtering the Data

Let’s switch over to the query tab and try writing a query to filter down to the incidents we care about. There are a few conditions we want to check:

**Vehicle-related incidents.** Each incident has an “Incident Subcategory” assigned by the Crime Analysis Unit of the Police Department. We do a `SELECT DISTINCT` query on this field and scan the results to pick out the ones we consider vehicle-related.

  - Motor Vehicle Theft
  - Motor Vehicle Theft (Attempted)
  - Theft From Vehicle
  - Larceny - Auto Parts
  - Larceny - From Vehicle

![image (4)](https://images.ctfassets.net/1d31s1aajogl/4Onw198CgowVVE8SCt16Z6/b92dbd2a9da78a98fb066f3a72c676f5/image__4_.png)

- **Initial report.** According to the [data documentation](https://data.sfgov.org/Public-Safety/Police-Department-Incident-Reports-2018-to-Present/wg3w-h783), records cannot be edited once they are filed, so some records are filed as “supplemental” to an existing incident. We can filter those out by looking for the word “Initial” in the report type description.

![image (5)](https://images.ctfassets.net/1d31s1aajogl/3Fj8GSCVvQNPIthVKs3M67/85588b3eccb299bd8934aa06385aa6be/image__5_.png)

- **Within SF.** The documentation also specifies that some incidents occur outside SF, and that such incidents will have the value “Out of SF” in the police district field.

![image (6)](https://images.ctfassets.net/1d31s1aajogl/2DKfo7TasT6zfxyNJE5gZw/8ccfcc1b38471d2cee5897f5d09fd9bf/image__6_.png)

- **Last year.** The dataset provides a datetime field, which we can parse and ensure is within the last 12 months.

![image (7)](https://images.ctfassets.net/1d31s1aajogl/6cwl9kjufwQrCzPAgtX4ho/f5c2e23d66cb9716fc94e84229d0774b/image__7_.png)

- **Geolocation available.** We notice some rows are missing the latitude and longitude fields, instead having an empty string. We will simply ignore these records by filtering them out.

Putting all these conditions together, we can prune down from 242,012 records in this dataset to just the 28,224 relevant vehicle incidents, packaged up into a `WITH` query.

![image (8)](https://images.ctfassets.net/1d31s1aajogl/2447gpZL6dJp2zLNnm6L1v/76036b14c84c2733f632be114837101d/image__8_.png)

## Calculating a Risk Score, One Spot

Now that we have all vehicle incidents in the last year, let’s see if we can calculate the security score for San Francisco City Hall, which has a latitude of 37.7793° N and longitude of 122.4193° W.

Using some good old math tricks (radius times angle in radians to get arc length, approximating arc length as straight-line distance, and Pythagorean theorem), we can compute the distance in miles to each past incident:

![image 9](https://images.ctfassets.net/1d31s1aajogl/jIkNDW8IF2YY1uKffoJAi/f716733301f39cd878f56c74745531f9/image__9_.png)

We aggregate these distances using our formula from above, and voila!

![image (10)](https://images.ctfassets.net/1d31s1aajogl/4ztemVlqRHW2Ve5RbsHREZ/822daa21e732b866525a74961b02bdee/image__10_.png)

For our app, we will replace the latitude/longitude of City Hall with parameters coming from the user’s browser location.

## Sample of Parking Spots in SF

So we can calculate a risk score—1.63 for City Hall—but that is meaningless unless we can compare it to the other parking spots in SF. We need to find a representative set of all possible parking spots in SF and compute the risk score for each to get a distribution of risk scores.

Turns out, the SFMTA has exactly what we need—field surveys are conducted to count the number of on-street parking spots and their results are [published as an open dataset](https://data.sfgov.org/Transportation/On-street-Parking-based-on-Parking-Census/9ivs-nf5y). We’ll upload this into Rockset as well!

![image (11)](https://images.ctfassets.net/1d31s1aajogl/3LmqUAp8f6sSaC0DT88fEW/7356cfe587a64c25adc0f5daac32e261/image__11_.png)

Let’s see what this dataset contains:

![image 12](https://images.ctfassets.net/1d31s1aajogl/2SGnNv7s1NvEgk1hetZwNw/ab678ba8b0bff6396a1e4bbb1cfa4fbc/image__12_.png)

For each street, let’s pull out the latitude/longitude values (just the first point, close enough approximation), count of spots, and a unique identifier (casting types as necessary):

![image 13](https://images.ctfassets.net/1d31s1aajogl/2HcHZaoaWn2IofkjLdyc4E/729c9df35de62fc8146f37e8a5a108b7/image__13_.png)

## Calculating Risk Score, Every Spot in SF

Now, let’s try calculating a score for each of these points, just like we did above for City Hall:

![image 14](https://images.ctfassets.net/1d31s1aajogl/24f9gHCNt1B3gb4ks16gKs/7ed9901ffc9fce657322e86287d35726/image__14_.png)

And there we have it! A parking risk score for each street segment in SF. This is a heavy query, so to lighten the load we’ve actually sampled 5% of each streets and incidents.

(Coming soon to Rockset: geo-indexing—watch out for a blog post about that in the coming weeks!)

Let’s stash the results of this query in another collection so that we can use it to calculate percentiles. We first create a new empty collection:

![image (15)](https://images.ctfassets.net/1d31s1aajogl/2hh1DMQefrR7cnLxsnuRs6/43598f6aa8953109a78901178503a7a9/image__15_.png)

Now we run an `INSERT INTO sf_risk_scores SELECT ...` query, bumping up to 10% sampling on both incidents and streets:

![image (17)](https://images.ctfassets.net/1d31s1aajogl/30cftaWgbKF8cOJc9Gdjru/fbeb23885fe41d921197d19ce192d92d/image__17_.png)

## Ranking Risk Score as Percentile

Now let’s get a percentile for City Hall against the sample we’ve inserted into `sf_risk_scores`. We keep our spot score calculation as we had at first, but now also count what percent of our sampled parking spots are safer than the current spot.

![image 16](https://images.ctfassets.net/1d31s1aajogl/4u9R298T4GXo1WykVwPWgw/70702ed7259413311a3b935e5e676908/image__16_.png)

## Parking-Spot-Risk-Score-as-a-Service

Now that we have an arguably useful query, let’s turn it into an app!

We’ll keep it simple—we’ll create an AWS Lambda function that will serve two types of requests. On `GET` requests, it will serve a local `index.html` file, which serves as the UI. On `POST` requests, it will parse query params for `lat` and `lon` and pass them on as parameters in the last query above. The lambda code looks like this:

{% gist https://gist.github.com/julie-mills/a3e19f4eabe8b213274031ed590283e4 %}

For the client-side, we write a script to fetch the browser's location and then call the backend:

{% gist https://gist.github.com/julie-mills/3219a3879f417f288d4bf2a7960ca048 %}

We add some basic HTML elements and styling, and it’s ready to ship!

To finish it off, we add API Gateway as a trigger for our lambda and drop a Rockset API key into the environment, which can all be done in the AWS Console.

## Conclusion

To summarize what we did here:

- We took two fairly straightforward datasets—one for incidents reported by SPFD and one for parking spots reported by SFMTA—and loaded the data into Rockset.
- Several iterations of SQL later, we had an API we could call to fetch a risk score for a given geolocation. 
- We wrote some simple code into an AWS Lambda to serve this as a mobile web app.

The only software needed was a web browser (download the data, query in Rockset Console, and deploy in AWS Console), and all told this took less than a day to build, from idea to production. The source code for the lambda is available [here](https://github.com/rockset/recipes/tree/master/sf-parking).

If you park in SF, feel free to try out the app [here](https://rockset.com/sf-parking). If not, comment with what kind of real-life decisions you think could be improved with more data!