Exemple #1
0
def make_sb_matrix2(ifgdates):
    """
    Make small baseline incidence-like matrix.
    Composed of -1 at primary and 1 at secondary. (n_ifg, n_im)
    Unknown is cumulative displacement.
    """
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_im = len(imdates)
    n_ifg = len(ifgdates)

    A = np.zeros((n_ifg, n_im), dtype=np.int16)
    for ifgix, ifgd in enumerate(ifgdates):
        primarydate = ifgd[:8]
        primaryix = imdates.index(primarydate)
        secondarydate = ifgd[-8:]
        secondaryix = imdates.index(secondarydate)
        A[ifgix, primaryix] = -1
        A[ifgix, secondaryix] = 1
    return A
Exemple #2
0
def make_sb_matrix2(ifgdates):
    """
    Make small baseline incidence-like matrix.
    Composed of -1 at master and 1 at slave. (n_ifg, n_im)
    Unknown is cumulative displacement.
    """
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_im = len(imdates)
    n_ifg = len(ifgdates)

    A = np.zeros((n_ifg, n_im), dtype=np.int16)
    for ifgix, ifgd in enumerate(ifgdates):
        masterdate = ifgd[:8]
        masterix = imdates.index(masterdate)
        slavedate = ifgd[-8:]
        slaveix = imdates.index(slavedate)
        A[ifgix, masterix] = -1
        A[ifgix, slaveix] = 1
    return A
Exemple #3
0
def make_sb_matrix(ifgdates):
    """
    Make small baseline incidence-like matrix.
    Composed of 1 between primary and secondary. (n_ifg, n_im-1)
    Unknown is incremental displacement.
    """
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_im = len(imdates)
    n_ifg = len(ifgdates)

    G = np.zeros((n_ifg, n_im - 1), dtype=np.int16)
    for ifgix, ifgd in enumerate(ifgdates):
        primarydate = ifgd[:8]
        primaryix = imdates.index(primarydate)
        secondarydate = ifgd[-8:]
        secondaryix = imdates.index(secondarydate)
        G[ifgix, primaryix:secondaryix] = 1

    return G
Exemple #4
0
def make_sb_matrix(ifgdates):
    """
    Make small baseline incidence-like matrix.
    Composed of 1 between master and slave. (n_ifg, n_im-1)
    Unknown is incremental displacement.
    """
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_im = len(imdates)
    n_ifg = len(ifgdates)

    G = np.zeros((n_ifg, n_im - 1), dtype=np.int16)
    for ifgix, ifgd in enumerate(ifgdates):
        masterdate = ifgd[:8]
        masterix = imdates.index(masterdate)
        slavedate = ifgd[-8:]
        slaveix = imdates.index(slavedate)
        G[ifgix, masterix:slaveix] = 1

    return G
