Skip to content

TerrainModel

TerrainModel

DTM helper built on rasterio.

Wraps GeoTIFF-backed elevation model and provides convenience methods for querying pixel values, retrieving the spatial extent, and cropping/resampling.

Source code in occpy/terrainmodel.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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
class TerrainModel():
    """
    DTM helper built on rasterio.

    Wraps GeoTIFF-backed elevation model and provides convenience methods for
    querying pixel values, retrieving the spatial extent, and cropping/resampling.
    """

    def __init__(self, path2geotiff):
        """
        Open a DTM GeoTIFF for reading.

        Parameters
        ----------
        path2geotiff : str
            Path to a GeoTIFF file (typically single-band) in the dataset CRS.
        """
        self.path2tiff = path2geotiff
        self.dtm = rasterio.open(path2geotiff)


    def get_terrainmodel_path(self):
        """
        Return the path to the currently opened DTM file.

        Returns
        -------
        str
            Absolute path of DTM file.
        """
        return self.dtm.name

    def get_pixel_value(self, x, y):
        """
        Sample the DTM at map coordinates.

        Parameters
        ----------
        x : float
            X coordinate in the dataset CRS.
        y : float
            Y coordinate in the dataset CRS.

        Returns
        -------
        float
            Elevation value at (x, y).
        """
        pix_val = self.dtm.sample([(x,y)])
        pix_val = list(pix_val)

        return pix_val[0][0] #TODO: check if this solution is generic!

    def get_extent(self):
        """
        Return the dataset bounding box.

        Returns
        -------
        rasterio.coords.BoundingBox
            Bounding box (left, bottom, right, top) in the dataset CRS.
        """
        return self.dtm.bounds

    # crop to extent and change resolution if not None
    def crop2extent(self, extent, out_file, res=None):
        """
        Crop the DTM to an extent and optionally resample to a target pixel size.
        Writes the cropped data to `out_file`. 
        If `res` is provided, the raster is resampled using bilinear interpolation 
        to the given pixel size. The instance is updated to reference the new file.

        Parameters
        ----------
        extent : tuple of float
            Bounding box in the dataset CRS as (min_x, max_y, max_x, min_y).
        out_file : str
            Output GeoTIFF path for the cropped (and optionally resampled) raster.
        res : float, optional
            Target pixel size (units per pixel). If None, the original resolution is kept.

        Returns
        -------
        numpy.ndarray
            Cropped (and optionally resampled) data with shape (count, height, width).
        """

        # first crop and then write back
        min_x, max_y, max_x, min_y = extent
        window = rasterio.windows.from_bounds(min_x, min_y, max_x, max_y, self.dtm.transform)
        data = self.dtm.read(1, window=window)
        if data.ndim == 2:
            data = data[np.newaxis, ...]
        # Calculate the transform for the window
        out_transform = self.dtm.window_transform(window)
        profile = self.dtm.profile.copy()
        profile.update({
            "height": data.shape[-2],
            "width": data.shape[-1],
            "transform": out_transform,
            "count": data.shape[0]
        })
        with rasterio.open(out_file, "w", **profile) as dataset:
            dataset.write(data)

        # also do resampling if necessary
        if res!=None:
            with rasterio.open(out_file) as dataset:
                scale_factor_x = dataset.res[0]/res
                scale_factor_y = dataset.res[1]/res

                profile = dataset.profile.copy()
                # resample data to target shape
                data = dataset.read(
                    out_shape=(
                        dataset.count,
                        int(dataset.height * scale_factor_y),
                        int(dataset.width * scale_factor_x)
                    ),
                    resampling=Resampling.bilinear
                )

                # scale image transform
                transform = dataset.transform * dataset.transform.scale(
                    (1 / scale_factor_x),
                    (1 / scale_factor_y)
                )
                profile.update({"height": data.shape[-2],
                                "width": data.shape[-1],
                                "transform": transform})
            with rasterio.open(out_file, "w", **profile) as dataset:
                dataset.write(data)

        # overwrite self.path2tiff to cropped file
        self.path2tiff = out_file
        self.dtm = rasterio.open(out_file)
        return data

