terrainseg

Submodules

Classes

defineUNet

UNet for terrain semantic segmentation.

defineCUNet

Customizable UNet for terrain semantic segmentation.

defineCNXTUNet

ConvNeXt-style UNet with attention-gated skip connections for semantic segmentation.

gaussPyramids

Base class for all neural network modules.

lspCalc

Base class for all neural network modules.

lspModule

Base class for all neural network modules.

terrainDataset

PyTorch dataset for raster-based terrain semantic segmentation.

terrainDatasetDynamic

PyTorch dataset that dynamically generates raster chips for terrain

unifiedFocalLoss

Base class for all neural network modules.

Functions

viewBatch(, cNames, cColors, padding, figsize, int] =, ...)

View a mini-batch of DTM chips and associated masks to visually validate that chips are being generated as expected.

makeMasks(→ None)

Rasterize vector features to a mask aligned to an existing raster grid, optionally cropping the raster first.

makeChips(→ None)

This function generates image and mask chips from an input image and associated raster mask.

makeChipsDF(→ pandas.DataFrame)

This function creates a data frame and, optionally, a CSV file that lists all of the image chips and associated masks in a directory.

makeChipsMulticlass(→ None)

Generates image and mask chips from an input image and associated raster mask.

makeDynamicChipsGDF(→ geopandas.GeoDataFrame)

Generate a GeoDataFrame of dynamic chip sampling locations.

checkDynamicChips(→ geopandas.GeoDataFrame)

Validate dynamically generated raster chips and append quality metrics.

terrainPredict(image_in, pred_out, model[, chip_size, ...])

Use train model to make predictions over a spatial extent.

Package Contents

class terrainseg.defineUNet(inChn: int = 6, nCls: int = 2, encoderChn: Tuple[int, int, int, int] = (16, 32, 64, 128), decoderChn: Tuple[int, int, int, int] = (128, 64, 32, 16), botChn: int = 256)[source]

Bases: torch.nn.Module

UNet for terrain semantic segmentation.

Parameters:
  • inChn (int, default=6) – Number of input channels.

  • nCls (int, default = 2) – Number of output classes.

  • encoderChn (Tuple[int, int, int, int], default=(16, 32, 64, 128).) – Number of output feature maps from each encoder block. Must be a tuple of 4 integers.

  • decoderChn (Tuple[int, int, int, int], default=(128,64,32,16).) – Number of output feature maps from each decoder block. Must be a tuple of 4 integers.

  • botChn (int, default=256) – Number of output feature maps from the bottleneck block.

Return type:

Model as nn.Module subclass.

inChn = 6
nCls = 2
encoderChn = (16, 32, 64, 128)
decoderChn = (128, 64, 32, 16)
botChn = 256
encoder1
encoder2
encoder3
encoder4
bottleneck
decoder1up
decoder1
decoder2up
decoder2
decoder3up
decoder3
decoder4up
decoder4
classifier
forward(x: torch.Tensor) → torch.Tensor[source]

Forward pass.

Parameters:

x (torch.Tensor) – Input tensor of shape (B, C, H, W).

Returns:

Segmentation logits of shape (B, n_classes, H, W).

Return type:

torch.Tensor

class terrainseg.defineCUNet(in_chn: int = 1, n_cls: int = 2, act_func: Literal['relu', 'lrelu', 'swish'] = 'relu', use_attn: bool = False, use_se: bool = False, use_res: bool = False, use_aspp: bool = False, en_chn: Tuple[int, int, int, int] = (16, 32, 64, 128), dc_chn: Tuple[int, int, int, int] = (128, 64, 32, 16), btn_chn: int = 256, dil_rates: Tuple[int, int, int] = (6, 12, 18), dil_chn: Tuple[int, int, int, int] = (256, 256, 256, 256), negative_slope: float = 0.01, se_ratio: int = 8)[source]

Bases: torch.nn.Module

Customizable UNet for terrain semantic segmentation.

