def configure(self): # copy inps to self object inps = cmd_line_parse(self.iargs) for key, value in inps.__dict__.items(): setattr(self, key, value) # copy inps from view.py to self object view_cmd = get_view_cmd(self.iargs) self.data_img, atr, inps_view = view.prep_slice(view_cmd) for key, value in inps_view.__dict__.items(): setattr(self, key, value) self.offset *= self.disp_scale # due to unit change from view.prep_slice() # do not update the following setting from view.py self.file = inps.file self.dset = inps.dset self.fig_size = inps.fig_size # auto figure size if not self.fig_size: length, width = int(self.atr['LENGTH']), int(self.atr['WIDTH']) fig_size = pp.auto_figure_size((length, width), disp_cbar=True) self.fig_size = [fig_size[0] + fig_size[1], fig_size[1]] return
def configure(self): inps = cmd_line_parse(self.iargs) # read network info inps = read_network_info(inps) # copy inps to self object for key, value in inps.__dict__.items(): setattr(self, key, value) # auto figure size if not self.fig_size: ds_shape = readfile.read(self.img_file)[0].shape fig_size = pp.auto_figure_size(ds_shape, disp_cbar=True, ratio=0.7) self.fig_size = [fig_size[0]+fig_size[1], fig_size[1]] vprint('create figure in size of {} inches'.format(self.fig_size)) # read aux data # 1. temporal coherence value self.tcoh = None if self.tcoh_file: self.tcoh = readfile.read(self.tcoh_file)[0] # 2. minimum used coherence from template file self.min_coh_used = 0.0 if self.template_file: template = readfile.read_template(self.template_file) template = ut.check_template_auto_value(template) if template['mintpy.networkInversion.maskDataset'] == 'coherence': self.min_coh_used = float(template['mintpy.networkInversion.maskThreshold']) vprint('Pixel-wised masking is applied in invert_network step') return
def plot(self): # read 3D time-series self.ts_data, self.mask = tsview.read_timeseries_data(self)[0:2] # Figure 1 - Cumulative Displacement Map if not self.figsize_img: self.figsize_img = pp.auto_figure_size( ds_shape=self.ts_data[0].shape[-2:], disp_cbar=True, disp_slider=True, print_msg=self.print_msg) self.fig_img = plt.figure(self.figname_img, figsize=self.figsize_img) # Figure 1 - Axes 1 - Displacement Map self.ax_img = self.fig_img.add_axes([0.125, 0.25, 0.75, 0.65]) img_data = np.array(self.ts_data[0][self.idx, :, :]) img_data[self.mask == 0] = np.nan self.plot_init_image(img_data) # Figure 1 - Axes 2 - Time Slider self.ax_tslider = self.fig_img.add_axes([0.125, 0.1, 0.75, 0.07]) self.plot_init_time_slider(init_idx=self.idx, ref_idx=self.ref_idx) self.tslider.on_changed(self.update_time_slider) # Figure 2 - Time Series Displacement - Point self.fig_pts, self.ax_pts = plt.subplots(num=self.figname_pts, figsize=self.figsize_pts) if self.yx: d_ts, m_strs = self.plot_point_timeseries(self.yx) # Figure 3 - Temporal Coherence - Point self.fig_coh, self.ax_coh = plt.subplots(nrows=1, ncols=3) if self.yx: d_coh = self.plot_point_coh_matrix(self.yx) # save figures and data to files if self.save_fig: save_ts_data_and_plot(self.yx, d_ts, self.fig_coh, m_strs, self) # Output #if self.save_fig: # save_ts_plot(self.yx, self.fig_img, self.fig_pts, d_ts, self.fig_coh, self) # Final linking of the canvas to the plots. self.fig_img.canvas.mpl_connect('button_press_event', self.update_plot_timeseries) self.fig_img.canvas.mpl_connect('button_press_event', self.update_plot_coh) self.fig_img.canvas.mpl_connect('key_press_event', self.on_key_event) if self.disp_fig: vprint('showing ...') msg = '\n------------------------------------------------------------------------' msg += '\nTo scroll through the image sequence:' msg += '\n1) Move the slider, OR' msg += '\n2) Press left or right arrow key (if not responding, click the image and try again).' msg += '\n------------------------------------------------------------------------' vprint(msg) plt.show() return
def plot(self): # read 3D time-series self.ts_data, self.mask = read_timeseries_data(self)[0:2] # Figure 1 - Cumulative Displacement Map if not self.figsize_img: self.figsize_img = pp.auto_figure_size( ds_shape=self.ts_data[0].shape[-2:], disp_cbar=True, disp_slider=True, print_msg=self.print_msg) subplot_kw = dict(projection=self.map_proj_obj ) if self.map_proj_obj is not None else {} self.fig_img, self.ax_img = plt.subplots(figsize=self.figsize_img, subplot_kw=subplot_kw) # Figure 1 - Axes 1 - Displacement Map img_data = np.array(self.ts_data[0][self.idx, :, :]) img_data[self.mask == 0] = np.nan self.plot_init_image(img_data) # Figure 1 - Axes 2 - Time Slider self.plot_init_time_slider(init_idx=self.idx, ref_idx=self.ref_idx) self.tslider.on_changed(self.update_time_slider) # Figure 2 - Time Series Displacement - Point self.fig_pts, self.ax_pts = plt.subplots(num=self.figname_pts, figsize=self.figsize_pts) if self.yx: d_ts, m_strs = self.plot_point_timeseries(self.yx) # save figures and data to files if self.save_fig: save_ts_data_and_plot(self.yx, d_ts, m_strs, self) # Final linking of the canvas to the plots. self.fig_img.canvas.mpl_connect('button_press_event', self.update_point_timeseries) self.fig_img.canvas.mpl_connect('key_press_event', self.update_image) if self.disp_fig: vprint('showing ...') msg = '\n------------------------------------------------------------------------' msg += '\nTo scroll through the image sequence:' msg += '\n1) Move the slider, OR' msg += '\n2) Press left or right arrow key (if not responding, click the image and try again).' msg += '\n------------------------------------------------------------------------' vprint(msg) plt.show() return
def configure(self): inps = cmd_line_parse(self.iargs) # read network info inps = read_network_info(inps) # copy inps to self object for key, value in inps.__dict__.items(): setattr(self, key, value) # auto figure size if not self.fig_size: ds_shape = readfile.read(self.img_file)[0].shape fig_size = pp.auto_figure_size(ds_shape, disp_cbar=True, ratio=0.7) self.fig_size = [fig_size[0]+fig_size[1], fig_size[1]] vprint('create figure in size of {} inches'.format(self.fig_size)) return
def plot_stitch(mat11, mat22, mat, mat_diff, out_fig=None): """plot stitching result""" # plot settings titles = ['file 1', 'file 2', 'stitched', 'difference'] mat_mli = multilook_data(mat, 20, 20, method='mean') vmin = np.nanmin(mat_mli) vmax = np.nanmax(mat_mli) fig_size = pp.auto_figure_size(ds_shape=mat.shape, scale=1.4, disp_cbar=True, print_msg=True) # plot fig, axs = plt.subplots(nrows=2, ncols=2, figsize=fig_size, sharex=True, sharey=True) for ax, data, title in zip(axs.flatten(), [mat11, mat22, mat, mat_diff], titles): im = ax.imshow(data, vmin=vmin, vmax=vmax, interpolation='nearest') ax.set_title(title, fontsize=12) ax.tick_params(which='both', direction='in', labelsize=12, left=True, right=True, top=True, bottom=True) fig.tight_layout() # colorbar fig.subplots_adjust(right=0.9) cax = fig.add_axes([0.901, 0.3, 0.01, 0.4]) plt.colorbar(im, cax=cax) # output fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=150) print('save figure to file: {}'.format(out_fig)) #if disp_fig: # print('showing ...') # plt.show() #else: # plt.close() return
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
def write_kmz_overlay(data, meta, out_file, inps): """Generate Google Earth Overlay KMZ file for data in GEO coordinates. Parameters: data - 2D np.array in int/float, data matrix to write meta - dict, containing the following attributes: WIDTH/LENGTH : required, file size X/Y_FIRST/STEP : required, for lat/lon spatial converage REF_X/Y : optional, column/row number of reference pixel out_file - string, output file name inps - Namespace, optional, input options for display Returns: kmz_file - string, output KMZ filename """ south, north, west, east = ut.four_corners(meta) # 1. Make PNG file - Data print('plotting data ...') # Figure size if not inps.fig_size: inps.fig_size = pp.auto_figure_size( ds_shape=[north - south, east - west], scale=2.0) fig = plt.figure(figsize=inps.fig_size, frameon=False) ax = fig.add_axes([0., 0., 1., 1.]) ax.set_axis_off() # Plot - data matrix ax.imshow(data, vmin=inps.vlim[0], vmax=inps.vlim[1], cmap=inps.colormap, aspect='auto', interpolation='nearest') # Plot - reference pixel rx = meta.get('REF_X', None) ry = meta.get('REF_Y', None) if inps.disp_ref_pixel and rx is not None and ry is not None: ax.plot(int(rx), int(ry), inps.ref_marker, color=inps.ref_marker_color, ms=inps.ref_marker_size) print('show reference point') else: print('no plot for reference point.') width = int(meta['WIDTH']) length = int(meta['LENGTH']) ax.set_xlim([0, width]) ax.set_ylim([length, 0]) out_file_base = os.path.splitext(out_file)[0] data_png_file = out_file_base + '.png' print('writing {} with dpi={}'.format(data_png_file, inps.fig_dpi)) plt.savefig(data_png_file, pad_inches=0.0, transparent=True, dpi=inps.fig_dpi) # 2. Generate KML file kml_doc = KML.Document() # Add data png file img_name = os.path.splitext(os.path.basename(data_png_file))[0] img_overlay = KML.GroundOverlay( KML.name(img_name), KML.Icon(KML.href(os.path.basename(data_png_file))), KML.altitudeMode('clampToGround'), KML.LatLonBox( KML.north(str(north)), KML.east(str(east)), KML.south(str(south)), KML.west(str(west)), ), ) kml_doc.append(img_overlay) # Add colorbar png file cbar_file = '{}_cbar.png'.format(out_file_base) cbar_overlay = generate_cbar_element( cbar_file, vmin=inps.vlim[0], vmax=inps.vlim[1], unit=inps.disp_unit, cmap=inps.colormap, loc=inps.cbar_loc, nbins=inps.cbar_bin_num, label=inps.cbar_label, ) kml_doc.append(cbar_overlay) # Write KML file kmz_file = write_kmz_file( out_file_base, kml_doc, data_files=[data_png_file, cbar_file], keep_kml_file=inps.keep_kml_file, ) return kmz_file