Source code for polsartools.sensors.nisar


import numpy as np
from osgeo import gdal,osr
gdal.UseExceptions()
import os,tempfile
import tables
# from skimage.util.shape import view_as_blocks
from polsartools.utils.utils import time_it
# from polsartools.utils.io_utils import write_s2_bin_ref, write_s2_ct_ref
from polsartools.utils.h5_utils import h5_polsar, get_ml_chunk
from netCDF4 import Dataset
from polsartools.utils.clip_utils import prepare_clip_window, apply_vector_mask
import warnings
from osgeo import gdal, osr, ogr
import numpy as np
from tqdm import tqdm


#%%
def rslc_meta(inFile):
    band_table = [
        ('/science/LSAR', 'L'),
        ('/science/SSAR', 'S')
    ]

    # Identify frequency band and root path
    try:
        with tables.open_file(inFile, mode="r") as h5:
            for path, band in band_table:
                if path in h5:
                    freq_band = band
                    freq_path = path
                    break
            else:
                print("Neither LSAR nor SSAR data found in the file.")
                return None

            # Read polarization list
            listOfPolarizations = None
            for base in ['RSLC', 'SLC']:
                pol_path = f'{freq_path}/{base}/swaths/frequencyA/listOfPolarizations'
                try:
                    listOfPolarizations = np.array(h5.get_node(pol_path).read()).astype(str)
                except tables.NoSuchNodeError:
                    # print(f"Polarization node missing: {pol_path}")
                    continue
                
            # pol_path = f'{freq_path}/RSLC/swaths/frequencyA/listOfPolarizations'
            # try:
            #     listOfPolarizations = np.array(h5.get_node(pol_path).read()).astype(str)
            # except tables.NoSuchNodeError:
            #     print(f"Polarization node missing: {pol_path}")
            #     listOfPolarizations = None

    except Exception:
        raise RuntimeError("Invalid .h5 file !!")

    return freq_band,listOfPolarizations

    
def get_rslc_path(h5, freq_band):
    for product_type in ['RSLC', 'SLC']:
        base_path = f'/science/{freq_band}SAR/{product_type}/swaths/frequencyA'
        if h5.__contains__(base_path):
            return base_path
        else:
            print(f"Base path not found: {base_path}")
    return None


def gslc_meta(inFile):
    band_table = [
        ('/science/LSAR', 'L'),
        ('/science/SSAR', 'S')
    ]

    # Identify frequency band and root path
    try:
        with tables.open_file(inFile, mode="r") as h5:
            for path, band in band_table:
                if path in h5:
                    freq_band = band
                    freq_path = path
                    break
            else:
                print("Neither LSAR nor SSAR data found in the file.")
                return None

            # Read polarization list
            pol_path = f'{freq_path}/GSLC/grids/frequencyA/listOfPolarizations'
            try:
                listOfPolarizations = np.array(h5.get_node(pol_path).read()).astype(str)
            except tables.NoSuchNodeError:
                print(f"Polarization node missing: {pol_path}")
                listOfPolarizations = None

    except Exception:
        raise RuntimeError("Invalid .h5 file !!")

    # Reopen to read raster metadata
    with tables.open_file(inFile, "r") as h5:
        base_grid = f'{freq_path}/GSLC/grids/frequencyA'
        projection_path = f'{freq_path}/GSLC/metadata/radarGrid/projection'

        try:
            projection = np.array(h5.get_node(projection_path).read())
            xSpacing = np.array(h5.get_node(base_grid + '/xCoordinateSpacing').read())
            ySpacing = np.array(h5.get_node(base_grid + '/yCoordinateSpacing').read())
        except tables.NoSuchNodeError as e:
            print(f"Missing expected metadata node: {e}")
            return None

    return freq_band,listOfPolarizations, xSpacing, ySpacing, int(projection)

def gcov_meta(inFile):
    band_table = [
        ('/science/LSAR', 'L'),
        ('/science/SSAR', 'S')
    ]

    # Identify frequency band and root path
    try:
        with tables.open_file(inFile, mode="r") as h5:
            for path, band in band_table:
                if path in h5:
                    freq_band = band
                    freq_path = path
                    break
            else:
                print("Neither LSAR nor SSAR data found in the file.")
                return None

            # Read polarization list
            pol_path = f'{freq_path}/GCOV/grids/frequencyA/listOfPolarizations'
            try:
                listOfPolarizations = np.array(h5.get_node(pol_path).read()).astype(str)
            except tables.NoSuchNodeError:
                print(f"Polarization node missing: {pol_path}")
                listOfPolarizations = None

    except Exception:
        raise RuntimeError("Invalid .h5 file !!")

    # Reopen to read raster metadata
    with tables.open_file(inFile, "r") as h5:
        base_grid = f'{freq_path}/GCOV/grids/frequencyA'
        projection_path = f'{freq_path}/GCOV/grids/frequencyA/projection'

        try:
            projection = np.array(h5.get_node(projection_path).read())
            xSpacing = np.array(h5.get_node(base_grid + '/xCoordinateSpacing').read())
            ySpacing = np.array(h5.get_node(base_grid + '/yCoordinateSpacing').read())
        except tables.NoSuchNodeError as e:
            print(f"Missing expected metadata node: {e}")
            return None

    return freq_band,listOfPolarizations, xSpacing, ySpacing, int(projection)

def get_geo_meta(inFile):
    """
    Combined metadata extractor for GSLC and GCOV products.
    """
    band_table = [('/science/LSAR', 'L'), ('/science/SSAR', 'S')]
    
    try:
        with tables.open_file(inFile, mode="r") as h5:
            # Detect frequency band (LSAR or SSAR)
            freq_band, freq_path = None, None
            for path, band in band_table:
                if path in h5:
                    freq_band, freq_path = band, path
                    break
            
            if not freq_band:
                print("Neither LSAR nor SSAR data found.")
                return None

            # Detect Product Type (GSLC or GCOV)
            # We check which group exists under the detected frequency path
            product_type = None
            for p_type in ["GSLC", "GCOV"]:
                if f"{freq_path}/{p_type}" in h5:
                    product_type = p_type
                    break
            
            if not product_type:
                print("Neither GSLC nor GCOV group found.")
                return None

            # 2. Set up paths based on detected product
            base_grid = f'{freq_path}/{product_type}/grids/frequencyA'
            pol_path = f'{base_grid}/listOfPolarizations'
            
            
            if product_type == "GCOV":
                projection_path = f'{base_grid}/projection'
                listofcov_path = f'{base_grid}/listOfCovarianceTerms'
            else:
                projection_path = f'{freq_path}/GSLC/metadata/radarGrid/projection'
                listofcov_path = None

            # 3. Read the data
            try:
                # Read Polarization
                pol_node = h5.get_node(pol_path).read()
                list_of_polarizations = np.array(pol_node).astype(str)
                
                # Read Spacing and Projection
                projection = int(h5.get_node(projection_path).read())
                x_spacing = h5.get_node(f"{base_grid}/xCoordinateSpacing").read()
                y_spacing = h5.get_node(f"{base_grid}/yCoordinateSpacing").read()
                numberofcovarianceTerms = 0
                if listofcov_path is not None:
                    listOfCovarianceTerms = np.array(h5.get_node(listofcov_path).read()).astype(str)
                    numberofcovarianceTerms = len(listOfCovarianceTerms)

                
                return freq_band, list_of_polarizations, x_spacing, y_spacing, int(projection), numberofcovarianceTerms
                

            except tables.NoSuchNodeError as e:
                print(f"Missing expected metadata node: {e}")
                return None

    except Exception as e:
        print(f"Error: {e}")
        raise RuntimeError("Invalid .h5 file or structure!!")


