Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / maps / src / main / java / com / vayunmathur / maps / data / PoiSearchEngine.kt

PoiSearchEngine.kt499 lines · 21.9 KiBRaw
1package com.vayunmathur.maps.data
2import com.vayunmathur.maps.domain.spatialFromE7
3
4/**
5 * The indexed name search: [searchByWordIndex] and the candidate collection behind it.
6 *
7 * Built around what a cold planet archive costs on a phone. The old search was correct but
8 * read far too much: for every query it walked the rarest token's whole word range
9 * checking each entry against its record's name, decoded and distance-sorted up to 5,000
10 * of the matches, then also scanned up to 40,000 records around the user by name. "pizza"
11 * from San Francisco touched 72 k distinct 4 KiB pages (283 MB) of the archive; "hotel"
12 * 92 k. On flash that is seconds per keystroke, which is what "searching takes forever"
13 * was. This version keeps the same answer shape while reading a few hundred pages:
14 *
15 * 1. **Tokens -> word ranges** (two binary searches per spelling, [queryTokens]).
16 * 2. **Candidates from ordinals only.** The rarest token's range is scanned sequentially
17 * into a [HitTable]; every other token's range is scanned and marked against it, so a
18 * multi-word query is an intersection of entry arrays — no names read. Word positions
19 * ride along, so "phrase" vs "every word" is known without the name too.
20 * 3. **Where.** A small survivor set is placed in full (it is the whole world's answer:
21 * "british museum", "ferry building"). A large one ("pizza", 81 k entries) is joined
22 * against the spatial grid in growing boxes around the bias point, then — only when
23 * those boxes yield too little — against a window of survivors nearest the bias point
24 * in Morton (= file) order. Coordinates are read only for rows that are actually
25 * near.
26 * 4. **Categories.** A purely categorical query ("coffee", "gas station") also
27 * collects the nearest places of the matching POI types over the same grid
28 * rings, at category tier — their names need not contain the words.
29 * 5. **Fallbacks only when short of results:** a name scan of the few thousand records
30 * closest to the bias point (mid-word substrings, typos, punctuation), then the
31 * index-wide typo lookup.
32 * 6. **Rank and decode** at most [SHORTLIST] names ([rankCandidates]: one blended score of
33 * text match and distance).
34 *
35 * Every scan polls the caller's cancel token, so a superseded keystroke stops promptly.
36 */
37
38/** Longest token range that is scanned at all; longer ones (one- or two-letter
39 * prefixes like "s") are checked against candidates' names instead. */
40private const val STREAM_CAP = 1_500_000
41
42/** Largest driver range materialised into a table (the others are joined ring by ring). */
43private const val MATERIALIZE_CAP = 250_000
44
45/** Survivor sets up to this size are placed whole: their coordinates are all read. */
46private const val GLOBAL_ALL_CAP = 1_500
47
48/** Half-sizes of the boxes around the bias point the grid join grows through. */
49private val RING_HALF_KM = doubleArrayOf(1.5, 8.0, 25.0)
50
51/**
52 * Boxes always joined, even when the first already filled the page: a city's landmark a
53 * few km out ("golden gate" -> the bridge, 6.5 km from Union Square) must get to compete
54 * with the dozen "Golden Gate …" shops next door. The join is a sequential grid read.
55 */
56private const val MIN_RINGS = 2
57
58/** Survivors nearest the bias point in file order read when the boxes come up short. */
59private const val REGIONAL_WINDOW = 1_500
60
61/** The name-scan fallback's box half-size and record budget. */
62private const val NAME_SCAN_HALF_KM = 0.8
63private const val NAME_SCAN_BUDGET = 5_000
64
65/** Candidates whose names are decoded for the final ranking. */
66private const val SHORTLIST = 30
67
68/** Shortest token allowed to drive the candidate scan. */
69private const val MIN_DRIVER_LEN = 2
70
71private const val KM_PER_DEGREE = 111.32
72private const val E7_PER_DEGREE = 1e7
73private const val MIN_COS_LAT = 1e-6
74private const val POLL_EVERY = 4_096
75
76/** One candidate row: where it is and how its name matched (a [PoiSearch] tier). */
77internal class Candidate(
78 val ordinal: Int,
79 val latE7: Int,
80 val lonE7: Int,
81 val type: Int,
82 var tier: Int,
83 val distKm: Double,
84)
85
86/**
87 * Name search over the word index. See the file comment for the phases; ranking is
88 * [rankCandidates].
89 */
90internal fun searchByWordIndex(
91 m: PoiIndex.Mapped,
92 query: String,
93 bias: SearchBias,
94 cancelled: () -> Boolean = { false },
95): List<PoiIndex.PoiRecord> {
96 val tokens = m.queryTokens(query)
97 if (tokens.isEmpty()) return emptyList()
98 val search = CandidateSearch(m, query, tokens, bias, cancelled)
99 search.collectIndexed()
100 search.collectCategory()
101 if (search.size < bias.limit) search.collectNearbyNames(acceptLoose = true)
102 if (search.size < bias.limit / 2) search.collectIndexTypos()
103 if (cancelled()) return emptyList()
104 return rankCandidates(m, query, search.candidates(), bias)
105}
106
107/** Mutable state of one search: the tokens, the bias point and the candidates so far. */
108internal class CandidateSearch(
109 private val m: PoiIndex.Mapped,
110 query: String,
111 private val tokens: List<QueryToken>,
112 private val bias: SearchBias,
113 private val cancelled: () -> Boolean,
114) {
115 private val found = LinkedHashMap<Int, Candidate>()
116 private val queryNorm = PoiSearch.normalize(query)
117 private val queryWords = PoiSearch.tokens(query)
118 private val categoryTypes: Set<Int> = categoryTypesForQuery(queryWords)
119 private val cosLat = Math.cos(Math.toRadians(bias.lat)).coerceAtLeast(MIN_COS_LAT)
120
121 /** The rarest token long enough to drive the scan, or null when none is. */
122 private val driver: Int? = tokens.indices
123 .filter { tokens[it].text.length >= MIN_DRIVER_LEN && tokens[it].size <= STREAM_CAP }
124 .minByOrNull { tokens[it].size }
125
126 /**
127 * Tokens whose ranges are scanned: the driver, and every other token whose range is no
128 * bigger than [MATERIALIZE_CAP] or the driver's own. A two-letter tail ("st" in "123
129 * market st": a million entries against a few thousand) is checked against the names
130 * of the few candidates instead of being read whole.
131 */
132 private val scanned: List<Int> = driver?.let { d ->
133 val cap = maxOf(MATERIALIZE_CAP, tokens[d].size)
134 tokens.indices.filter {
135 it == d || (tokens[it].text.length >= MIN_DRIVER_LEN && tokens[it].size <= cap)
136 }
137 }.orEmpty()
138 private val unscannedKeys: List<List<ByteArray>> = tokens.indices.filter { it !in scanned }
139 .map { tokenKeyVariants(tokens[it].text) }
140
141 val size: Int get() = found.size
142
143 fun candidates(): Collection<Candidate> = found.values
144
145 /** Phases 2-3: candidates from the word index, placed near the bias point first. */
146 fun collectIndexed() {
147 val driver = driver
148 when {
149 // Every token is one letter or matches millions of words: nothing to scan.
150 driver == null -> collectNearbyNames(acceptLoose = false)
151 tokens[driver].size == 0 -> Unit
152 tokens[driver].size <= MATERIALIZE_CAP -> collectMaterialized(driver)
153 else -> collectStreaming(driver)
154 }
155 }
156
157 /**
158 * Category candidates: when every query word is a category term
159 * ("coffee", "gas station"), places of the matching POI types are
160 * candidates at [PoiSearch.TIER_CATEGORY] even though their names do
161 * not contain the words — a cafe called "Starbucks" is what the
162 * coffee chip is asking for. Collected over the same growing grid
163 * rings as the indexed join, nearest first, and capped at a page of
164 * new candidates: farther same-tier places cannot outrank the
165 * nearest ones this already found. A name match already collected
166 * keeps its (better) tier.
167 */
168 fun collectCategory() {
169 if (categoryTypes.isEmpty()) return
170 var added = 0
171 for (half in RING_HALF_KM) {
172 if (cancelled()) return
173 forEachOrdinalNear(half) { o ->
174 if (o !in found && m.type(o) in categoryTypes) {
175 add(o, PoiSearch.TIER_CATEGORY)
176 added++
177 }
178 true
179 }
180 if (added >= bias.limit) return
181 }
182 }
183
184 /** The driver's whole range in a table, intersected with the other scanned tokens. */
185 private fun collectMaterialized(driver: Int) {
186 val table = intersectScanned(driver) ?: return
187 val survivors = BooleanArray(table.size) { i -> scanned.all { table.mask(i, it) != 0L } }
188 val count = survivors.count { it }
189 if (count == 0) return
190 // Near first: the grid's ordinals are a sequential read, a survivor's coordinates a
191 // random one, so even a small survivor set is only placed whole when the boxes
192 // around the bias point did not already fill the page.
193 if (joinRings(table, survivors)) return
194 if (count <= GLOBAL_ALL_CAP) {
195 for (i in 0 until table.size) if (survivors[i]) addIndexed(table.ordinals[i], table, i)
196 } else {
197 collectRegional(table, survivors)
198 }
199 }
200
201 /** The driver's entries in a [HitTable], marked by every scanned token; null when cancelled. */
202 private fun intersectScanned(driver: Int): HitTable? {
203 val table = HitTable(tokens.size, tokens[driver].size)
204 val read = m.scanToken(tokens[driver], cancelled) { o, e ->
205 table.mark(table.add(o), driver, m.entryWordIdx(e))
206 }
207 if (!read) return null
208 for (t in scanned.filter { it != driver }) {
209 val ok = m.scanToken(tokens[t], cancelled) { o, e ->
210 val i = table.indexOf(o)
211 if (i >= 0) table.mark(i, t, m.entryWordIdx(e))
212 }
213 if (!ok) return null
214 }
215 return table
216 }
217
218 /**
219 * Survivors inside the growing boxes around the bias point; true when that settled the
220 * search (the page is full after at least [MIN_RINGS] boxes, or it was cancelled).
221 */
222 private fun joinRings(table: HitTable, survivors: BooleanArray): Boolean {
223 RING_HALF_KM.forEachIndexed { ring, half ->
224 forEachOrdinalNear(half) { o ->
225 val i = table.indexOf(o)
226 if (i >= 0 && survivors[i]) addIndexed(o, table, i)
227 true
228 }
229 if ((ring + 1 >= MIN_RINGS && found.size >= bias.limit) || cancelled()) return true
230 }
231 return false
232 }
233
234 /**
235 * A driver too common to materialise (a two- or three-letter prefix): each box's
236 * records go into a small table and the token ranges are scanned against it.
237 */
238 private fun collectStreaming(driver: Int) {
239 for (half in RING_HALF_KM) {
240 val local = HitTable(tokens.size, POLL_EVERY)
241 var lo = Int.MAX_VALUE
242 var hi = Int.MIN_VALUE
243 forEachOrdinalNear(half) { o ->
244 local.add(o)
245 if (o < lo) lo = o
246 if (o > hi) hi = o
247 true
248 }
249 if (local.size == 0) continue
250 for (t in listOf(driver) + scanned.filter { it != driver }) {
251 // The box's ordinals span a narrow slice of the Morton-ordered file, so most of
252 // a two-letter prefix's million entries are rejected by one compare.
253 val ok = m.scanToken(tokens[t], cancelled) { o, e ->
254 if (o in lo..hi) {
255 val i = local.indexOf(o)
256 if (i >= 0) local.mark(i, t, m.entryWordIdx(e))
257 }
258 }
259 if (!ok) return
260 }
261 for (i in 0 until local.size) {
262 if (scanned.all { local.mask(i, it) != 0L }) addIndexed(local.ordinals[i], local, i)
263 }
264 if (found.size >= bias.limit) return
265 }
266 }
267
268 /**
269 * Survivors nearest the bias point in Morton order — the file's order, so a window of
270 * them around the bias point's own position is mostly the region around it — for when
271 * even the largest box came up short (a rare chain, a small town).
272 */
273 private fun collectRegional(table: HitTable, survivors: BooleanArray) {
274 var n = 0
275 val packed = LongArray(survivors.count { it })
276 for (i in 0 until table.size) {
277 if (survivors[i]) packed[n++] = (table.ordinals[i].toLong() shl Int.SIZE_BITS) or i.toLong()
278 }
279 packed.sort()
280 val centre = m.lowerBound(spatialFromE7(toE7(bias.lat), toE7(bias.lon)))
281 var hi = lowerBoundPacked(packed, centre)
282 var lo = hi - 1
283 var taken = 0
284 while (taken < REGIONAL_WINDOW && (lo >= 0 || hi < packed.size)) {
285 val pickLow = hi >= packed.size ||
286 (lo >= 0 && centre - (packed[lo] ushr Int.SIZE_BITS) <= (packed[hi] ushr Int.SIZE_BITS) - centre)
287 val p = if (pickLow) packed[lo--] else packed[hi++]
288 addIndexed((p ushr Int.SIZE_BITS).toInt(), table, p.toInt())
289 taken++
290 }
291 }
292
293 /**
294 * Phase 4a: names of the records closest to the bias point, matched leniently
295 * ([acceptLoose]: mid-word substrings and typos too) or by word prefix only.
296 */
297 fun collectNearbyNames(acceptLoose: Boolean) {
298 if (queryWords.isEmpty()) return
299 var visited = 0
300 val halves = if (acceptLoose) doubleArrayOf(NAME_SCAN_HALF_KM) else RING_HALF_KM.copyOf(2)
301 for (half in halves) {
302 forEachOrdinalNear(half) { o ->
303 if (o !in found) {
304 visited++
305 val name = m.nameAt(m.nameOff(o))
306 val tier = name?.let { PoiSearch.matchTier(it, queryNorm, queryWords) } ?: PoiSearch.NO_MATCH
307 val accept = tier != PoiSearch.NO_MATCH && (acceptLoose || tier <= PoiSearch.TIER_TOKENS)
308 if (accept) add(o, tier)
309 }
310 visited < NAME_SCAN_BUDGET && !(visited % POLL_EVERY == 0 && cancelled())
311 }
312 if (found.size >= bias.limit || visited >= NAME_SCAN_BUDGET) return
313 }
314 }
315
316 /**
317 * Phase 4b: index-wide typo lookup ([fuzzyWordMatches]), intersected across the tokens
318 * long enough to have a typo budget. Last resort: it costs a binary search per
319 * single-deletion spelling.
320 */
321 fun collectIndexTypos() {
322 val words = tokens.map { it.text }.filter { it.length >= MIN_TYPO_TOKEN_LEN }
323 if (words.isEmpty() || words.size != tokens.size) return
324 var common: Map<Int, Int>? = null
325 for (w in words) {
326 if (cancelled()) return
327 val hits = m.fuzzyWordMatches(w, PoiIndex.CANDIDATE_CAP)
328 common = common?.filterKeys { it in hits } ?: hits
329 }
330 common.orEmpty().keys.forEach { o -> if (o !in found) add(o, PoiSearch.TIER_FUZZY) }
331 }
332
333 /** Add an index candidate whose scanned tokens all matched; checks the rest by name. */
334 private fun addIndexed(ordinal: Int, table: HitTable, index: Int) {
335 if (ordinal in found) return
336 if (unscannedKeys.isNotEmpty() && unscannedKeys.any { !m.nameHasWordPrefix(ordinal, it) }) return
337 // Phrase: token t starts word t, for every scanned token.
338 val phrase = scanned.all { t -> table.mask(index, t) and (1L shl t) != 0L }
339 add(ordinal, if (phrase) PoiSearch.TIER_PREFIX else PoiSearch.TIER_TOKENS)
340 }
341
342 private fun add(ordinal: Int, tier: Int) {
343 val lat = m.latE7(ordinal)
344 val lon = m.lonE7(ordinal)
345 found[ordinal] = Candidate(ordinal, lat, lon, m.type(ordinal), tier, distanceKm(lat, lon))
346 }
347
348 private fun distanceKm(latE7: Int, lonE7: Int): Double =
349 Math.sqrt(distanceSq(bias.lat, bias.lon, latE7 / E7_PER_DEGREE, lonE7 / E7_PER_DEGREE)) *
350 KM_PER_DEGREE
351
352 /** Ordinals filed under the grid cells of the box of half-size [halfKm] around the bias point. */
353 private fun forEachOrdinalNear(halfKm: Double, visit: (Int) -> Boolean) {
354 val dLat = halfKm / KM_PER_DEGREE
355 val dLon = halfKm / (KM_PER_DEGREE * cosLat)
356 m.forEachGridOrdinal(
357 toE7(bias.lat - dLat), toE7(bias.lat + dLat), toE7(bias.lon - dLon), toE7(bias.lon + dLon), visit,
358 )
359 }
360}
361
362/**
363 * The POI types a query asks for by category, or empty when it is not a
364 * purely categorical query. Every word must be a category term, and a
365 * type must satisfy *every* word: "gas station" is fuel (its label and
366 * synonym cover both words), not every station; "coffee shop" names no
367 * single category and stays a name query. Words are singularised first
368 * ("restaurants" -> "restaurant"), as [PoiCategories.typesForTerm]
369 * expects.
370 */
371internal fun categoryTypesForQuery(queryWords: List<String>): Set<Int> {
372 if (queryWords.isEmpty()) return emptySet()
373 var types: Set<Int>? = null
374 for (word in queryWords) {
375 val found = PoiCategories.typesForTerm(PoiSearch.singular(word))
376 if (found.isEmpty()) return emptySet()
377 types = types?.intersect(found) ?: found
378 if (types.isEmpty()) return emptySet()
379 }
380 return types.orEmpty()
381}
382
383private fun toE7(deg: Double): Int = (deg * E7_PER_DEGREE).toInt()
384
385/** First index in [packed] (ordinal in the high half, ascending) whose ordinal is >= [ordinal]. */
386private fun lowerBoundPacked(packed: LongArray, ordinal: Int): Int {
387 var lo = 0
388 var hi = packed.size
389 while (lo < hi) {
390 val mid = (lo + hi) ushr 1
391 if ((packed[mid] ushr Int.SIZE_BITS) < ordinal) lo = mid + 1 else hi = mid
392 }
393 return lo
394}
395
396/**
397 * Text-match penalty per [PoiSearch] tier, in the same units as [distancePenalty] (one unit
398 * = doubling the distance past [DIST_SCALE_KM]). A step between tiers is worth roughly a
399 * 2-3x difference in distance: a "Pizza Hut" a few hundred metres away still beats a
400 * "Joe's Pizza" next door, but not one across town.
401 */
402private fun tierPenalty(tier: Int): Double = when (tier) {
403 PoiSearch.TIER_EXACT -> 0.0
404 PoiSearch.TIER_PREFIX -> PENALTY_PREFIX
405 PoiSearch.TIER_TOKENS -> PENALTY_TOKENS
406 PoiSearch.TIER_SUBSTRING, PoiSearch.TIER_CATEGORY -> PENALTY_SUBSTRING
407 else -> PENALTY_FUZZY
408}
409
410private const val PENALTY_PREFIX = 1.0
411private const val PENALTY_TOKENS = 2.0
412private const val PENALTY_SUBSTRING = 3.5
413private const val PENALTY_FUZZY = 4.5
414
415/** Distance below which places count as equally near (walking distance), in km. */
416private const val DIST_SCALE_KM = 1.0
417
418/**
419 * A place label whose name IS the query (a city, a neighbourhood) is searched for from
420 * afar, and its point stands for a whole area: it gets this much distance credit (~8x).
421 * It used to be a tier of its own above every distance, so from San Francisco "museum"
422 * opened on a village called Museum 16,987 km away and "coffee" on a hamlet 370 km away.
423 */
424private const val PLACE_EXACT_BONUS = 3.0
425
426/**
427 * The most a recency/favorites weight can buy: just under a tier step from a typo, so a
428 * familiar typo never outranks an exact match, while a saved place still wins over a
429 * same-tier match several times nearer.
430 */
431private const val MAX_BOOST_BONUS = 2.9
432
433/**
434 * Distance credit for kinds people search for by name from across a city — landmarks,
435 * parks, museums, stations, place labels — over the shops that borrow their names.
436 */
437private const val NOTABLE_BONUS = 1.0
438
439private val NOTABLE_TYPES = setOf(
440 PoiCategories.TYPE_PARK, PoiCategories.TYPE_ATTRACTION, PoiCategories.TYPE_MUSEUM,
441 PoiCategories.STATION_TYPE, PoiCategories.TYPE_PLACE,
442)
443
444private fun typeBonus(type: Int): Double = if (type in NOTABLE_TYPES) NOTABLE_BONUS else 0.0
445
446private fun distancePenalty(km: Double): Double = log2(1.0 + km / DIST_SCALE_KM)
447
448private fun boostBonus(weight: Double): Double =
449 if (weight <= 0.0) 0.0 else minOf(log2(1.0 + weight), MAX_BOOST_BONUS)
450
451private fun log2(x: Double): Double = Math.log(x) / LN2
452
453private val LN2 = Math.log(2.0)
454
455private class RankedRow(val record: PoiIndex.PoiRecord, val score: Double, val distKm: Double)
456
457/**
458 * Rank by one blended score — text-match penalty + log distance - place/notable/boost credit — and
459 * decode only the rows that can be returned.
460 *
461 * Distance used to be a tie-break: rank buckets first, then "is it exactly the name", and
462 * only then distance, so any exact or phrase match anywhere on earth beat a word match
463 * across the street ("it constantly finds places super far away instead of right here").
464 * Now distance is part of the score, logarithmically: within walking distance the text
465 * decides, beyond it each doubling of distance costs as much as a weaker match.
466 *
467 * Shortlisting uses the most optimistic score a candidate could reach once its name is
468 * read (a phrase match may turn out to be the exact name, a place label may earn the place
469 * credit), so the decode cannot drop a row that would have ranked.
470 */
471internal fun rankCandidates(
472 m: PoiIndex.Mapped,
473 query: String,
474 candidates: Collection<Candidate>,
475 bias: SearchBias,
476): List<PoiIndex.PoiRecord> {
477 val queryNorm = PoiSearch.normalize(query)
478 val queryWords = PoiSearch.tokens(query)
479 val shortlist = candidates.sortedBy { optimisticScore(it) }.take(SHORTLIST)
480 return shortlist.map { c ->
481 val record = m.record(c.ordinal)
482 val tier = PoiSearch.matchTier(record.name, queryNorm, queryWords)
483 .takeIf { it != PoiSearch.NO_MATCH } ?: c.tier
484 val exactPlace = tier == PoiSearch.TIER_EXACT && record.type == PoiCategories.TYPE_PLACE
485 val place = if (exactPlace) PLACE_EXACT_BONUS else 0.0
486 val score = tierPenalty(tier) + distancePenalty(c.distKm) - place - typeBonus(record.type) -
487 boostBonus(boostWeight(bias.boost, record.name))
488 RankedRow(record, score, c.distKm)
489 }.sortedWith(compareBy<RankedRow> { it.score }.thenBy { it.distKm })
490 .take(bias.limit)
491 .map { it.record }
492}
493
494/** The best score [c] can reach once its name is known (see [rankCandidates]). */
495private fun optimisticScore(c: Candidate): Double {
496 val tier = if (c.tier == PoiSearch.TIER_PREFIX) PoiSearch.TIER_EXACT else c.tier
497 val place = if (c.tier == PoiSearch.TIER_PREFIX && c.type == PoiCategories.TYPE_PLACE) PLACE_EXACT_BONUS else 0.0
498 return tierPenalty(tier) + distancePenalty(c.distKm) - place - typeBonus(c.type)
499}