Esempio n. 1
0
def remove_plane(filename, planefile, outfile, m1, m2, m3):
    xvalues, yvalues, zvalues = rwr.read_grd_xyz(filename)
    i, j = 0, 0
    new_z = np.zeros((len(yvalues), len(xvalues)))
    for z in np.nditer(zvalues):
        new_z[i, j] = zvalues[i, j] - (m1 + m2 * xvalues[j] + m3 * yvalues[i])
        j += 1
        if j == len(xvalues):
            j = 0
            i += 1
            if i == len(yvalues):
                i = 0
    print(new_z[0, 0])
    new_z = np.flipud(new_z)
    print(new_z[0, 0])
    rwr.produce_output_netcdf(xvalues, yvalues, np.flipud(new_z),
                              'unwrapped phase', outfile)
    rwr.flip_if_necessary(outfile)
    outfile1 = outfile.replace("no_ramp.grd", "no_ramp_comparison.png")

    fr = netcdf.netcdf_file(outfile, 'r')
    xread = fr.variables['x']
    yread = fr.variables['y']
    zread = fr.variables['z']
    zread_copy = zread[:][:].copy()

    fr2 = netcdf.netcdf_file(filename, 'r')
    xread2 = fr2.variables['x']
    yread2 = fr2.variables['y']
    zread2 = fr2.variables['z']
    zread2_copy = zread2[:][:].copy()

    fig = plt.figure(figsize=(7, 10))
    ax1 = plt.subplot(121)
    old = ax1.imshow(zread2_copy, aspect=1.2)
    ax1.invert_xaxis()
    ax1.get_xaxis().set_ticks([])
    ax1.get_yaxis().set_ticks([])
    ax1.set_xlabel("Range", fontsize=16)
    ax1.set_ylabel("Azimuth", fontsize=16)

    ax2 = plt.subplot(122)
    new = ax2.imshow(zread_copy,
                     aspect=1.2,
                     vmin=np.nanmin(zread_copy),
                     vmax=np.nanmax(zread2_copy))
    ax2.invert_xaxis()
    ax2.get_xaxis().set_ticks([])
    ax2.get_yaxis().set_ticks([])
    ax2.set_xlabel("Range", fontsize=16)
    cb = plt.colorbar(new)
    cb.set_label('unwrapped phase', size=16)

    plt.savefig(outfile1)
    plt.close()

    rwr.produce_output_plot(outfile, 'Ramp removed',
                            outfile.replace('grd', 'png'), 'unwraped phase')

    return
Esempio n. 2
0
def make_referenced_unwrapped(rowref, colref, prior_staging_directory,
                              post_staging_directory):
    files = glob.glob(prior_staging_directory + "/*")
    print("Imposing reference pixel on %d files in %s; saving output in %s" %
          (len(files), prior_staging_directory, post_staging_directory))
    out_dir = post_staging_directory + "/"
    subprocess.call(['mkdir', '-p', out_dir], shell=False)

    for filename in files:
        individual_name = filename.split('/')[-1]
        print(individual_name)
        [xdata, ydata, zdata] = netcdf_read_write.read_grd_xyz(filename)
        # xdata is range/columns, ydata is azimuth/rows

        # Here we subtract the value of zdata[rowref][colref] to fix the refernece pixel.
        # referenced_zdata[rowref][colref]=0 by definition.
        referenced_zdata = np.zeros(np.shape(zdata))
        for i in range(len(ydata)):
            for j in range(len(xdata)):
                referenced_zdata[i][j] = zdata[i][j] - zdata[rowref][colref]
        print(referenced_zdata[rowref][colref])

        outname = out_dir + individual_name
        netcdf_read_write.produce_output_netcdf(xdata, ydata, referenced_zdata,
                                                'phase', outname)
        netcdf_read_write.flip_if_necessary(outname)
    return
Esempio n. 3
0
def write_APS_to_files(xdata, ydata, aps_array, dates, iteration):
	nsar=np.shape(aps_array)[0];
	for i in range(nsar):
		filename="APS_"+str(dates[i])+"_IT"+str(iteration)+".grd";
		netcdf_read_write.produce_output_netcdf(xdata, ydata, aps_array[i][:][:],'',filename);
		netcdf_read_write.flip_if_necessary(filename);
	return;
