Ejemplo n.º 1
0
def get_region_data(inputs, region):
    orog = iris.load_cube(str(inputs['orog']), 'surface_altitude')
    surf_wind = iris.load(str(inputs['surf_wind'])).concatenate()
    precip = iris.load_cube(str(inputs['precip']))

    # Needed so that has same dims as surf_wind after extract constraint.
    orog.coord('latitude').guess_bounds()
    orog.coord('longitude').guess_bounds()
    precip.coord('latitude').guess_bounds()
    precip.coord('longitude').guess_bounds()

    region_constraint = get_region_constraint(region)

    orog_region = orog.extract(region_constraint)
    surf_wind_region = surf_wind.extract(region_constraint)
    precip_region = precip.extract(region_constraint)
    u_region = surf_wind_region.extract_strict('x_wind')
    v_region = surf_wind_region.extract_strict('y_wind')

    lon = orog_region.coord('longitude').points
    lat = orog_region.coord('latitude').points
    extent = util.get_extent_from_cube(orog_region)
    mid_lon = (lon[0] + lon[-1]) / 2
    lst_offset = mid_lon / 360 * 24
    return (lon, lat, extent, lst_offset, orog_region, precip_region, u_region,
            v_region)
Ejemplo n.º 2
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)
Ejemplo n.º 3
0
def plot_mean_orog_precip(inputs, outputs):
    cubes = iris.load(str(inputs[0]))
    orog_precip_mean = cubes.extract_strict('orog_precipitation_flux_mean')
    nonorog_precip_mean = cubes.extract_strict('non_orog_precipitation_flux_mean')
    ocean_precip_mean = cubes.extract_strict('ocean_precipitation_flux_mean')

    extent = util.get_extent_from_cube(orog_precip_mean)

    for i, (name, precip) in enumerate([('orog', orog_precip_mean.data),
                                        ('non orog', nonorog_precip_mean.data),
                                        ('ocean/water', ocean_precip_mean.data)]):
        plt.figure(figsize=(10, 7.5))
        ax = plt.axes(projection=ccrs.PlateCarree())
        configure_ax_asia(ax)
        im = ax.imshow(precip, origin='lower', extent=extent, norm=mpl.colors.LogNorm(),
                       vmin=1e-2, vmax=1e2)
        plt.colorbar(im, orientation='horizontal', label=f'{name} (mm day$^{{-1}}$)', pad=0.1)
        plt.savefig(outputs[i])

    plt.figure(figsize=(10, 7.5))
    ax = plt.axes(projection=ccrs.PlateCarree())
    configure_ax_asia(ax)
    im = ax.imshow(100 * orog_precip_mean.data / (orog_precip_mean.data + nonorog_precip_mean.data),
                   origin='lower', extent=extent, vmin=0, vmax=100)
    plt.colorbar(im, orientation='horizontal', label='% orog', pad=0.1)
    plt.savefig(outputs[3])
Ejemplo n.º 4
0
def plot_orog(orog, grad_orog):
    extent = util.get_extent_from_cube(orog)
    plt.figure('orog')
    plt.imshow(orog.data[1:-1], origin='lower', extent=extent)
    plt.colorbar()
    plt.figure('d orog dx')
    plt.imshow(grad_orog[0].data, origin='lower', extent=extent)
    plt.colorbar()
    plt.figure('d orog dy')
    plt.imshow(grad_orog[1].data, origin='lower', extent=extent)
    plt.colorbar()
    plt.show()
Ejemplo n.º 5
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])
Ejemplo n.º 6
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()
Ejemplo n.º 7
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])
Ejemplo n.º 8
0
grad_z = util.calc_uniform_lat_lon_grad(z)
from cosmic import util

grad_z = util.calc_uniform_lat_lon_grad(z)
gradient = np.sqrt(grad_z[0].data**2 + grad_z[1].data**2)
import numpy as np

