Debian Codegraph @

polsarpro/auxil.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 auxiliary helper functions
27
28 """
29
30 from typing import Sequence
31
32 import numpy as np
33 import xarray as xr
34
35 # Standardized required variables for each poltype
36 POLTYPES = {
37 "S": {
38 "description": "Scattering matrix",
39 "vars": {
40 "hh": {"dtype": "complex64"},
41 "hv": {"dtype": "complex64"},
42 "vh": {"dtype": "complex64"},
43 "vv": {"dtype": "complex64"},
44 },
45 # for some data, (e.g. H/A/Alpha) variables may not be required by default
46 "optional_vars": None,
47 },
48 "C2": {
49 "description": "Covariance matrix (2x2)",
50 "vars": {
51 "m11": {"dtype": "float32"},
52 "m12": {"dtype": "complex64"},
53 "m22": {"dtype": "float32"},
54 },
55 "optional_vars": None,
56 },
57 "C3": {
58 "description": "Covariance matrix (3x3)",
59 "vars": {
60 "m11": {"dtype": "float32"},
61 "m12": {"dtype": "complex64"},
62 "m22": {"dtype": "float32"},
63 "m13": {"dtype": "complex64"},
64 "m23": {"dtype": "complex64"},
65 "m33": {"dtype": "float32"},
66 },
67 "optional_vars": None,
68 },
69 "C4": {
70 "description": "Covariance matrix (4x4)",
71 "vars": {
72 "m11": {"dtype": "float32"},
73 "m12": {"dtype": "complex64"},
74 "m13": {"dtype": "complex64"},
75 "m14": {"dtype": "complex64"},
76 "m22": {"dtype": "float32"},
77 "m23": {"dtype": "complex64"},
78 "m24": {"dtype": "complex64"},
79 "m33": {"dtype": "float32"},
80 "m34": {"dtype": "complex64"},
81 "m44": {"dtype": "float32"},
82 },
83 "optional_vars": None,
84 },
85 "T3": {
86 "description": "Coherency matrix (3x3)",
87 "vars": {
88 "m11": {"dtype": "float32"},
89 "m12": {"dtype": "complex64"},
90 "m22": {"dtype": "float32"},
91 "m13": {"dtype": "complex64"},
92 "m23": {"dtype": "complex64"},
93 "m33": {"dtype": "float32"},
94 },
95 "optional_vars": None,
96 },
97 "T4": {
98 "description": "Coherency matrix (4x4)",
99 "vars": {
100 "m11": {"dtype": "float32"},
101 "m12": {"dtype": "complex64"},
102 "m13": {"dtype": "complex64"},
103 "m14": {"dtype": "complex64"},
104 "m22": {"dtype": "float32"},
105 "m23": {"dtype": "complex64"},
106 "m24": {"dtype": "complex64"},
107 "m33": {"dtype": "float32"},
108 "m34": {"dtype": "complex64"},
109 "m44": {"dtype": "float32"},
110 },
111 "optional_vars": None,
112 },
113 "h_a_alpha": {
114 "description": "Results of the H/A/Alpha decomposition.",
115 "vars": {
116 "entropy": {"dtype": "float32"},
117 "anisotropy": {"dtype": "float32"},
118 "alpha": {"dtype": "float32"},
119 "beta": {"dtype": "float32"},
120 "delta": {"dtype": "float32"},
121 "epsilon": {"dtype": "float32"},
122 "gamma": {"dtype": "float32"},
123 "lambda": {"dtype": "float32"},
124 "nhu": {"dtype": "float32"},
125 "alphas": {"dtype": "float32"},
126 "betas": {"dtype": "float32"},
127 "deltas": {"dtype": "float32"},
128 "epsilons": {"dtype": "float32"},
129 "gammas": {"dtype": "float32"},
130 "lambdas": {"dtype": "float32"},
131 "nhus": {"dtype": "float32"},
132 },
133 "optional_vars": (
134 "entropy",
135 "anisotropy",
136 "alpha",
137 "beta",
138 "delta",
139 "epsilon",
140 "gamma",
141 "lambda",
142 "nhu",
143 "alphas",
144 "betas",
145 "deltas",
146 "epsilons",
147 "gammas",
148 "lambdas",
149 "nhus",
150 ),
151 },
152 }
153
154
155 # Allowed 2D dimension conventions
156 ALLOWED_DIMS: tuple[tuple[str, str], ...] = (
157 ("y", "x"),
158 ("lat", "lon"),
159 # some H/A/Alpha outputs
160 ("y", "x", "i"),
161 ("lat", "lon", "i"),
162 )
163
164
165 def validate_dataset(
166 ds: xr.Dataset,
167 allowed_poltypes: str | Sequence[str] | None = None,
168 check_dims: bool = True,
169 check_vars: bool = True,
170 check_dtypes: bool = True,
171 ):
172 """
173 Validate a PolSAR dataset against standard conventions.
174 Used in processing functions to ensure the validity of inputs.
175
176 Args:
177 ds: Dataset to validate.
178 allowed_poltypes: Single poltype (e.g. "S") or sequence of poltypes
179 (e.g. ("S", "T3")). If None, accept any known poltype.
180 check_dims: If True, ensure that dims match one of ALLOWED_DIMS.
181 check_vars: If True, ensure that expected variables are present.
182 check_dtypes: If True, ensure that variable dtypes are correct.
183
184 Raises:
185 ValueError: If any check fails.
186 """
187
188 if not isinstance(ds, xr.Dataset):
189 raise TypeError("Input must be an xarray.Dataset.")
190
191 # Check poltype is in attrs
192 if "poltype" not in ds.attrs:
193 raise ValueError("Missing required 'poltype' in dataset attributes.")
194
195 # Check poltype is a valid name
196 poltype = str(ds.attrs["poltype"]) # .upper()
197 if poltype not in POLTYPES:
198 raise ValueError(
199 f"Unsupported poltype '{poltype}'. Must be one of {list(POLTYPES)}."
200 )
201
202 # Check poltype is in the input list
203 if allowed_poltypes is not None:
204 if isinstance(allowed_poltypes, str):
205 allowed = (allowed_poltypes,)
206 else:
207 allowed = tuple(p for p in allowed_poltypes)
208 if poltype not in allowed:
209 raise ValueError(
210 f"poltype='{poltype}' not allowed. Must be one of {allowed}."
211 )
212
213 # Check dimensions are valid (2D or 3D coordinates)
214 if check_dims:
215 ds_dims = tuple(ds.dims)
216 if ds_dims not in ALLOWED_DIMS:
217 raise ValueError(
218 f"Dataset dims {list(ds.dims)} do not match any allowed convention "
219 f"{[list(d) for d in ALLOWED_DIMS]}."
220 )
221
222 # Check variable names and shapes
223 specs = POLTYPES[poltype]
224 if check_vars:
225 if not ds.data_vars:
226 raise ValueError("No variable found in Dataset.")
227
228 allowed_vars = specs["vars"]
229 # Is this variable allowed?
230 for v in ds.data_vars:
231 if v not in allowed_vars:
232 raise ValueError(f"Unexpected variable '{v}' for poltype '{poltype}'.")
233
234 # Is this variable missing?
235 for v in allowed_vars:
236 optional_vars = specs.get("optional_vars") or []
237 if (v not in ds.data_vars) and (v not in optional_vars):
238 raise ValueError(f"Dataset is missing required variable: '{v}'")
239
240 shapes = [ds[v].shape for v in allowed_vars if v in ds.data_vars]
241 for shape in shapes:
242 if len(shape) < 2:
243 raise ValueError(f"Expected >= 2D variables, but found shape {shape}")
244
245 if check_dtypes:
246 for v in ds.data_vars:
247 expected_dtype = np.dtype(specs["vars"][v]["dtype"])
248 if ds[v].dtype != expected_dtype:
249 raise ValueError(
250 f"Variable '{v}': expected {expected_dtype} dtype, but found {ds[v].dtype}."
251 )
252 return ds.poltype