Parameters:
  • in_chn (int, default=1) – Number of input channels.

  • n_cls (int, default=2) – Number of predicted classes.

  • act_func (Literal["relu", "lrelu", "swish"], default="relu") – Activation function to use throughout architecture. “relu” = Rectified Linear Unit (ReLU); “lrelu” = Leaky ReLU; “swish” = Swish.

  • use_attn (bool, default=False) – Whether or not to incorporate attention gates along the skip connections.

  • use_se (bool, default=False) – Whether or not to incorporate squeeze and excitation modules into the encoder.

  • use_res (bool, default=False) – Whether or not to include residual connections with all double-convolution blocks in the encoder and decoder.

  • use_aspp (bool, default=False) – Whether or not to use an atrous spatial pyramid pooling (ASPP) module as the bottleneck block.

  • en_chn (Tuple[int, int, int, int], default=(16,32,64,128)) – Number of output feature maps from each encoder block. Must be tuple of 4 integers.

  • dc_chn (Tuple[int, int, int, int], default=(128,64,32,16)) – Number of output feature maps from each decoder block. Must be tuple of 4 integers.

  • btn_chn (int, default=256) – Number of output feature maps from the bottleneck.

  • dil_rates (Tuple[int, int, int], default=(6,12,18)) – If use_aspp = True, dilation rates to use in the ASPP module. Must be a tuple of 3 integers.

  • dil_chn (Tuple[int, int, int, int], default=(256,256,256,256)) – If use_aspp = True, number of feature maps to be generated by each component of the ASPP module. Must be a tuple of 4 integers.

  • negative_slope (float, default=0.01) – If act_func = “lrelu”, negative slope term.

  • se_ratio (int, default=8) – If use_se = True, reduction ratio to use.

Return type:

Model as nn.Module subclass.

use_attn = False
use_se = False
use_res = False
use_aspp = False
e1
e2
e3
e4
dUp1
dUp2
dUp3
dUp4
d1
d2
d3
d4
c4
forward(x: torch.Tensor) → torch.Tensor[source]

Forward pass.

Parameters:

x (torch.Tensor) – Input tensor of shape (B, C, H, W).

Returns:

Segmentation logits of shape (B, n_classes, H, W).

Return type:

torch.Tensor

class terrainseg.defineCNXTUNet(in_channels: int = 6, num_classes: int = 2, features: Tuple[int, int, int, int, int] = (64, 128, 256, 512, 1024), enc_depths: Tuple[int, int, int, int] = (2, 2, 2, 2), bottleneck_depth: int = 2, mlp_ratio: int = 4, gn_groups: int = 8, upsample_mode: Literal['interp', 'transpose'] = 'interp', interp_mode: Literal['bilinear', 'nearest'] = 'bilinear', attn_inter_channels: str = None, skip_proj: str = 'match', skip_proj_act: str = 'gelu')[source]

Bases: torch.nn.Module

ConvNeXt-style UNet with attention-gated skip connections for semantic segmentation.

This model uses a ConvNeXt-inspired encoder (stacked ConvNeXt blocks within downsampling stages), a bottleneck block stack, and a U-Net decoder with attention-gated skip connections and residual decoder blocks. Skip features can optionally be projected to match decoder widths (or to a user-specified channel count) prior to fusion.

Parameters:
  • in_channels (int, default=6) – Number of input channels in the input tensor (e.g., multispectral bands or terrain derivatives).

  • num_classes (int, default=2) – Number of output segmentation classes (i.e., number of logits per pixel).

  • features (tuple[int, int, int, int, int], default=(64, 128, 256, 512, 1024)) – Channel widths for each resolution level: (c1, c2, c3, c4, c5), where c1 is the highest-resolution stage width (stem/decoder output) and c5 is the deepest stage width (encoder output / bottleneck input).

  • enc_depths (tuple[int, int, int, int], default=(2, 2, 2, 2)) – Number of ConvNeXt blocks in each encoder downsampling stage: (d1, d2, d3, d4).

  • bottleneck_depth (int, default=2) – Number of ConvNeXt blocks in the bottleneck (deepest) stage.

  • mlp_ratio (int, default=4) – Expansion ratio for the ConvNeXt block MLP (channel mixing) sub-layer.

  • gn_groups (int, default=8) – Target number of groups for GroupNorm. The effective group count may be adjusted per stage to ensure it divides the channel count (see _valid_gn_groups).

  • upsample_mode ({"interp", "transpose"}, default="interp") – Upsampling strategy in decoder stages: - "interp" uses non-trainable interpolation followed by convolution. - "transpose" uses a learnable transposed convolution.

  • interp_mode ({"bilinear", "nearest"}, default="bilinear") – Interpolation mode used when upsample_mode="interp".

  • attn_inter_channels (str or None, default=None) – Intermediate channel setting for attention gates used on skip connections. Interpretation depends on UpStageAttnRes implementation (e.g., may accept "auto" or explicit sizing). If None, UpStageAttnRes chooses its default.

  • skip_proj ({"none", "match"} or int or None, default="match") – Skip projection strategy before fusing encoder skip features into the decoder: - "none" or None: no projection; skip features are used as-is. - "match": project skip features to match the decoder stage width. - int: project skip features to this fixed number of channels.

  • skip_proj_act (str, default="gelu") – Activation used in the skip projection path (if enabled). Passed through to UpStageAttnRes (e.g., "gelu", "relu", etc., depending on implementation).

