Beispiel #1
0
def movement_compare(t2, t3, traj23diffs):
    # maps of a select few pairs of 2d and 3d trajectories from the same point to illustrate the positions within the 
    # outflow volume from which there are the largest and least difference in inflow position
    
    pvts = iris.load('/export/cloud/migrated-NCASweather/ben/nawdex/mi-ar482/20160922_12/prodm_op_gl-mn_20160922_12_c012_thsfcs_5K.nc', 'ertel_potential_vorticity')[0][0][9]
    # pv at ts on 325K
    pvtf = iris.load('/export/cloud/migrated-NCASweather/ben/nawdex/mi-ar482/20160922_12/prodm_op_gl-mn_20160922_12_c042_thsfcs_5K.nc', 'ertel_potential_vorticity')[0][0][9]
    # pv at tf on 325K
    
    
    
    move_mid = np.nonzero((traj23diffs[:, 2, 0] > 25)*(traj23diffs[:, 2, 0] < 100)*(traj23diffs[:, 2, 3] > 18)*(traj23diffs[:, 2, 3] < 22))[0][::16]
    # 8 trajectories move between 18 - 22 degrees
    move_most = np.nonzero((traj23diffs[:, 2, 0] > 25)*(traj23diffs[:, 2, 0] < 100)*(traj23diffs[:, 2, 3] > 25))[0][::40]#29.35))[0]
    # 8 trajectories move > 29.35 degrees
    move_least = np.nonzero((traj23diffs[:, 2, 0] > 25)*(traj23diffs[:, 2, 0] < 100)*(traj23diffs[:, 2, 3] < 15))[0][::11]#10))[0]
    # 8 trajectories move < 10 degrees
    
    for move in [[move_most, 'most'], [move_mid, 'mid'], [move_least, 'least']]:
        
        plt.figure(figsize = (13, 7))
        
        iplt.contour(pvts, [2], colors = [[.5, .5, .5]], linewidths = [.5])
        iplt.contour(pvtf, [2], colors = ['k'])
        
        for i in move[0]:
            plt.plot(t3.data[i, :, 0]-360, t3.data[i, :, 1], color = 'r', linewidth = 3)
        for i in move[0]:
            plt.plot(t2.data[i, :, 0]-360, t2.data[i, :, 1], color = 'c', linestyle = '--', linewidth = 2)
            
        plt.title('Difference in path taken by isentropic v full trajectories')
        plt.savefig('/home/users/bn826011/NAWDEX/From N Drive/2019_figs/IOP3/Path_differences_'+move[1]+'.png')
        plt.show()
def make_plot(ax, dtheta, pv, tr):
    im = iplt.pcolormesh(dtheta, vmin=-30, vmax=30, cmap="seismic")
    print(dtheta.data.min(), dtheta.data.max())
    ax.coastlines()
    ax.gridlines()

    # Add a contour for PV=2 and also shade PV>2
    iplt.contour(pv, [2], colors='k')
    pv.data = (pv.data > 2).astype(float)
    iplt.contourf(pv, [0.9, 1.1], colors="k", alpha=0.25)

    # Need to use the cube's coordinate reference system to properly add regular
    # coordinates on top
    crs = dtheta.coord(axis="x").coord_system.as_cartopy_crs()
    plt.plot(tr.x[:, 0] - 360, tr.y[:, 0], transform=crs, lw=3, color='cyan')

    # With the projection the axis limits don't set well, so shrink it down as much as
    # possible
    x, y = pv.coord(axis="x"), pv.coord(axis="y")
    ax.set_extent(
        [x.points.min(),
         x.points.max(),
         y.points.min(),
         y.points.max()],
        crs=crs)

    return im
Beispiel #3
0
def make_plot(forecast, analysis, variable, levels, units, errlevs, clevs,
              cmap='coolwarm', mask=None):
    # Extract data and errors
    f = convert.calc(variable, forecast, levels=levels)[0]
    a = convert.calc(variable, analysis, levels=levels)[0]
    err = f - a

    for cube in [f, a, err]:
        cube.convert_units(units)

    if mask is not None:
        for cube in [f, a]:
            cube.data = np.ma.masked_where(mask, cube.data)

    # Plot error
    iplt.contourf(err, errlevs, cmap=cmap, extend='both')
    add_map()
    cbar = plt.colorbar(orientation='horizontal', spacing='proportional')
    errlevs.append(0)
    cbar.set_ticks(errlevs)
    cbar.set_label(units)

    # Overlay forecast and analysis
    cs = iplt.contour(f, clevs, colors='k', linewidths=2)
    iplt.contour(a, clevs, colors='k', linewidths=2, linestyles='--')
    plt.clabel(cs, fmt='%1.0f', colors='k')

    return
Beispiel #4
0
def main(cubes):
    lon, lat = grid.true_coords(cubes[0])
    z300 = convert.calc('altitude',
                        cubes,
                        levels=('equivalent_potential_temperature', [300]))[0]
    z300.convert_units('km')
    mslp = convert.calc('air_pressure_at_sea_level', cubes)
    mslp.convert_units('hPa')

    # Plot overview
    plot.contourf(z300, np.linspace(0, 10, 11))
    cs = iplt.contour(mslp, np.linspace(950, 1050, 11), colors='k')
    plt.clabel(cs, fmt='%1.0f')

    # Warm Sector
    warm_sector = z300.data.mask
    plim = mslp.data < 1000
    loc = np.logical_and(lon > -10, lon < 5)
    ws_mask = np.logical_and(np.logical_and(warm_sector, loc), plim)
    ws_mask = mslp.copy(data=ws_mask)
    iplt.contour(ws_mask, linestyles='--', colors='r')

    # Cold Sector
    cold_sector = z300.data < 5
    loc = np.logical_and(loc, lat < 65)
    cs_mask = np.logical_and(np.logical_and(cold_sector, loc), plim)
    cs_mask = mslp.copy(data=cs_mask)
    iplt.contour(cs_mask, linestyles='--', colors='b')

    plt.title(r'$z(\theta_e = 300)$')

    return
Beispiel #5
0
def main():
    fname = iris.sample_data_path("NAME_output.txt")

    boundary_volc_ash_constraint = iris.Constraint("VOLCANIC_ASH_AIR_CONCENTRATION", flight_level="From FL000 - FL200")

    # Callback shown as None to illustrate where a cube-level callback function would be used if required
    cube = iris.load_cube(fname, boundary_volc_ash_constraint, callback=None)

    # draw contour levels for the data (the top level is just a catch-all)
    levels = (0.0002, 0.002, 0.004, 1e10)
    cs = iplt.contourf(cube, levels=levels, colors=("#80ffff", "#939598", "#e00404"))

    # draw a black outline at the lowest contour to highlight affected areas
    iplt.contour(cube, levels=(levels[0], 100), colors="black")

    # set an extent and a background image for the map
    ax = plt.gca()
    ax.set_extent((-90, 20, 20, 75))
    ax.stock_img("ne_shaded")

    # make a legend, with custom labels, for the coloured contour set
    artists, _ = cs.legend_elements()
    labels = [
        r"$%s < x \leq %s$" % (levels[0], levels[1]),
        r"$%s < x \leq %s$" % (levels[1], levels[2]),
        r"$x > %s$" % levels[2],
    ]
    ax.legend(artists, labels, title="Ash concentration / g m-3", loc="upper left")

    time = cube.coord("time")
    time_date = time.units.num2date(time.points[0]).strftime(UTC_format)
    plt.title("Volcanic ash concentration forecast\nvalid at %s" % time_date)

    iplt.show()
Beispiel #6
0
 def test_xaxis_labels_with_axes(self):
     import matplotlib.pyplot as plt
     fig = plt.figure()
     ax = fig.add_subplot(111)
     iplt.contour(self.cube, axes=ax, coords=('str_coord', 'bar'))
     plt.close(fig)
     self.assertPointsTickLabels('xaxis', ax)
Beispiel #7
0
    def test_simple(self):
        # First sub-plot
        plt.subplot(221)
        plt.title('Default')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Second sub-plot
        plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120))
        plt.title('Molleweide')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Third sub-plot (the projection part is redundant, but a useful
        # test none-the-less)
        ax = plt.subplot(223, projection=iplt.default_projection(self.cube))
        plt.title('Native')
        iplt.contour(self.cube)
        ax.coastlines()

        # Fourth sub-plot
        ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree())
        plt.title('PlateCarree')
        iplt.contourf(self.cube)
        ax.coastlines()

        self.check_graphic()