Exemple #5
0
def main(argv=None):
    
    #%% Check argv
    if argv == None:
        argv = sys.argv
        
    start = time.time()
    ver=1.2; date=20200228; author="Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date, author), flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])), flush=True)


    #%% Set default
    in_dir = []
    out_dir = []
    gacosdir = 'GACOS'
    resampleAlg = 'cubicspline'# None # 'cubic' 
    fillholeflag = False


    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:o:g:z:", ["fillhole", "help"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-i':
                in_dir = a
            elif o == '-o':
                out_dir = a
            elif o == '-z': ## for backward-compatible
                gacosdir = a
            elif o == '-g':
                gacosdir = a
            elif o == "--fillhole":
                fillholeflag = True

        if not in_dir:
            raise Usage('No input directory given, -i is not optional!')
        elif not os.path.isdir(in_dir):
            raise Usage('No {} dir exists!'.format(in_dir))
        elif not os.path.exists(os.path.join(in_dir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(in_dir))
        if not out_dir:
            raise Usage('No output directory given, -o is not optional!')
        if not os.path.isdir(gacosdir):
            raise Usage('No {} dir exists!'.format(gacosdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  "+str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2
    
    
    #%% Read data information
    ### Directory
    in_dir = os.path.abspath(in_dir)
    gacosdir = os.path.abspath(gacosdir)

    out_dir = os.path.abspath(out_dir)
    if not os.path.exists(out_dir): os.mkdir(out_dir)

    sltddir = os.path.join(os.path.join(out_dir),'sltd')
    if not os.path.exists(sltddir): os.mkdir(sltddir)

    ### Get general info
    mlipar = os.path.join(in_dir, 'slc.mli.par')
    width_unw = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length_unw = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))
    speed_of_light = 299792458 #m/s
    radar_frequency = float(io_lib.get_param_par(mlipar, 'radar_frequency')) #Hz
    wavelength = speed_of_light/radar_frequency #meter
    m2r_coef = 4*np.pi/wavelength
    
    if wavelength > 0.2: ## L-band
        cycle = 1.5  # 2pi/cycle for png
    else: ## C-band
        cycle = 3  # 2pi*3/cycle for png

    ### Get geo info. Grid registration
    dempar = os.path.join(in_dir, 'EQA.dem_par')
    width_geo = int(io_lib.get_param_par(dempar, 'width'))
    length_geo = int(io_lib.get_param_par(dempar, 'nlines'))
    dlat_geo = float(io_lib.get_param_par(dempar, 'post_lat')) #minus
    dlon_geo = float(io_lib.get_param_par(dempar, 'post_lon'))
    latn_geo = float(io_lib.get_param_par(dempar, 'corner_lat'))
    lonw_geo = float(io_lib.get_param_par(dempar, 'corner_lon'))
    lats_geo = latn_geo+dlat_geo*(length_geo-1)
    lone_geo = lonw_geo+dlon_geo*(width_geo-1)

    ### Check coordinate
    if width_unw!=width_geo or length_unw!=length_geo:
        print('\n{} seems to contain files in radar coordinate!!\n'.format(in_dir), file=sys.stderr)
        print('Not supported.\n'.format(in_dir), file=sys.stderr)
        return 1

    ### Calc incidence angle from U.geo
    ufile = os.path.join(in_dir, 'U.geo')
    LOSu = io_lib.read_img(ufile, length_geo, width_geo)
    LOSu[LOSu==0] = np.nan

    ### Get ifgdates and imdates
    ifgdates = tools_lib.get_ifgdates(in_dir)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_ifg = len(ifgdates)
    n_im = len(imdates)


    #%% Process ztd files 
    print('\nConvert ztd/sltd.geo.tif files to sltd.geo files...', flush=True)
    ### First check if sltd already exist
    imdates2 = []
    for imd in imdates:
        sltd_geofile = os.path.join(sltddir, imd+'.sltd.geo')
        if not os.path.exists(sltd_geofile):
            imdates2.append(imd)

    n_im2 = len(imdates2)
    if n_im-n_im2 > 0:
        print("  {0:3}/{1:3} sltd already exist. Skip".format(n_im-n_im2, n_im), flush=True)

    no_gacos_imfile = os.path.join(out_dir, 'no_gacos_im.txt')
    if os.path.exists(no_gacos_imfile): os.remove(no_gacos_imfile)
    
    for ix_im, imd in enumerate(imdates2):
        if np.mod(ix_im, 10)==0:
            print('  Finished {0:4}/{1:4}th sltd...'.format(ix_im, n_im2), flush=True)

        ztdfile = os.path.join(gacosdir, imd+'.ztd')
        sltdtiffile = os.path.join(gacosdir, imd+'.sltd.geo.tif')

        if os.path.exists(sltdtiffile):
            infile = os.path.basename(sltdtiffile)
            try: ### Cut and resapmle. Already in rad.
                sltd_geo = gdal.Warp("", sltdtiffile, format='MEM', outputBounds=(lonw_geo, lats_geo, lone_geo, latn_geo), width=width_geo, height=length_geo, resampleAlg=resampleAlg, srcNodata=0).ReadAsArray()
            except: ## if broken
                print ('  {} cannot open. Skip'.format(infile), flush=True)
                with open(no_gacos_imfile, mode='a') as fnogacos:
                    print('{}'.format(imd), file=fnogacos)
                continue

        elif os.path.exists(ztdfile):
            infile = os.path.basename(ztdfile)
            hdrfile = os.path.join(sltddir, imd+'.hdr')
            bilfile = os.path.join(sltddir, imd+'.bil')
            if os.path.exists(hdrfile): os.remove(hdrfile)
            if os.path.exists(bilfile): os.remove(bilfile)
            make_hdr(ztdfile+'.rsc', hdrfile)
            os.symlink(os.path.relpath(ztdfile, sltddir), bilfile)
    
            ### Cut and resapmle ztd to geo
            ztd_geo = gdal.Warp("", bilfile, format='MEM', outputBounds=(lonw_geo, lats_geo, lone_geo, latn_geo), width=width_geo, height=length_geo, resampleAlg=resampleAlg, srcNodata=0).ReadAsArray()
            os.remove(hdrfile)
            os.remove(bilfile)
    
            ### Meter to rad, slantrange
            sltd_geo = ztd_geo/LOSu*m2r_coef ## LOSu=cos(inc)

        else:
            print('  There is no ztd|sltd.geo.tif for {}!'.format(imd), flush=True)
            with open(no_gacos_imfile, mode='a') as fnogacos:
                print('{}'.format(imd), file=fnogacos)
            continue ## Next imd

        ### Skip if no data in the area
        if np.all((sltd_geo==0)|np.isnan(sltd_geo)):
            print('  There is no valid data in {}!'.format(infile), flush=True)
            with open(no_gacos_imfile, mode='a') as fnogacos:
                print('{}'.format(imd), file=fnogacos)
            continue ## Next imd

        ### Fill hole is specified
        if fillholeflag:
            sltd_geo = fillhole(sltd_geo)
        
        ### Output as sltd.geo
        sltd_geofile = os.path.join(sltddir, imd+'.sltd.geo')
        sltd_geo.tofile(sltd_geofile)

    
    #%% Correct unw files
    print('\nCorrect unw data...', flush=True)
    ### Information files    
    gacinfofile = os.path.join(out_dir, 'GACOS_info.txt')
    if not os.path.exists(gacinfofile):
        ### Add header
        with open(gacinfofile, "w") as f:
            print(' Phase STD (rad) Before After  ReductionRate', file=f)
    
    no_gacos_ifgfile = os.path.join(out_dir, 'no_gacos_ifg.txt')
    if os.path.exists(no_gacos_ifgfile): os.remove(no_gacos_ifgfile)

    ### First check if already corrected unw exist
    ifgdates2 = []
    for i, ifgd in enumerate(ifgdates): 
        out_dir1 = os.path.join(out_dir, ifgd)
        unw_corfile = os.path.join(out_dir1, ifgd+'.unw')
        if not os.path.exists(unw_corfile):
            ifgdates2.append(ifgd)

    n_ifg2 = len(ifgdates2)
    if n_ifg-n_ifg2 > 0:
        print("  {0:3}/{1:3} corrected unw already exist. Skip".format(n_ifg-n_ifg2, n_ifg), flush=True)

    ### Correct
    for i, ifgd in enumerate(ifgdates2):
        if np.mod(i, 10)==0:
            print('  Finished {0:4}/{1:4}th unw...'.format(i, n_ifg2), flush=True)

        md = ifgd[:8]
        sd = ifgd[-8:]
        msltdfile = os.path.join(sltddir, md+'.sltd.geo')
        ssltdfile = os.path.join(sltddir, sd+'.sltd.geo')
        
        in_dir1 = os.path.join(in_dir, ifgd)
        out_dir1 = os.path.join(out_dir, ifgd)
        
        ### Check if sltd available for both master and slave. If not continue
        ## Not use in tsa because loop cannot be closed
        if not (os.path.exists(msltdfile) and os.path.exists(ssltdfile)):
            print('  ztd file not available for {}'.format(ifgd), flush=True)
            with open(no_gacos_ifgfile, mode='a') as fnogacos:
                print('{}'.format(ifgd), file=fnogacos)
            continue

        ### Prepare directory and file
        if not os.path.exists(out_dir1): os.mkdir(out_dir1)
        unwfile = os.path.join(in_dir1, ifgd+'.unw')
        unw_corfile = os.path.join(out_dir1, ifgd+'.unw')
        
        ### Calculate dsltd
        msltd = io_lib.read_img(msltdfile, length_unw, width_unw)
        ssltd = io_lib.read_img(ssltdfile, length_unw, width_unw)

        msltd[msltd==0] = np.nan
        ssltd[ssltd==0] = np.nan
        
        dsltd = ssltd-msltd
        
        ### Correct unw
        unw = io_lib.read_img(unwfile, length_unw, width_unw)
        
        unw[unw==0] = np.nan
        unw_cor = unw-dsltd
        unw_cor.tofile(unw_corfile)
        
        ### Output std
        std_unw = np.nanstd(unw)
        std_unwcor = np.nanstd(unw_cor)
        rate = (std_unw-std_unwcor)/std_unw*100
        with open(gacinfofile, "a") as f:
            print('{0}  {1:4.1f}  {2:4.1f} {3:5.1f}%'.format(ifgd, std_unw, std_unwcor, rate), file=f)

        ### Link cc
        if not os.path.exists(os.path.join(out_dir1, ifgd+'.cc')):
            os.symlink(os.path.relpath(os.path.join(in_dir1, ifgd+'.cc'), out_dir1), os.path.join(out_dir1, ifgd+'.cc'))
            
        ### Output png for comparison
        data3 = [np.angle(np.exp(1j*(data/cycle))*cycle) for data in [unw, unw_cor, dsltd]]
        title3 = ['unw_org (STD: {:.1f} rad)'.format(std_unw), 'unw_cor (STD: {:.1f} rad)'.format(std_unwcor), 'dsltd ({:.1f}% reduced)'.format(rate)]
        pngfile = os.path.join(out_dir1, ifgd+'.gacos.png')
        plot_lib.make_3im_png(data3, pngfile, 'insar', title3, vmin=-np.pi, vmax=np.pi, cbar=False)
        
        ## Output png for corrected unw
        pngfile = os.path.join(out_dir1, ifgd+'.unw.png')
        title = '{} ({}pi/cycle)'.format(ifgd, cycle*2)
        plot_lib.make_im_png(np.angle(np.exp(1j*unw_cor/cycle)*cycle), pngfile, 'insar', title, -np.pi, np.pi, cbar=False)

    print("", flush=True)
    
    
    #%% Create correlation png
    pngfile = os.path.join(out_dir, 'GACOS_info.png')
    plot_lib.plot_gacos_info(gacinfofile, pngfile)
    
    
    #%% Copy other files
    files = glob.glob(os.path.join(in_dir, '*'))
    for file in files:
        if not os.path.isdir(file): #not copy directory, only file
            print('Copy {}'.format(os.path.basename(file)), flush=True)
            shutil.copy(file, out_dir)
    
    
    #%% Finish
    elapsed_time = time.time()-start
    hour = int(elapsed_time/3600)
    minite = int(np.mod((elapsed_time/60),60))
    sec = int(np.mod(elapsed_time,60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour,minite,sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(out_dir)))

    if os.path.exists(no_gacos_ifgfile):
        print('Caution: Some ifgs below are excluded due to GACOS unavailable')
        with open(no_gacos_ifgfile) as f:
            for line in f:
                print(line, end='')
        print('')

    if os.path.exists(no_gacos_imfile):
        print('GACOS data for the following dates are missing:')
        with open(no_gacos_imfile) as f:
            for line in f:
                print(line, end='')
        print('')
Exemple #6
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = "1.7.1"
    date = 20201028
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    ### For parallel processing
    global ifgdates2, geocdir, outdir, nlook, n_valid_thre, cycle, cmap

    #%% Set default
    geocdir = []
    outdir = []
    nlook = 1
    radar_freq = 5.405e9
    try:
        n_para = len(os.sched_getaffinity(0))
    except:
        n_para = multi.cpu_count()

    cmap = 'insar'
    cycle = 3
    n_valid_thre = 0.5

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:o:n:",
                                       ["help", "freq=", "n_para="])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-i':
                geocdir = a
            elif o == '-o':
                outdir = a
            elif o == '-n':
                nlook = int(a)
            elif o == '--freq':
                radar_freq = float(a)
            elif o == '--n_para':
                n_para = int(a)

        if not geocdir:
            raise Usage('No GEOC directory given, -d is not optional!')
        elif not os.path.isdir(geocdir):
            raise Usage('No {} dir exists!'.format(geocdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Directory and file setting
    geocdir = os.path.abspath(geocdir)
    if not outdir:
        outdir = os.path.join(os.path.dirname(geocdir),
                              'GEOCml{}'.format(nlook))
    if not os.path.exists(outdir): os.mkdir(outdir)

    mlipar = os.path.join(outdir, 'slc.mli.par')
    dempar = os.path.join(outdir, 'EQA.dem_par')

    no_unw_list = os.path.join(outdir, 'no_unw_list.txt')
    if os.path.exists(no_unw_list): os.remove(no_unw_list)

    bperp_file_in = os.path.join(geocdir, 'baselines')
    bperp_file_out = os.path.join(outdir, 'baselines')

    metadata_file = os.path.join(geocdir, 'metadata.txt')
    if os.path.exists(metadata_file):
        center_time = subp.check_output(['grep', 'center_time', metadata_file
                                         ]).decode().split('=')[1].strip()
    else:
        center_time = None

    #%% ENU
    for ENU in ['E', 'N', 'U']:
        print('\nCreate {}'.format(ENU + '.geo'), flush=True)
        enutif = glob.glob(os.path.join(geocdir, '*.geo.{}.tif'.format(ENU)))

        ### Download if not exist
        if len(enutif) == 0:
            print('  No *.geo.{}.tif found in {}'.format(
                ENU, os.path.basename(geocdir)),
                  flush=True)
            continue

        else:
            enutif = enutif[0]  ## first one

        ### Create float
        data = gdal.Open(enutif).ReadAsArray()
        data[data == 0] = np.nan

        if nlook != 1:
            ### Multilook
            data = tools_lib.multilook(data, nlook, nlook)

        outfile = os.path.join(outdir, ENU + '.geo')
        data.tofile(outfile)
        print('  {}.geo created'.format(ENU), flush=True)

    #%% mli
    print('\nCreate slc.mli', flush=True)
    mlitif = glob.glob(os.path.join(geocdir, '*.geo.mli.tif'))
    if len(mlitif) > 0:
        mlitif = mlitif[0]  ## First one
        mli = np.float32(gdal.Open(mlitif).ReadAsArray())
        mli[mli == 0] = np.nan

        if nlook != 1:
            ### Multilook
            mli = tools_lib.multilook(mli, nlook, nlook)

        mlifile = os.path.join(outdir, 'slc.mli')
        mli.tofile(mlifile)
        mlipngfile = mlifile + '.png'
        mli = np.log10(mli)
        vmin = np.nanpercentile(mli, 5)
        vmax = np.nanpercentile(mli, 95)
        plot_lib.make_im_png(mli,
                             mlipngfile,
                             'gray',
                             'MLI (log10)',
                             vmin,
                             vmax,
                             cbar=True)
        print('  slc.mli[.png] created', flush=True)
    else:
        print('  No *.geo.mli.tif found in {}'.format(
            os.path.basename(geocdir)),
              flush=True)

    #%% hgt
    print('\nCreate hgt', flush=True)
    hgttif = glob.glob(os.path.join(geocdir, '*.geo.hgt.tif'))
    if len(hgttif) > 0:
        hgttif = hgttif[0]  ## First one
        hgt = np.float32(gdal.Open(hgttif).ReadAsArray())
        hgt[hgt == 0] = np.nan

        if nlook != 1:
            ### Multilook
            hgt = tools_lib.multilook(hgt, nlook, nlook)

        hgtfile = os.path.join(outdir, 'hgt')
        hgt.tofile(hgtfile)
        hgtpngfile = hgtfile + '.png'
        vmax = np.nanpercentile(hgt, 99)
        vmin = -vmax / 3  ## bnecause 1/4 of terrain is blue
        plot_lib.make_im_png(hgt,
                             hgtpngfile,
                             'terrain',
                             'DEM (m)',
                             vmin,
                             vmax,
                             cbar=True)
        print('  hgt[.png] created', flush=True)
    else:
        print('  No *.geo.hgt.tif found in {}'.format(
            os.path.basename(geocdir)),
              flush=True)

    #%% tif -> float (with multilook/downsampling)
    print('\nCreate unw and cc', flush=True)
    ifgdates = tools_lib.get_ifgdates(geocdir)
    n_ifg = len(ifgdates)

    ### First check if float already exist
    ifgdates2 = []
    for i, ifgd in enumerate(ifgdates):
        ifgdir1 = os.path.join(outdir, ifgd)
        unwfile = os.path.join(ifgdir1, ifgd + '.unw')
        ccfile = os.path.join(ifgdir1, ifgd + '.cc')
        if not (os.path.exists(unwfile) and os.path.exists(ccfile)):
            ifgdates2.append(ifgd)

    n_ifg2 = len(ifgdates2)
    if n_ifg - n_ifg2 > 0:
        print("  {0:3}/{1:3} unw and cc already exist. Skip".format(
            n_ifg - n_ifg2, n_ifg),
              flush=True)

    if n_ifg2 > 0:
        if n_para > n_ifg2:
            n_para = n_ifg2

        ### Create float with parallel processing
        print('  {} parallel processing...'.format(n_para), flush=True)
        p = multi.Pool(n_para)
        rc = p.map(convert_wrapper, range(n_ifg2))
        p.close()

        ifgd_ok = []
        for i, _rc in enumerate(rc):
            if _rc == 1:
                with open(no_unw_list, 'a') as f:
                    print('{}'.format(ifgdates2[i]), file=f)
            elif _rc == 0:
                ifgd_ok = ifgdates2[i]  ## readable tiff

        ### Read info
        ## If all float already exist, this will not be done, but no problem because
        ## par files should alerady exist!
        if ifgd_ok:
            unw_tiffile = os.path.join(geocdir, ifgd_ok,
                                       ifgd_ok + '.geo.unw.tif')
            geotiff = gdal.Open(unw_tiffile)
            width = geotiff.RasterXSize
            length = geotiff.RasterYSize
            lon_w_p, dlon, _, lat_n_p, _, dlat = geotiff.GetGeoTransform()
            ## lat lon are in pixel registration. dlat is negative
            lon_w_g = lon_w_p + dlon / 2
            lat_n_g = lat_n_p + dlat / 2
            ## to grit registration by shifting half pixel inside
            if nlook != 1:
                width = int(width / nlook)
                length = int(length / nlook)
                dlon = dlon * nlook
                dlat = dlat * nlook

    #%% EQA.dem_par, slc.mli.par
    if not os.path.exists(mlipar):
        print('\nCreate slc.mli.par', flush=True)
        #        radar_freq = 5.405e9 ## fixed for Sentnel-1

        with open(mlipar, 'w') as f:
            print('range_samples:   {}'.format(width), file=f)
            print('azimuth_lines:   {}'.format(length), file=f)
            print('radar_frequency: {} Hz'.format(radar_freq), file=f)
            if center_time is not None:
                print('center_time: {}'.format(center_time), file=f)

    if not os.path.exists(dempar):
        print('\nCreate EQA.dem_par', flush=True)

        text = [
            "Gamma DIFF&GEO DEM/MAP parameter file", "title: DEM",
            "DEM_projection:     EQA", "data_format:        REAL*4",
            "DEM_hgt_offset:          0.00000",
            "DEM_scale:               1.00000", "width: {}".format(width),
            "nlines: {}".format(length),
            "corner_lat:     {}  decimal degrees".format(lat_n_g),
            "corner_lon:    {}  decimal degrees".format(lon_w_g),
            "post_lat: {} decimal degrees".format(dlat),
            "post_lon: {} decimal degrees".format(dlon), "",
            "ellipsoid_name: WGS 84", "ellipsoid_ra:        6378137.000   m",
            "ellipsoid_reciprocal_flattening:  298.2572236", "",
            "datum_name: WGS 1984", "datum_shift_dx:              0.000   m",
            "datum_shift_dy:              0.000   m",
            "datum_shift_dz:              0.000   m",
            "datum_scale_m:         0.00000e+00",
            "datum_rotation_alpha:  0.00000e+00   arc-sec",
            "datum_rotation_beta:   0.00000e+00   arc-sec",
            "datum_rotation_gamma:  0.00000e+00   arc-sec",
            "datum_country_list: Global Definition, WGS84, World\n"
        ]

        with open(dempar, 'w') as f:
            f.write('\n'.join(text))

    #%% bperp
    print('\nCopy baselines file', flush=True)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    if os.path.exists(bperp_file_in):
        ## Check exisiting bperp_file
        if not io_lib.read_bperp_file(bperp_file_in, imdates):
            print('  baselines file found, but not complete. Make dummy',
                  flush=True)
            io_lib.make_dummy_bperp(bperp_file_out, imdates)
        else:
            shutil.copyfile(bperp_file_in, bperp_file_out)
    else:
        print('  No valid baselines file exists. Make dummy.', flush=True)
        io_lib.make_dummy_bperp(bperp_file_out, imdates)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(outdir)))
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = 1.2
    date = 20200227
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    frameID = []
    startdate = 20141001
    enddate = int(dt.date.today().strftime("%Y%m%d"))
    get_gacos = False

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hf:s:e:",
                                       ["help", "get_gacos"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-f':
                frameID = a
            elif o == '-s':
                startdate = int(a)
            elif o == '-e':
                enddate = int(a)
            elif o == '--get_gacos':
                get_gacos = True

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Determine frameID
    wd = os.getcwd()
    if not frameID:  ## if frameID not indicated
        _tmp = re.findall(r'\d{3}[AD]_\d{5}_\d{6}', wd)
        ##e.g., 021D_04972_131213
        if len(_tmp) == 0:
            print('\nFrame ID cannot be identified from dir name!',
                  file=sys.stderr)
            print('Use -f option', file=sys.stderr)
            return
        else:
            frameID = _tmp[0]
            print('\nFrame ID is {}\n'.format(frameID), flush=True)
    trackID = str(int(frameID[0:3]))

    #%% Directory and file setting
    outdir = os.path.join(wd, 'GEOC')
    if not os.path.exists(outdir): os.mkdir(outdir)
    os.chdir(outdir)

    LiCSARweb = 'http://gws-access.ceda.ac.uk/public/nceo_geohazards/LiCSAR_products/'

    #%% ENU and hgt
    for ENU in ['E', 'N', 'U', 'hgt']:
        enutif = '{}.geo.{}.tif'.format(frameID, ENU)
        if os.path.exists(enutif):
            print('{} already exist. Skip download.'.format(enutif),
                  flush=True)
            continue

        print('Download {}'.format(enutif), flush=True)

        url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', enutif)
        if not tools_lib.download_data(url, enutif):
            print('  Error while downloading from {}'.format(url),
                  file=sys.stderr,
                  flush=True)
            continue

    #%% baselines and metadata.txt
    print('Download baselines', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', 'baselines')
    if not tools_lib.download_data(url, 'baselines'):
        print('  Error while downloading from {}'.format(url),
              file=sys.stderr,
              flush=True)

    print('Download metadata.txt', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', 'metadata.txt')
    if not tools_lib.download_data(url, 'metadata.txt'):
        print('  Error while downloading from {}'.format(url),
              file=sys.stderr,
              flush=True)

    #%% mli
    ### Get available dates
    url = os.path.join(LiCSARweb, trackID, frameID, 'products', 'epochs')
    response = requests.get(url)
    if not response.ok:  ## Try new structure
        url = os.path.join(LiCSARweb, trackID, frameID, 'epochs')
        response = requests.get(url)

    response.encoding = response.apparent_encoding  #avoid garble
    html_doc = response.text
    soup = BeautifulSoup(html_doc, "html.parser")
    tags = soup.find_all(href=re.compile(r"\d{8}"))
    imdates_all = [tag.get("href")[0:8] for tag in tags]
    _imdates = np.int32(np.array(imdates_all))
    _imdates = (_imdates[(_imdates >= startdate) *
                         (_imdates <= enddate)]).astype('str').tolist()

    ## Find earliest date in which mli is available
    imd1 = []
    for imd in _imdates:
        url_mli = os.path.join(url, imd, imd + '.geo.mli.tif')
        response = requests.get(url_mli)
        if response.ok:
            imd1 = imd
            break

    ### Download
    if imd1:
        print('Donwnloading {}.geo.mli.tif as {}.geo.mli.tif...'.format(
            imd1, frameID),
              flush=True)
        url_mli = os.path.join(url, imd1, imd1 + '.geo.mli.tif')
        mlitif = frameID + '.geo.mli.tif'
        if os.path.exists(mlitif):
            print('    {} already exist. Skip'.format(mlitif), flush=True)
        elif not tools_lib.download_data(url_mli, mlitif):
            print('    Error while downloading from {}'.format(url_mli),
                  file=sys.stderr,
                  flush=True)
    else:
        print('No mli available on {}'.format(url),
              file=sys.stderr,
              flush=True)

    #%% GACOS if specified
    if get_gacos:
        gacosdir = os.path.join(wd, 'GACOS')
        if not os.path.exists(gacosdir): os.mkdir(gacosdir)

        ### Get available dates
        print('\nDownload GACOS data', flush=True)
        url = os.path.join(LiCSARweb, trackID, frameID, 'epochs')
        response = requests.get(url)
        response.encoding = response.apparent_encoding  #avoid garble
        html_doc = response.text
        soup = BeautifulSoup(html_doc, "html.parser")
        tags = soup.find_all(href=re.compile(r"\d{8}"))
        imdates_all = [tag.get("href")[0:8] for tag in tags]
        _imdates = np.int32(np.array(imdates_all))
        _imdates = (_imdates[(_imdates >= startdate) *
                             (_imdates <= enddate)]).astype('str').tolist()

        ### Extract available dates
        imdates = []
        for imd in _imdates:
            url_sltd = os.path.join(url, imd, imd + '.sltd.geo.tif')
            response = requests.get(url_sltd)
            if response.ok:
                imdates.append(imd)

        n_im = len(imdates)
        if n_im > 0:
            print('{} GACOS data available from {} to {}'.format(
                n_im, imdates[0], imdates[-1]),
                  flush=True)
        else:
            print('No GACOS data available from {} to {}'.format(
                startdate, enddate),
                  flush=True)

        ### Download
        for i, imd in enumerate(imdates):
            print('  Donwnloading {} ({}/{})...'.format(imd, i + 1, n_im),
                  flush=True)
            url_sltd = os.path.join(url, imd, imd + '.sltd.geo.tif')
            path_sltd = os.path.join(gacosdir, imd + '.sltd.geo.tif')
            if os.path.exists(path_sltd):
                print('    {}.sltd.geo.tif already exist. Skip'.format(imd),
                      flush=True)
            elif not tools_lib.download_data(url_sltd, path_sltd):
                print('    Error while downloading from {}'.format(url_sltd),
                      file=sys.stderr,
                      flush=True)

    #%% unw and cc
    ### Get available dates
    print('\nDownload geotiff of unw and cc', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'products')
    response = requests.get(url)
    if not response.ok:  ## Try new structure
        url = os.path.join(LiCSARweb, trackID, frameID, 'interferograms')
        response = requests.get(url)

    response.encoding = response.apparent_encoding  #avoid garble
    html_doc = response.text
    soup = BeautifulSoup(html_doc, "html.parser")
    tags = soup.find_all(href=re.compile(r"\d{8}_\d{8}"))
    ifgdates_all = [tag.get("href")[0:17] for tag in tags]

    ### Extract during start_date to end_date
    ifgdates = []
    for ifgd in ifgdates_all:
        mimd = int(ifgd[:8])
        simd = int(ifgd[-8:])
        if mimd >= startdate and simd <= enddate:
            ifgdates.append(ifgd)

    n_ifg = len(ifgdates)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    print('{} IFGs available from {} to {}'.format(n_ifg, imdates[0],
                                                   imdates[-1]),
          flush=True)

    ### Download
    for i, ifgd in enumerate(ifgdates):
        print('  Donwnloading {} ({}/{})...'.format(ifgd, i + 1, n_ifg),
              flush=True)
        url_unw = os.path.join(url, ifgd, ifgd + '.geo.unw.tif')
        path_unw = os.path.join(ifgd, ifgd + '.geo.unw.tif')
        if not os.path.exists(ifgd): os.mkdir(ifgd)
        if os.path.exists(path_unw):
            print('    {}.geo.unw.tif already exist. Skip'.format(ifgd),
                  flush=True)
        elif not tools_lib.download_data(url_unw, path_unw):
            print('    Error while downloading from {}'.format(url_unw),
                  file=sys.stderr,
                  flush=True)

        url_cc = os.path.join(url, ifgd, ifgd + '.geo.cc.tif')
        path_cc = os.path.join(ifgd, ifgd + '.geo.cc.tif')
        if os.path.exists(path_cc):
            print('    {}.geo.cc.tif already exist. Skip.'.format(ifgd),
                  flush=True)
        if not tools_lib.download_data(url_cc, path_cc):
            print('    Error while downloading from {}'.format(url_cc),
                  file=sys.stderr,
                  flush=True)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(outdir))
Exemple #8
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = "1.3.2"
    date = 20201116
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    ifgdir = []
    tsadir = []
    coh_thre = 0.05
    unw_cov_thre = 0.3

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hd:t:c:u:", ["help"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-d':
                ifgdir = a
            elif o == '-t':
                tsadir = a
            elif o == '-c':
                coh_thre = float(a)
            elif o == '-u':
                unw_cov_thre = float(a)

        if not ifgdir:
            raise Usage('No data directory given, -d is not optional!')
        elif not os.path.isdir(ifgdir):
            raise Usage('No {} dir exists!'.format(ifgdir))
        elif not os.path.exists(os.path.join(ifgdir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(ifgdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    print("\ncoh_thre     : {}".format(coh_thre), flush=True)
    print("unw_cov_thre : {}".format(unw_cov_thre), flush=True)

    #%% Directory setting
    ifgdir = os.path.abspath(ifgdir)

    if not tsadir:
        tsadir = os.path.join(os.path.dirname(ifgdir),
                              'TS_' + os.path.basename(ifgdir))

    if not os.path.exists(tsadir): os.mkdir(tsadir)

    ifg_rasdir = os.path.join(tsadir, '11ifg_ras')
    bad_ifg_rasdir = os.path.join(tsadir, '11bad_ifg_ras')

    if os.path.exists(ifg_rasdir): shutil.rmtree(ifg_rasdir)
    if os.path.exists(bad_ifg_rasdir): shutil.rmtree(bad_ifg_rasdir)
    os.mkdir(ifg_rasdir)
    os.mkdir(bad_ifg_rasdir)

    netdir = os.path.join(tsadir, 'network')
    if not os.path.exists(netdir): os.mkdir(netdir)

    infodir = os.path.join(tsadir, 'info')
    if not os.path.exists(infodir): os.mkdir(infodir)

    resultsdir = os.path.join(tsadir, 'results')
    if not os.path.exists(resultsdir): os.mkdir(resultsdir)

    #%% Read date, network information and size
    ### Get dates
    ifgdates = tools_lib.get_ifgdates(ifgdir)
    imdates = tools_lib.ifgdates2imdates(ifgdates)

    n_ifg = len(ifgdates)
    n_im = len(imdates)

    ### Get size
    mlipar = os.path.join(ifgdir, 'slc.mli.par')
    width = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))
    print("\nSize         : {} x {}".format(width, length), flush=True)

    ### Copy dempar and mli[png|par]
    for file in ['slc.mli.par', 'EQA.dem_par']:
        if os.path.exists(os.path.join(ifgdir, file)):
            shutil.copy(os.path.join(ifgdir, file), infodir)

    for file in ['slc.mli', 'slc.mli.png', 'hgt', 'hgt.png']:
        if os.path.exists(os.path.join(ifgdir, file)):
            shutil.copy(os.path.join(ifgdir, file), resultsdir)

    #%% Read data
    ### Allocate memory
    n_unw = np.zeros((length, width), dtype=np.float32)
    coh_avg_ifg = []
    n_unw_ifg = []

    ### Read data and calculate
    print('\nReading unw and cc data...', flush=True)
    ## First, identify valid area (n_unw>im)
    for ifgix, ifgd in enumerate(ifgdates):
        if np.mod(ifgix, 100) == 0:
            print("  {0:3}/{1:3}th unw to identify valid area...".format(
                ifgix, n_ifg),
                  flush=True)
        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        unw = io_lib.read_img(unwfile, length, width)

        unw[unw == 0] = np.nan  # Fill 0 with nan
        n_unw += ~np.isnan(unw)  # Summing number of unnan unw

    ## Identify valid area and calc rate_cov
    bool_valid = (n_unw >= n_im)
    n_unw_valid = bool_valid.sum()

    ## Read cc and unw data
    for ifgix, ifgd in enumerate(ifgdates):
        if np.mod(ifgix, 100) == 0:
            print("  {0:3}/{1:3}th cc and unw...".format(ifgix, n_ifg),
                  flush=True)
        ## unw
        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        unw = io_lib.read_img(unwfile, length, width)

        unw[unw == 0] = np.nan  # Fill 0 with nan
        unw[~bool_valid] = np.nan  # Fill sea area with nan
        n_unw_ifg.append((~np.isnan(unw)).sum())

        ## cc
        ccfile = os.path.join(ifgdir, ifgd, ifgd + '.cc')
        if os.path.getsize(ccfile) == length * width:
            coh = io_lib.read_img(ccfile, length, width, np.uint8)
            coh = coh.astype(np.float32) / 255
            coh[coh == 0] = np.nan
        else:
            coh = io_lib.read_img(ccfile, length, width)

        coh_avg_ifg.append(np.nanmean(coh[bool_valid]))  # Use valid area only

    rate_cov = np.array(n_unw_ifg) / n_unw_valid

    ## Read bperp data or dummy
    bperp_file = os.path.join(ifgdir, 'baselines')
    if os.path.exists(bperp_file):
        bperp = io_lib.read_bperp_file(bperp_file, imdates)
    else:  #dummy
        bperp = np.random.random(n_im).tolist()

    #%% Identify bad ifgs, link ras and output stats information
    bad_ifgdates = []
    ixs_bad_ifgdates = []

    ### Header of stats file
    ifg_statsfile = os.path.join(infodir, '11ifg_stats.txt')
    fstats = open(ifg_statsfile, 'w')
    print('# Size: {0}({1}x{2}), n_valid: {3}'.format(width * length, width,
                                                      length, n_unw_valid),
          file=fstats)
    print('# unw_cov_thre: {0}, coh_thre: {1}'.format(unw_cov_thre, coh_thre),
          file=fstats)
    print('# ifg dates         bperp   dt unw_cov  coh_av', file=fstats)

    ### Identify suffix of raster image (png, ras or bmp?)
    unwfile = os.path.join(ifgdir, ifgdates[0], ifgdates[0] + '.unw')
    if os.path.exists(unwfile + '.ras'):
        suffix = '.ras'
    elif os.path.exists(unwfile + '.bmp'):
        suffix = '.bmp'
    elif os.path.exists(unwfile + '.png'):
        suffix = '.png'
    else:
        print('\nERROR: No browse image available for {}!\n'.format(unwfile),
              file=sys.stderr)
        return 2

    for i, ifgd in enumerate(ifgdates):
        rasname = ifgdates[i] + '.unw' + suffix
        rasorg = os.path.join(ifgdir, ifgdates[i], rasname)

        if not os.path.exists(rasorg):
            print('\nERROR: No browse image {} available!\n'.format(rasorg),
                  file=sys.stderr)
            return 2

        ### Identify bad ifgs and link ras
        if rate_cov[i] < unw_cov_thre or coh_avg_ifg[i] < coh_thre:
            bad_ifgdates.append(ifgdates[i])
            ixs_bad_ifgdates.append(i)
            rm_flag = '*'
            os.symlink(os.path.relpath(rasorg, bad_ifg_rasdir),
                       os.path.join(bad_ifg_rasdir, rasname))
        else:
            os.symlink(os.path.relpath(rasorg, ifg_rasdir),
                       os.path.join(ifg_rasdir, rasname))
            rm_flag = ''

        ### For stats file
        ix_primary = imdates.index(ifgd[:8])
        ix_secondary = imdates.index(ifgd[-8:])
        bperp_ifg = bperp[ix_secondary] - bperp[ix_primary]
        mday = dt.datetime.strptime(ifgd[:8], '%Y%m%d').toordinal()
        sday = dt.datetime.strptime(ifgd[-8:], '%Y%m%d').toordinal()
        dt_ifg = sday - mday

        print('{0}  {1:6.1f}  {2:3}   {3:5.3f}   {4:5.3f} {5}'.format(
            ifgd, bperp_ifg, dt_ifg, rate_cov[i], coh_avg_ifg[i], rm_flag),
              file=fstats)

    fstats.close()

    ### Output list of bad ifg
    print('\n{0}/{1} ifgs are discarded from further processing.'.format(
        len(bad_ifgdates), n_ifg))
    print('ifg dates        unw_cov coh_av')
    bad_ifgfile = os.path.join(infodir, '11bad_ifg.txt')
    with open(bad_ifgfile, 'w') as f:
        for i, ifgd in enumerate(bad_ifgdates):
            print('{}'.format(ifgd), file=f)
            print('{}  {:5.3f}  {:5.3f}'.format(
                ifgd, rate_cov[ixs_bad_ifgdates[i]],
                coh_avg_ifg[ixs_bad_ifgdates[i]]),
                  flush=True)

    #%% Identify removed image and output file
    good_ifgdates = list(set(ifgdates) - set(bad_ifgdates))
    good_ifgdates.sort()
    good_imdates = tools_lib.ifgdates2imdates(good_ifgdates)
    bad_imdates = list(set(imdates) - set(good_imdates))
    bad_imdates.sort()

    ### Output list of removed image
    bad_imfile = os.path.join(infodir, '11removed_image.txt')
    with open(bad_imfile, 'w') as f:
        for i in bad_imdates:
            print('{}'.format(i), file=f)

    #%% Plot network
    pngfile = os.path.join(netdir, 'network11_all.png')
    plot_lib.plot_network(ifgdates, bperp, [], pngfile)

    pngfile = os.path.join(netdir, 'network11.png')
    plot_lib.plot_network(ifgdates, bperp, bad_ifgdates, pngfile)

    pngfile = os.path.join(netdir, 'network11_nobad.png')
    plot_lib.plot_network(ifgdates,
                          bperp,
                          bad_ifgdates,
                          pngfile,
                          plot_bad=False)

    #%% Finish
    print('\nCheck network/*, 11bad_ifg_ras/* and 11ifg_ras/* in TS dir.')
    print(
        'If you want to change the bad ifgs to be discarded, re-run with different thresholds or edit bad_ifg11.txt before next step.'
    )

    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(tsadir)))
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = 1.6
    date = 20200911
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    frameID = []
    startdate = 20141001
    enddate = int(dt.date.today().strftime("%Y%m%d"))
    get_gacos = False
    n_para = 4

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hf:s:e:",
                                       ["help", "get_gacos", "n_para="])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-f':
                frameID = a
            elif o == '-s':
                startdate = int(a)
            elif o == '-e':
                enddate = int(a)
            elif o == '--get_gacos':
                get_gacos = True
            elif o == '--n_para':
                n_para = int(a)

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Determine frameID
    wd = os.getcwd()
    if not frameID:  ## if frameID not indicated
        _tmp = re.findall(r'\d{3}[AD]_\d{5}_\d{6}', wd)
        ##e.g., 021D_04972_131213
        if len(_tmp) == 0:
            print('\nFrame ID cannot be identified from dir name!',
                  file=sys.stderr)
            print('Use -f option', file=sys.stderr)
            return
        else:
            frameID = _tmp[0]
            print('\nFrame ID is {}\n'.format(frameID), flush=True)
    else:
        print('\nFrame ID is {}\n'.format(frameID), flush=True)

    trackID = str(int(frameID[0:3]))

    #%% Directory and file setting
    outdir = os.path.join(wd, 'GEOC')
    if not os.path.exists(outdir): os.mkdir(outdir)
    os.chdir(outdir)

    LiCSARweb = 'http://gws-access.ceda.ac.uk/public/nceo_geohazards/LiCSAR_products/'

    #%% ENU and hgt
    for ENU in ['E', 'N', 'U', 'hgt']:
        enutif = '{}.geo.{}.tif'.format(frameID, ENU)
        url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', enutif)
        if os.path.exists(enutif):
            rc = tools_lib.comp_size_time(url, enutif)
            if rc == 0:
                print('{} already exist. Skip download.'.format(enutif),
                      flush=True)
                continue
            elif rc == 3:
                print('{} not available. Skip download.'.format(enutif),
                      flush=True)
                continue
            else:
                if rc == 1:
                    print("Size of {} is not identical.".format(enutif))
                elif rc == 2:
                    print("Newer {} available.".format(enutif))

        print('Download {}'.format(enutif), flush=True)
        tools_lib.download_data(url, enutif)

    #%% baselines and metadata.txt
    print('Download baselines', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', 'baselines')
    tools_lib.download_data(url, 'baselines')

    print('Download metadata.txt', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', 'metadata.txt')
    tools_lib.download_data(url, 'metadata.txt')

    #%% mli
    mlitif = frameID + '.geo.mli.tif'
    if os.path.exists(mlitif):
        print('{} already exist. Skip.'.format(mlitif), flush=True)
    else:
        ### Get available dates
        print('Searching earliest epoch for mli...', flush=True)
        url = os.path.join(LiCSARweb, trackID, frameID, 'epochs')
        response = requests.get(url)

        response.encoding = response.apparent_encoding  #avoid garble
        html_doc = response.text
        soup = BeautifulSoup(html_doc, "html.parser")
        tags = soup.find_all(href=re.compile(r"\d{8}"))
        imdates_all = [tag.get("href")[0:8] for tag in tags]
        _imdates = np.int32(np.array(imdates_all))
        _imdates = (_imdates[(_imdates >= startdate) *
                             (_imdates <= enddate)]).astype('str').tolist()

        ## Find earliest date in which mli is available
        imd1 = []
        for i, imd in enumerate(_imdates):
            if np.mod(i, 10) == 0:
                print("\r  {0:3}/{1:3}".format(i, len(_imdates)),
                      end='',
                      flush=True)
            url_epoch = os.path.join(url, imd)
            response = requests.get(url_epoch)
            response.encoding = response.apparent_encoding  #avoid garble
            html_doc = response.text
            soup = BeautifulSoup(html_doc, "html.parser")
            tag = soup.find(href=re.compile(r"\d{8}.geo.mli.tif"))
            if tag is not None:
                print('\n{} found as earliest.'.format(imd))
                imd1 = imd
                break

        ### Download
        if imd1:
            print('Donwnloading {}.geo.mli.tif as {}.geo.mli.tif...'.format(
                imd1, frameID),
                  flush=True)
            url_mli = os.path.join(url, imd1, imd1 + '.geo.mli.tif')
            tools_lib.download_data(url_mli, mlitif)
        else:
            print('\nNo mli available on {}'.format(url),
                  file=sys.stderr,
                  flush=True)

    #%% GACOS if specified
    if get_gacos:
        gacosdir = os.path.join(wd, 'GACOS')
        if not os.path.exists(gacosdir): os.mkdir(gacosdir)

        ### Get available dates
        print('\nDownload GACOS data', flush=True)
        url = os.path.join(LiCSARweb, trackID, frameID, 'epochs')
        response = requests.get(url)
        response.encoding = response.apparent_encoding  #avoid garble
        html_doc = response.text
        soup = BeautifulSoup(html_doc, "html.parser")
        tags = soup.find_all(href=re.compile(r"\d{8}"))
        imdates_all = [tag.get("href")[0:8] for tag in tags]
        _imdates = np.int32(np.array(imdates_all))
        _imdates = (_imdates[(_imdates >= startdate) *
                             (_imdates <= enddate)]).astype('str').tolist()
        print('  There are {} epochs from {} to {}'.format(
            len(_imdates), startdate, enddate),
              flush=True)

        ### Extract available dates
        print('  Searching available epochs ({} parallel)...'.format(n_para),
              flush=True)

        args = [(i, len(_imdates),
                 os.path.join(url, imd, '{}.sltd.geo.tif'.format(imd)),
                 os.path.join(gacosdir, imd + '.sltd.geo.tif'))
                for i, imd in enumerate(_imdates)]

        p = multi.Pool(n_para)
        rc = p.map(check_gacos_wrapper, args)
        p.close()

        n_im_existing = 0
        n_im_unavailable = 0
        imdates_dl = []
        for i, rc1 in enumerate(rc):
            if rc1 == 0:  ## No need to download
                n_im_existing = n_im_existing + 1
            if rc1 == 3 or rc1 == 5:  ## Can not download
                n_im_unavailable = n_im_unavailable + 1
            elif rc1 == 1 or rc1 == 2 or rc1 == 4:  ## Need download
                imdates_dl.append(_imdates[i])

        n_im_dl = len(imdates_dl)

        if n_im_existing > 0:
            print('  {} GACOS data already downloaded'.format(n_im_existing),
                  flush=True)
        if n_im_unavailable > 0:
            print('  {} GACOS data unavailable'.format(n_im_unavailable),
                  flush=True)

        ### Download
        if n_im_dl > 0:
            print('{} GACOS data will be downloaded'.format(n_im_dl),
                  flush=True)
            print('Download GACOS ({} parallel)...'.format(n_para), flush=True)
            ### Download
            args = [(i, imd, n_im_dl,
                     os.path.join(url, imd, '{}.sltd.geo.tif'.format(imd)),
                     os.path.join(gacosdir, '{}.sltd.geo.tif'.format(imd)))
                    for i, imd in enumerate(imdates_dl)]

            p = multi.Pool(n_para)
            p.map(download_wrapper, args)
            p.close()
        else:
            print('No GACOS data available from {} to {}'.format(
                startdate, enddate),
                  flush=True)

    #%% unw and cc
    ### Get available dates
    print('\nDownload geotiff of unw and cc', flush=True)
    url_ifgdir = os.path.join(LiCSARweb, trackID, frameID, 'interferograms')
    response = requests.get(url_ifgdir)

    response.encoding = response.apparent_encoding  #avoid garble
    html_doc = response.text
    soup = BeautifulSoup(html_doc, "html.parser")
    tags = soup.find_all(href=re.compile(r"\d{8}_\d{8}"))
    ifgdates_all = [tag.get("href")[0:17] for tag in tags]

    ### Extract during start_date to end_date
    ifgdates = []
    for ifgd in ifgdates_all:
        mimd = int(ifgd[:8])
        simd = int(ifgd[-8:])
        if mimd >= startdate and simd <= enddate:
            ifgdates.append(ifgd)

    n_ifg = len(ifgdates)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    print('{} IFGs available from {} to {}'.format(n_ifg, imdates[0],
                                                   imdates[-1]),
          flush=True)

    ### Check if both unw and cc already donwloaded, new, and same size
    print(
        'Checking existing unw and cc ({} parallel, may take time)...'.format(
            n_para),
        flush=True)

    ## unw
    args = [(i, n_ifg,
             os.path.join(url_ifgdir, ifgd, '{}.geo.unw.tif'.format(ifgd)),
             os.path.join(ifgd, '{}.geo.unw.tif'.format(ifgd)))
            for i, ifgd in enumerate(ifgdates)]

    p = multi.Pool(n_para)
    rc = p.map(check_exist_wrapper, args)
    p.close()

    n_unw_existing = 0
    unwdates_dl = []
    for i, rc1 in enumerate(rc):
        if rc1 == 0:  ## No need to download
            n_unw_existing = n_unw_existing + 1
        if rc1 == 3 or rc1 == 5:  ## Can not download
            print('  {}.geo.unw.tif not available.'.format(ifgdates[i]),
                  flush=True)
        elif rc1 == 1 or rc1 == 2 or rc1 == 4:  ## Need download
            unwdates_dl.append(ifgdates[i])

    ## cc
    args = [(i, n_ifg,
             os.path.join(url_ifgdir, ifgd, '{}.geo.cc.tif'.format(ifgd)),
             os.path.join(ifgd, '{}.geo.cc.tif'.format(ifgd)))
            for i, ifgd in enumerate(ifgdates)]

    p = multi.Pool(n_para)
    rc = p.map(check_exist_wrapper, args)
    p.close()

    n_cc_existing = 0
    ccdates_dl = []
    for i, rc1 in enumerate(rc):
        if rc1 == 0:  ## No need to download
            n_cc_existing = n_cc_existing + 1
        if rc1 == 3 or rc1 == 5:  ## Can not download
            print('  {}.geo.cc.tif not available.'.format(ifgdates[i]),
                  flush=True)
        elif rc1 == 1 or rc1 == 2 or rc1 == 4:  ## Need download
            ccdates_dl.append(ifgdates[i])

    n_unw_dl = len(unwdates_dl)
    n_cc_dl = len(ccdates_dl)
    print('{} unw already downloaded'.format(n_unw_existing), flush=True)
    print('{} unw will be downloaded'.format(n_unw_dl), flush=True)
    print('{} cc already downloaded'.format(n_cc_existing), flush=True)
    print('{} cc will be downloaded'.format(n_cc_dl), flush=True)

    ### Download unw with parallel
    if n_unw_dl != 0:
        print('Download unw ({} parallel)...'.format(n_para), flush=True)
        args = [(i, ifgd, n_unw_dl,
                 os.path.join(url_ifgdir, ifgd, '{}.geo.unw.tif'.format(ifgd)),
                 os.path.join(ifgd, '{}.geo.unw.tif'.format(ifgd)))
                for i, ifgd in enumerate(unwdates_dl)]

        p = multi.Pool(n_para)
        p.map(download_wrapper, args)
        p.close()

    ### Download cc with parallel
    if n_cc_dl != 0:
        print('Download cc ({} parallel)...'.format(n_para), flush=True)
        args = [(i, ifgd, n_cc_dl,
                 os.path.join(url_ifgdir, ifgd, '{}.geo.cc.tif'.format(ifgd)),
                 os.path.join(ifgd, '{}.geo.cc.tif'.format(ifgd)))
                for i, ifgd in enumerate(ccdates_dl)]

        p = multi.Pool(n_para)
        p.map(download_wrapper, args)
        p.close()

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(outdir))
Exemple #10
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = "1.5.5"
    date = 20201119
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    ### For parallel processing
    global imdates2, gacosdir, outputBounds, width_geo, length_geo, resampleAlg,\
        sltddir, LOSu, m2r_coef, fillholeflag, ifgdates2,\
        in_dir, out_dir, length_unw, width_unw, cycle, cmap_wrap

    #%% Set default
    in_dir = []
    out_dir = []
    gacosdir = 'GACOS'
    resampleAlg = 'cubicspline'  # None # 'cubic'
    fillholeflag = False
    try:
        n_para = len(os.sched_getaffinity(0))
    except:
        n_para = multi.cpu_count()

    q = multi.get_context('fork')
    cmap_wrap = SCM.romaO

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:o:g:z:",
                                       ["fillhole", "help", "n_para="])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-i':
                in_dir = a
            elif o == '-o':
                out_dir = a
            elif o == '-z':  ## for backward-compatible
                gacosdir = a
            elif o == '-g':
                gacosdir = a
            elif o == "--fillhole":
                fillholeflag = True
            elif o == '--n_para':
                n_para = int(a)

        if not in_dir:
            raise Usage('No input directory given, -i is not optional!')
        elif not os.path.isdir(in_dir):
            raise Usage('No {} dir exists!'.format(in_dir))
        elif not os.path.exists(os.path.join(in_dir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(in_dir))
        if not out_dir:
            raise Usage('No output directory given, -o is not optional!')
        if not os.path.isdir(gacosdir):
            raise Usage('No {} dir exists!'.format(gacosdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Read data information
    ### Directory
    in_dir = os.path.abspath(in_dir)
    gacosdir = os.path.abspath(gacosdir)

    out_dir = os.path.abspath(out_dir)
    if not os.path.exists(out_dir): os.mkdir(out_dir)

    sltddir = os.path.join(os.path.join(out_dir), 'sltd')
    if not os.path.exists(sltddir): os.mkdir(sltddir)

    ### Get general info
    mlipar = os.path.join(in_dir, 'slc.mli.par')
    width_unw = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length_unw = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))
    speed_of_light = 299792458  #m/s
    radar_frequency = float(io_lib.get_param_par(mlipar,
                                                 'radar_frequency'))  #Hz
    wavelength = speed_of_light / radar_frequency  #meter
    m2r_coef = 4 * np.pi / wavelength

    if wavelength > 0.2:  ## L-band
        cycle = 1.5  # 2pi/cycle for png
    else:  ## C-band
        cycle = 3  # 2pi*3/cycle for png

    ### Get geo info. Grid registration
    dempar = os.path.join(in_dir, 'EQA.dem_par')
    width_geo = int(io_lib.get_param_par(dempar, 'width'))
    length_geo = int(io_lib.get_param_par(dempar, 'nlines'))
    dlat_geo = float(io_lib.get_param_par(dempar, 'post_lat'))  #minus
    dlon_geo = float(io_lib.get_param_par(dempar, 'post_lon'))
    latn_geo = float(io_lib.get_param_par(dempar, 'corner_lat'))
    lonw_geo = float(io_lib.get_param_par(dempar, 'corner_lon'))
    lats_geo = latn_geo + dlat_geo * (length_geo - 1)
    lone_geo = lonw_geo + dlon_geo * (width_geo - 1)
    outputBounds = (lonw_geo, lats_geo, lone_geo, latn_geo)

    ### Check coordinate
    if width_unw != width_geo or length_unw != length_geo:
        print('\n{} seems to contain files in radar coordinate!!\n'.format(
            in_dir),
              file=sys.stderr)
        print('Not supported.\n', file=sys.stderr)
        return 1

    ### Calc incidence angle from U.geo
    ufile = os.path.join(in_dir, 'U.geo')
    LOSu = io_lib.read_img(ufile, length_geo, width_geo)
    LOSu[LOSu == 0] = np.nan

    ### Get ifgdates and imdates
    ifgdates = tools_lib.get_ifgdates(in_dir)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_ifg = len(ifgdates)
    n_im = len(imdates)

    #%% Process ztd files
    print('\nConvert ztd/sltd.geo.tif files to sltd.geo files...', flush=True)

    no_gacos_imfile = os.path.join(out_dir, 'no_gacos_im.txt')
    if os.path.exists(no_gacos_imfile): os.remove(no_gacos_imfile)

    ### First check if sltd already exist
    imdates2 = []
    for imd in imdates:
        sltd_geofile = os.path.join(sltddir, imd + '.sltd.geo')
        if not os.path.exists(sltd_geofile):
            imdates2.append(imd)

    n_im2 = len(imdates2)
    if n_im - n_im2 > 0:
        print("  {0:3}/{1:3} sltd already exist. Skip".format(
            n_im - n_im2, n_im),
              flush=True)

    if n_im2 > 0:
        ### Convert with parallel processing
        if n_para > n_im2:
            _n_para = n_im2
        else:
            _n_para = n_para

        print('  {} parallel processing...'.format(_n_para), flush=True)
        p = q.Pool(_n_para)
        no_gacos_imds = p.map(convert_wrapper, range(n_im2))
        p.close()

        for imd in no_gacos_imds:
            if imd is not None:
                with open(no_gacos_imfile, mode='a') as fnogacos:
                    print('{}'.format(imd), file=fnogacos)

    #%% Correct unw files
    print('\nCorrect unw data...', flush=True)
    ### Information files
    gacinfofile = os.path.join(out_dir, 'GACOS_info.txt')
    if not os.path.exists(gacinfofile):
        ### Add header
        with open(gacinfofile, "w") as f:
            print(' Phase STD (rad) Before After  ReductionRate', file=f)

    no_gacos_ifgfile = os.path.join(out_dir, 'no_gacos_ifg.txt')
    if os.path.exists(no_gacos_ifgfile): os.remove(no_gacos_ifgfile)

    ### First check if already corrected unw exist
    ifgdates2 = []
    for i, ifgd in enumerate(ifgdates):
        out_dir1 = os.path.join(out_dir, ifgd)
        unw_corfile = os.path.join(out_dir1, ifgd + '.unw')
        if not os.path.exists(unw_corfile):
            ifgdates2.append(ifgd)

    n_ifg2 = len(ifgdates2)
    if n_ifg - n_ifg2 > 0:
        print("  {0:3}/{1:3} corrected unw already exist. Skip".format(
            n_ifg - n_ifg2, n_ifg),
              flush=True)

    if n_ifg2 > 0:
        ### Correct with parallel processing
        if n_para > n_ifg2:
            _n_para = n_ifg2
        else:
            _n_para = n_para

        print('  {} parallel processing...'.format(_n_para), flush=True)
        p = q.Pool(_n_para)
        _return = p.map(correct_wrapper, range(n_ifg2))
        p.close()

        for i in range(n_ifg2):
            if _return[i][0] == 1:
                with open(no_gacos_ifgfile, mode='a') as fnogacos:
                    print('{}'.format(_return[i][1]), file=fnogacos)
            elif _return[i][0] == 2:
                with open(gacinfofile, "a") as f:
                    print('{0}  {1:4.1f}  {2:4.1f} {3:5.1f}%'.format(
                        *_return[i][1]),
                          file=f)

    print("", flush=True)

    #%% Create correlation png
    pngfile = os.path.join(out_dir, 'GACOS_info.png')
    plot_lib.plot_gacos_info(gacinfofile, pngfile)

    #%% Copy other files
    files = glob.glob(os.path.join(in_dir, '*'))
    for file in files:
        if not os.path.isdir(file):  #not copy directory, only file
            print('Copy {}'.format(os.path.basename(file)), flush=True)
            shutil.copy(file, out_dir)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(out_dir)))

    if os.path.exists(no_gacos_ifgfile):
        print('Caution: Some ifgs below are excluded due to GACOS unavailable')
        with open(no_gacos_ifgfile) as f:
            for line in f:
                print(line, end='')
        print('')

    if os.path.exists(no_gacos_imfile):
        print('GACOS data for the following dates are missing:')
        with open(no_gacos_imfile) as f:
            for line in f:
                print(line, end='')
        print('')