def nisar_dp(matrix_type, inFile, inFolder, base_path, azlks, rglks, recip, max_workers,
                 start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp,
                 inshape, outshape, listOfPolarizations, out_dir=None,cc=1, 
                 clip_window=None,clip_mode='crop', clip=None,
                    progress_callback=None):

    # Determine matrix type based on available polarizations
    # if matrix_type in ['C2','C2HV','C2HX','C2VX']:
        
    if matrix_type=='Sxy':
        print(f"Extracting {matrix_type} matrix elements...")

        if 'HH' in listOfPolarizations and 'HV' in listOfPolarizations:
            # matrix_type = 'C2HX'
            channels = ['HH', 'HV']
        elif 'VV' in listOfPolarizations and 'VH' in listOfPolarizations:
            # matrix_type = 'C2VX'
            channels = ['VV', 'VH']
        elif 'HH' in listOfPolarizations and 'VV' in listOfPolarizations:
            # matrix_type = 'C2HV'
            channels = ['HH', 'VV']
        elif 'RH' in listOfPolarizations and 'RV' in listOfPolarizations:
            # matrix_type = 'C2HV'
            channels = ['RH', 'RV']
        elif 'LH' in listOfPolarizations and 'LV' in listOfPolarizations:
            # matrix_type = 'C2HV'
            channels = ['LH', 'LV']
        else:
            print("No valid dual-channel polarization combination found.")
            return



        # Directory setup
        base_name = os.path.basename(inFile).split('.h5')[0]
        if out_dir is None:
            out_dir = os.path.join(inFolder, base_name, matrix_type)
        else:
            out_dir = os.path.join(out_dir, matrix_type)
        os.makedirs(out_dir, exist_ok=True)

        temp_dir = tempfile.mkdtemp(prefix=f"{matrix_type}_", dir=out_dir)
        os.makedirs(temp_dir, exist_ok=True)

        # Dataset paths
        dataset_paths = {ch: f"{base_path}/{ch}" for ch in channels}

        # Call h5_polsar
        h5_polsar(
            h5_file=inFile,
            dataset_paths=dataset_paths,
            output_dir=out_dir,
            temp_dir=temp_dir,
            azlks=azlks,
            rglks=rglks,
            matrix_type=matrix_type,
            apply_multilook=False,
            recip=recip,
            chunk_size_x=get_ml_chunk(rglks, 512),
            chunk_size_y=get_ml_chunk(azlks, 512),
            max_workers=max_workers,
            start_x=start_x, start_y=start_y,
            xres=xres, yres=yres,
            epsg=int(projection),
            fmt=fmt, cog=cog, ovr=ovr, comp=comp,
            dtype=np.complex64,
            inshape=inshape,
            outshape=outshape,
            calibration_constant=cc,
            clip_window=None,
    clip_mode='crop',
    clip=None,
            progress_callback=progress_callback
        )        
    else:
        if 'HH' in listOfPolarizations and 'HV' in listOfPolarizations:
            matrix_type = 'C2HX'
            channels = ['HH', 'HV']
        elif 'VV' in listOfPolarizations and 'VH' in listOfPolarizations:
            matrix_type = 'C2VX'
            channels = ['VV', 'VH']
        elif 'HH' in listOfPolarizations and 'VV' in listOfPolarizations:
            matrix_type = 'C2HV'
            channels = ['HH', 'VV']
        elif 'RH' in listOfPolarizations and 'RV' in listOfPolarizations:
            matrix_type = 'C2R'
            channels = ['RH', 'RV']
        elif 'LH' in listOfPolarizations and 'LV' in listOfPolarizations:
            matrix_type = 'C2L'
            channels = ['LH', 'LV']
        else:
            print("No valid dual-channel polarization combination found.")
            return

        print(f"Extracting {matrix_type} matrix elements...")

        # Directory setup
        base_name = os.path.basename(inFile).split('.h5')[0]
        if out_dir is None:
            out_dir = os.path.join(inFolder, base_name, matrix_type)
        else:
            out_dir = os.path.join(out_dir, matrix_type)
        os.makedirs(out_dir, exist_ok=True)

        temp_dir = tempfile.mkdtemp(prefix=f"{matrix_type}_", dir=out_dir)
        os.makedirs(temp_dir, exist_ok=True)

        # Dataset paths
        dataset_paths = {ch: f"{base_path}/{ch}" for ch in channels}

        # Call h5_polsar
        h5_polsar(
            h5_file=inFile,
            dataset_paths=dataset_paths,
            output_dir=out_dir,
            temp_dir=temp_dir,
            azlks=azlks,
            rglks=rglks,
            matrix_type=matrix_type,
            apply_multilook=True,
            recip=recip,
            chunk_size_x=get_ml_chunk(rglks, 512),
            chunk_size_y=get_ml_chunk(azlks, 512),
            max_workers=max_workers,
            start_x=start_x, start_y=start_y,
            xres=xres, yres=yres,
            epsg=int(projection),
            fmt=fmt, cog=cog, ovr=ovr, comp=comp,
            dtype=np.float32,
            inshape=inshape,
            outshape=outshape,
            calibration_constant=cc,
            clip_window=None,
    clip_mode='crop',
    clip=None,
            progress_callback=progress_callback
        )


