示例#1
0
def test_plot_create_map():

    # Read bathy
    f = cdms2.open(NCFILE_MANGA0)
    bathy = -f('H0')
    f.close()
    alon = bathy.getLongitude()
    alat = bathy.getLatitude()
    lon = (alon[:].min(), alon[:].max())
    lat = (alat[:].min(), alat[:].max())

    # 2D maps
    # - simple
    m = create_map(lon, lat)
    P.savefig(func_name() + '.2d.simple.png', title="2D / simple")
    P.close()
    # - bathy
    m = create_map(lon, lat, bathy=bathy, title="2D / bathy")
    P.savefig(func_name() + '.2d.bathy.png')
    P.close()

    # 3D maps
    # - simple
    m = create_map(lon, lat, level=-200, title="3D / simple")
    P.savefig(func_name() + '.3d.simple.png')
    P.close()
    # - bathy
    m = create_map(lon,
                   lat,
                   axes="3d",
                   bathy=bathy,
                   level=-200,
                   title="3D / bathy")
    P.savefig(func_name() + '.3d.bathy.png')
    P.close()
def plot(xx,
         yy,
         target,
         label,
         figfiles,
         figfile,
         lon=None,
         lat=None,
         show=False):
    xs, ys, mask = coord2slice(target, lon=lon, lat=lat)
    P.figure(figsize=(6, 3.5))
    P.title('Target=%(label)s / select: lon=%(lon)s, lat=%(lat)s' % locals())
    add_grid((xx, yy))
    xx = xx.asma()
    yy = yy.asma()
    if isinstance(lon, tuple):
        P.axvline(lon[0], color='m', ls='--', lw=2)
        P.axvline(lon[1], color='m', ls='--', lw=2)
    elif isinstance(lon, slice):
        i, j, k = lon.indices(xx.shape[1])
        P.plot(xx[:, i], yy[:, i], 'c--', lw=2)
        P.plot(xx[:, j - 1], yy[:, j - 1], 'c--', lw=2)
    if isinstance(lat, tuple):
        P.axhline(lat[0], color='m', ls='--', lw=2)
        P.axhline(lat[1], color='m', ls='--', lw=2)
    elif isinstance(lat, slice):
        i, j, k = lat.indices(yy.shape[0])
        P.plot(xx[i], yy[i], 'c--', lw=2)
        P.plot(xx[j - 1], yy[j - 1], 'c--', lw=2)
    P.xticks(N.arange(xx.min() - 1, xx.max() + 1))
    P.yticks(N.arange(yy.min() - 1, yy.max() + 1))
    xxi, yyi = xx, yy
    xx = xx[ys, xs]
    yy = yy[ys, xs]
    #    mask = mask[ys, xs]
    xxb, yyb = meshbounds(xx, yy)
    P.pcolormesh(xxb, yyb, mask, shading='faceted')
    P.scatter(xx.ravel(), yy.ravel(), c=(0, 1, 0))
    P.grid(True)
    P.axis('image')
    P.tight_layout()
    i = len(figfiles)
    savefig = figfile % i
    if os.path.exists(savefig): os.remove(savefig)
    P.savefig(savefig)
    figfiles.append(savefig)
    if show: P.show()
    else: P.close()
def plot(xx, yy, target, label, figfiles, figfile, lon=None, lat=None, show=False):
    xs, ys, mask = coord2slice(target, lon=lon, lat=lat)
    P.figure(figsize=(6, 3.5))
    P.title('Target=%(label)s / select: lon=%(lon)s, lat=%(lat)s'%locals())
    add_grid((xx, yy))
    xx = xx.asma()
    yy = yy.asma()
    if isinstance(lon, tuple): 
        P.axvline(lon[0], color='m', ls='--', lw=2)
        P.axvline(lon[1], color='m', ls='--', lw=2)
    elif isinstance(lon, slice):
        i, j, k = lon.indices(xx.shape[1])
        P.plot(xx[:, i], yy[:, i], 'c--', lw=2)
        P.plot(xx[:, j-1], yy[:, j-1], 'c--', lw=2)
    if isinstance(lat, tuple): 
        P.axhline(lat[0], color='m', ls='--', lw=2)
        P.axhline(lat[1], color='m', ls='--', lw=2)
    elif isinstance(lat, slice):
        i, j, k = lat.indices(yy.shape[0])
        P.plot(xx[i], yy[i], 'c--', lw=2)
        P.plot(xx[j-1], yy[j-1], 'c--', lw=2)
    P.xticks(N.arange(xx.min()-1, xx.max()+1))
    P.yticks(N.arange(yy.min()-1, yy.max()+1))
    xxi, yyi = xx, yy
    xx = xx[ys, xs]
    yy = yy[ys, xs]
