def dropSecondarysWithDifferentNumberOfBursts(secondaryList, reference, swathList):
    '''Drop secondary acquisitions that have different number of bursts
    than the reference acquisition.
    '''
    print('checking the number of bursts in coreg_secondarys against the one in reference')
    secondaryList2Drop = []
    for swath in swathList:
        prodReference = ut.loadProduct(os.path.join(reference, 'IW{0}.xml'.format(swath)))
        numBursts = len(prodReference.bursts)

        for secondary in secondaryList:
            prodSecondary = ut.loadProduct(os.path.join(secondary, 'IW{0}.xml'.format(swath)))
            if len(prodSecondary.bursts) != numBursts:
                msg = 'WARNING: {} has different number of bursts ({}) than the reference {} ({}) for swath {}'.format(
                    os.path.basename(secondary), len(prodSecondary.bursts),
                    os.path.basename(reference), numBursts, swath)
                msg += ' --> exclude it for common region calculation'
                print(msg)
                secondaryList2Drop.append(secondary)

    secondaryList2Drop = list(sorted(set(secondaryList2Drop)))
    if len(secondaryList2Drop) == 0:
        print('all secondary images have the same number of bursts as the reference')

    secondaryList = list(sorted(set(secondaryList) - set(secondaryList2Drop)))

    return secondaryList
Beispiel #2
0
def main(iargs=None):

    inps = cmdLineParse(iargs)

    swathList = ut.getSwathList(inps.master)

    demImage = isceobj.createDemImage()
    demImage.load(inps.dem + '.xml')

    boxes = []
    inputs = []

    for swath in swathList:
        master =  ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))
    
        ###Check if geometry directory already exists.
        dirname = os.path.join(inps.geom_masterDir, 'IW{0}'.format(swath))
        os.makedirs(dirname, exist_ok=True)

        for ind in range(master.numberOfBursts):
            inputs.append((dirname, demImage, master, ind))

    pool = mp.Pool(mp.cpu_count())
    results = pool.map(call_topo, inputs)
    pool.close()

    for bbox in results:
        boxes.append(bbox)

    boxes = np.array(boxes)
    bbox = [np.min(boxes[:,0]), np.max(boxes[:,1]), np.min(boxes[:,2]), np.max(boxes[:,3])]
    print ('bbox : ',bbox)
def main(iargs=None):
    '''extract common valid overlap region for the stack.
    '''
    inps=cmdLineParse(iargs)

    stackDir = os.path.join(os.path.dirname(inps.master),'stack')
    if not os.path.exists(stackDir):
        print('creating ', stackDir)
        os.makedirs(stackDir)
    else:
        print(stackDir , ' already exists.')
        print('Replacing master with existing stack.')
        inps.master = stackDir
        print('updating the valid overlap region of:')
        print(stackDir)

    masterSwathList = ut.getSwathList(inps.master)
    slaveList = glob.glob(os.path.join(inps.slave,'2*'))
    slaveSwathList = ut.getSwathList(slaveList[0]) # assuming all slaves have the same swaths
    swathList = list(sorted(set(masterSwathList+slaveSwathList)))

    for swath in swathList:
        print('******************')
        print('swath: ', swath)
        ####Load relevant products
        topMaster = ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))
        #print('master.firstValidLine: ', topMaster.bursts[4].firstValidLine)
        for slave in slaveList:
            topMaster = updateValidRegion(topMaster, slave, swath)

        print('writing ', os.path.join(stackDir , 'IW{0}.xml'.format(swath)))
        ut.saveProduct(topMaster, os.path.join(stackDir , 'IW{0}.xml'.format(swath)))
        os.makedirs(os.path.join(stackDir ,'IW{0}'.format(swath)), exist_ok=True)
def main(iargs=None):
    '''extract common valid overlap region for the stack.
    '''
    inps=cmdLineParse(iargs)

    stackDir = os.path.join(os.path.dirname(inps.reference),'stack')
    if not os.path.exists(stackDir):
        print('creating ', stackDir)
        os.makedirs(stackDir)
    elif len(glob.glob(os.path.join(stackDir, '*.xml'))) > 0:
        print(stackDir , ' already exists.')
        print('Replacing reference with existing stack.')
        inps.reference = stackDir
        print('updating the valid overlap region of:')
        print(stackDir)

    referenceSwathList = ut.getSwathList(inps.reference)
    secondaryList = glob.glob(os.path.join(inps.secondary,'2*'))
    secondarySwathList = ut.getSwathList(secondaryList[0]) # assuming all secondarys have the same swaths
    swathList = list(sorted(set(referenceSwathList+secondarySwathList)))
    # discard secondarys with different number of bursts than the reference
    secondaryList = dropSecondarysWithDifferentNumberOfBursts(secondaryList, inps.reference, swathList)

    for swath in swathList:
        print('******************')
        print('swath: ', swath)
        ####Load relevant products
        topReference = ut.loadProduct(os.path.join(inps.reference , 'IW{0}.xml'.format(swath)))
        #print('reference.firstValidLine: ', topReference.bursts[4].firstValidLine)
        for secondary in secondaryList:
            topReference = updateValidRegion(topReference, secondary, swath)

        print('writing ', os.path.join(stackDir , 'IW{0}.xml'.format(swath)))
        ut.saveProduct(topReference, os.path.join(stackDir , 'IW{0}.xml'.format(swath)))
        os.makedirs(os.path.join(stackDir ,'IW{0}'.format(swath)), exist_ok=True)
Beispiel #5
0
def main(iargs=None):
    '''
    adjust valid samples by considering number of looks
    '''
    inps = cmdLineParse(iargs)


    swathList = sorted(ut.getSwathList(inps.input))

    frames=[]
    for swath in swathList:
        frame = ut.loadProduct( os.path.join(inps.input , 'IW{0}.xml'.format(swath)))
        minBurst = frame.bursts[0].burstNumber
        maxBurst = frame.bursts[-1].burstNumber

        if minBurst==maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue

        frames.append(frame)


    if inps.nrlks != 1 or inps.nalks != 1:
        print('updating swath xml')
        box = mergeBox(frames)
        #adjust valid with looks, 'frames' ARE CHANGED AFTER RUNNING THIS
        #here numberRangeLooks, instead of numberRangeLooks0, is used, since we need to do next step multilooking after unwrapping. same for numberAzimuthLooks.
        (burstValidBox, burstValidBox2, message) = adjustValidWithLooks(frames, box, inps.nalks, inps.nrlks, edge=0, avalid='strict', rvalid='strict')
    else:
        print('number of range and azimuth looks are all equal to 1, no need to update swath xml')

    for swath in swathList:
        print('writing ', os.path.join(inps.output , 'IW{0}.xml'.format(swath)))
        os.makedirs(os.path.join(inps.output, 'IW{0}'.format(swath)), exist_ok=True)
        ut.saveProduct(frames[swath-1], os.path.join(inps.output , 'IW{0}.xml'.format(swath)))
Beispiel #6
0
def extractInfo(xmlName, inps):
    '''
    Extract required information from pickle file.
    '''
    from isceobj.Planet.Planet import Planet
    from isceobj.Util.geo.ellipsoid import Ellipsoid

    frame = ut.loadProduct(xmlName)

    burst = frame.bursts[0]
    planet = Planet(pname='Earth')
    elp = Ellipsoid(planet.ellipsoid.a, planet.ellipsoid.e2, 'WGS84')

    data = {}
    data['wavelength'] = burst.radarWavelength

    tstart = frame.bursts[0].sensingStart
    tend   = frame.bursts[-1].sensingStop
    #tmid = tstart + 0.5*(tend - tstart)
    tmid = tstart


    orbit = burst.orbit
    peg = orbit.interpolateOrbit(tmid, method='hermite')

    refElp = Planet(pname='Earth').ellipsoid
    llh = refElp.xyz_to_llh(peg.getPosition())
    hdg = orbit.getENUHeading(tmid)
    refElp.setSCH(llh[0], llh[1], hdg)

    earthRadius = refElp.pegRadCur

    altitude   = llh[2]


    #sv = burst.orbit.interpolateOrbit(tmid, method='hermite')
    #pos = sv.getPosition()
    #llh = elp.ECEF(pos[0], pos[1], pos[2]).llh()

    data['altitude'] = altitude  #llh.hgt

    #hdg = burst.orbit.getHeading()
    data['earthRadius'] = earthRadius  #elp.local_radius_of_curvature(llh.lat, hdg)
    
    #azspacing  = burst.azimuthTimeInterval * sv.getScalarVelocity()
    #azres = 20.0 

    #corrfile  = os.path.join(self._insar.mergedDirname, self._insar.coherenceFilename)
    rangeLooks = inps.rglooks
    azimuthLooks = inps.azlooks
    azfact = 0.8
    rngfact = 0.8

    corrLooks = rangeLooks * azimuthLooks/(azfact*rngfact)

    data['corrlooks'] = corrLooks  #inps.rglooks * inps.azlooks * azspacing / azres
    data['rglooks'] = inps.rglooks
    data['azlooks'] = inps.azlooks

    return data
def create_georectified_lat_lon(swathList, master, outdir, demZero):
    """ export geo rectified latitude and longitude """

    for swath in swathList:
        master = ut.loadProduct(os.path.join(master,
                                             'IW{0}.xml'.format(swath)))

        ###Check if geometry directory already exists.
        dirname = os.path.join(outdir, 'IW{0}'.format(swath))

        if os.path.isdir(dirname):
            print('Geometry directory {0} already exists.'.format(dirname))
        else:
            os.makedirs(dirname)

        ###For each burst
        for ind in range(master.numberOfBursts):
            burst = master.bursts[ind]

            latname = os.path.join(dirname, 'lat_%02d.rdr' % (ind + 1))
            lonname = os.path.join(dirname, 'lon_%02d.rdr' % (ind + 1))
            hgtname = os.path.join(dirname, 'hgt_%02d.rdr' % (ind + 1))
            losname = os.path.join(dirname, 'los_%02d.rdr' % (ind + 1))

            if not (os.path.exists(latname + '.xml')
                    or os.path.exists(lonname + '.xml')):

                #####Run Topo
                planet = Planet(pname='Earth')
                topo = createTopozero()
                topo.slantRangePixelSpacing = burst.rangePixelSize
                topo.prf = 1.0 / burst.azimuthTimeInterval
                topo.radarWavelength = burst.radarWavelength
                topo.orbit = burst.orbit
                topo.width = burst.numberOfSamples
                topo.length = burst.numberOfLines
                topo.wireInputPort(name='dem', object=demZero)
                topo.wireInputPort(name='planet', object=planet)
                topo.numberRangeLooks = 1
                topo.numberAzimuthLooks = 1
                topo.lookSide = -1
                topo.sensingStart = burst.sensingStart
                topo.rangeFirstSample = burst.startingRange
                topo.demInterpolationMethod = 'BIQUINTIC'
                topo.latFilename = latname
                topo.lonFilename = lonname
                topo.heightFilename = hgtname
                topo.losFilename = losname

                topo.topo()
    return
Beispiel #8
0
def main(iargs=None):
    '''
    Create subband burst SLCs.
    '''
    inps = cmdLineParse(iargs)
    swathList = ut.getSwathList(inps.directory)

    for swath in swathList:
        acquisition = ut.loadProduct(
            os.path.join(inps.directory, 'IW{0}.xml'.format(swath)))
        for burst in acquisition.bursts:

            print("processing swath {}, burst {}".format(
                swath, os.path.basename(burst.image.filename)))

            outname = burst.image.filename
            outnameLower = os.path.splitext(outname)[0] + '_lower.slc'
            outnameUpper = os.path.splitext(outname)[0] + '_upper.slc'
            if os.path.exists(outnameLower) and os.path.exists(outnameLower+'.vrt') and os.path.exists(outnameLower+'.xml') and \
               os.path.exists(outnameUpper) and os.path.exists(outnameUpper+'.vrt') and os.path.exists(outnameUpper+'.xml'):
                print('burst {} already processed, skip...'.format(
                    os.path.basename(burst.image.filename)))
                continue

            #subband filtering
            from Stack import ionParam
            from isceobj.Constants import SPEED_OF_LIGHT
            rangeSamplingRate = SPEED_OF_LIGHT / (2.0 * burst.rangePixelSize)

            ionParamObj = ionParam()
            ionParamObj.configure()
            outputfile = [outnameLower, outnameUpper]
            bw = [
                ionParamObj.rgBandwidthSub / rangeSamplingRate,
                ionParamObj.rgBandwidthSub / rangeSamplingRate
            ]
            bc = [
                -ionParamObj.rgBandwidthForSplit / 3.0 / rangeSamplingRate,
                ionParamObj.rgBandwidthForSplit / 3.0 / rangeSamplingRate
            ]
            rgRef = ionParamObj.rgRef
            subband(burst, 2, outputfile, bw, bc, rgRef, True)
Beispiel #9
0
def main(iargs=None):

    inps = cmdLineParse(iargs)

    swathList = ut.getSwathList(inps.reference)

    demImage = isceobj.createDemImage()
    demImage.load(inps.dem + '.xml')

    boxes = []
    inputs = []

    for swath in swathList:
        reference = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))

        ###Check if geometry directory already exists.
        dirname = os.path.join(inps.geom_referenceDir, 'IW{0}'.format(swath))
        os.makedirs(dirname, exist_ok=True)

        for ind in range(reference.numberOfBursts):
            inputs.append((dirname, demImage, reference, ind))

    # parallel processing
    print('running in parallel with {} processes'.format(inps.numProcess))
    pool = mp.Pool(inps.numProcess)
    results = pool.map(call_topo, inputs)
    pool.close()

    for bbox in results:
        boxes.append(bbox)

    boxes = np.array(boxes)
    bbox = [
        np.min(boxes[:, 0]),
        np.max(boxes[:, 1]),
        np.min(boxes[:, 2]),
        np.max(boxes[:, 3])
    ]
    print('bbox : ', bbox)
