def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--first_inputs', nargs='+',
                        help="""List of files containing variable to plot""")
    parser.add_argument('--second_inputs', nargs='+',
                        help="""List of files containing variable to plot""")
    parser.add_argument('--variable', default='temp',
                        help='The variable to plot.')
    parser.add_argument('--mask', default=None,
                        help="""
                        A mask file specifing the grid points to use in
                        the timeseries.""")
    parser.add_argument('--mask_var', default=None,
                        help='The variable name within the mask file to use.')
    parser.add_argument('--region', default=None, action='store', type=region,
                        help="""A region within to use instead of the mask.""")
    parser.add_argument('--plot_mask', default=None, help='Plot the mask used.')
    parser.add_argument('--output_file', default='sst_timeseries.png',
                        help='Name of plot to output.')
    args = parser.parse_args()

    assert not (args.mask is None) or (args.mask_var is None)
    assert not (args.mask is None) or not (args.region is None)

    if args.region:
        slat = args.region[0]
        nlat = args.region[1]
        wlon = args.region[2]
        elon = args.region[3]
        blayer = args.region[4]
        tlayer = args.region[5]
        mask = make_mask_from_region(slat, nlat, wlon, elon, blayer, tlayer,
                                        args.first_inputs[0], args.variable)
    else:
        with nc.Dataset(args.mask) as m:
            mask = m.variables[args.mask_var][0, :]

    if args.plot_mask:
        plt.imshow(np.flipud(mask))
        plt.savefig(args.plot_mask)
        plt.close()

    pool = mp.Pool()
    data_to_plot = []
    for name, data_files in zip(['A', 'B'], [args.first_inputs, args.second_inputs]):

        inputs = zip(data_files, [args.variable]*len(data_files),
                        [mask]*len(data_files),
                        [args.mask_var]*len(data_files))
        results = pool.map(make_timeseries, inputs)
        #results = map(make_timeseries, inputs)

        ts = pd.Series()
        for t in results:
            ts = ts.append(t)

        ts = ts.sort_index()
        data_to_plot.append((ts, name))

    fig, axarr = plt.subplots(2, sharex=True)

    # Extend colours list when necessary.
    colours = ['red', 'blue', 'green', 'black']
    assert(len(colours) >= 2)

    min_len = min(len(data_to_plot[0][0]), len(data_to_plot[1][0]))

    for colour, (ts, name) in zip(colours, data_to_plot):
        dates = [datetime.date(i.year, i.month, i.day) for i in ts.index]
        axarr[0].plot(dates[:min_len], ts.values[:min_len], colour,
                        label=name, lw=1.0)
        title = 'Spatial average {} in region'.format(args.variable)
        axarr[0].set_title(title)
        if args.variable == 'temp':
            axarr[0].set_ylabel('Temperature C')
        else:
            axarr[1].set_ylabel('Wind Stress N/m^2')
        axarr[0].legend()

    diff = data_to_plot[1][0] - data_to_plot[0][0]
    diff_smoothed = lowess_smooth(diff, smooth_years=8.0)

    # In a separate pane plot the difference between datasets
    dates = [datetime.date(i.year, i.month, i.day) for i in diff.index]
    axarr[1].plot(dates[:min_len], diff.values[:min_len], 'blue', lw=1.0)
    axarr[1].plot(dates[:min_len], diff_smoothed.values[:min_len], 'blue', lw=3.0)
    axarr[1].set_title('B - A')
    if args.variable == 'temp':
        axarr[1].set_ylabel('Temperature C')
    else:
        axarr[1].set_ylabel('Wind Stress N/m^2')
    axarr[1].set_xlabel('Time (years)')

    fig.set_size_inches(12, 6)
    plt.tight_layout()
    plt.savefig(args.output_file)
    plt.close()
Exemplo n.º 2
0
def plot_timeseries(data_file, output_file, offset=0):

    # Read data and plot
    with h5py.File(data_file) as f:
        time = f['/time'][:]
        amoc_index_sst = f['/amoc_index_sst'][:]
        nh_sst_average = f['/nh_sst_average'][:]
        amoc_psi_max = f['/amoc_psi_max'][:]
        amoc_psi_max_at_26n = f['/amoc_psi_max_at_26n'][:]

    start_date = datetime.datetime(year=1, month=1, day=1)
    time_dim = [start_date + datetime.timedelta(days=int(t)) for t in time]
    amoc_index = amoc_index_sst - nh_sst_average

    if offset != 0:
        time_dim = time_dim[:-offset]
        amoc_index = amoc_index[:-offset]
        amoc_psi_max = amoc_psi_max[offset:]

    # Do some smoothing
    amoc_index_sm = lowess_smooth(amoc_index)
    amoc_psi_max_anomaly = amoc_psi_max - np.mean(amoc_psi_max)
    amoc_psi_max_anomaly_sm = lowess_smooth(amoc_psi_max_anomaly)
    amoc_psi_max_sm = lowess_smooth(amoc_psi_max)

    # Time series of the maximum overturning stream function anomaly
    fig, axarr = plt.subplots(2, sharex=True)
    axarr[0].plot(time_dim, amoc_psi_max_anomaly, 'red', lw=1.0, alpha=0.5)
    axarr[0].plot(time_dim, amoc_psi_max_anomaly_sm, 'darkred', lw=3.0)
    axarr[0].set_ylabel('AMOC Maximum Anomaly (Sv)', color='darkred')
    axarr[0].set_title('Connection between Max Overturning Streamfunction and AMOC Index')

    # Time series of the AMOC index
    ax2 = axarr[0].twinx()
    ax2.plot(time_dim, amoc_index, 'blue', lw=1.0, alpha=0.5)
    ax2.plot(time_dim, amoc_index_sm, 'darkblue', lw=3.0)
    ax2.set_ylabel('AMOC Index (K)', color='darkblue')

    p_corr_sm = pearsonr(amoc_psi_max_anomaly_sm, amoc_index_sm)
    print('p_corr_sm: {}'.format(p_corr_sm))
    p_corr = pearsonr(amoc_psi_max_anomaly, amoc_index)
    print('p_corr: {}'.format(p_corr))
    text = 'Pearson correlation (smoothed): {0:.2f} ({1:.2f})'. \
                format(p_corr[0], p_corr_sm[0])
    print(text)

    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    axarr[0].text(0.05,  0.95, text, transform=axarr[0].transAxes,
                    verticalalignment='top', bbox=props)

    # Time series of AMOC mean
    time_dim = [start_date + datetime.timedelta(days=int(t)) for t in time]
    amoc_psi_max_at_26n_sm = lowess_smooth(amoc_psi_max_at_26n)
    axarr[1].plot(time_dim, amoc_psi_max_at_26n, 'green', lw=1.0)
    axarr[1].plot(time_dim, amoc_psi_max_at_26n_sm, 'darkgreen', lw=3.0)
    axarr[1].set_ylabel('Sv', color='darkgreen')
    axarr[1].set_xlabel('Year')
    axarr[1].set_title('AMOC monthly maximum at 26.5N')

    fig.set_size_inches(14,10)
    plt.tight_layout()
    plt.savefig(output_file)
    plt.close()