Beispiel #8
0
def pv(forecast, analysis, variable, levels, **kwargs):
    pv_f = convert.calc(variable, forecast, levels=levels)[0]
    pv_a = convert.calc(variable, analysis, levels=levels)[0]

    err = pv_f - pv_a
    axes = []

    # Initialise the plot
    fig = plt.figure(figsize=(18, 20))

    axes.append(plt.subplot2grid((25, 4), (0, 0), colspan=2, rowspan=10))
    im = make_pv_plot(pv_f, **kwargs)
    plt.title('Forecast')

    axes.append(plt.subplot2grid((25, 4), (0, 2), colspan=2, rowspan=10))
    im = make_pv_plot(pv_a, **kwargs)
    plt.title('Analysis')

    ax = plt.subplot2grid((25, 4), (10, 1), colspan=2, rowspan=1)
    cbar = plt.colorbar(im, cax=ax, orientation='horizontal')

    axes.append(plt.subplot2grid((25, 4), (13, 1), colspan=2, rowspan=10))
    im = iplt.pcolormesh(err, vmin=-5, vmax=5, cmap='coolwarm')
    iplt.contour(pv_f, [2], colors='k', linewidths=2)
    iplt.contour(pv_a, [2], colors='k', linewidths=2, linestyles='--')
    add_map()
    plt.title('Forecast Minus Analysis')

    ax = plt.subplot2grid((25, 4), (23, 1), colspan=2, rowspan=1)
    cbar = plt.colorbar(im, cax=ax, orientation='horizontal')

    for n, ax in enumerate(axes):
        ax.set_title(ascii_lowercase[n].ljust(20))
    plt.show()
Beispiel #9
0
    def test_simple(self):
        # First sub-plot
        plt.subplot(221)
        plt.title('Default')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Second sub-plot
        plt.subplot(222, projection=ccrs.Mollweide(central_longitude=120))
        plt.title('Molleweide')
        iplt.contourf(self.cube)
        plt.gca().coastlines()

        # Third sub-plot (the projection part is redundant, but a useful
        # test none-the-less)
        ax = plt.subplot(223, projection=iplt.default_projection(self.cube))
        plt.title('Native')
        iplt.contour(self.cube)
        ax.coastlines()

        # Fourth sub-plot
        ax = plt.subplot(2, 2, 4, projection=ccrs.PlateCarree())
        plt.title('PlateCarree')
        iplt.contourf(self.cube)
        ax.coastlines()

        self.check_graphic()
Beispiel #10
0
def make_plot(cubes, rings, wcb, theta_level, n):
    # Plot a map at verification time
    levels = ('air_potential_temperature', [theta_level])
    pv = convert.calc('ertel_potential_vorticity', cubes, levels=levels)[0]
    plot.pcolormesh(pv, vmin=-2, vmax=2, cmap='coolwarm')
    iplt.contour(pv, [0, 2], colors='k', linewidths=2)
    add_map()

    # Load the trajectories
    x = wcb['grid_longitude'] - 360
    y = wcb['grid_latitude']
    c = wcb['air_potential_temperature']

    # Plot the 3d trajectory positions
    plt.scatter(x[:, -n],
                y[:, -n],
                c=c[:, -n],
                vmin=300,
                vmax=340,
                cmap='coolwarm')

    # Plot the isentropic boundary
    x = rings['grid_longitude'] - 360
    y = rings['grid_latitude']
    plt.plot(x[:, -n], y[:, -n], color='r', linewidth=3)

    return
Beispiel #11
0
 def test_xaxis_labels_with_axes(self):
     import matplotlib.pyplot as plt
     fig = plt.figure()
     ax = fig.add_subplot(111)
     iplt.contour(self.cube, axes=ax, coords=('str_coord', 'bar'))
     plt.close(fig)
     self.assertPointsTickLabels('xaxis', ax)
Beispiel #12
0
def rotating_sequence(show_frames=True, save_frames=True, 
                      save_ani=False, show_ani=False,
                      ani_path='./puffer.mp4',
                      frames_basename='./puffer_frame_',
                      airtemp_cubes=None,
                      precip_cubes=None,
                      n_steps_round=20,
                      tilt_angle=21.7
                      ):
    plt.interactive(show_frames)
    figure = make_puffersphere_figure()
#    per_image_artists = []
    for (i_plt, lon_rotate) in enumerate(np.linspace(0.0, 360.0, n_steps_round, endpoint=False)):
        print 'rotate=', lon_rotate,' ...'
        axes = make_puffersphere_axes(
            projection_kwargs={'central_longitude': lon_rotate, 'central_latitude': tilt_angle})
        image = axes.stock_img()
        coast = axes.coastlines()
#        data = istk.global_pp()
        data = airtemp_cubes[i_plt]
        transparent_blue = (0.0, 0.0, 1.0, 0.25)
        transparent_red = (1.0, 0.0, 0.0, 0.25)
        cold_thresh = -10.0
        cold_fill = iplt.contourf(
              data,
              levels=[cold_thresh, cold_thresh],
              colors=[transparent_blue],
              extend='min')
        cold_contour = iplt.contour(
            data,
            levels=[cold_thresh], colors=['blue'],
            linestyles=['solid'])
        data = precip_cubes[i_plt]
        precip_thresh = 0.0001
        precip_fill = iplt.contourf(
            data,
            levels=[precip_thresh, precip_thresh],
            colors=[transparent_red],
            extend='max')
        precip_contour = iplt.contour(
            data,
            levels=[precip_thresh], colors=['red'],
            linestyles=['solid'])
        gridlines = draw_gridlines(n_meridians=6)
#        artists = []
#        artists += [coast]
#        artists += [image]
#        artists += cold_fill.collections
#        artists += precip_fill.collections
#        for gridline in gridlines:
#            artists += gridline
        if show_frames:
            plt.draw()
        if save_frames:
            save_path = frames_basename+str(i_plt)+'.png'
            save_figure_for_puffersphere(figure, save_path)
#        per_image_artists.append(artists)
        print '  ..done.'
Beispiel #13
0
def overview(cubes, areamask):
    theta_P = convert.calc('equivalent_potential_temperature',
                           cubes,
                           levels=('air_pressure', [75000]))[0]
    plot.contourf(theta_P[slices], np.linspace(280, 320, 17), extend='both')
    mask = theta_P.copy(data=areamask.astype(int))
    iplt.contour(mask[slices], [0.5], colors='k', linestyles='--')
    iplt.contour(theta_P[slices], [theta_front], colors='k')

    return
Beispiel #14
0
def pv_tracer(cubes, name, vmin=-2, vmax=2, cmap='coolwarm'):
    cube = convert.calc(name, cubes)
    epv = convert.calc('ertel_potential_vorticity', cubes)
    adv = convert.calc('advection_only_pv', cubes)

    plot.pcolormesh(cube, pv=epv, vmin=vmin, vmax=vmax, cmap=cmap)

    adv.data = np.abs(adv.data)
    iplt.contour(adv, [2], colors='k', linestyle='--')

    return
Beispiel #15
0
def cross_sections(tracers, theta, rh, z_bl, fig):
    # Plot each cube separately
    for n, cube in enumerate(tracers):
        row = n / ncols
        col = n - row * ncols
        ax = plt.subplot2grid((nrows, ncols), (row, col))

        # Interpolate along the cross section
        cube = cs_cube(cube, xs, xf, ys, yf)
        coords = ['grid_longitude', 'altitude']

        # Make the plot
        im = iplt.contourf(cube,
                           even_cscale(2),
                           coords=coords,
                           cmap='coolwarm',
                           extend='both')
        cs = iplt.contour(theta,
                          theta_levs,
                          coords=coords,
                          colors='k',
                          linewidths=2)
        iplt.plot(z_bl.coord('grid_longitude'), z_bl, color='y')
        iplt.contour(rh, [0.8], coords=coords, colors='w')
        iplt.contourf(rh, [0.8, 2],
                      coords=coords,
                      colors='None',
                      hatches=['.'])
        plt.title(second_analysis.all_diagnostics[cube.name()].symbol)

        if n == 0:
            plt.clabel(cs, fmt='%1.0f', colors='k')
        ax.set_ylim(0, 7)

        if n < 4:
            ax.set_xticks([])

    # Add letter labels to panels
    for n, ax in enumerate(fig.axes):
        multilabel(ax, n)

    # Add colorbar at bottom of figure
    cbar = plt.colorbar(im,
                        ax=fig.axes,
                        orientation='horizontal',
                        fraction=0.05,
                        spacing='proportional')
    cbar.set_label('PVU')
    cbar.set_ticks(np.linspace(-2, 2, 9))

    fig.text(0.075, 0.58, 'Height (km)', va='center', rotation='vertical')
    fig.text(0.5, 0.2, 'Grid Longitude', ha='center')
    return