Beispiel #10
0
def extractIsceMetadata(xmlFile):

    master = ut.loadProduct(xmlFile)
    burst = master.bursts[0]
    burstEnd = master.bursts[-1]
    metadata = {}
    metadata['radarWavelength'] = burst.radarWavelength
    metadata['rangePixelSize'] = burst.rangePixelSize
    metadata['prf'] = burst.prf
    metadata['startUTC'] = burst.burstStartUTC
    metadata['stopUTC'] = burstEnd.burstStopUTC
    metadata['startingRange'] = burst.startingRange

    time_seconds = burst.burstStartUTC.hour * 3600.0 + burst.burstStartUTC.minute * 60.0 + burst.burstStartUTC.second

    metadata['CENTER_LINE_UTC'] = time_seconds
    Vs = np.linalg.norm(
        burst.orbit.interpolateOrbit(burst.sensingMid,
                                     method='hermite').getVelocity())
    metadata['satelliteSpeed'] = Vs
    metadata['azimuthTimeInterval'] = burst.azimuthTimeInterval
    metadata['azimuthPixelSize'] = Vs * burst.azimuthTimeInterval

    tstart = burst.sensingStart
    tend = burstEnd.sensingStop
    tmid = tstart + 0.5 * (tend - tstart)

    orbit = burst.orbit
    peg = orbit.interpolateOrbit(tmid, method='hermite')

    refElp = Planet(pname='Earth').ellipsoid
    llh = refElp.xyz_to_llh(peg.getPosition())
    hdg = orbit.getENUHeading(tmid)
    refElp.setSCH(llh[0], llh[1], hdg)

    metadata['earthRadius'] = refElp.pegRadCur

    metadata['altitude'] = llh[2]

    return metadata
def updateValidRegion(topReference, secondaryPath, swath):

    #secondarySwathList = ut.getSwathList(secondary)
    #swathList = list(sorted(set(referenceSwathList+secondarySwathList)))

    #for swath in swathList:
        #IWstr = 'IW{0}'.format(swath)
    ####Load relevant products
        #topReference = ut.loadProduct(os.path.join(inps.reference , 'IW{0}.xml'.format(swath)))

    print(secondaryPath)
    topCoreg = ut.loadProduct(os.path.join(secondaryPath , 'IW{0}.xml'.format(swath)))

    topIfg = ut.coregSwathSLCProduct()
    topIfg.configure()


    minReference = topReference.bursts[0].burstNumber
    maxReference = topReference.bursts[-1].burstNumber

    minSecondary = topCoreg.bursts[0].burstNumber
    maxSecondary = topCoreg.bursts[-1].burstNumber

    minBurst = max(minSecondary, minReference)
    maxBurst = min(maxSecondary, maxReference)
    print ('minSecondary,maxSecondary',minSecondary, maxSecondary)
    print ('minReference,maxReference',minReference, maxReference)
    print ('minBurst, maxBurst: ', minBurst, maxBurst)

    for ii in range(minBurst, maxBurst + 1):

            ####Process the top bursts
        reference = topReference.bursts[ii-minReference]
        secondary  = topCoreg.bursts[ii-minSecondary]
        ut.adjustCommonValidRegion(reference,secondary)
        #topReference.bursts[ii-minReference].firstValidLine = reference.firstValidLine

    return topReference
def updateValidRegion(topMaster, slavePath, swath):

    #slaveSwathList = ut.getSwathList(slave)
    #swathList = list(sorted(set(masterSwathList+slaveSwathList)))

    #for swath in swathList:
        #IWstr = 'IW{0}'.format(swath)
    ####Load relevant products
        #topMaster = ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))

    topCoreg = ut.loadProduct(os.path.join(slavePath , 'IW{0}.xml'.format(swath)))

    topIfg = ut.coregSwathSLCProduct()
    topIfg.configure()


    minMaster = topMaster.bursts[0].burstNumber
    maxMaster = topMaster.bursts[-1].burstNumber

    minSlave = topCoreg.bursts[0].burstNumber
    maxSlave = topCoreg.bursts[-1].burstNumber

    minBurst = max(minSlave, minMaster)
    maxBurst = min(maxSlave, maxMaster)
    print ('minSlave,maxSlave',minSlave, maxSlave)
    print ('minMaster,maxMaster',minMaster, maxMaster)
    print ('minBurst, maxBurst: ', minBurst, maxBurst)

    for ii in range(minBurst, maxBurst + 1):

            ####Process the top bursts
        master = topMaster.bursts[ii-minMaster]
        slave  = topCoreg.bursts[ii-minSlave]
        ut.adjustCommonValidRegion(master,slave)
        #topMaster.bursts[ii-minMaster].firstValidLine = master.firstValidLine

    return topMaster
Beispiel #13
0
def main(iargs=None):
    '''
    check overlap among all acquistions, only keep the bursts that in the common overlap,
    and then renumber the bursts.
    '''
    inps = cmdLineParse(iargs)

    referenceDir = inps.reference
    secondaryDir = sorted(glob.glob(os.path.join(inps.secondarys, '*')))

    acquistionDir = [referenceDir] + secondaryDir


    invalidSwath = []
    for i in [1, 2, 3]:
        for x in acquistionDir:
            if not (os.path.isdir(os.path.join(x, 'IW{}'.format(i))) and os.path.isfile(os.path.join(x, 'IW{}.xml'.format(i)))):
                invalidSwath.append(i)
                break

    if invalidSwath == [1, 2, 3]:
        raise Exception('there are no common swaths among the acquistions')
    else:
        validSwath = [i for i in [1, 2, 3] if i not in invalidSwath]
        print('valid swath from scanning acquistion directory: {}'.format(validSwath))


    invalidSwath2 = []
    for swath in validSwath:
        referenceSwath = ut.loadProduct(os.path.join(referenceDir, 'IW{0}.xml'.format(swath)))

        burstoffsetAll = []
        minBurstAll = []
        maxBurstAll = []
        secondarySwathAll = []
        for secondaryDirX in secondaryDir:
            secondarySwath = ut.loadProduct(os.path.join(secondaryDirX, 'IW{0}.xml'.format(swath)))

            secondarySwathAll.append(secondarySwath)

            burstoffset, minBurst, maxBurst = referenceSwath.getCommonBurstLimits(secondarySwath)
            burstoffsetAll.append(burstoffset)
            minBurstAll.append(minBurst)
            maxBurstAll.append(maxBurst)

        minBurst = max(minBurstAll)
        maxBurst = min(maxBurstAll)

        numBurst = maxBurst - minBurst



        if minBurst >= maxBurst:
            invalidSwath2.append(swath)
        else:
            #add reference
            swathAll = [referenceSwath] + secondarySwathAll
            burstoffsetAll = [0] + burstoffsetAll

            for dirx, swathx, burstoffsetx in zip(acquistionDir, swathAll, burstoffsetAll):

                swathTmp = createTOPSSwathSLCProduct()
                swathTmp.configure()

                #change reserved burst properties and remove non-overlap bursts
                for jj in range(len(swathx.bursts)):
                    ii = jj - burstoffsetx
                    #burstFileName = os.path.join(os.path.abspath(dirx), 'IW{}'.format(swath), os.path.basename(swathx.bursts[jj].image.filename))
                    burstFileName = os.path.join(os.path.abspath(dirx), 'IW{}'.format(swath), 'burst_%02d'%(jj+1) + '.slc')
                    if minBurst <= ii < maxBurst:
                        kk = ii - minBurst
                        #change burst properties
                        swathx.bursts[jj].burstNumber = kk + 1
                        swathx.bursts[jj].image.filename = os.path.join(os.path.dirname(swathx.bursts[jj].image.filename), 'burst_%02d'%(kk+1) + '.slc')
                        swathTmp.bursts.append(swathx.bursts[jj])
                    else:
                        #remove non-overlap bursts
                        #os.remove(burstFileName)
                        os.remove(burstFileName+'.vrt')
                        os.remove(burstFileName+'.xml')
                        #remove geometry files accordingly if provided
                        if dirx == referenceDir:
                            if inps.geom_reference is not None:
                                for fileType in ['hgt', 'incLocal', 'lat', 'lon', 'los', 'shadowMask']:
                                    geomFileName = os.path.join(os.path.abspath(inps.geom_reference), 'IW{}'.format(swath), fileType + '_%02d'%(jj+1) + '.rdr')
                                    os.remove(geomFileName)
                                    os.remove(geomFileName+'.vrt')
                                    os.remove(geomFileName+'.xml')


                #change reserved burst file names
                for jj in range(len(swathx.bursts)):
                    ii = jj - burstoffsetx
                    #burstFileName = os.path.join(os.path.abspath(dirx), 'IW{}'.format(swath), os.path.basename(swathx.bursts[jj].image.filename))
                    burstFileName = os.path.join(os.path.abspath(dirx), 'IW{}'.format(swath), 'burst_%02d'%(jj+1) + '.slc')
                    if minBurst <= ii < maxBurst:
                        kk = ii - minBurst
                        burstFileNameNew = os.path.join(os.path.abspath(dirx), 'IW{}'.format(swath), 'burst_%02d'%(kk+1) + '.slc')
                        if burstFileName != burstFileNameNew:
                            img = isceobj.createImage()
                            img.load(burstFileName + '.xml')
                            img.setFilename(burstFileNameNew)
                            #img.extraFilename = burstFileNameNew+'.vrt'
                            img.renderHdr()

                            #still use original vrt
                            os.remove(burstFileName+'.xml')
                            os.remove(burstFileNameNew+'.vrt')
                            os.rename(burstFileName+'.vrt', burstFileNameNew+'.vrt')
                        #change geometry file names accordingly if provided
                        if dirx == referenceDir:
                            if inps.geom_reference is not None:
                                for fileType in ['hgt', 'incLocal', 'lat', 'lon', 'los', 'shadowMask']:
                                    geomFileName = os.path.join(os.path.abspath(inps.geom_reference), 'IW{}'.format(swath), fileType + '_%02d'%(jj+1) + '.rdr')
                                    geomFileNameNew = os.path.join(os.path.abspath(inps.geom_reference), 'IW{}'.format(swath), fileType + '_%02d'%(kk+1) + '.rdr')
                                    if geomFileName != geomFileNameNew:
                                        renameFile(geomFileName, geomFileNameNew)


                #change swath properties
                swathx.bursts = swathTmp.bursts
                swathx.numberOfBursts = numBurst

                #remove original and write new
                os.remove( os.path.join(dirx, 'IW{}.xml'.format(swath)) )
                ut.saveProduct(swathx, os.path.join(dirx, 'IW{}.xml'.format(swath)))

                
    #remove invalid swaths
    invalidSwath3 = list(sorted(set(invalidSwath+invalidSwath2)))
    for swath in invalidSwath3:
        for dirx in acquistionDir:
            iwdir = os.path.join(dirx, 'IW{}'.format(swath))
            iwxml = os.path.join(dirx, 'IW{}.xml'.format(swath))
            if os.path.isdir(iwdir):
                shutil.rmtree(iwdir)
            if os.path.isfile(iwxml):
                os.remove(iwxml)
Beispiel #14
0
def main(iargs=None):

    inps = cmdLineParse(iargs)

    swathList = ut.getSwathList(inps.master)

    demImage = isceobj.createDemImage()
    demImage.load(inps.dem + '.xml')

    boxes = []
    for swath in swathList:
        master =  ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))
    
        ###Check if geometry directory already exists.
        dirname = os.path.join(inps.geom_masterDir, 'IW{0}'.format(swath))

        if os.path.isdir(dirname):
            print('Geometry directory {0} already exists.'.format(dirname))
        else:
            os.makedirs(dirname)


    ###For each burst
        for ind in range(master.numberOfBursts):
            burst = master.bursts[ind]

            latname = os.path.join(dirname, 'lat_%02d.rdr'%(ind+1))
            lonname = os.path.join(dirname, 'lon_%02d.rdr'%(ind+1))
            hgtname = os.path.join(dirname, 'hgt_%02d.rdr'%(ind+1))
            losname = os.path.join(dirname, 'los_%02d.rdr'%(ind+1))
            maskname = os.path.join(dirname, 'shadowMask_%02d.rdr'%(ind+1))
            incname = os.path.join(dirname, 'incLocal_%02d.rdr'%(ind+1))
        #####Run Topo
            planet = Planet(pname='Earth')
            topo = createTopozero()
            topo.slantRangePixelSpacing = burst.rangePixelSize
            topo.prf = 1.0/burst.azimuthTimeInterval
            topo.radarWavelength = burst.radarWavelength
            topo.orbit = burst.orbit
            topo.width = burst.numberOfSamples
            topo.length = burst.numberOfLines
            topo.wireInputPort(name='dem', object=demImage)
            topo.wireInputPort(name='planet', object=planet)
            topo.numberRangeLooks = 1
            topo.numberAzimuthLooks = 1
            topo.lookSide = -1
            topo.sensingStart = burst.sensingStart
            topo.rangeFirstSample = burst.startingRange
            topo.demInterpolationMethod='BIQUINTIC'
            topo.latFilename = latname
            topo.lonFilename = lonname
            topo.heightFilename = hgtname
            topo.losFilename = losname
            topo.maskFilename = maskname
            topo.incFilename = incname
            topo.topo()

            bbox = [topo.minimumLatitude, topo.maximumLatitude, topo.minimumLongitude, topo.maximumLongitude]
            boxes.append(bbox)

            topo = None

    boxes = np.array(boxes)
    bbox = [np.min(boxes[:,0]), np.max(boxes[:,1]), np.min(boxes[:,2]), np.max(boxes[:,3])]
    print ('bbox : ',bbox)
Beispiel #15
0
def main(iargs=None):
    '''
    Merge burst products to make it look like stripmap.
    Currently will merge interferogram, lat, lon, z and los.
    '''
    inps = cmdLineParse(iargs)
    virtual = inps.useVirtualFiles

    swathList = ut.getSwathList(inps.reference)
    referenceFrames = []
    frames = []
    fileList = []
    namePattern = inps.namePattern.split('*')

    for swath in swathList:
        ifg = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))
        if inps.stack:
            stack = ut.loadProduct(
                os.path.join(inps.stack, 'IW{0}.xml'.format(swath)))
        if inps.isaligned:
            reference = ifg.reference

            #this does not make sense, number of burst in reference is not necessarily number of bursts in interferogram.
            #so comment it out.
            # # checking inconsistent number of bursts in the secondary acquisitions
            # if reference.numberOfBursts != ifg.numberOfBursts:
            #     raise ValueError('{} has different number of bursts ({}) than the reference ({})'.format(
            #         inps.reference, ifg.numberOfBursts, reference.numberOfBursts))

        else:
            reference = ifg

        minBurst = ifg.bursts[0].burstNumber
        maxBurst = ifg.bursts[-1].burstNumber

        if minBurst == maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue

        if inps.stack:
            minStack = stack.bursts[0].burstNumber
            print(
                'Updating the valid region of each burst to the common valid region of the stack'
            )
            for ii in range(minBurst, maxBurst + 1):
                ifg.bursts[ii - minBurst].firstValidLine = stack.bursts[
                    ii - minStack].firstValidLine
                ifg.bursts[ii - minBurst].firstValidSample = stack.bursts[
                    ii - minStack].firstValidSample
                ifg.bursts[ii - minBurst].numValidLines = stack.bursts[
                    ii - minStack].numValidLines
                ifg.bursts[ii - minBurst].numValidSamples = stack.bursts[
                    ii - minStack].numValidSamples

        frames.append(ifg)
        referenceFrames.append(reference)
        print('bursts: ', minBurst, maxBurst)
        fileList.append([
            os.path.join(inps.dirname, 'IW{0}'.format(swath),
                         namePattern[0] + '_%02d.%s' % (x, namePattern[1]))
            for x in range(minBurst, maxBurst + 1)
        ])

    mergedir = os.path.dirname(inps.outfile)
    os.makedirs(mergedir, exist_ok=True)

    suffix = '.full'
    if (inps.numberRangeLooks == 1) and (inps.numberAzimuthLooks == 1):
        suffix = ''
        ####Virtual flag is ignored for multi-swath data
        if (not virtual):
            print('User requested for multi-swath stitching.')
            print('Virtual files are the only option for this.')
            print('Proceeding with virtual files.')

    mergeBurstsVirtual(frames,
                       referenceFrames,
                       fileList,
                       inps.outfile + suffix,
                       validOnly=inps.validOnly)

    if (not virtual):
        print('writing merged file to disk via gdal.Translate ...')
        gdal.Translate(inps.outfile + suffix,
                       inps.outfile + suffix + '.vrt',
                       options='-of ENVI -co INTERLEAVE=BIL',
                       callback=progress_cb,
                       callback_data='.')

    if inps.multilook:
        multilook(inps.outfile + suffix,
                  outname=inps.outfile,
                  alks=inps.numberAzimuthLooks,
                  rlks=inps.numberRangeLooks,
                  multilook_tool=inps.multilookTool,
                  no_data=inps.noData)
    else:
        print('Skipping multi-looking ....')
