gafa 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. gafa/CHANGELOG.md +97 -0
  2. gafa/__init__.py +0 -0
  3. gafa/antenna_patterns.py +512 -0
  4. gafa/cli.py +173 -0
  5. gafa/config/s1/s1_ew_ipf.toml +59 -0
  6. gafa/config/s1/s1_iw_ipf.toml +46 -0
  7. gafa/config/s1/s1_s1_ipf.toml +19 -0
  8. gafa/config/s1/s1_s2_ipf.toml +19 -0
  9. gafa/config/s1/s1_s3_ipf.toml +19 -0
  10. gafa/config/s1/s1_s4_ipf.toml +19 -0
  11. gafa/config/s1/s1_s5_ipf.toml +19 -0
  12. gafa/config/s1/s1_s6_ipf.toml +19 -0
  13. gafa/config/s1/s1_wv_ipf.toml +34 -0
  14. gafa/defaults.py +61 -0
  15. gafa/forward/azimuth_processing.py +2035 -0
  16. gafa/forward/doppler_methods.py +660 -0
  17. gafa/forward/range_processing.py +559 -0
  18. gafa/forward/tdbp/tdbp_gafa.py +730 -0
  19. gafa/interpolators.py +70 -0
  20. gafa/io/__init__.py +8 -0
  21. gafa/io/gafa/__init__.py +10 -0
  22. gafa/io/gafa/reader.py +116 -0
  23. gafa/io/gafa/writer.py +450 -0
  24. gafa/io/gafa/xdt_tools.py +401 -0
  25. gafa/io/geosar/__init__.py +21 -0
  26. gafa/io/geosar/_common.py +262 -0
  27. gafa/io/geosar/aresys_raw_reader.py +132 -0
  28. gafa/io/geosar/aresys_slc_reader.py +46 -0
  29. gafa/io/geosar/grid.py +77 -0
  30. gafa/io/sentinel1/auxiliary.py +786 -0
  31. gafa/io/sentinel1/baq.py +164 -0
  32. gafa/io/sentinel1/calib.py +676 -0
  33. gafa/io/sentinel1/fdbaq.py +342 -0
  34. gafa/io/sentinel1/orbit.py +108 -0
  35. gafa/io/sentinel1/reader.py +663 -0
  36. gafa/io/sentinel1/sspheaders.py +829 -0
  37. gafa/io/sentinel1/timeline.py +2114 -0
  38. gafa/io/sentinel1/util.py +156 -0
  39. gafa/kernels.py +800 -0
  40. gafa/mbczt.py +838 -0
  41. gafa/metatools.py +30 -0
  42. gafa/processor.py +505 -0
  43. gafa/rastertools.py +122 -0
  44. gafa/util.py +337 -0
  45. gafa/window_functions.py +74 -0
  46. gafa-1.3.0.dist-info/METADATA +373 -0
  47. gafa-1.3.0.dist-info/RECORD +51 -0
  48. gafa-1.3.0.dist-info/WHEEL +4 -0
  49. gafa-1.3.0.dist-info/entry_points.txt +2 -0
  50. gafa-1.3.0.dist-info/licenses/LICENSE-Apache-2.0.txt +202 -0
  51. gafa-1.3.0.dist-info/licenses/LICENSE-ESA-PL-Permissive-2.5.txt +259 -0
