# City limits: `city-bounds.bin`

Passport One draws a selected city's **legal municipality** (Madrid's 604 km² municipio, Paris's 105 km² commune), not its metro area, when it has one. This folder holds the script that builds that file, and this README is the description of the derived database that the ODbL asks for.

## Licence

`App/Resources/city-bounds.bin` is a **derived database of OpenStreetMap data**, taken through Overture Maps Foundation's `divisions` theme (release recorded in `city-bounds-meta.json`, currently `2026-11-18.0`).

- © OpenStreetMap contributors. Available under the Open Database License (ODbL) 1.0: https://opendatacommons.org/licenses/odbl/1-0/ — https://www.openstreetmap.org/copyright
- Overture Maps Foundation divisions, ODbL 1.0: https://docs.overturemaps.org/attribution/
- New Zealand: 79 of the 34,321 outlines (P24 build; 34,451 since P25), all in New Zealand, are Land Information New Zealand (LINZ) geometry that Overture carries under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Overture's attribution page asks for the credit; the app shows "New Zealand city limits: LINZ, CC BY 4.0" in Settings ▸ Data sources.
- The join keys come from Wikidata (CC0) and GeoNames ids (the GeoNames data itself, CC BY 4.0, lives in `places.json`, not in this file).

`city-bounds.bin` is deliberately a **separate file** from `places.json` (GeoNames, CC BY 4.0) and `countries-shapes.json` / `regions-shapes.json` (Natural Earth, public domain). No geometry from those files is mixed into it, so they remain independent databases in a collective work and keep their own licences.

**Share-alike, in plain words.** Anyone who receives the app may ask for this derived database. ODbL §4.6 is satisfied by offering either the database itself (`city-bounds.bin`, under ODbL) or this script plus the public inputs it reads. The app shows "© OpenStreetMap contributors, ODbL" in Settings ▸ Data sources, with a link to the published database; see "Publishing" below.

## Rules (what counts as a city's outline)

For each of the 64,901 cities in `places.json` (P25, D135; 64,771 in P24, D132):

1. **Candidates**, best first:
   - `own`: an Overture division (locality, localadmin, county or region) whose Wikidata id is the city's own item (Wikidata `P1566` = the GeoNames id).
   - `p1376`: an item the city is the capital of (Wikidata `P1376`), e.g. Madrid `Q116170766` → municipio `Q2807`. Only Overture **locality / localadmin** and only when the names match.
   - `p131`: the item the city lies in (Wikidata `P131`), e.g. Coslada `Q24012750` → municipio `Q164197`. Same limits as `p1376`.
   - `name`: an Overture locality / localadmin in the same country with the same folded name (diacritics and "city of" stripped). Used for ids with no Wikidata link (Barcelona).
   Counties and regions are accepted **only** as the city's own item (city-states such as Berlin, Vienna, Seoul, Tokyo Metropolis); a walk never climbs to a parent region or country.
