Skip to content

samstars.features.cost_surface

samstars.features.cost_surface

CostSurfaceWeights dataclass

Weights for height edges, NDVI gaps, image texture, and experimental SLIC edges.

Weights must be nonnegative and sum to one. Terms without a supplied NIR band or SLIC layer are omitted and the remaining weights are rescaled.

Source code in samstars/features/cost_surface.py
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
@dataclass
class CostSurfaceWeights:
    """Weights for height edges, NDVI gaps, image texture, and experimental SLIC edges.

    Weights must be nonnegative and sum to one. Terms without a supplied
    NIR band or SLIC layer are omitted and the remaining weights are rescaled.
    """
    grad: float = 0.4
    gap: float = 0.3
    tex: float = 0.3
    slic: float = 0

    def __post_init__(self):
        """Validate and normalize configuration after initialization."""
        values = (self.grad, self.gap, self.tex, self.slic)
        if any(not np.isfinite(v) or v < 0 for v in values):
            raise ValueError("Weights must be finite and nonnegative.")
        s = sum(values)
        if abs(s - 1) > 1e-6:
            raise ValueError("Weights must sum to 1 (got {:.3f})".format(s))

__post_init__()

Validate and normalize configuration after initialization.

Source code in samstars/features/cost_surface.py
123
124
125
126
127
128
129
130
def __post_init__(self):
    """Validate and normalize configuration after initialization."""
    values = (self.grad, self.gap, self.tex, self.slic)
    if any(not np.isfinite(v) or v < 0 for v in values):
        raise ValueError("Weights must be finite and nonnegative.")
    s = sum(values)
    if abs(s - 1) > 1e-6:
        raise ValueError("Weights must sum to 1 (got {:.3f})".format(s))

build_cost_surface(*, img_path=None, chm_path, rgb_bands=None, nir_band=None, texture_band=None, wv3_path=None, slic_path=None, weights=(0.4, 0.3, 0.3, 0), nodata_value=-9999.0)

Build a 0–1 crown-boundary cost raster from aligned imagery and canopy height.

Parameters:

Name Type Description Default
img_path str | Path | None

Three-band RGB or multiband imagery raster.

None
chm_path str | Path

Single-band canopy heights in meters, on the imagery grid.

required
rgb_bands tuple[int, int, int] | None

One-based red, green, blue indices. Defaults to (1, 2, 3).

None
nir_band int | None

Optional near-infrared band for the NDVI gap term. With no NIR band, the cost uses height edges and image texture only.

None
texture_band int | None

Optional image band for texture. Defaults to the mean of the selected RGB channels.

None
wv3_path str | Path | None

Legacy alias for img_path; band choices are still explicit.

None
slic_path str | Path | None

Experimental SLIC labels on the imagery grid.

None
weights tuple[float, float, float, float]

Height-edge, NDVI-gap, texture, and SLIC weights. Unavailable terms are omitted and the remaining weights are rescaled to sum to one.

(0.4, 0.3, 0.3, 0)
nodata_value float

Output value at pixels with missing input data.

-9999.0

Returns:

Name Type Description
cost ndarray

Float32 array of boundary costs. Higher values indicate stronger cues.

profile dict

Rasterio profile for the single-band output.

