Ejemplo n.º 1
0
def firstPassCommandLine():
    '''
    Take a first parse at command line parsing.
    Read only the basic required fields
    '''

    #####Create the generic parser to get equation and output format first
    parser = argparse.ArgumentParser(description='ISCE Band math calculator.',
            formatter_class=IML.customArgparseFormatter)

#    help_parser = subparser.add_
    parser.add_argument('-H','--hh', nargs=0, action=customArgparseAction,
            help='Display detailed help information.')
    parser.add_argument('-e','--eval', type=str, required=True, action='store',
            help='Expression to evaluate.', dest='equation')
    parser.add_argument('-o','--out', type=str, default=None, action='store',
            help='Name of the output file', dest='out')
    parser.add_argument('-s','--scheme',type=str, default='BSQ', action='store',
            help='Output file format.', dest='scheme')
    parser.add_argument('-t','--type', type=str, default='float', action='store',
            help='Output data type.', dest='dtype')
    parser.add_argument('-d','--debug', action='store_true', default=False,
            help='Print debugging statements', dest='debug')
    parser.add_argument('-n','--noxml', action='store_true', default=False,
            help='Do not create an ISCE XML file for the output.', dest='noxml')

    #######Parse equation and output format first
    args, files = parser.parse_known_args()

    #####Check the output scheme for errors
    if args.scheme.upper() not in ['BSQ', 'BIL', 'BIP']:
        raise IOError('Unknown output scheme: %s'%(args.scheme))
    iMath['outScheme'] = args.scheme.upper()

    npType = IML.NUMPY_type(args.dtype)
    iMath['outType'] = npType

    return args, files
Ejemplo n.º 2
0
def mergeBursts(frame, fileList, outfile,
        method='top'):
    '''
    Merge burst products into single file.
    Simple numpy based stitching
    '''

    ###Check against metadata
    if frame.numberOfBursts != len(fileList):
        print('Warning : Number of burst products does not appear to match number of bursts in metadata')


    t0 = frame.bursts[0].sensingStart
    dt = frame.bursts[0].azimuthTimeInterval
    width = frame.bursts[0].numberOfSamples

    #######
    tstart = frame.bursts[0].sensingStart 
    tend = frame.bursts[-1].sensingStop
    nLines = int( np.round((tend - tstart).total_seconds() / dt)) + 1
    print('Expected total nLines: ', nLines)


    img = isceobj.createImage()
    img.load( fileList[0] + '.xml')
    bands = img.bands
    scheme = img.scheme
    npType = IML.NUMPY_type(img.dataType)

    azMasterOff = []
    for index in range(frame.numberOfBursts):
        burst = frame.bursts[index]
        soff = burst.sensingStart + datetime.timedelta(seconds = (burst.firstValidLine*dt)) 
        start = int(np.round((soff - tstart).total_seconds() / dt))
        end = start + burst.numValidLines

        azMasterOff.append([start,end])

        print('Burst: ', index, [start,end])

        if index == 0:
            linecount = start

    outMap = IML.memmap(outfile, mode='write', nchannels=bands,
            nxx=width, nyy=nLines, scheme=scheme, dataType=npType)

    for index in range(frame.numberOfBursts):
        curBurst = frame.bursts[index]
        curLimit = azMasterOff[index]

        curMap = IML.mmapFromISCE(fileList[index], logging)

        #####If middle burst
        if index > 0:
            topBurst = frame.bursts[index-1]
            topLimit = azMasterOff[index-1]
            topMap = IML.mmapFromISCE(fileList[index-1], logging)

            olap = topLimit[1] - curLimit[0]

            print("olap: ", olap)

            if olap <= 0:
                raise Exception('No Burst Overlap')


            for bb in range(bands):
                topData =  topMap.bands[bb][topBurst.firstValidLine: topBurst.firstValidLine + topBurst.numValidLines,:]

                curData =  curMap.bands[bb][curBurst.firstValidLine: curBurst.firstValidLine + curBurst.numValidLines,:]

                im1 = topData[-olap:,:]
                im2 = curData[:olap,:]

                if method=='avg':
                    data = 0.5*(im1 + im2)
                elif method == 'top':
                    data = im1
                elif method == 'bot':
                    data = im2
                else:
                    raise Exception('Method should be top/bot/avg')

                outMap.bands[bb][linecount:linecount+olap,:] = data

            tlim = olap
        else:
            tlim = 0

        linecount += tlim
            
        if index != (frame.numberOfBursts-1):
            botBurst = frame.bursts[index+1]
            botLimit = azMasterOff[index+1]
            
            olap = curLimit[1] - botLimit[0]

            if olap < 0:
                raise Exception('No Burst Overlap')

            blim = botLimit[0] - curLimit[0]
        else:
            blim = curBurst.numValidLines
       
        lineout = blim - tlim
        
        for bb in range(bands):
            curData =  curMap.bands[bb][curBurst.firstValidLine: curBurst.firstValidLine + curBurst.numValidLines,:]
            outMap.bands[bb][linecount:linecount+lineout,:] = curData[tlim:blim,:] 

        linecount += lineout
        curMap = None
        topMap = None

    IML.renderISCEXML(outfile, bands,
            nLines, width,
            img.dataType, scheme)

    oimg = isceobj.createImage()
    oimg.load(outfile + '.xml')
    oimg.imageType = img.imageType
    oimg.renderHdr()
    try:
        outMap.bands[0].base.base.flush()
    except:
        pass
