def get_common_region_int_ambiguity(ifgram_file, cc_mask_file, water_mask_file=None, num_sample=100,
                                    dsNameIn='unwrapPhase'):
    """Solve the phase unwrapping integer ambiguity for the common regions among all interferograms
    Parameters: ifgram_file     : str, path of interferogram stack file
                cc_mask_file    : str, path of common connected components file
                water_mask_file : str, path of water mask file
                num_sample      : int, number of pixel sampled for each region
                dsNameIn        : str, dataset name of the unwrap phase to be corrected
    Returns:    common_regions  : list of skimage.measure._regionprops._RegionProperties object
                    modified by adding two more variables:
                    sample_coords : 2D np.ndarray in size of (num_sample, 2) in int64 format
                    int_ambiguity : 1D np.ndarray in size of (num_ifgram,) in int format
    """
    print('-'*50)
    print('calculating the integer ambiguity for the common regions defined in', cc_mask_file)
    # stack info
    stack_obj = ifgramStack(ifgram_file)
    stack_obj.open()
    date12_list = stack_obj.get_date12_list(dropIfgram=True)
    num_ifgram = len(date12_list)
    C = matrix(ifgramStack.get_design_matrix4triplet(date12_list).astype(float))
    ref_phase = stack_obj.get_reference_phase(unwDatasetName=dsNameIn, dropIfgram=True).reshape(num_ifgram, -1)

    # prepare common label
    print('read common mask from', cc_mask_file)
    cc_mask = readfile.read(cc_mask_file)[0]
    if water_mask_file is not None and os.path.isfile(water_mask_file):
        water_mask = readfile.read(water_mask_file)[0]
        print('refine common mask based on water mask file', water_mask_file)
        cc_mask[water_mask == 0] = 0

    label_img, num_label = connectComponent.get_large_label(cc_mask, min_area=2.5e3, print_msg=True)
    common_regions = measure.regionprops(label_img)
    print('number of common regions:', num_label)

    # add sample_coords / int_ambiguity
    print('number of samples per region:', num_sample)
    print('solving the phase-unwrapping integer ambiguity for {}'.format(dsNameIn))
    print('\tbased on the closure phase of interferograms triplets (Yunjun et al., 2019)')
    print('\tusing the L1-norm regularzed least squares approximation (LASSO) ...')
    for i in range(num_label):
        common_reg = common_regions[i]
        # sample_coords
        idx = sorted(np.random.choice(common_reg.area, num_sample, replace=False))
        common_reg.sample_coords = common_reg.coords[idx, :].astype(int)

        # solve for int_ambiguity
        U = np.zeros((num_ifgram, num_sample))
        if common_reg.label == label_img[stack_obj.refY, stack_obj.refX]:
            print('{}/{} skip calculation for the reference region'.format(i+1, num_label))
        else:
            prog_bar = ptime.progressBar(maxValue=num_sample, prefix='{}/{}'.format(i+1, num_label))
            for j in range(num_sample):
                # read unwrap phase
                y, x = common_reg.sample_coords[j, :]
                unw = ifginv.read_unwrap_phase(stack_obj,
                                               box=(x, y, x+1, y+1),
                                               ref_phase=ref_phase,
                                               unwDatasetName=dsNameIn,
                                               dropIfgram=True,
                                               print_msg=False).reshape(num_ifgram, -1)

                # calculate closure_int
                closure_pha = np.dot(C, unw)
                closure_int = matrix(np.round((closure_pha - ut.wrap(closure_pha)) / (2.*np.pi)))

                # solve for U
                U[:,j] = np.round(l1regls(-C, closure_int, alpha=1e-2, show_progress=0)).flatten()
                prog_bar.update(j+1, every=5)
            prog_bar.close()
        # add int_ambiguity
        common_reg.int_ambiguity = np.median(U, axis=1)
        common_reg.date12_list = date12_list

    #sort regions by size to facilitate the region matching later
    common_regions.sort(key=lambda x: x.area, reverse=True)

    # plot sample result
    fig_size = pp.auto_figure_size(label_img.shape, disp_cbar=False)
    fig, ax = plt.subplots(figsize=fig_size)
    ax.imshow(label_img, cmap='jet')
    for common_reg in common_regions:
        ax.plot(common_reg.sample_coords[:,1],
                common_reg.sample_coords[:,0], 'k.', ms=2)
    pp.auto_flip_direction(stack_obj.metadata, ax, print_msg=False)
    out_img = 'common_region_sample.png'
    fig.savefig(out_img, bbox_inches='tight', transparent=True, dpi=300)
    print('saved common regions and sample pixels to file', out_img)

    return common_regions