2. **Checks** on every candidate (the first that passes wins):
   - the GeoNames point lies inside the outline (`name`), or inside or within 1 km (`own`, `p1376`, `p131`);
   - area ≤ 3,000 km² (Beijing, Chongqing, Shanghai municipalities keep the circle);
   - if area > 100 km², at least 5 people per km² (huge rural municipalities keep the circle);
   - (P25, D135) a **hole place** (below) keeps its `own` outline below this density floor (a rural hole: Herlitzka, AR), and its `own` item may be a neighbourhood-type division when `hole_places.py` accepted it as a Wikidata populated place; nothing changes for other cities;
   - area < 0.8 × the city's admin-1 region (Natural Earth, `regions-shapes.json`) unless the outline is the city's own item; those ids are listed in `city_states` in the meta file;
   - parts more than 100 km from the city point are dropped (Tokyo's Ogasawara islands).
3. **One outline, one city.** If two cities resolve to the same outline, the one whose name matches it keeps it (then the better candidate kind, then the larger population); the others keep the circle.
4. **Simplification:** Douglas–Peucker, 0.0009° (~100 m) tolerance, topology preserved; parts and holes under 0.01 km² dropped. Area is computed on a local equirectangular projection.

## Holes and the places in them (P25, D135)

An outline can have **holes**: enclaves that are another place (Beverly Hills and West Hollywood in Los Angeles, Bexley in Columbus). The app never gives a tap in a hole to the surrounding city (D131), so each hole needs its own city. Marina del Rey, an unincorporated community in a hole of Los Angeles, had none: GeoNames codes it a "section of a populated place", which the places data drops.

`hole_places.py` (run with the same Overture divisions and Wikidata TSVs as the build) lists, for every hole that other outlines cover less than 90 % of, the Overture division that fills it: not a county, filling at least 50 % of the hole and lying at least 80 % inside it. A `locality` or `localadmin` counts; a neighbourhood-type division counts only when its Wikidata item is a populated place (census-designated place, unincorporated community, village, town or city, and not a neighbourhood, suburb or quarter). The division's Wikidata item gives the GeoNames ids (`P1566`). The list, `data-tools/places/hole-places.tsv`, holds only those ids and names. `Scripts/build-places.py` adds each place from GeoNames (`allCountries`, populated places only) as a city, and the build above gives it its `own` outline. No geometry goes into `places.json`. Fillers without a GeoNames id are never given one; their holes stay without a city. The list only grows (a rerun keeps earlier rows, whose holes the new outlines then cover).

```
.venv/bin/python hole_places.py --bounds ../../App/Resources/city-bounds.bin --places ../../App/Resources/places.json \
  --overture <dir with division/ and division_area/> --wikidata <dir with the TSVs> --out ../places/hole-places.tsv
```

P25 (seeded from the 2026-11-22 audit of the shipped file): 168 holes whose place was added (130 distinct cities after the GeoNames check: US 105, RU 9, NL 8, CZ 3, ES 2, AR, IL, TR 1 each), 12 whose place was already a city, 78 fillers with no GeoNames id, 38 whose Wikidata GeoNames id is an administrative division rather than a populated place (not added).

## Data checks (P25, D135)

`invariants.py` runs at the end of every build (and alone: `invariants.py --bounds … --places …`) and fails the build when:
- (a) an outline's id isn't a city in `places.json`, or a hole has no city: the hole's interior point (a fixed scan-line rule on the stored integer coordinates) lies in no outline;
- (b)/(c) a city with an outline can't be picked inside it: none of its interior points lies in no other outline, or has it as the innermost (smallest) containing outline;

except what the **baselines** list: `holes-without-city.tsv` and `unselectable-cities.tsv`. A baseline never grows (`--write-baselines` refuses to raise a count without `--allow-growth`, which needs the owner's approval). The app's unit tests (`DataInvariantTests`) run the same rules on the bundled files, with the app's own resolver for (b).

Counts (P25 rebuild, Overture 2026-11-18.0): **34,451 outlines** for 64,901 cities (all 130 hole places have one), 21,408 hole rings, 865 of them zero-area slivers (no inside to tap), **19,995 holes without a city** (20,120 of 21,401 before the rebuild), 6 cities no point selects (New York City under its boroughs, Warsaw under its districts, Charleroi, Zaanstad, Dison, Colfontaine). Holes are the open coverage question; the baseline makes them visible, and each rebuild should lower it.

## File format (`PCB1`, little-endian)

- Header, 12 bytes: magic `PCB1`, `UInt32 count`, `UInt32 reserved = 0`.
- Index, `count` × 32 bytes, sorted by GeoNames id: `UInt32 id`, `Int32 minLon, minLat, maxLon, maxLat` (degrees × 100,000), `UInt32 offset`, `UInt32 length` (into the geometry blob that follows the index), `Float32 areaKm2`.
- Geometry: `UInt16 polygons`; per polygon `UInt16 rings` (ring 0 outer, counter-clockwise; holes clockwise); per ring `UInt32 vertices`, first vertex `Int32 lon, Int32 lat` (× 1e-5°), then `vertices − 1` pairs of zig-zag LEB128 varint deltas (lon, lat). Rings are not closed.

Side files written next to it: `city-bounds-meta.json` (licence, release, counts, match rates, reject counts, `city_states`) and `city-bounds-index.csv` (per outline: GeoNames id, name, candidate kind, Overture division id, Wikidata id, OSM relation, area, vertices).

## Rebuild

Inputs (all public):
- Overture `divisions` release, types `division` and `division_area` (about 4.6 GB): `s3://overturemaps-us-west-2/release/<release>/theme=divisions/type=division{,_area}/` (anonymous S3, region us-west-2).
- Wikidata TSVs from the QLever endpoint `https://qlever.dev/api/wikidata` (`Accept: text/tab-separated-values`):
  - `wikidata-gn.tsv`: `SELECT ?gn ?item WHERE { ?item wdt:P1566 ?gn }`
  - `wikidata-p1376.tsv`: `SELECT ?gn ?osm ?muni ?place WHERE { ?place wdt:P1566 ?gn . ?place wdt:P1376 ?muni . ?muni wdt:P402 ?osm }`
  - `wikidata-p131.tsv`: `SELECT ?gn ?osm ?muni ?place WHERE { ?place wdt:P1566 ?gn . ?place wdt:P131 ?muni . ?muni wdt:P402 ?osm }`
  (prefix `wdt:` = `http://www.wikidata.org/prop/direct/`)
- `App/Resources/places.json` and `App/Resources/regions-shapes.json` from this repo.

```
python3 -m venv .venv && .venv/bin/pip install duckdb shapely numpy pyarrow
.venv/bin/python build_city_bounds.py --places ../../App/Resources/places.json \
  --regions ../../App/Resources/regions-shapes.json --overture <dir with division/ and division_area/> \
  --wikidata <dir with the three TSVs> --release 2026-11-18.0 --out build
cp build/city-bounds.bin build/city-bounds-meta.json ../../App/Resources/
```
Takes about 3 minutes and 6 GB of RAM. The build ends with the data checks (above) against `--baseline-dir` (this folder); after a rebuild that lowers a count, run once with `--write-baselines` and commit the baselines with the file.

## Publishing

Published at **https://sypnapse.com/passportone/data/** (P20, RELEASE §6b #4): `city-bounds.bin`, `city-bounds-meta.json`, this README and the build script, under ODbL 1.0, so anyone who has the app can get the derived database. This README is the page's text source: keep it accurate when the data or the script changes, and republish with every rebuilt `city-bounds.bin`.

The app links to the page from Settings ▸ Data sources ("Get the city-boundary data (ODbL)", right after the OpenStreetMap credit). The URL is written once, in `Core/About/AboutLinks.swift` (`AboutLinks.cityBoundaryData`).