__init__

__init__(path2geotiff)

Open a DTM GeoTIFF for reading.

Parameters:

  • path2geotiff (str) –

    Path to a GeoTIFF file (typically single-band) in the dataset CRS.

Source code in occpy/terrainmodel.py
191
192
193
194
195
196
197
198
199
200
201
def __init__(self, path2geotiff):
    """
    Open a DTM GeoTIFF for reading.

    Parameters
    ----------
    path2geotiff : str
        Path to a GeoTIFF file (typically single-band) in the dataset CRS.
    """
    self.path2tiff = path2geotiff
    self.dtm = rasterio.open(path2geotiff)

crop2extent

crop2extent(extent, out_file, res=None)

Crop the DTM to an extent and optionally resample to a target pixel size. Writes the cropped data to out_file. If res is provided, the raster is resampled using bilinear interpolation to the given pixel size. The instance is updated to reference the new file.

Parameters:

  • extent (tuple of float) –

    Bounding box in the dataset CRS as (min_x, max_y, max_x, min_y).

  • out_file (str) –

    Output GeoTIFF path for the cropped (and optionally resampled) raster.

  • res (float, default: None ) –

    Target pixel size (units per pixel). If None, the original resolution is kept.

Returns:

  • ndarray –

    Cropped (and optionally resampled) data with shape (count, height, width).

Source code in occpy/terrainmodel.py
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
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
def crop2extent(self, extent, out_file, res=None):
    """
    Crop the DTM to an extent and optionally resample to a target pixel size.
    Writes the cropped data to `out_file`. 
    If `res` is provided, the raster is resampled using bilinear interpolation 
    to the given pixel size. The instance is updated to reference the new file.

    Parameters
    ----------
    extent : tuple of float
        Bounding box in the dataset CRS as (min_x, max_y, max_x, min_y).
    out_file : str
        Output GeoTIFF path for the cropped (and optionally resampled) raster.
    res : float, optional
        Target pixel size (units per pixel). If None, the original resolution is kept.

    Returns
    -------
    numpy.ndarray
        Cropped (and optionally resampled) data with shape (count, height, width).
    """

    # first crop and then write back
    min_x, max_y, max_x, min_y = extent
    window = rasterio.windows.from_bounds(min_x, min_y, max_x, max_y, self.dtm.transform)
    data = self.dtm.read(1, window=window)
    if data.ndim == 2:
        data = data[np.newaxis, ...]
    # Calculate the transform for the window
    out_transform = self.dtm.window_transform(window)
    profile = self.dtm.profile.copy()
    profile.update({
        "height": data.shape[-2],
        "width": data.shape[-1],
        "transform": out_transform,
        "count": data.shape[0]
    })
    with rasterio.open(out_file, "w", **profile) as dataset:
        dataset.write(data)

    # also do resampling if necessary
    if res!=None:
        with rasterio.open(out_file) as dataset:
            scale_factor_x = dataset.res[0]/res
            scale_factor_y = dataset.res[1]/res

            profile = dataset.profile.copy()
            # resample data to target shape
            data = dataset.read(
                out_shape=(
                    dataset.count,
                    int(dataset.height * scale_factor_y),
                    int(dataset.width * scale_factor_x)
                ),
                resampling=Resampling.bilinear
            )

            # scale image transform
            transform = dataset.transform * dataset.transform.scale(
                (1 / scale_factor_x),
                (1 / scale_factor_y)
            )
            profile.update({"height": data.shape[-2],
                            "width": data.shape[-1],
                            "transform": transform})
        with rasterio.open(out_file, "w", **profile) as dataset:
            dataset.write(data)

    # overwrite self.path2tiff to cropped file
    self.path2tiff = out_file
    self.dtm = rasterio.open(out_file)
    return data

get_extent

get_extent()

Return the dataset bounding box.

