Kaelan Anderson
← Code

Preparing San Diego 311 Encampment Data for SaTScan

Tutorial · Python · 2025

This tutorial walks through the data preparation pipeline for running a space-time cluster analysis on publicly available 311 service request data from the City of San Diego. The data comes from the Homelessness Hub San Diego ArcGIS portal maintained by UC San Diego.

The goal is to take a raw CSV of encampment reports and produce the two input files that SaTScan requires: a case file (.cas) recording when and where reports occurred, and a geography file (.geo) mapping each location ID to its coordinates. Along the way, we will look at the data carefully enough to make defensible modeling decisions — and understand what we can and cannot conclude from the results.

Step 1 — Download and load the data

Download the dataset from the 311 Encampment Reports page. Click Download and choose the CSV option. I use the 2024 calendar year — a full year matters for building a clean temporal baseline. If you pull a multi-year file, everything below still applies, but pay attention to the study period at the end.

import pandas as pd import matplotlib.pyplot as plt CSV_PATH = "311_Encampment_Reports_2C_2024_2C_City_of_San_Diego.csv" df = pd.read_csv(CSV_PATH) print(df.shape) df.head()
(59059, 26)

Each row is one 311 report — not one encampment, and not one person. That distinction matters more than almost anything else here, and we will come back to it. For cluster detection, only three things matter from those 26 columns:

What SaTScan needsColumn in this dataset
When it happeneddate_requested
Where it happenedlat, lng
How many at that place and timecomputed by counting

The other columns — council_district, status, case_age_days — are useful for exploration and for interpreting results afterward, but they are not model inputs. Before discarding them, we will use them.

df.dtypes
x float64 y float64 service_request_id int64 service_request_parent_id float64 sap_notification_number float64 date_requested object case_age_days int64 case_record_type object service_name object service_name_detail float64 date_closed object status object lat float64 lng float64 street_address object zipcode float64 council_district float64 comm_plan_code float64 comm_plan_name object park_name object case_origin object referred object iamfloc object floc object public_description object ObjectId int64 dtype: object

Step 2 — Explore the data

Before writing any modeling code, it's useful to get a feel for what's actually in the dataset — what the columns contain, when reports came in, and where they're concentrated. Catching data issues early tends to be much easier than tracing them back from unexpected results later.

print(df["service_name"].value_counts()) print() print(df["status"].value_counts())
service_name Encampment 59059 Name: service_name, dtype: int64 status Closed 53133 Referred 5926 Name: status, dtype: int64

Every row is an Encampment report, so this particular export doesn't need any type-based filtering. We'll still write the filter explicitly below — if you re-download this dataset later and the city has folded in additional service types, the code will catch that rather than quietly including rows we didn't intend.

Now let's look at the temporal distribution.

dates = pd.to_datetime(df["date_requested"], utc=True).dt.date weekly = pd.Series(1, index=pd.to_datetime(dates)).resample("W").sum() fig, ax = plt.subplots(figsize=(9, 3.6)) ax.plot(weekly.index, weekly.values, color="#c0392b", lw=1.6) ax.set_title("311 Encampment Reports per Week, San Diego 2024", fontsize=13) ax.set_xlabel("week") ax.set_ylabel("reports") ax.spines[["top", "right"]].set_visible(False) ax.grid(alpha=0.25) plt.tight_layout() plt.show()
Plot image — save the figure and replace this block with an <img> tag pointing to it.

Reports range from roughly 60 to 1,570 per week — a twenty-six-fold swing within a single year.

Does that mean the number of encampments swung twenty-six-fold? Almost certainly not. Report volume responds to enforcement pushes, media coverage, weather, and outreach campaigns. What we are measuring is reporting behavior, which is related to the underlying phenomenon but is not the same variable. SaTScan will find clusters in whatever you give it — if you feed it reports, it finds clusters of reporting.

Now let's look at the geographic distribution — where are reports coming from?

# comm_plan_name has inconsistent casing ('Downtown' vs 'DOWNTOWN'). # .str.title() folds them together before counting. cp = df["comm_plan_name"].str.title().value_counts().head(12).sort_values() fig, ax = plt.subplots(figsize=(7.5, 4.6)) ax.barh(cp.index, cp.values, color="#2c3e50") ax.set_title("Top Community Plan Areas by Encampment Reports (2024)", fontsize=13) ax.set_xlabel("reports") ax.spines[["top", "right"]].set_visible(False) plt.tight_layout() plt.show()
Plot image — save the figure and replace this block with an <img> tag pointing to it.

Downtown accounts for over 20,000 reports — roughly a third of the city's total. Uptown, Mid-City: City Heights, and North Park follow at a distance.