Beispiel #16
0
def main(iargs=None):
    '''
    '''
    inps = cmdLineParse(iargs)

    corThresholdSwathAdj = 0.85

    numberRangeLooks = inps.nrlks
    numberAzimuthLooks = inps.nalks
    remove_ramp = inps.remove_ramp

    ionParamObj = ionParam()
    ionParamObj.configure()

    #####################################################################
    framesBox = []
    swathList = sorted(ut.getSwathList(inps.reference))
    for swath in swathList:
        frame = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))

        minBurst = frame.bursts[0].burstNumber
        maxBurst = frame.bursts[-1].burstNumber
        if minBurst == maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue

        passDirection = frame.bursts[0].passDirection.lower()

        if inps.stack is not None:
            print(
                'Updating the valid region of each burst to the common valid region of the stack'
            )
            frame_stack = ut.loadProduct(
                os.path.join(inps.stack, 'IW{0}.xml'.format(swath)))
            updateValid(frame, frame_stack)

        framesBox.append(frame)

    box = mergeBox(framesBox)
    #adjust valid with looks, 'frames' ARE CHANGED AFTER RUNNING THIS
    #here numberRangeLooks, instead of numberRangeLooks0, is used, since we need to do next step multilooking after unwrapping. same for numberAzimuthLooks.
    (burstValidBox, burstValidBox2,
     message) = adjustValidWithLooks(framesBox,
                                     box,
                                     numberAzimuthLooks,
                                     numberRangeLooks,
                                     edge=0,
                                     avalid='strict',
                                     rvalid='strict')

    #1. we use adjustValidWithLooks() to compute burstValidBox for extracting burst bounding boxes, use each burst's bounding box to retrive
    #the corresponding burst in merged swath image and then put the burst in the final merged image.

    #so there is no need to use interferogram IW*.xml, reference IW*.xml is good enough. If there is no corresponding burst in interferogram
    #IW*.xml, the burst in merged swath image is just zero, and we can put this zero burst in the final merged image.

    #2. we use mergeBox() to compute box[1] to be used in cal_cross_ab_ramp()

    #####################################################################

    numValidSwaths = len(swathList)

    if numValidSwaths == 1:
        print('there is only one valid swath, simply copy the files')

        os.makedirs(inps.output, exist_ok=True)
        corName = os.path.join(inps.input, 'ion_cal_IW{}'.format(swathList[0]),
                               'raw_no_projection.cor')
        ionName = os.path.join(inps.input, 'ion_cal_IW{}'.format(swathList[0]),
                               'raw_no_projection.ion')
        corOutName = os.path.join(inps.output, 'raw_no_projection.cor')
        ionOutName = os.path.join(inps.output, 'raw_no_projection.ion')

        shutil.copy2(corName, corOutName)
        shutil.copy2(ionName, ionOutName)
        #os.symlink(os.path.abspath(corName), os.path.abspath(corOutName))
        #os.symlink(os.path.abspath(ionName), os.path.abspath(ionOutName))

        img = isceobj.createImage()
        img.load(corName + '.xml')
        img.setFilename(corOutName)
        img.extraFilename = corOutName + '.vrt'
        img.renderHdr()

        img = isceobj.createImage()
        img.load(ionName + '.xml')
        img.setFilename(ionOutName)
        img.extraFilename = ionOutName + '.vrt'
        img.renderHdr()

        return

    print('merging swaths')

    corList = []
    ampList = []
    ionosList = []
    for swath in swathList:
        corName = os.path.join(inps.input, 'ion_cal_IW{}'.format(swath),
                               'raw_no_projection.cor')
        ionName = os.path.join(inps.input, 'ion_cal_IW{}'.format(swath),
                               'raw_no_projection.ion')

        img = isceobj.createImage()
        img.load(ionName + '.xml')
        width = img.width
        length = img.length

        amp = (np.fromfile(corName,
                           dtype=np.float32).reshape(length * 2,
                                                     width))[0:length * 2:2, :]
        cor = (np.fromfile(corName,
                           dtype=np.float32).reshape(length * 2,
                                                     width))[1:length * 2:2, :]
        ion = (np.fromfile(ionName,
                           dtype=np.float32).reshape(length * 2,
                                                     width))[1:length * 2:2, :]

        corList.append(cor)
        ampList.append(amp)
        ionosList.append(ion)

    #do adjustment between ajacent swaths
    if numValidSwaths == 3:
        adjustList = [ionosList[0], ionosList[2]]
    else:
        adjustList = [ionosList[0]]
    for adjdata in adjustList:
        index = np.nonzero((adjdata != 0) * (ionosList[1] != 0) *
                           (corList[1] > corThresholdSwathAdj))
        if index[0].size < 5:
            print(
                'WARNING: too few samples available for adjustment between swaths: {} with coherence threshold: {}'
                .format(index[0].size, corThresholdSwathAdj))
            print('         no adjustment made')
            print(
                '         to do ajustment, please consider using lower coherence threshold'
            )
        else:
            print(
                'number of samples available for adjustment in the overlap area: {}'
                .format(index[0].size))
            #diff = np.mean((ionosList[1] - adjdata)[index], dtype=np.float64)

            #use weighted mean instead
            wgt = corList[1][index]**14
            diff = np.sum((ionosList[1] - adjdata)[index] * wgt /
                          np.sum(wgt, dtype=np.float64),
                          dtype=np.float64)

            index2 = np.nonzero(adjdata != 0)
            adjdata[index2] = adjdata[index2] + diff

    #get merged ionosphere
    ampMerged = np.zeros((length, width), dtype=np.float32)
    corMerged = np.zeros((length, width), dtype=np.float32)
    ionosMerged = np.zeros((length, width), dtype=np.float32)
    for i in range(numValidSwaths):
        nBurst = len(burstValidBox[i])
        for j in range(nBurst):

            #index after multi-looking in merged image, index starts from 1
            first_line = np.int(
                np.around((burstValidBox[i][j][0] - 1) / numberAzimuthLooks +
                          1))
            last_line = np.int(
                np.around(burstValidBox[i][j][1] / numberAzimuthLooks))
            first_sample = np.int(
                np.around((burstValidBox[i][j][2] - 1) / numberRangeLooks + 1))
            last_sample = np.int(
                np.around(burstValidBox[i][j][3] / numberRangeLooks))

            corMerged[first_line-1:last_line-1+1, first_sample-1:last_sample-1+1] = \
                corList[i][first_line-1:last_line-1+1, first_sample-1:last_sample-1+1]

            ampMerged[first_line-1:last_line-1+1, first_sample-1:last_sample-1+1] = \
                ampList[i][first_line-1:last_line-1+1, first_sample-1:last_sample-1+1]

            ionosMerged[first_line-1:last_line-1+1, first_sample-1:last_sample-1+1] = \
                ionosList[i][first_line-1:last_line-1+1, first_sample-1:last_sample-1+1]

    #remove an empirical ramp
    if remove_ramp != 0:
        #warningInfo = '{} calculating ionosphere for cross S-1A/B interferogram, an empirical ramp is removed from estimated ionosphere\n'.format(datetime.datetime.now())
        #with open(os.path.join(ionParam.ionDirname, ionParam.warning), 'a') as f:
        #    f.write(warningInfo)

        abramp = cal_cross_ab_ramp(swathList, box[1], numberRangeLooks,
                                   passDirection)
        if remove_ramp == -1:
            abramp *= -1.0
        #currently do not apply this
        #ionosMerged -= abramp[None, :]

    #dump ionosphere
    os.makedirs(inps.output, exist_ok=True)
    outFilename = os.path.join(inps.output, ionParamObj.ionRawNoProj)
    ion = np.zeros((length * 2, width), dtype=np.float32)
    ion[0:length * 2:2, :] = ampMerged
    ion[1:length * 2:2, :] = ionosMerged
    ion.astype(np.float32).tofile(outFilename)
    img.filename = outFilename
    img.extraFilename = outFilename + '.vrt'
    img.renderHdr()

    #dump coherence
    outFilename = os.path.join(inps.output, ionParamObj.ionCorNoProj)
    ion[1:length * 2:2, :] = corMerged
    ion.astype(np.float32).tofile(outFilename)
    img.filename = outFilename
    img.extraFilename = outFilename + '.vrt'
    img.renderHdr()
Beispiel #17
0
def main(iargs=None):
    '''
    Merge burst products to make it look like stripmap.
    Currently will merge interferogram, lat, lon, z and los.
    '''

    inps = cmdLineParse(iargs)
    from osgeo import ogr, osr
    import matplotlib
    if inps.shapefile is not None:
        matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches

    swathList = ut.getSwathList(inps.reference)

    swathColors = ['r', 'g', 'b']
    shapeColors = ['FF0000', '00FF00', '0000FF']

    fig = plt.figure('Burst map')
    ax = fig.add_subplot(111, aspect='equal')

    tmin = None
    rmin = None

    xmin = 1e10
    ymin = 1e10
    xmax = -1e10
    ymax = -1e10

    if inps.shapefile is not None:
        ds = ogr.GetDriverByName('KML').CreateDataSource(inps.shapefile)
        srs = osr.SpatialReference()
        srs.SetWellKnownGeogCS('WGS84')
        layer = ds.CreateLayer('bursts', srs=srs)
        field_name = ogr.FieldDefn("Name", ogr.OFTString)
        field_name.SetWidth(16)
        layer.CreateField(field_name)
        field_name = ogr.FieldDefn("OGR_STYLE", ogr.OFTString)
        layer.CreateField(field_name)

    for swath in swathList:
        ifg = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))
        minBurst = ifg.bursts[0].burstNumber
        maxBurst = ifg.bursts[-1].burstNumber

        if tmin is None:
            tmin = ifg.bursts[0].sensingStart
            dtime = ifg.bursts[0].azimuthTimeInterval
            rmin = ifg.bursts[0].startingRange
            drange = ifg.bursts[0].rangePixelSize

        if minBurst == maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue

        if not inps.shapefile:
            for ii in range(minBurst, maxBurst + 1):
                burst = ifg.bursts[ii - minBurst]
                x0 = np.round((burst.startingRange - rmin) / drange)
                y0 = np.round(
                    (burst.sensingStart - tmin).total_seconds() / dtime)
                if ii % 2 == 0:
                    style = 'solid'
                else:
                    style = 'dashdot'

                ax.add_patch(
                    patches.Rectangle((x0, y0),
                                      burst.numValidSamples,
                                      burst.numValidLines,
                                      edgecolor=swathColors[swath - 1],
                                      facecolor=swathColors[swath - 1],
                                      alpha=0.2,
                                      linestyle=style))

                xmin = min(xmin, x0)
                xmax = max(xmax, x0 + burst.numValidSamples)
                ymin = min(ymin, y0)
                ymax = max(ymax, y0 + burst.numValidLines)
        else:
            for ii in range(minBurst, maxBurst + 1):
                burst = ifg.bursts[ii - minBurst]
                t0 = burst.sensingStart + datetime.timedelta(
                    seconds=burst.firstValidLine * burst.azimuthTimeInterval)
                t1 = t0 + datetime.timedelta(seconds=burst.numValidLines *
                                             burst.azimuthTimeInterval)
                r0 = burst.startingRange + burst.firstValidSample * burst.rangePixelSize
                r1 = r0 + burst.numValidSamples * burst.rangePixelSize

                earlyNear = burst.orbit.rdr2geo(t0, r0)
                earlyFar = burst.orbit.rdr2geo(t0, r1)
                lateFar = burst.orbit.rdr2geo(t1, r1)
                lateNear = burst.orbit.rdr2geo(t1, r0)

                ring = ogr.Geometry(ogr.wkbLinearRing)
                ring.AddPoint(earlyNear[1], earlyNear[0])
                ring.AddPoint(earlyFar[1], earlyFar[0])
                ring.AddPoint(lateFar[1], lateFar[0])
                ring.AddPoint(lateNear[1], lateNear[0])
                ring.AddPoint(earlyNear[1], earlyNear[0])

                feature = ogr.Feature(layer.GetLayerDefn())
                feature.SetField('Name', 'IW{0}-{1}'.format(swath, ii))
                feature.SetField(
                    'OGR_STYLE',
                    "PEN(c:#{0},w:8px)".format(shapeColors[swath - 1]))
                feature.SetGeometry(ring)
                layer.CreateFeature(feature)
                feature = None

    if not inps.shapefile:
        plt.ylim([ymin, ymax])
        plt.xlim([xmin, xmax])

        if inps.figure is not None:
            plt.savefig(inps.figure, format='pdf')
        else:
            plt.show()

    else:
        ds = None
        print('Wrote KML file: ', inps.shapefile)
