Debian Codegraph @

polsarpro/decompositions.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, 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 polarimetric decomposition functions
27
28 """
29
30 import dask.array as da
31 import numpy as np
32 import xarray as xr
33
34 from polsarpro.auxil import validate_dataset
35 from polsarpro.util import C3_to_T3, C4_to_T4, S_to_C3, S_to_T3, T3_to_C3, boxcar
36
37
38 def cameron(
39 input_data: xr.Dataset,
40 ) -> xr.Dataset:
41 """Applies the Cameron decomposition to the S matrix.
42
43 Args:
44 input_data (xr.Dataset): Input image of S matrices.
45
46 Returns:
47 xr.Dataset: Output class (1: plane, 2: dihedral, 3: dipole, 4: cylinder, 5: narrow diplane, 6: 1/4 wave, 7: left helix, 8: right helix).
48
49 Notes:
50 This decomposition is only applicable to Sinclair matrices (S). Therefore it may not be applied to geocoded data since resampling the S matrix may result in a loss of polarimetric information.
51 """
52
53 allowed_poltypes = "S"
54 _ = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
55
56 in_ = input_data.astype("complex64", copy=False)
57
58 # remove NaNs
59 eps = 1e-30
60 mask = in_.to_array().isnull().any("variable")
61 in_ = in_.fillna(eps)
62
63 out = _compute_cameron(in_)
64 return xr.Dataset(
65 # add dimension names
66 {k: (tuple(input_data.dims), v) for k, v in out.items()},
67 attrs=dict(
68 poltype="cameron",
69 description="Results of the Cameron decomposition.",
70 ),
71 coords=input_data.coords,
72 ) # .where(~mask)
73
74
75 def freeman(
76 input_data: xr.Dataset,
77 boxcar_size: list[int, int] = [3, 3],
78 ) -> xr.Dataset:
79 """Applies the Freeman-Durden decomposition. This decomposition is based on physical modeling
80 of the covariance matrix and returns 3 components Ps, Pd and Pv which are the powers of resp.
81 surface, double bounce and volume backscattering.
82
83 Args:
84 input_data (xr.Dataset): Input image, may be a covariance (C3), coherency (T3) or Sinclair (S) matrix.
85 boxcar_size (list[int, int], optional): Boxcar dimensions along azimuth and range. Defaults to [3, 3].
86
87 Returns:
88 xr.Dataset: Ps, Pd and Pv components.
89
90 References:
91 Freeman A. and Durden S., “A Three-Component Scattering Model for Polarimetric SAR Data”, IEEE Trans. Geosci. Remote Sens., vol. 36, no. 3, May 1998.
92 """
93
94 allowed_poltypes = ("S", "C3", "T3")
95 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
96
97 # in_ = input_data.astype("complex64", copy=False)
98 if poltype == "C3":
99 in_ = input_data
100 elif poltype == "T3":
101 in_ = T3_to_C3(input_data)
102 elif poltype == "S":
103 in_ = S_to_C3(input_data)
104
105 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
106 in_ = boxcar(in_, boxcar_size[0], boxcar_size[1])
107
108 # remove NaNs
109 eps = 1e-30
110 mask = in_.to_array().isnull().any("variable")
111 in_ = in_.fillna(eps)
112
113 out = _compute_freeman_components(in_)
114 return xr.Dataset(
115 # add dimension names
116 {k: (tuple(input_data.dims), v) for k, v in out.items()},
117 attrs=dict(
118 poltype="freeman",
119 description="Results of the Freeman-Durden decomposition.",
120 ),
121 coords=input_data.coords,
122 ).where(~mask)
123
124
125 def h_a_alpha(
126 input_data: xr.Dataset,
127 boxcar_size: list[int, int] = [3, 3],
128 flags: tuple[str] = ("entropy", "alpha", "anisotropy"),
129 ) -> xr.Dataset:
130 """Performs the H/A/Alpha polarimetric decomposition on full-pol SAR data.
131
132 This function computes the H/A/Alpha decomposition from input polarimetric SAR data
133 using eigenvalue analysis of the coherency matrix. The decomposition
134 provides physical insight into scattering mechanisms through parameters such as
135 entropy (H), anisotropy (A), and the alpha scattering angle (alpha). Additional
136 eigenvalue-based parameters can also be computed by specifying corresponding flags.
137
138 Args:
139 input_data (xr.Dataset): Input polarimetric SAR dataset. Supported types are:
140
141 - "S": Sinclair scattering matrix
142
143 - "C3": Lexicographic covariance matrix
144
145 - "T3": Pauli coherency matrix
146
147 - "C4" and "T4": 4x4 versions of the above
148
149 - "C2": Dual-polarimetric covariance
150
151 boxcar_size (list[int, int], optional): Size of the spatial averaging window to be
152 applied before decomposition (boxcar filter). Defaults to [3, 3].
153 flags (tuple[str], optional): Parameters to compute and return from the decomposition.
154 Possible values include:
155
156 - "entropy": Scattering entropy (H)
157
158 - "anisotropy": Scattering anisotropy (A)
159
160 - "alpha": Mean alpha scattering angle (alpha)
161
162 - "beta", "delta", "gamma", "lambda": Other angular or eigenvalue related parameters
163
164 - "nhu", "epsilon" additional angles defined only for 4x4 matrices. Will be ignored if not processing 4x4 matrices.
165
166 - "alphas", "betas", "deltas", "gammas", "lambdas": Per-eigenvalue versions of the above
167 Defaults to ("entropy", "alpha", "anisotropy").
168
169 Returns:
170 xr.Dataset: An xarray.Dataset where data variable names correspond to the requested flags, and values are the corresponding 2D arrays (or 3D if the flag returns multiple values per pixel).
171
172 Notes:
173 For C2 inputs, only 'alpha(s)', 'delta(s)', 'anisotropy', 'entropy' and 'lambda(s)' can be computed. Other passed flags will be ignored.
174
175 If the S matrix is given as an input, a 3x3 analysis will be assumed using the T3 matrix. For 4x4 and 2x2, use 'C4', 'T4' or 'C2' as an input.
176
177 References:
178 Cloude, S. R., & Pottier, E. (1997). An entropy based classification scheme for land
179 applications of polarimetric SAR. *IEEE Transactions on Geoscience and Remote Sensing*,
180 35(1), 68-78.
181 """
182
183 # check flags validity
184
185 if not isinstance(flags, tuple):
186 raise ValueError("'flags' parameter must be a tuple.")
187
188 possible_flags = (
189 "entropy",
190 "anisotropy",
191 "alpha",
192 "beta",
193 "delta",
194 "epsilon",
195 "gamma",
196 "lambda",
197 "nhu",
198 "alphas",
199 "betas",
200 "deltas",
201 "epsilons",
202 "gammas",
203 "lambdas",
204 "nhus",
205 )
206 for flag in flags:
207 if flag not in possible_flags:
208 raise ValueError(
209 f"Flag '{flag}' not recognized. Possible values are {possible_flags}."
210 )
211 allowed_poltypes = ("S", "C2", "C3", "C4", "T3", "T4")
212 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
213
214 if poltype == "C2":
215 in_ = input_data
216 elif poltype == "C3":
217 in_ = C3_to_T3(input_data)
218 elif poltype == "T3":
219 in_ = input_data
220 elif poltype == "C4":
221 in_ = C4_to_T4(input_data)
222 elif poltype == "T4":
223 in_ = input_data
224 elif poltype == "S":
225 in_ = S_to_T3(input_data)
226 else:
227 raise ValueError(f"Invalid polarimetric type: {input_data.poltype}")
228
229 new_dims = tuple(input_data.dims)
230
231 eps = 1e-30
232 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
233 in_ = boxcar(in_, dim_az=boxcar_size[0], dim_rg=boxcar_size[1])
234
235 # remove NaNs to avoid errors in eigh
236 mask = in_.to_array().isnull().any("variable")
237 in_ = in_.fillna(eps)
238
239 M = _reconstruct_matrix_from_ds(in_)
240
241 # eigendecomposition
242 meta = (
243 np.array([], dtype="float32").reshape((0, 0, 0)),
244 np.array([], dtype="complex64").reshape((0, 0, 0, 0)),
245 )
246 l, v = da.apply_gufunc(np.linalg.eigh, "(i,j)->(i), (i,j)", M, meta=meta)
247
248 l = l[..., ::-1] # descending order
249 v = v[..., ::-1]
250
251 # returns a dict
252 if in_.poltype in ("S", "T3", "C4"):
253 out = _compute_h_a_alpha_parameters_T3(l, v, flags)
254 elif in_.poltype in ("T4", "C4"):
255 out = _compute_h_a_alpha_parameters_T4(l, v, flags)
256 elif in_.poltype in ("C2"):
257 out = _compute_h_a_alpha_parameters_C2(l, v, flags)
258
259 return xr.Dataset(
260 # add dimension names, account for 2D and 3D outputs
261 {
262 k: (new_dims, v) if v.ndim == 2 else (new_dims + ("i",), v)
263 for k, v in out.items()
264 },
265 attrs=dict(
266 poltype="h_a_alpha", description="Results of the H/A/Alpha decomposition."
267 ),
268 coords=input_data.coords,
269 ).where(~mask)
270
271
272 def yamaguchi3(
273 input_data: xr.Dataset,
274 boxcar_size: list[int, int] = [3, 3],
275 ) -> xr.Dataset:
276 """Applies the Yamaguchi 3 component decomposition. This decomposition is based on physical modeling
277 of the covariance matrix and returns 3 components "odd", "surface" and "volume" which are the powers of resp.
278 surface, double bounce and volume backscattering.
279
280 Args:
281 input_data (xr.Dataset): Input image, may be a covariance (C3), coherency (T3) or Sinclair (S) matrix.
282 boxcar_size (list[int, int], optional): Boxcar dimensions along azimuth and range. Defaults to [3, 3].
283
284 Returns:
285 xr.Dataset: odd, surface and volume scattering components.
286
287 References:
288 Yamaguchi Y., Moriyama T., Ishido M. and Yamada H., “Four-Component Scattering Model for Polarimetric SAR Image Decomposition”, IEEE Trans. Geos. Remote Sens., vol. 43, no. 8, August 2005.
289
290 """
291
292 allowed_poltypes = ("S", "C3", "T3")
293 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
294
295 # in_ = input_data.astype("complex64", copy=False)
296 if poltype == "C3":
297 in_ = input_data
298 elif poltype == "T3":
299 in_ = T3_to_C3(input_data)
300 elif poltype == "S":
301 in_ = S_to_C3(input_data)
302
303 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
304 in_ = boxcar(in_, boxcar_size[0], boxcar_size[1])
305
306 # remove NaNs
307 eps = 1e-30
308 mask = in_.to_array().isnull().any("variable")
309 in_ = in_.fillna(eps)
310
311 out = _compute_yamaguchi3_components(in_)
312
313 return xr.Dataset(
314 # add dimension names
315 {k: (tuple(input_data.dims), v) for k, v in out.items()},
316 attrs=dict(
317 poltype="yamaguchi3",
318 description="Results of the Yamaguchi 3 component decomposition.",
319 ),
320 coords=input_data.coords,
321 ).where(~mask)
322
323
324 def yamaguchi4(
325 input_data: xr.Dataset,
326 boxcar_size: list[int, int] = [3, 3],
327 mode: str = "y4o",
328 ) -> xr.Dataset:
329 """Applies the Yamaguchi 4 component decomposition. This decomposition is based on physical modeling
330 of the covariance matrix and returns 4 components "odd", "surface", "volume" and "helix" which are the powers of resp. surface, double bounce, volume and helix backscattering.
331
332 Args:
333 input_data (xr.Dataset): Input image, may be a covariance (C3), coherency (T3) or Sinclair (S) matrix.
334 boxcar_size (list[int, int], optional): Boxcar dimensions along azimuth and range. Defaults to [3, 3].
335 mode (str, optional): One of the following modes "y4o" (original), "y4r" (with rotation) or "s4r" (). Defaults to "y4o".
336
337 Returns:
338 xr.Dataset: odd, surface, volume and helix scattering components.
339
340 References:
341 Yamaguchi Y., Moriyama T., Ishido M. and Yamada H., “Four-Component Scattering Model for Polarimetric SAR Image Decomposition”, IEEE Trans. Geos. Remote Sens., vol. 43, no. 8, August 2005.
342 """
343
344 allowed_poltypes = ("S", "C3", "T3")
345 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
346 allowed_modes = ["y4o", "y4r", "s4r"]
347 if not mode in allowed_modes:
348 raise ValueError(f"Invalid mode {mode}. Possible values are {allowed_modes}")
349
350 # in_ = input_data.astype("complex64", copy=False)
351 if poltype == "C3":
352 in_ = C3_to_T3(input_data)
353 elif poltype == "T3":
354 in_ = input_data
355 elif poltype == "S":
356 in_ = S_to_T3(input_data)
357
358 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
359 in_ = boxcar(in_, boxcar_size[0], boxcar_size[1])
360
361 # remove NaNs
362 eps = 1e-30
363 mask = in_.to_array().isnull().any("variable")
364 in_ = in_.fillna(eps)
365
366 out = _compute_yamaguchi4_components(in_, mode=mode)
367
368 poltype_out = f"yamaguchi4_{mode.lower()}"
369 return xr.Dataset(
370 # add dimension names
371 {k: (tuple(input_data.dims), v) for k, v in out.items()},
372 attrs=dict(
373 poltype=poltype_out,
374 description=f"Results of the Yamaguchi 4 component decomposition (mode={mode.lower()}).",
375 ),
376 coords=input_data.coords,
377 ).where(~mask)
378
379
380 def tsvm(
381 input_data: xr.Dataset,
382 boxcar_size: list[int, int] = [3, 3],
383 flags: tuple[str] = ("alpha_phi_tau_psi",),
384 ) -> xr.Dataset:
385 """Applies the TSVM decomposition.
386
387 Args:
388 input_data (xr.Dataset): Input image, may be a covariance (C3), coherency (T3) or Sinclair (S) matrix.
389 boxcar_size (list[int, int], optional): Boxcar dimensions along azimuth and range. Defaults to [3, 3].
390 flags (tuple[str], optional): Parameters to compute and return from the decomposition. Possible values include:
391
392 - "alpha_phi_tau_psi": Compute mean values of all output parameters.
393
394 - "alpha", "phi", "tau", "psi": Compute per eigenvalue versions of the parameter.
395
396 Defaults to ("alpha_phi_tau_psi").
397
398 Returns:
399 xr.Dataset: An xarray.Dataset where data variable names depend the requested flags, and values are the corresponding 2D arrays.
400
401 Notes:
402 Output variables have the same names as in the original PolSARpro C version. "alpha_s", "phi_s", "psi", "tau_m" followed by 1, 2 or 3 in the case of per-eigenvalue parameters.
403 """
404 # check flags validity
405
406 if not isinstance(flags, tuple):
407 raise ValueError("'flags' parameter must be a tuple.")
408
409 possible_flags = (
410 "alpha_phi_tau_psi",
411 "alpha",
412 "phi",
413 "tau",
414 "psi",
415 )
416 for flag in flags:
417 if flag not in possible_flags:
418 raise ValueError(
419 f"Flag '{flag}' not recognized. Possible values are {possible_flags}."
420 )
421 allowed_poltypes = ("S", "C3", "T3")
422 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
423
424 if poltype == "S":
425 in_ = S_to_T3(input_data)
426 elif poltype == "C3":
427 in_ = C3_to_T3(input_data)
428 elif poltype == "T3":
429 in_ = input_data
430 else:
431 raise ValueError(f"Invalid polarimetric type: {input_data.poltype}")
432
433 new_dims = tuple(input_data.dims)
434
435 eps = 1e-30
436 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
437 in_ = boxcar(in_, dim_az=boxcar_size[0], dim_rg=boxcar_size[1])
438
439 # remove NaNs to avoid errors in eigh
440 mask = in_.to_array().isnull().any("variable")
441 in_ = in_.fillna(eps)
442
443 M = _reconstruct_matrix_from_ds(in_)
444
445 # eigendecomposition
446 meta = (
447 np.array([], dtype="float32").reshape((0, 0, 0)),
448 np.array([], dtype="complex64").reshape((0, 0, 0, 0)),
449 )
450 l, v = da.apply_gufunc(np.linalg.eigh, "(i,j)->(i), (i,j)", M, meta=meta)
451
452 l = l[..., ::-1] # descending order
453 v = v[..., ::-1]
454
455 out = _compute_tsvm_parameters(l, v, flags)
456
457 return xr.Dataset(
458 # add dimension names, account for 2D and 3D outputs
459 {
460 k: (new_dims, v) if v.ndim == 2 else (new_dims + ("i",), v)
461 for k, v in out.items()
462 },
463 attrs=dict(
464 poltype="tsvm", description="Results of Touzi's TSVM decomposition."
465 ),
466 coords=input_data.coords,
467 ).where(~mask)
468
469
470 def vanzyl(
471 input_data: xr.Dataset,
472 boxcar_size: list[int, int] = [3, 3],
473 ) -> xr.Dataset:
474 """Applies the Van Zyl 1992 3-component decomposition. This decomposition is based on physical modeling
475 of the covariance matrix and returns 3 components Ps, Pd and Pv which are the powers of resp.
476 surface, double bounce and volume backscattering.
477
478 Args:
479 input_data (xr.Dataset): Input image, may be a covariance (C3), coherency (T3) or Sinclair (S) matrix.
480 boxcar_size (list[int, int], optional): Boxcar dimensions along azimuth and range. Defaults to [3, 3].
481
482 Returns:
483 xr.Dataset: Ps, Pd and Pv components.
484
485 References:
486 Jakob J. van Zyl, Yunjin Kim, Synthetic Aperture Radar Polarimetry, Wiley; 1st edition (October 14, 2011), ISBN-10 1-118-11511-2, ISBN-13 978-1118115114
487 """
488
489 allowed_poltypes = ("S", "C3", "T3")
490 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
491
492 # in_ = input_data.astype("complex64", copy=False)
493 if poltype == "C3":
494 in_ = input_data
495 elif poltype == "T3":
496 in_ = T3_to_C3(input_data)
497 elif poltype == "S":
498 in_ = S_to_C3(input_data)
499
500 # pre-processing step, it is recommended to filter the matrices to mitigate speckle effects
501 in_ = boxcar(in_, boxcar_size[0], boxcar_size[1])
502
503 # remove NaNs
504 eps = 1e-30
505 mask = in_.to_array().isnull().any("variable")
506 in_ = in_.fillna(eps)
507
508 out = _compute_vanzyl_components(in_)
509 return xr.Dataset(
510 # add dimension names
511 {k: (tuple(input_data.dims), v) for k, v in out.items()},
512 attrs=dict(
513 poltype="freeman",
514 description="Results of the Freeman-Durden decomposition.",
515 ),
516 coords=input_data.coords,
517 ).where(~mask)
518
519
520 # below this line, functions are not meant to be called directly
521
522
523 def _compute_h_a_alpha_parameters_C2(l, v, flags):
524
525 eps = 1e-30
526
527 # Pseudo-probabilities (normalized eigenvalues)
528 p = np.clip(l / (eps + l.sum(axis=2)[..., None]), eps, 1)
529
530 outputs = {}
531 if "entropy" in flags:
532 H = np.sum(-p * np.log(p), axis=2) / np.float32(np.log(2))
533 outputs["entropy"] = H
534
535 if "anisotropy" in flags:
536 A = (p[..., 0] - p[..., 1]) / (p[..., 0] + p[..., 1] + eps)
537 outputs["anisotropy"] = A
538
539 if "alpha" in flags or "alphas" in flags:
540 # Alpha angles for each mechanism
541 alphas = np.arccos(np.abs(v[:, :, 0, :]))
542 # Convert to degrees
543 alphas *= 180 / np.pi
544
545 if "alpha" in flags:
546 # Mean alpha
547 alpha = np.sum(p * alphas, axis=2)
548 outputs["alpha"] = alpha
549
550 if "delta" in flags or "deltas" in flags:
551 phases = np.atan2(v[:, :, 0, :].imag, eps + v[:, :, 0, :].real)
552 deltas = np.atan2(v[:, :, 1, :].imag, eps + v[:, :, 1, :].real) - phases
553 deltas = np.atan2(np.sin(deltas), eps + np.cos(deltas))
554 deltas *= 180 / np.pi
555
556 if "delta" in flags:
557 delta = np.sum(p * deltas, axis=2)
558 outputs["delta"] = delta
559
560 # Average target eigenvalue
561 if "lambda" in flags or "lambdas" in flags:
562 # lambda is a python reserved keyword, using lambd instead
563 lambd = np.sum(p * l, axis=2)
564 outputs["lambda"] = lambd
565
566 # extras outputs: non averaged parameters (ex: alpha1, alpha2, alpha3)
567 if "alphas" in flags:
568 outputs["alphas"] = alphas
569 if "deltas" in flags:
570 outputs["deltas"] = deltas
571 if "lambdas" in flags:
572 outputs["lambdas"] = l
573 return outputs
574
575
576 def _compute_h_a_alpha_parameters_T3(l, v, flags):
577
578 eps = 1e-30
579
580 # Pseudo-probabilities (normalized eigenvalues)
581 p = np.clip(l / (eps + l.sum(axis=2)[..., None]), eps, 1)
582
583 outputs = {}
584 if "entropy" in flags:
585 H = np.sum(-p * np.log(p), axis=2) / np.float32(np.log(3))
586 outputs["entropy"] = H
587
588 if "anisotropy" in flags:
589 A = (p[..., 1] - p[..., 2]) / (p[..., 1] + p[..., 2] + eps)
590 outputs["anisotropy"] = A
591
592 if "alpha" in flags or "alphas" in flags:
593 # Alpha angles for each mechanism
594 alphas = np.arccos(np.abs(v[:, :, 0, :]))
595 # Convert to degrees
596 alphas *= 180 / np.pi
597
598 if "alpha" in flags:
599 # Mean alpha
600 alpha = np.sum(p * alphas, axis=2)
601 outputs["alpha"] = alpha
602
603 # Extra angles: beta, delta and gamma angles
604 if "beta" in flags or "betas" in flags:
605 betas = np.atan2(np.abs(v[:, :, 2, :]), eps + np.abs(v[:, :, 1, :]))
606 betas *= 180 / np.pi
607
608 if "beta" in flags:
609 beta = np.sum(p * betas, axis=2)
610 outputs["beta"] = beta
611
612 if "delta" in flags or "gamma" in flags or "deltas" in flags or "gammas" in flags:
613 phases = np.atan2(v[:, :, 0, :].imag, eps + v[:, :, 0, :].real)
614
615 if "delta" in flags or "deltas" in flags:
616 deltas = np.atan2(v[:, :, 1, :].imag, eps + v[:, :, 1, :].real) - phases
617 deltas = np.atan2(np.sin(deltas), eps + np.cos(deltas))
618 deltas *= 180 / np.pi
619
620 if "delta" in flags:
621 delta = np.sum(p * deltas, axis=2)
622 outputs["delta"] = delta
623
624 if "gamma" in flags or "gammas" in flags:
625 gammas = np.atan2(v[:, :, 2, :].imag, eps + v[:, :, 2, :].real) - phases
626 gammas = np.atan2(np.sin(gammas), eps + np.cos(gammas))
627 gammas *= 180 / np.pi
628
629 if "gamma" in flags:
630 gamma = np.sum(p * gammas, axis=2)
631 outputs["gamma"] = gamma
632
633 # Average target eigenvalue
634 if "lambda" in flags or "lambdas" in flags:
635 # lambda is a python reserved keyword, using lambd instead
636 lambd = np.sum(p * l, axis=2)
637 outputs["lambda"] = lambd
638
639 # extras outputs: non averaged parameters (ex: alpha1, alpha2, alpha3)
640 if "alphas" in flags:
641 outputs["alphas"] = alphas
642
643 if "betas" in flags:
644 outputs["betas"] = betas
645
646 if "deltas" in flags:
647 outputs["deltas"] = deltas
648
649 if "gammas" in flags:
650 outputs["gammas"] = gammas
651
652 if "lambdas" in flags:
653 outputs["lambdas"] = l
654 return outputs
655
656
657 def _compute_h_a_alpha_parameters_T4(l, v, flags):
658
659 eps = 1e-30
660
661 # Pseudo-probabilities (normalized eigenvalues)
662 p = np.clip(l / (eps + l.sum(axis=2)[..., None]), eps, 1)
663
664 outputs = {}
665 if "entropy" in flags:
666 H = np.sum(-p * np.log(p), axis=2) / np.float32(np.log(4))
667 outputs["entropy"] = H
668
669 if "anisotropy" in flags:
670 A = (p[..., 1] - p[..., 2]) / (p[..., 1] + p[..., 2] + eps)
671 outputs["anisotropy"] = A
672
673 if "alpha" in flags or "alphas" in flags:
674 # Alpha angles for each mechanism
675 alphas = np.arccos(np.abs(v[:, :, 0, :]))
676 # Convert to degrees
677 alphas *= 180 / np.pi
678
679 if "alpha" in flags:
680 # Mean alpha
681 alpha = np.sum(p * alphas, axis=2)
682 outputs["alpha"] = alpha
683
684 # Extra angles: beta, delta and gamma angles
685 if "beta" in flags or "betas" in flags:
686 # betas = np.atan2(np.abs(v[:, :, 2, :]), eps + np.abs(v[:, :, 1, :]))
687 beta_num = np.sqrt(
688 np.real(
689 v[:, :, 2, :] * v[:, :, 2, :].conj()
690 + v[:, :, 3, :] * v[:, :, 3, :].conj()
691 )
692 )
693 betas = np.atan2(beta_num, eps + np.abs(v[:, :, 1, :]))
694 betas *= 180 / np.pi
695
696 if "beta" in flags:
697 beta = np.sum(p * betas, axis=2)
698 outputs["beta"] = beta
699
700 if "epsilon" in flags or "epsilons" in flags:
701 epsilons = np.atan2(np.abs(v[:, :, 3, :]), eps + np.abs(v[:, :, 2, :]))
702 epsilons *= 180 / np.pi
703
704 if "epsilon" in flags:
705 epsilon = np.sum(p * epsilons, axis=2)
706 outputs["epsilon"] = epsilon
707
708 if "delta" in flags or "gamma" in flags or "deltas" in flags or "gammas" in flags:
709 phases = np.atan2(v[:, :, 0, :].imag, eps + v[:, :, 0, :].real)
710
711 if "delta" in flags or "deltas" in flags:
712 deltas = np.atan2(v[:, :, 1, :].imag, eps + v[:, :, 1, :].real) - phases
713 deltas = np.atan2(np.sin(deltas), eps + np.cos(deltas))
714 deltas *= 180 / np.pi
715
716 if "delta" in flags:
717 delta = np.sum(p * deltas, axis=2)
718 outputs["delta"] = delta
719
720 if "gamma" in flags or "gammas" in flags:
721 gammas = np.atan2(v[:, :, 2, :].imag, eps + v[:, :, 2, :].real) - phases
722 gammas = np.atan2(np.sin(gammas), eps + np.cos(gammas))
723 gammas *= 180 / np.pi
724
725 if "gamma" in flags:
726 gamma = np.sum(p * gammas, axis=2)
727 outputs["gamma"] = gamma
728
729 if "nhu" in flags or "nhus" in flags:
730 nhus = np.atan2(v[:, :, 3, :].imag, eps + v[:, :, 3, :].real) - phases
731 nhus = np.atan2(np.sin(nhus), eps + np.cos(nhus))
732 nhus *= 180 / np.pi
733
734 if "nhu" in flags:
735 nhu = np.sum(p * nhus, axis=2)
736 outputs["nhu"] = nhu
737
738 # Average target eigenvalue
739 if "lambda" in flags or "lambdas" in flags:
740 # lambda is a python reserved keyword, using lambd instead
741 lambd = np.sum(p * l, axis=2)
742 outputs["lambda"] = lambd
743
744 # extras outputs: non averaged parameters (ex: alpha1, alpha2, alpha3)
745 if "alphas" in flags:
746 outputs["alphas"] = alphas
747
748 if "betas" in flags:
749 outputs["betas"] = betas
750
751 if "epsilons" in flags:
752 outputs["epsilons"] = epsilons
753
754 if "deltas" in flags:
755 outputs["deltas"] = deltas
756
757 if "gammas" in flags:
758 outputs["gammas"] = gammas
759
760 if "nhus" in flags:
761 outputs["nhus"] = nhus
762
763 if "lambdas" in flags:
764 outputs["lambdas"] = l
765 return outputs
766
767
768 # this is a convenience function to give eigh the right data format
769 def _reconstruct_matrix_from_ds(ds):
770
771 eps = 1e-30
772
773 if {"y", "x"}.issubset(ds.dims):
774 new_dims = ("y", "x")
775 elif {"lat", "lon"}.issubset(ds.dims):
776 new_dims = ("lat", "lon")
777 else:
778 ValueError(
779 "Input data does not have valid dimension names. ('y', 'x') or ('lat', 'lon') allowed."
780 )
781
782 new_dims_array = new_dims + ("i", "j")
783 if ds.poltype == "C2":
784 # build each line of the T3 matrix
785 C2_l1 = xr.concat((ds.m11, ds.m12), dim="j")
786 C2_l2 = xr.concat((ds.m12.conj(), ds.m22), dim="j")
787
788 # Concatenate all lines into a 2x2 matrix
789 return (
790 xr.concat((C2_l1, C2_l2), dim="i")
791 .transpose(*new_dims_array)
792 .chunk({new_dims[0]: "auto", new_dims[1]: "auto", "i": 2, "j": 2})
793 + eps
794 )
795 if ds.poltype == "T3":
796 # build each line of the T3 matrix
797 T3_l1 = xr.concat((ds.m11, ds.m12, ds.m13), dim="j")
798 T3_l2 = xr.concat((ds.m12.conj(), ds.m22, ds.m23), dim="j")
799 T3_l3 = xr.concat((ds.m13.conj(), ds.m23.conj(), ds.m33), dim="j")
800
801 # Concatenate all lines into a 3x3 matrix
802 return (
803 xr.concat((T3_l1, T3_l2, T3_l3), dim="i")
804 .transpose(*new_dims_array)
805 .chunk({new_dims[0]: "auto", new_dims[1]: "auto", "i": 3, "j": 3})
806 + eps
807 )
808 elif ds.poltype == "T4":
809 # build each line of the T4 matrix
810 T4_l1 = xr.concat((ds.m11, ds.m12, ds.m13, ds.m14), dim="j")
811 T4_l2 = xr.concat((ds.m12.conj(), ds.m22, ds.m23, ds.m24), dim="j")
812 T4_l3 = xr.concat((ds.m13.conj(), ds.m23.conj(), ds.m33, ds.m34), dim="j")
813 T4_l4 = xr.concat(
814 (ds.m14.conj(), ds.m24.conj(), ds.m34.conj(), ds.m44), dim="j"
815 )
816
817 # concatenate all lines into a 4x4 matrix
818 return (
819 xr.concat((T4_l1, T4_l2, T4_l3, T4_l4), dim="i")
820 .transpose(*new_dims_array)
821 .chunk({new_dims[0]: "auto", new_dims[1]: "auto", "i": 4, "j": 4})
822 + eps
823 )
824 else:
825 raise NotImplementedError("Implemented only for C2, T3 and T4 poltypes.")
826
827
828 def _compute_freeman_components(C3):
829
830 eps = 1e-30
831
832 # Make copies to avoid modifying original data
833 c11 = C3.m11.data.copy()
834 c13r = C3.m13.data.real.copy()
835 c13i = C3.m13.data.imag.copy()
836 c22 = C3.m22.data.copy()
837 c33 = C3.m33.data.copy()
838
839 fv = 1.5 * c22
840 c11 -= fv
841 c33 -= fv
842 c13r -= fv / 3
843
844 # Volume scattering condition
845 cnd1 = (c11 <= eps) | (c33 <= eps)
846 fv = da.where(cnd1, 3 * (c11 + c22 + c33 + 2 * fv) / 8, fv)
847
848 # Compute c13 power
849 pow_c13 = c13r**2 + c13i**2
850
851 # Data conditioning for non-realizable term
852 cnd2 = ~cnd1 & (pow_c13 > c11 * c33)
853 arg_sqrt = da.maximum(c11 * c33 / da.maximum(pow_c13, eps), 0)
854 scale_factor = da.where(cnd2, da.sqrt(arg_sqrt), 1)
855 c13r *= scale_factor
856 c13i *= scale_factor
857
858 # Recompute after conditioning
859 pow_c13 = c13r**2 + c13i**2
860
861 # Odd bounce dominates
862 cnd3 = ~cnd1 & (c13r >= 0)
863 alpha = da.where(cnd3, da.float32(-1), da.float32(eps))
864 arg_div = c11 + c33 + 2 * c13r
865 arg_div = da.where(arg_div == 0, eps, arg_div)
866 fd = da.where(cnd3, (c11 * c33 - pow_c13) / arg_div, eps)
867 fs = da.where(cnd3, c33 - fd, eps)
868 arg_sqrt = da.maximum((fd + c13r) ** 2 + c13i**2, eps)
869 arg_div = da.where(fs == 0, eps, fs)
870 beta = da.where(cnd3, da.sqrt(arg_sqrt) / arg_div, eps)
871
872 # Even bounce dominates
873 cnd4 = ~cnd1 & (c13r < 0)
874 beta = da.where(cnd4, 1, beta)
875 arg_div = c11 + c33 - 2 * c13r
876 arg_div = da.where(arg_div == 0, eps, arg_div)
877 fs = da.where(cnd4, (c11 * c33 - pow_c13) / arg_div, fs)
878 fd = da.where(cnd4, c33 - fs, fd)
879 arg_sqrt = da.maximum((fs - c13r) ** 2 + c13i**2, eps)
880 arg_div = da.where(fd == 0, eps, fd)
881 alpha = da.where(cnd4, da.sqrt(arg_sqrt) / arg_div, alpha)
882
883 # Compute Freeman components
884 Ps = fs * (1 + beta**2)
885 Pd = fd * (1 + alpha**2)
886 Pv = 8 * fv / 3
887
888 # Compute span on __original__ covariance, not modified one
889 sp = C3.m11.data + C3.m22.data + C3.m33.data
890 min_span, max_span = da.nanmin(sp), da.nanmax(sp)
891 min_span = da.maximum(min_span, eps)
892
893 Ps = da.where(Ps <= min_span, min_span, da.where(Ps > max_span, max_span, Ps))
894 Pd = da.where(Pd <= min_span, min_span, da.where(Pd > max_span, max_span, Pd))
895 Pv = da.where(Pv <= min_span, min_span, da.where(Pv > max_span, max_span, Pv))
896 return {"odd": Ps, "double": Pd, "volume": Pv}
897
898
899 def _compute_yamaguchi3_components(C3):
900
901 eps = 1e-30
902
903 # Make copies to avoid modifying original data
904 c11 = C3.m11.data.copy()
905 c13r = C3.m13.data.real.copy()
906 c13i = C3.m13.data.imag.copy()
907 c22 = C3.m22.data.copy()
908 c33 = C3.m33.data.copy()
909
910 # Freeman-Yamaguchi algorithm
911 num = np.where(c33 != 0, c33, eps)
912 den = np.where(c11 != 0, c11, eps)
913 ratio = 10.0 * da.log10(num / den)
914 msk_l = ratio <= -2
915 msk_h = ratio > 2
916 msk_m = (ratio > -2) & (ratio <= 2)
917
918 fv = da.where(msk_m, 2 * c22, 15 * c22 / 8)
919 c13r = da.where(msk_m, c13r - fv / 8, c13r - 2 * fv / 15)
920
921 c11 = da.where(msk_l, c11 - 8 * fv / 15, c11)
922 c33 = da.where(msk_l, c33 - 3 * fv / 15, c33)
923
924 c11 = da.where(msk_h, c11 - 3 * fv / 15, c11)
925 c33 = da.where(msk_h, c33 - 8 * fv / 15, c33)
926
927 c11 = da.where(msk_m, c11 - 3 * fv / 8, c11)
928 c33 = da.where(msk_m, c33 - 3 * fv / 8, c33)
929
930 # Volume scattering condition
931 cnd1 = (c11 <= eps) | (c33 <= eps)
932 fv = da.where(cnd1 & msk_m, c11 + 3 * fv / 8 + c22 / 2 + c33 + 3 * fv / 8, fv)
933 fv = da.where(cnd1 & msk_l, c11 + 8 * fv / 15 + c22 / 2 + c33 + 3 * fv / 15, fv)
934 fv = da.where(cnd1 & msk_h, c11 + 3 * fv / 15 + c22 / 2 + c33 + 8 * fv / 15, fv)
935
936 # Compute c13 power
937 pow_c13 = c13r**2 + c13i**2
938
939 # Data conditioning for non-realizable term
940 cnd2 = ~cnd1 & (pow_c13 > c11 * c33)
941 arg_sqrt = da.maximum(c11 * c33 / da.maximum(pow_c13, eps), 0)
942 scale_factor = da.where(cnd2, da.sqrt(arg_sqrt), 1)
943 c13r *= scale_factor
944 c13i *= scale_factor
945
946 # Recompute after conditioning
947 pow_c13 = c13r**2 + c13i**2
948
949 # Odd bounce dominates
950 cnd3 = ~cnd1 & (c13r >= 0)
951 alpha = da.where(
952 cnd3, da.float32(-1) + 1j * da.float32(0), da.float32(eps) + 1j * da.float32(0)
953 )
954 arg_div = c11 + c33 + 2 * c13r
955 arg_div = da.where(arg_div == 0, eps, arg_div)
956 fd = da.where(cnd3, (c11 * c33 - pow_c13) / arg_div, eps)
957 fs = da.where(cnd3, c33 - fd, eps)
958 arg_div = da.where(fs == 0, eps, fs)
959 beta = da.where(cnd3, (fd + c13r + 1j * c13i) / arg_div, eps)
960
961 # Even bounce dominates
962 cnd4 = ~cnd1 & (c13r < 0)
963 beta = da.where(cnd4, 1 + 1j * 0, beta)
964 arg_div = c11 + c33 - 2 * c13r
965 arg_div = da.where(arg_div == 0, eps, arg_div)
966 fs = da.where(cnd4, (c11 * c33 - pow_c13) / arg_div, fs)
967 fd = da.where(cnd4, c33 - fs, fd)
968 arg_div = da.where(fd == 0, eps, fd)
969 alpha = da.where(cnd4, (c13r - fs + 1j * c13i) / arg_div, alpha)
970
971 # Compute Freeman components
972 Ps = fs * (1 + beta.real**2 + beta.imag**2)
973 Pd = fd * (1 + alpha.real**2 + alpha.imag**2)
974 Pv = fv
975
976 # Compute span on __original__ covariance, not modified one
977 sp = C3.m11.data + C3.m22.data + C3.m33.data
978 min_span, max_span = da.nanmin(sp), da.nanmax(sp)
979 min_span = da.maximum(min_span, eps)
980
981 Ps = da.where(Ps <= min_span, min_span, da.where(Ps > max_span, max_span, Ps))
982 Pd = da.where(Pd <= min_span, min_span, da.where(Pd > max_span, max_span, Pd))
983 Pv = da.where(Pv <= min_span, min_span, da.where(Pv > max_span, max_span, Pv))
984 return {"odd": Ps, "double": Pd, "volume": Pv}
985
986
987 def _compute_yamaguchi4_components(T3, mode="y4o"):
988
989 eps = 1e-30
990
991 span = T3.m11.data + T3.m22.data + T3.m33.data
992 min_span = span.min()
993 min_span = da.where(min_span > eps, min_span, eps)
994 max_span = span.max()
995
996 # Apply unitary rotation for corresponding modes
997 if mode in ["y4r", "s4r"]:
998 theta = 0.5 * da.arctan(
999 (2 * T3.m23.data.real + eps) / (T3.m22.data - T3.m33.data + eps)
1000 )
1001 T3_new = _unitary_rotation(T3, theta)
1002 else:
1003 T3_new = T3.copy(deep=True)
1004
1005 T11 = T3_new.m11.data
1006 T22 = T3_new.m22.data
1007 T33 = T3_new.m33.data
1008
1009 T12 = T3_new.m12.data
1010 T13 = T3_new.m13.data
1011 T23 = T3_new.m23.data
1012
1013 Pc = 2 * da.abs(T23.imag)
1014
1015 # Surface scattering
1016 hv_type = da.ones_like(T11, dtype="uint8")
1017
1018 if mode == "s4r":
1019 C1 = T11 - T22 + (7 / 8) * T33 + Pc / 16
1020 hv_type = da.where(C1 > 0, 1, 2)
1021
1022 # Surface scattering
1023 num = T11 + T22 - 2 * T12.real
1024 den = T11 + T22 + 2 * T12.real
1025 num = da.where(num != 0, num, eps)
1026 den = da.where(den != 0, den, eps)
1027 ratio = 10 * da.log10(num / den)
1028
1029 # ratio = 10 * da.log10((T11 + T22 - 2 * T12.real + eps) / (T11 + T22 + 2 * T12.real + eps))
1030 cnd = hv_type == 1
1031 cnd_ratio = (ratio > -2) & (ratio <= 2)
1032 Pv = da.where(
1033 cnd,
1034 da.where(cnd_ratio, np.float32(2), np.float32(15 / 8)) * (2 * T33 - Pc),
1035 np.float32(eps),
1036 )
1037
1038 # Double bounce scattering
1039 Pv = da.where(hv_type == 2, (15 / 16) * (2 * T33 - Pc), Pv)
1040
1041 mask_v = Pv >= 0
1042 TP = T11 + T22 + T33
1043
1044 # 4 component algorithm
1045
1046 # Expression used in both surface and double cases
1047 C = T12 + T13
1048
1049 # Surface scattering
1050 cnd_hv = hv_type == 1
1051 S = da.where(cnd_hv, T11 - Pv / 2, eps)
1052 D = da.where(cnd_hv, TP - Pv - Pc - S, eps)
1053 C = da.where(cnd_hv & (ratio <= -2), C - Pv / 6, C)
1054 C = da.where(cnd_hv & (ratio > 2), C + Pv / 6, C)
1055 C_pow = C.real**2 + C.imag**2
1056
1057 cnd_tp = (Pv + Pc) > TP
1058 Pv = da.where(cnd_hv & cnd_tp, TP - Pc, Pv)
1059 cnd_c0 = (2 * T11 + Pc - TP) > 0
1060
1061 S = da.where(S != 0, S, eps)
1062 D = da.where(D != 0, D, eps)
1063 Ps = da.where(cnd_hv & ~cnd_tp, da.where(cnd_c0, S + C_pow / S, S - C_pow / D), eps)
1064 Pd = da.where(cnd_hv & ~cnd_tp, da.where(cnd_c0, D - C_pow / S, D + C_pow / D), eps)
1065
1066 # Double bounce scattering
1067 cnd_hv = hv_type == 2
1068 S = da.where(cnd_hv, T11, S)
1069 D = da.where(cnd_hv, TP - Pv - Pc - S, D)
1070 D = da.where(D != 0, D, eps)
1071 Pd = da.where(cnd_hv, D + C_pow / D, Pd)
1072 Ps = da.where(cnd_hv, S - C_pow / D, Ps)
1073
1074 cnd_ps = Ps < 0
1075 cnd_pd = Pd < 0
1076
1077 # Corrections apply for both surface and double
1078 both_neg = cnd_ps & cnd_pd
1079 ps_neg = cnd_ps & ~cnd_pd
1080 pd_neg = ~cnd_ps & cnd_pd
1081
1082 Ps = da.where(both_neg, 0, Ps)
1083 Pd = da.where(both_neg, 0, Pd)
1084 Pv = da.where(both_neg, TP - Pc, Pv)
1085
1086 Ps = da.where(ps_neg, 0, Ps)
1087 Pd = da.where(ps_neg, TP - Pv - Pc, Pd)
1088
1089 Pd = da.where(pd_neg, 0, Pd)
1090 Ps = da.where(pd_neg, TP - Pv - Pc, Ps)
1091
1092 Ps = da.where(Ps <= min_span, min_span, da.where(Ps > max_span, max_span, Ps))
1093 Pd = da.where(Pd <= min_span, min_span, da.where(Pd > max_span, max_span, Pd))
1094 Pv = da.where(Pv <= min_span, min_span, da.where(Pv > max_span, max_span, Pv))
1095 Pc = da.where(Pc <= min_span, min_span, da.where(Pc > max_span, max_span, Pc))
1096
1097 # If Pv < 0 use three components and set Pc to 0
1098 out_3comp = _compute_yamaguchi3_components(T3_to_C3(T3_new))
1099 Ps = da.where(mask_v, Ps, out_3comp["odd"])
1100 Pd = da.where(mask_v, Pd, out_3comp["double"])
1101 Pv = da.where(mask_v, Pv, out_3comp["volume"])
1102 Pc = da.where(mask_v, Pc, 0)
1103 out = {
1104 "odd": Ps,
1105 "double": Pd,
1106 "volume": Pv,
1107 "helix": Pc,
1108 }
1109 return out
1110
1111
1112 def _compute_tsvm_parameters(l, v, flags):
1113
1114 eps = 1e-30
1115
1116 # Pseudo-probabilities (normalized eigenvalues)
1117 p = np.clip(l / (eps + l.sum(axis=2)[..., None]), eps, 1)
1118
1119 outputs = {}
1120
1121 # --- Psi parameters
1122 phases = np.atan2(v[:, :, 0, :].imag, eps + v[:, :, 0, :].real)
1123 # Rotation factor e^{-i phase} with shape (M, N, K)
1124 rot = np.exp(-1j * phases)
1125 v *= rot[..., None, :]
1126 psis = 0.5 * np.atan2(v[:, :, 2, :].real, eps + v[:, :, 1, :].real)
1127
1128 # --- Tau and Phi parameters
1129 z1 = v[:, :, 1, :].copy()
1130 z2 = v[:, :, 2, :].copy()
1131
1132 c = np.cos(2 * psis)
1133 s = np.sin(2 * psis)
1134
1135 v[:, :, 1, :] = z1 * c + z2 * s
1136 v[:, :, 2, :] = z2 * c - z1 * s
1137
1138 taus = 0.5 * np.atan2(-v[:, :, 2, :].imag, eps + v[:, :, 0, :].real)
1139 phis = np.atan2(v[:, :, 1, :].imag, eps + v[:, :, 1, :].real)
1140
1141 # --- Alpha parameters
1142 z1 = v[:, :, 0, :].copy()
1143 z2 = v[:, :, 2, :].copy()
1144
1145 c = np.cos(2 * taus)
1146 s = np.sin(2 * taus)
1147
1148 v[:, :, 0, :] = z1 * c + 1j * z2 * s
1149 v[:, :, 2, :] = z2 * c + 1j * z1 * s
1150
1151 alphas = np.arccos(v[:, :, 0, :].real)
1152
1153 taus = np.where((psis < -np.pi / 4) | (psis > np.pi / 4), -taus, taus)
1154 phis = np.where((psis < -np.pi / 4) | (psis > np.pi / 4), -phis, phis)
1155
1156 # Convert to degrees
1157 # for it in [psis, taus, phis, alphas]:
1158 # for it in [psis, taus, phis]:
1159 # for it in [psis]:
1160 # it *= 180 / np.pi
1161
1162 alphas *= 180 / np.pi
1163 phis *= 180 / np.pi
1164 taus *= 180 / np.pi
1165 psis *= 180 / np.pi
1166
1167 # Default flag: compute mean parameters
1168 if "alpha_phi_tau_psi" in flags:
1169 alpha = np.sum(p * alphas, axis=2)
1170 phi = np.sum(p * phis, axis=2)
1171 tau = np.sum(p * taus, axis=2)
1172 psi = np.sum(p * psis, axis=2)
1173 outputs["alpha_s"] = alpha
1174 outputs["phi_s"] = phi
1175 outputs["tau_m"] = tau
1176 outputs["psi"] = psi
1177
1178 # Extra outputs: non averaged parameters (ex: alpha1, alpha2, alpha3)
1179 if "alpha" in flags:
1180 outputs["alpha_s1"] = alphas[..., 0]
1181 outputs["alpha_s2"] = alphas[..., 1]
1182 outputs["alpha_s3"] = alphas[..., 2]
1183
1184 if "phi" in flags:
1185 outputs["phi_s1"] = phis[..., 0]
1186 outputs["phi_s2"] = phis[..., 1]
1187 outputs["phi_s3"] = phis[..., 2]
1188
1189 if "tau" in flags:
1190 outputs["tau_m1"] = taus[..., 0]
1191 outputs["tau_m2"] = taus[..., 1]
1192 outputs["tau_m3"] = taus[..., 2]
1193
1194 if "psi" in flags:
1195 outputs["psi1"] = psis[..., 0]
1196 outputs["psi2"] = psis[..., 1]
1197 outputs["psi3"] = psis[..., 2]
1198
1199 return outputs
1200
1201
1202 def _unitary_rotation(T3, theta):
1203
1204 T3_out = {}
1205
1206 cos_t = np.cos(theta)
1207 sin_t = np.sin(theta)
1208
1209 T11 = T3.m11.data.copy()
1210 T22 = T3.m22.data.copy()
1211 T33 = T3.m33.data.copy()
1212 # Decompose into real/imag
1213 T12_re, T12_im = da.real(T3.m12.data), da.imag(T3.m12.data)
1214 T13_re, T13_im = da.real(T3.m13.data), da.imag(T3.m13.data)
1215 T23_re, T23_im = da.real(T3.m23.data), da.imag(T3.m23.data)
1216
1217 # --- Rotation ---
1218 T11_new = T11
1219 T12_re_new = T12_re * cos_t + T13_re * sin_t
1220 T12_im_new = T12_im * cos_t + T13_im * sin_t
1221 T13_re_new = -T12_re * sin_t + T13_re * cos_t
1222 T13_im_new = -T12_im * sin_t + T13_im * cos_t
1223
1224 T22_new = T22 * cos_t**2 + 2.0 * T23_re * cos_t * sin_t + T33 * sin_t**2
1225 T23_re_new = (
1226 -T22 * cos_t * sin_t + T23_re * (cos_t**2 - sin_t**2) + T33 * cos_t * sin_t
1227 )
1228 T23_im_new = T23_im * (cos_t**2 + sin_t**2)
1229 T33_new = T22 * sin_t**2 + T33 * cos_t**2 - 2.0 * T23_re * cos_t * sin_t
1230
1231 # Recombine
1232 T3_out["m11"] = T11_new
1233 T3_out["m22"] = T22_new
1234 T3_out["m33"] = T33_new
1235 T3_out["m12"] = T12_re_new + 1j * T12_im_new
1236 T3_out["m13"] = T13_re_new + 1j * T13_im_new
1237 T3_out["m23"] = T23_re_new + 1j * T23_im_new
1238
1239 attrs = {"poltype": "T3", "description": "Coherency matrix (3x3)"}
1240 return xr.Dataset({k: (tuple(T3.dims), v) for k, v in T3_out.items()}, attrs=attrs)
1241
1242
1243 def _compute_vanzyl_components(C3):
1244
1245 # use larger eps to avoid overflow in square
1246 eps = 1e-15
1247
1248 HHHH = C3.m11.data
1249 HHVV = C3.m13.data
1250 HVHV = C3.m22.data / 2
1251 VVVV = C3.m33.data
1252
1253 # pre-compute some factors
1254 pow_HHVV = (HHVV * HHVV.conj()).real
1255 det = da.sqrt((HHHH - VVVV) ** 2 + 4 * pow_HHVV + eps)
1256
1257 factor1 = VVVV - HHHH + det
1258 factor2 = VVVV - HHHH - det
1259
1260 lambda1 = 0.5 * (HHHH + VVVV + det)
1261 lambda2 = 0.5 * (HHHH + VVVV - det)
1262
1263 alpha = 2 * HHVV / (factor1 + eps)
1264 beta = 2 * HHVV / (factor2 + eps)
1265
1266 omega1 = (lambda1 * factor1**2) / (factor1**2 + 4 * pow_HHVV + eps)
1267 omega2 = (lambda2 * factor2**2) / (factor2**2 + 4 * pow_HHVV + eps)
1268
1269 # target generator
1270 A0A0 = omega1 * ((1 + alpha.real) ** 2 + alpha.imag**2)
1271 B0Bp = omega1 * ((1 - alpha.real) ** 2 + alpha.imag**2)
1272
1273 Ps = da.where(
1274 A0A0 > B0Bp,
1275 omega1 * (1 + (alpha * alpha.conj()).real),
1276 omega2 * (1 + (beta * beta.conj()).real),
1277 )
1278 Pd = da.where(
1279 A0A0 > B0Bp,
1280 omega2 * (1 + (beta * beta.conj()).real),
1281 omega1 * (1 + (alpha * alpha.conj()).real),
1282 )
1283 Pv = 2 * HVHV
1284
1285 # compute span
1286 sp = C3.m11.data + C3.m22.data + C3.m33.data
1287 min_span, max_span = da.nanmin(sp), da.nanmax(sp)
1288 min_span = da.maximum(min_span, eps)
1289
1290 Ps = da.where(Ps <= min_span, min_span, da.where(Ps > max_span, max_span, Ps))
1291 Pd = da.where(Pd <= min_span, min_span, da.where(Pd > max_span, max_span, Pd))
1292 Pv = da.where(Pv <= min_span, min_span, da.where(Pv > max_span, max_span, Pv))
1293 return {"odd": Ps, "double": Pd, "volume": Pv}
1294
1295
1296 def _compute_cameron(S):
1297 eps = 1e-30
1298 Shh = S.hh.data
1299 Svv = S.vv.data
1300 Shv = 0.5 * (S.hv.data + S.vh.data)
1301
1302 r2 = da.sqrt(2)
1303
1304 alpha = (Shh + Svv) / r2
1305 beta = (Shh - Svv) / r2
1306 gamma = Shv * r2
1307
1308 pow_alpha = (alpha * alpha.conj()).real
1309 pow_beta = (beta * beta.conj()).real
1310 pow_gamma = (gamma * gamma.conj()).real
1311
1312 real = 2 * (beta.real * gamma.real + beta.imag * gamma.imag)
1313 diff_abs = pow_beta - pow_gamma
1314
1315 tol = (pow_alpha + pow_beta + pow_gamma) * eps
1316
1317 # magnitude used several times
1318 den = da.sqrt(real**2 + diff_abs**2)
1319 den = da.where(den > eps, den, eps)
1320
1321 # primary condition
1322 is_zero = (da.fabs(real) < tol) & (da.fabs(diff_abs) < tol)
1323
1324 sin_xi = real / den
1325 cos_xi = diff_abs / den
1326
1327 # angle when not zero
1328 xi_nonzero = da.where(
1329 cos_xi > 0,
1330 da.arcsin(sin_xi),
1331 da.pi - da.arcsin(sin_xi),
1332 )
1333
1334 # final Xi
1335 xi = da.where(is_zero, 0.0, xi_nonzero)
1336
1337 c = da.cos(xi / 2.0)
1338 s = da.sin(xi / 2.0)
1339
1340 epsilon = (1.0 / r2) * (c * (Shh - Svv) + s * 2.0 * Shv)
1341
1342 SMhh = (1.0 / r2) * (alpha + c * epsilon)
1343 SMvv = (1.0 / r2) * (alpha - c * epsilon)
1344 SMhv = (1.0 / r2) * (s * epsilon)
1345
1346 psi_max = -xi / 4.0
1347
1348 # norms of S and SM
1349 norm_S = da.sqrt(da.abs(Shh) ** 2 + 2.0 * da.abs(Shv) ** 2 + da.abs(Svv) ** 2)
1350 norm_SM = da.sqrt(da.abs(SMhh) ** 2 + 2.0 * da.abs(SMhv) ** 2 + da.abs(SMvv) ** 2)
1351 norm = norm_S * norm_SM
1352 norm = da.where(norm > eps, norm, eps)
1353
1354 # complex scalar product <S, SM>
1355 prod = Shh * da.conj(SMhh) + 2.0 * Shv * da.conj(SMhv) + Svv * da.conj(SMvv)
1356
1357 # avoid invalid values in arccos
1358 arg_acos = da.clip(da.abs(prod) / norm, -1, 1)
1359 # angle tau
1360 tau = da.arccos(arg_acos)
1361
1362 # --- case tau < pi/8
1363 cp = np.cos(psi_max)
1364 sp = np.sin(psi_max)
1365 s2p = np.sin(2 * psi_max)
1366
1367 ssm1 = cp**2 * SMhh - s2p * Shv + sp**2 * SMvv
1368 ssm2 = sp**2 * SMhh + s2p * Shv + cp**2 * SMvv
1369
1370 pow_ssm1 = da.real(ssm1 * ssm1.conj())
1371 pow_ssm2 = da.real(ssm2 * ssm2.conj())
1372
1373 cnd1 = pow_ssm1 >= pow_ssm2
1374
1375 z = da.where(
1376 cnd1,
1377 ssm2 * da.conj(ssm1) / pow_ssm1,
1378 ssm1 * da.conj(ssm2) / pow_ssm2,
1379 )
1380
1381 psi_max = da.where(cnd1, psi_max, psi_max + da.pi / 2.0)
1382 psi_max = da.fmod(psi_max, 2.0 * da.pi)
1383
1384 zr = z.real
1385 zi = z.imag
1386 pow_z = da.real(z * z.conj())
1387 den2 = 1.0 + pow_z
1388
1389 plane = da.sqrt((1 + zr) ** 2 + zi**2) / da.sqrt(2 * den2)
1390 dihedral = da.sqrt((1 - zr) ** 2 + zi**2) / da.sqrt(2 * den2)
1391 dipole = 1.0 / da.sqrt(den2)
1392 cylinder = da.sqrt((1 - zr / 2) ** 2 + zi**2 / 4) / da.sqrt(5 / 4 * den2)
1393 narrow_dip = da.sqrt((1 + zr / 2) ** 2 + zi**2 / 4) / da.sqrt(5 / 4 * den2)
1394 quartp = da.sqrt((1 + zi) ** 2 + zr**2) / da.sqrt(2 * den2)
1395 quartm = da.sqrt((1 - zi) ** 2 + zr**2) / da.sqrt(2 * den2)
1396
1397 # mechanism classification
1398 stack = da.stack(
1399 [
1400 plane,
1401 dihedral,
1402 dipole,
1403 cylinder,
1404 narrow_dip,
1405 da.maximum(quartp, quartm),
1406 ]
1407 )
1408
1409 cls_tau = da.argmax(stack, axis=0) + 1
1410 cls_tau = cls_tau.astype(da.int32)
1411
1412 # --- case where tau >= pi/8
1413
1414 norm_S = da.where(norm_S > eps, norm_S, eps)
1415
1416 p_r = Shh.real + 2 * Shv.imag - Svv.real
1417 p_i = -Shh.imag + 2 * Shv.real - Svv.imag
1418 c_hel_g = da.sqrt(p_r**2 + p_i**2) / (2 * norm_S)
1419
1420 p_r = Shh.real - 2 * Shv.imag - Svv.real
1421 p_i = -Shh.imag - 2 * Shv.real - Svv.imag
1422 c_hel_d = da.sqrt(p_r**2 + p_i**2) / (2 * norm_S)
1423
1424 cls_hel = da.where(c_hel_g > c_hel_d, da.int32(7), da.int32(8))
1425
1426 # --- combining the two possible cases
1427
1428 out = da.zeros_like(cls_tau, dtype=da.int32)
1429 mask_tau = tau < (da.pi / 8.0)
1430 out = da.where(mask_tau, cls_tau, cls_hel)
1431
1432 return {"cameron": out}