Debian Codegraph @

polsarpro/util.py

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