Esempio n. 1
0
def plot_phase_mag(inputs, outputs, scale, mode, row):
    raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                 f'hydrobasins_raster_{scale}')
    phase_filename, mag_filename = outputs
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig3_cb.pkl')
    phase_mag_cubes = iris.load(str(inputs['phase_mag_cubes']))
    phase_map = phase_mag_cubes.extract_strict('phase_map')
    mag_map = phase_mag_cubes.extract_strict('magnitude_map')

    extent = get_extent_from_cube(phase_map)

    plt.figure(f'{row.dataset}_{row.task.outputs[0]}_phase', figsize=(10, 8))
    plt.clf()
    plt.title(f'{row.dataset}: {row.analysis_order}_{row.method} phase')
    plt.imshow(np.ma.masked_array(phase_map.data, raster_cube.data == 0),
               cmap=cmap,
               norm=norm,
               origin='lower',
               extent=extent,
               vmin=0,
               vmax=24)
    plt.colorbar(orientation='horizontal')
    plt.tight_layout()
    savefig(phase_filename)
    plt.figure(f'{row.task.outputs[0]}_magnitude', figsize=(10, 8))
    plt.clf()
    plt.title(f'{row.dataset}: {row.analysis_order}_{row.method} magnitude')
    plt.imshow(np.ma.masked_array(mag_map.data, raster_cube.data == 0),
               origin='lower',
               extent=extent)
    plt.colorbar(orientation='horizontal')
    plt.tight_layout()
    savefig(mag_filename)
Esempio n. 2
0
    def add_titles_colourbars(self):
        for j, mode in enumerate(self.MODES):
            title_ax = self.fig_axes[0, j]
            title_ax.set_title(self.TITLE_MODE_MAP[mode])
            im = self.image_grid[-1][j]

        cax = self.cb_axes[0]
        # cax.axis('off')
        im = self.image_grid[-1][1]

        cmap, norm, bounds, cbar_kwargs = load_cmap_data('cmap_data/li2018_fig3_cb.pkl')
        if True:
            v = np.linspace(0, 1, 24)
            d = cmap(v)[None, :, :4] * np.ones((3, 24, 4))
            d[1, :, 3] = 0.66
            d[0, :, 3] = 0.33
            cax.imshow(d, origin='lower', extent=(0, 24, 0, 2), aspect='auto')
            cax.set_yticks([0.3, 1.7])
            cax.set_yticklabels(['weak', 'strong'])
            cax.set_xticks(np.linspace(0, 24, 9))
            cax.set_xlabel('phase and strength of diurnal cycle')
        else:
            plt.colorbar(im, ax=cax, label=f'diurnal cycle (hr)',
                         orientation='horizontal', norm=norm, **cbar_kwargs,
                         fraction=0.6, aspect=35)
Esempio n. 3
0
def plot_aphrodite_seasonal_analysis(inputs, outputs, use_li2018_cmap=True):
    nc_key = ' daily precipitation analysis interpolated onto 0.25deg grids'
    ppt = iris.load_cube(str(inputs[nc_key]), nc_key)

    epoch2009 = dt.datetime(2009, 1, 1)
    time_index = np.array([
        epoch2009 + dt.timedelta(minutes=m) for m in ppt.coord('time').points
    ])
    jja = ((time_index >= dt.datetime(2009, 6, 1)) &
           (time_index < dt.datetime(2009, 9, 1)))
    ppt_jja = ppt[jja]
    ppt_jja_mean = ppt_jja.data.mean(axis=0)

    fig = plt.figure('aphrodite2009 JJA')
    plt.clf()

    lon_min, lon_max = ppt.coord('longitude').points[[0, -1]]
    lat_min, lat_max = ppt.coord('latitude').points[[0, -1]]

    extent = (lon_min, lon_max, lat_min, lat_max)

    if use_li2018_cmap:
        cmap, norm, bounds, cbar_kwargs = load_cmap_data(
            'cmap_data/li2018_fig2_cb1.pkl')

        im = plt.imshow(ppt_jja_mean,
                        origin='lower',
                        extent=extent,
                        cmap=cmap,
                        norm=norm)
        plt.colorbar(im,
                     label=f'amount precip. (mm day$^{{-1}}$)',
                     orientation='horizontal',
                     **cbar_kwargs,
                     spacing='uniform')
    else:
        im = plt.imshow(ppt_jja_mean,
                        origin='lower',
                        extent=extent,
                        norm=LogNorm())
        plt.colorbar(im,
                     label=f'amount precip. (mm day$^{{-1}}$)',
                     orientation='horizontal')
    fig.set_size_inches(12, 8)
    ax = plt.gca()
    ax.set_xlim((57, 150))
    ax.set_ylim((1, 56))
    plt.savefig(outputs['asia'])

    ax.set_xlim((97.5, 125))
    ax.set_ylim((18, 41))
    ax.set_xticks([100, 110, 120])
    ax.set_yticks([20, 30, 40])
    fig.set_size_inches(6, 8)

    plt.savefig(outputs['china'])