Beispiel #18
0
def main(iargs=None):

    inps = cmdLineParse(iargs)
    swathList = ut.getSwathList(inps.reference)
    for swath in swathList:

        ####Load reference metadata
        mFrame = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))

        ####Output directory for overlap geometry images
        geomdir = os.path.join(inps.geom_reference, 'IW{0}'.format(swath))
        outdir = os.path.join(inps.geom_reference, inps.overlapDir,
                              'IW{0}'.format(swath))
        subreferencedir = os.path.join(inps.reference, inps.overlapDir,
                                       'IW{0}'.format(swath))

        if os.path.isdir(outdir):
            catalog.addItem(
                'Overlap directory {0} already exists'.format(outdir))
        else:
            os.makedirs(outdir)

        if os.path.isdir(subreferencedir):
            catalog.addItem(
                'Subreference Overlap directory {0} already exists'.format(
                    subreferencedir))
        else:
            os.makedirs(subreferencedir)

        ###Azimuth time interval
        dt = mFrame.bursts[0].azimuthTimeInterval
        topFrame = ut.coregSwathSLCProduct()

        topFrame.configure()
        bottomFrame = ut.coregSwathSLCProduct()
        bottomFrame.configure()

        numCommon = mFrame.numberOfBursts
        startIndex = 0

        ###For each overlap
        for ii in range(numCommon - 1):
            ind = ii + startIndex

            topBurst = mFrame.bursts[ind]
            botBurst = mFrame.bursts[ind + 1]

            overlap_start_time = botBurst.sensingStart
            overlap_end_time = topBurst.sensingStop
            catalog.addItem(
                'Overlap {0} start time - IW-{1}'.format(ind, swath),
                overlap_start_time, 'subset')
            catalog.addItem(
                'Overlap {0} stop time - IW-{1}'.format(ind, swath),
                overlap_end_time, 'subset')

            nLinesOverlap = int(
                np.round(
                    (overlap_end_time - overlap_start_time).total_seconds() /
                    dt)) + 1
            catalog.addItem(
                'Overlap {0} number of lines - IW-{1}'.format(ind, swath),
                nLinesOverlap, 'subset')

            length = topBurst.numberOfLines
            width = topBurst.numberOfSamples

            topStart = int(
                np.round((botBurst.sensingStart - topBurst.sensingStart
                          ).total_seconds() / dt)) + botBurst.firstValidLine
            overlapLen = topBurst.firstValidLine + topBurst.numValidLines - topStart

            catalog.addItem(
                'Overlap {0} number of valid lines - IW-{1}'.format(
                    ind, swath), overlapLen, 'subset')

            ###Create slice objects for overlaps
            topslicey = slice(topStart, topStart + overlapLen)
            topslicex = slice(0, width)

            botslicey = slice(botBurst.firstValidLine,
                              botBurst.firstValidLine + overlapLen)
            botslicex = slice(0, width)

            for prefix in ['lat', 'lon', 'hgt']:
                infile = os.path.join(geomdir,
                                      prefix + '_%02d.rdr' % (ind + 2))
                outfile = os.path.join(
                    outdir, prefix + '_%02d_%02d.rdr' % (ind + 1, ind + 2))

                subset(infile, outfile, botslicey, botslicex)

            masname1 = topBurst.image.filename
            masname2 = botBurst.image.filename

            reference_outname1 = os.path.join(
                subreferencedir,
                'burst_top_%02d_%02d.slc' % (ind + 1, ind + 2))
            reference_outname2 = os.path.join(
                subreferencedir,
                'burst_bot_%02d_%02d.slc' % (ind + 1, ind + 2))

            subset(masname1, reference_outname1, topslicey, topslicex)
            subset(masname2, reference_outname2, botslicey, botslicex)

            ####TOP frame
            burst = copy.deepcopy(topBurst)
            burst.firstValidLine = 0
            burst.numberOfLines = overlapLen
            burst.numValidLines = overlapLen
            burst.sensingStart = topBurst.sensingStart + datetime.timedelta(
                0, topStart * dt)  # topStart*dt
            burst.sensingStop = topBurst.sensingStart + datetime.timedelta(
                0,
                (topStart + overlapLen - 1) * dt)  # (topStart+overlapLen-1)*dt

            ###Replace file name in image
            burst.image.filename = reference_outname1
            burst.image.setLength(overlapLen)
            burst.image.setWidth(width)

            topFrame.bursts.append(burst)

            burst = None

            ####BOTTOM frame
            burst = copy.deepcopy(botBurst)
            burst.firstValidLine = 0
            burst.numberOfLines = overlapLen
            burst.numValidLines = overlapLen
            burst.sensingStart = botBurst.sensingStart + datetime.timedelta(
                seconds=botBurst.firstValidLine * dt)
            burst.sensingStop = botBurst.sensingStart + datetime.timedelta(
                seconds=(botBurst.firstValidLine + overlapLen - 1) * dt)

            ###Replace file name in image
            burst.image.filename = reference_outname2
            burst.image.setLength(overlapLen)
            burst.image.setWidth(width)

            bottomFrame.bursts.append(burst)

            burst = None

            print('Top: ', [x.image.filename for x in topFrame.bursts])
            print('Bottom: ', [x.image.filename for x in bottomFrame.bursts])

        topFrame.numberOfBursts = len(topFrame.bursts)
        bottomFrame.numberOfBursts = len(bottomFrame.bursts)

        #self._insar.saveProduct(topFrame, os.path.join(self._insar.referenceSlcOverlapProduct, 'top_IW{0}.xml'.format(swath)))
        #self._insar.saveProduct(bottomFrame, os.path.join(self._insar.referenceSlcOverlapProduct, 'bottom_IW{0}.xml'.format(swath)))

        topFrame.reference = mFrame
        bottomFrame.reference = mFrame

        topFrame.source = mFrame
        bottomFrame.source = mFrame

        ut.saveProduct(topFrame, subreferencedir + '_top.xml')
        ut.saveProduct(bottomFrame, subreferencedir + '_bottom.xml')