gradient = np.sqrt(grad_z[0].data**2 + grad_z[1].data**2)
gradient_mask = gradient > np.percentile(gradient, 95)
dist = util.CalcLatLonDistanceMask(Lat, Lon)
lat = z[1:-1].coord('latitude').points
lon = z[1:-1].coord('longitude').points
Lon, Lat = np.meshgrid(lon, lat)
dist = util.CalcLatLonDistanceMask(Lat, Lon)
expanded_gradient_mask = dist.calc_close_to_mask(gradient_mask)
extent = util.get_extent_from_cube(z)
extent = util.get_extent_from_cube(z[1:-1])
plt.imshow(expanded_gradient_mask, origin='lower', extent=extent)
plt.show()
r_clim = iris.load(
    '/home/markmuetz/mirrors/jasmin/gw_cosmic/mmuetz/data/experimental/R_clim.N1280.nc'
)
r_clim
r_clim = iris.load_cube(
    '/home/markmuetz/mirrors/jasmin/gw_cosmic/mmuetz/data/experimental/R_clim.N1280.nc'
)
r_clim = iris.load_cube(
    '/home/markmuetz/mirrors/jasmin/gw_cosmic/mmuetz/data/experimental/R_clim.N1280.nc'
)[:, 1:-1, :]
r_clim
plt.imshow(r_clim.data.mean(axis=0), origin='lower', extent=extent)
Ejemplo n.º 9
0
def plot_fig3(inputs, outputs):
    m1_cubes = iris.load([
        str(inputs[f'al508_diag_{month:02}']) for month in [6, 7, 8]
    ]).concatenate()
    m2_cubes = iris.load(str(inputs['al508_direct']))

    m1_orog_precip = m1_cubes.extract_strict('orog_precipitation_flux')
    m1_nonorog_precip = m1_cubes.extract_strict('non_orog_precipitation_flux')
    m1_ocean_precip = m1_cubes.extract_strict('ocean_precipitation_flux')
    assert m1_orog_precip.units == 'kg m-2 s-1'
    assert m1_nonorog_precip.units == 'kg m-2 s-1'
    assert m1_ocean_precip.units == 'kg m-2 s-1'

    m1_extent = util.get_extent_from_cube(m1_orog_precip)
    m1_orog_precip_mean = m1_orog_precip.data.mean(
        axis=0) * 3600 * 24  # kg m-2 s-1 -> mm day-1
    m1_nonorog_precip_mean = m1_nonorog_precip.data.mean(
        axis=0) * 3600 * 24  # kg m-2 s-1 -> mm day-1
    m1_ocean_precip_mean = m1_nonorog_precip.data.mean(
        axis=0) * 3600 * 24  # kg m-2 s-1 -> mm day-1

    m2_orog_precip_mean = m2_cubes.extract_strict(
        'orog_precipitation_flux_mean')
    m2_nonorog_precip_mean = m2_cubes.extract_strict(
        'non_orog_precipitation_flux_mean')
    m2_ocean_precip_mean = m2_cubes.extract_strict(
        'ocean_precipitation_flux_mean')
    m2_extent = util.get_extent_from_cube(m2_orog_precip_mean)

    fig, axes = plt.subplots(1,
                             2,
                             figsize=(10, 4),
                             subplot_kw={'projection': ccrs.PlateCarree()})
    for ax, (nonorog, orog, ocean), extent in zip(
            axes.flatten(),
        [(m1_nonorog_precip_mean, m1_orog_precip_mean, m1_ocean_precip_mean),
         (m2_nonorog_precip_mean.data, m2_orog_precip_mean.data,
          m2_ocean_precip_mean.data)], [m1_extent, m2_extent]):
        configure_ax_asia(ax, tight_layout=False)
        im = ax.imshow(100 * orog / (orog + nonorog),
                       origin='lower',
                       extent=extent,
                       vmin=0,
                       vmax=100)

    axes[1].get_yaxis().set_ticks([])
    cax = fig.add_axes([0.1, 0.12, 0.8, 0.03])
    for i, ax in enumerate(axes.flatten()):
        c = string.ascii_lowercase[i]
        ax.text(-0.07, 0.95, f'({c})', size=12, transform=ax.transAxes)

    axes[0].set_title('M1')
    axes[1].set_title('M2')

    plt.colorbar(im, cax=cax, orientation='horizontal', label='% orog.')
    plt.subplots_adjust(left=0.1,
                        top=0.96,
                        right=0.98,
                        bottom=0.2,
                        hspace=0.07,
                        wspace=0.09)

    plt.savefig(outputs[0])