Esempio n. 4
0
def plot_gridpoint_mean_precip_asia(inputs, outputs):

    # TODO: Saturated colour scale.
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')
    ppt_cubes = []
    for dataset, path in inputs.items():
        ppt_cube = iris.load_cube(str(path), 'precip_flux_mean')
        assert ppt_cube.units == 'mm hr-1'
        ppt_cubes.append(ppt_cube)

    extent = get_extent_from_cube(ppt_cube)
    fig, axes = plt.subplots(2,
                             2,
                             figsize=(10, 7),
                             subplot_kw=dict(projection=ccrs.PlateCarree()))
    for ax, cube, dataset in zip(axes.flatten(), ppt_cubes, inputs.keys()):
        ax.set_title(STANDARD_NAMES[dataset])
        # Convert from mm hr-1 to mm day-1
        im = ax.imshow(cube.data * 24, extent=extent, norm=norm, cmap=cmap)
        configure_ax_asia(ax, tight_layout=False)
        xticks = range(60, 160, 40)
        ax.set_xticks(xticks)
        ax.set_xticklabels([f'${t}\\degree$ E' for t in xticks])

    for ax in axes[:, 1]:
        ax.get_yaxis().set_ticklabels([])
    for ax in axes[0, :].flatten():
        ax.get_xaxis().set_ticklabels([])

    for i, ax in enumerate(axes.flatten()):
        c = string.ascii_lowercase[i]
        ax.text(0.01, 1.06, f'({c})', size=12, transform=ax.transAxes)

    cax = fig.add_axes([0.12, 0.10, 0.74, 0.02])
    cbar_kwargs['extend'] = 'max'
    cbar_kwargs['ticks'] = [0] + cbar_kwargs['ticks']
    plt.colorbar(im,
                 cax=cax,
                 orientation='horizontal',
                 label='precipitation (mm day$^{-1}$)',
                 **cbar_kwargs)
    plt.subplots_adjust(left=0.06,
                        right=0.95,
                        top=0.95,
                        bottom=0.2,
                        wspace=0.08)
    # plt.subplots_adjust(left=0.06, right=0.94, top=0.98, bottom=0.17, wspace=0.1)
    plt.savefig(outputs[0])
def plot_mean_precip(inputs, outputs, dataset, hb_name):
    weighted_basin_mean_precip_filename = inputs['weighted']
    df_mean_precip = pd.read_hdf(weighted_basin_mean_precip_filename)
    mean_max_min_precip = pickle.loads(
        inputs['mean_precip_max_min'].read_bytes())
    max_mean_precip = mean_max_min_precip['max_mean_precip']
    # min_mean_precip = mean_max_min_precip['min_mean_precip']

    raster_hb_name = hb_name
    raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                 f'hydrobasins_raster_{raster_hb_name}')
    raster = raster_cube.data
    logger.debug(f'Plot maps - {hb_name}: {dataset}')

    mean_precip_map = np.zeros_like(raster, dtype=float)
    for i in range(1, raster.max() + 1):
        mean_precip_map[raster == i] = df_mean_precip.values[i - 1]

    extent = get_extent_from_cube(raster_cube)
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')

    plt.figure(figsize=(10, 8))
    ax = plt.subplot(projection=ccrs.PlateCarree())
    plt.title(f'{dataset} mean_precip')
    grey_fill = np.zeros(
        (mean_precip_map.shape[0], mean_precip_map.shape[1], 3), dtype=int)
    grey_fill[raster_cube.data == 0] = (200, 200, 200)
    ax.imshow(grey_fill, extent=extent)

    masked_mean_precip_map = np.ma.masked_array(mean_precip_map,
                                                raster_cube.data == 0)
    im = ax.imshow(
        masked_mean_precip_map * 24,
        cmap=cmap,
        norm=norm,
        # vmin=1e-3, vmax=max_mean_precip,
        origin='lower',
        extent=extent)
    plt.colorbar(im,
                 label=f'precip. (mm day$^{{-1}}$)',
                 **cbar_kwargs,
                 spacing='uniform',
                 orientation='horizontal')
    configure_ax_asia(ax, extent)

    mean_precip_filename = outputs[0]
    plt.savefig(mean_precip_filename)
    plt.close()
Esempio n. 6
0
def plot_precip_station_jja_scatter(df_precip_station_jja):
    plt.figure('precip_gauge_china_2419_scatter')
    plt.clf()
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')
    sorted_df_precip_station_jja = df_precip_station_jja.sort_values(
        by='precip')
    plt.scatter(sorted_df_precip_station_jja.lon,
                sorted_df_precip_station_jja.lat,
                c=sorted_df_precip_station_jja.precip,
                s=300,
                cmap=cmap,
                norm=norm)
    plt.xlim((97.5, 125))
    plt.ylim((18, 41))
Esempio n. 7
0
    def plot_ax(self, ax, cube, runid, mode):
        lon_min, lon_max = cube.coord('longitude').points[[0, -1]]
        lat_min, lat_max = cube.coord('latitude').points[[0, -1]]

        extent = (lon_min, lon_max, lat_min, lat_max)

        if self.method == 'peak':
            season_phase_LST, amp = calc_diurnal_cycle_phase_amp_peak(cube)
        elif self.method == 'harmonic':
            season_phase_LST, amp = calc_diurnal_cycle_phase_amp_harmonic(cube)
        cmap, norm, bounds, cbar_kwargs = load_cmap_data('cmap_data/li2018_fig3_cb.pkl')
        if runid == 'cmorph':
            Lat, Lon = np.meshgrid(cube.coord('latitude').points, cube.coord('longitude').points, indexing='ij')
            season_phase_LST = np.ma.masked_array(season_phase_LST, Lat > 59)
            amp = np.ma.masked_array(amp, Lat > 59)

        if True:
            thresh_boundaries = [100 * 1 / 3, 100 * 2 / 3]
            if runid == 'cmorph':
                med_thresh, strong_thresh = np.percentile(amp.compressed(),
                                                          thresh_boundaries)
            else:
                med_thresh, strong_thresh = np.percentile(amp,
                                                          thresh_boundaries)
            peak_strong = np.ma.masked_array(season_phase_LST,
                                             amp < strong_thresh)
            peak_med = np.ma.masked_array(season_phase_LST,
                                          ((amp >= strong_thresh) |
                                           (amp < med_thresh)))
            peak_weak = np.ma.masked_array(season_phase_LST,
                                           amp >= med_thresh)
            im0 = ax.imshow(peak_strong, origin='lower', extent=extent,
                            vmin=0, vmax=24, cmap=cmap, norm=norm)
            ax.imshow(peak_med, origin='lower', extent=extent, alpha=0.66,
                      vmin=0, vmax=24, cmap=cmap, norm=norm)
            ax.imshow(peak_weak, origin='lower', extent=extent, alpha=0.33,
                      vmin=0, vmax=24, cmap=cmap, norm=norm)

            return im0
        else:
            im = ax.imshow(season_phase_LST, origin='lower', extent=extent, cmap=cmap, norm=norm,
                           vmin=0, vmax=24)
            return im