Beispiel #16
0
def _add_pv2(**kwargs):
    # Plots the 2 PVU tropopause if contained in kwargs
    # Remove pv from kwargs
    if 'pv' in kwargs:
        pv = kwargs.pop('pv').copy()

        pv.convert_units('PVU')
        # Allow PV=2 to be plotted for both hemispheres
        pv.data = np.abs(pv.data)

        iplt.contour(pv, [2], colors='k', linewidths=2)

    return kwargs
Beispiel #17
0
def main(cubes, p_level):
    # Load data
    theta = convert.calc('air_potential_temperature',
                         cubes,
                         levels=('air_pressure', [p_level]))[0]

    # Calculate the fronts
    loc = fronts.main(theta)
    loc = theta.copy(data=loc)

    # Plot the output
    plot.pcolormesh(theta, vmin=280, vmax=320, cmap='plasma')
    plt.title(r'$\theta$ at ' + str(p_level) + ' Pa')
    iplt.contour(loc, [0], colors='k')
    plt.show()
Beispiel #18
0
def main(cubes):
    pv = convert.calc('air_potential_temperature',
                      cubes,
                      levels=('ertel_potential_vorticity', [2]))[0]

    theta = convert.calc('air_potential_temperature',
                         cubes,
                         levels=('air_pressure', [85000]))[0]

    plot.pcolormesh(theta, vmin=250, vmax=300)
    iplt.contour(pv, [300, 320], colors='k')

    plt.show()

    return
Beispiel #19
0
def main(cubes):
    mass = convert.calc('mass', cubes)
    water = convert.calc('mass_fraction_of_water', cubes)
    total_water = mass * water
    tcw = total_water.collapsed('atmosphere_hybrid_height_coordinate', SUM)

    mslp = convert.calc('air_pressure_at_sea_level', cubes)
    mslp.convert_units('hPa')

    plot.pcolormesh(tcw, vmin=0, vmax=5e9, cmap='Greys_r')
    iplt.contour(mslp, np.linspace(950, 1050, 11), colors='k', linewidths=2)

    plt.show()

    return
Beispiel #20
0
def bottom_level(tracers, mslp, fig, **kwargs):
    # Plot each cube separately
    for n, cube in enumerate(tracers):
        row = n / ncols
        col = n - row * ncols
        ax = plt.subplot2grid((nrows, ncols), (row, col))

        # Make the plot
        im = iplt.pcolormesh(cube[0], **kwargs)
        mslp.convert_units('hPa')
        cs = iplt.contour(mslp, plevs, colors='k', linewidths=2)
        plt.clabel(cs, fmt='%1.0f')
        add_map()
        plt.title(second_analysis.all_diagnostics[cube.name()].symbol)

        # Label the cross section points
        if n == 0:
            plt.plot([xs, xf], [ys, yf], '-kx')
            plt.text(xs, ys, 'A', fontsize=20)
            plt.text(xf, yf, 'B', fontsize=20)

    # Add letter labels to panels
    for n, ax in enumerate(fig.axes):
        multilabel(ax, n)

    # Add colorbar at bottom of figure
    cbar = plt.colorbar(im,
                        ax=fig.axes,
                        orientation='horizontal',
                        fraction=0.05)
    cbar.set_label('PVU')

    return
Beispiel #21
0
def contour(cube, *args, **kwargs):
    """
    Draws contour lines on a labelled plot based on the given Cube.

    With the basic call signature, contour "level" values are chosen
    automatically::

        contour(cube)

    Supply a number to use *N* automatically chosen levels::

        contour(cube, N)

    Supply a sequence *V* to use explicitly defined levels::

        contour(cube, V)

    See :func:`iris.plot.contour` for details of valid keyword arguments.

    """
    coords = kwargs.get('coords')
    axes = kwargs.get('axes')
    result = iplt.contour(cube, *args, **kwargs)
    _label_with_points(cube, coords=coords, axes=axes)
    return result
Beispiel #22
0
def contour(cube, *args, **kwargs):
    """
    Draws contour lines on a labelled plot based on the given Cube.

    With the basic call signature, contour "level" values are chosen
    automatically::

        contour(cube)

    Supply a number to use *N* automatically chosen levels::

        contour(cube, N)

    Supply a sequence *V* to use explicitly defined levels::

        contour(cube, V)

    See :func:`iris.plot.contour` for details of valid keyword arguments.

    """
    coords = kwargs.get('coords')
    axes = kwargs.get('axes')
    result = iplt.contour(cube, *args, **kwargs)
    _label_with_points(cube, coords=coords, axes=axes)
    return result
Beispiel #23
0
def animation_plot(i, pressure, wind, direction, step=24):
    """
    Function to update the animation frame.

    """
    # Clear figure to refresh colorbar
    plt.gcf().clf()

    ax = plt.axes(projection=ccrs.Mercator())
    ax.set_extent([-10.5, 3.8, 48.3, 60.5], crs=ccrs.Geodetic())

    contour_wind = iplt.contourf(wind[i][::10, ::10],
                                 cmap='YlGnBu',
                                 levels=range(0, 31, 5))
    contour_press = iplt.contour(pressure[i][::10, ::10],
                                 colors='white',
                                 linewidth=1.25,
                                 levels=range(938, 1064, 4))
    plt.clabel(contour_press, inline=1, fontsize=14, fmt='%i', colors='white')
    quiver_plot(wind[i], direction[i], step)
    plt.gca().coastlines(resolution='50m')

    time_points = pressure[i].coord('time').points
    time = str(pressure[i].coord('time').units.num2date(time_points)[0])
    plt.gca().set_title(time)

    colorbar = plt.colorbar(contour_wind)
    colorbar.ax.set_ylabel('Wind speed ({})'.format(str(wind[i].units)))
Beispiel #24
0
def zonalplt_colcont(mod_zmval,
                     obs_zmval,
                     clevs,
                     c_color,
                     title=None,
                     ylog=False,
                     ylimits=None):
    """ Create zonal plot with colors vs contours """

    cf = iplt.contourf(mod_zmval, clevs, colors=c_color)
    plot = plt.gca()
    if title:
        plot.set_title(title)
    else:
        plot.set_title('Colours-Model,Contour-Obs')

    if ylog:
        plot.set_yscale('log')  # convert Y to log
    if ylimits != None:
        plot.set_ylim(ylimits)  # reverse if required
    plot.set_ylabel('Height (hPa)', linespacing=0.5)
    cl = iplt.contour(obs_zmval,
                      clevs,
                      linewidths=1.0,
                      colors='black',
                      linestyles='-')
    plot.clabel(cl, inline=1, fmt='%1.2f', fontsize=8)

    colorbar = plt.colorbar(cf, orientation='vertical')
Beispiel #25
0
def animation_plot(i, pressure, wind, direction, step=24):
    """
    Function to update the animation frame.

    """
    # Clear figure to refresh colorbar
    plt.gcf().clf()

    ax = plt.axes(projection=ccrs.Mercator())
    ax.set_extent([-10.5, 3.8, 48.3, 60.5], crs=ccrs.Geodetic())

    contour_wind = iplt.contourf(wind[i][::10, ::10], cmap='YlGnBu',
                                 levels=range(0, 31, 5))
    contour_press = iplt.contour(pressure[i][::10, ::10], colors='white',
                                 linewidth=1.25, levels=range(938, 1064, 4))
    plt.clabel(contour_press, inline=1, fontsize=14, fmt='%i', colors='white')
    quiver_plot(wind[i], direction[i], step)
    plt.gca().coastlines(resolution='50m')

    time_points = pressure[i].coord('time').points
    time = str(pressure[i].coord('time').units.num2date(time_points)[0])
    plt.gca().set_title(time)

    colorbar = plt.colorbar(contour_wind)
    colorbar.ax.set_ylabel('Wind speed ({})'.format(str(wind[i].units)))
Beispiel #26
0
def plot_timehgt(cube, levels, title, log=False, ax1=None):
    """
    Plot fields as time-pressure.

    Routine to plot fields as time-pressure contours with given
    contour levels.
    Option to plot against log(pressure).
    """
    (colormap, normalisation) = cmap_and_norm('brewer_RdBu_11', levels)
    if ax1 is None:
        ax1 = plt.gca()
    ax1.set_title(title)
    iplt.contourf(cube, levels=levels, cmap=colormap, norm=normalisation)
    lwid = 1. * np.ones_like(levels)
    cl1 = iplt.contour(cube, colors='k', linewidths=lwid, levels=levels)
    plt.clabel(cl1, cl1.levels, inline=1, fontsize=6, fmt='%1.0f')
    ax1.set_xlabel('Year', fontsize='small')
    time_coord = cube.coord('time')
    new_epoch = time_coord.points[0]
    new_unit_str = 'hours since {}'
    new_unit = new_unit_str.format(time_coord.units.num2date(new_epoch))
    ax1.xaxis.axis_date()
    ax1.xaxis.set_label(new_unit)
    ax1.xaxis.set_major_locator(mdates.YearLocator(4))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
    ax1.set_ylabel('Pressure (Pa)', fontsize='small')
    ax1.set_ylim(100000., 10.)
    if log:
        ax1.set_yscale("log")
