Debian Codegraph @

polsarpro/classification.py

raw
1 """
2 This code is part of the Python PolSARpro software:
3
4 "A re-implementation of selected PolSARPro functions in Python,
5 following the scientific recommendations of PolInSAR 2021"
6
7 developed within an ESA funded project with SATIM.
8
9 Author: Olivier D'Hondt, 2026.
10 Scientific advisors: Armando Marino and Eric Pottier.
11
12 Licensed under the Apache License, Version 2.0 (the "License");
13 you may not use this file except in compliance with the License.
14 You may obtain a copy of the License at
15
16 http://www.apache.org/licenses/LICENSE-2.0
17
18 Unless required by applicable law or agreed to in writing, software
19 distributed under the License is distributed on an "AS IS" BASIS,
20 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 See the License for the specific language governing permissions and
22 limitations under the License.
23
24 -----
25
26 # Description: module containing polarimetric classification functions
27
28 """
29
30 from __future__ import annotations
31
32 from typing import Optional
33
34 import dask.array as da
35 import numpy as np
36 import xarray as xr
37 from scipy.ndimage import label
38
39 from polsarpro.auxil import validate_dataset
40 from polsarpro.decompositions import h_a_alpha
41 from polsarpro.util import C3_to_T3, C4_to_T4, S_to_T3, boxcar
42
43
44 def wishart_h_a_alpha(
45 input_data: xr.Dataset,
46 boxcar_size: list[int] = [5, 5],
47 h_a_alpha_result: Optional[xr.Dataset] = None,
48 max_iter: int = 10,
49 tol_pct: float = None,
50 verbose: bool = True,
51 ) -> xr.Dataset:
52 """
53 Performs the Wishart H/A/Alpha classification on polarimetric SAR data.
54
55 This function implements an iterative unsupervised classification scheme based on
56 the H/A/Alpha decomposition and the Wishart distance measure. The algorithm:
57 1. Computes initial H/A/Alpha decomposition parameters
58 2. Performs initial classification using the H-Alpha decision boundaries
59 3. Iteratively refines the classification using Wishart distance to 8 class centers
60 4. Split the 8 classes into 16 based on a 0.5 threshold on anisotropy
61 5. Apply Wishart iterations on these classes
62
63 Args:
64 input_data (xr.Dataset): Input polarimetric SAR dataset. Supported types are:
65
66 - "S": Sinclair scattering matrix
67
68 - "C3": Lexicographic covariance matrix (3x3)
69
70 - "T3": Pauli coherency matrix (3x3)
71
72 - "C4": 4x4 covariance matrix
73
74 - "T4": 4x4 coherency matrix
75
76 boxcar_size (list[int, int], optional): Size of the spatial averaging window
77 (boxcar filter) applied before decomposition. Defaults to [5, 5].
78 h_a_alpha_result (xr.Dataset, optional): Pre-computed H/A/Alpha decomposition
79 results. If provided, the function will use these results for the initial
80 H-Alpha classification instead of computing them from input_data.
81 The dataset must contain at least 'entropy' and 'alpha' variables.
82 If None (default),
83 the H/A/Alpha decomposition is computed from input_data.
84 max_iter (int, optional): Maximum number of iterations for the classification
85 refinement loop. Must be a positive integer. Defaults to 10.
86 tol_pct (float or None, optional): Threshold for early stopping based on the
87 percentage of pixels changing class between iterations. This parameter
88 is kept only for compatibility with the C version (see notes below).
89 When the percentage of pixels that switch class is less than this
90 value, the algorithm stops.
91 If set, must be in the range [0.0, 100.0]. Defaults to None.
92 verbose (bool, optional): If True, print progress messages during the eager
93 tol_pct path. Defaults to True.
94
95 Returns:
96 xr.Dataset: Dataset containing the 8 and 18 class maps.
97 Pixels where any input polarimetric element is NaN are excluded from
98 class-center estimation and iterative class assignment, and are encoded
99 as class ``0`` in the output maps.
100
101 References:
102 Cloude, S. R., & Pottier, E. (1997). An entropy based classification
103 scheme for land applications of polarimetric SAR. *IEEE Transactions on
104 Geoscience and Remote Sensing*,
105 35(1), 68-78.
106
107 Notes:
108 It is recommended to leave the tol_pct parameter to its default None
109 state to take advantage of Dask lazy processing. Setting this parameter
110 to a value might result in a performance loss. It has been observed
111 that without early termination the python implementation is faster than
112 the legacy version.
113
114 For large products, calling this function without h_a_alpha_result
115 can still require substantial memory when the lazy result is eventually
116 computed or written to disk, because the H/A/Alpha decomposition is part
117 of the same Dask pipeline. If memory is limited, compute the H/A/Alpha
118 decomposition separately, write it to a file, reopen it with xarray,
119 and pass it through h_a_alpha_result.
120
121 """
122 # Validate max_iter parameter
123 if not isinstance(max_iter, int):
124 raise TypeError(f"max_iter must be an integer, got {type(max_iter).__name__}.")
125 if max_iter <= 0:
126 raise ValueError(f"max_iter must be a positive integer, got {max_iter}.")
127
128 # Validate stop_threshold parameter
129 if not isinstance(tol_pct, (int, float)) and tol_pct is not None:
130 raise TypeError(
131 f"tol_pct must be a number or None, got {type(tol_pct).__name__}."
132 )
133 if tol_pct is not None and (tol_pct < 0.0 or tol_pct > 100.0):
134 raise ValueError(f"tol_pct must be in the range [0.0, 100.0], got {tol_pct}.")
135 poltype = validate_dataset(
136 input_data, allowed_poltypes=("C3", "T3", "C4", "T4", "S")
137 )
138
139 # Handle optional pre-computed h_a_alpha result
140 if h_a_alpha_result is not None:
141 # Validate h_a_alpha_result
142 if not isinstance(h_a_alpha_result, xr.Dataset):
143 raise TypeError("h_a_alpha_result must be an xarray.Dataset.")
144 if h_a_alpha_result.attrs.get("poltype") != "h_a_alpha":
145 raise ValueError("h_a_alpha_result must have poltype='h_a_alpha'.")
146 required_vars = {"entropy", "alpha"}
147 if not required_vars.issubset(set(h_a_alpha_result.data_vars)):
148 raise ValueError(
149 f"h_a_alpha_result must contain variables: {required_vars}"
150 )
151 ds_ha = h_a_alpha_result
152 else:
153 # Compute H/A/Alpha decomposition from input_data
154 ds_ha = None
155
156 # Convert input to T3/T4 format for Wishart distance computation
157 if poltype == "S":
158 in_ = S_to_T3(input_data)
159 elif poltype == "C3":
160 in_ = C3_to_T3(input_data)
161 elif poltype == "T3":
162 in_ = input_data
163 elif poltype == "C4":
164 in_ = C4_to_T4(input_data)
165 elif poltype == "T4":
166 in_ = input_data
167
168 # Track invalid pixels and replace NaNs for numerical stability.
169 eps = 1e-30
170 valid_mask = (~in_.to_array().isnull().any("variable")).data
171 in_ = in_.fillna(eps)
172
173 # Apply boxcar filtering to the coherency matrix
174 in_ = boxcar(in_, dim_az=boxcar_size[0], dim_rg=boxcar_size[1])
175
176 # Compute H/A/Alpha decomposition if not provided
177 if ds_ha is None:
178 ds_ha = h_a_alpha(
179 input_data=in_,
180 boxcar_size=[1, 1], # Already filtered
181 flags=("entropy", "anisotropy", "alpha"),
182 )
183
184 # Initial classification using H-Alpha decision boundaries
185 class_map_init = da.where(valid_mask, _h_alpha_classifier(ds_ha), 0).astype("uint8")
186
187 # Iterative Wishart classification
188 nclass = 8
189 if tol_pct is None:
190 # Lazy pipeline: list the planned stages up front.
191 if verbose:
192 print("Starting Wishart H/A/Alpha operations")
193 if h_a_alpha_result is None:
194 print("- H/A/Alpha decomposition")
195 print("- H/Alpha initial classes")
196 print("- Wishart H/Alpha clustering (8 classes)")
197 print("- Wishart H/A/Alpha clustering (16 classes)")
198 class_map, percent_changed = _wishart_classifier_without_early_stop(
199 in_, class_map_init, nclass, max_iter, valid_mask=valid_mask
200 )
201 else:
202 # Eager pipeline: print progress as each stage runs.
203 if verbose:
204 first_stage_message = (
205 "Starting H/A/Alpha decomposition & Wishart H/Alpha clustering (8 classes)"
206 if h_a_alpha_result is None
207 else "Starting Wishart H/Alpha clustering (8 classes)"
208 )
209 print(first_stage_message)
210 class_map, percent_changed = _wishart_classifier_with_early_stop(
211 in_,
212 class_map_init,
213 nclass,
214 max_iter,
215 tol_pct,
216 valid_mask=valid_mask,
217 verbose=verbose,
218 )
219
220 # Divide classes according to anisotropy
221 class_map_init_16 = da.where(
222 valid_mask,
223 da.where(ds_ha.anisotropy.data <= 0.5, class_map, class_map + 8),
224 0,
225 ).astype("uint8")
226
227 nclass = 16
228 if tol_pct is None:
229 # Lazy pipeline: the stage list was already printed above.
230 class_map_16, percent_changed_16 = _wishart_classifier_without_early_stop(
231 in_, class_map_init_16, nclass, max_iter, valid_mask=valid_mask
232 )
233 else:
234 # Eager pipeline: print progress as each stage runs.
235 if verbose:
236 print("Starting Wishart H/A/Alpha clustering (16 classes)")
237 class_map_16, percent_changed_16 = _wishart_classifier_with_early_stop(
238 in_,
239 class_map_init_16,
240 nclass,
241 max_iter,
242 tol_pct,
243 valid_mask=valid_mask,
244 verbose=verbose,
245 )
246
247 # Build output dataset
248 result = xr.Dataset(
249 {
250 "wishart_h_alpha_class": (in_.dims, class_map.astype("uint8")),
251 "wishart_h_alpha_percent_change": percent_changed,
252 "wishart_h_a_alpha_class": (in_.dims, class_map_16.astype("uint8")),
253 "wishart_h_a_alpha_percent_change": percent_changed_16,
254 },
255 coords=in_.coords,
256 attrs=dict(
257 poltype="wishart_h_a_alpha",
258 description="Wishart H/A/Alpha classification result",
259 ),
260 )
261
262 return result
263
264
265 def wishart_supervised(
266 input_data: xr.Dataset,
267 training_labels: xr.DataArray,
268 boxcar_size: list[int] = [5, 5],
269 ) -> xr.Dataset:
270 """
271 Performs Wishart supervised classification based on user inputs.
272 Args:
273 input_data (xr.Dataset): Input polarimetric SAR dataset. Supported types are:
274 - "S": Sinclair scattering matrix
275 - "C3": Lexicographic covariance matrix (3x3)
276 - "T3": Pauli coherency matrix (3x3)
277 - "C4": 4x4 covariance matrix
278 - "T4": 4x4 coherency matrix
279 training_labels: (xr.DataArray): 2D array of the same spatial dimensions
280 as input_data, containing integer class labels for training pixels.
281 Each connected region for a class is used as a separate training
282 cluster. Pixels with label 0 are considered unlabeled and are not
283 used in training.
284 boxcar_size (list[int, int], optional): Size of the spatial averaging window
285 (boxcar filter) applied before decomposition. Defaults to [5, 5].
286
287 Returns:
288 xr.Dataset: Dataset containing the output classes.
289 Pixels where any input polarimetric element is NaN are excluded from
290 training and class assignment, and are encoded as class ``0`` in the
291 output map.
292 """
293
294 poltype = validate_dataset(
295 input_data, allowed_poltypes=("C3", "T3", "C4", "T4", "S")
296 )
297
298 if {"y", "x"}.issubset(input_data.dims):
299 dims = ("y", "x")
300 elif {"lat", "lon"}.issubset(input_data.dims):
301 dims = ("lat", "lon")
302
303 # Convert input to T3/T4 format for Wishart distance computation
304 if poltype == "S":
305 in_ = S_to_T3(input_data)
306 elif poltype == "C3":
307 in_ = C3_to_T3(input_data)
308 elif poltype == "T3":
309 in_ = input_data
310 elif poltype == "C4":
311 in_ = C4_to_T4(input_data)
312 elif poltype == "T4":
313 in_ = input_data
314
315 if training_labels.ndim != 2:
316 raise ValueError("training_labels must be a 2D DataArray.")
317 if training_labels.shape != (input_data.sizes[dims[0]], input_data.sizes[dims[1]]):
318 raise ValueError(
319 "training_labels must have the same spatial shape as input_data."
320 )
321
322 # Exclude invalid raster pixels (NaN in any matrix element).
323 eps = 1e-30
324 valid_mask = (~in_.to_array().isnull().any("variable")).data
325 in_ = in_.fillna(eps)
326
327 training_labels_data = training_labels.data
328 if isinstance(training_labels_data, da.Array):
329 training_labels_data = training_labels_data.compute()
330 training_labels_data = np.asarray(training_labels_data)
331 if isinstance(valid_mask, da.Array):
332 valid_mask_np = np.asarray(valid_mask.compute())
333 else:
334 valid_mask_np = np.asarray(valid_mask)
335 training_labels_data = training_labels_data.copy()
336 training_labels_data[~valid_mask_np] = 0
337
338 lab, cluster_classes = _label_training_clusters(training_labels_data)
339 nclass = len(cluster_classes) - 1
340
341 # Apply boxcar filtering to the coherency matrix
342 in_ = boxcar(in_, dim_az=boxcar_size[0], dim_rg=boxcar_size[1])
343
344 centers = _update_wishart_class_centers(
345 in_, lab, nclass=nclass, valid_mask=valid_mask
346 )
347 cluster_map = _update_wishart_class_map(
348 in_=in_, M_center=centers, valid_mask=valid_mask
349 )
350
351 # Remap training clusters back to their semantic class labels
352 class_map = cluster_map.map_blocks(
353 lambda block: cluster_classes[block],
354 dtype=cluster_classes.dtype,
355 )
356
357 # Build output dataset
358 result = xr.Dataset(
359 {
360 "wishart_supervised_class": (in_.dims, class_map.astype("uint8")),
361 },
362 coords=in_.coords,
363 attrs=dict(
364 poltype="wishart_supervised",
365 description="Wishart supervised classification result",
366 ),
367 )
368
369 return result
370
371
372 def _label_training_clusters(
373 training_labels: np.ndarray,
374 ) -> tuple[np.ndarray, np.ndarray]:
375 """Label connected training regions and keep their semantic class labels."""
376 if not np.issubdtype(training_labels.dtype, np.integer):
377 raise TypeError("training_labels must contain integer class labels.")
378 if np.any(training_labels < 0):
379 raise ValueError("training_labels must contain non-negative class labels.")
380
381 lab = np.zeros(training_labels.shape, dtype=np.int32)
382 cluster_classes = [0]
383 cluster_id = 0
384
385 for class_value in np.unique(training_labels):
386 if class_value == 0:
387 continue
388
389 # labeled connected regions for current class
390 class_regions, nregions = label(training_labels == class_value)
391 if nregions == 0:
392 continue
393
394 # update cluster -> class mapping list
395 region_mask = class_regions > 0
396 lab[region_mask] = class_regions[region_mask] + cluster_id
397 cluster_classes.extend([class_value] * nregions)
398 cluster_id += nregions
399
400 if cluster_id == 0:
401 raise ValueError("training_labels must contain at least one labeled pixel.")
402
403 return lab, np.asarray(cluster_classes, dtype=training_labels.dtype)
404
405
406 def _reconstruct_matrix_from_ds(ds):
407
408 eps = 1e-30
409
410 new_dims_array = ("c", "i", "j")
411
412 if ds.poltype in ["T3", "C3"]:
413 # build each line of the T3 matrix
414 M3_l1 = xr.concat((ds.m11, ds.m12, ds.m13), dim="j")
415 M3_l2 = xr.concat((ds.m12.conj(), ds.m22, ds.m23), dim="j")
416 M3_l3 = xr.concat((ds.m13.conj(), ds.m23.conj(), ds.m33), dim="j")
417
418 # Concatenate all lines into a 3x3 matrix
419 return (
420 xr.concat((M3_l1, M3_l2, M3_l3), dim="i")
421 .transpose(*new_dims_array)
422 .chunk({"i": 3, "j": 3})
423 + eps
424 )
425 elif ds.poltype in ["T4", "C4"]:
426 # build each line of the T4 matrix
427 M4_l1 = xr.concat((ds.m11, ds.m12, ds.m13, ds.m14), dim="j")
428 M4_l2 = xr.concat((ds.m12.conj(), ds.m22, ds.m23, ds.m24), dim="j")
429 M4_l3 = xr.concat((ds.m13.conj(), ds.m23.conj(), ds.m33, ds.m34), dim="j")
430 M4_l4 = xr.concat(
431 (ds.m14.conj(), ds.m24.conj(), ds.m34.conj(), ds.m44), dim="j"
432 )
433
434 # concatenate all lines into a 4x4 matrix
435 return (
436 xr.concat((M4_l1, M4_l2, M4_l3, M4_l4), dim="i")
437 .transpose(*new_dims_array)
438 .chunk({"i": 4, "j": 4})
439 + eps
440 )
441 else:
442 raise NotImplementedError(
443 "Implemented only for C2, C3, T3 and C4 and T4 poltypes."
444 )
445
446
447 def _trace_product_3(M_inv: da.Array, cov_ds: xr.Dataset) -> da.Array:
448 """
449 Compute Tr(M_inv @ C3) for 3x3 covariance/coherency matrices.
450
451 Uses direct element-wise computation for efficiency:
452 Tr(M_inv @ C3) = sum_ij M_inv[i,j] * C3[j,i]
453
454 Args:
455 M_inv: Inverse matrix array of shape (3, 3)
456 cov_ds: Dataset containing covariance/coherency matrix elements
457 (m11, m12, m22, m13, m23, m33)
458
459 Returns:
460 Trace of the product, same shape as cov_ds variables
461 """
462 m11 = cov_ds.m11.data
463 m12 = cov_ds.m12.data
464 m22 = cov_ds.m22.data
465 m13 = cov_ds.m13.data
466 m23 = cov_ds.m23.data
467 m33 = cov_ds.m33.data
468
469 M_inv_broad = M_inv[None, None]
470 trace = (
471 M_inv_broad[..., 0, 0] * m11[..., None]
472 + M_inv_broad[..., 0, 1] * da.conj(m12)[..., None]
473 + M_inv_broad[..., 0, 2] * da.conj(m13)[..., None]
474 + M_inv_broad[..., 1, 0] * m12[..., None]
475 + M_inv_broad[..., 1, 1] * m22[..., None]
476 + M_inv_broad[..., 1, 2] * da.conj(m23)[..., None]
477 + M_inv_broad[..., 2, 0] * m13[..., None]
478 + M_inv_broad[..., 2, 1] * m23[..., None]
479 + M_inv_broad[..., 2, 2] * m33[..., None]
480 )
481
482 return da.real(trace)
483
484
485 def _trace_product_4(M_inv: da.Array, cov_ds: xr.Dataset) -> da.Array:
486 """
487 Compute Tr(M_inv @ C4) for 4x4 covariance/coherency matrices.
488
489 Uses direct element-wise computation for efficiency:
490 Tr(M_inv @ C4) = sum_ij M_inv[i,j] * C4[j,i]
491
492 Args:
493 M_inv: Inverse matrix array of shape (4, 4)
494 cov_ds: Dataset containing covariance/coherency matrix elements
495 (m11, m12, m22, m13, m23, m33, m14, m24, m34, m44)
496
497 Returns:
498 Trace of the product, same shape as cov_ds variables
499 """
500 m11 = cov_ds.m11.data
501 m12 = cov_ds.m12.data
502 m22 = cov_ds.m22.data
503 m13 = cov_ds.m13.data
504 m23 = cov_ds.m23.data
505 m33 = cov_ds.m33.data
506 m14 = cov_ds.m14.data
507 m24 = cov_ds.m24.data
508 m34 = cov_ds.m34.data
509 m44 = cov_ds.m44.data
510 M_inv_broad = M_inv[None, None]
511 trace = (
512 M_inv_broad[..., 0, 0] * m11[..., None]
513 + M_inv_broad[..., 0, 1] * da.conj(m12)[..., None]
514 + M_inv_broad[..., 0, 2] * da.conj(m13)[..., None]
515 + M_inv_broad[..., 0, 3] * da.conj(m14)[..., None]
516 + M_inv_broad[..., 1, 0] * m12[..., None]
517 + M_inv_broad[..., 1, 1] * m22[..., None]
518 + M_inv_broad[..., 1, 2] * da.conj(m23)[..., None]
519 + M_inv_broad[..., 1, 3] * da.conj(m24)[..., None]
520 + M_inv_broad[..., 2, 0] * m13[..., None]
521 + M_inv_broad[..., 2, 1] * m23[..., None]
522 + M_inv_broad[..., 2, 2] * m33[..., None]
523 + M_inv_broad[..., 2, 3] * da.conj(m34)[..., None]
524 + M_inv_broad[..., 3, 0] * m14[..., None]
525 + M_inv_broad[..., 3, 1] * m24[..., None]
526 + M_inv_broad[..., 3, 2] * m34[..., None]
527 + M_inv_broad[..., 3, 3] * m44[..., None]
528 )
529
530 return da.real(trace)
531
532
533 def _h_alpha_classifier(ds_ha: xr.Dataset) -> da.Array:
534 """
535 Classify pixels based on H-Alpha decomposition using decision boundaries.
536
537 Parameters
538 ----------
539 ds_ha : xarray.Dataset
540 Dataset containing 'entropy' and 'alpha' variables.
541
542 Returns
543 -------
544 dask.array.Array
545 Classification map with integer class labels (1-9).
546 """
547 alpha = ds_ha.alpha.data
548 H = ds_ha.entropy.data
549
550 # Decision boundaries
551 thresh_al1 = 55.0
552 thresh_al2 = 50.0
553 thresh_al3 = 48.0
554 thresh_al4 = 42.0
555 thresh_al5 = 40.0
556 thresh_H1 = 0.9
557 thresh_H2 = 0.5
558
559 # Apply thresholds
560 # In Python/dask: True=1, False=0, so we use direct boolean operations
561 a1 = alpha <= thresh_al1
562 a2 = alpha <= thresh_al2
563 a3 = alpha <= thresh_al3
564 a4 = alpha <= thresh_al4
565 a5 = alpha <= thresh_al5
566
567 h1 = H <= thresh_H1
568 h2 = H <= thresh_H2
569
570 # 2-D regions
571 # In Python/dask: ~ for NOT, & for AND, | for OR
572 r1 = (~a3) & h2
573 r2 = a3 & (~a4) & h2
574 r3 = a4 & h2
575 r4 = (~a2) & h1 & (~h2)
576 r5 = a2 & (~a5) & h1 & (~h2)
577 r6 = a5 & h1 & (~h2)
578 r7 = (~a1) & (~h1)
579 r8 = a1 & (~a5) & (~h1)
580 r9 = a5 & (~h1) # Non feasible region
581
582 # Compute class labels (1-9)
583 # Each region contributes its class number where the region is True
584 class_map = (
585 1 * r1 + 2 * r2 + 3 * r3 + 4 * r4 + 5 * r5 + 6 * r6 + 7 * r7 + 8 * r8 + 9 * r9
586 )
587
588 return class_map.astype("uint8")
589
590
591 def _update_wishart_class_centers(input_data, class_map, nclass, valid_mask=None):
592
593 if {"y", "x"}.issubset(input_data.dims):
594 dims = ("y", "x")
595 elif {"lat", "lon"}.issubset(input_data.dims):
596 dims = ("lat", "lon")
597
598 # Compute class center -- broadcast arrays to avoid looping
599 mask = class_map[..., None] == da.arange(1, nclass + 1)[None, None]
600 if valid_mask is not None:
601 mask = mask & valid_mask[..., None]
602 npts = mask.sum((0, 1))
603 # Some classes can be temporarily empty: guard denominator to avoid 0/0.
604 npts_safe = da.maximum(npts, 1)
605
606 # Matrix dims
607 if input_data.poltype in ("C3", "T3"):
608 n = 3
609 elif input_data.poltype in ("C4", "T4"):
610 n = 4
611 else:
612 raise NotImplemented(f"Function is only implemented for 3x3 and 4x4 matrices.")
613
614 # Class centers
615 center = (mask * input_data.expand_dims(dim="c", axis=2)).sum(
616 (dims[0], dims[1]), keep_attrs=True
617 ) / npts_safe
618
619 # Reconstruct matrix and regularize
620 M_center = _reconstruct_matrix_from_ds(center) + 1e-30 * da.eye(n)
621
622 # otherwise M_center type is complex128
623 return M_center.astype("complex64")
624
625
626 def _update_wishart_class_map(in_, M_center, valid_mask=None):
627
628 # Compute inverse and determinant
629 meta = (np.array([], dtype="complex64").reshape((0, 0, 0)),)
630 M_inv = da.apply_gufunc(np.linalg.inv, "(i,j)->(i,j)", M_center.data, meta=meta)
631 M_det = da.apply_gufunc(np.linalg.det, "(i,j)->()", M_center.data, meta=meta)
632
633 # As in C version, let's clip the determinant
634 eps = 1e-30
635 M_det = M_det.real.clip(eps) + 1j * M_det.imag.clip(eps)
636
637 # Compute Wishart distance
638 if M_center.shape[1] == 3:
639 dist = da.log(da.abs(M_det)) + _trace_product_3(M_inv, in_)
640 else:
641 dist = da.log(da.abs(M_det)) + _trace_product_4(M_inv, in_)
642
643 # Assign class numbers
644 # +1 to convert from 0-based to 1-based class labels
645 class_map = da.argmin(dist, axis=-1) + 1
646 if valid_mask is not None:
647 class_map = da.where(valid_mask, class_map, 0)
648 return class_map.astype("uint8")
649
650
651 def _wishart_classifier_with_early_stop(
652 in_,
653 class_map,
654 nclass,
655 max_iter,
656 tol_pct,
657 valid_mask=None,
658 verbose: bool = True,
659 ):
660 if valid_mask is None:
661 total_pixels = class_map.shape[0] * class_map.shape[1]
662 else:
663 total_pixels = valid_mask.sum()
664
665 for iteration in range(max_iter):
666 if verbose:
667 print(f"Iteration #{iteration + 1}")
668 # Store previous classification for convergence check
669 class_map_prev = class_map
670
671 # Returns class centers as a dask array with shape (nclass, n, n)
672 M_center = _update_wishart_class_centers(
673 in_, class_map, nclass, valid_mask=valid_mask
674 ).persist()
675
676 # Assign new classes, use persist to avoid recomputing
677 class_map = _update_wishart_class_map(
678 in_, M_center, valid_mask=valid_mask
679 ).persist()
680
681 # Check for convergence based on percentage of pixels changing class
682 changed_mask = class_map != class_map_prev
683 if valid_mask is not None:
684 changed_mask = changed_mask & valid_mask
685 changed_pixels = changed_mask.sum()
686 percent_changed = (changed_pixels / total_pixels) * 100.0
687 percent_changed = percent_changed.compute()
688 if percent_changed < tol_pct:
689 break
690 return class_map, percent_changed
691
692
693 def _wishart_classifier_without_early_stop(
694 in_, class_map, nclass, max_iter, valid_mask=None
695 ):
696 if valid_mask is None:
697 total_pixels = class_map.shape[0] * class_map.shape[1]
698 else:
699 total_pixels = valid_mask.sum()
700 for iteration in range(max_iter):
701 # Store previous classification for convergence check
702 class_map_prev = class_map
703
704 # Returns class centers as a dask array with shape (nclass, n, n)
705 M_center = _update_wishart_class_centers(
706 in_, class_map, nclass, valid_mask=valid_mask
707 )
708
709 # Assign new classes
710 class_map = _update_wishart_class_map(in_, M_center, valid_mask=valid_mask)
711
712 # Check for convergence based on percentage of pixels changing class
713 changed_mask = class_map != class_map_prev
714 if valid_mask is not None:
715 changed_mask = changed_mask & valid_mask
716 changed_pixels = changed_mask.sum()
717 percent_changed = (changed_pixels / total_pixels) * 100.0
718
719 return class_map, percent_changed
720
721
722 # def inverse_hermitian_3x3(M: da.Array) -> da.Array:
723 # """
724 # Invert a batch of 3x3 Hermitian matrices using explicit cofactor expansion.
725
726 # Args:
727 # M: Complex Dask array with shape (..., 3, 3)
728
729 # Returns:
730 # Complex Dask array with shape (..., 3, 3)
731 # """
732
733 # # --- Extract elements ---
734 # m11 = M[..., 0, 0]
735 # m12 = M[..., 0, 1]
736 # m13 = M[..., 0, 2]
737 # m21 = M[..., 1, 0]
738 # m22 = M[..., 1, 1]
739 # m23 = M[..., 1, 2]
740 # m31 = M[..., 2, 0]
741 # m32 = M[..., 2, 1]
742 # m33 = M[..., 2, 2]
743
744 # # --- Cofactors (adjugate before transpose, but already aligned) ---
745 # c00 = m22 * m33 - m23 * m32
746 # c01 = -(m12 * m33 - m13 * m32)
747 # c02 = m12 * m23 - m22 * m13
748
749 # c10 = -(m21 * m33 - m31 * m23)
750 # c11 = m11 * m33 - m13 * m31
751 # c12 = -(m11 * m23 - m13 * m21)
752
753 # c20 = m21 * m32 - m22 * m31
754 # c21 = -(m11 * m32 - m12 * m31)
755 # c22 = m11 * m22 - m12 * m21
756
757 # # --- Determinant ---
758 # det = m11 * c00 + m21 * c01 + m31 * c02
759 # eps = 1e-30
760 # det_real = da.maximum(det.real, eps)
761 # det_imag = da.maximum(det.imag, eps)
762 # det = det_real + 1j * det_imag
763
764 # # Optional safety (uncomment if needed)
765 # # det = da.where(det == 0, da.nan, det)
766
767 # inv_det = 1.0 / det
768
769 # # --- Apply normalization ---
770 # i00 = c00 * inv_det
771 # i01 = c01 * inv_det
772 # i02 = c02 * inv_det
773
774 # i10 = c10 * inv_det
775 # i11 = c11 * inv_det
776 # i12 = c12 * inv_det
777
778 # i20 = c20 * inv_det
779 # i21 = c21 * inv_det
780 # i22 = c22 * inv_det
781
782 # # --- Stack back to matrix form ---
783 # row0 = da.stack([i00, i01, i02], axis=-1)
784 # row1 = da.stack([i10, i11, i12], axis=-1)
785 # row2 = da.stack([i20, i21, i22], axis=-1)
786
787 # M_inv = da.stack([row0, row1, row2], axis=-2)
788
789 # return M_inv
790
791
792 # def det_hermitian_3x3(M: da.Array) -> da.Array:
793 # """
794 # Compute determinant of 3x3 Hermitian matrices using the same
795 # method as the provided C implementation.
796
797 # Args:
798 # M: Complex Dask array with shape (..., 3, 3)
799
800 # Returns:
801 # Complex Dask array with shape (...)
802 # """
803
804 # # --- Extract elements ---
805 # m11 = M[..., 0, 0]
806 # m12 = M[..., 0, 1]
807 # m13 = M[..., 0, 2]
808 # m21 = M[..., 1, 0]
809 # m22 = M[..., 1, 1]
810 # m23 = M[..., 1, 2]
811 # m31 = M[..., 2, 0]
812 # m32 = M[..., 2, 1]
813 # m33 = M[..., 2, 2]
814
815 # # --- First row of cofactors (same as C: IHM[0][*]) ---
816 # c00 = m22 * m33 - m23 * m32
817 # c01 = -(m12 * m33 - m13 * m32)
818 # c02 = m12 * m23 - m22 * m13
819
820 # # --- Determinant (complex) ---
821 # # C version does this in real/imag parts explicitly
822 # det = m11 * c00 + m21 * c01 + m31 * c02
823
824 # # --- Optional epsilon handling (mimics C behaviour) ---
825 # # if eps is not None:
826 # eps = 1e-30
827 # det_real = da.maximum(det.real, eps)
828 # det_imag = da.maximum(det.imag, eps)
829 # det = det_real + 1j * det_imag
830
831 # return det