Пример #1
0
    def _autolev(self, z, N):
        '''
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        '''
        zmax = self.zmax
        zmin = self.zmin
        zmargin = (zmax - zmin) * 0.001  # so z < (zmax + zmargin)
        zmax = zmax + zmargin
        intv = Interval(Value(zmin), Value(zmax))
        if self.locator is None:
            self.locator = MaxNLocator(N + 1)
        self.locator.set_view_interval(intv)
        self.locator.set_data_interval(intv)
        lev = self.locator()
        self._auto = True
        if self.filled:
            return lev
        return lev[1:-1]
Пример #2
0
    def _autolev(self, z, N):
        '''
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        '''
        zmax = self.zmax
        zmin = self.zmin
        zmargin = (zmax - zmin) * 0.001 # so z < (zmax + zmargin)
        zmax = zmax + zmargin
        intv = Interval(Value(zmin), Value(zmax))
        if self.locator is None:
            self.locator = MaxNLocator(N+1)
        self.locator.set_view_interval(intv)
        self.locator.set_data_interval(intv)
        lev = self.locator()
        self._auto = True
        if self.filled:
            return lev
        return lev[1:-1]
Пример #3
0
class ContourSet(ScalarMappable, ContourLabeler):
    """
    Create and store a set of contour lines or filled regions.

    User-callable method: clabel

    Useful attributes:
        ax - the axes object in which the contours are drawn
        collections - a silent_list of LineCollections or PolyCollections
        levels - contour levels
        layers - same as levels for line contours; half-way between
                 levels for filled contours.  See _process_colors method.
    """
    def __init__(self, ax, *args, **kwargs):
        """
        Draw contour lines or filled regions, depending on
        whether keyword arg 'filled' is False (default) or True.

        The first argument of the initializer must be an axes
        object.  The remaining arguments and keyword arguments
        are described in ContourSet.contour_doc.

        """
        self.ax = ax
        self.levels = kwargs.get('levels', None)
        self.filled = kwargs.get('filled', False)
        self.linewidths = kwargs.get('linewidths', None)

        self.alpha = kwargs.get('alpha', 1.0)
        self.origin = kwargs.get('origin', None)
        self.extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        self.colors = kwargs.get('colors', None)
        norm = kwargs.get('norm', None)
        self.clip_ends = kwargs.get('clip_ends', None)  ########
        self.extend = kwargs.get('extend', 'neither')
        if self.clip_ends is not None:
            warnings.warn("'clip_ends' has been replaced by 'extend'")
            self.levels = self.levels[1:-1]  # discard specified end levels
            self.extend = 'both'  # regenerate end levels
        self.antialiased = kwargs.get('antialiased', True)
        self.nchunk = kwargs.get('nchunk', 0)
        self.locator = kwargs.get('locator', None)

        if self.origin is not None:
            assert (self.origin in ['lower', 'upper', 'image'])
        if self.extent is not None: assert (len(self.extent) == 4)
        if cmap is not None: assert (isinstance(cmap, Colormap))
        if self.colors is not None and cmap is not None:
            raise ValueError('Either colors or cmap must be None')
        if self.origin == 'image': self.origin = rcParams['image.origin']
        x, y, z = self._contour_args(*args)  # also sets self.levels,
        #  self.layers
        if self.colors is not None:
            cmap = ListedColormap(self.colors, N=len(self.layers))
        if self.filled:
            self.collections = silent_list('PolyCollection')
        else:
            self.collections = silent_list('LineCollection')
        # label lists must be initialized here
        self.cl = []
        self.cl_cvalues = []

        kw = {'cmap': cmap}
        if norm is not None:
            kw['norm'] = norm
        ScalarMappable.__init__(self, **kw)  # sets self.cmap;
        self._process_colors()

        if self.filled:
            if self.linewidths is None:
                self.linewidths = 0.05  # Good default for Postscript.
            if iterable(self.linewidths):
                self.linewidths = self.linewidths[0]
            #C = _contour.Cntr(x, y, z.filled(), z.mask())
            C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z))
            lowers = self._levels[:-1]
            uppers = self._levels[1:]
            for level, level_upper, color in zip(lowers, uppers, self.tcolors):
                nlist = C.trace(level,
                                level_upper,
                                points=0,
                                nchunk=self.nchunk)
                col = PolyCollection(nlist,
                                     linewidths=(self.linewidths, ),
                                     antialiaseds=(self.antialiased, ),
                                     facecolors=color,
                                     edgecolors='None')
                self.ax.add_collection(col)
                self.collections.append(col)

        else:
            tlinewidths = self._process_linewidths()
            self.tlinewidths = tlinewidths
            #C = _contour.Cntr(x, y, z.filled(), z.mask())
            C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z))
            for level, color, width in zip(self.levels, self.tcolors,
                                           tlinewidths):
                nlist = C.trace(level, points=0)
                col = LineCollection(nlist, colors=color, linewidths=width)

                if level < 0.0 and self.monochrome:
                    col.set_linestyle(
                        (0, rcParams['contour.negative_linestyle']))
                col.set_label(str(level))  # only for self-documentation
                self.ax.add_collection(col)
                self.collections.append(col)
        x0 = ma.minimum(x)
        x1 = ma.maximum(x)
        y0 = ma.minimum(y)
        y1 = ma.maximum(y)
        self.ax.update_datalim([(x0, y0), (x1, y1)])
        self.ax.set_xlim((x0, x1))
        self.ax.set_ylim((y0, y1))

    def changed(self):
        tcolors = [(tuple(rgba), )
                   for rgba in self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        contourNum = 0
        for color, collection in zip(tcolors, self.collections):
            collection.set_color(color)
        for label, cv in zip(self.cl, self.cl_cvalues):
            label.set_color(self.label_mappable.to_rgba(cv))
        # add label colors
        ScalarMappable.changed(self)

    def _autolev(self, z, N):
        '''
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        '''
        zmax = self.zmax
        zmin = self.zmin
        zmargin = (zmax - zmin) * 0.001  # so z < (zmax + zmargin)
        zmax = zmax + zmargin
        intv = Interval(Value(zmin), Value(zmax))
        if self.locator is None:
            self.locator = MaxNLocator(N + 1)
        self.locator.set_view_interval(intv)
        self.locator.set_data_interval(intv)
        lev = self.locator()
        self._auto = True
        if self.filled:
            return lev
        return lev[1:-1]

    def _initialize_x_y(self, z):
        '''
        Return X, Y arrays such that contour(Z) will match imshow(Z)
        if origin is not None.
        The center of pixel Z[i,j] depends on origin:
        if origin is None, x = j, y = i;
        if origin is 'lower', x = j + 0.5, y = i + 0.5;
        if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
        If extent is not None, x and y will be scaled to match,
        as in imshow.
        If origin is None and extent is not None, then extent
        will give the minimum and maximum values of x and y.
        '''
        if len(shape(z)) != 2:
            raise TypeError("Input must be a 2D array.")
        else:
            Ny, Nx = shape(z)
        if self.origin is None:  # Not for image-matching.
            if self.extent is None:
                return meshgrid(arange(Nx), arange(Ny))
            else:
                x0, x1, y0, y1 = self.extent
                x = linspace(x0, x1, Nx)
                y = linspace(y0, y1, Ny)
                return meshgrid(x, y)
        # Match image behavior:
        if self.extent is None:
            x0, x1, y0, y1 = (0, Nx, 0, Ny)
        else:
            x0, x1, y0, y1 = self.extent
        dx = float(x1 - x0) / Nx
        dy = float(y1 - y0) / Ny
        x = x0 + (arange(Nx) + 0.5) * dx
        y = y0 + (arange(Ny) + 0.5) * dy
        if self.origin == 'upper':
            y = y[::-1]
        return meshgrid(x, y)

    def _check_xyz(self, args):
        '''
        For functions like contour, check that the dimensions
        of the input arrays match; if x and y are 1D, convert
        them to 2D using meshgrid.

        Possible change: I think we should make and use an ArgumentError
        Exception class (here and elsewhere).

        Add checking for everything being the same numerix flavor?
        '''
        x, y, z = args
        if len(shape(z)) != 2:
            raise TypeError("Input z must be a 2D array.")
        else:
            Ny, Nx = shape(z)
        if shape(x) == shape(z) and shape(y) == shape(z):
            return x, y, z
        if len(shape(x)) != 1 or len(shape(y)) != 1:
            raise TypeError("Inputs x and y must be 1D or 2D.")
        nx, = shape(x)
        ny, = shape(y)
        if nx != Nx or ny != Ny:
            raise TypeError("Length of x must be number of columns in z,\n" +
                            "and length of y must be number of rows.")
        x, y = meshgrid(x, y)
        return x, y, z

    def _contour_args(self, *args):
        if self.filled: fn = 'contourf'
        else: fn = 'contour'
        Nargs = len(args)
        if Nargs <= 2:
            z = args[0]
            x, y = self._initialize_x_y(z)
        elif Nargs <= 4:
            x, y, z = self._check_xyz(args[:3])
        else:
            raise TypeError("Too many arguments to %s; see help(%s)" %
                            (fn, fn))
        z = ma.asarray(
            z)  # Convert to native masked array format if necessary.
        self.zmax = ma.maximum(z)
        self.zmin = ma.minimum(z)
        self._auto = False
        if self.levels is None:
            if Nargs == 1 or Nargs == 3:
                lev = self._autolev(z, 7)
            else:  # 2 or 4 args
                level_arg = args[-1]
                if type(level_arg) == int:
                    lev = self._autolev(z, level_arg)
                elif iterable(level_arg) and len(shape(level_arg)) == 1:
                    lev = array([float(fl) for fl in level_arg])
                else:
                    raise TypeError(
                        "Last %s arg must give levels; see help(%s)" %
                        (fn, fn))
            if self.filled and len(lev) < 2:
                raise ValueError("Filled contours require at least 2 levels.")
            # Workaround for cntr.c bug wrt masked interior regions:
            #if filled:
            #    z = ma.masked_array(z.filled(-1e38))
            # It's not clear this is any better than the original bug.
            self.levels = lev
        #if self._auto and self.extend in ('both', 'min', 'max'):
        #    raise TypeError("Auto level selection is inconsistent "
        #                             + "with use of 'extend' kwarg")
        self._levels = list(self.levels)
        if self.extend in ('both', 'min'):
            self._levels.insert(0, self.zmin - 1)
        if self.extend in ('both', 'max'):
            self._levels.append(self.zmax + 1)
        self._levels = asarray(self._levels)
        self.vmin = amin(self.levels)  # alternative would be self.layers
        self.vmax = amax(self.levels)
        if self.extend in ('both', 'min') or self.clip_ends:
            self.vmin = 2 * self.levels[0] - self.levels[1]
        if self.extend in ('both', 'max') or self.clip_ends:
            self.vmax = 2 * self.levels[-1] - self.levels[-2]
        self.layers = self._levels  # contour: a line is a thin layer
        if self.filled:
            self.layers = 0.5 * (self._levels[:-1] + self._levels[1:])
            if self.extend in ('both', 'min') or self.clip_ends:
                self.layers[0] = 0.5 * (self.vmin + self._levels[1])
            if self.extend in ('both', 'max') or self.clip_ends:
                self.layers[-1] = 0.5 * (self.vmax + self._levels[-2])

        return (x, y, z)

    def _process_colors(self):
        """
        Color argument processing for contouring.

        Note that we base the color mapping on the contour levels,
        not on the actual range of the Z values.  This means we
        don't have to worry about bad values in Z, and we always have
        the full dynamic range available for the selected levels.

        The color is based on the midpoint of the layer, except for
        an extended end layers.
        """
        self.monochrome = self.cmap.monochrome
        if self.colors is not None:
            i0, i1 = 0, len(self.layers)
            if self.extend in ('both', 'min'):
                i0 = -1
            if self.extend in ('both', 'max'):
                i1 = i1 + 1
            self.cvalues = range(i0, i1)
            self.set_norm(no_norm())
        else:
            self.cvalues = self.layers
        if not self.norm.scaled():
            self.set_clim(self.vmin, self.vmax)
        if self.extend in ('both', 'max', 'min'):
            self.norm.clip = False
        self.set_array(self.layers)
        # self.tcolors will be set by the "changed" method

    def _process_linewidths(self):
        linewidths = self.linewidths
        Nlev = len(self.levels)
        if linewidths is None:
            tlinewidths = [(rcParams['lines.linewidth'], )] * Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(
                    ceil(Nlev / len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w, ) for w in linewidths]
        return tlinewidths

    contour_doc = """
Пример #4
0
class ContourSet(ScalarMappable, ContourLabeler):
    """
    Create and store a set of contour lines or filled regions.

    User-callable method: clabel

    Useful attributes:
        ax - the axes object in which the contours are drawn
        collections - a silent_list of LineCollections or PolyCollections
        levels - contour levels
        layers - same as levels for line contours; half-way between
                 levels for filled contours.  See _process_colors method.
    """


    def __init__(self, ax, *args, **kwargs):
        """
        Draw contour lines or filled regions, depending on
        whether keyword arg 'filled' is False (default) or True.

        The first argument of the initializer must be an axes
        object.  The remaining arguments and keyword arguments
        are described in ContourSet.contour_doc.

        """
        self.ax = ax
        self.filled = kwargs.get('filled', False)
        self.linewidths = kwargs.get('linewidths', None)

        self.alpha = kwargs.get('alpha', 1.0)
        self.origin = kwargs.get('origin', None)
        self.extent = kwargs.get('extent', None)
        cmap = kwargs.get('cmap', None)
        self.colors = kwargs.get('colors', None)
        norm = kwargs.get('norm', None)
        self.clip_ends = kwargs.get('clip_ends', True)
        self.antialiased = kwargs.get('antialiased', True)
        self.nchunk = kwargs.get('nchunk', 0)
        self.locator = kwargs.get('locator', None)

        if self.origin is not None: assert(self.origin in
                                            ['lower', 'upper', 'image'])
        if self.extent is not None: assert(len(self.extent) == 4)
        if cmap is not None: assert(isinstance(cmap, Colormap))
        if self.colors is not None and cmap is not None:
            raise ValueError('Either colors or cmap must be None')
        if self.origin == 'image': self.origin = rcParams['image.origin']
        x, y, z = self._contour_args(*args)        # also sets self.levels,
                                                   #  self.layers
        if self.colors is not None:
            cmap = ListedColormap(self.colors, N=len(self.layers))
        if self.filled:
            self.collections = silent_list('PolyCollection')
        else:
            self.collections = silent_list('LineCollection')
        # label lists must be initialized here
        self.cl = []
        self.cl_cvalues = []

        kw = {'cmap': cmap}
        if norm is not None:
            kw['norm'] = norm
        ScalarMappable.__init__(self, **kw) # sets self.cmap;
        self._process_colors()

        if self.filled:
            if self.linewidths is None:
                self.linewidths = 0.05 # Good default for Postscript.
            if iterable(self.linewidths):
                self.linewidths = self.linewidths[0]
            #C = _contour.Cntr(x, y, z.filled(), z.mask())
            C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z))
            lowers = self.levels[:-1]
            uppers = self.levels[1:]
            for level, level_upper, color in zip(lowers, uppers, self.tcolors):
                nlist = C.trace(level, level_upper, points = 1,
                        nchunk = self.nchunk)
                col = PolyCollection(nlist,
                                     linewidths = (self.linewidths,),
                                     antialiaseds = (self.antialiased,))
                col.set_color(color) # sets both facecolor and edgecolor
                self.ax.add_collection(col)
                self.collections.append(col)

        else:
            tlinewidths = self._process_linewidths()
            #C = _contour.Cntr(x, y, z.filled(), z.mask())
            C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z))
            for level, color, width in zip(self.levels, self.tcolors, tlinewidths):
                nlist = C.trace(level, points = 1)
                col = LineCollection(nlist)
                col.set_color(color)
                col.set_linewidth(width)

                if level < 0.0 and self.monochrome:
                    col.set_linestyle((0, (6.,6.)),)
                col.set_label(str(level))         # only for self-documentation
                self.ax.add_collection(col)
                self.collections.append(col)

        ## check: seems like set_xlim should also be inside
        if not self.ax.ishold():
            self.ax.cla()
        self.ax.set_xlim((ma.minimum(x), ma.maximum(x)))
        self.ax.set_ylim((ma.minimum(y), ma.maximum(y)))



    def changed(self):
        tcolors = [ (tuple(rgba),) for rgba in
                                self.to_rgba(self.cvalues, alpha=self.alpha)]
        self.tcolors = tcolors
        contourNum = 0
        for color, collection in zip(tcolors, self.collections):
            collection.set_color(color)
        for label, cv in zip(self.cl, self.cl_cvalues):
            label.set_color(self.label_mappable.to_rgba(cv))
        # add label colors
        ScalarMappable.changed(self)


    def _autolev(self, z, N):
        '''
        Select contour levels to span the data.

        We need two more levels for filled contours than for
        line contours, because for the latter we need to specify
        the lower and upper boundary of each range. For example,
        a single contour boundary, say at z = 0, requires only
        one contour line, but two filled regions, and therefore
        three levels to provide boundaries for both regions.
        '''
        zmax = ma.maximum(z)
        zmin = ma.minimum(z)
        zmargin = (zmax - zmin) * 0.001 # so z < (zmax + zmargin)
        zmax += zmargin
        intv = Interval(Value(zmin), Value(zmax))
        if self.locator is None:
            self.locator = MaxNLocator(N+1)
        self.locator.set_view_interval(intv)
        self.locator.set_data_interval(intv)
        lev = self.locator()
        if self.filled:
            return lev
        return lev[1:-1]

    def _initialize_x_y(self, z):
        '''
        Return X, Y arrays such that contour(Z) will match imshow(Z)
        if origin is not None.
        The center of pixel Z[i,j] depends on origin:
        if origin is None, x = j, y = i;
        if origin is 'lower', x = j + 0.5, y = i + 0.5;
        if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5
        If extent is not None, x and y will be scaled to match,
        as in imshow.
        If origin is None and extent is not None, then extent
        will give the minimum and maximum values of x and y.
        '''
        if len(shape(z)) != 2:
            raise TypeError("Input must be a 2D array.")
        else:
            Ny, Nx = shape(z)
        if self.origin is None:  # Not for image-matching.
            if self.extent is None:
                return meshgrid(arange(Nx), arange(Ny))
            else:
                x0,x1,y0,y1 = self.extent
                x = linspace(x0, x1, Nx)
                y = linspace(y0, y1, Ny)
                return meshgrid(x, y)
        # Match image behavior:
        if self.extent is None:
            x0,x1,y0,y1 = (0, Nx, 0, Ny)
        else:
            x0,x1,y0,y1 = self.extent
        dx = float(x1 - x0)/Nx
        dy = float(y1 - y0)/Ny
        x = x0 + (arange(Nx) + 0.5) * dx
        y = y0 + (arange(Ny) + 0.5) * dy
        if self.origin == 'upper':
            y = y[::-1]
        return meshgrid(x,y)

    def _check_xyz(self, args):
        '''
        For functions like contour, check that the dimensions
        of the input arrays match; if x and y are 1D, convert
        them to 2D using meshgrid.

        Possible change: I think we should make and use an ArgumentError
        Exception class (here and elsewhere).

        Add checking for everything being the same numerix flavor?
        '''
        x,y,z = args
        if len(shape(z)) != 2:
            raise TypeError("Input z must be a 2D array.")
        else: Ny, Nx = shape(z)
        if shape(x) == shape(z) and shape(y) == shape(z):
            return x,y,z
        if len(shape(x)) != 1 or len(shape(y)) != 1:
            raise TypeError("Inputs x and y must be 1D or 2D.")
        nx, = shape(x)
        ny, = shape(y)
        if nx != Nx or ny != Ny:
            raise TypeError("Length of x must be number of columns in z,\n" +
                            "and length of y must be number of rows.")
        x,y = meshgrid(x,y)
        return x,y,z



    def _contour_args(self, *args):
        if self.filled: fn = 'contourf'
        else:           fn = 'contour'
        Nargs = len(args)
        if Nargs <= 2:
            z = args[0]
            x, y = self._initialize_x_y(z)
        elif Nargs <=4:
            x,y,z = self._check_xyz(args[:3])
        else:
            raise TypeError("Too many arguments to %s; see help(%s)" % (fn,fn))
        z = ma.asarray(z)  # Convert to native masked array format if necessary.
        if Nargs == 1 or Nargs == 3:
            lev = self._autolev(z, 7)
        else:   # 2 or 4 args
            level_arg = args[-1]
            if type(level_arg) == int:
                lev = self._autolev(z, level_arg)
            elif iterable(level_arg) and len(shape(level_arg)) == 1:
                lev = array([float(fl) for fl in level_arg])
            else:
                raise TypeError("Last %s arg must give levels; see help(%s)" % (fn,fn))
        if self.filled and len(lev) < 2:
            raise ValueError("Filled contours require at least 2 levels.")
        # Workaround for cntr.c bug wrt masked interior regions:
        #if filled:
        #    z = ma.masked_array(z.filled(-1e38))
        # It's not clear this is any better than the original bug.
        self.levels = lev
        self.layers = self.levels # contour: a line is a thin layer
        if self.filled:
            self.layers = 0.5 * (self.levels[:-1] + self.levels[1:])
        return (x, y, z)

    def _process_colors(self):
        """
        Color argument processing for contouring.

        Note that we base the color mapping on the contour levels,
        not on the actual range of the Z values.  This means we
        don't have to worry about bad values in Z, and we always have
        the full dynamic range available for the selected levels.

        The color is based on the midpoint of the layer, except for
        the end layers when clip_ends is True.
        """
        self.monochrome = self.cmap.monochrome
        if self.colors is not None:
            self.cvalues = range(len(self.layers))
            self.set_norm(no_norm())
        else:
            self.cvalues = self.layers
        if self.filled and len(self.layers) > 2 and self.clip_ends:
            vmin = 2 * self.levels[1] - self.levels[2]
            vmax = 2 * self.levels[-2] - self.levels[-3]
        else:
            vmin = amin(self.levels)  # alternative would be self.layers
            vmax = amax(self.levels)
        self.set_clim(vmin, vmax)
        self.set_array(self.layers)
        self.tcolors = [ (tuple(rgba),) for rgba in self.to_rgba(self.cvalues)]

    def _process_linewidths(self):
        linewidths = self.linewidths
        Nlev = len(self.levels)
        if linewidths is None:
            tlinewidths = [rcParams['lines.linewidth']] *Nlev
        else:
            if iterable(linewidths) and len(linewidths) < Nlev:
                linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths)))
            elif not iterable(linewidths) and type(linewidths) in [int, float]:
                linewidths = [linewidths] * Nlev
            tlinewidths = [(w,) for w in linewidths]
        return tlinewidths

    contour_doc = """