#    mask = mask[ys, xs]
    xxb, yyb = meshbounds(xx, yy)
    P.pcolor(xxb, yyb, mask, shading='faceted')
    P.scatter(xx.ravel(), yy.ravel(), c=(0, 1, 0))
    P.grid('on')
    P.axis('image')
    P.tight_layout()
    i = len(figfiles)
    savefig = figfile%i
    if os.path.exists(savefig): os.remove(savefig)
    P.savefig(savefig)
    figfiles.append(savefig)
    if show: P.show()
    else: P.close()
示例#4
0
# -*- coding: utf8 -*-
# Read sea level at Brest
from vcmq import cdms2, P, curve2, savefigs, data_sample
f = cdms2.open(data_sample("tide.sealevel.BREST.mars.nc"))
sea_level = f('sea_level')
f.close()

# Filtering
from vacumm.tide.filters import demerliac
cotes, tide = demerliac(sea_level, get_tide=True)

# Plots
kwplot = dict(date_fmt='%d/%m', show=False, date_rotation=0)
# - tidal signal
curve2(sea_level,
       'k',
       subplot=211,
       label='Original',
       title='Sea level at Brest',
       **kwplot)
curve2(tide, 'b', label='Tidal signal', **kwplot)
P.legend().legendPatch.set_alpha(.7)
# - surcotes/decotes
curve2(cotes, 'r', subplot=212, hspace=.3, label='Demerliac', **kwplot)
P.legend().legendPatch.set_alpha(.7)
savefigs(__file__, savefigs_pdf=True)
P.close()
yyob, xxob  = meshcells(yyo, x)

varon = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 0, extrap=0), mv)
varol = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 1, extrap=0), mv)
varoh = N.ma.masked_values(interp1dxx(vari.filled(), yyi, yyo, mv, 3, extrap=0), mv)

