Ejemplo n.º 1
0
def _adjust_ts_axis(ax, inps):
    ax.tick_params(which='both', direction='in', labelsize=inps.font_size, bottom=True, top=True, left=True, right=True)
    ax = pp.auto_adjust_xaxis_date(ax, inps.yearList, fontsize=inps.font_size)[0]
    ax.set_xlabel('Time [years]', fontsize=inps.font_size)
    ax.set_ylabel('Displacement [{}]'.format(inps.disp_unit), fontsize=inps.font_size)
    ax.set_ylim(inps.ylim)
    return ax
Ejemplo n.º 2
0
def plot_bar4date_rms(inps):
    inps.figName = os.path.splitext(inps.rmsFile)[0] + '.pdf'
    if ut.update_file(inps.figName,
                      [inps.exDateFile, inps.refDateFile, inps.template_file],
                      check_readable=False):
        if inps.fig_size:
            fig = plt.figure(figsize=inps.fig_size)
        else:
            fig = plt.figure()
        ax = fig.add_subplot(111)
        font_size = 12

        dates, datevector = ptime.date_list2vector(inps.dateList)
        try:
            bar_width = ut.most_common(np.diff(dates).tolist()) * 3 / 4
        except:
            bar_width = np.min(np.diff(dates).tolist()) * 3 / 4
        x_list = [i - bar_width / 2 for i in dates]

        inps.rmsList = [i * 1000. for i in inps.rmsList]
        min_rms = inps.min_rms * 1000.
        # Plot all dates
        ax.bar(x_list, inps.rmsList, bar_width.days)

        # Plot reference date
        ax.bar(x_list[inps.refDateIndex],
               inps.rmsList[inps.refDateIndex],
               bar_width.days,
               label='Reference date')

        # Plot exclude dates
        if inps.exIdxList:
            ex_x_list = [x_list[i] for i in inps.exIdxList]
            inps.exRmsList = [inps.rmsList[i] for i in inps.exIdxList]
            ax.bar(ex_x_list,
                   inps.exRmsList,
                   bar_width.days,
                   color='darkgray',
                   label='Exclude date(s)')

        # Plot min_rms line
        ax, xmin, xmax = pp.auto_adjust_xaxis_date(
            ax, datevector, font_size, every_year=inps.tick_year_num)
        ax.plot(np.array([xmin, xmax]), np.array([min_rms, min_rms]), '--k')

        # axis format
        ax = pp.auto_adjust_yaxis(ax,
                                  inps.rmsList + [min_rms],
                                  font_size,
                                  ymin=0.0)
        ax.set_xlabel('Time [years]', fontsize=font_size)
        ax.set_ylabel('Root Mean Square [mm]', fontsize=font_size)
        ax.yaxis.set_ticks_position('both')
        ax.tick_params(labelsize=font_size)
        plt.legend(fontsize=font_size)

        # save figure
        fig.savefig(inps.figName, bbox_inches='tight', transparent=True)
        print('save figure to file: ' + inps.figName)
    return inps
Ejemplo n.º 3
0
def main(iargs=None):
    inps = cmd_line_parse(iargs)
    print('\n*************** Spatial Average ******************')
    mean_list, date_list = ut.spatial_average(inps.file,
                                              datasetName=inps.datasetName,
                                              maskFile=inps.mask_file,
                                              saveList=True)
    atr = readfile.read_attribute(inps.file)
    k = atr['FILE_TYPE']
    if inps.disp_fig and k == 'timeseries':
        dates, datevector = ptime.date_list2vector(date_list)
        # plot
        fig = plt.figure()
        ax = fig.add_subplot(111)
        ax.plot(dates, mean_list, '-o')#, lw=2, ms=16, alpha=0.7) #, mfc='crimson')
        ax.set_title('Spatial Average', fontsize=12)
        ax = pp.auto_adjust_xaxis_date(ax, datevector)[0]
        ax.set_xlabel('Time [years]', fontsize=12)
        ax.set_ylabel('Mean', fontsize=12)
        plt.show()
    return
