Esempio n. 1
0
def test_dissolve_with_lists():
    assert anc.dissolve([[1, 2], [3, 4]]) == [1, 2, 3, 4]
    assert anc.dissolve([[[1]]]) == [1]
    assert anc.dissolve(((
        1,
        2,
    ), (3, 4))) == [1, 2, 3, 4]
    assert anc.dissolve(((1, 2), (1, 2))) == [1, 2, 1, 2]
Esempio n. 2
0
 def replace(inlist, replacement):
     outlist = list(inlist)
     for old, new, description in replacement:
         if old[0] not in outlist:
             return outlist
         outlist[outlist.index(old[0])] = new
         for i in range(1, len(old)):
             if old[i] in outlist:
                 outlist.remove(old[i])
     return dissolve(outlist)
Esempio n. 3
0
 def __buildvrt(archives, vrtfile, pattern, vsi, extent, nodata):
     locals = [
         vsi + x for x in dissolve([finder(x, [pattern]) for x in archives])
     ]
     gdalbuildvrt(src=locals,
                  dst=vrtfile,
                  options={
                      'outputBounds': (extent['xmin'], extent['ymin'],
                                       extent['xmax'], extent['ymax']),
                      'srcNodata':
                      nodata
                  })
Esempio n. 4
0
 def __buildvrt(archives, vrtfile, pattern, vsi, extent, nodata=None, srs=None):
     locals = [vsi + x for x in dissolve([finder(x, [pattern]) for x in archives])]
     if nodata is None:
         with Raster(locals[0]) as ras:
             nodata = ras.nodata
     opts = {'outputBounds': (extent['xmin'], extent['ymin'],
                              extent['xmax'], extent['ymax']),
             'srcNodata': nodata}
     if srs is not None:
         opts['outputSRS'] = crsConvert(srs, 'wkt')
     gdalbuildvrt(src=locals, dst=vrtfile,
                  options=opts)