Beispiel #27
0
def PlumeandMet(workdir, metDir):

    times = ['201303060600']

    for time in times:
        filenames = glob.glob(workdir + '*' + time + '.txt')
        filename = filenames[0]
        attConstraint = iris.AttributeConstraint(Name='TotalAC')
        cube = iris.load_cube(filename, attConstraint)
        conc = cube

        filename = metDir + '*' + time + '.txt'
        precip = iris.load_cube(filename)

        colorscale = ('#ffffff', '#b4dcff', '#04fdff', '#00ff00', '#fdff00',
                      '#ffbd02', '#ff6a00', '#fe0000', '#0000FF', '#800080',
                      '#008000')

        # Set up axes
        ax = plt.axes(projection=ccrs.PlateCarree())
        ax.set_extent([-23, -13, 63, 67])

        # Set up country outlines
        countries = cfeature.NaturalEarthFeature(category='cultural',
                                                 name='admin_0_countries',
                                                 scale='10m',
                                                 facecolor='none')
        ax.add_feature(countries, edgecolor='black', zorder=2)

        # Set-up the gridlines
        gl = ax.gridlines(draw_labels=True, linewidth=0.8, alpha=0.9)

        gl.xlabels_top = False
        gl.ylabels_right = False
        gl.xlocator = mticker.FixedLocator(
            [-23, -22, -21, -20, -19, -18, -17, -16, -15, -14])
        gl.ylocator = mticker.FixedLocator([63, 64, 65, 66, 67])
        gl.xformatter = LONGITUDE_FORMATTER
        gl.yformatter = LATITUDE_FORMATTER

        # Plot
        cf1 = iplt.contourf(precip,
                            levels=[0.0, 0.01, 0.1, 1.0, 10],
                            colors=colorscale)

        cf = iplt.contour(conc,
                          levels=[
                              1e-9, 3.16e-8, 1e-8, 3.16e-7, 1e-7, 3.16e-6,
                              1e-6, 3.16e-5, 1e-5
                          ])

        cb = plt.colorbar(cf1, orientation='horizontal', shrink=0.9)
        cb.set_label(str(precip.units))
        plt.title(
            'Precipitation (coloured) and Air Concentration (contoured) \n' +
            time,
            fontsize=12)

        plt.show()
Beispiel #28
0
 def draw(self, cube):
     self.element = iplt.contour(cube,
                                 axes=self.axes,
                                 coords=self.coords,
                                 **self.kwargs)
     if 'levels' not in self.kwargs:
         self.kwargs['levels'] = self.element.levels
     return self.element
Beispiel #29
0
def main(cubes):
    pv = convert.calc('ertel_potential_vorticity', cubes, levels=levels)[0]
    adv = convert.calc('advection_only_pv', cubes, levels=levels)[0]
    for n, name in enumerate([
            'sum_of_physics_pv_tracers', 'epsilon',
            'dynamics_tracer_inconsistency', 'residual_pv'
    ]):
        cube = convert.calc(name, cubes, levels=levels)[0]

        m = n / 2
        ax = plt.subplot2grid((2, 2), (n - 2 * m, m))
        iplt.contourf(cube, clevs, cmap=cmap)
        add_map()
        iplt.contour(pv, [2], colors='k', linestyles='-')
        iplt.contour(adv, [2], colors='k', linestyles='-')

    plt.show()
Beispiel #30
0
def theta_anomaly(theta, lon, lat):
    """
    """
    theta_b = rossby_waves.nae_map(grid.get_datetime(theta)[0])
    theta_anomaly = theta.data - theta_b.data
    theta_anomaly = theta.copy(data=theta_anomaly)

    iplt.contourf(theta_anomaly, levels - 310, cmap='coolwarm', extend='both')
    cb = plt.colorbar(orientation='horizontal')
    cb.set_label('K')
    iplt.contour(theta_anomaly, [0], colors='k')
    plt.gca().coastlines()
    plt.title('(d)'.ljust(30) +
              r'$\theta^{\prime} (\lambda, \phi, q=2)$'.ljust(65))

    add_gridlines(lon, lat)

    return
Beispiel #31
0
def overlay_pressure(cubes,
                     levels=np.linspace(950, 1050, 11),
                     colors='k',
                     linewidths=2):
    mslp = convert.calc('air_pressure_at_sea_level', cubes)
    mslp.convert_units('hPa')
    cs = iplt.contour(mslp, levels, colors=colors, linewidths=linewidths)

    return cs
Beispiel #32
0
def main():
    fname = iris.sample_data_path("NAME_output.txt")

    boundary_volc_ash_constraint = iris.Constraint(
        "VOLCANIC_ASH_AIR_CONCENTRATION", flight_level="From FL000 - FL200")

    # Callback shown as None to illustrate where a cube-level callback function
    # would be used if required
    cube = iris.load_cube(fname, boundary_volc_ash_constraint, callback=None)

    # draw contour levels for the data (the top level is just a catch-all)
    levels = (0.0002, 0.002, 0.004, 1e10)
    cs = iplt.contourf(
        cube,
        levels=levels,
        colors=("#80ffff", "#939598", "#e00404"),
    )

    # draw a black outline at the lowest contour to highlight affected areas
    iplt.contour(cube, levels=(levels[0], 100), colors="black")

    # set an extent and a background image for the map
    ax = plt.gca()
    ax.set_extent((-90, 20, 20, 75))
    ax.stock_img("ne_shaded")

    # make a legend, with custom labels, for the coloured contour set
    artists, _ = cs.legend_elements()
    labels = [
        r"$%s < x \leq %s$" % (levels[0], levels[1]),
        r"$%s < x \leq %s$" % (levels[1], levels[2]),
        r"$x > %s$" % levels[2],
    ]
    ax.legend(artists,
              labels,
              title="Ash concentration / g m-3",
              loc="upper left")

    time = cube.coord("time")
    time_date = time.units.num2date(time.points[0]).strftime(UTC_format)
    plt.title("Volcanic ash concentration forecast\nvalid at %s" % time_date)

    iplt.show()
Beispiel #33
0
def add_gridlines(lon, lat):
    iplt.contour(lon,
                 np.linspace(-180, 180, 37),
                 colors='k',
                 linestyles=':',
                 linewidths=1)
    iplt.contour(lat,
                 np.linspace(-90, 90, 19),
                 colors='k',
                 linestyles=':',
                 linewidths=1)

    kwargs = {'va': 'center', 'ha': 'center', 'fontsize': 20}
    plt.text(2, -21, r'$0^{\circ}$', **kwargs)
    plt.text(-16, -21, r'$20^{\circ}$', **kwargs)
    plt.text(20, -21, r'$20^{\circ}$', **kwargs)

    plt.text(-35, 10, r'$50^{\circ}$', **kwargs)
    plt.text(-35, -2, r'$40^{\circ}$', **kwargs)
    plt.text(-35, -14, r'$30^{\circ}$', **kwargs)
Beispiel #34
0
def composite(cubes):
    lon, lat = grid.true_coords(cubes[0])
    theta_e = convert.calc('equivalent_potential_temperature', cubes)
    mslp = convert.calc('air_pressure_at_sea_level', cubes)
    mslp.convert_units('hPa')
    mass = convert.calc('mass', cubes)

    # Warm Sector
    warm_sector = theta_e.data > 300
    plim = mslp.data < 1000
    loc = np.logical_and(lon > -10, lon < 5)
    ws_mask = np.logical_and(np.logical_and(warm_sector, loc), plim)
    ws_mask = theta_e.copy(data=ws_mask)

    for n in range(20):
        c = (n + 1) / 20
        iplt.contour(ws_mask[n], linestyles=':', colors=[(c, c, c)])

    plt.show()
    return
Beispiel #35
0
    def test_simple(self):
        # First sub-plot
        plt.subplot(221)
        plt.title('Default')

        iplt.contourf(self.cube)

        map = iplt.gcm()
        map.drawcoastlines()

        # Second sub-plot
        plt.subplot(222)
        plt.title('Molleweide')

        iplt.map_setup(projection='moll', lon_0=120)
        iplt.contourf(self.cube)

        map = iplt.gcm()
        map.drawcoastlines()

        # Third sub-plot
        plt.subplot(223)
        plt.title('Native')

        iplt.map_setup(cube=self.cube)
        iplt.contourf(self.cube)

        map = iplt.gcm()
        map.drawcoastlines()

        # Fourth sub-plot
        plt.subplot(224)
        plt.title('Three/six level')

        iplt.contourf(self.cube, 3)
        iplt.contour(self.cube, 6)

        map = iplt.gcm()
        map.drawcoastlines()

        self.check_graphic()