Exemple #11
0
def plot_network(ifgdates, bperp, rm_ifgdates, pngfile, plot_bad=True):
    """
    Plot network of interferometric pairs.
    
    bperp can be dummy (-1~1).
    Suffix of pngfile can be png, ps, pdf, or svg.
    plot_bad
        True  : Plot bad ifgs by red lines
        False : Do not plot bad ifgs
    """

    imdates_all = tools_lib.ifgdates2imdates(ifgdates)
    n_im_all = len(imdates_all)
    idlist_all = [dt.datetime.strptime(x, '%Y%m%d').toordinal() for x in imdates_all]

    ifgdates = list(set(ifgdates)-set(rm_ifgdates))
    ifgdates.sort()
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    n_im = len(imdates)
    idlist = [dt.datetime.strptime(x, '%Y%m%d').toordinal() for x in imdates]
    
    ### Identify gaps    
    G = inv_lib.make_sb_matrix(ifgdates)
    ixs_inc_gap = np.where(G.sum(axis=0)==0)[0]
    
    ### Plot fig
    figsize_x = np.round((idlist_all[-1]-idlist_all[0])/80)+2
    fig = plt.figure(figsize=(figsize_x, 6))
    ax = fig.add_axes([0.12, 0.12, 0.85,0.85])
    
    ### IFG blue lines
    for i, ifgd in enumerate(ifgdates):
        ix_m = imdates_all.index(ifgd[:8])
        ix_s = imdates_all.index(ifgd[-8:])
        label = 'IFG' if i==0 else '' #label only first
        plt.plot([idlist_all[ix_m], idlist_all[ix_s]], [bperp[ix_m], bperp[ix_s]], color='b', alpha=0.6, zorder=2, label=label)

    ### IFG bad red lines
    if plot_bad:
        for i, ifgd in enumerate(rm_ifgdates):
            ix_m = imdates_all.index(ifgd[:8])
            ix_s = imdates_all.index(ifgd[-8:])
            label = 'Removed IFG' if i==0 else '' #label only first
            plt.plot([idlist_all[ix_m], idlist_all[ix_s]], [bperp[ix_m], bperp[ix_s]], color='r', alpha=0.6, zorder=6, label=label)

    ### Image points and dates
    ax.scatter(idlist_all, bperp, alpha=0.6, zorder=4)
    for i in range(n_im_all):
        if bperp[i] > np.median(bperp): va='bottom'
        else: va = 'top'
        ax.annotate(imdates_all[i][4:6]+'/'+imdates_all[i][6:], (idlist_all[i], bperp[i]), ha='center', va=va, zorder=8)

    ### gaps
    if len(ixs_inc_gap)!=0:
        gap_idlist = []
        for ix_gap in ixs_inc_gap:
            gap_idlist.append((idlist[ix_gap]+idlist[ix_gap+1])/2)
        plt.vlines(gap_idlist, 0, 1, transform=ax.get_xaxis_transform(), zorder=1, label='Gap', alpha=0.6, colors='k', linewidth=3)
        
    ### Locater        
    loc = ax.xaxis.set_major_locator(mdates.AutoDateLocator())
    try:  # Only support from Matplotlib 3.1
        ax.xaxis.set_major_formatter(mdates.ConciseDateFormatter(loc))
    except:
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
        for label in ax.get_xticklabels():
            label.set_rotation(20)
            label.set_horizontalalignment('right')
    ax.grid(b=True, which='major')

    ### Add bold line every 1yr
    ax.xaxis.set_minor_locator(mdates.YearLocator())
    ax.grid(b=True, which='minor', linewidth=2)

    ax.set_xlim((idlist_all[0]-10, idlist_all[-1]+10))

    ### Labels and legend
    plt.xlabel('Time')
    if np.all(np.abs(np.array(bperp))<=1): ## dummy
        plt.ylabel('dummy')
    else:
        plt.ylabel('Bperp [m]')
    
    plt.legend()

    ### Save
    plt.savefig(pngfile)
    plt.close()