def get_common_region_int_ambiguity(ifgram_file,
                                    cc_mask_file,
                                    water_mask_file=None,
                                    num_sample=100,
                                    dsNameIn='unwrapPhase'):
    """Solve the phase unwrapping integer ambiguity for the common regions among all interferograms
    Parameters: ifgram_file     : str, path of interferogram stack file
                cc_mask_file    : str, path of common connected components file
                water_mask_file : str, path of water mask file
                num_sample      : int, number of pixel sampled for each region
                dsNameIn        : str, dataset name of the unwrap phase to be corrected
    Returns:    common_regions  : list of skimage.measure._regionprops._RegionProperties object
                    modified by adding two more variables:
                    sample_coords : 2D np.ndarray in size of (num_sample, 2) in int64 format
                    int_ambiguity : 1D np.ndarray in size of (num_ifgram,) in int format
    """
    print('-' * 50)
    print(
        'calculating the integer ambiguity for the common regions defined in',
        cc_mask_file)
    # stack info
    stack_obj = ifgramStack(ifgram_file)
    stack_obj.open()
    date12_list = stack_obj.get_date12_list(dropIfgram=True)
    num_ifgram = len(date12_list)
    C = matrix(
        ifgramStack.get_design_matrix4triplet(date12_list).astype(float))
    ref_phase = stack_obj.get_reference_phase(unwDatasetName=dsNameIn,
                                              dropIfgram=True).reshape(
                                                  num_ifgram, -1)

    # prepare common label
    print('read common mask from', cc_mask_file)
    cc_mask = readfile.read(cc_mask_file)[0]
    if water_mask_file is not None and os.path.isfile(water_mask_file):
        water_mask = readfile.read(water_mask_file)[0]
        print('refine common mask based on water mask file', water_mask_file)
        cc_mask[water_mask == 0] = 0

    label_img, num_label = connectComponent.get_large_label(cc_mask,
                                                            min_area=2.5e3,
                                                            print_msg=True)
    common_regions = measure.regionprops(label_img)
    print('number of common regions:', num_label)

    # add sample_coords / int_ambiguity
    print('number of samples per region:', num_sample)
    print('solving the phase-unwrapping integer ambiguity for {}'.format(
        dsNameIn))
    print(
        '\tbased on the closure phase of interferograms triplets (Yunjun et al., 2019)'
    )
    print(
        '\tusing the L1-norm regularzed least squares approximation (LASSO) ...'
    )
    for i in range(num_label):
        common_reg = common_regions[i]
        # sample_coords
        idx = sorted(
            np.random.choice(common_reg.area, num_sample, replace=False))
        common_reg.sample_coords = common_reg.coords[idx, :].astype(int)

        # solve for int_ambiguity
        U = np.zeros((num_ifgram, num_sample))
        if common_reg.label == label_img[stack_obj.refY, stack_obj.refX]:
            print('{}/{} skip calculation for the reference region'.format(
                i + 1, num_label))
        else:
            prog_bar = ptime.progressBar(maxValue=num_sample,
                                         prefix='{}/{}'.format(
                                             i + 1, num_label))
            for j in range(num_sample):
                # read unwrap phase
                y, x = common_reg.sample_coords[j, :]
                unw = ifginv.read_unwrap_phase(stack_obj,
                                               box=(x, y, x + 1, y + 1),
                                               ref_phase=ref_phase,
                                               unwDatasetName=dsNameIn,
                                               dropIfgram=True,
                                               print_msg=False).reshape(
                                                   num_ifgram, -1)

                # calculate closure_int
                closure_pha = np.dot(C, unw)
                closure_int = matrix(
                    np.round(
                        (closure_pha - ut.wrap(closure_pha)) / (2. * np.pi)))

                # solve for U
                U[:, j] = np.round(
                    l1regls(-C, closure_int, alpha=1e-2,
                            show_progress=0)).flatten()
                prog_bar.update(j + 1, every=5)
            prog_bar.close()
        # add int_ambiguity
        common_reg.int_ambiguity = np.median(U, axis=1)
        common_reg.date12_list = date12_list

    #sort regions by size to facilitate the region matching later
    common_regions.sort(key=lambda x: x.area, reverse=True)

    # plot sample result
    fig_size = pp.auto_figure_size(label_img.shape, disp_cbar=False)
    fig, ax = plt.subplots(figsize=fig_size)
    ax.imshow(label_img, cmap='jet')
    for common_reg in common_regions:
        ax.plot(common_reg.sample_coords[:, 1],
                common_reg.sample_coords[:, 0],
                'k.',
                ms=2)
    pp.auto_flip_direction(stack_obj.metadata, ax, print_msg=False)
    out_img = 'common_region_sample.png'
    fig.savefig(out_img, bbox_inches='tight', transparent=True, dpi=300)
    print('saved common regions and sample pixels to file', out_img)

    return common_regions