Beispiel #36
0
def main(cubes, theta_value, **kwargs):
    """Plot PV on theta and the equivalent latitude circle

    Args:
        cubes (iris.cube.CubeList): Contains variables to calculate PV and
            potential temperature
    """
    pv = convert.calc('ertel_potential_vorticity', cubes,
                      levels=('air_potential_temperature', [theta_value]))[0]

    # Add equivalent latitude
    lon, lat = grid.true_coords(pv)
    lat = pv.copy(data=lat)
    time = grid.get_datetime(pv)[0]
    time = PDT(month=time.month, day=time.day, hour=time.hour)
    eqlat = rossby_waves.equivalent_latitude(time, theta_value, 2)

    # Plot PV on theta
    plot.pcolormesh(pv, pv=pv, **kwargs)
    iplt.contour(lat, [eqlat.data], colors='r', linewidths=2)
    plt.title('')
    plt.show()
def gravity_wave_drag(cubes, time=-1, level=47):

    for cube in cubes:
        if cube.long_name == 'change_over_time_in_air_temperature_due_to_gravity_wave_drag':
            drag = cube.copy()

    heights = np.round(drag.coord('level_height').points * 1e-03, 0)
    run_length = np.arange(0, drag.shape[0])
    # longitudes = drag.shape[3]
    # latitudes = drag.coord('latitude').points

    plt.figure(figsize=(12, 6))
    iplt.contour(drag[time, level, :, :],
                 brewer_redblu.N,
                 cmap=brewer_redblu,
                 norm=TwoSlopeNorm(0))
    ax = plt.gca()
    ax.gridlines(draw_labels=True)
    plt.title('Temp change due to gravity wave drag [K], month %s, h=%s km' %
              (run_length[time], heights[level]),
              y=1.2)
    plt.colorbar(pad=0.1)
    plt.show()
def make_plot(projection_name, projection_crs):

    # Create a matplotlib Figure.
    plt.figure()

    # Add a matplotlib Axes, specifying the required display projection.
    # NOTE: specifying 'projection' (a "cartopy.crs.Projection") makes the
    # resulting Axes a "cartopy.mpl.geoaxes.GeoAxes", which supports plotting
    # in different coordinate systems.
    ax = plt.axes(projection=projection_crs)

    # Set display limits to include a set region of latitude * longitude.
    # (Note: Cartopy-specific).
    ax.set_extent((-80.0, 20.0, 10.0, 80.0), crs=crs_latlon)

    # Add coastlines and meridians/parallels (Cartopy-specific).
    ax.coastlines(linewidth=0.75, color='navy')
    ax.gridlines(crs=crs_latlon, linestyle='-')

    # Plot the first dataset as a pseudocolour filled plot.
    maindata_filepath = iris.sample_data_path('rotated_pole.nc')
    main_data = iris.load_cube(maindata_filepath)
    # NOTE: iplt.pcolormesh calls "pyplot.pcolormesh", passing in a coordinate
    # system with the 'transform' keyword:  This enables the Axes (a cartopy
    # GeoAxes) to reproject the plot into the display projection.
    iplt.pcolormesh(main_data, cmap='RdBu_r')

    # Overplot the other dataset (which has a different grid), as contours.
    overlay_filepath = iris.sample_data_path('space_weather.nc')
    overlay_data = iris.load_cube(overlay_filepath, 'total electron content')
    # NOTE: as above, "iris.plot.contour" calls "pyplot.contour" with a
    # 'transform' keyword, enabling Cartopy reprojection.
    iplt.contour(overlay_data, 20,
                 linewidths=2.0, colors='darkgreen', linestyles='-')

    # Draw a margin line, some way in from the border of the 'main' data...
    # First calculate rectangle corners, 7% in from each corner of the data.
    x_coord, y_coord = main_data.coord(axis='x'), main_data.coord(axis='y')
    x_start, x_end = np.min(x_coord.points), np.max(x_coord.points)
    y_start, y_end = np.min(y_coord.points), np.max(y_coord.points)
    margin = 0.07
    margin_fractions = np.array([margin, 1.0 - margin])
    x_lower, x_upper = x_start + (x_end - x_start) * margin_fractions
    y_lower, y_upper = y_start + (y_end - y_start) * margin_fractions
    box_x_points = x_lower + (x_upper - x_lower) * np.array([0, 1, 1, 0, 0])
    box_y_points = y_lower + (y_upper - y_lower) * np.array([0, 0, 1, 1, 0])
    # Get the Iris coordinate sytem of the X coordinate (Y should be the same).
    cs_data1 = x_coord.coord_system
    # Construct an equivalent Cartopy coordinate reference system ("crs").
    crs_data1 = cs_data1.as_cartopy_crs()
    # Draw the rectangle in this crs, with matplotlib "pyplot.plot".
    # NOTE: the 'transform' keyword specifies a non-display coordinate system
    # for the plot points (as used by the "iris.plot" functions).
    plt.plot(box_x_points, box_y_points, transform=crs_data1,
             linewidth=2.0, color='white', linestyle='--')

    # Mark some particular places with a small circle and a name label...
    # Define some test points with latitude and longitude coordinates.
    city_data = [('London', 51.5072, 0.1275),
                 ('Halifax, NS', 44.67, -63.61),
                 ('Reykjavik', 64.1333, -21.9333)]
    # Place a single marker point and a text annotation at each place.
    for name, lat, lon in city_data:
        plt.plot(lon, lat, marker='o', markersize=7.0, markeredgewidth=2.5,
                 markerfacecolor='black', markeredgecolor='white',
                 transform=crs_latlon)
        # NOTE: the "plt.annotate call" does not have a "transform=" keyword,
        # so for this one we transform the coordinates with a Cartopy call.
        at_x, at_y = ax.projection.transform_point(lon, lat,
                                                   src_crs=crs_latlon)
        plt.annotate(
            name, xy=(at_x, at_y), xytext=(30, 20), textcoords='offset points',
            color='black', backgroundcolor='white', size='large',
            arrowprops=dict(arrowstyle='->', color='white', linewidth=2.5))

    # Add a title, and display.
    plt.title('A pseudocolour plot on the {} projection,\n'
              'with overlaid contours.'.format(projection_name))
    iplt.show()
Beispiel #39
0
 def test_xaxis_labels(self):
     iplt.contour(self.cube, coords=("str_coord", "bar"))
     self.assertPointsTickLabels("xaxis")
def main():

    lon_low= 60
    lon_high = 105
    lat_low = -10
    lat_high = 30


    first_of_year = datetime.date(2011, 01, 01)
    first_ordinal = first_of_year.toordinal()

    #pickle_name = 'pickle_daily_mean_*.p'
    pickle_name = 'pickle_model_mean_collapsed*.p'
    flist = glob.glob ('/home/pwille/python_scripts/*/%s' % pickle_name)


    for i in flist:

        fname = str(i)

        experiment_id = fname.split('/')[4]
        if not os.path.exists('/home/pwille/python_scripts/pngs/%s' % (experiment_id)): os.makedirs('/home/pwille/python_scripts/pngs/%s' % (experiment_id))
      
       #daily_mean = pickle.load( open( "/home/pwille/python_scripts/%s/pickle_daily_mean_%s.p" % (experiment_id, experiment_id), "rb" ) )
        model_mean = pickle.load( open( "%s" % (fname), "rb" ) ) 
        for sub_cube in model_mean.slices(['grid_latitude', 'grid_longitude']):
            
      #Get date in iso format for title, if needed
      
            #day=sub_cube_daily.coord('dayyear')
            #day_number = day.points[0]
            #day_number_ordinal=first_ordinal-1 + day_number
            #date_print = datetime.date.fromordinal(day_number_ordinal)
            #date_iso = str(date_print.isoformat())

            sub_cube.units = 'hPa'
            sub_cube /= 100

            #local_min, local_max = extrema(sub_cube, mode='wrap', window=50)
            


            # Load a colour palette.
            cmap = mpl_cm.get_cmap('gist_rainbow')   
        
            # Set contour levels
            #clevs = np.arange(1002.,1016.,10.)

           
            sub_cube.coord('grid_latitude').guess_bounds()
            sub_cube.coord('grid_longitude').guess_bounds()

            ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low,lat_high))
            contour = iplt.contour(sub_cube, 16, colors='k',linewidths=1.)
            #iplt.contourf(sub_cube, 16, cmap=cmap)
            #plt.title('Daily Mean Sea Level Pressure: %s model run. %s' % (experiment_id, date_iso), fontsize=12)
            plt.title('Model Mean Sea Level Pressure: %s model run.' % (experiment_id), fontsize=12)
            dx, dy = 10, 10
                     
            plt.clabel(contour, fmt='%d')
            ax.stock_img()
            ax.coastlines(resolution='110m', color='gray') 
            
          
            gl = ax.gridlines(draw_labels=True,linewidth=1, color='gray', alpha=0.5, linestyle='--')
            gl.xlabels_top = False
            gl.ylabels_right = False
            #gl.xlines = False
            gl.xlocator = mticker.FixedLocator(range(60,105+dx,dx))
            gl.ylocator = mticker.FixedLocator(range(-10,30+dy,dx))
            gl.xformatter = LONGITUDE_FORMATTER
            gl.yformatter = LATITUDE_FORMATTER
            #gl.xlabel_style = {'size': 15, 'color': 'gray'}
            #gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
            #plt.savefig('/home/pwille/python_scripts/pngs/%s/msl_daily_mean_%s_%s.png' % (experiment_id, experiment_id, date_iso))
            #plt.stock_img()
            plt.savefig('/home/pwille/python_scripts/pngs/%s/msl_model_mean_%s.png' % (experiment_id, experiment_id))
            #plt.show()
            plt.close()
