Exemple #1
0
def read_init_info(inps):
    # Time Series Info
    ts_file0 = inps.timeseries_file[0]
    atr = readfile.read_attribute(ts_file0)
    inps.key = atr['FILE_TYPE']
    if inps.key == 'timeseries':
        obj = timeseries(ts_file0)
    elif inps.key == 'giantTimeseries':
        obj = giantTimeseries(ts_file0)
    elif inps.key == 'HDFEOS':
        obj = HDFEOS(ts_file0)
    else:
        raise ValueError('input file is {}, not timeseries.'.format(inps.key))
    obj.open()

    if not inps.file_label:
        inps.file_label = [
            str(i) for i in list(range(len(inps.timeseries_file)))
        ]

    # default mask file
    if not inps.mask_file and 'masked' not in ts_file0:
        dir_name = os.path.dirname(ts_file0)
        if 'Y_FIRST' in atr.keys():
            inps.mask_file = os.path.join(dir_name, 'geo_maskTempCoh.h5')
        else:
            inps.mask_file = os.path.join(dir_name, 'maskTempCoh.h5')
        if not os.path.isfile(inps.mask_file):
            inps.mask_file = None

    # date info
    inps.date_list = obj.dateList
    if inps.start_date:
        inps.date_list = [
            i for i in inps.date_list if int(i) >= int(inps.start_date)
        ]
    if inps.end_date:
        inps.date_list = [
            i for i in inps.date_list if int(i) <= int(inps.end_date)
        ]
    inps.num_date = len(inps.date_list)
    inps.dates, inps.yearList = ptime.date_list2vector(inps.date_list)
    (inps.ex_date_list, inps.ex_dates,
     inps.ex_flag) = read_exclude_date(inps.ex_date_list, inps.date_list)

    # initial display index
    if obj.metadata['REF_DATE'] in inps.date_list:
        inps.ref_idx = inps.date_list.index(obj.metadata['REF_DATE'])
    else:
        inps.ref_idx = 0
    if inps.ref_date:
        inps.ref_idx = inps.date_list.index(inps.ref_date)
    if not inps.init_idx:
        if inps.ref_idx < inps.num_date / 2.:
            inps.init_idx = -3
        else:
            inps.init_idx = 3

    # Display Unit
    (inps.disp_unit,
     inps.unit_fac) = pp.scale_data2disp_unit(metadata=atr,
                                              disp_unit=inps.disp_unit)[1:3]

    # Read Error List
    inps.error_ts = None
    inps.ex_error_ts = None
    if inps.error_file:
        error_fileContent = np.loadtxt(inps.error_file,
                                       dtype=bytes).astype(str)
        inps.error_ts = error_fileContent[:, 1].astype(
            np.float) * inps.unit_fac
        if inps.ex_date_list:
            e_ts = inps.error_ts[:]
            inps.ex_error_ts = e_ts[inps.ex_flag == 0]
            inps.error_ts = e_ts[inps.ex_flag == 1]

    # Zero displacement for 1st acquisition
    if inps.zero_first:
        inps.zero_idx = min(0, np.min(np.where(inps.ex_flag)[0]))

    # default lookup table file
    if not inps.lookup_file:
        inps.lookup_file = ut.get_lookup_file('./INPUTS/geometryRadar.h5')
    inps.coord = ut.coordinate(atr, inps.lookup_file)

    # size and lalo info
    inps.pix_box, inps.geo_box = subset.subset_input_dict2box(vars(inps), atr)
    inps.pix_box = inps.coord.check_box_within_data_coverage(inps.pix_box)
    inps.geo_box = inps.coord.box_pixel2geo(inps.pix_box)
    # Out message
    data_box = (0, 0, obj.width, obj.length)
    print('data   coverage in y/x: ' + str(data_box))
    print('subset coverage in y/x: ' + str(inps.pix_box))
    print('data   coverage in lat/lon: ' +
          str(inps.coord.box_pixel2geo(data_box)))
    print('subset coverage in lat/lon: ' + str(inps.geo_box))
    print(
        '------------------------------------------------------------------------'
    )

    # reference pixel
    if not inps.ref_lalo and 'REF_LAT' in atr.keys():
        inps.ref_lalo = (float(atr['REF_LAT']), float(atr['REF_LON']))
    if inps.ref_lalo:
        if inps.ref_lalo[1] > 180.:
            inps.ref_lalo[1] -= 360.
        inps.ref_yx = inps.coord.geo2radar(inps.ref_lalo[0],
                                           inps.ref_lalo[1],
                                           print_msg=False)[0:2]
    if not inps.ref_yx:
        inps.ref_yx = [int(atr['REF_Y']), int(atr['REF_X'])]

    # Initial Pixel Coord
    if inps.lalo:
        inps.yx = inps.coord.geo2radar(inps.lalo[0],
                                       inps.lalo[1],
                                       print_msg=False)[0:2]
    try:
        inps.lalo = inps.coord.radar2geo(inps.yx[0],
                                         inps.yx[1],
                                         print_msg=False)[0:2]
    except:
        inps.lalo = None

    # Flip up-down / left-right
    if inps.auto_flip:
        inps.flip_lr, inps.flip_ud = pp.auto_flip_direction(atr)

    # display unit ans wrap
    # if wrap_step == 2*np.pi (default value), set disp_unit_v = radian;
    # otherwise set disp_unit_v = disp_unit
    inps.disp_unit_v = inps.disp_unit
    if inps.wrap:
        inps.range2phase = -4. * np.pi / float(atr['WAVELENGTH'])
        if 'cm' == inps.disp_unit.split('/')[0]: inps.range2phase /= 100.
        elif 'mm' == inps.disp_unit.split('/')[0]: inps.range2phase /= 1000.
        elif 'm' == inps.disp_unit.split('/')[0]: inps.range2phase /= 1.
        else:
            raise ValueError('un-recognized display unit: {}'.format(
                inps.disp_unit))

        if (inps.wrap_range[1] - inps.wrap_range[0]) == 2 * np.pi:
            inps.disp_unit_v = 'radian'
        inps.vlim = inps.wrap_range
    inps.cbar_label = 'Displacement [{}]'.format(inps.disp_unit_v)

    return inps, atr
