def main(): """ A simple example. Note that the Tkinter lines are there only because this code will be run standalone. On the interpreter, simply invoking surf and view would do the job.""" import Tkinter r = Tkinter.Tk() r.withdraw() def f(x, y): return Numeric.sin(x*y)/(x*y) x = Numeric.arange(-7., 7.05, 0.1) y = Numeric.arange(-5., 5.05, 0.05) v = surf(x, y, f) import RandomArray z = RandomArray.random((50, 25)) v1 = view(z) v2 = view(z, warp=1) z_large = RandomArray.random((1024, 512)) v3 = viewi(z_large) # A hack for stopping Python when all windows are closed. v.master = r v1.master = r v2.master = r #v3.master = r r.mainloop()
def set_axes(self): Plot3D.set_axes(self) xlist = Num.arange(self.xstart, self.xstop+1, self.xstep) ylist = Num.arange(self.ystart, self.ystop+1, self.ystep) zlist = utilities.zcalculator(self.function, xlist, ylist) ai = auto_axes3D(xlist, ylist, zlist, axes = self.axes) self.axes(focustype = 'user', focuspoint = ai.focus)
def testAverage (self): "Test of average function." a = Numeric.arange(6) assert_eq(Numeric.average(a), 15.0/6.0) assert_eq(Numeric.average(a, weights=[1,1,1,2,1,0]), (0*1+1*1+2*1+3*2+4*1+5*0)/(1+1+1+2+1+0.0)) assert_eq(Numeric.average(a, weights=[1,1,1,2,1,0],returned=1)[0], (0*1+1*1+2*1+3*2+4*1+5*0)/(1+1+1+2+1+0.0)) assert_eq(Numeric.average(a, weights=[1,1,1,2,1,0],returned=1)[1], 1+1+1+2+1+0) b = Numeric.arange(6) * 3 assert_eq(Numeric.average([a,b]), (a + b) / 2.) assert_eq(Numeric.average([a,b],1), [15/6.0, 45/6.0]) assert_eq(Numeric.average([a,b], axis=0, weights=[3,1]), (3.0*a+b)/4.) w = Numeric.ones(Numeric.shape([a,b]), Numeric.Float)/2.0 assert_eq(Numeric.average([a,b], axis=1), Numeric.average([a,b], weights=w, axis=1) ) c = a[:] c.shape=(3,2) assert_eq(Numeric.average(a), Numeric.average(c, axis=None)) assert_eq(Numeric.average(a[::2]), (0+2+4)/3.0) r1, w1 = Numeric.average([[a,b],[b,a]], axis=1, returned=1) assert Numeric.shape(r1) == Numeric.shape(w1) assert r1.shape == w1.shape r2, w2 = Numeric.average(Numeric.ones((2,2,3)), axis=0, weights=[3,1], returned=1) assert Numeric.shape(w2) == Numeric.shape(r2) r2, w2 = Numeric.average(Numeric.ones((2,2,3)), returned=1) assert Numeric.shape(w2) == Numeric.shape(r2) r2, w2 = Numeric.average(Numeric.ones((2,2,3)), weights=Numeric.ones((2,2,3)), returned=1) assert Numeric.shape(w2) == Numeric.shape(r2)
def main(): X = Numeric.arange(0,20*Numeric.pi,0.01,typecode=Numeric.Float) Y1 = Numeric.sin(X) Y2 = Numeric.sin(2*X) out = open('fncs.dat','w') for i in range(len(X)): out.write(str(X[i])+' '+str(Y1[i])+' '+str(Y2[i])+'\n') out.close() # Take FFT's FY1 = FFT.fft(Y1).real FY2 = FFT.fft(Y2).real N = float(len(X)) # get # of data points dX = X[1]-X[0] # get distance spacing T = N*dX # define the period (total time) dQ = 1./T # define frequency step Q=Numeric.arange(N,typecode=Numeric.Float)*dQ print Q[list(FY1).index(max(FY1))], max(FY1) print Q[list(FY2).index(max(FY2))], max(FY2) print list(FY1).index(max(FY1)) print list(FY2).index(max(FY2)) out = open('FFTs.dat','w') for i in range(len(Q)): out.write(str(Q[i])+' '+str(FY1[i])+' '+str(FY2[i])+'\n') out.close()
def spline(data, quality): """Interpolate a trajectory using natural cubic splines. Arguments: - data a list or AMC object containing the data to be interpolated - quality the number of new points to insert between data points """ # Special case: The input data is an AMC object. For each bone in the AMC # object create a spline. Return an AMC object. if data.__class__ == AMC: interpolated = AMC() for bone, motion in data.bones.iteritems(): interpolated.bones[bone] = spline(motion, quality) return interpolated data = Numeric.array(data) quality += 1 # Assumming a 2-dimensional array. # FIXME - Needs error checking? length, dof = Numeric.shape(data) interpolated = Numeric.empty((length * quality, dof)) # Range of times we'll be using for the vast majority of the splining process times = Numeric.arange(2, 3, 1. / quality)[:-1] # For calculating interpolated data points f = lambda c: lambda t: c[0] + c[1] * t + c[2] * t**2 + c[3] * t**3 # Interpolate the data using chunks of the trajectory. Each chunk consists # of 4 points. Except for the first and last chunk, interpolate only the # inner 2 points of each chunk. for frame in range(length - 3): # Generate matrices and solve for the constants A, b = _getMatrix(data[frame:frame + 4], dof) Ainv = inverse(A) z = [Numeric.matrixmultiply(Ainv, x) for x in b] # Handle each degree of freedom individually for degree in range(dof): # At the beginning of the trajectory interpolate the first 2 points if frame == 0: smoothedFrame = frame * quality interpolated[smoothedFrame:smoothedFrame + quality, degree] = \ map(f(z[degree][:4]), Numeric.arange(1, 2, 1. / quality)[:-1]) # At the end of the trajectory interpolate the last 2 points elif frame == length - 4: smoothedFrame = (frame + 2) * quality interpolated[smoothedFrame:smoothedFrame + quality, degree] = \ map(f(z[degree][-4:]), Numeric.arange(3, 4, 1. / quality)[:-1]) # Interpolate the middle 2 points smoothedFrame = (frame + 1) * quality interpolated[smoothedFrame:smoothedFrame + quality, degree] = \ map(f(z[degree][4:8]), times) return interpolated
def testArange(self): "Test arange" x = Numeric.arange(5) assert_eq(x, [0,1,2,3,4]) x = Numeric.arange(4, 6) assert_eq(x, [4,5]) x = Numeric.arange(0, 1.5, .5) assert_eq(x, [0.0, 0.5, 1.0]) assert len(Numeric.arange(5,3,2)) == 0 x = Numeric.arange(3L) assert x[1] == 1L assert x.typecode() == Numeric.PyObject
def __init__(self, filename, testname, vecsize, nobjects, niter): self.file = filename self.test = testname self.vecsize = vecsize self.nobjects = nobjects self.niter = niter # Initialize the arrays self.a1 = Numeric.arange(0, 1*self.vecsize) self.a2 = Numeric.arange(1*self.vecsize, 2*self.vecsize) self.a3 = Numeric.arange(2*self.vecsize, 3*self.vecsize)
def _setField(self, data): points = [] values = [] colors = [] default_color = Color.ColorByName('black') for min, max, atoms in self.box.partitions(): center = 0.5*(min+max) points.append(center.array) v = data.zero() total_weight = 0. color = default_color for a in atoms: d = a.position()-center weight = Numeric.exp(-d*d/self.box.partition_size**2) v = v + weight*data[a] total_weight = total_weight + weight c = default_color try: c = a.color except AttributeError: pass if type(c) == type(''): c = Color.ColorByName(c) color = color + c values.append(v/total_weight) colors.append(color) min = Numeric.minimum.reduce(points) max = Numeric.maximum.reduce(points) axes = (Numeric.arange(min[0], max[0]+1, self.box.partition_size), Numeric.arange(min[1], max[1]+1, self.box.partition_size), Numeric.arange(min[2], max[2]+1, self.box.partition_size)) array = Numeric.zeros(tuple(map(len, axes)) + data.value_rank*(3,), Numeric.Float) inside = Numeric.zeros(tuple(map(len, axes)), Numeric.Float) for p, v in map(None, points, values): indices = Numeric.floor((p-min)/self.box.partition_size+0.5) indices = indices.astype(Numeric.Int) array[indices] = v inside[indices] = 1. self.field = self.field_class(axes, array, data.zero()) inside = TensorAnalysis.ScalarField(axes, inside).gradient().length() self.points = [] self.colors = [] for i in range(len(points)): p = points[i] test = 0 try: test = apply(inside, tuple(p)) > 1.e-10 except ValueError: pass if test: self.points.append(p) self.colors.append(colors[i])
def __init__(self, data, xvals=None, yvals=None, **keyw): """GridData constructor. Arguments: 'data' -- a 2-d array with dimensions (numx,numy) 'xvals' -- a 1-d array with dimension (numx) 'yvals' -- a 1-d array with dimension (numy) 'data' is meant to hold the values of a function f(x,y) tabulated on a grid of points, such that 'data[i,j] == f(xvals[i], yvals[j])'. These data are written to a datafile as 'x y f(x,y)' triplets that can be used by gnuplot's splot command. Thus if you have three arrays in the above format and a Gnuplot instance called g, you can plot your data by typing for example: g.splot(Gnuplot.GridData(data,xvals,yvals)) If 'xvals' and/or 'yvals' are omitted, integers (starting with 0) are used for that coordinate. The data are written to a temporary file; no copy of the data is kept in memory. """ data = Numeric.asarray(data, Numeric.Float) assert len(data.shape) == 2 (numx, numy) = data.shape if xvals is None: xvals = Numeric.arange(numx) else: xvals = Numeric.asarray(xvals, Numeric.Float) assert len(xvals.shape) == 1 assert xvals.shape[0] == numx if yvals is None: yvals = Numeric.arange(numy) else: yvals = Numeric.asarray(yvals, Numeric.Float) assert len(yvals.shape) == 1 assert yvals.shape[0] == numy set = Numeric.transpose( Numeric.array( (Numeric.transpose(Numeric.resize(xvals, (numy, numx))), Numeric.resize(yvals, (numx, numy)), data)), (1,2,0)) apply(File.__init__, (self, TempArrayFile(set)), keyw)
def plotBox(self, name, data, data_range=None): box = Frame(self, border=2, relief=SUNKEN) box.pack(side=TOP, fill=BOTH, expand=YES) frame = Frame(box, background='grey') frame.pack(side=TOP, fill=X, expand=NO) Label(frame, text=string.capitalize(string.join( string.split(name , '_'), ' ')), background='grey').pack(side=LEFT) if data_range is None: min = Numeric.minimum.reduce(data[:,1]) max = Numeric.maximum.reduce(data[:,1]) min, max = plotRange(min, max) else: min, max = data_range plot_objects = [] plot_data = data time = plot_data[:,0] jumps = Numeric.repeat(Numeric.arange(len(time)-1), Numeric.less(time[1:], time[:-1]))+1 for i in self.master.restarts: plot_objects.append(PolyLine([(self.time[i], min), (self.time[i], max)], color='black', stipple='gray25')) plot_objects.insert(0, PolyLine(plot_data, color = 'red')) plot = PlotCanvas(box, 400, 100, zoom=1, select=self.master._selectRange) plot.pack(side=LEFT, fill=BOTH, expand=YES) plot.draw(PlotGraphics(plot_objects), 'automatic', (min, max)) plot.bind('<Double-Button-1>', lambda event, d=plot_data: externalPlot(d)) self.registerPlot(plot) self.setSelection(plot)
def test(): if not hasnumeric: print "quickplots.test requires Numeric" return None import Numeric as Num, random, math x = Num.arange(100, typecode=Num.Float) plot(x, Num.sin(x / 5)) y = [random.normalvariate(i, 4) for i in x] scatter(x, y) y = [random.normalvariate(0, 0.5) for i in range(1000)] histogram(y, nbins=15) z = Num.array([math.cos(i / (math.pi * 2)) * math.sin(j / (math.pi * 2)) for i in x for j in x]) z.shape = (len(x), len(x)) pseudocolor(z) x = range(10) y = range(10) z = [i ** 2 - j ** 2 for i in x for j in y] surface(x, y, z) def f(x, y): return abs(x ** 2 - 1) ** 0.5 + abs(y ** 2 - 1) ** 0.5 contour(f, (0, 10), (0, 10), 1)
def __getitem__(self, item): if type(item) != type(0): return SubTrajectory(self, Numeric.arange(len(self)))[item] if item >= len(self): raise IndexError tindex = Numeric.add.reduce(Numeric.greater_equal(item, self.nsteps))-1 return self.trajectories[tindex][item-self.nsteps[tindex]]
def cb_interpolate(self, action): plugin = self.app.get_plugin('pygsl') pygsl = plugin.pygsl table = self.dataset.get_data() x, y = table[0], table[1] steps = table.nrows * 3 start, end = x[0], x[-1] stepwidth = (end - start) / steps new_x = Numeric.arange(start=start, stop=end+stepwidth, step=stepwidth) new_table = Table(nrows=steps, ncols=2, typecodes=[table.get_typecode(0), table.get_typecode(1)]) sp = pygsl.spline.cspline(table.nrows) sp.init(x, y) iter = new_table.row(0) for xi in new_x: iter.set( (xi, sp.eval(xi)) ) try: iter = iter.next() except StopIteration: print "Iteration stopped" # set new Dataset self.project.datasets.append( Dataset(key="Niklas", data=new_table) ) Signals.emit(self.project.datasets, "changed")
def main(): # Retrieve user input try: TD = float(sys.argv[1]) except: print '\n usage: '+sys.argv[0]+' Debye_temperature(K)\n' sys.exit(0) # Create array of possible N(0)*V values N0V = Numeric.arange(0.005,1.001,0.001,typecode=Numeric.Float) # Calculate Tc from unapproximated expression Tc = 1.14 * TD / ( Numeric.e**(1/N0V) - 1 ) Tc2 = Numeric.e**(1/N0V) - 1 # Calculate in the weak coupling limit WCL_Tc = 1.14 * TD * Numeric.e**(-1/N0V) WCL_Tc2 = Numeric.e**(-1/N0V) # Calculate the percentage difference between the two P = ( Tc2 - WCL_Tc2 ) / Tc2 *100 # Write the results to file out = open('BCS.dat','w') out.write('# N(0)*V, %_difference, Tc(K), WCL_Tc(K), done using Debye_temperature of '+str(TD)+'\n') for i in range(len(P)): out.write(str(N0V[i])+' '+str(P[i])+' '+str(Tc[i])+' '+str(WCL_Tc[i])+'\n') out.close()
def __getitem__(self, item): if type(item) != type(0): return SubVariable(self, Numeric.arange(len(self)))[item] if item < 0: item = item + len(self.trajectory) if item >= len(self.trajectory): raise IndexError if self.name == 'configuration': if self.box_size is None: box = None elif len(self.box_size.shape) == 3: bs = self.trajectory.block_size box = self.box_size[item/bs, :, item%bs].astype(Numeric.Float) else: box = self.box_size[item].astype(Numeric.Float) array = ParticleProperties.Configuration(self.universe, self.trajectory.trajectory.readParticleVector(self.name, item), box) elif 'xyz' in self.var.dimensions: array = ParticleProperties.ParticleVector(self.universe, self.trajectory.trajectory.readParticleVector(self.name, item)) else: array = ParticleProperties.ParticleScalar(self.universe, self.trajectory.trajectory.readParticleScalar(self.name, item)) return array
def main(): """Exercise the Gnuplot module.""" print ( 'This program exercises many of the features of Gnuplot.py. The\n' 'commands that are actually sent to gnuplot are printed for your\n' 'enjoyment.' ) wait('Popping up a blank gnuplot window on your screen.') g = Gnuplot.Gnuplot(debug=1) g.clear() # Make a temporary file: filename1 = tempfile.mktemp() f = open(filename1, 'w') try: for x in Numeric.arange(100)/5. - 10.: f.write('%s %s %s\n' % (x, math.cos(x), math.sin(x))) f.close() print '############### test Func ###################################' wait('Plot a gnuplot-generated function') g.plot(Gnuplot.Func('sin(x)')) wait('Set title and axis labels and try replot()') g.title('Title') g.xlabel('x') g.ylabel('y') g.replot() wait('Style linespoints') g.plot(Gnuplot.Func('sin(x)', with='linespoints'))
def testMeshgrid_DenseFromMixedArrayTypes(self): # Other combination of arrays #print 'testing Meshgrid with mixed array implementations' y = N.arange(4) z = N.arange(3) import Numeric x = Numeric.arange(10) X, Y, Z = N.meshgrid(x, y, z, sparse=False) if not N.rank(X) == 3: raise AssertionError( "Meshgrid failed with arraytype mix of Numeric and %s"\ %N.basic_NumPy) import numarray x = numarray.arange(10) X, Y, Z = N.meshgrid(x, y, z, sparse=False) if not N.rank(X) == 3: raise AssertionError( "Meshgrid failed with arraytype mix of numarray and %s"\ %N.basic_NumPy) import numpy x = numpy.arange(10) X, Y, Z = N.meshgrid(x, y, z, sparse=False) #assert N.rank(X) == 3 if not N.rank(X) == 3: raise AssertionError( "Meshgrid failed with arraytype mix of numpy and %s"\ %N.basic_NumPy)
def main(): # Retrieve user input try: f = open(sys.argv[1],'r') lines = f.readlines() f.close() except: print '\n usage: '+sys.argv[0]+' XY.dat\n' sys.exit(0) # Parse the data t, y = [], [] for line in lines: t.append(float(line.split()[0])) y.append(float(line.split()[1])) # Calculate the FFT and get the frequencies N = float(len(t)) dt = t[1] - t[0] T = N * dt df = 1.0 / T f = Numeric.arange(N,typecode=Numeric.Float)*df H = ( FFT.fft(y)*Numeric.conjugate(FFT.fft(y)) ).real / N # Write to file out = open('PSD.dat','w') for i in range(len(f)/2): out.write(str(f[i])+' '+str(H[i])+'\n') out.close()
def visualise_mesh(mesh): import mayavi sys.argv=["",""] mesh_info = mesh.tolists() # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0,1.05,0.05) globals()['call_counter'] = 0 # to visualise without writing to disk, uncomment this section vtkData, points, simplices, simplexIndicies, icradii, ccradii = nmesh.visual.mesh2vtk(mesh_info, VTKonly=False) in2circ = nmesh.visual.findRatios(icradii, ccradii, factor=2) #2D mesh vtkData = nmesh.visual.append2vtk(vtkData, in2circ, "2*inradius/circumradius") globals()['v'].close_all() globals()['v'] = nmesh.visual.mesh2mayavi(vtkData, myv=globals()['v'], lut_range=(0,1)) m2 = v.load_module('SurfaceMap',0) m2.actor.GetProperty().SetRepresentationToWireframe() m2.mapper.SetScalarVisibility(0) m2.renwin.Render() dvm = v.get_current_dvm() mm = dvm.get_current_module_mgr() luthandler = mm.get_scalar_lut_handler() luthandler.set_lut_red_blue() luthandler.sc_bar.SetVisibility(1) luthandler.sc_bar.GetTitleTextProperty().SetShadow(1) luthandler.sc_bar.GetLabelTextProperty().SetShadow(1) globals()['v'].renwin.z_plus_view() # this line will reduce fluidity v.Render() raw_input()
def test_application(): app = Application() p = app.new_project() # set up sample project print "Setting up sample project with a Dataset and a Plot." ds = p.new_dataset() data = ds.get_data() data.extend(20) data[0] = Numeric.arange(21) data[1] = Numeric.sin(data[0]) layer = Layer(type='line2d', lines=[Line(source=ds)], axes = {'x': Axis(label="A Number (arb. units)"), 'y': Axis(label="The Sin (arb. units)")}) plot = Plot(label=u"A silly example", layers=[layer], key="a plot") p.add_plot(plot) p.list() return app
def set_speed(self, speed): self.speed = speed if self.speed > 0: self.speed = min(1.0, max(self.speed, 0.000001)) else: self.speed = max(-1.0, min(self.speed, -0.000001)) self.centers = [] xmin, ymin, xwidth, ywidth = self.xmin, self.ymin, self.xwidth, self.ywidth for dy in Numeric.arange(ymin, ymin + ywidth, ywidth / 10): for dx in Numeric.arange(xmin, xmin + xwidth, xwidth * speed / 8): self.centers.append((-dx, -dy)) if self.speed < 0: self.centers.reverse() self.idx = 0
def generate_lut(self): """Return triple of rgb arrays with values in [0,255]. """ r,g,b=(Numeric.zeros(256),Numeric.zeros(256),Numeric.zeros(256)) for i in Numeric.arange(256): r_,g_,b_=self.colfct(i/255.0) # these are from [0,1] r[i],g[i],b[i]=int(255*r_),int(255*g_),int(255*b_) return r,g,b
def makeidx(self, force=False): """Make the index arrays, if necessary.""" if force or self._isparallel: natoms = len(self.atoms) self.indices = num.compress(self.mask, num.arange(natoms)) self.n = len(self.indices) self.reverse = num.clip(num.add.accumulate(self.mask)-1, 0, natoms)
def testComplex (self): "Test complex numbers" y = Numeric.arange(5) * 1.0 x = y + y[::-1] * 1.0j assert x.typecode() == Numeric.Complex assert_eq(x.real, y) assert_eq(x.imag, y[::-1])
def main(): try: BM, rs = [], [] BM.append(float(sys.argv[1])) BM.append(float(sys.argv[2])) BM.append(float(sys.argv[3])) rs.append(float(sys.argv[4])) rs.append(float(sys.argv[5])) except: print '\nusage: '+sys.argv[0]+' BM_param[0], BM_param[1], BM_param[2], min_rs, max_rs\n' sys.exit(0) RS = Numeric.arange(rs[0],rs[1],0.001,typecode=Numeric.Float) V = RS**3*4./3.*math.pi*320.0 P = (3*BM[0]/2.0)*( (BM[1]/V)**(7./3.) - (BM[1]/V)**(5./3.) )*( 1+3/4.*(BM[2]-4.)*((BM[1]/V)**(2./3.)-1) ) # print P, V out = open('BM_range.dat','w') for i in range(len(P)): out.write(str(RS[i])+' '+str(P[i])+'\n') out.close()
def draw(self, x1, x2, y1, y2, maxiter=30): # draw the Mandelbrot set, from numpy example xx = nm.arange(x1, x2, (x2-x1)/w*2) yy = nm.arange(y2, y1, (y1-y2)/h*2) * 1j q = nm.ravel(xx+yy[:, nm.NewAxis]) z = nm.zeros(q.shape, nm.Complex) output = nm.resize(nm.array(0,), q.shape) for iter in range(maxiter): z = z*z + q done = nm.greater(abs(z), 2.0) q = nm.where(done,0+0j, q) z = nm.where(done,0+0j, z) output = nm.where(done, iter, output) output = (output + (256*output) + (256**2)*output) * 8 # convert output to a string self.mandel = output.tostring()
def execute_module(self): if self._imageAccumulate.GetInput() == None: return self._imageAccumulate.Update() # get histogram params directly from logic minValue = self._imageAccumulate.GetComponentOrigin()[0] cs = self._imageAccumulate.GetComponentSpacing() ce = self._imageAccumulate.GetComponentExtent() numberOfBins = ce[1] - ce[0] + 1 maxValue = minValue + numberOfBins * cs[0] # end of param extraction histArray = Numeric.arange(numberOfBins * 2) histArray.shape = (numberOfBins, 2) od = self._imageAccumulate.GetOutput() for i in range(numberOfBins): histArray[i, 0] = minValue + i * cs[0] histArray[i, 1] = od.GetScalarComponentAsDouble(i, 0, 0, 0) lines = wxPyPlot.PolyLine(histArray, colour="blue") self._viewFrame.plotCanvas.Draw(wxPyPlot.PlotGraphics([lines], "Histogram", "Value", "Occurrences"))
def main(): # Retrieve data from user and format try: f = open(sys.argv[1]) lines = f.readlines() f.close() except: print '\n usage: '+sys.argv[0]+' P_melt-T_melt.dat \n' sys.exit(0) P, T = [], [] for line in lines: P.append(float(line.split()[0])) T.append(float(line.split()[1])) P = Numeric.array(P) T = Numeric.array(T) # Define P0 and T0 P0, T0 = P[0], T[0] # Get the fitting parameters a = kechin(P,T,P0,T0,verbose=True) # Create a new data set from the fit P_fit = Numeric.arange(P[0],P[-1],1.0) T_fit = T0*(1.0 + (P_fit-P0)/a[0])**a[1] * math.e**(-a[2]*(P_fit-P0)) # Write the fit to file out = open('kechin.fit','w') for i in range(len(P_fit)): out.write(str(P_fit[i])+' '+str(T_fit[i])+'\n') out.close()
def __warray(self): """function returning an array with info on walkers""" #arrays that Walker will handle itself skip_size = self.particles*self.dimension*9 w = Numeric.zeros(self.sizeof_walker*self.size,'f') last_i=0 stride=self.sizeof_walker # set for i in Numeric.arange(0,len(w),stride): index = i+skip_size w[index] = 0 # e_l index += 1 w[index] = 0 # wave_func index += 1 w[index] = self.particles index += 1 w[index] = self.dimension index += 1 w[index] = 0 # particles_moved index += 1 w[index] = 0 # replicate index += 1 w[index] = self.sizeof_walker index += 1 w[index] = 0 # dead index += 1 w[index] = 0 # old_eq_new index += 1 return w
def imagesc(z, x=None, y=None, show=None, p=None, scale=1): global HOLD, LAST, TABLE, NROWS, NCOLS, R, C if p is None: if HOLD: p = HOLD else: t = gettable() p = FramedPlot() t[R,C] = p try: nth = p.mplotnum + 1 except KeyError: nth = 0 p.mplotnum = nth if x is None: x = Numeric.arange(0, z.shape[0]) if y is None: y = Numeric.arange(0, z.shape[1]) if scale: z = (0.5 + 255.0 * \ (z - min(Numeric.ravel(z))) \ / (max(Numeric.ravel(z)) - \ min(Numeric.ravel(z)))).astype(Numeric.Int32) else: z = z.astype(Numeric.Int32) # convert RGB/Greyscale to 24bit integer array if len(z.shape) == 2: z = (z << 16) | (z << 8) | z else: z = (z[:,:,0] << 16) | (z[:,:,1] << 8) | z[:,:,2] i, j = 0, 0 for ii in range(z.shape[0]): i = x[ii] for jj in range(z.shape[1]): j = z.shape[1] - y[jj] c = FillBetween([i,i+1], [j,j], [i,i+1], [j+1,j+1],color=z[ii,jj]) p.add(c) if show: p.show() LAST = p return p
self.label = self.canvas.create_window(x, y, window=Label(self.canvas, text=text)) def _hideValue(self, event): if self.label is not None: self.canvas.delete(self.label) self.label = None if __name__ == '__main__': window = Frame() window.pack(fill=BOTH, expand=YES) data1 = 2.*Numeric.pi*Numeric.arange(200)/200. data1.shape = (100, 2) data1[:,1] = Numeric.sin(data1[:,0]) lines1 = PolyLine(data1, color='green') pi = Numeric.pi lines2 = PolyLine([(0., 0.), (pi/2., 1.), (pi, 0.), (3.*pi/2., -1), (2.*pi, 0.)], color='red') markers = PolyMarker([(0., 0.), (pi/2., 1.), (pi, 0.), (3.*pi/2., -1), (2.*pi, 0.)], color='blue', fillcolor='blue', marker='triangle') object = PlotGraphics([lines1, lines2, markers]) def display(value):
# Delete event callback def delete_event(widget, event, data=None): return gtk.FALSE # Destroy event calback def destroy(widget, data=None): gtk.main_quit() # Parse the options plplot.plparseopts(sys.argv, plplot.PL_PARSE_FULL) # The data to plot x = Numeric.arange(11) y = x**2 / 10. # Create the canvas and set its size; during the creation process, # the gcw driver is loaded into plplot, and plinit() is invoked. canvas = plplotcanvas.Canvas() canvas.set_size(WIDTH, HEIGHT) # Create a new window and stuff the canvas into it window = gtk.Window(gtk.WINDOW_TOPLEVEL) window.set_border_width(10) window.add(canvas) # Connect the signal handlers to the window decorations window.connect("delete_event", delete_event) window.connect("destroy", destroy)
def plot3d(data=None, xvec=None, yvec=None, xaxis=None, yaxis=None, zaxis=None, xmin=None, xmax=None, ymin=None, ymax=None, zmin=None, zmax=None, title=None, cmds=None, terminal='openev', output=None, plottype="parametric", wintitle=None): """plot3d(data [,xvec=xaxis_values] [,yvec=yaxis_values] [, xaxis=text] [,yaxis=text] [,zaxis=text] [,title=text] [, xmin=n, xmax=n] [, ymin=n, ymax=n] [, zmin=n, zmax=n] [, cmds=cmd_list] [,terminal={"openev","gnuplot","rasterlayer"}] [, output=ps_filename] [,plottype = {"parametric","contour"}] [, wintitle=text]) data -- data array to plot, should be 2-D set of Z values. Size of data should be length(x) x length(y), if x and y are present.' xvec -- 1-D Vector of values for axis of first dimension of data. yvec -- 1-D Vector of values for axis of second dimension of data. """ ########################################################################### # Print usage() message if no options given. if data is None: print 'Usage: plot3d(data [,xvec=xaxis_values] [,yvec=yaxis_values] ' print ' [, xaxis=text] [,yaxis=text] [,zaxis=text] [,title=text] ' print ' [, xmin=n, xmax=n] [, ymin=n, ymax=n] [, zmin=n, zmax=n] ' print ' [, cmds=cmd_list] [,terminal={"openev","gnuplot,"rasterlayer"}]' print ' [, output=ps_filename] [,plottype = {"parametric","contour"}]' print '' print ' data -- data array to plot, should be 2-D set of Z values.' print ' Size of data should be length(x) x length(y), if x' print ' and y are present.' print ' xvec -- 1-D Vector of values for axis of first dimension of data.' print ' yvec -- 1-D Vector of values for axis of second dimension of data.' print '' return ########################################################################### # Work out the shape of the data. A 1-D array is assumed to be Y # values. An Nx2 array is assumed to be (X,Y) values. All others are # currently invalid. try: dshape = Numeric.shape(data) except: raise ValueError, "data argument to plot() does not appear to be a NumPy array" ########################################################################## # Make sure xvec, yvec are valid indices for x/y axis and revert to # default if not. if xvec is None: xvec = Numeric.arange(dshape[0]) else: try: xshape = Numeric.shape(xvec) if (len(xvec) != dshape[0]): print 'Incorrect length for xvec- reverting to default.' xvec = Numeric.arange(dshape[0]) elif (len(xshape) > 1): print 'xvec should be 1-D- reverting to default.' xvec = Numeric.arange(dshape[0]) except: print 'xvec appears not to be a NumPy array- reverting to default.' xvec = Numeric.arange(dshape[0]) if yvec is None: yvec = Numeric.arange(dshape[1]) else: try: yshape = Numeric.shape(yvec) if (len(yvec) != dshape[1]): print 'Incorrect length for yvec- reverting to default.' yvec = Numeric.arange(dshape[1]) elif (len(yshape) > 1): print 'yvec should be 1-D- reverting to default.' yvec = Numeric.arange(dshape[1]) except: print 'yvec appears not to be a NumPy array- reverting to default.' yvec = Numeric.arange(dshape[1]) ########################################################################### # Setup Plot Options. g = llplot() g.batch = 1 if plottype == "contour": g.add_cmd('set nosurface') g.add_cmd('set contour') g.add_cmd('set view 0,0') g.add_cmd('set data style lines') g.add_cmd('set cntrparam levels 15') else: # g.add_cmd('set parametric') g.add_cmd('set data style lines') g.add_cmd('set hidden3d') if xaxis is not None: g.add_cmd('set xlabel "%s"' % xaxis) if yaxis is not None: g.add_cmd('set ylabel "%s"' % yaxis) if title is not None: g.add_cmd('set title "%s"' % title) if xmin is not None and xmax is not None: g.add_cmd('set xrange [%s:%s]' % (str(xmin), str(xmax))) if ymin is not None and ymax is not None: g.add_cmd('set yrange [%s:%s]' % (str(ymin), str(ymax))) if plottype != "contour": if zaxis is not None: g.add_cmd('set zlabel "%s"' % zaxis) if plottype != "contour": if zmin is not None and zmax is not None: g.add_cmd('set zrange [%s:%s]' % (str(zmin), str(zmax))) if cmds is not None: for cmd in cmds: g.add_cmd(cmd) ########################################################################### # Attach the data. # # Note that we emit the x and y values with each data point. It would # be nice to rewrite this to use binary format eventually. tup_data = [] for x_i in range(len(xvec)): for y_i in range(len(yvec)): tup_data.append((xvec[x_i], yvec[y_i], data[x_i][y_i])) g.set_data(tup_data, dimension=3, xlen=len(xvec)) ########################################################################### # Generate output. if terminal == 'gnuplot': g.batch = 0 g.plot_current() raw_input('Please press return to continue...\n') elif terminal == 'postscript': if (os.name == 'nt'): output = string.join(string.split(output, '\\'), '/') g.add_cmd('set terminal postscript color 10') g.add_cmd("set output '%s'" % output) g.plot_current() else: import gdal import gdalnumeric import time import gview temp_file = gvutils.tempnam() g.add_cmd('set terminal pbm color') g.add_cmd("set output '%s'" % temp_file) g.plot_current() image = gdalnumeric.LoadFile(temp_file) image_ds = gdalnumeric.OpenArray(image) try: os.unlink(temp_file) except: pass rlayer = gview.GvRasterLayer(gview.GvRaster(dataset=image_ds, real=1), rl_mode=gview.RLM_RGBA) rlayer.set_source(1, gview.GvRaster(dataset=image_ds, real=2)) rlayer.set_source(2, gview.GvRaster(dataset=image_ds, real=3)) if terminal == 'rasterlayer': return rlayer graphwin = GvGraphWindow(rlayer) if wintitle is not None: graphwin.set_title(wintitle)
tmp = xj - x tmp[j] = 1. tmp2 = Numeric.product(tmp) l.append(tmp1 / tmp2) ynew.append(Numeric.sum(y * Numeric.array(l))) return Numeric.array(ynew) # Test program if __name__ == '__main__': # Create some data to fit x = Numeric.arange(0., 2 * pi + pi / 4, pi / 4) y = Numeric.sin(x) y[-1] = 0.8 y[-3] = -0.5 y[0] = -0.5 # Fit at some higher resolution x1 = Numeric.arange(0., 2 * pi + pi / 40, pi / 40) y1 = poly(x, y, x1) # Plot the result pylab.plot(x1, y1, linewidth=3) pylab.plot(x, y, 'ro') pylab.axis((0, 7, -1.5, 2.0)) pylab.xlabel('x', fontsize='large') pylab.ylabel('f(x)', fontsize='large')
from matplotlib.axes import Subplot import Numeric as numpy import gtk win = gtk.Window() win.set_name("Embedding in GTK") win.connect("destroy", gtk.mainquit) win.set_border_width(5) vbox = gtk.VBox(spacing=3) win.add(vbox) vbox.show() f = Figure(figsize=(5, 4), dpi=100) a = Subplot(f, 111) t = numpy.arange(0.0, 3.0, 0.01) s = numpy.sin(2 * numpy.pi * t) a.plot(t, s) f.add_axes(a) f.show() vbox.pack_start(f) button = gtk.Button('Quit') button.connect('clicked', lambda b: gtk.mainquit()) button.show() vbox.pack_start(button) win.show() gtk.mainloop()
def setUp(self): self.x = Numeric.arange(10) / 2.0 open('tmp.foo', 'wb').write(self.x.tostring())
box = nmesh.box([0.0, 0.0], [1.0, 1.0]) # create cone cone = nmesh.conic([3.0, 0.0], 1.0, [3.0, 4.0], 0.0) rod = 0.4 bbox = [[-1., -1.], [7., 6.]] # Set up a MayaVi window ready for use during mesher 'pauses'. # The sys.argv hack is only required when MayaVi is used in # a 'callback' function as below, it is not needed in static mode. import mayavi, sys, pylab, shutil sys.argv = ["", ""] # define a few globals, so that the interval function can use them globals()['v'] = mayavi.mayavi() globals()['intervals'] = Numeric.arange(0, 1.05, 0.05) globals()['call_counter'] = 0 # define the interval function def my_function(piece, timestep, mesh_info): """This function can be called to provide MayaVi and pylab visualisations of a mesh whilst it is growing. Author: James Kenny """ globals()['v'], in2circ = nmesh.visual.solid_in2circ(mesh_info, myv=globals()['v']) globals()['v'].renwin.z_plus_view() # to save the VTK files as a series rather than overwriting the same
def nc_setup(nc, varname): """ Does the standard stuff to a new NetCDF file """ # Requirements nc.institution = "Iowa State University, Ames, IA, USA" nc.source = "MM5 (2009): atmosphere: MM5v3.6.3 non-hydrostatic, split-explicit; sea ice: Noah; land: Noah" nc.project_id = "MRED" nc.table_id = "Table 2" nc.realization = 1 nc.forcing_data = "CFS01" nc.experiment_id = "CFS Seasonal Run %s" % (run,) # Optional nc.Conventions = 'CF-1.0' nc.contact = "Daryl Herzmann, [email protected], 515-294-5978" nc.history = "%s Generated" % (mx.DateTime.now().strftime("%d %B %Y"),) nc.comment = "Runs processed on derecho@ISU, output processed on mred@ISU" nc.title = "ISU MM5 model output prepared for MRED using CFS input" # Setup Dimensions tsteps = int( (tsend - ts0).days * 8 ) # 3 hourly nc.createDimension('time', tsteps) nc.createDimension('lat', 66) nc.createDimension('lon', 155) nc.createDimension('bnds', 2) # Generate the coordinate variables tm = nc.createVariable('time', 'd', ('time',) ) tm.units = "days since %s 00:00:00.0" % (ts0.strftime("%Y-%m-%d"),) tm.calendar = "gregorian" tm.long_name = "time" tm.standard_name = "time" tm.axis = "T" tm[:] = Numeric.arange(0.125, (tsend - ts0).days + 0.125, 0.125) # Compute the time_bnds variable, somewhat yucky if varname in ['cuhusa', 'cvhusa', 'hfls', 'hfss', 'mrro', 'pr', 'psl', 'rsds', 'rlds', 'mrros']: tm.bounds = "time_bnds" tb = nc.createVariable('time_bnds', 'd', ('time','bnds') ) val = Numeric.zeros( (tsteps,2), 'd' ) val[:,0] = Numeric.arange(0, (tsend - ts0).days , 0.125) val[:,1] = Numeric.arange(0.125, (tsend - ts0).days + 0.125, 0.125) tb[:] = val lat = nc.createVariable('lat', 'd', ('lat',) ) lat.units = "degrees_north" lat.long_name = "latitude" lat.standard_name = "latitude" lat.axis = "Y" lat[:] = Numeric.arange(24.75,49.5,0.375) lon = nc.createVariable('lon', 'd', ('lon',) ) lon.units = "degrees_east" lon.long_name = "longitude" lon.standard_name = "longitude" lon.axis = "X" lon[:] = Numeric.arange(-124.75,-66.625,0.375) # Generate singletons if varname in ['huss','tas','tasmax', 'tasmin','uas','vas']: height = nc.createVariable('height', 'd') height.long_name = "height" height.standard_name = "height" height.units = "m" height.positive = "up" height.axis = "Z" if varname in ['huss','tas','tasmax','tasmin']: height[:] = 2. elif varname in ['uas','vas']: height[:] = 10. if varname in ['zg850','zg500','zg200','mpuhusa','mpvhusa']: plev = nc.createVariable('plev', 'd') plev.long_name = "pressure" plev.standard_name = "air_pressure" plev.units = "Pa" plev.positive = "down" plev.axis = "Z" if varname in ['zg850','mpuhusa','mpvhusa']: plev[:] = 85000. elif varname in ['zg500',]: plev[:] = 50000. elif varname in ['zg200',]: plev[:] = 20000.
#! /usr/bin/env python import biggles import Numeric, math x = Numeric.arange( 0, 3*math.pi, math.pi/10 ) y = Numeric.sin(x) p = biggles.FramedPlot() p.title = "Title" p.xlabel = "X axis" p.ylabel = "Y axis" p.add( biggles.Histogram(y) ) p.add( biggles.PlotLabel(.5, .5, "Histogram", color=0xcc0000) ) t1 = biggles.Table( 1, 2 ) t1[0,0] = p t1[0,1] = p t2 = biggles.Table( 2, 1 ) t2[0,0] = t1 t2[1,0] = p t2.show()
#!/usr/bin/env python #!/usr/bin/env python """A simple weave exercise. Problem: write a routine, called asum, which will correctly return the sum of all the elements of a 1-d array. Test that it does the right thing by comparing to nx.sum() for the array """ from weave import inline, converters import Numeric as nx #----------------------------------------------------------------------------- # Problem 1 # Let's fill up some arrays with numbers array_bytes = nx.arange(256).astype(nx.UInt8) array_short = nx.arange(256**2).astype(nx.UInt16) # nx.sum has a problem. What is it? print 'WRONG' print nx.sum(array_bytes) print nx.sum(array_short) # Now, a brute-force Python sum works OK def pysum(arr): """Return the sum of all the elements in the array""" ss = 0 for i in xrange(len(arr)): ss += arr[i] return ss
num = (sys.argv[1]) evec_num = int(sys.argv[2]) nc = int(sys.argv[3]) coord = (sys.argv[-nc:]) nc = len(coord) N_fac = 10 EV = get_EV(num) ereal = ((EV.evals[evec_num])).real eimag = ((EV.evals[evec_num])).imag minx = 0 maxx = EV.data['a'] if 'xr' in sys.argv: ind = sys.argv.index('xr') minx = max(0,float(sys.argv[ind+1])) maxx = min(EV.data['a'],float(sys.argv[ind+2])) x = Numeric.arange(minx,maxx,EV.data['a']/(EV.data['ngrid']*N_fac)) print_keys = EV.idata tt = '{/Symbol w}=%g+%gi, '%(ereal,eimag) for i in range(len(print_keys)): tt = tt+'%s=%g, '%(print_keys[i],EV.data[print_keys[i]]) title=tt[:-2] ylabels = [] d = [] for i in range(nc): #ylabels.append('{/Symbol x}_%s'%coord[i]) (y,yl) = EV.get_evec1(coord[i],evec_num,x) ylabels.append(yl) dr = Gnuplot.Data(x,y.real,title='Real',with='lines') di = Gnuplot.Data(x,y.imag,title='Imag',with='lines') inds = Numeric.nonzero((EV.grid>=minx)*(EV.grid<=maxx)) dg = Gnuplot.Data(Numeric.take(EV.grid,inds),0*inds,with='points 1',title='Grid')
#! /usr/pppl/python/2.3.5x/bin/python import Numeric, Gnuplot, sys, math, multiplot from get_EV import * num = (sys.argv[1]) coord = sys.argv[2] evec_num = sys.argv[3:] for i in range(len(evec_num)): evec_num[i] = int(evec_num[i]) nn = len(evec_num) N_fac = 10 EV = get_EV(num) acoef = EV.get_EVrot(minr=.04,maxr=EV.data['k']*EV.data['Vz0']) norm = EV.get_EVnorm() ylabels = [] d = [] x = Numeric.arange(0,EV.data['a'],EV.data['a']/(EV.data['ngrid']*N_fac)) tt = '{/Symbol x}_%s, '%coord print_keys = EV.idata for i in range(len(print_keys)): tt = tt+'%s=%g, '%(print_keys[i],EV.data[print_keys[i]]) title=tt[:-2] for i in range(nn): EV.imag=False try: del EV.sevecs except: pass (y,yl) = EV.get_evec1(coord,evec_num[i],x) ereal = ((EV.evals[evec_num[i]])).real eimag = ((EV.evals[evec_num[i]])).imag ylabels.append( '{/Symbol w}=%g+%gi'%(ereal,eimag))
#!/usr/bin/env python """ Code for Kreuzer's surface science class to plot the coverage for different interaction strengths """ import Numeric, pylab e = Numeric.e v_list = [0,-3,3,10,20,50,100] colors = ['k','b','r','g','m','c','y'] x = Numeric.arange(0.01,50,0.1,typecode=Numeric.Float) theta = [] for v in v_list: theta.append( ( e**(x-v) + (e**(2*(x-v))-e**(x-v)+2*e**(x))*((e**(x-v)-1)**2+4*e**(x))**-0.5 ) / \ ( 1 + e**(x-v) + ( (e**(x-v)-1)**2 + 4*e**(x))**0.5 ) ) for i in range(len(v_list)): pylab.plot(x,theta[i],colors[i]+'-',linewidth=2,label='v = '+str(v_list[i])) pylab.title('Coverage for various interaction strengths') pylab.xlabel(r'$\tt{(\mu - E_{s}) \ / \ k_{B}T}$') pylab.ylabel(r'$\tt{\theta(T,\mu)}$') pylab.legend(loc=0) pylab.savefig('coverage.png')
# Array printing function # # Written by Konrad Hinsen <*****@*****.**> # last revision: 1996-3-13 # modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details) import sys from umath import * import Numeric def array2string(a, max_line_width=None, precision=None, suppress_small=None, separator=' ', array_output=0): """array2string(a, max_line_width = None, precision = None, suppress_small = None, separator=' ', array_output=0)""" if len(a.shape) == 0: return str(a[0]) if multiply.reduce(a.shape) == 0: return "zeros(%s, '%s')" % (a.shape, a.typecode()) if max_line_width is None: try: max_line_width = sys.output_line_width except AttributeError: max_line_width = 77 if precision is None: try: precision = sys.float_output_precision
def __init__(self, mca, command=None): """ Creates a new GUI window for calibrating energy for an Mca object. Inputs: mca: An Mca instance to be calibrated. The Mca must have at least 2 Regions of Interest (ROIs) defined for a linear calibration and 2 ROIs defined for a quadratic calibration. Keywords: command: A callback command that will be executed if the OK button on the GUI window is pressed. The callback will be invoked as: command(exit_status) where exit_status is 1 if OK was pressed, and 0 if Cancel was pressed or the window was closed with the window manager. Procedure: The calibration is done by determining the centroid position and energy of each ROI. The centroids positions are computed by fitting the ROI counts to a Gaussian, using CARSMath.fit_gaussian. The energy the ROI can be entered manually in the GUI window, or it can be determined automatically if the label of the ROI can be successfully used in Xrf.lookup_xrf_line() or Xrf.lookup_gamma_line(). Each ROI can be selectively used or omitted when doing the calibration. The errors in the energy calibration and the FWHM of each ROI as a function of energy, can be plotted using BltPlot. """ self.input_mca = mca self.mca = copy.copy(mca) self.exit_command = command self.roi = self.mca.get_rois() self.nrois = len(self.roi) if (self.nrois < 2): tkMessageBox.showerror(title='mcaCalibrateEnergy Error', message='Must have at least two ROIs to perform calibration') return self.calibration = self.mca.get_calibration() self.fwhm_chan = Numeric.zeros(self.nrois, Numeric.Float) self.widgets = mcaCalibrateEnergy_widgets(self.nrois) self.data = self.mca.get_data() # Compute the centroid and FWHM of each ROI for i in range(self.nrois): left = self.roi[i].left right = self.roi[i].right+1 total_counts = self.data[left:right] n_sel = right - left sel_chans = left + Numeric.arange(n_sel) left_counts = self.data[left] right_counts = self.data[right] bgd_counts = (left_counts + Numeric.arange(float(n_sel))/(n_sel-1) * (right_counts - left_counts)) net_counts = total_counts - bgd_counts net = Numeric.sum(net_counts) if ((net > 0.) and (n_sel >= 3)): amplitude, centroid, fwhm = CARSMath.fit_gaussian(sel_chans, net_counts) self.roi[i].centroid = centroid self.fwhm_chan[i] = fwhm else: self.roi[i].centroid = (left + right)/2. self.fwhm_chan[i] = right-left self.roi[i].fwhm = (self.mca.channel_to_energy(self.roi[i].centroid + self.fwhm_chan[i]/2.) - self.mca.channel_to_energy(self.roi[i].centroid - self.fwhm_chan[i]/2.)) self.widgets.top = t = Pmw.Dialog(command=self.menu_ok_cancel, buttons=('OK', 'Apply', 'Cancel'), title='mcaCalibrateEnergy') top = t.component('dialogchildsite') box = Frame(top, borderwidth=1, relief=SOLID); box.pack(fill=X, pady=3) t = Label(box, text='ROI'); t.grid(row=0, column=0) t = Label(box, text='Use?'); t.grid(row=0, column=1) t = Label(box, text='Centroid'); t.grid(row=0, column=2) t = Label(box, text='FWHM'); t.grid(row=0, column=3) t = Label(box, text='Energy'); t.grid(row=0, column=4) t = Label(box, text='Fluor. line'); t.grid(row=0, column=5) t = Label(box, text='Energy diff.'); t.grid(row=0, column=6) text_width=10 for i in range(self.nrois): row=i+1 t = Label(box, text=str(i)); t.grid(row=row, column=0) self.widgets.use_flag[i] = t = Pmw.OptionMenu(box, items=('No','Yes'), initialitem = self.roi[i].use, command=lambda e, s=self, r=i: s.menu_use(e,r)) t.grid(row=row, column=1) self.widgets.centroid[i] = t = Pmw.EntryField(box, value=('%.3f' % self.roi[i].centroid), entry_width=text_width, entry_justify=CENTER, command=lambda s=self, r=i: s.menu_centroid(r)) t.grid(row=row, column=2) self.widgets.fwhm[i] = t = Label(box, text=('%.3f' % self.roi[i].fwhm), width=text_width, justify=CENTER, borderwidth=1, relief=SOLID) t.grid(row=row, column=3) # If the ROI energy is zero, then try to use the label to lookup an # XRF line energy if (self.roi[i].energy == 0.0): self.roi[i].energy = Xrf.lookup_xrf_line(self.roi[i].label) if (self.roi[i].energy == None): self.roi[i].energy = Xrf.lookup_gamma_line(self.roi[i].label) if (self.roi[i].energy == None): self.roi[i].energy=0.0 self.widgets.energy[i] = t = Pmw.EntryField(box, value=('%.3f' % self.roi[i].energy), entry_width=text_width, entry_justify=CENTER, command=lambda s=self, r=i: s.menu_energy(r)) t.grid(row=row, column=4) self.widgets.line[i] = t = Pmw.EntryField(box, value=str(self.roi[i].label), entry_width=text_width, entry_justify=CENTER, command=lambda s=self, r=i: s.menu_line(r)) t.grid(row=row, column=5) self.widgets.energy_diff[i] = t = Label(box, text=('%.3f' % 0.0), width=text_width, justify=CENTER, borderwidth=1, relief=SOLID) t.grid(row=row, column=6) row = Frame(top, borderwidth=1, relief=SOLID); row.pack(fill=X, pady=3) self.widgets.fit_type = t = Pmw.OptionMenu(row, labelpos=N, label_text='Calibration type:', items=('Linear','Quadratic')) t.pack(side=LEFT, anchor=S) self.widgets.do_fit = t = Button(row, text='Compute calibration', command=self.menu_do_fit) t.pack(side=LEFT, anchor=S) self.widgets.plot_cal = t = Button(row, text='Plot calibration error', command=self.menu_plot_calibration) t.pack(side=LEFT, anchor=S) self.widgets.plot_fwhm = t = Button(row, text='Plot FWHM', command=self.menu_plot_fwhm) t.pack(side=LEFT, anchor=S) row = Frame(top, borderwidth=1, relief=SOLID); row.pack(fill=X, pady=3) text_width=10 t = Label(row, text='Calibration coefficients'); t.pack() self.widgets.cal_units = t = Pmw.EntryField(row, label_text='Units:', labelpos=W, value=self.calibration.units, entry_width=text_width, entry_justify=CENTER) t.pack(side=LEFT) self.widgets.cal_offset = t = Pmw.EntryField(row, label_text='Offset:', labelpos=W, value=self.calibration.offset, entry_width=text_width, entry_justify=CENTER) t.pack(side=LEFT) self.widgets.cal_slope = t = Pmw.EntryField(row, label_text='Slope:', labelpos=W, value=self.calibration.slope, entry_width=text_width, entry_justify=CENTER) t.pack(side=LEFT) self.widgets.cal_quad = t = Pmw.EntryField(row, label_text='Quadratic:', labelpos=W, value=self.calibration.quad, entry_width=text_width, entry_justify=CENTER) t.pack(side=LEFT)
print "%s: %s" % (ImportError, message) print "Install NumPy to plot NumPy arrays" except TypeError, message: print "%s: %s" % (TypeError, message) print "Rebuild PyQwt to plot NumPy arrays" self.removeChild(numpy_plot) # try to create a plot widget for Numeric arrays try: # import does_not_exist import Numeric numeric_plot = QwtPlot('Plot -- Numeric arrays', self) numeric_plot.plotLayout().setCanvasMargin(0) numeric_plot.plotLayout().setAlignCanvasToScales(1) numeric_x = Numeric.arange(0.0, 10.0, 0.01) numeric_y = lorentzian(numeric_x) # insert a curve, make it red and copy the arrays key = numeric_plot.insertCurve('y = lorentzian(x)') numeric_plot.setCurvePen(key, QPen(Qt.red)) numeric_plot.setCurveData(key, numeric_x, numeric_y) grid.addWidget(numeric_plot, 0, 1) numeric_plot.replot() except ImportError, message: print "%s: %s" % (ImportError, message) print "Install Numeric to plot Numeric arrays" except TypeError, message: print "%s: %s" % (TypeError, message) print "Rebuild PyQwt to plot Numeric arrays" self.removeChild(numeric_plot)
def frange2(start, end=None, inc=1.0, typecode=None): if end == None: end = start + 0.0 # Ensure a float value for 'end' start = 0.0 nitems = math.ceil((end - start) / inc) return Numeric.arange(nitems) * inc + start
rho = 20 R = 1 k = .5 from pygsl import sf from get_EV import * import Numeric import Gnuplot import sys m=1 gamma = ([1.841183781, 5.331442774, 8.536316366, 11.7060049, 14.86358863, 18.01552786, 21.16436986, 24.31132686, 27.45705057, 30.60192297, 33.7461829, 3.68899874E+01, 40.03344405, 43.17662897, 46.31959756, 49.46239114, 52.60504111, 55.74757179, 58.8900023]) N = 10 d = get_EV(int(sys.argv[1])) data = d.data nphi = data['ngrid'] xgrid = d.grid x = Numeric.arange(0,data['a'],data['a']/100.) x[0] = x[1]/10000.0 y = Numeric.zeros(len(x),typecode=Numeric.Float) ygrid = Numeric.zeros(len(xgrid),typecode=Numeric.Float) dk = data A = dk['a']**2 s2 = dk['s2'] evals = d.evals.real**2 if data['fe_type'] == 'linconst': xgrid = xgrid+xgrid[1]/2. for gamma_ind in range(6):#min(nphi,len(gamma)-1)):#nphi,2): for i in range(len(x)): y[i] = sf.bessel_J1(x[i]*gamma[gamma_ind])[0] for i in range(len(xgrid)): ygrid[i] = sf.bessel_J1(xgrid[i]*gamma[gamma_ind])[0] omega1 = dk['Bz0']**2/(2*dk['rho0']*s2/(5./3.)*dk['Bz0']**2*A)*(A*dk['k']**2+gamma[gamma_ind]**2)*(1+s2)*(1-(1-4*s2*A*dk['k']**2/((1+s2)**2*(A*dk['k']**2+gamma[gamma_ind]**2)))**(1./2.))
# An example of use # ================= # # In order to get an idea of what the above extension offers, try to run # this script against the !NumInd extension: # # <codecell> import Numeric import numarray import numpy import numind # Create an arbitrary object for each package nu=Numeric.arange(12) nu.shape = (4,3) na=numarray.arange(12) na.shape = (4,3) np=numpy.arange(12) np.shape = (4,3) # Wrap the different objects with the NumInd class # and execute some actions on it for obj in [nu, na, np]: ni = numind.NumInd(obj) print "original object type-->", type(ni.undarray) # Print some values print "typestr -->", ni.typestr print "shape -->", ni.shape print "strides -->", ni.strides
PERIOD = 30 # The width and height for each plot widget WIDTH = 800 HEIGHT = 300 # Run the plots in different threads thread0 = None thread1 = None # Create two different canvases canvas0 = None canvas1 = None # Create the x array x = Numeric.arange(NPTS) # Lock on the gtkstate so that we don't try to plot after gtk_main_quit GTKSTATE_CONTINUE = True GTKSTATE_QUIT = False gtk_state_lock = threading.Lock() gtk_state = GTKSTATE_CONTINUE # setup_plt - preparation for plotting an animation to a canvas def setup_plot(canvas, title): # Set up the viewport and window canvas.plvsta() canvas.plwind(x[0], x[NPTS - 1], -2., 2.) # Set the pen width
def makePlots(data, airmass, color1, color2, outfile, fits, label): file = outfile + ".ps" pgbeg(file + "/cps", 2, 3) pgiden() for i in range(len(fits)): result = fits[i]['fitvars'] # Airmass plot pgpanl(1, i + 1) airMin = 1 airMax = Numeric.sort(airmass)[-1] * 1.1 print result dataAirMax = result['zp'] + result['airmass'] + 1 dataAirMin = result['zp'] + result['airmass'] - 1 dataColMax = result['zp'] + 1 dataColMin = result['zp'] - 1 colMinVal = Numeric.sort(color)[0] if colMinVal < 0: colMin = colMinVal * 1.1 else: colMin = colMinVal * 0.95 colMax = Numeric.sort(color)[-1] * 1.1 if result[0] and result[1]: eqStr = "%d parameter fit: Mag-Mag(Inst) = %.2f\\(2233)%.2f + (%.2f\\(2233)%.2f) airmass + "\ "(%.2f\\(2233)%.2f) color" % \ (3-i, result[0]['zp'], result[1][0], result[0]['airmass'], result[1][1], result[0]['color1'], result[1][2]) else: eqStr = "%d parameter fit not possible" % (3 - i, ) fixenv([1, airMax], [dataAirMin, dataAirMax], eqStr, label=["Airmass", "Mag - Mag(Inst)"]) condition = result[4] goodAirmass = Numeric.compress(condition, airmass) goodData = Numeric.compress(condition, data) goodColor = Numeric.compress(condition, color) badAirmass = Numeric.compress(Numeric.logical_not(condition), airmass) badData = Numeric.compress(Numeric.logical_not(condition), data) badColor = Numeric.compress(Numeric.logical_not(condition), color) #remove the color dependence if len(goodData): pgsci(3) # Rescale to zero color and filter for data within # our plotting range plotData = goodData - result[0]['color'] * goodColor plotCond1 = Numeric.less(plotData, dataAirMax) plotCond2 = Numeric.greater(plotData, dataAirMin) plotCond = Numeric.logical_and(plotCond1, plotCond2) plotAirmass = Numeric.compress(plotCond, goodAirmass) plotData = Numeric.compress(plotCond, plotData) pgpt(plotAirmass, plotData, 5) print type(plotAirmass), type(plotData) if len(badData): pgsci(2) plotData = badData - result[0][2] * badColor plotCond1 = Numeric.less(plotData, dataAirMax) plotCond2 = Numeric.greater(plotData, dataAirMin) plotCond = Numeric.logical_and(plotCond1, plotCond2) plotAirmass = Numeric.compress(plotCond, badAirmass) plotData = Numeric.compress(plotCond, plotData) pgpt(plotAirmass, plotData, 5) pgsci(1) a = Numeric.arange(1, airMax, 0.01) m = result[0][0] + result[0][1] * a pgline(a, m) # Color Plot pgpanl(2, i + 1) fixenv([colMin, colMax], [dataColMin, dataColMax], eqStr, label=[label, "Mag - Mag(Inst)"]) if len(goodData): pgsci(3) # Rescale to zero airmass and filter for data within # our plotting range plotData = goodData - result[0][1] * goodAirmass plotCond1 = Numeric.less(plotData, dataColMax) plotCond2 = Numeric.greater(plotData, dataColMin) plotCond = Numeric.logical_and(plotCond1, plotCond2) plotColor = Numeric.compress(plotCond, goodColor) plotData = Numeric.compress(plotCond, plotData) pgpt(plotColor, plotData, 5) if len(badData): pgsci(2) plotData = badData - result[0][1] * badAirmass plotCond1 = Numeric.less(plotData, dataColMax) plotCond2 = Numeric.greater(plotData, dataColMin) plotCond = Numeric.logical_and(plotCond1, plotCond2) plotColor = Numeric.compress(plotCond, badColor) plotData = Numeric.compress(plotCond, plotData) pgpt(plotColor, plotData, 5) pgsci(1) a = Numeric.arange(colMin, colMax, 0.01) m = result[0][0] + result[0][2] * a pgline(a, m) return
y = [] dy = [] dx = [] for s in u1runs: x.append(bboutdata[s][0] * 2000. + u1shifts[s][0]) y.append(bboutdata[s][1]) dy.append(bboutdata[s][2]) dx.append(u1shifts[s][1]) p.add( biggles.Points(x, y, symboltype="filled circle", symbolsize=1, color="red")) p.add(biggles.SymmetricErrorBarsY(x, y, dy, color="red")) p.add(biggles.SymmetricErrorBarsX(x, y, dx, color="red")) # p.show() x = Numeric.arange(9460 - 5, 9460 + 5, 0.025) y = map( lambda xi: u1func(318.5185, 3.78739, 0.40577 * nbish2nb, 0.053, 0.01864, 0., 0.0267, 0.2, 0., 0.0792, xi, lumisource=0), x) p.add(biggles.Curve(x, y, color="black")) # p.show()
#!/usr/bin/env python """ Code for Kreuzer's surface science class to plot the coverage for different interaction strengths """ import Numeric, pylab e = Numeric.e P_list = [0.01, 0.1, 1, 10, 100, 1000, 10000, 100000] colors = ['k', 'b', 'r', 'g', 'm', 'c', 'y', 'k'] v = Numeric.arange(-5.99, 12, 0.1, typecode=Numeric.Float) theta = [] B = 1 A = B * e**-v for P in P_list: theta.append( (A*P + ((A*P)**2 - A*P + 2*B*P)*((A*P-1)**2+4*B*P)**-0.5) / \ (1 + A*P + ((A*P-1)**2+4*B*P)**0.5) ) last = [] pylab.plot(v, [0.5 for i in v], 'r--', linewidth=2, label=r'$\tt{\theta(T,P)\ =\ 0.5}$') for i in range(len(P_list)): pylab.plot(v, theta[i], colors[i] + '-', linewidth=2, label='P = ' + str(P_list[i])) last.append(theta[i][-1])
try: executable = os.environ["SIESTA_COMMAND"] except: executable = "siesta" print "using executable: ", executable # # Standard bond length (units: Angstrom) # d0 = math.sqrt(0.757**2 + 0.586**2) # Range of bond lengths around the presumed minimum bonds = num.arange(0.8*d0,1.3*d0,0.1) energy = 0.0*bonds theta=0.5*(180.-105.0)*math.pi/180. # Angle with the x axis, in radians print bonds a = Siesta(executable="siesta") # Initialize object ##a.SetOption("DM.UseSaveDM","T") # create a work subdirectory orig_dir = os.getcwd() dir = "bond_work" if os.path.isdir(dir): # does dir exist? shutil.rmtree(dir) # yes, remove old directory os.mkdir(dir) # make dir directory os.chdir(dir) # move to dir
s = format % x return s def _formatComplex(x, real_format, imag_format): r = _formatFloat(x.real, real_format) i = _formatFloat(x.imag, imag_format, 0) if imag_format[-1] == 'f': zeros = len(i) while zeros > 2 and i[zeros - 1] == '0': zeros = zeros - 1 i = i[:zeros] + 'j' + (len(i) - zeros) * ' ' else: i = i + 'j' return r + i def _formatGeneral(x): return str(x) + ' ' if __name__ == '__main__': a = Numeric.arange(10) b = Numeric.array([a, a + 10, a + 20]) c = Numeric.array([b, b + 100, b + 200]) print array2string(a) print array2string(b) print array2string(sin(c), separator=', ', array_output=1) print array2string(sin(c) + 1j * cos(c), separator=', ', array_output=1) print array2string(Numeric.array([[], []]))
def GridData(data, xvals=None, yvals=None, inline=_unset, **keyw): """Return a _FileItem representing a function of two variables. 'GridData' represents a function that has been tabulated on a rectangular grid. The data are written to a file; no copy is kept in memory. Arguments: 'data' -- the data to plot: a 2-d array with dimensions (numx,numy). 'xvals' -- a 1-d array with dimension 'numx' 'yvals' -- a 1-d array with dimension 'numy' 'binary=<bool>' -- send data to gnuplot in binary format? 'inline=<bool>' -- send data to gnuplot "inline"? Note the unusual argument order! The data are specified *before* the x and y values. (This inconsistency was probably a mistake; after all, the default xvals and yvals are not very useful.) 'data' must be a data array holding the values of a function f(x,y) tabulated on a grid of points, such that 'data[i,j] == f(xvals[i], yvals[j])'. If 'xvals' and/or 'yvals' are omitted, integers (starting with 0) are used for that coordinate. The data are written to a temporary file; no copy of the data is kept in memory. If 'binary=0' then the data are written to a datafile as 'x y f(x,y)' triplets (y changes most rapidly) that can be used by gnuplot's 'splot' command. Blank lines are included each time the value of x changes so that gnuplot knows to plot a surface through the data. If 'binary=1' then the data are written to a file in a binary format that 'splot' can understand. Binary format is faster and usually saves disk space but is not human-readable. If your version of gnuplot doesn't support binary format (it is a recently-added feature), this behavior can be disabled by setting the configuration variable 'gp.GnuplotOpts.recognizes_binary_splot=0' in the appropriate gp*.py file. Thus if you have three arrays in the above format and a Gnuplot instance called g, you can plot your data by typing 'g.splot(Gnuplot.GridData(data,xvals,yvals))'. """ # Try to interpret data as an array: data = utils.float_array(data) try: (numx, numy) = data.shape except ValueError: raise Errors.DataError('data array must be two-dimensional') if xvals is None: xvals = Numeric.arange(numx) else: xvals = utils.float_array(xvals) if xvals.shape != (numx,): raise Errors.DataError( 'The size of xvals must be the same as the size of ' 'the first dimension of the data array') if yvals is None: yvals = Numeric.arange(numy) else: yvals = utils.float_array(yvals) if yvals.shape != (numy,): raise Errors.DataError( 'The size of yvals must be the same as the size of ' 'the second dimension of the data array') # Binary defaults to true if recognizes_binary_plot is set; # otherwise it is forced to false. binary = keyw.get('binary', 1) and gp.GnuplotOpts.recognizes_binary_splot keyw['binary'] = binary if inline is _unset: inline = (not binary) and gp.GnuplotOpts.prefer_inline_data # xvals, yvals, and data are now all filled with arrays of data. if binary: if inline: raise Errors.OptionError('binary inline data not supported') # write file in binary format # It seems that the gnuplot documentation for binary mode # disagrees with its actual behavior (as of v. 3.7). The # documentation has the roles of x and y exchanged. We ignore # the documentation and go with the code. mout = Numeric.zeros((numy + 1, numx + 1), Numeric.Float32) mout[0,0] = numx mout[0,1:] = xvals.astype(Numeric.Float32) mout[1:,0] = yvals.astype(Numeric.Float32) try: # try copying without the additional copy implied by astype(): mout[1:,1:] = Numeric.transpose(data) except: # if that didn't work then downcasting from double # must be necessary: mout[1:,1:] = Numeric.transpose(data.astype(Numeric.Float32)) content = mout.tostring() if gp.GnuplotOpts.prefer_fifo_data: return apply(_FIFOFileItem, (content,), keyw) else: return apply(_TempFileItem, (content,), keyw) else: # output data to file as "x y f(x)" triplets. This # requires numy copies of each x value and numx copies of # each y value. First reformat the data: set = Numeric.transpose( Numeric.array( (Numeric.transpose(Numeric.resize(xvals, (numy, numx))), Numeric.resize(yvals, (numx, numy)), data)), (1,2,0)) # Now output the data with the usual routine. This will # produce data properly formatted in blocks separated by blank # lines so that gnuplot can connect the points into a grid. f = StringIO() utils.write_array(f, set) content = f.getvalue() if inline: return apply(_InlineFileItem, (content,), keyw) elif gp.GnuplotOpts.prefer_fifo_data: return apply(_FIFOFileItem, (content,), keyw) else: return apply(_TempFileItem, (content,), keyw)
d = 1.13 paw = GPAW('co.gpw', txt=None) import pylab as p dpi = 2 * 80 p.figure(figsize=(4, 3), dpi=dpi) p.axes([0.15, 0.15, 0.8, 0.8]) import sys if len(sys.argv) == 1: N = 1 else: N = int(sys.argv[1]) psit = paw.kpt_u[0].psit_nG[N] psit = psit[:, 0, 0] ng = len(psit) x = num.arange(ng) * a / ng - c p.plot(x, psit, 'bx', mew=2, label=r'$\tilde{\psi}$') C = 'g' for n in paw.nuclei: s = n.setup phi_j, phit_j = s.get_partial_waves()[:2] print s.rcut_j[0] r = num.arange(30) * s.rcut_j[0] / 30 phi_i = num.empty((s.ni, 59), num.Float) phit_i = num.empty((s.ni, 59), num.Float) x = num.empty(59, num.Float) x[29:] = r x[29::-1] = -r x *= paw.a0 i = 0
# Various statistics functions.
LowChan = 0 HighChan = 0 Count = 2000 Rate = 3125 Options = UL.CONVERTDATA ADData = Numeric.zeros((Count, ), Numeric.Int16) ActualRate = UL.cbAInScan(BoardNum, LowChan, HighChan, Count, Rate, Gain, ADData, Options) # convert to Volts data_in_volts = [UL.cbToEngUnits(BoardNum, Gain, y) for y in ADData] time = Numeric.arange(ADData.shape[0]) * 1.0 / ActualRate pylab.plot(time, data_in_volts, 'o-') pylab.xlabel('time (sec)') pylab.ylabel('Volts') pylab.savefig('example3.png', dpi=72) pylab.show() # <markdowncell> # The) output looks much better: ![](files/Data_Acquisition_with_PyUL_attachments/example3.png # # Example 4 - computing the power spectrum # ======================================== # # Now we can use the function from pylab (part of matplotlib) to compute
ymin = -.05 ymax = max(aveaperr) #ymax=10. ppgplot.pgenv(DATAMIN, DATAMAX, ymin, ymax, 0) ppgplot.pglab("linear size N of aperture (pixel)", "rms in Sky (ADU/s)", title) ppgplot.pgsci(2) #red ppgplot.pgslw(4) #line width x = N.sqrt(avearea) y = aveaperr ppgplot.pgpt(x, y, 7) #errory(x,y,erry) ppgplot.pgsci(1) #black #ppgplot.pgpt(isoarea,fluxerriso,3) #x1=N.sqrt(contsubisoarea) #y1=contsuberr x1 = N.sqrt(isoarea) y1 = fluxerriso y = n * y1 ppgplot.pgpt(x1, y1, 1) ppgplot.pgsci(4) #blue ppgplot.pgpt(x1, y, 1) ppgplot.pgsci(1) #black x = N.arange(0, 50, 1) y = x * (a + b * a * x) #y=N.sqrt(x)*.02 ppgplot.pgline(x, y) #errory(x,y,erry) ppgplot.pgend()