kw = dict(vmin=vari.min(), vmax=vari.max())
axlims = [x[0], x[-1], yo[0], yo[-1]]
P.figure(figsize=(8, 8))
P.subplot(221)
P.pcolor(xxib, yyib, vari)
P.axis(axlims)
P.title('Original')
P.subplot(222)
P.pcolor(xxob, yyob, varon, **kw)
P.axis(axlims)
P.title('Nearest1dxx')
P.subplot(223)
P.pcolor(xxob, yyob, varol, **kw)
P.axis(axlims)
P.title('Linear1dxx')
P.subplot(224)
P.pcolor(xxob, yyob, varoh, **kw)
P.axis(axlims)
P.title('Hermit1dxx')
P.tight_layout()
figfile = code_file_name(ext='png')
if os.path.exists(figfile): os.remove(figfile)
P.savefig(figfile)
P.close()
示例#6
0
    def plot_fields(self,
                    variables,
                    surf=None,
                    bottom=None,
                    horiz_sections=False,
                    points=None,
                    zonal_sections=None,
                    merid_sections=None,
                    titlepat="{var_name} - {slice_loc}",
                    props=None,
                    subst={},
                    figpat='sonat.ens.{var_name}_{slice_type}_{slice_loc}.png',
                    fmtlonlat=u'{:.2f}°{}',
                    fmtdep='{:04.0f}m',
                    savefig=True,
                    obs=None,
                    close=True,
                    show=False,
                    **kwargs):
        """Plot one or several platform like variables

        Parameters
        ----------
        depths: string, floats
            List of depths for horizontal slices. All by default.
            It accepts scalars or list of floats and of the two special values
            "bottom" and "surf". In the latter case, these variable must
            be explicitely included in the ensemble, like "temp_surf". A depth
            of 0 is not equivalent to "surf", despite results may be similar,
            or equivalent when the sea level is always 0.
            In the case of floats, the
            ensemble must contain 3d variables.
        props: dict, None
            Dictionary of graphic properties passed as keywords to plotting
            functions. The keys must be valid diagnostics names such as
            "mean", or one of the follow plotting function: map, curve.

        """
        # Init
        if props is None:
            props = {}
        kwprops = dict_merge(props, DEFAULT_PLOT_KWARGS_PER_ENS_DIAG)
        kwprops.update(fig='new')  # TODO: must be more flexible like for obs
        figs = OrderedDict()
        kwobs = kwfilter(kwargs, 'obs')
        kwobs.update(surf=False,
                     bottom=False,
                     zonal_sections=None,
                     merid_sections=None,
                     horiz_sections=None)

        # Loop on variables
        for variable in ArgList(variables).get():
            var_short_name, var_depth, diag_name = split_varname(variable)
            diag_name = getattr(variable, 'sonat_ens_diag', diag_name)
            var_name = (var_short_name if var_depth is None else
                        (var_short_name + '_' + var_depth))
            varname = var_name
            id = variable.id
            self.debug(' Variable: ' + id)
            order = variable.getOrder()
            if diag_name:
                kw = kwprops.get(diag_name, {})
            else:
                kw = {}
            toplot = []

            # Maps
            if (horiz_sections is not False or surf is not False
                    or bottom is not False):

                # Surf/bottom/3D
                if ((var_depth == 'surf' and surf is not False) or
                    (var_depth == 'bottom' and bottom is not False)):  # 2D
                    slice_loc = var_depth
                    toplot.append(
                        dict(slice_loc=slice_loc,
                             kw=kw,
                             keys=(var_short_name, 'map', slice_loc),
                             obs_plot={var_depth: True},
                             slice_type='map'))

                elif (variable.getLevel() is not None
                      and horiz_sections is not False
                      and horiz_sections is not None):  # 3D

                    # Surf and bottom
                    for ok, slice_loc in [(surf, 'surf'), (bottom, 'bottom')]:
                        if ok is True:
                            toplot.append(
                                dict(
                                    slice_loc=slice_loc,
                                    slice_type='map',
                                    keys=(var_short_name, 'map', slice_loc),
                                    kw=dict_merge(dict(depth=slice_loc), kw),
                                    obs_plot={slice_loc: True},
                                ))

                    # Loop on 3D depths specs
                    if horiz_sections is True:
                        depths = variable.getLevel()
                    else:
                        depths = horiz_sections
                        if N.isscalar(depths):
                            depths = [depths]
                    depths = list(depths)
                    for depth in depths:
                        if isinstance(depth, str):
                            slice_loc = depth
                        else:
                            slice_loc = fmtdep.format(abs(depth))
                        toplot.append(
                            dict(
                                slice_loc=slice_loc,
                                slice_type='map',
                                keys=(var_name, 'map', slice_loc),
                                kw=dict_merge(dict(depth=depth), kw),
                                obs_plot={'horiz_sections': depth},
                            ))

            # Zonal sections
            if zonal_sections is not None and zonal_sections is not False:
                slice_type = 'zonal'
                if N.isscalar(zonal_sections):
                    zonal_sections = [zonal_sections]
                for lat in zonal_sections:
                    slice_loc = latlab(lat, no_symbol=True)
                    toplot.append(
                        dict(
                            slice_loc=slice_loc,
                            slice_type=slice_type,
                            keys=(var_name, slice_type, slice_loc),
                            kw=dict_merge(dict(lat=lat), kw),
                            obs_plot={'zonal_sections': lat},
                        ))

            # Meridional sections
            if merid_sections is not None and merid_sections is not False:
                slice_type = 'merid'
                if N.isscalar(merid_sections):
                    merid_sections = [merid_sections]
                for lon in merid_sections:
                    slice_loc = lonlab(lon, no_symbol=True)
                    toplot.append(
                        dict(
                            slice_loc=slice_loc,
                            slice_type=slice_type,
                            keys=(var_name, slice_type, slice_loc),
                            kw=dict_merge(dict(lon=lon), kw),
                            obs_plot={'merid_sections': lon},
                        ))