Exemple #12
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = 1.4
    date = 20200228
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    geocdir = []
    outdir = []
    nlook = 1
    frameID = []
    cmap = 'insar'
    cycle = 3
    n_valid_thre = 0.5

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:o:n:f:", ["help"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-i':
                geocdir = a
            elif o == '-o':
                outdir = a
            elif o == '-n':
                nlook = int(a)
            elif o == '-f':
                frameID = a

        if not geocdir:
            raise Usage('No GEOC directory given, -d is not optional!')
        elif not os.path.isdir(geocdir):
            raise Usage('No {} dir exists!'.format(geocdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Directory and file setting
    geocdir = os.path.abspath(geocdir)
    if not outdir:
        outdir = os.path.join(os.path.dirname(geocdir),
                              'GEOCml{}'.format(nlook))
    if not os.path.exists(outdir): os.mkdir(outdir)

    mlipar = os.path.join(outdir, 'slc.mli.par')
    dempar = os.path.join(outdir, 'EQA.dem_par')

    no_unw_list = os.path.join(outdir, 'no_unw_list.txt')
    if os.path.exists(no_unw_list): os.remove(no_unw_list)

    bperp_file_in = os.path.join(geocdir, 'baselines')
    bperp_file_out = os.path.join(outdir, 'baselines')

    metadata_file = os.path.join(geocdir, 'metadata.txt')
    if os.path.exists(metadata_file):
        center_time = subp.check_output(['grep', 'center_time', metadata_file
                                         ]).decode().split('=')[1].strip()
    else:
        center_time = None

    LiCSARweb = 'http://gws-access.ceda.ac.uk/public/nceo_geohazards/LiCSAR_products/'

    ### Frame ID even if not used
    if not frameID:  ## if not specified
        _tmp = re.findall(r'\d{3}[AD]_\d{5}_\d{6}', geocdir)
        ##e.g., 021D_04972_131213
        if len(_tmp) != 0:  ## if not found, keep []
            frameID = _tmp[0]
            trackID = str(int(frameID[0:3]))
    else:
        trackID = str(int(frameID[0:3]))

    #%% ENU
    for ENU in ['E', 'N', 'U']:
        print('\nCreate {}'.format(ENU + '.geo'), flush=True)
        enutif = glob.glob(os.path.join(geocdir, '*.geo.{}.tif'.format(ENU)))

        ### Download if not exist
        if len(enutif) == 0:
            print('  No *.geo.{}.tif found in {}'.format(
                ENU, os.path.basename(geocdir)),
                  flush=True)

            if not frameID:  ## if frameID not found above
                print('  Frame ID cannot be identified from dir name!',
                      file=sys.stderr)
                print('  Use -f option if you need {}.geo'.format(ENU),
                      file=sys.stderr)
                continue

            ### Download tif
            url = os.path.join(LiCSARweb, trackID, frameID, 'metadata',
                               '{}.geo.{}.tif'.format(frameID, ENU))
            enutif = os.path.join(geocdir,
                                  '{}.geo.{}.tif'.format(frameID, ENU))
            if not tools_lib.download_data(url, enutif):
                print('  Error while downloading from {}'.format(url),
                      file=sys.stderr,
                      flush=True)
                continue
            else:
                print('  {} dowonloaded from LiCSAR-portal'.format(
                    os.path.basename(url)),
                      flush=True)
        else:
            enutif = enutif[0]  ## first one

        ### Create float
        data = gdal.Open(enutif).ReadAsArray()
        data[data == 0] = np.nan

        if nlook != 1:
            ### Multilook
            data = tools_lib.multilook(data, nlook, nlook)

        outfile = os.path.join(outdir, ENU + '.geo')
        data.tofile(outfile)
        print('  {}.geo created'.format(ENU), flush=True)

    #%% mli
    mlitif = os.path.join(geocdir, '{}.geo.mli.tif'.format(frameID))
    if os.path.exists(mlitif):
        print('\nCreate slc.mli', flush=True)
        mli = gdal.Open(mlitif).ReadAsArray()
        mli[mli == 0] = np.nan

        if nlook != 1:
            ### Multilook
            mli = tools_lib.multilook(mli, nlook, nlook)

        mlifile = os.path.join(outdir, 'slc.mli')
        mli.tofile(mlifile)
        mlipngfile = mlifile + '.png'
        vmin = np.nanpercentile(mli, 5)
        vmax = np.nanpercentile(mli, 95)
        plot_lib.make_im_png(mli,
                             mlipngfile,
                             'gray',
                             'MLI',
                             vmin,
                             vmax,
                             cbar=True)
        print('  slc.mli[.png] created', flush=True)

    #%% hgt
    hgttif = os.path.join(geocdir, '{}.geo.hgt.tif'.format(frameID))
    if os.path.exists(hgttif):
        print('\nCreate hgt', flush=True)
        hgt = gdal.Open(hgttif).ReadAsArray()
        hgt[hgt == 0] = np.nan

        if nlook != 1:
            ### Multilook
            hgt = tools_lib.multilook(hgt, nlook, nlook)

        hgtfile = os.path.join(outdir, 'hgt')
        hgt.tofile(hgtfile)
        hgtpngfile = hgtfile + '.png'
        vmax = np.nanpercentile(hgt, 99)
        vmin = -vmax / 3  ## bnecause 1/4 of terrain is blue
        plot_lib.make_im_png(hgt,
                             hgtpngfile,
                             'terrain',
                             'DEM (m)',
                             vmin,
                             vmax,
                             cbar=True)
        print('  hgt[.png] created', flush=True)

    #%% tif -> float (with multilook/downsampling)
    print('\nCreate unw and cc', flush=True)
    ifgdates = tools_lib.get_ifgdates(geocdir)
    n_ifg = len(ifgdates)

    ### First check if float already exist
    ifgdates2 = []
    for i, ifgd in enumerate(ifgdates):
        ifgdir1 = os.path.join(outdir, ifgd)
        unwfile = os.path.join(ifgdir1, ifgd + '.unw')
        ccfile = os.path.join(ifgdir1, ifgd + '.cc')
        if not (os.path.exists(unwfile) and os.path.exists(ccfile)):
            ifgdates2.append(ifgd)

    n_ifg2 = len(ifgdates2)
    if n_ifg - n_ifg2 > 0:
        print("  {0:3}/{1:3} unw and cc already exist. Skip".format(
            n_ifg - n_ifg2, n_ifg),
              flush=True)

    ### Create
    for i, ifgd in enumerate(ifgdates2):
        if np.mod(i, 10) == 0:
            print("  {0:3}/{1:3}th IFG...".format(i, n_ifg2), flush=True)

        unw_tiffile = os.path.join(geocdir, ifgd, ifgd + '.geo.unw.tif')
        cc_tiffile = os.path.join(geocdir, ifgd, ifgd + '.geo.cc.tif')

        ### Check if inputs exist
        if not os.path.exists(unw_tiffile):
            print('  No {} found. Skip'.format(ifgd + '.geo.unw.tif'),
                  flush=True)
            with open(no_unw_list, 'a') as f:
                print('{}'.format(ifgd), file=f)
            continue
        elif not os.path.exists(cc_tiffile):
            print('  No {} found. Skip'.format(ifgd + '.geo.cc.tif'),
                  flush=True)
            with open(no_unw_list, 'a') as f:
                print('{}'.format(ifgd), file=f)
            continue

        ### Output dir and files
        ifgdir1 = os.path.join(outdir, ifgd)
        if not os.path.exists(ifgdir1): os.mkdir(ifgdir1)
        unwfile = os.path.join(ifgdir1, ifgd + '.unw')
        ccfile = os.path.join(ifgdir1, ifgd + '.cc')

        ### Read data from geotiff
        try:
            unw = gdal.Open(unw_tiffile).ReadAsArray()
            unw[unw == 0] = np.nan
        except:  ## if broken
            print('  {} cannot open. Skip'.format(ifgd + '.geo.unw.tif'),
                  flush=True)
            with open(no_unw_list, 'a') as f:
                print('{}'.format(ifgd), file=f)
            shutil.rmtree(ifgdir1)
            continue

        try:
            cc = gdal.Open(cc_tiffile).ReadAsArray()
            #if cc.dtype == np.uint8: ## New format since 201910
            #cc = cc.astype(np.float32)/255
            #cc[cc==0] = np.nan
        except:  ## if broken
            print('  {} cannot open. Skip'.format(ifgd + '.geo.cc.tif'),
                  flush=True)
            with open(no_unw_list, 'a') as f:
                print('{}'.format(ifgd), file=f)
            shutil.rmtree(ifgdir1)
            continue

        ### Read info (only once)
        ## If all float already exist, this is not done, but no problem because
        ## par files should alerady be exits!
        if not 'length' in locals():
            geotiff = gdal.Open(unw_tiffile)
            width = geotiff.RasterXSize
            length = geotiff.RasterYSize
            lon_w_p, dlon, _, lat_n_p, _, dlat = geotiff.GetGeoTransform()
            ## lat lon are in pixel registration. dlat is negative
            lon_w_g = lon_w_p + dlon / 2
            lat_n_g = lat_n_p + dlat / 2
            ## to grit registration by shifting half pixel inside
            if nlook != 1:
                width = int(width / nlook)
                length = int(length / nlook)
                dlon = dlon * nlook
                dlat = dlat * nlook

        ### Multilook
        if nlook != 1:
            unw = tools_lib.multilook(unw, nlook, nlook, n_valid_thre)
            cc = cc.astype(np.float32)
            cc[cc == 0] = np.nan
            cc = tools_lib.multilook(cc, nlook, nlook, n_valid_thre)
            cc = cc.astype(np.uint8)  ##nan->0, max255, auto-floored

        ### Output float
        unw.tofile(unwfile)
        cc.tofile(ccfile)

        ### Make png
        unwpngfile = os.path.join(ifgdir1, ifgd + '.unw.png')
        plot_lib.make_im_png(np.angle(np.exp(1j * unw / cycle) * cycle),
                             unwpngfile,
                             cmap,
                             ifgd + '.unw',
                             vmin=-np.pi,
                             vmax=np.pi,
                             cbar=False)

    #%% EQA.dem_par, slc.mli.par
    if not os.path.exists(mlipar):
        print('\nCreate slc.mli.par', flush=True)
        radar_freq = 5.405e9  ## fixed for Sentnel-1

        with open(mlipar, 'w') as f:
            print('range_samples:   {}'.format(width), file=f)
            print('azimuth_lines:   {}'.format(length), file=f)
            print('radar_frequency: {} Hz'.format(radar_freq), file=f)
            if center_time is not None:
                print('center_time: {}'.format(center_time), file=f)

    if not os.path.exists(dempar):
        print('\nCreate EQA.dem_par', flush=True)

        text = [
            "Gamma DIFF&GEO DEM/MAP parameter file", "title: DEM",
            "DEM_projection:     EQA", "data_format:        REAL*4",
            "DEM_hgt_offset:          0.00000",
            "DEM_scale:               1.00000", "width: {}".format(width),
            "nlines: {}".format(length),
            "corner_lat:     {}  decimal degrees".format(lat_n_g),
            "corner_lon:    {}  decimal degrees".format(lon_w_g),
            "post_lat: {} decimal degrees".format(dlat),
            "post_lon: {} decimal degrees".format(dlon), "",
            "ellipsoid_name: WGS 84", "ellipsoid_ra:        6378137.000   m",
            "ellipsoid_reciprocal_flattening:  298.2572236", "",
            "datum_name: WGS 1984", "datum_shift_dx:              0.000   m",
            "datum_shift_dy:              0.000   m",
            "datum_shift_dz:              0.000   m",
            "datum_scale_m:         0.00000e+00",
            "datum_rotation_alpha:  0.00000e+00   arc-sec",
            "datum_rotation_beta:   0.00000e+00   arc-sec",
            "datum_rotation_gamma:  0.00000e+00   arc-sec",
            "datum_country_list: Global Definition, WGS84, World\n"
        ]

        with open(dempar, 'w') as f:
            f.write('\n'.join(text))

    #%% bperp
    print('\nCopy baselines file', flush=True)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    if os.path.exists(bperp_file_in):
        ## Check exisiting bperp_file
        if not io_lib.read_bperp_file(bperp_file_in, imdates):
            print('  baselines file found, but not complete. Make dummy',
                  flush=True)
            io_lib.make_dummy_bperp(bperp_file_out, imdates)
        else:
            shutil.copyfile(bperp_file_in, bperp_file_out)
    else:
        print('  No valid baselines exists.', flush=True)
        if not frameID:  ## if frameID not found above
            print('  Frame ID cannot be identified from dir name!')
            print('  Make dummy.', flush=True)
            io_lib.make_dummy_bperp(bperp_file_out, imdates)
        else:
            print('  Try download.', flush=True)
            url = os.path.join(LiCSARweb, trackID, frameID, 'metadata',
                               'baselines')
            if not tools_lib.download_data(url, bperp_file_out):
                print(
                    '  Error while downloading from {}.\n  Make dummy.'.format(
                        url),
                    file=sys.stderr,
                    flush=True)
                io_lib.make_dummy_bperp(bperp_file_out, imdates)
            else:
                print('  {} dowonloaded from LiCSAR-portal'.format(
                    os.path.basename(url)),
                      flush=True)
                if not io_lib.read_bperp_file(bperp_file_out, imdates):
                    print('  but not complete. Make dummy.', flush=True)
                    io_lib.make_dummy_bperp(bperp_file_out, imdates)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(outdir)))