Esempio n. 8
0
def plot_precip_station_jja_cressman(ax, hydrosheds_dir, df_precip_station_jja,
                                     stretch_lat, search_rad, grid_spacing,
                                     **kwargs):
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')

    if stretch_lat:
        lat = df_precip_station_jja.lat * 1.5
    else:
        lat = df_precip_station_jja.lat

    gx, gy, griddata = interpolate_to_grid(df_precip_station_jja.lon,
                                           lat,
                                           df_precip_station_jja.precip,
                                           interp_type='cressman',
                                           minimum_neighbors=1,
                                           hres=grid_spacing,
                                           search_radius=search_rad)
    griddata = np.ma.masked_where(np.isnan(griddata), griddata)
    lon_min = df_precip_station_jja.lon.min()
    lon_max = df_precip_station_jja.lon.max()
    lat_min = df_precip_station_jja.lat.min()
    lat_max = df_precip_station_jja.lat.max()
    extent = (lon_min, lon_max, lat_min, lat_max)

    # Use to mask out ocean.
    hb = load_hydrobasins_geodataframe(hydrosheds_dir, 'as', [1])
    raster = build_raster_from_lon_lat(hb.geometry, lon_min, lon_max, lat_min,
                                       lat_max, griddata.shape[1],
                                       griddata.shape[0])

    griddata = np.ma.masked_array(griddata, raster == 0)
    im = ax.imshow(griddata,
                   origin='lower',
                   cmap=cmap,
                   norm=norm,
                   extent=extent,
                   interpolation='bilinear')
    # im = ax.imshow(img, origin='lower', cmap=cmap, norm=norm, extent=extent)
    # plt.colorbar(im, label='precip. (mm day$^{-1}$)',
    # orientation='horizontal', norm=norm, spacing='uniform', **cbar_kwargs)
    return im
Esempio n. 9
0
def plot_cmorph_min_max(inputs, outputs):
    min_max_text = inputs['min_max'].read_text()
    min_data = min_max_text.split('\n')[0].split('=')
    max_data = min_max_text.split('\n')[1].split('=')
    assert min_data[0] == 'min' and max_data[0] == 'max'
    min_start_year = int(min_data[1])
    max_start_year = int(max_data[1])
    print(min_start_year)
    print(max_start_year)

    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')

    fig, axes = plt.subplots(1, 3)
    keys = ['full', min_start_year, max_start_year]
    title_min_max = {min_start_year: '(min)', max_start_year: '(max)'}

    ppt_cubes = []
    for ax, key in zip(axes, keys):
        path = inputs[key]
        ppt_cube = iris.load_cube(str(path), 'precip_flux_mean')
        assert ppt_cube.units == 'mm hr-1'
        ppt_cubes.append(ppt_cube)

    extent = get_extent_from_cube(ppt_cube)
    fig, axes = plt.subplots(1,
                             3,
                             figsize=(10, 3.5),
                             subplot_kw=dict(projection=ccrs.PlateCarree()))
    for ax, cube, key in zip(axes.flatten(), ppt_cubes, keys):
        if key == 'full':
            name = '1998-2018'
        else:
            name = f'{key}-{key + 3}'
        ax.set_title(name)
        # Convert from mm hr-1 to mm day-1
        im = ax.imshow(cube.data * 24, extent=extent, norm=norm, cmap=cmap)
        configure_ax_asia(ax, tight_layout=False)
        xticks = range(60, 160, 40)
        ax.set_xticks(xticks)
        ax.set_xticklabels([f'${t}\\degree$ E' for t in xticks])

    for ax in axes[1:]:
        ax.get_yaxis().set_ticklabels([])

    for i, ax in enumerate(axes.flatten()):
        c = string.ascii_lowercase[i]
        ax.text(0.01, 1.06, f'({c})', size=12, transform=ax.transAxes)

    cax = fig.add_axes([0.12, 0.20, 0.74, 0.02])
    plt.colorbar(im,
                 cax=cax,
                 orientation='horizontal',
                 label='precipitation (mm day$^{-1}$)',
                 **cbar_kwargs)
    plt.subplots_adjust(left=0.06,
                        right=0.94,
                        top=0.99,
                        bottom=0.2,
                        wspace=0.1)
    plt.savefig(outputs[0])
