Exemplo n.º 1
0
    def togrid(self, grid=None, mask=None, cgrid=False,  proj=None, **kwargs):


        # Shoreline for masking
        if mask is not None and mask is not False and mask is not MV2.nomask and grid is not None:

            # Clip for polygons
            kwmask = kwfilter(kwargs, 'mask')
            clip = kwmask.pop('clip', .1)
            if isinstance(clip, float):
                xx, yy = get_xy(grid)
                xmin = xx[:].min() ; xmax = xx[:].max()
                ymin = yy[:].min() ; ymax = yy[:].max()
                dx = (xmax-xmin)*clip
                dy = (ymax-ymin)*clip
                clip = [xmin-dx, ymin-dy, xmax+dx, ymax+dy]

            # Auto resolution
            if mask=='auto' and False:
                if grid is None:
                    grid = self.get_grid(**kwfilter(kwargs, 'grid'))
                mask = get_best(grid)

            # Direct handling
            if isinstance(mask, (str, Shapes)):
                # Get mask
                mask = get_shoreline(mask, clip=clip)

        # Normal case
        return XYZ.togrid(self, grid=grid, mask=mask, cgrid=cgrid,  proj=proj, **kwargs)
Exemplo n.º 2
0
    def __init__(self, **kwargs):
        '''

        :Keyword arguments:
            - **config*: load a configuration (:meth:`load_config()`)
            - **logger**: A :class:`Logger` instance.
            - **logger_<param>**: ``<param>`` is passed to the
              :class:`Logger` constructor. Not used if **logger** is passed.

        '''
        # Setup logging
        lkw = kwfilter(kwargs, 'logger', {'name':self.__class__.__name__})
        if isinstance(lkw.get('config', None), Object):
            lkw['config'] = lkw['config'].get_logger()
        lkw['name_filters'] = list(lkw.get('name_filters', [])) + [self.__class__.__name__]
        if 'logger' in lkw:
            self._logger = lkw['logger']
            if not isinstance(self._logger, Logger):
                vacumm_warning(self.__class__.__name__.split('.')[-1]+
                    '{} is initialised with an invalid logger type')
        else:
            self._logger = Logger(**lkw)
        self._logger.skipCaller(self.get_class_logger().skipCaller())
        # Load passed or default configuration
        self.load_config(kwargs.get('config', None),  cfgpatch=kwargs.get('cfgpatch', None))
Exemplo n.º 3
0
 def kwfilter(cls, kwargs, filters=None, *args, **kwa):
     '''
     Shortcut to :func:`vacumm.misc.misc.kwfilter` with a filters argument which
     defaults to this class lowercase name.
     '''
     if filters is None: filters = cls.__name__.lower()
     return kwfilter(kwargs, filters, *args, **kwa)
Exemplo n.º 4
0
 def kwfilter(cls, kwargs, filters=None, *args, **kwa):
     '''
     Shortcut to :func:`vacumm.misc.misc.kwfilter` with a filters argument which
     defaults to this class lowercase name.
     '''
     if filters is None: filters = cls.__name__.lower()
     return kwfilter(kwargs, filters, *args, **kwa)
Exemplo n.º 5
0
    def __init__(self, **kwargs):
        '''

        :Keyword arguments:
            - **config*: load a configuration (:meth:`load_config()`)
            - **logger**: A :class:`Logger` instance.
            - **logger_<param>**: ``<param>`` is passed to the
              :class:`Logger` constructor. Not used if **logger** is passed.

        '''
        # Setup logging
        lkw = kwfilter(kwargs, 'logger', {'name':self.__class__.__name__})
        if isinstance(lkw.get('config', None), Object):
            lkw['config'] = lkw['config'].get_logger()
        lkw['name_filters'] = list(lkw.get('name_filters', [])) + [self.__class__.__name__]
        if 'logger' in lkw:
            self._logger = lkw['logger']
            if not isinstance(self._logger, Logger):
                vacumm_warning(self.__class__.__name__.split('.')[-1]+
                    '{} is initialised with an invalid logger type')
        else:
            self._logger = Logger(**lkw)
        # Load passed or default configuration
        self.load_config(kwargs.get('config', None),  cfgpatch=kwargs.get('cfgpatch', None))
Exemplo n.º 6
0
    def plot(self, **kwargs):
        """Plot current bathies using a :class:`XYZBathyMerger` instance"""

        return self.merger(**kwfilter(kwargs, 'merger')).plot(**kwargs)