Esempio n. 4
0
def intf_stack_to_grds(xdata, ydata, corrected_intfs, date_pairs, out_dir):
	print("Writing corrected interferograms to file. ")
	zdim, rowdim, coldim = np.shape(corrected_intfs);
	for i in range(zdim):
		item_name=date_pairs[i]
		netcdfname=out_dir+'/'+item_name+'_unwrap.grd';
		netcdf_read_write.produce_output_netcdf(xdata, ydata, corrected_intfs[i][:][:], 'unwrapped_phase', netcdfname);
		netcdf_read_write.flip_if_necessary(netcdfname);
	return;
Esempio n. 5
0
def generate_reflon_reflat(velfile, veldir, rowref, colref):
    # In this part, I sometimes need to flip the x-axis of the input array to make sense with the geographic
    # coordinates.
    # I suspect that for ascending orbits, this may not be necessary.
    # Worth checking if it introduces bugs.

    # Here we will use GMTSAR to geocode a small region including the reference pixel.
    # We extract the latitude and longitude of the reference pixel.
    refpoint_file = 'reference_point.grd'
    # names only here. directory gets added later.
    ref_ll_name = 'ref_ll'
    # These are temporary files.
    ref_ll = ref_ll_name + '.grd'

    [xdata, ydata, zdata] = netcdf_read_write.read_any_grd_xyz(velfile)

    colref = len(xdata) - colref
    # switching the x-axis direction. required for descending data, unsure about ascending.
    # In general we can figure this out from the flight_angle.

    rowarray = np.array([ydata[rowref], ydata[rowref + 1]])
    colarray = np.array([xdata[colref], xdata[colref + 1]])

    # plt.figure();
    # plt.contourf(xdata, ydata, zdata, cmap='jet');
    # plt.plot(xdata[colref],ydata[rowref],'.',markersize=20);
    # plt.gca().invert_xaxis();
    # plt.savefig('test1.eps');
    plt.figure()
    plt.imshow(zdata, vmin=-20, vmax=20, cmap='jet')
    plt.plot(len(xdata) - colref, rowref, '.', markersize=10, color='k')
    plt.savefig('refpoint.eps')

    zarray = np.array([[0.0, 0.01], [0.01, 0.01]])

    netcdf_read_write.produce_output_netcdf(colarray, rowarray, zarray,
                                            'mm/yr',
                                            veldir + '/' + refpoint_file)
    netcdf_read_write.flip_if_necessary(veldir + '/' + refpoint_file)
    subprocess.call(
        ['geocode_mod.csh', refpoint_file, ref_ll, ref_ll_name, veldir],
        shell=False)

    [xll, yll,
     zll] = netcdf_read_write.read_any_grd_variables(veldir + '/' + ref_ll,
                                                     'lon', 'lat', 'z')
    latref = yll[0]
    lonref = xll[0]
    print("\nReference Location is: ")
    print(lonref)
    print(latref)

    subprocess.call(['rm', veldir + '/' + ref_ll_name + '.png'], shell=False)
    subprocess.call(['rm', veldir + '/' + ref_ll_name + '.kml'], shell=False)

    return [lonref, latref]