Esempio n. 5
0
def geocode(infile,
            outdir,
            t_srs=4326,
            tr=20,
            polarizations='all',
            shapefile=None,
            scaling='dB',
            geocoding_type='Range-Doppler',
            removeS1BorderNoise=True,
            removeS1BorderNoiseMethod='pyroSAR',
            removeS1ThermalNoise=True,
            offset=None,
            allow_RES_OSV=False,
            demName='SRTM 1Sec HGT',
            externalDEMFile=None,
            externalDEMNoDataValue=None,
            externalDEMApplyEGM=True,
            terrainFlattening=True,
            basename_extensions=None,
            test=False,
            export_extra=None,
            groupsize=1,
            cleanup=True,
            tmpdir=None,
            gpt_exceptions=None,
            gpt_args=None,
            returnWF=False,
            nodataValueAtSea=True,
            demResamplingMethod='BILINEAR_INTERPOLATION',
            imgResamplingMethod='BILINEAR_INTERPOLATION',
            alignToStandardGrid=False,
            standardGridOriginX=0,
            standardGridOriginY=0,
            speckleFilter=False,
            refarea='gamma0'):
    """
    wrapper function for geocoding SAR images using ESA SNAP

    Parameters
    ----------
    infile: str or ~pyroSAR.drivers.ID or list
        the SAR scene(s) to be processed; multiple scenes are treated as consecutive acquisitions, which will be
        mosaicked with SNAP's SliceAssembly operator
    outdir: str
        The directory to write the final files to.
    t_srs: int, str or osr.SpatialReference
        A target geographic reference system in WKT, EPSG, PROJ4 or OPENGIS format.
        See function :func:`spatialist.auxil.crsConvert()` for details.
        Default: `4326 <http://spatialreference.org/ref/epsg/4326/>`_.
    tr: int or float, optional
        The target resolution in meters. Default is 20
    polarizations: list or str
        The polarizations to be processed; can be a string for a single polarization, e.g. 'VV', or a list of several
        polarizations, e.g. ['VV', 'VH']. With the special value 'all' (default) all available polarizations are
        processed.
    shapefile: str or :py:class:`~spatialist.vector.Vector` or dict or None
        A vector geometry for subsetting the SAR scene to a test site.
    scaling: {'dB', 'db', 'linear'}, optional
        Should the output be in linear or decibel scaling? Default is 'dB'.
    geocoding_type: {'Range-Doppler', 'SAR simulation cross correlation'}, optional
        The type of geocoding applied; can be either 'Range-Doppler' (default) or 'SAR simulation cross correlation'
    removeS1BorderNoise: bool, optional
        Enables removal of S1 GRD border noise (default).
    removeS1BorderNoiseMethod: str
        the border noise removal method to be applied, See :func:`pyroSAR.S1.removeGRDBorderNoise` for details; one of the following:
         - 'ESA': the pure implementation as described by ESA
         - 'pyroSAR': the ESA method plus the custom pyroSAR refinement
    removeS1ThermalNoise: bool, optional
        Enables removal of S1 thermal noise (default).
    offset: tuple, optional
        A tuple defining offsets for left, right, top and bottom in pixels, e.g. (100, 100, 0, 0); this variable is
        overridden if a shapefile is defined. Default is None.
    allow_RES_OSV: bool
        (only applies to Sentinel-1) Also allow the less accurate RES orbit files to be used?
        The function first tries to download a POE file for the scene.
        If this fails and RES files are allowed, it will download the RES file.
        The selected OSV type is written to the workflow XML file.
        Processing is aborted if the correction fails (Apply-Orbit-File parameter continueOnFail set to false).
    demName: str
        the name of the auto-download DEM. Default is 'SRTM 1Sec HGT'. Is ignored when `externalDEMFile` is not None.
    externalDEMFile: str or None, optional
        The absolute path to an external DEM file. Default is None. Overrides `demName`.
    externalDEMNoDataValue: int, float or None, optional
        The no data value of the external DEM. If not specified (default) the function will try to read it from the
        specified external DEM.
    externalDEMApplyEGM: bool, optional
        Apply Earth Gravitational Model to external DEM? Default is True.
    terrainFlattening: bool
        apply topographic normalization on the data?
    basename_extensions: list of str or None
        names of additional parameters to append to the basename, e.g. ['orbitNumber_rel']
    test: bool, optional
        If set to True the workflow xml file is only written and not executed. Default is False.
    export_extra: list or None
        a list of image file IDs to be exported to outdir. The following IDs are currently supported:
         - incidenceAngleFromEllipsoid
         - localIncidenceAngle
         - projectedLocalIncidenceAngle
         - DEM
         - layoverShadowMask
         - scatteringArea
    groupsize: int
        the number of workers executed together in one gpt call
    cleanup: bool
        should all files written to the temporary directory during function execution be deleted after processing?
    tmpdir: str or None
        path of custom temporary directory, useful to separate output folder and temp folder. If `None`, the `outdir`
        location will be used. The created subdirectory will be deleted after processing.
    gpt_exceptions: dict or None
        a dictionary to override the configured GPT executable for certain operators;
        each (sub-)workflow containing this operator will be executed with the define executable;
        
         - e.g. ``{'Terrain-Flattening': '/home/user/snap/bin/gpt'}``
    gpt_args: list or None
        a list of additional arguments to be passed to the gpt call
        
        - e.g. ``['-x', '-c', '2048M']`` for increased tile cache size and intermediate clearing
    returnWF: bool
        return the full name of the written workflow XML file?
    nodataValueAtSea: bool
        mask pixels acquired over sea? The sea mask depends on the selected DEM.
    demResamplingMethod: str
        one of the following:
         - 'NEAREST_NEIGHBOUR'
         - 'BILINEAR_INTERPOLATION'
         - 'CUBIC_CONVOLUTION'
         - 'BISINC_5_POINT_INTERPOLATION'
         - 'BISINC_11_POINT_INTERPOLATION'
         - 'BISINC_21_POINT_INTERPOLATION'
         - 'BICUBIC_INTERPOLATION'
    imgResamplingMethod: str
        the resampling method for geocoding the SAR image; the options are identical to demResamplingMethod
    speckleFilter: str
        one of the following:
         - 'Boxcar'
         - 'Median'
         - 'Frost'
         - 'Gamma Map'
         - 'Refined Lee'
         - 'Lee'
         - 'Lee Sigma'
    refarea: str or list
        'sigma0', 'gamma0' or a list of both
    alignToStandardGrid: bool
        align all processed images to a common grid?
    standardGridOriginX: int or float
        the x origin value for grid alignment
    standardGridOriginY: int or float
        the y origin value for grid alignment
    
    Returns
    -------
    str or None
        either the name of the workflow file if `returnWF == True` or None otherwise

    Note
    ----
    If only one polarization is selected and not extra products are defined the results are directly written to GeoTiff.
    Otherwise the results are first written to a folder containing ENVI files and then transformed to GeoTiff files
    (one for each polarization/extra product).
    If GeoTiff would directly be selected as output format for multiple polarizations then a multilayer GeoTiff
    is written by SNAP which is considered an unfavorable format
    
    
    .. figure:: figures/snap_geocode.png
        :scale: 25%
        :align: center
        
        Workflow diagram for function geocode for processing a Sentinel-1 Ground Range
        Detected (GRD) scene to radiometrically terrain corrected (RTC) backscatter.
        An additional Subset node might be inserted in case a vector geometry is provided.

    Examples
    --------
    geocode a Sentinel-1 scene and export the local incidence angle map with it

    >>> from pyroSAR.snap import geocode
    >>> filename = 'S1A_IW_GRDH_1SDV_20180829T170656_20180829T170721_023464_028DE0_F7BD.zip'
    >>> geocode(infile=filename, outdir='outdir', tr=20, scaling='dB',
    >>>         export_extra=['DEM', 'localIncidenceAngle'], t_srs=4326)

    See Also
    --------
    :class:`pyroSAR.drivers.ID`,
    :class:`spatialist.vector.Vector`,
    :func:`spatialist.auxil.crsConvert()`
    """

    if isinstance(infile, pyroSAR.ID):
        id = infile
    elif isinstance(infile, str):
        id = pyroSAR.identify(infile)
    elif isinstance(infile, list):
        ids = pyroSAR.identify_many(infile, verbose=False, sortkey='start')
        id = ids[0]
    else:
        raise TypeError("'infile' must be of type str, list or pyroSAR.ID")

    if id.is_processed(outdir):
        print('scene {} already processed'.format(id.outname_base()))
        return
    # print(os.path.basename(id.scene))
    if not os.path.isdir(outdir):
        os.makedirs(outdir)
    ############################################
    # general setup

    if id.sensor in ['ASAR', 'ERS1', 'ERS2']:
        formatName = 'ENVISAT'
    elif id.sensor in ['S1A', 'S1B']:
        if id.product == 'SLC':
            raise RuntimeError('Sentinel-1 SLC data is not supported yet')
        formatName = 'SENTINEL-1'
    else:
        raise RuntimeError('sensor not supported (yet)')

    # several options like resampling are modified globally for the whole workflow at the end of this function
    # this list gathers IDs of nodes for which this should not be done because they are configured individually
    resampling_exceptions = []
    ######################
    # print('- assessing polarization selection')
    if isinstance(polarizations, str):
        if polarizations == 'all':
            polarizations = id.polarizations
        else:
            if polarizations in id.polarizations:
                polarizations = [polarizations]
            else:
                raise RuntimeError(
                    'polarization {} does not exists in the source product'.
                    format(polarizations))
    elif isinstance(polarizations, list):
        polarizations = [x for x in polarizations if x in id.polarizations]
    else:
        raise RuntimeError('polarizations must be of type str or list')

    bandnames = dict()
    bandnames['int'] = ['Intensity_' + x for x in polarizations]
    bandnames['beta0'] = ['Beta0_' + x for x in polarizations]
    bandnames['gamma0'] = ['Gamma0_' + x for x in polarizations]
    bandnames['sigma0'] = ['Sigma0_' + x for x in polarizations]
    ############################################
    ############################################
    # parse base workflow
    # print('- parsing base workflow')
    workflow = parse_recipe('base')
    ############################################
    # Read node configuration
    # print('-- configuring Read Node')
    read = workflow['Read']
    read.parameters['file'] = id.scene
    read.parameters['formatName'] = formatName
    readers = [read.id]

    if isinstance(infile, list):
        for i in range(1, len(infile)):
            readn = parse_node('Read')
            readn.parameters['file'] = ids[i].scene
            readn.parameters['formatName'] = formatName
            workflow.insert_node(readn,
                                 before=read.id,
                                 resetSuccessorSource=False)
            readers.append(readn.id)
        sliceAssembly = parse_node('SliceAssembly')
        sliceAssembly.parameters['selectedPolarisations'] = polarizations
        workflow.insert_node(sliceAssembly, before=readers)
        read = sliceAssembly
    ############################################
    # Remove-GRD-Border-Noise node configuration
    # print('-- configuring Remove-GRD-Border-Noise Node')
    if id.sensor in ['S1A', 'S1B'] and removeS1BorderNoise:
        bn = parse_node('Remove-GRD-Border-Noise')
        workflow.insert_node(bn, before=read.id)
        bn.parameters['selectedPolarisations'] = polarizations
    ############################################
    # ThermalNoiseRemoval node configuration
    # print('-- configuring ThermalNoiseRemoval Node')
    if id.sensor in ['S1A', 'S1B'] and removeS1ThermalNoise:
        for reader in readers:
            tn = parse_node('ThermalNoiseRemoval')
            workflow.insert_node(tn, before=reader)
            tn.parameters['selectedPolarisations'] = polarizations
    ############################################
    # orbit file application node configuration
    # print('-- configuring Apply-Orbit-File Node')
    orbit_lookup = {
        'ENVISAT': 'DELFT Precise (ENVISAT, ERS1&2) (Auto Download)',
        'SENTINEL-1': 'Sentinel Precise (Auto Download)'
    }
    orbitType = orbit_lookup[formatName]
    if formatName == 'ENVISAT' and id.acquisition_mode == 'WSM':
        orbitType = 'DORIS Precise VOR (ENVISAT) (Auto Download)'

    if formatName == 'SENTINEL-1':
        match = id.getOSV(osvType='POE', returnMatch=True)
        if match is None and allow_RES_OSV:
            id.getOSV(osvType='RES')
            orbitType = 'Sentinel Restituted (Auto Download)'

    orb = workflow['Apply-Orbit-File']
    orb.parameters['orbitType'] = orbitType
    orb.parameters['continueOnFail'] = False
    ############################################
    # calibration node configuration
    # print('-- configuring Calibration Node')
    cal = workflow['Calibration']
    cal.parameters['selectedPolarisations'] = polarizations
    cal.parameters['sourceBands'] = bandnames['int']
    if isinstance(refarea, str):
        refarea = [refarea]
    if terrainFlattening:
        if 'gamma0' not in refarea:
            raise RuntimeError(
                'if terrain flattening is applied refarea must be gamma0')
        cal.parameters['outputBetaBand'] = True
        if 'sigma0' in refarea:
            cal.parameters['outputSigmaBand'] = True
    else:
        refarea_options = ['sigma0', 'gamma0']
        for opt in refarea:
            if opt not in refarea_options:
                message = '{0} must be one of the following:\n- {1}'
                raise ValueError(
                    message.format('refarea', '\n- '.join(refarea_options)))
            cal.parameters['output{}Band'.format(opt[:-1].capitalize())] = True
    last = cal.id
    ############################################
    # terrain flattening node configuration
    # print('-- configuring Terrain-Flattening Node')
    if terrainFlattening:
        tf = parse_node('Terrain-Flattening')
        workflow.insert_node(tf, before=last)
        if id.sensor in ['ERS1', 'ERS2'] or (id.sensor == 'ASAR'
                                             and id.acquisition_mode != 'APP'):
            tf.parameters['sourceBands'] = 'Beta0'
        else:
            tf.parameters['sourceBands'] = bandnames['beta0']
        if 'reGridMethod' in tf.parameters.keys():
            if externalDEMFile is None:
                tf.parameters['reGridMethod'] = True
            else:
                tf.parameters['reGridMethod'] = False
        last = tf.id
    ############################################
    # speckle filtering node configuration
    speckleFilter_options = [
        'Boxcar', 'Median', 'Frost', 'Gamma Map', 'Refined Lee', 'Lee',
        'Lee Sigma'
    ]

    if speckleFilter:
        message = '{0} must be one of the following:\n- {1}'
        if speckleFilter not in speckleFilter_options:
            raise ValueError(
                message.format('speckleFilter',
                               '\n- '.join(speckleFilter_options)))
        sf = parse_node('Speckle-Filter')
        workflow.insert_node(sf, before=last)
        sf.parameters['sourceBands'] = None
        sf.parameters['filter'] = speckleFilter
        last = sf.id
    ############################################
    # configuration of node sequence for specific geocoding approaches
    bands = dissolve([bandnames[opt] for opt in refarea])
    if geocoding_type == 'Range-Doppler':
        tc = parse_node('Terrain-Correction')
        workflow.insert_node(tc, before=last)
        tc.parameters['sourceBands'] = bands
    elif geocoding_type == 'SAR simulation cross correlation':
        sarsim = parse_node('SAR-Simulation')
        workflow.insert_node(sarsim, before=last)
        sarsim.parameters['sourceBands'] = bands

        workflow.insert_node(parse_node('Cross-Correlation'),
                             before='SAR-Simulation')

        tc = parse_node('SARSim-Terrain-Correction')
        workflow.insert_node(tc, before='Cross-Correlation')
    else:
        raise RuntimeError('geocode_type not recognized')

    tc.parameters['alignToStandardGrid'] = alignToStandardGrid
    tc.parameters['standardGridOriginX'] = standardGridOriginX
    tc.parameters['standardGridOriginY'] = standardGridOriginY
    ############################################
    # Multilook node configuration

    try:
        image_geometry = id.meta['image_geometry']
        incidence = id.meta['incidence']
    except KeyError:
        raise RuntimeError(
            'This function does not yet support sensor {}'.format(id.sensor))

    rlks, azlks = multilook_factors(sp_rg=id.spacing[0],
                                    sp_az=id.spacing[1],
                                    tr_rg=tr,
                                    tr_az=tr,
                                    geometry=image_geometry,
                                    incidence=incidence)

    if azlks > 1 or rlks > 1:
        workflow.insert_node(parse_node('Multilook'), before='Calibration')
        ml = workflow['Multilook']
        ml.parameters['nAzLooks'] = azlks
        ml.parameters['nRgLooks'] = rlks
        ml.parameters['sourceBands'] = None
    ############################################
    # merge sigma0 and gamma0 bands to pass them to Terrain-Correction
    if len(refarea) > 1 and terrainFlattening:
        bm = parse_node('BandMerge')
        workflow.insert_node(bm, before=[tf.source, tf.id])
        sources = bm.source
        gamma_index = sources.index('Terrain-Flattening')
        sigma_index = abs(gamma_index - 1)
        s1_id = os.path.basename(os.path.splitext(id.scene)[0])
        bands_long = []
        for band in bands:
            comp = [band + '::']
            if shapefile is not None:
                comp.append('Subset_')
            comp.append(s1_id)
            if band.startswith('Gamma'):
                comp.append('_' + workflow.suffix(stop=sources[gamma_index]))
            else:
                comp.append('_' + workflow.suffix(stop=sources[sigma_index]))
            bands_long.append(''.join(comp))
        bm.parameters['sourceBands'] = bands_long
        bm.parameters['geographicError'] = 0.0
        ############################################
    # specify spatial resolution and coordinate reference system of the output dataset
    # print('-- configuring CRS')
    tc.parameters['pixelSpacingInMeter'] = tr

    try:
        t_srs = crsConvert(t_srs, 'epsg')
    except TypeError:
        raise RuntimeError("format of parameter 't_srs' not recognized")

    # the EPSG code 4326 is not supported by SNAP and thus the WKT string has to be defined;
    # in all other cases defining EPSG:{code} will do
    if t_srs == 4326:
        t_srs = 'GEOGCS["WGS84(DD)",' \
                'DATUM["WGS84",' \
                'SPHEROID["WGS84", 6378137.0, 298.257223563]],' \
                'PRIMEM["Greenwich", 0.0],' \
                'UNIT["degree", 0.017453292519943295],' \
                'AXIS["Geodetic longitude", EAST],' \
                'AXIS["Geodetic latitude", NORTH]]'
    else:
        t_srs = 'EPSG:{}'.format(t_srs)

    tc.parameters['mapProjection'] = t_srs
    ############################################
    # (optionally) add node for conversion from linear to db scaling
    # print('-- configuring LinearToFromdB Node')
    if scaling not in ['dB', 'db', 'linear']:
        raise RuntimeError(
            'scaling must be  a string of either "dB", "db" or "linear"')

    if scaling in ['dB', 'db']:
        lin2db = parse_node('LinearToFromdB')
        workflow.insert_node(lin2db, before=tc.id)
        lin2db.parameters['sourceBands'] = bands

    ############################################
    # (optionally) add subset node and add bounding box coordinates of defined shapefile
    # print('-- configuring Subset Node')
    if shapefile:
        # print('--- read')
        if isinstance(shapefile, dict):
            ext = shapefile
        else:
            if isinstance(shapefile, Vector):
                shp = shapefile.clone()
            elif isinstance(shapefile, str):
                shp = Vector(shapefile)
            else:
                raise TypeError(
                    "argument 'shapefile' must be either a dictionary, a Vector object or a string."
                )
            # reproject the geometry to WGS 84 latlon
            shp.reproject(4326)
            ext = shp.extent
            shp.close()
        # add an extra buffer of 0.01 degrees
        buffer = 0.01
        ext['xmin'] -= buffer
        ext['ymin'] -= buffer
        ext['xmax'] += buffer
        ext['ymax'] += buffer
        # print('--- create bbox')
        with bbox(ext, 4326) as bounds:
            # print('--- intersect')
            inter = intersect(id.bbox(), bounds)
            if not inter:
                raise RuntimeError(
                    'no bounding box intersection between shapefile and scene')
            inter.close()
            wkt = bounds.convert2wkt()[0]

        subset = parse_node('Subset')
        workflow.insert_node(subset, before=read.id)
        subset.parameters['region'] = [0, 0, id.samples, id.lines]
        subset.parameters['geoRegion'] = wkt
        subset.parameters['copyMetadata'] = True
    ############################################
    # (optionally) configure subset node for pixel offsets
    if offset and not shapefile:
        subset = parse_node('Subset')
        workflow.insert_node(subset, before=read.id)

        # left, right, top and bottom offset in pixels
        l, r, t, b = offset

        subset_values = [l, t, id.samples - l - r, id.lines - t - b]
        subset.parameters['region'] = subset_values
        subset.parameters['geoRegion'] = ''
    ############################################
    # parametrize write node
    # print('-- configuring Write Node')
    # create a suffix for the output file to identify processing steps performed in the workflow
    suffix = workflow.suffix()
    if tmpdir is None:
        tmpdir = outdir
    basename = os.path.join(tmpdir, id.outname_base(basename_extensions))
    outname = basename + '_' + suffix

    write = workflow['Write']
    write.parameters['file'] = outname
    write.parameters['formatName'] = 'ENVI'
    ############################################
    ############################################
    if export_extra is not None:
        tc_options = [
            'incidenceAngleFromEllipsoid', 'localIncidenceAngle',
            'projectedLocalIncidenceAngle', 'DEM'
        ]
        tc_write = None
        tc_selection = []
        for item in export_extra:
            if item in tc_options:
                if tc_write is None:
                    tc_write = parse_node('Write')
                    workflow.insert_node(tc_write,
                                         before=tc.id,
                                         resetSuccessorSource=False)
                    tc_write.parameters['file'] = outname
                    tc_write.parameters['formatName'] = 'ENVI'
                key = 'save{}{}'.format(item[0].upper(), item[1:])
                tc.parameters[key] = True
                tc_selection.append(item)
            elif item == 'layoverShadowMask':
                sarsim = parse_node('SAR-Simulation')
                sarsim.parameters['saveLayoverShadowMask'] = True
                workflow.insert_node(sarsim,
                                     after=tc.id,
                                     resetSuccessorSource=False)
                sarsim_select = parse_node('BandSelect')
                sarsim_select.parameters['sourceBands'] = 'layover_shadow_mask'
                workflow.insert_node(sarsim_select,
                                     before=sarsim.id,
                                     resetSuccessorSource=False)

                sarsim_tc = parse_node('Terrain-Correction')
                workflow.insert_node(sarsim_tc, before=sarsim_select.id)
                sarsim_tc.parameters[
                    'alignToStandardGrid'] = alignToStandardGrid
                sarsim_tc.parameters[
                    'standardGridOriginX'] = standardGridOriginX
                sarsim_tc.parameters[
                    'standardGridOriginY'] = standardGridOriginY
                sarsim_tc.parameters[
                    'imgResamplingMethod'] = 'NEAREST_NEIGHBOUR'
                resampling_exceptions.append(sarsim_tc.id)

                sarsim_write = parse_node('Write')
                sarsim_write.parameters['file'] = outname
                sarsim_write.parameters['formatName'] = 'ENVI'
                workflow.insert_node(sarsim_write,
                                     before=sarsim_tc.id,
                                     resetSuccessorSource=False)
            elif item == 'scatteringArea':
                area_select = parse_node('BandSelect')
                workflow.insert_node(area_select,
                                     before=tf.source,
                                     resetSuccessorSource=False)
                area_select.parameters['sourceBands'] = bandnames['beta0']

                area_merge1 = parse_node('BandMerge')
                workflow.insert_node(area_merge1,
                                     before=[tf.id, area_select.id],
                                     resetSuccessorSource=False)

                math = parse_node('BandMaths')
                math.element.attrib[
                    'class'] = '"com.bc.ceres.binding.dom.XppDomElement"'
                workflow.insert_node(math,
                                     before=area_merge1.id,
                                     resetSuccessorSource=False)

                # math = parse_node('BandMaths')
                # workflow.insert_node(math, before=[tf.id, area_select.id], resetSuccessorSource=False)
                math.parameters.clear_variables()
                exp = math.parameters['targetBands'][0]
                exp['name'] = 'scatteringArea_VV'
                exp['type'] = 'float32'
                exp['expression'] = 'Beta0_VV / Gamma0_VV'
                exp['noDataValue'] = 0.0

                area_merge2 = parse_node('BandMerge')
                workflow.insert_node(area_merge2,
                                     before=[tf.id, math.id],
                                     resetSuccessorSource=False)
                tc.source = area_merge2.id

                # modify Terrain-Correction source bands
                tc_bands = tc.parameters['sourceBands'] + ',scatteringArea_VV'
                tc.parameters['sourceBands'] = tc_bands

                # add scattering Area to list of band directly written from Terrain-Correction
                tc_selection.append('scatteringArea_VV')
            else:
                raise RuntimeError(
                    "ID '{}' not valid for argument 'export_extra'".format(
                        item))
        if len(tc_selection) > 0:
            tc_select = parse_node('BandSelect')
            workflow.insert_node(tc_select, after=tc_write.id)
            tc_select.parameters['sourceBands'] = tc_selection
    ############################################
    ############################################
    # select DEM type
    # print('-- configuring DEM')
    dempar = {
        'externalDEMFile': externalDEMFile,
        'externalDEMApplyEGM': externalDEMApplyEGM
    }
    if externalDEMFile is not None:
        if os.path.isfile(externalDEMFile):
            if externalDEMNoDataValue is None:
                with Raster(externalDEMFile) as dem:
                    dempar['externalDEMNoDataValue'] = dem.nodata
                if dempar['externalDEMNoDataValue'] is None:
                    raise RuntimeError(
                        'Cannot read NoData value from DEM file. '
                        'Please specify externalDEMNoDataValue')
            else:
                dempar['externalDEMNoDataValue'] = externalDEMNoDataValue
            dempar['reGridMethod'] = False
        else:
            raise RuntimeError('specified externalDEMFile does not exist')
        dempar['demName'] = 'External DEM'
    else:
        dempar['demName'] = demName
        dempar['externalDEMFile'] = None
        dempar['externalDEMNoDataValue'] = 0

    for key, value in dempar.items():
        workflow.set_par(key, value)

    # download the EGM lookup table if necessary
    if dempar['externalDEMApplyEGM']:
        get_egm96_lookup()
    ############################################
    ############################################
    # configure the resampling methods

    options = [
        'NEAREST_NEIGHBOUR', 'BILINEAR_INTERPOLATION', 'CUBIC_CONVOLUTION',
        'BISINC_5_POINT_INTERPOLATION', 'BISINC_11_POINT_INTERPOLATION',
        'BISINC_21_POINT_INTERPOLATION', 'BICUBIC_INTERPOLATION'
    ]

    message = '{0} must be one of the following:\n- {1}'
    if demResamplingMethod not in options:
        raise ValueError(
            message.format('demResamplingMethod', '\n- '.join(options)))
    if imgResamplingMethod not in options:
        raise ValueError(
            message.format('imgResamplingMethod', '\n- '.join(options)))

    workflow.set_par('demResamplingMethod', demResamplingMethod)
    workflow.set_par('imgResamplingMethod',
                     imgResamplingMethod,
                     exceptions=resampling_exceptions)
    ############################################
    ############################################
    # additional parameter settings applied to the whole workflow

    workflow.set_par('nodataValueAtSea', nodataValueAtSea)
    ############################################
    ############################################
    # write workflow to file and optionally execute it
    # print('- writing workflow to file')

    wf_name = outname.replace(tmpdir, outdir) + '_proc.xml'
    workflow.write(wf_name)

    # execute the newly written workflow
    if not test:
        try:
            groups = groupbyWorkers(wf_name, groupsize)
            gpt(wf_name,
                groups=groups,
                cleanup=cleanup,
                gpt_exceptions=gpt_exceptions,
                gpt_args=gpt_args,
                removeS1BorderNoiseMethod=removeS1BorderNoiseMethod,
                outdir=outdir)
        except RuntimeError as e:
            print(str(e))
            with open(wf_name.replace('_proc.xml', '_error.log'), 'w') as log:
                log.write(str(e))
    if returnWF:
        return wf_name