Ejemplo n.º 10
0
def plot_fig4(inputs, outputs):
    al508_cubes = iris.load(str(inputs['al508_direct']))
    ak543_cubes = iris.load(str(inputs['ak543_direct']))

    al508_orog_precip_mean = al508_cubes.extract_strict(
        'orog_precipitation_flux_mean')
    al508_nonorog_precip_mean = al508_cubes.extract_strict(
        'non_orog_precipitation_flux_mean')
    al508_ocean_precip_mean = al508_cubes.extract_strict(
        'ocean_precipitation_flux_mean')
    al508_extent = util.get_extent_from_cube(al508_orog_precip_mean)

    ak543_orog_precip_mean = ak543_cubes.extract_strict(
        'orog_precipitation_flux_mean')
    ak543_nonorog_precip_mean = ak543_cubes.extract_strict(
        'non_orog_precipitation_flux_mean')
    ak543_ocean_precip_mean = ak543_cubes.extract_strict(
        'ocean_precipitation_flux_mean')
    ak543_extent = util.get_extent_from_cube(ak543_orog_precip_mean)

    al508_mean = al508_orog_precip_mean.data + al508_nonorog_precip_mean.data + al508_ocean_precip_mean.data
    ak543_mean = ak543_orog_precip_mean.data + ak543_nonorog_precip_mean.data + ak543_ocean_precip_mean.data

    al508_opf = 100 * al508_orog_precip_mean.data / (
        al508_orog_precip_mean.data + al508_nonorog_precip_mean.data)
    ak543_opf = 100 * ak543_orog_precip_mean.data / (
        ak543_orog_precip_mean.data + ak543_nonorog_precip_mean.data)

    fig, axes = plt.subplots(2,
                             2,
                             figsize=(10, 6.4),
                             subplot_kw={'projection': ccrs.PlateCarree()})

    extent = al508_extent
    for ax in axes.flatten():
        configure_ax_asia(ax, tight_layout=False)
    im0 = axes[0, 0].imshow(al508_mean,
                            origin='lower',
                            extent=extent,
                            norm=mpl.colors.LogNorm(),
                            vmin=1,
                            vmax=1e2)
    im1 = axes[1, 0].imshow(ak543_mean,
                            origin='lower',
                            extent=extent,
                            norm=mpl.colors.LogNorm(),
                            vmin=1,
                            vmax=1e2)

    im3 = axes[0, 1].imshow(al508_opf,
                            origin='lower',
                            extent=extent,
                            vmin=0,
                            vmax=100)
    im4 = axes[1, 1].imshow(ak543_opf,
                            origin='lower',
                            extent=extent,
                            vmin=0,
                            vmax=100)

    for ax in axes.flatten()[:2]:
        ax.get_xaxis().set_ticks([])
    for ax in axes[:, 1].flatten():
        ax.get_yaxis().set_ticks([])
    for i, ax in enumerate(axes.flatten()):
        c = string.ascii_lowercase[i]
        ax.text(-0.07, 0.95, f'({c})', size=12, transform=ax.transAxes)

    axes[0, 0].set_title('total precip.')
    axes[0, 1].set_title('% orog.')
    axes[0, 0].set_ylabel('N1280')
    axes[1, 0].set_ylabel('N1280-EC')

    cax1 = fig.add_axes([0.1, 0.1, 0.4, 0.03])
    cax2 = fig.add_axes([0.56, 0.1, 0.4, 0.03])

    plt.colorbar(im1,
                 cax=cax1,
                 orientation='horizontal',
                 label='precip. (mm day$^{-1}$)')
    plt.colorbar(im3, cax=cax2, orientation='horizontal', label='% orog.')
    plt.subplots_adjust(left=0.1,
                        top=0.96,
                        right=0.98,
                        bottom=0.2,
                        hspace=0.07,
                        wspace=0.09)
    plt.savefig(outputs[0])

    fig, axes = plt.subplots(1,
                             2,
                             figsize=(10, 4),
                             subplot_kw={'projection': ccrs.PlateCarree()})
    for ax in axes.flatten():
        configure_ax_asia(ax, tight_layout=False)
    for i, ax in enumerate(axes.flatten()):
        c = string.ascii_lowercase[i]
        ax.text(-0.07, 0.95, f'({c})', size=12, transform=ax.transAxes)

    levels = [-20, -10, -5, -1, 1, 5, 10, 20]
    colour_levels = [0, 0.2, 0.4, 0.5, 0.6, 0.8, 0.99]

    norm1 = mpl.colors.BoundaryNorm(levels, ncolors=256)
    colours = [(i / (len(colour_levels) - 1), mpl.cm.bwr_r(v))
               for i, v in enumerate(colour_levels)]
    cmap1 = mpl.colors.LinearSegmentedColormap.from_list('frac_list', colours)
    im2 = axes[0].imshow(ak543_mean - al508_mean,
                         origin='lower',
                         extent=extent,
                         cmap=cmap1,
                         norm=norm1)

    levels = [-100, -50, -10, -1, 1, 10, 50, 100]
    colour_levels = [0, 0.2, 0.4, 0.5, 0.6, 0.8, 0.99]
    norm2 = mpl.colors.BoundaryNorm(levels, ncolors=256)
    colours = [(i / (len(colour_levels) - 1), mpl.cm.bwr_r(v))
               for i, v in enumerate(colour_levels)]
    cmap2 = mpl.colors.LinearSegmentedColormap.from_list('frac_list', colours)
    im5 = axes[1].imshow(ak543_opf - al508_opf,
                         origin='lower',
                         extent=extent,
                         vmin=-100,
                         vmax=100,
                         cmap=cmap2,
                         norm=norm2)

    axes[1].get_yaxis().set_ticks([])
    axes[0].set_title('$\Delta$ total precip.')
    axes[1].set_title('$\Delta$ % orog.')

    cax3 = fig.add_axes([0.1, 0.12, 0.4, 0.03])
    cax4 = fig.add_axes([0.56, 0.12, 0.4, 0.03])
    plt.suptitle('N1280-EC $\minus$ N1280')
    plt.colorbar(im2,
                 cax=cax3,
                 orientation='horizontal',
                 label='$\Delta$ precip. (mm day$^{-1}$)',
                 extend='both')
    plt.colorbar(im5,
                 cax=cax4,
                 orientation='horizontal',
                 label='$\Delta$ % orog.')

    plt.subplots_adjust(left=0.1,
                        top=0.96,
                        right=0.98,
                        bottom=0.2,
                        hspace=0.07,
                        wspace=0.09)
    plt.savefig(outputs[1])
