def longest_ones(x): """ return the indicies of the longest stretch of contiguous ones in x, assuming x is a vector of zeros and ones. If there are two equally long stretches, pick the first """ x = asarray(x) if len(x) == 0: return array([]) #print 'x', x ind = find(x == 0) if len(ind) == 0: return arange(len(x)) if len(ind) == len(x): return array([]) y = zeros((len(x) + 2, ), Int) y[1:-1] = x d = diff(y) #print 'd', d up = find(d == 1) dn = find(d == -1) #print 'dn', dn, 'up', up, ind = find(dn - up == max(dn - up)) # pick the first if iterable(ind): ind = ind[0] ind = arange(up[ind], dn[ind]) return ind
def _initialize_x_y(self, z, origin, extent): ''' 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 len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if origin is None: return meshgrid(arange(Nx), arange(Ny)) if extent is None: x0, x1, y0, y1 = (0, Nx, 0, Ny) else: x0, x1, y0, y1 = 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 origin == 'upper': y = y[::-1] return meshgrid(x, y)
def longest_ones(x): """ return the indicies of the longest stretch of contiguous ones in x, assuming x is a vector of zeros and ones. If there are two equally long stretches, pick the first """ x = asarray(x) if len(x)==0: return array([]) #print 'x', x ind = find(x==0) if len(ind)==0: return arange(len(x)) if len(ind)==len(x): return array([]) y = zeros( (len(x)+2,), Int) y[1:-1] = x d = diff(y) #print 'd', d up = find(d == 1); dn = find(d == -1); #print 'dn', dn, 'up', up, ind = find( dn-up == max(dn - up)) # pick the first if iterable(ind): ind = ind[0] ind = arange(up[ind], dn[ind]) return ind
def filled_regions(epsoutfile): x = arange(0.0, 10.0, 0.1) phi = arange(0.0, 2.0*pi, 0.1) x_circ = cos(phi)-1.5 y_circ = sin(phi)-1.0 x_ell = 1.5*cos(phi)+1.0 y_ell = 0.5*sin(phi)+0.5 g=pyxgraph(xlabel=r"$x$", ylabel=r"$y$", xlimits=(-3.0, 3.0), ylimits=(-4.0, 4.0), key=False) g.pyxplot((x, -sin(x)-1.0), style="p", title=None) # we need at least one plot!! # even if invisible p1 = convert_to_path(g, x_circ, y_circ) g.stroke(p1, [pyx.deco.filled([pyx.color.rgb(0.8, 0.8, 0.8)])]) p2 = convert_to_path(g, x_ell, y_ell) g.stroke(p2, [pyx.deco.stroked([pyx.color.rgb(0.8, 0.2, 0.0)]), pyx.style.linewidth(0.35), pyx.deco.filled([pyx.color.rgb(0.8, 0.8, 0.8)]), ]) # a more funny shape p3 = convert_to_path(g, phi/2.0/pi*x_ell-2.4, 3*y_ell+0.5) g.fill(p3, [pyx.deco.filled([pyx.color.rgb(0.2, 0.8, 0.2)]), ]) g.pyxsave(epsoutfile)
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() b = self._base vmin, vmax = self.viewInterval.get_bounds() vmin = math.log(vmin) / math.log(b) vmax = math.log(vmax) / math.log(b) if vmax < vmin: vmin, vmax = vmax, vmin ticklocs = [] numdec = math.floor(vmax) - math.ceil(vmin) if self._subs is None: # autosub if numdec > 10: subs = array([1.0]) elif numdec > 6: subs = arange(2.0, b, 2.0) else: subs = arange(2.0, b) else: subs = self._subs stride = 1 while numdec / stride + 1 > self.numticks: stride += 1 for decadeStart in b**arange(math.floor(vmin), math.ceil(vmax) + stride, stride): ticklocs.extend(subs * decadeStart) return array(ticklocs)
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() b=self._base vmin, vmax = self.viewInterval.get_bounds() vmin = math.log(vmin)/math.log(b) vmax = math.log(vmax)/math.log(b) if vmax<vmin: vmin, vmax = vmax, vmin ticklocs = [] numdec = math.floor(vmax)-math.ceil(vmin) if self._subs is None: # autosub if numdec>10: subs = array([1.0]) elif numdec>6: subs = arange(2.0, b, 2.0) else: subs = arange(2.0, b) else: subs = self._subs for decadeStart in b**arange(math.floor(vmin),math.ceil(vmax)): ticklocs.extend( subs*decadeStart ) if(len(subs) and subs[0]==1.0): ticklocs.append(b**math.ceil(vmax)) ticklocs = array(ticklocs) ind = nonzero(logical_and(ticklocs>=b**vmin , ticklocs<=b**vmax)) ticklocs = take(ticklocs,ind) return ticklocs
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() b=self._base vmin, vmax = self.viewInterval.get_bounds() vmin = math.log(vmin)/math.log(b) vmax = math.log(vmax)/math.log(b) if vmax<vmin: vmin, vmax = vmax, vmin ticklocs = [] numdec = math.floor(vmax)-math.ceil(vmin) if self._subs is None: # autosub if numdec>10: subs = array([1.0]) elif numdec>6: subs = arange(2.0, b, 2.0) else: subs = arange(2.0, b) else: subs = self._subs stride = 1 while numdec/stride+1 > self.numticks: stride += 1 for decadeStart in b**arange(math.floor(vmin),math.ceil(vmax)+stride, stride): ticklocs.extend( subs*decadeStart ) return array(ticklocs)
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 len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if self.origin is None: return meshgrid(arange(Nx), arange(Ny)) 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 get_xyz_where(Z, Cond): """ Z and Cond are MxN matrices. Z are data and Cond is a boolean matrix where some condition is satisfied. Return value is x,y,z where x and y are the indices into Z and z are the values of Z at those indices. x,y,z are 1D arrays """ M, N = Z.shape z = ravel(Z) ind = nonzero(ravel(Cond)) x = arange(M) x.shape = M, 1 X = repeat(x, N, 1) x = ravel(X) y = arange(N) y.shape = 1, N Y = repeat(y, M) y = ravel(Y) x = take(x, ind) y = take(y, ind) z = take(z, ind) return x, y, z
def colorbars(epsoutfile): x = (arange(50.0)-25)/2.0 y = (arange(50.0)-25)/2.0 r = sqrt(x[:,NewAxis]**2+y**2) z = 5.0*cos(r) colmap = ColMapper.ColorMapper("yellow-red", exponent=0.55, brightness=0.5) lut = colmap.generate_lut() c = pyx.canvas.canvas() g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6) g.pyxplot("y(x)=sin(x)", style="p") # FIXME: can't do empty plots! g.pyxplotarray(z, colmap=lut) c.insert(g) minz = minvalue=min(ravel(z)) maxz = maxvalue=max(ravel(z)) # --- vertical bars dist = 1.2 for orientation, position in [("vertical", "right"), ("vertical", "middle"), ("vertical2", "middle")]: cb = pyxcolorbar(lut=lut, frame=g, pos=(dist, 0), orientation = orientation, position = position, minvalue = minz, maxvalue=maxz) # add a short note on the style: txt = orientation[0] if "2" in orientation: txt += "2" txt += ", "+position[0] cb.pyxlabel( (0.0, 1.3), txt, style=[pyx.text.halign.left]) c.insert(cb) dist = dist + 0.5 # horizontal ones: dist = -0.3 for orientation, position in [("horizontal", "middle"), ("horizontal2", "middle")]: cb = pyxcolorbar(lut=lut, frame=g, pos=(0.0, dist), orientation = orientation, position = position, minvalue = minz, maxvalue=maxz) # add a short note on the style: txt = orientation[0] if "2" in orientation: txt += "2" txt += ", "+position[0] cb.pyxlabel( (1.3, 0.5), txt, style=[pyx.text.halign.left]) c.insert(cb) dist = dist - 0.3 pyxsave(c, epsoutfile)
def _set_clip(self): if not self._useDataClipping: return #self._logcache = None try: self._xmin, self._xmax except AttributeError: indx = arange(len(self._x)) else: if not hasattr(self, '_xsorted'): self._xsorted = self._is_sorted(self._x) if len(self._x) == 1: indx = [0] elif self._xsorted: # for really long signals, if we know they are sorted # on x we can save a lot of time using search sorted # since the alternative approach requires 3 O(len(x) ) ops indMin, indMax = searchsorted(self._x, array([self._xmin, self._xmax])) indMin = max(0, indMin - 1) indMax = min(indMax + 1, len(self._x)) skip = 0 if self._lod: # if level of detail is on, decimate the data # based on pixel width raise NotImplementedError('LOD deprecated') l, b, w, h = self.get_window_extent().get_bounds() skip = int((indMax - indMin) / w) if skip > 0: indx = arange(indMin, indMax, skip) else: indx = arange(indMin, indMax) else: indx = nonzero( logical_and(self._x >= self._xmin, self._x <= self._xmax)) self._xc = take(self._x, indx) self._yc = take(self._y, indx) # y data clipping for connected lines can introduce horizontal # line artifacts near the clip region. If you really need y # clipping for efficiency, consider using plot(y,x) instead. if (self._yc.shape == self._xc.shape and self._linestyle is None): try: self._ymin, self._ymax except AttributeError: indy = arange(len(self._yc)) else: indy = nonzero( logical_and(self._yc >= self._ymin, self._yc <= self._ymax)) else: indy = arange(len(self._yc)) self._xc = take(self._xc, indy) self._yc = take(self._yc, indy)
def _set_clip(self): if not self._useDataClipping: return # self._logcache = None try: self._xmin, self._xmax except AttributeError: indx = arange(len(self._x)) else: if not hasattr(self, "_xsorted"): self._xsorted = self._is_sorted(self._x) if len(self._x) == 1: indx = [0] elif self._xsorted: # for really long signals, if we know they are sorted # on x we can save a lot of time using search sorted # since the alternative approach requires 3 O(len(x) ) ops indMin, indMax = searchsorted(self._x, array([self._xmin, self._xmax])) indMin = max(0, indMin - 1) indMax = min(indMax + 1, len(self._x)) skip = 0 if self._lod: # if level of detail is on, decimate the data # based on pixel width raise NotImplementedError("LOD deprecated") l, b, w, h = self.get_window_extent().get_bounds() skip = int((indMax - indMin) / w) if skip > 0: indx = arange(indMin, indMax, skip) else: indx = arange(indMin, indMax) else: indx = nonzero(logical_and(self._x >= self._xmin, self._x <= self._xmax)) self._xc = take(self._x, indx) self._yc = take(self._y, indx) # y data clipping for connected lines can introduce horizontal # line artifacts near the clip region. If you really need y # clipping for efficiency, consider using plot(y,x) instead. if self._yc.shape == self._xc.shape and self._linestyle is None: try: self._ymin, self._ymax except AttributeError: indy = arange(len(self._yc)) else: indy = nonzero(logical_and(self._yc >= self._ymin, self._yc <= self._ymax)) else: indy = arange(len(self._yc)) self._xc = take(self._xc, indy) self._yc = take(self._yc, indy)
def array_example1(epsoutfile): x = (arange(100.0)-50)/25.0 y = (arange(100.0)-50)/25.0 # Important: z[y, x] -- y first! z = 5.0*sin(2*x[NewAxis, :]) + 3.0*cos(3*y[:, NewAxis]) g=pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6, key=False) g.pyxplotcontour(z, x, y, levels=15, colors='map', colmap=ColMapper.ColorMapper("pm3d", exponent=1.0, brightness=0.2)) g.pyxsave(epsoutfile)
def array_example1(epsoutfile): x = (arange(50.0)-25)/2.0 y = (arange(50.0)-25)/2.0 r = sqrt(x[:,NewAxis]**2+y**2) z = 5.0*sin(r) g=pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6, key=False) # WARNING: if key is not specified to be False, one gets a weird # error .... #g.pyxplot("y(x)=sin(x)", style="p") # FIXME: can't do empty plots! g.pyxplotarray(z, colmap=ColMapper.ColorMapper("yellow-red", exponent=0.55, brightness=0.5)) g.pyxsave(epsoutfile)
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=128): """ Compute a spectrogram of data in x. Data are split into NFFT length segements and the PSD of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap See pdf for more info. The returned times are the midpoints of the intervals over which the ffts are calculated """ x = asarray(x) assert (NFFT > noverlap) if log(NFFT) / log(2) != int(log(NFFT) / log(2)): raise ValueError, 'NFFT must be a power of 2' # zero pad x up to NFFT if it is shorter than NFFT if len(x) < NFFT: n = len(x) x = resize(x, (NFFT, )) x[n:] = 0 # for real x, ignore the negative frequencies if typecode(x) == Complex: numFreqs = NFFT else: numFreqs = NFFT // 2 + 1 windowVals = window(ones((NFFT, ), typecode(x))) step = NFFT - noverlap ind = arange(0, len(x) - NFFT + 1, step) n = len(ind) Pxx = zeros((numFreqs, n), Float) # do the ffts of the slices for i in range(n): thisX = x[ind[i]:ind[i] + NFFT] thisX = windowVals * detrend(thisX) fx = absolute(fft(thisX))**2 # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2 Pxx[:, i] = divide(fx[:numFreqs], norm(windowVals)**2) t = 1 / Fs * (ind + NFFT / 2) freqs = Fs / NFFT * arange(numFreqs) return Pxx, freqs, t
def test_bar2D(): ax = Axes3D() for c,z in zip(['r','g','b','y'],[30,20,10,0]): xs = nx.arange(20) ys = [random.random() for x in xs] ax.bar(xs,ys,z=z,dir='y',color=c)
def __init__(self, dpi, numsides, rotation = 0 , sizes = (1,), **kwargs): """ Draw a regular polygon with numsides. sizes gives the area of the circle circumscribing the regular polygon and rotation is the rotation of the polygon in radians. offsets are a sequence of x,y tuples that give the centers of the polygon in data coordinates, and transOffset is the Transformation instance used to transform the centers onto the canvas. dpi is the figure dpi instance, and is required to do the area scaling. """ PatchCollection.__init__(self,**kwargs) self._sizes = asarray(sizes) self._dpi = dpi r = 1.0/math.sqrt(math.pi) # unit area theta = (2*math.pi/numsides)*arange(numsides) + rotation self._verts = zip( r*sin(theta), r*cos(theta) )
def test_polys(): from matplotlib.collections import LineCollection, PolyCollection from matplotlib.colors import colorConverter cc = lambda arg: colorConverter.to_rgba(arg, alpha=0.6) ax = Axes3D() xs = nx.arange(0,10,0.4) verts = [] zs = [0.0,1.0,2.0,3.0] for z in zs: ys = [random.random() for x in xs] ys[0],ys[-1] = 0,0 verts.append(zip(xs,ys)) poly = PolyCollection(verts, facecolors = [cc('r'),cc('g'),cc('b'), cc('y')]) #patches = art3d.Poly3DCollectionW(poly, zs=zs, dir='y') #poly = PolyCollection(verts) ax.add_collection(poly,zs=zs,dir='y') #ax.wrapped.add_collection(poly) # ax.plot(xs,ys, z=z, dir='y', c='r') ax.set_xlim(0,10) ax.set_ylim(-1,4) ax.set_zlim(0,1)
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() b=self.base subs=self.subs vmin, vmax = self.viewInterval.get_bounds() vmin = math.log(vmin)/math.log(b) vmax = math.log(vmax)/math.log(b) if vmax<vmin: vmin, vmax = vmax, vmin ticklocs = [] for decadeStart in b**arange(math.floor(vmin),math.ceil(vmax)): ticklocs.extend( subs*decadeStart ) if(len(subs) and subs[0]==1.0): ticklocs.append(b**math.ceil(vmax)) ticklocs = array(ticklocs) ind = nonzero(logical_and(ticklocs>=b**vmin , ticklocs<=b**vmax)) ticklocs = take(ticklocs,ind) return ticklocs
def psd(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=0): """ The power spectral density by Welches average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noperlap gives the length of the overlap between segments. The absolute(fft(segment))**2 of each segment are averaged to compute Pxx, with a scaling to correct for power loss due to windowing. Fs is the sampling frequency. -- NFFT must be a power of 2 -- detrend and window are functions, unlike in matlab where they are vectors. -- if length x < NFFT, it will be zero padded to NFFT Returns the tuple Pxx, freqs Refs: Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986) """ if NFFT % 2: raise ValueError, 'NFFT must be a power of 2' # zero pad x up to NFFT if it is shorter than NFFT if len(x)<NFFT: n = len(x) x = resize(x, (NFFT,)) x[n:] = 0 # for real x, ignore the negative frequencies if x.typecode()==Complex: numFreqs = NFFT else: numFreqs = NFFT//2+1 windowVals = window(ones((NFFT,),x.typecode())) step = NFFT-noverlap ind = range(0,len(x)-NFFT+1,step) n = len(ind) Pxx = zeros((numFreqs,n), Float) # do the ffts of the slices for i in range(n): thisX = x[ind[i]:ind[i]+NFFT] thisX = windowVals*detrend(thisX) fx = absolute(fft(thisX))**2 Pxx[:,i] = divide(fx[:numFreqs], norm(windowVals)**2) # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2 if n>1: Pxx = mean(Pxx,1) freqs = Fs/NFFT*arange(numFreqs) Pxx.shape = len(freqs), return Pxx, freqs
def _draw_circle(self, renderer, gc, xt, yt, point=False): w = renderer.points_to_pixels(self._markersize) if point: w *= self._point_size_reduction rgbFace = self._get_rgb_face() if self._newstyle: N = 50.0 r = w/2. rads = (2*math.pi/N)*arange(N) xs = r*cos(rads) ys = r*sin(rads) # todo: use curve3! path = agg.path_storage() path.move_to(xs[0], ys[0]) for x, y in zip(xs[1:], ys[1:]): path.line_to(x, y) path.end_poly() renderer.draw_markers(gc, path, rgbFace, xt, yt, self._transform) else: for (x,y) in zip(xt, yt): renderer.draw_arc(gc, rgbFace, x, y, w, w, 0.0, 360.0)
def specgram(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, noverlap=128): """ Compute a spectrogram of data in x. Data are split into NFFT length segements and the PSD of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap See pdf for more info. The returned times are the midpoints of the intervals over which the ffts are calculated """ assert(NFFT>noverlap) if log(NFFT)/log(2) != int(log(NFFT)/log(2)): raise ValueError, 'NFFT must be a power of 2' # zero pad x up to NFFT if it is shorter than NFFT if len(x)<NFFT: n = len(x) x = resize(x, (NFFT,)) x[n:] = 0 # for real x, ignore the negative frequencies if x.typecode()==Complex: numFreqs = NFFT else: numFreqs = NFFT//2+1 windowVals = window(ones((NFFT,),x.typecode())) step = NFFT-noverlap ind = arange(0,len(x)-NFFT+1,step) n = len(ind) Pxx = zeros((numFreqs,n), Float) # do the ffts of the slices for i in range(n): thisX = x[ind[i]:ind[i]+NFFT] thisX = windowVals*detrend(thisX) fx = absolute(fft(thisX))**2 # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2 Pxx[:,i] = divide(fx[:numFreqs], norm(windowVals)**2) t = 1/Fs*(ind+NFFT/2) freqs = Fs/NFFT*arange(numFreqs) return Pxx, freqs, t
def plot_surface(self, X, Y, Z, *args, **kwargs): had_data = self.has_data() rows, cols = Z.shape tX,tY,tZ = nx.transpose(X), nx.transpose(Y), nx.transpose(Z) rstride = cbook.popd(kwargs, 'rstride', 10) cstride = cbook.popd(kwargs, 'cstride', 10) # polys = [] boxes = [] for rs in nx.arange(0,rows,rstride): for cs in nx.arange(0,cols,cstride): ps = [] corners = [] for a,ta in [(X,tX),(Y,tY),(Z,tZ)]: ztop = a[rs][cs:min(cols-1,cs+cstride)] zleft = ta[min(cols-1,cs+cstride)][rs:min(rows,rs+rstride+1)] zbase = a[min(rows-1,rs+rstride)][cs:min(cols,cs+cstride+1):] zbase = zbase[::-1] zright = ta[cs][rs:min(rows-1,rs+rstride):] zright = zright[::-1] corners.append([ztop[0],ztop[-1],zbase[0],zbase[-1]]) z = nx.concatenate((ztop,zleft,zbase,zright)) ps.append(z) boxes.append(map(nx.array,zip(*corners))) polys.append(zip(*ps)) # lines = [] shade = [] for box in boxes: n = proj3d.cross(box[0]-box[1], box[0]-box[2]) n = n/proj3d.mod(n)*5 shade.append(nx.dot(n,[-1,-1,0.5])) lines.append((box[0],n+box[0])) # color = nx.array([0,0,1,1]) norm = normalize(min(shade),max(shade)) colors = [color * (0.5+norm(v)*0.5) for v in shade] for c in colors: c[3] = 1 polyc = art3d.Poly3DCollection(polys, facecolors=colors, *args, **kwargs) polyc._zsort = 1 self.add_collection(polyc) # self.auto_scale_xyz(X,Y,Z, had_data) return polyc
def array_example2(epsoutfile): x = (arange(100.0)-50)/25.0 y = (arange(100.0)-50)/25.0 # Important: z[y, x] -- y first! z = 5.0*sin(2*x[NewAxis, :]) + 3.0*cos(3*y[:, NewAxis]) colmap = ColMapper.ColorMapper("yellow-red", invert=1, exponent=0.55, brightness=0.5) #lut = colmap.generate_lut() # c = pyx.canvas.canvas() g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6, key=False) g.pyxplotarray(z[::-1,:], colmap=colmap) g.pyxplotcontour(z, x, y, colors='color', color='black', labels=True) pyxsave(g, epsoutfile)
def drange(dstart, dend, delta): """ Return a date range as float gregorian ordinals. dstart and dend are datetime instances. delta is a datetime.timedelta instance """ step = delta.days + delta.seconds/SECONDS_PER_DAY + delta.microseconds/MUSECONDS_PER_DAY f1 = _to_ordinalf(dstart) f2 = _to_ordinalf(dend) return arange(f1, f2, step)
def frange(xini, xfin=None, delta=None, **kw): """frange([start,] stop[, step, keywords]) -> array of floats Return a Numeric array() containing a progression of floats. Similar to arange(), but defaults to a closed interval. frange(x0, x1) returns [x0, x0+1, x0+2, ..., x1]; start defaults to 0, and the endpoint *is included*. This behavior is different from that of range() and arange(). This is deliberate, since frange will probably be more useful for generating lists of points for function evaluation, and endpoints are often desired in this use. The usual behavior of range() can be obtained by setting the keyword 'closed=0', in this case frange() basically becomes arange(). When step is given, it specifies the increment (or decrement). All arguments can be floating point numbers. frange(x0,x1,d) returns [x0,x0+d,x0+2d,...,xfin] where xfin<=x1. frange can also be called with the keyword 'npts'. This sets the number of points the list should contain (and overrides the value 'step' might have been given). arange() doesn't offer this option. Examples: >>> frange(3) array([ 0., 1., 2., 3.]) >>> frange(3,closed=0) array([ 0., 1., 2.]) >>> frange(1,6,2) array([1, 3, 5]) >>> frange(1,6.5,npts=5) array([ 1. , 2.375, 3.75 , 5.125, 6.5 ]) """ #defaults kw.setdefault('closed', 1) endpoint = kw['closed'] != 0 # funny logic to allow the *first* argument to be optional (like range()) # This was modified with a simpler version from a similar frange() found # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 if xfin == None: xfin = xini + 0.0 xini = 0.0 if delta == None: delta = 1.0 # compute # of points, spacing and return final list try: npts = kw['npts'] delta = (xfin - xini) / float(npts - endpoint) except KeyError: # round() gets npts right even with the vagaries of floating point. npts = int(round((xfin - xini) / delta + endpoint)) return arange(npts) * delta + xini
def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs from initial state y0 at sample times t. derivs returns the derivative of the system and has the signature dy = derivs(yi, ti) Example 1 : ## 2D system # Numeric solution def derivs6(x,t): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1, d2) dt = 0.0005 t = arange(0.0, 2.0, dt) y0 = (1,2) yout = rk4(derivs6, y0, t) Example 2: ## 1D system alpha = 2 def derivs(x,t): return -alpha*x + exp(-t) y0 = 1 yout = rk4(derivs, y0, t) """ try: Ny = len(y0) except TypeError: yout = zeros((len(t), ), Float) else: yout = zeros((len(t), Ny), Float) yout[0] = y0 i = 0 for i in arange(len(t) - 1): thist = t[i] dt = t[i + 1] - thist dt2 = dt / 2.0 y0 = yout[i] k1 = asarray(derivs(y0, thist)) k2 = asarray(derivs(y0 + dt2 * k1, thist + dt2)) k3 = asarray(derivs(y0 + dt2 * k2, thist + dt2)) k4 = asarray(derivs(y0 + dt * k3, thist + dt)) yout[i + 1] = y0 + dt / 6.0 * (k1 + 2 * k2 + 2 * k3 + k4) return yout
def frange(xini,xfin=None,delta=None,**kw): """frange([start,] stop[, step, keywords]) -> array of floats Return a Numeric array() containing a progression of floats. Similar to arange(), but defaults to a closed interval. frange(x0, x1) returns [x0, x0+1, x0+2, ..., x1]; start defaults to 0, and the endpoint *is included*. This behavior is different from that of range() and arange(). This is deliberate, since frange will probably be more useful for generating lists of points for function evaluation, and endpoints are often desired in this use. The usual behavior of range() can be obtained by setting the keyword 'closed=0', in this case frange() basically becomes arange(). When step is given, it specifies the increment (or decrement). All arguments can be floating point numbers. frange(x0,x1,d) returns [x0,x0+d,x0+2d,...,xfin] where xfin<=x1. frange can also be called with the keyword 'npts'. This sets the number of points the list should contain (and overrides the value 'step' might have been given). arange() doesn't offer this option. Examples: >>> frange(3) array([ 0., 1., 2., 3.]) >>> frange(3,closed=0) array([ 0., 1., 2.]) >>> frange(1,6,2) array([1, 3, 5]) >>> frange(1,6.5,npts=5) array([ 1. , 2.375, 3.75 , 5.125, 6.5 ]) """ #defaults kw.setdefault('closed',1) endpoint = kw['closed'] != 0 # funny logic to allow the *first* argument to be optional (like range()) # This was modified with a simpler version from a similar frange() found # at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66472 if xfin == None: xfin = xini + 0.0 xini = 0.0 if delta == None: delta = 1.0 # compute # of points, spacing and return final list try: npts=kw['npts'] delta=(xfin-xini)/float(npts-endpoint) except KeyError: # round() gets npts right even with the vagaries of floating point. npts=int(round((xfin-xini)/delta+endpoint)) return arange(npts)*delta+xini
def rk4(derivs, y0, t): """ Integrate 1D or ND system of ODEs from initial state y0 at sample times t. derivs returns the derivative of the system and has the signature dy = derivs(yi, ti) Example 1 : ## 2D system # Numeric solution def derivs6(x,t): d1 = x[0] + 2*x[1] d2 = -3*x[0] + 4*x[1] return (d1, d2) dt = 0.0005 t = arange(0.0, 2.0, dt) y0 = (1,2) yout = rk4(derivs6, y0, t) Example 2: ## 1D system alpha = 2 def derivs(x,t): return -alpha*x + exp(-t) y0 = 1 yout = rk4(derivs, y0, t) """ try: Ny = len(y0) except TypeError: yout = zeros( (len(t),), Float) else: yout = zeros( (len(t), Ny), Float) yout[0] = y0 i = 0 for i in arange(len(t)-1): thist = t[i] dt = t[i+1] - thist dt2 = dt/2.0 y0 = yout[i] k1 = asarray(derivs(y0, thist)) k2 = asarray(derivs(y0 + dt2*k1, thist+dt2)) k3 = asarray(derivs(y0 + dt2*k2, thist+dt2)) k4 = asarray(derivs(y0 + dt*k3, thist+dt)) yout[i+1] = y0 + dt/6.0*(k1 + 2*k2 + 2*k3 + k4) return yout
def levypdf(x, gamma, alpha): "Returm the levy pdf evaluated at x for params gamma, alpha" N = len(x) if N % 2 != 0: raise ValueError, 'x must be an event length array; try\n' + \ 'x = linspace(minx, maxx, N), where N is even' dx = x[1] - x[0] f = 1 / (N * dx) * arange(-N / 2, N / 2, Float) ind = concatenate([arange(N / 2, N, Int), arange(N / 2, Int)]) df = f[1] - f[0] cfl = exp(-gamma * absolute(2 * pi * f)**alpha) px = fft(take(cfl, ind) * df).astype(Float) return take(px, ind)
def contour_nogrid(z, levels): '''calculate the contours of z on a rectangular, equispaced grid at levels. z[y, x] holds the value of some scalar function on that grid. y and x are taken equispaced with a step length of 1. levels is a list of float values for which the contours shall be calculated. Returns a list of equal length to levels. Each entry is a set of contour lines for the corresponding level value. A set of contour lines is a list which contains 2-element lists [xarr, yarr]. xarr and yarr hold the points of one contour line in cartesic coordinates. xarr = result[levidx][lineidx][0] yarr = result[levidx][lineidx][1]''' return contour_rectgrid(arange(z.shape[1]), arange(z.shape[0]), z, levels)
def longest_contiguous_ones(x): """ return the indicies of the longest stretch of contiguous ones in x, assuming x is a vector of zeros and ones. """ if len(x) == 0: return array([]) ind = find(x == 0) if len(ind) == 0: return arange(len(x)) if len(ind) == len(x): return array([]) y = zeros((len(x) + 2, ), typecode(x)) y[1:-1] = x dif = diff(y) up = find(dif == 1) dn = find(dif == -1) ind = find(dn - up == max(dn - up)) ind = arange(take(up, ind), take(dn, ind)) return ind
def longest_contiguous_ones(x): """ return the indicies of the longest stretch of contiguous ones in x, assuming x is a vector of zeros and ones. """ if len(x)==0: return array([]) ind = find(x==0) if len(ind)==0: return arange(len(x)) if len(ind)==len(x): return array([]) y = zeros( (len(x)+2,), x.typecode()) y[1:-1] = x dif = diff(y) up = find(dif == 1); dn = find(dif == -1); ind = find( dn-up == max(dn - up)) ind = arange(take(up, ind), take(dn, ind)) return ind
def array_example3(epsoutfile): x = (arange(200.0) - 100) / 10.0 y = (arange(200.0) - 100) / 10.0 r = sqrt(x[:, NewAxis] ** 2 + y ** 2) z = 5.0 * cos(r) colmap1 = ColMapper.ColorMapper("red") colmap1.exponent = 0.9 colmap1.invert = True colmap2 = ColMapper.ColorMapper("green") colmap2.exponent = 0.9 colmap3 = ColMapper.ColorMapper("green") colmap3.invert = True colmap3.exponent = 0.9 colmap4 = ColMapper.ColorMapper("blue") colmap4.exponent = 0.9 colmap = ColMapper.SegmentedColorMapping( [(-5.0, -2.5, colmap1), (-2.5, 0.0, colmap2), (0.0, 2.5, colmap3), (2.5, 5.0, colmap4)], -5.0, 5.0 ) # colmap = ColMapper.example_SegmentedColorMapping(min(ravel(z)),max(ravel(z))) lut = colmap.generate_lut() pilbitmap = ColMapper.Array2PIL(z, lut=lut) c = pyx.canvas.canvas() g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6, key=False) g.pyxplot("y(x)=sin(x)+20", style="p") # FIXME: can't do empty plots! g.pyxbitmap(pilbitmap) c.insert(g) cb = pyxcolorbar(lut=lut, frame=g, pos=(1.1, 0.0), minvalue=min(ravel(z)), maxvalue=max(ravel(z))) c.insert(cb) pyxsave(c, epsoutfile)
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() vmin, vmax = self.viewInterval.get_bounds() if vmax<vmin: vmin, vmax = vmax, vmin vmin = self.base.ge(vmin) locs = arange(vmin, vmax+0.001*self.base.get_base(), self.base.get_base()) return locs
def detrend_linear(x): "Return x minus best fit line; 'linear' detrending " # I'm going to regress x on xx=range(len(x)) and return x - # (b*xx+a). Now that I have polyfit working, I could convert the # code here, but if it ain't broke, don't fix it! xx = arange(float(len(x))) X = transpose(array([xx] + [x])) C = cov(X) b = C[0, 1] / C[0, 0] a = mean(x) - b * mean(xx) return x - (b * xx + a)
def symbols(epsoutfile): y = arange(5)/5.0+0.1 g = pyxgraph(xlimits=(-1, 25), ylimits=(0, 1), xticks=(0, 24, 2), yticks=(0, 1, 1), key=None) for i in xrange(25): x = zeros(5)+i g.pyxplot((x, y), style="p", pt=i) # ``pt=i`` can be omitted # (then the next symbol is choosen # automatically) g.pyxsave(epsoutfile)
def detrend_linear(x): "Return x minus best fit line; 'linear' detrending " # I'm going to regress x on xx=range(len(x)) and return x - # (b*xx+a). Now that I have polyfit working, I could convert the # code here, but if it ain't broke, don't fix it! xx = arange(float(len(x))) X = transpose(array([xx]+[x])) C = cov(X) b = C[0,1]/C[0,0] a = mean(x) - b*mean(xx) return x-(b*xx+a)
def array_example2(epsoutfile): x = (arange(50.0)-25)/2.0 y = (arange(50.0)-25)/2.0 r = sqrt(x[:,NewAxis]**2+y**2) z = 5.0*cos(r) colmap = ColMapper.ColorMapper("yellow-red", exponent=0.55, brightness=0.5) lut = colmap.generate_lut() c = pyx.canvas.canvas() g = pyxgraph(xlimits=(min(x), max(x)), ylimits=(min(y), max(y)), width=6, height=6) g.pyxplot("y(x)=sin(x)", style="p") # FIXME: can't do empty plots! g.pyxplotarray(z, colmap=lut) c.insert(g) cb = pyxcolorbar(lut=lut, frame=g, pos=(1.1,0.0), minvalue=min(ravel(z)), maxvalue=max(ravel(z))) c.insert(cb) pyxsave(c, epsoutfile)
def styles_example2(epsoutfile): x = arange(2.0, 10.0, 0.1) y = 0.0 * x y[::2] = 1.0 g = pyxgraph(xlimits=(0, 10), ylimits=(-1, 6), key=None, width=8) # lines for comparison: x2 = arange(0.0, 5.0, 0.1) for i in xrange(6): g.pyxplot((x2, 0 * x2 + i), color=(0.6, 0.6, 0.6), style="l", lt=0, lw=0.25) g.pyxplot((x, y), style="l", lt=0) # pyx.style.linejoin.meter is default g.pyxplot((x, y + 2), style="l", lt=0, lineattrs=[pyx.style.linejoin.bevel]) g.pyxplot((x, y + 4), style="l", lt=0, lineattrs=[pyx.style.linejoin.round]) txtstyle = [pyx.text.halign.left, pyx.text.valign.middle] g.pyxlabel((0.5, 0.5), "miter", txtstyle, graphcoords=True) g.pyxlabel((0.5, 2.5), "bevel", txtstyle, graphcoords=True) g.pyxlabel((0.5, 4.5), "round", txtstyle, graphcoords=True) g.pyxsave(epsoutfile)
def get_test_data(delta=0.05): from mlab import meshgrid, bivariate_normal x = y = nx.arange(-3.0, 3.0, delta) X, Y = meshgrid(x,y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2-Z1 X = X * 10 Y = Y * 10 Z = Z * 500 return X,Y,Z
def levypdf(x, gamma, alpha): "Returm the levy pdf evaluated at x for params gamma, alpha" N = len(x) if N%2 != 0: raise ValueError, 'x must be an event length array; try\n' + \ 'x = linspace(minx, maxx, N), where N is even' dx = x[1]-x[0] f = 1/(N*dx)*arange(-N/2, N/2, Float) ind = concatenate([arange(N/2, N, Int), arange(N/2,Int)]) df = f[1]-f[0] cfl = exp(-gamma*absolute(2*pi*f)**alpha) px = fft(take(cfl,ind)*df).astype(Float) return take(px, ind)
def unmasked_index_ranges(mask, compressed = True): ''' Calculate the good data ranges in a masked 1-D array, based on mask. Returns Nx2 array with each row the start and stop indices for slices of the compressed array corresponding to each of N uninterrupted runs of unmasked values. If optional argument compressed is False, it returns the start and stop indices into the original array, not the compressed array. In either case, an empty array is returned if there are no unmasked values. Example: y = ma.array(arange(5), mask = [0,0,1,0,0]) #ii = unmasked_index_ranges(y.mask()) ii = unmasked_index_ranges(ma.getmask(y)) # returns [[0,2,] [2,4,]] y.compressed().filled()[ii[1,0]:ii[1,1]] # returns array [3,4,] # (The 'filled()' method converts the masked array to a numerix array.) #i0, i1 = unmasked_index_ranges(y.mask(), compressed=False) i0, i1 = unmasked_index_ranges(ma.getmask(y), compressed=False) # returns [[0,3,] [2,5,]] y.filled()[ii[1,0]:ii[1,1]] # returns array [3,4,] ''' m = concatenate(((1,), mask, (1,))) indices = arange(len(mask) + 1) mdif = m[1:] - m[:-1] i0 = compress(mdif == -1, indices) i1 = compress(mdif == 1, indices) assert len(i0) == len(i1) if not compressed: if len(i1): return concatenate((i0[:, ma.NewAxis], i1[:, ma.NewAxis]), axis=1) else: return zeros((0,0), 'i') seglengths = i1 - i0 breakpoints = cumsum(seglengths) try: ic0 = concatenate(((0,), breakpoints[:-1])) ic1 = breakpoints return concatenate((ic0[:, ma.NewAxis], ic1[:, ma.NewAxis]), axis=1) except: return zeros((0,0), 'i')
def makeMappingArray(N, data): """Create an N-element 1-d lookup table data represented by a list of x,y0,y1 mapping correspondences. Each element in this list represents how a value between 0 and 1 (inclusive) represented by x is mapped to a corresponding value between 0 and 1 (inclusive). The two values of y are to allow for discontinuous mapping functions (say as might be found in a sawtooth) where y0 represents the value of y for values of x <= to that given, and y1 is the value to be used for x > than that given). The list must start with x=0, end with x=1, and all values of x must be in increasing order. Values between the given mapping points are determined by simple linear interpolation. The function returns an array "result" where result[x*(N-1)] gives the closest value for values of x between 0 and 1. """ try: adata = array(data) except: raise TypeError("data must be convertable to an array") shape = adata.shape if len(shape) != 2 and shape[1] != 3: raise ValueError("data must be nx3 format") x = adata[:,0] y0 = adata[:,1] y1 = adata[:,2] if x[0] != 0. or x[-1] != 1.0: raise ValueError( "data mapping points must start with x=0. and end with x=1") if sometrue(sort(x)-x): raise ValueError( "data mapping points must have x in increasing order") # begin generation of lookup table x = x * (N-1) lut = zeros((N,), Float) xind = arange(float(N)) ind = searchsorted(x, xind)[1:-1] lut[1:-1] = ( divide(xind[1:-1] - take(x,ind-1), take(x,ind)-take(x,ind-1) ) *(take(y0,ind)-take(y1,ind-1)) + take(y1,ind-1)) lut[0] = y1[0] lut[-1] = y0[-1] # ensure that the lut is confined to values between 0 and 1 by clipping it clip(lut, 0.0, 1.0) #lut = where(lut > 1., 1., lut) #lut = where(lut < 0., 0., lut) return lut
def unmasked_index_ranges(mask, compressed=True): ''' Calculate the good data ranges in a masked 1-D array, based on mask. Returns Nx2 array with each row the start and stop indices for slices of the compressed array corresponding to each of N uninterrupted runs of unmasked values. If optional argument compressed is False, it returns the start and stop indices into the original array, not the compressed array. In either case, an empty array is returned if there are no unmasked values. Example: y = ma.array(arange(5), mask = [0,0,1,0,0]) #ii = unmasked_index_ranges(y.mask()) ii = unmasked_index_ranges(ma.getmask(y)) # returns [[0,2,] [2,4,]] y.compressed().filled()[ii[1,0]:ii[1,1]] # returns array [3,4,] # (The 'filled()' method converts the masked array to a numerix array.) #i0, i1 = unmasked_index_ranges(y.mask(), compressed=False) i0, i1 = unmasked_index_ranges(ma.getmask(y), compressed=False) # returns [[0,3,] [2,5,]] y.filled()[ii[1,0]:ii[1,1]] # returns array [3,4,] ''' m = concatenate(((1, ), mask, (1, ))) indices = arange(len(mask) + 1) mdif = m[1:] - m[:-1] i0 = compress(mdif == -1, indices) i1 = compress(mdif == 1, indices) assert len(i0) == len(i1) if not compressed: if len(i1): return concatenate((i0[:, ma.NewAxis], i1[:, ma.NewAxis]), axis=1) else: return zeros((0, 0), 'i') seglengths = i1 - i0 breakpoints = cumsum(seglengths) try: ic0 = concatenate(((0, ), breakpoints[:-1])) ic1 = breakpoints return concatenate((ic0[:, ma.NewAxis], ic1[:, ma.NewAxis]), axis=1) except: return zeros((0, 0), 'i')
def makeMappingArray(N, data): """Create an N-element 1-d lookup table data represented by a list of x,y0,y1 mapping correspondences. Each element in this list represents how a value between 0 and 1 (inclusive) represented by x is mapped to a corresponding value between 0 and 1 (inclusive). The two values of y are to allow for discontinuous mapping functions (say as might be found in a sawtooth) where y0 represents the value of y for values of x <= to that given, and y1 is the value to be used for x > than that given). The list must start with x=0, end with x=1, and all values of x must be in increasing order. Values between the given mapping points are determined by simple linear interpolation. The function returns an array "result" where result[x*(N-1)] gives the closest value for values of x between 0 and 1. """ try: adata = array(data) except: raise TypeError("data must be convertable to an array") shape = adata.shape if len(shape) != 2 and shape[1] != 3: raise ValueError("data must be nx3 format") x = adata[:,0] y0 = adata[:,1] y1 = adata[:,2] if x[0] != 0. or x[-1] != 1.0: raise ValueError( "data mapping points must start with x=0. and end with x=1") if sometrue(sort(x)-x): raise ValueError( "data mapping points must have x in increasing order") # begin generation of lookup table x = x * (N-1) lut = zeros((N,), Float) xind = arange(float(N)) ind = searchsorted(x, xind)[1:-1] lut[1:-1] = ( divide(xind[1:-1] - take(x,ind-1), take(x,ind)-take(x,ind-1) ) *(take(y0,ind)-take(y1,ind-1)) + take(y1,ind-1)) lut[0] = y1[0] lut[-1] = y0[-1] # ensure that the lut is confined to values between 0 and 1 by clipping it lut = where(lut > 1., 1., lut) lut = where(lut < 0., 0., lut) return lut
def test_plot(): ax = Axes3D() xs = nx.arange(0,4*nx.pi+0.1,0.1) ys = nx.sin(xs) ax.plot(xs,ys, label='zl') ax.plot(xs,ys+max(xs),label='zh') ax.plot(xs,ys,dir='x', label='xl') ax.plot(xs,ys,dir='x', z=max(xs),label='xh') ax.plot(xs,ys,dir='y', label='yl') ax.plot(xs,ys,dir='y', z=max(xs), label='yh') ax.set_xlabel('X') ax.set_ylabel('Y') ax.set_zlabel('Z') ax.legend()
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 get_xyz_where(Z, Cond): """ Z and Cond are MxN matrices. Z are data and Cond is a boolean matrix where some condition is satisfied. Return value is x,y,z where x and y are the indices into Z and z are the values of Z at those indices. x,y,z are 1D arrays """ M,N = Z.shape z = ravel(Z) ind = nonzero( ravel(Cond) ) x = arange(M); x.shape = M,1 X = repeat(x, N, 1) x = ravel(X) y = arange(N); y.shape = 1,N Y = repeat(y, M) y = ravel(Y) x = take(x, ind) y = take(y, ind) z = take(z, ind) return x,y,z
def __init__(self, xy, numVertices, radius=5, orientation=0, **kwargs): Patch.__init__(self, **kwargs) self.xy = xy self.numVertices = numVertices self.radius = radius self.orientation = orientation theta = 2*pi/self.numVertices*arange(self.numVertices) + \ self.orientation r = self.radius xs = self.xy[0] + r * cos(theta) ys = self.xy[1] + r * sin(theta) self.verts = zip(xs, ys)
def __init__(self, center, r, theta1, theta2, dtheta=0.1, **kwargs): """ Draw a wedge centered at x,y tuple center with radius r that sweeps theta1 to theta2 (angles) kwargs are Polygon keyword args dtheta is the resolution in degrees """ xc, yc = center rads = (math.pi / 180.) * arange(theta1, theta2 + 0.1 * dtheta, dtheta) xs = r * cos(rads) + xc ys = r * sin(rads) + yc verts = [center] verts.extend([(x, y) for x, y in zip(xs, ys)]) Polygon.__init__(self, verts, **kwargs)
def bin_boundaries(self, vmin, vmax): nbins = self._nbins scale, offset = scale_range(vmin, vmax, nbins) vmin -= offset vmax -= offset raw_step = (vmax-vmin)/nbins scaled_raw_step = raw_step/scale for step in self._steps: if step < scaled_raw_step: continue step *= scale best_vmin = step*divmod(vmin, step)[0] best_vmax = best_vmin + step*nbins if (best_vmax >= vmax): break if self._trim: extra_bins = int(divmod((best_vmax - vmax), step)[0]) nbins -= extra_bins return (arange(nbins+1) * step + best_vmin + offset)
def _draw_circle(self, renderer, gc, xt, yt): w = h = renderer.points_to_pixels(self._markersize) rgbFace = self._get_rgb_face() if self._newstyle: N = 50.0 r = w/2. rads = (2*math.pi/N)*arange(N) xs = r*cos(rads) ys = r*sin(rads) verts = [(MOVETO, xs[0], ys[0])] verts.extend([(LINETO, x, y) for x, y in zip(xs[1:], ys[1:])]) CLOSE = self._get_close(rgbFace) verts.append(CLOSE) renderer.draw_markers(gc, verts, xt, yt, self._transform) else: for (x,y) in zip(xt, yt): renderer.draw_arc(gc, rgbFace, x, y, w, h, 0.0, 360.0)