Esempio n. 6
0
def plane_fitter(filename, outfile):
    """This function fits the inputted data (filename) to the model: z = A + Bx + Cy. It saves the model in
    outfile. It plots a comparison of the data and the model, and also returns the model parameters A, B and C."""
    xvalues, yvalues, zvalues = rwr.read_grd_xyz(filename)
    i, j = 0, 0
    d, x, y = [], [], []
    for z in np.nditer(zvalues):
        if np.isnan(z) == False:
            d.append(zvalues[i, j])
            x.append(xvalues[j])
            y.append(yvalues[i])
        j += 1
        if j == len(xvalues):
            j = 0
            i += 1
            if i == len(yvalues):
                i = 0
    temp = np.ones(len(d))
    G = np.column_stack((temp, x, y))
    GTG = np.dot(np.transpose(G), G)
    GTd = np.dot(np.transpose(G), d)
    soln = np.dot(np.linalg.inv(GTG), GTd)
    i, j = 0, 0
    model_z = np.zeros((len(yvalues), len(xvalues)))
    for z in np.nditer(zvalues):
        model_z[i, j] = soln[0] + soln[1] * xvalues[j] + soln[2] * yvalues[i]
        j += 1
        if j == len(xvalues):
            j = 0
            i += 1
            if i == len(yvalues):
                i = 0
    rwr.produce_output_netcdf(xvalues, yvalues, model_z, 'unwrapped phase',
                              outfile)
    rwr.flip_if_necessary(outfile)
    outfile1 = outfile.replace("model.grd", "model_comparison.png")
    fr = netcdf.netcdf_file(outfile, 'r')
    xread = fr.variables['x']
    yread = fr.variables['y']
    zread = fr.variables['z']
    zread_copy = zread[:][:].copy()

    fr2 = netcdf.netcdf_file(filename, 'r')
    xread2 = fr2.variables['x']
    yread2 = fr2.variables['y']
    zread2 = fr2.variables['z']
    zread2_copy = zread2[:][:].copy()

    fig = plt.figure(figsize=(7, 10))
    ax1 = plt.subplot(121)
    old = ax1.imshow(zread2_copy, aspect=1.2)
    ax1.invert_xaxis()
    ax1.get_xaxis().set_ticks([])
    ax1.get_yaxis().set_ticks([])
    ax1.set_xlabel("Range", fontsize=16)
    ax1.set_ylabel("Azimuth", fontsize=16)

    ax2 = plt.subplot(122)
    new = ax2.imshow(zread_copy,
                     aspect=1.2,
                     vmin=np.nanmin(zread_copy),
                     vmax=np.nanmax(zread2_copy))
    ax2.invert_xaxis()
    ax2.get_xaxis().set_ticks([])
    ax2.get_yaxis().set_ticks([])
    ax2.set_xlabel("Range", fontsize=16)
    cb = plt.colorbar(new)
    cb.set_label('unwrapped phase', size=16)

    plt.savefig(outfile1)
    plt.close()

    return soln[0], soln[1], soln[2]
Esempio n. 7
0
    model, content_1 = [], []
    for i in range(len(content)):
        content_1.append('intf_all_remote/' + content[i] + '/unwrap.grd')
        m1, m2, m3 = plane_fitter(
            content_1[i], content_1[i].replace('unwrap', 'unwrap_model'))
        model.append(content_1[i].replace('unwrap', 'unwrap_model'))
        remove_plane(content_1[i], model[i],
                     model[i].replace('model', 'no_ramp'), m1, m2, m3)
        temp1 = ['intf_all_remote/' + content[i] + '/unwrap_no_ramp.grd']
        d = rmd.reader(temp1)
        store = phr.phase_ref(d, 621, 32)
        temp = temp1[0].split('/')[-1]
        stem = temp1[0][0:-len(temp)]
        rwr.produce_output_netcdf(d.xvalues, d.yvalues, store[0], 'Radians',
                                  stem + 'unwrap_ref_corrected.grd')
        rwr.flip_if_necessary(stem + 'unwrap_ref_corrected.grd')
        rwr.produce_output_plot(stem + 'unwrap_ref_corrected.grd',
                                'Referenced and Corrected Unwrapped Phase',
                                stem + 'unwrap_ref_corrected.png',
                                'unwrapped phase')
        print('Done with file ' + str(i + 1))

# if __name__=="__main__":
# grdname="intf_all_remote/2018281_2018305/unwrap.grd"
# remove_trend2d(grdname,4);
# remove_trend2d(grdname,3);
# remove_trend2d(grdname,6);
# outfile = "classic_unwrapped_N4_good.grd"
# rwr.produce_output_plot(outfile, 'Ramp removed', 'Ramp_remove.png', 'phase')