Ejemplo n.º 11
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()
Ejemplo n.º 12
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])
Ejemplo n.º 13
0
def plot_obs_mean_precip_diff(inputs, outputs, dataset, hb_name):
    weighted_basin_mean_precip_filename = inputs['dataset_weighted']
    obs_weighted_basin_mean_precip_filename = inputs['obs_weighted']

    df_mean_precip = pd.read_hdf(weighted_basin_mean_precip_filename)
    df_obs_mean_precip = pd.read_hdf(obs_weighted_basin_mean_precip_filename)

    # There can be NaNs in the datasets, as in e.g. APHRODITE at some fine-scale basins.
    # Use version of RMSE and MAE that mask these out.
    obs_rmse = rmse_mask_out_nan(
        df_mean_precip.basin_weighted_mean_precip_mm_per_hr.values.astype(
            float),
        df_obs_mean_precip.basin_weighted_mean_precip_mm_per_hr.values.astype(
            float))
    obs_mae = mae_mask_out_nan(
        df_mean_precip.basin_weighted_mean_precip_mm_per_hr.values.astype(
            float),
        df_obs_mean_precip.basin_weighted_mean_precip_mm_per_hr.values.astype(
            float))

    raster_hb_name = hb_name
    raster_cube = iris.load_cube(str(inputs['raster_cubes']),
                                 f'hydrobasins_raster_{raster_hb_name}')
    raster = raster_cube.data

    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]

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

    extent = get_extent_from_cube(raster_cube)

    plt.figure(figsize=(10, 8))
    ax = plt.subplot(projection=ccrs.PlateCarree())
    plt.title(
        f'{dataset} mean_precip. RMSE: {obs_rmse:.3f} mm hr$^{{-1}}$; MAE: {obs_mae:.3f} mm hr$^{{-1}}$'
    )
    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 - obs_mean_precip_map, raster_cube.data == 0)

    im = ax.imshow(
        masked_mean_precip_map,
        cmap='bwr',
        norm=MidPointNorm(0, -1, 3),
        # vmin=-absmax, vmax=absmax,
        origin='lower',
        extent=extent)

    plt.colorbar(im,
                 label=f'precip. (mm hr$^{{-1}}$)',
                 orientation='horizontal')
    configure_ax_asia(ax, extent)
    mean_precip_filename = outputs[0]
    plt.savefig(mean_precip_filename)
    plt.close()
