PyGeoFetch 2.6.9.0__py3-none-any.whl → 2.6.9.2__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.0.4"
33
+ __version__ = "2.6.9.2.4"
34
34
  __author__ = "PyGeoFetch Contributors"
35
35
  __license__ = "MIT"
36
36
 
@@ -148,6 +148,12 @@ from pygeofetch.insar.gpu import gpu_available
148
148
  from pygeofetch.insar.errors import (
149
149
  BurstProcessingError, CoregistrationError, CropError, FlatEarthError, InputError, ProcessingError,
150
150
  QualityRecord, TopographicPhaseError, AtmosphereError, GeometryProcessingError,
151
+ UnwrapError, ModelLoadError, UnwrapDependencyError,
152
+ )
153
+ from pygeofetch.insar.hybrid_unwrap import HybridConfig, HybridUnwrapper, HybridUnwrapResult, tie_components
154
+ from pygeofetch.insar.learned_unwrap import (
155
+ LearnedUnwrapConfig, LearnedUnwrapper, LearnedUnwrapResult, UnwrapModel, load_unwrap_model,
156
+ unwrap_diagnostics, unwrap_interferograms,
151
157
  )
152
158
  from pygeofetch.insar.interferogram import InterferogramGenerator, InterferogramResult
153
159
  from pygeofetch.insar.ionosphere import IonosphericCorrector, parse_ionex