Exemple #13
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = 1.0
    date = 20200225
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    ifgfile = []
    bperpfile = []
    pngfile = 'network.png'
    bad_ifgfile = []
    plot_bad_flag = True

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hi:b:o:r:",
                                       ["help", "not_plot_bad"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-i':
                ifgfile = a
            elif o == '-b':
                bperpfile = a
            elif o == '-o':
                pngfile = a
            elif o == '-r':
                bad_ifgfile = a
            elif o == '--not_plot_bad':
                plot_bad_flag = False

        if not ifgfile:
            raise Usage('No ifg list given, -i is not optional!')
        elif not os.path.exists(ifgfile):
            raise Usage('No {} exists!'.format(ifgfile))
        elif not bperpfile:
            raise Usage('No bperp list given, -b is not optional!')
        elif not os.path.exists(bperpfile):
            raise Usage('No {} exists!'.format(bperpfile))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Read info
    ifgdates = io_lib.read_ifg_list(ifgfile)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    bperp = io_lib.read_bperp_file(bperpfile, imdates)

    if bad_ifgfile:
        bad_ifgdates = io_lib.read_ifg_list(bad_ifgfile)
    else:
        bad_ifgdates = []

    #%% Plot image
    plot_lib.plot_network(ifgdates, bperp, bad_ifgdates, pngfile,
                          plot_bad_flag)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output: {}\n'.format(pngfile), flush=True)
Exemple #14
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    ifgdir = []
    tsadir = []
    refflag = 'auto'  ## not supported
    inv_alg = 'LS'
    n_core = 1

    memory_size = 4000
    gamma = 0.0001
    n_unw_r_thre = []
    keep_incfile = False

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hd:t:r:", [
                "help", "mem_size=", "gamma=", "n_unw_r_thre=", "keep_incfile",
                "inv_alg=", "n_core="
            ])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-d':
                ifgdir = a
            elif o == '-t':
                tsadir = a
            elif o == '-r':
                refflag = a
            elif o == '--mem_size':
                memory_size = float(a)
            elif o == '--gamma':
                gamma = float(a)
            elif o == '--n_unw_r_thre':
                n_unw_r_thre = float(a)
            elif o == '--keep_incfile':
                keep_incfile = True
            elif o == '--inv_alg':
                inv_alg = a
            elif o == '--n_core':
                n_core = int(a)

        if not ifgdir:
            raise Usage('No data directory given, -d is not optional!')
        elif not os.path.isdir(ifgdir):
            raise Usage('No {} dir exists!'.format(ifgdir))
        elif not os.path.exists(os.path.join(ifgdir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(ifgdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Directory settings
    ifgdir = os.path.abspath(ifgdir)

    if not tsadir:
        tsadir = os.path.join(os.path.dirname(ifgdir),
                              'TS_' + os.path.basename(ifgdir))

    if not os.path.isdir(tsadir):
        print('\nNo {} exists!'.format(tsadir), file=sys.stderr)
        return 1

    tsadir = os.path.abspath(tsadir)
    resultsdir = os.path.join(tsadir, 'results')
    infodir = os.path.join(tsadir, 'info')
    netdir = os.path.join(tsadir, 'network')

    bad_ifg11file = os.path.join(infodir, '11bad_ifg.txt')
    bad_ifg12file = os.path.join(infodir, '12bad_ifg.txt')
    reffile = os.path.join(infodir, 'ref.txt')

    incdir = os.path.join(tsadir, '13increment')
    if not os.path.exists(incdir): os.mkdir(incdir)

    resdir = os.path.join(tsadir, '13resid')
    if not os.path.exists(resdir): os.mkdir(resdir)
    restxtfile = os.path.join(infodir, '13resid.txt')

    cumh5file = os.path.join(tsadir, 'cum.h5')

    #%% Check files
    try:
        if not os.path.exists(bad_ifg11file):
            raise Usage('No 11bad_ifg.txt file exists in {}!'.format(tsadir))
        if not os.path.exists(bad_ifg12file):
            raise Usage('No 12bad_ifg.txt file exists in {}!'.format(tsadir))
        if not os.path.exists(reffile):
            raise Usage('No ref.txt file exists in {}!'.format(tsadir))
    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Check and set reference
    if refflag == 'auto':  # Automatic setting based on ref.txt
        with open(reffile, "r") as f:
            refarea = f.read().split()[0]  #str, x1/x2/y1/y2
        refx1, refx2, refy1, refy2 = [
            int(s) for s in re.split('[:/]', refarea)
        ]

    #%% Read data information
    ### Get size
    mlipar = os.path.join(ifgdir, 'slc.mli.par')
    width = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))
    speed_of_light = 299792458  #m/s
    radar_frequency = float(io_lib.get_param_par(mlipar,
                                                 'radar_frequency'))  #Hz
    wavelength = speed_of_light / radar_frequency  #meter
    coef_r2m = -wavelength / 4 / np.pi * 1000  #rad -> mm, positive is -LOS

    ### Calc pixel spacing depending on IFG or GEOC, used in later spatial filter
    dempar = os.path.join(ifgdir, 'EQA.dem_par')
    width_geo = int(io_lib.get_param_par(dempar, 'width'))
    length_geo = int(io_lib.get_param_par(dempar, 'nlines'))
    dlat = float(io_lib.get_param_par(dempar, 'post_lat'))  #negative
    dlon = float(io_lib.get_param_par(dempar, 'post_lon'))  #positive
    lat1 = float(io_lib.get_param_par(dempar, 'corner_lat'))
    lon1 = float(io_lib.get_param_par(dempar, 'corner_lon'))
    if width == width_geo and length == length_geo:  ## Geocoded
        print('In geographical coordinates', flush=True)
        centerlat = lat1 + dlat * (length / 2)
        ra = float(io_lib.get_param_par(dempar, 'ellipsoid_ra'))
        recip_f = float(
            io_lib.get_param_par(dempar, 'ellipsoid_reciprocal_flattening'))
        rb = ra * (1 - 1 / recip_f)  ## polar radius
        pixsp_a = 2 * np.pi * rb / 360 * abs(dlat)
        pixsp_r = 2 * np.pi * ra / 360 * dlon * np.cos(np.deg2rad(centerlat))

        ### Make ref.kml
        reflat = lat1 + dlat * refy1
        reflon = lon1 + dlon * refx1
        make_point_kml(reflat, reflon, os.path.join(infodir, 'ref.kml'))

    else:
        print('In radar coordinates', flush=True)
        pixsp_r_org = float(io_lib.get_param_par(mlipar,
                                                 'range_pixel_spacing'))
        pixsp_a = float(io_lib.get_param_par(mlipar, 'azimuth_pixel_spacing'))
        inc_agl = float(io_lib.get_param_par(mlipar, 'incidence_angle'))
        pixsp_r = pixsp_r_org / np.sin(np.deg2rad(inc_agl))

    ### Set n_unw_r_thre and cycle depending on L- or C-band
    if wavelength > 0.2:  ## L-band
        if not n_unw_r_thre: n_unw_r_thre = 0.5
        cycle = 1.5  # 2pi/cycle for comparison png
    elif wavelength <= 0.2:  ## C-band
        if not n_unw_r_thre: n_unw_r_thre = 1.0
        cycle = 3  # 3*2pi/cycle for comparison png

    #%% Read date and network information
    ### Get all ifgdates in ifgdir
    ifgdates_all = tools_lib.get_ifgdates(ifgdir)
    imdates_all = tools_lib.ifgdates2imdates(ifgdates_all)
    n_im_all = len(imdates_all)
    n_ifg_all = len(ifgdates_all)

    ### Read bad_ifg11 and 12
    bad_ifg11 = io_lib.read_ifg_list(bad_ifg11file)
    bad_ifg12 = io_lib.read_ifg_list(bad_ifg12file)
    bad_ifg_all = list(set(bad_ifg11 + bad_ifg12))
    bad_ifg_all.sort()

    ### Remove bad ifgs and images from list
    ifgdates = list(set(ifgdates_all) - set(bad_ifg_all))
    ifgdates.sort()

    imdates = tools_lib.ifgdates2imdates(ifgdates)

    n_ifg = len(ifgdates)
    n_ifg_bad = len(set(bad_ifg11 + bad_ifg12))
    n_im = len(imdates)
    n_unw_thre = int(n_unw_r_thre * n_im)

    ### Make 13used_image.txt
    imfile = os.path.join(infodir, '13used_image.txt')
    with open(imfile, 'w') as f:
        for i in imdates:
            print('{}'.format(i), file=f)

    ### Calc dt in year
    imdates_dt = ([
        dt.datetime.strptime(imd, '%Y%m%d').toordinal() for imd in imdates
    ])
    dt_cum = np.float32((np.array(imdates_dt) - imdates_dt[0]) / 365.25)

    ### Construct G and Aloop matrix for increment and n_gap
    G = inv_lib.make_sb_matrix(ifgdates)
    Aloop = loop_lib.make_loop_matrix(ifgdates)
    n_loop = Aloop.shape[0]  # (n_loop,n_ifg)

    #%% Plot network
    ## Read bperp data or dummy
    bperp_file = os.path.join(ifgdir, 'baselines')
    if os.path.exists(bperp_file):
        bperp_all = io_lib.read_bperp_file(bperp_file, imdates_all)
        bperp = io_lib.read_bperp_file(bperp_file, imdates)
    else:  #dummy
        bperp_all = np.random.random(len(imdates_all)).tolist()
        bperp = np.random.random(n_im).tolist()

    pngfile = os.path.join(netdir, 'network13_all.png')
    plot_lib.plot_network(ifgdates_all, bperp_all, [], pngfile, pdf=True)

    pngfile = os.path.join(netdir, 'network13.png')
    plot_lib.plot_network(ifgdates_all,
                          bperp_all,
                          bad_ifg_all,
                          pngfile,
                          pdf=True)

    pngfile = os.path.join(netdir, 'network13_nobad.png')
    plot_lib.plot_network(ifgdates_all,
                          bperp_all,
                          bad_ifg_all,
                          pngfile,
                          plot_bad=False,
                          pdf=True)

    #%% Get patch row number
    if inv_alg == 'WLS':
        n_store_data = n_ifg * 3 + n_im * 2 + n_im * 0.3  #
    else:
        n_store_data = n_ifg * 2 + n_im * 2 + n_im * 0.3  #not sure

    n_patch, patchrow = tools_lib.get_patchrow(width, length, n_store_data,
                                               memory_size)

    #%% Display and output settings & paramters
    print('')
    print('Size of image (w,l)    : {}, {}'.format(width, length))
    print('# of all images        : {}'.format(n_im_all))
    print('# of images to be used : {}'.format(n_im))
    print('# of all ifgs          : {}'.format(n_ifg_all))
    print('# of ifgs to be used   : {}'.format(n_ifg))
    print('# of removed ifgs      : {}'.format(n_ifg_bad))
    print('Threshold of used unw  : {}'.format(n_unw_thre))
    print('')
    print('Reference area (X/Y)   : {}:{}/{}:{}'.format(
        refx1, refx2, refy1, refy2))
    print('Allowed memory size    : {} MB'.format(memory_size))
    print('Number of patches      : {}'.format(n_patch))
    print('Inversion algorism     : {}'.format(inv_alg))
    print('Gamma value            : {}'.format(gamma), flush=True)

    with open(os.path.join(infodir, 'parameters.txt'), "w") as f:
        print('range_samples:  {}'.format(width), file=f)
        print('azimuth_lines:  {}'.format(length), file=f)
        print('wavelength:     {}'.format(wavelength), file=f)
        print('n_im_all:       {}'.format(n_im_all), file=f)
        print('n_im:           {}'.format(n_im), file=f)
        print('n_ifg_all:      {}'.format(n_ifg_all), file=f)
        print('n_ifg:          {}'.format(n_ifg), file=f)
        print('n_ifg_bad:      {}'.format(n_ifg_bad), file=f)
        print('n_unw_thre:     {}'.format(n_unw_thre), file=f)
        print('ref_area:       {}:{}/{}:{}'.format(refx1, refx2, refy1, refy2),
              file=f)
        print('memory_size:    {} MB'.format(memory_size), file=f)
        print('n_patch:        {}'.format(n_patch), file=f)
        print('inv_alg:        {}'.format(inv_alg), file=f)
        print('gamma:          {}'.format(gamma), file=f)
        print('pixel_spacing_r: {:.2f} m'.format(pixsp_r), file=f)
        print('pixel_spacing_a: {:.2f} m'.format(pixsp_a), file=f)

#%% Ref phase for inversion
    lengththis = refy2 - refy1
    countf = width * refy1
    countl = width * lengththis  # Number to be read
    ref_unw = []
    for i, ifgd in enumerate(ifgdates):
        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        f = open(unwfile, 'rb')
        f.seek(countf * 4, os.SEEK_SET)  #Seek for >=2nd path, 4 means byte

        ### Read unw data (mm) at ref area
        unw = np.fromfile(f, dtype=np.float32, count=countl).reshape(
            (lengththis, width))[:, refx1:refx2] * coef_r2m

        unw[unw == 0] = np.nan
        if np.all(np.isnan(unw)):
            print('All nan in ref area in {}.'.format(ifgd))
            print('Rerun LiCSBAS12.')
            return 1

        ref_unw.append(np.nanmean(unw))

        f.close()

    #%% Open cum.h5 for output
    if os.path.exists(cumh5file): os.remove(cumh5file)
    cumh5 = h5.File(cumh5file, 'w')
    cumh5.create_dataset('imdates', data=[np.int32(imd) for imd in imdates])
    cumh5.create_dataset('refarea', data=refarea)
    if not np.all(np.abs(np.array(bperp)) <= 1):  # if not dummy
        cumh5.create_dataset('bperp', data=bperp)
    cum = cumh5.require_dataset('cum', (n_im, length, width), dtype=np.float32)
    vel = cumh5.require_dataset('vel', (length, width), dtype=np.float32)
    vconst = cumh5.require_dataset('vintercept', (length, width),
                                   dtype=np.float32)
    gap = cumh5.require_dataset('gap', (n_im - 1, length, width),
                                dtype=np.int8)

    if width == width_geo and length == length_geo:  ## if geocoded
        cumh5.create_dataset('corner_lat', data=lat1)
        cumh5.create_dataset('corner_lon', data=lon1)
        cumh5.create_dataset('post_lat', data=dlat)
        cumh5.create_dataset('post_lon', data=dlon)

    #%% For each patch
    i_patch = 1
    for rows in patchrow:
        print('\nProcess {0}/{1}th line ({2}/{3}th patch)...'.format(
            rows[1], patchrow[-1][-1], i_patch, n_patch),
              flush=True)
        start2 = time.time()

        #%% Read data
        ### Allocate memory
        lengththis = rows[1] - rows[0]
        n_pt_all = lengththis * width
        unwpatch = np.zeros((n_ifg, lengththis, width), dtype=np.float32)

        if inv_alg == 'WLS':
            cohpatch = np.zeros((n_ifg, lengththis, width), dtype=np.float32)

        ### For each ifg
        print("  Reading {0} ifg's unw data...".format(n_ifg), flush=True)
        countf = width * rows[0]
        countl = width * lengththis
        for i, ifgd in enumerate(ifgdates):
            unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
            f = open(unwfile, 'rb')
            f.seek(countf * 4, os.SEEK_SET)  #Seek for >=2nd path, 4 means byte

            ### Read unw data (mm) at patch area
            unw = np.fromfile(f, dtype=np.float32, count=countl).reshape(
                (lengththis, width)) * coef_r2m
            unw[unw == 0] = np.nan  # Fill 0 with nan
            unw = unw - ref_unw[i]
            unwpatch[i] = unw
            f.close()

            ### Read coh file at patch area for WLS
            if inv_alg == 'WLS':
                cohfile = os.path.join(ifgdir, ifgd, ifgd + '.cc')
                f = open(cohfile, 'rb')
                f.seek(countf * 4,
                       os.SEEK_SET)  #Seek for >=2nd path, 4 means byte
                cohpatch[i, :, :] = np.fromfile(f,
                                                dtype=np.float32,
                                                count=countl).reshape(
                                                    (lengththis, width))

        unwpatch = unwpatch.reshape(
            (n_ifg, n_pt_all)).transpose()  #(n_pt_all, n_ifg)

        ### Calc variance from coherence for WLS
        if inv_alg == 'WLS':
            cohpatch = cohpatch.reshape(
                (n_ifg, n_pt_all)).transpose()  #(n_pt_all, n_ifg)
            cohpatch[
                cohpatch <
                0.01] = 0.01  ## because negative value possible due to geocode
            cohpatch[
                cohpatch > 0.99] = 0.99  ## because >1 possible due to geocode
            varpatch = (1 - cohpatch**2) / (2 * cohpatch**2)
            del cohpatch

        #%% Remove points with less valid data than n_unw_thre
        ix_unnan_pt = np.where(
            np.sum(~np.isnan(unwpatch), axis=1) > n_unw_thre)[0]
        n_pt_unnan = len(ix_unnan_pt)

        unwpatch = unwpatch[ix_unnan_pt, :]  ## keep only unnan data
        if inv_alg == 'WLS':
            varpatch = varpatch[ix_unnan_pt, :]  ## keep only unnan data

        print('  {}/{} points removed due to not enough ifg data...'.format(
            n_pt_all - n_pt_unnan, n_pt_all),
              flush=True)

        #%% Compute number of gaps, ifg_noloop, maxTlen point-by-point
        ns_gap_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
        gap_patch = np.zeros((n_im - 1, n_pt_all), dtype=np.int8)
        ns_ifg_noloop_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
        maxTlen_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan

        ### n_gap
        print('\n  Identifing gaps and counting n_gap...', flush=True)
        #        ns_unw_unnan4inc = (np.matmul(np.int8(G[:, :, None]), (~np.isnan(unwpatch.T))[:, None, :])).sum(axis=0, dtype=np.int16) #n_ifg, n_im-1, n_pt -> n_im-1, n_pt
        ns_unw_unnan4inc = np.array([
            (G[:, i] * (~np.isnan(unwpatch))).sum(axis=1, dtype=np.int16)
            for i in range(n_im - 1)
        ])  #n_ifg*(n_pt,n_ifg) -> (n_im-1,n_pt)
        ns_gap_patch[ix_unnan_pt] = (ns_unw_unnan4inc == 0).sum(axis=0)  #n_pt
        gap_patch[:, ix_unnan_pt] = ns_unw_unnan4inc == 0

        del ns_unw_unnan4inc

        ### n_ifg_noloop
        print('  Counting n_ifg_noloop...', flush=True)
        # n_ifg*(n_pt,n_ifg)->(n_loop,n_pt)
        # Number of ifgs for each loop at eath point.
        # 3 means complete loop, 1 or 2 means broken loop.
        ns_ifg4loop = np.array([
            (np.abs(Aloop[i, :]) * (~np.isnan(unwpatch))).sum(axis=1)
            for i in range(n_loop)
        ])
        bool_loop = (ns_ifg4loop == 3
                     )  #(n_loop,n_pt) identify complete loop only

        # n_loop*(n_loop,n_pt)*n_pt->(n_ifg,n_pt)
        # Number of loops for each ifg at eath point.
        ns_loop4ifg = np.array([((np.abs(Aloop[:, i]) * bool_loop.T).T *
                                 (~np.isnan(unwpatch[:, i]))).sum(axis=0)
                                for i in range(n_ifg)])  #

        ns_ifg_noloop_tmp = (ns_loop4ifg == 0).sum(axis=0)  #n_pt
        ns_nan_ifg = np.isnan(unwpatch).sum(axis=1)  #n_pt, nan ifg count
        ns_ifg_noloop_patch[ix_unnan_pt] = ns_ifg_noloop_tmp - ns_nan_ifg

        del bool_loop, ns_ifg4loop, ns_loop4ifg

        ### maxTlen
        _maxTlen = np.zeros((n_pt_unnan), dtype=np.float32)  #temporaly
        _Tlen = np.zeros((n_pt_unnan), dtype=np.float32)  #temporaly
        for imx in range(n_im - 1):
            _Tlen = _Tlen + (dt_cum[imx + 1] - dt_cum[imx])  ## Adding dt
            _Tlen[gap_patch[imx, ix_unnan_pt] == 1] = 0  ## reset to 0 if gap
            _maxTlen[_maxTlen < _Tlen] = _Tlen[_maxTlen <
                                               _Tlen]  ## Set Tlen to maxTlen
        maxTlen_patch[ix_unnan_pt] = _maxTlen

        #%% Time series inversion
        print('\n  Small Baseline inversion by {}...\n'.format(inv_alg),
              flush=True)
        if inv_alg == 'WLS':
            inc_tmp, vel_tmp, vconst_tmp = inv_lib.invert_nsbas_wls(
                unwpatch, varpatch, G, dt_cum, gamma, n_core)
        else:
            inc_tmp, vel_tmp, vconst_tmp = inv_lib.invert_nsbas(
                unwpatch, G, dt_cum, gamma, n_core)

        ### Set to valuables
        inc_patch = np.zeros((n_im - 1, n_pt_all), dtype=np.float32) * np.nan
        vel_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
        vconst_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan

        inc_patch[:, ix_unnan_pt] = inc_tmp
        vel_patch[ix_unnan_pt] = vel_tmp
        vconst_patch[ix_unnan_pt] = vconst_tmp

        ### Calculate residuals
        res_patch = np.zeros((n_ifg, n_pt_all), dtype=np.float32) * np.nan
        res_patch[:, ix_unnan_pt] = unwpatch.T - np.dot(G, inc_tmp)

        res_sumsq = np.nansum(res_patch**2, axis=0)
        res_n = np.float32((~np.isnan(res_patch)).sum(axis=0))
        res_n[res_n == 0] = np.nan  # To avoid 0 division
        res_rms_patch = np.sqrt(res_sumsq / res_n)

        ### Cumulative displacememt
        cum_patch = np.zeros((n_im, n_pt_all), dtype=np.float32) * np.nan
        cum_patch[1:, :] = np.cumsum(inc_patch, axis=0)

        ## Fill 1st image with 0 at unnan points from 2nd images
        bool_unnan_pt = ~np.isnan(cum_patch[1, :])
        cum_patch[0, bool_unnan_pt] = 0

        ## Drop (fill with nan) interpolated cum by 2 continuous gaps
        for i in range(n_im - 2):  ## from 1->n_im-1
            gap2 = gap_patch[i, :] + gap_patch[i + 1, :]
            bool_gap2 = (gap2 == 2
                         )  ## true if 2 continuous gaps for each point
            cum_patch[i + 1, :][bool_gap2] = np.nan

        ## Last (n_im th) image. 1 gap means interpolated
        cum_patch[-1, :][gap_patch[-1, :] == 1] = np.nan

        #%% Output data and image
        ### cum.h5 file
        cum[:, rows[0]:rows[1], :] = cum_patch.reshape(
            (n_im, lengththis, width))
        vel[rows[0]:rows[1], :] = vel_patch.reshape((lengththis, width))
        vconst[rows[0]:rows[1], :] = vconst_patch.reshape((lengththis, width))
        gap[:, rows[0]:rows[1], :] = gap_patch.reshape(
            (n_im - 1, lengththis, width))

        ### Others
        openmode = 'w' if rows[0] == 0 else 'a'  #w only 1st patch

        ## For each imd. cum and inc
        for imx, imd in enumerate(imdates):
            ## Incremental displacement
            if imd == imdates[-1]: continue  #skip last
            incfile = os.path.join(incdir,
                                   '{0}_{1}.inc'.format(imd, imdates[imx + 1]))
            with open(incfile, openmode) as f:
                inc_patch[imx, :].tofile(f)

        ## For each ifgd. resid
        for i, ifgd in enumerate(ifgdates):
            resfile = os.path.join(resdir, '{0}.res'.format(ifgd))
            with open(resfile, openmode) as f:
                res_patch[i, :].tofile(f)

        ## velocity and noise indecies in results dir
        names = [
            'vel', 'vintercept', 'resid_rms', 'n_gap', 'n_ifg_noloop',
            'maxTlen'
        ]
        data = [
            vel_patch, vconst_patch, res_rms_patch, ns_gap_patch,
            ns_ifg_noloop_patch, maxTlen_patch
        ]
        for i in range(len(names)):
            file = os.path.join(resultsdir, names[i])
            with open(file, openmode) as f:
                data[i].tofile(f)

        #%% Finish patch
        elapsed_time2 = int(time.time() - start2)
        hour2 = int(elapsed_time2 / 3600)
        minite2 = int(np.mod((elapsed_time2 / 60), 60))
        sec2 = int(np.mod(elapsed_time2, 60))
        print("  Elapsed time for {0}th patch: {1:02}h {2:02}m {3:02}s".format(
            i_patch, hour2, minite2, sec2),
              flush=True)

        i_patch += 1  #Next patch count

    #%% Close h5 file
    cumh5.close()

    #%% Output png images
    print('\nOutput png images...', flush=True)
    ### Incremental displacement
    for imx, imd in enumerate(imdates):
        if imd == imdates[-1]: continue  #skip last for increment
        ## Comparison of increment and daisy chain pair
        ifgd = '{}_{}'.format(imd, imdates[imx + 1])
        incfile = os.path.join(incdir, '{}.inc'.format(ifgd))
        unwfile = os.path.join(ifgdir, ifgd, '{}.unw'.format(ifgd))
        pngfile = os.path.join(incdir, '{}.inc_comp.png'.format(ifgd))

        inc = io_lib.read_img(incfile, length, width)

        try:
            unw = io_lib.read_img(unwfile, length, width) * coef_r2m
            ix_ifg = ifgdates.index(ifgd)
            unw = unw - ref_unw[ix_ifg]
        except:
            unw = np.zeros((length, width), dtype=np.float32) * np.nan

        ### Output png for comparison
        data3 = [
            np.angle(np.exp(1j * (data / coef_r2m / cycle)) * cycle)
            for data in [unw, inc, inc - unw]
        ]
        title3 = ['Daisy-chain IFG', 'Inverted', 'Difference']
        pngfile = os.path.join(incdir, '{}.increment.png'.format(ifgd))
        plot_lib.make_3im_png(data3,
                              pngfile,
                              'insar',
                              title3,
                              vmin=-np.pi,
                              vmax=np.pi,
                              cbar=False)

        if not keep_incfile:
            os.remove(incfile)

    ### Residual for each ifg. png and txt.
    cmap = 'jet'
    with open(restxtfile, "w") as f:
        print('# RMS of residual (mm)', file=f)
    for ifgd in ifgdates:
        infile = os.path.join(resdir, '{}.res'.format(ifgd))
        resid = io_lib.read_img(infile, length, width)
        resid_rms = np.sqrt(np.nanmean(resid**2))
        with open(restxtfile, "a") as f:
            print('{} {:5.2f}'.format(ifgd, resid_rms), file=f)

        pngfile = infile + '.png'
        title = 'Residual (mm) of {} (RMS:{:.2f}mm)'.format(ifgd, resid_rms)
        plot_lib.make_im_png(resid, pngfile, cmap, title,
                             -wavelength / 2 * 1000, wavelength / 2 * 1000)

        if not keep_incfile:
            os.remove(infile)

    ### Velocity and noise indices
    #names = ['vel', 'vconst', 'resid_rms', 'n_gap', 'n_ifg_noloop', 'maxTlen']
    cmins = [None, None, None, None, None, None]
    cmaxs = [None, None, None, None, None, None]
    cmaps = ['jet', 'jet', 'viridis_r', 'viridis_r', 'viridis_r', 'viridis']
    titles = [
        'Velocity (mm/yr)', 'Intercept of velocity (mm)',
        'RMS of residual (mm)', 'Number of gaps in SB network',
        'Number of ifgs with no loops',
        'Max length of connected SB network (yr)'
    ]

    for i in range(len(names)):
        file = os.path.join(resultsdir, names[i])
        data = io_lib.read_img(file, length, width)

        pngfile = file + '.png'

        ## Get color range if None
        if cmins[i] is None:
            cmins[i] = np.nanpercentile(data, 1)
        if cmaxs[i] is None:
            cmaxs[i] = np.nanpercentile(data, 99)
        if cmins[i] == cmaxs[i]: cmins[i] = cmaxs[i] - 1

        plot_lib.make_im_png(data, pngfile, cmaps[i], titles[i], cmins[i],
                             cmaxs[i])

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(tsadir)))
Exemple #15
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    #%% Set default
    frameID = []
    startdate = 20141001
    enddate = int(dt.date.today().strftime("%Y%m%d"))

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hf:s:e:", ["help"])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-f':
                frameID = a
            elif o == '-s':
                startdate = int(a)
            elif o == '-e':
                enddate = int(a)

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Determine frameID
    wd = os.getcwd()
    if not frameID:  ## if frameID not indicated
        _tmp = re.findall(r'\d{3}[AD]_\d{5}_\d{6}', wd)
        ##e.g., 021D_04972_131213
        if len(_tmp) == 0:
            print('\nFrame ID cannot be identified from dir name!',
                  file=sys.stderr)
            print('Use -f option', file=sys.stderr)
            return
        else:
            frameID = _tmp[0]
            print('\nFrame ID is {}\n'.format(frameID), flush=True)
    trackID = str(int(frameID[0:3]))

    #%% Directory and file setting
    outdir = os.path.join(wd, 'GEOC')
    if not os.path.exists(outdir): os.mkdir(outdir)
    os.chdir(outdir)

    LiCSARweb = 'http://gws-access.ceda.ac.uk/public/nceo_geohazards/LiCSAR_products/'

    #%% ENU
    for ENU in ['E', 'N', 'U']:
        enutif = '{}.geo.{}.tif'.format(frameID, ENU)
        if os.path.exists(enutif):
            print('{} already exist. Skip download.'.format(enutif),
                  flush=True)
            continue

        print('Download {}'.format(enutif), flush=True)

        url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', enutif)
        if not tools_lib.download_data(url, enutif):
            print('  Error while downloading from {}'.format(url),
                  file=sys.stderr,
                  flush=True)
            continue

    #%% baselines
    print('Download baselines', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'metadata', 'baselines')
    if not tools_lib.download_data(url, 'baselines'):
        print('  Error while downloading from {}'.format(url),
              file=sys.stderr,
              flush=True)

    #%% unw and cc
    ### Get available dates
    print('\nDownload geotiff of unw and cc', flush=True)
    url = os.path.join(LiCSARweb, trackID, frameID, 'products')
    response = requests.get(url)
    response.encoding = response.apparent_encoding  #avoid garble
    html_doc = response.text
    soup = BeautifulSoup(html_doc, "html.parser")
    tags = soup.find_all(href=re.compile(r"\d{8}_\d{8}"))
    ifgdates_all = [tag.get("href")[0:17] for tag in tags]

    ### Extract during start_date to end_date
    ifgdates = []
    for ifgd in ifgdates_all:
        mimd = int(ifgd[:8])
        simd = int(ifgd[-8:])
        if mimd >= startdate and simd <= enddate:
            ifgdates.append(ifgd)

    n_ifg = len(ifgdates)
    imdates = tools_lib.ifgdates2imdates(ifgdates)
    print('{} IFGs available from {} to {}'.format(n_ifg, imdates[0],
                                                   imdates[-1]),
          flush=True)

    ### Download
    for i, ifgd in enumerate(ifgdates):
        print('  Donwnloading {} ({}/{})...'.format(ifgd, i + 1, n_ifg),
              flush=True)
        url_unw = os.path.join(url, ifgd, ifgd + '.geo.unw.tif')
        path_unw = os.path.join(ifgd, ifgd + '.geo.unw.tif')
        if not os.path.exists(ifgd): os.mkdir(ifgd)
        if os.path.exists(path_unw):
            print('    {}.geo.unw.tif already exist. Skip'.format(ifgd),
                  flush=True)
        elif not tools_lib.download_data(url_unw, path_unw):
            print('    Error while downloading from {}'.format(url_unw),
                  file=sys.stderr,
                  flush=True)

        url_cc = os.path.join(url, ifgd, ifgd + '.geo.cc.tif')
        path_cc = os.path.join(ifgd, ifgd + '.geo.cc.tif')
        if os.path.exists(path_cc):
            print('    {}.geo.cc.tif already exist. Skip.'.format(ifgd),
                  flush=True)
        if not tools_lib.download_data(url_cc, path_cc):
            print('    Error while downloading from {}'.format(url_cc),
                  file=sys.stderr,
                  flush=True)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(outdir))