gafa/CHANGELOG.md ADDED
@@ -0,0 +1,97 @@
1
+ # Changelog
2
+
3
+ ## v1.3.0
4
+
5
+ The first public release of gafa. It needs Python 3.11 or later, and
6
+ gdar-base, gdar-orbit and gdar-sar 1.3.0 or later, which install from PyPI
7
+ automatically.
8
+
9
+ ### Licensing
10
+
11
+ - **Dual licensed under Apache-2.0 and ESA-PL Permissive v2.5**, at the user's
12
+ option. Both licence texts are distributed with the package as
13
+ `LICENSE-Apache-2.0.txt` and `LICENSE-ESA-PL-Permissive-2.5.txt`.
14
+
15
+ ### For pre-release users
16
+
17
+ gafa has not been published before, so nothing here breaks a released
18
+ version. One move is worth flagging for anyone who has been using gafa
19
+ internally: the orbit propagator is now `gdar.orbit.propagator`, so import
20
+ `Propagator` from there rather than from `gafa.propagator`.
21
+
22
+ ### New features
23
+
24
+ - **GeoSAR RAW and SLC readers.**
25
+
26
+ - **Time-domain back-projection with full-aperture block focusing.**
27
+
28
+ - **Bistatic elevation pattern correction** in the calibration path.
29
+
30
+ - **SLC metadata helpers** in `metatools`, and a `slc` level added when
31
+ annotating processing parameters.
32
+
33
+ - **A command-line entry point**, `cli/gafa_tool`.
34
+
35
+ - **Demonstration notebooks** for the bistatic point-target response, GeoSAR,
36
+ and region-of-interest processing, alongside a `getting-started.md` and
37
+ bistatic Doppler documentation.
38
+
39
+ ### Bug fixes
40
+
41
+ - **Auxiliary and product files under a symlinked directory were never
42
+ found.** `find_paths` searched with `Path.glob("**/*")`, which does not
43
+ descend into symlinked directories on any Python version, so an aux root or
44
+ a `.SAFE` assembled from symlinks appeared empty and the run fell back as
45
+ though the files were absent. The search now uses
46
+ `os.walk(..., followlinks=True)`. Affects the AUX_INS/AUX_CAL and orbit
47
+ lookup, the measurement files inside a product, and the annotation XML
48
+ inside a located AUX directory.
49
+
50
+ - **Range compression used the wrong chirp bandwidth** — it now uses the
51
+ transmitted bandwidth.
52
+
53
+ - **TOPS focusing did not preserve phase or align the focused output.** Both
54
+ are corrected, along with the bistatic TOPS path.
55
+
56
+ - **Bistatic kernel evaluation was unstable at high squint.**
57
+
58
+ - **Doppler geometry ignored the annotated grid time and the sampled
59
+ pointing.**
60
+
61
+ - **The reference range rate was a scalar** where it varies across the grid,
62
+ and is now an array.
63
+
64
+ - **Nested complex metadata was not preserved** by the I/O layer.
65
+
66
+ - Fixed code after numpy's deprecation of assignment to `array.shape`.
67
+
68
+ ### Tests
69
+
70
+ - Reference models for antenna patterns and Doppler, against which the
71
+ processing chain is checked.
72
+
73
+ - New coverage for azimuth spectral extension, azimuth kernel degree, lazy and
74
+ bulk focusing, range processing and the range CZT, TDBP, the GeoSAR reader,
75
+ NetCDF output, and processing metadata.
76
+
77
+ ### Packaging
78
+
79
+ - **The Sentinel-1 processing configurations ship with the package**, as
80
+ `gafa/config/s1/*.toml` — one per mode, covering IW, EW, WV and the six
81
+ stripmap beams. They are in the wheel, so they are available from an
82
+ installed copy and not only from a checkout.
83
+
84
+ - **Configuration files are read through `gdar.base.config`**, so gafa and the
85
+ gdar packages share one configuration file and format.
86
+
87
+ - **`CHANGELOG.md` ships inside the wheel** as `gafa/CHANGELOG.md`, which the
88
+ ESA-PL licence requires, as well as in the source distribution.
89
+
90
+ - **The example notebooks are in the source distribution**, under `examples/`,
91
+ alongside a `gafa_config.toml.example` and a worked IPF script. They are not
92
+ in the wheel.
93
+
94
+ - **A `dev` dependency group** provides `pytest` and `pytest-subtests`.
95
+
96
+ - **The `crs` extra is empty.** It exists only for symmetry with the gdar
97
+ packages, and does nothing.
gafa/__init__.py ADDED
File without changes
@@ -0,0 +1,512 @@
1
+ """Complex antenna-pattern evaluation for SAR radiometric compensation.
2
+
3
+ The antenna quantities used here are one-way complex *voltage* patterns.
4
+ Elevation is kept as an absolute, unnormalised complex response. Only the
5
+ azimuth dependence is normalised to its value at the azimuth reference
6
+ coordinate. For a bistatic acquisition the complex signal illumination is
7
+ therefore
8
+
9
+ ``G(u_tx, v_tx, u_rx, v_rx) = A_tx(u_tx, v_tx) A_rx(u_rx, v_rx)``.
10
+
11
+ The transmitter and receiver directions must be evaluated independently in
12
+ their respective beam frames. In particular, a Tx angle must never be
13
+ shifted or reused as an approximation to the Rx angle.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Any
19
+
20
+ import numpy as np
21
+ from gdar.base.util import unit_vector
22
+ from gdar.orbit.attitude import Attitude
23
+ from gdar.orbit.orbit import Sampled_orbit
24
+ from scipy.interpolate import RegularGridInterpolator, interp1d
25
+
26
+ from gafa.forward.doppler_methods import (
27
+ antenna_azimuth_steering,
28
+ antenna_steering_direction,
29
+ )
30
+
31
+ _TWO_DIMENSIONAL_PATTERN_KEYS = (
32
+ ("pattern_voltage", "pattern_u", "pattern_v"),
33
+ ("complex_pattern", "u", "v"),
34
+ )
35
+
36
+
37
+ def _as_dict(value: Any) -> dict[str, Any]:
38
+ if isinstance(value, dict):
39
+ return value
40
+ try:
41
+ return value[..., ...]
42
+ except (AttributeError, IndexError, KeyError, TypeError):
43
+ return value[...]
44
+
45
+
46
+ def _sorted_axis(axis: np.ndarray, values: np.ndarray, dimension: int):
47
+ order = np.argsort(axis)
48
+ axis = axis[order]
49
+ values = np.take(values, order, axis=dimension)
50
+ if np.any(np.diff(axis) <= 0):
51
+ raise ValueError("Antenna-pattern coordinates must be unique")
52
+ return axis, values
53
+
54
+
55
+ def _voltage_reference(pattern: np.ndarray) -> complex:
56
+ """Return the finite sample with maximum voltage magnitude."""
57
+
58
+ pattern = np.asarray(pattern)
59
+ finite = np.isfinite(pattern.real) & np.isfinite(pattern.imag)
60
+ if not np.any(finite):
61
+ raise ValueError("Antenna pattern has no finite samples")
62
+ magnitude = np.where(finite, np.abs(pattern), -np.inf)
63
+ reference = complex(pattern.reshape(-1)[int(np.argmax(magnitude))])
64
+ if not np.isfinite(reference) or abs(reference) == 0:
65
+ raise ValueError("Antenna pattern has zero peak voltage")
66
+ return reference
67
+
68
+
69
+ def _pattern_schema(antenna: dict[str, Any]):
70
+ for value_key, u_key, v_key in _TWO_DIMENSIONAL_PATTERN_KEYS:
71
+ if value_key in antenna and u_key in antenna and v_key in antenna:
72
+ return value_key, u_key, v_key
73
+ return None
74
+
75
+
76
+ def has_complex_pattern(antenna: dict[str, Any] | Any) -> bool:
77
+ """Return whether a full 2-D or separable one-way pattern is present."""
78
+
79
+ antenna = _as_dict(antenna)
80
+ if _pattern_schema(antenna) is not None:
81
+ return True
82
+ return all(
83
+ key in antenna
84
+ for key in (
85
+ "azimuthangle",
86
+ "azimuthpattern",
87
+ "elevationangle",
88
+ "elevationpattern",
89
+ )
90
+ )
91
+
92
+
93
+ def _coordinate_queries(antenna, u, v):
94
+ coordinate_system = str(
95
+ antenna.get("pattern_coordinate_system", antenna.get("coordinate_system", "uv"))
96
+ ).lower()
97
+ if coordinate_system in {"uv", "direction_cosine", "direction_cosines"}:
98
+ return np.asarray(u, dtype=float), np.asarray(v, dtype=float)
99
+ if coordinate_system in {"az_el", "azel", "azimuth_elevation"}:
100
+ u = np.asarray(u, dtype=float)
101
+ v = np.asarray(v, dtype=float)
102
+ w = np.sqrt(np.maximum(1.0 - u * u - v * v, 0.0))
103
+ azimuth = np.arctan2(u, w)
104
+ elevation = np.arcsin(np.clip(v, -1.0, 1.0))
105
+ unit = str(antenna.get("angleunit", antenna.get("angle_unit", "rad"))).lower()
106
+ if unit in {"deg", "degree", "degrees"}:
107
+ azimuth = np.degrees(azimuth)
108
+ elevation = np.degrees(elevation)
109
+ elif unit not in {"rad", "radian", "radians"}:
110
+ raise ValueError(f"Unsupported antenna angle unit: {unit}")
111
+ return azimuth, elevation
112
+ raise ValueError(f"Unsupported antenna coordinate system: {coordinate_system}")
113
+
114
+
115
+ def _complex_1d_interpolant(
116
+ axis,
117
+ pattern,
118
+ query,
119
+ *,
120
+ normalize=False,
121
+ reference_coordinate=0.0,
122
+ ):
123
+ axis = np.asarray(axis, dtype=float).squeeze()
124
+ pattern = np.asarray(pattern).squeeze()
125
+ if axis.ndim != 1 or pattern.ndim != 1 or axis.shape != pattern.shape:
126
+ raise ValueError("Antenna cut coordinate and voltage must be equal 1-D arrays")
127
+ if not np.iscomplexobj(pattern):
128
+ pattern = np.asarray(pattern, dtype=float).astype(np.complex128)
129
+ order = np.argsort(axis)
130
+ axis = axis[order]
131
+ pattern = np.nan_to_num(pattern[order], nan=0.0)
132
+ if normalize:
133
+ reference = complex(
134
+ np.interp(reference_coordinate, axis, pattern.real),
135
+ np.interp(reference_coordinate, axis, pattern.imag),
136
+ )
137
+ if not np.isfinite(reference) or abs(reference) == 0:
138
+ reference = _voltage_reference(pattern)
139
+ pattern = pattern / reference
140
+ real = interp1d(axis, pattern.real, bounds_error=False, fill_value=0.0, assume_sorted=True)(
141
+ query
142
+ )
143
+ imag = interp1d(axis, pattern.imag, bounds_error=False, fill_value=0.0, assume_sorted=True)(
144
+ query
145
+ )
146
+ result = real + 1j * imag
147
+ reference_magnitude = float(np.max(np.abs(pattern)))
148
+ return result, reference_magnitude
149
+
150
+
151
+ def _complex_2d_interpolant(v_axis, u_axis, values, v_query, u_query):
152
+ """Interpolate a complex ``(v, u)`` LUT without changing its scale."""
153
+
154
+ points = np.column_stack((np.ravel(v_query), np.ravel(u_query)))
155
+ real = RegularGridInterpolator(
156
+ (v_axis, u_axis), values.real, bounds_error=False, fill_value=0.0
157
+ )(points)
158
+ imag = RegularGridInterpolator(
159
+ (v_axis, u_axis), values.imag, bounds_error=False, fill_value=0.0
160
+ )(points)
161
+ return (real + 1j * imag).reshape(np.shape(u_query))
162
+
163
+
164
+ def evaluate_complex_pattern(
165
+ antenna: dict[str, Any] | Any,
166
+ u: np.ndarray,
167
+ v: np.ndarray,
168
+ *,
169
+ include_azimuth: bool = True,
170
+ include_elevation: bool = True,
171
+ return_reference_magnitude: bool = False,
172
+ ) -> np.ndarray | tuple[np.ndarray, float]:
173
+ """Evaluate a one-way complex-voltage antenna pattern.
174
+
175
+ A full 2-D LUT is preferred. Its array order is ``(v, u)``, matching a
176
+ tabulated elevation-by-azimuth voltage array. Legacy separable cuts
177
+ remain supported, but both cuts must represent voltage; squaring a complex
178
+ LUT in the reader and again in a simulator/processor would incorrectly
179
+ produce the fourth power of the underlying aperture amplitude.
180
+
181
+ Elevation is never normalised. For a full two-dimensional pattern, let
182
+ ``u0`` be the azimuth reference coordinate (zero unless explicitly
183
+ annotated). The evaluated pattern is separated as
184
+
185
+ ``E(v) = A(u0, v)`` and ``Z(u, v) = A(u, v) / A(u0, v)``.
186
+
187
+ Thus ``E`` is the absolute complex elevation response, ``Z`` is the
188
+ normalised complex azimuth response, and ``E * Z`` is exactly the
189
+ original two-dimensional LUT. This follows the same normalization rule
190
+ used by Sentinel-1 AUX_CAL: its complex two-way elevation cut is absolute
191
+ and linear, whereas its azimuth cut is normalised (and stored in dB). The
192
+ Sentinel-1 two-way magnitude convention itself remains handled by the
193
+ established monostatic range-processing path.
194
+
195
+ Separable legacy metadata follow the same rule: ``azimuthpattern`` is
196
+ normalised at the annotated azimuth reference and ``elevationpattern`` is
197
+ left unchanged.
198
+
199
+ If ``return_reference_magnitude`` is true, also return a representative
200
+ peak magnitude for applying a relative inverse-gain floor.
201
+ """
202
+
203
+ antenna = _as_dict(antenna)
204
+ quantity = str(antenna.get("pattern_quantity", "voltage")).lower()
205
+ if quantity not in {"voltage", "complex_voltage"}:
206
+ raise ValueError(
207
+ "Antenna compensation requires one-way complex-voltage LUTs; "
208
+ f"received pattern_quantity={quantity!r}"
209
+ )
210
+ u_query, v_query = _coordinate_queries(antenna, u, v)
211
+ pattern_model = str(antenna.get("pattern_model", "two_dimensional")).lower()
212
+ use_separable_cuts = pattern_model in {
213
+ "separable",
214
+ "separable_cuts",
215
+ "dyadic",
216
+ "rank_one",
217
+ }
218
+ schema = None if use_separable_cuts else _pattern_schema(antenna)
219
+ if schema is not None:
220
+ value_key, u_key, v_key = schema
221
+ values = np.asarray(antenna[value_key])
222
+ u_axis = np.asarray(antenna[u_key], dtype=float).squeeze()
223
+ v_axis = np.asarray(antenna[v_key], dtype=float).squeeze()
224
+ if values.shape != (v_axis.size, u_axis.size):
225
+ raise ValueError("The 2-D antenna voltage array must have shape (len(v), len(u))")
226
+ values = np.nan_to_num(values.astype(np.complex128), nan=0.0)
227
+ v_axis, values = _sorted_axis(v_axis, values, 0)
228
+ u_axis, values = _sorted_axis(u_axis, values, 1)
229
+ u_reference = float(
230
+ antenna.get(
231
+ "azimuth_reference_coordinate",
232
+ antenna.get("azimuth_reference", 0.0),
233
+ )
234
+ )
235
+ elevation_lut = np.array(
236
+ [
237
+ complex(
238
+ np.interp(u_reference, u_axis, row.real),
239
+ np.interp(u_reference, u_axis, row.imag),
240
+ )
241
+ for row in values
242
+ ]
243
+ )
244
+ elevation, _ = _complex_1d_interpolant(
245
+ v_axis,
246
+ elevation_lut,
247
+ v_query,
248
+ normalize=False,
249
+ )
250
+
251
+ if include_azimuth:
252
+ full_pattern = _complex_2d_interpolant(v_axis, u_axis, values, v_query, u_query)
253
+ if include_elevation:
254
+ result = full_pattern
255
+ reference_magnitude = float(np.max(np.abs(values)))
256
+ else:
257
+ result = np.zeros_like(full_pattern)
258
+ np.divide(
259
+ full_pattern,
260
+ elevation,
261
+ out=result,
262
+ where=np.abs(elevation) > 0,
263
+ )
264
+ valid_rows = np.abs(elevation_lut) > 0
265
+ normalized_lut = np.zeros_like(values)
266
+ np.divide(
267
+ values,
268
+ elevation_lut[:, None],
269
+ out=normalized_lut,
270
+ where=valid_rows[:, None],
271
+ )
272
+ reference_magnitude = float(np.max(np.abs(normalized_lut)))
273
+ elif include_elevation:
274
+ result = elevation
275
+ reference_magnitude = float(np.max(np.abs(elevation_lut)))
276
+ else:
277
+ result = np.ones_like(u_query, dtype=np.complex128)
278
+ reference_magnitude = 1.0
279
+
280
+ if return_reference_magnitude:
281
+ return result, reference_magnitude
282
+ return result
283
+
284
+ required = (
285
+ "azimuthangle",
286
+ "azimuthpattern",
287
+ "elevationangle",
288
+ "elevationpattern",
289
+ )
290
+ if not all(key in antenna for key in required):
291
+ raise KeyError("No supported complex antenna pattern found in metadata")
292
+ if include_azimuth:
293
+ azimuth, azimuth_reference_magnitude = _complex_1d_interpolant(
294
+ antenna["azimuthangle"],
295
+ antenna["azimuthpattern"],
296
+ u_query,
297
+ normalize=True,
298
+ reference_coordinate=float(
299
+ antenna.get(
300
+ "azimuth_reference_coordinate",
301
+ antenna.get("azimuth_reference", 0.0),
302
+ )
303
+ ),
304
+ )
305
+ else:
306
+ azimuth = np.ones_like(u_query, dtype=np.complex128)
307
+ azimuth_reference_magnitude = 1.0
308
+ if include_elevation:
309
+ elevation, elevation_reference_magnitude = _complex_1d_interpolant(
310
+ antenna["elevationangle"],
311
+ antenna["elevationpattern"],
312
+ v_query,
313
+ normalize=False,
314
+ )
315
+ else:
316
+ elevation = np.ones_like(v_query, dtype=np.complex128)
317
+ elevation_reference_magnitude = 1.0
318
+ result = azimuth * elevation
319
+ reference_magnitude = azimuth_reference_magnitude * elevation_reference_magnitude
320
+ if return_reference_magnitude:
321
+ return result, reference_magnitude
322
+ return result
323
+
324
+
325
+ def inverse_complex_pattern_product(
326
+ tx_voltage: np.ndarray,
327
+ rx_voltage: np.ndarray,
328
+ *,
329
+ floor_db: float = -20.0,
330
+ reference_magnitude: float = 1.0,
331
+ ) -> np.ndarray:
332
+ """Return a stable inverse of the complex bistatic Tx times Rx voltage.
333
+
334
+ The floor is relative to ``reference_magnitude``. This matters because
335
+ elevation patterns retain their absolute linear scale, while azimuth-only
336
+ patterns are normalised. Below the floor the inverse gain is clipped
337
+ instead of diverging, which limits noise amplification while retaining
338
+ the conjugate phase correction.
339
+ """
340
+
341
+ if floor_db > 0:
342
+ raise ValueError("Antenna-pattern floor must not exceed 0 dB")
343
+ product = np.asarray(tx_voltage) * np.asarray(rx_voltage)
344
+ if not np.isfinite(reference_magnitude) or reference_magnitude <= 0:
345
+ raise ValueError("Pattern reference magnitude must be finite and positive")
346
+ floor = float(reference_magnitude) * 10.0 ** (float(floor_db) / 20.0)
347
+ magnitude = np.abs(product)
348
+ # Preserve the inverse phase while limiting its magnitude to 1/floor.
349
+ # The phase of an exact zero is undefined, so leave those samples at zero.
350
+ conjugate_unit = np.zeros_like(product, dtype=np.complex128)
351
+ np.divide(
352
+ np.conj(product),
353
+ magnitude,
354
+ out=conjugate_unit,
355
+ where=magnitude > 0,
356
+ )
357
+ return conjugate_unit / np.maximum(magnitude, floor)
358
+
359
+
360
+ def _beam_frame_direction(meta, xyz, ytime, side):
361
+ meta = _as_dict(meta)
362
+ refsys = meta["grid"]["refsys"]
363
+ trajectory = refsys[f"trajectory_{side}"]
364
+ attitude_data = refsys[f"attitude_{side}"]
365
+ orbit = Sampled_orbit(trajectory, ytime_ref=refsys["utc"], utc=True)
366
+ position = orbit.get_statevector(ytime).pos
367
+ tai_ref = orbit.get_ytime_ref(tai=True)
368
+ attitude = Attitude(
369
+ attitude_data["quat"],
370
+ attitude_data["tai"],
371
+ time_ref=tai_ref,
372
+ time_scale="tai",
373
+ )
374
+ rotation = attitude.get_attitude(ytime, as_matrix=True)
375
+ line_of_sight = unit_vector(np.asarray(xyz) - position[:, None, :])
376
+ return np.einsum("nij,nkj->nki", np.swapaxes(rotation, -1, -2), line_of_sight)
377
+
378
+
379
+ def _relative_tops_steering(antenna, ytime, utc_reference):
380
+ """Use GAFA's sampled pointing or annotated scalar steering law."""
381
+ antenna = {"azsweeprate": 0.0, **_as_dict(antenna)}
382
+ return antenna_azimuth_steering(antenna, ytime, utc_ref=utc_reference)
383
+
384
+
385
+ def _apply_tops_steering(direction, steering):
386
+ """Express fixed-frame look directions relative to a steered TOPS beam.
387
+
388
+ The annotated steering angle is positive in the beam-frame azimuth
389
+ direction. The pattern query is consequently ``azimuth - steering``.
390
+ Written directly in direction cosines, this is a rotation about the
391
+ beam-frame elevation axis and avoids unnecessary angle conversions.
392
+ """
393
+
394
+ direction = np.asarray(direction, dtype=float)
395
+ steering = np.asarray(steering, dtype=float)
396
+ while steering.ndim < direction.ndim - 1:
397
+ steering = steering[..., None]
398
+ cosine = np.cos(steering)
399
+ sine = np.sin(steering)
400
+ u = direction[..., 0]
401
+ v = direction[..., 1]
402
+ w = direction[..., 2]
403
+ return np.stack(
404
+ (u * cosine - w * sine, v, w * cosine + u * sine),
405
+ axis=-1,
406
+ )
407
+
408
+
409
+ def _pattern_query_direction(antenna, direction, ytime, utc_reference):
410
+ """Remove the metadata-declared azimuth steering from LUT coordinates.
411
+
412
+ ``azimuth_rotation`` is the angular beam-frame convention. ``u_shift``
413
+ translates only the azimuth direction cosine, using sampled pointing;
414
+ elevation steering already present in the LUT is retained in that case.
415
+ A translated LUT query is not itself a physical unit direction.
416
+ """
417
+ convention = str(antenna.get("pattern_steering_convention", "azimuth_rotation")).lower()
418
+ if convention == "u_shift":
419
+ pointing = antenna_steering_direction(antenna, ytime, utc_ref=utc_reference)
420
+ shift = pointing[..., 0]
421
+ result = np.array(direction, dtype=float, copy=True)
422
+ while shift.ndim < result.ndim - 1:
423
+ shift = shift[..., None]
424
+ result[..., 0] -= shift
425
+ return result
426
+ if convention != "azimuth_rotation":
427
+ raise ValueError(f"Unsupported antenna pattern steering convention: {convention}")
428
+ return _apply_tops_steering(direction, _relative_tops_steering(antenna, ytime, utc_reference))
429
+
430
+
431
+ def bistatic_antenna_pattern_correction(
432
+ meta: dict[str, Any] | Any,
433
+ xyz: np.ndarray,
434
+ ytime: np.ndarray,
435
+ *,
436
+ include_azimuth: bool = True,
437
+ include_elevation: bool = True,
438
+ floor_db: float = -20.0,
439
+ return_voltage: bool = False,
440
+ ):
441
+ """Evaluate the inverse complex Tx×Rx pattern on a ground-coordinate grid.
442
+
443
+ Parameters
444
+ ----------
445
+ xyz : array, shape (nazimuth, nrange, 3)
446
+ Ground positions in ECEF coordinates.
447
+ ytime : array, shape (nazimuth,)
448
+ Acquisition slow time in seconds relative to ``grid.refsys.utc``.
449
+
450
+ Notes
451
+ -----
452
+ This function uses the Tx orbit/attitude for the Tx direction and the Rx
453
+ orbit/attitude for the Rx direction. Trajectories must already describe
454
+ the selected antenna phase centres, as required by the focusing geometry.
455
+ Reader-specific phase-centre offsets are not applied a second time.
456
+
457
+ For TOPS, those attitude-derived directions remain in the fixed antenna
458
+ frame. The independently annotated Tx and Rx electronic steering laws
459
+ are therefore removed before LUT evaluation. This is deliberately
460
+ separate from Sentinel-1 ``apply_element_pattern_correction``: that path
461
+ consumes a normalized one-dimensional AUX_CAL element pattern, whereas
462
+ this function consumes one-way complex Tx and Rx voltage LUTs.
463
+
464
+ Elevation response is kept absolute and complex. Only the azimuth factor
465
+ is normalised at its reference coordinate. Consequently enabling both
466
+ dimensions applies the inverse of the original complex Tx times Rx LUT,
467
+ including its reference phase; it does not silently discard the absolute
468
+ elevation calibration.
469
+
470
+ The evaluator is usable on either a range-compressed geometric sampling
471
+ grid or a focused target grid. GAFA's production bistatic path evaluates
472
+ the elevation-only term on the range-compressed grid so that it follows
473
+ range-cell migration before azimuth integration. The normalized
474
+ azimuth term remains a target-domain correction; it does not attempt to
475
+ invert the aperture illumination that determines the focused azimuth
476
+ impulse response and therefore is not an azimuth deconvolution filter.
477
+ """
478
+
479
+ meta = _as_dict(meta)
480
+ instrument = meta["instrument"]
481
+ tx = _as_dict(instrument["antenna_tx"])
482
+ rx = _as_dict(instrument["antenna_rx"])
483
+ tx_body = _beam_frame_direction(meta, xyz, np.asarray(ytime), "tx")
484
+ rx_body = _beam_frame_direction(meta, xyz, np.asarray(ytime), "rx")
485
+ utc_reference = meta["grid"]["refsys"]["utc"]
486
+ tx_body = _pattern_query_direction(tx, tx_body, ytime, utc_reference)
487
+ rx_body = _pattern_query_direction(rx, rx_body, ytime, utc_reference)
488
+ tx_voltage, tx_reference_magnitude = evaluate_complex_pattern(
489
+ tx,
490
+ tx_body[..., 0],
491
+ tx_body[..., 1],
492
+ include_azimuth=include_azimuth,
493
+ include_elevation=include_elevation,
494
+ return_reference_magnitude=True,
495
+ )
496
+ rx_voltage, rx_reference_magnitude = evaluate_complex_pattern(
497
+ rx,
498
+ rx_body[..., 0],
499
+ rx_body[..., 1],
500
+ include_azimuth=include_azimuth,
501
+ include_elevation=include_elevation,
502
+ return_reference_magnitude=True,
503
+ )
504
+ correction = inverse_complex_pattern_product(
505
+ tx_voltage,
506
+ rx_voltage,
507
+ floor_db=floor_db,
508
+ reference_magnitude=tx_reference_magnitude * rx_reference_magnitude,
509
+ )
510
+ if return_voltage:
511
+ return correction, tx_voltage, rx_voltage, tx_body, rx_body
512
+ return correction