Beispiel #19
0
def main(iargs=None):
    '''
    Estimate offsets for the overlap regions of the bursts.
    '''
    inps = cmdLineParse(iargs)

    # see if the user compiled isce with GPU enabled
    run_GPU = False
    try:
        from zerodop.GPUtopozero.GPUtopozero import PyTopozero
        from zerodop.GPUgeo2rdr.GPUgeo2rdr import PyGeo2rdr
        run_GPU = True
    except:
        pass
    
    if inps.useGPU and not run_GPU:
        print("GPU mode requested but no GPU ISCE code found")

    # setting the respective version of geo2rdr for CPU and GPU
    if run_GPU and inps.useGPU:
        print('GPU mode')
        runGeo2rdr = runGeo2rdrGPU
    else:
        print('CPU mode')
        runGeo2rdr = runGeo2rdrCPU
    

    masterSwathList = ut.getSwathList(inps.master)
    slaveSwathList = ut.getSwathList(inps.slave)

    swathList = list(sorted(set(masterSwathList+slaveSwathList)))

    for swath in swathList:
        ##Load slave metadata
        slave = ut.loadProduct(os.path.join(inps.slave, 'IW{0}.xml'.format(swath)))
        master = ut.loadProduct(os.path.join(inps.master, 'IW{0}.xml'.format(swath)))
    
        ### output directory
        if inps.overlap:
            outdir = os.path.join(inps.coregdir, inps.overlapDir, 'IW{0}'.format(swath))
        else:
            outdir = os.path.join(inps.coregdir, 'IW{0}'.format(swath))

        if not os.path.isdir(outdir):
           os.makedirs(outdir)

        if os.path.exists(str(inps.misreg_az)):
            with open(inps.misreg_az, 'r') as f:
                misreg_az = float(f.readline())
        else:
            misreg_az = 0.0
        
        if os.path.exists(str(inps.misreg_rng)):
            with open(inps.misreg_rng, 'r') as f:
                misreg_rg = float(f.readline())
        else:
             misreg_rg = 0.0

        burstoffset, minBurst, maxBurst = master.getCommonBurstLimits(slave)

        ###Burst indices w.r.t master
        if inps.overlap:
            maxBurst = maxBurst - 1
            geomDir = os.path.join(inps.geom_masterDir, inps.overlapDir, 'IW{0}'.format(swath))   
       
        else:
            geomDir = os.path.join(inps.geom_masterDir, 'IW{0}'.format(swath))
      
    
        slaveBurstStart = minBurst + burstoffset
    
        for mBurst in range(minBurst, maxBurst):
        
            ###Corresponding slave burst
            sBurst = slaveBurstStart + (mBurst - minBurst)
            burstTop = slave.bursts[sBurst]
            if inps.overlap:
                burstBot = slave.bursts[sBurst+1]
        
            print('Overlap pair {0}: Burst {1} of master matched with Burst {2} of slave'.format(mBurst-minBurst, mBurst, sBurst))
            if inps.overlap:
                ####Generate offsets for top burst
                rdict = {'lat': os.path.join(geomDir,'lat_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'lon': os.path.join(geomDir,'lon_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'hgt': os.path.join(geomDir,'hgt_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'rangeOffName': os.path.join(outdir, 'range_top_%02d_%02d.off'%(mBurst+1,mBurst+2)),
                     'azOffName': os.path.join(outdir, 'azimuth_top_%02d_%02d.off'%(mBurst+1,mBurst+2))}
        
                runGeo2rdr(burstTop, rdict, misreg_az=misreg_az, misreg_rg=misreg_rg)
        
                print('Overlap pair {0}: Burst {1} of master matched with Burst {2} of slave'.format(mBurst-minBurst, mBurst+1, sBurst+1))
                ####Generate offsets for bottom burst
                rdict = {'lat': os.path.join(geomDir,'lat_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'lon': os.path.join(geomDir, 'lon_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'hgt': os.path.join(geomDir, 'hgt_%02d_%02d.rdr'%(mBurst+1,mBurst+2)),
                     'rangeOffName': os.path.join(outdir, 'range_bot_%02d_%02d.off'%(mBurst+1,mBurst+2)),
                     'azOffName': os.path.join(outdir, 'azimuth_bot_%02d_%02d.off'%(mBurst+1,mBurst+2))}

                runGeo2rdr(burstBot, rdict, misreg_az=misreg_az, misreg_rg=misreg_rg)

            else:
                print('Burst {1} of master matched with Burst {2} of slave'.format(mBurst-minBurst, mBurst, sBurst))
                ####Generate offsets for top burst
                rdict = {'lat': os.path.join(geomDir,'lat_%02d.rdr'%(mBurst+1)),
                     'lon': os.path.join(geomDir,'lon_%02d.rdr'%(mBurst+1)),
                     'hgt': os.path.join(geomDir,'hgt_%02d.rdr'%(mBurst+1)),
                     'rangeOffName': os.path.join(outdir, 'range_%02d.off'%(mBurst+1)),
                     'azOffName': os.path.join(outdir, 'azimuth_%02d.off'%(mBurst+1))}

                runGeo2rdr(burstTop, rdict, misreg_az=misreg_az, misreg_rg=misreg_rg)
def main(iargs=None):

    inps = cmdLineParse(iargs)
    '''
    Estimate constant offset in range.
    '''

    #if not self.doESD:
    #    return

    #catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)

    #swathList = self._insar.getValidSwathList(self.swaths)
    masterSwathList = ut.getSwathList(os.path.join(inps.master, 'overlap'))
    slaveSwathList = ut.getSwathList(os.path.join(inps.slave, 'overlap'))
    swathList = list(sorted(set(masterSwathList + slaveSwathList)))

    rangeOffsets = []
    snr = []

    for swath in swathList:

        #if self._insar.numberOfCommonBursts[swath-1] < 2:
        #    print('Skipping range coreg for swath IW{0}'.format(swath))
        #    continue

        #minBurst, maxBurst = self._insar.commonMasterBurstLimits(swath-1)

        #maxBurst = maxBurst - 1  ###For overlaps

        #masterTop = self._insar.loadProduct( os.path.join(self._insar.masterSlcOverlapProduct, 'top_IW{0}.xml'.format(swath)))
        #masterBottom  = self._insar.loadProduct( os.path.join(self._insar.masterSlcOverlapProduct , 'bottom_IW{0}.xml'.format(swath)))
        masterTop = ut.loadProduct(
            os.path.join(inps.master, 'overlap',
                         'IW{0}_top.xml'.format(swath)))
        masterBottom = ut.loadProduct(
            os.path.join(inps.master, 'overlap',
                         'IW{0}_bottom.xml'.format(swath)))
        slaveTop = ut.loadProduct(
            os.path.join(inps.slave, 'overlap', 'IW{0}_top.xml'.format(swath)))
        slaveBottom = ut.loadProduct(
            os.path.join(inps.slave, 'overlap',
                         'IW{0}_bottom.xml'.format(swath)))

        #slaveTop = self._insar.loadProduct( os.path.join(self._insar.coregOverlapProduct , 'top_IW{0}.xml'.format(swath)))
        #slaveBottom = self._insar.loadProduct( os.path.join(self._insar.coregOverlapProduct, 'bottom_IW{0}.xml'.format(swath)))
        minMaster = masterTop.bursts[0].burstNumber
        maxMaster = masterTop.bursts[-1].burstNumber

        minSlave = slaveTop.bursts[0].burstNumber
        maxSlave = slaveTop.bursts[-1].burstNumber

        minBurst = max(minSlave, minMaster)
        maxBurst = min(maxSlave, maxMaster)
        maxBurst = maxBurst - 1  ###For overlaps

        for pair in [(masterTop, slaveTop), (masterBottom, slaveBottom)]:
            for ii in range(minBurst, maxBurst):
                mFile = pair[0].bursts[ii - minMaster].image.filename
                sFile = pair[1].bursts[ii - minSlave].image.filename

                field = runAmpcor(mFile, sFile)

                for offset in field:
                    rangeOffsets.append(offset.dx)
                    snr.append(offset.snr)

    ###Cull
    mask = np.logical_and(
        np.array(snr) > inps.offsetSNRThreshold,
        np.abs(rangeOffsets) < 1.2)
    val = np.array(rangeOffsets)[mask]

    medianval = np.median(val)
    meanval = np.mean(val)
    stdval = np.std(val)

    # convert the estimations to meters
    medianval = medianval * masterTop.bursts[0].rangePixelSize
    meanval = meanval * masterTop.bursts[0].rangePixelSize
    stdval = stdval * masterTop.bursts[0].rangePixelSize

    hist, bins = np.histogram(val, 50, normed=1)
    center = 0.5 * (bins[:-1] + bins[1:])

    outputDir = os.path.dirname(inps.output)
    if not os.path.exists(outputDir):
        os.makedirs(outputDir)

    try:
        import matplotlib as mpl
        mpl.use('Agg')
        import matplotlib.pyplot as plt
    except:
        print('Matplotlib could not be imported. Skipping debug plot ...')
        debugPlot = False

    debugPlot = False
    if debugPlot:

        try:
            ####Plotting
            plt.figure()
            plt.bar(center,
                    hist,
                    align='center',
                    width=0.7 * (bins[1] - bins[0]))
            plt.xlabel('Range shift in pixels')
            plt.savefig(os.path.join(outputDir, 'rangeMisregistration.jpg'))
            plt.show()
            plt.close()
        except:
            print(
                'Looks like matplotlib could not save image to JPEG, continuing .....'
            )
            print(
                'Install Pillow to ensure debug plots for Residual range offsets are generated.'
            )
            pass

    with open(inps.output, 'w') as f:
        f.write('median : ' + str(medianval) + '\n')
        f.write('mean : ' + str(meanval) + '\n')
        f.write('std : ' + str(stdval) + '\n')
        f.write('snr threshold : ' + str(inps.offsetSNRThreshold) + '\n')
        f.write('mumber of coherent points : ' + str(len(val)) + '\n')
Beispiel #21
0
def main(iargs=None):
    '''
    Create additional layers for performing ESD.
    '''

    inps = cmdLineParse(iargs)
    inps.interferogram = os.path.join(inps.interferogram, 'overlap')
    inps.master = os.path.join(inps.master, 'overlap')
    inps.slave = os.path.join(inps.slave, 'overlap')

    masterSwathList = ut.getSwathList(inps.master)
    slaveSwathList = ut.getSwathList(inps.slave)

    swathList = list(sorted(set(masterSwathList + slaveSwathList)))

    for swath in swathList:
        IWstr = 'IW{0}'.format(swath)
        masterTop = ut.loadProduct(
            os.path.join(inps.master, IWstr + '_top.xml'))
        masterBot = ut.loadProduct(
            os.path.join(inps.master, IWstr + '_bottom.xml'))

        slaveTop = ut.loadProduct(os.path.join(inps.slave, IWstr + '_top.xml'))
        slaveBot = ut.loadProduct(
            os.path.join(inps.slave, IWstr + '_bottom.xml'))

        ####Load metadata for burst IFGs
        ifgTop = ut.loadProduct(
            os.path.join(inps.interferogram, IWstr + '_top.xml'))
        ifgBottom = ut.loadProduct(
            os.path.join(inps.interferogram, IWstr + '_bottom.xml'))

        ####Create ESD output directory
        esddir = os.path.join(inps.overlap, IWstr)
        os.makedirs(esddir, exist_ok=True)

        ####Overlap offsets directory
        masterOffdir = os.path.join(inps.master, IWstr)
        slaveOffdir = os.path.join(inps.slave, IWstr)

        #########
        minMaster = masterTop.bursts[0].burstNumber
        maxMaster = masterTop.bursts[-1].burstNumber

        minSlave = slaveTop.bursts[0].burstNumber
        maxSlave = slaveTop.bursts[-1].burstNumber

        minBurst = ifgTop.bursts[0].burstNumber
        maxBurst = ifgTop.bursts[-1].burstNumber
        print('minSlave,maxSlave', minSlave, maxSlave)
        print('minMaster,maxMaster', minMaster, maxMaster)
        print('minBurst, maxBurst: ', minBurst, maxBurst)

        #########

        ifglist = []
        factorlist = []
        offsetlist = []
        cohlist = []

        for ii in range(minBurst, maxBurst + 1):
            ind = ii - minBurst  ###Index into overlaps
            mind = ii - minMaster  ### Index into master
            sind = ii - minSlave  ###Index into slave

            topBurstIfg = ifgTop.bursts[ind]
            botBurstIfg = ifgBottom.bursts[ind]

            ###############
            '''stackMasterTop = ifgTop.source.bursts[mind]
            stackMasterBot = ifgBottom.source.bursts[mind]

            dt = stackMasterTop.azimuthTimeInterval
            topStart = int(np.round((stackMasterBot.sensingStart - stackMasterTop.sensingStart).total_seconds() / dt))
            #overlapLen = .numberOfLines
            botStart = stackMasterBot.firstValidLine #int(np.round((.sensingStart - masterBot.sensingStart).total_seconds() / dt))
            print('+++++++++++++++++++')
            print(topStart, botStart)
            print('+++++++++++++++++++') '''
            ###############

            ####Double difference interferograms
            topInt = np.memmap(topBurstIfg.image.filename,
                               dtype=np.complex64,
                               mode='r',
                               shape=(topBurstIfg.numberOfLines,
                                      topBurstIfg.numberOfSamples))

            botInt = np.memmap(botBurstIfg.image.filename,
                               dtype=np.complex64,
                               mode='r',
                               shape=(botBurstIfg.numberOfLines,
                                      botBurstIfg.numberOfSamples))

            intName = os.path.join(esddir, 'overlap_%02d.int' % (ii))
            freqName = os.path.join(esddir, 'freq_%02d.bin' % (ii))

            with open(intName, 'wb') as fid:
                fid.write(topInt * np.conj(botInt))

            img = isceobj.createIntImage()
            img.setFilename(intName)
            img.setWidth(topBurstIfg.numberOfSamples)
            img.setLength(topBurstIfg.numberOfLines)
            img.setAccessMode('READ')
            img.renderHdr()
            img.renderVRT()
            img.createImage()
            img.finalizeImage()

            multIntName = multilook(intName,
                                    alks=inps.esdAzimuthLooks,
                                    rlks=inps.esdRangeLooks)
            ifglist.append(multIntName)

            ####Estimate coherence of double different interferograms
            multCor = createCoherence(multIntName)
            cohlist.append(multCor)

            ####Estimate the frequency difference
            azMasTop = os.path.join(masterOffdir,
                                    'azimuth_top_%02d_%02d.off' % (ii, ii + 1))
            rgMasTop = os.path.join(masterOffdir,
                                    'range_top_%02d_%02d.off' % (ii, ii + 1))
            azMasBot = os.path.join(masterOffdir,
                                    'azimuth_bot_%02d_%02d.off' % (ii, ii + 1))
            rgMasBot = os.path.join(masterOffdir,
                                    'range_bot_%02d_%02d.off' % (ii, ii + 1))

            azSlvTop = os.path.join(slaveOffdir,
                                    'azimuth_top_%02d_%02d.off' % (ii, ii + 1))
            rgSlvTop = os.path.join(slaveOffdir,
                                    'range_top_%02d_%02d.off' % (ii, ii + 1))
            azSlvBot = os.path.join(slaveOffdir,
                                    'azimuth_bot_%02d_%02d.off' % (ii, ii + 1))
            rgSlvBot = os.path.join(slaveOffdir,
                                    'range_bot_%02d_%02d.off' % (ii, ii + 1))

            mFullTop = masterTop.source.bursts[mind]
            mFullBot = masterBot.source.bursts[mind + 1]
            sFullTop = slaveTop.source.bursts[sind]
            sFullBot = slaveBot.source.bursts[sind + 1]

            freqdiff = overlapSpectralSeparation(topBurstIfg, botBurstIfg,
                                                 mFullTop, mFullBot, sFullTop,
                                                 sFullBot, azMasTop, rgMasTop,
                                                 azMasBot, rgMasBot, azSlvTop,
                                                 rgSlvTop, azSlvBot, rgSlvBot)

            with open(freqName, 'wb') as fid:
                (freqdiff * 2 * np.pi * mFullTop.azimuthTimeInterval).astype(
                    np.float32).tofile(fid)

            img = isceobj.createImage()
            img.setFilename(freqName)
            img.setWidth(topBurstIfg.numberOfSamples)
            img.setLength(topBurstIfg.numberOfLines)
            img.setAccessMode('READ')
            img.bands = 1
            img.dataType = 'FLOAT'
            # img.createImage()
            img.renderHdr()
            img.renderVRT()
            img.createImage()
            img.finalizeImage()

            multConstName = multilook(freqName,
                                      alks=inps.esdAzimuthLooks,
                                      rlks=inps.esdRangeLooks)
            factorlist.append(multConstName)
Beispiel #22
0
def main(iargs=None):
    '''Create overlap interferograms.
    '''
    inps = cmdLineParse(iargs)

    if inps.overlap:
        referenceSwathList = ut.getSwathList(
            os.path.join(inps.reference, 'overlap'))
        secondarySwathList = ut.getSwathList(
            os.path.join(inps.secondary, 'overlap'))
    else:
        referenceSwathList = ut.getSwathList(inps.reference)
        secondarySwathList = ut.getSwathList(inps.secondary)
    swathList = list(sorted(set(referenceSwathList + secondarySwathList)))

    for swath in swathList:
        IWstr = 'IW{0}'.format(swath)
        if inps.overlap:
            ifgdir = os.path.join(inps.interferogram, 'overlap', IWstr)
        else:
            ifgdir = os.path.join(inps.interferogram, IWstr)

        os.makedirs(ifgdir, exist_ok=True)

        ####Load relevant products
        if inps.overlap:
            topReference = ut.loadProduct(
                os.path.join(inps.reference, 'overlap',
                             'IW{0}_top.xml'.format(swath)))
            botReference = ut.loadProduct(
                os.path.join(inps.reference, 'overlap',
                             'IW{0}_bottom.xml'.format(swath)))
            topCoreg = ut.loadProduct(
                os.path.join(inps.secondary, 'overlap',
                             'IW{0}_top.xml'.format(swath)))
            botCoreg = ut.loadProduct(
                os.path.join(inps.secondary, 'overlap',
                             'IW{0}_bottom.xml'.format(swath)))

        else:
            topReference = ut.loadProduct(
                os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))
            topCoreg = ut.loadProduct(
                os.path.join(inps.secondary, 'IW{0}.xml'.format(swath)))

        if inps.overlap:
            coregdir = os.path.join(inps.secondary, 'overlap',
                                    'IW{0}'.format(swath))
        else:
            coregdir = os.path.join(inps.secondary, 'IW{0}'.format(swath))

        topIfg = ut.coregSwathSLCProduct()
        topIfg.configure()

        if inps.overlap:
            botIfg = ut.coregSwathSLCProduct()
            botIfg.configure()

        minReference = topReference.bursts[0].burstNumber
        maxReference = topReference.bursts[-1].burstNumber

        minSecondary = topCoreg.bursts[0].burstNumber
        maxSecondary = topCoreg.bursts[-1].burstNumber

        minBurst = max(minSecondary, minReference)
        maxBurst = min(maxSecondary, maxReference)
        print('minSecondary,maxSecondary', minSecondary, maxSecondary)
        print('minReference,maxReference', minReference, maxReference)
        print('minBurst, maxBurst: ', minBurst, maxBurst)

        for ii in range(minBurst, maxBurst + 1):

            ####Process the top bursts
            reference = topReference.bursts[ii - minReference]
            secondary = topCoreg.bursts[ii - minSecondary]

            print('matching burst numbers: ', reference.burstNumber,
                  secondary.burstNumber)

            referencename = reference.image.filename
            secondaryname = secondary.image.filename

            if inps.reference_suffix is not None:
                referencename = os.path.splitext(referencename)[
                    0] + inps.reference_suffix + os.path.splitext(
                        referencename)[1]
            if inps.secondary_suffix is not None:
                secondaryname = os.path.splitext(secondaryname)[
                    0] + inps.secondary_suffix + os.path.splitext(
                        secondaryname)[1]

            if inps.overlap:
                rdict = {
                    'rangeOff1':
                    os.path.join(inps.reference, 'overlap', IWstr,
                                 'range_top_%02d_%02d.off' % (ii, ii + 1)),
                    'rangeOff2':
                    os.path.join(inps.secondary, 'overlap', IWstr,
                                 'range_top_%02d_%02d.off' % (ii, ii + 1)),
                    'azimuthOff':
                    os.path.join(inps.secondary, 'overlap', IWstr,
                                 'azimuth_top_%02d_%02d.off' % (ii, ii + 1))
                }

                intname = os.path.join(
                    ifgdir,
                    '%s_top_%02d_%02d.int' % (inps.intprefix, ii, ii + 1))

            else:

                rdict = {
                    'rangeOff1':
                    os.path.join(inps.reference, IWstr,
                                 'range_%02d.off' % (ii)),
                    'rangeOff2':
                    os.path.join(inps.secondary, IWstr,
                                 'range_%02d.off' % (ii)),
                    'azimuthOff1':
                    os.path.join(inps.secondary, IWstr,
                                 'azimuth_%02d.off' % (ii))
                }

                intname = os.path.join(ifgdir,
                                       '%s_%02d.int' % (inps.intprefix, ii))

            ut.adjustCommonValidRegion(reference, secondary)
            fact = 4 * np.pi * secondary.rangePixelSize / secondary.radarWavelength
            intimage = multiply(referencename,
                                secondaryname,
                                intname,
                                rdict['rangeOff1'],
                                rdict['rangeOff2'],
                                fact,
                                reference,
                                flatten=inps.flatten)

            burst = copy.deepcopy(reference)
            burst.image = intimage
            burst.burstNumber = ii
            topIfg.bursts.append(burst)

            if inps.overlap:
                ####Process the bottom bursts
                reference = botReference.bursts[ii - minReference]
                secondary = botCoreg.bursts[ii - minSecondary]

                referencename = reference.image.filename
                secondaryname = secondary.image.filename
                #            rdict = {'rangeOff' : os.path.join(coregdir, 'range_bot_%02d_%02d.off'%(ii,ii+1)),
                #                   'azimuthOff': os.path.join(coregdir, 'azimuth_bot_%02d_%02d.off'%(ii,ii+1))}

                rdict = {
                    'rangeOff1':
                    os.path.join(inps.reference, 'overlap', IWstr,
                                 'range_bot_%02d_%02d.off' % (ii, ii + 1)),
                    'rangeOff2':
                    os.path.join(inps.secondary, 'overlap', IWstr,
                                 'range_bot_%02d_%02d.off' % (ii, ii + 1)),
                    'azimuthOff':
                    os.path.join(inps.secondary, 'overlap', IWstr,
                                 'azimuth_bot_%02d_%02d.off' % (ii, ii + 1))
                }

                print('rdict: ', rdict)

                ut.adjustCommonValidRegion(reference, secondary)
                intname = os.path.join(
                    ifgdir,
                    '%s_bot_%02d_%02d.int' % (inps.intprefix, ii, ii + 1))
                fact = 4 * np.pi * secondary.rangePixelSize / secondary.radarWavelength

                #intimage = multiply(referencename, secondaryname, intname,
                #        rdict['rangeOff'], fact, reference, flatten=True)

                intimage = multiply(referencename,
                                    secondaryname,
                                    intname,
                                    rdict['rangeOff1'],
                                    rdict['rangeOff2'],
                                    fact,
                                    reference,
                                    flatten=inps.flatten)

                burst = copy.deepcopy(reference)
                burst.burstNumber = ii
                burst.image = intimage
                botIfg.bursts.append(burst)

        topIfg.numberOfBursts = len(topIfg.bursts)
        if hasattr(topCoreg, 'reference'):
            topIfg.reference = topCoreg.reference
        else:
            topIfg.reference = topReference.reference

        print('Type: ', type(topIfg.reference))

        if inps.overlap:
            ut.saveProduct(topIfg, ifgdir + '_top.xml')
            botIfg.numberOfBursts = len(botIfg.bursts)
            botIfg.reference = botCoreg.reference
            print(botIfg.reference)
            ut.saveProduct(botIfg, ifgdir + '_bottom.xml')
        else:
            ut.saveProduct(topIfg, ifgdir + '.xml')
Beispiel #23
0
def main(iargs=None):
    '''
    merge bursts
    '''
    inps = cmdLineParse(iargs)

    if inps.rvalid is None:
        inps.rvalid = 'strict'
    else:
        if not (1 <= inps.rvalid <= inps.nrlks):
            raise Exception('1<=rvalid<=nrlks')
    if inps.avalid is None:
        inps.avalid = 'strict'
    else:
        if not (1 <= inps.avalid <= inps.nalks):
            raise Exception('1<=avalid<=nalks')

    namePattern = inps.name_pattern.split('*')

    frameReferenceList = []
    frameProductList = []
    burstList = []
    swathList = ut.getSwathList(inps.reference)
    for swath in swathList:
        frameReference = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))

        minBurst = frameReference.bursts[0].burstNumber
        maxBurst = frameReference.bursts[-1].burstNumber
        if minBurst == maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue

        frameProduct = ut.loadProduct(
            os.path.join(inps.dirname, 'IW{0}.xml'.format(swath)))
        minBurst = frameProduct.bursts[0].burstNumber
        maxBurst = frameProduct.bursts[-1].burstNumber

        if inps.stack is not None:
            print(
                'Updating the valid region of each burst to the common valid region of the stack'
            )
            frameStack = ut.loadProduct(
                os.path.join(inps.stack, 'IW{0}.xml'.format(swath)))
            updateValid(frameReference, frameStack)
            updateValid(frameProduct, frameStack)

        frameReferenceList.append(frameReference)

        if inps.swath is not None:
            if swath == inps.swath:
                frameProductList.append(frameProduct)
                burstList.append([
                    os.path.join(
                        inps.dirname, 'IW{0}'.format(swath),
                        namePattern[0] + '%02d' % (x) + namePattern[1])
                    for x in range(minBurst, maxBurst + 1)
                ])
        else:
            frameProductList.append(frameProduct)
            burstList.append([
                os.path.join(inps.dirname, 'IW{0}'.format(swath),
                             namePattern[0] + '%02d' % (x) + namePattern[1])
                for x in range(minBurst, maxBurst + 1)
            ])

    os.makedirs(os.path.dirname(inps.outfile), exist_ok=True)
    suffix = '.full'
    if (inps.nrlks0 == 1) and (inps.nalks0 == 1):
        suffix = ''

    box = mergeBox(frameReferenceList)
    #adjust valid with looks, 'frames' ARE CHANGED AFTER RUNNING THIS
    #here numberRangeLooks, instead of numberRangeLooks0, is used, since we need to do next step multilooking after unwrapping. same for numberAzimuthLooks.
    (burstValidBox, burstValidBox2,
     message) = adjustValidWithLooks(frameProductList,
                                     box,
                                     inps.nalks,
                                     inps.nrlks,
                                     edge=0,
                                     avalid=inps.avalid,
                                     rvalid=inps.rvalid)
    mergeBurstsVirtual(frameProductList, burstList, box, inps.outfile + suffix)
    if suffix not in ['', None]:
        multilook2(inps.outfile + suffix,
                   outname=inps.outfile,
                   alks=inps.nalks0,
                   rlks=inps.nrlks0)
    #this is never used for ionosphere correction
    else:
        print('Skipping multi-looking ....')