@@ -255,28 +261,11 @@ from pygeofetch.insar.visualize import (
255
261
  from pygeofetch.insar.workflow import InSARProject
256
262
 
257
263
  __all__ = [
258
- "ProcessingError",
259
- "InputError",
260
- "CoregistrationError",
261
- "BurstProcessingError",
262
- "FlatEarthError",
263
- "TopographicPhaseError",
264
- "CropError",
265
- "QualityRecord",
266
- "PSStack",
267
- "PSSelection",
268
- "PSSelector",
269
- "ADISelector",
270
- "build_ps_stack",
271
- "build_stack",
272
- "select_ps",
273
- "compare_selections",
274
- "holdout_stability",
275
- "residual_phase_coherence",
276
- "stability_weights",
277
- "choose_master",
278
- "boost_coherence_with_ps",
279
- "compare_velocity_maps",
264
+ "ProcessingError", "InputError", "CoregistrationError", "BurstProcessingError", "FlatEarthError",
265
+ "TopographicPhaseError", "CropError", "QualityRecord",
266
+ "PSStack", "PSSelection", "PSSelector", "ADISelector", "build_ps_stack", "build_stack",
267
+ "select_ps", "compare_selections", "holdout_stability", "residual_phase_coherence",
268
+ "stability_weights", "choose_master", "boost_coherence_with_ps", "compare_velocity_maps",
280
269
  "InterferogramGenerator",
281
270
  "InterferogramResult",
282
271
  "PhaseUnwrapper",
@@ -299,18 +288,12 @@ __all__ = [
299
288
  "despike_velocity",
300
289
  "InterferogramPair",
301
290
  "TimeSeriesResult",
302
- "AtmosphericCorrector",
303
- "estimate_height_slopes_per_date",
304
- "fit_height_dependence",
305
- "structure_function",
306
- "variance_reduction",
307
- "GeometryNodes",
308
- "PixelFrame",
309
- "compute_geometry_nodes",
310
- "apply_geometric_phase",
311
- "heights_on_output_grid",
312
- "AtmosphereError",
313
- "GeometryProcessingError",
291
+ "AtmosphericCorrector", "estimate_height_slopes_per_date", "fit_height_dependence", "structure_function",
292
+ "variance_reduction", "GeometryNodes", "PixelFrame", "compute_geometry_nodes", "apply_geometric_phase",
293
+ "heights_on_output_grid", "AtmosphereError", "GeometryProcessingError",
294
+ "UnwrapError", "ModelLoadError", "UnwrapDependencyError", "LearnedUnwrapConfig", "LearnedUnwrapper",
295
+ "LearnedUnwrapResult", "UnwrapModel", "load_unwrap_model", "unwrap_diagnostics", "unwrap_interferograms",
296
+ "HybridConfig", "HybridUnwrapper", "HybridUnwrapResult", "tie_components",
314
297
  "SLCExtractor",
315
298
  "DataValidator",
316
299
  "ValidationResult",
@@ -80,6 +80,11 @@ class CoregistrationQuality:
80
80
  # Populated by callers that ran refine_offsets_by_coherence() before
81
81
  # fitting; None if the field going into the fit was orbit/DEM-only.
82
82
  mean_coherence: Optional[float] = None
83
+ # Set by fit_geometry_first_offsets(): how the final field was built
84
+ # ("geometry_only", "geometry+constant" or "geometry+linear") and how many
85
+ # orbit/DEM points defined the base field. None for the plain polynomial fit.
86
+ mode: Optional[str] = None
87
+ n_geometry_points: Optional[int] = None
83
88
 
84
89
  def log_summary(self, level: int = logging.INFO) -> None:
85
90
  coh_part = (
@@ -133,6 +138,8 @@ class CoregistrationQuality:
133
138
  "iterations_used": self.iterations_used,
134
139
  "degree": self.degree,
135
140
  "mean_coherence": self.mean_coherence,
141
+ "mode": self.mode,
142
+ "n_geometry_points": self.n_geometry_points,
136
143
  }
137
144
 
138
145
 
@@ -1004,6 +1011,9 @@ def fit_offset_polynomial_robust(
1004
1011
  degree: int = 1,
1005
1012
  max_iterations: int = 2,
1006
1013
  rms_threshold: Optional[float] = None,
1014
+ outlier_rule: str = "mad",
1015
+ mad_k: float = 3.0,
1016
+ mad_floor_px: float = 0.05,
1007
1017
  ):
1008
1018
  """
1009
1019
  Fit row and column offset polynomials with SNAP WarpOp-style
@@ -1033,6 +1043,15 @@ def fit_offset_polynomial_robust(
1033
1043
  each GCP, in pixels.
1034
1044
  degree: Warp polynomial order (1, 2, or 3).
1035
1045
  max_iterations: Number of mean-RMS filtering passes (SNAP: 2).
1046
+ outlier_rule: "mad" (default): reject GCPs whose RMS exceeds
1047
+ median + mad_k * 1.4826 * MAD (scale floored at
1048
+ mad_floor_px), and never reduce the set below the
1049
+ minimum the degree needs. "mean": SNAP WarpOp's
1050
+ rule (reject every GCP above the mean RMS). The mean
1051
+ rule removes roughly half the points on every pass
1052
+ even when all are good, which on a sparse
1053
+ low-coherence GCP set leaves 3 points and a fit that
1054
+ passes exactly through their noise.
1036
1055
  rms_threshold: Optional final absolute RMS cutoff, in pixels.
1037
1056
  None (default) skips this and relies only on
1038
1057
  the iterative mean-RMS filtering above, which
@@ -1102,8 +1121,21 @@ def fit_offset_polynomial_robust(
1102
1121
  if iteration == max_iterations:
1103
1122
  break
1104
1123
 
1105
- mean_rms = float(np.mean(rms))
1106
- is_outlier = rms > mean_rms
1124
+ if outlier_rule == "mean":
1125
+ is_outlier = rms > float(np.mean(rms))
1126
+ elif outlier_rule == "mad":
1127
+ med = float(np.median(rms))
1128
+ scale = max(1.4826 * float(np.median(np.abs(rms - med))), mad_floor_px)
1129
+ is_outlier = rms > med + mad_k * scale
1130
+ # never reject below what the degree needs: drop the worst first
1131
+ if rms.size - int(np.count_nonzero(is_outlier)) < min_gcps:
1132
+ n_drop = max(rms.size - min_gcps, 0)
1133
+ worst = np.argsort(rms)[::-1][:n_drop]
1134
+ cand = np.zeros_like(is_outlier)
1135
+ cand[worst] = True
1136
+ is_outlier = cand & is_outlier
1137
+ else:
1138
+ raise ValueError(f"outlier_rule must be 'mad' or 'mean', got {outlier_rule!r}")
1107
1139
  if not np.any(is_outlier):
1108
1140
  break # converged -- nothing left to reject
1109
1141
 
@@ -1159,6 +1191,150 @@ def fit_offset_polynomial_robust(
1159
1191
  return row_fn, col_fn, quality
1160
1192
 
1161
1193
 
1194
+ def fit_geometry_first_offsets(
1195
+ geom_rows,
1196
+ geom_cols,
1197
+ geom_offset_rows,
1198
+ geom_offset_cols,
1199
+ xc_rows,
1200
+ xc_cols,
1201
+ xc_offset_rows,
1202
+ xc_offset_cols,
1203
+ degree: int = 1,
1204
+ min_points_linear: int = 8,
1205
+ min_points_constant: int = 2,
1206
+ mad_k: float = 3.0,
1207
+ mad_floor_px: float = 0.05,
1208
+ max_iterations: int = 2,
1209
+ ):
1210
+ """
1211
+ Build the final offset field from the orbit/DEM geometry, corrected by
1212
+ image content only as far as the image content can support.
1213
+
1214
+ The orbit/DEM field is dense (tens of points) and physically grounded
1215
+ but can carry a bias from orbit timing or DEM datum errors. Cross-
1216
+ correlation offsets are image-based but sparse and noisy at low
1217
+ coherence (at gamma 0.3 only a handful of windows pass the threshold).
1218
+ Fitting a plane through 3-5 of them, as a free polynomial, gives a
1219
+ field that passes through their noise and extrapolates it across the
1220
+ scene. Instead:
1221
+
1222
+ 1. Fit the geometry points with a degree-`degree` polynomial (g).
1223
+ 2. Take d = xcorr offset - g at the cross-correlation points.
1224
+ 3. Reject outliers in d with median + k*MAD (at most `max_iterations`
1225
+ passes, never below `min_points_constant`).
1226
+ 4. Correct g by a model only as rich as the surviving points support:
1227
+ >= min_points_linear points -> degree-1 correction,
1228
+ >= min_points_constant -> constant (median) correction,
1229
+ otherwise -> none (geometry only).
1230
+
1231
+ Returns (row_fn, col_fn, quality): evaluable f(row, col) -> offset, and
1232
+ a CoregistrationQuality with .mode and .n_gcps_final = number of
1233
+ cross-correlation points that support the correction.
1234
+ """
1235
+ import numpy as np
1236
+
1237
+ gr = np.asarray(geom_rows, dtype=np.float64)
1238
+ gc = np.asarray(geom_cols, dtype=np.float64)
1239
+ gor = np.asarray(geom_offset_rows, dtype=np.float64)
1240
+ goc = np.asarray(geom_offset_cols, dtype=np.float64)
1241
+ xr = np.asarray(xc_rows, dtype=np.float64)
1242
+ xcl = np.asarray(xc_cols, dtype=np.float64)
1243
+ xor_ = np.asarray(xc_offset_rows, dtype=np.float64)
1244
+ xoc = np.asarray(xc_offset_cols, dtype=np.float64)
1245
+
1246
+ deg = degree
1247
+ while deg > 1 and gr.size < _min_points_for_degree(deg):
1248
+ deg -= 1
1249
+ if gr.size < _min_points_for_degree(deg):
1250
+ raise RuntimeError(
1251
+ f"fit_geometry_first_offsets: only {gr.size} orbit/DEM points; "
1252
+ f"a degree-{deg} geometry fit needs {_min_points_for_degree(deg)}."
1253
+ )
1254
+ g_row = fit_offset_polynomial(gr, gc, gor, degree=deg)
1255
+ g_col = fit_offset_polynomial(gr, gc, goc, degree=deg)
1256
+
1257
+ n_xc = int(xr.size)
1258
+ dr = np.empty(0)
1259
+ dc = np.empty(0)
1260
+ keep = np.zeros(n_xc, dtype=bool)
1261
+ iterations_used = 0
1262
+ if n_xc:
1263
+ dr = xor_ - g_row(xr, xcl)
1264
+ dc = xoc - g_col(xr, xcl)
1265
+ keep = np.ones(n_xc, dtype=bool)
1266
+ for it in range(max_iterations):
1267
+ idx = np.nonzero(keep)[0]
1268
+ if idx.size <= min_points_constant:
1269
+ break
1270
+ mr, mc = float(np.median(dr[idx])), float(np.median(dc[idx]))
1271
+ dist = np.hypot(dr[idx] - mr, dc[idx] - mc)
1272
+ med = float(np.median(dist))
1273
+ scale = max(1.4826 * float(np.median(np.abs(dist - med))), mad_floor_px)
1274
+ bad = dist > med + mad_k * scale
1275
+ if not np.any(bad) or idx.size - int(bad.sum()) < min_points_constant:
1276
+ break
1277
+ keep[idx[bad]] = False
1278
+ iterations_used = it + 1
1279
+
1280
+ idx = np.nonzero(keep)[0]
1281
+ n_support = int(idx.size)
1282
+
1283
+ def _zero(r, c):
1284
+ return np.zeros_like(np.asarray(r, dtype=np.float64) + np.asarray(c, dtype=np.float64))
1285
+
1286
+ corr_row = corr_col = _zero
1287
+ mode = "geometry_only"
1288
+ if n_support >= min_points_linear:
1289
+ try:
1290
+ corr_row = fit_offset_polynomial(xr[idx], xcl[idx], dr[idx], degree=1)
1291
+ corr_col = fit_offset_polynomial(xr[idx], xcl[idx], dc[idx], degree=1)
1292
+ mode = "geometry+linear"
1293
+ except Exception:
1294
+ corr_row = corr_col = _zero
1295
+ if mode == "geometry_only" and n_support >= min_points_constant:
1296
+ cr, cc_ = float(np.median(dr[idx])), float(np.median(dc[idx]))
1297
+
1298
+ def corr_row(r, c, _v=cr):
1299
+ return np.full_like(np.asarray(r, dtype=np.float64) + np.asarray(c, dtype=np.float64), _v)
1300
+
1301
+ def corr_col(r, c, _v=cc_):
1302
+ return np.full_like(np.asarray(r, dtype=np.float64) + np.asarray(c, dtype=np.float64), _v)
1303
+
1304
+ mode = "geometry+constant"
1305
+
1306
+ def row_fn(r, c):
1307
+ return g_row(r, c) + corr_row(r, c)
1308
+
1309
+ def col_fn(r, c):
1310
+ return g_col(r, c) + corr_col(r, c)
1311
+
1312
+ if n_support:
1313
+ er = row_fn(xr[idx], xcl[idx]) - xor_[idx]
1314
+ ec = col_fn(xr[idx], xcl[idx]) - xoc[idx]
1315
+ rms = np.sqrt(er**2 + ec**2)
1316
+ quality = CoregistrationQuality(
1317
+ n_gcps_initial=n_xc, n_gcps_final=n_support, n_gcps_rejected=n_xc - n_support,
1318
+ rms_mean=float(np.mean(rms)), rms_std=float(np.std(rms)),
1319
+ row_residual_mean=float(np.mean(er)), row_residual_std=float(np.std(er)),
1320
+ col_residual_mean=float(np.mean(ec)), col_residual_std=float(np.std(ec)),
1321
+ per_point_rms=rms.tolist(), iterations_used=iterations_used, degree=deg,
1322
+ mode=mode, n_geometry_points=int(gr.size))
1323
+ else:
1324
+ quality = CoregistrationQuality(
1325
+ n_gcps_initial=n_xc, n_gcps_final=0, n_gcps_rejected=n_xc,
1326
+ rms_mean=0.0, rms_std=0.0, row_residual_mean=0.0, row_residual_std=0.0,
1327
+ col_residual_mean=0.0, col_residual_std=0.0, per_point_rms=[],
1328
+ iterations_used=iterations_used, degree=deg, mode=mode,
1329
+ n_geometry_points=int(gr.size))
1330
+ logger.info(
1331
+ "Geometry-first coregistration: %s from %d orbit/DEM points (degree-%d); %d/%d "
1332
+ "cross-correlation points support the correction%s",
1333
+ mode, gr.size, deg, n_support, n_xc,
1334
+ f", residual RMS {quality.rms_mean:.3f} px" if n_support else " (image content did not constrain it)")
1335
+ return row_fn, col_fn, quality
1336
+
1337
+
1162
1338
  def resample_with_offset_field(
1163
1339
  data,
1164
1340
  row_offset_fn,
@@ -1325,4 +1501,4 @@ def _linspace(start, stop, n):
1325
1501
  if n == 1:
1326
1502
  return [start]
1327
1503
  step = (stop - start) / (n - 1)
1328
- return [start + i * step for i in range(n)]
1504
+ return [start + i * step for i in range(n)]
@@ -71,6 +71,18 @@ class CropError(ProcessingError):
71
71
  """The AOI crop was requested and could not be done (the caller would otherwise get a different extent than asked)."""
72
72
 
73
73
 
74
+ class UnwrapError(ProcessingError):
75
+ """Phase unwrapping was requested and failed (a tile could not be predicted, the output is not finite, no valid pixels)."""
76
+
77
+
78
+ class ModelLoadError(UnwrapError):
79
+ """A learned-unwrapping checkpoint could not be loaded or does not match the model it is meant for."""
80
+
81
+
82
+ class UnwrapDependencyError(UnwrapError):
83
+ """A package a learned unwrapper needs (torch, pyunwrap) is not installed."""
84
+
85
+
74
86
  # ---------------------------------------------------------------------------------------------------------
75
87
 
76
88
 
@@ -0,0 +1,324 @@
1
+ """Hybrid phase unwrapping: SNAPHU where it is reliable, the pyunwrap network where it is not.
2
+
3
+ What is different from pyunwrap's own ``HybridUnwrapper``
4
+ ---------------------------------------------------------
5
+ Both unwrappers return an integer cycle map ``k`` that is only defined up to a whole number of cycles, and SNAPHU
6
+ defines it separately for every connected component (a real run on a scene split by a dead band gave two components at
7
+ offsets of 0 and -1 cycles from the truth). pyunwrap's hybrid picks ``k`` per pixel from one method or the other
8
+ without removing those offsets, so every boundary between the two sources is a cycle jump, and its own "SNAPHU +
9
+ do-nothing" control loses 15 points to SNAPHU alone on the hard scenes (47.4 % against 63.2 %).
10
+
11
+ Here every SNAPHU component is tied to the network's global cycle frame before any pixel is exchanged: the offset is
12
+ the most common whole-cycle difference ``k_network - k_snaphu`` over pixels where both are trusted and coherence is
13
+ at least ``offset_min_coherence``. A component whose pixels do not agree on one offset (``min_offset_agreement``) or
14
+ that is too small is *not* tied; it keeps SNAPHU's own offset, is labelled as such (provenance 3, its own
15
+ ``conncomp`` label) and raises the flag ``component_offset_uncertain``.
16
+
17
+ Which method supplies which pixel
18
+ ---------------------------------
19
+ * coherence at or below ``low_coherence``: the network (SNAPHU integrates through noise there);
20
+ * pixels SNAPHU left out of every component (``conncomp == 0``): the network, if it trusts them;
21
+ * everything else: SNAPHU, shifted into the network's frame.
22
+
23
+ A pixel is reported as reliable only if the method that supplied it reports it reliable. The network's own gate
24
+ (coherence >= 0.3 by default) therefore still applies to the pixels it supplies, so the hybrid completes the field at
25
+ very low coherence but does not claim those pixels.
26
+
27
+ Defaults and what they rest on
28
+ ------------------------------
29
+ ``low_coherence = 0.15`` is the threshold chosen on the validation scenes in the training run's hybrid summary
30
+ (``low_threshold_chosen_on_val``). Those scenes are synthetic. Nothing here was tuned on real data, and the same
31
+ summary shows the tuned hybrid only equal to SNAPHU on its hard test scenes (63.3 % against 63.2 %). Expect the hybrid to
32
+ differ from SNAPHU mainly by tying components together and by filling regions SNAPHU dropped.
33
+
34
+ Error policy: ``on_error="raise"`` (default) raises ``UnwrapError`` if either method fails; ``"degrade"`` returns the
35
+ surviving method's result, records the failure and grades the result ``degraded``. If both fail it always raises.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import logging
41
+ import time
42
+ from dataclasses import asdict, dataclass
43
+ from pathlib import Path
44
+ from typing import Any, Dict, List, Optional, Tuple, Union
45
+
46
+ import numpy as np
47
+
48
+ from .errors import InputError, QualityRecord, UnwrapError
49
+ from .learned_unwrap import (
50
+ TWO_PI,
51
+ LearnedUnwrapper,
52
+ LearnedUnwrapResult,
53
+ _as_wrapped_phase,
54
+ unwrap_diagnostics,
55
+ )
56
+ from .unwrap import PhaseUnwrapper
57
+
58
+ logger = logging.getLogger("pygeofetch.insar.hybrid_unwrap")
59
+
60
+ PROV_NONE, PROV_CLASSICAL, PROV_LEARNED, PROV_CLASSICAL_UNTIED = 0, 1, 2, 3
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class HybridConfig:
65
+ low_coherence: float = 0.15 # at or below: the network supplies k (chosen on synthetic validation scenes)
66
+ learned_fills_classical_gaps: bool = True # pixels outside every SNAPHU component go to the network
67
+ offset_min_coherence: float = 0.4 # pixels used to tie a component to the network's frame
68
+ min_offset_pixels: int = 200 # fewer trusted pixels than this: the component is not tied
69
+ min_offset_agreement: float = 0.5 # share of those pixels that must sit at the modal offset
70
+ on_error: str = "raise"
71
+
72
+ def __post_init__(self) -> None:
73
+ if not 0.0 <= self.low_coherence <= 1.0:
74
+ raise ValueError("low_coherence must be in [0, 1]")
75
+ if not 0.0 < self.min_offset_agreement <= 1.0:
76
+ raise ValueError("min_offset_agreement must be in (0, 1]")
77
+ if self.min_offset_pixels < 1:
78
+ raise ValueError("min_offset_pixels must be >= 1")
79
+ if self.on_error not in ("raise", "degrade"):
80
+ raise ValueError("on_error must be 'raise' or 'degrade'")
81
+
82
+
83
+ @dataclass
84
+ class HybridUnwrapResult(LearnedUnwrapResult):
85
+ """``LearnedUnwrapResult`` plus ``provenance``: 0 none, 1 SNAPHU (tied), 2 network, 3 SNAPHU (not tied).
86
+
87
+ ``ambiguity_map`` is the merged cycle map. ``conncomp`` is 0 where the supplying method does not trust the pixel.
88
+ """
89
+
90
+ provenance: Any = None
91
+
92
+ def save(self, output_dir: Union[str, Path], save_png: bool = False, mask_unreliable: bool = True) -> Dict[str, Path]:
93
+ paths = super().save(output_dir, save_png=save_png, mask_unreliable=mask_unreliable)
94
+ if self.provenance is not None:
95
+ import rasterio
96
+
97
+ path = Path(output_dir) / "provenance.tif"
98
+ prof = {"driver": "GTiff", "count": 1, "height": self.provenance.shape[0], "width": self.provenance.shape[1],
99
+ "crs": self.profile.get("crs"), "transform": self.profile.get("transform"), "compress": "deflate",
100
+ "dtype": "uint8", "nodata": 255}
101
+ with rasterio.open(path, "w", **prof) as dst:
102
+ dst.write(np.asarray(self.provenance, dtype=np.uint8)[np.newaxis])
103
+ paths["provenance"] = path
104
+ return paths
105
+
106
+
107
+ def tie_components(
108
+ k_classical: np.ndarray,
109
+ components: np.ndarray,
110
+ k_learned: np.ndarray,
111
+ trusted: np.ndarray,
112
+ min_pixels: int = 200,
113
+ min_agreement: float = 0.5,
114
+ ) -> Tuple[np.ndarray, List[Dict[str, Any]]]:
115
+ """Whole-cycle offset that brings each SNAPHU component into the network's cycle frame.
116
+
117
+ ``trusted``: pixels where both methods may be compared. Returns ``(offsets_by_pixel, table)`` where
118
+ ``offsets_by_pixel`` holds the offset to add to ``k_classical`` (0 for components that could not be tied) and
119
+ ``table`` has one row per component: label, pixels, offset, agreement, tied.
120
+ """
121
+ offsets = np.zeros(k_classical.shape, dtype=np.float64)
122
+ table: List[Dict[str, Any]] = []
123
+ for c in np.unique(components[components > 0]):
124
+ in_c = components == c
125
+ m = in_c & trusted
126
+ n = int(m.sum())
127
+ row = {"label": int(c), "pixels": int(in_c.sum()), "trusted_pixels": n, "offset": 0, "agreement": float("nan"),
128
+ "tied": False}
129
+ if n >= min_pixels:
130
+ d = np.rint(k_learned[m] - k_classical[m]).astype(np.int64)
131
+ vals, counts = np.unique(d, return_counts=True)
132
+ j = int(np.argmax(counts))
133
+ agreement = float(counts[j] / n)
134
+ row["agreement"] = agreement
135
+ if agreement >= min_agreement:
136
+ row.update(offset=int(vals[j]), tied=True)
137
+ offsets[in_c] = float(vals[j])
138
+ table.append(row)
139
+ return offsets, table
140
+
141
+
142
+ class HybridUnwrapper:
143
+ """SNAPHU and the network, tied into one cycle frame.
144
+
145
+ hybrid = HybridUnwrapper(LearnedUnwrapper.from_checkpoint("model/best.pt", run_config="model/config.json"),
146
+ PhaseUnwrapper(cost_mode="defo", init_method="mcf"))
147
+ res = hybrid.unwrap_pair(phase_ml, coh_ml, profile, amplitude=amp_ml, nlooks=256.0)
148
+
149
+ The call signature matches ``LearnedUnwrapper.unwrap_pair`` plus the SNAPHU arguments, so ``unwrap_interferograms``
150
+ accepts it in place of the learned unwrapper.
151
+ """
152
+
153
+ def __init__(self, learned: LearnedUnwrapper, classical: Optional[PhaseUnwrapper] = None,
154
+ config: Optional[HybridConfig] = None):
155
+ self.learned = learned
156
+ self.classical = classical if classical is not None else PhaseUnwrapper()
157
+ self.config = config or HybridConfig()
158
+
159
+ # -- helpers ----------------------------------------------------------------------------------------
160
+ def _run_classical(self, psi0: np.ndarray, coh: np.ndarray, valid: np.ndarray, profile: Dict[str, Any],
161
+ nlooks: float, min_conncomp_frac: float, min_region_size: int):
162
+ return self.classical.unwrap_pair(
163
+ psi0, np.where(valid, coh, 0.0), profile, nlooks=nlooks, mask=valid,
164
+ min_conncomp_frac=min_conncomp_frac, min_region_size=min_region_size)
165
+
166
+ # -- public API -------------------------------------------------------------------------------------
167
+ def unwrap_pair(
168
+ self,
169
+ interferogram: Any,
170
+ coherence: Any,
171
+ profile: Dict[str, Any],
172
+ reference_date: Optional[str] = None,
173
+ secondary_date: Optional[str] = None,
174
+ nlooks: float = 1.0,
175
+ looks_azimuth: int = 1,
176
+ looks_range: int = 1,
177
+ amplitude: Optional[Any] = None,
178
+ mask: Optional[Any] = None,
179
+ pixel_size_m: Optional[Tuple[float, float]] = None,
180
+ min_region_size: int = 100,
181
+ min_conncomp_frac: float = 0.001,
182
+ ) -> HybridUnwrapResult:
183
+ cfg = self.config
184
+ t0 = time.time()
185
+ psi = _as_wrapped_phase(interferogram)
186
+ coh = np.asarray(coherence, dtype=np.float64)
187
+ if coh.shape != psi.shape:
188
+ raise InputError("unwrap_inputs", f"coherence shape {coh.shape} differs from the interferogram {psi.shape}")
189
+ valid = np.isfinite(psi) & np.isfinite(coh)
190
+ if mask is not None:
191
+ m = np.asarray(mask, dtype=bool)
192
+ if m.shape != psi.shape:
193
+ raise InputError("unwrap_inputs", f"mask shape {m.shape} differs from the interferogram {psi.shape}")
194
+ valid &= m
195
+ if not valid.any():
196
+ raise InputError("unwrap_inputs", "no valid pixel (everything is NaN or masked)")
197
+ psi0 = np.where(valid, psi, 0.0)
198
+
199
+ q = QualityRecord(on_error=cfg.on_error)
200
+ cl = le = None
201
+ errors: Dict[str, Exception] = {}
202
+
203
+ # -- the two unwrappers ---------------------------------------------------------------------
204
+ try:
205
+ cl = self._run_classical(psi0, coh, valid, profile, nlooks, min_conncomp_frac, min_region_size)
206
+ q.ok("classical", f"SNAPHU: {100 * cl.reliable_fraction:.1f}% of pixels in a component")
207
+ except Exception as exc: # noqa: BLE001 - policy below decides
208
+ errors["classical"] = exc
209
+ try:
210
+ le = self.learned.unwrap_pair(
211
+ psi, coh, profile, reference_date, secondary_date, nlooks, looks_azimuth, looks_range,
212
+ amplitude=amplitude, mask=mask, pixel_size_m=pixel_size_m, min_region_size=min_region_size)
213
+ except Exception as exc: # noqa: BLE001
214
+ errors["learned"] = exc
215
+
216
+ if len(errors) == 2:
217
+ raise UnwrapError("hybrid", "both unwrappers failed: SNAPHU: "
218
+ f"{type(errors['classical']).__name__}: {errors['classical']}; network: "
219
+ f"{type(errors['learned']).__name__}: {errors['learned']}") from errors["learned"]
220
+ if errors and cfg.on_error == "raise":
221
+ which, exc = next(iter(errors.items()))
222
+ raise UnwrapError("hybrid", f"the {'SNAPHU' if which == 'classical' else 'network'} unwrapper failed and "
223
+ f"on_error='raise': {type(exc).__name__}: {exc}") from exc
224
+
225
+ scaled_profile = (le.profile if le is not None else cl.profile)
226
+ if le is None: # network failed, degrade to SNAPHU alone
227
+ q.failed("learned", f"{type(errors['learned']).__name__}: {errors['learned']}", "hybrid_learned_failed")
228
+ return self._single(cl, psi, valid, coh, q, "classical", scaled_profile, reference_date, secondary_date,
229
+ nlooks, errors, t0, min_region_size)
230
+ for f in le.metadata["quality"]["flags"]:
231
+ q.flag(f)
232
+ q.ok("learned", f"network: {100 * le.reliable_fraction:.1f}% of pixels reliable, grade "
233
+ f"{le.metadata['quality']['grade']}")
234
+ if cl is None: # SNAPHU failed, degrade to the network alone
235
+ q.failed("classical", f"{type(errors['classical']).__name__}: {errors['classical']}", "hybrid_classical_failed")
236
+ return self._single(le, psi, valid, coh, q, "learned", scaled_profile, reference_date, secondary_date,
237
+ nlooks, errors, t0, min_region_size)
238
+
239
+ # -- tie SNAPHU's components into the network's cycle frame ---------------------------------
240
+ phi_c = np.asarray(cl.unwrapped_phase, dtype=np.float64)
241
+ cc = np.asarray(cl.conncomp)
242
+ k_c = np.where(np.isfinite(phi_c) & valid, np.rint((phi_c - psi0) / TWO_PI), 0.0)
243
+ k_l = np.asarray(le.ambiguity_map, dtype=np.float64)
244
+ trusted = valid & (cc > 0) & (le.conncomp > 0) & (coh >= cfg.offset_min_coherence)
245
+ offsets, table = tie_components(k_c, cc, k_l, trusted, cfg.min_offset_pixels, cfg.min_offset_agreement)
246
+ n_tied = sum(r["tied"] for r in table)
247
+ if table and n_tied < len(table):
248
+ q.flag("component_offset_uncertain")
249
+ if table:
250
+ q.ok("offset_alignment", f"{n_tied} of {len(table)} SNAPHU components tied to the network's cycle frame "
251
+ f"(offsets {[r['offset'] for r in table if r['tied']]})")
252
+ else:
253
+ q.flag("no_classical_component")
254
+ q.ok("offset_alignment", "SNAPHU returned no component; the network supplies every pixel")
255
+ tied_px = np.zeros(psi.shape, bool)
256
+ for r in table:
257
+ if r["tied"]:
258
+ tied_px |= cc == r["label"]
259
+
260
+ # -- choose a source per pixel ----------------------------------------------------------------
261
+ use_learned = valid & (coh <= cfg.low_coherence)
262
+ if cfg.learned_fills_classical_gaps:
263
+ use_learned |= valid & (cc == 0)
264
+ prov = np.zeros(psi.shape, dtype=np.uint8)
265
+ prov[valid & ~use_learned & tied_px] = PROV_CLASSICAL
266
+ prov[valid & ~use_learned & (cc > 0) & ~tied_px] = PROV_CLASSICAL_UNTIED
267
+ prov[use_learned] = PROV_LEARNED
268
+ k = np.where(prov == PROV_LEARNED, k_l, k_c + offsets)
269
+ unwrapped = np.where(valid, psi0 + TWO_PI * k, np.nan)
270
+
271
+ # -- reliability: only where the supplying method trusts the pixel ---------------------------
272
+ rel_aligned = ((prov == PROV_CLASSICAL) & (cc > 0)) | ((prov == PROV_LEARNED) & (le.conncomp > 0))
273
+ conncomp = LearnedUnwrapper._components(rel_aligned, min_region_size)
274
+ nxt = int(conncomp.max()) + 1
275
+ for r in table:
276
+ if not r["tied"]:
277
+ sel = (prov == PROV_CLASSICAL_UNTIED) & (cc == r["label"])
278
+ if sel.any():
279
+ conncomp[sel] = nxt
280
+ nxt += 1
281
+ reliable_fraction = float(np.mean(conncomp > 0))
282
+ share = {n: float(np.mean(prov == v)) for n, v in
283
+ (("classical", PROV_CLASSICAL), ("learned", PROV_LEARNED), ("classical_untied", PROV_CLASSICAL_UNTIED))}
284
+ q.ok("merge", f"{100 * share['classical']:.1f}% SNAPHU, {100 * share['learned']:.1f}% network, "
285
+ f"{100 * share['classical_untied']:.1f}% SNAPHU not tied; {100 * reliable_fraction:.1f}% reliable")
286
+ both = valid & (cc > 0) & (le.conncomp > 0) & tied_px
287
+ agree = float(np.mean((k_c + offsets)[both] == k_l[both])) if both.any() else float("nan")
288
+ diag = unwrap_diagnostics(unwrapped, psi, conncomp > 0)
289
+ if diag.get("wrap_error_max", 0.0) > 1e-4:
290
+ raise UnwrapError("hybrid", f"internal check failed: wrap(unwrapped - wrapped) reaches {diag['wrap_error_max']:.2e} rad")
291
+ meta = {
292
+ "method": "hybrid-snaphu-pyunwrap", "hybrid_config": asdict(cfg), "components": table,
293
+ "source_share": share, "agreement_where_both_trusted": agree, "diagnostics": diag, "quality": q.to_dict(),
294
+ "model": le.metadata["model"], "learned_config": le.metadata["config"], "seconds": time.time() - t0,
295
+ "classical_reliable_fraction": cl.reliable_fraction, "learned_reliable_fraction": le.reliable_fraction,
296
+ "median_coherence": le.metadata["median_coherence"],
297
+ }
298
+ return HybridUnwrapResult(
299
+ unwrapped_phase=unwrapped.astype(np.float32), conncomp=conncomp, coherence=np.asarray(coherence),
300
+ profile=scaled_profile, reference_date=reference_date, secondary_date=secondary_date, nlooks=nlooks,
301
+ cost_mode="hybrid", init_method="snaphu+ambiguitynet", reliable_fraction=reliable_fraction, metadata=meta,
302
+ ambiguity_map=np.where(valid, k, 0).astype(np.int16), residue_prob=le.residue_prob, k_spread=le.k_spread,
303
+ provenance=prov)
304
+
305
+ def _single(self, src, psi, valid, coh, q, which, profile, d1, d2, nlooks, errors, t0, min_region_size):
306
+ """Result from one surviving method (``on_error='degrade'``), in the hybrid result type."""
307
+ psi0 = np.where(valid, psi, 0.0)
308
+ phi = np.asarray(src.unwrapped_phase, dtype=np.float64)
309
+ k = np.where(np.isfinite(phi) & valid, np.rint((phi - psi0) / TWO_PI), 0.0)
310
+ prov_val = PROV_CLASSICAL_UNTIED if which == "classical" else PROV_LEARNED
311
+ prov = np.where(valid, prov_val, PROV_NONE).astype(np.uint8)
312
+ conncomp = np.asarray(src.conncomp)
313
+ unwrapped = np.where(valid, psi0 + TWO_PI * k, np.nan)
314
+ diag = unwrap_diagnostics(unwrapped, psi, conncomp > 0)
315
+ meta = {"method": f"hybrid-degraded-{which}-only", "components": [], "diagnostics": diag, "quality": q.to_dict(),
316
+ "failures": {k_: f"{type(v).__name__}: {v}" for k_, v in errors.items()}, "seconds": time.time() - t0,
317
+ "hybrid_config": asdict(self.config)}
318
+ if which == "learned":
319
+ meta.update(model=src.metadata["model"], learned_config=src.metadata["config"])
320
+ return HybridUnwrapResult(
321
+ unwrapped_phase=unwrapped.astype(np.float32), conncomp=conncomp, coherence=np.asarray(coh), profile=profile,
322
+ reference_date=d1, secondary_date=d2, nlooks=nlooks, cost_mode="hybrid", init_method="degraded",
323
+ reliable_fraction=float(np.mean(conncomp > 0)), metadata=meta, ambiguity_map=np.where(valid, k, 0).astype(np.int16),
324
+ residue_prob=getattr(src, "residue_prob", None), k_spread=getattr(src, "k_spread", None), provenance=prov)