def overlay_gps(netcdfname, smoothing, misfit): z = rwr.read_grd(netcdfname) ma = np.nanmax(z, axis=None, out=None) mi = np.nanmin(z, axis=None, out=None) xread, yread, zread = rwr.read_grd_xyz(netcdfname) # Make a plot fig = plt.figure(figsize=(7, 10)) ax1 = fig.add_axes([0.0, 0.1, 0.9, 0.8]) image = plt.imshow( zread, aspect=1.2, extent=[15.984871407, 21116.0151286, 12196, 4.4408920985 * (10**-16)], cmap='jet', vmin=-10, vmax=10) plt.gca().invert_xaxis() # plt.gca().invert_yaxis() plt.title('Reasonable WNSBAS without ramps - smoothing factor: ' + str(smoothing) + ' - Misfit: ' + str(misfit)) plt.gca().set_xlabel("Range", fontsize=16) plt.gca().set_ylabel("Azimuth", fontsize=16) scatter = plt.gca().scatter(xfinal, yfinal, c=velfinal, marker='v', s=100, cmap='jet', vmin=-10, vmax=10) cb = plt.colorbar(image) cb.set_label('velocity in mm/yr', size=16) plt.show() return
def inputs(file_names, skip_file): try: [xdata, ydata] = netcdf_read_write.read_grd_xy(file_names[0]) # can read either netcdf3 or netcdf4. except TypeError: [xdata, ydata, _] = netcdf_read_write.read_netcdf4_xyz(file_names[0]) data_all = [] date_pairs = [] file_names = sorted(file_names) # To force into date-ascending order. for ifile in file_names: # Read the data try: data = netcdf_read_write.read_grd(ifile) except TypeError: [_, _, data] = netcdf_read_write.read_netcdf4_xyz(ifile) data_all.append(data) pairname = ifile.split('/')[-2][0:15] date_pairs.append(pairname) # returning something like '2016292_2016316' for each intf print(pairname) skip_intfs = [] if skip_file is not None: ifile = open(skip_file, 'r') for line in ifile: skip_intfs.append(line.split()[0]) ifile.close() return [xdata, ydata, data_all, date_pairs, skip_intfs]
def inputs(file_names, config_params): [xdata,ydata] = netcdf_read_write.read_grd_xy(file_names[0]); data_all=[]; date_pairs=[]; dates=[]; start_dt = dt.datetime.strptime(str(config_params.start_time),"%Y%m%d"); end_dt = dt.datetime.strptime(str(config_params.end_time),"%Y%m%d"); for ifile in file_names: # this happens to be in date order on my mac pairname=ifile.split('/')[-1][0:15]; image1=pairname.split('_')[0]; image2=pairname.split('_')[1]; image1_dt = dt.datetime.strptime(image1,"%Y%j"); image2_dt = dt.datetime.strptime(image2,"%Y%j"); if image1_dt>=start_dt and image1_dt<= end_dt: if image2_dt>=start_dt and image2_dt <= end_dt: data = netcdf_read_write.read_grd(ifile); data_all.append(data); date_pairs.append(pairname); # returning something like '2016292_2016316' for each intf dates.append(image1); dates.append(image2); dates=list(set(dates)); dates=sorted(dates); print(dates); print("Reading %d interferograms from %d acquisitions. " % (len(date_pairs), len(dates) ) ); return [xdata, ydata, data_all, dates, date_pairs];
def drive_velocity_gmtsar(intf_files, nsbas_min_intfs, smoothing, wavelength, rowref, colref, outdir, signal_spread_file, baseline_file=None, coh_files=None): # GMTSAR DRIVING VELOCITIES signal_spread_file = outdir + "/" + signal_spread_file intf_tuple = rmd.reader(intf_files) coh_tuple = None if coh_files is not None: coh_tuple = rmd.reader(coh_files) signal_spread_data = rwr.read_grd(signal_spread_file) velocities = nsbas.Velocities(intf_tuple, nsbas_min_intfs, smoothing, wavelength, rowref, colref, signal_spread_data, baseline_file=baseline_file, coh_tuple=coh_tuple) rwr.produce_output_netcdf(intf_tuple.xvalues, intf_tuple.yvalues, velocities, 'mm/yr', outdir + '/velo_nsbas.grd') rwr.produce_output_plot(outdir + '/velo_nsbas.grd', 'LOS Velocity', outdir + '/velo_nsbas.png', 'velocity (mm/yr)') return
def inputs(file_names, start_time, end_time, run_type): # Read the input grd files. Support for netcdf3 and netcdf4. try: [xdata, ydata] = netcdf_read_write.read_grd_xy(file_names[0]) except TypeError: [xdata, ydata, _] = netcdf_read_write.read_netcdf4_xyz(file_names[0]) data_all = [] date_pairs = [] dates = [] start_dt = dt.datetime.strptime(str(start_time), "%Y%m%d") end_dt = dt.datetime.strptime(str(end_time), "%Y%m%d") # Get the dates of the acquisitions from the file names. for ifile in file_names: # this happens to be in date order on my mac if run_type == 'test': # testing with Kang's format. "20171117_20171123/unwrap_new.grd" pairname = ifile.split('/')[-2] image1 = pairname.split('_')[0] image2 = pairname.split('_')[1] image1_dt = dt.datetime.strptime(image1, "%Y%m%d") image2_dt = dt.datetime.strptime(image2, "%Y%m%d") else: # the usual GMTSAR format pairname = ifile.split('/')[-1][0:15] image1 = pairname.split('_')[0] image2 = pairname.split('_')[1] image1_dt = dt.datetime.strptime(image1, "%Y%j") image2_dt = dt.datetime.strptime(image2, "%Y%j") if image1_dt >= start_dt and image1_dt <= end_dt: if image2_dt >= start_dt and image2_dt <= end_dt: try: data = netcdf_read_write.read_grd(ifile) except TypeError: [_, _, data] = netcdf_read_write.read_netcdf4_xyz(ifile) if run_type == "test": data_all.append(data * -0.0555 / 4 / np.pi) # mcandis preprocessing involves changing to LOS distances. print( "Converting phase to LOS (mm) with 55.5mm wavelength") else: data_all.append(data) pairname = dt.datetime.strftime( image1_dt, "%Y%j") + '_' + dt.datetime.strftime( image2_dt, "%Y%j") date_pairs.append(pairname) # returning something like '2016292_2016316' for each intf dates.append(dt.datetime.strftime(image1_dt, "%Y%j")) dates.append(dt.datetime.strftime(image2_dt, "%Y%j")) data_all = np.array(data_all) # this allows easy indexing later on. dates = list(set(dates)) dates = sorted(dates) print(date_pairs) print("Reading %d interferograms from %d acquisitions. " % (len(date_pairs), len(dates))) return [xdata, ydata, data_all, dates, date_pairs]
def estimated_gpsvel(netcdfname): z = rwr.read_grd(netcdfname) est = [] for i in range(len(xfinal_ratioed)): est.append( np.nanmean(z[(yfinal_ratioed[i] - 50):(yfinal_ratioed[i] + 51), (xfinal_ratioed[i] - 50):(xfinal_ratioed[i] + 51)])) return est
def velocity_simple_stack(filepathslist, wavelength, manual_exclude, signal_threshold): """This function takes in a list of files that contain arrays of phases and times. It will compute the velocity of each pixel using the given wavelength of the satellite. Finally, it will return a 2D array of velocities, ready to be plotted. For the manual exclude argument, enter either 0 (no images excluded), 1 (15 images excluded), or 2 (40 images excluded). The final argument should be a number between 0 and 100 inclusive that tells the function which pixels to exclude based on this signal percentage.""" print(signal_threshold) if manual_exclude != 0: f = open('Metadata/manual_remove.txt', 'r') if manual_exclude == 1: content, x = f.readlines()[0:15], [] for i in range(len(content)): x.append(content[i].strip('\n')) if manual_exclude == 2: content = f.read() x = content.split('\n') f.close() filesmodified = [] filepathslist = filesmodified for i in range(len(myfiles_new)): if myfiles_new[i][16:31] not in x: filesmodified.append(myfiles_new[i]) print('Number of files being stacked: ' + str(len(filepathslist))) signal_spread_data = rwr.read_grd("signalspread_please_test.nc") mytuple = rmd.reader(filepathslist) phases, times = [], [] velocities = np.zeros((len(mytuple.yvalues), len(mytuple.xvalues))) i, j, f, c = 0, 0, 0, 0 for z in np.nditer(mytuple.zvalues, order='F'): if np.isnan(z) == False: if signal_spread_data[i, j] < signal_threshold: times.append(np.nan) else: phases.append(mytuple.zvalues[f][i][j]) times.append(mytuple.date_deltas[f]) if np.isnan(z) == True: times.append(np.nan) f += 1 if f == len(mytuple.zvalues): velocities[i, j] = (wavelength / (4 * (np.pi))) * ((np.sum(phases)) / (np.sum(times))) phases, times = [], [] c += 1 print('Done with ' + str(c) + ' out of ' + str(len(mytuple.xvalues) * len(mytuple.yvalues)) + ' pixels') f = 0 j += 1 if j == len(mytuple.xvalues): j = 0 i += 1 if i == len(mytuple.yvalues): i = 0 return velocities, mytuple.xvalues, mytuple.yvalues
def drive_velocity_simple_stack(intfs, wavelength, rowref, colref, outdir): signal_spread_data = rwr.read_grd(outdir + "/signalspread.nc") intf_tuple = rmd.reader(intfs) velocities, x, y = velocity_simple_stack(intf_tuple, wavelength, rowref, colref, signal_spread_data, 25) # last argument is signal threshold (< 100%). lower signal threshold allows for more data into the stack. rwr.produce_output_netcdf(x, y, velocities, 'mm/yr', outdir + '/velo_simple_stack.grd') rwr.produce_output_plot(outdir + '/velo_simple_stack.grd', 'LOS Velocity ', outdir + '/velo_simple_stack.png', 'velocity (mm/yr)') return
def inputs(file_names): [xdata, ydata] = netcdf_read_write.read_grd_xy(file_names[0]) data_all = [] for ifile in file_names: # this happens to be in date order on my mac data = netcdf_read_write.read_grd(ifile) data_all.append(data) date_pairs = [] for name in file_names: pairname = name.split('/')[-2][0:15] date_pairs.append(pairname) # returning something like '2016292_2016316' for each intf print(pairname) return [xdata, ydata, data_all, date_pairs]
def readGRD(file_type): # Read in SAR data from .grd formatted file # INPUT FILES MUST BE LOCATED IN A GMTSAR DIRECTORY! # Path_list format: # 20170426_20170520/corr.grd # 20170426_20170601/corr.grd # 20170426_20170613/corr.grd # ... # Get list of file paths path_list = glob.glob("*/" + file_type) print('Number of files to read: ' + str(len(path_list))) # Establish tuple tupleGRD = collections.namedtuple('GRD_data', ['path_list', 'xdata', 'ydata', 'zdata']) # Get dimensional data try: [xdata, ydata] = netcdf_read_write.read_grd_xy( path_list[0]) # can read either netcdf3 or netcdf4. except TypeError: [xdata, ydata] = netcdf_read_write.read_netcdf4_xy(path_list[0]) # Loop through path_list to read in target datafiles zdata = [] date_pairs = [] i = 0 for file in path_list: try: data = netcdf_read_write.read_grd(file) except TypeError: data = netcdf_read_write.read_netcdf4(file) zdata.append(data) pairname = file.split('/')[-2][0:19] date_pairs.append( pairname ) # returning something like '2016292_2016316' for each intf if i == floor(len(path_list) / 2): print('Halfway done reading...') myData = tupleGRD(path_list=np.array(path_list), xdata=np.array(xdata), ydata=np.array(ydata), zdata=np.array(zdata)) return myData
def reader_simple_format(file_names): """ An earlier reading function, works fast, useful for things like coherence statistics """ [xdata, ydata] = rwr.read_grd_xy(file_names[0]); data_all = []; for ifile in file_names: # this happens to be in date order on my mac data = rwr.read_grd(ifile); data_all.append(data); date_pairs = []; for name in file_names: pairname = name.split('/')[-2][0:15]; date_pairs.append(pairname); # returning something like '2016292_2016316' for each intf print(pairname) return [xdata, ydata, data_all, date_pairs];
def inputs(myfiles_no_ramp, remove_ramp_flag, myfiles_phase, signal_spread_file, manual_remove, number_of_excluded_images, wls_flag=0): signal_spread_data = rwr.read_grd(signal_spread_file) f = open(manual_remove, 'r') raw, content = f.readlines()[0:number_of_excluded_images], [] for i in range(len(raw)): content.append(raw[i].strip('\n')) filesmodified = [] for i in range(len(myfiles_phase)): if myfiles_phase[i][16:31] not in content: filesmodified.append(myfiles_phase[i]) if remove_ramp_flag != 0: f = open("Metadata/Ramp_need_fix.txt", 'r') raw, content = f.readlines()[:], [] for i in range(len(raw)): content.append(raw[i].strip('\n')) myfiles_new = [] for i in range(len(filesmodified)): test = filesmodified[i].replace("ref", "ref_corrected") if test in myfiles_no_ramp: myfiles_new.append(test) if filesmodified[i][16:31] not in content: myfiles_new.append(filesmodified[i]) print(len(myfiles_new)) datatuple = rmd.reader(myfiles_new) if remove_ramp_flag == 0: print(len(filesmodified)) datatuple = rmd.reader(filesmodified) if wls_flag == 1: filesmodified_coherence = [ x.replace(x[32:], "corr.grd") for x in filesmodified ] coherence_cube = rmd.reader(filesmodified_coherence) coherence_cube = coherence_cube.zvalues else: coherence_cube = np.ones(np.shape(datatuple.zvalues)) print(datatuple.dates_correct) dates = read_dates(myfiles_phase) date_pairs = datatuple.dates_correct print("Reading %d interferograms from %d acquisitions. " % (len(date_pairs), len(dates))) return datatuple, signal_spread_data, dates, date_pairs, coherence_cube
def histogram_of_grd_file_values(filename, varname='Deviation', plotname='histogram_values.png'): """ simple plot to make a histogram of a grid file """ z = netcdf_read_write.read_grd(filename) z_vector = np.reshape(z, (np.shape(z)[0] * np.shape(z)[1], )) plt.figure(dpi=250, figsize=(8, 7)) plt.hist(z_vector, bins=50, color='orange') plt.yscale('log') plt.ylabel('Number of Pixels', fontsize=20) plt.xlabel(varname, fontsize=20) plt.gca().tick_params(axis='both', which='major', labelsize=16) plt.savefig(plotname) plt.close() return
def inputs(file_names): [xdata,ydata] = netcdf_read_write.read_grd_xy(file_names[0]); data_all=[]; for ifile in file_names: # this happens to be in date order on my mac data = netcdf_read_write.read_grd(ifile); data_all.append(data); date_pairs=[]; dates=[]; for name in file_names: pairname=name.split('/')[-1][0:15]; date_pairs.append(pairname); # returning something like '2016292_2016316' for each intf splitname=pairname.split('_'); dates.append(splitname[0]) dates.append(splitname[1]) dates=list(set(dates)); dates=sorted(dates); print(dates); print("%d interferograms read from %d acquisitions." % (len(date_pairs), len(dates)) ); return [xdata, ydata, data_all, dates, date_pairs];
def drive_full_TS_isce(intf_files, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, outdir, baseline_file=None, coh_files=None): # SETUP. signal_spread_file = outdir + "/signalspread_cut.nc" intf_tuple = rmd.reader_isce(intf_files) coh_tuple = None if coh_files is not None: coh_tuple = rmd.reader_isce(coh_files) xdates = stacking_utilities.get_xdates_from_intf_tuple(intf_tuple) signal_spread_data = rwr.read_grd(signal_spread_file) # TIME SERIES TS = nsbas.Full_TS(intf_tuple, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, signal_spread_data, baseline_file=baseline_file, coh_tuple=coh_tuple) # OUTPUTS TS_NC_file = outdir + "/TS.nc" TS_image_file = outdir + "/TS.png" rwr.produce_output_timeseries(intf_tuple.xvalues, intf_tuple.yvalues, TS, xdates, 'mm', TS_NC_file) stacking_utilities.plot_full_timeseries(TS_NC_file, xdates, TS_image_file, vmin=-50, vmax=200, aspect=1 / 8) return
def inputs(file_names): try: [xdata, ydata] = netcdf_read_write.read_grd_xy( file_names[0]) # can read either netcdf3 or netcdf4. except TypeError: [xdata, ydata] = netcdf_read_write.read_netcdf4_xy(file_names[0]) data_all = [] file_names = sorted(file_names) # To force into date-ascending order. titles = [] for ifile in file_names: # Read the data try: data = netcdf_read_write.read_grd(ifile) except TypeError: data = netcdf_read_write.read_netcdf4(ifile) data_all.append(data) # LOS_20161121_INT3.grd titles.append(ifile[-17:-9]) return [xdata, ydata, data_all, titles]
def drive_full_TS_gmtsar(intf_files, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, outdir, signal_spread_file, baseline_file=None, coh_files=None): # SETUP. start_index = 0 end_index = 7000000 signal_spread_file = outdir + "/" + signal_spread_file intf_tuple = rmd.reader(intf_files) coh_tuple = None if coh_files is not None: coh_tuple = rmd.reader(coh_files) xdates = stacking_utilities.get_xdates_from_intf_tuple(intf_tuple) signal_spread_data = rwr.read_grd(signal_spread_file) # TIME SERIES TS = nsbas.Full_TS(intf_tuple, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, signal_spread_data, start_index=start_index, end_index=end_index, baseline_file=baseline_file, coh_tuple=coh_tuple) rwr.produce_output_TS_grids(intf_tuple.xvalues, intf_tuple.yvalues, TS, xdates, 'mm', outdir) return
def compute_loops(all_loops, loops_dir, loops_guide, rowref, colref): subprocess.call(['mkdir', '-p', loops_dir], shell=False) ofile = open(loops_dir + loops_guide, 'w') for i in range(len(all_loops)): ofile.write("Loop %d: %s %s %s\n" % (i, all_loops[i][0], all_loops[i][1], all_loops[i][2])) ofile.close() unwrapped = 'unwrap.grd' wrapped = 'phasefilt.grd' z1_sample = netcdf_read_write.read_grd('intf_all/' + all_loops[0][0] + '_' + all_loops[0][1] + '/' + unwrapped) number_of_errors = np.zeros(np.shape(z1_sample)) for i in range(0, len(all_loops)): edge1 = all_loops[i][0] + '_' + all_loops[i][1] edge2 = all_loops[i][1] + '_' + all_loops[i][2] edge3 = all_loops[i][0] + '_' + all_loops[i][2] [xdata, ydata, z1] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge1 + '/' + unwrapped) [_, _, z2] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge2 + '/' + unwrapped) [_, _, z3] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge3 + '/' + unwrapped) [xdata, ydata, wr_z1] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge1 + '/' + wrapped) [_, _, wr_z2] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge2 + '/' + wrapped) [_, _, wr_z3] = netcdf_read_write.read_any_grd_xyz('intf_all/' + edge3 + '/' + wrapped) print("Loop " + str(i) + ":") rowdim, coldim = np.shape(z1) histdata_raw = [] histdata_fix = [] znew_raw = np.zeros(np.shape(z1)) znew_fix = np.zeros(np.shape(z1)) errorcount = 0 for j in range(rowdim): for k in range(coldim): wr1 = wr_z1[j][k] - wr_z1[rowref, colref] z1_adj = z1[j][k] - z1[rowref, colref] wr2 = wr_z2[j][k] - wr_z2[rowref, colref] z2_adj = z2[j][k] - z2[rowref, colref] wr3 = wr_z3[j][k] - wr_z3[rowref, colref] z3_adj = z3[j][k] - z3[rowref, colref] # Using equation from Heresh Fattahi's PhD thesis to isolate unwrapping errors. wrapped_closure_raw = wr_z1[j][k] + wr_z2[j][k] - wr_z3[j][k] wrapped_closure_fix = wr1 + wr2 - wr3 offset_before_unwrapping = np.mod(wrapped_closure_fix, 2 * np.pi) if offset_before_unwrapping > np.pi: offset_before_unwrapping = offset_before_unwrapping - 2 * np.pi # send it to the -pi to pi realm. unwrapped_closure_raw = z1[j][k] + z2[j][k] - z3[j][k] unwrapped_closure_fix = z1_adj + z2_adj - z3_adj znew_raw[j][ k] = unwrapped_closure_raw - offset_before_unwrapping znew_fix[j][ k] = unwrapped_closure_fix - offset_before_unwrapping if ~np.isnan(znew_raw[j][k]): histdata_raw.append(znew_raw[j][k] / np.pi) if ~np.isnan(znew_fix[j][k]): histdata_fix.append(znew_fix[j][k] / np.pi) if abs(znew_fix[j][k]) > 0.5: # if this pixel has errorcount = errorcount + 1 number_of_errors[j][k] = number_of_errors[j][k] + 1 errorpixels = round(100 * float(errorcount) / len(histdata_fix), 2) print("Most common raw loop sum: ") print(np.median(histdata_raw)) print("Most common fix loop sum: ") print(np.median(histdata_fix)) print("\n") make_plot(xdata, ydata, znew_fix, loops_dir + 'phase_closure_' + str(i) + '.eps', errorpixels) make_histogram(histdata_fix, loops_dir + 'histogram_' + str(i) + '.eps') return [xdata, ydata, number_of_errors]
# plot_grid_file('intf_all/'+folder+'/mask.grd','mask_decimated'); # [nanpixels, totalpixels] = how_many_nans('intf_all/'+folder+'/mask_full.grd'); # [nanpixels, totalpixels] = how_many_nans('intf_all/'+folder+'/mask.grd'); #How many pixels are decorrelated? # counter=0; # tolerance=0; # for i in range(len(newx)): # for j in range(len(newy)): # if numbelow[j][i]>=(xdec*ydec)-tolerance: # counter=counter+1; # print("%d out of %d blocks have %d coherent pixels" % (counter, len(newx)*len(newy), tolerance) ); # APS TESTING # staging_directory='intf_all/referenced_unwrap.grd' # out_dir='intf_all/aps_unwrap.grd' # aps.main_function(staging_directory, out_dir); # TESTING OUTPUTS OF ATM/TOPO CORRECTION filename = "intf_all/referenced_unwrap.grd/2015153_2015177_unwrap.grd" zc = netcdf_read_write.read_grd(filename) print(np.shape(zc)) filename = "topo/topo_ra_subsampled.grd" zc = netcdf_read_write.read_grd(filename) print(np.shape(zc)) filename = "intf_all/atm_topo_corrected.grd/2018113_2018125_unwrap.grd" zc = netcdf_read_write.read_grd(filename) print(np.shape(zc))
def plot_two_general_grids(file1, file2, plotname, vmin1=-20, vmax1=5, flip_sign1=False, title1='', scalelabel1='Velocity (mm/yr)', vmin2=None, vmax2=None, flip_sign2=False, title2='', scalelabel2='Velocity (mm/yr)', readfile=True, invert_yaxis=True, cmap='rainbow'): """ A little function that plots two grid files in subplots side by side (they don't have to have the same registration, so no need to compute residuals) If readfile=True: then we read files. Otherwise, those two arguments are actually data """ if readfile: data1 = netcdf_read_write.read_grd(file1) data2 = netcdf_read_write.read_grd(file2) else: data1 = file1 data2 = file2 if flip_sign1: data1 = -1 * data1 if flip_sign2: data2 = -1 * data2 if vmin2 is None: vmin2 = vmin1 if vmax2 is None: vmax2 = vmax1 # First figure fig, axarr = plt.subplots(1, 2, sharey='none', figsize=(15, 8), dpi=300) axarr[0].imshow(data1, vmin=vmin1, vmax=vmax1, cmap=cmap) axarr[0].tick_params(labelsize=16) axarr[0].set_title(title1, fontsize=20) if invert_yaxis: axarr[0].invert_yaxis() # Second figure axarr[1].imshow(data2, vmin=vmin2, vmax=vmax2, cmap=cmap) axarr[1].tick_params(labelsize=16) axarr[1].set_title(title2, fontsize=20) if invert_yaxis: axarr[1].invert_yaxis() # Colorbar #1 cbarax = fig.add_axes([0.15, 0.06, 0.1, 0.9], visible=False) color_boundary_object = matplotlib.colors.Normalize(vmin=vmin1, vmax=vmax1) custom_cmap = cm.ScalarMappable(norm=color_boundary_object, cmap=cmap) custom_cmap.set_array(np.arange(vmin1, vmax1, 0.1)) cb = plt.colorbar(custom_cmap, aspect=12, fraction=0.2, orientation='horizontal') cb.set_label(scalelabel1, fontsize=18) cb.ax.tick_params(labelsize=16) # Colorbar #2 cbarax = fig.add_axes([0.58, 0.06, 0.1, 0.9], visible=False) color_boundary_object = matplotlib.colors.Normalize(vmin=vmin2, vmax=vmax2) custom_cmap = cm.ScalarMappable(norm=color_boundary_object, cmap=cmap) custom_cmap.set_array(np.arange(vmin2, vmax2, 0.1)) cb = plt.colorbar(custom_cmap, aspect=12, fraction=0.2, orientation='horizontal') cb.set_label(scalelabel2, fontsize=18) cb.ax.tick_params(labelsize=16) plt.savefig(plotname) plt.close() return
def make_residual_plot(file1, file2, plotname, histname, vmin=-20, vmax=5, title1='', title2='', scalelabel='LOS Velocity', units='mm/yr', flip_sign1=False, flip_sign2=False): """ A basic function that takes two co-registered grids and subtracts them, showing residuals in the third panel and histogram of residuals in separate plot. """ data1 = netcdf_read_write.read_grd(file1) data2 = netcdf_read_write.read_grd(file2) if flip_sign1: data1 = -1 * data1 if flip_sign2: data2 = -1 * data2 residuals = np.subtract(data1, data2) residuals_vector = np.reshape( residuals, (np.shape(residuals)[0] * np.shape(residuals)[1], )) fig, axarr = plt.subplots(1, 3, sharey='all', figsize=(20, 8), dpi=300) axarr[0].imshow(data1, vmin=vmin, vmax=vmax, cmap='rainbow') axarr[0].tick_params(labelsize=16) axarr[0].set_title(title1, fontsize=20) axarr[0].invert_yaxis() axarr[1].imshow(data2, vmin=vmin, vmax=vmax, cmap='rainbow') axarr[1].tick_params(labelsize=16) axarr[1].set_title(title2, fontsize=20) axarr[1].invert_yaxis() axarr[2].imshow(residuals, vmin=-10, vmax=10, cmap='rainbow') axarr[2].tick_params(labelsize=16) axarr[2].set_title('Residuals', fontsize=20) axarr[2].invert_yaxis() # Fancy color bar #1 cbarax = fig.add_axes([0.85, 0.08, 0.1, 0.9], visible=False) color_boundary_object = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) custom_cmap = cm.ScalarMappable(norm=color_boundary_object, cmap='rainbow') custom_cmap.set_array(np.arange(vmin, vmax, 0.1)) cb = plt.colorbar(custom_cmap, aspect=12, fraction=0.2, orientation='vertical') cb.set_label(scalelabel + ' (' + units + ')', fontsize=18) cb.ax.tick_params(labelsize=16) # Fancy color bar for residuals cbarax = fig.add_axes([0.68, 0.05, 0.1, 0.9], visible=False) color_boundary_object = matplotlib.colors.Normalize(vmin=-10, vmax=10) custom_cmap = cm.ScalarMappable(norm=color_boundary_object, cmap='rainbow') custom_cmap.set_array(np.arange(vmin, vmax, 0.1)) cb = plt.colorbar(custom_cmap, aspect=12, fraction=0.2, orientation='horizontal') cb.set_label('Residual (' + units + ')', fontsize=16) cb.ax.tick_params(labelsize=14) plt.savefig(plotname) plt.close() plt.figure(dpi=300, figsize=(8, 6)) plt.hist(residuals_vector, bins=50, color='orange') plt.yscale('log') plt.ylabel('Number of Pixels', fontsize=20) plt.xlabel('Residuals (' + units + ')', fontsize=20) plt.gca().tick_params(axis='both', which='major', labelsize=16) plt.savefig(histname) plt.close() return