PyGeoFetch 2.6.9.8__py3-none-any.whl → 2.7.0.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.
pygeofetch/__init__.py CHANGED
@@ -30,7 +30,7 @@ CLI::
30
30
  pygeofetch doctor
31
31
  """
32
32
 
33
- __version__ = "2.6.9.8.4"
33
+ __version__ = "2.7.0.0.4"
34
34
  __author__ = "PyGeoFetch Contributors"
35
35
  __license__ = "MIT"
36
36
 
@@ -229,6 +229,11 @@ class AdaptiveDownloader:
229
229
  # network truncation is typically transient. Route through
230
230
  # the same backoff-and-retry path a raised exception would
231
231
  # take, instead of returning early.
232
+ # A refused login does not get better by retrying (and repeated
233
+ # failed logins can lock an account), so stop at once.
234
+ if getattr(result, "error_type", None) == "AuthenticationError":
235
+ logger.error(f"Download failed (authentication): {result.error}")
236
+ return result
232
237
  if attempt < options.retry_attempts:
233
238
  delay = self._backoff(attempt, options)
234
239
  logger.warning(
@@ -245,6 +250,18 @@ class AdaptiveDownloader:
245
250
  )
246
251
  return result
247
252
  except Exception as exc:
253
+ from pygeofetch.providers.base import AuthenticationError as _AuthErr
254
+
255
+ if isinstance(exc, _AuthErr):
256
+ logger.error(f"Download failed (authentication): {exc}")
257
+ return DownloadResult(
258
+ status=DownloadStatus.FAILED,
259
+ data_id=data.id,
260
+ provider=data.provider,
261
+ error=str(exc),
262
+ error_type="AuthenticationError",
263
+ retries_used=attempt,
264
+ )
248
265
  if attempt < options.retry_attempts:
249
266
  delay = self._backoff(attempt, options)
250
267
  logger.warning(
@@ -1352,4 +1369,4 @@ class AdaptiveDownloader:
1352
1369
  @property
1353
1370
  def _result_total_size_mb(self) -> float:
1354
1371
  """Property used by result objects."""
1355
- return 0.0
1372
+ return 0.0
@@ -113,12 +113,24 @@ from pygeofetch.insar.annotation import (
113
113
  parse_burst_info,
114
114
  parse_slc_geometry,
115
115
  )
116
- from pygeofetch.insar.atmosphere import AtmosphericCorrector
116
+ from pygeofetch.insar.atmosphere import (
117
+ AtmosphericCorrector,
118
+ )
117
119
  from pygeofetch.insar.atmosphere_core import (
118
- estimate_height_slopes_per_date, fit_height_dependence, structure_function, variance_reduction,
120
+ estimate_height_slopes_per_date,
121
+ fit_height_dependence,
122
+ structure_function,
123
+ variance_reduction,
124
+ )
125
+ from pygeofetch.insar.radar_geometry import (
126
+ GeometryNodes,
127
+ PixelFrame,
128
+ compute_geometry_nodes,
129
+ )
130
+ from pygeofetch.insar.topo import (
131
+ apply_geometric_phase,
132
+ heights_on_output_grid,
119
133
  )
120
- from pygeofetch.insar.radar_geometry import GeometryNodes, PixelFrame, compute_geometry_nodes
121
- from pygeofetch.insar.topo import apply_geometric_phase, heights_on_output_grid
122
134
  from pygeofetch.insar.coregister import (
123
135
  CoregistrationQuality,
124
136
  collocate_by_geocoding,
@@ -128,14 +140,21 @@ from pygeofetch.insar.coregister import (
128
140
  refine_offsets_by_coherence,
129
141
  resample_with_offset_field,
130
142
  )
131
- from pygeofetch.insar.deburst import compute_burst_row_ranges, deburst_array
143
+ from pygeofetch.insar.deburst import (
144
+ compute_burst_row_ranges,
145
+ deburst_array,
146
+ )
132
147
  from pygeofetch.insar.esd import (
133
148
  SENTINEL1_IW_DELTA_F_OVL_HZ,
134
149
  compute_overlap_row_ranges,
135
150
  estimate_esd_shift_per_burst_overlap,
136
151
  )
137
- from pygeofetch.insar.extraction import SLCExtractor
138
- from pygeofetch.insar.flatearth import compute_flat_earth_phase
152
+ from pygeofetch.insar.extraction import (
153
+ SLCExtractor,
154
+ )
155
+ from pygeofetch.insar.flatearth import (
156
+ compute_flat_earth_phase,
157
+ )
139
158
  from pygeofetch.insar.geolocation import (
140
159
  find_zero_doppler_time,
141
160
  geodetic_to_ecef,
@@ -144,20 +163,52 @@ from pygeofetch.insar.geolocation import (
144
163
  parse_orbit_file,
145
164
  range_offset_to_vertical_displacement,
146
165
  )
147
- from pygeofetch.insar.gpu import gpu_available, gpu_info
148
- from pygeofetch.insar.logs import set_verbosity, current_verbosity
166
+ from pygeofetch.insar.gpu import (
167
+ gpu_available,
168
+ gpu_info,
169
+ )
170
+ from pygeofetch.insar.logs import (
171
+ set_verbosity,
172
+ current_verbosity,
173
+ )
149
174
  from pygeofetch.insar.errors import (
150
- BurstProcessingError, CoregistrationError, CropError, FlatEarthError, InputError, ProcessingError,
151
- QualityRecord, TopographicPhaseError, AtmosphereError, GeometryProcessingError,
152
- UnwrapError, ModelLoadError, UnwrapDependencyError,
175
+ BurstProcessingError,
176
+ CoregistrationError,
177
+ CropError,
178
+ FlatEarthError,
179
+ InputError,
180
+ ProcessingError,
181
+ QualityRecord,
182
+ TopographicPhaseError,
183
+ AtmosphereError,
184
+ GeometryProcessingError,
185
+ UnwrapError,
186
+ ModelLoadError,
187
+ UnwrapDependencyError,
188
+ )
189
+ from pygeofetch.insar.hybrid_unwrap import (
190
+ HybridConfig,
191
+ HybridUnwrapper,
192
+ HybridUnwrapResult,
193
+ tie_components,
153
194
  )
154
- from pygeofetch.insar.hybrid_unwrap import HybridConfig, HybridUnwrapper, HybridUnwrapResult, tie_components
155
195
  from pygeofetch.insar.learned_unwrap import (
156
- LearnedUnwrapConfig, LearnedUnwrapper, LearnedUnwrapResult, UnwrapModel, load_unwrap_model,
157
- unwrap_diagnostics, unwrap_interferograms,
196
+ LearnedUnwrapConfig,
197
+ LearnedUnwrapper,
198
+ LearnedUnwrapResult,
199
+ UnwrapModel,
200
+ load_unwrap_model,
201
+ unwrap_diagnostics,
202
+ unwrap_interferograms,
203
+ )
204
+ from pygeofetch.insar.interferogram import (
205
+ InterferogramGenerator,
206
+ InterferogramResult,
207
+ )
208
+ from pygeofetch.insar.ionosphere import (
209
+ IonosphericCorrector,
210
+ parse_ionex,
158
211
  )
159
- from pygeofetch.insar.interferogram import InterferogramGenerator, InterferogramResult
160
- from pygeofetch.insar.ionosphere import IonosphericCorrector, parse_ionex
161
212
 
162
213
  # Range/azimuth pixel offsets to ground East/North/Up displacement. The
163
214
  # math is verified (solve_enu_displacement agrees with
@@ -184,8 +235,14 @@ from pygeofetch.insar.offset_tracking import (
184
235
  normalized_cross_correlation,
185
236
  subpixel_peak_offset,
186
237
  )
187
- from pygeofetch.insar.preflight import PreflightGate, PreflightIssue, PreflightReport
188
- from pygeofetch.insar.provenance import write_provenance_manifest
238
+ from pygeofetch.insar.preflight import (
239
+ PreflightGate,
240
+ PreflightIssue,
241
+ PreflightReport,
242
+ )
243
+ from pygeofetch.insar.provenance import (
244
+ write_provenance_manifest,
245
+ )
189
246
 
190
247
  # Persistent Scatterer InSAR (Ferretti, Prati & Rocca 2001). Real, tested
191
248
  # against synthetic data with known ground truth at every stage (ADI
@@ -201,7 +258,10 @@ from pygeofetch.insar.ps_selection import (
201
258
  select_persistent_scatterers,
202
259
  temporal_coherence,
203
260
  )
204
- from pygeofetch.insar.ps_eval import boost_coherence_with_ps, compare_velocity_maps
261
+ from pygeofetch.insar.ps_eval import (
262
+ boost_coherence_with_ps,
263
+ compare_velocity_maps,
264
+ )
205
265
  from pygeofetch.insar.ps_stack import (
206
266
  ADISelector,
207
267
  PSSelection,
@@ -259,14 +319,33 @@ from pygeofetch.insar.visualize import (
259
319
  visualize_timeseries,
260
320
  visualize_unwrapped,
261
321
  )
262
- from pygeofetch.insar.workflow import InSARProject
322
+ from pygeofetch.insar.workflow import (
323
+ InSARProject,
324
+ )
263
325
 
264
326
  __all__ = [
265
- "ProcessingError", "InputError", "CoregistrationError", "BurstProcessingError", "FlatEarthError",
266
- "TopographicPhaseError", "CropError", "QualityRecord",
267
- "PSStack", "PSSelection", "PSSelector", "ADISelector", "build_ps_stack", "build_stack",
268
- "select_ps", "compare_selections", "holdout_stability", "residual_phase_coherence",
269
- "stability_weights", "choose_master", "boost_coherence_with_ps", "compare_velocity_maps",
327
+ "ProcessingError",
328
+ "InputError",
329
+ "CoregistrationError",
330
+ "BurstProcessingError",
331
+ "FlatEarthError",
332
+ "TopographicPhaseError",
333
+ "CropError",
334
+ "QualityRecord",
335
+ "PSStack",
336
+ "PSSelection",
337
+ "PSSelector",
338
+ "ADISelector",
339
+ "build_ps_stack",
340
+ "build_stack",
341
+ "select_ps",
342
+ "compare_selections",
343
+ "holdout_stability",
344
+ "residual_phase_coherence",
345
+ "stability_weights",
346
+ "choose_master",
347
+ "boost_coherence_with_ps",
348
+ "compare_velocity_maps",
270
349
  "InterferogramGenerator",
271
350
  "InterferogramResult",
272
351
  "PhaseUnwrapper",
@@ -289,12 +368,32 @@ __all__ = [
289
368
  "despike_velocity",
290
369
  "InterferogramPair",
291
370
  "TimeSeriesResult",
292
- "AtmosphericCorrector", "estimate_height_slopes_per_date", "fit_height_dependence", "structure_function",
293
- "variance_reduction", "GeometryNodes", "PixelFrame", "compute_geometry_nodes", "apply_geometric_phase",
294
- "heights_on_output_grid", "AtmosphereError", "GeometryProcessingError",
295
- "UnwrapError", "ModelLoadError", "UnwrapDependencyError", "LearnedUnwrapConfig", "LearnedUnwrapper",
296
- "LearnedUnwrapResult", "UnwrapModel", "load_unwrap_model", "unwrap_diagnostics", "unwrap_interferograms",
297
- "HybridConfig", "HybridUnwrapper", "HybridUnwrapResult", "tie_components",
371
+ "AtmosphericCorrector",
372
+ "estimate_height_slopes_per_date",
373
+ "fit_height_dependence",
374
+ "structure_function",
375
+ "variance_reduction",
376
+ "GeometryNodes",
377
+ "PixelFrame",
378
+ "compute_geometry_nodes",
379
+ "apply_geometric_phase",
380
+ "heights_on_output_grid",
381
+ "AtmosphereError",
382
+ "GeometryProcessingError",
383
+ "UnwrapError",
384
+ "ModelLoadError",
385
+ "UnwrapDependencyError",
386
+ "LearnedUnwrapConfig",
387
+ "LearnedUnwrapper",
388
+ "LearnedUnwrapResult",
389
+ "UnwrapModel",
390
+ "load_unwrap_model",
391
+ "unwrap_diagnostics",
392
+ "unwrap_interferograms",
393
+ "HybridConfig",
394
+ "HybridUnwrapper",
395
+ "HybridUnwrapResult",
396
+ "tie_components",
298
397
  "SLCExtractor",
299
398
  "DataValidator",
300
399
  "ValidationResult",
@@ -686,8 +686,15 @@ def compute_offset_field(
686
686
  return grid_rows, grid_cols, offset_rows, offset_cols
687
687
 
688
688
 
689
- def _sample_complex_imagette(data, center_row: float, center_col: float, size: int):
689
+ def _sample_complex_imagette(data, center_row: float, center_col: float, size: int,
690
+ phase_ramp=None, row_offset: float = 0.0, col_offset: float = 0.0):
690
691
  """
