AI-driven InSAR phase unwrapping via a Physics-Informed U-Net (Ambiguity-Net) that predicts the discrete integer ambiguity map, enforcing the rewrapping constraint by construction.
pip install pyunwrap-insar==0.1.3 Copy PIP instructions
InSAR phase unwrapping by predicting the integer ambiguity: the wrap identity holds by construction.
Why this exists · How it works · Synthetic data · Curriculum · Honest evaluation · Hybrid unwrapping · Install · Quickstart · Notebooks · Docs · Citation
pyunwrap is a research package for unwrapping Interferometric Synthetic Aperture Radar (InSAR) phase, the core measurement behind satellite-based ground-deformation monitoring. A deep network (AmbiguityNet) predicts the integer number of phase cycles at every pixel, and the unwrapped phase is rebuilt from it. Because of that design, the output always re-wraps to exactly the observed interferogram.
Synthetic C-band interferograms from the package's generator (Gaussian bowl, Okada fault, Mogi volcano, and a no-deformation control). One colour cycle is one fringe, 2.77 cm of line-of-sight motion. Bottom row: the true ground motion the network never sees.
Every classical phase-unwrapping algorithm (branch-cut methods, minimum-cost flow as in SNAPHU, Goldstein's algorithm) rests on one assumption: the true phase gradient between adjacent pixels never exceeds π radians (the Nyquist/Itoh condition). Two situations break it in practice:
pyunwrap targets both regimes without inheriting the most common failure mode of naive deep-learning approaches: regressing the unwrapped phase gives a network no reason to respect wrap(prediction) == observed_phase. Predicting the integer ambiguity makes that identity a mathematical guarantee.
AmbiguityNet outputs a continuous ambiguity prediction, rounds it with a straight-through estimator, and reconstructs phase directly:
φ̂ = ψ + 2π · round(k̂), k̂ ∈ ℤ Approach Failure mode Regress φ directly Nothing constrains wrap(prediction) == ψ; the network can output any real value Predict k (this package) wrap(ψ + 2π·round(k̂)) == ψ holds by construction; the network only has to get the integer cycle count right
The physics identity in action: re-wrapping the predicted unwrapped phase reproduces the observed interferogram to 8.9e-16 rad. This figure shows that the output is self-consistent, which is guaranteed by the design. It says nothing about whether the cycle counts are correct; that is what the evaluation below is for.
Two consequences shape the rest of the code: training uses a physics-informed loss with a component that is provably near-zero regardless of prediction quality (documented explicitly in pyunwrap/models/losses.py), and tiled inference merges the integer ambiguity map across overlapping patches, never the phase itself, because averaging phase across a tile boundary can silently produce a value that satisfies no physical interferogram.
pyunwrap.synthetic generates interferograms with exactly known ground truth: Gaussian subsidence bowls, a from-scratch Okada (1985) rectangular-fault dislocation, a Mogi (1958) volcanic point source, DEM-driven topographic phase, Kolmogorov-spectrum atmospheric turbulence, orbital ramps, and coherence-dependent decorrelation noise. A pseudo-real strategy rewraps real L-band (ALOS-2) unwrapped phase into simulated C-band data to help bridge the sim-to-real gap.
Anatomy of one composite training scene: three sources are summed, then topography, atmosphere and an orbital ramp are added, coherence is degraded by patches, lakes and steep fringes, and the result is wrapped.
The advanced notebook builds composite scenes with domain randomisation (X, C and L band, incidence angle, heading, ±25 % parameter jitter) under an ambiguity budget: every scene keeps max |k| ≤ 8, matching the output range of the network, so no label is unreachable by construction.
Training starts on clean, wrapped scenes and adds difficulty in stages. The easy and moderate bowls are sized in fringes, not metres, so every scene is guaranteed to wrap in every band (an early version used a fixed 2 cm bowl, which barely wrapped at C-band and almost never in L-band, so the "easy" tier taught nothing but k = 0).
The three stages in C and L band. Easy: one source, coherence 0.95, no atmosphere. Moderate: two sources, coherence 0.70. Hard: three sources, coherence ≈ 0.4, lakes, patches, steep fringes (Nyquist violations ≈ 30 %). Bottom row: the integer ambiguity map k the network must predict.
The library also provides curriculum replay (pyunwrap.training.curriculum): every epoch draws a fixed-proportion mixture of easy/moderate/hard tiles, with automatic forgetting detection. Optional SNAPHU pseudo-ground-truth fine-tuning on real data is supported through pyunwrap.utils.snaphu_integration.
Two facts make naive evaluation misleading, and the package's reporting is built around them.
1. The absolute cycle count is unobservable. Shifting a whole scene by n cycles leaves the wrapped phase unchanged, so no model can know the absolute level. Every score is therefore computed after removing each tile's whole-cycle offset, and the advanced notebook trains with an offset-invariant loss (and checks numerically that the loss is unchanged when the target is shifted by a constant).
2. A model must beat "do nothing". Predicting k = 0 everywhere is already right on a large share of pixels in gentle scenes. The headline metric is therefore skill:
skill = 1 − RMSE(model) / RMSE(do-nothing) (offset-corrected, in radians) 0 % means no better than guessing zero; 100 % is perfect; negative is worse. The notebook also reports a per-stage ceiling (the skill of an oracle that knows the noise-free cycle count) so a number can be read against what is achievable.
pyunwrap.inference.hybrid.HybridUnwrapper routes each pixel to a classical or a learned method by local regime:
The merge never averages raw phase. Both methods' results are converted to integer ambiguity maps, blended there, and the final phase is rebuilt as wrapped_phase + 2π·round(k_merged), so the wrap identity holds exactly regardless of how the two maps were merged.
from pyunwrap.inference.hybrid import HybridUnwrapper hybrid = HybridUnwrapper(learned_unwrapper) # auto-selects SNAPHU or a scikit-image fallback result = hybrid.unwrap("wrapped.tif", "coherence.tif", "amplitude.tif") result.save_geotiff("unwrapped.tif") # result.regime_mask / .provenance_mask / .confidence_map / .uncertainty_map # are also available, so you can see which method produced which region. pyunwrap.analytics.benchmark.generate_regime_report reports which scenes each method wins, scene by scene, instead of one aggregate score.
Real-data + synthetic-injection pipeline (pyunwrap.data.real_injection): inject synthetic deformation (Gaussian bowl, Mogi, Okada, orbital ramp or a nonlinear transient) with exactly known ground truth into a real (or real-like) wrapped-phase/amplitude/coherence stack, preserving real speckle and decorrelation texture. Spatially-blocked splitting prevents pixel-level leakage between train/val/test.
AmbiguityNet (pyunwrap.models): a ResNet-34-encoder U-Net (about 24 M parameters) with a dual head, the integer ambiguity map via a straight-through rounding layer and an auxiliary residue-probability map, plus Dropout2d layers for Monte Carlo Dropout uncertainty. Trained with a physics-informed loss (ambiguity regression, re-wrap consistency, ambiguity-map residue penalty, and an optional coherence-weighted edge-preserving smoothness term).
Production inference (pyunwrap.inference): tiled processing of arbitrarily large interferograms with edge-aware, residue-probability-weighted merging of the ambiguity map, test-time augmentation over the eight dihedral views (integer median), Monte Carlo Dropout uncertainty, and an ONNX Runtime → OpenVINO fallback chain for deployment without PyTorch.
Scientific analytics (pyunwrap.analytics): residue detection and clustering, Nyquist gradient-violation mapping, error-distribution statistics, Grad-CAM and Integrated-Gradients explainability, uncertainty-calibration diagrams, and an offset-corrected, regime-separated benchmark harness.
Visualization & reporting (pyunwrap.visualization): interactive Plotly 3D phase surfaces and heatmaps, a folium swipe-comparison map, and a self-contained HTML report.
InSARSyntheticGenerator ──┐ real GeoTIFFs │ (wrapped, coherence, amplitude) ▼ │ tiling + normalization ▼ │ tiled inference ▼ via PhaseUnwrapper InSARTileDataset │ │ │ ▼ ▼ Trainer.fit() ──── AmbiguityNet ──── smart ambiguity-map (curriculum, (the same merging (never physics loss) model) the phase) │ ▼ unwrapped phase + analytics + report See docs/architecture.md for the module-by-module reference.
From PyPI (distributed as pyunwrap-insar; the importable module is pyunwrap):
pip install pyunwrap-insar From source, for development:
git clone https://github.com/EOCoreINT/pyunwrap.git cd pyunwrap pip install -e . Optional extras:
pip install -e ".[dev,maps,deploy,notebooks,snaphu]" # everything, from source pip install "pyunwrap-insar[maps,snaphu]" # extras also work from PyPI Quickstart from pyunwrap.synthetic.generator import InSARSyntheticGenerator from pyunwrap.models.ambiguity_net import AmbiguityNet from pyunwrap.inference.unwrapper import PhaseUnwrapper # Generate a synthetic sample (Mogi volcanic source deformation). gen = InSARSyntheticGenerator(size=256, seed=42) sample = gen.generate_sample(deformation_type="mogi") # Tiled inference on an interferogram with a trained model. model = AmbiguityNet(pretrained=False, k_max=10.0) # or load your own checkpoint unwrapper = PhaseUnwrapper(model=model, device="cuda") result = unwrapper.unwrap( wrapped_phase_path="data/wrapped_phase.tif", coherence_path="data/coherence.tif", amplitude_path="data/amplitude.tif", tile_size=512, overlap=64, generate_report=True, ) result.save_geotiff("unwrapped_output.tif") Training a model end to end:
pyunwrap-train \ --train-hdf5 train_tiles.h5 --val-hdf5 val_tiles.h5 \ --epochs 60 --warmup-epochs 5 \ --finetune-hdf5 snaphu_pseudo_gt.h5 --finetune-start-epoch 55 \ --use-curriculum-replay --smoothness-weight 0.1 \ --out-dir runs/pyunwrap_v1 Or from a real (or real-like) data stack, via the real-data injection pipeline:
pyunwrap-train --real-data-path ./my_real_stack/ --epochs 60 --out-dir runs/pyunwrap_v1 Inference from the command line:
pyunwrap-unwrap \ --wrapped-phase wrapped.tif --coherence coherence.tif --amplitude amplitude.tif \ --checkpoint model.pt --output unwrapped.tif # add --no-hybrid to use the learned model alone Notebooks The notebooks in notebooks/ walk through the package hands-on. The first three are checked in pre-executed with real outputs:
pip install -e ".[dev,maps,notebooks]" jupyter notebook notebooks/ Documentation The full documentation site (installation, quickstart, architecture guide, tutorial notebooks rendered with their outputs, and the API reference generated from source) is built with Sphinx and hosted at pyunwrap.readthedocs.io.
pip install -e ".[docs]" sphinx-build -b html docs docs/_build/html Testing pytest -m "not slow" # fast unit + integration tests pytest # full suite, including the end-to-end # synthetic → train → infer → report test pytest --cov=pyunwrap --cov-report=term-missing The suite includes known-answer physics tests (e.g. residue detection is checked against a hand-constructed phase vortex with an exact, known topological charge) and a tile-merging regression test asserting that tiled-and-merged inference is numerically identical to a whole-image pass. See CONTRIBUTING.md for the breakdown and setup.
Early-stage and actively developed. The goal is a model that demonstrably beats a do-nothing baseline and is honest about where it beats classical unwrapping, not a blanket claim to beat SNAPHU. The pipeline (synthetic data, real-data injection, curriculum training, tiled inference, the hybrid router, analytics and reporting) is implemented and tested end to end.
Where the learned model stands (latest internal run, synthetic validation data, not a released checkpoint). With the staged curriculum above, a 60-epoch run on a single laptop GPU reached, on held-out synthetic scenes:
and about 77 % of pixels with exactly the right cycle count, against 56 % for do-nothing. In words: the model has learned something real on gentle scenes and about half of what is possible there; it has not yet learned hard scenes, which is the regime the hybrid design most needs. Progress stopped improving after roughly epoch 15 in that run; the next experiments are documented in the advanced notebook.
APIs may change between minor versions until 1.0. See CHANGELOG.md.
pyunwrap works standalone, but is designed to sit downstream of pygeofetch (interferogram acquisition/formation) and alongside ps-gnn (persistent scatterer identification) in an open-source InSAR processing stack.
If pyunwrap is useful in your research, please cite the archived release via its Zenodo DOI:
@software{pyunwrap2026, title = {pyunwrap: Physics-Informed Deep Learning for InSAR Phase Unwrapping}, author = {Appiah Kubi, Samuel}, year = {2026}, url = {https://github.com/EOCoreINT/pyunwrap}, doi = {10.5281/zenodo.22209219}, note = {Version 0.1.0} } References Goldstein, R. M., Zebker, H. A., & Werner, C. L. (1988). Satellite radar interferometry: Two-dimensional phase unwrapping. Radio Science, 23(4). Itoh, K. (1982). Analysis of the phase unwrapping algorithm. Applied Optics, 21(14). Chen, C. W., & Zebker, H. A. (2001). Two-dimensional phase unwrapping with use of statistical models for cost functions in nonlinear optimization (SNAPHU). JOSA A, 18(2). Okada, Y. (1985). Surface deformation due to shear and tensile faults in a half-space. Bulletin of the Seismological Society of America, 75(4). Mogi, K. (1958). Relations between the eruptions of various volcanoes and the deformations of the ground surfaces around them. Bulletin of the Earthquake Research Institute, 36. Contributing Contributions are welcome: bug reports, documentation, new deformation models, or core improvements. See CONTRIBUTING.md for development setup, test/lint conventions, and the design principles worth knowing before touching the physics-critical modules.
InSAR phase-unwrapping SAR remote-sensing deep-learning earth-observation geospatial
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
None of the files in this release were uploaded with provenance metadata.
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.