def main():
  
 
#experiment_ids = ['djznw', 'djzny', 'djznq', 'djzns', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkbhu', 'djznu', 'dkhgu' ] # All 12
 #experiment_ids = ['djzny', 'djzns', 'djznw', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq' ] 
 #experiment_ids = ['djzny', 'djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['djzns', 'djznu', 'dkbhu', 'dkjxq', 'dklyu', 'dkmbq', 'dklwu', 'dklzq', 'dkhgu'] 
 #experiment_ids = ['dklzq', 'dkmbq', 'dkjxq', 'dklwu', 'dklyu', 'djzns']
#experiment_ids = ['djzns' ] 
 #experiment_ids = ['dkhgu','dkjxq']
 
    for p_level in plot_levels:

        # Set pressure height contour min/max
        if p_level == 925:
            clevgh_min = -24.
            clevgh_max = 24.
        elif p_level == 850:
            clevgh_min = -24.
            clev_max = 24.
        elif p_level == 700:
            clevgh_min = -24.
            clev_max = 24.
        elif p_level == 500:
            clevgh_min = -24.
            clevgh_max = 24.
        else:
            print 'Contour min/max not set for this pressure level'

# Set potential temperature min/max       
        if p_level == 925:
            clevpt_min = -3.
            clevpt_max = 100.
        elif p_level == 850:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p_level == 700:
            clevpt_min = -3.
            clevpt_max = 3.
        elif p_level == 500:
            clevpt_min = -3.
            clevpt_max = 3.
        else:
            print 'Potential temperature min/max not set for this pressure level'

 # Set specific humidity min/max       
        if p_level == 925:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 850:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 700:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        elif p_level == 500:
            clevsh_min = -0.0025
            clevsh_max = 0.0025
        else:
            print 'Specific humidity min/max not set for this pressure level'

        clevs_lin = np.linspace(clevgh_min, clevgh_max, num=24)

        

        p_level_constraint = iris.Constraint(pressure=p_level)

        height_pp_diff = '%s_408_on_p_levs_mean_by_hour.pp' % difference_id
        height_pfile_diff = '%s%s/%s/%s' % (pp_file_path, diffidmin1, difference_id, height_pp_diff)
        height_cube_diff = iris.load_cube(height_pfile_diff, p_level_constraint)

       

        for plot_diag in plot_diags:
        
            pp_file_diff = '%s_%s_on_p_levs_mean_by_hour.pp' % (difference_id, plot_diag)
            pfile_diff = '%s%s/%s/%s' % (pp_file_path, diffidmin1, difference_id, pp_file_diff)

            cube_diff = iris.load_cube(pfile_diff, p_level_constraint )

            for experiment_id in experiment_ids:
            
                expmin1 = experiment_id[:-1]

                pp_file = '%s_%s_on_p_levs_mean_by_hour.pp' % (experiment_id, plot_diag)
                pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, pp_file)
                pcube = iris.load_cube(pfile, p_level_constraint)
                #cube=iris.analysis.maths.multiply(pcube,3600)
                # For each hour in cube

                height_pp_file = '%s_408_on_p_levs_mean_by_hour.pp' % (experiment_id)
                height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, height_pp_file)
                height_cube = iris.load_cube(height_pfile, p_level_constraint)

                #time_coords = cube_f.coord('time')
                add_hour_of_day(pcube, pcube.coord('time'))
                add_hour_of_day(cube_diff, cube_diff.coord('time'))
                add_hour_of_day(height_cube, height_cube.coord('time'))
                add_hour_of_day(height_cube_diff, height_cube_diff.coord('time'))

                #pcube.remove_coord('time')
                #cube_diff.remove_coord('time')
                #height_cube.remove_coord('time')
                #height_cube_diff.remove_coord('time')

                #p_cube_difference = iris.analysis.maths.subtract(pcube, cube_diff, dim='hour')
                #height_cube_difference = iris.analysis.maths.subtract(height_cube, height_cube_diff, dim='hour')
                
                #pdb.set_trace()

                #del height_cube, pcube, height_cube_diff, cube_diff

                for t, time_cube in enumerate(pcube.slices(['grid_latitude', 'grid_longitude'])):
    

                    #pdb.set_trace()

                    cube_diff_slice = cube_diff.extract(iris.Constraint(hour=time_cube.coord('hour').points))
                
                    p_cube_difference = time_cube - cube_diff_slice
                    
                    #pdb.set_trace()
                
                    print time_cube
                    time_cube_408 = height_cube.extract(iris.Constraint(hour=time_cube.coord('hour').points))
                    height_cube_diff_slice = height_cube_diff.extract(iris.Constraint(hour=time_cube.coord('hour').points))
                    
                    height_cube_difference = time_cube_408 - height_cube_diff_slice
                    # Get  time of averagesfor plot title
  

                    h = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).strftime('%H%M')


                    #Convert to India time

                    from_zone = tz.gettz('UTC')
                    to_zone = tz.gettz('Asia/Kolkata')
                    
                    h_utc = u.num2date(np.array(time_cube.coord('hour').points, dtype=float)[0]).replace(tzinfo=from_zone)
                   
                    h_local = h_utc.astimezone(to_zone).strftime('%H%M')
                
                    fig = plt.figure(**figprops)
         
                    cmap=plt.cm.RdBu_r
                    
                    ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
                    
                    m =\
                        Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229)
                    #pdb.set_trace()
                    lat = p_cube_difference.coord('grid_latitude').points
                    lon = p_cube_difference.coord('grid_longitude').points
                    
                    cs = p_cube_difference.coord_system('CoordSystem')
                    
                    lons, lats = np.meshgrid(lon, lat) 
                    lons, lats = iris.analysis.cartography.unrotate_pole\
                                (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
                    
                    
                    x,y = m(lons,lats)
                    
                    
                    if plot_diag=='temp':
                        min_contour = clevpt_min
                        max_contour = clevpt_max
                        cb_label='K' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\
                                          and wind (vectors) %s UTC    %s IST' % (h, h_local)
                        tick_interval=1
                    elif plot_diag=='sp_hum':
                        min_contour = clevsh_min
                        max_contour = clevsh_max 
                        cb_label='kg/kg' 
                        main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\
                                         and wind (vectors) %s-%s UTC    %s-%s IST' % (h, h_local)
                        tick_interval=0.0005
                        
                    clevs = np.linspace(min_contour, max_contour, 32)
                    clevs = np.linspace(-3, 3, 32)
                    cont = plt.contourf(x,y,p_cube_difference.data, clevs, cmap=cmap, extend='both')
                    
                    
                    #cont = iplt.contourf(time_cube, cmap=cmap, extend='both')
                    

                    cs_lin = iplt.contour(height_cube_difference, clevs_lin,colors='#262626',linewidths=1.)
                    plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black')
                    
                    #del time_cube
                     
                    #plt.clabel(cont, fmt='%d')
                    #ax.stock_img()
                    ax.coastlines(resolution='110m', color='#262626') 
                     
                    gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
                    gl.xlabels_top = False
                    gl.ylabels_right = False
                    #gl.xlines = False
                    dx, dy = 10, 10

                    gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
                    gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
                    gl.xformatter = LONGITUDE_FORMATTER
                    gl.yformatter = LATITUDE_FORMATTER
                    
                    gl.xlabel_style = {'size': 12, 'color':'#262626'}
                    #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
                    gl.ylabel_style = {'size': 12, 'color':'#262626'}         
                    
                    cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
                    cbar.set_label('%s' % cb_label, fontsize=10, color='#262626') 
                    #cbar.set_label(time_cube.units, fontsize=10, color='#262626')
                    cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    cbar.set_ticklabels(['${%.1f}$' % i for i in ticks])
                    
                    cbar.ax.tick_params(labelsize=10, color='#262626')
                    
                    
                    #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local)
                    #main_title=time_cube.standard_name.title().replace('_',' ')
                    #model_info = re.sub(r'[(\']', ' ', model_info)
                    #model_info = re.sub(r'[\',)]', ' ', model_info)
                    #print model_info
                    
                    file_save_name = '%s_%s_%s_diff_from_%s_%s' % (experiment_id, plot_diag, p_level, difference_id, h)
                    save_dir = '%s%s/%s' % (save_path, experiment_id, plot_diag)
                    if not os.path.exists('%s' % save_dir): os.makedirs('%s' % (save_dir))
                    
                    #plt.show()

                    fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
                    
                    
                    plt.title('%s UTC %s IST' % (h, h_local))
                    fig.savefig('%s/%s_short_title.png' % (save_dir, file_save_name) , format='png', bbox_inches='tight')
                    
                    
                    model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
                    plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)               
                    fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
 
                    fig.clf()
                    plt.close()
                    #del time_cube
                    gc.collect()