Exemple #16
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = 1.3
    date = 20200907
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    global Aloop, ifgdates, ifgdir, length, width, loop_pngdir  ## for parallel processing

    #%% Set default
    ifgdir = []
    tsadir = []
    loop_thre = 1.5
    n_para = len(os.sched_getaffinity(0))

    cmap_noise = 'viridis'
    cmap_noise_r = 'viridis_r'

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hd:t:l:",
                                       ["help", "n_para="])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-d':
                ifgdir = a
            elif o == '-t':
                tsadir = a
            elif o == '-l':
                loop_thre = float(a)
            elif o == '--n_para':
                n_para = int(a)

        if not ifgdir:
            raise Usage('No data directory given, -d is not optional!')
        elif not os.path.isdir(ifgdir):
            raise Usage('No {} dir exists!'.format(ifgdir))
        elif not os.path.exists(os.path.join(ifgdir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(ifgdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    print("\nloop_thre : {} rad".format(loop_thre), flush=True)

    #%% Directory setting
    ifgdir = os.path.abspath(ifgdir)

    if not tsadir:
        tsadir = os.path.join(os.path.dirname(ifgdir),
                              'TS_' + os.path.basename(ifgdir))

    if not os.path.isdir(tsadir):
        print('\nNo {} exists!'.format(tsadir), file=sys.stderr)
        return 1

    tsadir = os.path.abspath(tsadir)

    loopdir = os.path.join(tsadir, '12loop')
    if not os.path.exists(loopdir): os.mkdir(loopdir)

    loop_pngdir = os.path.join(loopdir, 'good_loop_png')
    bad_loop_pngdir = os.path.join(loopdir, 'bad_loop_png')
    bad_loop_cand_pngdir = os.path.join(loopdir, 'bad_loop_cand_png')

    if os.path.exists(loop_pngdir):
        shutil.move(loop_pngdir + '/', loop_pngdir + '_old')  #move to old dir
    if os.path.exists(bad_loop_pngdir):
        for png in glob.glob(bad_loop_pngdir + '/*.png'):
            shutil.move(png, loop_pngdir + '_old')  #move to old dir
        shutil.rmtree(bad_loop_pngdir)
    if os.path.exists(bad_loop_cand_pngdir):
        for png in glob.glob(bad_loop_cand_pngdir + '/*.png'):
            shutil.move(png, loop_pngdir + '_old')  #move to old dir
        shutil.rmtree(bad_loop_cand_pngdir)

    os.mkdir(loop_pngdir)
    os.mkdir(bad_loop_pngdir)
    os.mkdir(bad_loop_cand_pngdir)

    ifg_rasdir = os.path.join(tsadir, '12ifg_ras')
    if os.path.isdir(ifg_rasdir): shutil.rmtree(ifg_rasdir)
    os.mkdir(ifg_rasdir)

    bad_ifgrasdir = os.path.join(tsadir, '12bad_ifg_ras')
    if os.path.isdir(bad_ifgrasdir): shutil.rmtree(bad_ifgrasdir)
    os.mkdir(bad_ifgrasdir)

    bad_ifg_candrasdir = os.path.join(tsadir, '12bad_ifg_cand_ras')
    if os.path.isdir(bad_ifg_candrasdir): shutil.rmtree(bad_ifg_candrasdir)
    os.mkdir(bad_ifg_candrasdir)

    no_loop_ifgrasdir = os.path.join(tsadir, '12no_loop_ifg_ras')
    if os.path.isdir(no_loop_ifgrasdir): shutil.rmtree(no_loop_ifgrasdir)
    os.mkdir(no_loop_ifgrasdir)

    infodir = os.path.join(tsadir, 'info')
    if not os.path.exists(infodir): os.mkdir(infodir)

    resultsdir = os.path.join(tsadir, 'results')
    if not os.path.exists(resultsdir): os.mkdir(resultsdir)

    netdir = os.path.join(tsadir, 'network')

    #%% Read date, network information and size
    ### Get dates
    ifgdates = tools_lib.get_ifgdates(ifgdir)

    ### Read bad_ifg11
    bad_ifg11file = os.path.join(infodir, '11bad_ifg.txt')
    bad_ifg11 = io_lib.read_ifg_list(bad_ifg11file)

    ### Remove bad ifgs and images from list
    ifgdates = list(set(ifgdates) - set(bad_ifg11))
    ifgdates.sort()

    imdates = tools_lib.ifgdates2imdates(ifgdates)

    n_ifg = len(ifgdates)
    n_im = len(imdates)

    ### Get size
    mlipar = os.path.join(ifgdir, 'slc.mli.par')
    width = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))

    ### Get loop matrix
    Aloop = loop_lib.make_loop_matrix(ifgdates)
    n_loop = Aloop.shape[0]

    ### Extract no loop ifgs
    ns_loop4ifg = np.abs(Aloop).sum(axis=0)
    ixs_ifg_no_loop = np.where(ns_loop4ifg == 0)[0]
    no_loop_ifg = [ifgdates[ix] for ix in ixs_ifg_no_loop]

    #%% 1st loop closure check. First without reference
    print('\n1st Loop closure check and make png for all possible {} loops,'.
          format(n_loop),
          flush=True)
    print('with {} parallel processing...'.format(n_para), flush=True)

    bad_ifg_cand = []
    good_ifg = []

    ### Parallel processing
    p = multi.Pool(n_para)
    loop_ph_rms_ifg = np.array(p.map(loop_closure_1st_wrapper, range(n_loop)),
                               dtype=object)
    p.close()

    for i in range(n_loop):
        ### Find index of ifg
        ix_ifg12, ix_ifg23 = np.where(Aloop[i, :] == 1)[0]
        ix_ifg13 = np.where(Aloop[i, :] == -1)[0][0]
        ifgd12 = ifgdates[ix_ifg12]
        ifgd23 = ifgdates[ix_ifg23]
        ifgd13 = ifgdates[ix_ifg13]

        ### List as good or bad candidate
        if loop_ph_rms_ifg[i] >= loop_thre:  #Bad loop including bad ifg.
            bad_ifg_cand.extend([ifgd12, ifgd23, ifgd13])
        else:
            good_ifg.extend([ifgd12, ifgd23, ifgd13])

    if os.path.exists(loop_pngdir + '_old/'):
        shutil.rmtree(loop_pngdir + '_old/')

    #%% Identify bad ifgs and output text
    bad_ifg = loop_lib.identify_bad_ifg(bad_ifg_cand, good_ifg)

    bad_ifgfile = os.path.join(loopdir, 'bad_ifg_loop.txt')
    with open(bad_ifgfile, 'w') as f:
        for i in bad_ifg:
            print('{}'.format(i), file=f)

    ### Compute n_unw without bad_ifg11 and bad_ifg
    n_unw = np.zeros((length, width), dtype=np.int16)
    for ifgd in ifgdates:
        if ifgd in bad_ifg:
            continue

        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        unw = io_lib.read_img(unwfile, length, width)

        unw[unw == 0] = np.nan  # Fill 0 with nan
        n_unw += ~np.isnan(unw)  # Summing number of unnan unw

    #%% 2nd loop closure check without bad ifgs to define stable ref area
    print('\n2nd Loop closure check without bad ifgs to define ref area...',
          flush=True)
    ns_loop_ph = np.zeros((length, width), dtype=np.float32)
    ns_bad_loop = np.zeros((length, width), dtype=np.int16)
    loop_ph_rms_points = np.zeros((length, width), dtype=np.float32)

    for i in range(n_loop):
        if np.mod(i, 100) == 0:
            print("  {0:3}/{1:3}th loop...".format(i, n_loop), flush=True)

        ### Read unw
        unw12, unw23, unw13, ifgd12, ifgd23, ifgd13 = loop_lib.read_unw_loop_ph(
            Aloop[i, :], ifgdates, ifgdir, length, width)

        ### Skip if bad ifg is included
        if ifgd12 in bad_ifg or ifgd23 in bad_ifg or ifgd13 in bad_ifg:
            continue

        ## Calculate loop phase and rms at points
        loop_ph = unw12 + unw23 - unw13
        loop_2pin = int(np.round(np.nanmedian(loop_ph) /
                                 (2 * np.pi))) * 2 * np.pi
        loop_ph = loop_ph - loop_2pin  #unbias
        ns_loop_ph = ns_loop_ph + ~np.isnan(loop_ph)

        loop_ph_sq = loop_ph**2
        loop_ph_sq[np.isnan(loop_ph_sq)] = 0
        loop_ph_rms_points = loop_ph_rms_points + loop_ph_sq

        ns_bad_loop = ns_bad_loop + (loop_ph_sq > np.pi**2
                                     )  #suspected unw error
#        ns_bad_loop = ns_bad_loop+(np.abs(loop_ph)>loop_thre)
## multiple nan seem to generate RuntimeWarning

    ns_loop_ph[ns_loop_ph == 0] = np.nan  # To avoid 0 division
    loop_ph_rms_points = np.sqrt(loop_ph_rms_points / ns_loop_ph)

    ### Find stable ref area which have all n_unw and minimum ns_bad_loop and loop_ph_rms_points
    mask1 = (n_unw == np.nanmax(n_unw))
    min_ns_bad_loop = np.nanmin(ns_bad_loop)
    while True:
        mask2 = (ns_bad_loop == min_ns_bad_loop)
        if np.all(~(mask1 * mask2)):  ## All masked
            min_ns_bad_loop = min_ns_bad_loop + 1  ## Make mask2 again
        else:
            break
    loop_ph_rms_points_masked = loop_ph_rms_points * mask1 * mask2
    loop_ph_rms_points_masked[loop_ph_rms_points_masked == 0] = np.nan
    refyx = np.where(
        loop_ph_rms_points_masked == np.nanmin(loop_ph_rms_points_masked))
    refy1 = refyx[0][0]  # start from 0, not 1
    refy2 = refyx[0][
        0] + 1  # shift +1 for python custom. start from 1 end with width
    refx1 = refyx[1][0]
    refx2 = refyx[1][0] + 1

    ### Save 12ref.txt
    reffile = os.path.join(infodir, '12ref.txt')
    with open(reffile, 'w') as f:
        print('{0}:{1}/{2}:{3}'.format(refx1, refx2, refy1, refy2), file=f)

    ### Save loop_ph_rms_masked and png
    loop_ph_rms_maskedfile = os.path.join(loopdir, 'loop_ph_rms_masked')
    loop_ph_rms_points_masked.tofile(loop_ph_rms_maskedfile)

    cmax = np.nanpercentile(loop_ph_rms_points_masked, 95)
    pngfile = loop_ph_rms_maskedfile + '.png'
    title = 'RMS of loop phase (rad)'
    plot_lib.make_im_png(loop_ph_rms_points_masked, pngfile, cmap_noise_r,
                         title, None, cmax)

    ### Check ref exist in unw. If not, list as noref_ifg
    noref_ifg = []
    for ifgd in ifgdates:
        if ifgd in bad_ifg:
            continue

        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        unw_ref = io_lib.read_img(unwfile, length, width)[refy1:refy2,
                                                          refx1:refx2]

        unw_ref[unw_ref == 0] = np.nan  # Fill 0 with nan
        if np.all(np.isnan(unw_ref)):
            noref_ifg.append(ifgd)

    bad_ifgfile = os.path.join(loopdir, 'bad_ifg_noref.txt')
    with open(bad_ifgfile, 'w') as f:
        for i in noref_ifg:
            print('{}'.format(i), file=f)

    #%% 3rd loop closure check without bad ifgs wrt ref point
    print('\n3rd loop closure check taking into account ref phase...',
          flush=True)
    bad_ifg_cand2 = []
    good_ifg2 = []
    loop_ph_rms_ifg2 = []

    for i in range(n_loop):
        if np.mod(i, 100) == 0:
            print("  {0:3}/{1:3}th loop...".format(i, n_loop), flush=True)

        ### Read unw
        unw12, unw23, unw13, ifgd12, ifgd23, ifgd13 = loop_lib.read_unw_loop_ph(
            Aloop[i, :], ifgdates, ifgdir, length, width)

        ### Skip if bad ifg is included
        if ifgd12 in bad_ifg or ifgd23 in bad_ifg or ifgd13 in bad_ifg:
            loop_ph_rms_ifg2.append('--')
            continue

        ### Skip if noref ifg is included
        if ifgd12 in noref_ifg or ifgd23 in noref_ifg or ifgd13 in noref_ifg:
            loop_ph_rms_ifg2.append('--')
            continue

        ## Skip if no data in ref area in any unw. It is bad data.
        ref_unw12 = np.nanmean(unw12[refy1:refy2, refx1:refx2])
        ref_unw23 = np.nanmean(unw23[refy1:refy2, refx1:refx2])
        ref_unw13 = np.nanmean(unw13[refy1:refy2, refx1:refx2])

        ## Calculate loop phase taking into account ref phase
        loop_ph = unw12 + unw23 - unw13 - (ref_unw12 + ref_unw23 - ref_unw13)
        loop_ph_rms_ifg2.append(np.sqrt(np.nanmean((loop_ph)**2)))

        ### List as good or bad candidate
        if loop_ph_rms_ifg2[i] >= loop_thre:  #Bad loop including bad ifg.
            bad_ifg_cand2.extend([ifgd12, ifgd23, ifgd13])
        else:
            good_ifg2.extend([ifgd12, ifgd23, ifgd13])

    #%% Identify additional bad ifgs and output text
    bad_ifg2 = loop_lib.identify_bad_ifg(bad_ifg_cand2, good_ifg2)

    bad_ifgfile = os.path.join(loopdir, 'bad_ifg_loopref.txt')
    with open(bad_ifgfile, 'w') as f:
        for i in bad_ifg2:
            print('{}'.format(i), file=f)

    #%% Output all bad ifg list and identify remaining candidate of bad ifgs
    ### Merge bad ifg, bad_ifg2, noref_ifg
    bad_ifg_all = list(set(bad_ifg + bad_ifg2 + noref_ifg))  # Remove multiple
    bad_ifg_all.sort()

    ifgdates_good = list(set(ifgdates) - set(bad_ifg_all))
    ifgdates_good.sort()

    bad_ifgfile = os.path.join(infodir, '12bad_ifg.txt')
    with open(bad_ifgfile, 'w') as f:
        for i in bad_ifg_all:
            print('{}'.format(i), file=f)

    ### Identify removed image and output file
    imdates_good = tools_lib.ifgdates2imdates(ifgdates_good)
    imdates_bad = list(set(imdates) - set(imdates_good))
    imdates_bad.sort()

    bad_imfile = os.path.join(infodir, '12removed_image.txt')
    with open(bad_imfile, 'w') as f:
        for i in imdates_bad:
            print('{}'.format(i), file=f)

    ### Remaining candidate of bad ifg
    bad_ifg_cand_res = list(set(bad_ifg_cand2) - set(bad_ifg_all))
    bad_ifg_cand_res.sort()

    bad_ifg_candfile = os.path.join(infodir, '12bad_ifg_cand.txt')
    with open(bad_ifg_candfile, 'w') as f:
        for i in bad_ifg_cand_res:
            print('{}'.format(i), file=f)

    #%% 4th loop to be used to calc n_loop_err and n_ifg_noloop
    print('\n4th loop to compute statistics...', flush=True)
    ns_loop_err = np.zeros((length, width), dtype=np.int16)

    for i in range(n_loop):
        if np.mod(i, 100) == 0:
            print("  {0:3}/{1:3}th loop...".format(i, n_loop), flush=True)

        ### Read unw
        unw12, unw23, unw13, ifgd12, ifgd23, ifgd13 = loop_lib.read_unw_loop_ph(
            Aloop[i, :], ifgdates, ifgdir, length, width)

        ### Skip if bad ifg is included
        if ifgd12 in bad_ifg_all or ifgd23 in bad_ifg_all or ifgd13 in bad_ifg_all:
            continue

        ## Compute ref
        ref_unw12 = np.nanmean(unw12[refy1:refy2, refx1:refx2])
        ref_unw23 = np.nanmean(unw23[refy1:refy2, refx1:refx2])
        ref_unw13 = np.nanmean(unw13[refy1:refy2, refx1:refx2])

        ## Calculate loop phase taking into account ref phase
        loop_ph = unw12 + unw23 - unw13 - (ref_unw12 + ref_unw23 - ref_unw13)

        ## Count number of loops with suspected unwrap error (>pi)
        loop_ph[np.isnan(loop_ph)] = 0  #to avoid warning
        ns_loop_err = ns_loop_err + (np.abs(loop_ph) > np.pi
                                     )  #suspected unw error

    #%% Output loop info, move bad_loop_png
    loop_info_file = os.path.join(loopdir, 'loop_info.txt')
    f = open(loop_info_file, 'w')
    print('# loop_thre: {} rad. *: Removed w/o ref, **: Removed w/ ref'.format(
        loop_thre),
          file=f)
    print('# /: Candidates of bad loops but causative ifgs unidentified',
          file=f)
    print('# image1   image2   image3 RMS w/oref  w/ref', file=f)

    for i in range(n_loop):
        ### Find index of ifg
        ix_ifg12, ix_ifg23 = np.where(Aloop[i, :] == 1)[0]
        ix_ifg13 = np.where(Aloop[i, :] == -1)[0][0]
        ifgd12 = ifgdates[ix_ifg12]
        ifgd23 = ifgdates[ix_ifg23]
        ifgd13 = ifgdates[ix_ifg13]
        imd1 = ifgd12[:8]
        imd2 = ifgd23[:8]
        imd3 = ifgd23[-8:]

        ## Move loop_png if bad ifg or bad ifg_cand is included
        looppngfile = os.path.join(
            loop_pngdir, '{0}_{1}_{2}_loop.png'.format(imd1, imd2, imd3))
        badlooppngfile = os.path.join(
            bad_loop_pngdir, '{0}_{1}_{2}_loop.png'.format(imd1, imd2, imd3))
        badloopcandpngfile = os.path.join(
            bad_loop_cand_pngdir,
            '{0}_{1}_{2}_loop.png'.format(imd1, imd2, imd3))

        badloopflag1 = ' '
        badloopflag2 = '  '
        if ifgd12 in bad_ifg or ifgd23 in bad_ifg or ifgd13 in bad_ifg:
            badloopflag1 = '*'
            shutil.move(looppngfile, badlooppngfile)
        elif ifgd12 in bad_ifg2 or ifgd23 in bad_ifg2 or ifgd13 in bad_ifg2:
            badloopflag2 = '**'
            shutil.move(looppngfile, badlooppngfile)
        elif ifgd12 in bad_ifg_cand_res or ifgd23 in bad_ifg_cand_res or ifgd13 in bad_ifg_cand_res:
            badloopflag1 = '/'
            if os.path.exists(looppngfile):
                shutil.move(looppngfile, badloopcandpngfile)

        if type(loop_ph_rms_ifg2[i]) == np.float32:
            str_loop_ph_rms_ifg2 = "{:.2f}".format(loop_ph_rms_ifg2[i])
        else:  ## --
            str_loop_ph_rms_ifg2 = loop_ph_rms_ifg2[i]

        print('{0} {1} {2}    {3:5.2f} {4}  {5:5s} {6}'.format(
            imd1, imd2, imd3, loop_ph_rms_ifg[i], badloopflag1,
            str_loop_ph_rms_ifg2, badloopflag2),
              file=f)

    f.close()

    #%% Saving coh_avg, n_unw, and n_loop_err only for good ifgs
    print('\nSaving coh_avg, n_unw, and n_loop_err...', flush=True)
    ### Calc coh avg and n_unw
    coh_avg = np.zeros((length, width), dtype=np.float32)
    n_coh = np.zeros((length, width), dtype=np.int16)
    n_unw = np.zeros((length, width), dtype=np.int16)
    for ifgd in ifgdates_good:
        ccfile = os.path.join(ifgdir, ifgd, ifgd + '.cc')
        if os.path.getsize(ccfile) == length * width:
            coh = io_lib.read_img(ccfile, length, width, np.uint8)
            coh = coh.astype(np.float32) / 255
        else:
            coh = io_lib.read_img(ccfile, length, width)
            coh[np.isnan(coh)] = 0  # Fill nan with 0

        coh_avg += coh
        n_coh += (coh != 0)

        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        unw = io_lib.read_img(unwfile, length, width)

        unw[unw == 0] = np.nan  # Fill 0 with nan
        n_unw += ~np.isnan(unw)  # Summing number of unnan unw

    coh_avg[n_coh == 0] = np.nan
    n_coh[n_coh == 0] = 1  #to avoid zero division
    coh_avg = coh_avg / n_coh

    ### Save files
    n_unwfile = os.path.join(resultsdir, 'n_unw')
    np.float32(n_unw).tofile(n_unwfile)

    coh_avgfile = os.path.join(resultsdir, 'coh_avg')
    coh_avg.tofile(coh_avgfile)

    n_loop_errfile = os.path.join(resultsdir, 'n_loop_err')
    np.float32(ns_loop_err).tofile(n_loop_errfile)

    ### Save png
    title = 'Average coherence'
    plot_lib.make_im_png(coh_avg, coh_avgfile + '.png', cmap_noise, title)
    title = 'Number of used unw data'
    plot_lib.make_im_png(n_unw, n_unwfile + '.png', cmap_noise, title, n_im)

    title = 'Number of unclosed loops'
    plot_lib.make_im_png(ns_loop_err, n_loop_errfile + '.png', cmap_noise_r,
                         title)

    #%% Link ras
    ### First, identify suffix of raster image (ras, bmp, or png?)
    unwfile = os.path.join(ifgdir, ifgdates[0], ifgdates[0] + '.unw')
    if os.path.exists(unwfile + '.ras'):
        suffix = '.ras'
    elif os.path.exists(unwfile + '.bmp'):
        suffix = '.bmp'
    elif os.path.exists(unwfile + '.png'):
        suffix = '.png'

    for ifgd in ifgdates:
        rasname = ifgd + '.unw' + suffix
        rasorg = os.path.join(ifgdir, ifgd, rasname)
        ### Bad ifgs
        if ifgd in bad_ifg_all:
            os.symlink(os.path.relpath(rasorg, bad_ifgrasdir),
                       os.path.join(bad_ifgrasdir, rasname))
        ### Remaining bad ifg candidates
        elif ifgd in bad_ifg_cand_res:
            os.symlink(os.path.relpath(rasorg, bad_ifg_candrasdir),
                       os.path.join(bad_ifg_candrasdir, rasname))
        ### Good ifgs
        else:
            os.symlink(os.path.relpath(rasorg, ifg_rasdir),
                       os.path.join(ifg_rasdir, rasname))

        if ifgd in no_loop_ifg:
            os.symlink(os.path.relpath(rasorg, no_loop_ifgrasdir),
                       os.path.join(no_loop_ifgrasdir, rasname))

    #%% Plot network
    ## Read bperp data or dummy
    bperp_file = os.path.join(ifgdir, 'baselines')
    if os.path.exists(bperp_file):
        bperp = io_lib.read_bperp_file(bperp_file, imdates)
    else:  #dummy
        bperp = np.random.random(n_im).tolist()

    pngfile = os.path.join(netdir, 'network12_all.png')
    plot_lib.plot_network(ifgdates, bperp, [], pngfile)

    pngfile = os.path.join(netdir, 'network12.png')
    plot_lib.plot_network(ifgdates, bperp, bad_ifg_all, pngfile)

    pngfile = os.path.join(netdir, 'network12_nobad.png')
    plot_lib.plot_network(ifgdates,
                          bperp,
                          bad_ifg_all,
                          pngfile,
                          plot_bad=False)

    ### Network info
    ## Identify gaps
    G = inv_lib.make_sb_matrix(ifgdates_good)
    ixs_inc_gap = np.where(G.sum(axis=0) == 0)[0]

    ## Connected network
    ix1 = 0
    connected_list = []
    for ix2 in np.append(ixs_inc_gap,
                         len(imdates_good) - 1):  #append for last image
        imd1 = imdates_good[ix1]
        imd2 = imdates_good[ix2]
        dyear = (dt.datetime.strptime(imd2, '%Y%m%d').toordinal() -
                 dt.datetime.strptime(imd1, '%Y%m%d').toordinal()) / 365.25
        n_im_connect = ix2 - ix1 + 1
        connected_list.append(
            [imdates_good[ix1], imdates_good[ix2], dyear, n_im_connect])
        ix1 = ix2 + 1  # Next connection

    #%% Caution about no_loop ifg, remaining large RMS loop and gap
    ### no_loop ifg
    if len(no_loop_ifg) != 0:
        no_loop_ifgfile = os.path.join(infodir, '12no_loop_ifg.txt')
        with open(no_loop_ifgfile, 'w') as f:
            print(
                "\nThere are {} ifgs without loop, recommend to check manually in no_loop_ifg_ras12"
                .format(len(no_loop_ifg)),
                flush=True)
            for ifgd in no_loop_ifg:
                print('{}'.format(ifgd), flush=True)
                print('{}'.format(ifgd), file=f)

    ### Remaining candidates of bad ifgs
    if len(bad_ifg_cand_res) != 0:
        print(
            "\nThere are {} remaining candidates of bad ifgs but not identified."
            .format(len(bad_ifg_cand_res)),
            flush=True)
        print("Check 12bad_ifg_cand_ras and loop/bad_loop_cand_png.",
              flush=True)
#        for ifgd in bad_ifg_cand_res:
#            print('{}'.format(ifgd))

    print('\n{0}/{1} ifgs are discarded from further processing.'.format(
        len(bad_ifg_all), n_ifg),
          flush=True)
    for ifgd in bad_ifg_all:
        print('{}'.format(ifgd), flush=True)

    ### Gap
    gap_infofile = os.path.join(infodir, '12network_gap_info.txt')
    with open(gap_infofile, 'w') as f:
        if ixs_inc_gap.size != 0:
            print("Gaps between:", file=f)
            print("\nGaps in network between:", flush=True)
            for ix in ixs_inc_gap:
                print("{} {}".format(imdates_good[ix], imdates_good[ix + 1]),
                      file=f)
                print("{} {}".format(imdates_good[ix], imdates_good[ix + 1]),
                      flush=True)

        print("\nConnected network (year, n_image):", file=f)
        print("\nConnected network (year, n_image):", flush=True)
        for list1 in connected_list:
            print("{0}-{1} ({2:.2f}, {3})".format(list1[0], list1[1], list1[2],
                                                  list1[3]),
                  file=f)
            print("{0}-{1} ({2:.2f}, {3})".format(list1[0], list1[1], list1[2],
                                                  list1[3]),
                  flush=True)

    print(
        '\nIf you want to change the bad ifgs to be discarded, re-run with different thresholds before next step.',
        flush=True)

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(tsadir)))
Exemple #17
0
def main(argv=None):

    #%% Check argv
    if argv == None:
        argv = sys.argv

    start = time.time()
    ver = "1.4.8"
    date = 20210127
    author = "Y. Morishita"
    print("\n{} ver{} {} {}".format(os.path.basename(argv[0]), ver, date,
                                    author),
          flush=True)
    print("{} {}".format(os.path.basename(argv[0]), ' '.join(argv[1:])),
          flush=True)

    ## For parallel processing
    global n_para_gap, G, Aloop, unwpatch, imdates, incdir, ifgdir, length, width,\
        coef_r2m, ifgdates, ref_unw, cycle, keep_incfile, resdir, restxtfile, \
        cmap_vel, cmap_wrap, wavelength

    #%% Set default
    ifgdir = []
    tsadir = []
    inv_alg = 'LS'

    try:
        n_para = len(os.sched_getaffinity(0))
    except:
        n_para = multi.cpu_count()
    n_para_inv = 1

    memory_size = 4000
    gamma = 0.0001
    n_unw_r_thre = []
    keep_incfile = False

    cmap_vel = SCM.roma.reversed()
    cmap_noise = 'viridis'
    cmap_noise_r = 'viridis_r'
    cmap_wrap = SCM.romaO
    # q = multi.get_context('fork')
    q = multi.get_context('spawn')
    compress = 'gzip'

    #%% Read options
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "hd:t:", [
                "help", "mem_size=", "gamma=", "n_unw_r_thre=", "keep_incfile",
                "inv_alg=", "n_para="
            ])
        except getopt.error as msg:
            raise Usage(msg)
        for o, a in opts:
            if o == '-h' or o == '--help':
                print(__doc__)
                return 0
            elif o == '-d':
                ifgdir = a
            elif o == '-t':
                tsadir = a
            elif o == '--mem_size':
                memory_size = float(a)
            elif o == '--gamma':
                gamma = float(a)
            elif o == '--n_unw_r_thre':
                n_unw_r_thre = float(a)
            elif o == '--keep_incfile':
                keep_incfile = True
            elif o == '--inv_alg':
                inv_alg = a
            elif o == '--n_para':
                n_para = int(a)

        if not ifgdir:
            raise Usage('No data directory given, -d is not optional!')
        elif not os.path.isdir(ifgdir):
            raise Usage('No {} dir exists!'.format(ifgdir))
        elif not os.path.exists(os.path.join(ifgdir, 'slc.mli.par')):
            raise Usage('No slc.mli.par file exists in {}!'.format(ifgdir))

    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Directory settings
    ifgdir = os.path.abspath(ifgdir)

    if not tsadir:
        tsadir = os.path.join(os.path.dirname(ifgdir),
                              'TS_' + os.path.basename(ifgdir))

    if not os.path.isdir(tsadir):
        print('\nNo {} exists!'.format(tsadir), file=sys.stderr)
        return 1

    tsadir = os.path.abspath(tsadir)
    resultsdir = os.path.join(tsadir, 'results')
    infodir = os.path.join(tsadir, 'info')
    netdir = os.path.join(tsadir, 'network')

    bad_ifg11file = os.path.join(infodir, '11bad_ifg.txt')
    bad_ifg12file = os.path.join(infodir, '12bad_ifg.txt')
    reffile = os.path.join(infodir, '12ref.txt')
    if not os.path.exists(reffile):  ## for old LiCSBAS12 < v1.1
        reffile = os.path.join(infodir, 'ref.txt')

    incdir = os.path.join(tsadir, '13increment')
    if not os.path.exists(incdir): os.mkdir(incdir)

    resdir = os.path.join(tsadir, '13resid')
    if not os.path.exists(resdir): os.mkdir(resdir)
    restxtfile = os.path.join(infodir, '13resid.txt')

    cumh5file = os.path.join(tsadir, 'cum.h5')

    #%% Check files
    try:
        if not os.path.exists(bad_ifg11file):
            raise Usage('No 11bad_ifg.txt file exists in {}!'.format(infodir))
        if not os.path.exists(bad_ifg12file):
            raise Usage('No 12bad_ifg.txt file exists in {}!'.format(infodir))
        if not os.path.exists(reffile):
            raise Usage('No 12ref.txt file exists in {}!'.format(infodir))
    except Usage as err:
        print("\nERROR:", file=sys.stderr, end='')
        print("  " + str(err.msg), file=sys.stderr)
        print("\nFor help, use -h or --help.\n", file=sys.stderr)
        return 2

    #%% Set preliminaly reference
    with open(reffile, "r") as f:
        refarea = f.read().split()[0]  #str, x1/x2/y1/y2
    refx1, refx2, refy1, refy2 = [int(s) for s in re.split('[:/]', refarea)]

    #%% Check RAM
    mem_avail = (psutil.virtual_memory().available) / 2**20  #MB
    if memory_size > mem_avail / 2:
        print('\nNot enough memory available compared to mem_size ({} MB).'.
              format(memory_size))
        print('Reduce mem_size automatically to {} MB.'.format(
            int(mem_avail / 2)))
        memory_size = int(mem_avail / 2)

    #%% Read data information
    ### Get size
    mlipar = os.path.join(ifgdir, 'slc.mli.par')
    width = int(io_lib.get_param_par(mlipar, 'range_samples'))
    length = int(io_lib.get_param_par(mlipar, 'azimuth_lines'))
    speed_of_light = 299792458  #m/s
    radar_frequency = float(io_lib.get_param_par(mlipar,
                                                 'radar_frequency'))  #Hz
    wavelength = speed_of_light / radar_frequency  #meter
    coef_r2m = -wavelength / 4 / np.pi * 1000  #rad -> mm, positive is -LOS

    ### Calc pixel spacing depending on IFG or GEOC, used in later spatial filter
    dempar = os.path.join(ifgdir, 'EQA.dem_par')
    width_geo = int(io_lib.get_param_par(dempar, 'width'))
    length_geo = int(io_lib.get_param_par(dempar, 'nlines'))
    dlat = float(io_lib.get_param_par(dempar, 'post_lat'))  #negative
    dlon = float(io_lib.get_param_par(dempar, 'post_lon'))  #positive
    lat1 = float(io_lib.get_param_par(dempar, 'corner_lat'))
    lon1 = float(io_lib.get_param_par(dempar, 'corner_lon'))
    if width == width_geo and length == length_geo:  ## Geocoded
        print('\nIn geographical coordinates', flush=True)
        centerlat = lat1 + dlat * (length / 2)
        ra = float(io_lib.get_param_par(dempar, 'ellipsoid_ra'))
        recip_f = float(
            io_lib.get_param_par(dempar, 'ellipsoid_reciprocal_flattening'))
        rb = ra * (1 - 1 / recip_f)  ## polar radius
        pixsp_a = 2 * np.pi * rb / 360 * abs(dlat)
        pixsp_r = 2 * np.pi * ra / 360 * dlon * np.cos(np.deg2rad(centerlat))
    else:
        print('\nIn radar coordinates', flush=True)
        pixsp_r_org = float(io_lib.get_param_par(mlipar,
                                                 'range_pixel_spacing'))
        pixsp_a = float(io_lib.get_param_par(mlipar, 'azimuth_pixel_spacing'))
        inc_agl = float(io_lib.get_param_par(mlipar, 'incidence_angle'))
        pixsp_r = pixsp_r_org / np.sin(np.deg2rad(inc_agl))

    ### Set n_unw_r_thre and cycle depending on L- or C-band
    if wavelength > 0.2:  ## L-band
        if not n_unw_r_thre: n_unw_r_thre = 0.5
        cycle = 1.5  # 2pi/cycle for comparison png
    elif wavelength <= 0.2:  ## C-band
        if not n_unw_r_thre: n_unw_r_thre = 1.0
        cycle = 3  # 3*2pi/cycle for comparison png

    #%% Read date and network information
    ### Get all ifgdates in ifgdir
    ifgdates_all = tools_lib.get_ifgdates(ifgdir)
    imdates_all = tools_lib.ifgdates2imdates(ifgdates_all)
    n_im_all = len(imdates_all)
    n_ifg_all = len(ifgdates_all)

    ### Read bad_ifg11 and 12
    bad_ifg11 = io_lib.read_ifg_list(bad_ifg11file)
    bad_ifg12 = io_lib.read_ifg_list(bad_ifg12file)
    bad_ifg_all = list(set(bad_ifg11 + bad_ifg12))
    bad_ifg_all.sort()

    ### Remove bad ifgs and images from list
    ifgdates = list(set(ifgdates_all) - set(bad_ifg_all))
    ifgdates.sort()

    imdates = tools_lib.ifgdates2imdates(ifgdates)

    n_ifg = len(ifgdates)
    n_ifg_bad = len(set(bad_ifg11 + bad_ifg12))
    n_im = len(imdates)
    n_unw_thre = int(n_unw_r_thre * n_im)

    ### Make 13used_image.txt
    imfile = os.path.join(infodir, '13used_image.txt')
    with open(imfile, 'w') as f:
        for i in imdates:
            print('{}'.format(i), file=f)

    ### Calc dt in year
    imdates_dt = ([
        dt.datetime.strptime(imd, '%Y%m%d').toordinal() for imd in imdates
    ])
    dt_cum = np.float32((np.array(imdates_dt) - imdates_dt[0]) / 365.25)

    ### Construct G and Aloop matrix for increment and n_gap
    G = inv_lib.make_sb_matrix(ifgdates)
    Aloop = loop_lib.make_loop_matrix(ifgdates)

    #%% Plot network
    ## Read bperp data or dummy
    bperp_file = os.path.join(ifgdir, 'baselines')
    if os.path.exists(bperp_file):
        bperp_all = io_lib.read_bperp_file(bperp_file, imdates_all)
        bperp = io_lib.read_bperp_file(bperp_file, imdates)
    else:  #dummy
        bperp_all = np.random.random(len(imdates_all)).tolist()
        bperp = np.random.random(n_im).tolist()

    pngfile = os.path.join(netdir, 'network13_all.png')
    plot_lib.plot_network(ifgdates_all, bperp_all, [], pngfile)

    pngfile = os.path.join(netdir, 'network13.png')
    plot_lib.plot_network(ifgdates_all, bperp_all, bad_ifg_all, pngfile)

    pngfile = os.path.join(netdir, 'network13_nobad.png')
    plot_lib.plot_network(ifgdates_all,
                          bperp_all,
                          bad_ifg_all,
                          pngfile,
                          plot_bad=False)

    #%% Get patch row number
    if inv_alg == 'WLS':
        n_store_data = n_ifg * 3 + n_im * 2 + n_im * 0.3  #
    else:
        n_store_data = n_ifg * 2 + n_im * 2 + n_im * 0.3  #not sure

    n_patch, patchrow = tools_lib.get_patchrow(width, length, n_store_data,
                                               memory_size)

    #%% Display and output settings & parameters
    print('')
    print('Size of image (w,l)    : {}, {}'.format(width, length))
    print('# of all images        : {}'.format(n_im_all))
    print('# of images to be used : {}'.format(n_im))
    print('# of all ifgs          : {}'.format(n_ifg_all))
    print('# of ifgs to be used   : {}'.format(n_ifg))
    print('# of removed ifgs      : {}'.format(n_ifg_bad))
    print('Threshold of used unw  : {}'.format(n_unw_thre))
    print('')
    print('Reference area (X/Y)   : {}:{}/{}:{}'.format(
        refx1, refx2, refy1, refy2))
    print('Allowed memory size    : {} MB'.format(memory_size))
    print('Number of patches      : {}'.format(n_patch))
    print('Inversion algorism     : {}'.format(inv_alg))
    print('Gamma value            : {}'.format(gamma), flush=True)

    with open(os.path.join(infodir, '13parameters.txt'), "w") as f:
        print('range_samples:  {}'.format(width), file=f)
        print('azimuth_lines:  {}'.format(length), file=f)
        print('wavelength:     {}'.format(wavelength), file=f)
        print('n_im_all:       {}'.format(n_im_all), file=f)
        print('n_im:           {}'.format(n_im), file=f)
        print('n_ifg_all:      {}'.format(n_ifg_all), file=f)
        print('n_ifg:          {}'.format(n_ifg), file=f)
        print('n_ifg_bad:      {}'.format(n_ifg_bad), file=f)
        print('n_unw_thre:     {}'.format(n_unw_thre), file=f)
        print('ref_area:       {}:{}/{}:{}'.format(refx1, refx2, refy1, refy2),
              file=f)
        print('memory_size:    {} MB'.format(memory_size), file=f)
        print('n_patch:        {}'.format(n_patch), file=f)
        print('inv_alg:        {}'.format(inv_alg), file=f)
        print('gamma:          {}'.format(gamma), file=f)
        print('pixel_spacing_r: {:.2f} m'.format(pixsp_r), file=f)
        print('pixel_spacing_a: {:.2f} m'.format(pixsp_a), file=f)

    #%% Ref phase for inversion
    lengththis = refy2 - refy1
    countf = width * refy1
    countl = width * lengththis  # Number to be read
    ref_unw = []
    for i, ifgd in enumerate(ifgdates):
        unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
        f = open(unwfile, 'rb')
        f.seek(countf * 4, os.SEEK_SET)  #Seek for >=2nd path, 4 means byte

        ### Read unw data (mm) at ref area
        unw = np.fromfile(f, dtype=np.float32, count=countl).reshape(
            (lengththis, width))[:, refx1:refx2] * coef_r2m

        unw[unw == 0] = np.nan
        if np.all(np.isnan(unw)):
            print('All nan in ref area in {}.'.format(ifgd))
            print('Rerun LiCSBAS12.')
            return 1

        ref_unw.append(np.nanmean(unw))

        f.close()

    #%% Open cum.h5 for output
    if os.path.exists(cumh5file): os.remove(cumh5file)
    cumh5 = h5.File(cumh5file, 'w')
    cumh5.create_dataset('imdates', data=[np.int32(imd) for imd in imdates])
    if not np.all(np.abs(np.array(bperp)) <= 1):  # if not dummy
        cumh5.create_dataset('bperp', data=bperp)
    cum = cumh5.require_dataset('cum', (n_im, length, width),
                                dtype=np.float32,
                                compression=compress)
    vel = cumh5.require_dataset('vel', (length, width),
                                dtype=np.float32,
                                compression=compress)
    vconst = cumh5.require_dataset('vintercept', (length, width),
                                   dtype=np.float32,
                                   compression=compress)
    gap = cumh5.require_dataset('gap', (n_im - 1, length, width),
                                dtype=np.int8,
                                compression=compress)

    if width == width_geo and length == length_geo:  ## if geocoded
        cumh5.create_dataset('corner_lat', data=lat1)
        cumh5.create_dataset('corner_lon', data=lon1)
        cumh5.create_dataset('post_lat', data=dlat)
        cumh5.create_dataset('post_lon', data=dlon)

    #%% For each patch
    for i_patch, rows in enumerate(patchrow):
        print('\nProcess {0}/{1}th line ({2}/{3}th patch)...'.format(
            rows[1], patchrow[-1][-1], i_patch + 1, n_patch),
              flush=True)
        start2 = time.time()

        #%% Read data
        ### Allocate memory
        lengththis = rows[1] - rows[0]
        n_pt_all = lengththis * width
        unwpatch = np.zeros((n_ifg, lengththis, width), dtype=np.float32)

        if inv_alg == 'WLS':
            cohpatch = np.zeros((n_ifg, lengththis, width), dtype=np.float32)

        ### For each ifg
        print("  Reading {0} ifg's unw data...".format(n_ifg), flush=True)
        countf = width * rows[0]
        countl = width * lengththis
        for i, ifgd in enumerate(ifgdates):
            unwfile = os.path.join(ifgdir, ifgd, ifgd + '.unw')
            f = open(unwfile, 'rb')
            f.seek(countf * 4,
                   os.SEEK_SET)  #Seek for >=2nd patch, 4 means byte

            ### Read unw data (mm) at patch area
            unw = np.fromfile(f, dtype=np.float32, count=countl).reshape(
                (lengththis, width)) * coef_r2m
            unw[unw == 0] = np.nan  # Fill 0 with nan
            unw = unw - ref_unw[i]
            unwpatch[i] = unw
            f.close()

            ### Read coh file at patch area for WLS
            if inv_alg == 'WLS':
                cohfile = os.path.join(ifgdir, ifgd, ifgd + '.cc')
                f = open(cohfile, 'rb')

                if os.path.getsize(cohfile) == length * width:  ## uint8 format
                    f.seek(countf, os.SEEK_SET)  #Seek for >=2nd patch
                    cohpatch[i, :, :] = (np.fromfile(
                        f, dtype=np.uint8, count=countl).reshape(
                            (lengththis, width))).astype(np.float32) / 255
                else:  ## old float32 format
                    f.seek(countf * 4,
                           os.SEEK_SET)  #Seek for >=2nd patch, 4 means byte
                    cohpatch[i, :, :] = np.fromfile(f,
                                                    dtype=np.float32,
                                                    count=countl).reshape(
                                                        (lengththis, width))
                cohpatch[cohpatch == 0] = np.nan

        unwpatch = unwpatch.reshape(
            (n_ifg, n_pt_all)).transpose()  #(n_pt_all, n_ifg)

        ### Calc variance from coherence for WLS
        if inv_alg == 'WLS':
            cohpatch = cohpatch.reshape(
                (n_ifg, n_pt_all)).transpose()  #(n_pt_all, n_ifg)
            cohpatch[
                cohpatch <
                0.01] = 0.01  ## because negative value possible due to geocode
            cohpatch[
                cohpatch > 0.99] = 0.99  ## because >1 possible due to geocode
            varpatch = (1 - cohpatch**2) / (2 * cohpatch**2)
            del cohpatch

        #%% Remove points with less valid data than n_unw_thre
        ix_unnan_pt = np.where(
            np.sum(~np.isnan(unwpatch), axis=1) > n_unw_thre)[0]
        n_pt_unnan = len(ix_unnan_pt)

        unwpatch = unwpatch[ix_unnan_pt, :]  ## keep only unnan data
        if inv_alg == 'WLS':
            varpatch = varpatch[ix_unnan_pt, :]  ## keep only unnan data

        print('  {}/{} points removed due to not enough ifg data...'.format(
            n_pt_all - n_pt_unnan, n_pt_all),
              flush=True)

        #%% Compute number of gaps, ifg_noloop, maxTlen point-by-point
        if n_pt_unnan != 0:
            ns_gap_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            gap_patch = np.zeros((n_im - 1, n_pt_all), dtype=np.int8)
            ns_ifg_noloop_patch = np.zeros(
                (n_pt_all), dtype=np.float32) * np.nan
            maxTlen_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan

            ### Determine n_para
            n_pt_patch_min = 1000
            if n_pt_patch_min * n_para > n_pt_unnan:
                ## Too much n_para
                n_para_gap = int(np.floor(n_pt_unnan / n_pt_patch_min))
                if n_para_gap == 0: n_para_gap = 1
            else:
                n_para_gap = n_para

            print('\n  Identifing gaps, and counting n_gap and n_ifg_noloop,')
            print('  with {} parallel processing...'.format(n_para_gap),
                  flush=True)

            ### Devide unwpatch by n_para for parallel processing
            p = q.Pool(n_para_gap)
            # _result = np.array(p.map(count_gaps_wrapper, range(n_para_gap)), dtype=object)
            _result = np.array(p.map(count_gaps_wrapper,
                                     [(i, n_para_gap, G, Aloop, unwpatch)
                                      for i in range(n_para_gap)]),
                               dtype=object)
            p.close()

            ns_gap_patch[ix_unnan_pt] = np.hstack(_result[:, 0])  #n_pt
            gap_patch[:, ix_unnan_pt] = np.hstack(_result[:, 1])  #n_im-1, n_pt
            ns_ifg_noloop_patch[ix_unnan_pt] = np.hstack(_result[:, 2])

            ### maxTlen
            _maxTlen = np.zeros((n_pt_unnan), dtype=np.float32)  #temporaly
            _Tlen = np.zeros((n_pt_unnan), dtype=np.float32)  #temporaly
            for imx in range(n_im - 1):
                _Tlen = _Tlen + (dt_cum[imx + 1] - dt_cum[imx])  ## Adding dt
                _Tlen[gap_patch[imx,
                                ix_unnan_pt] == 1] = 0  ## reset to 0 if gap
                _maxTlen[_maxTlen < _Tlen] = _Tlen[
                    _maxTlen < _Tlen]  ## Set Tlen to maxTlen
            maxTlen_patch[ix_unnan_pt] = _maxTlen

            #%% Time series inversion
            print('\n  Small Baseline inversion by {}...\n'.format(inv_alg),
                  flush=True)
            if inv_alg == 'WLS':
                inc_tmp, vel_tmp, vconst_tmp = inv_lib.invert_nsbas_wls(
                    unwpatch, varpatch, G, dt_cum, gamma, n_para_inv)
            else:
                inc_tmp, vel_tmp, vconst_tmp = inv_lib.invert_nsbas(
                    unwpatch, G, dt_cum, gamma, n_para_inv)

            ### Set to valuables
            inc_patch = np.zeros(
                (n_im - 1, n_pt_all), dtype=np.float32) * np.nan
            vel_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            vconst_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan

            inc_patch[:, ix_unnan_pt] = inc_tmp
            vel_patch[ix_unnan_pt] = vel_tmp
            vconst_patch[ix_unnan_pt] = vconst_tmp

            ### Calculate residuals
            res_patch = np.zeros((n_ifg, n_pt_all), dtype=np.float32) * np.nan
            res_patch[:, ix_unnan_pt] = unwpatch.T - np.dot(G, inc_tmp)

            res_sumsq = np.nansum(res_patch**2, axis=0)
            res_n = np.float32((~np.isnan(res_patch)).sum(axis=0))
            res_n[res_n == 0] = np.nan  # To avoid 0 division
            res_rms_patch = np.sqrt(res_sumsq / res_n)

            ### Cumulative displacememt
            cum_patch = np.zeros((n_im, n_pt_all), dtype=np.float32) * np.nan
            cum_patch[1:, :] = np.cumsum(inc_patch, axis=0)

            ## Fill 1st image with 0 at unnan points from 2nd images
            bool_unnan_pt = ~np.isnan(cum_patch[1, :])
            cum_patch[0, bool_unnan_pt] = 0

            ## Drop (fill with nan) interpolated cum by 2 continuous gaps
            for i in range(n_im - 2):  ## from 1->n_im-1
                gap2 = gap_patch[i, :] + gap_patch[i + 1, :]
                bool_gap2 = (gap2 == 2
                             )  ## true if 2 continuous gaps for each point
                cum_patch[i + 1, :][bool_gap2] = np.nan

            ## Last (n_im th) image. 1 gap means interpolated
            cum_patch[-1, :][gap_patch[-1, :] == 1] = np.nan

        #%% Fill by np.nan if n_pt_unnan == 0
        else:
            cum_patch = np.zeros((n_im, n_pt_all), dtype=np.float32) * np.nan
            vel_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            vconst_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            gap_patch = np.zeros((n_im - 1, n_pt_all), dtype=np.int8)
            inc_patch = np.zeros(
                (n_im - 1, n_pt_all), dtype=np.float32) * np.nan
            res_patch = np.zeros((n_ifg, n_pt_all), dtype=np.float32) * np.nan
            res_rms_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            ns_gap_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan
            ns_ifg_noloop_patch = np.zeros(
                (n_pt_all), dtype=np.float32) * np.nan
            maxTlen_patch = np.zeros((n_pt_all), dtype=np.float32) * np.nan

        #%% Output data and image
        ### cum.h5 file
        cum[:, rows[0]:rows[1], :] = cum_patch.reshape(
            (n_im, lengththis, width))
        vel[rows[0]:rows[1], :] = vel_patch.reshape((lengththis, width))
        vconst[rows[0]:rows[1], :] = vconst_patch.reshape((lengththis, width))
        gap[:, rows[0]:rows[1], :] = gap_patch.reshape(
            (n_im - 1, lengththis, width))

        ### Others
        openmode = 'w' if rows[0] == 0 else 'a'  #w only 1st patch

        ## For each imd. cum and inc
        for imx, imd in enumerate(imdates):
            ## Incremental displacement
            if imd == imdates[-1]: continue  #skip last
            incfile = os.path.join(incdir,
                                   '{0}_{1}.inc'.format(imd, imdates[imx + 1]))
            with open(incfile, openmode) as f:
                inc_patch[imx, :].tofile(f)

        ## For each ifgd. resid
        for i, ifgd in enumerate(ifgdates):
            resfile = os.path.join(resdir, '{0}.res'.format(ifgd))
            with open(resfile, openmode) as f:
                res_patch[i, :].tofile(f)

        ## velocity and noise indecies in results dir
        names = [
            'vel', 'vintercept', 'resid_rms', 'n_gap', 'n_ifg_noloop',
            'maxTlen'
        ]
        data = [
            vel_patch, vconst_patch, res_rms_patch, ns_gap_patch,
            ns_ifg_noloop_patch, maxTlen_patch
        ]
        for i in range(len(names)):
            file = os.path.join(resultsdir, names[i])
            with open(file, openmode) as f:
                data[i].tofile(f)

        #%% Finish patch
        elapsed_time2 = int(time.time() - start2)
        hour2 = int(elapsed_time2 / 3600)
        minite2 = int(np.mod((elapsed_time2 / 60), 60))
        sec2 = int(np.mod(elapsed_time2, 60))
        print("  Elapsed time for {0}th patch: {1:02}h {2:02}m {3:02}s".format(
            i_patch + 1, hour2, minite2, sec2),
              flush=True)

    #%% Find stable ref point
    print('\nFind stable reference point...', flush=True)
    ### Compute RMS of time series with reference to all points
    sumsq_cum_wrt_med = np.zeros((length, width), dtype=np.float32)
    for i in range(n_im):
        sumsq_cum_wrt_med = sumsq_cum_wrt_med + (cum[i, :, :] -
                                                 np.nanmedian(cum[i, :, :]))**2
    rms_cum_wrt_med = np.sqrt(sumsq_cum_wrt_med / n_im)

    ### Mask by minimum n_gap
    n_gap = io_lib.read_img(os.path.join(resultsdir, 'n_gap'), length, width)
    min_n_gap = np.nanmin(n_gap)
    mask_n_gap = np.float32(n_gap == min_n_gap)
    mask_n_gap[mask_n_gap == 0] = np.nan
    rms_cum_wrt_med = rms_cum_wrt_med * mask_n_gap

    ### Find stable reference
    min_rms = np.nanmin(rms_cum_wrt_med)
    refy1s, refx1s = np.where(rms_cum_wrt_med == min_rms)
    refy1s, refx1s = refy1s[0], refx1s[0]  ## Only first index
    refy2s, refx2s = refy1s + 1, refx1s + 1
    print('Selected ref: {}:{}/{}:{}'.format(refx1s, refx2s, refy1s, refy2s),
          flush=True)

    ### Rerferencing cumulative displacement  and vel to new stable ref
    for i in range(n_im):
        cum[i, :, :] = cum[i, :, :] - cum[i, refy1s, refx1s]
    vel = vel - vel[refy1s, refx1s]
    vconst = vconst - vconst[refy1s, refx1s]

    ### Save image
    rms_cum_wrt_med_file = os.path.join(infodir, '13rms_cum_wrt_med')
    with open(rms_cum_wrt_med_file, 'w') as f:
        rms_cum_wrt_med.tofile(f)

    pngfile = os.path.join(infodir, '13rms_cum_wrt_med.png')
    plot_lib.make_im_png(rms_cum_wrt_med, pngfile, cmap_noise_r,
                         'RMS of cum wrt median (mm)',
                         np.nanpercentile(rms_cum_wrt_med, 1),
                         np.nanpercentile(rms_cum_wrt_med, 99))

    ### Save ref
    cumh5.create_dataset('refarea',
                         data='{}:{}/{}:{}'.format(refx1s, refx2s, refy1s,
                                                   refy2s))
    refsfile = os.path.join(infodir, '13ref.txt')
    with open(refsfile, 'w') as f:
        print('{}:{}/{}:{}'.format(refx1s, refx2s, refy1s, refy2s), file=f)

    if width == width_geo and length == length_geo:  ## Geocoded
        ### Make ref_stable.kml
        reflat = lat1 + dlat * refy1s
        reflon = lon1 + dlon * refx1s
        io_lib.make_point_kml(reflat, reflon,
                              os.path.join(infodir, '13ref.kml'))

    #%% Close h5 file
    cumh5.close()

    #%% Output png images
    ### Incremental displacement
    _n_para = n_im - 1 if n_para > n_im - 1 else n_para
    print(
        '\nOutput increment png images with {} parallel processing...'.format(
            _n_para),
        flush=True)
    p = q.Pool(_n_para)
    # p.map(inc_png_wrapper, range(n_im-1))
    p.map(inc_png_wrapper,
          [(i, imdates, incdir, ifgdir, length, width, coef_r2m, ifgdates,
            ref_unw, cycle, cmap_wrap, keep_incfile) for i in range(n_im - 1)])
    p.close()

    ### Residual for each ifg. png and txt.
    with open(restxtfile, "w") as f:
        print('# RMS of residual (mm)', file=f)
    _n_para = n_ifg if n_para > n_ifg else n_para
    print('\nOutput residual png images with {} parallel processing...'.format(
        _n_para),
          flush=True)
    p = q.Pool(_n_para)
    # p.map(resid_png_wrapper, range(n_ifg))
    p.map(resid_png_wrapper, [(i, ifgdates, resdir, length, width, restxtfile,
                               cmap_vel, wavelength, keep_incfile)
                              for i in range(n_ifg)])
    p.close()

    ### Velocity and noise indices
    cmins = [None, None, None, None, None, None]
    cmaxs = [None, None, None, None, None, None]
    cmaps = [
        cmap_vel, cmap_vel, cmap_noise_r, cmap_noise_r, cmap_noise_r,
        cmap_noise
    ]
    titles = [
        'Velocity (mm/yr)', 'Intercept of velocity (mm)',
        'RMS of residual (mm)', 'Number of gaps in SB network',
        'Number of ifgs with no loops',
        'Max length of connected SB network (yr)'
    ]

    print('\nOutput noise png images...', flush=True)
    for i in range(len(names)):
        file = os.path.join(resultsdir, names[i])
        data = io_lib.read_img(file, length, width)

        pngfile = file + '.png'

        ## Get color range if None
        if cmins[i] is None:
            cmins[i] = np.nanpercentile(data, 1)
        if cmaxs[i] is None:
            cmaxs[i] = np.nanpercentile(data, 99)
        if cmins[i] == cmaxs[i]: cmins[i] = cmaxs[i] - 1

        plot_lib.make_im_png(data, pngfile, cmaps[i], titles[i], cmins[i],
                             cmaxs[i])

    #%% Finish
    elapsed_time = time.time() - start
    hour = int(elapsed_time / 3600)
    minite = int(np.mod((elapsed_time / 60), 60))
    sec = int(np.mod(elapsed_time, 60))
    print("\nElapsed time: {0:02}h {1:02}m {2:02}s".format(hour, minite, sec))

    print('\n{} Successfully finished!!\n'.format(os.path.basename(argv[0])))
    print('Output directory: {}\n'.format(os.path.relpath(tsadir)))