Exemple #1
0
def reshape_TS_into_standard(outdir, earlyfile, cofile, latefile, outfile):
    """
    This is not particular general. It's using hard-coded information about time axis
    and the timing of the earthquake.
    It's for track 26509.
    This function pastes together a pre-seismic, co-seismic, and post-seismic set of time series or jumps.
    On the same xy grid.
    """
    tolerance = 300;  # Purposely killing all pixels above this value.
    print("Reshaping UAVSAR file into single TS File");
    [_tdata1, xdata1, ydata1, zdata1] = netcdf_read_write.read_3D_netcdf(earlyfile);
    [_xdata2, _ydata2, zdata2] = netcdf_read_write.read_netcdf3(cofile);
    [_tdata3, _xdata3, _ydata3, zdata3] = netcdf_read_write.read_3D_netcdf(latefile);
    print(np.shape(zdata1), np.shape(zdata2), np.shape(zdata3));
    ynum = np.shape(zdata1)[1];
    xnum = np.shape(zdata1)[2];
    znum = np.shape(zdata1)[0] + np.shape(zdata3)[0];
    total_data = np.zeros([znum, ynum, xnum]);
    print(np.shape(total_data));
    for i in range(np.shape(zdata1)[0]):
        temp = zdata1[i, :, :];
        temp[abs(temp) > tolerance] = np.nan;  # killing outliers
        total_data[i, :, :] = temp;  # doing this six times.
        print("Early data Slice %d" % i);
    temp = zdata2;
    temp[abs(temp) > tolerance] = np.nan;
    total_data[7, :, :] = np.add(total_data[6, :, :], zdata2);  # The coseismic chunk
    print("Coseismic data slice 7");
    for i in range(1, np.shape(zdata3)[0]):
        temp = zdata3[i, :, :];
        temp[abs(temp) > tolerance] = np.nan;  # killing outliers
        total_data[i + np.shape(zdata1)[0], :, :] = np.add(temp, total_data[7, :, :]);
        print("Postseismic data slice %d " % (i + np.shape(zdata1)[0]));
    dtarray = [];
    dtarray.append(dt.datetime.strptime("2009-04-24", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2009-09-21", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2010-04-12", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2010-07-01", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2010-12-01", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2011-05-18", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2011-11-10", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2012-09-26", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2013-05-24", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2014-06-11", "%Y-%m-%d"));  # Hard-coded
    dtarray.append(dt.datetime.strptime("2017-11-01", "%Y-%m-%d"));  # Hard-coded
    zunits = "mm";
    print(np.shape(total_data));
    netcdf_read_write.produce_output_timeseries(xdata1, ydata1, total_data, dtarray, zunits, outfile);
    stacking_utilities.plot_full_timeseries(outfile, dtarray, outdir + "TS_cumulative.png", vmin=-50, vmax=200,
                                            aspect=1 / 8);
    stacking_utilities.plot_incremental_timeseries(outfile, dtarray, outdir + "TS_incremental.png", vmin=-50, vmax=100,
                                                   aspect=1 / 8);
    return;
def inputs_TS_grd(filename, lonfile, latfile, day0=dt.datetime.strptime("2009-04-24", "%Y-%m-%d")):
    """
    Reads a TS file with associated lat/lon files
    The files generally are not orthorectified grids
    GRDnetcdf has tdata (days since day0), x, y, and zdata (3D cube)
    lon and lat files are 2D arrays with corresponding lon and lat for each point
    day0 is the day of the first acquisition in the time series (hard coded for a UAVSAR track default)
    """
    print("Reading TS Grid file  %s" % filename);
    [tdata, _, _, zdata] = netcdf_read_write.read_3D_netcdf(filename);
    print("tdata:", tdata);
    print("   where Day0 of this time series is %s " % dt.datetime.strftime(day0, "%Y-%m-%d"));
    [_, _, lon] = netcdf_read_write.read_any_grd(lonfile);
    [_, _, lat] = netcdf_read_write.read_any_grd(latfile);
    print("lon and lat:", np.shape(lon));
    print("zdata:", np.shape(zdata));
    zdata_correct_size = [];
    if np.shape(zdata[0])[0] == np.shape(lon)[0]+1 and np.shape(zdata[0])[1] == np.shape(lat)[1]+1:
        for i in range(len(zdata)):
            zdata_correct_size.append(zdata[i][0:-1, 0:-1]);  # cutting off one pixel on each end for pixel node problem
    else:
        zdata_correct_size = zdata;
    dtarray = [];
    for i in range(len(tdata)):
        dtarray.append(day0 + dt.timedelta(days=int(tdata[i])));

    assert(np.shape(lon) == np.shape(zdata_correct_size[0])), ValueError("Lon and Data size don't match");
    assert(np.shape(lat) == np.shape(zdata_correct_size[0])), ValueError("Lat and Data size don't match");
    assert(np.shape(zdata_correct_size)[0] == len(dtarray)), ValueError("dtarray and zdata size don't match");
    myGridTS = GrdTSData(dtarray=dtarray, lon=lon, lat=lat, TS=zdata_correct_size);
    return myGridTS;
def gmtsar_nc_stack_2_isce_stack(ts_file, output_dir, bands=2):
    # Decompose a 3D time series object into a series of slices
    # Write the slices into isce unwrapped format.
    call(["mkdir", "-p", output_dir], shell=False)
    tdata, xdata, ydata, zdata = rwr.read_3D_netcdf(ts_file)
    for i in range(np.shape(zdata)[0]):
        call(["mkdir", "-p", output_dir + "/scene_" + str(i)])
        temp = zdata[i, :, :]

        # Write data out in isce format
        ny, nx = np.shape(temp)
        name = "ts_slice_" + str(i)
        filename = output_dir + "/scene_" + str(i) + "/" + name + ".unw"
        temp = np.float32(temp)
        isce_read_write.write_isce_unw(temp, temp, nx, ny, "FLOAT", filename)

        isce_read_write.plot_scalar_data(filename,
                                         band=bands,
                                         colormap='rainbow',
                                         datamin=-50,
                                         datamax=200,
                                         aspect=1 / 5,
                                         outname=output_dir + "/scene_" +
                                         str(i) + "/isce_unw_band.png")
    return
def plot_incremental_timeseries(TS_NC_file,
                                xdates,
                                TS_image_file,
                                vmin=-50,
                                vmax=200,
                                aspect=1):
    """Make a nice incremental displacement time series plot. """
    tdata, xdata, ydata, TS_array = netcdf_read_write.read_3D_netcdf(
        TS_NC_file)
    num_rows_plots = 3
    num_cols_plots = 4

    # Combining the two shortest intervals into one.
    print(np.shape(TS_array))
    selected = [0, 1, 3, 4, 5, 6, 7, 8, 9, 10]
    TS_array = TS_array[selected, :, :]
    xdates = [xdates[i] for i in range(11) if i in selected]
    print(np.shape(TS_array))
    print(len(xdates))

    f, axarr = plt.subplots(num_rows_plots,
                            num_cols_plots,
                            figsize=(16, 10),
                            dpi=300)
    for i in range(1, len(xdates)):
        rownum, colnum = get_axarr_numbers(num_cols_plots, i)
        data = np.subtract(TS_array[i, :, :], TS_array[i - 1, :, :])
        axarr[rownum][colnum].imshow(data,
                                     aspect=aspect,
                                     cmap='rainbow',
                                     vmin=vmin,
                                     vmax=vmax)
        titlestr = dt.datetime.strftime(xdates[i], "%Y-%m-%d")
        axarr[rownum][colnum].get_xaxis().set_visible(False)
        axarr[rownum][colnum].set_title(titlestr, fontsize=20)

    _ = f.add_axes([0.75, 0.35, 0.2, 0.3], 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))
    cb = plt.colorbar(custom_cmap,
                      aspect=12,
                      fraction=0.2,
                      orientation='vertical')
    cb.set_label('Displacement (mm)', fontsize=18)
    cb.ax.tick_params(labelsize=12)

    plt.savefig(TS_image_file)
    return
def plot_full_timeseries(TS_NC_file,
                         xdates,
                         TS_image_file,
                         vmin=-50,
                         vmax=200,
                         aspect=1):
    """ Make a nice time series plot. """
    tdata, xdata, ydata, TS_array = netcdf_read_write.read_3D_netcdf(
        TS_NC_file)
    num_rows_plots = 3
    num_cols_plots = 4

    f, axarr = plt.subplots(num_rows_plots,
                            num_cols_plots,
                            figsize=(16, 10),
                            dpi=300)
    for i in range(len(xdates)):
        rownum, colnum = get_axarr_numbers(num_cols_plots, i)
        axarr[rownum][colnum].imshow(TS_array[i, :, :],
                                     aspect=aspect,
                                     cmap='rainbow',
                                     vmin=vmin,
                                     vmax=vmax)
        titlestr = dt.datetime.strftime(xdates[i], "%Y-%m-%d")
        axarr[rownum][colnum].get_xaxis().set_visible(False)
        axarr[rownum][colnum].set_title(titlestr, fontsize=20)

    _ = f.add_axes([0.75, 0.35, 0.2, 0.3], 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))
    cb = plt.colorbar(custom_cmap,
                      aspect=12,
                      fraction=0.2,
                      orientation='vertical')
    cb.set_label('Displacement (mm)', fontsize=18)
    cb.ax.tick_params(labelsize=12)

    plt.savefig(TS_image_file)
    return