Skip to content

streetlidar

Manifest discovery and transactional PostGIS streetlidar catalogs.

Paths in tile rows are relative to the catalog root. Footprints are 2D RD; the point coordinates use the compound RD + NAP CRS, EPSG:7415.

Catalog dataclass

Source code in packages/common/src/bag3d/common/streetlidar.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
@dataclass
class Catalog:
    root: Path | None
    manifest: dict
    manifest_sha256: str
    tiles: list[Tile]
    source_fingerprint: str | None = None

    def validate_root(self, root: Path) -> Path:
        """Require consumers to use the store from the published catalog."""
        root = root.resolve()
        if self.root is not None and self.root.resolve() != root:
            raise ValueError(
                "Streetlidar store differs from the published catalog; "
                "refresh streetlidar/tile_index after changing the directory"
            )
        return root

    @property
    def identity(self) -> str:
        return fingerprint(
            {
                "version": 1,
                "root": str(self.root) if self.root else None,
                "manifest": self.manifest,
                "manifest_sha256": self.manifest_sha256,
                "tiles": [
                    asdict(tile)
                    for tile in sorted(self.tiles, key=lambda t: t.location)
                ],
                "source_fingerprint": self.source_fingerprint,
            }
        )

    @property
    def datasets(self) -> dict[str, int]:
        counts = Counter(tile.dataset_id for tile in self.tiles)
        return {
            dataset["id"]: counts[dataset["id"]]
            for dataset in self.manifest["datasets"]
        }

validate_root(root)

Require consumers to use the store from the published catalog.

Source code in packages/common/src/bag3d/common/streetlidar.py
118
119
120
121
122
123
124
125
126
def validate_root(self, root: Path) -> Path:
    """Require consumers to use the store from the published catalog."""
    root = root.resolve()
    if self.root is not None and self.root.resolve() != root:
        raise ValueError(
            "Streetlidar store differs from the published catalog; "
            "refresh streetlidar/tile_index after changing the directory"
        )
    return root

fixture_catalog(root, relative, verify)

Load only declared fixture files; relocation may change filesystem mtimes.

Source code in packages/common/src/bag3d/common/streetlidar.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
def fixture_catalog(
    root: Path, relative: str, verify: Callable[[str], None]
) -> Catalog:
    """Load only declared fixture files; relocation may change filesystem mtimes."""
    path = contained_path(root, relative)
    verify(relative)
    value = json.loads(path.read_bytes())
    if value.get("version") != 1 or value.get("crs") != CRS:
        raise ValueError("Invalid streetlidar fixture catalog")
    manifest = validate_manifest(value["manifest"])
    datasets = {dataset["id"]: dataset["path"] for dataset in manifest["datasets"]}
    tiles = []
    locations = set()
    fixture_root = path.parent
    for record in value["tiles"]:
        location = record["location"]
        tile_path = contained_path(fixture_root, location)
        verify(tile_path.relative_to(root.resolve()).as_posix())
        stat = tile_path.stat()
        dataset_path = datasets.get(record["dataset_id"])
        if dataset_path is None or not tile_path.is_relative_to(
            contained_path(fixture_root, dataset_path)
        ):
            raise ValueError(f"Tile outside declared streetlidar dataset: {location}")
        tile = Tile(
            record["dataset_id"],
            location,
            record["size"],
            stat.st_mtime_ns,
            tuple(record["bounds"]),
            record["point_count"],
            record["metadata"],
        )
        tile.validate()
        tile.path(fixture_root)
        if location in locations:
            raise ValueError(f"Duplicate streetlidar fixture tile: {location}")
        locations.add(location)
        tiles.append(tile)
    catalog = Catalog(
        fixture_root,
        manifest,
        fingerprint(manifest),
        tiles,
        value["source_fingerprint"],
    )
    if any(count == 0 for count in catalog.datasets.values()):
        raise ValueError("Streetlidar fixture declares a dataset without tiles")
    return catalog

publish(connection, catalog)

Caller holds the refresh advisory lock and commits only on success.