示例#3
0
def main(argv):
    
    inps = cmdLineParse() 
    ifgram = inps.ifgram_file
    Bperp = readfile.read(ifgram, datasetName='bperp')[0]
    Date = readfile.read(ifgram, datasetName='date')[0]
    DropIfgram = readfile.read(ifgram, datasetName='dropIfgram')[0]
    
    #invRes = inps.inversion_res
    mask_file = inps.mask_file
    mask = readfile.read(mask_file, datasetName='mask')[0]
    meta = readfile.read_attribute(ifgram, datasetName=None) 
    REF_X = int(meta['REF_X'])
    REF_Y = int(meta['REF_Y'])
    
    if inps.out_file:
        OUT = inps.out_file
    else:
        OUT = 'ifgramStackCor.h5'

    sliceList = readfile.get_slice_list(ifgram)
    N_list =len(sliceList)
        
    g_list = []
    for i in range(N_list):
        if 'unwrapPhase-' in sliceList[i]:
            g_list.append(sliceList[i])
    
    N_list = len(g_list)
    Ifg = [] 
    
    print('Start to calculate the integer ambugity for each closure')
    for i in range(N_list):
        print_progress(i+1, N_list, prefix='Data: ', suffix=g_list[i])
        dset = g_list[i]
        ifgram1 = readfile.read(ifgram, datasetName=dset)[0]
        ifgram0 = ifgram1 - ifgram1[REF_Y,REF_X]
        Ifg.append(np.mean(ifgram0[mask==1]))

    
    stack_obj = ifgramStack(ifgram)
    stack_obj.open()
    date12_list = stack_obj.get_date12_list(dropIfgram=True)
    num_ifgram = len(date12_list)
    date12_list = stack_obj.get_date12_list(dropIfgram=True)
    num_ifgram = len(date12_list)
    
    C0 = ifgramStack.get_design_matrix4triplet(date12_list)
    #Ifg = np.asarray(Ifg);Ifg=Ifg.reshape(len(Ifg),)
    #ResC = np.dot(C0,Ifg)
    #good_pair = get_good_pair_closure(C,ResC)
    #good_pair = list(good_pair)
    #bad_pair = get_bad_pair(good_pair,N_list)    
    #print('Bad interferograms: ' + str(bad_pair)) 
    
    
    
    #Ifg_org = []
    #for k in bad_pair:
    #    Ifg_org.append(Ifg[k])

    #Ifg_org = np.asarray(Ifg_org)
    #Ifg_org.reshape(len(bad_pair),)

    #A,L = get_design_matrix_unwrap_error(C,bad_pair,Ifg)
    #Ifg_est, var_ts = estimate_timeseries(A, -L, weight_sqrt=None, rcond=1e-5)

    #Ifg_est = Ifg_est.reshape(len(Ifg_est),)
    #kk = np.round((Ifg_est - Ifg_org)/(2*np.pi))
    #print('Cycle shift of the bad interferogram: ' + str(kk))

    
    C = matrix(ifgramStack.get_design_matrix4triplet(date12_list).astype(float)) 
    ResC = np.dot(C,Ifg)
    L = matrix(np.round(ResC/(2*np.pi)))

    U = l1regls(-C, L, alpha=1e-2, show_progress=0)
    kk = np.round(U)
 
    num_row = stack_obj.length
    num_col = stack_obj.width
    box = [0,0,stack_obj.width,stack_obj.length]
    ref_phase = stack_obj.get_reference_phase(unwDatasetName='unwrapPhase',
                                                      skip_reference=None,
                                                       dropIfgram=True)
    pha_data = read_unwrap_phase(stack_obj,box,ref_phase,unwDatasetName='unwrapPhase',dropIfgram=True)
    data = pha_data.reshape(N_list,num_row,num_col)
    data0 = data
    
    print('Start to correct and write new unwrapIfg file ...')
    for i in range(N_list):  
        
        ifgram1 = data[i,:,:]
        ifgram0 = ifgram1 - ifgram1[REF_Y,REF_X]
        #print(ifgram0.shape)
        #ifgram0 = ifgram0 + mask*(kk*(2*np.pi)) 
        ifgram0[mask==1] = ifgram0[mask==1] + kk[i]*(2*np.pi) 
        data0[i,:,:] = ifgram0
    
    datasetDict = dict()
    datasetDict['unwrapPhase'] = data0
    datasetDict['IntAmbiguity'] = kk
    datasetDict['bperp'] = Bperp
    datasetDict['date'] = Date
    datasetDict['dropIfgram'] = DropIfgram
    datasetDict['C'] = C0
    write_variogram_h5(datasetDict, OUT, metadata=meta, ref_file=ifgram, compression=None)

    sys.exit(1)