Returns:

  • BoundingBox –

    Bounding box (left, bottom, right, top) in the dataset CRS.

Source code in occpy/terrainmodel.py
236
237
238
239
240
241
242
243
244
245
def get_extent(self):
    """
    Return the dataset bounding box.

    Returns
    -------
    rasterio.coords.BoundingBox
        Bounding box (left, bottom, right, top) in the dataset CRS.
    """
    return self.dtm.bounds

get_pixel_value

get_pixel_value(x, y)

Sample the DTM at map coordinates.

Parameters:

  • x (float) –

    X coordinate in the dataset CRS.

  • y (float) –

    Y coordinate in the dataset CRS.

Returns:

  • float –

    Elevation value at (x, y).

Source code in occpy/terrainmodel.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def get_pixel_value(self, x, y):
    """
    Sample the DTM at map coordinates.

    Parameters
    ----------
    x : float
        X coordinate in the dataset CRS.
    y : float
        Y coordinate in the dataset CRS.

    Returns
    -------
    float
        Elevation value at (x, y).
    """
    pix_val = self.dtm.sample([(x,y)])
    pix_val = list(pix_val)

    return pix_val[0][0] #TODO: check if this solution is generic!

get_terrainmodel_path

get_terrainmodel_path()

Return the path to the currently opened DTM file.

Returns:

  • str –

    Absolute path of DTM file.

Source code in occpy/terrainmodel.py
204
205
206
207
208
209
210
211
212
213
def get_terrainmodel_path(self):
    """
    Return the path to the currently opened DTM file.

    Returns
    -------
    str
        Absolute path of DTM file.
    """
    return self.dtm.name

nhit_to_dsm

nhit_to_dsm(nhit_grid, config, out_file, smoothing_sigma=None)

Generate a canopy-surface GeoTIFF from an Nhit grid by taking, for each (x, y) column, the height of the highest voxel with at least one hit.

The resulting file has the same extent and pixel size as the voxel grid, so it can be used directly as the dsm_file argument of occpy.util.normalize_occlusion_output (which derives a canopy height model internally as dsm - dtm).

Parameters:

  • nhit_grid (ndarray) –

    3D array (nx, ny, nz) with the number of hits per voxel, as produced by the occpy raytracer.

  • config (dict) –

    Configuration dictionary containing 'plot_dim' ([minX, minY, minZ, maxX, maxY, maxZ]) and 'vox_dim' (voxel size), matching the values used to derive nhit_grid. An optional 'crs' key (anything accepted by rasterio, e.g. an EPSG string) sets the output CRS.

  • out_file (str) –

    Path to the output GeoTIFF file for the generated DSM.

  • smoothing_sigma (float, default: None ) –

    Standard deviation of the Gaussian kernel (in voxels/pixels) for a nodata-aware smoothing pass to remove per-column max-height spike noise before writing. If None, no smoothing is applied.

Returns:

  • ndarray –

    2D DSM array as written to out_file, with shape (ny, nx).

Source code in occpy/terrainmodel.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def nhit_to_dsm(nhit_grid, config, out_file, smoothing_sigma=None):
    """
    Generate a canopy-surface GeoTIFF from an Nhit grid by taking, for each (x, y)
    column, the height of the highest voxel with at least one hit.

    The resulting file has the same extent and pixel size as the voxel grid, so it
    can be used directly as the `dsm_file` argument of
    `occpy.util.normalize_occlusion_output` (which derives a canopy height model
    internally as dsm - dtm).

    Parameters
    ----------
    nhit_grid : numpy.ndarray
        3D array (nx, ny, nz) with the number of hits per voxel, as produced by
        the occpy raytracer.
    config : dict
        Configuration dictionary containing 'plot_dim' ([minX, minY, minZ, maxX,
        maxY, maxZ]) and 'vox_dim' (voxel size), matching the values used to
        derive `nhit_grid`. An optional 'crs' key (anything accepted by
        rasterio, e.g. an EPSG string) sets the output CRS. 
    out_file : str
        Path to the output GeoTIFF file for the generated DSM.
    smoothing_sigma : float, optional
        Standard deviation of the Gaussian kernel (in voxels/pixels) for a
        nodata-aware smoothing pass to remove per-column max-height spike noise
        before writing. If None, no smoothing is applied.

    Returns
    -------
    numpy.ndarray
        2D DSM array as written to `out_file`, with shape (ny, nx).
    """
    plot_dim = config["plot_dim"]
    vox_dim = config["vox_dim"]

    dsm = _elevation_from_nhit_grid(nhit_grid, plot_dim, vox_dim, use_min=False)
    dsm = _smooth_elevation(dsm, smoothing_sigma)
    _write_elevation_geotiff(dsm, plot_dim, vox_dim, out_file, crs=config.get("crs"))
    return dsm