Source code in packages/common/src/bag3d/common/streetlidar.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def publish(connection: Connection, catalog: Catalog) -> dict:
    """Caller holds the refresh advisory lock and commits only on success."""
    identity = catalog.identity
    stats = {
        "tiles": len(catalog.tiles),
        "datasets": catalog.datasets,
        "fingerprint": identity,
        "manifest_sha256": catalog.manifest_sha256,
        "added": 0,
        "changed": 0,
        "removed": 0,
    }
    state = connection.execute(
        "SELECT fingerprint FROM streetlidar.catalog_state WHERE singleton"
    ).fetchone()
    if state and state[0] == identity:
        return stats
    with connection.cursor() as cursor:
        cursor.execute("SELECT location FROM streetlidar.tile_index")
        before = {row[0] for row in cursor}
        changed = added = 0
        for tile in catalog.tiles:
            tile.validate()
            minx, miny, maxx, maxy = tile.bounds
            with connection.cursor() as writer:
                writer.execute(
                    """INSERT INTO streetlidar.tile_index AS old
                    (location,dataset_id,size,mtime_ns,point_count,boundary,metadata)
                    VALUES (%s,%s,%s,%s,%s,ST_MakeEnvelope(%s,%s,%s,%s,28992),%s)
                    ON CONFLICT(location) DO UPDATE SET
                    dataset_id=excluded.dataset_id,size=excluded.size,mtime_ns=excluded.mtime_ns,
                    point_count=excluded.point_count,boundary=excluded.boundary,metadata=excluded.metadata
                    WHERE (old.dataset_id,old.size,old.mtime_ns,old.point_count,old.boundary,old.metadata)
                    IS DISTINCT FROM (excluded.dataset_id,excluded.size,excluded.mtime_ns,
                                      excluded.point_count,excluded.boundary,excluded.metadata)
                    RETURNING location""",
                    (
                        tile.location,
                        tile.dataset_id,
                        tile.size,
                        tile.mtime_ns,
                        tile.point_count,
                        minx,
                        miny,
                        maxx,
                        maxy,
                        Jsonb(tile.metadata),
                    ),
                )
                if writer.fetchone():
                    if tile.location in before:
                        changed += 1
                    else:
                        added += 1
        cursor.execute(
            "DELETE FROM streetlidar.tile_index WHERE NOT (location = ANY(%s))",
            ([t.location for t in catalog.tiles],),
        )
        removed = cursor.rowcount
        cursor.execute(
            """INSERT INTO streetlidar.catalog_state
            (singleton,root,manifest,manifest_sha256,fingerprint,source_fingerprint,datasets)
            VALUES (true,%s,%s,%s,%s,%s,%s)
            ON CONFLICT(singleton) DO UPDATE SET root=excluded.root,manifest=excluded.manifest,
            manifest_sha256=excluded.manifest_sha256,fingerprint=excluded.fingerprint,
            source_fingerprint=excluded.source_fingerprint,datasets=excluded.datasets,updated_at=now()""",
            (
                str(catalog.root) if catalog.root else None,
                Jsonb(catalog.manifest),
                catalog.manifest_sha256,
                identity,
                catalog.source_fingerprint,
                Jsonb(catalog.datasets),
            ),
        )
    return {**stats, "added": added, "changed": changed, "removed": removed}

selected_locations(connection, source, polygon_buffer, table=TILE_INDEX)

Conservative coverage query; the estimator performs exact crop selection.

Source code in packages/common/src/bag3d/common/streetlidar.py
354
355
356
357
358
359
360
361
362
363
364
365
366
def selected_locations(
    connection: Connection,
    source: PostgresTableIdentifier,
    polygon_buffer: float,
    table: PostgresTableIdentifier = TILE_INDEX,
) -> set[str]:
    """Conservative coverage query; the estimator performs exact crop selection."""
    rows = connection.execute(
        sql.SQL("""SELECT DISTINCT t.location FROM {} t
        JOIN {} g ON t.boundary && ST_Expand(g.geom,%s)""").format(table.id, source.id),
        (max(0.0, polygon_buffer),),
    )
    return {row[0] for row in rows}