#            # Points
#            if points:
#                slice_type = 'point'
#                if isinstance(points, tuple):
#                    points = [points]
#                for lon, lat in points:
#                    slice_loc = (lonlab(lon, no_symbol=True) + '-' +
#                                 latlab(lat, no_symbol=True))
#                    toplot.append(dict(
#                        slice_loc=slice_loc,
#                        slice_type=slice_type,
#                        keys=(var_name, slice_type, slice_loc),
#                        kw=dict_merge(dict(lon=lon, lat=lat), kw),
#                        obs_plot={'points':(lon, lat)},
#                        ))

# Make all pending plots for this variable
            for spec in toplot:

                # Get specs
                slice_loc = spec['slice_loc']
                slice_type = spec['slice_type']
                obs_plot = spec['obs_plot']
                keys = map(str.title, spec['keys'])
                kw = kwargs.copy()
                kw.update(spec['kw'])
                self.debug('  Location: ' + slice_loc)

                # Setup
                dfmt = locals()
                dfmt.update(subst)
                title = titlepat.format(**dfmt)
                kw.update(title=title, savefig=False, close=False)
                dict_check_defaults(kw,
                                    fig='new',
                                    **DEFAULT_PLOT_KWARGS_PER_ENS_DIAG)

                # Plot
                p = plot_gridded_var(variable, **kw)  # Action !

                # Plot obs locations on 2D plots only
                if obs and isinstance(p, Plot2D):
                    #FIXME: should we pass lon/lat/level from variable?
                    kwo = kwobs.copy()
                    kwo.update(obs_plot,
                               full3d=False,
                               full2d=False,
                               plotter=p,
                               savefig=False,
                               close=False,
                               title=False,
                               colorbar=False)
                    #                    obs.set_cached_plot('locations', slice_type, slice_loc, p)
                    obs.plot('locations', **kwo)

                # Finalise
                if savefig:
                    figfile = figpat.format(**dfmt)
                    checkdir(figfile)
                    p.savefig(figfile)
                    close = True
                    self.created(figfile)
                    kw = {keys[-1]: figfile, '__class__': OrderedDict}
                    dicttree_set(figs, *keys[:-1], **kw)
                if not show and close:
                    p.close()
        if show:
            P.show()
        elif close:
            P.close()

        return figs
示例#7
0
"""Test the :func:`~vacumm.misc.grid.io.Shapes` class"""
from vcmq import N, P, code_file_name, data_sample
from vacumm.misc.io import Shapes
result = []

# File names
shpfile = data_sample("ne_110m_land/ne_110m_land")
figfile = code_file_name(ext=False)+'_%i.png'

# Basic
S = Shapes(shpfile)
result.append(('assertEqual', [len(S), 127]))
S.plot(title='Basic', show=False)
P.savefig(figfile%0);P.close()

# Min area
S = Shapes(shpfile, min_area=1000)
result.append(('assertEqual', [len(S), 3]))
S.plot(title='Min area', show=False)
P.savefig(figfile%1);P.close()

# Projection
S = Shapes(shpfile, proj='merc')
result.append(('assertGreater', [S[1].area(), 1e12]))
S.plot(title='Projected', show=False)
P.savefig(figfile%2);P.close()

# Clips
S = Shapes(shpfile, clip=[-10, 42, 10, 51.])
result.append(('assertEqual', [len(S), 3]))
S.plot(title='Clipped', show=False)