Esempio n. 6
0
def getAuxdata(datasets, scenes):
    def getOrbitContentVersions(contentVersion):
        content = contentVersion.read().split('\n')
        items = [
            re.split(r'\s*=\s*', x.strip('\r')) for x in content
            if re.search('^[0-9]{4}', x)
        ]
        return dict(items)

    auxDataPath = os.path.join(expanduser("~"), '.snap/auxdata')

    scenes = [
        identify(scene) if isinstance(scene, str) else scene
        for scene in scenes
    ]
    sensors = list(set([scene.sensor for scene in scenes]))
    for dataset in datasets:
        if dataset == 'SRTM 1Sec HGT':
            files = [
                x.replace('hgt', 'SRTMGL1.hgt.zip') for x in list(
                    set(dissolve([scene.getHGT() for scene in scenes])))
            ]
            for file in files:
                infile = os.path.join(
                    'https://step.esa.int/auxdata/dem/SRTMGL1', file)
                outfile = os.path.join(auxDataPath, 'dem/SRTM 1Sec HGT', file)
                if not os.path.isfile(outfile):
                    print(infile)
                    try:
                        input = urlopen(infile)
                    except HTTPError:
                        print('-> not available')
                        continue
                    with open(outfile, 'wb') as output:
                        output.write(input.read())
                    input.close()
        elif dataset == 'POEORB':
            for sensor in sensors:
                if re.search('S1[AB]', sensor):

                    dates = [(scene.start[:4], scene.start[4:6])
                             for scene in scenes]
                    years = list(set([x[0] for x in dates]))

                    remote_contentVersion = urlopen(
                        'https://step.esa.int/auxdata/orbits/Sentinel-1/POEORB/remote_contentVersion.txt'
                    )
                    versions_remote = getOrbitContentVersions(
                        remote_contentVersion)

                    for year in years:
                        dir_orb = os.path.join(auxDataPath,
                                               'Orbits/Sentinel-1/POEORB',
                                               year)

                        if not os.path.isdir(dir_orb):
                            os.makedirs(dir_orb)
                        contentVersionFile = os.path.join(
                            dir_orb, 'contentVersion.txt')

                        if os.path.isfile(contentVersionFile):
                            contentVersion = open(contentVersionFile, 'r+')
                            versions_local = getOrbitContentVersions(
                                contentVersion)
                        else:
                            contentVersion = open(contentVersionFile, 'w')
                            versions_local = {}

                        combine = dict(
                            set(versions_local.items())
                            & set(versions_remote.items()))

                        dates_select = [x for x in dates if x[0] == year]
                        months = list(set([x[1] for x in dates_select]))

                        orb_ids = sorted([
                            x for x in [
                                '{}-{}.zip'.format(year, month)
                                for month in months
                            ] if not x in combine
                        ])

                        if len(orb_ids) > 0:
                            contentVersion.write('#\n#{}\n'.format(
                                strftime('%a %b %d %H:%M:%S %Z %Y', gmtime())))

                            for orb_id in orb_ids:
                                orb_remote = urlopen(
                                    'https://step.esa.int/auxdata/orbits/Sentinel-1/POEORB/{}'
                                    .format(orb_id))
                                orb_remote_stream = zf.ZipFile(
                                    StringIO(orb_remote.read()), 'r')
                                orb_remote.close()

                                targets = [
                                    x for x in orb_remote_stream.namelist()
                                    if not os.path.isfile(
                                        os.path.join(dir_orb, x))
                                ]
                                orb_remote_stream.extractall(dir_orb, targets)
                                orb_remote_stream.close()

                                versions_local[orb_id] = versions_remote[
                                    orb_id]

                                for key, val in versions_local.iteritems():
                                    contentVersion.write('{}={}\n'.format(
                                        key, val))

                        contentVersion.close()
                    remote_contentVersion.close()
                else:
                    print('not implemented yet')
        elif dataset == 'Delft Precise Orbits':
            path_server = 'dutlru2.lr.tudelft.nl'
            subdirs = {
                'ASAR:': 'ODR.ENVISAT1/eigen-cg03c',
                'ERS1': 'ODR.ERS-1/dgm-e04',
                'ERS2': 'ODR.ERS-2/dgm-e04'
            }
            ftp = FTP(path_server)
            ftp.login()
            for sensor in sensors:
                if sensor in subdirs.keys():
                    path_target = os.path.join('pub/orbits', subdirs[sensor])
                    path_local = os.path.join(auxDataPath,
                                              'Orbits/Delft Precise Orbits',
                                              subdirs[sensor])
                    ftp.cwd(path_target)
                    for item in ftp.nlst():
                        ftp.retrbinary(
                            'RETR ' + item,
                            open(os.path.join(path_local, item), 'wb').write)
            ftp.quit()
        else:
            print('not implemented yet')