# # BASH Version
Esempio n. 8
0
def make_histogram(histdata, plotname):
    plt.figure()
    plt.hist(histdata, bins=700)
    plt.yscale('log')
    plt.xlabel('Phase Difference (#*pi radians)')
    plt.ylabel('number of pixels')
    plt.savefig(plotname)
    plt.close()
    return


if __name__ == "__main__":
    loops_dir = "Phase_Circuits/"
    loops_guide = "loops.txt"
    rowref = 237
    # doing correction for phase ambiguity
    colref = 172
    # reference_pixel = [];  # not doing any correction for phase ambiguity

    all_loops = identify_all_loops()
    [xdata, ydata,
     number_of_errors] = compute_loops(all_loops, loops_dir, loops_guide,
                                       rowref, colref)

    # Print how often phase unwrapping errors affect different pixels.
    outfile = loops_dir + "how_many_errors.grd"
    netcdf_read_write.produce_output_netcdf(xdata, ydata, number_of_errors,
                                            'phase unwrapping errors', outfile)
    netcdf_read_write.flip_if_necessary(outfile)
    make_plot(xdata, ydata, number_of_errors,
              loops_dir + 'Number of Unwrapping Errors', 0.00)
Esempio n. 9
0
    for f in range(len(store)):
        ref_values.append(store[f, yvalue, xvalue])

    print(len(ref_values))

    i,j,f = 0,0,0
    while f < len(mytuple.zvalues):
            store[f, i ,j] = store[f, i ,j] - ref_values[f]
            j+=1
            if j==len(mytuple.xvalues):
                j=0
                i+=1
                if i == len(mytuple.yvalues):
                    i=0
                    print('Referencing phases in file ' + str(f+1) + ' out of ' + str(len(mytuple.zvalues)))
                    f+=1

    return store

if __name__ == "__main__":
    myfiles = glob.glob("intf_all_remote/???????_???????/unwrap.grd")
    d=rmd.reader(myfiles)
    store = phase_ref(d, 621, 32)
    for i in range(len(myfiles)):
        print('Dealing with file ' + str(i+1))
        temp = myfiles[i].split('/')[-1]
        stem = myfiles[i][0:-len(temp)]
        rwr.produce_output_netcdf(d.xvalues, d.yvalues, store[i], 'Radians', stem + 'unwrap_ref.grd')
        rwr.flip_if_necessary(stem + 'unwrap_ref.grd')
        rwr.produce_output_plot(stem + 'unwrap_ref.grd', 'Referenced Unwrapped Phase', stem + 'unwrap_ref.png', 'unwrapped phase')
    plt.show()
    return


if __name__ == "__main__":
    myfiles_no_ramp, remove_ramp_flag, wls_flag, myfiles_phase, manual_remove, signal_spread_file, wavelength, nsbas_good_num, smoothing, outfile = configure(
    )
    datatuple, signal_spread_data, dates, date_pairs, coherence_cube = inputs(
        myfiles_no_ramp, remove_ramp_flag, myfiles_phase, signal_spread_file,
        manual_remove, 15, wls_flag)
    vel = compute(coherence_cube, datatuple, nsbas_good_num,
                  signal_spread_data, dates, date_pairs, smoothing, wavelength,
                  outfile, wls_flag)
    rwr.produce_output_netcdf(datatuple.xvalues, datatuple.yvalues, vel,
                              'velocity', outfile)
    rwr.flip_if_necessary(outfile)
    rwr.produce_output_plot(
        outfile, 'Reasonable WNSBAS - smoothing factor: ' + str(smoothing),
        "Stacking/NSBAS/velocity_weighted50NSBAS_reasonable_smooth1.png",
        'velocity in mm/yr')

    # x,y,vel = rwr.read_grd_xyz(outfile)
    # signal = rwr.read_grd(signal_spread_file)
    # updated_vel = np.zeros((np.shape(vel)))
    # i, j,c  = 0, 0, 0
    # for v in np.nditer(vel):
    # 	print(c)
    # 	if signal[i,j] < 65 and signal[i,j] > 50:
    # 		updated_vel[i,j] = np.nan
    # 	else:
    # 		updated_vel[i,j] = vel[i,j]