692
+ With ``phase_ramp`` (a TOPS ramp, see resample_with_offset_field), the
693
+ neighbourhood is deramped before the bilinear interpolation and the
694
+ imagette is reramped at the sampled (full-scene) positions, so a
695
+ sub-pixel shift of a TOPS burst keeps its phase; ``row_offset`` and
696
+ ``col_offset`` are `data`'s origin in full-scene coordinates.
697
+
691
698
  Extract a `size` x `size` complex imagette centered at an
692
699
  arbitrary (possibly sub-pixel, possibly out-of-bounds) position via
693
700
  bilinear interpolation. Positions outside `data` read as 0+0j
@@ -704,6 +711,25 @@ def _sample_complex_imagette(data, center_row: float, center_col: float, size: i
704
711
  row_idx = row_idx - half + center_row
705
712
  col_idx = col_idx - half + center_col
706
713
 
714
+ if phase_ramp is not None:
715
+ h, w = data.shape
716
+ r0 = max(0, int(np.floor(row_idx.min())) - 1)
717
+ r1 = min(h, int(np.ceil(row_idx.max())) + 2)
718
+ c0 = max(0, int(np.floor(col_idx.min())) - 1)
719
+ c1 = min(w, int(np.ceil(col_idx.max())) + 2)
720
+ if r1 <= r0 or c1 <= c0:
721
+ return np.zeros((size, size), dtype=np.complex64)
722
+ block = data[r0:r1, c0:c1].astype(np.complex128)
723
+ rows_g = np.arange(r0, r1, dtype=np.float64)[:, None] + row_offset
724
+ cols_g = np.arange(c0, c1, dtype=np.float64)[None, :] + col_offset
725
+ block = block * np.exp(-1j * phase_ramp(rows_g, cols_g))
726
+ coords = [row_idx - r0, col_idx - c0]
727
+ out = map_coordinates(block.real, coords, order=1, mode="constant", cval=0.0) + 1j * map_coordinates(
728
+ block.imag, coords, order=1, mode="constant", cval=0.0
729
+ )
730
+ out = out * np.exp(1j * phase_ramp(row_idx + row_offset, col_idx + col_offset))
731
+ return out.astype(np.complex64)
732
+
707
733
  real = map_coordinates(
708
734
  data.real, [row_idx, col_idx], order=1, mode="constant", cval=0.0
709
735
  )
@@ -761,6 +787,8 @@ def refine_offsets_by_coherence(
761
787
  coarse_search_radius: int = 4,
762
788
  fine_search_radius: float = 1.5,
763
789
  coherence_threshold: float = 0.3,
790
+ ref_phase_ramp=None,
791
+ sec_phase_ramp=None,
764
792
  ):
765
793
  """
766
794
  Refine an orbit/DEM-derived offset field against the actual image
@@ -864,7 +892,8 @@ def refine_offsets_by_coherence(
864
892
  continue
865
893
 
866
894
  ref_imagette = _sample_complex_imagette(
867
- ref_complex, ref_local_row, ref_local_col, window
895
+ ref_complex, ref_local_row, ref_local_col, window,
896
+ phase_ramp=ref_phase_ramp, row_offset=ref_row_offset, col_offset=ref_col_offset,
868
897
  )
869
898
 
870
899
  # --- Coarse stage: integer-pixel cross-correlation search ---
@@ -872,7 +901,8 @@ def refine_offsets_by_coherence(
872
901
  for dr in range(-coarse_search_radius, coarse_search_radius + 1):
873
902
  for dc in range(-coarse_search_radius, coarse_search_radius + 1):
874
903
  sec_imagette = _sample_complex_imagette(
875
- sec_complex, sec_local_row + dr, sec_local_col + dc, window
904
+ sec_complex, sec_local_row + dr, sec_local_col + dc, window,
905
+ phase_ramp=sec_phase_ramp, row_offset=sec_row_offset, col_offset=sec_col_offset,
876
906
  )
877
907
  coh = _imagette_coherence(ref_imagette, sec_imagette)
878
908
  if coh > best_coh:
@@ -883,7 +913,8 @@ def refine_offsets_by_coherence(
883
913
  shift, _row0=sec_local_row + best_dr, _col0=sec_local_col + best_dc
884
914
  ):
885
915
  sec_imagette = _sample_complex_imagette(
886
- sec_complex, _row0 + shift[0], _col0 + shift[1], window
916
+ sec_complex, _row0 + shift[0], _col0 + shift[1], window,
917
+ phase_ramp=sec_phase_ramp, row_offset=sec_row_offset, col_offset=sec_col_offset,
887
918
  )
888
919
  return -_imagette_coherence(ref_imagette, sec_imagette)
889
920
 
@@ -1343,6 +1374,7 @@ def resample_with_offset_field(
1343
1374
  ref_col_offset: float = 0.0,
1344
1375
  sec_row_offset: float = 0.0,
1345
1376
  sec_col_offset: float = 0.0,
1377
+ phase_ramp=None,
1346
1378
  ):
1347
1379
  """
1348
1380
  Resample a complex array using a real, per-pixel offset field
@@ -1370,6 +1402,18 @@ def resample_with_offset_field(
1370
1402
  offset than the reference crop.
1371
1403
  All four default to 0 for already-full-scene
1372
1404
  (uncropped) data.
1405
+ phase_ramp: Optional callable ``phase_ramp(rows, cols)`` giving
1406
+ the azimuth phase ramp (rad) that `data` carries at
1407
+ full-scene secondary positions -- for Sentinel-1
1408
+ TOPS bursts, :meth:`pygeofetch.insar.tops.TopsRamp.phase`.
1409
+ When given, `data` is deramped (multiplied by
1410
+ exp(-i ramp)) before interpolation and the result is
1411
+ reramped with the ramp at the positions sampled. A
1412
+ TOPS burst's Doppler centroid sweeps by ~5 kHz, ten
1413
+ times the azimuth sampling rate, so interpolating it
1414
+ without deramping corrupts its phase (fringes along
1415
+ azimuth that jump at burst edges) and its coherence.
1416
+ `data` itself is not modified.
1373
1417
 
1374
1418
  Returns:
1375
1419
  The resampled complex array, on the reference image's grid.
@@ -1400,6 +1444,15 @@ def resample_with_offset_field(
1400
1444
  # One complex64 output filled tile by tile. The previous version built two float32 planes and then
1401
1445
  # (out_real + 1j * out_imag).astype(complex64), which held about four extra full-size arrays at the end.
1402
1446
  out = np.empty((h, w), dtype=np.complex64)
1447
+ if phase_ramp is not None:
1448
+ # Deramp a copy of the secondary on its own grid (baseband), in row chunks.
1449
+ work = np.array(data, dtype=np.complex64, copy=True)
1450
+ sec_cols_global = np.arange(work.shape[1], dtype=np.float64)[None, :] + sec_col_offset
1451
+ for r0 in range(0, work.shape[0], 512):
1452
+ r1 = min(work.shape[0], r0 + 512)
1453
+ rows_global = np.arange(r0, r1, dtype=np.float64)[:, None] + sec_row_offset
1454
+ work[r0:r1] *= np.exp(-1j * phase_ramp(rows_global, sec_cols_global)).astype(np.complex64)
1455
+ data = work
1403
1456
  data_real = data.real
1404
1457
  data_imag = data.imag
1405
1458
 
@@ -1448,6 +1501,10 @@ def resample_with_offset_field(
1448
1501
  mode="constant",
1449
1502
  cval=0.0,
1450
1503
  )
1504
+ if phase_ramp is not None:
1505
+ tile *= np.exp(
1506
+ 1j * phase_ramp(sample_rows_2d + sec_row_offset, sample_cols_2d + sec_col_offset)
1507
+ ).astype(np.complex64)
1451
1508
 
1452
1509
  del sample_rows_2d, sample_cols_2d, offset_row, offset_col
1453
1510
 
@@ -612,6 +612,9 @@ class InterferogramGenerator:
612
612
  # metadata cannot be parsed for either date (a real, logged,
613
613
  # non-fatal degradation).
614
614
  self._use_real_burst_processing = use_real_burst_processing
615
+ self._tops_ctx = None
616
+ # Part of every pair fingerprint: results saved before TOPS deramping (version 0) are not reused.
617
+ self._tops_deramp_version = 1
615
618
  # Automatic by default (None): on when the inputs exist, explicit
616
619
  # True/False always respected. It used to be opt-in and silent, which
617
620
  # left a full-width range ramp in every interferogram unless the caller
@@ -1384,12 +1387,22 @@ class InterferogramGenerator:
1384
1387
  # structure as the shared row-coordinate system for
1385
1388
  # comparing reference and secondary at the same real rows.
1386
1389
  if self._esd_enabled:
1390
+ # Doppler separation of the two looks in the overlaps, from this swath's own annotation when the
1391
+ # TOPS parameters were parsed (~4.8 kHz for IW2, not the 5.2 kHz maximum); the published
1392
+ # constant otherwise. Positive, as the ESD estimator's sign convention expects.
1393
+ _ctx = getattr(self, "_tops_ctx", None)
1394
+ _df = None
1395
+ if _ctx is not None:
1396
+ _df = abs(_ctx["ref_ramp"].overlap_doppler_difference_hz())
1397
+ metadata["esd_delta_f_ovl_hz"] = _df
1398
+ _esd_kwargs = {} if _df is None or not (_df > 0) else {"delta_f_ovl_hz": _df}
1387
1399
  esd_shift_s, per_overlap = estimate_esd_shift_per_burst_overlap(
1388
1400
  ref_complex,
1389
1401
  sec_complex,
1390
1402
  ref_burst_info,
1391
1403
  azimuth_time_interval_s,
1392
1404
  row_offset=int(ref_row_off),
1405
+ **_esd_kwargs,
1393
1406
  )
1394
1407
  if esd_shift_s is not None:
1395
1408
  esd_shift_px = esd_shift_s / azimuth_time_interval_s
@@ -1415,7 +1428,7 @@ class InterferogramGenerator:
1415
1428
  try:
1416
1429
  resid_s, _ = estimate_esd_shift_per_burst_overlap(
1417
1430
  ref_complex, sec_complex, ref_burst_info, azimuth_time_interval_s,
1418
- row_offset=int(ref_row_off),
1431
+ row_offset=int(ref_row_off), **_esd_kwargs,
1419
1432
  )
1420
1433
  metadata["esd_residual_after_correction_px"] = (
1421
1434
  None if resid_s is None else float(resid_s / azimuth_time_interval_s)
@@ -1548,7 +1561,8 @@ class InterferogramGenerator:
1548
1561
  _FINGERPRINT_EXCLUDED_ARGS = frozenset({
1549
1562
  "self", "chunk_rows", "use_chunked_processing", "output_dir", "resume", "save_visualizations",
1550
1563
  "min_coreg_gcps", "max_coreg_rms_px", "max_burst_sync_ms"})
1551
- _FINGERPRINT_EXCLUDED_SETTINGS = frozenset({"_use_gpu", "_chunk_size", "_on_error", "_coherence_backend", "_memory_guard"})
1564
+ _FINGERPRINT_EXCLUDED_SETTINGS = frozenset({"_use_gpu", "_chunk_size", "_on_error", "_coherence_backend", "_memory_guard",
1565
+ "_tops_ctx"})
1552
1566
 
1553
1567
  def _pair_fingerprint(self, arguments: Dict[str, Any]) -> Dict[str, Any]:
1554
1568
  """What a saved result depends on, from the process_pair arguments (all of them, defaults included)."""
@@ -1821,6 +1835,13 @@ class InterferogramGenerator:
1821
1835
  ProcessingError subclasses (all ValueError) when a step that was asked for fails, unless the
1822
1836
  generator was built with ``on_error="degrade"``.
1823
1837
  """
1838
+ # accept a plain (min_lon, min_lat, max_lon, max_lat) tuple as well as a BoundingBox
1839
+ if aoi_bbox is not None and not hasattr(aoi_bbox, "min_lon"):
1840
+ from pygeofetch.models.search_query import BoundingBox
1841
+
1842
+ aoi_bbox = BoundingBox(
1843
+ min_lon=aoi_bbox[0], min_lat=aoi_bbox[1], max_lon=aoi_bbox[2], max_lat=aoi_bbox[3]
1844
+ )
1824
1845
  # What this result depends on, taken before anything else is assigned. Used to decide on resume
1825
1846
  # whether a saved result was made by the same pipeline with the same inputs and settings.
1826
1847
  _fingerprint = self._pair_fingerprint(dict(locals()))
@@ -1854,6 +1875,8 @@ class InterferogramGenerator:
1854
1875
  ", ".join(_changed) or "unknown")
1855
1876
 
1856
1877
  quality = QualityRecord(on_error=self._on_error)
1878
+ # TOPS deramp context of this pair (set by _orbit_based_coregister, used by the ESD shift).
1879
+ self._tops_ctx = None
1857
1880
 
1858
1881
  # Resolve chunk size: explicit param > instance default > None (full)
1859
1882
  effective_chunk = chunk_rows if chunk_rows is not None else self._chunk_size
@@ -1946,6 +1969,11 @@ class InterferogramGenerator:
1946
1969
 
1947
1970
  # ── Step 1: Coregistration ──
1948
1971
  if coregistration_method == "raster_collocation":
1972
+ logger.warning(
1973
+ "coregistration_method='raster_collocation' resamples the secondary without TOPS deramping: "
1974
+ "for Sentinel-1 IW/EW bursts this corrupts the phase (fringes along azimuth, jumps at burst "
1975
+ "edges). Use coregistration_method='orbit_dem' for interferometry."
1976
+ )
1949
1977
  ref_has_geocoding = (
1950
1978
  profile.get("crs") is not None and profile.get("transform") is not None
1951
1979
  )
@@ -2557,6 +2585,12 @@ class InterferogramGenerator:
2557
2585
  "chunk_rows": effective_chunk,
2558
2586
  "esd_per_overlap_px": burst_metadata.get("esd_per_overlap_px"),
2559
2587
  "esd_overlap_std_px": burst_metadata.get("esd_overlap_std_px"),
2588
+ "tops_deramp": coreg_metadata.get("tops_deramp", False),
2589
+ "tops_deramp_reason": coreg_metadata.get("tops_deramp_reason"),
2590
+ "tops_sign": coreg_metadata.get("tops_sign"),
2591
+ "tops_sign_check_secondary": coreg_metadata.get("tops_sign_check_secondary"),
2592
+ "tops_doppler_rate_hz_s": coreg_metadata.get("tops_doppler_rate_hz_s"),
2593
+ "esd_delta_f_ovl_hz": burst_metadata.get("esd_delta_f_ovl_hz"),
2560
2594
  "esd_residual_after_correction_px": burst_metadata.get("esd_residual_after_correction_px"),
2561
2595
  "quality": quality.to_dict(),
2562
2596
  "quality_grade": quality.grade,
@@ -2820,6 +2854,36 @@ class InterferogramGenerator:
2820
2854
  b = src.bounds
2821
2855
  sample_bounds = (b.left, b.bottom, b.right, b.top)
2822
2856
 
2857
+ # TOPS (IW/EW) bursts must be deramped before any sub-pixel interpolation or shift: their Doppler
2858
+ # centroid sweeps ~5 kHz through each burst, so interpolating them directly corrupts the phase
2859
+ # (fringes along azimuth, jumps at burst edges) and biases the cross-correlation offsets.
2860
+ ref_ramp = sec_ramp = None
2861
+ tops_meta: Dict[str, Any] = {"tops_deramp": False}
2862
+ try:
2863
+ from pygeofetch.insar.tops import parse_tops_ramp
2864
+
2865
+ ref_ramp = parse_tops_ramp(reference_safe_zip, member_hint=ref_swath_hint)
2866
+ sec_ramp = parse_tops_ramp(secondary_safe_zip, member_hint=sec_swath_hint)
2867
+ sec_scores = sec_ramp.calibrate_sign(sec_complex, sec_row_off, sec_col_off)
2868
+ ref_scores = ref_ramp.calibrate_sign(ref_complex, ref_row_off, ref_col_off)
2869
+ tops_meta = {
2870
+ "tops_deramp": True,
2871
+ "tops_sign": sec_ramp.sign,
2872
+ "tops_sign_check_secondary": {k: (float(v) if isinstance(v, (int, float)) else v)
2873
+ for k, v in sec_scores.items()},
2874
+ "tops_sign_check_reference": {k: (float(v) if isinstance(v, (int, float)) else v)
2875
+ for k, v in ref_scores.items()},
2876
+ "tops_doppler_rate_hz_s": ref_ramp.doppler_rate_hz_s(),
2877
+ "tops_overlap_doppler_difference_hz": ref_ramp.overlap_doppler_difference_hz(),
2878
+ }
2879
+ if ref_ramp.sign != sec_ramp.sign:
2880
+ logger.warning("TOPS deramp sign differs between reference (%+d) and secondary (%+d)",
2881
+ int(ref_ramp.sign), int(sec_ramp.sign))
2882
+ except Exception as exc: # stripmap, or annotation without the TOPS fields
2883
+ ref_ramp = sec_ramp = None
2884
+ tops_meta = {"tops_deramp": False, "tops_deramp_reason": str(exc)}
2885
+ logger.info("No TOPS deramping for this pair (%s)", exc)
2886
+
2823
2887
  grid_rows, grid_cols, off_rows, off_cols = compute_offset_field_from_dem(
2824
2888
  ref_geom,
2825
2889
  ref_orbit,
@@ -2867,6 +2931,8 @@ class InterferogramGenerator:
2867
2931
  ref_col_offset=ref_col_off,
2868
2932
  sec_row_offset=sec_row_off,
2869
2933
  sec_col_offset=sec_col_off,
2934
+ ref_phase_ramp=None if ref_ramp is None else ref_ramp.phase,
2935
+ sec_phase_ramp=None if sec_ramp is None else sec_ramp.phase,
2870
2936
  **refine_kwargs,
2871
2937
  )
2872
2938
  )
@@ -2928,6 +2994,7 @@ class InterferogramGenerator:
2928
2994
  "representative_row_offset_px": representative_row_offset,
2929
2995
  "coreg_mode": coreg_quality.mode,
2930
2996
  "n_geometry_points": coreg_quality.n_geometry_points,
2997
+ **tops_meta,
2931
2998
  }
2932
2999
 
2933
3000
  if ref_row_off or ref_col_off or sec_row_off or sec_col_off:
@@ -2954,9 +3021,17 @@ class InterferogramGenerator:
2954
3021
  ref_col_offset=ref_col_off,
2955
3022
  sec_row_offset=sec_row_off,
2956
3023
  sec_col_offset=sec_col_off,
3024
+ phase_ramp=None if sec_ramp is None else sec_ramp.phase,
2957
3025
  )
2958
3026
  if resampled.shape != ref_complex.shape:
2959
3027
  resampled = self._resample_to_reference(resampled, ref_complex.shape)
3028
+ elif sec_ramp is not None:
3029
+ # Remember where the resampled secondary's samples came from, so a later azimuth shift (ESD)
3030
+ # can deramp and reramp it with the right phase.
3031
+ self._tops_ctx = {
3032
+ "ref_ramp": ref_ramp, "sec_ramp": sec_ramp, "row_fn": row_fn, "col_fn": col_fn,
3033
+ "ref_row_off": float(ref_row_off), "ref_col_off": float(ref_col_off),
3034
+ }
2960
3035
  return resampled, coreg_metadata
2961
3036
 
2962
3037
  except Exception as exc:
@@ -3195,6 +3270,25 @@ class InterferogramGenerator:
3195
3270
  the whole-array ones. Written into ``data`` when that is a plain writable complex64 array of its own
3196
3271
  (every caller replaces its variable with the return value); otherwise into a new array."""
3197
3272
  np = self._np()
3273
+ ctx = getattr(self, "_tops_ctx", None)
3274
+ if ctx is not None:
3275
+ # TOPS: deramp with the phase the resampled secondary carries, shift at baseband, reramp at the
3276
+ # shifted positions (see pygeofetch.insar.tops.shift_azimuth_tops). A plain Fourier shift of a
3277
+ # TOPS burst moves its amplitude but leaves a 2 pi f_DC * shift phase error that ramps through
3278
+ # every burst.
3279
+ from pygeofetch.insar.tops import shift_azimuth_tops
3280
+
3281
+ sec_ramp, row_fn, col_fn = ctx["sec_ramp"], ctx["row_fn"], ctx["col_fn"]
3282
+ r_off, c_off = ctx["ref_row_off"], ctx["ref_col_off"]
3283
+
3284
+ def content_phase(rows, cols):
3285
+ rg = np.asarray(rows, dtype=np.float64) + r_off
3286
+ cg = np.asarray(cols, dtype=np.float64) + c_off
3287
+ return sec_ramp.phase(rg + np.asarray(row_fn(rg, cg), dtype=np.float64),
3288
+ cg + np.asarray(col_fn(rg, cg), dtype=np.float64))
3289
+
3290
+ return shift_azimuth_tops(np.asarray(data), float(shift_px), content_phase,
3291
+ ctx["ref_ramp"].lines_per_burst, r_off)
3198
3292
  h, w = data.shape
3199
3293
  freq = np.fft.fftfreq(h).reshape(-1, 1)
3200
3294
  ramp = np.exp(-2j * np.pi * freq * shift_px)