maps: add a POI spatial grid and word-level name index
- Commit
c675940f083457f4ec7fbbf239605fe4c3bcbd10- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-24 21:10 UTC (3 months ago)
- Parents
40193ff
Diff
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 06ceff580c..6263f817dc 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -102,6 +102,14 @@ class MainActivity : ComponentActivity() { // itself treats the file as optional, so a device that somehow // lacks it degrades to no attributes rather than breaking. Triple("https://data.vayunmathur.com/poi_attrs.bin", "poi_attrs.bin", getString(R.string.downloading_poi_data)),+ // The two POI lookup indexes: a spatial grid so a tap or a viewport+ // refresh is cell-local, and a word index so name search is a binary+ // search. Same hosting order hazard as the sidecar above — both must+ // be published before this version ships. Both are optional to+ // PoiIndex, which falls back to the Morton walk and the name scan, so+ // a device that ends up without them is slow rather than broken.+ Triple("https://data.vayunmathur.com/poi_spatial.bin", "poi_spatial.bin", getString(R.string.downloading_poi_data)),+ Triple("https://data.vayunmathur.com/poi_name_index.bin", "poi_name_index.bin", getString(R.string.downloading_poi_data)), Triple("https://data.vayunmathur.com/world.transit", "world.transit", getString(R.string.downloading_transit_data)) )) { val perms = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.ktindex cf6e30db8d..fd3dacdf74 100644--- a/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt+++ b/maps/src/main/java/com/vayunmathur/maps/util/PoiIndex.kt@@ -20,30 +20,39 @@ import java.nio.channels.FileChannel * `{ int32 lat_e7; int32 lon_e7; uint32 name_off; uint16 type }`, * `count = filesize / 14`, sorted ascending by the 64-bit Morton(lat,lon) * key (the key itself is not stored — [spatialFromE7] recomputes it).- * * `poi_attrs.bin` — OPTIONAL attribute sidecar (opening hours, phone,+ * * `poi_attrs.bin` - OPTIONAL attribute sidecar (opening hours, phone, * website, address, cuisine, wheelchair), indexed by the ORDINAL of the * matching `poi_index.bin` record. See `scripts/maps/osm_ingest/src/poi_attrs.rs` * for the layout.+ * * `poi_spatial.bin` - OPTIONAL sparse CSR lat/lon grid over record ordinals, so+ * a bbox query visits only the cells it overlaps.+ * * `poi_name_index.bin` - OPTIONAL word index: one `(record, word)` entry for+ * every word of every name, sorted by word, so name search is a binary search.+ * Both are laid out in `scripts/maps/osm_ingest/src/poi_side.rs`. *- * It exposes a name search (prefix/substring over the deduped name pool) and a- * spatial nearest lookup, so a POI query can resolve locally without a Google- * call. Everything is a harmless no-op until both files are present (they ship- * from the same host as the graph); queries then return empty lists. The sidecar- * is separately optional: an install that has the index but not the attributes- * keeps working, and every attribute reads as null.+ * It exposes a name search and a spatial nearest lookup, so a POI query can resolve+ * locally without a Google call. Everything is a harmless no-op until the index and+ * the name pool are present (they ship from the same host as the graph); queries then+ * return empty lists. The three side files are each separately optional, and each is+ * refused rather than trusted when its record count disagrees with the index — they+ * all join by ordinal, so a stale one would return the wrong place rather than none. *- * **The spatial queries binary-search; they do not scan.** They used to walk all- * `count` records, which was imperceptible over a California extract and ANR'd the- * app on a planet-wide one — 22.6 M records on the main thread inside a tap- * handler. `poi_index.bin` was already sorted by Morton key; this reader simply- * never used it. See [Mapped.forEachInBbox] for the bound that replaced the scan,- * and its caveat.+ * **Nothing here scans the dataset.** Every lookup used to walk all `count` records,+ * which was imperceptible over a California extract and ANR'd the app on a planet-wide+ * one - 22.6 M records on the main thread inside a tap handler. Now:+ *+ * * bbox queries go through the grid, or fall back to a Morton-span walk of the+ * already-sorted `poi_index.bin` — see [Mapped.forEachInBbox] and its caveat;+ * * name search goes through the word index, or falls back to the two-pass scan.+ * The two differ deliberately; [searchByName] says how. */ object PoiIndex { private const val TAG = "PoiIndex" const val INDEX_FILE = "poi_index.bin" const val NAMES_FILE = "poi_names.bin" const val ATTRS_FILE = "poi_attrs.bin"+ const val SPATIAL_FILE = "poi_spatial.bin"+ const val NAME_INDEX_FILE = "poi_name_index.bin" /** Bytes per record: int32 lat_e7 + int32 lon_e7 + uint32 name_off + uint16 type. */ private const val RECORD_BYTES = 14@@ -60,6 +69,42 @@ object PoiIndex { /** `attr_off` for a POI that carries no attributes. */ private const val NO_ATTRS = -1 + // --- poi_spatial.bin / poi_name_index.bin (see osm_ingest/src/poi_side.rs) -----+ private val SPATIAL_MAGIC =+ byteArrayOf('P'.code.toByte(), 'S'.code.toByte(), 'P'.code.toByte(), '1'.code.toByte())+ private const val SPATIAL_VERSION = 1+ private const val SPATIAL_HEADER_BYTES = 32++ private val NAME_INDEX_MAGIC =+ byteArrayOf('P'.code.toByte(), 'N'.code.toByte(), 'I'.code.toByte(), '1'.code.toByte())+ private const val NAME_INDEX_VERSION = 1+ private const val NAME_INDEX_HEADER_BYTES = 16++ /**+ * ASCII-only lowercase, and deliberately not [Char.lowercase].+ *+ * `poi_name_index.bin` is sorted by the writer, so the reader has to reproduce that+ * order byte for byte. Rust's `to_lowercase` and Kotlin's `lowercase` do not agree on+ * every input, and here a disagreement is a POI that can never be found. See the+ * cross-language contract in `osm_ingest/src/poi_side.rs`.+ */+ private fun asciiLower(b: Byte): Int {+ val v = b.toInt() and 0xFF+ return if (v >= 'A'.code && v <= 'Z'.code) v + 32 else v+ }++ private fun isAsciiSpace(b: Byte): Boolean {+ val v = b.toInt() and 0xFF+ return v == ' '.code || v == '\t'.code || v == '\n'.code || v == '\r'.code ||+ v == 0x0B || v == 0x0C+ }++ /** A query as the index's sort key: UTF-8 bytes, ASCII-lowercased. */+ private fun queryKey(query: String): ByteArray {+ val raw = query.toByteArray(Charsets.UTF_8)+ return ByteArray(raw.size) { asciiLower(raw[it]).toByte() }+ }+ private const val KEY_OPENING_HOURS = 1 private const val KEY_PHONE = 2 private const val KEY_WEBSITE = 3@@ -142,6 +187,16 @@ object PoiIndex { val attrs: MappedByteBuffer?, /** Byte offset of the attribute blob, i.e. just past the offset array. */ val attrsBlobStart: Int,+ /** The CSR spatial grid, or null when absent or mismatched. */+ val spatial: MappedByteBuffer? = null,+ val cellCount: Int = 0,+ val lat0E7: Int = 0,+ val lon0E7: Int = 0,+ val cellE7: Int = 0,+ val cols: Int = 0,+ /** The word index, or null when absent or mismatched. */+ val nameIdx: MappedByteBuffer? = null,+ val entryCount: Int = 0, ) { fun latE7(i: Int): Int = index.getInt(i * RECORD_BYTES) fun lonE7(i: Int): Int = index.getInt(i * RECORD_BYTES + 4)@@ -183,15 +238,23 @@ object PoiIndex { } /**- * Visit every record inside the bbox in file order, stopping early when [onHit]- * returns false.+ * Visit every record inside the bbox in **ordinal order**, stopping early when+ * [onHit] returns false.+ *+ * Two implementations, picked by whether `poi_spatial.bin` was mapped: *- * Cost is the box's Morton span — a binary search to its lower bound, then a walk to- * its upper bound — rather than [count]. That span is not the box: a box straddling the- * equator or the prime meridian flips a top-level Z-curve bit and covers most of the- * key space, so those degenerate back toward a full walk. `poi_spatial.bin` makes the- * lookup exactly cell-local; this is the bound available without a format change, and- * it is what takes a POI tap from 22.6 M records to a local handful.+ * * **Grid** — only the cells the box actually overlaps are visited, so the cost+ * is the box's own area. Exact, and with no pathological cases.+ * * **Morton walk** — a binary search to the box's lower key bound, then a walk to+ * its upper bound. The bound is the box's *Morton span*, which is not the box: a+ * box straddling the equator or the prime meridian flips a top-level Z-curve bit+ * and covers most of the key space, degenerating back toward a full walk. Kept+ * because the side file is optional, and it still beats scanning [count].+ *+ * Ordinal order either way. The grid visits cells row by row, so its hits come out+ * shuffled relative to the file and are sorted before being yielded — callers that+ * truncate at a cap, or that break distance ties by file order, must not see a+ * different answer depending on which side files happen to be present. */ fun forEachInBbox( minLatE7: Int,@@ -201,6 +264,20 @@ object PoiIndex { onHit: (ordinal: Int, latE7: Int, lonE7: Int) -> Boolean, ) { if (minLatE7 > maxLatE7 || minLonE7 > maxLonE7) return+ if (spatial != null && cellCount > 0 && cols > 0 && cellE7 > 0) {+ forEachInCells(minLatE7, maxLatE7, minLonE7, maxLonE7, onHit)+ } else {+ forEachInMortonSpan(minLatE7, maxLatE7, minLonE7, maxLonE7, onHit)+ }+ }++ private fun forEachInMortonSpan(+ minLatE7: Int,+ maxLatE7: Int,+ minLonE7: Int,+ maxLonE7: Int,+ onHit: (ordinal: Int, latE7: Int, lonE7: Int) -> Boolean,+ ) { val (first, last) = spatialRangeForBbox(minLatE7, maxLatE7, minLonE7, maxLonE7) var i = lowerBound(first) while (i < count) {@@ -215,6 +292,151 @@ object PoiIndex { i++ } }++ /** Cell offset along one axis. Must match `cell_axis` in `poi_side.rs`. */+ private fun axis(value: Int, origin: Int): Int {+ val d = value.toLong() - origin.toLong()+ return if (d <= 0) 0 else (d / cellE7).toInt()+ }++ private fun row(latE7: Int): Int = axis(latE7, lat0E7)+ private fun col(lonE7: Int): Int = axis(lonE7, lon0E7).coerceAtMost(cols - 1)++ /** Index of [cellId] in the ascending cell-id array, or -1 when unpopulated. */+ private fun cellIndexOf(cellId: Int): Int {+ val buf = spatial ?: return -1+ var lo = 0+ var hi = cellCount+ while (lo < hi) {+ val mid = (lo + hi) ushr 1+ val v = buf.getInt(SPATIAL_HEADER_BYTES + 4 * mid)+ if (v == cellId) return mid+ if (v < cellId) lo = mid + 1 else hi = mid+ }+ return -1+ }++ /** CSR prefix entry [i], i.e. where cell `i`'s ordinals begin. */+ private fun cellOff(i: Int): Int =+ spatial!!.getInt(SPATIAL_HEADER_BYTES + 4 * cellCount + 4 * i)++ private fun gridOrdinal(k: Int): Int =+ spatial!!.getInt(SPATIAL_HEADER_BYTES + 4 * cellCount + 4 * (cellCount + 1) + 4 * k)++ private fun forEachInCells(+ minLatE7: Int,+ maxLatE7: Int,+ minLonE7: Int,+ maxLonE7: Int,+ onHit: (ordinal: Int, latE7: Int, lonE7: Int) -> Boolean,+ ) {+ val hits = ArrayList<Int>()+ for (r in row(minLatE7)..row(maxLatE7)) {+ for (c in col(minLonE7)..col(maxLonE7)) {+ val ci = cellIndexOf(r * cols + c)+ if (ci < 0) continue+ for (k in cellOff(ci) until cellOff(ci + 1)) {+ val ordinal = gridOrdinal(k)+ if (ordinal < 0 || ordinal >= count) continue+ if (latE7(ordinal) in minLatE7..maxLatE7 &&+ lonE7(ordinal) in minLonE7..maxLonE7+ ) {+ hits.add(ordinal)+ }+ }+ }+ }+ hits.sort()+ for (ordinal in hits) {+ if (!onHit(ordinal, latE7(ordinal), lonE7(ordinal))) return+ }+ }++ // --- Word index --------------------------------------------------------++ private fun entryOrdinal(i: Int): Int =+ nameIdx!!.getInt(NAME_INDEX_HEADER_BYTES + 4 * i)++ private fun entryWordIdx(i: Int): Int =+ nameIdx!!.get(NAME_INDEX_HEADER_BYTES + 4 * entryCount + i).toInt() and 0xFF++ /**+ * Byte range of the [wordIdx]th whitespace-separated word of the name at [off], or+ * null when the name has fewer words. Must match `word_at` in `poi_side.rs`.+ */+ private fun wordRange(off: Int, wordIdx: Int): IntRange? {+ if (off < 0 || off >= namesLen) return null+ var i = off+ var idx = 0+ while (i < namesLen && names.get(i).toInt() != 0) {+ while (i < namesLen && names.get(i).toInt() != 0 && isAsciiSpace(names.get(i))) i+++ if (i >= namesLen || names.get(i).toInt() == 0) break+ val start = i+ while (i < namesLen && names.get(i).toInt() != 0 && !isAsciiSpace(names.get(i))) i+++ if (idx == wordIdx) return start until i+ idx+++ }+ return null+ }++ private fun entryWord(i: Int): IntRange? =+ wordRange(nameOff(entryOrdinal(i)), entryWordIdx(i))++ /** ASCII-lowercased byte compare of the word at [range] against [key]. */+ private fun compareWord(range: IntRange, key: ByteArray): Int {+ val len = range.last - range.first + 1+ for (k in 0 until minOf(len, key.size)) {+ val d = asciiLower(names.get(range.first + k)) - (key[k].toInt() and 0xFF)+ if (d != 0) return d+ }+ return len - key.size+ }++ private fun wordStartsWith(range: IntRange, key: ByteArray): Boolean {+ if (range.last - range.first + 1 < key.size) return false+ for (k in key.indices) {+ if (asciiLower(names.get(range.first + k)) != (key[k].toInt() and 0xFF)) return false+ }+ return true+ }++ /** First entry whose word is >= [key], or [entryCount]. */+ private fun lowerBoundWord(key: ByteArray): Int {+ var lo = 0+ var hi = entryCount+ while (lo < hi) {+ val mid = (lo + hi) ushr 1+ val w = entryWord(mid)+ // A word we cannot resolve sorts first, so the search steps past it rather+ // than stalling on a name the index disagrees with.+ if (w == null || compareWord(w, key) < 0) lo = mid + 1 else hi = mid+ }+ return lo+ }++ /**+ * Ordinals whose name has a word starting with [key], each paired with whether the+ * match was on the name's *first* word.+ *+ * Binary search plus a walk of the matching range, so the cost is the number of+ * matches rather than the size of the name pool.+ */+ fun wordPrefixMatches(key: ByteArray, cap: Int): List<IntArray> {+ if (nameIdx == null || entryCount == 0) return emptyList()+ val out = ArrayList<IntArray>()+ val seen = HashSet<Int>()+ var i = lowerBoundWord(key)+ while (i < entryCount && out.size < cap) {+ val w = entryWord(i) ?: break+ if (!wordStartsWith(w, key)) break+ val ordinal = entryOrdinal(i)+ // A name can match on more than one word ("Pizza Pizza"); the better rank+ // wins, and the index lists word 0 first within one name.+ if (seen.add(ordinal)) out.add(intArrayOf(ordinal, entryWordIdx(i)))+ i+++ }+ return out+ } } @Volatile@@ -280,6 +502,8 @@ object PoiIndex { // Separate and optional: a failure here leaves the index perfectly // usable, just without attributes. val attrs = openAttrs(File(dir, ATTRS_FILE), count)+ val grid = openSpatial(File(dir, SPATIAL_FILE), count)+ val words = openNameIndex(File(dir, NAME_INDEX_FILE), count) mapped = Mapped( index = indexBuf, names = namesBuf,@@ -287,8 +511,20 @@ object PoiIndex { count = count, attrs = attrs?.first, attrsBlobStart = attrs?.second ?: 0,+ spatial = grid?.buf,+ cellCount = grid?.cellCount ?: 0,+ lat0E7 = grid?.lat0E7 ?: 0,+ lon0E7 = grid?.lon0E7 ?: 0,+ cellE7 = grid?.cellE7 ?: 0,+ cols = grid?.cols ?: 0,+ nameIdx = words?.first,+ entryCount = words?.second ?: 0,+ )+ Log.d(+ TAG,+ "Loaded $count POI records, names=${namesBuf.capacity()}B, " ++ "grid=${grid?.cellCount ?: 0} cells, words=${words?.second ?: 0}", )- Log.d(TAG, "Loaded $count POI records, names=${namesBuf.capacity()}B") true } catch (e: Exception) { Log.w(TAG, "Failed to map POI side files", e)@@ -349,6 +585,96 @@ object PoiIndex { } } + /** The mapped spatial grid plus the parameters read out of its header. */+ private class Grid(+ val buf: MappedByteBuffer,+ val cellCount: Int,+ val lat0E7: Int,+ val lon0E7: Int,+ val cellE7: Int,+ val cols: Int,+ )++ /**+ * Map `poi_spatial.bin`, or null when it is absent, stale or malformed.+ *+ * The record-count check matters for the same reason it does for the sidecar: the grid+ * stores *ordinals*, so a grid built against a different `poi_index.bin` would return+ * the wrong places rather than none. Refusing it costs only the Morton fallback.+ */+ private fun openSpatial(file: File, count: Int): Grid? {+ if (!file.isFile) return null+ return try {+ val buf = mapReadOnly(file).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ if (buf.capacity() < SPATIAL_HEADER_BYTES) return null+ for (i in SPATIAL_MAGIC.indices) {+ if (buf.get(i) != SPATIAL_MAGIC[i]) {+ Log.w(TAG, "$SPATIAL_FILE has the wrong magic; ignoring it")+ return null+ }+ }+ if (buf.getInt(4) != SPATIAL_VERSION) {+ Log.w(TAG, "$SPATIAL_FILE version ${buf.getInt(4)} unsupported; ignoring it")+ return null+ }+ val records = buf.getInt(8)+ if (records != count) {+ Log.w(TAG, "$SPATIAL_FILE covers $records record(s), index has $count; ignoring it")+ return null+ }+ val cellCount = buf.getInt(12)+ val cols = buf.getInt(28)+ // cell_ids + cell_off + ordinals must all be present before any of them is read.+ val need = SPATIAL_HEADER_BYTES + 4L * cellCount + 4L * (cellCount + 1) + 4L * count+ if (cellCount < 0 || cols < 0 || need > buf.capacity()) {+ Log.w(TAG, "$SPATIAL_FILE is truncated; ignoring it")+ return null+ }+ Grid(buf, cellCount, buf.getInt(16), buf.getInt(20), buf.getInt(24), cols)+ } catch (e: Exception) {+ Log.w(TAG, "Failed to map $SPATIAL_FILE", e)+ null+ }+ }++ /** Map `poi_name_index.bin` and its entry count, or null when unusable. */+ private fun openNameIndex(file: File, count: Int): Pair<MappedByteBuffer, Int>? {+ if (!file.isFile) return null+ return try {+ val buf = mapReadOnly(file).also { it.order(ByteOrder.LITTLE_ENDIAN) }+ if (buf.capacity() < NAME_INDEX_HEADER_BYTES) return null+ for (i in NAME_INDEX_MAGIC.indices) {+ if (buf.get(i) != NAME_INDEX_MAGIC[i]) {+ Log.w(TAG, "$NAME_INDEX_FILE has the wrong magic; ignoring it")+ return null+ }+ }+ if (buf.getInt(4) != NAME_INDEX_VERSION) {+ Log.w(TAG, "$NAME_INDEX_FILE version ${buf.getInt(4)} unsupported; ignoring it")+ return null+ }+ val records = buf.getInt(8)+ if (records != count) {+ Log.w(+ TAG,+ "$NAME_INDEX_FILE covers $records record(s), index has $count; ignoring it",+ )+ return null+ }+ val entries = buf.getInt(12)+ if (entries < 0 ||+ NAME_INDEX_HEADER_BYTES + 5L * entries > buf.capacity()+ ) {+ Log.w(TAG, "$NAME_INDEX_FILE is truncated; ignoring it")+ return null+ }+ buf to entries+ } catch (e: Exception) {+ Log.w(TAG, "Failed to map $NAME_INDEX_FILE", e)+ null+ }+ }+ private fun mapReadOnly(file: File): MappedByteBuffer = RandomAccessFile(file, "r").use { raf -> raf.channel.use { ch ->@@ -359,10 +685,20 @@ object PoiIndex { } /**- * Case-insensitive prefix/substring search over the deduped name pool,- * returning matching POIs ranked prefix-first then by distance to- * ([nearLat],[nearLon]). Returns an empty list when nothing matches or the- * index isn't loaded.+ * Name search, ranked first-word-first then by distance to ([nearLat],[nearLon]).+ *+ * Two implementations, picked by whether `poi_name_index.bin` was mapped:+ *+ * * **Indexed** — binary search to the query's place in a word-sorted index, then a+ * walk of the matching range, so the cost is the number of matches. Because every+ * word of a name is indexed, "pizza" still finds "Joe's Pizza".+ * * **Scan** — the name pool, then every record. Two passes whose cost is the whole+ * dataset, kept only because the side file is optional.+ *+ * **The two do not match exactly, by design.** The scan matches a substring anywhere,+ * so "izza" finds "Pizza"; a sorted index can only answer prefix questions, so the+ * indexed path matches a prefix *of any word*. That is a deliberate narrowing —+ * mid-word matches are lost, whole-word ones are not. */ fun searchByName( query: String,@@ -371,6 +707,45 @@ object PoiIndex { limit: Int = 20, ): List<PoiRecord> { val m = mapped ?: return emptyList()+ if (query.isBlank()) return emptyList()+ if (m.nameIdx != null) return searchByWordIndex(m, query, nearLat, nearLon, limit)+ return searchByScan(m, query, nearLat, nearLon, limit)+ }++ private fun searchByWordIndex(+ m: Mapped,+ query: String,+ nearLat: Double,+ nearLon: Double,+ limit: Int,+ ): List<PoiRecord> {+ val key = queryKey(query.trim())+ if (key.isEmpty()) return emptyList()+ val out = ArrayList<Ranked>()+ for (hit in m.wordPrefixMatches(key, CANDIDATE_CAP)) {+ val (ordinal, wordIdx) = hit+ // Matching the name's first word is the indexed equivalent of the scan's+ // "starts with", and ranks the same way.+ val rank = if (wordIdx == 0) 0 else 1+ out.add(+ Ranked(+ m.record(ordinal),+ rank,+ distanceSq(nearLat, nearLon, m.latE7(ordinal) / 1e7, m.lonE7(ordinal) / 1e7),+ )+ )+ }+ out.sortWith(compareBy({ it.rank }, { it.distSq }))+ return out.take(limit).map { it.record }+ }++ private fun searchByScan(+ m: Mapped,+ query: String,+ nearLat: Double,+ nearLon: Double,+ limit: Int,+ ): List<PoiRecord> { val q = query.trim().lowercase() if (q.isEmpty()) return emptyList()
maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt
diff --git a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.ktindex 0d0dc7745e..628e70ede4 100644--- a/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt+++ b/maps/src/test/java/com/vayunmathur/maps/util/PoiIndexTest.kt@@ -46,7 +46,19 @@ class PoiIndexTest { * `poi_index.bin` the reader is allowed to assume. [returns] the records in file order, so a * list index is an ordinal. */- private fun load(pois: List<Poi>, attrs: Map<Int, String> = emptyMap(), attrSlots: Int? = null): List<Poi> {+ private fun load(+ pois: List<Poi>,+ attrs: Map<Int, String> = emptyMap(),+ attrSlots: Int? = null,+ /** Whether to write `poi_spatial.bin` / `poi_name_index.bin` at all. */+ sideFiles: Boolean = true,+ /** Record count to claim in `poi_spatial.bin`, for the refusal case. */+ spatialRecords: Int? = null,+ /** Record count to claim in `poi_name_index.bin`, for the refusal case. */+ nameRecords: Int? = null,+ /** Bytes to lop off the end of `poi_spatial.bin`, for the truncation case. */+ spatialTruncateBy: Int = 0,+ ): List<Poi> { val dir = Files.createTempDirectory("poiindex").toFile() temp = dir @@ -82,11 +94,101 @@ class PoiIndexTest { File(dir, PoiIndex.ATTRS_FILE) .writeBytes(attrsFile(attrSlots ?: sorted.size, attrs)) }+ if (sideFiles) {+ val grid = spatialFile(sorted, spatialRecords ?: sorted.size)+ File(dir, PoiIndex.SPATIAL_FILE)+ .writeBytes(grid.copyOf(grid.size - spatialTruncateBy))+ File(dir, PoiIndex.NAME_INDEX_FILE)+ .writeBytes(nameIndexFile(sorted, nameRecords ?: sorted.size))+ } assertTrue(PoiIndex.reload(dir), "fixture did not map") return sorted } + /** Cell size the writer uses; see `CELL_E7` in `osm_ingest/src/poi_side.rs`. */+ private val cellE7 = 200_000++ private fun axis(value: Int, origin: Int): Int {+ val d = value.toLong() - origin.toLong()+ return if (d <= 0) 0 else (d / cellE7).toInt()+ }++ /**+ * A `poi_spatial.bin` for [pois], built the way `poi_side.rs` builds it.+ *+ * Written independently of the Rust writer on purpose: if the two drift, the reader+ * stops agreeing with one of them, and these tests are the only thing on this side of+ * the language boundary that would notice.+ */+ private fun spatialFile(pois: List<Poi>, records: Int): ByteArray {+ val lat0 = pois.minOfOrNull { it.latE7 } ?: 0+ val lon0 = pois.minOfOrNull { it.lonE7 } ?: 0+ val cols = if (pois.isEmpty()) 0 else axis(pois.maxOf { it.lonE7 }, lon0) + 1+ val pairs = pois.mapIndexed { ordinal, p ->+ axis(p.latE7, lat0) * cols + axis(p.lonE7, lon0).coerceAtMost(cols - 1) to ordinal+ }.sortedWith(compareBy({ it.first }, { it.second }))++ val cellIds = ArrayList<Int>()+ val cellOff = ArrayList<Int>()+ pairs.forEachIndexed { i, (cell, _) ->+ if (cellIds.lastOrNull() != cell) {+ cellIds.add(cell)+ cellOff.add(i)+ }+ }+ cellOff.add(pairs.size)++ val buf = ByteBuffer+ .allocate(32 + 4 * cellIds.size + 4 * cellOff.size + 4 * pairs.size)+ .order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PSP1".toByteArray(Charsets.US_ASCII))+ buf.putInt(1)+ buf.putInt(records)+ buf.putInt(cellIds.size)+ buf.putInt(lat0)+ buf.putInt(lon0)+ buf.putInt(cellE7)+ buf.putInt(cols)+ cellIds.forEach { buf.putInt(it) }+ cellOff.forEach { buf.putInt(it) }+ pairs.forEach { buf.putInt(it.second) }+ return buf.array()+ }++ /** The whitespace-separated words of a name, as `poi_side.rs` splits them. */+ private fun words(name: String): List<String> =+ name.split(' ', '\t', '\n', '\r', '\u000B', '\u000C').filter { it.isNotEmpty() }++ /**+ * A `poi_name_index.bin` for [pois]: one entry per (record, word), sorted by the word.+ *+ * Fixture names are ASCII, so `lowercase()` here matches the writer's ASCII-only fold+ * and Kotlin's string order matches its byte order. A non-ASCII fixture would need the+ * byte-wise comparison the reader does.+ */+ private fun nameIndexFile(pois: List<Poi>, records: Int): ByteArray {+ val entries = ArrayList<Pair<Int, Int>>()+ pois.forEachIndexed { ordinal, p ->+ words(p.name).indices.take(255).forEach { wordIdx -> entries.add(ordinal to wordIdx) }+ }+ entries.sortWith(+ compareBy(+ { words(pois[it.first].name)[it.second].lowercase() },+ { it.first },+ { it.second },+ )+ )+ val buf = ByteBuffer.allocate(16 + 5 * entries.size).order(ByteOrder.LITTLE_ENDIAN)+ buf.put("PNI1".toByteArray(Charsets.US_ASCII))+ buf.putInt(1)+ buf.putInt(records)+ buf.putInt(entries.size)+ entries.forEach { buf.putInt(it.first) }+ entries.forEach { buf.put(it.second.toByte()) }+ return buf.array()+ }+ /** * A `poi_attrs.bin` carrying one phone number per entry of [phones], keyed by ordinal. *@@ -194,10 +296,21 @@ class PoiIndexTest { // --- equivalence ------------------------------------------------------- + /**+ * Both lookup paths must agree with the original scan, so every equivalence test runs+ * twice: once with the side files present (cell-local grid) and once without (Morton+ * span walk). A bug in either would otherwise hide behind the other.+ */+ private fun bothPaths(body: (sideFiles: Boolean) -> Unit) {+ for (sideFiles in listOf(true, false)) {+ body(sideFiles)+ }+ }+ @Test- fun `nearest returns exactly what the full scan returned`() {+ fun `nearest returns exactly what the full scan returned`() = bothPaths { sideFiles -> val rng = Random(1)- val recs = load(scatter(rng, 4_000, 37.7749, -122.4194, 0.35))+ val recs = load(scatter(rng, 4_000, 37.7749, -122.4194, 0.35), sideFiles = sideFiles) assertEquals(4_000, PoiIndex.recordCount) repeat(200) { val lat = 37.7749 + rng.nextDouble(-0.35, 0.35)@@ -207,28 +320,29 @@ class PoiIndexTest { assertEquals( refNearest(recs, lat, lon, limit, meters), PoiIndex.nearest(lat, lon, limit = limit, maxMeters = meters),- "nearest($lat, $lon, limit=$limit, maxMeters=$meters)",+ "nearest($lat, $lon, limit=$limit, maxMeters=$meters) sideFiles=$sideFiles", ) } } @Test- fun `inViewport returns exactly what the full scan returned, cap included`() {- val rng = Random(2)- val recs = load(scatter(rng, 4_000, 51.5074, -0.1278, 0.4))- repeat(200) {- val lat = 51.5074 + rng.nextDouble(-0.4, 0.4)- val lon = -0.1278 + rng.nextDouble(-0.4, 0.4)- val h = rng.nextDouble(0.001, 0.3)- val w = rng.nextDouble(0.001, 0.3)- val cap = rng.nextInt(1, 60)- assertEquals(- refInViewport(recs, lon - w, lat - h, lon + w, lat + h, cap),- PoiIndex.inViewport(lon - w, lat - h, lon + w, lat + h, cap = cap),- "inViewport around ($lat, $lon) +-($h, $w) cap=$cap",- )+ fun `inViewport returns exactly what the full scan returned, cap included`() =+ bothPaths { sideFiles ->+ val rng = Random(2)+ val recs = load(scatter(rng, 4_000, 51.5074, -0.1278, 0.4), sideFiles = sideFiles)+ repeat(200) {+ val lat = 51.5074 + rng.nextDouble(-0.4, 0.4)+ val lon = -0.1278 + rng.nextDouble(-0.4, 0.4)+ val h = rng.nextDouble(0.001, 0.3)+ val w = rng.nextDouble(0.001, 0.3)+ val cap = rng.nextInt(1, 60)+ assertEquals(+ refInViewport(recs, lon - w, lat - h, lon + w, lat + h, cap),+ PoiIndex.inViewport(lon - w, lat - h, lon + w, lat + h, cap = cap),+ "inViewport around ($lat, $lon) +-($h, $w) cap=$cap sideFiles=$sideFiles",+ )+ } }- } /** * Z-order's discontinuity is a *performance* caveat, not a correctness one, and this is the@@ -351,4 +465,113 @@ class PoiIndexTest { assertEquals(0, PoiIndex.recordCount) assertTrue(PoiIndex.nearest(37.7749, -122.4194).isEmpty()) }++ // --- word index --------------------------------------------------------++ /** The point of indexing every word rather than just the name's first. */+ @Test+ fun `a word in the middle of a name is findable`() {+ load(+ listOf(+ Poi(377_749_000, -1_224_194_000, 1, "Joe's Pizza"),+ Poi(377_749_100, -1_224_194_100, 2, "Pizza Hut"),+ )+ )+ val got = PoiIndex.searchByName("pizza", 37.7749, -122.4194).map { it.name }+ assertEquals(setOf("Joe's Pizza", "Pizza Hut"), got.toSet())+ }++ /** A first-word match is the indexed equivalent of the scan's "starts with". */+ @Test+ fun `a first-word match outranks a later-word match`() {+ load(+ listOf(+ // Deliberately the farther of the two, so only the rank can order them.+ Poi(377_760_000, -1_224_194_000, 1, "Pizza Hut"),+ Poi(377_749_000, -1_224_194_000, 2, "Joe's Pizza"),+ )+ )+ val got = PoiIndex.searchByName("pizza", 37.7749, -122.4194).map { it.name }+ assertEquals(listOf("Pizza Hut", "Joe's Pizza"), got)+ }++ @Test+ fun `a word prefix matches, and an unrelated word does not`() {+ load(listOf(Poi(377_749_000, -1_224_194_000, 1, "Blue Bottle Coffee")))+ for (q in listOf("blue", "bot", "coffee", "BOTTLE")) {+ assertEquals(+ 1,+ PoiIndex.searchByName(q, 37.7749, -122.4194).size,+ "\"$q\" should match",+ )+ }+ assertTrue(PoiIndex.searchByName("tearoom", 37.7749, -122.4194).isEmpty())+ }++ /**+ * The documented narrowing: a sorted index answers prefix questions, so a match in the+ * middle of a *word* is lost where the scan found it. Asserted rather than left to be+ * discovered, since it is the one thing the two paths disagree about.+ */+ @Test+ fun `a mid-word match is found by the scan but not by the index`() {+ val pois = listOf(Poi(377_749_000, -1_224_194_000, 1, "Pizza"))+ load(pois, sideFiles = false)+ assertEquals(1, PoiIndex.searchByName("izza", 37.7749, -122.4194).size)+ load(pois, sideFiles = true)+ assertTrue(PoiIndex.searchByName("izza", 37.7749, -122.4194).isEmpty())+ }++ @Test+ fun `a blank query matches nothing on either path`() = bothPaths { sideFiles ->+ load(listOf(Poi(377_749_000, -1_224_194_000, 1, "Cafe")), sideFiles = sideFiles)+ assertTrue(PoiIndex.searchByName(" ", 37.7749, -122.4194).isEmpty())+ }++ // --- side-file refusal -------------------------------------------------++ /**+ * The grid stores ordinals, so one built against a different `poi_index.bin` would+ * return the wrong places. It must be refused and the Morton walk used instead — the+ * results still have to be right, which is what makes refusing safe.+ */+ @Test+ fun `a spatial grid whose record count disagrees with the index is refused`() {+ val rng = Random(11)+ val recs = load(scatter(rng, 200, 37.7749, -122.4194, 0.05), spatialRecords = 199)+ assertTrue(PoiIndex.available)+ assertEquals(+ refInViewport(recs, -122.47, 37.72, -122.37, 37.82, 500),+ PoiIndex.inViewport(-122.47, 37.72, -122.37, 37.82, cap = 500),+ "a refused grid must fall back, not return less",+ )+ }++ @Test+ fun `a name index whose record count disagrees with the index is refused`() {+ load(+ listOf(Poi(377_749_000, -1_224_194_000, 1, "Joe's Pizza")),+ nameRecords = 7,+ )+ // Refused, so the scan answers — and the scan still matches mid-word.+ assertEquals(1, PoiIndex.searchByName("izza", 37.7749, -122.4194).size)+ }++ @Test+ fun `absent side files leave the index working on the Morton path`() {+ load(listOf(Poi(377_749_000, -1_224_194_000, 1, "Mall")), sideFiles = false)+ assertTrue(PoiIndex.available)+ assertEquals(1, PoiIndex.nearest(37.7749, -122.4194, maxMeters = 50.0).size)+ assertEquals(1, PoiIndex.searchByName("mall", 37.7749, -122.4194).size)+ }++ @Test+ fun `a truncated spatial grid is refused rather than read past its end`() {+ val recs = load(scatter(Random(12), 50, 37.7749, -122.4194, 0.02), spatialTruncateBy = 8)+ assertTrue(PoiIndex.available)+ assertEquals(+ refInViewport(recs, -122.44, 37.75, -122.40, 37.79, 500),+ PoiIndex.inViewport(-122.44, 37.75, -122.40, 37.79, cap = 500),+ )+ } }
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex e69a9dc4db..ca404e7f4f 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -98,8 +98,8 @@ tap). It deliberately does **not** reuse the base Protomaps `pois` layer (which the app suppresses). It is built by [`build_pois_layer.sh`](build_pois_layer.sh) (→ [`osm_ingest`](osm_ingest/)'s `poi_extract`) at zooms **z12–z16**. The same pass also-emits three compact side files (`poi_names.bin` + `poi_index.bin` +-`poi_attrs.bin`, formats below)+emits five compact side files (`poi_names.bin` + `poi_index.bin` ++`poi_attrs.bin`, `poi_spatial.bin`, `poi_name_index.bin`, formats below) so the app can mmap + binary-scan POIs; the layer and the side files are mutually consistent (same POI set, same coordinates). See [POI layer & side files (P27)](#poi-layer--side-files-p27) below.@@ -543,7 +543,7 @@ Individual layers can also be built standalone — see each script's `--help`. | `maxspeed.pmtiles` | planet | ~1–3 GB (line features on tagged ways) | | `transit_lines.pmtiles` | planet | ~0.2–1 GB (rail/transit line features) | | `ma_pois.pmtiles` | planet | ~0.5–2 GB (named POI points) |-| `poi_names.bin` + `poi_index.bin` + `poi_attrs.bin` | planet | ~0.5–2 GB combined (side files) |+| `poi_names.bin` + `poi_index.bin` + `poi_attrs.bin` + `poi_spatial.bin` + `poi_name_index.bin` | planet | ~1–3 GB combined (side files) | | `admin_country/region/city.pmtiles` | planet | ~50–300 MB combined | | **`v5-overlay.pmtiles`** | planet | ~**2–7 GB** (every overlay, no base) | | `v5.pmtiles` | planet | ≈ **137 GB** (base + overlays; the base is > 97% of it) |@@ -553,10 +553,20 @@ The base dominates so completely that publishing it together with the overlays means re-uploading 127 GB of unchanged bytes to ship a POI fix. Hence the split. The side-file budget grew with `poi_attrs.bin`. Its offset array alone is-`4 × record_count` — about 90 MB against 22.6 M planet POIs — before the+`4 x record_count` - about 90 MB against 22.6 M planet POIs - before the deduplicated attribute blob. Recheck it against a real planet run rather than trusting this estimate. +The two lookup indexes added more, and `poi_name_index.bin` is now the largest of+the side files. It carries one 5-byte entry per `(record, word)`, so at ~2.2 words+per name it is roughly `11 x record_count` - order 250 MB against 22.6 M POIs.+It cannot be per-*name* instead: `poi_names.bin` is deduplicated, so a word only+identifies a name and a name still has to be resolved to the records using it.+`poi_spatial.bin` adds `4 x record_count` (~90 MB) for its ordinal array plus+8 bytes per populated cell. Both are optional to the app - it falls back to a+Morton-span walk and a name-pool scan - so a size problem is a performance+regression, not an outage. Measure them on a real planet run.+ --- ## Publishing to R2@@ -646,9 +656,11 @@ binary-scan POIs without opening the tileset: poi_names.bin poi_index.bin poi_attrs.bin+poi_spatial.bin+poi_name_index.bin ``` -All three are published by `build_all.sh --publish` (they are in its artifact list,+All five are published by `build_all.sh --publish` (they are in its artifact list, so `publish_r2.sh` keys each by basename) and ship from the same `data.vayunmathur.com` host as the routing graph. @@ -840,6 +852,61 @@ to it — an exact match does not work. `PoiIndex.attributesNear` takes the near record within a few metres **whose name also matches**, because a mall and a cafe inside it can share a coordinate to within a metre. +### `poi_spatial.bin` + `poi_name_index.bin` - the two lookup indexes++Both are optional, both join to `poi_index.bin` **by record ordinal**, and both carry+its record count so the reader refuses a stale one rather than returning someone+else's place. `osm_ingest/src/poi_side.rs` is the authoritative layout;+`maps/.../util/PoiIndex.kt` is the reader.++They exist because `poi_index.bin`'s Morton order bounds a bbox query by the box's+*Morton span*, and a box straddling the equator or the prime meridian flips a+top-level Z-curve bit and covers most of the key space - geographically tiny, but+nearly a full walk. A plain row/column grid has no such pathology.++```+poi_spatial.bin+0..4 magic "PSP1"+4..8 uint32 version (1)+8..12 uint32 record_count (must equal poi_index.bin's, else refused)+12..16 uint32 cell_count (populated cells only)+16..20 int32 lat0_e7 grid origin: the records' own minimum corner+20..24 int32 lon0_e7+24..28 uint32 cell_e7 200000, i.e. 0.02 deg, same as the transit pack+28..32 uint32 cols+then uint32 cell_ids[cell_count] ascending+ uint32 cell_off[cell_count + 1] CSR prefix into ordinals+ uint32 ordinals[record_count] grouped by cell, ascending within one+```++```+poi_name_index.bin+0..4 magic "PNI1"+4..8 uint32 version (1)+8..12 uint32 record_count (must equal poi_index.bin's, else refused)+12..16 uint32 entry_count+then uint32 ordinals[entry_count] the record the word belongs to+ uint8 word_idx[entry_count] which word of that record's name+```++Parallel arrays, so an entry is 5 bytes rather than the 8 alignment would round a+packed struct up to. One entry per `(record, word)`, sorted by the word, so a name+search is a binary search plus a walk of the matching range - and because *every*+word is indexed, "pizza" finds "Joe's Pizza".++**The sort order is a cross-language contract.** A word is a maximal run of bytes+that are not ASCII whitespace, and the sort key is those bytes with ASCII `A-Z`+folded to lowercase and every other byte, including all non-ASCII, left alone.+Deliberately not Unicode case folding: Rust's `to_lowercase` and Kotlin's+`lowercase` do not agree byte-for-byte on every input, and a disagreement here is a+POI that can never be found. Both sides pin it with tests.++One consequence worth stating: a sorted index can only answer prefix questions, so+name search matches a prefix **of any word** where the old scan matched a substring+anywhere. "izza" no longer finds "Pizza"; "pizza" still finds "Joe's Pizza". The+fallback scan keeps the old behaviour when the file is absent, so the two paths+differ - `PoiIndex.searchByName` documents that, and a test asserts it.+ --- ## Single global routing graph (P16)
scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index 77ea59146b..b41131bcad 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -18,7 +18,7 @@ # THE 11 ARTIFACTS, all landing in -OutDir: # graph metadata.bin road_names.bin nodes.bin edges.bin lanes.bin # intermediate.bin-# pois poi_names.bin poi_index.bin poi_attrs.bin+# pois poi_names.bin poi_index.bin poi_attrs.bin poi_spatial.bin poi_name_index.bin # transit world.transit # tiles v5-overlay.pmtiles (name from -Out) # plus manifest.txt with each one's size and SHA-256, byte-comparable with the@@ -215,13 +215,15 @@ if (Test-Stage "pois") { } else { Assert-Pbf "Pois" $poiGeo = Join-Path $Work "ma_pois.geojsonseq"- Write-Host "=== pois -> $OutDir\poi_names.bin + poi_index.bin + poi_attrs.bin ==="+ Write-Host "=== pois -> $OutDir\poi_names.bin + poi_index.bin + poi_attrs.bin + poi_spatial.bin + poi_name_index.bin ===" Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $OsmManifest, "--bin", "poi_extract", "--", $Pbf, "--geojson", $poiGeo, "--names", (Join-Path $OutDir "poi_names.bin"), "--index", (Join-Path $OutDir "poi_index.bin"),- "--attrs", (Join-Path $OutDir "poi_attrs.bin"))+ "--attrs", (Join-Path $OutDir "poi_attrs.bin"),+ "--spatial", (Join-Path $OutDir "poi_spatial.bin"),+ "--name-index", (Join-Path $OutDir "poi_name_index.bin")) Write-Host "=== pois -> $PoisTile (z12-16, tile_points) ===" Invoke-Step "cargo" @("run", "--release", "--quiet", "--manifest-path", $TileManifest, "--bin", "tile_points", "--",@@ -336,7 +338,8 @@ if (Test-Stage "tiles") { # so the digests compare directly. $artifacts = @("metadata.bin", "road_names.bin", "nodes.bin", "edges.bin", "lanes.bin", "intermediate.bin",- "poi_names.bin", "poi_index.bin", "poi_attrs.bin", "world.transit",+ "poi_names.bin", "poi_index.bin", "poi_attrs.bin", "poi_spatial.bin",+ "poi_name_index.bin", "world.transit", (Split-Path $Out -Leaf)) function Get-ArtifactPath {
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex 3e75845a80..ba93f5316d 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -12,7 +12,7 @@ set -euo pipefail # THE 11 ARTIFACTS, all landing in --out-dir: # graph metadata.bin road_names.bin nodes.bin edges.bin lanes.bin # intermediate.bin-# pois poi_names.bin poi_index.bin poi_attrs.bin+# pois poi_names.bin poi_index.bin poi_attrs.bin poi_spatial.bin poi_name_index.bin # transit world.transit # tiles v5-overlay.pmtiles (name from --out) # plus manifest.txt listing every one with its size and SHA-256. The first ten@@ -344,6 +344,8 @@ if want_stage pois; then --names-out "$OUT_DIR/poi_names.bin" \ --index-out "$OUT_DIR/poi_index.bin" \ --attrs-out "$OUT_DIR/poi_attrs.bin" \+ --spatial-out "$OUT_DIR/poi_spatial.bin" \+ --name-index-out "$OUT_DIR/poi_name_index.bin" \ --engine "$ENGINE_POIS" mark_done pois fi@@ -417,9 +419,10 @@ if want_stage tiles; then fi fi -# --- manifest.txt: name, size, SHA-256 for all 9 ---+# --- manifest.txt: name, size, SHA-256 for all 12 --- ARTIFACTS=(metadata.bin road_names.bin nodes.bin edges.bin lanes.bin intermediate.bin- poi_names.bin poi_index.bin poi_attrs.bin world.transit)+ poi_names.bin poi_index.bin poi_attrs.bin poi_spatial.bin poi_name_index.bin+ world.transit) sha256_of() { if command -v sha256sum >/dev/null; then
scripts/maps/build_pois_layer.sh
diff --git a/scripts/maps/build_pois_layer.sh b/scripts/maps/build_pois_layer.shindex b9298f44f6..63fc1d52de 100644--- a/scripts/maps/build_pois_layer.sh+++ b/scripts/maps/build_pois_layer.sh@@ -8,10 +8,10 @@ set -euo pipefail # when the user taps a POI. This deliberately does NOT reuse the Protomaps base # `pois` layer (the app suppresses that one). #-# Produces four mutually-consistent outputs from a single `poi_extract` pass+# Produces six mutually-consistent outputs from a single `poi_extract` pass # (same POI set, same order, same coordinates): #-# * <out>.pmtiles source-layer `ma_pois` (Point) — attrs: name, type, osm_id+# * <out>.pmtiles source-layer `ma_pois` (Point) - attrs: name, type, osm_id # * poi_names.bin deduped NUL-terminated UTF-8 name table (each unique name # once); a "name start index" is the byte offset of a name # * poi_index.bin flat 14-byte records (little-endian):@@ -19,6 +19,13 @@ set -euo pipefail # sorted by Morton (Z-order) key of (lat,lon) # * poi_attrs.bin attribute sidecar keyed by poi_index.bin RECORD ORDINAL: # opening_hours, phone, website, addr:*, cuisine, wheelchair+# * poi_spatial.bin sparse CSR lat/lon grid over record ordinals, so a bbox+# query is cell-local instead of a Morton-span walk+# * poi_name_index.bin one (record, word) entry per word of every name,+# sorted by word, so name search is a binary search+#+# The last two are OPTIONAL for the app - it falls back to the Morton walk and+# the name-pool scan - but they are what keeps a planet-sized index usable. # # See scripts/maps/osm_ingest (src/poi_build.rs, src/poi_attrs.rs) for the full # TYPE MAP + the exact on-disk layouts, and the README (`ma_pois` schema + file@@ -36,6 +43,10 @@ set -euo pipefail # --index-out FILE Output record index (default: poi_index.bin) # --attrs-out FILE Output attribute sidecar (default: poi_attrs.bin beside # --index-out)+# --spatial-out FILE Output spatial grid (default: poi_spatial.bin beside+# --index-out)+# --name-index-out FILE Output word index (default: poi_name_index.bin beside+# --index-out) # --bbox BOX Optional "minlon,minlat,maxlon,maxlat" metro extract (dry runs) # --minzoom N tiler minzoom (default 12) # --maxzoom N tiler maxzoom (default 16)@@ -56,6 +67,8 @@ OUT="ma_pois.pmtiles" NAMES_OUT="poi_names.bin" INDEX_OUT="poi_index.bin" ATTRS_OUT=""+SPATIAL_OUT=""+NAME_INDEX_OUT="" BBOX="" MINZOOM=12 MAXZOOM=16@@ -69,6 +82,8 @@ while [[ $# -gt 0 ]]; do --names-out) NAMES_OUT="$2"; shift 2 ;; --index-out) INDEX_OUT="$2"; shift 2 ;; --attrs-out) ATTRS_OUT="$2"; shift 2 ;;+ --spatial-out) SPATIAL_OUT="$2"; shift 2 ;;+ --name-index-out) NAME_INDEX_OUT="$2"; shift 2 ;; --bbox) BBOX="$2"; shift 2 ;; --minzoom) MINZOOM="$2"; shift 2 ;; --maxzoom) MAXZOOM="$2"; shift 2 ;;@@ -82,6 +97,8 @@ done # Beside the index by default, because that is where the app looks for it and # because the two are only meaningful as a pair. [[ -n "$ATTRS_OUT" ]] || ATTRS_OUT="$(dirname "$INDEX_OUT")/poi_attrs.bin"+[[ -n "$SPATIAL_OUT" ]] || SPATIAL_OUT="$(dirname "$INDEX_OUT")/poi_spatial.bin"+[[ -n "$NAME_INDEX_OUT" ]] || NAME_INDEX_OUT="$(dirname "$INDEX_OUT")/poi_name_index.bin" [[ -n "$PBF" ]] || { echo "ERROR: --pbf required" >&2; exit 1; } [[ -f "$PBF" ]] || { echo "ERROR: pbf not found: $PBF" >&2; exit 1; }@@ -110,13 +127,15 @@ if [[ -n "$BBOX" ]]; then SRC="$TMP/metro.osm.pbf" fi -echo "[ma_pois] extracting POIs -> geojsonseq + $NAMES_OUT + $INDEX_OUT + $ATTRS_OUT"+echo "[ma_pois] extracting POIs -> geojsonseq + $NAMES_OUT + $INDEX_OUT + $ATTRS_OUT + $SPATIAL_OUT + $NAME_INDEX_OUT" cargo run --release --manifest-path "$HERE/osm_ingest/Cargo.toml" --bin poi_extract -- \ "$SRC" \ --geojson "$TMP/ma_pois.geojsonseq" \ --names "$NAMES_OUT" \ --index "$INDEX_OUT" \- --attrs "$ATTRS_OUT"+ --attrs "$ATTRS_OUT" \+ --spatial "$SPATIAL_OUT" \+ --name-index "$NAME_INDEX_OUT" FEATURES="$(wc -l < "$TMP/ma_pois.geojsonseq" | tr -d ' ')" echo "[ma_pois] $FEATURES POI feature(s)"
scripts/maps/build_v5_pmtiles.sh
diff --git a/scripts/maps/build_v5_pmtiles.sh b/scripts/maps/build_v5_pmtiles.shindex e95b5fa3be..3c575ed3d9 100644--- a/scripts/maps/build_v5_pmtiles.sh+++ b/scripts/maps/build_v5_pmtiles.sh@@ -306,7 +306,9 @@ if [[ "$SKIP_POIS" == "0" ]]; then [[ -n "$PBF" ]] || { echo "ERROR: --pbf required for ma_pois layer (or --skip-pois)" >&2; exit 1; } POIS_ARGS=(--pbf "$PBF" --out "$WORK/ma_pois.pmtiles" \ --names-out "$OUTDIR/poi_names.bin" --index-out "$OUTDIR/poi_index.bin" \- --attrs-out "$OUTDIR/poi_attrs.bin")+ --attrs-out "$OUTDIR/poi_attrs.bin" \+ --spatial-out "$OUTDIR/poi_spatial.bin" \+ --name-index-out "$OUTDIR/poi_name_index.bin") [[ -n "$BBOX" ]] && POIS_ARGS+=(--bbox "$BBOX") run "$HERE/build_pois_layer.sh" "${POIS_ARGS[@]}" INPUTS+=("$WORK/ma_pois.pmtiles")@@ -408,6 +410,8 @@ if [[ "$SKIP_POIS" == "0" ]]; then echo " $OUTDIR/poi_names.bin (deduped NUL-terminated UTF-8 name table)" echo " $OUTDIR/poi_index.bin (flat 14-byte records: lat_e7,lon_e7,name_off,type)" echo " $OUTDIR/poi_attrs.bin (attribute sidecar, keyed by poi_index record ordinal)"+ echo " $OUTDIR/poi_spatial.bin (sparse CSR lat/lon grid over record ordinals)"+ echo " $OUTDIR/poi_name_index.bin (one (record, word) entry per word, word-sorted)" echo "" fi
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex 88aa87eae2..961fd696c2 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -6,7 +6,7 @@ Maps app's offline artifacts. Three binaries share one library: | Binary | Replaces | Emits | |---|---|---| | `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `intermediate.bin`, `road_names.bin` |-| `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin`, `poi_attrs.bin` |+| `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin`, `poi_attrs.bin`, `poi_spatial.bin`, `poi_name_index.bin` | | `osm_extract` | `osmium tags-filter \| osmium export \| normalize_*.py` | one `<layer>.geojsonseq` per baked vector layer | ## Why Rust (LANGUAGE RULE)@@ -37,7 +37,9 @@ cargo run --release --bin road_graph -- california-latest.osm.pbf --out map_data # POI layer side files + the geojsonseq tippecanoe consumes cargo run --release --bin poi_extract -- california-latest.osm.pbf \ --geojson pois.geojsonseq --names poi_names.bin --index poi_index.bin \- --attrs poi_attrs.bin+ --attrs poi_attrs.bin \+ --spatial poi_spatial.bin \+ --name-index poi_name_index.bin # One baked vector layer, with the bbox clip done inline (no osmium extract) cargo run --release --bin osm_extract -- california-latest.osm.pbf \@@ -139,6 +141,8 @@ changing its reader produces a graph that loads as garbage, which is why | `poi_index.bin` | 14-byte records: `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type`, Morton-sorted | `PoiIndex.kt` | | `poi_names.bin` | same pool convention as `road_names.bin` | `PoiIndex.kt` | | `poi_attrs.bin` | attribute sidecar keyed by `poi_index.bin` record ordinal; layout in `src/poi_attrs.rs` | `PoiIndex.kt` |+| `poi_spatial.bin` | sparse CSR lat/lon grid over record ordinals, so a bbox query is cell-local; layout in `src/poi_side.rs` | `PoiIndex.kt` |+| `poi_name_index.bin` | one `(record, word)` entry per word of every name, sorted by word; layout in `src/poi_side.rs` | `PoiIndex.kt` | `GRAPH_VERSION` is **5**. Version 1 stored a 16-byte node record and a dense `u64` offset per edge in both blob files; version 2 fixed that, and version 3 gave
scripts/maps/osm_ingest/src/bin/poi_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/poi_extract.rs b/scripts/maps/osm_ingest/src/bin/poi_extract.rsindex 8c9ee12081..f83e0d05a3 100644--- a/scripts/maps/osm_ingest/src/bin/poi_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -25,6 +25,8 @@ fn main() -> ExitCode { &args.names, &args.index, &args.attrs,+ &args.spatial,+ &args.name_index, ) { Ok(stats) => { println!(@@ -43,11 +45,17 @@ fn main() -> ExitCode { stats.with_attrs, stats.unique_attrs, stats.attr_bytes ); println!(- "Wrote {}, {}, {}, {}",+ "{} populated grid cell(s), {} name index entr(ies)",+ stats.spatial_cells, stats.name_entries+ );+ println!(+ "Wrote {}, {}, {}, {}, {}, {}", args.geojson.display(), args.names.display(), args.index.display(),- args.attrs.display()+ args.attrs.display(),+ args.spatial.display(),+ args.name_index.display() ); ExitCode::SUCCESS }
scripts/maps/osm_ingest/src/lib.rs
diff --git a/scripts/maps/osm_ingest/src/lib.rs b/scripts/maps/osm_ingest/src/lib.rsindex 7ad6752b35..2a54dff75b 100644--- a/scripts/maps/osm_ingest/src/lib.rs+++ b/scripts/maps/osm_ingest/src/lib.rs@@ -32,6 +32,7 @@ pub mod par; pub mod pbf; pub mod poi_attrs; pub mod poi_build;+pub mod poi_side; pub mod proto; pub mod rings; pub mod safety;
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex e5cfc881f8..eb0058ad6f 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -46,6 +46,7 @@ use crate::names::NamePool; use crate::osm::{self, visit_block, Element, MEMBER_WAY}; use crate::pbf::{self, KIND_NODES, KIND_RELATIONS, KIND_WAYS}; use crate::poi_attrs::AttrPool;+use crate::poi_side; use crate::proto::{Error, Result}; use crate::spatial::spatial_from_e7; use crate::tags::{self, PoiTags};@@ -67,6 +68,10 @@ pub struct Stats { pub with_attrs: usize, pub unique_attrs: usize, pub attr_bytes: usize,+ /// Populated cells in `poi_spatial.bin`.+ pub spatial_cells: usize,+ /// `(record, word)` entries in `poi_name_index.bin`.+ pub name_entries: usize, } struct Poi {@@ -125,10 +130,12 @@ pub fn build( names: &Path, index: &Path, attrs: &Path,+ spatial: &Path,+ name_index: &Path, ) -> Result<Stats> { // Fail before the three passes rather than after them if an output path is // unwritable.- for path in [geojson, names, index, attrs] {+ for path in [geojson, names, index, attrs, spatial, name_index] { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { std::fs::create_dir_all(parent) .map_err(|e| Error(format!("cannot create {}: {e}", parent.display())))?;@@ -255,7 +262,7 @@ pub fn build( // are stable across runs. pois.sort_by_key(|p| (p.morton, p.osm_id)); - let written = write_outputs(&pois, geojson, names, index, attrs)?;+ let written = write_outputs(&pois, geojson, names, index, attrs, spatial, name_index)?; Ok(Stats { records: written.records, unique_names: written.unique_names,@@ -266,6 +273,8 @@ pub fn build( with_attrs: written.with_attrs, unique_attrs: written.unique_attrs, attr_bytes: written.attr_bytes,+ spatial_cells: written.spatial_cells,+ name_entries: written.name_entries, }) } @@ -453,6 +462,8 @@ struct Written { with_attrs: usize, unique_attrs: usize, attr_bytes: usize,+ spatial_cells: usize,+ name_entries: usize, } fn write_outputs(@@ -461,6 +472,8 @@ fn write_outputs( names: &Path, index: &Path, attrs: &Path,+ spatial: &Path,+ name_index: &Path, ) -> Result<Written> { let mut pool = NamePool::new(BufWriter::new(create(names)?)); let mut index_out = BufWriter::new(create(index)?);@@ -495,6 +508,20 @@ fn write_outputs( attr_pool.write(&mut attrs_out).map_err(io_err)?; attrs_out.flush().map_err(io_err)?; + // Both side files are derived from the same Morton-sorted vector as the index, in+ // the same function, for the same reason the sidecar is: they join by record+ // ordinal, and any second pass over `pois` is an opportunity to disagree.+ let coords: Vec<(i32, i32)> = pois.iter().map(|p| (p.lat_e7, p.lon_e7)).collect();+ let mut spatial_out = BufWriter::new(create(spatial)?);+ let spatial_cells = poi_side::write_spatial(&mut spatial_out, &coords).map_err(io_err)?;+ spatial_out.flush().map_err(io_err)?;++ let name_slices: Vec<&[u8]> = pois.iter().map(|p| p.name.as_slice()).collect();+ let mut name_index_out = BufWriter::new(create(name_index)?);+ let name_entries =+ poi_side::write_name_index(&mut name_index_out, &name_slices).map_err(io_err)?;+ name_index_out.flush().map_err(io_err)?;+ index_out.flush().map_err(io_err)?; geojson_out.flush().map_err(io_err)?; let unique = pool.unique_count();@@ -510,6 +537,9 @@ fn write_outputs( attr_pool.unique_count(), attr_pool.total_len() );+ println!(+ "Wrote {spatial_cells} populated grid cell(s), {name_entries} name index entr(ies)"+ ); Ok(Written { records: pois.len(), unique_names: unique,@@ -517,6 +547,8 @@ fn write_outputs( with_attrs: attr_pool.with_attrs(), unique_attrs: attr_pool.unique_count(), attr_bytes: attr_pool.total_len(),+ spatial_cells,+ name_entries, }) } @@ -534,23 +566,29 @@ pub struct Args { pub names: PathBuf, pub index: PathBuf, pub attrs: PathBuf,+ pub spatial: PathBuf,+ pub name_index: PathBuf, } /// `poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE [--attrs FILE]`+/// `[--spatial FILE] [--name-index FILE]` ///-/// `--attrs` defaults to `poi_attrs.bin` beside `--index`, so a caller that predates-/// the sidecar keeps working and still emits it. Making it required would break-/// build_pois_layer.sh and build_all.* on the same commit.+/// The optional outputs default to their conventional names beside `--index`, so a+/// caller that predates any of them keeps working and still emits them. Making them+/// required would break build_pois_layer.sh and build_all.* on the same commit. pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { let mut input: Option<PathBuf> = None; let mut geojson: Option<PathBuf> = None; let mut names: Option<PathBuf> = None; let mut index: Option<PathBuf> = None; let mut attrs: Option<PathBuf> = None;+ let mut spatial: Option<PathBuf> = None;+ let mut name_index: Option<PathBuf> = None; let mut i = 0; while i < args.len() { match args[i].as_str() {- flag @ ("--geojson" | "--names" | "--index" | "--attrs") => {+ flag @ ("--geojson" | "--names" | "--index" | "--attrs" | "--spatial"+ | "--name-index") => { let flag = flag.to_string(); i += 1; let value = args@@ -561,6 +599,8 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { "--geojson" => geojson = Some(value), "--names" => names = Some(value), "--attrs" => attrs = Some(value),+ "--spatial" => spatial = Some(value),+ "--name-index" => name_index = Some(value), _ => index = Some(value), } }@@ -581,12 +621,16 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> { let names = names.ok_or_else(|| "--names is required".to_string())?; let index = index.ok_or_else(|| "--index is required".to_string())?; let attrs = attrs.unwrap_or_else(|| index.with_file_name("poi_attrs.bin"));+ let spatial = spatial.unwrap_or_else(|| index.with_file_name("poi_spatial.bin"));+ let name_index = name_index.unwrap_or_else(|| index.with_file_name("poi_name_index.bin")); Ok(Args { input, geojson, names, index, attrs,+ spatial,+ name_index, }) } @@ -666,6 +710,8 @@ mod tests { &dir.join("poi_names.bin"), &dir.join("poi_index.bin"), &dir.join("poi_attrs.bin"),+ &dir.join("poi_spatial.bin"),+ &dir.join("poi_name_index.bin"), ) .unwrap(); (stats, dir)@@ -779,6 +825,8 @@ mod tests { &dir.join(format!("names{suffix}.bin")), &dir.join(format!("index{suffix}.bin")), &dir.join(format!("attrs{suffix}.bin")),+ &dir.join(format!("spatial{suffix}.bin")),+ &dir.join(format!("nameidx{suffix}.bin")), ) .unwrap(); };@@ -789,6 +837,8 @@ mod tests { ("namesa.bin", "namesb.bin"), ("indexa.bin", "indexb.bin"), ("attrsa.bin", "attrsb.bin"),+ ("spatiala.bin", "spatialb.bin"),+ ("nameidxa.bin", "nameidxb.bin"), ] { assert_eq!( std::fs::read(dir.join(a)).unwrap(),
scripts/maps/osm_ingest/src/poi_side.rs
diff --git a/scripts/maps/osm_ingest/src/poi_side.rs b/scripts/maps/osm_ingest/src/poi_side.rsnew file mode 100644index 0000000000..8c2812a207--- /dev/null+++ b/scripts/maps/osm_ingest/src/poi_side.rs@@ -0,0 +1,390 @@+//! The two optional POI side files: `poi_spatial.bin` and `poi_name_index.bin`.+//!+//! Both exist to remove lookups whose cost grew with the size of the whole dataset.+//! `poi_index.bin` is Morton-sorted, which bounds a bbox query by the *Morton span* of+//! that bbox — and a box straddling a high-order Morton boundary spans a huge key+//! interval even when it is geographically tiny. A plain row/column grid has no such+//! pathology, so `nearest`/`inViewport` become exactly cell-local. Name search had no+//! index at all and scanned the name pool and then every record.+//!+//! ## Layouts+//!+//! Both files are little-endian, self-describing (unlike the transit pack's grid, whose+//! parameters live in a shared header), and both carry the record count so a reader can+//! refuse a side file left over from a different `poi_index.bin` rather than silently+//! joining by a stale ordinal.+//!+//! **`poi_spatial.bin`** — the sparse CSR grid the transit pack already uses+//! (`gtfs_ingest/src/index.rs`, read by `maps/src/main/rust/src/transit.rs`), so there+//! is a working reference on both sides:+//!+//! ```text+//! magic "PSP1" | u32 version | u32 record_count | u32 cell_count+//! i32 lat0_e7 | i32 lon0_e7 | u32 cell_e7 | u32 cols (32-byte header)+//! u32 cell_ids[cell_count] ascending, populated cells only+//! u32 cell_off[cell_count + 1] CSR prefix into ordinals+//! u32 ordinals[record_count] grouped by cell, ascending within a cell+//! ```+//!+//! **`poi_name_index.bin`** — one entry per (record, word), sorted by the word:+//!+//! ```text+//! magic "PNI1" | u32 version | u32 record_count | u32 entry_count (16-byte header)+//! u32 ordinals[entry_count] the record the word belongs to+//! u8 word_idx[entry_count] which word of that record's name+//! ```+//!+//! Parallel arrays rather than a packed struct, so an entry costs 5 bytes and not the 8+//! that alignment would round it up to. It is still the largest of the POI files:+//! indexing *every* word, not just the name's first, means the entry count is roughly+//! the record count times the average word count, and it cannot be per-*name* instead —+//! `poi_names.bin` is deduplicated, so a word only identifies a name, and a name still+//! has to be resolved to the records that use it.+//!+//! ## The cross-language contract+//!+//! A sorted index is only searchable if the reader orders words exactly as the writer+//! did, so both sides commit to this and nothing subtler:+//!+//! * A **word** is a maximal run of bytes that are not ASCII whitespace. Splitting on+//! whitespace only is safe on raw UTF-8 because no byte of a multi-byte sequence is+//! ever below `0x80`.+//! * The **sort key** is the word's bytes with ASCII `A-Z` mapped to lowercase and every+//! other byte, including all non-ASCII, left alone. Deliberately *not* Unicode+//! case folding: `str::to_lowercase` and Kotlin's `String.lowercase` do not agree+//! byte-for-byte on every input, and a disagreement here is a silently unfindable POI.+//! * At most [`MAX_WORDS`] words per name are indexed, since the word index is a `u8`.+//!+//! The Kotlin reader is `PoiIndex.kt`; [`tests`] pins the ordering from this side.++use std::cmp::Ordering;+use std::io::{self, Write};++pub const SPATIAL_MAGIC: &[u8; 4] = b"PSP1";+pub const SPATIAL_VERSION: u32 = 1;+pub const SPATIAL_HEADER_BYTES: usize = 32;++pub const NAME_MAGIC: &[u8; 4] = b"PNI1";+pub const NAME_VERSION: u32 = 1;+pub const NAME_HEADER_BYTES: usize = 16;++/// Grid cell size in 1e-7 degrees: 0.02°, the same as the transit pack's.+pub const CELL_E7: u32 = 200_000;++/// Words indexed per name. Bounded because the word index is stored as a `u8`.+pub const MAX_WORDS: usize = 255;++/// ASCII-only lowercase. See the module's cross-language contract.+#[inline]+pub fn ascii_lower(b: u8) -> u8 {+ if b.is_ascii_uppercase() {+ b + 32+ } else {+ b+ }+}++/// Order two words as the index is sorted: ASCII-lowercased byte order.+pub fn cmp_word(a: &[u8], b: &[u8]) -> Ordering {+ let common = a.len().min(b.len());+ for i in 0..common {+ match ascii_lower(a[i]).cmp(&ascii_lower(b[i])) {+ Ordering::Equal => {}+ other => return other,+ }+ }+ a.len().cmp(&b.len())+}++/// The whitespace-separated words of `name`, paired with their index, capped at+/// [`MAX_WORDS`].+pub fn words(name: &[u8]) -> impl Iterator<Item = (u8, &[u8])> {+ name.split(|b| b.is_ascii_whitespace())+ .filter(|w| !w.is_empty())+ .take(MAX_WORDS)+ .enumerate()+ .map(|(i, w)| (i as u8, w))+}++/// The `word_idx`th word of `name`, or `None` when the name has fewer.+///+/// The reader needs the same lookup, so this is the definition both sides share rather+/// than each re-deriving "which run of bytes is word 3".+pub fn word_at(name: &[u8], word_idx: u8) -> Option<&[u8]> {+ words(name).find(|(i, _)| *i == word_idx).map(|(_, w)| w)+}++/// Where the grid is anchored and how wide it is.+///+/// Anchored at the minimum corner of the records' own extent, like the transit pack's,+/// so a regional extract does not pay for cells covering the rest of the planet.+pub struct Grid {+ pub lat0_e7: i32,+ pub lon0_e7: i32,+ pub cols: u32,+}++impl Grid {+ /// Fit a grid to `coords`. `None` when there are no records to bound.+ pub fn fit(coords: &[(i32, i32)]) -> Option<Grid> {+ let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX);+ let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN);+ for &(lat, lon) in coords {+ min_lat = min_lat.min(lat);+ min_lon = min_lon.min(lon);+ max_lat = max_lat.max(lat);+ max_lon = max_lon.max(lon);+ }+ if min_lat > max_lat {+ return None;+ }+ let cols = cell_axis(max_lon, min_lon) + 1;+ Some(Grid {+ lat0_e7: min_lat,+ lon0_e7: min_lon,+ cols,+ })+ }++ pub fn row(&self, lat_e7: i32) -> u32 {+ cell_axis(lat_e7, self.lat0_e7)+ }++ pub fn col(&self, lon_e7: i32) -> u32 {+ cell_axis(lon_e7, self.lon0_e7).min(self.cols.saturating_sub(1))+ }++ pub fn cell(&self, lat_e7: i32, lon_e7: i32) -> u32 {+ self.row(lat_e7)+ .saturating_mul(self.cols)+ .saturating_add(self.col(lon_e7))+ }+}++/// Cell offset of `value` from the grid origin, floored at 0.+fn cell_axis(value: i32, origin: i32) -> u32 {+ let d = value as i64 - origin as i64;+ if d <= 0 {+ 0+ } else {+ (d / CELL_E7 as i64) as u32+ }+}++/// Write `poi_spatial.bin` for records whose coordinates are `coords[ordinal]`.+///+/// Returns the number of populated cells. Writes a valid, empty grid for no records+/// rather than refusing, so the file's presence never depends on the extract.+pub fn write_spatial<W: Write>(out: &mut W, coords: &[(i32, i32)]) -> io::Result<usize> {+ let grid = Grid::fit(coords);+ let (lat0, lon0, cols) = match &grid {+ Some(g) => (g.lat0_e7, g.lon0_e7, g.cols),+ None => (0, 0, 0),+ };++ // (cell, ordinal), sorted so equal cells are adjacent and ordinals ascend within+ // one — the order the CSR encodes, and the order a reader walks.+ let mut pairs: Vec<(u32, u32)> = Vec::with_capacity(coords.len());+ if let Some(g) = &grid {+ for (ordinal, &(lat, lon)) in coords.iter().enumerate() {+ pairs.push((g.cell(lat, lon), ordinal as u32));+ }+ }+ pairs.sort_unstable();++ let mut cell_ids: Vec<u32> = Vec::new();+ let mut cell_off: Vec<u32> = Vec::new();+ for (i, &(cell, _)) in pairs.iter().enumerate() {+ if cell_ids.last() != Some(&cell) {+ cell_ids.push(cell);+ cell_off.push(i as u32);+ }+ }+ cell_off.push(pairs.len() as u32);++ out.write_all(SPATIAL_MAGIC)?;+ out.write_all(&SPATIAL_VERSION.to_le_bytes())?;+ out.write_all(&(coords.len() as u32).to_le_bytes())?;+ out.write_all(&(cell_ids.len() as u32).to_le_bytes())?;+ out.write_all(&lat0.to_le_bytes())?;+ out.write_all(&lon0.to_le_bytes())?;+ out.write_all(&CELL_E7.to_le_bytes())?;+ out.write_all(&cols.to_le_bytes())?;+ for id in &cell_ids {+ out.write_all(&id.to_le_bytes())?;+ }+ for off in &cell_off {+ out.write_all(&off.to_le_bytes())?;+ }+ for &(_, ordinal) in &pairs {+ out.write_all(&ordinal.to_le_bytes())?;+ }+ Ok(cell_ids.len())+}++/// Write `poi_name_index.bin` for records whose names are `names[ordinal]`.+///+/// Returns the number of entries. The sort resolves each entry's word out of `names`+/// rather than materialising it, which keeps the working set to 8 bytes per entry+/// instead of that plus a copy of every word.+pub fn write_name_index<W: Write>(out: &mut W, names: &[&[u8]]) -> io::Result<usize> {+ let mut entries: Vec<(u32, u8)> = Vec::new();+ for (ordinal, name) in names.iter().enumerate() {+ for (word_idx, _) in words(name) {+ entries.push((ordinal as u32, word_idx));+ }+ }+ // Ordinal breaks ties so the file is reproducible: two runs over the same input+ // must be byte-identical, which an unstable sort only gives on a total order.+ entries.sort_unstable_by(|a, b| {+ let wa = word_at(names[a.0 as usize], a.1).unwrap_or_default();+ let wb = word_at(names[b.0 as usize], b.1).unwrap_or_default();+ cmp_word(wa, wb).then(a.cmp(b))+ });++ out.write_all(NAME_MAGIC)?;+ out.write_all(&NAME_VERSION.to_le_bytes())?;+ out.write_all(&(names.len() as u32).to_le_bytes())?;+ out.write_all(&(entries.len() as u32).to_le_bytes())?;+ for &(ordinal, _) in &entries {+ out.write_all(&ordinal.to_le_bytes())?;+ }+ for &(_, word_idx) in &entries {+ out.write_all(&[word_idx])?;+ }+ Ok(entries.len())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn u32_at(bytes: &[u8], at: usize) -> u32 {+ u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())+ }++ #[test]+ fn words_split_on_whitespace_only() {+ let got: Vec<&[u8]> = words(b"Joe's Pizza\tBar").map(|(_, w)| w).collect();+ assert_eq!(got, vec![&b"Joe's"[..], &b"Pizza"[..], &b"Bar"[..]]);+ }++ #[test]+ fn word_indices_count_from_zero() {+ let name = b"San Francisco Public Library";+ assert_eq!(word_at(name, 0), Some(&b"San"[..]));+ assert_eq!(word_at(name, 3), Some(&b"Library"[..]));+ assert_eq!(word_at(name, 4), None);+ }++ /// Only ASCII folds. A Unicode-aware lowercase would disagree with the reader.+ #[test]+ fn comparison_folds_ascii_and_leaves_other_bytes_alone() {+ assert_eq!(cmp_word(b"PIZZA", b"pizza"), Ordering::Equal);+ assert_eq!(cmp_word(b"Cafe", b"cafz"), Ordering::Less);+ // U+00C9 vs U+00E9: both pass through, so they order by raw byte.+ assert_eq!(cmp_word("É".as_bytes(), "é".as_bytes()), Ordering::Less);+ }++ #[test]+ fn a_shorter_word_sorts_before_a_longer_one_sharing_its_prefix() {+ assert_eq!(cmp_word(b"pizz", b"pizza"), Ordering::Less);+ }++ #[test]+ fn the_grid_is_anchored_at_the_records_minimum_corner() {+ let coords = [(37_700_000, -122_400_000), (37_720_000, -122_380_000)];+ let g = Grid::fit(&coords).expect("records exist");+ assert_eq!(g.lat0_e7, 37_700_000);+ assert_eq!(g.lon0_e7, -122_400_000);+ assert_eq!(g.cell(37_700_000, -122_400_000), 0);+ }++ #[test]+ fn an_empty_extract_has_no_grid() {+ assert!(Grid::fit(&[]).is_none());+ }++ #[test]+ fn the_spatial_csr_groups_every_ordinal_under_its_cell() {+ // Two POIs in one cell (0.02deg apart is one cell over, so keep them closer)+ // and a third far away.+ let coords = [+ (37_700_000, -122_400_000),+ (37_700_100, -122_400_100),+ (38_000_000, -122_000_000),+ ];+ let mut buf = Vec::new();+ let cells = write_spatial(&mut buf, &coords).unwrap();+ assert_eq!(cells, 2, "two populated cells");+ assert_eq!(&buf[0..4], SPATIAL_MAGIC);+ assert_eq!(u32_at(&buf, 8), 3, "record count");+ assert_eq!(u32_at(&buf, 12), 2, "cell count");++ let ids = SPATIAL_HEADER_BYTES;+ let off = ids + 4 * cells;+ let ords = off + 4 * (cells + 1);+ assert!(u32_at(&buf, ids) < u32_at(&buf, ids + 4), "cell ids ascend");+ assert_eq!(u32_at(&buf, off), 0);+ assert_eq!(u32_at(&buf, off + 4), 2, "first cell holds two records");+ assert_eq!(u32_at(&buf, off + 8), 3);+ assert_eq!(u32_at(&buf, ords), 0);+ assert_eq!(u32_at(&buf, ords + 4), 1);+ assert_eq!(u32_at(&buf, ords + 8), 2);+ assert_eq!(buf.len(), ords + 4 * coords.len());+ }++ #[test]+ fn the_name_index_sorts_every_word_of_every_record() {+ let names: Vec<&[u8]> = vec![b"Joe's Pizza", b"Pizza Hut"];+ let mut buf = Vec::new();+ let entries = write_name_index(&mut buf, &names).unwrap();+ assert_eq!(entries, 4, "two words each");+ assert_eq!(&buf[0..4], NAME_MAGIC);+ assert_eq!(u32_at(&buf, 8), 2, "record count");+ assert_eq!(u32_at(&buf, 12), 4, "entry count");++ // Sorted: "hut", "joe's", "pizza"(#0 word 1), "pizza"(#1 word 0).+ let ord = NAME_HEADER_BYTES;+ let widx = ord + 4 * entries;+ let got: Vec<(u32, u8)> =+ (0..entries).map(|i| (u32_at(&buf, ord + 4 * i), buf[widx + i])).collect();+ assert_eq!(got, vec![(1, 1), (0, 0), (0, 1), (1, 0)]);+ }++ /// Both words of a name resolve to the same record, which is what makes "pizza"+ /// find "Joe's Pizza" without a scan.+ #[test]+ fn a_trailing_word_still_points_at_its_record() {+ let names: Vec<&[u8]> = vec![b"Joe's Pizza"];+ let mut buf = Vec::new();+ let entries = write_name_index(&mut buf, &names).unwrap();+ assert_eq!(entries, 2);+ let widx = NAME_HEADER_BYTES + 4 * entries;+ assert_eq!(u32_at(&buf, NAME_HEADER_BYTES), 0);+ assert_eq!(buf[widx], 0, "\"joe's\" first");+ assert_eq!(buf[widx + 1], 1, "then \"pizza\"");+ }++ #[test]+ fn two_runs_over_the_same_input_are_byte_identical() {+ let names: Vec<&[u8]> = vec![b"Cafe Roma", b"Roma Cafe", b"Cafe Roma"];+ let coords = [(1_000, 2_000), (3_000, 4_000), (5_000, 6_000)];+ let (mut a, mut b) = (Vec::new(), Vec::new());+ write_name_index(&mut a, &names).unwrap();+ write_name_index(&mut b, &names).unwrap();+ assert_eq!(a, b);+ let (mut c, mut d) = (Vec::new(), Vec::new());+ write_spatial(&mut c, &coords).unwrap();+ write_spatial(&mut d, &coords).unwrap();+ assert_eq!(c, d);+ }++ #[test]+ fn an_unnamed_record_contributes_no_entries() {+ let names: Vec<&[u8]> = vec![b"", b" ", b"Real Name"];+ let mut buf = Vec::new();+ assert_eq!(write_name_index(&mut buf, &names).unwrap(), 2);+ assert_eq!(u32_at(&buf, 8), 3, "record count still counts them");+ }+}