Esempio n. 7
0
def process(cmd,
            outdir=None,
            logfile=None,
            logpath=None,
            inlist=None,
            void=True,
            shellscript=None):
    """
    wrapper function to execute GAMMA commands via module :mod:`subprocess`
    
    Parameters
    ----------
    cmd: list
        the command line arguments
    outdir: str
        the directory to execute the command in
    logfile: str
        a file to write the command log to; overrides parameter logpath
    logpath: str
        a directory to write logfiles to; the file will be named {GAMMA command}.log, e.g. gc_map.log;
        is overridden by parameter logfile
    inlist: list
        a list of values, which is passed as interactive inputs via stdin
    void: bool
        return the stdout and stderr messages?
    shellscript: str
        a file to write the Gamma commands to in shell format
    
    Returns
    -------
    tuple of str or None
        the stdout and stderr messages if void is False, otherwise None
    """
    if logfile is not None:
        log = logfile
    else:
        log = os.path.join(logpath,
                           os.path.basename(cmd[0]) +
                           '.log') if logpath else None
    if shellscript is not None:
        if not os.path.isfile(shellscript):
            with open(shellscript, 'w') as init:
                pass
        line = ' '.join([str(x) for x in dissolve(cmd)])
        if inlist is not None:
            line += ' <<< $"{}"'.format('\n'.join([str(x)
                                                   for x in inlist]) + '\n')
        with open(shellscript, 'r+') as sh:
            if outdir is not None:
                content = sh.read()
                sh.seek(0)
                is_new = re.search(
                    'this script was created automatically by pyroSAR',
                    content) is None
                if is_new:
                    ts = datetime.now().strftime('%a %b %d %H:%M:%S %Y')
                    sh.write(
                        '# this script was created automatically by pyroSAR on {}\n\n'
                        .format(ts))
                    sh.write('export base={}\n\n'.format(outdir))
                    sh.write(content)
                line = line.replace(outdir, '$base')
            sh.seek(0, 2)  # set pointer to the end of the file
            sh.write(line + '\n\n')

    # create an environment containing the locations of all GAMMA submodules to be passed ot the subprocess calls
    gammaenv = {'GAMMA_HOME': ExamineGamma().home}
    for module in ['DIFF', 'DISP', 'IPTA', 'ISP', 'LAT']:
        loc = os.path.join(gammaenv['GAMMA_HOME'], module)
        if os.path.isdir(loc):
            gammaenv[module + '_HOME'] = loc

    # execute the command
    out, err = run(cmd,
                   outdir=outdir,
                   logfile=log,
                   inlist=inlist,
                   void=False,
                   errorpass=True,
                   env=gammaenv)
    gammaErrorHandler(out, err)
    if not void:
        return out, err
