Skip to content

samstars.features.cost_surface

samstars.features.cost_surface

CostSurfaceWeights dataclass

Source code in samstars/features/cost_surface.py
87
88
89
90
91
92
93
94
95
96
97
98
@dataclass
class CostSurfaceWeights:
    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."""
        s = self.grad + self.gap + self.tex + self.slic
        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
94
95
96
97
98
def __post_init__(self):
    """Validate and normalize configuration after initialization."""
    s = self.grad + self.gap + self.tex + self.slic
    if abs(s - 1) > 1e-6:
        raise ValueError("Weights must sum to 1 (got {:.3f})".format(s))

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

Build cost surface.

Source code in samstars/features/cost_surface.py
101
102
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
141
142
143
144
145
146
147
148
149
150
151
def build_cost_surface(
    *,
    wv3_path: str | Path,
    chm_path: str | Path,
    slic_path: str | Path | None = None,
    weights: tuple[float, float, float, float] = (0.4, 0.3, 0.3, 0),
    nodata_value: float = -9999.0,
):
    """Build cost surface."""
    w = CostSurfaceWeights(*weights)

    with rasterio.open(wv3_path) as src:
        C, B, G, Y, R, RE, N1, N2 = src.read(masked=True).astype(np.float32)
        profile = src.profile.copy()
        profile["bounds"] = rasterio.transform.array_bounds(
            profile["height"], profile["width"], profile["transform"]
        )

    chm, _ = _read_band(chm_path)

    grad = _chm_gradient(chm)
    gap  = _normalise(1 - _ndvi(R, N1))
    tex  = _texture_entropy(C)

    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)
        w_slic = w.slic
    else:
        edge = 0.0
        s = w.grad + w.gap + w.tex
        w.grad, w.gap, w.tex = (w.grad / s, w.gap / s, w.tex / s)
        w_slic = 0.0
        warnings.warn("No SLIC provided – cost built from 3 terms only.")

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

    cost[np.isnan(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 cost surface.

Source code in samstars/features/cost_surface.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def write_cost_surface(
    cost: np.ndarray,
    profile: dict,
    out_path: str | Path,
    *,
    exist_ok: bool = True,
):
    """Write cost surface."""
    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