Source code in samstars/features/cost_surface.py
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
def build_cost_surface(
    *,
    img_path: str | Path | None = None,
    chm_path: str | Path,
    rgb_bands: tuple[int, int, int] | None = None,
    nir_band: int | None = None,
    texture_band: int | None = None,
    wv3_path: str | Path | None = None,
    slic_path: str | Path | None = None,
    weights: tuple[float, float, float, float] = (0.4, 0.3, 0.3, 0),
    nodata_value: float = -9999.0,
) -> tuple[np.ndarray, dict]:
    """Build a 0–1 crown-boundary cost raster from aligned imagery and canopy height.

    Args:
        img_path: Three-band RGB or multiband imagery raster.
        chm_path: Single-band canopy heights in meters, on the imagery grid.
        rgb_bands: One-based red, green, blue indices. Defaults to `(1, 2, 3)`.
        nir_band: Optional near-infrared band for the NDVI gap term. With no NIR
            band, the cost uses height edges and image texture only.
        texture_band: Optional image band for texture. Defaults to the mean of
            the selected RGB channels.
        wv3_path: Legacy alias for `img_path`; band choices are still explicit.
        slic_path: Experimental SLIC labels on the imagery grid.
        weights: Height-edge, NDVI-gap, texture, and SLIC weights. Unavailable
            terms are omitted and the remaining weights are rescaled to sum to one.
        nodata_value: Output value at pixels with missing input data.

    Returns:
        cost: Float32 array of boundary costs. Higher values indicate stronger cues.
        profile: Rasterio profile for the single-band output.
    """
    if (img_path is None) == (wv3_path is None):
        raise ValueError("Provide img_path (or its legacy alias wv3_path), but not both.")
    w = CostSurfaceWeights(*weights)

    with rasterio.open(img_path if img_path is not None else wv3_path) as src:
        rgb_bands = _resolve_image_bands(src.count, rgb_bands, nir_band, texture_band)
        rgb = src.read(rgb_bands, masked=True).astype(np.float32).filled(np.nan)
        texture = rgb.mean(axis=0) if texture_band is None else src.read(
            texture_band, masked=True
        ).astype(np.float32).filled(np.nan)
        nir = None if nir_band is None else src.read(
            nir_band, masked=True
        ).astype(np.float32).filled(np.nan)
        profile = src.profile.copy()
        profile["bounds"] = rasterio.transform.array_bounds(
            profile["height"], profile["width"], profile["transform"]
        )

    chm, chm_profile = _read_band(chm_path)
    if (chm.shape != rgb.shape[1:] or chm_profile["crs"] != profile["crs"]
            or chm_profile["transform"] != profile["transform"]):
        raise ValueError("Imagery and CHM must have the same CRS, transform, and shape.")

    grad = _chm_gradient(chm)
    gap = 0.0 if nir is None else _normalise(1 - _ndvi(rgb[0], nir))
    tex = _texture_entropy(texture)
    valid = np.isfinite(chm) & np.isfinite(rgb).all(axis=0) & np.isfinite(texture)
    if nir is not None:
        valid &= np.isfinite(nir)

    if slic_path:
        if str(slic_path).lower().endswith(".gpkg"):
            slic_lab = _rasterise_slic_gpkg(slic_path, profile)
        else:                                  # assume raster label image
            slic_lab, _ = _read_band(slic_path)
        edge = _slic_edge(slic_lab)
    else:
        edge = 0.0

    w_gap = w.gap if nir is not None else 0.0
    w_slic = w.slic if slic_path is not None else 0.0
    total_weight = w.grad + w_gap + w.tex + w_slic
    if total_weight <= 0:
        raise ValueError("At least one available cost term must have a positive weight.")

    cost = (
        w.grad * grad +
        w_gap  * gap  +
        w.tex  * tex  +
        w_slic * edge
    ) / total_weight
    cost = np.clip(cost, 0, 1).astype(np.float32)

    cost[~valid | ~np.isfinite(cost)] = nodata_value
    profile.update(count=1, dtype="float32",
                   compress="deflate",
                   nodata=nodata_value)
    return cost, profile

write_cost_surface(cost, profile, out_path, *, exist_ok=True)

Write a cost array and Rasterio profile to a single-band GeoTIFF.

The parent directory is created when needed. Set exist_ok=False to reject an existing output file. Returns the output path.

Source code in samstars/features/cost_surface.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def write_cost_surface(
    cost: np.ndarray,
    profile: dict,
    out_path: str | Path,
    *,
    exist_ok: bool = True,
) -> Path:
    """Write a cost array and Rasterio profile to a single-band GeoTIFF.

    The parent directory is created when needed. Set `exist_ok=False` to
    reject an existing output file. Returns the output path.
    """
    out_path = Path(out_path)
    if not exist_ok and out_path.exists():
        raise FileExistsError(out_path)
    out_path.parent.mkdir(parents=True, exist_ok=True)
    with rasterio.open(out_path, "w", **profile) as dst:
        dst.write(cost, 1)
    return out_path