Picking an H3 Cell Size with MAUP, and Crossfiltering AIS Pings with DuckDB-WASM
I have a week of AIS vessel pings from NOAA MarineCadastre: 48,734,843 rows from 20,234 vessels in US waters, 2020-01-01 to 2020-01-07. I wanted two things from it. First, a map of pings per H3 cell where the cell size is chosen by a number, not by my eye. Second, a page where I put the pointer on a day and an hour, and the map shows the pings of that hour, instantly, in the browser. This post covers both. All the aggregation runs in DuckDB, on my laptop for the build and in the browser (as WebAssembly) for the interactive views. The source is on GitHub: mraad/heatmap.
The data
An AIS ping is one row in the NOAA CSV: one vessel position (LAT, LON) at one time (BaseDateTime, UTC), with the vessel id (MMSI). NOAA publishes one zip per day at https://coast.noaa.gov/htdata/CMSP/AISDataHandler/<year>/AIS_YYYY_MM_DD.zip, about 250 MB zipped and 700 MB as CSV. The format is the same from 2015 to 2024. The repo has a small script that downloads the week:
export AIS_DIR=/path/to/AIS # optional, default is ./data
zsh fetch_ais_week.sh
uv run heatmap_marginals.py
uv run build_h3.py
uv run build_points.py
Each Python script has a PEP 723 header, so uv run brings DuckDB, Altair and Pandas with it. One gotcha: AIS uses latitude 91 and longitude 181 for "not available". H3 does not reject these values. It hashes them to a valid but wrong cell. So the build deletes pings outside −90..90 and −180..180 before anything else.
Day by hour first
The first view is the simple one: pings per day of week and hour, with marginal bars. DuckDB does the counting (isodow(BaseDateTime), hour(BaseDateTime), count(*)), and Altair draws the chart. The script asserts that the day totals and the hour totals both equal the row count before it plots anything.
Be careful reading this chart. The hourly totals are almost equal (1,952,543 to 2,106,562), and viridis stretches that small range over all its colors. Small differences look large. The dark Monday cells are real, though: they are gaps in the NOAA files, not quiet hours at sea.
How big should an H3 cell be?
H3 is a global grid of hexagons, from resolution 0 (huge) to 15 (tiny). Each step down splits a cell into about 7 children. Choose a large cell and the map becomes a smooth blob. Choose a small cell and most cells hold 1 ping, so there is no pattern to see. This is the Modifiable Areal Unit Problem (MAUP): the result changes with the size of the unit. Instead of picking a resolution by eye, I give each candidate resolution r (2 to 9) a score from two competing metrics.
V, point count variety, favors large cells. Put each cell count n in a log2 class, floor(log2(n)), take the Shannon entropy of the classes, and divide by log2 of the number of classes. V is low when almost every cell holds 1 ping.
P, pattern preservation, favors small cells. I use resolution 11 as a fine reference grid (about 29 m edge, close to AIS GPS precision). Replace each reference cell count with the mean of its parent cell at resolution r. P is the share of the sum of squares that stays:
P(r) = Σ n_r² / ( 7^(11 − r) · Σ n_11² )
P is 1 at resolution 11 and drops about 7 times per coarser level, so I use log10(P). Then I min-max scale V and log10(P) to 0..1 over the candidates and multiply: Score = Vn × Pn. The product is 0 at both ends, so only a balance scores high. In DuckDB the whole thing is one query over parent cells:
SELECT r, count(*) AS cells,
entropy(floor(log2(n))::INT) / log2($k) AS V,
log10(sum(n * n) / (pow(7, $ref - r) * $ss)) AS logP
FROM g GROUP BY r ORDER BY r
| Res | Cells | V | log10 P | Score |
|---|---|---|---|---|
| 4 | 5,976 | 0.875 | −3.68 | 0.251 |
| 5 | 24,469 | 0.806 | −3.24 | 0.316 |
| 6 | 96,307 | 0.718 | −2.72 | 0.352 |
| 7 | 357,136 | 0.612 | −2.22 | 0.319 |
| 8 | 1,162,998 | 0.477 | −1.70 | 0.203 |
Resolution 6 wins (cells of about 36 km²). One day of data alone also picks resolution 6. One detail matters here: H3 children do not tile their parent exactly. If I hash the points again at resolution 6, I get a different cell count (37,298 against 38,314 for one day) than the parent method that the score uses. So the map uses the parent of each resolution-11 cell too, and its cell count matches the score table.
The H3 map: GeoParquet into ArcGIS
The build writes the 96,307 cells as GeoParquet: DuckDB spatial writes the polygon as WKB plus the geo metadata. The file is 5.3 MB. For one day, the same cells were 9.6 MB as GeoJSON and 2.1 MB as gzip Parquet. The map is a VanillaJS page on the ArcGIS Maps SDK for JavaScript 5.2 with a ParquetLayer and a class-breaks renderer on quantiles of the ping count.
Three things cost me time, so here they are:
ParquetLayerreads the file with HTTP Range requests.python3 -m http.serverignores Range, and the layer fails withFailed to parse file. The repo has a small standard-libraryserve.pythat answers 206 Partial Content.- The layer rejects zstd. Use gzip or snappy.
- With geometry auto-detection from the
geometadata, the layer loads and every geometry isnull. Set it explicitly:
new ParquetLayer({
data: new ParquetFilesData({ urls: [new URL("./cells.parquet", location.href).href] }),
geometryEncoding: { type: "wkb", field: "geometry" },
geometryType: "polygon",
spatialReference: { wkid: 4326 },
renderer: { type: "class-breaks", field: "pings", classBreakInfos }
});
Now the best part: crossfilter in the browser
A crossfilter is a set of linked charts: a selection in one chart filters the data of the others. I wanted the heatmap, the two bar charts and a map linked this way, with hover on a heatmap cell highlighting its pings. I built it two ways, and both run DuckDB-WASM, which is DuckDB compiled to WebAssembly. It reads Parquet over HTTP Range requests and runs SQL in a browser worker.
The browser cannot take 48.7 million rows, so build_points.py writes one row per H3 cell, day of week and hour (I call this a slice): cell center lon/lat, dow, hour, and the count n. Which resolution? The same MAUP score, but over slices, because the apps filter by day and hour. Resolution 7 wins with 2,040,988 rows, a 15.6 MB file. To be honest, resolution 6 is in a tie: 0.352 against 0.352. More data can flip it. I also dropped the WKB column from this file. ParquetLayer can read points straight from two columns with geometryEncoding: { type: "location", xField: "lon", yField: "lat" }, and that halved the file.
Version 1: Mosaic
Mosaic (Heer and Moritz, IEEE VIS 2023) links views by sending each filter and aggregate to DuckDB as SQL, so the charts never hold the raw rows. The whole app is vgplot: rectY bars with intervalX, a cell heatmap, rectX bars with intervalY, and two raster marks on lon/lat for the map, one filtered by the crossfilter selection and one by the hover selection.
vgplot 0.35.1 fought me in three places. The interval and nearest interactors call scale.invert(), which band scales do not have (t.invert is not a function), so the bars use linear scales with x1: hour, x2: hour + 1 and the heatmap hover is my own pointermove handler. A raster over zero rows throws, so the hover selection cannot select "nothing", and a CSS rule hides the highlight layer instead. And linear density only shows the ports, so the opacity is ln(1 + sum(n)) per pixel. The Mosaic map has no basemap; the coasts appear from the pings themselves.
Version 2: ArcGIS Maps SDK
Here DuckDB-WASM runs three queries per change (pings per hour, per day, per day and hour) and a few lines of SVG draw the charts. Each bar chart ignores its own brush, so it still shows what you can select. The map is a ParquetLayer on the same file, drawn with WebGL2. The interaction maps to two layer view properties, so the data is never loaded again:
// brush on a bar chart
lv.filter = { where: "hour BETWEEN 8 AND 12" };
// pointer on a heatmap cell
lv.featureEffect = {
filter: { where: "dow = 1 AND hour = 12" },
includedEffect: "bloom(1.5, 0.5px, 0.1)",
excludedEffect: "opacity(10%)"
};
The map talks back too: when the view stops moving, its extent becomes a lon/lat clause in the chart queries, so the heatmap counts only what you see. Zoom into Houston and the charts recount the Gulf in about 20 ms.
| ArcGIS app (headless Chrome, software WebGL) | Value |
|---|---|
| Load DuckDB-WASM, SDK and 2,040,988 rows | 1.6 to 2.0 s |
| Three chart queries, initial view (zoom 4) | 80 to 83 ms |
| Three chart queries, hours 8 to 12 brushed | 33 to 34 ms |
| Three chart queries, zoomed to Houston | 21 ms |
These numbers come from my Playwright checks with SwiftShader, which is software rendering. A real GPU will draw the hover faster. I did not measure that.
What this does and does not show
- The MAUP score depends on the candidate range. Min-max scaling over 2..9 picked 6; a different range can pick something else. Resolutions 5 and 7 are within 0.04.
- The crossfilter apps show slice centers, not raw pings. That is the price of putting a week in a browser tab.
- The ArcGIS app reads the Parquet file twice, once in DuckDB-WASM and once in
ParquetLayer. - Everything loads from CDNs (the SDK, Mosaic, DuckDB-WASM), so the pages need a network connection.
Next, I want to try a month of data, to see how far DuckDB-WASM goes before the slices must get coarser, and to check whether the res 6 / res 7 tie settles. The code, the data download script and a full STE100-style README are at github.com/mraad/heatmap. Run python3 serve.py and open http://localhost:8765/ to pick a view. More to come.
Comments