Ejemplo n.º 4
0
    def update_timeseries(ax_ts, y, x):
        """Plot point time series displacement at pixel [y, x]"""
        d_ts = read_timeseries_yx(
            inps.timeseries_file, y, x, ref_yx=inps.ref_yx) * inps.unit_fac
        # for date in dateList:
        #    d = h5[k].get(date)[y,x]
        #    if inps.ref_yx:
        #        d -= h5[k].get(date)[inps.ref_yx[0], inps.ref_yx[1]]
        #    d_ts.append(d*inps.unit_fac)

        if inps.zero_first:
            d_ts -= d_ts[inps.zero_idx]

        ax_ts.cla()
        if inps.error_file:
            ax_ts = plot_timeseries_errorbar(ax_ts, d_ts, inps)
        else:
            ax_ts = plot_timeseries_scatter(ax_ts, d_ts, inps)
        if inps.ylim:
            ax_ts.set_ylim(inps.ylim)
        for tick in ax_ts.yaxis.get_major_ticks():
            tick.label.set_fontsize(inps.font_size)

        # Title
        title_ts = 'Y = %d, X = %d' % (y, x)
        try:
            lat = ullat + y * lat_step
            lon = ullon + x * lon_step
            title_ts += ', lat = %.4f, lon = %.4f' % (lat, lon)
        except:
            pass
        if inps.disp_title:
            ax_ts.set_title(title_ts)

        ax_ts = pp.auto_adjust_xaxis_date(ax_ts,
                                          inps.yearList,
                                          fontSize=inps.font_size)[0]
        ax_ts.set_xlabel('Time', fontsize=inps.font_size)
        ax_ts.set_ylabel('Displacement [%s]' % inps.disp_unit,
                         fontsize=inps.font_size)

        fig_ts.canvas.draw()

        # Print to terminal
        print('\n---------------------------------------')
        print(title_ts)
        print(d_ts)

        # Slope estimation
        if inps.ex_date_list:
            inps.yearList_kept = [
                inps.yearList[i] for i in range(date_num)
                if i not in inps.ex_idx_list
            ]
            d_ts_kept = [
                d_ts[i] for i in range(date_num) if i not in inps.ex_idx_list
            ]
            d_slope = stats.linregress(np.array(inps.yearList_kept),
                                       np.array(d_ts_kept))
        else:
            d_slope = stats.linregress(np.array(inps.yearList), np.array(d_ts))
        print('linear velocity: %.2f +/- %.2f [%s/yr]' %
              (d_slope[0], d_slope[4], inps.disp_unit))

        return d_ts
Ejemplo n.º 5
0
def plot_rms_bar(ax,
                 date_list,
                 rms,
                 cutoff=3.,
                 font_size=12,
                 tick_year_num=1,
                 legend_loc='best',
                 disp_legend=True,
                 disp_side_plot=True,
                 disp_thres_text=True,
                 ylabel=r'Residual Phase $\hat \phi_{resid}$ RMS [mm]'):
    """ Bar plot Phase Residual RMS
    Parameters: ax : Axes object
                date_list : list of string in YYYYMMDD format
                rms    : 1D np.array of float for RMS value in mm
                cutoff : cutoff value of MAD outlier detection
                tick_year_num : int, number of years per major tick
                legend_loc : 'upper right' or (0.5, 0.5)
    Returns:    ax : Axes object
    """
    dates, datevector = ptime.date_list2vector(date_list)
    try:
        bar_width = min(ut.most_common(np.diff(dates).tolist(), k=2)) * 3 / 4
    except:
        bar_width = np.min(np.diff(dates).tolist()) * 3 / 4
    rms = np.array(rms)

    # Plot all dates
    ax.bar(dates, rms, bar_width.days, color=pp.mplColors[0])

    # Plot reference date
    ref_idx = np.argmin(rms)
    ax.bar(dates[ref_idx],
           rms[ref_idx],
           bar_width.days,
           color=pp.mplColors[1],
           label='Reference date')

    # Plot exclude dates
    rms_threshold = ut.median_abs_deviation_threshold(rms,
                                                      center=0.,
                                                      cutoff=cutoff)
    ex_idx = rms > rms_threshold
    if not np.all(ex_idx == False):
        ax.bar(dates[ex_idx],
               rms[ex_idx],
               bar_width.days,
               color='darkgray',
               label='Exclude date')

    # Plot rms_threshold line
    (ax, xmin, xmax) = pp.auto_adjust_xaxis_date(ax,
                                                 datevector,
                                                 font_size,
                                                 every_year=tick_year_num)
    ax.plot(np.array([xmin, xmax]),
            np.array([rms_threshold, rms_threshold]),
            '--k',
            label='RMS threshold')

    # axis format
    ax = pp.auto_adjust_yaxis(ax,
                              np.append(rms, rms_threshold),
                              font_size,
                              ymin=0.0)
    ax.set_xlabel('Time [years]', fontsize=font_size)
    ax.set_ylabel(ylabel, fontsize=font_size)
    ax.tick_params(which='both',
                   direction='in',
                   labelsize=font_size,
                   bottom=True,
                   top=True,
                   left=True,
                   right=True)

    # 2nd axes for circles
    if disp_side_plot:
        divider = make_axes_locatable(ax)
        ax2 = divider.append_axes("right", "10%", pad="2%")
        ax2.plot(np.ones(rms.shape, np.float32) * 0.5,
                 rms,
                 'o',
                 mfc='none',
                 color=pp.mplColors[0])
        ax2.plot(np.ones(rms.shape, np.float32)[ref_idx] * 0.5,
                 rms[ref_idx],
                 'o',
                 mfc='none',
                 color=pp.mplColors[1])
        if not np.all(ex_idx == False):
            ax2.plot(np.ones(rms.shape, np.float32)[ex_idx] * 0.5,
                     rms[ex_idx],
                     'o',
                     mfc='none',
                     color='darkgray')
        ax2.plot(np.array([0, 1]), np.array([rms_threshold, rms_threshold]),
                 '--k')

        ax2.set_ylim(ax.get_ylim())
        ax2.set_xlim([0, 1])
        ax2.tick_params(which='both',
                        direction='in',
                        labelsize=font_size,
                        bottom=True,
                        top=True,
                        left=True,
                        right=True)
        ax2.get_xaxis().set_ticks([])
        ax2.get_yaxis().set_ticklabels([])

    if disp_legend:
        ax.legend(loc=legend_loc, frameon=False, fontsize=font_size)

    # rms_threshold text
    if disp_thres_text:
        ymin, ymax = ax.get_ylim()
        yoff = (ymax - ymin) * 0.1
        if (rms_threshold - ymin) > 0.5 * (ymax - ymin):
            yoff *= -1.
        ax.annotate('Median Abs Dev * {}'.format(cutoff),
                    xy=(xmin + (xmax - xmin) * 0.05, rms_threshold + yoff),
                    color='k',
                    xycoords='data',
                    fontsize=font_size)
    return ax