Esempio n. 10
0
def plot_phase_mag(inputs, outputs, dataset, hb_name, mode):
    weighted_basin_phase_mag_filename = inputs['weighted']
    df_phase_mag = pd.read_hdf(weighted_basin_phase_mag_filename)

    raster_hb_name = hb_name
    raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                 f'hydrobasins_raster_{raster_hb_name}')
    raster = raster_cube.data
    phase_filename, alpha_phase_filename, mag_filename = outputs
    print(f'Plot maps - {hb_name}_{mode}: {dataset}')
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig3_cb.pkl')

    phase_map, mag_map = gen_map_from_basin_values(df_phase_mag, raster)
    phase_map = iris.cube.Cube(phase_map,
                               long_name='phase_map',
                               units='hr',
                               dim_coords_and_dims=[
                                   (raster_cube.coord('latitude'), 0),
                                   (raster_cube.coord('longitude'), 1)
                               ])
    mag_map = iris.cube.Cube(mag_map,
                             long_name='magnitude_map',
                             units='-',
                             dim_coords_and_dims=[
                                 (raster_cube.coord('latitude'), 0),
                                 (raster_cube.coord('longitude'), 1)
                             ])

    extent = get_extent_from_cube(phase_map)

    plt.figure(figsize=(10, 8))
    ax = plt.subplot(projection=ccrs.PlateCarree())
    ax.set_title(f'{dataset} {mode} phase')
    masked_phase_map = np.ma.masked_array(phase_map.data,
                                          raster_cube.data == 0)
    masked_mag_map = np.ma.masked_array(mag_map.data, raster_cube.data == 0)

    im = ax.imshow(masked_phase_map,
                   cmap=cmap,
                   norm=norm,
                   origin='lower',
                   extent=extent,
                   vmin=0,
                   vmax=24)
    plt.colorbar(im, orientation='horizontal')
    configure_ax_asia(ax, extent)
    # plt.tight_layout()
    plt.savefig(phase_filename)
    plt.close()

    fig = plt.figure(figsize=(10, 8))
    ax = plt.subplot(projection=ccrs.PlateCarree())
    ax.set_title(f'{dataset} {mode} phase (alpha)')

    _plot_phase_alpha(ax, masked_phase_map, masked_mag_map, cmap, norm, extent)
    configure_ax_asia(ax, extent)

    cax, _ = cbar.make_axes_gridspec(ax, orientation='horizontal')
    v = np.linspace(0, 1, 24)
    d = cmap(v)[None, :, :4] * np.ones((3, 24, 4))
    d[1, :, 3] = 0.66
    d[0, :, 3] = 0.33
    cax.imshow(d, origin='lower', extent=(0, 24, 0, 2), aspect='auto')
    cax.set_yticks([])
    cax.set_xticks(np.linspace(0, 24, 9))

    # plt.tight_layout()
    plt.savefig(alpha_phase_filename)
    plt.close()

    plt.figure(figsize=(10, 8))
    ax = plt.subplot(projection=ccrs.PlateCarree())
    ax.set_title(f'{dataset} {mode} strength')
    im = ax.imshow(masked_mag_map,
                   origin='lower',
                   extent=extent,
                   vmin=1e-2,
                   norm=LogNorm())
    plt.colorbar(im, orientation='horizontal')
    configure_ax_asia(ax, extent)
    # plt.tight_layout()
    plt.savefig(mag_filename)
    plt.close()
Esempio n. 11
0
def plot_phase_alpha_combined(inputs, outputs, datasets, hb_names, mode):
    imshow_data = {}
    for hb_name in hb_names:
        raster_hb_name = hb_name
        raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                     f'hydrobasins_raster_{raster_hb_name}')
        raster = raster_cube.data
        for dataset in datasets:
            weighted_basin_phase_mag_filename = inputs[
                f'weighted_{hb_name}_{dataset}']
            df_phase_mag = pd.read_hdf(weighted_basin_phase_mag_filename)

            phase_map, mag_map = gen_map_from_basin_values(
                df_phase_mag, raster)
            phase_map = iris.cube.Cube(phase_map,
                                       long_name='phase_map',
                                       units='hr',
                                       dim_coords_and_dims=[
                                           (raster_cube.coord('latitude'), 0),
                                           (raster_cube.coord('longitude'), 1)
                                       ])
            mag_map = iris.cube.Cube(mag_map,
                                     long_name='magnitude_map',
                                     units='-',
                                     dim_coords_and_dims=[
                                         (raster_cube.coord('latitude'), 0),
                                         (raster_cube.coord('longitude'), 1)
                                     ])
            masked_phase_map = np.ma.masked_array(phase_map.data,
                                                  raster_cube.data == 0)
            masked_mag_map = np.ma.masked_array(mag_map.data,
                                                raster_cube.data == 0)
            imshow_data[(hb_name, dataset)] = (masked_phase_map,
                                               masked_mag_map)

    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig3_cb.pkl')
    # Fills masked values.
    cmap.set_bad(color='k', alpha=0.1)
    figsize = (10, 7) if len(datasets) == 3 else (10, 9)
    fig, axes = plt.subplots(len(datasets),
                             3,
                             figsize=figsize,
                             subplot_kw={'projection': ccrs.PlateCarree()})
    for axrow, dataset in zip(axes, datasets):
        for ax, hb_name in zip(axrow, hb_names):
            masked_phase_map, masked_mag_map = imshow_data[(hb_name, dataset)]
            extent = get_extent_from_cube(phase_map)
            _plot_phase_alpha(ax, masked_phase_map, masked_mag_map, cmap, norm,
                              extent)

    for ax, dataset in zip(axes[:, 0], datasets):
        ax.set_ylabel(STANDARD_NAMES[dataset])
    _configure_hb_name_dataset_map_grid(axes, hb_names, datasets)

    cax = fig.add_axes([0.10, 0.07, 0.8, 0.05])
    v = np.linspace(0, 1, 24)
    d = cmap(v)[None, :, :4] * np.ones((3, 24, 4))
    d[1, :, 3] = 0.66
    d[0, :, 3] = 0.33
    cax.imshow(d, origin='lower', extent=(0, 24, 0, 2), aspect='auto')
    cax.set_yticks([0.3, 1.7])
    cax.set_yticklabels(['weak', 'strong'])
    cax.set_xticks(np.linspace(0, 24, 9))
    cax.set_xlabel('phase and strength of diurnal cycle')

    plt.subplots_adjust(left=0.06,
                        right=0.94,
                        top=0.96,
                        bottom=0.16,
                        wspace=0.1,
                        hspace=0.15)

    plt.savefig(outputs[0])