density_cube.standard_name = 'sea_water_density'
density_cube.units = 'kg m-3'

density_cube.data = seawater.dens(salinity_cube.data,temperature_cube.data,1)
density_cube_meridional = density_cube.collapsed('longitude',MEAN)

maps=[m for m in cm.datad if not m.endswith("_r")]

#figure()
#quickplot.contourf(density_cube_meridional, 30,cmap=get_cmap(maps[14])) 
#CS = quickplot.contour(density_cube_meridional,[1028.0,1027.9,1027.75,1027.5,1027.0,1026.5,1026.0],colors='k',linewideths=30)
#clabel(CS, fontsize=9, inline=1)
#savefig('/home/ph290/Documents/figures/isopycnals.pdf')

fig = figure()
ax = iplt.contourf(density_cube_meridional, numpy.linspace(1026.0,1028,50),cmap=get_cmap(maps[14]))
cbar = colorbar(ax)
cbar.formatter.set_useOffset(False)
cbar.set_label('kg m$^{-3}$')

xlim(-80,-40)
ylim(3000,0)
CS = iplt.contour(density_cube_meridional,[1028.0,1027.9,1027.75,1027.5,1027.0,1026.5,1026.0],colors='k',linewideths=30)
clabel(CS, fontsize=9, inline=1)

#show()
savefig('/home/ph290/Documents/figures/isopycnals_b.pdf',transparent = True)


#plt.show()
def main():
 
    for p_level in plot_levels:

        # Set pressure height contour min/max
        if p_level == 925:
            clev_min = 660.
            clev_max = 810.
        elif p_level == 850:
            clev_min = 1435.
            clev_max = 1530.
        elif p_level == 700:
            clev_min = 3090.
            clev_max = 3155.
        elif p_level == 500:
            clev_min = 5800.
            clev_max = 5890.
        else:
            print 'Contour min/max not set for this pressure level'

       

        #clevs_col = np.arange(clev_min, clev_max)
        clevs_lin = np.arange(clev_min, clev_max, 5)    

        p_level_constraint = iris.Constraint(pressure=p_level)      

        #for plot_diag in plot_diags:    

        for experiment_id in experiment_ids:
            
                expmin1 = experiment_id[:-1]
                pfile = '/nfs/a90/eepdw/Data/EMBRACE/%s/%s/%s_%s.pp' % (expmin1, experiment_id, experiment_id, pp_file_contourf)

                #pc =  iris(pfile)
                pcube_contourf = iris.load_cube(pfile)
                pcube_contourf=iris.analysis.maths.multiply(pcube_contourf,3600)


                height_pp_file = '%s_%s_on_p_levs_mean_by_date_range.pp' % (experiment_id, pp_file_contour)
                height_pfile = '%s%s/%s/%s' % (pp_file_path, expmin1, experiment_id, height_pp_file)
                pcube_contour = iris.load_cube(height_pfile, p_level_constraint)
                

                time_coords = pcube_contourf.coord('time')
                iris.coord_categorisation.add_day_of_year(pcube_contourf, time_coords, name='day_of_year')

                time_coords = pcube_contour.coord('time')
                iris.coord_categorisation.add_day_of_year(pcube_contour, time_coords, name='day_of_year')


                for t, time_cube in enumerate(pcube_contourf.slices(['grid_latitude', 'grid_longitude'])):
                                   
                    #height_cube_slice = pcube_contour.extract(iris.Constraint(day_of_year=time_cube.coord('day_of_year').points))
                    height_cube_slice = pcube_contour[t]

                    #pdb.set_trace()
                    
                    # Get  time of averagesfor plot title
  

                    h = u.num2date(np.array(time_cube.coord('time').points, dtype=float)[0]).strftime('%d%b')

                    #Convert to India time

                    from_zone = tz.gettz('UTC')
                    to_zone = tz.gettz('Asia/Kolkata')
                    
                    h_utc = u.num2date(np.array(time_cube.coord('day_of_year').points, dtype=float)[0]).replace(tzinfo=from_zone)
                   
                    h_local = h_utc.astimezone(to_zone).strftime('%H%M')
                
                    fig = plt.figure(**figprops)
         
                    #cmap=plt.cm.RdBu_r
                    
                    ax = plt.axes(projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low+degs_crop_bottom,lat_high-degs_crop_top))
                    
                    m =\
                        Basemap(llcrnrlon=lon_low,llcrnrlat=lat_low,urcrnrlon=lon_high,urcrnrlat=lat_high, rsphere = 6371229)
                    # #pdb.set_trace()
                    # lat = pcube_contourf.coord('grid_latitude').points
                    # lon = pcube_contourf.coord('grid_longitude').points
                    
                    # cs = cube.coord_system('CoordSystem')
                    
                    # lons, lats = np.meshgrid(lon, lat) 
                    # lons, lats = iris.analysis.cartography.unrotate_pole\
                    #             (lons,lats, cs.grid_north_pole_longitude, cs.grid_north_pole_latitude)
                    
                    
                    # x,y = m(lons,lats)
                    
                    
                    # if plot_diag=='temp':
                    #     min_contour = clevpt_min
                    #     max_contour = clevpt_max
                    #     cb_label='K' 
                    #     main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), potential temperature (colours),\
                    #                       and wind (vectors) %s UTC    %s IST' % (h, h_local)
                    #     tick_interval=2
                    #     clev_number=max_contour-min_contour+1
                    # elif plot_diag=='sp_hum':
                    #     min_contour = clevsh_min
                    #     max_contour = clevsh_max 
                    #     cb_label='kg/kg' 
                    #     main_title='8km  Explicit model (dklyu) minus 8km parametrised model geopotential height (grey contours), specific humidity (colours),\
                    #                      and wind (vectors) %s UTC    %s IST' % (h, h_local)
                    #     tick_interval=0.002
                    #     clev_number=max_contour-min_contour+0.001

                    # clevs = np.linspace(min_contour, max_contour, clev_number)
                    # #clevs = np.linspace(-3, 3, 32)
                    # cont = plt.contourf(x,y,time_cube.data, clevs, cmap=cmap, extend='both')
                    
                    
                    cont = iplt.contourf(time_cube, clevs, cmap=cmap, extend='both')
                    
                    #pdb.set_trace()
                    cs_lin = iplt.contour(height_cube_slice, clevs_lin,colors='#262626',linewidths=1.)
                    plt.clabel(cs_lin, fontsize=14, fmt='%d', color='black')
                    
                    #del time_cube
                     
                    #plt.clabel(cont, fmt='%d')
                    #ax.stock_img()
                    ax.coastlines(resolution='110m', color='#262626') 
                     
                    gl = ax.gridlines(draw_labels=True,linewidth=0.5, color='#262626', alpha=0.5, linestyle='--')
                    gl.xlabels_top = False
                    gl.ylabels_right = False
                    #gl.xlines = False
                    dx, dy = 10, 10

                    gl.xlocator = mticker.FixedLocator(range(int(lon_low_tick),int(lon_high_tick)+dx,dx))
                    gl.ylocator = mticker.FixedLocator(range(int(lat_low_tick),int(lat_high_tick)+dy,dy))
                    gl.xformatter = LONGITUDE_FORMATTER
                    gl.yformatter = LATITUDE_FORMATTER
                    
                    gl.xlabel_style = {'size': 12, 'color':'#262626'}
                    #gl.xlabel_style = {'color': '#262626', 'weight': 'bold'}
                    gl.ylabel_style = {'size': 12, 'color':'#262626'}         
                    
                    # cbar = fig.colorbar(cont, orientation='horizontal', pad=0.05, extend='both')
                    # cbar.set_label('%s' % cb_label, fontsize=10, color='#262626') 
                    # #cbar.set_label(time_cube.units, fontsize=10, color='#262626')
                    # cbar.set_ticks(np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    # ticks = (np.arange(min_contour, max_contour+tick_interval,tick_interval))
                    # cbar.set_ticklabels(['${%.1f}$' % i for i in ticks])
                    
                    # cbar.ax.tick_params(labelsize=10, color='#262626')
                    
                    
                    #main_title='Mean Rainfall for EMBRACE Period -%s UTC (%s IST)' % (h, h_local)
                    #main_title=time_cube.standard_name.title().replace('_',' ')
                    #model_info = re.sub(r'[(\']', ' ', model_info)
                    #model_info = re.sub(r'[\',)]', ' ', model_info)
                    #print model_info
                    
                    file_save_name = '%s_%s_and_%s_%s_hPa_and_geop_height_%s' % (experiment_id, pp_file_contour, pp_file_contourf, p_level, h)
                    save_dir = '%s%s/%s_and_%s' % (save_path, experiment_id, pp_file_contour, pp_file_contourf)
                    if not os.path.exists('%s' % save_dir): os.makedirs('%s' % (save_dir))
                    
                    #plt.show()

                    #fig.savefig('%s/%s_notitle.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
                    
                    
                    plt.title('%s UTC' % (h))
                    fig.savefig('%s/%s_short_title.png' % (save_dir, file_save_name) , format='png', bbox_inches='tight')
                    
                    
                    #model_info=re.sub('(.{68} )', '\\1\n', str(model_name_convert_title.main(experiment_id)), 0, re.DOTALL)
                    #plt.title('\n'.join(wrap('%s\n%s' % (main_title, model_info), 1000,replace_whitespace=False)), fontsize=16)               
                    #fig.savefig('%s/%s.png' % (save_dir, file_save_name), format='png', bbox_inches='tight')
 
                    fig.clf()
                    plt.close()
                    #del time_cube
                    gc.collect()