This is worth keeping in mind for when we get to the SaTScan results. Downtown will likely show up as a cluster, partly just because it has so many reports. What SaTScan is actually asking is a more specific question: given how many reports this area typically generates, was there a particular stretch of time where it produced more than expected? That's different from simply having the highest total count — and it's what makes the method useful beyond what a bar chart already tells us.

Step 3 — Build the analysis dataset

Subset to encampment reports only, keep the three columns we need, and parse the date.

camp_data = df[df["service_name"].str.strip().str.lower() == "encampment"].copy() camp_data = camp_data[["service_request_id", "date_requested", "lat", "lng"]] print(camp_data.shape)
(59059, 4)
# Normalize to day resolution. # Timestamps are UTC ('2024/01/01 08:32:00+00'); utc=True makes that explicit. camp_data["date"] = pd.to_datetime(camp_data["date_requested"], utc=True).dt.date camp_data["date"] = pd.to_datetime(camp_data["date"]) camp_data = camp_data.drop(columns=["date_requested"]) camp_data.head()
service_request_id lat lng date 0 4563179 32.716936 -117.154526 2024-01-01 1 4563180 32.748568 -117.131777 2024-01-01 2 4563181 32.916662 -117.116820 2024-01-01 3 4563187 32.713853 -117.158849 2024-01-01 4 4563192 32.705174 -117.148147 2024-01-01

A subtle point: San Diego is 7–8 hours behind UTC. A report filed at 5 pm local on January 1st lands at 00:32 UTC on January 2nd, so a handful of reports get assigned to the next day. For day-resolution analysis over a full year this is negligible — but if you ever move to hourly analysis, convert to America/Los_Angeles first.

Step 4 — Clean coordinates

print("missing coordinates:", camp_data[["lat", "lng"]].isna().any(axis=1).sum()) camp_data = camp_data.dropna(subset=["lat", "lng"]) # Guard against (0, 0) 'null island' — a geocoding failure mode that lands a phantom # cluster in the Gulf of Guinea rather than producing a visible NaN. camp_data = camp_data[(camp_data["lat"] != 0) & (camp_data["lng"] != 0)] print(camp_data.shape)
missing coordinates: 17 (59042, 4)

Only 17 records are missing coordinates, so dropping them leaves 59,042. The null-island filter finds nothing here, but it's a useful habit. Some geocoders return (0, 0) on failure instead of NaN, which means a broken coordinate can pass a range check and show up as a point in the Gulf of Guinea. Checking for it explicitly costs nothing.

Step 5 — Decide what counts as "the same place"

SaTScan doesn't take a list of raw GPS points. It needs a defined set of locations — each with a stable ID and a single coordinate pair — plus a separate table counting how many cases occurred at each location on each date. So before we can build those files, we need to decide when two reports should be treated as happening at "the same place."

The practical lever is coordinate precision. Decimal degrees of latitude translate to ground distance roughly like this:

Decimal placesApprox. resolution
6~10 cm
5~1 m
4~11 m
3~110 m

Let's see what each precision level does to the number of distinct locations.

for p in [6, 5, 4, 3]: n = ( camp_data.assign(a=camp_data["lat"].round(p), b=camp_data["lng"].round(p))[["a", "b"]] .drop_duplicates() .shape[0] ) print(f"{p} decimals -> {n:6,d} locations, {len(camp_data)/n:5.2f} reports per location")
6 decimals -> 56,470 locations, 1.05 reports per location 5 decimals -> 53,951 locations, 1.09 reports per location 4 decimals -> 31,095 locations, 1.90 reports per location 3 decimals -> 8,337 locations, 7.08 reports per location

At 6 decimal places, nearly every report becomes its own unique location. Two calls about the same spot, geocoded a few centimeters apart, get treated as separate places — which means we're throwing away the repeat signals that cluster detection is looking for.

At 3 decimal places, 110 meters covers more than a city block in a dense area like Downtown, so we end up merging distinct locations and inflating counts in ways that aren't really there.

Four decimal places (~11 m, roughly one address width) sits in a reasonable middle: 31,095 locations averaging 1.9 reports each. I'll use 4 here, though it's worth noting this is a modeling choice that affects results, not a fixed rule.

One way to check this: run the full analysis at COORD_PRECISION = 4 and then again at 3. Clusters that appear at both precisions are more likely to reflect something real. Clusters that show up at one but not the other are worth flagging as potentially sensitive to this choice.