def main(iargs=None):
    '''Compute baseline.
    '''
    inps = cmdLineParse(iargs)
    from isceobj.Planet.Planet import Planet
    import numpy as np

    #swathList = self._insar.getInputSwathList(self.swaths)
    #commonBurstStartMasterIndex = [-1] * self._insar.numberOfSwaths
    #commonBurstStartSlaveIndex = [-1] * self._insar.numberOfSwaths
    #numberOfCommonBursts = [0] * self._insar.numberOfSwaths

    masterSwathList = ut.getSwathList(inps.master)
    slaveSwathList = ut.getSwathList(inps.slave)
    swathList = list(sorted(set(masterSwathList + slaveSwathList)))

    #catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)
    baselineDir = os.path.dirname(inps.baselineFile)
    if not os.path.exists(baselineDir):
        os.makedirs(baselineDir)

    f = open(inps.baselineFile, 'w')

    for swath in swathList:

        masterxml = os.path.join(inps.master, 'IW{0}.xml'.format(swath))
        slavexml = os.path.join(inps.slave, 'IW{0}.xml'.format(swath))

        if os.path.exists(masterxml) and os.path.exists(slavexml):

            master = ut.loadProduct(
                os.path.join(inps.master, 'IW{0}.xml'.format(swath)))
            slave = ut.loadProduct(
                os.path.join(inps.slave, 'IW{0}.xml'.format(swath)))

            minMaster = master.bursts[0].burstNumber
            maxMaster = master.bursts[-1].burstNumber

            minSlave = slave.bursts[0].burstNumber
            maxSlave = slave.bursts[-1].burstNumber

            minBurst = max(minSlave, minMaster)
            maxBurst = min(maxSlave, maxMaster)
            print('minSlave,maxSlave', minSlave, maxSlave)
            print('minMaster,maxMaster', minMaster, maxMaster)
            print('minBurst, maxBurst: ', minBurst, maxBurst)
            refElp = Planet(pname='Earth').ellipsoid
            Bpar = []
            Bperp = []

            for ii in range(minBurst, maxBurst + 1):

                ###Bookkeeping
                #commonBurstStartMasterIndex[swath-1] = minBurst
                #commonBurstStartSlaveIndex[swath-1]  = commonSlaveIndex
                #numberOfCommonBursts[swath-1] = numberCommon

                #catalog.addItem('IW-{0} Number of bursts in master'.format(swath), master.numberOfBursts, 'baseline')
                #catalog.addItem('IW-{0} First common burst in master'.format(swath), minBurst, 'baseline')
                #catalog.addItem('IW-{0} Last common burst in master'.format(swath), maxBurst, 'baseline')
                #catalog.addItem('IW-{0} Number of bursts in slave'.format(swath), slave.numberOfBursts, 'baseline')
                #catalog.addItem('IW-{0} First common burst in slave'.format(swath), minBurst + burstOffset, 'baseline')
                #catalog.addItem('IW-{0} Last common burst in slave'.format(swath), maxBurst + burstOffset, 'baseline')
                #catalog.addItem('IW-{0} Number of common bursts'.format(swath), numberCommon, 'baseline')

                #refElp = Planet(pname='Earth').ellipsoid
                #Bpar = []
                #Bperp = []

                #for boff in [0, numberCommon-1]:
                ###Baselines at top of common bursts
                mBurst = master.bursts[ii - minMaster]
                sBurst = slave.bursts[ii - minSlave]

                ###Target at mid range
                tmid = mBurst.sensingMid
                rng = mBurst.midRange
                masterSV = mBurst.orbit.interpolate(tmid, method='hermite')
                target = mBurst.orbit.rdr2geo(tmid, rng)

                slvTime, slvrng = sBurst.orbit.geo2rdr(target)
                slaveSV = sBurst.orbit.interpolateOrbit(slvTime,
                                                        method='hermite')

                targxyz = np.array(
                    refElp.LLH(target[0], target[1],
                               target[2]).ecef().tolist())
                mxyz = np.array(masterSV.getPosition())
                mvel = np.array(masterSV.getVelocity())
                sxyz = np.array(slaveSV.getPosition())

                aa = np.linalg.norm(sxyz - mxyz)
                costheta = (rng * rng + aa * aa - slvrng * slvrng) / (2. *
                                                                      rng * aa)

                Bpar.append(aa * costheta)

                perp = aa * np.sqrt(1 - costheta * costheta)
                direction = np.sign(
                    np.dot(np.cross(targxyz - mxyz, sxyz - mxyz), mvel))
                Bperp.append(direction * perp)

                #catalog.addItem('IW-{0} Bpar at midrange for first common burst'.format(swath), Bpar[0], 'baseline')
                #catalog.addItem('IW-{0} Bperp at midrange for first common burst'.format(swath), Bperp[0], 'baseline')
                #catalog.addItem('IW-{0} Bpar at midrange for last common burst'.format(swath), Bpar[1], 'baseline')
                #catalog.addItem('IW-{0} Bperp at midrange for last common burst'.format(swath), Bperp[1], 'baseline')

            print('Bprep: ', Bperp)
            print('Bpar: ', Bpar)
            f.write('swath: IW{0}'.format(swath) + '\n')
            f.write('Bperp (average): ' + str(np.mean(Bperp)) + '\n')
            f.write('Bpar (average): ' + str(np.mean(Bpar)) + '\n')

    f.close()
Beispiel #25
0
def main(iargs=None):
    '''Compute baseline.
    '''
    inps = cmdLineParse(iargs)
    from isceobj.Planet.Planet import Planet
    import numpy as np

    referenceSwathList = ut.getSwathList(inps.reference)
    secondarySwathList = ut.getSwathList(inps.secondary)
    swathList = list(sorted(set(referenceSwathList + secondarySwathList)))

    #catalog = isceobj.Catalog.createCatalog(self._insar.procDoc.name)
    baselineDir = os.path.dirname(inps.baselineFile)
    if baselineDir != '':
        os.makedirs(baselineDir, exist_ok=True)

    referenceswaths = []
    secondaryswaths = []
    for swath in swathList:
        referencexml = os.path.join(inps.reference, 'IW{0}.xml'.format(swath))
        secondaryxml = os.path.join(inps.secondary, 'IW{0}.xml'.format(swath))

        if os.path.exists(referencexml) and os.path.exists(secondaryxml):

            reference = ut.loadProduct(
                os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))
            secondary = ut.loadProduct(
                os.path.join(inps.secondary, 'IW{0}.xml'.format(swath)))

            referenceswaths.append(reference)
            secondaryswaths.append(secondary)

    refElp = Planet(pname='Earth').ellipsoid
    mStartingRange = min([x.startingRange for x in referenceswaths])
    mFarRange = max([x.farRange for x in referenceswaths])
    mSensingStart = min([x.sensingStart for x in referenceswaths])
    mSensingStop = max([x.sensingStop for x in referenceswaths])
    mOrb = getMergedOrbit(referenceswaths)

    dr = referenceswaths[0].bursts[0].rangePixelSize
    dt = referenceswaths[0].bursts[0].azimuthTimeInterval

    nPixels = int(np.round((mFarRange - mStartingRange) / dr)) + 1
    nLines = int(np.round(
        (mSensingStop - mSensingStart).total_seconds() / dt)) + 1

    sOrb = getMergedOrbit(secondaryswaths)

    rangeLimits = mFarRange - mStartingRange
    nRange = int(np.ceil(rangeLimits / 7000.))
    slantRange = mStartingRange + np.arange(nRange) * rangeLimits / (nRange -
                                                                     1.0)

    azimuthLimits = (mSensingStop - mSensingStart).total_seconds()
    nAzimuth = int(np.ceil(azimuthLimits))
    azimuthTime = [
        mSensingStart + datetime.timedelta(seconds=x * azimuthLimits /
                                           (nAzimuth - 1.0))
        for x in range(nAzimuth)
    ]

    Bpar = np.zeros(nRange, dtype=np.float32)
    Bperp = np.zeros(nRange, dtype=np.float32)

    fid = open(inps.baselineFile, 'wb')
    print('Baseline file {0} dims: {1}L x {2}P'.format(inps.baselineFile,
                                                       nAzimuth, nRange))

    if inps.reference == inps.secondary:
        Bperp = np.zeros((nAzimuth, nRange), dtype=np.float32)
        Bperp.tofile(fid)
    else:
        for ii, taz in enumerate(azimuthTime):

            referenceSV = mOrb.interpolate(taz, method='hermite')
            mxyz = np.array(referenceSV.getPosition())
            mvel = np.array(referenceSV.getVelocity())

            for jj, rng in enumerate(slantRange):

                target = mOrb.rdr2geo(taz, rng)

                targxyz = np.array(
                    refElp.LLH(target[0], target[1],
                               target[2]).ecef().tolist())
                slvTime, slvrng = sOrb.geo2rdr(target)

                secondarySV = sOrb.interpolateOrbit(slvTime, method='hermite')

                sxyz = np.array(secondarySV.getPosition())

                aa = np.linalg.norm(sxyz - mxyz)
                costheta = (rng * rng + aa * aa - slvrng * slvrng) / (2. *
                                                                      rng * aa)

                Bpar[jj] = aa * costheta

                perp = aa * np.sqrt(1 - costheta * costheta)
                direction = np.sign(
                    np.dot(np.cross(targxyz - mxyz, sxyz - mxyz), mvel))
                Bperp[jj] = direction * perp

            Bperp.tofile(fid)

    fid.close()

    ####Write XML
    img = isceobj.createImage()
    img.setFilename(inps.baselineFile)
    img.bands = 1
    img.scheme = 'BIP'
    img.dataType = 'FLOAT'
    img.setWidth(nRange)
    img.setAccessMode('READ')
    img.setLength(nAzimuth)
    img.renderHdr()
    img.renderVRT()

    ###Create oversampled VRT file
    cmd = 'gdal_translate -of VRT -ot Float32 -r bilinear -outsize {xsize} {ysize} {infile}.vrt {infile}.full.vrt'.format(
        xsize=nPixels, ysize=nLines, infile=inps.baselineFile)

    status = os.system(cmd)
    if status:
        raise Exception('cmd: {0} Failed'.format(cmd))