stem

Initial convolutional stem (Conv2d + GroupNorm + GELU) that maps inputs to c1.

Type:

nn.Module

down1, down2, down3, down4

Encoder downsampling stages producing multi-scale features.

Type:

nn.Module

bottleneck

Sequence of ConvNeXt blocks operating at the deepest resolution (c5 channels).

Type:

nn.Module

up4, up3, up2, up1

Decoder upsampling stages with attention-gated skip connections and residual blocks.

Type:

nn.Module

head

Final 1x1 convolution mapping c1 channels to num_classes logits.

Type:

nn.Module

Notes

  • Output logits have shape (N, num_classes, H, W) and are typically passed to a loss such as CrossEntropyLoss (multi-class) or BCEWithLogitsLoss (binary/multi-label), depending on your label encoding.

  • GroupNorm is used in the stem/decoder for stability across batch sizes.

See also

DownStage

Encoder stage module used for downsampling and feature extraction.

ConvNeXtBlock

Core ConvNeXt-style block used in encoder and bottleneck.

UpStageAttnRes

Decoder stage with attention-gated skip fusion and residual blocks.

stem
down1
down2
down3
down4
bottleneck
up4
up3
up2
up1
head
forward(x: torch.Tensor) → torch.Tensor[source]

Forward pass.

Parameters:

x (torch.Tensor) – Input tensor of shape (B, C, H, W).

Returns:

Segmentation logits of shape (B, n_classes, H, W).

Return type:

torch.Tensor

terrainseg.viewBatch(dataloader, ncols: int = 3, cCodes: Sequence[int] = (), cNames: Sequence[str] = (), cColors: Sequence[str] = (), padding: int = 10, figsize: Tuple[int, int] = (10, 10), mask_mode: Literal['auto', 'index', 'onehote'] = 'auto', stretch: str = 'percentile', p_low: float = 2.0, p_high: float = 98.0) → Dict[str, Any][source]

View a mini-batch of DTM chips and associated masks to visually validate that chips are being generated as expected.