Esempio n. 12
0
def plot_mean_precip_asia_combined(inputs, outputs, datasets, hb_names):
    imshow_data = {}
    for hb_name in hb_names:
        raster_hb_name = hb_name
        raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                     f'hydrobasins_raster_{raster_hb_name}')
        raster = raster_cube.data
        extent = get_extent_from_cube(raster_cube)

        cmorph_weighted_basin_mean_precip_filename = inputs[
            f'weighted_{hb_name}_cmorph']
        df_cmorph_mean_precip = pd.read_hdf(
            cmorph_weighted_basin_mean_precip_filename)

        cmorph_mean_precip_map = np.zeros_like(raster, dtype=float)
        for i in range(1, raster.max() + 1):
            cmorph_mean_precip_map[raster == i] = df_cmorph_mean_precip.values[
                i - 1]

        masked_cmorph_mean_precip_map = np.ma.masked_array(
            cmorph_mean_precip_map, raster_cube.data == 0)
        imshow_data[('cmorph', hb_name)] = masked_cmorph_mean_precip_map * 24

        for dataset in datasets[1:]:
            weighted_basin_mean_precip_filename = inputs[
                f'weighted_{hb_name}_{dataset}']
            df_mean_precip = pd.read_hdf(weighted_basin_mean_precip_filename)

            mean_precip_map = np.zeros_like(raster, dtype=float)
            for i in range(1, raster.max() + 1):
                mean_precip_map[raster == i] = df_mean_precip.values[i - 1]

            masked_mean_precip_map = np.ma.masked_array(
                mean_precip_map - cmorph_mean_precip_map,
                raster_cube.data == 0)
            imshow_data[(dataset, hb_name)] = masked_mean_precip_map * 24

    figsize = (10, 5.5) if len(datasets) == 3 else (10, 8)
    fig, axes = plt.subplots(len(datasets),
                             3,
                             figsize=figsize,
                             subplot_kw={'projection': ccrs.PlateCarree()})
    cmap, norm, bounds, cbar_kwargs = load_cmap_data(
        'cmap_data/li2018_fig2_cb1.pkl')

    # orig. -- continuous scale.
    # diff_cmap = mpl.cm.get_cmap('bwr')
    # diff_norm = MidPointNorm(0, -24, 72)
    bwr = mpl.cm.get_cmap('bwr')
    cmap_scale = [0., .5 / 3, 1 / 3, .5, .6, .7, .8,
                  1.]  # 8 -- colours from bwr to use.
    diff_bounds = [-27, -9, -3, -1, 1, 3, 9, 27, 81]  # 9 -- bounds to use.

    # https://matplotlib.org/3.1.0/tutorials/colors/colormap-manipulation.html
    top = mpl.cm.get_cmap('Oranges_r', 128)
    bottom = mpl.cm.get_cmap('Blues', 128)

    newcolors = np.vstack(
        (top(np.linspace(0, 1, 128)), bottom(np.linspace(0, 1, 128))))
    newcmp = colors.ListedColormap(newcolors, name='OrangeBlue')
    diff_cmap = colors.LinearSegmentedColormap.from_list(
        'diff_cmap', [newcmp(x) for x in cmap_scale], newcmp.N)
    diff_norm = colors.BoundaryNorm(diff_bounds, diff_cmap.N)

    # Fills masked values.
    cmap.set_bad(color='k', alpha=0.1)
    diff_cmap.set_bad(color='k', alpha=0.1)

    for axrow, hb_name in zip(axes.T, hb_names):
        masked_cmorph_mean_precip_map = imshow_data[('cmorph', hb_name)]
        ax = axrow[0]

        cmorph_im = ax.imshow(
            masked_cmorph_mean_precip_map,
            cmap=cmap,
            norm=norm,
            # vmin=1e-3, vmax=max_mean_precip,
            origin='lower',
            extent=extent)

        for ax, dataset in zip(axrow.T[1:], datasets[1:]):
            masked_mean_precip_map = imshow_data[(dataset, hb_name)]
            dataset_im = ax.imshow(
                masked_mean_precip_map,
                cmap=diff_cmap,
                norm=diff_norm,
                # vmin=-absmax, vmax=absmax,
                origin='lower',
                extent=extent)

    for ax, dataset in zip(axes[:, 0], datasets):
        if dataset == 'cmorph':
            ax.set_ylabel(STANDARD_NAMES[dataset])
        else:
            ax.set_ylabel(
                f'{STANDARD_NAMES[dataset]} $-$ {STANDARD_NAMES["cmorph"]}')
    _configure_hb_name_dataset_map_grid(axes, hb_names, datasets)

    if len(datasets) == 3:
        cax = fig.add_axes([0.92, 0.66, 0.01, 0.3])
        cax2 = fig.add_axes([0.92, 0.02, 0.01, 0.6])
    elif len(datasets) == 4:
        cax = fig.add_axes([0.92, 0.75, 0.01, 0.2])
        cax2 = fig.add_axes([0.92, 0.02, 0.01, 0.7])
    # plt.colorbar(cmorph_im, cax=cax, orientation='vertical', label='precipitation (mm day$^{-1}$)', **cbar_kwargs)
    cbar_kwargs['extend'] = 'max'
    plt.colorbar(cmorph_im, cax=cax, orientation='vertical', **cbar_kwargs)
    cax.text(5.8, 1, 'precipitation (mm day$^{-1}$)', rotation=90)

    # cax2 = fig.add_axes([0.46, 0.07, 0.4, 0.01])
    # cb = plt.colorbar(dataset_im, cax=cax2, orientation='vertical', label='$\\Delta$ precipitation (mm hr$^{-1}$)')
    cb = plt.colorbar(dataset_im, cax=cax2, orientation='vertical')
    cax2.text(5.8, 0.8, '$\\Delta$ precipitation (mm day$^{-1}$)', rotation=90)
    # cb.set_label_coords(-0.2, 0.5)

    plt.subplots_adjust(left=0.06,
                        right=0.86,
                        top=0.96,
                        bottom=0.04,
                        wspace=0.1,
                        hspace=0.15)

    mean_precip_filename = outputs[0]
    plt.savefig(mean_precip_filename)
    plt.close()