Ejemplo n.º 14
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()
Ejemplo n.º 15
0
            dist_asia = util.CalcLatLonDistanceMask(Lat_asia, Lon_asia, 100, False)
            mask_asia = dist_asia.calc_close_to_mask(dotplus_thresh_asia)
            mask_asia_acc = util.calc_close_to_mask(dotplus_thresh_asia, 100, 'accurate')

        plt.figure('acc vs new method')
        plt.imshow(mask_asia_acc.data.astype(int) - mask_asia.data.astype(int), origin='lower')

    if sys.argv[1] == 'plot_masks':
        dists = [20, 30, 40]
        fig, axes = plt.subplots(2, 2 + len(dists), sharex=True, sharey=True,
                                 subplot_kw={'projection': ccrs.PlateCarree()})
        for axrow, dot, dot_thresh_asia in zip(axes,
                                               [dotplus, dotminus],
                                               [dotplus_thresh_asia, dotminus_thresh_asia]):

            extent = util.get_extent_from_cube(dot_thresh_asia)
            for ax in axrow:
                configure_ax_asia(ax, tight_layout=False)
            ax0, ax1, *axdist = axrow
            ax0.imshow(dot.extract(CONSTRAINT_ASIA).data, origin='lower', extent=extent)
            ax1.imshow(dot_thresh_asia.data, origin='lower', extent=extent)
            for ax, dist in zip(axdist, dists):
                dist_asia = util.CalcLatLonDistanceMask(Lat_asia, Lon_asia, dist, False)
                mask_asia = dist_asia.calc_close_to_mask(dot_thresh_asia)
                ax.imshow(mask_asia.data, origin='lower', extent=extent)

        axes[0, 0].set_title('(u, v) x $\\nabla$z')
        axes[0, 1].set_title(f'mask on > {forced_ascent_thresh} (m s$^{{-1}}$)')

        for ax, dist in zip(axes[0, 2:], dists):
            ax.set_title(f'expand by {dist} km')