Beispiel #44
0
 def test_xaxis_labels(self):
     iplt.contour(self.cube, coords=('str_coord', 'bar'))
     self.assertPointsTickLabels('xaxis')
#We can use the above, and the python package 'seawater' to calculate seawaters density for us 

density_cube = temperature_cube.copy()
#first we need to make a new cube to hold the density data when we calculate it. This is what we do here. 

#we also want to give that cube the right metadata
density_cube.standard_name = 'sea_water_density'
density_cube.units = 'kg m-3'

density_cube.data = seawater.dens(salinity_cube.data,temperature_cube.data,1)
density_atlantic = density_cube.extract(atlantic_region2)
density_atlantic_meridional = density_atlantic.collapsed('longitude',MEAN)

figure()
qplt.contourf(cfc_atlantic_meridional,linspace(0,300,50))
CS=iplt.contour(density_atlantic_meridional,array([1026.2,1026.4,1027.6,1026.8,1027.0,1027.2,1027.3,1027.4,1027.5,1027.6,1027.7,1027.8]),colors='gray')
clabel(CS, fontsize=12, inline=1)
savefig('/home/ph290/Documents/figures/atl_meridional_cfc_density.png')
show()


'''
And how might we do some future analysis?
'''

model_future_temperature_file = '/home/ph290/Documents/teaching/canesm2_potential_temperature_rcp85_regridded.nc'

future_temperature_cube = load_cube(model_future_temperature_file)

#just do this to make sure that the cube has teh right metadata
if not future_temperature_cube.coord('latitude').has_bounds():
def main():

    lon_low= 60
    lon_high = 105
    lat_low = -10
    lat_high = 30

    first_of_year = datetime.date(2011, 01, 01)
    first_ordinal = first_of_year.toordinal()

    j=1
    #pickle_name = 'pickle_daily_mean_*.p'
    pickle_name = 'pickle_model_mean_collapsed_*.p'
    flist = glob.glob ('/home/pwille/python_scripts/*/%s' % pickle_name)


    plt.figure(figsize=(30, 15))
    #plt.gcf().subplots_adjust(hspace=0.05, wspace=0.05, top=0.95, bottom=0.05, left=0.075, right=0.925)

    plt.gcf().subplots_adjust(top=0.5)

    plt.suptitle('Mean sea level pressure of model runs (average of entire model run)')
    for i in flist:

        fname = str(i)
        
        experiment_id = fname.split('/')[4]
        if not os.path.exists('/home/pwille/python_scripts/pngs/%s' % (experiment_id)): os.makedirs('/home/pwille/python_scripts/pngs/%s' % (experiment_id))
      
  #daily_mean = pickle.load( open( "/home/pwille/python_scripts/%s/pickle_daily_mean_%s.p" % (experiment_id, experiment_id), "rb" ) )
        model_mean = pickle.load( open( "%s" % (fname), "rb" ) )
        #print model_mean
       
        for sub_cube in model_mean.slices(['grid_latitude', 'grid_longitude']):
            
      #Get date in iso format for title, if needed
      
            #day=sub_cube_daily.coord('dayyear')
            #day_number = day.points[0]
            #day_number_ordinal=first_ordinal-1 + day_number
            #date_print = datetime.date.fromordinal(day_number_ordinal)
            #date_iso = str(date_print.isoformat())

            sub_cube.units = 'hPa'
            sub_cube /= 100


 # Load a Cynthia Brewer palette.
            brewer_cmap = mpl_cm.get_cmap('Spectral')   
        #contour = qplt.contour(sub_cube_daily, brewer_cmap.N, cmap=brewer_cmap)
           

            clevs = np.arange(996,1016)
            
            sub_cube.coord('grid_latitude').guess_bounds()
            sub_cube.coord('grid_longitude').guess_bounds()
            print j
            plt.subplot(2, 4, j, projection=ccrs.PlateCarree(), extent=(lon_low,lon_high,lat_low,lat_high))
            #plt.subplot(4, 2, j, projection=ccrs.PlateCarree())
            j+=1

            contour = iplt.contour(sub_cube, clevs, colors='k',linewidths=0.5)
            #iplt.contourf(sub_cube, 16, cmap=brewer_cmap)
            #plt.title('Daily Mean Sea Level Pressure: %s model run. %s' % (experiment_id, date_iso), fontsize=12)
            plt.title('%s' % (experiment_id), fontsize=8)
            dx, dy = 10, 10
           
                      
            plt.clabel(contour, fmt='%d', inline=1, fontsize=8)
           
            plt.gca().coastlines(resolution='110m', color='gray') 
            plt.gca().stock_img()
            
            gl = plt.gca().gridlines(draw_labels=True,linewidth=1, color='gray', alpha=0.5, linestyle='--')
            gl.xlabels_top = False
            gl.ylabels_right = False
            #gl.xlines = False
            gl.xlocator = mticker.FixedLocator(range(60,105+dx,dx))
            gl.ylocator = mticker.FixedLocator(range(-10,30+dy,dx))
            gl.xformatter = LONGITUDE_FORMATTER
            gl.yformatter = LATITUDE_FORMATTER
            gl.xlabel_style = {'size': 8, 'color': 'gray'}
            #gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
            gl.ylabel_style = {'size': 8, 'color': 'gray'}
            #gl.xlabel_style = {'color': 'red', 'weight': 'bold'}
           
            #plt.savefig('/home/pwille/python_scripts/pngs/%s/msl_model_mean_%s.png' % (experiment_id, experiment_id))
#    plt.subplots_adjust(top=0.9, bottom=0.1, hspace=0.2)
    plt.tight_layout()
    plt.subplots_adjust(top=0.9, wspace=0.2, hspace=0.2)
#plt.show()
    plt.savefig('/home/pwille/python_scripts/pngs/msl_model_mean_ensemble.png')
    plt.close()          
Beispiel #47
0
 def draw(self, cube):
     self.element = iplt.contour(cube, axes=self.axes, coords=self.coords,
                                 extend='both', **self.kwargs)
     if 'levels' not in self.kwargs:
         self.kwargs['levels'] = self.element.levels
     return self.element
Beispiel #48
0
def custom_contour(*args, **kwargs):
    result = iplt.contour(*args, colors='white')
    plt.clabel(result, inline=1, fontsize=14, fmt='%i', colors='white')
    ax = plt.gca()
    ax.stock_img()
    ax.coastlines(resolution='50m')
Beispiel #49
0
 def test_simple(self):
     iplt.contour(self.cube)
     self.check_graphic()
Beispiel #50
0
 def draw(self, cube):
     self.element = iplt.contour(cube, axes=self.axes, coords=self.coords,
                                 **self.kwargs)
     return self.element