Beispiel #26
0
def runGeocode(inps, prodlist, bbox, demfilename, is_offset_mode=False):
    '''Generalized geocoding of all the files listed above.'''
    from isceobj.Catalog import recordInputsAndOutputs
    logger.info("Geocoding Image")
    #insar = self._insar

    #if (not self.doInSAR) and (not is_offset_mode):
    #    print('Skipping geocoding as InSAR processing has not been requested ....')
    #    return

    #elif (not self.doDenseOffsets) and (is_offset_mode):
    #    print('Skipping geocoding as Dense Offsets has not been requested ....')
    #    return


    if isinstance(prodlist,str):
        from isceobj.Util.StringUtils import StringUtils as SU
        tobeGeocoded = SU.listify(prodlist)
    else:
        tobeGeocoded = prodlist

    
    #remove files that have not been processed
    newlist=[]
    for toGeo in tobeGeocoded:
        if os.path.exists(toGeo):
            newlist.append(toGeo)

    
    tobeGeocoded = newlist
    print('Number of products to geocode: ', len(tobeGeocoded))

    if len(tobeGeocoded) == 0:
        print('No products found to geocode')
        return


    #swathList = self._insar.getValidSwathList(self.swaths)

    referenceSwathList = ut.getSwathList(inps.reference)
    secondarySwathList = ut.getSwathList(inps.secondary)
    swathList = list(sorted(set(referenceSwathList+secondarySwathList)))

    frames = []
    for swath in swathList:
        #topReference = ut.loadProduct(os.path.join(inps.reference , 'IW{0}.xml'.format(swath)))
        referenceProduct = ut.loadProduct(os.path.join(inps.secondary , 'IW{0}.xml'.format(swath)))
        #referenceProduct = insar.loadProduct( os.path.join(insar.fineCoregDirname, 'IW{0}.xml'.format(swath)))
        frames.append(referenceProduct)

    orb = getMergedOrbit(frames)

    if bbox is None:
        bboxes = []

        for frame in frames:
            bboxes.append(frame.getBbox())

        snwe = [min([x[0] for x in bboxes]),
                max([x[1] for x in bboxes]),
                min([x[2] for x in bboxes]),
                max([x[3] for x in bboxes])]

    else:
        snwe = list(bbox)
        if len(snwe) != 4:
            raise ValueError('Bounding box should be a list/tuple of length 4')


    ###Identify the 4 corners and dimensions
    topSwath = min(frames, key = lambda x: x.sensingStart)
    leftSwath = min(frames, key = lambda x: x.startingRange)


    ####Get required values from product
    burst = frames[0].bursts[0]
    t0 = topSwath.sensingStart
    dtaz = burst.azimuthTimeInterval
    r0 = leftSwath.startingRange
    dr = burst.rangePixelSize
    wvl = burst.radarWavelength
    planet = Planet(pname='Earth')
    
    ###Setup DEM
    #demfilename = self.verifyGeocodeDEM()
    demImage = isceobj.createDemImage()
    demImage.load(demfilename + '.xml')

    ###Catalog for tracking
    #catalog = isceobj.Catalog.createCatalog(insar.procDoc.name)
    #catalog.addItem('Dem Used', demfilename, 'geocode')

    #####Geocode one by one
    first = False
    ge = Geocodable()
    for prod in tobeGeocoded:
        objGeo = createGeozero()
        objGeo.configure()

        ####IF statements to check for user configuration
        objGeo.snwe = snwe
        objGeo.demImage = demImage
        objGeo.demCropFilename = os.path.join(os.path.dirname(demfilename), "dem.crop") 
        if is_offset_mode:  ### If using topsOffsetApp, image has been "pre-looked" by the
            objGeo.numberRangeLooks = inps.skipwidth    ### skips in runDenseOffsets
            objGeo.numberAzimuthLooks = inps.skiphgt
        else:
            objGeo.numberRangeLooks = inps.numberRangeLooks
            objGeo.numberAzimuthLooks = inps.numberAzimuthLooks
        objGeo.lookSide = -1 #S1A is currently right looking only

        #create the instance of the input image and the appropriate
        #geocode method
        inImage,method = ge.create(prod)
        objGeo.method = method

        objGeo.slantRangePixelSpacing = dr
        objGeo.prf = 1.0 / dtaz
        objGeo.orbit = orb 
        objGeo.width = inImage.getWidth()
        objGeo.length = inImage.getLength()
        objGeo.dopplerCentroidCoeffs = [0.]
        objGeo.radarWavelength = wvl

        if is_offset_mode:  ### If using topsOffsetApp, as above, the "pre-looking" adjusts the range/time start
            objGeo.rangeFirstSample = r0 + (inps.offset_left-1) * dr
            objGeo.setSensingStart( t0 + datetime.timedelta(seconds=((inps.offset_top-1)*dtaz)))
        else:
            objGeo.rangeFirstSample = r0 + ((inps.numberRangeLooks-1)/2.0) * dr
            objGeo.setSensingStart( t0 + datetime.timedelta(seconds=(((inps.numberAzimuthLooks-1)/2.0)*dtaz)))
        objGeo.wireInputPort(name='dem', object=demImage)
        objGeo.wireInputPort(name='planet', object=planet)
        objGeo.wireInputPort(name='tobegeocoded', object=inImage)

        objGeo.geocode()

        print('Geocoding: ', inImage.filename, 'geocode')
        print('Output file: ', inImage.filename + '.geo', 'geocode')
        print('Width', inImage.width, 'geocode')
        print('Length', inImage.length, 'geocode')
        print('Range looks', inps.numberRangeLooks, 'geocode')
        print('Azimuth looks', inps.numberAzimuthLooks, 'geocode')
        print('South' , objGeo.minimumGeoLatitude, 'geocode')
        print('North', objGeo.maximumGeoLatitude, 'geocode')
        print('West', objGeo.minimumGeoLongitude, 'geocode')
        print('East', objGeo.maximumGeoLongitude, 'geocode')
Beispiel #27
0
def main(iargs=None):
    '''
    Merge burst products to make it look like stripmap.
    Currently will merge interferogram, lat, lon, z and los.
    '''
    inps=cmdLineParse(iargs)
    virtual = inps.useVirtualFiles
     
    swathList = ut.getSwathList(inps.master)
    referenceFrames = [] 
    frames=[]
    fileList = []
    namePattern = inps.namePattern.split('*')

    for swath in swathList:
        ifg = ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))
        if inps.stack:
            stack =  ut.loadProduct(os.path.join(inps.stack , 'IW{0}.xml'.format(swath)))
        if inps.isaligned:
            reference = ifg.reference
        else:
            reference = ifg

        minBurst = ifg.bursts[0].burstNumber
        maxBurst = ifg.bursts[-1].burstNumber


        if minBurst==maxBurst:
            print('Skipping processing of swath {0}'.format(swath))
            continue
        
        if inps.stack:
            minStack = stack.bursts[0].burstNumber
            print('Updating the valid region of each burst to the common valid region of the stack')
        ####Updating the valid region of each burst to the common valid region of the stack
            for ii in range(minBurst, maxBurst + 1):

                ifg.bursts[ii-minBurst].firstValidLine = stack.bursts[ii-minStack].firstValidLine
                ifg.bursts[ii-minBurst].firstValidSample = stack.bursts[ii-minStack].firstValidSample
                ifg.bursts[ii-minBurst].numValidLines = stack.bursts[ii-minStack].numValidLines
                ifg.bursts[ii-minBurst].numValidSamples = stack.bursts[ii-minStack].numValidSamples

        frames.append(ifg)
        referenceFrames.append(reference)
        print('bursts: ', minBurst, maxBurst)
        fileList.append([os.path.join(inps.dirname, 'IW{0}'.format(swath), namePattern[0] + '_%02d.%s'%(x,namePattern[1])) for x in range(minBurst, maxBurst+1)])

    mergedir = os.path.dirname(inps.outfile)
    os.makedirs(mergedir, exist_ok=True)

    suffix = '.full'
    if (inps.numberRangeLooks == 1) and (inps.numberAzimuthLooks==1):
        suffix=''


    ####Virtual flag is ignored for multi-swath data
    
        if (not virtual):
            print('User requested for multi-swath stitching.')
            print('Virtual files are the only option for this.')
            print('Proceeding with virtual files.')

    mergeBurstsVirtual(frames, referenceFrames, fileList, inps.outfile+suffix, validOnly=inps.validOnly)

    if (not virtual):
        print('writing merged file to disk ...')
        cmd = 'gdal_translate -of ENVI -co INTERLEAVE=BIL ' + inps.outfile + suffix + '.vrt ' + inps.outfile + suffix 
        os.system(cmd)

    print(inps.multilook)
    if inps.multilook:
        multilook(inps.outfile+suffix, outname = inps.outfile, 
            alks = inps.numberAzimuthLooks, rlks=inps.numberRangeLooks,
            multilook_tool=inps.multilookTool, no_data=inps.noData)

    else:
        print('Skipping multi-looking ....')
Beispiel #28
0
def main(iargs=None):
    '''Create overlap interferograms.
    '''
    inps=cmdLineParse(iargs)

    if inps.overlap:
        masterSwathList = ut.getSwathList(os.path.join(inps.master, 'overlap'))
        slaveSwathList = ut.getSwathList(os.path.join(inps.slave, 'overlap'))
    else:
        masterSwathList = ut.getSwathList(inps.master)
        slaveSwathList = ut.getSwathList(inps.slave)
    swathList = list(sorted(set(masterSwathList+slaveSwathList)))

    for swath in swathList:
        IWstr = 'IW{0}'.format(swath)
        if inps.overlap:
            ifgdir = os.path.join(inps.interferogram, 'overlap', 'IW{0}'.format(swath))
        else:
            ifgdir = os.path.join(inps.interferogram, 'IW{0}'.format(swath))
            
        if not os.path.exists(ifgdir):
                os.makedirs(ifgdir)

    ####Load relevant products
        if inps.overlap:
            topMaster = ut.loadProduct(os.path.join(inps.master , 'overlap','IW{0}_top.xml'.format(swath)))
            botMaster = ut.loadProduct(os.path.join(inps.master ,'overlap', 'IW{0}_bottom.xml'.format(swath)))
            topCoreg = ut.loadProduct(os.path.join(inps.slave, 'overlap', 'IW{0}_top.xml'.format(swath)))
            botCoreg = ut.loadProduct(os.path.join(inps.slave, 'overlap', 'IW{0}_bottom.xml'.format(swath)))

        else:
            topMaster = ut.loadProduct(os.path.join(inps.master , 'IW{0}.xml'.format(swath)))
            topCoreg = ut.loadProduct(os.path.join(inps.slave , 'IW{0}.xml'.format(swath)))

        if inps.overlap:
            coregdir = os.path.join(inps.slave, 'overlap', 'IW{0}'.format(swath))
        else:
            coregdir = os.path.join(inps.slave,'IW{0}'.format(swath))
    
        topIfg = ut.coregSwathSLCProduct()
        topIfg.configure()

        if inps.overlap:
            botIfg = ut.coregSwathSLCProduct()
            botIfg.configure()

        minMaster = topMaster.bursts[0].burstNumber
        maxMaster = topMaster.bursts[-1].burstNumber

        minSlave = topCoreg.bursts[0].burstNumber
        maxSlave = topCoreg.bursts[-1].burstNumber

        minBurst = max(minSlave, minMaster)
        maxBurst = min(maxSlave, maxMaster)
        print ('minSlave,maxSlave',minSlave, maxSlave)
        print ('minMaster,maxMaster',minMaster, maxMaster)
        print ('minBurst, maxBurst: ', minBurst, maxBurst)

        for ii in range(minBurst, maxBurst + 1):

            ####Process the top bursts
            master = topMaster.bursts[ii-minMaster]
            slave  = topCoreg.bursts[ii-minSlave]

            print('matching burst numbers: ',master.burstNumber, slave.burstNumber)

            mastername = master.image.filename
            slavename = slave.image.filename

            if inps.overlap:
                rdict = { 'rangeOff1' : os.path.join(inps.master, 'overlap', IWstr, 'range_top_%02d_%02d.off'%(ii,ii+1)),
                     'rangeOff2' : os.path.join(inps.slave, 'overlap', IWstr, 'range_top_%02d_%02d.off'%(ii,ii+1)),
                     'azimuthOff': os.path.join(inps.slave, 'overlap', IWstr, 'azimuth_top_%02d_%02d.off'%(ii,ii+1))}

                intname = os.path.join(ifgdir, '%s_top_%02d_%02d.int'%(inps.intprefix,ii,ii+1))
        
            else:

                rdict = {'rangeOff1' : os.path.join(inps.master, IWstr, 'range_%02d.off'%(ii)),
                     'rangeOff2' : os.path.join(inps.slave, IWstr, 'range_%02d.off'%(ii)),
                     'azimuthOff1': os.path.join(inps.slave, IWstr, 'azimuth_%02d.off'%(ii))}
            
                intname = os.path.join(ifgdir, '%s_%02d.int'%(inps.intprefix,ii))


            ut.adjustCommonValidRegion(master,slave)
            fact = 4 * np.pi * slave.rangePixelSize / slave.radarWavelength
            intimage = multiply(mastername, slavename, intname,
                        rdict['rangeOff1'], rdict['rangeOff2'], fact, master, flatten=inps.flatten)

            burst = copy.deepcopy(master)
            burst.image = intimage
            burst.burstNumber = ii
            topIfg.bursts.append(burst)


            if inps.overlap:
                ####Process the bottom bursts
                master = botMaster.bursts[ii-minMaster]
                slave = botCoreg.bursts[ii-minSlave]


                mastername =  master.image.filename
                slavename = slave.image.filename
#            rdict = {'rangeOff' : os.path.join(coregdir, 'range_bot_%02d_%02d.off'%(ii,ii+1)),
#                   'azimuthOff': os.path.join(coregdir, 'azimuth_bot_%02d_%02d.off'%(ii,ii+1))}

                rdict = { 'rangeOff1' : os.path.join(inps.master, 'overlap', IWstr, 'range_bot_%02d_%02d.off'%(ii,ii+1)),
                     'rangeOff2' : os.path.join(inps.slave, 'overlap', IWstr, 'range_bot_%02d_%02d.off'%(ii,ii+1)),
                    'azimuthOff': os.path.join(inps.slave, 'overlap', IWstr, 'azimuth_bot_%02d_%02d.off'%(ii,ii+1))}


                print ('rdict: ', rdict)

                ut.adjustCommonValidRegion(master,slave)
                intname = os.path.join(ifgdir, '%s_bot_%02d_%02d.int'%(inps.intprefix,ii,ii+1))
                fact = 4 * np.pi * slave.rangePixelSize / slave.radarWavelength

            #intimage = multiply(mastername, slavename, intname,
            #        rdict['rangeOff'], fact, master, flatten=True)

                intimage = multiply(mastername, slavename, intname,
                        rdict['rangeOff1'], rdict['rangeOff2'], fact, master, flatten=inps.flatten)

                burst = copy.deepcopy(master)
                burst.burstNumber = ii
                burst.image = intimage
                botIfg.bursts.append(burst)


        topIfg.numberOfBursts = len(topIfg.bursts)
        if hasattr(topCoreg, 'reference'):
            topIfg.reference = topCoreg.reference
        else:
            topIfg.reference = topMaster.reference

        print('Type: ',type(topIfg.reference))

        if inps.overlap:
            ut.saveProduct(topIfg, ifgdir +  '_top.xml')
            botIfg.numberOfBursts = len(botIfg.bursts)
            botIfg.reference = botCoreg.reference
            print(botIfg.reference)
            ut.saveProduct(botIfg, ifgdir + '_bottom.xml')
        else:
            ut.saveProduct(topIfg, ifgdir + '.xml')    