def main_function():

	# GLOBAL PARAMETERS
	nfit=0
	ivar=1
	alt_ref=100
	thresh_amp=0.2
	subsampled_dem_grd="topo/topo_ra_subsampled_june.grd"  # subsampled in the same way as the intf grd files. 
	demfile="topo/topo_radar.hgt"
	example_rsc="rsc_files/example_sd.int.rsc"

	# INPUTS
	intf_list=glob.glob("intf_all/???????_???????");
	print(intf_list);

	# [width, length] = readbin.write_gmtsar2roipac_topo(subsampled_dem_grd,demfile);  # copying the demfile into roipac format just in case we've switched the master. 

	# COMPUTE
	for data_dir in intf_list:
		print(data_dir);
		intf_name=data_dir.split('/')[1];
		infile=data_dir+"/intf_sd.int";
		infile_filtered=data_dir+"/intf_filt.int";
		stratfile=data_dir+"/strat.unw"
		outfile=data_dir+"/out.int"
		outfile_filtered=data_dir+"/out_filtered.int"

		# Pretty standard GMTSAR files. 
		phasefile=data_dir+"/phase.grd";
		phasefilt_file=data_dir+"/phasefilt.grd";
		ampfile=data_dir+"/amp.grd";
		orig_phasefile=data_dir+"/orig_phase.grd";
		orig_phasefilt_file=data_dir+"/orig_phasefilt.grd";

		readbin.prep_files(phasefile, phasefilt_file, orig_phasefile, orig_phasefilt_file);  # copy files into safekeeping if necessary

		# MAKE BINARY INTERFEROGRAMS
		[width, length] = readbin.write_gmtsar2roipac_phase(data_dir,orig_phasefile, orig_phasefilt_file, ampfile,infile,infile_filtered);
		# width=661; length=1524

		# # # RUN THE FORTRAN
		print("\nRunning the fortran code to remove atmospheric artifacts from interferogram.")
		subprocess.call(['cp',example_rsc,data_dir+'/intf_sd.int.rsc'],shell=False);
		print("flatten_topo "+infile+" "+infile_filtered+" "+demfile+" "+outfile+" "+outfile_filtered+" "+str(nfit)+" "+str(ivar)+" "+str(alt_ref)+" "+str(thresh_amp)+" "+stratfile+"\n");
		subprocess.call(["flatten_topo",infile,infile_filtered,demfile,outfile,outfile_filtered,str(nfit),str(ivar),str(alt_ref),str(thresh_amp),stratfile],shell=False);
		subprocess.call(['mv','ncycle_topo',data_dir+'/ncycle_topo'],shell=False);
		subprocess.call(['mv','ncycle_topo_az',data_dir+'/ncycle_topo_az'],shell=False);

		# Output handling. First reading 1D arrays
		[real,imag]=readbin.read_binary_roipac_real_imag(infile);
		[phase_early,amp_early]=readbin.real_imag2phase_amp(real,imag); 
		[real,imag]=readbin.read_binary_roipac_real_imag(outfile);
		[phase_out,amp_late]=readbin.real_imag2phase_amp(real,imag);
		[real,imag]=readbin.read_binary_roipac_real_imag(outfile_filtered);
		[phasefilt_out,amp_late]=readbin.real_imag2phase_amp(real,imag);  # 1d arrays


		# # Write the GRD files , fixing an issue with pixel node registration. 
		[xdata_p,ydata_p]=netcdf_read_write.read_grd_xy(orig_phasefile);
		[xdata_pf,ydata_pf]=netcdf_read_write.read_grd_xy(orig_phasefilt_file);
		phase_out_grd=np.reshape(phase_out,(length,width));
		phasefilt_out_grd=np.reshape(phasefilt_out,(length,width));
		
		netcdf_read_write.produce_output_netcdf(xdata_p, ydata_p, phase_out_grd, 'radians', phasefile);
		netcdf_read_write.flip_if_necessary(phasefile);
		origrange=subprocess.check_output('gmt grdinfo -I- '+orig_phasefile,shell=True);   # fixing pixel node registration issue. 
		subprocess.call('gmt grdsample '+phasefile+' '+origrange.split()[0]+' -G'+phasefile+' -r', shell=True);

		netcdf_read_write.produce_output_netcdf(xdata_pf, ydata_pf, phasefilt_out_grd, 'radians', phasefilt_file);
		netcdf_read_write.flip_if_necessary(phasefilt_file);
		origrange=subprocess.check_output('gmt grdinfo -I- '+orig_phasefilt_file,shell=True);
		subprocess.call('gmt grdsample '+phasefilt_file+' '+origrange.split()[0]+' -G'+phasefilt_file+' -r', shell=True);

		# Making plot
		readbin.output_plots(phase_early, phasefilt_out, width, length, data_dir+"/"+intf_name+"_corrected.eps");

	return;