Esempio n. 13
0
    def plot_basin_afi_diurnal_cycle(self,
                                     mode,
                                     method='peak',
                                     cmap_name='li2018fig3',
                                     basin_filter='level',
                                     scale=6):
        raise Exception('Superseded by basin_diurnal_cycle_analysis.py')

        hb = self.hb
        for season in self.seasons:
            cube = self.cubes[f'{mode}_{season}']
            if basin_filter == 'level':
                hb_filtered = hb[hb.LEVEL == scale]
            elif basin_filter == 'area':
                if scale == 'small':
                    min_area, max_area = 2_000, 20_000
                elif scale == 'medium':
                    min_area, max_area = 20_000, 200_000
                elif scale == 'large':
                    min_area, max_area = 200_000, 2_000_000
                hb_filtered = hb.area_select(min_area, max_area)

            raster_cache_key = (basin_filter, scale)
            if raster_cache_key in self.raster_cache:
                raster = self.raster_cache[raster_cache_key]
            else:
                raster = build_raster_from_cube(hb_filtered.geometry, cube)
                self.raster_cache[raster_cache_key] = raster

            lon_min, lon_max = cube.coord('longitude').points[[0, -1]]
            lat_min, lat_max = cube.coord('latitude').points[[0, -1]]

            extent = (lon_min, lon_max, lat_min, lat_max)

            if method == 'peak':
                season_phase_LST, season_amp = calc_diurnal_cycle_phase_amp_peak(
                    cube)
            elif method == 'harmonic':
                season_phase_LST, season_amp = calc_diurnal_cycle_phase_amp_harmonic(
                    cube)

            ax = plt.axes(projection=ccrs.PlateCarree())
            fig = plt.gcf()
            ax.coastlines()

            title = f'{self.runid} diurnal cycle time {mode} {season} ' \
                    f'LST ppt_thresh={self.precip_thresh} mm hr$^{{-1}}$'
            print(title)
            plt.title(title)

            if cmap_name == 'li2018fig3':
                cmap, norm, bounds, cbar_kwargs = load_cmap_data(
                    'cmap_data/li2018_fig3_cb.pkl')
                imshow_kwargs = {'cmap': cmap, 'norm': norm}
                cbar_kwargs['norm'] = norm
            elif cmap_name == 'sky_colour':
                cmap = LinearSegmentedColormap.from_list(
                    'cmap', ['k', 'pink', 'cyan', 'blue', 'red', 'k'], N=24)
                imshow_kwargs = {'cmap': cmap}
                cbar_kwargs = {}

            basin_index = range(1, raster.max() + 1)

            basin_mean_field = np.zeros(raster.shape, dtype=np.float)
            for i in basin_index:
                basin_mean_field[raster == i] = daily_circular_mean(
                    season_phase_LST[raster == i])

            ma_basin_mean_field = np.ma.masked_array(basin_mean_field,
                                                     mask=raster == 0)

            im0 = ax.imshow(ma_basin_mean_field,
                            origin='lower',
                            extent=extent,
                            vmin=0,
                            vmax=24,
                            **imshow_kwargs)

            plt.colorbar(im0,
                         label=f'{mode} peak (hr)',
                         orientation='horizontal',
                         **cbar_kwargs)

            rect = Rectangle((97.5, 18),
                             125 - 97.5,
                             41 - 18,
                             linewidth=1,
                             edgecolor='k',
                             facecolor='none')
            ax.add_patch(rect)
            fig.set_size_inches(12, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/basin_diurnal_cycle/'
                f'asia_diurnal_cycle_{mode}_{season}_{method}.{cmap_name}.{basin_filter}_{scale}.png'
            )
            ax.set_xlim((97.5, 125))
            ax.set_ylim((18, 41))
            ax.set_xticks([100, 110, 120])
            ax.set_yticks([20, 30, 40])
            fig.set_size_inches(6, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/basin_diurnal_cycle/'
                f'china_diurnal_cycle_{mode}_{season}_{method}.{cmap_name}.{basin_filter}_{scale}.png'
            )

            plt.close('all')