Exemplo n.º 7
0
def plot_bathy(bathy, shadow=True, contour=True, shadow_stretch=1., shadow_shapiro=False,
    show=True, shadow_alpha=1., shadow_black=.3, white_deep=False, nmax=30,m=None, alpha=1.,
    zmin=None, zmax=None, **kwargs):
    """Plot a bathymetry

    - *lon*: Longitude range.
    - *lat*: Latitude range.
    - *show*:Display the figure [default: True]
    - *pcolor*: Use pcolor instead of contour [default: False]
    - *contour*: Add line contours [default: True]
    - *shadow*:Plot south-west shadows instead of filled contours.
    - *nmax*: Max number of levels for contours [default: 30]
    - *white_deep*: Deep contours are white [default: False]
    - All other keyword are passed to :func:`~vacumm.misc.plot.map2`
    """

    # Input
    bb = bathy
    if isinstance(bathy, GriddedBathy):
        bathy = bathy.bathy()
        if shadow:
            xxs = getattr(bb, '_xxs', None)
            yys = getattr(bb, '_yys', None)
            if xxs is None:
                lon2d = bb._lon2d
                lat2d = bb._lat2d
    elif shadow:
        xxs = yys = None
        lon2d,lat2d = meshgrid(get_axis(bathy, -1).getValue(),get_axis(bathy, -2).getValue())

    # Masking
    if 'maxdep' in kwargs:
        zmin = -maxdep
    if 'maxalt' in kwargs:
        zmax = maxalt
    if zmin is not None:
        bathy[:] = MV2.masked_less(bathy, zmin)
    if zmax is not None:
        bathy[:] = MV2.masked_greater(bathy, zmax)

    # Default arguments for map
    if hasattr(bathy, 'long_name'):
        kwargs.setdefault('title',bathy.long_name)
    if 'cmap' not in kwargs:
        vmin, vmax = minmax(bathy)
#        print 'cmap topo', vmin, vmax
        kwargs['cmap'] = auto_cmap_topo((kwargs.get('vmin', vmin), kwargs.get('vmax', vmax)))
#       kwargs.setdefault('ticklabel_size','smaller')
    kwargs.setdefault('clabel_fontsize', 8)
    kwargs.setdefault('clabel_alpha',.7*alpha)
    kwargs.setdefault('clabel_glow_alpha', kwargs['clabel_alpha'])
    kwargs.setdefault('fill', 'contourf')
    kwargs['nmax'] = nmax
    kwargs['show'] = False
    kwargs['contour'] = contour
    if shadow: kwargs.setdefault('alpha',.5*alpha)
    kwargs.setdefault('projection', 'merc')
    kwargs.setdefault('fmt', BathyFormatter())
    kwargs.setdefault('colorbar_format', BathyFormatter())
    kwargs.setdefault('units', False)
    kwargs.setdefault('levels_mode','normal')
    kwargs.setdefault('bgcolor', '0.8')
    kwargs.setdefault('contour_linestyle', '-')
    savefig = kwargs.pop('savefig', None)
    kwsavefig = kwfilter(kwargs, 'savefig_')


    # White contour when dark
    if contour and white_deep:
        levels = auto_scale(bathy,nmax=nmax)
        colors = []
        nlevel = len(levels)
        for i in range(nlevel):
            if i < old_div(nlevel,2):
                colors.append('w')
            else:
                colors.append('k')
        kwargs.setdefault('contour_colors',tuple(colors))

    # Call to map
    m = map2(bathy, m=m, **kwargs)

    # Add shadow
    if shadow:

        # Filter
        data = MV.array(bathy,'f',fill_value=0.)
        if shadow_shapiro:
            data = shapiro2d(data,fast=True).shape

        # Gradient
        grd = deriv2d(data,direction=45.,fast=True,fill_value=0.).filled(0.)
        grdn = refine(grd, 3)
        grdn = norm_atan(grdn,stretch=shadow_stretch).clip(0,1.) ; del grd

        # Grid
#           im = m.map.imshow(grdn,cmap=P.get_cmap('gist_yarg'),alpha=1) # gist_yarg , YlGnBu
        if xxs is None or yys is None:
            xx, yy = m(lon2d,lat2d)
            xxr = refine(xx, 3)
            yyr = refine(yy, 3)
            xxs, yys = meshbounds(xxr, yyr)
            if isinstance(bb, GriddedBathy):
                bb._xxs = xxs
                bb._yys = yys
            del xx, yy, xxr, yyr

        # Cmap
        cmap = cmap_custom(( ((1, )*3, 0), ((shadow_black, )*3, 1) ))

        # Plot
        pp = m.map.pcolormesh(xxs, yys, grdn,cmap=cmap)#P.get_cmap('gist_yarg'))
        pp.set_zorder(.9)
        pp.set_linewidth(0)
        pp.set_alpha(shadow_alpha*N.clip(alpha*2, 0, 1))
        del grdn

    # Show it?
    if savefig:
        m.savefig(savefig, **kwsavefig)
    if show:
        P.show()
    return m