Esempio n. 12
0
    a=np.zeros((len(mytuple.yvalues), len(mytuple.xvalues)))
    i,j = 0,0
    for z in np.nditer(mytuple.zvalues):
        if z >= cutoff:
            a[i,j] = a[i,j] + 1
        j+=1
        if j== len(mytuple.xvalues):
            j=0
            i+=1
            if i == len(mytuple.yvalues):
                i=0
    i,j = 0,0
    for n in np.nditer(a):
        a[i,j] = (a[i,j]/(len(mytuple.filepaths)))*100
        j+=1
        if j== len(mytuple.xvalues):
            j=0
            i+=1
            if i == len(mytuple.yvalues):
                i=0
    return a


if __name__ == "__main__":
    myfiles = glob.glob("intf_all_remote/???????_???????/corr.grd")
    mytuple=rmd.reader(myfiles)
    a=stack_corr(mytuple, 0.1)
    rwr.produce_output_netcdf(mytuple.xvalues, mytuple.yvalues, a, 'Percentage', 'signalspread_please_test.nc')
    rwr.flip_if_necessary('signalspread_please_test.nc')
    rwr.produce_output_plot('signalspread_please_test.nc', 'Signal Spread', 'signalspread_please_test.png', 'Percentage of coherence (out of 288 images)' )
Esempio n. 13
0
# i, j = 0,0
# for x in range(len(xfinal_ratioed)):
# 	pixel_box = z[(yfinal_ratioed[x]-50):(yfinal_ratioed[x]+51),(xfinal_ratioed[x]-50):(xfinal_ratioed[x]+51) ]
# 	print(np.shape(pixel_box))
# 	for v in np.nditer(pixel_box):
# 		if np.isnan(v) == False:
# 			counter.append(v)
# 	print(len(counter))

x1, y1, z1 = rwr.read_grd_xyz('signalspread_please_test.nc')
x2, y2, z2 = rwr.read_grd_xyz(filenames[-2][0])
thing1 = z1[1200:1424, 400:660]
thing2 = z2[1200:1424, 400:660]
rwr.produce_output_netcdf(x1[400:660], y1[1200:1424], thing1, 'signal',
                          'possible_fault_info.grd')
rwr.flip_if_necessary('possible_fault_info.grd')
rwr.produce_output_plot('possible_fault_info.grd', '',
                        'possible_fault_info.png', '%')
rwr.produce_output_netcdf(x2[400:660], y2[1200:1424], thing2, 'velocity',
                          'possible_fault_info_vel.grd')
rwr.flip_if_necessary('possible_fault_info_vel.grd')

[x, y] = np.meshgrid(x1[400:660], y1[1200:1424])
[x_, y_] = np.meshgrid(x2[400:660], y2[1200:1424])