Esempio n. 14
0
    def plot_afi_diurnal_cycle(
            self,
            mode,
            method='peak',
            cmap_name='li2018fig3',
            overlay_style=None,
            predom_pixel=None,  # No longer working.
    ):
        if predom_pixel:
            raise NotImplemented('predom_pixel no longer works.')
        for season in self.seasons:
            cube = self.cubes[f'{mode}_{season}']
            if predom_pixel:
                nlat = cube.shape[1] // predom_pixel * predom_pixel
                nlon = cube.shape[2] // predom_pixel * predom_pixel
                cube = cube[:, :nlat, :nlon]
            lon_min, lon_max = cube.coord('longitude').points[[0, -1]]
            lat_min, lat_max = cube.coord('latitude').points[[0, -1]]

            extent = (lon_min, lon_max, lat_min, lat_max)
            if method == 'peak':
                season_phase_LST, season_amp = calc_diurnal_cycle_phase_amp_peak(
                    cube)
            elif method == 'harmonic':
                season_phase_LST, season_amp = calc_diurnal_cycle_phase_amp_harmonic(
                    cube)

            ax = plt.axes(projection=ccrs.PlateCarree())
            fig = plt.gcf()
            ax.coastlines()

            title = f'{self.runid} diurnal cycle time {mode} {season} ' \
                    f'LST ppt_thresh={self.precip_thresh} mm hr$^{{-1}}$'
            print(title)
            plt.title(title)

            season_max = cube.data.max(axis=0)
            season_mean = cube.data.mean(axis=0)
            season_strength = season_max / season_mean

            season_strength_filtered = gaussian_filter(season_strength, 3)
            thresh_boundaries = [100 * 1 / 3, 100 * 2 / 3]
            # thresh_boundaries = [100 * 1 / 4, 100 * 1 / 3]
            filtered_med_thresh, filtered_strong_thresh = np.percentile(
                season_strength_filtered, thresh_boundaries)
            med_thresh, strong_thresh = np.percentile(season_strength,
                                                      thresh_boundaries)

            if cmap_name == 'li2018fig3':
                cmap, norm, bounds, cbar_kwargs = load_cmap_data(
                    'cmap_data/li2018_fig3_cb.pkl')
                imshow_kwargs = {'cmap': cmap, 'norm': norm}
                cbar_kwargs['norm'] = norm
            elif cmap_name == 'sky_colour':
                cmap = LinearSegmentedColormap.from_list(
                    'cmap', ['k', 'pink', 'cyan', 'blue', 'red', 'k'], N=24)
                imshow_kwargs = {'cmap': cmap}
                cbar_kwargs = {}

            if overlay_style != 'alpha_overlay':
                im0 = ax.imshow(season_phase_LST,
                                origin='lower',
                                extent=extent,
                                vmin=0,
                                vmax=24,
                                **imshow_kwargs)
            elif overlay_style == 'alpha_overlay':
                peak_strong = np.ma.masked_array(
                    season_phase_LST, season_strength < strong_thresh)
                peak_med = np.ma.masked_array(
                    season_phase_LST, ((season_strength > strong_thresh) |
                                       (season_strength < med_thresh)))
                peak_weak = np.ma.masked_array(season_phase_LST,
                                               season_strength > med_thresh)

                im0 = ax.imshow(peak_strong,
                                origin='lower',
                                extent=extent,
                                vmin=0,
                                vmax=24,
                                **imshow_kwargs)
                ax.imshow(peak_med,
                          origin='lower',
                          extent=extent,
                          alpha=0.66,
                          vmin=0,
                          vmax=24,
                          **imshow_kwargs)
                ax.imshow(peak_weak,
                          origin='lower',
                          extent=extent,
                          alpha=0.33,
                          vmin=0,
                          vmax=24,
                          **imshow_kwargs)

            plt.colorbar(im0,
                         label=f'{mode} peak (hr)',
                         orientation='horizontal',
                         **cbar_kwargs)

            if overlay_style == 'contour_overlay':
                plt.contour(season_strength_filtered,
                            [filtered_med_thresh, filtered_strong_thresh],
                            colors=['w', 'w'],
                            linestyles=['--', '-'],
                            extent=extent)

            rect = Rectangle((97.5, 18),
                             125 - 97.5,
                             41 - 18,
                             linewidth=1,
                             edgecolor='k',
                             facecolor='none')
            ax.add_patch(rect)
            fig.set_size_inches(12, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/diurnal_cycle/'
                f'asia_diurnal_cycle_{mode}_{season}_{method}.{cmap_name}.{overlay_style}.png'
            )
            ax.set_xlim((97.5, 125))
            ax.set_ylim((18, 41))
            ax.set_xticks([100, 110, 120])
            ax.set_yticks([20, 30, 40])
            fig.set_size_inches(6, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/diurnal_cycle/'
                f'china_diurnal_cycle_{mode}_{season}_{method}.{cmap_name}.{overlay_style}.png'
            )

            plt.close('all')

            ax = plt.axes(projection=ccrs.PlateCarree())
            fig = plt.gcf()
            fig.set_size_inches(12, 8)
            ax.coastlines()
            title = f'{self.runid} diurnal cycle strength {mode} {season} ' \
                    f'LST ppt_thresh={self.precip_thresh} mm hr$^{{-1}}$'
            plt.title(title)
            if mode == 'freq':
                kwargs = {'vmin': 1, 'vmax': 11, 'norm': LogNorm()}
            elif mode == 'amount':
                kwargs = {'vmin': 1, 'vmax': 22, 'norm': LogNorm()}
            elif mode == 'intensity':
                kwargs = {'vmin': 1, 'vmax': 22, 'norm': LogNorm()}

            im0 = plt.imshow(season_strength,
                             origin='lower',
                             extent=extent,
                             **kwargs)
            rect = Rectangle((97.5, 18),
                             125 - 97.5,
                             41 - 18,
                             linewidth=1,
                             edgecolor='k',
                             facecolor='none')
            ax.add_patch(rect)

            plt.colorbar(im0,
                         label=f'{mode} strength (-)',
                         orientation='horizontal')
            fig.set_size_inches(12, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/diurnal_cycle/'
                f'asia_diurnal_cycle_{mode}_{season}_{method}_strength.png')
            ax.set_xlim((97.5, 125))
            ax.set_ylim((18, 41))
            ax.set_xticks([100, 110, 120])
            ax.set_yticks([20, 30, 40])
            fig.set_size_inches(6, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/diurnal_cycle/'
                f'china_diurnal_cycle_{mode}_{season}_{method}_strength.png')
            plt.close('all')
