Example #1
0
    def recache(self):
        #if self.axes is None: print 'recache no axes'
        #else: print 'recache units', self.axes.xaxis.units, self.axes.yaxis.units
        x = ma.asarray(self.convert_xunits(self._xorig), float)
        y = ma.asarray(self.convert_yunits(self._yorig), float)

        x = ma.ravel(x)
        y = ma.ravel(y)
        if len(x)==1 and len(y)>1:
            x = x * npy.ones(y.shape, float)
        if len(y)==1 and len(x)>1:
            y = y * npy.ones(x.shape, float)

        if len(x) != len(y):
            raise RuntimeError('xdata and ydata must be the same length')

        mx = ma.getmask(x)
        my = ma.getmask(y)
        mask = ma.mask_or(mx, my)
        if mask is not ma.nomask:
            x = ma.masked_array(x, mask=mask).compressed()
            y = ma.masked_array(y, mask=mask).compressed()
            self._segments = unmasked_index_ranges(mask)
        else:
            self._segments = None

        self._x = npy.asarray(x, float)
        self._y = npy.asarray(y, float)

        self._logcache = None
Example #2
0
 def to_rgba(self, x, alpha=1.0):
     # assume normalized rgb, rgba
     if len(x.shape)>2: return x
     x = ma.asarray(x)
     x = self.norm(x)
     x = self.cmap(x, alpha)
     return x
Example #3
0
 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 __call__(self, value, clip=None):
     if clip is None:
         clip = self.clip
     if isinstance(value, (int, float)):
         vtype = 'scalar'
         val = ma.array([value])
     else:
         vtype = 'array'
         val = ma.asarray(value)
     self.autoscale(val)
     vmin, vmax = self.vmin, self.vmax
     if vmin > vmax:
         raise ValueError("minvalue must be less than or equal to maxvalue")
     elif vmin<=0:
         raise ValueError("values must all be positive")
     elif vmin==vmax:
         return 0.*value
     else:
         if clip:
             mask = ma.getmask(val)
             val = ma.array(nx.clip(val.filled(vmax), vmin, vmax),
                             mask=mask)
         result = (ma.log(val)-nx.log(vmin))/(nx.log(vmax)-nx.log(vmin))
     if vtype == 'scalar':
         result = result[0]
     return result
Example #5
0
 def _contour_args(self, filled, origin, extent, *args):
     if filled: fn = 'contourf'
     else:      fn = 'contour'
     Nargs = len(args)
     if Nargs <= 2:
         z = args[0]
         x, y = self._initialize_x_y(z, origin, extent)
     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, filled)
     else:   # 2 or 4 args
         level_arg = args[-1]
         if type(level_arg) == int:
             lev = self._autolev(z, level_arg, filled)
         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 filled and len(lev) < 2:
         raise ValueError("Filled contours require at least 2 levels.")
     self.ax.set_xlim((ma.minimum(x), ma.maximum(x)))
     self.ax.set_ylim((ma.minimum(y), ma.maximum(y)))
     # 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.
     return (x, y, z, lev)
Example #6
0
 def to_rgba(self, x, alpha=1.0):
     '''Return a normalized rgba array corresponding to x.
     If x is already an rgb or rgba array, return it unchanged.
     '''
     if hasattr(x, 'shape') and len(x.shape)>2: return x
     x = ma.asarray(x)
     x = self.norm(x)
     x = self.cmap(x, alpha)
     return x
Example #7
0
 def to_rgba(self, x, alpha=1.0):
     # assume normalized rgb, rgba
     #print '0', type(x), x.shape
     x = ma.asarray(x)
     #print '1', type(x), x.shape
     if len(x.shape)>2: return x
     x = self.norm(x)
     x = self.cmap(x, alpha)
     return x
Example #8
0
    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)
Example #9
0
 def to_rgba(self, x, alpha=1.0):
     '''Return a normalized rgba array corresponding to x.
     If x is already an rgb or rgba array, return it unchanged.
     '''
     if hasattr(x, 'shape') and len(x.shape)>2: return x
     x = ma.asarray(x)
     x = self.norm(x)
     x = self.cmap(x, alpha)
     return x
    def inverse(self, value):
        if not self.scaled():
            raise ValueError("Not invertible until scaled")
        vmin, vmax = self.vmin, self.vmax

        if isinstance(value, (int, float)):
            return vmin * pow((vmax/vmin), value)
        else:
            val = ma.asarray(value)
            return vmin * ma.power((vmax/vmin), val)