Exemple #2
0
def read_timeseries_data(inps):
    """Read data of time-series files
    Parameters: inps : Namespace of input arguments
    Returns:    ts_data : list of 3D np.array in size of (num_date, length, width)
                mask : 2D np.array in size of (length, width)
                inps : Namespace of input arguments
    """
    # read list of 3D time-series
    ts_data = []
    for fname in inps.timeseries_file:
        print('reading timeseries from file {} ...'.format(fname))
        data, atr = readfile.read(fname,
                                  datasetName=inps.date_list,
                                  box=inps.pix_box)
        try:
            ref_phase = data[:, inps.ref_yx[0] - inps.pix_box[1],
                             inps.ref_yx[1] - inps.pix_box[0]]
            data -= np.tile(ref_phase.reshape(-1, 1, 1),
                            (1, data.shape[-2], data.shape[-1]))
            print('reference to pixel {}'.format(inps.ref_yx))
        except:
            pass
        data -= np.tile(data[inps.ref_idx, :, :], (inps.num_date, 1, 1))

        # Display Unit
        (data, inps.disp_unit,
         inps.unit_fac) = pp.scale_data2disp_unit(data,
                                                  metadata=atr,
                                                  disp_unit=inps.disp_unit)
        ts_data.append(data)

    # Mask file: input mask file + non-zero ts pixels
    mask = np.ones(ts_data[0].shape[-2:], np.bool_)
    msk = pp.read_mask(inps.timeseries_file[0],
                       mask_file=inps.mask_file,
                       datasetName='displacement',
                       box=inps.pix_box)[0]
    mask[msk == 0.] = False
    del msk

    ts_stack = np.sum(ts_data[0], axis=0)
    mask[ts_stack == 0.] = False
    mask[np.isnan(ts_stack)] = False
    del ts_stack

    #print('masking data')
    #ts_mask = np.tile(mask, (inps.num_date, 1, 1))
    #for i in range(len(ts_data)):
    #    ts_data[i][ts_mask == 0] = np.nan
    #    try:
    #        ts_data[i][:, inps.ref_yx[0], inps.ref_yx[1]] = 0.   # keep value on reference pixel
    #    except:
    #        pass
    #del ts_mask

    # default vlim
    inps.dlim = [np.nanmin(ts_data[0]), np.nanmax(ts_data[0])]
    ts_data_mli = multilook_data(np.squeeze(ts_data[0]), 10, 10)
    if not inps.vlim:
        inps.vlim = [
            np.nanmin(ts_data_mli[inps.ex_flag != 0]),
            np.nanmax(ts_data_mli[inps.ex_flag != 0])
        ]
    print('data    range: {} {}'.format(inps.dlim, inps.disp_unit))
    print('display range: {} {}'.format(inps.vlim, inps.disp_unit))

    # default ylim
    num_file = len(inps.timeseries_file)
    if not inps.ylim:
        ts_data_mli = multilook_data(np.squeeze(ts_data[-1]), 10, 10)
        if inps.zero_first:
            ts_data_mli -= np.tile(ts_data_mli[inps.zero_idx, :, :],
                                   (inps.num_date, 1, 1))
        ymin, ymax = (np.nanmin(ts_data_mli[inps.ex_flag != 0]),
                      np.nanmax(ts_data_mli[inps.ex_flag != 0]))
        ybuffer = (ymax - ymin) * 0.05
        inps.ylim = [ymin - ybuffer, ymax + ybuffer]
        if inps.offset:
            inps.ylim[1] += inps.offset * (num_file - 1)
    del ts_data_mli

    return ts_data, mask, inps
