API Reference¶
pysarflow¶
Preprocessing Sentinel1 GRD Data.
This Python script enables users to perform essential preprocessing steps on Sentinel-1 GRD data, including thermal noise removal, radiometric calibration, and terrain correction.
It accepts Sentinel-1 products in the .SAFE format.
The script depends on the 'esa_snappy' library, which must be installed in the Python environment where this script is executed.
This file can also be imported as a module and contains the following functions
Major: * read_grd_product Supporting: *
apply_orbit_file(product)
¶
Apply precise satellite orbit file to the SAR product.
This operation orthorectifies the SAR product to improve accuracy by using precise orbit information.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/grd.py
band_difference(product_stacked)
¶
Computes the difference between two bands of a stacked SAR product.
A new band named 'Difference_Band' is created, calculated as: Difference_Band = band2 - band1
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
border_noise_removal(product)
¶
Remove border noise from the SAR product.
Border noise appears as a low-backscatter band along the image edges and can affect SAR measurements near scene boundaries. This operation trims the noisy border region to improve data quality.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/grd.py
conversion_to_db(product)
¶
Converts SAR backscatter values from linear scale to decibels (dB).
This transformation is commonly applied to Sentinel-1 GRD products after radiometric calibration, as dB units are easier to interpret and compare across scenes.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/grd.py
export(product, output_path)
¶
Exports a SNAP product as a GeoTIFF file.
| Parameters: |
|
|---|
Source code in pysarflow/grd.py
generateFloodMask(product_masked, threshold=0.1)
¶
Generates a flood mask from a masked difference band in a SAR product.
The function creates a new band called 'flooded', where pixels are classified as: - -9999.0: NoData - 0: Permanent water - 1: Flooded - 2: Others
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
maskPermanentWater(product)
¶
Masks permanent water areas in a SAR product using land cover data.
The function first adds a land cover band to the input product, then creates a binary water mask based on GlobCover classification (210 = water). Finally, it applies the mask to the SAR product, creating a permanent water masked while preserving NoData values.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
plotBand(product1, band_name1, vmin=None, vmax=None, cmap=plt.cm.binary, figsize=(10, 10))
¶
Plots one or two SNAP Product bands side by side. Axes ticks are shown, and each subplot has its own title.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/grd.py
preprocess_grd_product(file_path, config)
¶
Preprocess a Sentinel-1 GRD product using a given configuration.
The function performs a series of preprocessing steps including AOI subsetting, orbit file application, thermal and border noise removal, radiometric calibration, speckle filtering, and terrain correction.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 | |
radiometric_calibration(product, polarization, pols_selected)
¶
Perform radiometric calibration on the SAR product.
Calibration converts the raw SAR data into radar brightness values.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
read_grd_product(file_path)
¶
Read a Sentinel-1 SAR GRD product from a .SAFE directory or a .zip archive.
This function utilizes ESA SNAP's ProductIO.readProduct to load the SAR data
into a SNAP Product object, which is the base object for further processing.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
speckle_filter(product, filterSizeY='5', filterSizeX='5', filter='Lee')
¶
Apply speckle filtering to a SAR product using the specified filter parameters.
This function uses the Sentinel-1 toolbox's Speckle-Filter operator via GPF (Graph Processing Framework) to reduce speckle noise in SAR imagery.
Parameters:¶
product : Product The input SAR product to be filtered.
str, optional
Filter size in the Y direction (default is '5').
str, optional
Filter size in the X direction (default is '5').
str, optional
Type of speckle filter to apply. Common options include "Lee", "Refined Lee", etc. Default is "Lee".
Returns:¶
Product The filtered SAR product after applying the speckle filter.
Source code in pysarflow/grd.py
stack(master_product, slave_product)
¶
Collocates two SAR products (master and slave) into a single stacked product.
This creates a new product where the bands from the master and slave products are aligned spatially. Optionally, the master and slave components can be renamed to avoid conflicts.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
subset_AOI(product, bbox=[], file_path=None)
¶
Subset the product to a specific AOI to reduce resource usage for large images.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
terrain_correction(product, demName='SRTM 3Sec', pixelSpacingInMeter=10.0, demResamplingMethod='BILINEAR_INTERPOLATION', imgResamplingMethod='BILINEAR_INTERPOLATION')
¶
Performs terrain correction on a SAR product using a specified DEM. This step corrects geometric distortions caused by the side-looking geometry of SAR sensors and normalizes pixel spacing.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/grd.py
thermal_noise_removal(product)
¶
Remove thermal noise from the SAR product.
Thermal noise is a constant noise floor that affects SAR images, especially in low-backscatter areas. This step removes this noise, improving the signal-to-noise ratio.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/grd.py
Preprocessing Sentinel1 SLC Data
This Python script enables users to perform essential preprocessing steps on Sentinel-1 SLC data, including thermal noise removal, radiometric calibration, and terrain correction.
It accepts Sentinel-1 products in the .SAFE format.
The script depends on the 'esa_snappy' library, which must be installed in the Python environment where this script is executed.
This file can also be imported as a module and contains the following functions
Major: * read_slc_product Supporting: *
apply_orbit(product, orbit_type='Sentinel Precise (Auto Download)')
¶
Run SNAP 'Apply-Orbit-File' on a Product.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/slc.py
back_geocoding(products, dem_name='SRTM 1Sec HGT', ext_dem=None)
¶
Run SNAP Back-Geocoding on master + slave(s).
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/slc.py
burst_for_geometry(product, safe_dir, geom, subswath=None)
¶
Determine TOPS burst index (or range) for a geometry in a Sentinel-1 IW SLC.
| Parameters: |
|
|---|
Returns (dict): { 'swath': 'IW1'|'IW2'|'IW3', 'band_name': 'Intensity_IW1_VV', # band used 'linesPerBurst': 1495, 'numberOfBursts': 10, 'burst': 5, # for Point 'firstBurst': 4, # for Polygon 'lastBurst': 6, # for Polygon 'geom_type': 'Point'|'Polygon' }
Raises:
ValueError:
- If geom is not a Shapely Point/Polygon, a WKT string, or a 4-element bbox ``(minx, miny, maxx, maxy)``
- If the geometry lies outside the products IW1/IW2/IW3 coverage.
- If the AOI polygon does not intersect the chosen sub-swath.
FileNotFoundError:
- If no annotation XML file is found for the selected sub-swath
Source code in pysarflow/slc.py
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
enhanced_spectral_diversity(product, preset='default', **overrides)
¶
Enhanced Spectral Diversity (ESD) with sensible defaults + optional overrides.
Args:
product:
A SNAP Product — usually the output of Back-Geocoding
containing the master and one or more slave images.
preset:
Convenience preset passed to esd_parameters(preset) that supplies a
default parameter set. Expected values:
- "default" - full computation.
- "fast" – less lighter computation.
- "faster" – lighter computation.
**overrides:
Any ESD operator parameter you want to force/override from the
preset (e.g., cohWinAz=5, cohWinRg=10, maxIterations=25,
etc.). Keys must match the operator's parameter names.
| Returns: |
|
|---|
Source code in pysarflow/slc.py
goldstein_phase_filtering(product)
¶
Apply Goldstein Phase Filtering to an interferogram.
Goldstein filtering is used in InSAR processing to enhance the signal-to-noise ratio of the interferometric phase. This filter suppresses noise while preserving the phase fringes, improving the quality of unwrapping and subsequent deformation analysis.
Args:¶
product : org.esa.snap.core.datamodel.Product The input product containing the interferometric phase, typically the output of the "Interferogram" operator.
Returns:¶
output : org.esa.snap.core.datamodel.Product The product with Goldstein phase filtering applied.
Notes:¶
alpha: Controls the filtering strength. Higher values result in stronger filtering (default is 1.0).FFTSizeString: Defines the FFT window size used for filtering (default is '64').windowSizeString: Defines the size of the filtering window (default is '3').useCoherenceMask: If set to True, filtering is applied only where coherence exceeds the given threshold.coherenceThreshold: Minimum coherence value used if coherence masking is enabled (default is 0.2, but ignored ifuseCoherenceMaskis False).
This function is typically used after interferogram generation and before phase unwrapping in an InSAR processing chain.
Source code in pysarflow/slc.py
interferogram(product)
¶
Generate an interferogram from a Sentinel-1 interferometric product.
This function uses the SNAP Graph Processing Framework (GPF) to create an interferogram, which represents the phase difference between two co-registered SAR images. The interferogram is an essential step in interferometric SAR (InSAR) processing for deriving surface deformation, elevation models, or coherence analysis.
Args:¶
product : org.esa.snap.core.datamodel.Product The co-registered Sentinel-1 product (usually the output of the "Back-Geocoding" operator with two coregistered images).
Returns:¶
output : org.esa.snap.core.datamodel.Product The product containing the generated interferogram and optional coherence band.
Notes:¶
- The function uses predefined parameters for flat-earth phase removal, polynomial fitting, and orbit interpolation.
- Coherence estimation is enabled by default.
- Pixel size is set to be square.
- Uncomment and customize the window size parameters if you want to control the coherence estimation resolution.
- This function is typically followed by Goldstein filtering and phase unwrapping steps in an InSAR workflow.
Source code in pysarflow/slc.py
multilooking(product, n_rg=3, n_az=1, source_bands=None, output_intensity=False)
¶
SNAP 'Multilook' operator.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/slc.py
phase_to_elevation(product, DEM)
¶
Convert unwrapped interferometric phase to elevation using a Digital Elevation Model (DEM).
This function uses the SNAP Graph Processing Framework (GPF) to apply the "Phase to Elevation" operator. It transforms unwrapped phase data into an elevation map by referencing a known DEM. This step is commonly used in Differential InSAR (DInSAR) or when generating DEMs from SAR data.
Args:¶
product : org.esa.snap.core.datamodel.Product The input product containing unwrapped interferometric phase, typically the result of a phase unwrapping operator.
str
The name of the DEM to use for reference (e.g., 'SRTM 3Sec', 'Copernicus 30m', or path to an external DEM file).
Returns:¶
output : org.esa.snap.core.datamodel.Product The product containing the elevation map derived from phase data.
Notes:¶
- The DEM is used to geocode the elevation output and aid in the transformation.
- Bilinear interpolation is used to resample the DEM for better accuracy.
externalDEMNoDataValueis set to 0.0, which defines how to handle no-data pixels in the DEM.- This step assumes the input phase has already been unwrapped and filtered.
Source code in pysarflow/slc.py
plot(dim_path, i_band=None, q_band=None, coh_band=None, downsample=1, fade=(0.2, 0.8), title='', save_path=None, return_rgb=False, ax=None)
¶
Visualize an interferogram as SNAP-like rainbow (HSV). This can be used to plot any interferogram outputs
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/slc.py
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | |
read_slc_product(product_path)
¶
Reads a Sentinel-1 SLC product using SNAP's ProductIO.
This function checks whether the provided product path exists on disk, then attempts to load the product using ProductIO.readProduct. If the product cannot be read, it raises a RuntimeError with details about the failure.
| Parameters: |
|
|---|
| Returns: |
|
|---|
| Raises: |
|
|---|
Source code in pysarflow/slc.py
save_product(product, filename, output_dir='_results', fmt='BEAM-DIMAP')
¶
Save a SNAP product to disk.
Args¶
product : snappy.Product The SNAP product to save. filename : str Output filename (without extension). output_dir : str, optional Directory where results will be saved (default: "_results"). fmt : str, optional Output format (default: "BEAM-DIMAP").
Returns¶
str The full output path where the product was saved.
Source code in pysarflow/slc.py
snaphu_export(xml_path, new_input_file, new_target_folder)
¶
Modify a SNAP XML graph to update input and output paths, then execute it using GPT.
This function updates the SNAP XML workflow file by:
- Replacing the file path in the 'Read' node with the given input file.
- Replacing the target folder in the 'SnaphuExport' node with the given output folder.
After updating, it saves the modified XML and runs the graph using the gpt command-line tool.
Parameters¶
xml_path : str Path to the SNAP XML graph file to be modified and executed. new_input_file : str Path to the new input file (to replace the one in the 'Read' node). new_target_folder : str Path to the new target folder (to replace the one in the 'SnaphuExport' node).
Returns¶
None
The function prints progress updates and the output of the gpt execution.
Raises¶
FileNotFoundError
If the provided xml_path does not exist.
xml.etree.ElementTree.ParseError
If the XML file cannot be parsed.
subprocess.CalledProcessError
If the gpt command execution fails.
Notes¶
- Requires SNAP's Graph Processing Tool (
gpt) to be installed and available in the system PATH. - The XML graph must contain nodes with IDs 'Read' and 'SnaphuExport' for the function to work correctly.
Source code in pysarflow/slc.py
snaphu_import(source_product, unwrapped_product)
¶
Import SNAPHU unwrapped interferogram results back into SNAP.
This function uses SNAP's Graph Processing Framework (GPF) to merge the unwrapped interferogram produced by SNAPHU with the original source product. The resulting product contains the unwrapped phase information, making it available for further processing within SNAP.
Parameters¶
source_product : snappy.Product The original interferogram product before SNAPHU unwrapping. unwrapped_product : snappy.Product The product containing the SNAPHU unwrapped interferogram.
Returns¶
snappy.Product A SNAP product containing the imported unwrapped phase data.
Notes¶
- The parameter
'doNotKeepWrapped'is set to False to keep the wrapped phase along with the unwrapped phase. - Requires SNAP's snappy module and the GPF operator
'SnaphuImport'.
Source code in pysarflow/slc.py
snaphu_unwrapping(conf_file_path, snaphu_exe_path, output_directory)
¶
Run the SNAPHU unwrapping process using a configuration file.
This function reads a SNAPHU configuration file, extracts the command line arguments, and executes the SNAPHU binary with those arguments in the specified output directory. It ensures the working directory exists before execution and reports success or failure after completion.
Parameters¶
conf_file_path : str Path to the SNAPHU configuration file (typically generated by SNAP or manually prepared). snaphu_exe_path : str Path to the SNAPHU executable to be used for unwrapping. output_directory : str Directory where SNAPHU will be executed and output files will be stored.
Returns¶
bool True if SNAPHU unwrapping completed successfully (return code 0), False otherwise.
Raises¶
FileNotFoundError If the configuration file does not exist. IndexError If the configuration file has fewer than 7 lines (expected command at line 7). subprocess.SubprocessError If there is an unexpected error while executing the SNAPHU command.
Notes¶
- The function assumes that the unwrapping command is located on line 7 of the configuration file.
- Any leading '#' or 'snaphu' prefixes in the command line will be stripped before execution.
- Requires SNAPHU to be compiled and available at the specified
snaphu_exe_path.
Source code in pysarflow/slc.py
temporal_baseline(product1_path, product2_path)
¶
Calculate and print the temporal baseline between two Sentinel-1 products.
The temporal baseline is defined as the absolute difference in days between the acquisition times (start times) of the two SAR products. This metric is commonly used in interferometric SAR (InSAR) analysis to assess the temporal separation between image acquisitions.
Args:¶
product1_path : str File path to the first Sentinel-1 product (e.g., the master image). product2_path : str File path to the second Sentinel-1 product (e.g., the slave image).
Returns: It prints the temporal baseline None The function prints the temporal baseline in days and does not return a value.
Notes:¶
- This function uses
read_productto open the Sentinel-1 products. - It assumes that both products contain valid start time metadata.
- Resources are released after processing by calling
.dispose()on each product.
Source code in pysarflow/slc.py
terrain_correction_slc(product, DEM)
¶
Apply terrain correction to a SAR product using a specified DEM.
Terrain correction removes geometric distortions caused by topography and sensor viewing geometry. This step geocodes the image into a map coordinate system and ensures that pixel locations align with their true geographic position.
Args¶
product : snappy.Product The SAR product to which terrain correction will be applied. DEM : str The name of the Digital Elevation Model (e.g., 'SRTM 3Sec' or a custom DEM) to be used for terrain correction.
Returns¶
snappy.Product The terrain-corrected product.
Notes¶
- The DEM is saved as part of the output product.
- Areas with missing DEM values are assigned an external no-data value (0.0).
- This step is typically performed near the end of the preprocessing chain to produce a geocoded product suitable for analysis and visualization.
Source code in pysarflow/slc.py
topsar_deburst(product, polarization)
¶
Apply TOPSAR deburst operation to a Sentinel-1 product.
This function removes burst discontinuities in TOPSAR acquisitions by merging bursts into a seamless image for the specified polarization. It is a necessary preprocessing step for Sentinel-1 TOPSAR IW and EW data before further interferometric or geocoding analysis.
Args¶
product : snappy.Product The input Sentinel-1 product to which the deburst operation will be applied. polarization : str The polarization channel to process (e.g., 'VV', 'VH', 'HH', 'HV').
Returns¶
snappy.Product The deburst-processed Sentinel-1 product.
Source code in pysarflow/slc.py
topsar_split(product, burst_dict, pols=None, output_complex=True)
¶
Run TOPSAR-Split using burst indices from burst_for_geometry(...).
| Parameters: |
|
|---|
Returns Product restricted to the specified sub-swath, burst range, and polarisations.
Source code in pysarflow/slc.py
It includes common or secondary functionalities that would be used in other modules.
convert_0_to_nan(product)
¶
Convert all zero values in the bands of a Sentinel-1 product to NaN (represented as -9999.0).
This function iterates over all bands in the input product and replaces pixels with a value of 0 with -9999.0, which is commonly used as the NoData value in SNAP products. The data type of each band is set to float32 to accommodate NaN values.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/utils.py
extract_bbox(file_path)
¶
Extracts a bounding box from a shapefile and returns it as a WKT polygon.
| Parameters: |
|
|---|
| Returns: |
|
|---|
Source code in pysarflow/utils.py
extract_info(product_path)
¶
Extract and display basic information about a Sentinel-1 product.
Parameters¶
product_path : str Path to the Sentinel-1 product file.
Prints¶
- Product name
- Product type
- Product description
- Scene width and height
- Acquisition start and end time
- Number of bands and their names
Notes¶
This function uses the SNAP API to read the product and display its metadata. It disposes of the product after extraction to free resources. Useful for quickly inspecting a product before further processing.
Source code in pysarflow/utils.py
get_subswath(aoi, product)
¶
Identify the Sentinel-1 subswath (e.g., IW1, IW2, or IW3) covering the given Area of Interest (AOI).
This function determines which Sentinel-1 interferometric wide (IW) subswath contains the centroid of a given AOI. This is useful when selecting or cropping data specific to one of the three IW subswaths.
Parameters:¶
aoi : str | shapely.geometry.Polygon | list[tuple[float, float]]
The Area of Interest to test for subswath coverage. It can be:
- A WKT polygon string (e.g., 'POLYGON((lon lat, lon lat, ...))')
- A Shapely Polygon object
- A list or tuple of (lon, lat) coordinate pairs
org.esa.snap.core.datamodel.Product
The Sentinel-1 product containing IW subswath bands.
Returns:¶
result : str The name of the subswath ('IW1', 'IW2', or 'IW3') that contains the AOI centroid. Returns 'No subswath for the AOI' if none of the available subswaths cover it.
Notes:¶
- The function uses the product's band names to infer available subswaths.
- It checks whether the AOI centroid lies within the bounds of each subswath's geocoded raster.
- Requires that the product bands include geocoding information.