Skip to content

terrain

Portable raw-AHN snapshot contract shared by core and terrain.

covers_bounds(extents, bounds)

Check rectangle union coverage by merging vertical intervals in each x strip.

Source code in packages/common/src/bag3d/common/terrain.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def covers_bounds(extents, bounds) -> bool:
    """Check rectangle union coverage by merging vertical intervals in each x strip."""
    west, south, east, north = bounds
    edges = sorted(
        {west, east}
        | {x for extent in extents for x in (extent[0], extent[2]) if west < x < east}
    )
    for left, right in zip(edges, edges[1:]):
        intervals = sorted(
            (bottom, top)
            for x0, bottom, x1, top in extents
            if x0 <= left and x1 >= right
        )
        covered = south
        for bottom, top in intervals:
            if bottom > covered:
                break
            covered = max(covered, top)
        if covered < north:
            return False
    return True

padded_bounds(bounds, radius_m)

Include interpolation neighbors and the source-transition warp buffer.

Source code in packages/common/src/bag3d/common/terrain.py
13
14
15
16
17
def padded_bounds(bounds, radius_m):
    """Include interpolation neighbors and the source-transition warp buffer."""
    west, south, east, north = bounds
    halo = radius_m + SELECTION_MARGIN_M
    return west - halo, south - halo, east + halo, north + halo

terrain_snapshot(root, manifest=None)

Verify the declared terrain catalog and files without modifying the snapshot.

Source code in packages/common/src/bag3d/common/terrain.py
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
151
152
153
154
155
156
157
158
def terrain_snapshot(root: Path, manifest: Mapping | None = None) -> dict:
    """Verify the declared terrain catalog and files without modifying the snapshot."""
    if manifest is None:
        manifest = json.loads((root / "manifest.json").read_text())
    if not isinstance(manifest, Mapping):
        raise ValueError("Integration snapshot manifest must be a JSON object")
    if str(manifest.get("fixture_version")) not in {"2", "3"}:
        raise ValueError("Unsupported terrain integration snapshot version")
    source = manifest.get("sources", {}).get("terrain")
    if not isinstance(source, dict) or not isinstance(source.get("path"), str):
        raise ValueError(
            "Integration snapshot has no terrain data; regenerate it with integration_data"
        )
    inventory = manifest["files"]

    def verify(relative):
        path = snapshot_path(root, relative)
        record = inventory.get(relative)
        if (
            not isinstance(record, dict)
            or not path.is_file()
            or path.stat().st_size != record.get("size")
            or sha256_file(path) != record.get("sha256")
        ):
            raise ValueError(
                f"Missing, changed or undeclared terrain fixture: {relative}"
            )
        return path

    catalog = json.loads(verify(source["path"]).read_text())
    validate_terrain_catalog(catalog, manifest.get("aoi"))
    for record in catalog["files"]:
        relative = record["path"]
        verify(relative)
        declared = inventory[relative]
        if (
            record["bytes"] != declared["size"]
            or record["sha256"] != declared["sha256"]
        ):
            raise ValueError(
                f"Terrain catalog and snapshot inventory disagree: {relative}"
            )
    return catalog

validate_terrain_catalog(catalog, aoi=None)

Apply the same metadata and coverage contract before publishing and reading.

Source code in packages/common/src/bag3d/common/terrain.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def validate_terrain_catalog(catalog: dict, aoi: dict | None = None) -> None:
    """Apply the same metadata and coverage contract before publishing and reading."""
    if (
        catalog.get("version") != 1
        or catalog.get("height_reference") != "NAP"
        or catalog.get("crs") != "EPSG:28992"
        or catalog.get("resolution_m") != 5
    ):
        raise ValueError("Expected a version-1 raw 5 m RD/NAP terrain catalog")
    validate_bounds(catalog["bounds"])
    bounds_rd = validate_bounds(catalog["bounds_rd"])
    validate_bounds(catalog["selection_bounds_rd"])
    radius = catalog["selection_radius_m"]
    if not isinstance(radius, (int, float)) or not math.isfinite(radius) or radius <= 0:
        raise ValueError("Invalid terrain snapshot interpolation radius")
    if not contains(catalog["selection_bounds_rd"], padded_bounds(bounds_rd, radius)):
        raise ValueError("Terrain snapshot has insufficient interpolation neighbors")
    if aoi is not None:
        required = [
            aoi["minx"] - 10,
            aoi["miny"] - 10,
            aoi["maxx"] + 10,
            aoi["maxy"] + 10,
        ]
        if not contains(bounds_rd, validate_bounds(required)):
            raise ValueError("Terrain snapshot does not cover the integration AOI")
    records = catalog.get("files")
    if not isinstance(records, list) or not records:
        raise ValueError("Terrain snapshot contains no raw AHN rasters")
    locations = [record["path"] for record in records]
    if len(set(locations)) != len(locations):
        raise ValueError("Duplicate terrain fixture paths")
    extents = [validate_bounds(record["bounds_rd"]) for record in records]
    if not covers_bounds(extents, bounds_rd):
        raise ValueError(
            "Terrain rasters have insufficient coverage of the snapshot AOI"
        )