Esempio n. 8
0
def process(cmd,
            outdir=None,
            logfile=None,
            logpath=None,
            inlist=None,
            void=True,
            shellscript=None):
    """
    wrapper function to execute GAMMA commands via module :mod:`subprocess`
    
    Parameters
    ----------
    cmd: list
        the command line arguments
    outdir: str
        the directory to execute the command in
    logfile: str
        a file to write the command log to; overrides parameter logpath
    logpath: str
        a directory to write logfiles to; the file will be named {GAMMA command}.log, e.g. gc_map.log;
        is overridden by parameter logfile
    inlist: list
        a list of values, which is passed as interactive inputs via stdin
    void: bool
        return the stdout and stderr messages?
    shellscript: str
        a file to write the Gamma commands to in shell format
    
    Returns
    -------
    tuple of str or None
        the stdout and stderr messages if void is False, otherwise None
    """
    if logfile is not None:
        log = logfile
    else:
        log = os.path.join(logpath,
                           os.path.basename(cmd[0]) +
                           '.log') if logpath else None
    if shellscript is not None:
        line = ' '.join([str(x) for x in dissolve(cmd)])
        if inlist is not None:
            line += ' <<< $"{}"'.format('\n'.join([str(x)
                                                   for x in inlist]) + '\n')
        with open(shellscript, 'a+') as sh:
            if outdir is not None:
                first = sh.read(1)
                if not first:
                    ts = datetime.now().strftime('%a %b %d %H:%M:%S %Y')
                    sh.write(
                        '# this script was created automatically by pyroSAR on {}\n\n'
                        .format(ts))
                    sh.write('export base={}\n\n'.format(outdir))
                line = line.replace(outdir, '$base')
            sh.write(line + '\n\n')
    out, err = run(cmd,
                   outdir=outdir,
                   logfile=log,
                   inlist=inlist,
                   void=False,
                   errorpass=True)
    gammaErrorHandler(out, err)
    if not void:
        return out, err