COORD_PRECISION = 4 camp_data["latitude"] = camp_data["lat"].round(COORD_PRECISION) camp_data["longitude"] = camp_data["lng"].round(COORD_PRECISION) camp_data = camp_data.drop(columns=["lat", "lng"]) # Assign a stable integer ID to each distinct coordinate pair unique_coords = ( camp_data[["latitude", "longitude"]] .drop_duplicates() .sort_values(["latitude", "longitude"]) .reset_index(drop=True) ) unique_coords["location_id"] = range(1, len(unique_coords) + 1) camp_data = camp_data.merge(unique_coords, on=["latitude", "longitude"], how="left") print("unique locations:", len(unique_coords)) camp_data.head()
unique locations: 31095 service_request_id date latitude longitude location_id 0 4563179 2024-01-01 32.7169 -117.1545 8111 1 4563180 2024-01-01 32.7486 -117.1318 15707 2 4563181 2024-01-01 32.9167 -117.1168 30323 3 4563187 2024-01-01 32.7139 -117.1588 6383 4 4563192 2024-01-01 32.7052 -117.1481 2392
counts = camp_data.groupby("location_id").size().rename("n").reset_index() geo = unique_coords.merge(counts, on="location_id").sort_values("n") fig, ax = plt.subplots(figsize=(6.4, 6.8)) sc = ax.scatter(geo["longitude"], geo["latitude"], c=geo["n"], s=4 + geo["n"] * 1.2, cmap="inferno_r", alpha=0.75, linewidths=0, vmin=1, vmax=20) ax.set_title("Encampment Reports by Location, 2024", fontsize=13) ax.set_xlabel("longitude") ax.set_ylabel("latitude") ax.set_aspect(1 / 0.84) cb = fig.colorbar(sc, ax=ax, shrink=0.6) cb.set_label("reports at location (capped at 20 for color scale)") ax.spines[["top", "right"]].set_visible(False) plt.tight_layout() plt.show() print("most reports at one location:", geo["n"].max())
Plot image — save the figure and replace this block with an <img> tag pointing to it.
most reports at one location: 211

Even without a basemap, the shape of San Diego comes through in the point density. The concentrated cluster in the southwest is Downtown; you can also see corridors running east along the I-8 and El Cajon Blvd. The single busiest location had 211 reports over the year — roughly one every 1.7 days, all year, from the same ~11 m patch. That could be a persistently occupied site, or it could be a single frequent caller. It's useful to know which before reading too much into any cluster centered there.

Step 6 — Build the case file (.cas)

The case file records counts by (location, date). We aggregate all individual reports down to that grain.

aggregated_df = camp_data.groupby(["date", "location_id"]).size().reset_index(name="cases") aggregated_df = aggregated_df.sort_values(["date", "location_id"]) aggregated_df["case_id"] = range(1, len(aggregated_df) + 1) cas_df = aggregated_df[["case_id", "date", "cases", "location_id"]].copy() cas_df["date"] = cas_df["date"].dt.strftime("%Y/%m/%d") print(cas_df.shape) print("total cases:", cas_df["cases"].sum()) print("rows with more than one case:", (cas_df["cases"] > 1).sum()) cas_df.head()
(55784, 4) total cases: 59042 rows with more than one case: 2636 case_id date cases location_id 0 1 2024/01/01 1 974 1 2 2024/01/01 1 2086 2 3 2024/01/01 1 2261 3 4 2024/01/01 1 2390 4 5 2024/01/01 1 2392

55,784 rows covering 59,042 cases. Only 2,636 rows have a count above 1, so same-day repeat reports at the same spot are relatively uncommon.

It's worth pausing on what those multi-case rows represent. If three people call about the same tent on the same afternoon, this aggregation records 3 cases at that location that day, not 1. Whether that's the right framing depends on the research question: three calls could be three independent signals of community concern, or they could be one tent counted three times. There's no universal right answer — just make the choice deliberately and note it.

import os OUT_DIR = "satscan_usable" os.makedirs(OUT_DIR, exist_ok=True) cas_path = os.path.join(OUT_DIR, "2024_camps.cas") cas_df.to_csv(cas_path, index=False, header=True) print("wrote", cas_path)
wrote satscan_usable/2024_camps.cas

Step 7 — Build the geography file (.geo)

The geography file is the lookup table: one row per location ID with its coordinates. Every location referenced in the .cas file must appear here, or SaTScan will refuse to run.

geo_df = ( camp_data[["location_id", "latitude", "longitude"]] .drop_duplicates(subset=["location_id"]) .sort_values("location_id") ) # Sanity-check coordinate ranges before writing if not ((geo_df["latitude"].between(-90, 90)) & (geo_df["longitude"].between(-180, 180))).all(): raise ValueError("Invalid coordinates found.") geo_path = os.path.join(OUT_DIR, "2024_camps.geo") geo_df.to_csv(geo_path, index=False, header=True) print(geo_df.shape) geo_df.head()
(31095, 3) location_id latitude longitude 55899 1 32.5434 -117.0340 5186 2 32.5436 -117.0512 30357 3 32.5436 -117.0510 15248 4 32.5436 -117.0502 6628 5 32.5436 -117.0499