Example #11
0
    def set_data(self, A, shape=None):
        """
        Set the image array

        ACCEPTS: numeric/numarray/PIL Image A"""
        # check if data is PIL Image without importing Image
        if hasattr(A, "getpixel"):
            X = pil_to_array(A)
        else:
            X = ma.asarray(A)  # assume array

        if typecode(X) != UInt8 or len(X.shape) != 3 or X.shape[2] > 4 or X.shape[2] < 3:
            cm.ScalarMappable.set_array(self, X)
        else:
            self._A = X

        self._imcache = None
Example #12
0
    def __call__(self, value):

        if isinstance(value, (int, float)):
            vtype = 'scalar'
            val = ma.array([value])
        else:
            vtype = 'array'
            val = ma.asarray(value)

        self.autoscale(val)
        vmin, vmax = self.vmin, self.vmax
        if vmin > vmax:
            raise ValueError("minvalue must be less than or equal to maxvalue")
        elif vmin==vmax:
            return 0.*value
        else:
            if self.clip:
                val = clip(val.filled(vmax), vmin, vmax)
            result = (1.0/(vmax-vmin))*(val-vmin)
        if vtype == 'scalar':
            result = result[0]
        return result
Example #13
0
 def __call__(self, X, alpha=1.0):
     """
     X is either a scalar or an array (of any dimension).
     If scalar, a tuple of rgba values is returned, otherwise
     an array with the new shape = oldshape+(4,). If the X-values
     are integers, then they are used as indices into the array.
     If they are floating point, then they must be in the
     interval (0.0, 1.0).
     Alpha must be a scalar.
     """
     if not self._isinit: self._init()
     alpha = min(alpha, 1.0) # alpha must be between 0 and 1
     alpha = max(alpha, 0.0)
     self._lut[:-3, -1] = alpha
     mask_bad = None
     if isinstance(X, (int, float)):
         vtype = 'scalar'
         xa = array([X])
     else:
         vtype = 'array'
         xma = ma.asarray(X)
         xa = xma.filled(0)
         mask_bad = ma.getmaskorNone(xma)
     if typecode(xa) in typecodes['Float']:
         xa = where(xa == 1.0, 0.9999999, xa) # Tweak so 1.0 is in range.
         xa = (xa * self.N).astype(Int)
     mask_under = xa < 0
     mask_over = xa > self.N-1
     xa = where(mask_under, self._i_under, xa)
     xa = where(mask_over, self._i_over, xa)
     if mask_bad is not None: # and sometrue(mask_bad):
         xa = where(mask_bad, self._i_bad, xa)
     #print 'types', typecode(self._lut), typecode(xa), xa.shape
     rgba = take(self._lut, xa)
     if vtype == 'scalar':
         rgba = tuple(rgba[0,:])
     #print rgba[0,1:10,:]       # Now the same for numpy, numeric...
     return rgba
    def __call__(self, X, alpha=1.0):
        """
        X is either a scalar or an array (of any dimension).
        If scalar, a tuple of rgba values is returned, otherwise
        an array with the new shape = oldshape+(4,). If the X-values
        are integers, then they are used as indices into the array.
        If they are floating point, then they must be in the
        interval (0.0, 1.0).
        Alpha must be a scalar.
        """

        if not self._isinit: self._init()
        alpha = min(alpha, 1.0) # alpha must be between 0 and 1
        alpha = max(alpha, 0.0)
        self._lut[:-3, -1] = alpha
        mask_bad = None
        if not iterable(X):
            vtype = 'scalar'
            xa = array([X])
        else:
            vtype = 'array'
            xma = ma.asarray(X)
            xa = xma.filled(0)
            mask_bad = ma.getmask(xma)
        if typecode(xa) in typecodes['Float']:
            putmask(xa, xa==1.0, 0.9999999) #Treat 1.0 as slightly less than 1.
            xa = (xa * self.N).astype(Int)
        # Set the over-range indices before the under-range;
        # otherwise the under-range values get converted to over-range.
        putmask(xa, xa>self.N-1, self._i_over)
        putmask(xa, xa<0, self._i_under)
        if mask_bad is not None and mask_bad.shape == xa.shape:
            putmask(xa, mask_bad, self._i_bad)
        rgba = take(self._lut, xa)
        if vtype == 'scalar':
            rgba = tuple(rgba[0,:])
        return rgba