Esempio n. 15
0
    def plot_season_afi_mean(self, mode):
        for i, season in enumerate(self.seasons):
            cube = self.cubes[f'{mode}_{season}']
            lon_min, lon_max = cube.coord('longitude').points[[0, -1]]
            lat_min, lat_max = cube.coord('latitude').points[[0, -1]]

            extent = (lon_min, lon_max, lat_min, lat_max)
            plt.clf()
            ax = plt.axes(projection=ccrs.PlateCarree())
            fig = plt.gcf()
            ax.coastlines()

            # plt.figure(figsize=(12.8, 9.6))
            title = f'{self.runid} {mode} {season} mean ppt_thresh={self.precip_thresh} mm hr$^{{-1}}$'
            print(title)
            plt.title(title)
            if mode == 'freq':
                data = cube.data.mean(axis=0) * 100
                units = '%'
                cmap, norm, bounds, cbar_kwargs = load_cmap_data(
                    'cmap_data/li2018_fig2_cb2.pkl')
                kwargs = {'vmin': 0, 'cmap': cmap}
                cbar_kwargs['norm'] = norm
                kwargs['vmin'] = 3
                kwargs['vmax'] = 40

                # if self.precip_thresh == 0.1:
                #     # Consistent with Li 2018.
                #     kwargs['vmin'] = 3
                #     kwargs['vmax'] = 40
                #     ticks = [3, 5, 8, 15, 25, 40]
                #     kwargs['norm'] = VrangeNorm(ticks)
                #     cbar_kwargs['extend'] = 'both'
            elif mode == 'amount':
                cmap, norm, bounds, cbar_kwargs = load_cmap_data(
                    'cmap_data/li2018_fig2_cb1.pkl')
                cbar_kwargs['norm'] = norm
                data = cube.data.mean(axis=0) * 24  # mm/hr -> mm/day
                kwargs = {'vmin': 1e-3, 'vmax': 12, 'cmap': cmap}
                units = 'mm day$^{-1}$'
            elif mode == 'intensity':
                cmap, norm, bounds, cbar_kwargs = load_cmap_data(
                    'cmap_data/li2018_fig2_cb3.pkl')
                cbar_kwargs['norm'] = norm
                data = cube.data.mean(axis=0)
                kwargs = {'vmin': 1e-2, 'vmax': 4, 'cmap': cmap}
                # cbar_kwargs = {'extend': 'max'}
                units = 'mm hr$^{-1}$'
            im0 = ax.imshow(data,
                            origin='lower',
                            norm=norm,
                            extent=extent,
                            **kwargs)
            rect = Rectangle((97.5, 18),
                             125 - 97.5,
                             41 - 18,
                             linewidth=1,
                             edgecolor='k',
                             facecolor='none')
            ax.add_patch(rect)

            # cax = fig.add_axes([0.12, 0.1, 0.8, 0.03])
            # cb = mpl.colorbar.ColorbarBase(cax, cmap=cmap,
            #                                spacing='uniform',
            #                                orientation='horizontal',
            #                                label=f'{mode} precip. ({units})',
            #                                **cbar_kwargs)

            plt.colorbar(im0,
                         label=f'{mode} precip. ({units})',
                         orientation='horizontal',
                         **cbar_kwargs,
                         spacing='uniform')
            if mode == 'amount':
                index_argmax = np.unravel_index(data.argmax(), data.shape)
                print(f'max. amount: {data.max()} mm hr-1')
                lat = cube[:, index_argmax[0],
                           index_argmax[1]].coord('latitude').points[0]
                lon = cube[:, index_argmax[0],
                           index_argmax[1]].coord('longitude').points[0]
                print(f'lat, lon: {lat}, {lon}')
                ax.plot(lon, lat, 'kx')
            fig.set_size_inches(12, 8)
            print(extent)
            ax.set_xticks(np.linspace(60, 150, 10))
            ax.set_yticks(np.linspace(10, 50, 5))
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/hourly/mean/asia_{mode}_{season}_mean.png'
            )

            # Same as Li 2018.
            ax.set_xlim((97.5, 125))
            ax.set_ylim((18, 41))
            ax.set_xticks([100, 110, 120])
            ax.set_yticks([20, 30, 40])
            fig.set_size_inches(6, 8)
            self.savefig(
                f'ppt_thresh_{self.thresh_text}/hourly/mean/china_{mode}_{season}_mean.png'
            )
            plt.close('all')