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

Modern-Apps.git / scripts / geocoder_gen.cpp

geocoder_gen.cpp728 lines · 32.8 KiBRaw
1// geocoder_gen.cpp — offline planet geocoder database builder.
2//
3// Reads an OSM-address GeoJSONSeq stream (one GeoJSON Feature per line, as produced by
4// `osmium export`) and writes a packed `geocoder.geodb` that the Modern Apps network-location
5// app mmaps at runtime (see networklocation/.../geocoder/GeoDb.kt + GeoDbReader.kt).
6//
7// This replaces the old in-app Kotlin generator: generating the whole planet needs tens of GB
8// of working memory and a multi-hour run, which does not belong on the JVM test classpath.
9//
10// On-disk format (must byte-match GeoDbReader.kt — all ints/longs are BIG-ENDIAN):
11// int MAGIC = 0x4D414745 ("MAGE")
12// int VERSION = 2 (v2 = per-block codec is Zstandard)
13// int n (record count)
14// 6x dict section : [int size][ [int rawLen][int compLen][zstd(raw)] ]
15// raw = [int count]( [int len][utf8 bytes] )*count
16// order: house, street, city, state, country, postcode
17// street/city/state/country are sorted in Kotlin String order (UTF-16
18// code units) so the reader's binary search (forward geocoding) works.
19// house/postcode are never searched by name (display only), so they are
20// ordered by descending frequency to keep their columns near 1 byte/rec.
21// 8x column section : [int size][ [int n][int blocks]([int rawLen][int compLen])*blocks
22// [zstd block]*blocks ]
23// each block: up to BLOCK values, delta(optional)+zigzag+varint(LEB128).
24// order: lat(delta), lon(delta), house, street, city, state, country,
25// postcode. lat/lon are micro-degrees; the rest are dict indices.
26// Records are in grid-primary order (0.05-deg cell id), and within each
27// cell sorted by (lat, lon) so the coordinate deltas stay tiny.
28// grid section : [int size][ [int cellCount]( [long cellId][int startRec] )*count ]
29// (uncompressed; cellIds ascending)
30// fwd section : one delta column of record indices sorted by
31// (country,state,city,street,house) dict index — for forward lookup.
32//
33// Build (see geocoder_gen.sh):
34// g++ -O2 -fopenmp -std=c++17 geocoder_gen.cpp simdjson.cpp -lzstd -o geocoder_gen
35// Run:
36// ./geocoder_gen generate addr.geojsonseq geocoder.geodb # build (then self-verifies)
37// ./geocoder_gen reencode old.geodb new.geodb # repack with the current encoder
38// ./geocoder_gen verify geocoder.geodb # re-check an existing DB
39
40#include <algorithm>
41#include <cmath>
42#include <cstdint>
43#include <cstdio>
44#include <cstdlib>
45#include <cstring>
46#include <string>
47#include <unordered_map>
48#include <vector>
49
50#include <fcntl.h>
51#include <sys/mman.h>
52#include <sys/stat.h>
53#include <unistd.h>
54
55#include <zstd.h>
56
57#include "simdjson.h"
58
59// ------------------------------------------------------------------ constants (match GeoDb.kt)
60static const uint32_t MAGIC = 0x4D414745u;
61static const uint32_t VERSION = 2u;
62static const int BLOCK = 4096;
63static const int CELL_MICRO = 50000;
64static const int64_t COLS = 360000000LL / CELL_MICRO; // 7200
65static const int MIN_LAT_MICRO = -90000000;
66static const int MIN_LON_MICRO = -180000000;
67static const int ZSTD_LEVEL = 19;
68static const int FIELDS = 6; // house, street, city, state, country, postcode
69enum { F_HOUSE = 0, F_STREET, F_CITY, F_STATE, F_COUNTRY, F_POSTCODE };
70
71[[noreturn]] static void die(const std::string& m) {
72 fprintf(stderr, "geocoder_gen: %s\n", m.c_str());
73 exit(1);
74}
75
76// ------------------------------------------------------------------ little helpers
77static inline void be32(std::string& o, uint32_t v) {
78 o.push_back((char)(v >> 24)); o.push_back((char)(v >> 16));
79 o.push_back((char)(v >> 8)); o.push_back((char)v);
80}
81static inline void be64(std::string& o, uint64_t v) {
82 for (int s = 56; s >= 0; s -= 8) o.push_back((char)(v >> s));
83}
84static inline uint32_t rd32(const uint8_t* p) {
85 return ((uint32_t)p[0] << 24) | ((uint32_t)p[1] << 16) | ((uint32_t)p[2] << 8) | p[3];
86}
87static inline uint64_t rd64(const uint8_t* p) {
88 uint64_t v = 0; for (int i = 0; i < 8; i++) v = (v << 8) | p[i]; return v;
89}
90static inline uint32_t zigzag(int32_t v) { return ((uint32_t)v << 1) ^ (uint32_t)(v >> 31); }
91static inline int32_t unzigzag(uint32_t v) { return (int32_t)(v >> 1) ^ -(int32_t)(v & 1); }
92static inline void writeVarInt(std::string& o, uint32_t v) {
93 while (true) {
94 uint8_t b = v & 0x7F; v >>= 7;
95 if (v == 0) { o.push_back((char)b); return; }
96 o.push_back((char)(b | 0x80));
97 }
98}
99static inline int toMicro(double deg) {
100 // Kotlin roundToInt(): ties round toward +infinity == floor(x + 0.5).
101 return (int)std::floor(deg * 1000000.0 + 0.5);
102}
103static inline int64_t cellIdOf(int latM, int lonM) {
104 int64_t row = (int64_t)(latM - MIN_LAT_MICRO) / CELL_MICRO;
105 int64_t col = (int64_t)(lonM - MIN_LON_MICRO) / CELL_MICRO;
106 return row * COLS + col;
107}
108// Interleave the low 16 bits of x into even bit positions (for a 2D Morton/Z-order key).
109static inline uint64_t interleave16(uint32_t x) {
110 uint64_t v = x & 0xFFFFu;
111 v = (v | (v << 8)) & 0x00FF00FFULL;
112 v = (v | (v << 4)) & 0x0F0F0F0FULL;
113 v = (v | (v << 2)) & 0x33333333ULL;
114 v = (v | (v << 1)) & 0x55555555ULL;
115 return v;
116}
117// Z-order key of a record's position *within* its 0.05-deg cell (offsets are < 50000 < 2^16).
118// Sorting a cell's records by this makes both lat and lon vary in small steps, so both delta
119// columns compress well (plain (lat,lon) sort only helps lat and leaves lon oscillating).
120static inline uint64_t mortonInCell(int32_t latM, int32_t lonM) {
121 uint32_t latOff = (uint32_t)(((int64_t)latM - MIN_LAT_MICRO) % CELL_MICRO);
122 uint32_t lonOff = (uint32_t)(((int64_t)lonM - MIN_LON_MICRO) % CELL_MICRO);
123 return (interleave16(latOff) << 1) | interleave16(lonOff);
124}
125
126static std::string zstdCompress(const std::string& raw) {
127 size_t bound = ZSTD_compressBound(raw.size());
128 std::string c; c.resize(bound);
129 size_t r = ZSTD_compress(&c[0], bound, raw.data(), raw.size(), ZSTD_LEVEL);
130 if (ZSTD_isError(r)) die(std::string("zstd compress: ") + ZSTD_getErrorName(r));
131 c.resize(r);
132 return c;
133}
134static std::string zstdDecompress(const uint8_t* comp, size_t compLen, size_t rawLen) {
135 std::string raw; raw.resize(rawLen);
136 size_t r = ZSTD_decompress(&raw[0], rawLen, comp, compLen);
137 if (ZSTD_isError(r) || r != rawLen) die(std::string("zstd decompress: ") + ZSTD_getErrorName(r));
138 return raw;
139}
140
141// Decode UTF-8 -> UTF-16 units so we can sort exactly like Kotlin's String.compareTo.
142static std::u16string toUtf16(const std::string& s) {
143 std::u16string o; o.reserve(s.size());
144 size_t i = 0, n = s.size();
145 while (i < n) {
146 uint32_t cp; unsigned char c = (unsigned char)s[i];
147 if (c < 0x80) { cp = c; i += 1; }
148 else if ((c >> 5) == 0x6 && i + 1 < n) { cp = (c & 0x1F); cp = (cp << 6) | (s[i + 1] & 0x3F); i += 2; }
149 else if ((c >> 4) == 0xE && i + 2 < n) { cp = (c & 0x0F); cp = (cp << 6) | (s[i + 1] & 0x3F); cp = (cp << 6) | (s[i + 2] & 0x3F); i += 3; }
150 else if ((c >> 3) == 0x1E && i + 3 < n) { cp = (c & 0x07); cp = (cp << 6) | (s[i + 1] & 0x3F); cp = (cp << 6) | (s[i + 2] & 0x3F); cp = (cp << 6) | (s[i + 3] & 0x3F); i += 4; }
151 else { cp = 0xFFFD; i += 1; }
152 if (cp <= 0xFFFF) o.push_back((char16_t)cp);
153 else { cp -= 0x10000; o.push_back((char16_t)(0xD800 + (cp >> 10))); o.push_back((char16_t)(0xDC00 + (cp & 0x3FF))); }
154 }
155 return o;
156}
157
158// ------------------------------------------------------------------ record model
159struct Rec {
160 int32_t latM, lonM;
161 uint32_t f[FIELDS]; // dict ids (provisional during parse, final after remap)
162};
163
164// Per-field string interner: value -> provisional id, plus the unique values in insertion order.
165struct Interner {
166 std::unordered_map<std::string, uint32_t> id;
167 std::vector<std::string> vals;
168 uint32_t intern(const std::string& s) {
169 auto it = id.find(s);
170 if (it != id.end()) return it->second;
171 uint32_t v = (uint32_t)vals.size();
172 id.emplace(s, v);
173 vals.push_back(s);
174 return v;
175 }
176};
177
178// ------------------------------------------------------------------ column encoder
179// Encode `values` as [int n][int blocks]([int rawLen][int compLen])*blocks [zstd block]*blocks.
180static std::string encodeColumn(const std::vector<int32_t>& values, bool delta) {
181 int n = (int)values.size();
182 int blocks = (n + BLOCK - 1) / BLOCK;
183 std::vector<std::string> comp(blocks);
184 std::vector<int> rawLens(blocks), compLens(blocks);
185#pragma omp parallel for schedule(dynamic, 16)
186 for (int b = 0; b < blocks; b++) {
187 int start = b * BLOCK;
188 int end = std::min(start + BLOCK, n);
189 std::string raw;
190 int32_t prev = 0;
191 for (int i = start; i < end; i++) {
192 int32_t v = values[i];
193 int32_t enc = delta ? (v - prev) : v;
194 writeVarInt(raw, zigzag(enc));
195 prev = v;
196 }
197 rawLens[b] = (int)raw.size();
198 std::string c = zstdCompress(raw);
199 compLens[b] = (int)c.size();
200 comp[b] = std::move(c);
201 }
202 std::string head;
203 be32(head, (uint32_t)n);
204 be32(head, (uint32_t)blocks);
205 for (int b = 0; b < blocks; b++) { be32(head, (uint32_t)rawLens[b]); be32(head, (uint32_t)compLens[b]); }
206 std::string out = std::move(head);
207 for (int b = 0; b < blocks; b++) out += comp[b];
208 return out;
209}
210
211static std::string encodeDict(const std::vector<std::string>& sorted) {
212 std::string raw;
213 be32(raw, (uint32_t)sorted.size());
214 for (const auto& s : sorted) { be32(raw, (uint32_t)s.size()); raw += s; }
215 std::string comp = zstdCompress(raw);
216 std::string out;
217 be32(out, (uint32_t)raw.size());
218 be32(out, (uint32_t)comp.size());
219 out += comp;
220 return out;
221}
222
223static void writeSection(FILE* f, const std::string& bytes) {
224 std::string h; be32(h, (uint32_t)bytes.size());
225 if (fwrite(h.data(), 1, 4, f) != 4) die("write section size");
226 if (fwrite(bytes.data(), 1, bytes.size(), f) != bytes.size()) die("write section body");
227}
228
229// ------------------------------------------------------------------ GeoJSON field extraction
230using namespace simdjson;
231
232static std::string getStr(dom::element obj, const char* key) {
233 dom::element v;
234 if (obj[key].get(v) != SUCCESS) return {};
235 std::string_view sv;
236 if (v.get_string().get(sv) != SUCCESS) return {};
237 return std::string(sv);
238}
239static bool getNum(dom::element e, double& out) {
240 double d; if (e.get_double().get(d) == SUCCESS) { out = d; return true; }
241 int64_t i; if (e.get_int64().get(i) == SUCCESS) { out = (double)i; return true; }
242 uint64_t u; if (e.get_uint64().get(u) == SUCCESS) { out = (double)u; return true; }
243 return false;
244}
245// Average of every [lon,lat] leaf (a cheap representative point for ways/areas), matching
246// the old Kotlin averageCoord().
247static void walkCoords(dom::element e, double& sumLon, double& sumLat, long& cnt) {
248 dom::array a;
249 if (e.get_array().get(a) != SUCCESS) return;
250 auto it = a.begin();
251 if (it == a.end()) return;
252 dom::element first = *it;
253 if (first.is_number()) {
254 double lon, lat;
255 if (!getNum(first, lon)) return;
256 auto it2 = it; ++it2;
257 if (it2 == a.end()) return;
258 if (!getNum(*it2, lat)) return;
259 sumLon += lon; sumLat += lat; cnt++;
260 } else {
261 for (dom::element child : a) walkCoords(child, sumLon, sumLat, cnt);
262 }
263}
264
265static void generate(const char* inPath, const char* outPath);
266static void verify(const char* dbPath);
267// Shared write path: (re)orders records + house/postcode dicts and emits the DB, then verifies.
268// `dicts` must already have street/city/state/country in UTF-16 order (house/postcode any order).
269static void writeDb(const char* outPath, std::vector<Rec>& recs,
270 std::vector<std::vector<std::string>>& dicts);
271// Rebuild an existing geocoder.geodb with the current encoder (no 100+ GB reparse needed).
272static void reencode(const char* inDb, const char* outDb);
273
274static const char* const COL_NAME[8] = {
275 "lat", "lon", "house", "street", "city", "state", "country", "postcode"};
276
277// ------------------------------------------------------------------ generate
278static void generate(const char* inPath, const char* outPath) {
279 int fd = open(inPath, O_RDONLY);
280 if (fd < 0) die(std::string("open input: ") + inPath);
281 struct stat st{};
282 if (fstat(fd, &st) != 0) die("fstat input");
283 size_t fsize = (size_t)st.st_size;
284 void* map = mmap(nullptr, fsize, PROT_READ, MAP_PRIVATE, fd, 0);
285 if (map == MAP_FAILED) die("mmap input");
286 madvise(map, fsize, MADV_SEQUENTIAL);
287 const char* data = (const char*)map;
288
289 fprintf(stderr, "Parsing %s (%.1f GB)...\n", inPath, fsize / 1e9);
290
291 Interner interns[FIELDS];
292 std::vector<Rec> recs;
293 recs.reserve(240000000);
294
295 dom::parser parser;
296
297 auto isTrim = [](unsigned char c) {
298 return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == 0x1e;
299 };
300
301 long long lines = 0, kept = 0, skipped = 0;
302 size_t pos = 0;
303 while (pos < fsize) {
304 size_t nl = pos;
305 while (nl < fsize && data[nl] != '\n') nl++;
306 size_t s = pos, e = nl;
307 pos = nl + 1;
308 while (s < e && isTrim((unsigned char)data[s])) s++;
309 while (e > s && isTrim((unsigned char)data[e - 1])) e--;
310 if (s >= e || data[s] != '{') continue;
311 lines++;
312
313 dom::element doc;
314 if (parser.parse(data + s, e - s, true).get(doc) != SUCCESS) { skipped++; goto progress; }
315 {
316 dom::element props;
317 if (doc["properties"].get(props) != SUCCESS) { skipped++; goto progress; }
318 std::string street = getStr(props, "addr:street");
319 if (street.empty()) { skipped++; goto progress; } // require a street; drop house-only
320 std::string house = getStr(props, "addr:housenumber");
321
322 dom::element geom, coords;
323 if (doc["geometry"].get(geom) != SUCCESS) { skipped++; goto progress; }
324 if (geom["coordinates"].get(coords) != SUCCESS) { skipped++; goto progress; }
325 double sumLon = 0, sumLat = 0; long cnt = 0;
326 walkCoords(coords, sumLon, sumLat, cnt);
327 if (cnt == 0) { skipped++; goto progress; }
328
329 std::string city = getStr(props, "addr:city");
330 std::string state = getStr(props, "addr:state");
331 if (state.empty()) state = getStr(props, "addr:province");
332 std::string country = getStr(props, "addr:country");
333 std::string postcode = getStr(props, "addr:postcode");
334
335 Rec r;
336 r.latM = toMicro(sumLat / cnt);
337 r.lonM = toMicro(sumLon / cnt);
338 r.f[F_HOUSE] = interns[F_HOUSE].intern(house);
339 r.f[F_STREET] = interns[F_STREET].intern(street);
340 r.f[F_CITY] = interns[F_CITY].intern(city);
341 r.f[F_STATE] = interns[F_STATE].intern(state);
342 r.f[F_COUNTRY] = interns[F_COUNTRY].intern(country);
343 r.f[F_POSTCODE] = interns[F_POSTCODE].intern(postcode);
344 recs.push_back(r);
345 kept++;
346 }
347 progress:
348 if ((lines % 20000000) == 0 && lines > 0)
349 fprintf(stderr, " ...parsed %lld lines, kept %lld\n", lines, kept);
350 }
351 munmap(map, fsize);
352 close(fd);
353
354 size_t n = recs.size();
355 if (n == 0) die("no records kept");
356 if (n > 0x7fffffffull) die("record count exceeds 2^31 (reader uses signed int)");
357 fprintf(stderr, "Parsed %lld features; kept %lld; skipped %lld.\n", lines, kept, skipped);
358 for (int fi = 0; fi < FIELDS; fi++)
359 fprintf(stderr, " distinct[%d] = %zu\n", fi, interns[fi].vals.size());
360
361 // Build sorted dictionaries (Kotlin String / UTF-16 order) and remap provisional->final ids.
362 std::vector<std::vector<std::string>> dicts(FIELDS);
363 std::vector<std::vector<uint32_t>> remap(FIELDS);
364 for (int fi = 0; fi < FIELDS; fi++) {
365 size_t m = interns[fi].vals.size();
366 std::vector<uint32_t> ord(m);
367 for (size_t i = 0; i < m; i++) ord[i] = (uint32_t)i;
368 std::vector<std::u16string> keys(m);
369 for (size_t i = 0; i < m; i++) keys[i] = toUtf16(interns[fi].vals[i]);
370 std::sort(ord.begin(), ord.end(),
371 [&](uint32_t a, uint32_t b) { return keys[a] < keys[b]; });
372 dicts[fi].resize(m);
373 remap[fi].resize(m);
374 for (size_t rank = 0; rank < m; rank++) {
375 uint32_t prov = ord[rank];
376 dicts[fi][rank] = interns[fi].vals[prov];
377 remap[fi][prov] = (uint32_t)rank;
378 }
379 std::vector<std::u16string>().swap(keys);
380 std::unordered_map<std::string, uint32_t>().swap(interns[fi].id);
381 std::vector<std::string>().swap(interns[fi].vals);
382 }
383 for (auto& r : recs)
384 for (int fi = 0; fi < FIELDS; fi++) r.f[fi] = remap[fi][r.f[fi]];
385
386 writeDb(outPath, recs, dicts);
387}
388
389// ------------------------------------------------------------------ shared write path
390static void writeDb(const char* outPath, std::vector<Rec>& recs,
391 std::vector<std::vector<std::string>>& dicts) {
392 size_t n = recs.size();
393 if (n == 0) die("no records to write");
394
395 // Frequency-order the house and postcode dictionaries: the reader never string-searches
396 // them (only display), so giving the most common values the smallest ids makes those
397 // columns almost entirely 1-byte varints. street/city/state/country stay UTF-16 sorted
398 // because forward geocoding binary-searches them by name.
399 auto freqReorder = [&](int fi) {
400 size_t m = dicts[fi].size();
401 if (m == 0) return;
402 std::vector<uint64_t> freq(m, 0);
403 for (const auto& r : recs) freq[r.f[fi]]++;
404 std::vector<uint32_t> ord(m);
405 for (size_t i = 0; i < m; i++) ord[i] = (uint32_t)i;
406 std::sort(ord.begin(), ord.end(), [&](uint32_t a, uint32_t b) {
407 if (freq[a] != freq[b]) return freq[a] > freq[b]; // most common -> id 0
408 return a < b;
409 });
410 std::vector<std::string> nd(m);
411 std::vector<uint32_t> rm(m);
412 for (size_t rank = 0; rank < m; rank++) { nd[rank] = std::move(dicts[fi][ord[rank]]); rm[ord[rank]] = (uint32_t)rank; }
413 dicts[fi].swap(nd);
414 for (auto& r : recs) r.f[fi] = rm[r.f[fi]];
415 };
416 freqReorder(F_HOUSE);
417 freqReorder(F_POSTCODE);
418
419 // Grid-primary order, then by Morton (Z-order) position within each cell so BOTH the lat and
420 // lon delta columns stay small (a plain lat,lon sort leaves lon oscillating).
421 std::vector<int64_t> cell(n);
422 std::vector<uint64_t> mort(n);
423 for (size_t i = 0; i < n; i++) {
424 cell[i] = cellIdOf(recs[i].latM, recs[i].lonM);
425 mort[i] = mortonInCell(recs[i].latM, recs[i].lonM);
426 }
427 std::vector<uint32_t> order(n);
428 for (size_t i = 0; i < n; i++) order[i] = (uint32_t)i;
429 std::sort(order.begin(), order.end(), [&](uint32_t a, uint32_t b) {
430 if (cell[a] != cell[b]) return cell[a] < cell[b];
431 return mort[a] < mort[b];
432 });
433
434 fprintf(stderr, "Writing %s (%zu records)...\n", outPath, n);
435 FILE* f = fopen(outPath, "wb");
436 if (!f) die(std::string("open output: ") + outPath);
437 setvbuf(f, nullptr, _IOFBF, 1 << 22);
438
439 std::string hdr;
440 be32(hdr, MAGIC); be32(hdr, VERSION); be32(hdr, (uint32_t)n);
441 if (fwrite(hdr.data(), 1, hdr.size(), f) != hdr.size()) die("write header");
442
443 for (int fi = 0; fi < FIELDS; fi++) {
444 std::string sec = encodeDict(dicts[fi]);
445 fprintf(stderr, " dict[%-8s] = %10zu bytes (%zu entries)\n", COL_NAME[fi + 2], sec.size(), dicts[fi].size());
446 writeSection(f, sec);
447 }
448
449 std::vector<int32_t> col(n);
450 auto emitCol = [&](int which, bool delta) {
451 for (size_t i = 0; i < n; i++) {
452 const Rec& r = recs[order[i]];
453 switch (which) {
454 case 0: col[i] = r.latM; break;
455 case 1: col[i] = r.lonM; break;
456 default: col[i] = (int32_t)r.f[which - 2]; break; // house..postcode
457 }
458 }
459 std::string sec = encodeColumn(col, delta);
460 fprintf(stderr, " col [%-8s] = %10zu bytes (%.3f B/rec)\n", COL_NAME[which], sec.size(), sec.size() / (double)n);
461 writeSection(f, sec);
462 };
463 emitCol(0, true); emitCol(1, true); // lat, lon
464 for (int c = 2; c < 8; c++) emitCol(c, false); // house..postcode
465
466 { // Grid directory: (cellId, startRec) per non-empty cell, ascending cell order.
467 std::string grid, body;
468 uint32_t count = 0;
469 int64_t prevCell = INT64_MIN;
470 for (size_t i = 0; i < n; i++) {
471 int64_t c = cell[order[i]];
472 if (c != prevCell) { be64(body, (uint64_t)c); be32(body, (uint32_t)i); count++; prevCell = c; }
473 }
474 be32(grid, count);
475 grid += body;
476 fprintf(stderr, " grid = %10zu bytes (%u cells)\n", grid.size() + 4, count);
477 writeSection(f, grid);
478 }
479
480 { // Forward ordering: positions sorted by (country,state,city,street,house), delta column.
481 std::vector<int32_t> fwd(n);
482 for (size_t i = 0; i < n; i++) fwd[i] = (int32_t)i;
483 std::sort(fwd.begin(), fwd.end(), [&](int32_t a, int32_t b) {
484 const Rec& ra = recs[order[a]];
485 const Rec& rb = recs[order[b]];
486 if (ra.f[F_COUNTRY] != rb.f[F_COUNTRY]) return ra.f[F_COUNTRY] < rb.f[F_COUNTRY];
487 if (ra.f[F_STATE] != rb.f[F_STATE]) return ra.f[F_STATE] < rb.f[F_STATE];
488 if (ra.f[F_CITY] != rb.f[F_CITY]) return ra.f[F_CITY] < rb.f[F_CITY];
489 if (ra.f[F_STREET] != rb.f[F_STREET]) return ra.f[F_STREET] < rb.f[F_STREET];
490 return ra.f[F_HOUSE] < rb.f[F_HOUSE];
491 });
492 std::string sec = encodeColumn(fwd, true);
493 fprintf(stderr, " fwd = %10zu bytes (%.3f B/rec)\n", sec.size(), sec.size() / (double)n);
494 writeSection(f, sec);
495 }
496
497 if (fclose(f) != 0) die("close output");
498
499 struct stat ost{};
500 stat(outPath, &ost);
501 fprintf(stderr, "Done: %s = %lld bytes (%.3f GB), %.2f B/record.\n",
502 outPath, (long long)ost.st_size, ost.st_size / (double)(1LL << 30),
503 (double)ost.st_size / (double)n);
504
505 fprintf(stderr, "Self-verifying...\n");
506 verify(outPath);
507}
508
509// ------------------------------------------------------------------ verify (mirrors GeoDbReader)
510struct MappedDb {
511 const uint8_t* p = nullptr;
512 size_t size = 0;
513 int fd = -1;
514 void openFile(const char* path) {
515 fd = open(path, O_RDONLY);
516 if (fd < 0) die(std::string("open db: ") + path);
517 struct stat st{}; fstat(fd, &st); size = (size_t)st.st_size;
518 void* m = mmap(nullptr, size, PROT_READ, MAP_PRIVATE, fd, 0);
519 if (m == MAP_FAILED) die("mmap db");
520 p = (const uint8_t*)m;
521 }
522 ~MappedDb() { if (p) munmap((void*)p, size); if (fd >= 0) close(fd); }
523};
524
525// A single delta/raw column, decoding one block on demand (as GeoDbReader.Column does).
526struct ColReader {
527 const uint8_t* base = nullptr;
528 int n = 0, blocks = 0;
529 bool delta = false;
530 std::vector<int> rawLens, compLens;
531 std::vector<size_t> blockOff;
532 int cachedBlock = -1;
533 std::vector<int32_t> cachedVals;
534 void init(const uint8_t* fileBase, size_t bodyOff, bool d) {
535 delta = d;
536 const uint8_t* q = fileBase + bodyOff;
537 n = (int)rd32(q); q += 4;
538 blocks = (int)rd32(q); q += 4;
539 rawLens.resize(blocks); compLens.resize(blocks); blockOff.resize(blocks);
540 for (int b = 0; b < blocks; b++) { rawLens[b] = (int)rd32(q); q += 4; compLens[b] = (int)rd32(q); q += 4; }
541 size_t off = (size_t)(q - fileBase);
542 for (int b = 0; b < blocks; b++) { blockOff[b] = off; off += compLens[b]; }
543 base = fileBase;
544 }
545 void decode(int block) {
546 std::string raw = zstdDecompress(base + blockOff[block], compLens[block], rawLens[block]);
547 int count = std::min(BLOCK, n - block * BLOCK);
548 cachedVals.assign(count, 0);
549 const uint8_t* r = (const uint8_t*)raw.data();
550 size_t rp = 0; int32_t prev = 0;
551 for (int k = 0; k < count; k++) {
552 uint32_t v = 0; int shift = 0;
553 while (true) { uint8_t b = r[rp++]; v |= (uint32_t)(b & 0x7F) << shift; if (!(b & 0x80)) break; shift += 7; }
554 int32_t dv = unzigzag(v);
555 int32_t actual = delta ? prev + dv : dv;
556 cachedVals[k] = actual; prev = actual;
557 }
558 cachedBlock = block;
559 }
560 int32_t get(int i) {
561 int block = i / BLOCK;
562 if (block != cachedBlock) decode(block);
563 return cachedVals[i - block * BLOCK];
564 }
565};
566
567static std::vector<std::string> decodeDict(const uint8_t* section) {
568 uint32_t rawSize = rd32(section), compSize = rd32(section + 4);
569 std::string raw = zstdDecompress(section + 8, compSize, rawSize);
570 const uint8_t* r = (const uint8_t*)raw.data();
571 uint32_t count = rd32(r); r += 4;
572 std::vector<std::string> out; out.reserve(count);
573 for (uint32_t i = 0; i < count; i++) { uint32_t len = rd32(r); r += 4; out.emplace_back((const char*)r, len); r += len; }
574 return out;
575}
576
577static void verify(const char* dbPath) {
578 MappedDb db; db.openFile(dbPath);
579 const uint8_t* p = db.p;
580 if (rd32(p) != MAGIC) die("verify: bad magic");
581 if (rd32(p + 4) != VERSION) die("verify: bad version");
582 int n = (int)rd32(p + 8);
583 size_t cursor = 12;
584 auto readSectionOff = [&](size_t& bodyOff) {
585 uint32_t sz = rd32(p + cursor); cursor += 4; bodyOff = cursor; cursor += sz;
586 };
587
588 std::vector<std::vector<std::string>> dict(FIELDS);
589 for (int fi = 0; fi < FIELDS; fi++) { size_t off; readSectionOff(off); dict[fi] = decodeDict(p + off); }
590 ColReader cols[8];
591 bool delta[8] = {true, true, false, false, false, false, false, false};
592 for (int i = 0; i < 8; i++) { size_t off; readSectionOff(off); cols[i].init(p, off, delta[i]); }
593
594 size_t gridOff; readSectionOff(gridOff);
595 const uint8_t* g = p + gridOff;
596 uint32_t cellCount = rd32(g); g += 4;
597 std::vector<int64_t> cellIds(cellCount);
598 std::vector<int32_t> cellStarts(cellCount);
599 for (uint32_t i = 0; i < cellCount; i++) { cellIds[i] = (int64_t)rd64(g); g += 8; cellStarts[i] = (int32_t)rd32(g); g += 4; }
600
601 size_t fwdOff; readSectionOff(fwdOff);
602 ColReader fwd; fwd.init(p, fwdOff, true);
603 if (cursor != db.size) die("verify: trailing bytes / size mismatch");
604
605 // Force-decode every block of every column to catch any zstd/varint/framing error.
606 for (int c = 0; c < 8; c++) for (int i = 0; i < n; i += BLOCK) (void)cols[c].get(i);
607 for (int i = 0; i < n; i += BLOCK) (void)fwd.get(i);
608
609 // Reverse: nearest stored record to a coordinate (mirrors GeoDbReader.reverse).
610 auto reverse = [&](double lat, double lon) -> int {
611 int qLatM = toMicro(lat), qLonM = toMicro(lon);
612 int row = (qLatM - MIN_LAT_MICRO) / CELL_MICRO;
613 int colc = (qLonM - MIN_LON_MICRO) / CELL_MICRO;
614 double lonScale = cos(lat * M_PI / 180.0);
615 int bestRec = -1; double bestDist = 1e300;
616 for (int radius = 1; bestRec < 0 && radius <= 32; radius++) {
617 for (int r = row - radius; r <= row + radius; r++) {
618 if (r < 0) continue;
619 for (int c = colc - radius; c <= colc + radius; c++) {
620 if (radius > 1 && r > row - radius && r < row + radius && c > colc - radius && c < colc + radius) continue;
621 int64_t cc = ((c % COLS) + COLS) % COLS;
622 int64_t cellv = (int64_t)r * COLS + cc;
623 int lo = 0, hi = (int)cellCount - 1, gi = -1;
624 while (lo <= hi) { int mid = (lo + hi) >> 1; if (cellIds[mid] < cellv) lo = mid + 1; else if (cellIds[mid] > cellv) hi = mid - 1; else { gi = mid; break; } }
625 if (gi < 0) continue;
626 int start = cellStarts[gi];
627 int end = (gi + 1 < (int)cellCount) ? cellStarts[gi + 1] : n;
628 for (int i = start; i < end; i++) {
629 double dLat = cols[0].get(i) - qLatM;
630 double dLon = (cols[1].get(i) - qLonM) * lonScale;
631 double d = dLat * dLat + dLon * dLon;
632 if (d < bestDist) { bestDist = d; bestRec = i; }
633 }
634 }
635 }
636 }
637 return bestRec;
638 };
639 auto compareKey = [&](int rec, int co, int stt, int ci, int str) {
640 int c;
641 c = cols[6].get(rec) - co; if (c) return c;
642 c = cols[5].get(rec) - stt; if (c) return c;
643 c = cols[4].get(rec) - ci; if (c) return c;
644 return cols[3].get(rec) - str;
645 };
646 auto resolve = [&](int rec, const char* tag) {
647 fprintf(stderr, " %s rec=%d %.6f,%.6f %s %s, %s, %s, %s %s\n", tag, rec,
648 cols[0].get(rec) / 1e6, cols[1].get(rec) / 1e6,
649 dict[F_HOUSE][cols[2].get(rec)].c_str(), dict[F_STREET][cols[3].get(rec)].c_str(),
650 dict[F_CITY][cols[4].get(rec)].c_str(), dict[F_STATE][cols[5].get(rec)].c_str(),
651 dict[F_COUNTRY][cols[6].get(rec)].c_str(), dict[F_POSTCODE][cols[7].get(rec)].c_str());
652 };
653
654 int samples[] = {0, n / 3, (2 * n) / 3, n - 1};
655 int prev = -1;
656 for (int s : samples) {
657 if (s < 0 || s >= n || s == prev) continue;
658 prev = s;
659 resolve(s, "sample");
660 // Forward round-trip: this record must be findable by its own key.
661 int co = cols[6].get(s), stt = cols[5].get(s), ci = cols[4].get(s), str = cols[3].get(s);
662 int lo = 0, hi = n;
663 while (lo < hi) { int mid = (lo + hi) >> 1; if (compareKey(fwd.get(mid), co, stt, ci, str) < 0) lo = mid + 1; else hi = mid; }
664 bool found = false;
665 for (int k = lo; k < n; k++) { int rec = fwd.get(k); if (compareKey(rec, co, stt, ci, str) != 0) break; if (rec == s) { found = true; break; } }
666 if (!found) die("verify: forward round-trip failed");
667 // Reverse round-trip: nearest to the record's own coordinate is at that exact coordinate.
668 double lat = cols[0].get(s) / 1e6, lon = cols[1].get(s) / 1e6;
669 int rr = reverse(lat, lon);
670 if (rr < 0) die("verify: reverse returned nothing");
671 if (cols[0].get(rr) != toMicro(lat) || cols[1].get(rr) != toMicro(lon))
672 die("verify: reverse nearest not at query coordinate");
673 }
674
675 fprintf(stderr, "Verify OK: n=%d, dicts[h/s/c/st/co/pc]=%zu/%zu/%zu/%zu/%zu/%zu, cells=%u, size=%zu bytes.\n",
676 n, dict[0].size(), dict[1].size(), dict[2].size(), dict[3].size(), dict[4].size(), dict[5].size(),
677 cellCount, db.size);
678}
679
680// ------------------------------------------------------------------ reencode
681// Load a v2 geocoder.geodb back into memory (dicts + per-record field ids + coords), then
682// re-emit it with the current encoder. Lets us re-tune the packing without reparsing the
683// multi-hundred-GB GeoJSONSeq. Loaded street/city/state/country dicts are already UTF-16
684// sorted; writeDb re-derives grid order, forward index, and house/postcode dict order.
685static void reencode(const char* inDb, const char* outDb) {
686 MappedDb db; db.openFile(inDb);
687 const uint8_t* p = db.p;
688 if (rd32(p) != MAGIC) die("reencode: bad magic");
689 if (rd32(p + 4) != VERSION) die("reencode: bad version");
690 int n = (int)rd32(p + 8);
691 size_t cursor = 12;
692 auto readSectionOff = [&](size_t& bodyOff) {
693 uint32_t sz = rd32(p + cursor); cursor += 4; bodyOff = cursor; cursor += sz;
694 };
695
696 fprintf(stderr, "Reencoding %s (%d records)...\n", inDb, n);
697 std::vector<std::vector<std::string>> dicts(FIELDS);
698 for (int fi = 0; fi < FIELDS; fi++) { size_t off; readSectionOff(off); dicts[fi] = decodeDict(p + off); }
699 ColReader cols[8];
700 bool delta[8] = {true, true, false, false, false, false, false, false};
701 for (int i = 0; i < 8; i++) { size_t off; readSectionOff(off); cols[i].init(p, off, delta[i]); }
702 // grid + fwd sections are recomputed on write; ignore them here.
703
704 std::vector<Rec> recs((size_t)n);
705 for (int i = 0; i < n; i++) {
706 Rec r;
707 r.latM = cols[0].get(i);
708 r.lonM = cols[1].get(i);
709 for (int fi = 0; fi < FIELDS; fi++) r.f[fi] = (uint32_t)cols[2 + fi].get(i);
710 recs[(size_t)i] = r;
711 }
712 writeDb(outDb, recs, dicts);
713}
714
715// ------------------------------------------------------------------ main
716int main(int argc, char** argv) {
717 if (argc >= 4 && strcmp(argv[1], "generate") == 0) { generate(argv[2], argv[3]); return 0; }
718 if (argc >= 4 && strcmp(argv[1], "reencode") == 0) { reencode(argv[2], argv[3]); return 0; }
719 if (argc >= 3 && strcmp(argv[1], "verify") == 0) { verify(argv[2]); return 0; }
720 if (argc == 3) { generate(argv[1], argv[2]); return 0; } // shorthand: <in> <out>
721 fprintf(stderr,
722 "usage:\n"
723 " %s generate <addr.geojsonseq> <geocoder.geodb>\n"
724 " %s reencode <in.geodb> <out.geodb> # repack an existing DB with current encoder\n"
725 " %s verify <geocoder.geodb>\n",
726 argv[0], argv[0], argv[0]);
727 return 2;
728}