loconym 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
loconym/__init__.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.0.1"
loconym/bench.py ADDED
@@ -0,0 +1,122 @@
1
+ """Benchmark a built database with the reference reader: correctness against its own data + pages read per query.
2
+
3
+ loconym-bench DB [--n 300] [--seed 7]
4
+ Page counting uses an apsw logging VFS (4 KiB pages, cold = fresh connection per query, warm = 256 KiB cache).
5
+ """
6
+ import argparse
7
+ import random
8
+ import statistics
9
+
10
+ import apsw
11
+
12
+ from .codec import decode_housenumbers
13
+ from .reader import Loconym
14
+
15
+ PAGE = 4096
16
+ _reads: set[int] = set()
17
+
18
+
19
+ class _LogFile(apsw.VFSFile):
20
+ def xRead(self, amount, offset):
21
+ _reads.update(range(offset // PAGE, (offset + amount - 1) // PAGE + 1))
22
+ return super().xRead(amount, offset)
23
+
24
+
25
+ class _LogVFS(apsw.VFS):
26
+ def __init__(self):
27
+ super().__init__("lgbench", "")
28
+
29
+ def xOpen(self, name, flags):
30
+ return _LogFile("", name, flags)
31
+
32
+
33
+ _vfs = _LogVFS()
34
+
35
+
36
+ def _open(path, cache_pages=0):
37
+ db = apsw.Connection(str(path), flags=apsw.SQLITE_OPEN_READONLY, vfs="lgbench")
38
+ db.pragma("cache_size", cache_pages)
39
+ return db
40
+
41
+
42
+ def _stats(xs):
43
+ xs = sorted(xs)
44
+ return f"avg={statistics.mean(xs):.1f} p95={xs[int(len(xs) * 0.95)]} max={xs[-1]}"
45
+
46
+
47
+ def sample_addresses(path, n, rng):
48
+ db = apsw.Connection(str(path), flags=apsw.SQLITE_OPEN_READONLY)
49
+ names = dict(db.execute("SELECT id, name FROM street"))
50
+ cities = dict(db.execute("SELECT id, name FROM admin"))
51
+ parents = dict(db.execute("SELECT id, parent FROM street"))
52
+ ids = [r[0] for r in db.execute("SELECT street_id FROM housenumber")]
53
+ out = []
54
+ for sid in rng.sample(ids, min(n, len(ids))):
55
+ blob = db.execute("SELECT data FROM housenumber WHERE street_id=?", (sid,)).fetchone()[0]
56
+ sn = decode_housenumbers(bytes(blob))
57
+ if sn.addrs:
58
+ hn, lon, lat = rng.choice(sn.addrs)
59
+ out.append((sid, names[sid], cities.get(parents[sid], ""), hn, lon, lat))
60
+ db.close()
61
+ return out
62
+
63
+
64
+ def run(path, n=300, seed=7, out=print):
65
+ rng = random.Random(seed)
66
+ samples = sample_addresses(path, n, rng)
67
+ # reverse
68
+ cold, ok_s, ok_n = [], 0, 0
69
+ for sid, _name, _city, hn, lon, lat in samples:
70
+ _reads.clear()
71
+ g = Loconym(_open(path))
72
+ r = g.reverse(lon, lat)
73
+ cold.append(len(_reads))
74
+ ok_s += bool(r and r["street_id"] == sid)
75
+ ok_n += bool(r and r["housenumber"] == hn)
76
+ warm_db = Loconym(_open(path, 64))
77
+ for _, _, _, _, lon, lat in samples[:50]:
78
+ warm_db.reverse(lon, lat)
79
+ warm = []
80
+ for _, _, _, _, lon, lat in samples:
81
+ _reads.clear()
82
+ warm_db.reverse(lon, lat)
83
+ warm.append(len(_reads))
84
+ out(f"reverse@address n={len(samples)}: street-ok={ok_s / len(samples):.1%} number-ok={ok_n / len(samples):.1%} "
85
+ f"pages cold {_stats(cold)} | warm {_stats(warm)}")
86
+ # search
87
+ cold, top1, top5, located = [], 0, 0, 0
88
+ for sid, name, city, hn, _lon, _lat in samples:
89
+ q = f"{name} {hn}, {city}" if city else f"{name} {hn}"
90
+ _reads.clear()
91
+ g = Loconym(_open(path))
92
+ res = g.search(q)
93
+ cold.append(len(_reads))
94
+ ids = [h["street_id"] for h in res]
95
+ top1 += bool(ids and ids[0] == sid)
96
+ top5 += sid in ids
97
+ located += any(h["street_id"] == sid and h["housenumber"] == hn for h in res)
98
+ out(f"search 'street N, city' n={len(samples)}: top1={top1 / len(samples):.1%} top5={top5 / len(samples):.1%} "
99
+ f"number-located={located / len(samples):.1%} pages cold {_stats(cold)}")
100
+ # type-ahead: first half of the street name (>= 3 chars) + city
101
+ cold, top5 = [], 0
102
+ for sid, name, city, *_ in samples[:100]:
103
+ pre = name[: max(3, len(name) // 2)]
104
+ _reads.clear()
105
+ g = Loconym(_open(path))
106
+ res = g.search(f"{pre}, {city}" if city else pre)
107
+ cold.append(len(_reads))
108
+ top5 += any(h["street_id"] == sid for h in res)
109
+ out(f"search type-ahead n={len(cold)}: top5={top5 / len(cold):.1%} pages cold {_stats(cold)}")
110
+
111
+
112
+ def main(argv=None):
113
+ p = argparse.ArgumentParser(prog="loconym-bench")
114
+ p.add_argument("db")
115
+ p.add_argument("--n", type=int, default=300)
116
+ p.add_argument("--seed", type=int, default=7)
117
+ a = p.parse_args(argv)
118
+ run(a.db, a.n, a.seed)
119
+
120
+
121
+ if __name__ == "__main__":
122
+ main()
loconym/build.py ADDED
@@ -0,0 +1,310 @@
1
+ """Stages 2-4: tile the scratch data into cells, build tables, write the final SQLite file (format-spec.md)."""
2
+ import datetime
3
+ import re
4
+ import sqlite3
5
+ import tempfile
6
+ from collections import defaultdict
7
+ from pathlib import Path
8
+
9
+ import shapely
10
+ import shapely.wkb as wkb
11
+
12
+ from .codec import (
13
+ COORD_QUANTUM,
14
+ Cell,
15
+ StreetNumbers,
16
+ cell_key,
17
+ encode_housenumbers,
18
+ encode_leaf,
19
+ encode_postings,
20
+ encode_split,
21
+ lonlat_tile,
22
+ tile_bounds,
23
+ )
24
+ from .extract import ROOT_ZOOM, extract, root_key, root_xy
25
+ from .normalize import NORMALIZER_VERSION, normalize_key, normalize_tokens
26
+ from .prefilter import available as osmium_available
27
+ from .prefilter import prefilter
28
+
29
+ FORMAT_VERSION = "0.1"
30
+ CELL_ZOOM = 16
31
+ MAX_SPLIT_ZOOM = 19
32
+ PAGE_SIZE = 4096
33
+ ATTRIBUTION = "© OpenStreetMap contributors, ODbL 1.0"
34
+
35
+ SCHEMA = """
36
+ CREATE TABLE meta(k TEXT PRIMARY KEY, v) WITHOUT ROWID;
37
+ CREATE TABLE admin(id INTEGER PRIMARY KEY, level INT, name TEXT, parent INT, city INT, rank INT);
38
+ CREATE TABLE street(id INTEGER PRIMARY KEY, name TEXT, parent INT, lat INT, lon INT);
39
+ CREATE TABLE cell(id INTEGER PRIMARY KEY, data BLOB);
40
+ CREATE TABLE term(t TEXT, parent INT, postings BLOB, PRIMARY KEY(t, parent)) WITHOUT ROWID;
41
+ CREATE TABLE housenumber(street_id INTEGER PRIMARY KEY, data BLOB);
42
+ """
43
+
44
+ # admin_level -> Nominatim-style place_rank (germany/europe defaults; documented in meta)
45
+ LEVEL_RANK = {2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18, 10: 20, 11: 22}
46
+
47
+
48
+ def natural_key(s: str):
49
+ return [int(t) if t.isdigit() else t for t in re.split(r"(\d+)", s)]
50
+
51
+
52
+ # ------------------------------------------------------------------ geometry helpers
53
+ def lines_of(g):
54
+ if g.is_empty:
55
+ return []
56
+ if g.geom_type == "LineString":
57
+ return [g] if len(g.coords) >= 2 else []
58
+ if hasattr(g, "geoms"):
59
+ return [l for part in g.geoms for l in lines_of(part)]
60
+ return []
61
+
62
+
63
+ def polys_of(g):
64
+ if g.is_empty:
65
+ return []
66
+ if g.geom_type == "Polygon":
67
+ return [g]
68
+ if hasattr(g, "geoms"):
69
+ return [p for part in g.geoms for p in polys_of(part)]
70
+ return []
71
+
72
+
73
+ def clip(g, box):
74
+ return shapely.clip_by_rect(g, *box)
75
+
76
+
77
+ # ------------------------------------------------------------------ tiling
78
+ class CellWriter:
79
+ def __init__(self, out_db, max_leaf_bytes):
80
+ self.db, self.max_leaf = out_db, max_leaf_bytes
81
+ self.rows, self.n_leaf, self.n_split, self.bytes = [], 0, 0, 0
82
+
83
+ def put(self, key, blob, split=False):
84
+ self.rows.append((key, blob))
85
+ self.n_split += split
86
+ self.n_leaf += not split
87
+ self.bytes += len(blob)
88
+
89
+ def flush(self):
90
+ self.db.executemany("INSERT INTO cell VALUES (?,?)", self.rows)
91
+ self.rows = []
92
+
93
+
94
+ def _to_cell(adm, streets, addrs, interps) -> Cell:
95
+ c = Cell()
96
+ for aid, g in adm:
97
+ if g is None:
98
+ c.admin.append((aid, None))
99
+ else:
100
+ polys = [[list(p.exterior.coords)] + [list(r.coords) for r in p.interiors] for p in polys_of(g)]
101
+ c.admin.append((aid, polys))
102
+ c.streets = [(sid, list(l.coords)) for sid, g in streets for l in lines_of(g)]
103
+ c.addrs = list(addrs)
104
+ c.interps = [(sid, step, first, last, list(l.coords)) for sid, step, first, last, g in interps for l in lines_of(g)]
105
+ return c
106
+
107
+
108
+ def _children(x, y, z, adm, streets, addrs, interps):
109
+ for i in (0, 1):
110
+ for j in (0, 1):
111
+ cx, cy = 2 * x + i, 2 * y + j
112
+ cb = tile_bounds(cx, cy, z + 1)
113
+ cbox = shapely.box(*cb)
114
+ cadm = []
115
+ for aid, g in adm:
116
+ if g is None:
117
+ cadm.append((aid, None))
118
+ continue
119
+ piece = clip(g, cb)
120
+ if piece.is_empty or piece.area == 0:
121
+ continue
122
+ full = piece.area >= cbox.area * (1 - 1e-9) or piece.contains(cbox)
123
+ cadm.append((aid, None if full else piece))
124
+ cst = [(sid, p) for sid, g in streets if lines_of(p := clip(g, cb))]
125
+ cin = [(*t[:4], p) for t in interps if lines_of(p := clip(t[4], cb))]
126
+ cad = [a for a in addrs if cb[0] <= a[2] < cb[2] and cb[1] <= a[3] < cb[3]]
127
+ yield cx, cy, cadm, cst, cad, cin
128
+
129
+
130
+ def _rec(w: CellWriter, x, y, z, adm, streets, addrs, interps):
131
+ if not (adm or streets or addrs or interps):
132
+ return
133
+ key = cell_key(x, y, z)
134
+ if not (streets or addrs or interps): # featureless: one coarse admin-only leaf
135
+ w.put(key, encode_leaf(tile_bounds(x, y, z), _to_cell(adm, [], [], [])))
136
+ return
137
+ if z < CELL_ZOOM: # features exist: refine down to the base zoom
138
+ for cx, cy, *rest in _children(x, y, z, adm, streets, addrs, interps):
139
+ _rec(w, cx, cy, z + 1, *rest)
140
+ return
141
+ blob = encode_leaf(tile_bounds(x, y, z), _to_cell(adm, streets, addrs, interps))
142
+ if len(blob) > w.max_leaf and z < MAX_SPLIT_ZOOM: # oversized hot cell: marker + children
143
+ w.put(key, encode_split(), split=True)
144
+ for cx, cy, *rest in _children(x, y, z, adm, streets, addrs, interps):
145
+ _rec(w, cx, cy, z + 1, *rest)
146
+ else:
147
+ w.put(key, blob)
148
+
149
+
150
+ def _admin_roots(admins):
151
+ roots = set()
152
+ for a in admins:
153
+ x0, y0, x1, y1 = a.geom.bounds
154
+ ax, ay = lonlat_tile(x0, y1, ROOT_ZOOM)
155
+ bx, by = lonlat_tile(x1, y0, ROOT_ZOOM)
156
+ for rx in range(ax, bx + 1):
157
+ for ry in range(ay, by + 1):
158
+ if a.geom.intersects(shapely.box(*tile_bounds(rx, ry, ROOT_ZOOM))):
159
+ roots.add(root_key(rx, ry))
160
+ return roots
161
+
162
+
163
+ def build_cells(ex, scratch: sqlite3.Connection, out_db, final_id, max_leaf_bytes, log):
164
+ admins = ex.admins
165
+ atree = shapely.STRtree([a.geom for a in admins]) if admins else None
166
+ interp_by_root = defaultdict(list)
167
+ for t in ex.interps:
168
+ x0, y0, x1, y1 = t[4].bounds
169
+ ax, ay = lonlat_tile(x0, y1, ROOT_ZOOM)
170
+ bx, by = lonlat_tile(x1, y0, ROOT_ZOOM)
171
+ for rx in range(ax, bx + 1):
172
+ for ry in range(ay, by + 1):
173
+ if t[4].intersects(shapely.box(*tile_bounds(rx, ry, ROOT_ZOOM))):
174
+ interp_by_root[root_key(rx, ry)].append((final_id[t[0]], t[1], t[2], t[3], t[4]))
175
+ roots = {r for (r,) in scratch.execute("SELECT DISTINCT root FROM way")}
176
+ roots |= {r for (r,) in scratch.execute("SELECT DISTINCT root FROM addr")}
177
+ roots |= set(interp_by_root) | _admin_roots(admins)
178
+ w = CellWriter(out_db, max_leaf_bytes)
179
+ for n, r in enumerate(sorted(roots), 1):
180
+ rx, ry = root_xy(r)
181
+ box = tile_bounds(rx, ry, ROOT_ZOOM)
182
+ bx = shapely.box(*box)
183
+ adm = []
184
+ if atree is not None:
185
+ for ai in atree.query(bx, predicate="intersects"):
186
+ piece = clip(admins[ai].geom, box)
187
+ if piece.is_empty or piece.area == 0:
188
+ continue
189
+ adm.append((admins[ai].id, None if piece.area >= bx.area * (1 - 1e-9) else piece))
190
+ way_rows = scratch.execute("SELECT gid, wkb FROM way WHERE root=?", (r,))
191
+ streets = [(final_id[g], wkb.loads(b)) for g, b in way_rows]
192
+ addr_rows = scratch.execute("SELECT gid,hn,lon,lat FROM addr WHERE root=?", (r,))
193
+ addrs = [(final_id[g], hn, lon, lat) for g, hn, lon, lat in addr_rows]
194
+ _rec(w, rx, ry, ROOT_ZOOM, adm, streets, addrs, interp_by_root.get(r, []))
195
+ if n % 20 == 0 or len(w.rows) > 20000:
196
+ w.flush()
197
+ log(f" roots {n}/{len(roots)} cells={w.n_leaf} split markers={w.n_split}")
198
+ w.flush()
199
+ return w
200
+
201
+
202
+ # ------------------------------------------------------------------ driver
203
+ BIG_INPUT_BYTES = 400 * 2**20 # above this, 'auto' prefilters and keeps the node-location index on disk
204
+
205
+
206
+ def build(pbf: str, output: str, *, language="en", city_level=8, search=True, max_leaf_bytes=16384,
207
+ keep_scratch=False, log=print, prefilter_mode="auto", node_index="auto") -> dict:
208
+ """prefilter_mode: auto|always|never (osmium-tool pre-filtering, see prefilter.py);
209
+ node_index: auto|memory|disk (where libosmium keeps node locations)."""
210
+ out_path = Path(output)
211
+ out_path.unlink(missing_ok=True)
212
+ tmpdir = tempfile.mkdtemp(prefix="loconym-", dir=str(out_path.parent))
213
+ scratch_path = str(Path(tmpdir) / "scratch.sqlite")
214
+ big = Path(pbf).stat().st_size > BIG_INPUT_BYTES
215
+ use_prefilter = prefilter_mode == "always" or (prefilter_mode == "auto" and big and osmium_available())
216
+ boundaries = None
217
+ if use_prefilter:
218
+ boundaries, pbf_in = prefilter(pbf, tmpdir, log)
219
+ else:
220
+ pbf_in = pbf
221
+ on_disk = node_index == "disk" or (node_index == "auto" and big)
222
+ idx = f"sparse_file_array,{Path(tmpdir) / 'nodes.idx'}" if on_disk else "flex_mem"
223
+ ex = extract(pbf_in, scratch_path, city_level, log, boundaries_pbf=boundaries, node_index=idx)
224
+ if not keep_scratch: # large and no longer needed
225
+ for f in ("nodes.idx.1", "nodes.idx.2", "boundaries.pbf", "features.pbf"):
226
+ (Path(tmpdir) / f).unlink(missing_ok=True)
227
+
228
+ # final street ids: dense, ordered by (city, normalized name)
229
+ order = sorted(ex.groups, key=lambda g: (g[2], normalize_key(g[1])))
230
+ final_id = {g[0]: i + 1 for i, g in enumerate(order)}
231
+
232
+ db = sqlite3.connect(out_path)
233
+ db.executescript(f"PRAGMA page_size={PAGE_SIZE}; PRAGMA journal_mode=off; PRAGMA synchronous=off;" + SCHEMA)
234
+ scratch = sqlite3.connect(scratch_path)
235
+ log("stage 2: cells")
236
+ w = build_cells(ex, scratch, db, final_id, max_leaf_bytes, log)
237
+
238
+ log("stage 3: tables")
239
+ db.executemany("INSERT INTO admin VALUES (?,?,?,?,?,?)",
240
+ [(a.id, a.level, a.name, a.parent, a.city, LEVEL_RANK.get(a.level, 30)) for a in ex.admins])
241
+ srows = []
242
+ for tmp, name, city in order:
243
+ lon, lat = ex.group_point.get(tmp, (0.0, 0.0))
244
+ srows.append((final_id[tmp], name, city, round(lat * 1e6), round(lon * 1e6)))
245
+ db.executemany("INSERT INTO street VALUES (?,?,?,?,?)", srows)
246
+
247
+ post = defaultdict(set)
248
+ for a in ex.admins:
249
+ for t in set(normalize_tokens(a.name)):
250
+ post[(t, -1)].add(a.id)
251
+ for sid, name, city, *_ in srows:
252
+ for t in set(normalize_tokens(name)):
253
+ post[(t, city)].add(sid)
254
+ db.executemany("INSERT INTO term VALUES (?,?,?)", ((t, p, encode_postings(ids)) for (t, p), ids in post.items()))
255
+
256
+ log("stage 4: housenumbers")
257
+ scratch.execute("CREATE TEMP TABLE remap(tmp INTEGER PRIMARY KEY, fin INT)")
258
+ scratch.executemany("INSERT INTO remap VALUES (?,?)", final_id.items())
259
+ ints = defaultdict(list)
260
+ for tmp, step, first, last, g in ex.interps:
261
+ ints[final_id[tmp]].append((step, first, last, list(g.coords)))
262
+ cur = scratch.execute("SELECT fin, hn, lon, lat FROM addr JOIN remap ON gid=tmp ORDER BY fin")
263
+ cur_id, items, n_hn = None, [], 0
264
+
265
+ def emit(sid, items):
266
+ items.sort(key=lambda a: natural_key(a[0]))
267
+ db.execute("INSERT INTO housenumber VALUES (?,?)",
268
+ (sid, encode_housenumbers(StreetNumbers(items, ints.pop(sid, [])))))
269
+
270
+ for fin, hn, lon, lat in cur:
271
+ if fin != cur_id and cur_id is not None:
272
+ emit(cur_id, items)
273
+ items = []
274
+ cur_id = fin
275
+ items.append((hn, lon, lat))
276
+ n_hn += 1
277
+ if cur_id is not None:
278
+ emit(cur_id, items)
279
+ for sid in list(ints):
280
+ emit(sid, [])
281
+
282
+ caps = ["reverse"] + (["search", "housenumber", "interpolation"] if search else [])
283
+ meta = {
284
+ "format_version": FORMAT_VERSION,
285
+ "created_utc": datetime.datetime.now(datetime.UTC).isoformat(timespec="seconds"),
286
+ "source": Path(pbf).name, "bbox": ",".join(f"{v:.6f}" for v in ex.bbox), "language": language,
287
+ "capabilities": ",".join(caps), "cell_zoom": CELL_ZOOM, "root_zoom": ROOT_ZOOM, "coord_quantum": COORD_QUANTUM,
288
+ "city_level": city_level, "attribution": ATTRIBUTION, "normalizer": NORMALIZER_VERSION,
289
+ "max_leaf_bytes": max_leaf_bytes,
290
+ }
291
+ db.executemany("INSERT INTO meta VALUES (?,?)", meta.items())
292
+ db.execute("PRAGMA application_id=0x4c474154")
293
+ db.execute("PRAGMA user_version=0")
294
+ db.commit()
295
+ scratch.close()
296
+ if not keep_scratch:
297
+ for f in Path(tmpdir).glob("*"):
298
+ f.unlink()
299
+ Path(tmpdir).rmdir()
300
+ if not search:
301
+ for t in ("term", "housenumber"): # reverse still needs street names
302
+ db.execute(f"DELETE FROM {t}")
303
+ db.commit()
304
+ log("vacuum")
305
+ db.execute("VACUUM")
306
+ db.close()
307
+ stats = dict(size=out_path.stat().st_size, cells=w.n_leaf, split_markers=w.n_split, streets=len(srows),
308
+ housenumbers=n_hn, admins=len(ex.admins))
309
+ log(f"done: {stats}")
310
+ return stats
loconym/cli.py ADDED
@@ -0,0 +1,25 @@
1
+ import argparse
2
+ import sys
3
+
4
+ from .build import build
5
+
6
+
7
+ def main(argv=None) -> None:
8
+ p = argparse.ArgumentParser(prog="loconym")
9
+ sub = p.add_subparsers(dest="cmd", required=True)
10
+ b = sub.add_parser("build", help="Build a database from an .osm.pbf")
11
+ b.add_argument("input")
12
+ b.add_argument("-o", "--output", required=True)
13
+ b.add_argument("--language", default="en")
14
+ b.add_argument("--city-level", type=int, default=8, help="admin_level streets are grouped under")
15
+ b.add_argument("--search", choices=["none", "full"], default="full")
16
+ b.add_argument("--max-leaf-bytes", type=int, default=16384)
17
+ b.add_argument("--keep-scratch", action="store_true")
18
+ b.add_argument("--prefilter", choices=["auto", "always", "never"], default="auto",
19
+ help="pre-filter the input with osmium-tool (auto: only for inputs > 400 MiB)")
20
+ b.add_argument("--node-index", choices=["auto", "memory", "disk"], default="auto",
21
+ help="where node locations are cached (auto: disk for inputs > 400 MiB)")
22
+ a = p.parse_args(argv)
23
+ build(a.input, a.output, language=a.language, city_level=a.city_level, search=a.search == "full",
24
+ max_leaf_bytes=a.max_leaf_bytes, keep_scratch=a.keep_scratch,
25
+ prefilter_mode=a.prefilter, node_index=a.node_index, log=lambda m: print(m, file=sys.stderr))