Step 8 — Validate before handing off

SaTScan's error messages can be sparse, and some failures are silent — the run completes but the results are wrong. Running a few assertions here is much easier than trying to trace a problem back from a suspicious cluster. Four things should hold: coordinates map one-to-one with location IDs, no ID is duplicated, every location in the case file exists in the geography file, and the total case count survived aggregation without any rows being added or dropped.

# Coordinates map 1:1 with location IDs, no duplicates in either direction assert not geo_df.duplicated(subset=["latitude", "longitude"]).any(), "duplicate coordinate pairs" assert not geo_df.duplicated(subset=["location_id"]).any(), "duplicate location_ids" # Referential integrity: every location in .cas must exist in .geo assert set(cas_df["location_id"]).issubset(set(geo_df["location_id"])), \ "cas references unknown locations" # Conservation: no cases invented or lost during aggregation assert cas_df["cases"].sum() == len(camp_data), "case count does not match record count" check = camp_data.groupby(["date", "location_id"]).size().reset_index(name="expected") check["date"] = check["date"].dt.strftime("%Y/%m/%d") merged = check.merge(cas_df, on=["date", "location_id"], how="inner") assert len(merged) == len(cas_df) and (merged["expected"] == merged["cases"]).all(), \ "count mismatch between source and cas" print("All checks passed.") print(f" {len(geo_df):,} locations") print(f" {len(cas_df):,} case rows") print(f" {cas_df['cases'].sum():,} total cases")
All checks passed. 31,095 locations 55,784 case rows 59,042 total cases
from datetime import datetime min_date, max_date = cas_df["date"].min(), cas_df["date"].max() start = datetime.strptime(min_date, "%Y/%m/%d") end = datetime.strptime(max_date, "%Y/%m/%d") print(f"Study Period Start: {min_date}") print(f"Study Period End: {max_date}") print(f"Total days: {(end - start).days + 1}")
Study Period Start: 2024/01/01 Study Period End: 2024/12/31 Total days: 366

366 days — 2024 was a leap year. Note these dates down; you'll enter them manually in SaTScan and it won't warn you if they're wrong.

Step 9 — Configure and run SaTScan

Download SaTScan free from satscan.org. Create a new session and point it at the two files we produced.

Input tab

Analysis tab

The Space-Time Permutation model is the right choice here because we have no denominator — no population-at-risk data to convert raw counts into rates. Most SaTScan models require one. Space-Time Permutation sidesteps the issue by using the data as its own control: given how many reports this location produced all year, and given how many reports the whole city produced during this time window, is the count in this place during this window surprising? No external denominator required.

Under Output, enable the Google Earth / KML export to see clusters on a map. The default maximum spatial cluster size (50% of the population) is usually too permissive — try 10% under the Spatial Window tab. Under Temporal Window, 30 days is a reasonable starting point if you're hunting for acute flare-ups rather than season-long shifts.

Step 10 — Read the output honestly

SaTScan returns a ranked list of clusters — each with a center, radius, date range, observed-to-expected ratio, and p-value. A few things are worth understanding before drawing conclusions from those results.

The p-values come from Monte Carlo simulation. SaTScan repeatedly shuffles the data and measures how often a cluster as extreme as the one found would appear by chance. That's a well-founded approach, but what it's testing is narrow: no space-time interaction, given the observed margins. A low p-value doesn't mean the cluster represents an encampment hotspot — it means the pattern is unlikely under a specific null model applied to whatever data you fed in.

Clusters of reports are not necessarily clusters of encampments. Reporting behavior is shaped by many things beyond encampment presence — outreach campaigns, media coverage, neighborhood organization, and whether residents feel that calling 311 leads to any response. Areas with lower reporting rates may have just as many encampments but less trust in the system, or fewer people who know the service exists.

Some clusters reflect city activity, not underlying conditions. An enforcement sweep in a particular district in March will likely produce a cluster there in March. That's a real pattern in the data — but it's a cluster of city operations. Cross-referencing results with the city's outreach calendar and local news for that period can help distinguish those cases from others.

Space-time cluster analysis is exploratory. It's useful for generating hypotheses and flagging areas that warrant closer attention — not for confirming that something definitively happened. Treating the top-ranked cluster as a conclusion, rather than a starting point for further investigation, tends to overstate what the method can actually show.

It's also worth keeping in mind that this dataset is about unhoused people. The same map could inform services and outreach, or it could be used to direct enforcement. That's not a question the analysis answers — it's a decision about how the results get used.

Extensions and next steps

Once you have baseline results, here are worthwhile directions to push on: