Debian Codegraph @

polsarpro/physical_inversion.py

raw
1 """
2 This code is part of the Python PolSARpro software:
3
4 "A re-implementation of selected PolSARPro functions in Python,
5 following the scientific recommendations of PolInSAR 2021"
6
7 developed within an ESA funded project with SATIM.
8
9 Author: Olivier D'Hondt, 2026.
10 Scientific advisors: Armando Marino and Eric Pottier.
11
12 Licensed under the Apache License, Version 2.0 (the "License");
13 you may not use this file except in compliance with the License.
14 You may obtain a copy of the License at
15
16 http://www.apache.org/licenses/LICENSE-2.0
17
18 Unless required by applicable law or agreed to in writing, software
19 distributed under the License is distributed on an "AS IS" BASIS,
20 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 See the License for the specific language governing permissions and
22 limitations under the License.
23
24 -----
25
26 # Description: module containing physical inversion functions
27
28 """
29 import dask.array as da
30 import numpy as np
31 import xarray as xr
32
33 from polsarpro.auxil import validate_dataset
34 from polsarpro.util import C4_to_C3, S_to_C3, T3_to_C3, T4_to_C3
35
36
37 def dubois_surface_inversion(
38 input_data: xr.Dataset,
39 incidence_angle: xr.DataArray,
40 freq_ghz: float,
41 thresh1: float,
42 thresh2: float,
43 calibration_coeff: float | None = None,
44 ) -> xr.Dataset:
45 """Run the Dubois surface inversion on a PolSAR covariance dataset.
46
47 The function accepts a single-scattering input product in any of the
48 supported polarimetric representations, converts it to C3 form when
49 needed, and applies the Dubois empirical model using the supplied
50 incidence-angle raster.
51
52 Args:
53 input_data (xr.Dataset): Input polarimetric dataset. Supported
54 products are:
55
56 - "S": Sinclair scattering matrix
57
58 - "C3": Lexicographic covariance matrix (3x3)
59
60 - "T3": Pauli coherency matrix (3x3)
61
62 - "C4": 4x4 covariance matrix
63
64 - "T4": 4x4 coherency matrix
65
66 The dataset must share the same spatial grid as
67 ``incidence_angle``.
68 incidence_angle (xr.DataArray): Incidence angle raster in radians.
69 Values must be numeric and in the range ``(0, pi/2)``.
70 freq_ghz (float): Radar center frequency in GHz.
71 thresh1 (float): Maximum allowed ``HV / VV`` ratio in dB for the
72 Dubois validity mask.
73 thresh2 (float): Maximum allowed ``HH / VV`` ratio in dB for the
74 Dubois validity mask.
75 calibration_coeff (float or None, optional): Optional multiplicative
76 calibration coefficient. When provided, the HH, VV, and HV
77 channels are scaled by ``sin(theta) / calibration_coeff`` before
78 the inversion is applied. Defaults to None.
79
80 Returns:
81 xr.Dataset: Dataset containing the Dubois estimates and masks:
82 ``dubois_ks`` (surface roughness parameter), ``dubois_er``
83 (relative dielectric constant), ``dubois_mv`` (volumetric moisture
84 estimate), ``dubois_mask_in`` (input validity mask),
85 ``dubois_mask_out`` (model validity mask), and
86 ``dubois_mask_valid_in_out`` (combined mask).
87
88 Notes:
89 The returned dataset preserves the input coordinates and uses the
90 input spatial dimensions. Output variables are stored as ``float32``
91 arrays.
92 """
93 if not isinstance(incidence_angle, xr.DataArray):
94 raise TypeError("incidence_angle must be an xarray.DataArray.")
95 if not np.issubdtype(incidence_angle.dtype, np.number):
96 raise TypeError("incidence_angle must contain numeric values.")
97
98 if not isinstance(freq_ghz, (int, float, np.number)):
99 raise TypeError(f"freq_ghz must be a number, got {type(freq_ghz).__name__}.")
100 if freq_ghz <= 0:
101 raise ValueError(f"freg_ghz must be strictly positive, got {freq_ghz}.")
102
103 if not isinstance(thresh1, (int, float, np.number)):
104 raise TypeError(f"thresh1 must be a number, got {type(thresh1).__name__}.")
105 if not isinstance(thresh2, (int, float, np.number)):
106 raise TypeError(f"thresh2 must be a number, got {type(thresh2).__name__}.")
107
108 if calibration_coeff is not None:
109 if not isinstance(calibration_coeff, (int, float, np.number)):
110 raise TypeError(
111 "calibration_coeff must be a number or None, "
112 f"got {type(calibration_coeff).__name__}."
113 )
114 if calibration_coeff <= 0:
115 raise ValueError(
116 f"calibration_coeff must be strictly positive, got {calibration_coeff}."
117 )
118
119 allowed_poltypes = ("S", "C3", "T3", "C4", "T4")
120 poltype = validate_dataset(input_data, allowed_poltypes=allowed_poltypes)
121
122 converters = {
123 "C3": lambda ds: ds,
124 "T3": T3_to_C3,
125 "C4": C4_to_C3,
126 "T4": T4_to_C3,
127 "S": S_to_C3,
128 }
129 C3 = converters[poltype](input_data)
130
131 out = _apply_dubois_inversion(
132 theta=incidence_angle,
133 f0=freq_ghz,
134 hh=C3.m11,
135 vv=C3.m33,
136 hv=C3.m22 / 2.0,
137 calib=calibration_coeff,
138 thresh1=thresh1,
139 thresh2=thresh2,
140 )
141 original_non_nan_mask = input_data.to_array().notnull().all("variable")
142 out["dubois_mask_valid_in_out"] = (
143 out["dubois_mask_in"]
144 * out["dubois_mask_out"]
145 * original_non_nan_mask.astype(np.float32, copy=False)
146 ).astype(np.float32, copy=False)
147
148 return xr.Dataset(
149 {k: (tuple(input_data.dims), v.data) for k, v in out.items()},
150 attrs={
151 "poltype": "dubois_surface_inversion",
152 "description": "Results of the Dubois surface inversion.",
153 },
154 coords=input_data.coords,
155 )
156
157
158 # helper function, do not use directly
159 def _apply_dubois_inversion(theta, f0, hh, vv, hv, calib, thresh1, thresh2):
160
161 scale = np.sin(theta) / calib if calib is not None else 1.0
162 hh = hh * scale
163 vv = vv * scale
164 hv = hv * scale
165
166 lambd = 100 * 0.3 / f0
167 eps = np.finfo(np.float32).eps
168
169 theta_valid = np.isfinite(theta) & (theta > 0) & (theta < (np.pi / 2.0))
170 hh_pos = hh > 0
171 vv_pos = vv > 0
172 base_valid = theta_valid & hh_pos & vv_pos
173
174 vv_safe = xr.where(vv_pos, vv, 1.0)
175 hh_safe = xr.where(hh_pos, hh, 1.0)
176 theta_safe = xr.where(theta_valid, theta, 1.0)
177
178 msk_valid = (
179 base_valid
180 & (hv / vv_safe < 10 ** (thresh1 / 10.0))
181 & (hh / vv_safe < 10 ** (thresh2 / 10.0))
182 )
183
184 ks_inv = np.exp(
185 1.36905 * np.log(hh_safe)
186 - 0.83333 * np.log(vv_safe)
187 + 0.446425 * np.log(np.cos(theta_safe))
188 + 3.34525 * np.log(np.sin(theta_safe))
189 - 0.375 * np.log(lambd)
190 + 1.78989 * np.log(10)
191 )
192 msk_ks = base_valid & (ks_inv >= 0) & (ks_inv <= np.pi)
193 ks_dub = xr.where(msk_valid & msk_ks, ks_inv, 0.0)
194
195 ks_safe = xr.where(ks_dub > 0, ks_dub, np.nan)
196 er_inv = (
197 np.log10(hh_safe)
198 + np.log10(vv_safe)
199 + 5.12
200 + np.log10(np.cos(theta_safe))
201 - 2.5 * np.log10(ks_safe + eps)
202 - 1.4 * np.log10(lambd)
203 ) / (0.074 * np.tan(theta_safe) + eps)
204 msk_er = base_valid & (er_inv > 0) & (er_inv <= 100)
205 er_dub = xr.where(msk_valid & msk_ks & msk_er, er_inv, 0.0)
206
207 er_safe = xr.where(er_dub > 0, er_dub, np.nan)
208 mv_inv = (
209 -5.3e-2 + 2.92e-2 * er_safe - 5.5e-4 * er_safe**2 + 4.3e-6 * er_safe**3
210 ) * 100
211 msk_mv = base_valid & (mv_inv > 0) & (mv_inv <= 100)
212 mv_dub = xr.where(msk_valid & msk_ks & msk_er & msk_mv, mv_inv, 0.0)
213
214 msk_out = (msk_valid & msk_ks & msk_er & msk_mv).astype(np.float32)
215
216 return {
217 "dubois_ks": ks_dub.astype(np.float32, copy=False),
218 "dubois_er": er_dub.astype(np.float32, copy=False),
219 "dubois_mv": mv_dub.astype(np.float32, copy=False),
220 "dubois_mask_out": msk_out.astype(np.float32, copy=False),
221 "dubois_mask_in": msk_valid.astype(np.float32, copy=False),
222 }