Debian Codegraph @

polsarpro/util.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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, 2025.
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 various utility functions
27
28 """
29
30 import logging
31
32 import dask.array as da
33 import matplotlib.pyplot as plt
34 import numpy as np
35 import xarray
36 import xarray as xr
37 from scipy.ndimage import convolve
38
39 from polsarpro.auxil import validate_dataset
40
41 log = logging.getLogger(__name__)
42
43
44 def S_to_C2(S: xarray.Dataset, p1: str = "hh", p2: str = "hv") -> xarray.Dataset:
45 """Converts the Sinclair scattering matrix S to the lexicographic dual polarization covariance matrix C2.
46
47 Args:
48 S (xarray.Dataset): input image of scattering matrices
49 p1 (str): first polarization.
50 p2 (str): second polarization.
51
52 Returns:
53 xarray.Dataset: C2 covariance matrix
54 Note:
55 p1 and p2 must be different and belong to {'hh', 'hv', 'vv', 'vh'}
56 """
57
58 _ = validate_dataset(S, allowed_poltypes="S")
59
60 pols = {"hh", "hv", "vv", "vh"}
61 if not {p1, p2}.issubset(pols):
62 raise ValueError(f"Polarizations need to be in {pols}")
63
64 if p1 == p2:
65 raise ValueError(f"Polarizations must be different.")
66
67 # scattering vector, enforce type as in C version
68 k1 = S[p1].astype("complex64", copy=False)
69 k2 = S[p2].astype("complex64", copy=False)
70
71 # compute the Hermitian matrix elements
72 C2 = {}
73
74 # force real diagonal to save space
75 C2["m11"] = (k1 * k1.conj()).real
76 C2["m22"] = (k2 * k2.conj()).real
77
78 # upper diagonal terms
79 C2["m12"] = k1 * k2.conj()
80
81 attrs = {
82 "poltype": "C2",
83 "description": f"Covariance matrix (2x2), with polarizations {p1} and {p2}",
84 }
85 return xr.Dataset(C2, attrs=attrs)
86
87
88 def S_to_C3(S: xarray.Dataset) -> xarray.Dataset:
89 """Converts the Sinclair scattering matrix S to the lexicographic covariance matrix C3.
90
91 Args:
92 S (xarray.Dataset): input image of scattering matrices
93
94 Returns:
95 xarray.Dataset: C3 covariance matrix
96 """
97 _ = validate_dataset(S, allowed_poltypes="S")
98
99 # scattering vector, enforce type as in C version
100 c = np.sqrt(np.float32(2))
101 k1 = S.hh.astype("complex64", copy=False)
102 k2 = ((S.hv + S.vh) / c).astype("complex64", copy=False)
103 k3 = S.vv.astype("complex64", copy=False)
104
105 # compute the Hermitian matrix elements
106 C3 = {}
107
108 # force real diagonal to save space
109 C3["m11"] = (k1 * k1.conj()).real
110 C3["m22"] = (k2 * k2.conj()).real
111 C3["m33"] = (k3 * k3.conj()).real
112
113 # upper diagonal terms
114 C3["m12"] = k1 * k2.conj()
115 C3["m13"] = k1 * k3.conj()
116 C3["m23"] = k2 * k3.conj()
117
118 attrs = {"poltype": "C3", "description": "Covariance matrix (3x3)"}
119 return xr.Dataset(C3, attrs=attrs)
120
121
122 def S_to_C4(S: xarray.Dataset) -> xarray.Dataset:
123 """Converts the Sinclair scattering matrix S to the lexicographic covariance matrix C4.
124
125 Args:
126 S (xarray.Dataset): input image of scattering matrices
127
128 Returns:
129 xarray.Dataset: C4 covariance matrix
130 """
131 _ = validate_dataset(S, allowed_poltypes="S")
132
133 # scattering vector, enforce type as in C version
134 k1 = S.hh.astype("complex64", copy=False)
135 k2 = S.hv.astype("complex64", copy=False)
136 k3 = S.vh.astype("complex64", copy=False)
137 k4 = S.vv.astype("complex64", copy=False)
138
139 # compute the Hermitian matrix elements
140 C4 = {}
141 # force real diagonal to save space
142 C4["m11"] = (k1 * k1.conj()).real
143 C4["m22"] = (k2 * k2.conj()).real
144 C4["m33"] = (k3 * k3.conj()).real
145 C4["m44"] = (k4 * k4.conj()).real
146
147 # upper diagonal terms
148 C4["m12"] = k1 * k2.conj()
149 C4["m13"] = k1 * k3.conj()
150 C4["m14"] = k1 * k4.conj()
151 C4["m23"] = k2 * k3.conj()
152 C4["m24"] = k2 * k4.conj()
153 C4["m34"] = k3 * k4.conj()
154
155 attrs = {"poltype": "C4", "description": "Covariance matrix (4x4)"}
156 return xr.Dataset(C4, attrs=attrs)
157
158
159 def S_to_T3(S: xarray.Dataset) -> xarray.Dataset:
160 """Converts the Sinclair scattering matrix S to the Pauli coherency matrix T3.
161
162 Args:
163 S (xarray.Dataset): input image of scattering matrices
164
165 Returns:
166 xarray.Dataset: T3 covariance matrix
167 """
168 _ = validate_dataset(S, allowed_poltypes="S")
169
170 # scattering vector
171 c = np.sqrt(np.float32(2))
172 k1 = ((S.hh + S.vv) / c).astype("complex64", copy=False)
173 k2 = ((S.hh - S.vv) / c).astype("complex64", copy=False)
174 k3 = ((S.hv + S.vh) / c).astype("complex64", copy=False)
175
176 # compute the Hermitian matrix elements
177 T3 = {}
178
179 # force real diagonal to save space
180 T3["m11"] = (k1 * k1.conj()).real
181 T3["m22"] = (k2 * k2.conj()).real
182 T3["m33"] = (k3 * k3.conj()).real
183
184 # upper diagonal terms
185 T3["m12"] = k1 * k2.conj()
186 T3["m13"] = k1 * k3.conj()
187 T3["m23"] = k2 * k3.conj()
188
189 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
190 return xr.Dataset(T3, attrs=attrs)
191
192
193 def S_to_T4(S: xarray.Dataset) -> xarray.Dataset:
194 """Converts the Sinclair scattering matrix S to the Pauli coherency matrix T4.
195
196 Args:
197 S (xarray.Dataset): input image of scattering matrices
198
199 Returns:
200 xarray.Dataset: T4 coherency matrix
201 """
202 _ = validate_dataset(S, allowed_poltypes="S")
203
204 # scattering vector
205 c = np.sqrt(np.float32(2))
206 k1 = ((S.hh + S.vv) / c).astype("complex64", copy=False)
207 k2 = ((S.hh - S.vv) / c).astype("complex64", copy=False)
208 k3 = ((S.hv + S.vh) / c).astype("complex64", copy=False)
209 # NOTE: it might work only with ALOS-1 (hv-vh is inverted, according to C-PSP)
210 k4 = (1j * (S.vh - S.hv) / c).astype("complex64", copy=False)
211 # alternate version
212 # k4 = (1j * (S.hv - S.vh) / c).astype("complex64", copy=False)
213
214 # compute the Hermitian matrix elements
215 T4 = {}
216
217 # force real diagonal to save space
218 T4["m11"] = (k1 * k1.conj()).real
219 T4["m22"] = (k2 * k2.conj()).real
220 T4["m33"] = (k3 * k3.conj()).real
221 T4["m44"] = (k4 * k4.conj()).real
222
223 # upper diagonal terms
224 T4["m12"] = k1 * k2.conj()
225 T4["m13"] = k1 * k3.conj()
226 T4["m14"] = k1 * k4.conj()
227 T4["m23"] = k2 * k3.conj()
228 T4["m24"] = k2 * k4.conj()
229 T4["m34"] = k3 * k4.conj()
230
231 attrs = {"poltype": "T4", "description": "Coherency matrix (4x4)"}
232 return xr.Dataset(T4, attrs=attrs)
233
234
235 def C3_to_T3(C3: xarray.Dataset) -> xarray.Dataset:
236 """Converts the lexicographic covariance matrix C3 to the Pauli coherency matrix T3.
237
238 Args:
239 C3 (xarray.Dataset): input image of covariance matrices
240
241 Returns:
242 xarray.Dataset: T3 coherency matrix
243 """
244 _ = validate_dataset(C3, allowed_poltypes="C3")
245
246 T3 = {}
247
248 c = 1 / np.sqrt(np.float32(2))
249
250 # force real diagonal to save space
251 T3["m11"] = 0.5 * (C3.m11 + C3.m33) + C3.m13.real
252 T3["m22"] = 0.5 * (C3.m11 + C3.m33) - C3.m13.real
253 T3["m33"] = C3.m22
254 # upper diagonal terms
255 T3["m12"] = 0.5 * (C3.m11 - C3.m33) - 1j * C3.m13.imag
256 T3["m13"] = c * (C3.m12 + C3.m23.conj())
257 T3["m23"] = c * (C3.m12 - C3.m23.conj())
258
259 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
260 return xr.Dataset(T3, attrs=attrs)
261
262
263 def T3_to_C3(T3: xarray.Dataset) -> xarray.Dataset:
264 """Converts the Pauli coherency matrix T3 to the lexicographic covariance matrix C3.
265
266 Args:
267 T3 (xarray.Dataset): input image of coherency matrices
268
269 Returns:
270 xarray.Dataset: C3 covariance matrix
271 """
272
273 _ = validate_dataset(T3, allowed_poltypes="T3")
274
275 C3 = {}
276
277 c = 1 / np.sqrt(np.float32(2))
278
279 # force real diagonal to save space
280 C3["m11"] = 0.5 * (T3.m11 + T3.m22) + T3.m12.real
281 C3["m22"] = T3.m33
282 C3["m33"] = 0.5 * (T3.m11 + T3.m22) - T3.m12.real
283
284 # upper diagonal terms
285 C3["m12"] = c * (T3.m13 + T3.m23)
286 C3["m13"] = 0.5 * (T3.m11.real - T3.m22.real) - 1j * T3.m12.imag
287 C3["m23"] = c * (T3.m13.conj() - T3.m23.conj())
288
289 attrs = {"poltype": "C3", "description": "Covariance matrix (3x3)"}
290 return xr.Dataset(C3, attrs=attrs)
291
292
293 def C4_to_T4(C4: xarray.Dataset) -> xarray.Dataset:
294 """Converts the lexicographic covariance matrix C4 to the Pauli coherency matrix T4.
295
296 Args:
297 C4 (xarray.Dataset): input image of covariance matrices
298
299 Returns:
300 xarray.Dataset: T4 coherency matrix
301 """
302 _ = validate_dataset(C4, allowed_poltypes="C4")
303
304 T4 = {}
305
306 # force real diagonal to save space
307 # diagonal terms
308 T4["m11"] = 0.5 * (C4.m11 + 2 * C4.m14.real + C4.m44)
309 T4["m22"] = 0.5 * (C4.m11 - 2 * C4.m14.real + C4.m44)
310 T4["m33"] = 0.5 * (C4.m22 + C4.m33 + 2 * C4.m23.real)
311 T4["m44"] = 0.5 * (C4.m22 + C4.m33 - 2 * C4.m23.real)
312
313 # m12
314 T4["m12"] = 0.5 * (C4.m11 - C4.m44) - 1j * C4.m14.imag
315
316 # m13
317 T4["m13"] = 0.5 * (C4.m12 + C4.m13 + C4.m24.conj() + C4.m34.conj())
318
319 # m14
320 T4["m14"] = 0.5 * (
321 C4.m12.imag - C4.m13.imag - C4.m24.imag + C4.m34.imag
322 ) + 0.5 * 1j * (-C4.m12.real + C4.m13.real - C4.m24.real + C4.m34.real)
323
324 # m23
325 T4["m23"] = 0.5 * (C4.m12 + C4.m13 - C4.m24.conj() - C4.m34.conj())
326
327 # m24
328 T4["m24"] = 0.5 * (
329 C4.m12.imag - C4.m13.imag + C4.m24.imag - C4.m34.imag
330 ) + 0.5 * 1j * (-C4.m12.real + C4.m13.real + C4.m24.real - C4.m34.real)
331
332 # m34
333 T4["m34"] = -C4.m23.imag + 0.5j * (-C4.m22 + C4.m33)
334
335 attrs = {"poltype": "T4", "description": "Coherency matrix (4x4)"}
336 return xr.Dataset(T4, attrs=attrs)
337
338
339 def C4_to_C3(C4: xarray.Dataset) -> xarray.Dataset:
340 """Converts the lexicographic covariance matrix C4 to the lexicographic covariance matrix C3.
341
342 Args:
343 C4 (xarray.Dataset): input image of covariance matrices
344
345 Returns:
346 xarray.Dataset: C3 covariance matrix
347 """
348 _ = validate_dataset(C4, allowed_poltypes="C4")
349
350 C3 = {}
351
352 c = 1 / np.sqrt(np.float32(2))
353
354 # force real diagonal to save space
355 C3["m11"] = C4.m11
356 C3["m22"] = 0.5 * (C4.m22 + C4.m33 + 2 * C4.m23.real)
357 C3["m33"] = C4.m44
358
359 # upper diagonal terms
360 C3["m12"] = c * (C4.m12 + C4.m13)
361 C3["m13"] = C4.m14
362 C3["m23"] = c * (C4.m24 + C4.m34)
363
364 attrs = {"poltype": "C3", "description": "Covariance matrix (3x3)"}
365 return xr.Dataset(C3, attrs=attrs)
366
367
368 def C4_to_T3(C4: xarray.Dataset) -> xarray.Dataset:
369 """Converts the lexicographic covariance matrix C4 to the Pauli coherency matrix T3.
370
371 Args:
372 C4 (xarray.Dataset): input image of covariance matrices
373
374 Returns:
375 xarray.Dataset: T3 coherency matrix
376 """
377 _ = validate_dataset(C4, allowed_poltypes="C4")
378
379 T3 = {}
380
381 # force real diagonal to save space
382 T3["m11"] = 0.5 * (C4.m11 + C4.m44) + C4.m14.real
383 T3["m22"] = 0.5 * (C4.m11 + C4.m44) - C4.m14.real
384 T3["m33"] = 0.5 * (C4.m22 + C4.m33 + 2 * C4.m23.real)
385
386 # upper diagonal terms
387 T3["m12"] = 0.5 * (C4.m11 - C4.m44) - 1j * C4.m14.imag
388 T3["m13"] = 0.5 * (C4.m12 + C4.m13 + C4.m24.conj() + C4.m34.conj())
389 T3["m23"] = 0.5 * (C4.m12 + C4.m13 - C4.m24.conj() - C4.m34.conj())
390
391 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
392 return xr.Dataset(T3, attrs=attrs)
393
394
395 def T4_to_C4(T4: xarray.Dataset) -> xarray.Dataset:
396 """Converts the Pauli coherency matrix T4 to the lexicographic covariance matrix C4.
397
398 Args:
399 T4 (xarray.Dataset): input image of coherency matrices
400
401 Returns:
402 xarray.Dataset: C4 covariance matrix
403
404 """
405 _ = validate_dataset(T4, allowed_poltypes="T4")
406
407 C4 = {}
408
409 # force real diagonal to save space
410 C4["m11"] = 0.5 * (T4.m11 + 2 * T4.m12.real + T4.m22)
411 C4["m22"] = 0.5 * (T4.m33 - 2 * T4.m34.imag + T4.m44)
412 C4["m33"] = 0.5 * (T4.m33 + T4.m44 + 2 * T4.m34.imag)
413 C4["m44"] = 0.5 * (T4.m11 - 2 * T4.m12.real + T4.m22)
414
415 # upper diagonal terms
416 C4["m12"] = 0.5 * (
417 T4.m13.real + T4.m23.real - T4.m14.imag - T4.m24.imag
418 ) + 0.5 * 1j * (T4.m13.imag + T4.m23.imag + T4.m14.real + T4.m24.real)
419
420 C4["m13"] = 0.5 * (
421 T4.m13.real + T4.m23.real + T4.m14.imag + T4.m24.imag
422 ) + 0.5 * 1j * (T4.m13.imag + T4.m23.imag - T4.m14.real - T4.m24.real)
423
424 C4["m14"] = 0.5 * (T4.m11 - T4.m22) - 1j * T4.m12.imag
425
426 C4["m23"] = 0.5 * (T4.m33 - T4.m44) - 1j * T4.m34.real
427
428 C4["m24"] = 0.5 * (
429 T4.m13.real - T4.m23.real - T4.m14.imag + T4.m24.imag
430 ) + 0.5 * 1j * (-T4.m13.imag + T4.m23.imag - T4.m14.real + T4.m24.real)
431
432 C4["m34"] = 0.5 * (
433 T4.m13.real - T4.m23.real + T4.m14.imag - T4.m24.imag
434 ) + 0.5 * 1j * (-T4.m13.imag + T4.m23.imag + T4.m14.real - T4.m24.real)
435
436 attrs = {"poltype": "C4", "description": "Covariance matrix (4x4)"}
437 return xr.Dataset(C4, attrs=attrs)
438
439
440 def T4_to_C3(T4: xarray.Dataset) -> xarray.Dataset:
441 """Converts the Pauli coherency matrix T4 to the lexicographic covariance matrix C3.
442
443 Args:
444 T4 (xarray.Dataset): input image of coherency matrices
445
446 Returns:
447 xarray.Dataset: C3 covariance matrix
448
449 """
450 _ = validate_dataset(T4, allowed_poltypes="T4")
451
452 C3 = {}
453
454 c = 1 / np.sqrt(np.float32(2))
455
456 # force real diagonal to save space
457 C3["m11"] = 0.5 * (T4.m11 + 2 * T4.m12.real + T4.m22)
458 C3["m22"] = T4.m33
459 C3["m33"] = 0.5 * (T4.m11 - 2 * T4.m12.real + T4.m22)
460
461 # upper diagonal terms
462 C3["m12"] = c * (T4.m13 + T4.m23)
463 C3["m13"] = 0.5 * (T4.m11 - T4.m22) - 1j * T4.m12.imag
464 C3["m23"] = c * (T4.m13.conj() - T4.m23.conj())
465
466 attrs = {"poltype": "C3", "description": "Covariance matrix (3x3)"}
467 return xr.Dataset(C3, attrs=attrs)
468
469
470 def T4_to_T3(T4: xarray.Dataset) -> xarray.Dataset:
471 """Converts the Pauli coherency matrix T4 to the Pauli coherency matrix T3.
472
473 Args:
474 T4 (xarray.Dataset): input image of coherency matrices
475
476 Returns:
477 xarray.Dataset: T3 coherency matrix
478
479 """
480 _ = validate_dataset(T4, allowed_poltypes="T4")
481
482 T3 = {
483 "m11": T4.m11,
484 "m22": T4.m22,
485 "m33": T4.m33,
486 "m12": T4.m12,
487 "m13": T4.m13,
488 "m23": T4.m23,
489 }
490
491 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
492 return xr.Dataset(T3, attrs=attrs)
493
494
495 # this function is used only in unit tests
496 def vec_to_mat(vec: np.ndarray) -> np.ndarray:
497 if vec.ndim != 3:
498 raise ValueError("Vector valued image is expected (dimension 3)")
499 return vec[:, :, None, :] * vec[:, :, :, None].conj()
500
501
502 def boxcar(img: xarray.Dataset, dim_az: int, dim_rg: int) -> xarray.Dataset:
503 """
504 Apply a boxcar filter to an image.
505
506 Args:
507 img (xarray.Dataset): Input image with variables of shape (naz, nrg, ...).
508 dim_az (int): Size in azimuth of the filter.
509 dim_rg (int): Size in range of the filter.
510
511 Returns:
512 xarray.Dataset: Filtered image, shape (naz, nrg, ...).
513
514 Note:
515 The filter is always applied along 2 dimensions (azimuth, range). Please ensure to provide a valid image.
516 """
517 _ = validate_dataset(img)
518
519 if type(dim_az) != int and type(dim_rg) != int:
520 raise ValueError("dimaz and dimrg must be integers")
521 if (dim_az < 1) or (dim_rg < 1):
522 raise ValueError("dimaz and dimrg must be strictly positive")
523
524 process_args = dict(
525 dim_az=dim_az,
526 dim_rg=dim_rg,
527 depth=(dim_az, dim_rg),
528 )
529 data_out = {}
530 for var in img.data_vars:
531 # if data is not chunked, apply directly
532 if isinstance(img[var].data, np.ndarray):
533 da_in = _boxcar_core(img[var].data, dim_az=dim_az, dim_rg=dim_rg)
534 # for dask chunked arrays, apply blockwise parallel processing
535 else:
536 da_in = da.map_overlap(
537 _boxcar_core,
538 img[var].data,
539 **process_args,
540 dtype=img[var].dtype,
541 )
542 data_out[var] = (img[var].dims, da_in)
543
544 return xr.Dataset(data_out, coords=img.coords, attrs=img.attrs)
545
546
547 # this should not be used directly
548 def _boxcar_core(img: np.ndarray, dim_az: int, dim_rg: int) -> np.ndarray:
549 n_extra_dims = img.ndim - 2
550
551 ker_dtype = img.dtype if not np.iscomplexobj(img) else img.real.dtype
552
553 # this convolution mode reduces error between C and python implementations
554 mode = "constant"
555 if (dim_az > 1) or (dim_rg > 1):
556 # avoid nan propagation
557 msk = np.isnan(img)
558 img_ = img.copy()
559
560 img_[msk] = 0
561 ker = np.ones((dim_az, dim_rg), dtype=ker_dtype) / (dim_az * dim_rg)
562 ker = np.expand_dims(ker, axis=tuple(range(2, 2 + n_extra_dims)))
563 if np.iscomplexobj(img_):
564 imgout = convolve(img_.real, ker, mode=mode) + 1j * convolve(
565 img_.imag, ker, mode=mode
566 )
567 imgout[msk] = np.nan + 1j * np.nan
568 else:
569 imgout = convolve(img_, ker, mode=mode)
570 imgout[msk] = np.nan
571 return imgout
572 else:
573 return img
574
575
576 # This is an alternative version that uses xarray's rolling mean
577 # performance is not clear so I just keep it here for now
578 # def boxcar(img: xarray.Dataset, dim_az: int, dim_rg: int) -> xarray.Dataset:
579 # """
580 # Apply a boxcar filter to an image.
581
582 # Args:
583 # img (complex or real array): Input image with arbitrary number of dimensions, shape (naz, nrg, ...).
584 # dim_az (int): Size in azimuth (or latitude) of the filter.
585 # dim_rg (int): Size in range (or longitude) of the filter.
586
587 # Returns:
588 # complex or real array: Filtered image, shape (naz, nrg, ...).
589
590 # Note:
591 # The filter is always applied along 2 dimensions (azimuth, range).
592 # If the input is a geocoded image, azimuth and range become latitude and longitude.
593 # Please ensure to provide a valid image.
594 # """
595
596 # if not isinstance(img, xarray.Dataset):
597 # raise TypeError("Input must be a valid PolSARPro Dataset.")
598
599 # if not all((isinstance(dim_az, int), isinstance(dim_rg, int))):
600 # raise TypeError("Parameters dim_az and dim_rg must be integers.")
601
602 # if dim_az <= 0 or dim_rg <= 0:
603 # raise ValueError("Parameters dim_az and dim_rg must strictly positive.")
604
605 # dims_sar = {"y", "x"}
606 # dims_geo = {"lat", "lon"}
607
608 # if dims_sar.issubset(img.dims):
609 # dict_filter = dict(x=dim_rg, y=dim_az)
610 # dict_slice = dict(x=slice(dim_rg, -dim_rg), y=slice(dim_az, -dim_az))
611 # elif dims_geo.issubset(img.dims):
612 # dict_filter = dict(lon=dim_rg, lat=dim_az)
613 # dict_slice = dict(lon=slice(dim_rg, -dim_rg), lat=slice(dim_az, -dim_az))
614 # else:
615 # raise ValueError("Input data must have dimensions ('y','x') or ('lat', 'lon').")
616
617 # # pad the data with zeros
618 # res = img.pad(dict_filter, mode="constant", constant_values=0)
619
620 # # compute rolling mean
621 # res = res.rolling(**dict_filter, center=True).mean()
622
623 # # trim the padded borders
624 # res = res.isel(**dict_slice)
625 # return res
626
627
628 def multilook(input_data: xr.Dataset, dim_az: int = 2, dim_rg: int = 2) -> xr.Dataset:
629 """Apply multilooking to polarimetric matrices.
630
631 Args:
632 input_data (xr.Dataset): Input PolSARpro Dataset.
633 dim_az (int): Multilook dimension in azimuth.
634 dim_rg (int): Multilook dimension in range.
635
636 Returns:
637 xr.Dataset: Multilooked PolSARpro Dataset.
638
639 Note:
640 The input dataset must be in the SAR geometry (i.e. have 'y' and 'x' coordinates).
641 """
642
643 if type(dim_az) != int and type(dim_rg) != int:
644 raise ValueError("dimaz and dimrg must be integers")
645
646 if (dim_az < 1) or (dim_rg < 1):
647 raise ValueError("dimaz and dimrg must be strictly positive")
648
649 if not {"y", "x"}.issubset(set(input_data.coords)):
650 raise ValueError(
651 "Multilooking requires images in the SAR geometry. 'y' and 'x' must be present in the coordinates. For geocoded data, please use xarray.coarsen."
652 )
653
654 allowed_poltypes = ("C2", "C3", "C4", "T3", "T4")
655 validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
656 return input_data.coarsen(y=dim_az, x=dim_rg, boundary="trim").mean()
657
658
659 def plot_h_alpha_plane(ds, bins=500, min_pts=5):
660 """Plot H-Alpha 2D histogram.
661
662 Args:
663 ds (xr.Dataset): Dataset containing 'entropy' and 'alpha' variables.
664 bins (int): Number of bins along each dimension.
665 min_pts (int): If the number of points in one bin is less than this value, display is omitted.
666 """
667
668 if not ds.poltype == "h_a_alpha":
669 raise ValueError("Input must be a valid PolSARpro H/A/Alpha result.")
670
671 if not {"entropy", "alpha"}.issubset(ds.data_vars):
672 raise ValueError("Entropy or Alpha is missing from the input data.")
673
674 def curve1(n_points):
675
676 m = np.linspace(1e-30, 1, n_points)
677 l1 = np.ones(n_points)
678 l2 = m
679 l3 = m
680 l = np.vstack([l1, l2, l3])
681
682 p = l / l.sum(0)
683 H = np.sum(-p * np.log(p), 0) / np.float32(np.log(3))
684 alpha = p[1] + p[2]
685
686 return H, alpha
687
688 def curve2(n_points):
689 m = np.linspace(1e-30, 1, n_points)
690 l1 = np.zeros_like(m)
691 l2 = np.ones_like(m)
692 l3 = np.zeros_like(m)
693 # l1[m < 0.5] = 0
694 l1[m >= 0.5] = 2 * m[m >= 0.5] - 1
695
696 # l3[m < 0.5] = 2 * m[m<0.5]
697 l3[m >= 0.5] = 1
698
699 l = np.vstack([l1, l2, l3])
700
701 p = l / l.sum(0)
702 H = np.sum(-p * np.log(p + 1e-30), 0) / np.float32(np.log(3))
703 alpha = p[1] + p[2]
704
705 return H[m >= 0.5], alpha[m >= 0.5]
706
707 x1, y1 = curve1(bins)
708 x2, y2 = curve2(bins)
709
710 # Flatten and remove NaNs
711 entropy = ds.entropy.values.ravel()
712 alpha = ds.alpha.values.ravel()
713 mask = ~np.isnan(entropy) & ~np.isnan(alpha)
714 entropy = entropy[mask].clip(0, 1)
715 alpha = alpha[mask].clip(0, 90)
716
717 fig, ax = plt.subplots(figsize=(8, 6))
718
719 # 2D histogram
720 h = ax.hist2d(
721 entropy, alpha, bins=bins, range=((0, 1), (0, 90)), cmap="jet", cmin=min_pts
722 )
723 plt.colorbar(h[3], ax=ax, label="Number of points")
724
725 # Overlay curves
726 ax.plot(x1, 90 * y1, color="black", linewidth=1)
727 ax.plot(x2, 90 * y2, color="black", linewidth=1)
728
729 # Labels and title
730 ax.set_xlabel("Entropy (H)")
731 ax.set_ylabel("Alpha (°)")
732 ax.set_title("H-Alpha plane")
733
734 return ax, fig
735
736
737 def pauli_rgb(input_data: xr.Dataset, q: float = 0.98) -> xr.DataArray:
738 """Compute Pauli RGB representation from polarimetric data.
739
740 Args:
741 input_data (xr.Dataset): Input PolSARpro Dataset.
742 q (float): Quantile for dynamic range clipping (between 0 and 1).
743
744 Returns:
745 xr.DataArray: RGB representation with 'band' dimension.
746 """
747 allowed_poltypes = ("S", "C3", "T3")
748 validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
749
750 def pauli_from_S(S):
751 r = abs(S.hh - S.vv) ** 2
752 g = abs(0.5 * (S.hv + S.vh)) ** 2
753 b = abs(S.hh + S.vv) ** 2
754 return r, g, b
755
756 def pauli_from_T3(T3):
757 r = T3.m22
758 g = T3.m33
759 b = T3.m11
760 return r, g, b
761
762 def pauli_from_C3(C3):
763 T3 = C3_to_T3(C3)
764 return pauli_from_T3(T3)
765
766 if input_data.poltype == "S":
767 r, g, b = pauli_from_S(input_data)
768 elif input_data.poltype == "C3":
769 r, g, b = pauli_from_C3(input_data)
770 elif input_data.poltype == "T3":
771 r, g, b = pauli_from_T3(input_data)
772
773 rgb = xr.concat([r, g, b], dim="band").rename("Pauli RGB").chunk("auto")
774
775 # resampling may introduce negative values
776 rgb = xr.where(rgb < 0, 0, rgb)
777 rgb = np.sqrt(rgb)
778
779 # compute clipping values to handle the high dynamic range
780 # clip_val = rgb.quantile(dim=("x", "y"), q=q).astype("float32").drop_vars("quantile")
781 clip_val = (
782 rgb.quantile(dim=input_data.dims, q=q).astype("float32").drop_vars("quantile")
783 )
784
785 # clip and normalize
786 return rgb.clip(max=clip_val) / clip_val