def __call__(self, value, clip=None): if clip is None: clip = self.clip if cbook.iterable(value): vtype = 'array' val = ma.asarray(value).astype(npy.float) else: vtype = 'scalar' val = ma.array([value]).astype(npy.float) self.autoscale_None(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.0 * val else: if clip: mask = ma.getmask(val) val = ma.array(npy.clip(val.filled(vmax), vmin, vmax), mask=mask) result = (ma.log(val)-npy.log(vmin))/(npy.log(vmax)-npy.log(vmin)) if vtype == 'scalar': result = result[0] return result
def set_data(self, x, y, A): A = ma.asarray(A) if x is None: x = npy.arange(0, A.shape[1] + 1, dtype=npy.float64) else: x = npy.asarray(x, npy.float64).ravel() if y is None: y = npy.arange(0, A.shape[0] + 1, dtype=npy.float64) else: y = npy.asarray(y, npy.float64).ravel() if A.shape[:2] != (y.size - 1, x.size - 1): print A.shape print y.size print x.size raise ValueError("Axes don't match array shape") if A.ndim not in [2, 3]: raise ValueError("A must be 2D or 3D") if A.ndim == 3 and A.shape[2] == 1: A.shape = A.shape[:2] self.is_grayscale = False if A.ndim == 3: if A.shape[2] in [3, 4]: if (A[:, :, 0] == A[:, :, 1]).all() and (A[:, :, 0] == A[:, :, 2]).all(): self.is_grayscale = True else: raise ValueError("3D arrays must have RGB or RGBA as last dim") self._A = A self._Ax = x self._Ay = y self.update_dict['array'] = True
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). ''' x = npy.asarray(args[0], dtype=npy.float64) y = npy.asarray(args[1], dtype=npy.float64) z = ma.asarray(args[2], dtype=npy.float64) if z.ndim != 2: raise TypeError("Input z must be a 2D array.") else: Ny, Nx = z.shape if x.shape == z.shape and y.shape == z.shape: return x,y,z if x.ndim != 1 or y.ndim != 1: raise TypeError("Inputs x and y must be 1D or 2D.") nx, = x.shape ny, = y.shape 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 = npy.meshgrid(x,y) return x,y,z
def to_rgba(self, x, alpha=1.0, bytes=False): '''Return a normalized rgba array corresponding to x. If x is already an rgb array, insert alpha; if it is already rgba, return it unchanged. If bytes is True, return rgba as 4 uint8s instead of 4 floats. ''' try: if x.ndim == 3: if x.shape[2] == 3: if x.dtype == npy.uint8: alpha = npy.array(alpha*255, npy.uint8) m, n = x.shape[:2] xx = npy.empty(shape=(m,n,4), dtype = x.dtype) xx[:,:,:3] = x xx[:,:,3] = alpha elif x.shape[2] == 4: xx = x else: raise ValueError("third dimension must be 3 or 4") if bytes and xx.dtype != npy.uint8: xx = (xx * 255).astype(npy.uint8) return xx except AttributeError: pass x = ma.asarray(x) x = self.norm(x) x = self.cmap(x, alpha=alpha, bytes=bytes) return x
def __call__(self, value, clip=None): if clip is None: clip = self.clip if cbook.iterable(value): vtype = 'array' val = ma.asarray(value).astype(npy.float) else: vtype = 'scalar' val = ma.array([value]).astype(npy.float) self.autoscale_None(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.0 * val else: if clip: mask = ma.getmask(val) val = ma.array(npy.clip(val.filled(vmax), vmin, vmax), mask=mask) result = (ma.log(val) - npy.log(vmin)) / (npy.log(vmax) - npy.log(vmin)) if vtype == 'scalar': result = result[0] return result
def set_data(self, x, y, A): A = ma.asarray(A) if x is None: x = npy.arange(0, A.shape[1]+1, dtype=npy.float64) else: x = npy.asarray(x, npy.float64).ravel() if y is None: y = npy.arange(0, A.shape[0]+1, dtype=npy.float64) else: y = npy.asarray(y, npy.float64).ravel() if A.shape[:2] != (y.size-1, x.size-1): print A.shape print y.size print x.size raise ValueError("Axes don't match array shape") if A.ndim not in [2, 3]: raise ValueError("A must be 2D or 3D") if A.ndim == 3 and A.shape[2] == 1: A.shape = A.shape[:2] self.is_grayscale = False if A.ndim == 3: if A.shape[2] in [3, 4]: if (A[:,:,0] == A[:,:,1]).all() and (A[:,:,0] == A[:,:,2]).all(): self.is_grayscale = True else: raise ValueError("3D arrays must have RGB or RGBA as last dim") self._A = A self._Ax = x self._Ay = y self.update_dict['array'] = True
def _make_verts(self, U, V): uv = ma.asarray(U+V*1j) a = ma.absolute(uv) if self.scale is None: sn = max(10, math.sqrt(self.N)) scale = 1.8 * a.mean() * sn / self.span # crude auto-scaling self.scale = scale length = a/(self.scale*self.width) X, Y = self._h_arrows(length) # There seems to be a ma bug such that indexing # a masked array with one element converts it to # an ndarray. theta = npy.angle(ma.asarray(uv[..., npy.newaxis]).filled(0)) xy = (X+Y*1j) * npy.exp(1j*theta)*self.width xy = xy[:,:,npy.newaxis] XY = ma.concatenate((xy.real, xy.imag), axis=2) return XY
def _make_verts(self, U, V): uv = ma.asarray(U + V * 1j) a = ma.absolute(uv) if self.scale is None: sn = max(10, math.sqrt(self.N)) scale = 1.8 * a.mean() * sn / self.span # crude auto-scaling self.scale = scale length = a / (self.scale * self.width) X, Y = self._h_arrows(length) # There seems to be a ma bug such that indexing # a masked array with one element converts it to # an ndarray. theta = npy.angle(ma.asarray(uv[..., npy.newaxis]).filled(0)) xy = (X + Y * 1j) * npy.exp(1j * theta) * self.width xy = xy[:, :, npy.newaxis] XY = ma.concatenate((xy.real, xy.imag), axis=2) return XY
def inverse(self, value): if not self.scaled(): raise ValueError("Not invertible until scaled") vmin, vmax = self.vmin, self.vmax if cbook.iterable(value): val = ma.asarray(value) return vmin * ma.power((vmax / vmin), val) else: return vmin * pow((vmax / vmin), value)
def inverse(self, value): if not self.scaled(): raise ValueError("Not invertible until scaled") vmin, vmax = self.vmin, self.vmax if cbook.iterable(value): val = ma.asarray(value) return vmin * ma.power((vmax/vmin), val) else: return vmin * pow((vmax/vmin), value)
def _parse_args(self, *args): X, Y, U, V, C = [None] * 5 args = list(args) if len(args) == 3 or len(args) == 5: C = ma.asarray(args.pop(-1)).ravel() V = ma.asarray(args.pop(-1)) U = ma.asarray(args.pop(-1)) nn = npy.shape(U) nc = nn[0] nr = 1 if len(nn) > 1: nr = nn[1] if len(args) == 2: X, Y = [npy.array(a).ravel() for a in args] if len(X) == nc and len(Y) == nr: X, Y = [a.ravel() for a in npy.meshgrid(X, Y)] else: indexgrid = npy.meshgrid(npy.arange(nc), npy.arange(nr)) X, Y = [npy.ravel(a) for a in indexgrid] return X, Y, U, V, C
def _parse_args(self, *args): X, Y, U, V, C = [None]*5 args = list(args) if len(args) == 3 or len(args) == 5: C = ma.asarray(args.pop(-1)).ravel() V = ma.asarray(args.pop(-1)) U = ma.asarray(args.pop(-1)) nn = npy.shape(U) nc = nn[0] nr = 1 if len(nn) > 1: nr = nn[1] if len(args) == 2: X, Y = [npy.array(a).ravel() for a in args] if len(X) == nc and len(Y) == nr: X, Y = [a.ravel() for a in npy.meshgrid(X, Y)] else: indexgrid = npy.meshgrid(npy.arange(nc), npy.arange(nr)) X, Y = [npy.ravel(a) for a in indexgrid] return X, Y, U, V, C
def set_data(self, A, shape=None): """ Set the image array ACCEPTS: numpy/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 self._A = X self._imcache = None
def set_data(self, A, shape=None): """ Set the image array ACCEPTS: numpy/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 self._A = X self._imcache =None
def recache(self): #if self.axes is None: print 'recache no axes' #else: print 'recache units', self.axes.xaxis.units, self.axes.yaxis.units if ma.isMaskedArray(self._xorig) or ma.isMaskedArray(self._yorig): 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) else: x = npy.asarray(self.convert_xunits(self._xorig), float) y = npy.asarray(self.convert_yunits(self._yorig), float) x = npy.ravel(x) y = npy.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') x = x.reshape((len(x), 1)) y = y.reshape((len(y), 1)) if ma.isMaskedArray(x) or ma.isMaskedArray(y): self._xy = ma.concatenate((x, y), 1) else: self._xy = npy.concatenate((x, y), 1) self._x = self._xy[:, 0] # just a view self._y = self._xy[:, 1] # just a view # Masked arrays are now handled by the Path class itself self._path = Path(self._xy) self._transformed_path = TransformedPath(self._path, self.get_transform()) self._invalid = False
def __call__(self, X, alpha=1.0, bytes=False): """ 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 bytes is False, the rgba values will be floats on a 0-1 scale; if True, they will be uint8, 0-255. """ 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 cbook.iterable(X): vtype = 'scalar' xa = npy.array([X]) else: vtype = 'array' xma = ma.asarray(X) xa = xma.filled(0) mask_bad = ma.getmask(xma) if xa.dtype.char in npy.typecodes['Float']: npy.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. npy.putmask(xa, xa > self.N - 1, self._i_over) npy.putmask(xa, xa < 0, self._i_under) if mask_bad is not None and mask_bad.shape == xa.shape: npy.putmask(xa, mask_bad, self._i_bad) if bytes: lut = (self._lut * 255).astype(npy.uint8) else: lut = self._lut rgba = lut[xa] if vtype == 'scalar': rgba = tuple(rgba[0, :]) return rgba
def __call__(self, X, alpha=1.0, bytes=False): """ 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 bytes is False, the rgba values will be floats on a 0-1 scale; if True, they will be uint8, 0-255. """ 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 cbook.iterable(X): vtype = 'scalar' xa = npy.array([X]) else: vtype = 'array' xma = ma.asarray(X) xa = xma.filled(0) mask_bad = ma.getmask(xma) if xa.dtype.char in npy.typecodes['Float']: npy.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. npy.putmask(xa, xa>self.N-1, self._i_over) npy.putmask(xa, xa<0, self._i_under) if mask_bad is not None and mask_bad.shape == xa.shape: npy.putmask(xa, mask_bad, self._i_bad) if bytes: lut = (self._lut * 255).astype(npy.uint8) else: lut = self._lut rgba = lut[xa] if vtype == 'scalar': rgba = tuple(rgba[0,:]) return rgba
def _contour_args(self, *args): if self.filled: fn = 'contourf' else: fn = 'contour' Nargs = len(args) if Nargs <= 2: z = ma.asarray(args[0], dtype=npy.float64) 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)) self.zmax = ma.maximum(z) self.zmin = ma.minimum(z) if self.logscale and self.zmin <= 0: z = ma.masked_where(z <= 0, z) warnings.warn('Log scale: values of z <=0 have been masked') self.zmin = z.min() 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] try: if type(level_arg) == int: lev = self._autolev(z, level_arg) else: lev = npy.asarray(level_arg).astype(npy.float64) except: 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, min(self.levels[0],self.zmin) - 1) if self.extend in ('both', 'max'): self._levels.append(max(self.levels[-1],self.zmax) + 1) self._levels = npy.asarray(self._levels) self.vmin = npy.amin(self.levels) # alternative would be self.layers self.vmax = npy.amax(self.levels) if self.extend in ('both', 'min'): self.vmin = 2 * self.levels[0] - self.levels[1] if self.extend in ('both', 'max'): 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'): self.layers[0] = 0.5 * (self.vmin + self._levels[1]) if self.extend in ('both', 'max'): self.layers[-1] = 0.5 * (self.vmax + self._levels[-2]) return (x, y, z)