Ejemplo n.º 6
0
def update_timeseries(y, x, plot_number, data_only=False):
    '''Plot point time series displacement at pixel [y, x]
        Inputs:
            y           : int, y coordinate to update
            x           : int, x coordinate to update
            plot_number : int, plot number (1/2) to update
            data_only   : bool, compute and return data only, or set remainder of plot variables
        Outputs:
            d_ts        : [float], timeseries data at x, y point
    '''
    global fig_ts, ax_ts, second_plot_axis, inps, dateList, h5, k, inps, inps.tims, fig_v, inps.num_date, d_ts

    set_scatter_coords(plot_number, x, y)

    if plot_number == 1:
        axis = ax_ts
    else:
        axis = second_plot_axis

    d_ts = []
    for i, date in enumerate(dateList):
        d = h5['timeseries'][i][y, x]
        if inps.ref_yx:
            d -= h5['timeseries'][i][inps.ref_yx[0], inps.ref_yx[1]]
        d_ts.append(d * inps.unit_fac)

    if inps.zero_first:
        d_ts -= d_ts[inps.zero_idx]

    # Returns computed data without setting any plot or figure parameters
    if data_only:
        return d_ts

    axis.cla()
    if inps.error_file:
        axis = plot_timeseries_errorbar(ax_ts, d_ts, inps)
    else:
        axis, scatter = plot_timeseries_scatter(axis, d_ts, inps, plot_number)
        scatter.set_label('2')

    if inps.ylim:
        axis.set_ylim(inps.ylim)
    for tick in axis.yaxis.get_major_ticks():
        tick.label.set_fontsize(inps.font_size)

    # Title
    title_ts = set_axis_title(x, y)
    if inps.disp_title:
        axis.set_title(title_ts)

    axis = pp.auto_adjust_xaxis_date(axis, inps.tims, fontSize=inps.font_size)[0]
    axis.set_xlabel('Time', fontsize=inps.font_size)
    axis.set_ylabel('Displacement [%s]' % inps.disp_unit, fontsize=inps.font_size)

    fig_v.canvas.draw()

    # Print to terminal
    print('\n---------------------------------------')
    print(title_ts)
    print(d_ts)

    # Slope estimation
    estimate_slope()

    return d_ts