Parameters:
  • dataloader – Instantiated torch dataloader created using terrainDataset() or terrainDatasetDynamic().

  • ncols (int, default=3) – Number of columns in image grids.

  • cCode (Sequence[int]) – Integer codes assigned to each class. Must be the same length as the number of classes.

  • cNames (Sequence[int]) – Class names associated with each class code and in the same order as the class codes.

  • cColors (Sequence[int]) – Named Python colors or hex codes as strings that define colors used to differentiate the classes.

  • padding (int, default=10) – Number of cells or pixels to add between each chip in the image array.

  • figsize (Tuple[int, int], default=(10, 10)) – Size of image as a tuple of height and width values.

  • mask_mode (Literal["auto", "index", "onehot"], default="auto",) – Defines how masks are represented (either “auto”, “index”, or “onehot”). terrainseg uses “index”. Recommend leaving this set to the default value of “auto”.

  • stretch (str, default="percentile) – Type of stretch to apply (either “percentile”, “minmax”, or “max”). Recommend using the default.

  • p_low (float, default=2.0) – If stretch = “percentile”, defines the lower percentile.

  • p_high (float, default=98.0) – If stretch = “percentile”, defines the upper percentile to use.

Return type:

Matplotlib plot.

terrainseg.makeMasks(image: str, features: str, crop: bool = False, extent: str | None = None, field: str | None = None, background: int | float = 0, out_image: str | None = None, out_mask: str | None = None, mode: ModeMask = 'Both', all_touched: bool = False, dtype: str = 'uint8') → None[source]

Rasterize vector features to a mask aligned to an existing raster grid, optionally cropping the raster first.

Parameters:
  • image (str) – Path to reference raster (defines grid, resolution, transform, CRS).

  • features (str) – Path to vector data (e.g., .shp, .gpkg).

  • crop (bool) – If True, crop the raster to extent geometry before rasterizing.

  • extent (Optional[str]) – Path to polygon vector defining crop extent (required if crop=True).

  • field (Optional[str]) – Attribute field name to burn into raster. If None, burns 1s.

  • background (int|float, default=0.) – Background value for mask where no features exist. Default is 0.

  • out_image (Optional[str]) – Output path for (cropped) image. Required if mode=”Both”.

  • out_mask (Optional[str]) – Output path for mask. Required if mode in {“Both”,”Mask”}.

  • mode ({"Both","Mask"}, default="Both") – Write both raster + mask, or only mask.

  • all_touched (bool, default=False) – If True, burn all pixels touched by geometries (rasterize option).

  • dtype (str, default="uint8") – Output dtype for mask (e.g., “uint8”, “int16”, “float32”).

Notes

  • Uses rasterio.mask.mask for cropping (masking by polygons).

  • Uses rasterio.features.rasterize aligned to the (possibly cropped) raster grid.

terrainseg.makeChips(image: str, mask: str, n_channels: int = 1, size: int = 256, stride_x: int = 256, stride_y: int = 256, out_dir: str = '.', mode: Literal['All', 'Positive', 'Divided'] = 'All', use_existing_dir: bool = False) → None[source]

This function generates image and mask chips from an input image and associated raster mask.

The chips are written into the defined directory. The number of rows and columns of pixels in each chip are equal to the size argument. If a stride_x and/or stride_y is used that is different from the size argument, resulting chips will either overlap or have gaps between them. In order to not have overlap or gaps, the stride_x and stride_y arguments should be the same as the size argument. Both the image chips and associated masks are written to TIFF format (“.tif”). Input data are not limited to three band images. This function is specifically for a binary classification where the positive case is indicated with a cell value of 1 and the background or negative case is indicated with a cell value of 0. If an irregular shaped raster grid is provided, only chips and masks that contain no NA or NoDATA cells will be produced. Three modes are available. If “All” is used, all image chips are generated even if they do not contain pixels mapped to the positive case. Within the provided directory, image chips will be written to an “images” folder and masks will be written to a “masks” folder. If “Positive” is used, only chips that have at least 1 pixel mapped to the positive class will be produced. Background-only chips will not be generated. Within the provided directory, image chips will be written to an “images” folder and masks will be written to a “masks” folder. Lastly, if the “Divided” method is used, separate “positive” and “background” folders will be created with “images” and “masks” subfolders. Any chip that has at least 1 pixel mapped to the positive class will be written to the “positive” folder while any chip having only background pixels will be written to the “background” folder.

Parameters:
  • image (str) – Path to image file or DTM on disk.

  • mask (str) – Path to raster mask on disk. Must align with image and have the same number of rows and columns of cells, cell size, and CRS.

  • n_channels (int, default=1) – Number of input channels. Default is 1 since DTMs are single channel.

  • size (int, default=256) – Size of image chips in height and width directions. We recommend 128, 256, or 512.

  • stride_x (int, default=256) – Stride in the x or row direction when making chips. If stride_x is smaller than size, generated chips will overlap in x direction. If stride_x is larger than size, there will be gaps between chips in x direction. If stride_x is the same as size, image will be partitioned into non-overlapping chips with no gaps in x direction.

  • stride_y (int, default=256) – Stride in the y or column direction when making chips. If stride_y is smaller than size, generated chips will overlap in y direction. If stride_y is larger than size, there will be gaps between chips in the y direction. If stride_y is the same as size, image will be partitioned into non-overlapping chips with no gaps in the y direction.

  • out_dir (str) – Location at which to store chips. Must include a trailing path separator.

  • mode (Literal["All", "Positive", "Divided"], default="All") – Either “All”, “Positive”, or “Divided”. See notes.

  • use_existing_dir (bool, default=False) – Either True or False. If True, uses an existing directory that already contains chips and has an established folder structure.

terrainseg.makeChipsDF(folder: str | pathlib.Path, out_csv: str | pathlib.Path | None = None, extension: str = '.tif', mode: Literal['All', 'Positive', 'Divided'] = 'All', shuffle: bool = False, save_csv: bool = False, seed: int | None = None) → pandas.DataFrame[source]

This function creates a data frame and, optionally, a CSV file that lists all of the image chips and associated masks in a directory.

Three columns are produced. The chpN column provides the name of the chip, the chpPth column provides the path to the chip, and the chpMsk column provides the path to the associated mask. All paths are relative to the input folder as opposed to the full file path so that the results can still be used if the data are copied to a new location on disk or to a new computer.

Parameters:
  • folder (Union[str, Path]) – Folder location of chips. Must include final slash in folder path.

  • out_csv (Optional[Union[str, Path]]) – If a CSV will be saved on disk, path and name of csv file with .csv extension.

  • extension (str) – Extension used for chips and mask data. Default is “.tif”.

  • mode (Literal["All", "Positive", "Divided"], default="All") – Mode used to generate chips. Must match the setting used in makeChips. If makeChipsMulticlass was used, mode should be “All”.

  • shuffle (bool, default=False) – Whether or not to shuffle the chips.

  • save_csv (bool, Default=False) – Whether or not to save a CSV file. If True, out_csv must be defined.

  • seed (int) – Random seed to make shuffling reproducible.

Returns:

Output Pandas data frame where one row provides information for one chip.

Return type:

pd.DataFrame

terrainseg.makeChipsMulticlass(image: str, mask: str, n_channels: int = 3, size: int = 256, stride_x: int = 256, stride_y: int = 256, out_dir: str = '.', use_existing_dir: bool = False) → None[source]

Generates image and mask chips from an input image and associated raster mask.

The chips will be written into the defined directory. The number of rows and columns of pixels per chip are equal to the size argument. If a stride_x and/or stride_y is used that is different from the size argument, resulting chips will either overlap or have gaps between them. In order to not have overlap or gaps, the stride_x and stride_y arguments should be the same as the size argument. Both the image chips and associated masks are written to TIFF format (“.tif”). Input data are not limited to three band images. This function is specifically for a multiclass classification. For a binary classification or when only two classes are differentiated, use the makeChips() function. If an irregular shaped raster grid is provided, only chips and masks that contain no NA or NoDATA cells will be produced. Within the provided directory, image chips will be written to an “images” folder and masks will be written to a “masks” folder.

Parameters:
  • image (str) – Path to image file or DTM on disk.

  • mask (str) – Path to raster mask on disk. Must align with image and have the same number of rows and columns of cells, cell size, and CRS.

  • n_channels (int, default=1) – Number of input channels. Default is 1 since DTMs are single channel.

  • size (int, default=256) – Size of image chips in height and width directions. We recommend 128, 256, or 512.

  • stride_x (int, default=256) – Stride in the x or row direction when making chips. If stride_x is smaller than size, generated chips will overlap in x direction. If stride_x is larger than size, there will be gaps between chips in x direction. If stride_x is the same as size, image will be partitioned into non-overlapping chips with no gaps in x direction.

  • stride_y (int, default=256) – Stride in the y or column direction when making chips. If stride_y is smaller than size, generated chips will overlap in y direction. If stride_y is larger than size, there will be gaps between chips in the y direction. If stride_y is the same as size, image will be partitioned into non-overlapping chips with no gaps in the y direction.

  • out_dir (str) – Location at which to store chips. Must include final slash in folder path.

  • use_existing_dir (bool, default=False) – Either True or False. If True, uses an existing directory that already contains chips and has an established folder structure.

terrainseg.makeDynamicChipsGDF(center_featPth: str, center_featName: str, mask_featPth: str, mask_featName: str, extentPth: str, extentName: str, imgPth: str, imgName: str, extent_crop: float = 50.0, do_background: bool = False, background_cnt: int = 0, background_dist: float = 0.0, use_seed: bool = False, seed: int = 42, do_shuffle: bool = False) → geopandas.GeoDataFrame[source]

Generate a GeoDataFrame of dynamic chip sampling locations.

This function builds a table of chip-center locations from a point or polygon feature dataset, associates them with predictor raster grids, and links them to a separate polygon dataset used for mask generation.

Chip centers and mask polygons are explicitly separated:

  • Chip centers → define where chips are sampled

  • Mask polygons → define semantic labels rasterized into masks

If chip centers are provided as polygons, centroids are computed and used as sampling locations.

Parameters:
  • center_featPth (str) – Directory containing chip-center feature dataset (Point or Polygon).

  • center_featName (str) – Filename of chip-center feature dataset.

  • mask_featPth (str) – Directory containing polygon features used to generate raster masks.

  • mask_featName (str) – Filename of polygon feature dataset used for mask generation.

  • extentPth (str) – Directory containing study-area extent polygon dataset.

  • extentName (str) – Filename of extent polygon dataset.

  • imgPth (str) – Directory containing predictor raster grid(s).

  • imgName (str) – Filename of predictor raster grid used for chip extraction.

  • extent_crop (float, default=50.0) – Buffer distance applied to the extent geometry (map units). Positive values expand the sampling area; negative values shrink it.

  • do_background (bool, default=False) – If True, randomly generate background chip centers within the extent.

  • background_cnt (int, default=0) – Number of background chip centers to generate.

  • background_dist (float, default=0.0) – Minimum distance from the extent boundary for background points.

  • use_seed (bool, default=False) – If True, use deterministic random sampling.

  • seed (int, default=42) – Random seed used when use_seed=True.

  • do_shuffle (bool, default=False) – If True, randomly shuffle output rows before assigning chip IDs.

Returns:

GeoDataFrame containing:

  • chipID : unique integer identifier

  • geometry : Point geometries defining chip centers

  • imgPth / imgName : predictor raster metadata

  • center_featPth / center_featName : chip-center dataset metadata

  • mask_featPth / mask_featName : mask polygon dataset metadata

  • extentPth / extentName : extent dataset metadata

Return type:

geopandas.GeoDataFrame

Raises:
  • ValueError – If any dataset lacks a CRS.

  • ValueError – If chip-center geometries are not Point/MultiPoint or Polygon/MultiPolygon.

Notes

This function produces a sampling table only — raster chips and masks are generated dynamically by makeDynamicChip.

This design allows:
  • Multiple label schemas per sampling grid

  • Easy swapping of predictor rasters

  • Clean separation of sampling geometry and supervision geometry

terrainseg.checkDynamicChips(chips_gdf: geopandas.GeoDataFrame, chip_size: int = 512, cell_size: float = 1.0, nodata_ok: bool = False) → geopandas.GeoDataFrame[source]

Validate dynamically generated raster chips and append quality metrics.

For each sampling location in chips_gdf, this function generates a dynamic image chip and segmentation mask using makeDynamicChip, then inspects them for missing values, nodata pixels, and dimensional consistency. The resulting quality metrics are appended to the input GeoDataFrame and returned.

All dataset paths (predictor raster and mask polygon layers) are read directly from chips_gdf, which must be produced by makeDynamicChipsGDF.

Parameters:
  • chips_gdf (geopandas.GeoDataFrame) – Table of sampling locations produced by makeDynamicChipsGDF. Must contain imgPth, imgName, mask_featPth, and mask_featName.

  • chip_size (int, default=512) – Width and height of generated chips in pixels.

  • cell_size (float, default=1.0) – Spatial resolution of generated chips (map units per pixel).

  • nodata_ok (bool, default=False) – If False, nodata values from the source raster are counted as invalid. If True, nodata values are ignored in validation.

Returns:

Copy of chips_gdf with additional columns:

  • NoData : “Yes”/”No” flag indicating presence of nodata pixels

  • cCntImg : image width in pixels

  • rCntImg : image height in pixels

  • naCntImg : number of NaN or nodata pixels in image

  • cCntMsk : mask width in pixels

  • rCntMsk : mask height in pixels

  • naCntMsk : number of NaN pixels in mask

Return type:

geopandas.GeoDataFrame

Notes

This function does not modify chip geometry — it only evaluates the raster content generated dynamically.

class terrainseg.gaussPyramids(inChn: int, spatDims: int, device=None, dtype=torch.float32)[source]

Bases: torch.nn.Module

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will also have their parameters converted when you call to(), etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

Variables:

training (bool) – Boolean represents whether this module is in training or evaluation mode.

inChn
spatDims
forward(x: torch.Tensor) → torch.Tensor[source]

x: [N, C, H, W] (H=W should match spatDims for the mask as written) returns: [N, 5*C, H, W] (concatenation of 5 pyramid levels along channel dim)

class terrainseg.lspCalc(cellSize: float = 1.0, innerRadius: int = 2, outerRadius: int = 5, hsRadius: int = 50, smoothRadius: int = 11, doTPIHS: bool = True, device=None, dtype=torch.float32)[source]

Bases: torch.nn.Module

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will also have their parameters converted when you call to(), etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

Variables:

training (bool) – Boolean represents whether this module is in training or evaluation mode.

cellSize
innerRadius = 2
outerRadius = 5
hsRadius = 50
smoothRadius = 11
doTPIHS = True
forward(inDTM: torch.Tensor) → torch.Tensor[source]

inDTM: [N, 1, H, W] :returns: [N, 6, H, W] (tpiHS, slp, tpiL, hillshade, crvPro, crvPln)

else: [N, 5, H, W] (slp, tpiL, hillshade, crvPro, crvPln)

Return type:

if doTPIHS

class terrainseg.lspModule(cell_size: float = 1.0, spat_dim: int = 640, do_gp: bool = False, inner_radius: float = 2.0, outer_radius: float = 10.0, hs_radius: float = 50.0, smooth_radius: float = 11.0)[source]

Bases: torch.nn.Module

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will also have their parameters converted when you call to(), etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

Variables:

training (bool) – Boolean represents whether this module is in training or evaluation mode.

cell_size = 1.0
spat_dim = 640
do_gp = False
inner_radius = 2.0
outer_radius = 10.0
hs_radius = 50.0
smooth_radius = 11.0
in_channels = 6
gaussPyramid
lspOrig
lspGP
forward(x: torch.Tensor) → torch.Tensor[source]

x: torch.Tensor [B, 1, H, W] (typical) or whatever lspOrig expects.

terrainseg.terrainPredict(image_in: str, pred_out: str, model: torch.nn.Module, chip_size: int = 640, stride_x: int = 256, stride_y: int = 256, crop: int = 128, device: str = 'cuda')[source]

Use train model to make predictions over a spatial extent.

Parameters:
  • image_in (str) – Path and name of input DTM over which to make prediction. Must include the file extension.

  • pred_out (str) – Path and name of output raster grid. Must include the file extension.

  • model (nn.Module) – Instantiated model with weights loaded.

  • chip_size (int, default=640) – Size of window used to make predictions.

  • stride_x (int, default=256) – Stride in the x direction. Must be smaller than chip_size.

  • stride_y (int, default=256) – Stride in the y direction. Must be smaller than chip_size.

  • crop (int, default=128) – Number of rows and columns of cells or pixels to crop from each window. Avoids including margin cells in final predictions.

  • device (str) – Device on which to perform predictions. Default is “cuda”.

class terrainseg.terrainDataset(df: pandas.DataFrame, transform: None)[source]

Bases: torch.utils.data.Dataset

PyTorch dataset for raster-based terrain semantic segmentation.

Each sample consists of a single-band raster image and a corresponding segmentation mask read from disk using rasterio. The dataset expects a pandas DataFrame containing file paths to images and masks. Optional transforms (e.g., Albumentations) can be applied jointly to image and mask.

Parameters:
  • df (pandas.DataFrame) – Table containing file paths to input rasters and masks. The dataset expects: - column index 1 : image path - column index 2 : mask path

  • transform (callable or None, default=None) – Joint transform applied to both image and mask. Must accept transform(image=img, mask=mask) and return a dictionary with keys "image" and "mask" (e.g., Albumentations Compose).

Notes

  • Images are read as single-band rasters and returned as float tensors of shape (1, H, W).

  • Masks are converted to integer class labels using rounding and returned as torch.long tensors of shape (H, W).

  • Label value 0 is preserved and can be treated as an ignore index during loss/metric computation.

df
transform
__getitem__(idx)[source]

Load a single sample from the dataset.

Parameters:

idx (int) – Index of the sample.

Returns:

imagetorch.Tensor

Float tensor of shape (1, H, W).

masktorch.Tensor

Long tensor of shape (H, W) containing integer class labels.

Return type:

tuple[torch.Tensor, torch.Tensor]

Notes

  • Images are read using rasterio and converted to float tensors.

  • Masks are rounded to the nearest integer and cast to int64.

  • If a transform is provided, it is applied before conversion to tensors.

__len__()[source]

Return dataset size.

Returns:

Number of samples in the dataset.

Return type:

int

class terrainseg.terrainDatasetDynamic(df: geopandas.GeoDataFrame, chip_size: int, cell_size: int, background_value: int = 0, transforms=None)[source]

Bases: torch.utils.data.Dataset

PyTorch dataset that dynamically generates raster chips for terrain semantic segmentation.

Instead of reading pre-saved rasters from disk, each sample is created on-the-fly using dynamicchips.makeDynamicChip, typically from vector geometry (e.g., polygons, points, or bounding boxes stored in a GeoDataFrame). This allows stochastic sampling, jittering, and extremely large training datasets without storing image tiles on disk.

Parameters:
  • df (geopandas.GeoDataFrame) – Table describing chip locations and metadata required by dynamicchips.makeDynamicChip. Each row must contain all fields required by that function (e.g., geometry, raster paths, attributes).

  • chip_size (int) – Output chip width/height in pixels.

  • cell_size (int) – Pixel resolution used when rasterizing the chip (map units per pixel).

  • background_value (int, default=0) – Value assigned to pixels outside valid data regions. Typically used as an ignore label in loss functions.

  • transforms (callable or None, default=None) – Joint transform applied to both image and mask. Must accept transform(image=img, mask=mask) and return a dictionary with keys "image" and "mask" (e.g., Albumentations Compose).

Notes

  • Chips are generated dynamically at each access; repeated epochs may yield slightly different samples if the chip generator is stochastic.

  • Masks are rounded and converted to integer labels.

  • Label value 0 is preserved and can be treated as an ignore index.

  • Returned image tensor has shape (1, H, W) and dtype float32.

df
chip_size
cell_size
background_value = 0
transforms = None
__getitem__(i)[source]

Generate and return a single training sample.

Parameters:

i (int) – Index of the sample.

Returns:

imagetorch.Tensor

Float tensor of shape (1, H, W).

masktorch.Tensor

Long tensor of shape (H, W) containing integer class labels.

Return type:

tuple[torch.Tensor, torch.Tensor]

Notes

  • Chips are created using dynamicchips.makeDynamicChip.

  • Mask values are rounded to integers.

  • If transforms are provided, they are applied before tensor conversion.

__len__()[source]

Return dataset size.

Returns:

Number of sampling locations available.

Return type:

int

class terrainseg.unifiedFocalLoss(nCls: int = 3, lambda_: float = 0.5, gamma: float = 0.5, delta: float = 0.6, smooth: float = 1e-08, zeroStart: bool = True, clsWghtsDist: float = 1.0, clsWghtsReg: float = 1.0, useLogCosH: bool = False, device: str = 'cuda')[source]

Bases: torch.nn.Module

Base class for all neural network modules.

Your models should also subclass this class.

Modules can also contain other Modules, allowing them to be nested in a tree structure. You can assign the submodules as regular attributes:

import torch.nn as nn
import torch.nn.functional as F


class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

Submodules assigned in this way will be registered, and will also have their parameters converted when you call to(), etc.

Note

As per the example above, an __init__() call to the parent class must be made before assignment on the child.

Variables:

training (bool) – Boolean represents whether this module is in training or evaluation mode.

nCls = 3
lambda_
gamma
delta = 0.6
smooth
zeroStart = True
useLogCosH = False
device = 'cuda'
forward(pred: torch.Tensor, target: torch.Tensor) → torch.Tensor[source]

pred: [B,C,H,W] logits target: [B,1,H,W] or [B,H,W] integer labels