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)
Beispiel #2
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)))
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 #4
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')
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 #6
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 #7
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 #8
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)