Exemple #3
0
def plot_transect(ax, inps):
    print('plot profiles')

    # disp_unit/scale
    if not inps.disp_unit:
        inps.disp_unit = inps.atrList[0]['UNIT']
    inps.disp_unit, inps.disp_scale = pp.scale_data2disp_unit(
        data=None, metadata=inps.atrList[0], disp_unit=inps.disp_unit)[1:3]

    # Plot 2.1 - Input Files
    value_min = 0
    value_max = 0
    for i in range(len(inps.file)):
        # Profile Color based on Asc/Desc direction
        if inps.atrList[i]['ORBIT_DIRECTION'][0].upper() == 'A':
            p_color = 'crimson'
        else:
            p_color = 'royalblue'
        # Plot
        distance = inps.transectList[i][:, 0] / 1000.0  # km
        value = inps.transectList[
            i][:, 1] * inps.disp_scale - inps.disp_offset * i
        ax.plot(distance,
                value,
                '.',
                color=p_color,
                markersize=inps.marker_size)
        # Y Stat
        value_min = np.nanmin([value_min, np.nanmin(value)])
        value_max = np.nanmax([value_max, np.nanmax(value)])

    # Y axis
    if not inps.disp_min:
        inps.disp_min = np.floor(value_min - (value_max - value_min) * 1.2 /
                                 len(inps.file))
    if not inps.disp_max:
        inps.disp_max = np.ceil(value_max)
    ax.set_ylim(inps.disp_min, inps.disp_max)
    ax.set_ylabel('Mean LOS Velocity ({})'.format(inps.disp_unit),
                  fontsize=inps.font_size)
    # X axis
    ax.set_xlabel('Distance (km)', fontsize=inps.font_size)
    ax.tick_params(which='both', direction='out', labelsize=inps.font_size)

    # Plot 2.2 - DEM
    if inps.dem:
        ax2 = ax.twinx()
        distance = inps.demTransectList[0][:, 0] / 1000.0  # km
        value = inps.demTransectList[0][:, 1] / 1000.0  # km
        ax2.fill_between(distance, 0, value, facecolor='gray')

        # Y axis - display DEM in the bottom
        value_min = np.nanmin(value)
        value_max = np.nanmax(value)
        if not inps.dem_disp_min:
            inps.dem_disp_min = np.floor(value_min * 2.0) / 2.0
        if not inps.dem_disp_max:
            inps.dem_disp_max = np.ceil((value_max + (value_max - value_min) *
                                         (len(inps.file) + 0.0)) * 2.0) / 2.0
        ax2.set_ylim(inps.dem_disp_min, inps.dem_disp_max)
        # Show lower part of yaxis
        #dem_tick = ax2.yaxis.get_majorticklocs()
        #dem_tick = dem_tick[:len(dem_tick)/2]
        # ax2.set_yticks(dem_tick)
        ax2.set_ylabel('Elevation (km)', fontsize=inps.font_size)
        ax2.tick_params(which='both',
                        direction='out',
                        labelsize=inps.font_size)

    # X axis - Shared
    distanceMax = np.nanmax(inps.transectList[0][:, 0] / 1000.0)  # in km
    plt.xlim(0, distanceMax)
    plt.tight_layout()
    return