def test_fwt1Dc4(self): """test that fwt1D works on a 'random' vector, D=4""" # Matlab random vector X = Numeric.array( [ 0.81797434083925, 0.66022755644160, 0.34197061827022, 0.28972589585624, 0.34119356941488, 0.53407901762660, 0.72711321692968, 0.30929015979096, ] ) # Result from fwt(X, 4) in Matlab Y_ref = Numeric.array( [ 1.42184125586417, -0.15394808354817, 0.05192707167183, 0.37115044369886, -0.10770249228974, -0.08172091206233, 0.29500215027890, 0.20196258114742, ] ) Y = fwt(X, 4) assert Numeric.allclose(Y - Y_ref, 0)
def test_fwt1Dc8(self): """test that fwt1D works on a 'random' vector, D=8""" # Matlab random vector X = Numeric.array( [ 0.81797434083925, 0.66022755644160, 0.34197061827022, 0.28972589585624, 0.34119356941488, 0.53407901762660, 0.72711321692968, 0.30929015979096, ] ) # Result from fwt(X, 8) in Matlab Y_ref = Numeric.array( [ 1.42184125586417, -0.27774330567583, 0.26539391030148, 0.02521137886213, 0.13638973750197, 0.31441497909028, -0.20260945655043, 0.05934606703242, ] ) Y = fwt(X, 8) assert Numeric.allclose(Y - Y_ref, 0)
def readdata(self, input1, input2): infile1 = open(input1, 'r') self.morphall = [] for line in infile1: if line.find('#') > -1: continue f = line.split() self.morphall.append(float(f[1])) self.morphall = N.array(self.morphall, 'f') infile1.close() infile2 = open(input2, 'r') self.morph24 = [] self.f24 = [] self.errf24 = [] for line in infile2: if line.find('#') > -1: continue f = line.split() self.morph24.append(float(f[1])) self.f24.append(float(f[2])) self.errf24.append(float(f[3])) self.morph24 = N.array(self.morph24, 'f') self.f24 = N.array(self.f24, 'f') self.errf24 = N.array(self.errf24, 'f') infile2.close()
def doubleParityChksum(data): """Computes horizontal an vertical parities. One horizontal parity bit is computed per octet. 8 vertical parity bits are computed. The checksum is the 8 vertical parity bits plus the horizontal parity bits, padded by a variable number of 0 bits to align on an octet boundary. Even parity is used. The checksum is returned as a string where each character codes a byte of the checksum. """ bitmask = Numeric.array([128,64,32,16,8,4,2,1]) bytes = Numeric.fromstring(data,Numeric.UnsignedInt8) numBytes = len(bytes) bits = Numeric.bitwise_and.outer(bytes,bitmask).flat Numeric.putmask(bits,bits,1) bits = Numeric.reshape(bits, (numBytes,8)) verParities = Numeric.bitwise_and(Numeric.sum(bits),1) bits = Numeric.concatenate((bits,[verParities])) horParities = Numeric.bitwise_and(Numeric.sum(bits,1),1) if len(horParities)%8: horParities = Numeric.concatenate((horParities, [0]*(8-len(horParities)%8))) bitmask = Numeric.array([128,64,32,16,8,4,2,1]) chksumstring = chr(Numeric.dot(verParities,bitmask)) for i in range(len(horParities)/8): chksumstring += chr(Numeric.dot(horParities[i*8:(i+1)*8],bitmask)) return chksumstring
def plotsnr(self,name): outfile=str(name)+'snr.dat' output=open(outfile,'w') flux1=[] errflux1=[] flux2=[] errflux2=[] fluxsnr=[] for i in range(len(self.f24)): if self.matchflagediscs24[i] > 0: fluxsnr = (self.f24[i])/(self.errf24[i]) flux1.append(fluxsnr) flux2.append(self.f24[i]) #print "found match with Halpha source!\n" i=i+1 flux1=N.array(flux1,'f') flux2=N.array(flux2,'f') pylab.xlabel('24 micron flux') pylab.ylabel('24 micron Flux/24 micron Flux error') title='24 Micron Flux/24 micron Flux error Versus 24 micron Flux for '+str(name) pylab.title(title) pylab.plot(flux2,flux1, 'bo') pylab.axhline(6.) k=6.*19. pylab.axhline(3.) k=6.*19. pylab.axvline(k) k=6.*26. pylab.axvline(k) pylab.axis([0,500,0,20]) pylab.show()
def __init__(self,fname,sep=None,timescale = 0.001): """Initialise fname: name of file to read from. sep: separator (whitespace if set to none timescale: scale time""" infile = open(fname,'r') self.timescale = 0.001 stime = [] sdata = [] self.numt = 0 self.__index = 0 for line in infile.readlines(): pos = line.find('#') if pos>-1: line = line[:pos] line = line.strip() if len(line) == 0: continue if sep == None: l = line.split() else: l = line.split(sep) stime.append(float(l[0])*self.timescale) data = [] for d in l[1:]: d = float(d) data.append(d) sdata.append(data) self.numt = self.numt + 1 self.time = Numeric.array(stime) self.data = Numeric.array(sdata)
def single_well_numerov_match(V0, dx, parity=1, overlapsize=5): "generate a candidate eigenfunction with given potential, assuming the potential well has a single allowed region bounded on both sides" assert len(V0) & 1, "Must have a grid with an odd number of points" vminchan=Numeric.argmin(V0) #position of bottom of well right_turn=Numeric.searchsorted(V0[vminchan:], 0.0)+vminchan #position of right-hand turning point #integrate from left end to right-hand turning point, at which point numerov method becomes unstable leftpsi=bare_numerov(V0[:right_turn], dx) #iterate backwards on right part to turning point, and flatten to normal array rightpsi= Numeric.array(bare_numerov(V0[right_turn-overlapsize:][::-1], dx)[::-1]) #remember that since Numeric handles slices without copying, leftend and rightend also scale here slopeweight=Numeric.array(range(overlapsize),Numeric.Float)-overlapsize/2.0 leftend=leftpsi[-overlapsize:] rightend=rightpsi[:overlapsize] scale=abs(Numeric.sum(leftend*rightend)/Numeric.sum(leftend**2)) #'least-squares' scale estimate #note that since leftend and rightend are Numeric slice references, modifying psi also changes them! rightpsi*=float(parity)/scale error=Numeric.sum((leftend-rightend)*slopeweight) #average derivative psi0=Numeric.concatenate((leftpsi, rightpsi[overlapsize:])) psi2=psi0*psi0 integral=psi2[0]+psi2[-1]+4.0*Numeric.sum(psi2[1:-1:2])+2.0*Numeric.sum(psi2[2:-2:2]) #use simpson's rule psimag=1.0/math.sqrt(integral*dx/3.0) return psi0*psimag, error*psimag
def testMultipleDimensionCreation (self): 'Test creation of multidimensional arrays.' alist = [[2,3],[4,5]] x = Numeric.array(alist) assert x.shape == (2,2) y = Numeric.array([x, x + 1, x + 2]) assert y.shape == (3,2,2)
def plotit(xs,ys,title,legends): # # Do it # num_points=0 for x in xs: num_points=num_points+len(x) print num_points,'data points' #x=[1,2,3,4,5,6,7,8,9] #y=[2,4,6,8,10,12,14,16,18] mat_fix=[] vec_fix=[] for x in xs: for point in x: mat_fix.append([point,1.0]) for y in ys: for point in y: vec_fix.append(point) import LinearAlgebra sols,rsq,rank,junk=LinearAlgebra.linear_least_squares(Numeric.array(mat_fix), Numeric.array(vec_fix)) slope=sols[0] intercept=sols[1] print rsq rsq=float(rsq[0]) print 'Slope: %.2f, Intercept: %.2f, R^2: %.2f' %(slope,intercept,rsq) file=dislin_driver.graf_mult3(xs,ys,title,'Simple E','PBE_ene',legends) return
def getpositions(ximage, yimage, isoarea): dmin = 30. #minimum distance to object + sqrt(isoarea) xmax = c.xmax[ncl] #max x dimension ymax = c.ymax[ncl] #max y dimension xpos = [] ypos = [] da = N.sqrt(isoarea) d = N.zeros(len(ximage), 'f') #print len(d) i = 0 while i < npoints: xtemp = random.uniform(0, 1) * xmax ytemp = random.uniform(0, 1) * ymax if (checkposition(xtemp, ytemp) > 0): j = 0 for j in range(len(ximage)): #print j,len(ximage),len(yimage),len(da),len(d) d[j] = N.sqrt((ximage[j] - xtemp)**2 + (yimage[j] - ytemp)**2) - da[j] if (min(d) > dmin): xpos.append(xtemp) ypos.append(ytemp) i = i + 1 xpos = N.array(xpos, 'f') ypos = N.array(ypos, 'f') return xpos, ypos
def demo(): """ Non-interactive demonstration of the clusterers with simple 2-D data. """ # use a set of tokens with 2D indices tokens = [Token(FEATURES=Numeric.array([3, 3])), Token(FEATURES=Numeric.array([1, 2])), Token(FEATURES=Numeric.array([4, 2])), Token(FEATURES=Numeric.array([4, 0])), Token(FEATURES=Numeric.array([2, 3])), Token(FEATURES=Numeric.array([3, 1]))] # test k-means using the euclidean distance metric, 2 means and repeat # clustering 10 times with random seeds clusterer = KMeansClusterer(2, euclidean_distance, repeats=10) clusterer.cluster(tokens, True) print 'using clusterer', clusterer print 'clustered', str(tokens)[:60], '...' # classify a new token token = Token(FEATURES=Numeric.array([3, 3])) print 'classify(%s)' % token, clusterer.classify(token) print token # test the GAAC clusterer with 4 clusters clusterer = GroupAverageAgglomerativeClusterer(4) print 'using clusterer', clusterer clusterer.cluster(tokens, True) #print 'clustered', str(tokens)[:60], '...' print 'clustered', tokens # show the dendogram clusterer.dendogram().show() # classify a new token token = Token(FEATURES=Numeric.array([3, 3])) print 'classify(%s)' % token, clusterer.classify(token) print token print # test the EM clusterer with means given by k-means (2) and # dimensionality reduction clusterer = KMeansClusterer(2, euclidean_distance, svd_dimensions=1) clusterer.cluster(tokens) means = clusterer.means() clusterer = ExpectationMaximizationClusterer(means, svd_dimensions=1) clusterer.cluster(tokens, True) print 'using clusterer', clusterer print 'clustered', str(tokens)[:60], '...' # classify a new token token = Token(FEATURES=Numeric.array([3, 3])) print 'classify(%s)' % token, clusterer.classify(token) print token # show the classification probabilities token = Token(FEATURES=Numeric.array([2.2, 2])) print 'classification_probdist(%s)' % token clusterer.classification_probdist(token) for sample in token['CLUSTER_PROBDIST'].samples(): print '%s => %.0f%%' % (sample, token['CLUSTER_PROBDIST'].prob(sample) *100)
def addtogroupsplot2(csfunc): combinemap = {} combinemap[0] = [] combinemap[1] = [] combinemap[2] = [] combinemap[3] = [] combinemap[4] = [] combinemap[5] = [] combinemap[6] = [] combinemap[7] = [] combinemap[8] = [] combinemap[9] = [] for r in testsample: combinemap[0].append(csfunc(r)) combinemap[groupify(r)].append(csfunc(r)) groups = range(1, 10) hadgroup = [0] * 9 hadgroup_err = [0] * 9 for g in groups: hadgroup[g - 1], hadgroup_err[g - 1] = jt.wmean(combinemap[g]) center_of_groups = jt.wmean(combinemap[0])[0] centers, errors = Numeric.array( hadgroup) / center_of_groups, Numeric.array( hadgroup_err) / center_of_groups chi2 = 0. for c, e in zip(centers, errors): print(c - 1), e chi2 += ((c - 1) / e)**2 print chi2
def addtogroupsplot(p, csfunc, offset, color, kind): combinemap = {} combinemap[0] = [] combinemap[1] = [] combinemap[2] = [] combinemap[3] = [] combinemap[4] = [] combinemap[5] = [] combinemap[6] = [] combinemap[7] = [] combinemap[8] = [] combinemap[9] = [] for r in testsample: combinemap[0].append(csfunc(r)) combinemap[groupify(r)].append(csfunc(r)) groups = range(1, 10) hadgroup = [0] * 9 hadgroup_err = [0] * 9 for g in groups: hadgroup[g - 1], hadgroup_err[g - 1] = jt.wmean(combinemap[g]) center_of_groups = jt.wmean(combinemap[0])[0] tmp = biggles.Points(Numeric.array(groups) + offset, Numeric.array(hadgroup) / center_of_groups, type=kind, color=color) p.add(tmp) p.add( biggles.SymmetricErrorBarsY(Numeric.array(groups) + offset, Numeric.array(hadgroup) / center_of_groups, Numeric.array(hadgroup_err) / center_of_groups, color=color)) p.add(biggles.LineY(1., type="longdashed")) return tmp
def petrify(self): """ Make this object Since the last block of shapes might not be full, this function copies them to a new block exactly big enough to hold the shapes in that block. The gc has a chance to release the old block and reduce memory use. After this point, shapes must not be added to this ShapeList. """ self.petrified = True if len(self.spheres) > 0: count = self.spheres[-1][1] if count < ShapeList_inplace._blocking: block = self.spheres[-1][0] newblock = Numeric.array(block[0:count], 'f') self.spheres[-1][0] = newblock if len(self.cylinders) > 0: count = self.cylinders[-1][1] if count < ShapeList_inplace._blocking: block = self.cylinders[-1][0] newblock = Numeric.array(block[0:count], 'f') self.cylinders[-1][0] = newblock
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 __init__(self,grps): self.atoms={} count=1 import random for grp in grps.keys(): x=random.randint(-10,10) y=random.randint(-10,10) z=random.randint(-10,10) grp_name=grps[grp] pos=Numeric.array([200+x,200+y,200+z]) vel=Numeric.array([0,0,0]) acc=Numeric.array([0,0,0]) self.atoms[grp_name]={'pos':pos,'vel':vel,'acc':acc} count=count+1 #pass # # For each pair of atoms set the energy func # self.enes={} #for grp1 in grps.keys(): # self.enes[grp1]={} # for grp2 in grps.keys(): # self.enes[grp1][grp2]=None #print self.enes return
def plot(x, *args, **keywords): """Draws a 2D line plots. Comments: * Multiple curves can be specified eg. plot(xlist1, ylist1, xlist2, ylist2, etc.) * Sets up default axis values based on first set of x,y values. * Will also accept a single sequence of complex values (sets up Argand Diagram like reperesentation). * Use keyword setting draw=0 to just return the plot object without first drawing the plot. """ draw = 1 if 'draw' in keywords.keys(): draw = keywords['draw'] del keywords['draw'] if not args: x = Num.ravel(Num.array(x)) if type(x[0]) == types.ComplexType: tplot = plots.CurvePlot(x.real, x.imag, **keywords) tplot.axes(squared = 1) tplot.curve(symbols = 1, symbolshape='circle') tplot.draw() return tplot raise pxdislin.DislinException('Invalid argument(s) to mlab.plot') tplot = plots.CurvePlot(Num.array(x), Num.array(args[0]), **keywords) args = args[1:] clr = 1 for i in range(1,len(args),2): curve = pxdislin.Curve(args[i-1], args[i], color=plots.colorloop[clr]) tplot.add(curve) clr += 1 if draw: tplot.draw() return tplot
def plotEWhavsgimmorph(self,name): outfile=str(name)+'EWhavsgim.dat' output=open(outfile,'w') bulgefrac=[] EWha=[] EWhaerr=[] for i in range(len(self.EW)): if self.matchflaggimtype[i] > 0: if self.matchflagha[i] > 0: bulgefrac.append(self.gimtype[i]) EWha.append(self.EW[i]) EWhaerr.append(self.EWerr[i]) bulgefrac=N.array(bulgefrac,'f') bulgefracerr=N.zeros(len(bulgefrac),'f') EWha=N.array(EWha,'f') EWhaerr=N.array(EWhaerr,'f') pylab.xlabel('Morphology') pylab.ylabel('Equivalent Widths') title='Equivalent Widths vs Morphology for GIM2D '+str(name) pylab.title(title) pylab.errorbar(bulgefrac,EWha,EWhaerr,bulgefracerr, 'bo') pylab.show() self.gimbulgefrac = bulgefrac self.gimbulgefracerr = bulgefracerr self.gimEWha = EWha self.gimEWhaerr = EWhaerr
def getpositions(ximage, yimage, isoarea, im): dmin = 30. #minimum distance to object + sqrt(isoarea) iraf.imgets(image=im, param='naxis1') #get RA of image t = float(iraf.imgets.value) xmax = t xcenter = t / 2. iraf.imgets(image=im, param='naxis2') #get RA of image t = float(iraf.imgets.value) ymax = t ycenter = t / 2. xpos = [] ypos = [] da = N.sqrt(isoarea) d = N.zeros(len(ximage), 'f') #print len(d) i = 0 while i < npoints: xtemp = random.uniform(0, 1) * xmax ytemp = random.uniform(0, 1) * ymax dcenter = N.sqrt((xtemp - xcenter)**2 + (ytemp - ycenter)**2) if (dcenter < 500.): j = 0 d = N.sqrt((ximage - xtemp)**2 + (yimage - ytemp)**2) - da #for j in range(len(ximage)): #print j,len(ximage),len(yimage),len(da),len(d) #d[j] = N.sqrt((ximage[j]-xtemp)**2+(yimage[j]-ytemp)**2)-da[j] if (min(d) > dmin): xpos.append(xtemp) ypos.append(ytemp) i = i + 1 xpos = N.array(xpos, 'f') ypos = N.array(ypos, 'f') return xpos, ypos
def getDiffractionImage(data, lowerBound, upperBound, logScale, colorMaps, colorMapName, maskedPixelInfo, invert=None): mode = "RGB" if maskedPixelInfo.doLessThanMask: (lessThanMaskColorR,lessThanMaskColorG,lessThanMaskColorB) = \ maskedPixelInfo.getLessThanMaskColorRGB() lessThanMask = maskedPixelInfo.lessThanMask else: # We can just send the function a bunch of junk since it won't be used (lessThanMaskColorR, lessThanMaskColorG, lessThanMaskColorB) = (0, 0, 0) lessThanMask = -1 if maskedPixelInfo.doGreaterThanMask: (greaterThanMaskColorR,greaterThanMaskColorG,greaterThanMaskColorB) = \ maskedPixelInfo.getGreaterThanMaskColorRGB() greaterThanMask = maskedPixelInfo.greaterThanMask else: (greaterThanMaskColorR, greaterThanMaskColorG, greaterThanMaskColorB) = (0, 0, 0) greaterThanMask = -1 if maskedPixelInfo.doPolygonMask: (polygonMaskColorR,polygonMaskColorG,polygonMaskColorB) = \ maskedPixelInfo.getPolygonMaskColorRGB() polygonsX = maskedPixelInfo.polygonsX polygonsY = maskedPixelInfo.polygonsY polygonBeginningsIndex = maskedPixelInfo.polygonBeginningsIndex polygonNumberOfItems = maskedPixelInfo.polygonNumberOfItems else: (polygonMaskColorR, polygonMaskColorG, polygonMaskColorB) = (0, 0, 0) polygonsX = Numeric.array([]) polygonsY = Numeric.array([]) polygonBeginningsIndex = Numeric.array([]) polygonNumberOfItems = Numeric.array([]) palette = colorMaps.getPalette(colorMapName, invert=invert) string = DrawWrap.getDiffractionImageString( data, lowerBound, upperBound, logScale, palette, maskedPixelInfo.doLessThanMask, lessThanMask, lessThanMaskColorR, lessThanMaskColorG, lessThanMaskColorB, maskedPixelInfo.doGreaterThanMask, greaterThanMask, greaterThanMaskColorR, greaterThanMaskColorG, greaterThanMaskColorB, maskedPixelInfo.doPolygonMask, polygonsX, polygonsY, polygonBeginningsIndex, polygonNumberOfItems, polygonMaskColorR, polygonMaskColorG, polygonMaskColorB) img = Image.fromstring(mode, (data.shape[0], data.shape[1]), string) img = img.rotate(90) img = img.transpose(Image.FLIP_TOP_BOTTOM) return img
def demo_em(): # example from figure 14.10, page 519, Manning and Schutze tokens = [ Token(FEATURES=Numeric.array(f)) for f in [[0.5, 0.5], [1.5, 0.5], [1, 3]] ] means = [[4, 2], [4, 2.01]] clusterer = ExpectationMaximizationClusterer(means, bias=0.1) clusterer.cluster(tokens, True, trace=True) print 'clustered', tokens for c in range(2): print 'cluster %d' % c print 'prior', clusterer._priors[c] print 'mean ', clusterer._means[c] print 'covar', clusterer._covariance_matrices[c] # classify a new token token = Token(FEATURES=Numeric.array([2, 2])) print 'classify(%s)' % token, clusterer.classify(token) print token # show the classification probabilities token = Token(FEATURES=Numeric.array([2, 2])) print 'classification_probdist(%s)' % token clusterer.classification_probdist(token) for sample in token['CLUSTER_PROBDIST'].samples(): print '%s => %.0f%%' % (sample, token['CLUSTER_PROBDIST'].prob(sample) * 100)
def dounpack(x, cpx): uf = fmt * (len(x) / struct.calcsize(fmt)) s = struct.unpack(uf, x) if cpx: return Numeric.array(s[::2]) + Numeric.array(s[1::2]) * j else: return Numeric.array(s)
def subcounts(self, prefix=[]): if not prefix: return Numeric.array([m._count for m in self.t_table.itervalues()]) elif prefix[0] not in self.t_table: return Numeric.array([0]) else: return self.t_table[prefix[0]].subcounts(prefix[1:])
def main(): # Retrieve data from user and format try: f = open(sys.argv[1]) header = f.readline() if '#' != header.strip()[0]: f.close() f = open(sys.argv[1]) lines = f.readlines() V, P = [], [] for line in lines: V.append(float(line.split()[0])) P.append(float(line.split()[1])) V = Numeric.array(V) P = Numeric.array(P) except: print '\n usage: ' + sys.argv[ 0] + ' file_with_V_and_P_as_1st_two_columns.dat \n' sys.exit(0) # P_new = BM_2nd_order(V,P,verbose=True) P_new = BM_3rd_order(V, P, verbose=True) # Write the fit to file out = open('BM_fit.dat', 'w') for i in range(len(V)): out.write(str(V[i]) + ' ' + str(P_new[i]) + '\n') out.close()
def CFinterpolate_xy(profile,interval): "linearly interpolate profile, return interpolated array and number of points outside region" data = [] p = Numeric.array(profile) for i in range(0,len(p[0,:])): data.append([float(p[0,i]),float(p[1,i])]) remainder = lr = 0. d0 = data[0] ix = [] iy = [] ix.append(d0[0]) iy.append(d0[1]) for d in data[1:]: x = d[0] - d0[0] y = d[1] - d0[1] dist = math.sqrt(x*x + y*y) remainder = remainder + dist cm = x/dist sm = y/dist while (remainder - interval) >= 0.: d0[0] = d0[0] + (interval-lr)*cm d0[1] = d0[1] + (interval-lr)*sm lr = 0. ix.append(d0[0]) iy.append(d0[1]) remainder = remainder - interval lr = remainder d0 = d return Numeric.array([ix,iy],Numeric.Float32)
def contiguous(self, source, typeCode=None): """Get contiguous array from source source -- Numeric Python array (or compatible object) for use as the data source. If this is not a contiguous array of the given typeCode, a copy will be made, otherwise will just be returned unchanged. typeCode -- optional 1-character typeCode specifier for the Numeric.array function. All gl*Pointer calls should use contiguous arrays, as non- contiguous arrays will be re-copied on every rendering pass. Although this doesn't raise an error, it does tend to slow down rendering. """ typeCode = GL_TYPE_TO_ARRAY_MAPPING.get(typeCode) if isinstance(source, Numeric.ArrayType): if source.iscontiguous() and (typeCode is None or typeCode == source.typecode()): return source else: if typeCode is None: typeCode = source.typecode() # We have to do astype to avoid errors about unsafe conversions # XXX Confirm that this will *always* create a new contiguous array # XXX Allow a way to make this raise an error for performance reasons # XXX Guard against wacky conversion types like uint to float, where # we really don't want to have the C-level conversion occur. return Numeric.array(source.astype(typeCode), typeCode) elif typeCode: return Numeric.array(source, typeCode) else: return Numeric.array(source)
def plot(self,profile,time,level=None,pen='1/0/0/0'): """Plot Profile. profile: CF profile time: time slice level: level to be processed""" if profile.is3d and level == None and not profile.average: self.ylabel = 'elevation [m]' data = profile.getProfile2D(time) self.image(data,profile.colourmap.cptfile) ihdata = Numeric.array(profile.cffile.getprofile('thk').getProfile(time)) try: rhdata = Numeric.array(profile.cffile.getprofile('topg').getProfile(time)) self.line('-W%s'%pen,profile.cffile.xvalues,rhdata) except: rhdata = Numeric.zeros(len(ihdata)) ihdata = rhdata+ihdata self.line('-W%s'%pen,profile.cffile.xvalues,ihdata) else: if level == None: level = 0 self.ylabel = '%s [%s]'%(profile.long_name,profile.units) data = profile.getProfile(time,level=level) self.line('-W%s'%pen,profile.cffile.xvalues,data) if profile.name == 'is': rhdata = Numeric.array(profile.cffile.getprofile('topg').getProfile(time)) self.line('-W%s'%pen,profile.cffile.xvalues,rhdata)
def use_cross_section(csfunc, filename): hads = [] hads_err = [] for r in testsample: c, e = csfunc(r) hads.append(c) hads_err.append(e) hads_center = jt.wmean(zip(hads, hads_err))[0] p = biggles.FramedPlot() p.add( biggles.Points(range(len(testsample)), Numeric.array(hads) / hads_center, type="filled circle")) p.add( biggles.SymmetricErrorBarsY(range(len(testsample)), Numeric.array(hads) / hads_center, Numeric.array(hads_err) / hads_center)) p.x1.draw_ticklabels = 0 p.x1.label = "Runs by index" p.y1.label = "Normalized hadronic cross-section" p.add(biggles.LineY(1.)) p.add(biggles.LineX(41.5, type="dashed")) l, r = 0.8, 1.2 p.yrange = l, r + 0.001 p.add(biggles.DataLabel(41.5 - 10, l + 0.15 * (r - l), "db16")) p.add(biggles.DataLabel(41.5 + 10, l + 0.15 * (r - l), "db17")) p.aspect_ratio = 8.5 / 11. p.show() p.write_eps(filename)
def test_internal_coherance(axes_i): sum = Numeric.add.reduce r = random.uniform a1, a2, a3 = r(-180,180),r(-180,180),r(-180,180) angles_i = Numeric.array([a1, a2, a3]) angles_r = angles_i[::-1] axes_r = axes_i[2], axes_i[1], axes_i[0] rotdnz_new = ThreeAxisRotation(angles_i/r2d, rotationAxes=axes_i, inversAxesOrder=1) rotdnz_inv = ThreeAxisRotation(angles_r/r2d, rotationAxes=axes_r, inversAxesOrder=0) diffmat1 = sum(sum(Numeric.absolute(rotdnz_new.tensor - rotdnz_inv.tensor))) sol1_new, sol2_new = rotdnz_new.getAngles() sol1_inv, sol2_inv = rotdnz_inv.getAngles() diffinit = min(sum(Numeric.absolute(sol1_new*r2d-angles_i)), sum(Numeric.absolute(sol2_new*r2d-angles_i))) diffinv = min(sum(Numeric.absolute(sol1_inv[::-1]*r2d-angles_i)), sum(Numeric.absolute(sol2_inv[::-1]*r2d-angles_i))) #print rotdnz_new.asQuaternion() if diffmat1 > 1e-12 or diffinit > 2e-11 or diffinv > 2e-11: print "I"+3*"%10.2f" % tuple(Numeric.array(angles_i)) print "N"+3*"%10.2f" % tuple(Numeric.array(sol1_new)*r2d) print "N"+3*"%10.2f" % tuple(Numeric.array(sol2_new)*r2d) print 'Matrix difference \t%.1e' % diffmat1 print 'Init Angle difference \t%.1e' % diffinit print 'Inv Angle difference \t%.1e' % diffinv
def lregress(x,y): """Fits a straight line to data points (x,y). The line to be fit is y = A + Bx Returns: A, B, dy, dA, dB """ x = Numeric.array(x,typecode=Numeric.Float) y = Numeric.array(y,typecode=Numeric.Float) N = len(x) DELTA = N * Numeric.sum(x**2) - Numeric.sum(x)**2 # print Numeric.shape(Numeric.sum(x**2)),Numeric.shape(Numeric.sum(y)) A = ( Numeric.sum(x**2)*Numeric.sum(y)-Numeric.sum(x)*Numeric.sum(x*y) ) / DELTA B = ( N*Numeric.sum(x*y) - Numeric.sum(x)*Numeric.sum(y) )/ DELTA sigma_y = Numeric.sqrt( (1./(N-2)) * Numeric.sum((y - A - B*x)**2) ) sigma_A = sigma_y * Numeric.sqrt( Numeric.sum(x**2)/DELTA ) sigma_B = sigma_y * Numeric.sqrt( N/DELTA ) return A,B,sigma_y,sigma_A,sigma_B
def mouseMoveEvent(self, event): x = event.x() y = event.y() if self.mouse_state == 0: scale, shift = self.transformation p = (Numeric.array([self.startx, self.starty])-shift)/scale bb1, bb2 = self.bbox if self.selectfn is not None and p[1] < bb1[1]: self.painter.setPen(QPen(Qt.NoPen)) self.painter.setBrush(QBrush(Qt.blue, Qt.Dense5Pattern)) self.rectangle = (self.startx, 0, x-self.startx, self.height()) self.painter.drawRect(*self.rectangle) self.mouse_state = 2 elif self.zoom: self.painter.setPen(QPen(Qt.white, 1, Qt.DotLine)) self.painter.setBrush(QBrush(Qt.NoBrush)) self.rectangle = (self.startx, self.starty, x-self.startx, y-self.starty) self.painter.drawRect(*self.rectangle) self.mouse_state = 1 elif self.mouse_state == 1 or self.mouse_state == 2: self.painter.drawRect(*self.rectangle) if self.mouse_state == 1: self.rectangle = (self.startx, self.starty, x-self.startx, y-self.starty) elif self.mouse_state == 2: self.rectangle = (self.startx, 0, x-self.startx, self.height()) self.painter.drawRect(*self.rectangle) elif self.mouse_state == 3: scale, shift = self.transformation point = Numeric.array([x, y]) point = (point-shift)/scale self.value_label.setText(" x = %f\n y = %f" % tuple(point))
def main(): # Retrieve data from user and format try: f = open(sys.argv[1]) header = f.readline() if '#' != header.strip()[0]: f.close() f = open(sys.argv[1]) lines = f.readlines() V, P = [], [] for line in lines: V.append(float(line.split()[0])) P.append(float(line.split()[1])) V = Numeric.array(V) P = Numeric.array(P) except: print '\n usage: '+sys.argv[0]+' file_with_V_and_P_as_1st_two_columns.dat \n' sys.exit(0) # P_new = BM_2nd_order(V,P,verbose=True) P_new = BM_3rd_order(V,P,verbose=True) # Write the fit to file out = open('BM_fit.dat','w') for i in range(len(V)): out.write(str(V[i])+' '+str(P_new[i])+'\n') out.close()
def testDiagonal (self): "Test the diagonal function." b=Numeric.array([[1,2,3,4],[5,6,7,8]]*2) assert_eq(Numeric.diagonal(b), [1,6,3,8]) assert_eq(Numeric.diagonal(b, -1), [5,2,7]) c = Numeric.array([b,b]) assert_eq(Numeric.diagonal(c,1), [[2,7,4], [2,7,4]])
def __init__(self, elements, nocheck = None): self.array = Numeric.array(elements) if nocheck is None: if not Numeric.logical_and.reduce( Numeric.equal(Numeric.array(self.array.shape), 3)): raise ValueError, 'Tensor must have length 3 along any axis' self.rank = len(self.array.shape)
def plothavs24(self,name): outfile=str(name)+'match24ha.dat' output=open(outfile,'w') flux1=[] errflux1=[] flux2=[] errflux2=[] for i in range(len(self.EW)): if self.matchflagha[i] > 0: if self.matchflag24[i] > 0: flux1.append(self.SFR[i]) flux2.append(self.flux24[i]) errflux1.append(self.SFRerr[i]) errflux2.append(self.flux24err[i]) #print "found match with Halpha source!\n" flux1=N.array(flux1,'f') flux2=N.array(flux2,'f') pylab.xlabel('H Alpha Flux - SFR') pylab.ylabel('24 micron Flux') title='24 Micron Flux Versus Ha Flux for '+str(name) pylab.title(title) pylab.errorbar(flux1,flux2,errflux2,errflux1, 'bo') pylab.show() self.ha24flux1=flux1 self.ha24flux2=flux2 self.ha24errflux1=errflux1 self.ha24errflux2=errflux2
def plotEWhavsvismorph(self,name): outfile=str(name)+'EWhavsvis.dat' bulgefrac=[] EWha=[] EWhaerr=[] for i in range(len(self.EW)): if self.matchflagvistype[i] > 0: if self.matchflagha[i] > 0: bulgefrac.append(self.vistype[i]) EWha.append(self.EW[i]) EWhaerr.append(self.EWerr[i]) bulgefrac=N.array(bulgefrac,'f') bulgefracerr=N.zeros(len(bulgefrac),'f') EWha=N.array(EWha,'f') EWhaerr=N.array(EWhaerr,'f') pylab.xlabel('Morphology') pylab.ylabel('Equivalent Widths') title='Equivalent Widths vs Morphology for Visual '+str(name) pylab.title(title) pylab.errorbar(bulgefrac,EWha,EWhaerr,bulgefracerr, 'gs') pylab.axis([-10.,15.,-10.,50.]) pylab.show() self.visbulgefrac = bulgefrac self.visbulgefracerr = bulgefracerr self.visEWha = EWha self.visEWhaerr = EWhaerr
def evaluatorTerms(self, universe, subset1, subset2, global_data): if subset1 is not None: for s1, s2 in [(subset1, subset2), (subset2, subset1)]: set = {} for a in s1.atomList(): set[a.index] = None for a in s2.atomList(): try: del set[a.index] except KeyError: pass set = {} for a in subset1.atomList(): set[a.index] = None for a in subset2.atomList(): set[a.index] = None atom_subset = set.keys() atom_subset.sort() atom_subset = Numeric.array(atom_subset) else: atom_subset = Numeric.array([], Numeric.Int) nothing = Numeric.zeros((0,2), Numeric.Int) nbl = NonbondedList(nothing, nothing, atom_subset, universe._spec, self.cutoff) update = NonbondedListTerm(nbl) cutoff = self.cutoff if cutoff is None: cutoff = 0. ev = CalphaTerm(universe._spec, nbl, cutoff, self.scale_factor, self.version) return [update, ev]
def __init__(self, elements, nocheck=None): self.array = Numeric.array(elements) if nocheck is None: if not Numeric.logical_and.reduce( Numeric.equal(Numeric.array(self.array.shape), 3)): raise ValueError, 'Tensor must have length 3 along any axis' self.rank = len(self.array.shape)
def removePolygons(self): """ Remove all the polygons from the object. """ self.polygonsX = Numeric.array([], Numeric.Float) self.polygonsY = Numeric.array([], Numeric.Float) self.polygonBeginningsIndex = Numeric.array([], Numeric.Int) self.polygonNumberOfItems = Numeric.array([], Numeric.Int)
def pairsWithinCutoff(self, cutoff): """Returns a list containing all pairs of objects in the collection whose center-of-mass distance is less than |cutoff|.""" pairs = [] positions = {} for index, objects in self.partition.items(): pos = map(lambda o: o.position(), objects) positions[index] = pos for o1, o2 in Utility.pairs(map(None, objects, pos)): if (o2[1]-o1[1]).length() <= cutoff: pairs.append((o1[0], o2[0])) partition_cutoff = int(Numeric.floor((cutoff/self.partition_size)**2)) ones = Numeric.array([1,1,1]) zeros = Numeric.array([0,0,0]) keys = self.partition.keys() for i in range(len(keys)): p1 = keys[i] for j in range(i+1, len(keys)): p2 = keys[j] d = Numeric.maximum(abs(Numeric.array(p2)-Numeric.array(p1)) - ones, zeros) if Numeric.add.reduce(d*d) <= partition_cutoff: for o1, pos1 in map(None, self.partition[p1], positions[p1]): for o2, pos2 in map(None, self.partition[p2], positions[p2]): if (pos2-pos1).length() <= cutoff: pairs.append((o1, o2)) return pairs
def _mouseRelease(self, event): if self.mouse_state == 1: self.canvas.delete(self.rubberband) self.rubberband = None p1 = Numeric.array([self.startx, self.starty]) p2 = Numeric.array([self.canvas.canvasx(event.x), self.canvas.canvasy(event.y)]) if Numeric.minimum.reduce(Numeric.fabs(p1-p2)) > 5: scale, shift = self.transformation p1 = (p1-shift)/scale p2 = (p2-shift)/scale graphics, xaxis, yaxis = self.last_draw if xaxis is not None: xaxis = (p1[0], p2[0]) if yaxis is not None: yaxis = (p2[1], p1[1]) self.clear() self.draw(graphics, xaxis, yaxis) elif self.mouse_state == 2: scale, shift = self.transformation x1 = (self.startx-shift[0])/scale[0] x2 = (self.canvas.canvasx(event.x)-shift[0])/scale[0] if x1 < x2: self.selected_range = (x1, x2) else: self.selected_range = (x2, x1) if self.selectfn is not None: self.selectfn(self.selected_range) else: self.canvas.delete(self.rectangle) self.rectangle = None self.selected_range = None if self.selectfn is not None: self.selectfn(self.selected_range) self.mouse_state = 0
def get_h0_extrap(ref,d,hexp=1): nomatch=get_numeric_nomatch_keys() nomatch.append('ngrid') d1 = get_matching(ref,d,nomatch) h_min = [] max_eval=[] for d2 in d1: try: h_min.append(min(d2.grid[1:]-d2.grid[0:-1])**hexp) except: h_min.append(1./(d2.data['ngrid']-1)**hexp) max_eval.append(max(d2.evals.imag)) uh = list(sets.Set(h_min)) min_uh = min(uh) uuh = [] for uh1 in uh: if len(Numeric.nonzero(Numeric.absolute(Numeric.array(uuh)-uh1)<1e-8))==0: uuh.append(uh1) min_eval=[] #print Numeric.sort(uuh) for hm in uuh: inds = Numeric.nonzero(Numeric.absolute(Numeric.array(h_min)-hm)<1e-8) min_eval.append(min(Numeric.take(max_eval,inds))) inds = Numeric.argsort(uuh) h_min = list(Numeric.take(uuh,inds)) min_eval = list(Numeric.take(min_eval,inds)) if len(min_eval)>1: m=(min_eval[1]-min_eval[0])/(h_min[1]-h_min[0]) else: m=0 return min_eval[0]-m*h_min[0]
def dounpack(x,cpx): uf = fmt * ( len(x) / struct.calcsize(fmt) ) s = struct.unpack(uf,x) if cpx: return Numeric.array(s[::2]) + Numeric.array( s[1::2] )*j else: return Numeric.array(s )
def _setsize(self): self.width = string.atoi(self.canvas.cget('width')) self.height = string.atoi(self.canvas.cget('height')) self.plotbox_size = 0.97*Numeric.array([self.width, -self.height]) xo = 0.5*(self.width-self.plotbox_size[0]) yo = self.height-0.5*(self.height+self.plotbox_size[1]) self.plotbox_origin = Numeric.array([xo, yo])
def polynomialChksum(data,polynomial=[1,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1, 0,0,0,1,1,1,0,1,1,0,1,1,0,1,1,1]): """Compute a polynomial checksum with the given generating polynomial. Arguments: data:String -- data to compute the checksum for polynomial:Sequence -- Binary coefficients of the generating polynomial. Highest coefficient first,eg x**3+x**2=[1,1,0,0] Default is the polynomial for CRC-32. Return value: checksum:String -- String of 4 octets of the checksum, highest bit first. """ bitmask = Numeric.array([128,64,32,16,8,4,2,1]) bytes=Numeric.fromstring(data,Numeric.UnsignedInt8) bits=Numeric.bitwise_and.outer(bytes,bitmask).flat Numeric.putmask(bits,bits,1) u=list(bits)+([0]*(len(polynomial)-1)) u.reverse() v=polynomial[:] v.reverse() q,r = dividePolynomial(u,v) r = Numeric.array(r) r = r[::-1] # Reverse it if len(r)%8: r=Numeric.concatenate(([0]* (8 - len(r)%8), r)) checksumstring="" for i in range(len(r)/8): checksumstring += chr(Numeric.dot(r[i*8:(i+1)*8],bitmask)) return checksumstring
def test_fwt1Dc6(self): """test that fwt1D works on a 'random' vector, D=6""" # Matlab random vector X = Numeric.array( [ 0.81797434083925, 0.66022755644160, 0.34197061827022, 0.28972589585624, 0.34119356941488, 0.53407901762660, 0.72711321692968, 0.30929015979096, ] ) # Result from fwt(X, 6) in Matlab Y_ref = Numeric.array( [ 1.42184125586417, -0.27979815817808, 0.21836186329686, 0.17939935114879, 0.00345049516774, 0.22893484261518, 0.25762577687352, -0.18246978758220, ] ) Y = fwt(X, 6) assert Numeric.allclose(Y - Y_ref, 0)
def readInput(file): f = open(file, "r") instMagList = [] stdMagList = [] magErrList = [] colList = [] airmassList = [] for line in f.readlines(): instMag, stdMag, col, airmass, instMagErr, stdMagErr = string.split(line) magErr = (float(instMagErr)**2. + float(stdMagErr)**2.)**0.5 magErrList.append(magErr) instMagList.append(float(instMag)) stdMagList.append(float(stdMag)) colList.append(float(col)) airmassList.append(float(airmass)) f.close() instMag = Numeric.array(instMagList) stdMag = Numeric.array(stdMagList) data = stdMag - instMag airmass = Numeric.array(airmassList) color = Numeric.array(colList) magErr = Numeric.array(magErrList) return data, airmass, color, magErr
def __init__(self, grps): self.atoms = {} count = 1 import random for grp in grps.keys(): x = random.randint(-10, 10) y = random.randint(-10, 10) z = random.randint(-10, 10) grp_name = grps[grp] pos = Numeric.array([200 + x, 200 + y, 200 + z]) vel = Numeric.array([0, 0, 0]) acc = Numeric.array([0, 0, 0]) self.atoms[grp_name] = {'pos': pos, 'vel': vel, 'acc': acc} count = count + 1 #pass # # For each pair of atoms set the energy func # self.enes = {} #for grp1 in grps.keys(): # self.enes[grp1]={} # for grp2 in grps.keys(): # self.enes[grp1][grp2]=None #print self.enes return
def test_internal_coherance(axes_i): sum = Numeric.add.reduce r = random.uniform a1, a2, a3 = r(-180, 180), r(-180, 180), r(-180, 180) angles_i = Numeric.array([a1, a2, a3]) angles_r = angles_i[::-1] axes_r = axes_i[2], axes_i[1], axes_i[0] rotdnz_new = ThreeAxisRotation(angles_i / r2d, rotationAxes=axes_i, inversAxesOrder=1) rotdnz_inv = ThreeAxisRotation(angles_r / r2d, rotationAxes=axes_r, inversAxesOrder=0) diffmat1 = sum(sum(Numeric.absolute(rotdnz_new.tensor - rotdnz_inv.tensor))) sol1_new, sol2_new = rotdnz_new.getAngles() sol1_inv, sol2_inv = rotdnz_inv.getAngles() diffinit = min(sum(Numeric.absolute(sol1_new * r2d - angles_i)), sum(Numeric.absolute(sol2_new * r2d - angles_i))) diffinv = min(sum(Numeric.absolute(sol1_inv[::-1] * r2d - angles_i)), sum(Numeric.absolute(sol2_inv[::-1] * r2d - angles_i))) #print rotdnz_new.asQuaternion() if diffmat1 > 1e-12 or diffinit > 2e-11 or diffinv > 2e-11: print "I" + 3 * "%10.2f" % tuple(Numeric.array(angles_i)) print "N" + 3 * "%10.2f" % tuple(Numeric.array(sol1_new) * r2d) print "N" + 3 * "%10.2f" % tuple(Numeric.array(sol2_new) * r2d) print 'Matrix difference \t%.1e' % diffmat1 print 'Init Angle difference \t%.1e' % diffinit print 'Inv Angle difference \t%.1e' % diffinv
def subcounts(self,prefix=[]): if not prefix: return Numeric.array([m._count for m in self.t_table.itervalues()]) elif prefix[0] not in self.t_table: return Numeric.array([0]) else: return self.t_table[prefix[0]].subcounts(prefix[1:])
def lregress(x, y): """Fits a straight line to data points (x,y). The line to be fit is y = A + Bx Returns: A, B, dy, dA, dB """ x = Numeric.array(x, typecode=Numeric.Float) y = Numeric.array(y, typecode=Numeric.Float) N = len(x) DELTA = N * Numeric.sum(x**2) - Numeric.sum(x)**2 # print Numeric.shape(Numeric.sum(x**2)),Numeric.shape(Numeric.sum(y)) A = (Numeric.sum(x**2) * Numeric.sum(y) - Numeric.sum(x) * Numeric.sum(x * y)) / DELTA B = (N * Numeric.sum(x * y) - Numeric.sum(x) * Numeric.sum(y)) / DELTA sigma_y = Numeric.sqrt((1. / (N - 2)) * Numeric.sum((y - A - B * x)**2)) sigma_A = sigma_y * Numeric.sqrt(Numeric.sum(x**2) / DELTA) sigma_B = sigma_y * Numeric.sqrt(N / DELTA) return A, B, sigma_y, sigma_A, sigma_B
def near(self, lhsrowwords, rhsrowwords, mask=_BEFORE | _AFTER): # only check matching rows rows = soomfunc.intersect(lhsrowwords[0], rhsrowwords[0]) lhswords = lhsrowwords[1] rhswords = rhsrowwords[1] words = {} _BEFORE = self._BEFORE _AFTER = self._AFTER nearness = self.nearness for row in rows: hits = sets.Set() # this is O(n*n) and could be improved # find all hits and then remove duplicates for left in lhswords[row]: for right in rhswords[row]: if (mask & _BEFORE) and right - nearness <= left <= right: hits.add(left) hits.add(right) if (mask & _AFTER) and right <= left <= right + nearness: hits.add(left) hits.add(right) if hits: hits = list(hits) hits.sort() words[row] = Numeric.array(hits, Numeric.Int) # remove rows that have no hits left rows = Numeric.array(filter(lambda r: r in words, rows), Numeric.Int) return rows, words
def LinearLeastSquaresFit(xdata,ydata): """ Special case of polynomialLeastSquaresFit, which returns the R^2 value intercept,slope,R_squared = LinearLeastSquaresFit(xdata,ydata) """ xdata=Numeric.array(xdata) ydata=Numeric.array(ydata) # form that LeastSquaresFit wants the data in data=map(lambda x,y:(x,y),xdata,ydata) # I am not sure if the particular guess for parameters will result in a error in some cases lsq=polynomialLeastSquaresFit(parameters=(0,0), data=data) intercept=lsq[0][0] slope=lsq[0][1] avg_y=mean(ydata) predicted_data = intercept + slope*xdata numerator=Numeric.sum((predicted_data-ydata)**2) denominator=Numeric.sum((ydata-avg_y)**2) R_squared = 1 - numerator/denominator return intercept,slope, R_squared
def pushPacket(self, data, ts, EOS, stream_id): """ Pushes data to the file. Input: <data> The actual data to write to the file <ts> The timestamp <EOS> Flag indicating if this is the End Of the Stream <stream_id> The name of the file """ self.port_lock.acquire() if EOS: self.gotEOS = True self.eos_cond.notifyAll() else: self.gotEOS = False try: # If complex data, need to convert data back from array of scalar values # to some form of complex values if self.header != None and self.header['format'][0] == 'C': # float and double are handled by numpy # each array element is a single complex value if self.header['format'][1] == 'F' or self.header['format'][ 1] == 'D': real = data[0:len(data):2] imag = data[1:len(data):2] tmp = multiply(imag, 1.0j).tolist() data = add(real, tmp).tolist() # other data types are not handled by numpy # each element is two value array representing real and imaginary values elif self.header['format'][1] == 'I' or self.header['format'][ 1] == 'L': if arch == "x86_64": # Need to rehape the data into complex value pairs # numpy reshape is used to avoid 64-bit error data = reshape(data, (-1, 2)) # Need to convert numpy array to Numeric array which bluefile.write() is expecting data = Numeric.array(data) else: data = Numeric.reshape(data, (-1, 2)) elif self.header['format'][1] == 'B': # convert back from string to array of 8-bit integers data = Numeric.fromstring(data, Numeric.Int8) if arch == "x86_64": # Need to rehape the data into complex value pairs # numpy reshape is used to avoid 64-bit error data = reshape(data, (-1, 2)) # Need to convert numpy array to Numeric array which bluefile.write() is expecting data = Numeric.array(data) else: data = Numeric.reshape(data, (-1, 2)) elif self.header != None and self.header['format'] == "SB": data = Numeric.fromstring(data, Numeric.Int8) bluefile.write(self.outFile, hdr=None, data=data, append=1) finally: self.port_lock.release()