def set_data(self, data): if data is None: self.inputdata = None self.chartdata = None return data = array(data) dim = len(shape(data)) if dim not in (1, 2, 3): raise AttributeError, "Input data must be a 1, 2, or 3d matrix" self.inputdata = data # If the input data is a 1d matrix, then it describes a # standard bar chart. if dim == 1: self.chartdata = array([[data]]) # If the input data is a 2d matrix, then it describes a bar # chart with groups. The matrix being an array of groups of # bars. if dim == 2: self.chartdata = transpose([data], axes=(2, 0, 1)) # If the input data is a 3d matrix, then it describes an array # of groups of bars with each bar being an array of stacked # values. if dim == 3: self.chartdata = transpose(data, axes=(1, 2, 0))
def _process_values(self, b=None): ''' Set the _boundaries and _values attributes based on the input boundaries and values. Input boundaries can be self.boundaries or the argument b. ''' if b is None: b = self.boundaries if b is not None: self._boundaries = nx.array(b) if self.values is None: self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.no_norm): self._values = (self._values + 0.00001).astype(nx.Int16) return self._values = nx.array(self.values) return if self.values is not None: self._values = nx.array(self.values) if self.boundaries is None: b = nx.zeros(len(self.values) + 1, 'd') b[1:-1] = 0.5 * (self._values[:-1] - self._values[1:]) b[0] = 2.0 * b[1] - b[2] b[-1] = 2.0 * b[-2] - b[-3] self._boundaries = b return self._boundaries = nx.array(self.boundaries) return if isinstance(self.norm, colors.no_norm): b = nx.arange(self.norm.vmin, self.norm.vmax + 2) - 0.5 else: dv = self.norm.vmax - self.norm.vmin b = self.norm.vmin + dv * self._uniform_y(self.cmap.N + 1) self._process_values(b)
def _process_values(self, b=None): """ Set the _boundaries and _values attributes based on the input boundaries and values. Input boundaries can be self.boundaries or the argument b. """ if b is None: b = self.boundaries if b is not None: self._boundaries = nx.array(b) if self.values is None: self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:]) if isinstance(self.norm, colors.no_norm): self._values = (self._values + 0.00001).astype(nx.Int16) return self._values = nx.array(self.values) return if self.values is not None: self._values = nx.array(self.values) if self.boundaries is None: b = nx.zeros(len(self.values) + 1, "d") b[1:-1] = 0.5 * (self._values[:-1] - self._values[1:]) b[0] = 2.0 * b[1] - b[2] b[-1] = 2.0 * b[-2] - b[-3] self._boundaries = b return self._boundaries = nx.array(self.boundaries) return if isinstance(self.norm, colors.no_norm): b = nx.arange(self.norm.vmin, self.norm.vmax + 2) - 0.5 else: dv = self.norm.vmax - self.norm.vmin b = self.norm.vmin + dv * self._uniform_y(self.cmap.N + 1) self._process_values(b)
def draw_line(self, gc, x1, y1, x2, y2): """ x and y are equal length arrays, draw lines connecting each point in x, y """ if DEBUG: print 'RendererAgg.draw_line' x = array([x1,x2], typecode=Float) y = array([y1,y2], typecode=Float) self._renderer.draw_lines(gc, x, y)
def draw_line(self, gc, x1, y1, x2, y2): """ x and y are equal length arrays, draw lines connecting each point in x, y """ if DEBUG: print 'RendererAgg.draw_line' x = array([x1, x2], typecode=Float) y = array([y1, y2], typecode=Float) self._renderer.draw_lines(gc, x, y)
def draw_line(self, gc, x1, y1, x2, y2): """ x and y are equal length arrays, draw lines connecting each point in x, y """ if __debug__: verbose.report('RendererAgg.draw_line', 'debug-annoying') x = array([x1,x2], typecode=Float) y = array([y1,y2], typecode=Float) self._renderer.draw_lines(gc, x, y)
def draw_line(self, gc, x1, y1, x2, y2): """ x and y are equal length arrays, draw lines connecting each point in x, y """ if __debug__: verbose.report('RendererAgg.draw_line', 'debug-annoying') x = array([x1, x2], typecode=Float) y = array([y1, y2], typecode=Float) self._renderer.draw_lines(gc, x, y)
def plot(self): win = gtk.Window() winBox = gtk.HBox() plotBox = gtk.VBox() rightBox = gtk.VBox() statFrame = gtk.Frame() statBox = gtk.VBox() winBox.pack_start(plotBox) rightBox.pack_start(statFrame, True, False) winBox.pack_start(rightBox, False, False) # statFrame.add (statBox) win.add (winBox) fig = Figure(figsize=(5,4), dpi=100) ax = fig.add_subplot(111) ax.plot(self.x,self.y) ax.hold(True) xMean = array([0.0, self.y.size()]) yMean = array([self.mean, self.mean]) h1 = ax.plot(xMean, yMean, 'g', linewidth=2) ax.set_title(self.name) ax.set_xlabel("block") ax.set_ylabel("Energy") canvas = FigureCanvas(fig) plotBox.pack_start(canvas) toolbar = NavigationToolbar(canvas, win) plotBox.pack_start(toolbar, False, False) # Make statistics box statFrame.set_label("Statistics") statTable = gtk.Table(3, 2, False) statFrame.add(statTable) (meanStr, errorStr) = MeanErrorString(self.mean, self.error) meanLabel1 = gtk.Label("Mean: ") meanLabel2 = gtk.Label(meanStr + " +/- " + errorStr) statTable.attach(meanLabel1, 0, 1, 0, 1, gtk.SHRINK) statTable.attach(meanLabel2, 1, 2, 0, 1, gtk.SHRINK) varStr = '%1.2f' % self.var varLabel1 = gtk.Label("Variance:") varLabel2 = gtk.Label(varStr) statTable.attach(varLabel1, 0, 1, 1, 2, gtk.SHRINK) statTable.attach(varLabel2, 1, 2, 1, 2, gtk.SHRINK) kappaStr= '%1.2f' % self.kappa kappaLabel1=gtk.Label("Kappa: ") kappaLabel2=gtk.Label(kappaStr) statTable.attach(kappaLabel1, 0, 1, 2, 3, gtk.SHRINK) statTable.attach(kappaLabel2, 1, 2, 2, 3, gtk.SHRINK) win.set_size_request(650,500) win.show_all()
def volume_overlay2(ax, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """ Add a volume overlay to the current axes. The closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency nb: first point is not displayed - it is used only for choosing the right color """ opens = nx.array(closes[:-1]) last = 0 for i in range(0,len(opens)): if opens[i] == -1: opens[i] = last else: last = opens[i] return volume_overlay(ax,opens,closes[1:],volumes[1:],colorup,colordown,width,alpha)
def _ticker(self): ''' Return two sequences: ticks (colorbar data locations) and ticklabels (strings). ''' locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.no_norm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.no_norm): intv = Interval(Value(self._values[0]), Value(self._values[-1])) else: intv = Interval(Value(self.vmin), Value(self.vmax)) locator.set_view_interval(intv) locator.set_data_interval(intv) formatter.set_view_interval(intv) formatter.set_data_interval(intv) b = nx.array(locator()) eps = 0.001 * (self.vmax - self.vmin) b = nx.compress((b >= self.vmin - eps) & (b <= self.vmax + eps), b) ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t) for t in b] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def load(fname,comments='%',delimiter=None): """ Load ASCII data from fname into an array and return the array (from pylab). """ if fname.endswith('.gz'): import gzip fh = gzip.open(fname) else: fh = file(fname) X = [] numCols = None for line in fh: line = line[:line.find(comments)].strip() if not len(line): continue row = [float(val) for val in line.split(delimiter)] thisLen = len(row) if numCols is not None and thisLen != numCols: raise ValueError('All rows must have the same number of columns') X.append(row) X = nx.array(X) r,c = X.shape if r==1 or c==1: X.shape = max([r,c]), return X
def volume_overlay2(ax, closes, volumes, colorup='k', colordown='r', width=4, alpha=1.0): """ Add a volume overlay to the current axes. The closes are used to determine the color of the bar. -1 is missing. If a value is missing on one it must be missing on all ax : an Axes instance to plot to width : the bar width in points colorup : the color of the lines where close >= open colordown : the color of the lines where close < open alpha : bar transparency nb: first point is not displayed - it is used only for choosing the right color """ opens = nx.array(closes[:-1]) last = 0 for i in range(0, len(opens)): if opens[i] == -1: opens[i] = last else: last = opens[i] return volume_overlay(ax, opens, closes[1:], volumes[1:], colorup, colordown, width, alpha)
def _ticker(self): """ Return two sequences: ticks (colorbar data locations) and ticklabels (strings). """ locator = self.locator formatter = self.formatter if locator is None: if self.boundaries is None: if isinstance(self.norm, colors.no_norm): nv = len(self._values) base = 1 + int(nv / 10) locator = ticker.IndexLocator(base=base, offset=0) else: locator = ticker.MaxNLocator() else: b = self._boundaries[self._inside] locator = ticker.FixedLocator(b, nbins=10) if isinstance(self.norm, colors.no_norm): intv = Interval(Value(self._values[0]), Value(self._values[-1])) else: intv = Interval(Value(self.vmin), Value(self.vmax)) locator.set_view_interval(intv) locator.set_data_interval(intv) formatter.set_view_interval(intv) formatter.set_data_interval(intv) b = nx.array(locator()) eps = 0.001 * (self.vmax - self.vmin) b = nx.compress((b >= self.vmin - eps) & (b <= self.vmax + eps), b) ticks = self._locate(b) formatter.set_locs(b) ticklabels = [formatter(t) for t in b] offset_string = formatter.get_offset() return ticks, ticklabels, offset_string
def _clicked(self, event): if event.button !=1 : return if event.inaxes != self.ax: return xy = self.ax.transAxes.inverse_xy_tup((event.x, event.y)) pclicked = array([xy[0], xy[1]]) def inside(p): pcirc = array([p.center[0], p.center[1]]) return dist(pclicked, pcirc) < p.radius for p,t in zip(self.circles, self.labels): if t.get_window_extent().contains(event.x, event.y) or inside(p): inp = p thist = t break else: return for p in self.circles: if p==inp: color = self.activecolor else: color = self.ax.get_axis_bgcolor() p.set_facecolor(color) if self.drawon: self.ax.figure.canvas.draw() if not self.eventson: return for cid, func in self.observers.items(): func(thist.get_text())
def init_plot_data(self): a = self.figmgr.add_subplot(111) self.ind = numpy.arange(60) tmp = [] for i in range(60): tmp.append(numpy.sin((self.ind + i) * numpy.pi / 15)) self.X = numpy.array(tmp) self.lines = a.plot(self.X[:, 0], 'o') self.count = 0
def init_plot_data(self): a = self.figmgr.add_subplot(111) self.ind = numpy.arange(60) tmp = [] for i in range(60): tmp.append(numpy.sin((self.ind+i)*numpy.pi/15)) self.X = numpy.array(tmp) self.lines = a.plot(self.X[:,0],'o') self.count = 0
def _h_arrows(self, length): ''' length is in arrow width units ''' minsh = self.minshaft * self.headlength N = len(length) length = nx.reshape(length, (N,1)) x = nx.array([0, -self.headaxislength, -self.headlength, 0], nx.Float64) x = x + nx.array([0,1,1,1]) * length y = 0.5 * nx.array([1, 1, self.headwidth, 0], nx.Float64) y = nx.repeat(y[nx.newaxis,:], N) x0 = nx.array([0, minsh-self.headaxislength, minsh-self.headlength, minsh], nx.Float64) y0 = 0.5 * nx.array([1, 1, self.headwidth, 0], nx.Float64) ii = [0,1,2,3,2,1,0] X = nx.take(x, ii, 1) Y = nx.take(y, ii, 1) Y[:, 3:] *= -1 X0 = nx.take(x0, ii) Y0 = nx.take(y0, ii) Y0[3:] *= -1 shrink = length/minsh X0 = shrink * X0[nx.newaxis,:] Y0 = shrink * Y0[nx.newaxis,:] short = nx.repeat(length < minsh, 7, 1) #print 'short', length < minsh X = nx.where(short, X0, X) Y = nx.where(short, Y0, Y) if self.pivot[:3] == 'mid': X -= 0.5 * X[:,3, nx.newaxis] elif self.pivot[:3] == 'tip': X = X - X[:,3, nx.newaxis] #numpy bug? using -= does not # work here unless we multiply # by a float first, as with 'mid'. tooshort = length < self.minlength if nx.any(tooshort): th = nx.arange(0,7,1, nx.Float64) * (nx.pi/3.0) x1 = nx.cos(th) * self.minlength * 0.5 y1 = nx.sin(th) * self.minlength * 0.5 X1 = nx.repeat(x1[nx.newaxis, :], N, 0) Y1 = nx.repeat(y1[nx.newaxis, :], N, 0) tooshort = nx.repeat(tooshort, 7, 1) X = nx.where(tooshort, X1, X) Y = nx.where(tooshort, Y1, Y) return X, Y
def onpress(self, event): if event.inaxes != self.ax: return if event.button != 1: return # click location in screen coords x, y = nx.array((event.x, event.y)) tx, ty = event.inaxes.transData.numerix_x_y(self.xs, self.ys) d = nx.sqrt((x - tx)**2 + (y - ty)**2) ind = nx.nonzero(d < 5) for i in ind: self.pnts[i].plotraw()
def onpress(self, event): if event.inaxes != self.ax: return if event.button!=1: return # click location in screen coords x, y = nx.array((event.x, event.y)) tx, ty = event.inaxes.transData.numerix_x_y(self.xs, self.ys) d = nx.sqrt((x-tx)**2 + (y-ty)**2) ind = nx.nonzero(d<5) for i in ind: self.pnts[i].plotraw()
def set_err(self, err): if err is None: self.inputerr = None self.charterr = None return err = array(err) dim = len(shape(err)) if dim not in (1, 2, 3): raise AttributeError, "Input err must be a 1, 2, or 3d matrix" self.inputerr = err if dim == 1: self.charterr = array([[err]]) if dim == 2: self.charterr = transpose([err], axes=(2, 0, 1)) if dim == 3: self.charterr = transpose(err, axes=(1, 2, 0))
def __call__(self,lon,lat,inverse=False): """ Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. For cylindrical equidistant projection ('cyl'), this does nothing (i.e. x,y == lon,lat). lon,lat can be either scalar floats or N arrays. """ if self.projection == 'cyl': # for cyl x,y == lon,lat return lon,lat # if inputs are numarray arrays, get shape and typecode. try: shapein = lon.shape lontypein = lon.typecode() lattypein = lat.typecode() except: shapein = False # make sure inputs have same shape. if shapein and lat.shape != shapein: raise ValueError, 'lon, lat must be scalars or numarrays with the same shape' if shapein: x = N.ravel(lon).tolist() y = N.ravel(lat).tolist() if inverse: outx, outy = self._inv(x,y) else: outx, outy = self._fwd(x,y) outx = N.reshape(N.array(outx,lontypein),shapein) outy = N.reshape(N.array(outy,lattypein),shapein) else: if inverse: outx,outy = self._inv(lon,lat) else: outx,outy = self._fwd(lon,lat) return outx,outy
def __call__(self, lon, lat, inverse=False): """ Calling a Proj class instance with the arguments lon, lat will convert lon/lat (in degrees) to x/y native map projection coordinates (in meters). If optional keyword 'inverse' is True (default is False), the inverse transformation from x/y to lon/lat is performed. For cylindrical equidistant projection ('cyl'), this does nothing (i.e. x,y == lon,lat). lon,lat can be either scalar floats or N arrays. """ if self.projection == 'cyl': # for cyl x,y == lon,lat return lon, lat # if inputs are numarray arrays, get shape and typecode. try: shapein = lon.shape lontypein = lon.typecode() lattypein = lat.typecode() except: shapein = False # make sure inputs have same shape. if shapein and lat.shape != shapein: raise ValueError, 'lon, lat must be scalars or numarrays with the same shape' if shapein: x = N.ravel(lon).tolist() y = N.ravel(lat).tolist() if inverse: outx, outy = self._inv(x, y) else: outx, outy = self._fwd(x, y) outx = N.reshape(N.array(outx, lontypein), shapein) outy = N.reshape(N.array(outy, lattypein), shapein) else: if inverse: outx, outy = self._inv(lon, lat) else: outx, outy = self._fwd(lon, lat) return outx, outy
def get_ticker(ticker): vals = [] lines = file( 'data/%s.csv' % ticker ).readlines() for line in lines[1:]: vals.append([float(val) for val in line.split(',')[1:]]) M = array(vals) c = C() c.open = M[:,0] c.high = M[:,1] c.low = M[:,2] c.close = M[:,3] c.volume = M[:,4] return c
def invert_vec6(v): """ v is a,b,c,d,tx,ty vec6 repr of a matrix [ a b 0 c d 0 tx ty 1] Return the inverse of v as a vec6 """ M = array([[a, b, 0], [c, d, 0], [tx, ty, 1]], typecode=Float) Mi = inverse(M) a, b = M[0, 0:2] c, d = M[1, 0:2] tx, ty = M[2, 0:2] return a, b, c, d, tx, ty
def invert_vec6(v): """ v is a,b,c,d,tx,ty vec6 repr of a matrix [ a b 0 c d 0 tx ty 1] Return the inverse of v as a vec6 """ M = array([ [a,b,0], [c,d,0], [tx,ty,1]], typecode=Float) Mi = inverse(M) a, b = M[0,0:2] c, d = M[1,0:2] tx, ty = M[2,0:2] return a,b,c,d,tx,ty
def add_lines(self, levels, colors, linewidths): """ Draw lines on the colorbar. """ N = len(levels) y = self._locate(levels) x = nx.array([0.0, 1.0]) X, Y = meshgrid(x, y) if self.orientation == "vertical": xy = [zip(X[i], Y[i]) for i in range(N)] else: xy = [zip(Y[i], X[i]) for i in range(N)] col = LineCollection(xy, linewidths=linewidths) self.lines = col col.set_color(colors) self.ax.add_collection(col)
def add_lines(self, levels, colors, linewidths): ''' Draw lines on the colorbar. ''' N = len(levels) y = self._locate(levels) x = nx.array([0.0, 1.0]) X, Y = meshgrid(x, y) if self.orientation == 'vertical': xy = [zip(X[i], Y[i]) for i in range(N)] else: xy = [zip(Y[i], X[i]) for i in range(N)] col = LineCollection(xy, linewidths=linewidths) self.lines = col col.set_color(colors) self.ax.add_collection(col)
def get_ticker(ticker): vals = [] lines = file( '%s' % ticker ).readlines() for line in lines[1:]: try: vals.append([float(val) for val in line.split()[0:]]) except: pass M = array(vals) c = C() c.sma = M[:,0] c.flux = M[:,1] c.flux_err = M[:,2] c.mag = M[:,3] c.mag_uerr = M[:,4] c.mag_lerr = M[:,5] return c
def _init(self): if not self._initialized: self._set_transform() _pivot = self.Q.pivot self.Q.pivot = self.pivot[self.labelpos] self.verts = self.Q._make_verts(nx.array([self.U]), nx.zeros((1,))) self.Q.pivot = _pivot kw = self.Q.polykw kw.update(self.kw) self.vector = PolyCollection(self.verts, offsets=[(self.X,self.Y)], transOffset=self.get_transform(), **kw) if self.color is not None: self.vector.set_color(self.color) self.vector.set_transform(self.Q.get_transform()) self._initialized = True
def __init__( self, strengthRange, ax, pos, decay_time=2 ) : n = 25 t = arange(n)*2*pi/n self.disc = array([(cos(x),sin(x)) for x in t]) self.strength = 0 self.pos = pos self.offset = (279, 157) self.scale = 1.35 self.max_size = 5 #0.5 self.min_size = 0.10 #0.05 self.size = self.min_size self.color = '#ff8000' self.decay_time = decay_time self.strengthRange = strengthRange self.t0 = 0 v = self.disc * self.size + self.pos self.poly = ax.fill( v[:,0], v[:,1], self.color )
def _mesh(self): ''' Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function. ''' x = nx.array([0.0, 1.0]) if self.spacing == 'uniform': y = self._uniform_y(self._central_N()) else: y = self._proportional_y() self._y = y X, Y = meshgrid(x, y) if self.extend in ('min', 'both'): X[0, :] = 0.5 if self.extend in ('max', 'both'): X[-1, :] = 0.5 return X, Y
def _mesh(self): """ Return X,Y, the coordinate arrays for the colorbar pcolormesh. These are suitable for a vertical colorbar; swapping and transposition for a horizontal colorbar are done outside this function. """ x = nx.array([0.0, 1.0]) if self.spacing == "uniform": y = self._uniform_y(self._central_N()) else: y = self._proportional_y() self._y = y X, Y = meshgrid(x, y) if self.extend in ("min", "both"): X[0, :] = 0.5 if self.extend in ("max", "both"): X[-1, :] = 0.5 return X, Y
def savecsv(self, name): f = file(name, 'w') data = array(self.inputdata) dim = len(data.shape) if dim == 1: #if self.xlabel: # f.write(', '.join(list(self.xlabel)) + '\n') f.write(', '.join(['%f' % val for val in data]) + '\n') if dim == 2: #if self.xlabel: # f.write(', '.join([''] + list(self.xlabel)) + '\n') for i, row in enumerate(data): ylabel = [] #if self.ylabel: # ylabel = [ self.ylabel[i] ] f.write(', '.join(ylabel + ['%f' % v for v in row]) + '\n') if dim == 3: f.write("don't do 3D csv files\n") pass f.close()
def savecsv(self, name): f = file(name, "w") data = array(self.inputdata) dim = len(data.shape) if dim == 1: # if self.xlabel: # f.write(', '.join(list(self.xlabel)) + '\n') f.write(", ".join(["%f" % val for val in data]) + "\n") if dim == 2: # if self.xlabel: # f.write(', '.join([''] + list(self.xlabel)) + '\n') for i, row in enumerate(data): ylabel = [] # if self.ylabel: # ylabel = [ self.ylabel[i] ] f.write(", ".join(ylabel + ["%f" % v for v in row]) + "\n") if dim == 3: f.write("don't do 3D csv files\n") pass f.close()
def _locate(self, x): ''' Return the colorbar data coordinate(s) corresponding to the color value(s) in scalar or array x. Used for tick positioning. ''' b = self._boundaries y = self._y N = len(b) ii = nx.minimum(nx.searchsorted(b, x), N - 1) isscalar = False if not iterable(ii): isscalar = True ii = nx.array((ii, )) i0 = nx.maximum(ii - 1, 0) #db = b[ii] - b[i0] db = nx.take(b, ii) - nx.take(b, i0) db = nx.where(i0 == ii, 1.0, db) #dy = y[ii] - y[i0] dy = nx.take(y, ii) - nx.take(y, i0) z = nx.take(y, i0) + (x - nx.take(b, i0)) * dy / db if isscalar: z = z[0] return z
def _locate(self, x): """ Return the colorbar data coordinate(s) corresponding to the color value(s) in scalar or array x. Used for tick positioning. """ b = self._boundaries y = self._y N = len(b) ii = nx.minimum(nx.searchsorted(b, x), N - 1) isscalar = False if not iterable(ii): isscalar = True ii = nx.array((ii,)) i0 = nx.maximum(ii - 1, 0) # db = b[ii] - b[i0] db = nx.take(b, ii) - nx.take(b, i0) db = nx.where(i0 == ii, 1.0, db) # dy = y[ii] - y[i0] dy = nx.take(y, ii) - nx.take(y, i0) z = nx.take(y, i0) + (x - nx.take(b, i0)) * dy / db if isscalar: z = z[0] return z
def __array__(self, t=None, context=None): ret = nx.array([1]) if t is not None: return ret.astype(t) else: return ret
if not len(line): continue row = [float(val) for val in line.split(delimiter)] thisLen = len(row) if numCols is not None and thisLen != numCols: raise ValueError('All rows must have the same number of columns') X.append(row) X = nx.array(X) r,c = X.shape if r==1 or c==1: X.shape = max([r,c]), return X # read in topo data (on a regular lat/lon grid) # longitudes go from 20 to 380. etopo = nx.array(load('etopo20data.gz'),'d') lons = nx.array(load('etopo20lons.gz'),'d') lats = nx.array(load('etopo20lats.gz'),'d') # create figure. fig = Figure() canvas = FigureCanvas(fig) # create axes instance, leaving room for colorbar at bottom. ax = fig.add_axes([0.125,0.175,0.75,0.75]) # create Basemap instance for Robinson projection. # set 'ax' keyword so pylab won't be imported. m = Basemap(projection='robin',lon_0=0.5*(lons[0]+lons[-1]),ax=ax) # reset figure size to have same aspect ratio as map. # fig will be 8 inches wide. # (don't use createfigure, since that imports pylab). fig.set_figsize_inches((8,m.aspect*8.)) # make filled contour plot.
#!/usr/bin/env python2.3 import matplotlib matplotlib.use('TkAgg') import pylab #import Tkinter as Tk import matplotlib.numerix as numerix fig = pylab.figure(1) ind = numerix.arange(60) x_tmp = [] for i in range(100): x_tmp.append(numerix.sin((ind + i) * numerix.pi / 15.0)) X = numerix.array(x_tmp) lines = pylab.plot(X[:, 0], 'o') manager = pylab.get_current_fig_manager() def updatefig(*args): updatefig.count += 1 lines[0].set_ydata(X[:, updatefig.count % 60]) manager.canvas.draw() return updatefig.count updatefig.count = -1
that is, a single tuple instead of a list of tuples, to generate successively offset curves, with the offset given in data units. This behavior is available only for the LineCollection. ''' import pylab as P from matplotlib import collections, axes, transforms from matplotlib.colors import colorConverter import matplotlib.numerix as N nverts = 50 npts = 100 # Make some spirals r = N.array(range(nverts)) theta = N.array(range(nverts)) * (2*N.pi)/(nverts-1) xx = r * N.sin(theta) yy = r * N.cos(theta) spiral = zip(xx,yy) # Make some offsets xo = P.randn(npts) yo = P.randn(npts) xyo = zip(xo, yo) # Make a list of colors cycling through the rgbcmyk series. colors = [colorConverter.to_rgba(c) for c in ('r','g','b','c','y','m','k')] fig = P.figure()
# test transformation of sequence of xy tuples xy = affine.seq_xy_tups(( (10, 20), (20, 30), )) assert (xy[0] == (90, 380)) assert (xy[1] == (190, 580)) # test transformation of x and y sequences xy = affine.seq_x_y((10, 20), (20, 30)) assert (xy[0] == (90, 190)) assert (xy[1] == (380, 580)) # test with numeric arrays xy = affine.seq_x_y(array((10, 20)), array((20, 30))) assert (xy[0] == (90, 190)) assert (xy[1] == (380, 580)) # now change the x scale factor and make sure the affine updated # properly a.set(20) xy = affine.seq_xy_tups(( (10, 20), (20, 30), )) assert (xy[0] == (190, 380)) assert (xy[1] == (390, 580)) # Test the aritmetic operations on lazy values v1 = Value(10)
#!/usr/bin/env python2.3 import matplotlib matplotlib.use('TkAgg') import matplotlib.matlab #import Tkinter as Tk import matplotlib.numerix as numerix fig = matplotlib.matlab.figure(1) ind = numerix.arange(60) x_tmp=[] for i in range(100): x_tmp.append(numerix.sin((ind+i)*numerix.pi/15.0)) X=numerix.array(x_tmp) lines = matplotlib.matlab.plot(X[:,0],'o') manager = matplotlib.matlab.get_current_fig_manager() def updatefig(*args): updatefig.count += 1 lines[0].set_ydata(X[:,updatefig.count%60]) manager.canvas.draw() return updatefig.count updatefig.count=-1 manager.show() import time tstart = time.time() while 1:
x, y = affine.xy_tup( (10,20) ) assert(x==90) assert(y==380) # test transformation of sequence of xy tuples xy = affine.seq_xy_tups( ( (10,20), (20,30), ) ) assert(xy[0] == (90, 380)) assert(xy[1] == (190, 580)) # test transformation of x and y sequences xy = affine.seq_x_y( (10,20), (20,30)) assert(xy[0] == (90, 190)) assert(xy[1] == (380, 580)) # test with numeric arrays xy = affine.seq_x_y( array((10,20)), array((20,30))) assert(xy[0] == (90, 190)) assert(xy[1] == (380, 580)) # now change the x scale factor and make sure the affine updated # properly a.set(20) xy = affine.seq_xy_tups( ( (10,20), (20,30), ) ) assert(xy[0] == (190, 380)) assert(xy[1] == (390, 580)) # Test the aritmetic operations on lazy values v1 = Value(10) v2 = Value(20) o1 = v1 + v2 assert( o1.get() == 30)
def graph(self): if self.chartdata is None: raise AttributeError, "Data not set for bar chart!" dim = len(shape(self.inputdata)) cshape = shape(self.chartdata) if self.charterr is not None and shape(self.charterr) != cshape: raise AttributeError, 'Dimensions of error and data do not match' if dim == 1: colors = self.gen_colors(cshape[2]) colors = [[colors] * cshape[1]] * cshape[0] if dim == 2: colors = self.gen_colors(cshape[0]) colors = [[[c] * cshape[2]] * cshape[1] for c in colors] if dim == 3: colors = self.gen_colors(cshape[1]) colors = [[[c] * cshape[2] for c in colors]] * cshape[0] colors = array(colors) self.figure = pylab.figure(figsize=self.chart_size) outer_axes = None inner_axes = None if self.xsubticks is not None: color = self.figure.get_facecolor() self.metaaxes = self.figure.add_axes(self.figure_size, axisbg=color, frameon=False) for tick in self.metaaxes.xaxis.majorTicks: tick.tick1On = False tick.tick2On = False self.metaaxes.set_yticklabels([]) self.metaaxes.set_yticks([]) size = [0] * 4 size[0] = self.figure_size[0] size[1] = self.figure_size[1] + .12 size[2] = self.figure_size[2] size[3] = self.figure_size[3] - .12 self.axes = self.figure.add_axes(size) outer_axes = self.metaaxes inner_axes = self.axes else: self.axes = self.figure.add_axes(self.figure_size) outer_axes = self.axes inner_axes = self.axes bars_in_group = len(self.chartdata) width = 1.0 / (bars_in_group + 1) center = width / 2 bars = [] for i, stackdata in enumerate(self.chartdata): bottom = array([0.0] * len(stackdata[0]), Float) stack = [] for j, bardata in enumerate(stackdata): bardata = array(bardata) ind = arange(len(bardata)) + i * width + center yerr = None if self.charterr is not None: yerr = self.charterr[i][j] bar = self.axes.bar(ind, bardata, width, bottom=bottom, color=colors[i][j], yerr=yerr) if self.xsubticks is not None: self.metaaxes.bar(ind, [0] * len(bardata), width) stack.append(bar) bottom += bardata bars.append(stack) if self.xlabel is not None: outer_axes.set_xlabel(self.xlabel) if self.ylabel is not None: inner_axes.set_ylabel(self.ylabel) if self.yticks is not None: ymin, ymax = self.axes.get_ylim() nticks = float(len(self.yticks)) ticks = arange(nticks) / (nticks - 1) * (ymax - ymin) + ymin inner_axes.set_yticks(ticks) inner_axes.set_yticklabels(self.yticks) elif self.ylim is not None: inner_axes.set_ylim(self.ylim) if self.xticks is not None: outer_axes.set_xticks(arange(cshape[2]) + .5) outer_axes.set_xticklabels(self.xticks) if self.xsubticks is not None: numticks = (cshape[0] + 1) * cshape[2] inner_axes.set_xticks(arange(numticks) * width + 2 * center) xsubticks = list(self.xsubticks) + [''] inner_axes.set_xticklabels(xsubticks * cshape[2], fontsize=7, rotation=30) if self.legend is not None: if dim == 1: lbars = bars[0][0] if dim == 2: lbars = [bars[i][0][0] for i in xrange(len(bars))] if dim == 3: number = len(bars[0]) lbars = [bars[0][number - j - 1][0] for j in xrange(number)] if self.fig_legend: self.figure.legend(lbars, self.legend, self.legend_loc, prop=FontProperties(size=self.legend_size)) else: self.axes.legend(lbars, self.legend, self.legend_loc, prop=FontProperties(size=self.legend_size)) if self.title is not None: self.axes.set_title(self.title)
def draw_line(self, gc, x1, y1, x2, y2): """ Draw a single line from x1,y1 to x2,y2 """ self.draw_lines(gc, array([x1, x2]), array([y1, y2]))
import fileinput HEADER_END = 0 #step = [] sig_ts = [] infile = sys.argv[1] INTERVAL = int(sys.argv[2]) outfile = sys.argv[1].split('.')[0] + '.pdf' for line in fileinput.input(infile): if fileinput.lineno() <= HEADER_END: continue else: ts = line.split()[1] sig_ts.append(int(ts)) items = len(sig_ts) #x = arange(len(sig_ts)) y1 = array(sig_ts) b = (sig_ts[items - 1] - sig_ts[0]) / INTERVAL hist(y1, b) #plot(x, y1) #title("TaskInfo Signaling Frequency" ) xlabel("TimeStamp (s)") ylabel("No. of Received Peer Signals") grid("True") savefig(outfile) show()
def inside(p): pcirc = array([p.center[0], p.center[1]]) return dist(pclicked, pcirc) < p.radius
def graph(self, name, graphdir, proxy=None): from os.path import expanduser, isdir, join as joinpath from barchart import BarChart from matplotlib.numerix import Float, array, zeros import os, re, urllib from jobfile import crossproduct confgroups = self.jobfile.groups() ngroups = len(confgroups) skiplist = [ False ] * ngroups groupopts = [] baropts = [] groups = [] for i,group in enumerate(confgroups): if group.flags.graph_group: groupopts.append(group.subopts()) skiplist[i] = True elif group.flags.graph_bars: baropts.append(group.subopts()) skiplist[i] = True else: groups.append(group) has_group = bool(groupopts) if has_group: groupopts = [ group for group in crossproduct(groupopts) ] else: groupopts = [ None ] if baropts: baropts = [ bar for bar in crossproduct(baropts) ] else: raise AttributeError, 'No group selected for graph bars' directory = expanduser(graphdir) if not isdir(directory): os.mkdir(directory) html = file(joinpath(directory, '%s.html' % name), 'w') print >>html, '<html>' print >>html, '<title>Graphs for %s</title>' % name print >>html, '<body>' html.flush() for options in self.jobfile.options(groups): chart = BarChart(self) data = [ [ None ] * len(baropts) for i in xrange(len(groupopts)) ] enabled = False stacked = 0 for g,gopt in enumerate(groupopts): for b,bopt in enumerate(baropts): if gopt is None: gopt = [] job = self.jobfile.job(options + gopt + bopt) if not job: continue if proxy: import db proxy.dict['system'] = self.info[job.system] val = self.info.get(job, self.stat) if val is None: print 'stat "%s" for job "%s" not found' % \ (self.stat, job) if isinstance(val, (list, tuple)): if len(val) == 1: val = val[0] else: stacked = len(val) data[g][b] = val if stacked == 0: for i in xrange(len(groupopts)): for j in xrange(len(baropts)): if data[i][j] is None: data[i][j] = 0.0 else: for i in xrange(len(groupopts)): for j in xrange(len(baropts)): val = data[i][j] if val is None: data[i][j] = [ 0.0 ] * stacked elif len(val) != stacked: raise ValueError, "some stats stacked, some not" data = array(data) if data.sum() == 0: continue dim = len(data.shape) x = data.shape[0] xkeep = [ i for i in xrange(x) if data[i].sum() != 0 ] y = data.shape[1] ykeep = [ i for i in xrange(y) if data[:,i].sum() != 0 ] data = data.take(xkeep, axis=0) data = data.take(ykeep, axis=1) if not has_group: data = data.take([ 0 ], axis=0) chart.data = data bopts = [ baropts[i] for i in ykeep ] bdescs = [ ' '.join([o.desc for o in opt]) for opt in bopts] if has_group: gopts = [ groupopts[i] for i in xkeep ] gdescs = [ ' '.join([o.desc for o in opt]) for opt in gopts] if chart.legend is None: if stacked: try: chart.legend = self.info.rcategories except: chart.legend = [ str(i) for i in xrange(stacked) ] else: chart.legend = bdescs if chart.xticks is None: if has_group: chart.xticks = gdescs else: chart.xticks = [] chart.graph() names = [ opt.name for opt in options ] descs = [ opt.desc for opt in options ] if names[0] == 'run': names = names[1:] descs = descs[1:] basename = '%s-%s' % (name, ':'.join(names)) desc = ' '.join(descs) pngname = '%s.png' % basename psname = '%s.eps' % re.sub(':', '-', basename) epsname = '%s.ps' % re.sub(':', '-', basename) chart.savefig(joinpath(directory, pngname)) chart.savefig(joinpath(directory, epsname)) chart.savefig(joinpath(directory, psname)) html_name = urllib.quote(pngname) print >>html, '''%s<br><img src="%s"><br>''' % (desc, html_name) html.flush() print >>html, '</body>' print >>html, '</html>' html.close()
def graph(self, name, graphdir, proxy=None): from os.path import expanduser, isdir, join as joinpath from barchart import BarChart from matplotlib.numerix import Float, array, zeros import os, re, urllib from jobfile import crossproduct confgroups = self.jobfile.groups() ngroups = len(confgroups) skiplist = [False] * ngroups groupopts = [] baropts = [] groups = [] for i, group in enumerate(confgroups): if group.flags.graph_group: groupopts.append(group.subopts()) skiplist[i] = True elif group.flags.graph_bars: baropts.append(group.subopts()) skiplist[i] = True else: groups.append(group) has_group = bool(groupopts) if has_group: groupopts = [group for group in crossproduct(groupopts)] else: groupopts = [None] if baropts: baropts = [bar for bar in crossproduct(baropts)] else: raise AttributeError, 'No group selected for graph bars' directory = expanduser(graphdir) if not isdir(directory): os.mkdir(directory) html = file(joinpath(directory, '%s.html' % name), 'w') print >> html, '<html>' print >> html, '<title>Graphs for %s</title>' % name print >> html, '<body>' html.flush() for options in self.jobfile.options(groups): chart = BarChart(self) data = [[None] * len(baropts) for i in xrange(len(groupopts))] enabled = False stacked = 0 for g, gopt in enumerate(groupopts): for b, bopt in enumerate(baropts): if gopt is None: gopt = [] job = self.jobfile.job(options + gopt + bopt) if not job: continue if proxy: import db proxy.dict['system'] = self.info[job.system] val = self.info.get(job, self.stat) if val is None: print 'stat "%s" for job "%s" not found' % \ (self.stat, job) if isinstance(val, (list, tuple)): if len(val) == 1: val = val[0] else: stacked = len(val) data[g][b] = val if stacked == 0: for i in xrange(len(groupopts)): for j in xrange(len(baropts)): if data[i][j] is None: data[i][j] = 0.0 else: for i in xrange(len(groupopts)): for j in xrange(len(baropts)): val = data[i][j] if val is None: data[i][j] = [0.0] * stacked elif len(val) != stacked: raise ValueError, "some stats stacked, some not" data = array(data) if data.sum() == 0: continue dim = len(data.shape) x = data.shape[0] xkeep = [i for i in xrange(x) if data[i].sum() != 0] y = data.shape[1] ykeep = [i for i in xrange(y) if data[:, i].sum() != 0] data = data.take(xkeep, axis=0) data = data.take(ykeep, axis=1) if not has_group: data = data.take([0], axis=0) chart.data = data bopts = [baropts[i] for i in ykeep] bdescs = [' '.join([o.desc for o in opt]) for opt in bopts] if has_group: gopts = [groupopts[i] for i in xkeep] gdescs = [' '.join([o.desc for o in opt]) for opt in gopts] if chart.legend is None: if stacked: try: chart.legend = self.info.rcategories except: chart.legend = [str(i) for i in xrange(stacked)] else: chart.legend = bdescs if chart.xticks is None: if has_group: chart.xticks = gdescs else: chart.xticks = [] chart.graph() names = [opt.name for opt in options] descs = [opt.desc for opt in options] if names[0] == 'run': names = names[1:] descs = descs[1:] basename = '%s-%s' % (name, ':'.join(names)) desc = ' '.join(descs) pngname = '%s.png' % basename psname = '%s.eps' % re.sub(':', '-', basename) epsname = '%s.ps' % re.sub(':', '-', basename) chart.savefig(joinpath(directory, pngname)) chart.savefig(joinpath(directory, epsname)) chart.savefig(joinpath(directory, psname)) html_name = urllib.quote(pngname) print >> html, '''%s<br><img src="%s"><br>''' % (desc, html_name) html.flush() print >> html, '</body>' print >> html, '</html>' html.close()