Ejemplo n.º 3
0
    def readIsce(self, dates, filesDir, igramName):
        '''
        Read files from ISCE software.

        Args:
            * dates             : Dates of the interferogram (list)
            * filesDir          : Files directory (str)
            * igramName         : Interferogram filename (str)
        '''

        # Import ISCE stuff
        import isce
        import isceobj
        from isceobj.Util.ImageUtil import ImageLib as IML

        #-------------------------------------------------
        # READ IGRAM

        # Igram filenames (wrapped, unwrapped and corrected)
        ifgInt = '{}/{}_{}/{}.int'.format(
            filesDir, dates[0], dates[1],
            os.path.splitext(os.path.basename(igramName))[0])
        ifgFile = '{}/{}_{}/{}'.format(filesDir, dates[0], dates[1], igramName)
        ifgFile_corrected = '{}_corrected{}'.format(
            os.path.splitext(ifgFile)[0],
            os.path.splitext(ifgFile)[1])

        # Igram.unw xml infos
        imgIfgFile = isceobj.createImage()
        imgIfgFile.load(ifgFile + '.xml')
        bands = imgIfgFile.bands
        length = imgIfgFile.getLength()
        width = imgIfgFile.getWidth()
        scheme = imgIfgFile.scheme

        # Igram.int xml infos
        imgInt = isceobj.createImage()
        imgInt.load(ifgInt + '.xml')
        bandsInt = imgInt.bands
        schemeInt = imgInt.scheme
        datatypeInt = IML.NUMPY_type(imgInt.dataType)

        # Igram not yet corrected
        if not os.path.exists(ifgFile_corrected):

            # Read igram.unw
            data = IML.memmap(ifgFile,
                              mode='readonly',
                              nchannels=bands,
                              nyy=length,
                              nxx=width,
                              scheme=scheme)

            # Create the corrected igram
            data_corrected = IML.memmap(ifgFile_corrected,
                                        mode='write',
                                        nchannels=bands,
                                        nyy=length,
                                        nxx=width,
                                        scheme=scheme)

            # Copy igram.unw in the new file
            data_corrected.bands[0][:, :] = data.bands[0][:, :]
            data_corrected.bands[1][:, :] = data.bands[1][:, :]

            # New xml infos
            data_correctedXml = isceobj.Image.createUnwImage()
            data_correctedXml.bands = 2
            data_correctedXml.setWidth(width)
            data_correctedXml.setLength(length)
            data_correctedXml.setFilename(ifgFile_corrected)
            data_correctedXml.renderHdr()
            data_correctedXml.renderVRT()

            # Flag
            flag_corr = True

        # Igram already corrected, start from it
        else:

            # Read igram.unw already corrected
            data = IML.memmap(ifgFile_corrected,
                              mode='readwrite',
                              nchannels=bands,
                              nyy=length,
                              nxx=width,
                              scheme=scheme)

            # Flag
            flag_corr = False

        # Read wrap igram where to compute misclosure
        data_int = IML.memmap(ifgInt,
                              mode='readonly',
                              nchannels=bandsInt,
                              dataType=datatypeInt,
                              nyy=length,
                              nxx=width,
                              scheme=schemeInt)

        #-------------------------------------------------
        # READ MASK

        # Initialize the mask
        mask = np.zeros((length, width))

        #-------------------------------------------------
        # SAVE

        # Save things
        if flag_corr:
            self.phase = data_corrected.bands[1]
        else:
            self.phase = data.bands[1]
        self.phase_int = data_int.bands[0]
        self.dates = dates
        self.igramsDir = filesDir
        self.igramName = igramName
        self.width = width
        self.length = length
        self.ifgFile_corrected = ifgFile_corrected

        # Close files
        del data
        del data_int

        # All done
        return