def nisar_fp(mat, inFile, inFolder, base_path, azlks, rglks, recip, max_workers,
                   start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp,
                   inshape, outshape, out_dir=None,cc=1, clip_window=None,clip_mode='crop', clip=None,
                   progress_callback=None):

    MATRIX_CONFIG = {
        'S2':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': False, 'dtype': np.complex64},
        'T4':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': True,  'dtype': np.float32},
        'T3':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': True,  'dtype': np.float32},
        'C4':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': True,  'dtype': np.float32},
        'M4':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': True,  'dtype': np.float32},
        'C3':   {'channels': ['HH', 'HV', 'VH', 'VV'], 'apply_multilook': True,  'dtype': np.float32},
        'C2HV': {'channels': ['HH', 'VV'],             'apply_multilook': True,  'dtype': np.float32},
        'C2HX': {'channels': ['HH', 'HV'],             'apply_multilook': True,  'dtype': np.float32},
        'C2VX': {'channels': ['VV', 'VH'],             'apply_multilook': True,  'dtype': np.float32},
        'T2HV': {'channels': ['HH', 'VV'],             'apply_multilook': True,  'dtype': np.float32},
        'C2L':  {'channels': ['LH', 'LV'],             'apply_multilook': True,  'dtype': np.float32},
        'C2R':  {'channels': ['RH', 'RV'],             'apply_multilook': True,  'dtype': np.float32},
    }


    if mat not in MATRIX_CONFIG:
        raise ValueError(f"Unsupported matrix type: {mat}. Choose from {', '.join(MATRIX_CONFIG.keys())}")

    print(f"Extracting {mat} matrix elements...")

    # Directory setup
    base_name = os.path.basename(inFile).split('.h5')[0]
    if out_dir is None:
        out_dir = os.path.join(inFolder, base_name, mat)
        os.makedirs(out_dir, exist_ok=True)
    else:
        out_dir = os.path.join(out_dir, mat)
        os.makedirs(out_dir, exist_ok=True)

    # Use tempfile for temp_dir
    temp_dir = tempfile.mkdtemp(prefix=f"{mat}_", dir=out_dir)
    os.makedirs(temp_dir, exist_ok=True)

    # Dataset paths
    channels = MATRIX_CONFIG[mat]['channels']
    dataset_paths = {ch: f"{base_path}/{ch}" for ch in channels}

    # Call h5_polsar
    h5_polsar(
        h5_file=inFile,
        dataset_paths=dataset_paths,
        output_dir=out_dir,
        temp_dir=temp_dir,
        azlks=azlks,
        rglks=rglks,
        matrix_type=mat,
        apply_multilook=MATRIX_CONFIG[mat]['apply_multilook'],
        recip=recip,
        chunk_size_x=get_ml_chunk(rglks, 512),
        chunk_size_y=get_ml_chunk(azlks, 512),
        max_workers=max_workers,
        start_x=start_x, start_y=start_y,
        xres=xres, yres=yres,
        epsg=int(projection),
        fmt=fmt, cog=cog, ovr=ovr, comp=comp,
        dtype=MATRIX_CONFIG[mat]['dtype'],
        inshape=inshape,
        outshape=outshape,
        calibration_constant=cc,
        clip_window=clip_window,
        clip_mode=clip_mode,
        clip=clip,

        progress_callback=progress_callback
    )