nhit_to_dtm

nhit_to_dtm(nhit_grid, config, out_file, smoothing_sigma=None)

Generate a DTM GeoTIFF from an Nhit grid by taking, for each (x, y) column, the height of the lowest voxel with at least one hit (i.e. the ground return).

The resulting file has the same extent and pixel size as the voxel grid, so it can be used directly as the dtm_file argument of occpy.util.normalize_occlusion_output.

Parameters:

  • nhit_grid (ndarray) –

    3D array (nx, ny, nz) with the number of hits per voxel, as produced by the occpy raytracer.

  • config (dict) –

    Configuration dictionary containing 'plot_dim' ([minX, minY, minZ, maxX, maxY, maxZ]) and 'vox_dim' (voxel size), matching the values used to derive nhit_grid. An optional 'crs' key (anything accepted by rasterio, e.g. an EPSG string) sets the output CRS.

  • out_file (str) –

    Path to the output GeoTIFF file for the generated DTM.

  • smoothing_sigma (float, default: None ) –

    Standard deviation of the Gaussian kernel (in voxels/pixels) for a nodata-aware smoothing pass to remove per-column max-height spike noise before writing. If None, no smoothing is applied.

Returns:

  • ndarray –

    2D DTM array as written to out_file, with shape (ny, nx).

Source code in occpy/terrainmodel.py
103
104
105
106
107
108
109
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
def nhit_to_dtm(nhit_grid, config, out_file, smoothing_sigma=None):
    """
    Generate a DTM GeoTIFF from an Nhit grid by taking, for each (x, y) column,
    the height of the lowest voxel with at least one hit (i.e. the ground return).

    The resulting file has the same extent and pixel size as the voxel grid, so it
    can be used directly as the `dtm_file` argument of
    `occpy.util.normalize_occlusion_output`.

    Parameters
    ----------
    nhit_grid : numpy.ndarray
        3D array (nx, ny, nz) with the number of hits per voxel, as produced by
        the occpy raytracer.
    config : dict
        Configuration dictionary containing 'plot_dim' ([minX, minY, minZ, maxX,
        maxY, maxZ]) and 'vox_dim' (voxel size), matching the values used to
        derive `nhit_grid`. An optional 'crs' key (anything accepted by
        rasterio, e.g. an EPSG string) sets the output CRS.
    out_file : str
        Path to the output GeoTIFF file for the generated DTM.
    smoothing_sigma : float, optional
        Standard deviation of the Gaussian kernel (in voxels/pixels) for a
        nodata-aware smoothing pass to remove per-column max-height spike noise
        before writing. If None, no smoothing is applied.

    Returns
    -------
    numpy.ndarray
        2D DTM array as written to `out_file`, with shape (ny, nx).
    """
    plot_dim = config["plot_dim"]
    vox_dim = config["vox_dim"]

    dtm = _elevation_from_nhit_grid(nhit_grid, plot_dim, vox_dim, use_min=True)
    dtm = _smooth_elevation(dtm, smoothing_sigma)
    _write_elevation_geotiff(dtm, plot_dim, vox_dim, out_file, crs=config.get("crs"))
    return dtm