fig = plt.figure(figsize=(18, 10))
ax1 = plt.subplot(121)
image1 = ax1.contourf(x,
                      y,
                      thing1,
                      cmap='jet',
Esempio n. 14
0
def outputs(xdata, ydata, number_of_datas, zdim, vel, out_dir):
	
	netcdf_read_write.produce_output_netcdf(xdata, ydata, number_of_datas, 'coherent_intfs', out_dir+'/number_of_datas.grd');
	netcdf_read_write.flip_if_necessary(out_dir+'/number_of_datas.grd');
	netcdf_read_write.produce_output_plot(out_dir+'/number_of_datas.grd', "Number of Coherent Intfs (Total = "+str(zdim)+")", out_dir+'/number_of_coherent_intfs.eps', 'intfs');
	geocode(out_dir+'/number_of_datas.grd',out_dir);

	netcdf_read_write.produce_output_netcdf(xdata,ydata, vel, 'mm/yr', out_dir+'/vel.grd');
	netcdf_read_write.flip_if_necessary(out_dir+'/vel.grd');
	geocode(out_dir+'/vel.grd',out_dir);


	# Visualizing the velocity field in a few different ways. 
	zdata2=np.reshape(vel, [len(xdata)*len(ydata), 1])
	zdata2=sentinel_utilities.remove_nans_array(zdata2);
	plt.figure();
	plt.hist(zdata2,bins=80);
	plt.gca().set_yscale('log');
	plt.title('Pixels by Velocity: mean=%.2fmm/yr, sdev=%.2fmm/yr' % (np.mean(zdata2), np.std(zdata2)) )
	plt.ylabel('Number of Pixels');
	plt.xlabel('LOS velocity (mm/yr)')
	plt.grid('on');
	plt.savefig(out_dir+'/velocity_hist_log.png');
	plt.close();

	plt.figure();
	plt.gca().set_yscale('linear');
	plt.title('Pixels by Velocity: mean=%.2fmm/yr, sdev=%.2fmm/yr' % (np.mean(zdata2), np.std(zdata2)) )
	plt.hist(zdata2,bins=80);
	plt.ylabel('Number of Pixels');
	plt.xlabel('LOS velocity (mm/yr)')
	plt.grid('on');
	plt.savefig(out_dir+'/velocity_hist_lin.png');
	plt.close();


	plt.figure(figsize=(8,10));
	plt.imshow(vel,aspect=0.5,cmap='jet',vmin=-30, vmax=30);
	plt.gca().invert_yaxis()
	plt.gca().invert_xaxis()
	plt.gca().get_xaxis().set_ticks([]);
	plt.gca().get_yaxis().set_ticks([]);
	plt.title("Velocity");
	plt.gca().set_xlabel("Range",fontsize=16);
	plt.gca().set_ylabel("Azimuth",fontsize=16);
	cb = plt.colorbar();
	cb.set_label("mm/yr", size=16);
	plt.savefig(out_dir+"/vel_cutoff.png");
	plt.close();

	plt.figure(figsize=(8,10));
	plt.imshow(vel,aspect=0.5,cmap='jet',vmin=-150, vmax=150);
	plt.gca().invert_yaxis()
	plt.gca().invert_xaxis()
	plt.gca().get_xaxis().set_ticks([]);
	plt.gca().get_yaxis().set_ticks([]);
	plt.title("Velocity");
	plt.gca().set_xlabel("Range",fontsize=16);
	plt.gca().set_ylabel("Azimuth",fontsize=16);
	cb = plt.colorbar();
	cb.set_label("mm/yr", size=16);
	plt.savefig(out_dir+"/vel.png");
	plt.close();


	return;
                       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


if __name__ == "__main__":
    ramps, outfile_stem, myfiles, myfiles_no_ramp, remove_ramp = configure()
    myfiles_new = inputs(ramps, myfiles, myfiles_no_ramp, remove_ramp)
    velocities, x, y = velocity_simple_stack(myfiles_new, 56, 1, 50)
    rwr.produce_output_netcdf(
        x, y, velocities, 'mm/yr',
        outfile_stem + 'velo_prof_reasonable50_remastered.grd')
    rwr.flip_if_necessary(outfile_stem +
                          'velo_prof_reasonable50_remastered.grd')
    rwr.produce_output_plot(
        outfile_stem + 'velo_prof_reasonable50_remastered.grd',
        'Velocity Profile Reasonable (15 images removed)',
        outfile_stem + 'velo_prof_reasonable50_remastered.png',
        'velocity (mm/yr)')