tables.parameters.PYTABLES_SYS_ATTRS = False 
def get_geo_info(inFile, azlks, rglks):

    with tables.open_file(inFile, "r") as h5:
        try:
            # Access the 'science' group
            science_grp = h5.root.science
            
            # Detect SAR band (e.g., 'SSAR' or 'LSAR')
            sar_key = [node._v_name for node in science_grp if "SAR" in node._v_name][0]
            sar_node = h5.get_node(f"/science/{sar_key}")
            
            # Detect Product Type ('GSLC' or 'GCOV')
            product_type = [node._v_name for node in sar_node if node._v_name in ["GSLC", "GCOV"]][0]
            
            # Construct path and fetch coordinates
            grid_base = f"/science/{sar_key}/{product_type}/grids/frequencyA"
            
            xcoords = h5.get_node(f"{grid_base}/xCoordinates").read()
            ycoords = h5.get_node(f"{grid_base}/yCoordinates").read()
        
            # Calculate Shapes and Extents
            # Note: PyTables/HDF5 usually follows [y, x] (Row, Col) convention
            # inshape = [len(ycoords), len(xcoords)] 
            # outshape = [len(ycoords) // azlks, len(xcoords) // rglks]
            inshape = [len(xcoords), len(ycoords)]  
            outshape = [len(xcoords) // rglks, len(ycoords) // azlks]
            
            # Standard Geo-referencing: min X (West) and max Y (North)
            start_x = np.min(xcoords)
            start_y = np.max(ycoords)
            
            # Optional: Print detection for debugging
            # print(f"Detected: {sar_key} | {product_type}")
            
            return inshape, outshape, start_x, start_y, xcoords, ycoords

        except IndexError:
            raise KeyError(f"Could not find valid SAR band or GSLC/GCOV group in {inFile}")
        except Exception as e:
            print(f"Error processing HDF5: {e}")
            raise

def get_nisar_incidence_meta(inFile, product_type, freq_band):

    band_path = f'/science/{freq_band}SAR'

    if product_type == 'GSLC':
        incidence_path = (
            f'{band_path}/GSLC/metadata/radarGrid/incidenceAngle'
        )

    elif product_type == 'GCOV':
        incidence_path = (
            f'{band_path}/GCOV/metadata/radarGrid/incidenceAngle'
        )

    else:
        raise ValueError(
            f"Unsupported product type: {product_type}"
        )

    with tables.open_file(inFile, 'r') as h5:

        incidence = h5.get_node(incidence_path)

        print("Incidence angle shape:", incidence.shape)

        return incidence_path

def nisar_incidence_angle(
    inFile,
    product_type,
    freq_band,
    output_dir,
    xcoords,
    ycoords,
    outshape,
    projection,
    start_x,
    start_y,
    xres,
    yres,
    azlks=1,
    rglks=1,
    fmt='tif',
    clip_window=None,
    clip_mode='crop',
    clip=None,
    progress_callback=None,
    block_rows=128,
    block_cols=4096,
    max_workers=2
):


    # --------------------------------------------------
    # 1. Validation
    # --------------------------------------------------

    product_type = product_type.upper()

    if product_type not in ['GSLC', 'GCOV']:
        raise ValueError("product_type must be GSLC or GCOV")

    if fmt not in ['tif', 'bin']:
        raise ValueError("fmt must be tif or bin")

    if clip_mode not in ['crop', 'mask']:
        raise ValueError("clip_mode must be crop or mask")

    if clip_mode == 'mask' and clip is None:
        raise ValueError("A vector file is required for mask mode.")

    if block_rows < 1 or block_cols < 1:
        raise ValueError("block_rows and block_cols must be >= 1")

    os.makedirs(output_dir, exist_ok=True)

    xcoords = np.asarray(xcoords, dtype=np.float32)
    ycoords = np.asarray(ycoords, dtype=np.float32)

    out_cols, out_rows = map(int, outshape)

    azlks = int(azlks)
    rglks = int(rglks)

    if azlks < 1 or rglks < 1:
        raise ValueError("Multilooking factors must be >= 1")

    if len(xcoords) < out_cols * rglks:
        raise ValueError("Insufficient range coordinates")

    if len(ycoords) < out_rows * azlks:
        raise ValueError("Insufficient azimuth coordinates")

    if len(xcoords) < 2 or len(ycoords) < 2:
        raise ValueError("Coordinate arrays must contain at least 2 elements")

    # Both ascending and descending coordinates are supported.
    dx_target = np.diff(xcoords)
    dy_target = np.diff(ycoords)

    if not (
        np.all(dx_target > 0) or
        np.all(dx_target < 0)
    ):
        raise ValueError("xcoords must be strictly monotonic")

    if not (
        np.all(dy_target > 0) or
        np.all(dy_target < 0)
    ):
        raise ValueError("ycoords must be strictly monotonic")

    print(
        f"Incidence angle multilooking: "
        f"{azlks} x {rglks}"
    )

    # --------------------------------------------------
    # 2. HDF5 metadata
    # --------------------------------------------------

    base = f"/science/{freq_band}SAR/{product_type}"

    incidence_path = (
        f"{base}/metadata/radarGrid/incidenceAngle"
    )

    with tables.open_file(inFile, 'r') as h5:

        inc_node = h5.get_node(incidence_path)

        if len(inc_node.shape) == 3:
            ny, nx = inc_node.shape[1:]
        else:
            ny, nx = inc_node.shape

        # Look direction
        lookDirection = None

        look_paths = [
            f"{base}/metadata/sourceData/lookDirection",
            f"{base}/metadata/lookDirection"
        ]

        for path in look_paths:

            try:
                value = h5.get_node(path).read()

                if isinstance(value, np.ndarray):
                    value = value.item()

                lookDirection = value
                break

            except tables.NoSuchNodeError:
                continue

        # Orbit direction
        orbit_path = (
            f"/science/{freq_band}SAR/"
            "identification/orbitPassDirection"
        )

        orbitPassDirection = h5.get_node(
            orbit_path
        ).read()

    # --------------------------------------------------
    # Decode metadata values
    # --------------------------------------------------

    def decode_metadata(value):

        if isinstance(value, np.ndarray):
            value = value.item()

        if isinstance(value, (bytes, np.bytes_)):
            value = value.decode("utf-8")

        return str(value).strip()


    lookDirection = decode_metadata(lookDirection)
    orbitPassDirection = decode_metadata(orbitPassDirection)

    # print("Decoded look direction:", repr(lookDirection))
    # print("Decoded orbit direction:", repr(orbitPassDirection))

    # --------------------------------------------------
    # 3. Orientation correction
    # --------------------------------------------------

    # Exactly the same orientation logic as classic method.

    flip_y = False
    flip_x = False

    if (
        lookDirection == 'Left'
        and orbitPassDirection == 'Descending'
    ):
        flip_y = True

    elif (
        lookDirection == 'Left'
        and orbitPassDirection == 'Ascending'
    ):
        flip_x = True

    elif (
        lookDirection == 'Right'
        and orbitPassDirection == 'Descending'
    ):
        flip_x = True
        flip_y = True

    # print("Look direction:", lookDirection)
    # print("Orbit direction:", orbitPassDirection)

    # print("Flip vertical:", flip_y)
    # print("Flip horizontal:", flip_x)




    # print("\n--- COORDINATE DEBUG ---")

    # print("X first:", xcoords[0])
    # print("X last:", xcoords[-1])

    # print("Y first:", ycoords[0])
    # print("Y last:", ycoords[-1])

    # print("X direction:", np.sign(xcoords[-1] - xcoords[0]))
    # print("Y direction:", np.sign(ycoords[-1] - ycoords[0]))

    # print("\n--- ORIENTATION ---")

    # print("Look:", lookDirection)
    # print("Orbit:", orbitPassDirection)
    # print("flip_x:", flip_x)
    # print("flip_y:", flip_y)



    # --------------------------------------------------
    # 4. Source interpolation grid
    # --------------------------------------------------

    # RegularGridInterpolator in the classic implementation
    # uses ascending source coordinate axes.

    orig_x0 = float(np.min(xcoords))
    orig_y0 = float(np.min(ycoords))

    dx = (
        float(np.max(xcoords)) - orig_x0
    ) / (nx - 1)

    dy = (
        float(np.max(ycoords)) - orig_y0
    ) / (ny - 1)

    if dx <= 0 or dy <= 0:
        raise ValueError("Invalid incidence-angle coordinate spacing")

    # --------------------------------------------------
    # 5. Output clipping dimensions
    # --------------------------------------------------

    x_offset = 0
    y_offset = 0

    x_end = out_cols
    y_end = out_rows

    if clip_window is not None:

        x0, x1, y0, y1 = map(int, clip_window)

        x_offset = x0 // rglks
        y_offset = y0 // azlks

        x_end = min(
            out_cols,
            int(np.ceil(x1 / rglks))
        )

        y_end = min(
            out_rows,
            int(np.ceil(y1 / azlks))
        )

    final_cols = x_end - x_offset
    final_rows = y_end - y_offset

    if final_cols <= 0 or final_rows <= 0:
        raise ValueError("Clipping window produces empty raster")

    # print(
    #     f"Output dimensions: {final_cols} x {final_rows}"
    # )

    # --------------------------------------------------
    # 6. Georeferencing
    # --------------------------------------------------

    pixel_width = abs(float(xres)) * rglks
    pixel_height = -abs(float(yres)) * azlks

    geo_x = float(start_x) + x_offset * pixel_width
    geo_y = float(start_y) + y_offset * pixel_height

    geotransform = (
        geo_x,
        pixel_width,
        0,
        geo_y,
        0,
        pixel_height
    )

    srs = osr.SpatialReference()

    srs.ImportFromEPSG(int(projection))

    srs.SetAxisMappingStrategy(
        osr.OAMS_TRADITIONAL_GIS_ORDER
    )

    target_wkt = srs.ExportToWkt()

    # --------------------------------------------------
    # 7. Prepare polygon mask
    # --------------------------------------------------

    mem_ds = None
    mem_layer = None

    if clip_mode == 'mask' and clip is not None:

        vector_ds = ogr.Open(clip)

        if vector_ds is None:
            raise ValueError(
                f"Cannot open vector file: {clip}"
            )

        layer = vector_ds.GetLayer()

        source_srs = layer.GetSpatialRef()

        if source_srs is None:
            raise ValueError(
                "Vector file has no CRS information"
            )

        source_srs = source_srs.Clone()

        source_srs.SetAxisMappingStrategy(
            osr.OAMS_TRADITIONAL_GIS_ORDER
        )

        transform = osr.CoordinateTransformation(
            source_srs,
            srs
        )

        mem_ds = ogr.GetDriverByName(
            'Memory'
        ).CreateDataSource('')

        mem_layer = mem_ds.CreateLayer(
            'mask',
            srs,
            ogr.wkbUnknown
        )

        layer.ResetReading()

        for feature in layer:

            geom = feature.GetGeometryRef()

            if geom is None:
                continue

            geom = geom.Clone()

            geom.Transform(transform)

            out_feature = ogr.Feature(
                mem_layer.GetLayerDefn()
            )

            out_feature.SetGeometry(geom)

            mem_layer.CreateFeature(out_feature)

            out_feature = None

        vector_ds = None

    # --------------------------------------------------
    # 8. Create output
    # --------------------------------------------------

    output_path = os.path.join(
        output_dir,
        f"incidenceAngle.{fmt}"
    )

    if fmt == 'tif':

        out_ds = gdal.GetDriverByName(
            'GTiff'
        ).Create(
            output_path,
            final_cols,
            final_rows,
            1,
            gdal.GDT_Float32,
            options=[
                'TILED=YES',
                'COMPRESS=LZW',
                'BIGTIFF=IF_SAFER'
            ]
        )

        out_ds.SetGeoTransform(geotransform)
        out_ds.SetProjection(target_wkt)

        out_band = out_ds.GetRasterBand(1)

        out_band.SetNoDataValue(float('nan'))

    else:

        out_ds = None

        out_band = np.memmap(
            output_path,
            dtype=np.float32,
            mode='w+',
            shape=(final_rows, final_cols)
        )

    # --------------------------------------------------
    # 9. Bilinear interpolation helper
    # --------------------------------------------------

    def interpolate_tile(tx, ty, node):

        # Convert target coordinates into fractional
        # source-grid indices.

        col_f = (
            (tx.astype(np.float32) - orig_x0) / dx
        )

        row_f = (
            (ty.astype(np.float32) - orig_y0) / dy
        )

        # Outside source bounds
        valid_x = (
            (col_f >= 0) &
            (col_f <= nx - 1)
        )

        valid_y = (
            (row_f >= 0) &
            (row_f <= ny - 1)
        )

        if not np.any(valid_x) or not np.any(valid_y):

            return np.full(
                (len(ty), len(tx)),
                np.nan,
                dtype=np.float32
            )

        # Bilinear neighbour indices
        c0 = np.floor(col_f).astype(np.int64)
        r0 = np.floor(row_f).astype(np.int64)

        c0 = np.clip(c0, 0, nx - 2)
        r0 = np.clip(r0, 0, ny - 2)

        c1 = c0 + 1
        r1 = r0 + 1

        # Smallest source window needed by this tile
        sc0 = int(c0.min())
        sc1 = int(c1.max()) + 1

        sr0 = int(r0.min())
        sr1 = int(r1.max()) + 1

        # Map corrected coordinates to original HDF5 indices.
        if flip_y:

            read_r0 = ny - sr1
            read_r1 = ny - sr0

        else:

            read_r0 = sr0
            read_r1 = sr1

        if flip_x:

            read_c0 = nx - sc1
            read_c1 = nx - sc0

        else:

            read_c0 = sc0
            read_c1 = sc1

        # Read only the required HDF5 region.
        if len(node.shape) == 3:

            source = node[
                0,
                read_r0:read_r1,
                read_c0:read_c1
            ]

        else:

            source = node[
                read_r0:read_r1,
                read_c0:read_c1
            ]

        source = np.asarray(
            source,
            dtype=np.float32
        )

        # Restore the classic orientation.
        if flip_y:
            source = np.flipud(source)

        if flip_x:
            source = np.fliplr(source)

        # Convert to local source indices.
        rr0 = r0 - sr0
        rr1 = r1 - sr0

        cc0 = c0 - sc0
        cc1 = c1 - sc0

        # Bilinear interpolation weights.
        wy = (
            row_f - r0
        ).astype(np.float32)

        wx = (
            col_f - c0
        ).astype(np.float32)

        # Extract the four neighbouring values.
        v00 = source[
            rr0[:, None],
            cc0[None, :]
        ]

        v01 = source[
            rr0[:, None],
            cc1[None, :]
        ]

        v10 = source[
            rr1[:, None],
            cc0[None, :]
        ]

        v11 = source[
            rr1[:, None],
            cc1[None, :]
        ]

        wx = wx[None, :]
        wy = wy[:, None]

        # Bilinear interpolation.
        with np.errstate(invalid='ignore'):

            top = (
                v00 * (1.0 - wx) +
                v01 * wx
            )

            bottom = (
                v10 * (1.0 - wx) +
                v11 * wx
            )

            result = (
                top * (1.0 - wy) +
                bottom * wy
            )

        # Set out-of-bounds pixels to NaN.
        result[
            ~valid_y[:, None] |
            ~valid_x[None, :]
        ] = np.nan

        return result.astype(
            np.float32,
            copy=False
        )

    # --------------------------------------------------
    # 10. Chunked interpolation and multilooking
    # --------------------------------------------------

    completed_rows = 0

    with tables.open_file(inFile, 'r') as h5:

        node = h5.get_node(incidence_path)

        pbar = tqdm(
            total=final_rows,
            desc="Incidence angle",
            unit="rows",
            dynamic_ncols=True
        )

        for row_start in range(
            0,
            final_rows,
            block_rows
        ):

        # for row_start in range(
        #     0,
        #     final_rows,
        #     block_rows
        # ):

            row_end = min(
                row_start + block_rows,
                final_rows
            )

            current_rows = row_end - row_start

            global_row = y_offset + row_start

            # Original-resolution source row indices.
            src_row_start = global_row * azlks

            src_row_end = (
                src_row_start +
                current_rows * azlks
            )

            ty = ycoords[
                src_row_start:src_row_end
            ]

            for col_start in range(
                0,
                final_cols,
                block_cols
            ):

                col_end = min(
                    col_start + block_cols,
                    final_cols
                )

                current_cols = col_end - col_start

                global_col = x_offset + col_start

                src_col_start = global_col * rglks

                src_col_end = (
                    src_col_start +
                    current_cols * rglks
                )

                tx = xcoords[
                    src_col_start:src_col_end
                ]

                # --------------------------------------
                # Interpolation
                # --------------------------------------

                block_data = interpolate_tile(
                    tx,
                    ty,
                    node
                )

                # --------------------------------------
                # Multilooking
                # --------------------------------------

                block_data = block_data.reshape(
                    current_rows,
                    azlks,
                    current_cols,
                    rglks
                )

                with np.errstate(
                    invalid='ignore'
                ):

                    block_data = np.nanmean(
                        block_data,
                        axis=(1, 3),
                        dtype=np.float32
                    )

                block_data = block_data.astype(
                    np.float32,
                    copy=False
                )

                # --------------------------------------
                # Polygon mask
                # --------------------------------------

                if mem_layer is not None:

                    tile_gt = (
                        geo_x + col_start * pixel_width,
                        pixel_width,
                        0,
                        geo_y + row_start * pixel_height,
                        0,
                        pixel_height
                    )

                    mask_ds = gdal.GetDriverByName(
                        'MEM'
                    ).Create(
                        '',
                        current_cols,
                        current_rows,
                        1,
                        gdal.GDT_Byte
                    )

                    mask_ds.SetGeoTransform(tile_gt)

                    mask_ds.SetProjection(target_wkt)

                    mask_band = mask_ds.GetRasterBand(1)

                    mask_band.Fill(0)

                    gdal.RasterizeLayer(
                        mask_ds,
                        [1],
                        mem_layer,
                        burn_values=[1]
                    )

                    mask = mask_band.ReadAsArray()

                    block_data[mask == 0] = np.nan

                    mask_ds = None
                    mask_band = None
                    mask = None

                # --------------------------------------
                # Write output
                # --------------------------------------

                if fmt == 'tif':

                    out_band.WriteArray(
                        block_data,
                        xoff=col_start,
                        yoff=row_start
                    )

                else:

                    out_band[
                        row_start:row_end,
                        col_start:col_end
                    ] = block_data

                del block_data

            # completed_rows += current_rows

            # if progress_callback is not None:

            #     progress_callback(
            #         completed_rows / final_rows
            #     )
            completed_rows += current_rows

            pbar.update(current_rows)

            if progress_callback is not None:
                progress_callback(
                    completed_rows / final_rows
                )

            # print(
            #     f"Incidence angle: "
            #     f"{completed_rows}/{final_rows} rows"
            # )

    pbar.close()
    # --------------------------------------------------
    # 11. Finalize
    # --------------------------------------------------

    if fmt == 'tif':

        out_band.FlushCache()

        out_band = None
        out_ds = None

    else:

        out_band.flush()

        del out_band

    mem_layer = None
    mem_ds = None

    print(
        "Incidence angle saved:",
        output_path
    )

    return output_path



def _process_incidence_chunk(args):

    from scipy.ndimage import map_coordinates
    import tables
    import numpy as np

    (
        inFile,
        incidence_path,
        row_start,
        row_end,
        xcoords,
        ycoords,
        orig_x0,
        orig_y0,
        dx,
        dy,
        nx,
        ny,
        azlks,
        rglks,
        flip_y,
        flip_x
    ) = args

    # --------------------------------------------------
    # 1. Determine required source window
    # --------------------------------------------------

    tx_min = float(np.min(xcoords))
    tx_max = float(np.max(xcoords))

    ty_min = float(np.min(ycoords))
    ty_max = float(np.max(ycoords))

    # Source coordinate indices
    c0 = max(int(np.floor((tx_min - orig_x0) / dx)) - 1, 0)
    c1 = min(int(np.ceil((tx_max - orig_x0) / dx)) + 2, nx)

    r0 = max(int(np.floor((ty_min - orig_y0) / dy)) - 1, 0)
    r1 = min(int(np.ceil((ty_max - orig_y0) / dy)) + 2, ny)

    # Ensure minimum dimensions
    c1 = min(nx, max(c1, c0 + 2))
    r1 = min(ny, max(r1, r0 + 2))

    # --------------------------------------------------
    # 2. Map to original HDF5 orientation
    # --------------------------------------------------

    read_r0 = ny - r1 if flip_y else r0
    read_r1 = ny - r0 if flip_y else r1

    read_c0 = nx - c1 if flip_x else c0
    read_c1 = nx - c0 if flip_x else c1

    # --------------------------------------------------
    # 3. Read only required HDF5 window
    # --------------------------------------------------

    with tables.open_file(inFile, 'r') as h5:

        node = h5.get_node(incidence_path)

        if len(node.shape) == 3:

            data = node[
                0,
                read_r0:read_r1,
                read_c0:read_c1
            ]

        else:

            data = node[
                read_r0:read_r1,
                read_c0:read_c1
            ]

        data = np.asarray(data, dtype=np.float32)

    # Restore orientation
    if flip_y:
        data = np.flipud(data)

    if flip_x:
        data = np.fliplr(data)

    # --------------------------------------------------
    # 4. Calculate fractional source indices
    # --------------------------------------------------

    x_indices = (
        (xcoords - orig_x0) / dx - c0
    ).astype(np.float32)

    y_indices = (
        (ycoords - orig_y0) / dy - r0
    ).astype(np.float32)

    # --------------------------------------------------
    # 5. Bilinear interpolation
    # --------------------------------------------------

    block = np.empty(
        (len(ycoords), len(xcoords)),
        dtype=np.float32
    )

    # Only one row of interpolation coordinates in memory
    for i, yi in enumerate(y_indices):

        coordinates = np.empty(
            (2, len(x_indices)),
            dtype=np.float32
        )

        coordinates[0, :] = yi
        coordinates[1, :] = x_indices

        map_coordinates(
            data,
            coordinates,
            output=block[i],
            order=1,
            mode='constant',
            cval=np.nan,
            prefilter=False
        )

    # --------------------------------------------------
    # 6. Multilooking
    # --------------------------------------------------

    rows = len(ycoords) // azlks
    cols = len(xcoords) // rglks

    block = block[
        :rows * azlks,
        :cols * rglks
    ]

    block = block.reshape(
        rows,
        azlks,
        cols,
        rglks
    )

    # Float32 accumulation
    with np.errstate(invalid='ignore'):

        block = np.nanmean(
            block,
            axis=(1, 3),
            dtype=np.float32
        )

    return row_start, block.astype(np.float32, copy=False)


def nisar_gcov(matrix_type, inFile, inFolder, base_path, azlks, rglks, max_workers,
                 start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp,
                 inshape, outshape, listOfPolarizations, numberofcovarianceTerms, out_dir=None,cc=1, 
                 rtc_factor_path=None,
                 clip_window=None,
                clip_mode='crop',
                clip=None,
                 progress_callback=None):

    print(f"Extracting elements...")
    if len(listOfPolarizations)==2 and numberofcovarianceTerms==2:
        if 'HH' in listOfPolarizations and 'HV' in listOfPolarizations:
            # matrix_type = 'C2HX'
            channels = ['HHHH', 'HVHV']
        elif 'VV' in listOfPolarizations and 'VH' in listOfPolarizations:
            # matrix_type = 'C2VX'
            channels = ['VVVV', 'VHVH']
        elif 'HH' in listOfPolarizations and 'VV' in listOfPolarizations:
            # matrix_type = 'C2HV'
            channels = ['HHHH', 'VVVV']
        elif 'RH' in listOfPolarizations and 'RV' in listOfPolarizations:
            # matrix_type = 'C2HV'
            channels = ['RHRH', 'RVRV']
        else:
            print("No valid dual-channel polarization combination found.")
            return
    elif len(listOfPolarizations)==2 and numberofcovarianceTerms==3:
        if 'HH' in listOfPolarizations and 'HV' in listOfPolarizations:
            matrix_type = 'C2HX'
            channels = ['HHHH', 'HVHV','HHHV']
        elif 'VV' in listOfPolarizations and 'VH' in listOfPolarizations:
            matrix_type = 'C2VX'
            channels = ['VVVV', 'VHVH','VVVH']
        elif 'HH' in listOfPolarizations and 'VV' in listOfPolarizations:
            matrix_type = 'C2HV'
            channels = ['HHHH', 'VVVV','HHVV']
        elif 'RH' in listOfPolarizations and 'RV' in listOfPolarizations:
            matrix_type = 'C2R'
            channels = ['RHRH', 'RVRV','RHRV']
        elif 'LH' in listOfPolarizations and 'LV' in listOfPolarizations:
            matrix_type = 'C2L'
            channels = ['LHLH', 'LVLV','LHLV']
        else:
            print("No valid dual-channel polarization combination found.")
            return
    elif len(listOfPolarizations)==4 and numberofcovarianceTerms==4:
        channels = ['HHHH', 'HVHV','VVVV','VHVH']
    elif len(listOfPolarizations)==4 and numberofcovarianceTerms==10:
        # channels = ['HHHH', 'HVHV','VVVV','VHVH','HHHV','HHVV','HVVV','VHVH','VVVH','HHVV']
        channels = ['HHHH', 'HHHV','HHVH','HHVV','HVHV','HVVH','HVVV','VHVH','VHVV','VVVV']

    else:
        print("No valid polarization combination found.")
        return

    # Directory setup
    base_name = os.path.basename(inFile).split('.h5')[0]
    if out_dir is None:
        out_dir = os.path.join(inFolder, base_name, matrix_type)
    else:
        out_dir = os.path.join(out_dir, matrix_type)
    os.makedirs(out_dir, exist_ok=True)

    temp_dir = tempfile.mkdtemp(prefix=f"{matrix_type}_", dir=out_dir)
    os.makedirs(temp_dir, exist_ok=True)

    # Dataset paths
    dataset_paths = {ch: f"{base_path}/{ch}" for ch in channels}
    recip = False
    # print(dataset_paths)
    # Call h5_polsar
    h5_polsar(
        h5_file=inFile,
        dataset_paths=dataset_paths,
        output_dir=out_dir,
        temp_dir=temp_dir,
        azlks=azlks,
        rglks=rglks,
        matrix_type=matrix_type,
        apply_multilook=True,
        recip=recip,
        chunk_size_x=get_ml_chunk(rglks, 512),
        chunk_size_y=get_ml_chunk(azlks, 512),
        max_workers=max_workers,
        start_x=start_x, start_y=start_y,
        xres=xres, yres=yres,
        epsg=int(projection),
        fmt=fmt, cog=cog, ovr=ovr, comp=comp,
        dtype=np.float32,
        inshape=inshape,
        outshape=outshape,
        calibration_constant=cc,
        rtc_factor_path=rtc_factor_path,
        clip_window=clip_window,
        clip_mode=clip_mode,
        clip=clip,
        progress_callback=progress_callback
    )        
 
[docs] @time_it def import_nisar_rslc(inFile, mat='T3', azlks=22,rglks=10, #inc=False, fmt='tif', cog=False, ovr = [2, 4, 8, 16], comp=False, out_dir=None, recip=False, max_workers=None, progress_callback=None ): """ Extracts the C2 (for dual-pol), S2/C3/T3 (for full-pol) matrix elements from a NISAR RSLC HDF5 file and saves them into respective binary files. Example: -------- >>> import_nisar_rslc("path_to_file.h5", azlks=30, rglks=15) This will extract the C2 (for dual-pol), S2/C3/T3 (for full-pol) matrix elements from the specified NISAR RSLC file and save them in the respective folders. Parameters: ----------- inFile : str The path to the NISAR RSLC HDF5 file containing the radar data. mat : str, optional (default = 'T3' or 'C2) Type of matrix to extract. Valid options for Full-pol: 'S2', 'C4, 'C3', 'T4', 'T3', 'C2HX', 'C2VX', 'C2HV','T2HV', 'M4' and Dual-pol: 'Sxy','C2'. azlks : int, optional (default=3) The number of azimuth looks for multi-looking. rglks : int, optional (default=3) The number of range looks for multi-looking. fmt : {'tif', 'bin'}, optional (default='tif') Output format: - 'tif': GeoTIFF - 'bin': Raw binary format cog : bool, optional (default=False) If True, outputs will be saved as Cloud Optimized GeoTIFFs with internal tiling and overviews. ovr : list of int, optional (default=[2, 4, 8, 16]) Overview levels for COG generation. Ignored if cog=False. comp : bool, optional (default=False) If True, applies LZW compression to GeoTIFF outputs. out_dir : str or None, optional (default=None) Directory to save output files. If None, a folder named after the matrix type will be created in the same location as the input file. recip : bool, optional (default=False) If True, scattering matrix reciprocal symmetry is applied, i.e, S_HV = S_VH. """ freq_band,listOfPolarizations = rslc_meta(inFile) nchannels = len(listOfPolarizations) print(f"Detected {freq_band}-band {listOfPolarizations} ") inFolder = os.path.dirname(inFile) if not inFolder: inFolder = "." with tables.open_file(inFile, mode="r") as h5: base_path = get_rslc_path(h5, freq_band) h5.close() start_x = 0 start_y = 0 xres = 1 yres = 1 projection = 4326 if nchannels==2: nisar_dp(mat,inFile, inFolder, base_path, azlks, rglks, recip, max_workers, start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp, None, None, listOfPolarizations, out_dir, progress_callback=progress_callback) elif nchannels==4: nisar_fp(mat, inFile, inFolder, base_path, azlks, rglks, recip, max_workers, start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp, None, None, out_dir, progress_callback=progress_callback)
[docs] @time_it def import_nisar_gslc(inFile, mat='T3', azlks=2, rglks=2, inc=False,clip=None, clip_crs=None, clip_mode='crop',fmt='tif', cog=False,ovr = [2, 4, 8, 16],comp=False, out_dir=None, recip=False, max_workers=None, progress_callback=None): """ Extracts the C2 matrix elements (C11, C22, and C12) from a NISAR GSLC HDF5 file and saves them into respective binary files. Example: -------- >>> import_nisar_gslc("path_to_file.h5", azlks=30, rglks=15) This will extract the C2 matrix elements from the dual-pol NISAR GSLC file and save them in the 'C2' folder. or for full-pol 'T3' Parameters: ----------- inFile : str The path to the NISAR GSLC HDF5 file containing the radar data. mat : str, optional (default = 'C2' for Dual-pol, 'T3' for Full-pol) Type of matrix to extract. Valid options for Full-pol: 'S2', 'C4, 'C3', 'T4', 'T3', 'C2HX', 'C2VX', 'C2HV','T2HV','M4' and Dual-pol: 'Sxy','C2'. azlks : int, optional (default=3) The number of azimuth looks for multi-looking. rglks : int, optional (default=3) The number of range looks for multi-looking. inc : bool, optional (default=False) If True, extracts the incidence angle data and saves it as a GeoTIFF (.tif). clip : str, os.PathLike, tuple, list, or None, optional (default=None) Defines the Area of Interest (AOI) for clipping output rasters. Accepts a vector file path (Shapefile, GeoPackage, GeoJSON) or a bounding box (xmin, ymin, xmax, ymax). Vector files must have a valid CRS. If None, the entire raster is processed. clip_crs : int or None, optional (default=None) EPSG code of the bounding box CRS. Required when clip is a bounding box. For vector inputs, the CRS is read automatically. clip_mode : {'crop', 'mask'}, optional (default='crop') Clipping method: - 'crop': Crops the raster to the AOI bounding extent. - 'mask': Masks pixels outside the AOI while preserving the raster dimensions and georeferencing. fmt : {'tif', 'bin'}, optional (default='tif') Output format: - 'tif': GeoTIFF with georeferencing - 'bin': Raw binary format cog : bool, optional (default=False) If True, outputs will be saved as Cloud Optimized GeoTIFFs with internal tiling and overviews. ovr : list of int, optional (default=[2, 4, 8, 16]) Overview levels for COG generation. Ignored if cog=False. comp : bool, optional (default=False) If True, applies LZW compression to GeoTIFF outputs. out_dir : str or None, optional (default=None) Directory to save output files. If None, a folder named after the matrix type will be created in the same location as the input file. recip : bool, optional (default=False) If True, scattering matrix reciprocal symmetry is applied, i.e, S_HV = S_VH. """ # freq_band,listOfPolarizations, xres, yres, projection = gslc_meta(inFile) freq_band,listOfPolarizations, xres, yres, projection, numberofcovarianceTerms = get_geo_meta(inFile) nchannels = len(listOfPolarizations) print(f"Detected {freq_band}-band polarization channels: {listOfPolarizations}") inshape, outshape, start_x, start_y, xcoords,ycoords = get_geo_info(inFile, azlks, rglks) # Prepare clipping window clip_window = prepare_clip_window( clip, clip_crs, projection, xcoords, ycoords, azlks, rglks ) if clip_window is not None: x0, x1, y0, y1 = clip_window print("AOI pixel window:", clip_window) print( "AOI dimensions:", x1 - x0, "x", y1 - y0 ) # print(projection,start_x,start_y,xres,yres,inshape,outshape) # print(min(ycoords),max(ycoords), min(ycoords)+np.abs(yres)*(inshape[1]-1)) inFolder = os.path.dirname(inFile) or "." base_name = os.path.basename(inFile).split('.h5')[0] if out_dir is None: out_dir = os.path.join(inFolder, base_name) os.makedirs(out_dir, exist_ok=True) base_path = f'/science/{freq_band}SAR/GSLC/grids/frequencyA' if nchannels==2: # print("Dual-Pol data detected.",mat) nisar_dp(mat,inFile, inFolder, base_path, azlks, rglks, recip, max_workers, start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp, inshape, outshape, listOfPolarizations, out_dir, clip_window=clip_window, clip_mode=clip_mode, clip=clip, progress_callback=progress_callback) elif nchannels==4: nisar_fp(mat, inFile, inFolder, base_path, azlks, rglks, recip, max_workers, start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp, inshape, outshape, out_dir, clip_window=clip_window, clip_mode=clip_mode, clip=clip, progress_callback=progress_callback) if inc: nisar_incidence_angle( inFile=inFile, product_type='GSLC', freq_band=freq_band, output_dir=out_dir, xcoords=xcoords, ycoords=ycoords, outshape=outshape, projection=projection, start_x=start_x, start_y=start_y, xres=xres, yres=yres, azlks=azlks, rglks=rglks, fmt=fmt, clip_window=clip_window, clip_mode=clip_mode, clip=clip, progress_callback=progress_callback, block_rows=64 )
[docs] @time_it def import_nisar_gcov(inFile, azlks=1, rglks=1, bsc='sigma0',inc=False,clip=None, clip_crs=None, clip_mode='crop',fmt='tif', cog=False,ovr = [2, 4, 8, 16],comp=False, out_dir=None, max_workers=None, progress_callback=None): """ Extracts the backscatter intensity elements from a NISAR GCOV HDF5 file and saves them into respective tif/binar files. Example: -------- >>> import_nisar_gcov("path_to_file.h5") This will extract the intensity elements from NISAR GCOV HDF5 file without multi-looking >>> import_nisar_gcov("path_to_file.h5", azlks=3, rglks=3) This will extract the intensity elements from NISAR GCOV HDF5 file with 3x3 multi-looking. Parameters: ----------- inFile : str The path to the NISAR GCOV HDF5 file containing the radar data. azlks : int, optional (default=1) The number of azimuth looks for multi-looking. rglks : int, optional (default=1) The number of range looks for multi-looking. bsc : str, optional (default='sigma0') Backscatter type to extract. Valid options are: - 'sigma0': Sigma nought backscatter - 'gamma0': Gamma nought backscatter inc : bool, optional (default=False) If True, extracts the incidence angle data and saves it as a GeoTIFF (.tif). clip : str, os.PathLike, tuple, list, or None, optional (default=None) Defines the Area of Interest (AOI) for clipping output rasters. Accepts a vector file path (Shapefile, GeoPackage, GeoJSON) or a bounding box (xmin, ymin, xmax, ymax). Vector files must have a valid CRS. If None, the entire raster is processed. clip_crs : int or None, optional (default=None) EPSG code of the bounding box CRS. Required when clip is a bounding box. For vector inputs, the CRS is read automatically. clip_mode : {'crop', 'mask'}, optional (default='crop') Clipping method: - 'crop': Crops the raster to the AOI bounding extent. - 'mask': Masks pixels outside the AOI while preserving the raster dimensions and georeferencing. fmt : {'tif', 'bin'}, optional (default='tif') Output format: - 'tif': GeoTIFF with georeferencing - 'bin': Raw binary format cog : bool, optional (default=False) If True, outputs will be saved as Cloud Optimized GeoTIFFs with internal tiling and overviews. ovr : list of int, optional (default=[2, 4, 8, 16]) Overview levels for COG generation. Ignored if cog=False. comp : bool, optional (default=False) If True, applies LZW compression to GeoTIFF outputs. out_dir : str or None, optional (default=None) Directory to save output files. If None, a folder named after the matrix type will be created in the same location as the input file. """ # freq_band,listOfPolarizations, xres, yres, projection = gcov_meta(inFile) freq_band,listOfPolarizations, xres, yres, projection, numberofcovarianceTerms = get_geo_meta(inFile) nchannels = len(listOfPolarizations) print(f"Detected {freq_band}-band polarization channels: {listOfPolarizations}") # Backscatter type selection backscatter_type = bsc.lower() if backscatter_type not in ['gamma0', 'sigma0']: raise ValueError( "backscatter_type must be 'gamma0' or 'sigma0'" ) rtc_factor_path = None if backscatter_type == 'sigma0': rtc_factor_path = ( f'/science/{freq_band}SAR/GCOV/grids/' f'frequencyA/rtcGammaToSigmaFactor' ) with tables.open_file(inFile, 'r') as h5: if rtc_factor_path not in h5: raise ValueError( f"RTC factor not found: {rtc_factor_path}" ) print(f"Selected backscatter type: {backscatter_type}") inshape, outshape, start_x, start_y, xcoords,ycoords = get_geo_info(inFile, azlks, rglks) clip_window = prepare_clip_window( clip, clip_crs, projection, xcoords, ycoords, azlks, rglks ) if clip_window is not None: print("AOI pixel window:", clip_window) inFolder = os.path.dirname(inFile) or "." base_name = os.path.basename(inFile).split('.h5')[0] if out_dir is None: out_dir = os.path.join(inFolder, base_name) os.makedirs(out_dir, exist_ok=True) base_path = f'/science/{freq_band}SAR/GCOV/grids/frequencyA' listOfCovarianceTerms = f"{base_path}/listOfCovarianceTerms" print(f"numberofcovarianceTerms: {numberofcovarianceTerms}") if nchannels==2 and numberofcovarianceTerms==2: mat='I2' elif nchannels==2 and numberofcovarianceTerms==3: mat='C2' elif nchannels==4 and numberofcovarianceTerms==4: mat='I4' elif nchannels==4 and numberofcovarianceTerms==10: mat='C4' else: raise('Invalid number of channels!!') if out_dir is None: out_dir = os.path.join(inFolder, mat) os.makedirs(out_dir, exist_ok=True) nisar_gcov(mat,inFile, inFolder, base_path, azlks, rglks, max_workers, start_x, start_y, xres, yres, projection, fmt, cog, ovr, comp, inshape, outshape, listOfPolarizations, numberofcovarianceTerms, out_dir,rtc_factor_path=rtc_factor_path, clip_window=clip_window, clip_mode=clip_mode, clip=clip, progress_callback=progress_callback) if inc: nisar_incidence_angle( inFile=inFile, product_type='GCOV', freq_band=freq_band, output_dir=out_dir, xcoords=xcoords, ycoords=ycoords, outshape=outshape, projection=projection, start_x=start_x, start_y=start_y, xres=xres, yres=yres, azlks=azlks, rglks=rglks, fmt=fmt, clip_window=clip_window, clip_mode=clip_mode, clip=clip, progress_callback=progress_callback, block_rows=64 )