Beispiel #29
0
def main(iargs=None):
    '''
    Create coregistered overlap secondarys.
    '''
    inps = cmdLineParse(iargs)
    referenceSwathList = ut.getSwathList(inps.reference)
    secondarySwathList = ut.getSwathList(inps.secondary)
    swathList = list(sorted(set(referenceSwathList + secondarySwathList)))

    for swath in swathList:

        ####Load secondary metadata
        reference = ut.loadProduct(
            os.path.join(inps.reference, 'IW{0}.xml'.format(swath)))
        secondary = ut.loadProduct(
            os.path.join(inps.secondary, 'IW{0}.xml'.format(swath)))
        if inps.overlap:
            referenceTop = ut.loadProduct(
                os.path.join(inps.reference, inps.overlapDir,
                             'IW{0}_top.xml'.format(swath)))
            referenceBottom = ut.loadProduct(
                os.path.join(inps.reference, inps.overlapDir,
                             'IW{0}_bottom.xml'.format(swath)))

        dt = secondary.bursts[0].azimuthTimeInterval
        dr = secondary.bursts[0].rangePixelSize

        if os.path.exists(str(inps.misreg_az)):
            with open(inps.misreg_az, 'r') as f:
                misreg_az = float(f.readline())
        else:
            misreg_az = 0.0

        if os.path.exists(str(inps.misreg_rng)):
            with open(inps.misreg_rng, 'r') as f:
                misreg_rg = float(f.readline())
        else:
            misreg_rg = 0.0

        ###Output directory for coregistered SLCs
        if not inps.overlap:
            outdir = os.path.join(inps.coreg, 'IW{0}'.format(swath))
            offdir = os.path.join(inps.coreg, 'IW{0}'.format(swath))
        else:
            outdir = os.path.join(inps.coreg, inps.overlapDir,
                                  'IW{0}'.format(swath))
            offdir = os.path.join(inps.coreg, inps.overlapDir,
                                  'IW{0}'.format(swath))
        os.makedirs(outdir, exist_ok=True)

        ####Indices w.r.t reference
        burstoffset, minBurst, maxBurst = reference.getCommonBurstLimits(
            secondary)
        secondaryBurstStart = minBurst + burstoffset
        secondaryBurstEnd = maxBurst

        relShifts = ut.getRelativeShifts(reference, secondary, minBurst,
                                         maxBurst, secondaryBurstStart)
        print('Shifts: ', relShifts)
        if inps.overlap:
            maxBurst = maxBurst - 1  ###For overlaps

        ####Can corporate known misregistration here

        apoly = Poly2D()
        apoly.initPoly(rangeOrder=0, azimuthOrder=0, coeffs=[[0.]])

        rpoly = Poly2D()
        rpoly.initPoly(rangeOrder=0, azimuthOrder=0, coeffs=[[0.]])

        #topCoreg = createTOPSSwathSLCProduct()
        topCoreg = ut.coregSwathSLCProduct()
        topCoreg.configure()

        if inps.overlap:
            botCoreg = ut.coregSwathSLCProduct()
            botCoreg.configure()

        for ii in range(minBurst, maxBurst):
            jj = secondaryBurstStart + ii - minBurst

            if inps.overlap:
                botBurst = referenceBottom.bursts[ii]
                topBurst = referenceTop.bursts[ii]
            else:
                topBurst = reference.bursts[ii]

            secBurst = secondary.bursts[jj]

            #####Top burst processing
            try:
                offset = relShifts[jj]
            except:
                raise Exception(
                    'Trying to access shift for secondary burst index {0}, which may not overlap with reference'
                    .format(jj))

            if inps.overlap:
                outname = os.path.join(
                    outdir, 'burst_top_%02d_%02d.slc' % (ii + 1, ii + 2))

                ####Setup initial polynomials
                ### If no misregs are given, these are zero
                ### If provided, can be used for resampling without running to geo2rdr again for fast results
                rdict = {
                    'azpoly':
                    apoly,
                    'rgpoly':
                    rpoly,
                    'rangeOff':
                    os.path.join(offdir,
                                 'range_top_%02d_%02d.off' % (ii + 1, ii + 2)),
                    'azimuthOff':
                    os.path.join(
                        offdir, 'azimuth_top_%02d_%02d.off' % (ii + 1, ii + 2))
                }

                ###For future - should account for azimuth and range misreg here .. ignoring for now.
                azCarrPoly, dpoly = secondary.estimateAzimuthCarrierPolynomials(
                    secBurst, offset=-1.0 * offset)
                rdict['carrPoly'] = azCarrPoly
                rdict['doppPoly'] = dpoly

                outimg = resampSecondary(topBurst, secBurst, rdict, outname,
                                         (not inps.noflat))

                copyBurst = copy.deepcopy(topBurst)
                ut.adjustValidSampleLine(copyBurst)
                copyBurst.image.filename = outimg.filename
                print('After: ', copyBurst.firstValidLine,
                      copyBurst.numValidLines)
                topCoreg.bursts.append(copyBurst)
                #######################################################

                secBurst = secondary.bursts[jj + 1]
                outname = os.path.join(
                    outdir, 'burst_bot_%02d_%02d.slc' % (ii + 1, ii + 2))

                ####Setup initial polynomials
                ### If no misregs are given, these are zero
                ### If provided, can be used for resampling without running to geo2rdr again for fast results
                rdict = {
                    'azpoly':
                    apoly,
                    'rgpoly':
                    rpoly,
                    'rangeOff':
                    os.path.join(offdir,
                                 'range_bot_%02d_%02d.off' % (ii + 1, ii + 2)),
                    'azimuthOff':
                    os.path.join(
                        offdir, 'azimuth_bot_%02d_%02d.off' % (ii + 1, ii + 2))
                }

                azCarrPoly, dpoly = secondary.estimateAzimuthCarrierPolynomials(
                    secBurst, offset=-1.0 * offset)
                rdict['carrPoly'] = azCarrPoly
                rdict['doppPoly'] = dpoly

                outimg = resampSecondary(botBurst, secBurst, rdict, outname,
                                         (not inps.noflat))

                copyBurst = copy.deepcopy(botBurst)
                ut.adjustValidSampleLine(copyBurst)
                copyBurst.image.filename = outimg.filename
                print('After: ', copyBurst.firstValidLine,
                      copyBurst.numValidLines)
                botCoreg.bursts.append(copyBurst)
            #######################################################

            else:
                outname = os.path.join(outdir, 'burst_%02d.slc' % (ii + 1))

                ####Setup initial polynomials
                ### If no misregs are given, these are zero
                ### If provided, can be used for resampling without running to geo2rdr again for fast results
                rdict = {
                    'azpoly':
                    apoly,
                    'rgpoly':
                    rpoly,
                    'rangeOff':
                    os.path.join(offdir, f'range{suffix}_{ii+1:02d}.off'),
                    'azimuthOff':
                    os.path.join(offdir, f'azimuth{suffix}_{ii+1:02d}.off')
                }

                ###For future - should account for azimuth and range misreg here .. ignoring for now.
                azCarrPoly, dpoly = secondary.estimateAzimuthCarrierPolynomials(
                    secBurst, offset=-1.0 * offset)
                rdict['carrPoly'] = azCarrPoly
                rdict['doppPoly'] = dpoly

                outimg = resampSecondary(topBurst, secBurst, rdict, outname,
                                         (not inps.noflat))
                minAz, maxAz, minRg, maxRg = ut.getValidLines(
                    secBurst,
                    rdict,
                    outname,
                    misreg_az=misreg_az - offset,
                    misreg_rng=misreg_rg)

                copyBurst = copy.deepcopy(topBurst)
                ut.adjustValidSampleLine_V2(copyBurst,
                                            secBurst,
                                            minAz=minAz,
                                            maxAz=maxAz,
                                            minRng=minRg,
                                            maxRng=maxRg)
                copyBurst.image.filename = outimg.filename
                print('After: ', copyBurst.firstValidLine,
                      copyBurst.numValidLines)
                topCoreg.bursts.append(copyBurst)

        #######################################################
        topCoreg.numberOfBursts = len(topCoreg.bursts)
        topCoreg.source = ut.asBaseClass(secondary)

        if inps.overlap:
            botCoreg.numberOfBursts = len(botCoreg.bursts)
            topCoreg.reference = ut.asBaseClass(referenceTop)
            botCoreg.reference = ut.asBaseClass(referenceBottom)
            botCoreg.source = ut.asBaseClass(secondary)
            ut.saveProduct(topCoreg, outdir + '_top.xml')
            ut.saveProduct(botCoreg, outdir + '_bottom.xml')

        else:
            topCoreg.reference = reference
            ut.saveProduct(topCoreg, outdir + '.xml')
Beispiel #30
0
def main(iargs=None):
    '''
    Create coregistered overlap secondarys.
    '''
    inps = cmdLineParse(iargs)
    referenceSwathList = ut.getSwathList(inps.reference)
    secondarySwathList = ut.getSwathList(inps.secondary)

    swathList = list(sorted(set(referenceSwathList+secondarySwathList)))

    #if os.path.abspath(inps.reference) == os.path.abspath(inps.secondary):
    #    print('secondary is the same as reference, only performing subband filtering')

    for swath in swathList:
    
        ####Load secondary metadata
        reference = ut.loadProduct( os.path.join(inps.reference , 'IW{0}.xml'.format(swath)))
        secondary = ut.loadProduct( os.path.join(inps.secondary , 'IW{0}.xml'.format(swath)))


        if os.path.exists(str(inps.misreg_az)):
             with open(inps.misreg_az, 'r') as f:
                misreg_az = float(f.readline())
        else:
             misreg_az = 0.0

        if os.path.exists(str(inps.misreg_rng)):
             with open(inps.misreg_rng, 'r') as f:
                misreg_rg = float(f.readline())
        else:
             misreg_rg = 0.0

        ###Output directory for coregistered SLCs
        outdir = os.path.join(inps.coreg,'IW{0}'.format(swath))
        offdir = os.path.join(inps.coreg,'IW{0}'.format(swath))
        os.makedirs(outdir, exist_ok=True)

    
        ####Indices w.r.t reference
        burstoffset, minBurst, maxBurst = reference.getCommonBurstLimits(secondary)
        secondaryBurstStart = minBurst +  burstoffset
        secondaryBurstEnd = maxBurst
    
        relShifts = ut.getRelativeShifts(reference, secondary, minBurst, maxBurst, secondaryBurstStart)

        print('Shifts: ', relShifts)
    
        ####Can corporate known misregistration here
    
        apoly = Poly2D()
        apoly.initPoly(rangeOrder=0,azimuthOrder=0,coeffs=[[0.]])
    
        rpoly = Poly2D()
        rpoly.initPoly(rangeOrder=0,azimuthOrder=0,coeffs=[[0.]])

    
        #slvCoreg = createTOPSSwathSLCProduct()
        slvCoreg = ut.coregSwathSLCProduct()
        slvCoreg.configure()


        for ii in range(minBurst, maxBurst):

            outname = os.path.join(outdir, 'burst_%02d.slc'%(ii+1))  
            outnameLower = os.path.splitext(outname)[0]+'_lower.slc'
            outnameUpper = os.path.splitext(outname)[0]+'_upper.slc'
            if os.path.exists(outnameLower) and os.path.exists(outnameLower+'.vrt') and os.path.exists(outnameLower+'.xml') and \
               os.path.exists(outnameUpper) and os.path.exists(outnameUpper+'.vrt') and os.path.exists(outnameUpper+'.xml'):
                print('burst %02d already processed, skip...'%(ii+1))
                continue

            jj = secondaryBurstStart + ii - minBurst

            masBurst = reference.bursts[ii]
            slvBurst = secondary.bursts[jj]

            #####Top burst processing
            try:
                offset = relShifts[jj]
            except:
                raise Exception('Trying to access shift for secondary burst index {0}, which may not overlap with reference'.format(jj))

        
            ####Setup initial polynomials
            ### If no misregs are given, these are zero
            ### If provided, can be used for resampling without running to geo2rdr again for fast results
            rdict = {'azpoly' : apoly,
                 'rgpoly' : rpoly,
                  'rangeOff' : os.path.join(offdir, 'range_%02d.off'%(ii+1)),
                  'azimuthOff': os.path.join(offdir, 'azimuth_%02d.off'%(ii+1))}
                 

            ###For future - should account for azimuth and range misreg here .. ignoring for now.
            azCarrPoly, dpoly = secondary.estimateAzimuthCarrierPolynomials(slvBurst, offset = -1.0 * offset)
    
            rdict['carrPoly'] = azCarrPoly
            rdict['doppPoly'] = dpoly
    

            #subband filtering
            from Stack import ionParam
            from isceobj.Constants import SPEED_OF_LIGHT
            rangeSamplingRate = SPEED_OF_LIGHT / (2.0 * slvBurst.rangePixelSize)

            ionParamObj=ionParam()
            ionParamObj.configure()
            lower_tmpfile = os.path.splitext(slvBurst.image.filename)[0]+'_lower_tmp.slc'
            upper_tmpfile = os.path.splitext(slvBurst.image.filename)[0]+'_upper_tmp.slc'
            outputfile = [lower_tmpfile, upper_tmpfile]
            bw = [ionParamObj.rgBandwidthSub / rangeSamplingRate, ionParamObj.rgBandwidthSub / rangeSamplingRate]
            bc = [-ionParamObj.rgBandwidthForSplit / 3.0 / rangeSamplingRate, ionParamObj.rgBandwidthForSplit / 3.0 / rangeSamplingRate]
            rgRef = ionParamObj.rgRef
            subband(slvBurst, 2, outputfile, bw, bc, rgRef, True)

            #resampling
            slvBurst.radarWavelength = ionParamObj.radarWavelengthLower
            slvBurst.image.filename = lower_tmpfile
            outnameSubband = outnameLower
            outimg = resampSecondary(masBurst, slvBurst, rdict, outnameSubband, (not inps.noflat))

            slvBurst.radarWavelength = ionParamObj.radarWavelengthUpper
            slvBurst.image.filename = upper_tmpfile
            outnameSubband = outnameUpper
            outimg = resampSecondary(masBurst, slvBurst, rdict, outnameSubband, (not inps.noflat))

            #remove original subband images
            os.remove(lower_tmpfile)
            os.remove(lower_tmpfile+'.vrt')
            os.remove(lower_tmpfile+'.xml')

            os.remove(upper_tmpfile)
            os.remove(upper_tmpfile+'.vrt')
            os.remove(upper_tmpfile+'.xml')