def factor_check(x, y, z): x_factors = [] y_factors = [] z_factors = [] check_x = arange(3, x + 1, typecode=Float) check_y = arange(3, y + 1, typecode=Float) check_z = arange(3, z + 1, typecode=Float) for i in range(len(check_x)): if x % check_x[i] == 0: x_factors.append(check_x[i]) for j in range(len(check_y)): if y % check_y[j] == 0: y_factors.append(check_y[j]) for k in range(len(check_z)): if z % check_z[k] == 0: z_factors.append(check_z[k]) for factor in x_factors: if factor in y_factors: x_share_y = True break else: x_share_y = False for factor in x_factors: if factor in z_factors: x_share_z = True break else: x_share_z = False for factor in y_factors: if factor in z_factors: y_share_z = True break else: y_share_z = False if y_share_z or x_share_z or x_share_y: sharing = True else: sharing = False return sharing
def _compute_vertices(self): theta = 2*pi/self.numVertices*arange(self.numVertices) + \ self.orientation self.xs = self.xy[0] + self.radius * cos(theta) self.ys = self.xy[1] + self.radius * sin(theta)
def eval_formula(error, formula): global current_formula, t, last_time, start needed = int(min(rate * (time.time() - start + 1.5*interval/1000.0) - t, 3 * interval / 1000.0 * rate)) granularity = 1024 if needed % granularity != 0: needed += granularity - needed % granularity print time.time() - last_time, needed try: new_formula = shuntparse.parse(shuntparse.tokenize(formula.text)) new_formula.eval({'t': array(0)}) current_formula = new_formula except: _, exc, _ = sys.exc_info() error.text=repr(exc) else: error.text='' try: rv = current_formula.eval({'t': arange(t, t+needed)}).astype(UInt8).tostring() t += needed return rv except: if current_formula: error.text=str(sys.exc_info()[1]) return ''
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 = 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)) self.project.sig_emit("notify::datasets")
def eval_formula(error, formula): global current_formula, t, last_time, start needed = int( min(rate * (time.time() - start + 1.5 * interval / 1000.0) - t, 3 * interval / 1000.0 * rate)) granularity = 1024 if needed % granularity != 0: needed += granularity - needed % granularity print time.time() - last_time, needed try: new_formula = shuntparse.parse(shuntparse.tokenize(formula.text)) new_formula.eval({'t': array(0)}) current_formula = new_formula except: _, exc, _ = sys.exc_info() error.text = repr(exc) else: error.text = '' try: rv = current_formula.eval({ 't': arange(t, t + needed) }).astype(UInt8).tostring() t += needed return rv except: if current_formula: error.text = str(sys.exc_info()[1]) return ''
def __init__(self): self.widgets = gtk.glade.XML('mpl_with_glade.glade') self.widgets.signal_autoconnect(GladeHandlers.__dict__) self.figure = Figure(figsize=(8,6), dpi=72) self.axis = Subplot(self.figure, 111) self.figure.add_axis(self.axis) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) self.axis.plot(t,s) self.axis.set_xlabel('time (s)') self.axis.set_ylabel('voltage') self.canvas = FigureCanvasGTK(self.figure) # a gtk.DrawingArea self.canvas.show() self['vboxMain'].pack_start(self.canvas, gtk.TRUE, gtk.TRUE) self['vboxMain'].show() # below is optional if you want the navigation toolbar self.navToolbar = NavigationToolbar(self.canvas, self['windowMain']) self.navToolbar.lastDir = '/var/tmp/' self['vboxMain'].pack_start(self.navToolbar) self.navToolbar.show() sep = gtk.HSeparator() sep.show() self['vboxMain'].pack_start(sep, gtk.TRUE, gtk.TRUE) self['vboxMain'].reorder_child(self['buttonClickMe'],-1)
def _compute_vertices(self): theta = 2*pi/self.numVertices*arange(self.numVertices) + \ self.orientation self.xs = self.xy[0] + self.radius*cos(theta) self.ys = self.xy[1] + self.radius*sin(theta)
def getValue(data, index, ctype='l', endian='>', number=1): """ getValue(data,index,ctype,endian,number) """ if (ctype == 'l') | (ctype == 'long') | (ctype == 'int32'): size = l_long ctype = 'l' elif (ctype == 'L') | (ctype == 'ulong') | (ctype == 'uint32'): size = l_ulong ctype = 'L' elif (ctype == 'h') | (ctype == 'short') | (ctype == 'int16'): size = l_short ctype = 'h' elif (ctype == 'H') | (ctype == 'ushort') | (ctype == 'uint16'): size = l_ushort ctype = 'H' elif (ctype == 'c') | (ctype == 'char'): size = l_char ctype = 'c' elif (ctype == 'B') | (ctype == 'uchar'): size = l_uchar ctype = 'B' elif (ctype == 'f') | (ctype == 'float'): size = l_float ctype = 'f' elif (ctype == 'ibm'): size = l_float else: printverbose('Bad Ctype : ' + ctype, -1) cformat = endian + ctype * number printverbose('getValue : cformat : ' + cformat, 40) index_end = index + size * number if (ctype == 'ibm'): # ASSUME IBM FLOAT DATA Value = range(number) for i in arange(number): index_ibm = i * 4 + index Value[i] = ibm2ieee2(data[index_ibm:index_ibm + 4]) # this resturn an array as opposed to a tuple else: # ALL OTHER TYPES OF DATA Value = struct.unpack(cformat, data[index:index_end]) if (ctype == 'B'): printverbose('getValue : Ineficient use of 1byte Integer...', -1) vtxt = 'getValue : ' + 'start=' + str(index) + ' size=' + str( size) + ' number=' + str(number) + ' Value=' + str( Value) + ' cformat=' + str(cformat) printverbose(vtxt, 20) if number == 1: return Value[0], index_end else: return Value, index_end
def gen_wav(seconds, frequency, amplitudePercentOfMax, samplesPerSecond): # calculate frequency as radians/sample radiansPerSample = (2.0 * pi * frequency) / samplesPerSecond numberOfSamples = int(seconds*samplesPerSecond) maxAmplitude = (amplitudePercentOfMax / 100.0) * 32767 samples = sin(arange(numberOfSamples) * radiansPerSample) * maxAmplitude # round and convert to array of 16-bit shorts return floor(samples + 0.5).astype('s')
def getValue(data,index,ctype='l',endian='>',number=1): """ getValue(data,index,ctype,endian,number) """ if (ctype=='l')|(ctype=='long')|(ctype=='int32'): size=l_long ctype='l' elif (ctype=='L')|(ctype=='ulong')|(ctype=='uint32'): size=l_ulong ctype='L' elif (ctype=='h')|(ctype=='short')|(ctype=='int16'): size=l_short ctype='h' elif (ctype=='H')|(ctype=='ushort')|(ctype=='uint16'): size=l_ushort ctype='H' elif (ctype=='c')|(ctype=='char'): size=l_char ctype='c' elif (ctype=='B')|(ctype=='uchar'): size=l_uchar ctype='B' elif (ctype=='f')|(ctype=='float'): size=l_float ctype='f' elif (ctype=='ibm'): size=l_float else: printverbose('Bad Ctype : ' +ctype,-1) cformat=endian + ctype*number printverbose('getValue : cformat : ' + cformat,40) index_end=index+size*number if (ctype=='ibm'): # ASSUME IBM FLOAT DATA Value = range(number) for i in arange(number): index_ibm=i*4+index Value[i] = ibm2ieee2(data[index_ibm:index_ibm+4]) # this resturn an array as opposed to a tuple else: # ALL OTHER TYPES OF DATA Value=struct.unpack(cformat, data[index:index_end]) if (ctype=='B'): printverbose('getValue : Ineficient use of 1byte Integer...',-1) vtxt = 'getValue : '+'start='+str(index)+' size='+str(size)+ ' number='+str(number)+' Value='+str(Value)+' cformat='+str(cformat) printverbose(vtxt,20) if number==1: return Value[0], index_end else:
def factor_check(x,y,z): x_factors = [] y_factors = [] z_factors = [] check_x = arange(3, x+1,typecode=Float) check_y = arange(3, y+1,typecode=Float) check_z = arange(3, z+1,typecode=Float) for i in range(len(check_x)): if x % check_x[i] == 0: x_factors.append(check_x[i]) for j in range(len(check_y)): if y % check_y[j] == 0: y_factors.append(check_y[j]) for k in range(len(check_z)): if z % check_z[k] == 0: z_factors.append(check_z[k]) for factor in x_factors: if factor in y_factors: x_share_y = True break else: x_share_y = False for factor in x_factors: if factor in z_factors: x_share_z = True break else: x_share_z = False for factor in y_factors: if factor in z_factors: y_share_z = True break else: y_share_z = False if y_share_z or x_share_z or x_share_y: sharing = True else: sharing = False return sharing
def pythagorean_triples(top, bottom=2): triples = [] x = arange(bottom, top + 1, typecode=Float) y = arange(bottom, top + 1, typecode=Float) for i in range(len(x)): for j in range(len(y)): z = (x[i]**2 + y[j]**2)**.5 sharing = factor_check(x[i], y[j], z) if z == math.floor(z) and sharing == False: triple = (x[i], y[j], z) if (y[j], x[i], z) not in triples: triples.append(triple) return triples
def pythagorean_triples(top, bottom=2): triples = [] x = arange(bottom, top+1, typecode=Float) y = arange(bottom, top+1, typecode=Float) for i in range(len(x)): for j in range(len(y)): z = ( x[i]**2 + y[j]**2 )**.5 sharing = factor_check(x[i],y[j],z) if z == math.floor(z) and sharing == False: triple = (x[i],y[j],z) if (y[j],x[i],z) not in triples: triples.append(triple) return triples
def detrend_linear(x): """Remove the best fit line from x""" # I'm going to regress x on xx=range(len(x)) and return # x - (b*xx+a) # xx = arange(len(x), typecode=x.typecode()) xx = arange(len(x), type(x)) X = transpose(array([xx] + [x])) C = cov(X) b = C[0, 1] / C[0, 0] a = mean(x) - b * mean(xx) return x - (b * xx + a)
class TestVectorDB(unittest.TestCase): dim = 2 N = 1000 probes = [ array((x, y)) for x in arange(0, 1.25, 0.25) for y in arange(0, 1.25, 0.25) ] def setUp(self): rand.seed(0, 0) self.data = [(rand.uniform(0, 1, (self.dim, )), None) for i in range(self.N)] for x, y in self.data: self.db.add(x, y) def testKNearest(self): k = 10 def probe_cmp(a, b, probe): ax, ay = a bx, by = b diff = norm(ax - probe) - norm(bx - probe) return int(diff / abs(diff)) for p in self.probes: k_nearest, dists = self.db.k_nearest(p, k) self.data.sort(lambda a, b: probe_cmp(a, b, p)) assert k_nearest == self.data[:k] def testFindInRadius(self): r = 0.1 for p in self.probes: found, dists = self.db.find_in_radius(p, r) dists = [norm(p - x) for x, y in self.data] truth = [(x, y) for d, (x, y) in zip(dists, self.data) if d <= r] for pair in truth: assert pair in found for pair in found: assert pair in truth
def play_bytebeat(astr, out): t = 0 n_samples = 256 formula = ps(astr) if formula is None: return if out is not sys.stdout: print formula print formula.rpn() while True: x = formula.eval({'t': arange(t, t + n_samples)}) out.write(x.astype(UInt8).tostring()) t += n_samples
def play_bytebeat(astr, out): t = 0 n_samples = 256 formula = ps(astr) if formula is None: return if out is not sys.stdout: print formula print formula.rpn() while True: x = formula.eval({'t': arange(t, t+n_samples)}) out.write(x.astype(UInt8).tostring()) t += n_samples
def main(): from hamiltonian import hamiltonian from Numeric import arange import os import sys # parse command line options, set debug flag, set outFile name debugFlag,outFileName = parseArgs() # parse hamiltonian,system data etc (inbuilt ham methods) ham = hamiltonian() ham.parse() # open the outfile outFile = open(outFileName+'.out','w') # change the fileName to a file object # SHOULD BE ABLE TO DO THIS BY RECURSION... # only loop over 1st token till I can sort out the recursion # loop over token 1 # ..... # set the hamiltonian tokens to their values # print the hamiltonian to ham.tmp # call huckel_energy ham.tmp tmp.out N # read in tmp.out # append the token values followed by the eigenvalues to the outfile # if len(ham.getTokens()) != 0: token = ham.getTokens()[0] start = float(ham.getTokenRange(token)[0]) stop = float(ham.getTokenRange(token)[1]) step = float(ham.getTokenRange(token)[2]) for tokenVal in arange(start,stop,step): ham.assign(token,tokenVal) ham.filePrint("ham.tmp") os.system("../src/huckel_energy ham.tmp out.tmp N") # call Fortran code outTmp = open('out.tmp','r') outFile.write(str(tokenVal)+' '+outTmp.readline()) # write the eigenvalues to the outFile outTmp.close() os.system('rm ham.tmp out.tmp') else: print 'FAIL: no tokens specified' # close the outfile outFile.close() # write a gnuplot script plot(outFileName)
def read_nicolet(tmin, tmax): """Load Nicolet BMSI data.""" if tmin < 0: tmin = 0 fh = file(filename, 'rb') indmin = Fs * tmin numsamples = os.path.getsize(filename) / (channels * 2) indmax = min(numsamples, Fs * tmax) byte0 = int(indmin * channels * 2) numbytes = int((indmax - indmin) * channels * 2) fh.seek(byte0) data = fromstring(fh.read(numbytes), Int16).astype(Float) data.shape = -1, channels t = (1 / Fs) * arange(indmin, indmax) return t, data
def read_nicolet(tmin, tmax): """Load Nicolet BMSI data.""" if tmin<0: tmin=0 fh = file(filename, 'rb') indmin = Fs*tmin numsamples = os.path.getsize(filename)/(channels*2) indmax = min(numsamples, Fs*tmax) byte0 = int(indmin*channels*2) numbytes = int( (indmax-indmin)*channels*2 ) fh.seek(byte0) data = fromstring(fh.read(numbytes), Int16).astype(Float) data.shape = -1, channels t = (1/Fs)*arange(indmin, indmax) return t, data
def RenderGradient(surf, topcolor, bottomcolor): '''Creates a new 3d vertical gradient array. This code was copied from the vgrade example''' import pygame from Numeric import array, repeat, resize, arange, \ Float, NewAxis, Int, UnsignedInt8 topcolor = array(topcolor, copy=0) bottomcolor = array(bottomcolor, copy=0) diff = bottomcolor - topcolor width, height = surf.get_size() # create array from 0.0 to 1.0 triplets column = arange(height, typecode=Float)/height column = repeat(column[:, NewAxis], [3], 1) # create a single column of gradient column = topcolor + (diff * column).astype(Int) # make the column a 3d image column by adding X column = column.astype(UnsignedInt8)[NewAxis,:,:] #3d array into 2d array column = pygame.surfarray.map_array(surf, column) # stretch the column into a full image return resize(column, (width, height))
def main(argv): pygame.init() screen = pygame.display.set_mode(screensize, pygame.FULLSCREEN) buf = zeros(screensize) fiery_rgb_integers = clamp(0, subtract.outer(arange(ncolors) + ncolors/8, ((array([0, 1, 2]) * ncolors) / 4)), ncolors / 4) masks = screen.get_masks()[:3] # I'm not sure this palette is exactly right; it only goes to 63 # in the original... palette = array([colors(masks, levels/float(ncolors/4)) for levels in fiery_rgb_integers]) frames = 0 while 1: ev = pygame.event.poll() if ev.type == pygame.NOEVENT: frames += 1 redraw(screen, buf, palette, frames) pygame.display.flip() elif ev.type == pygame.KEYDOWN: break elif ev.type == pygame.QUIT: break
def sinus(hz, pico, n_muestras): theta = arange(n_muestras) * (2*pi * hz / tasa) return (pico * sin(theta)).astype(Int16)
def unmasked_to_masked(mask): """Returns array mapping indices in ungapped to indices in original. Any position where the mask is True will be omitted from the final result. """ return compress(logical_not(mask), arange(len(mask)))
return 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() fig = Figure(figsize=(5, 4), dpi=100) ax = Subplot(fig, 111) t = arange(0.0, 3.0, 0.01) s = sin(2 * pi * t) ax.plot(t, s) ax.set_title("click on line or text") fig.add_axis(ax) canvas = PickerCanvas(fig) canvas.show() vbox.pack_start(canvas) toolbar = NavigationToolbar(canvas, win) toolbar.show() vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE)
def readSegy(filename) : """ Data,SegyHeader,SegyTraceHeaders=getSegyHeader(filename) """ printverbose("readSegy : Trying to read "+filename,0) data = open(filename).read() filesize=len(data) SH=getSegyHeader(filename) bps=getBytePerSample(SH) ntraces = (filesize-3600)/(SH['ns']*bps+240) # ntraces = 100 printverbose("readSegy : Length of data : " + str(filesize),2) SH["ntraces"]=ntraces; ndummy_samples=240/bps printverbose("readSegy : ndummy_samples="+str(ndummy_samples),6) printverbose("readSegy : ntraces=" + str(ntraces) + " nsamples="+str(SH['ns']),2) # GET TRACE index=3600; nd=(filesize-3600)/bps # READ ALL SEGY TRACE HEADRES SegyTraceHeaders = getAllSegyTraceHeaders(SH,data) printverbose("readSegy : reading segy data",2) # READ ALL DATA EXCEPT FOR SEGY HEADER #Data = zeros((SH['ns'],ntraces)) revision=SH["SegyFormatRevisionNumber"] if (revision==100): revision=1 dsf=SH["DataSampleFormat"] DataDescr=SH_def["DataSampleFormat"]["descr"][revision][dsf] printverbose("readSegy : SEG-Y revision = "+str(revision),1) printverbose("readSegy : DataSampleFormat="+str(dsf)+"("+DataDescr+")",1) if (SH["DataSampleFormat"]==1): printverbose("readSegy : Assuming DSF=1, IBM FLOATS",2) Data1 = getValue(data,index,'ibm',endian,nd) elif (SH["DataSampleFormat"]==2): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 32bit INT",2) Data1 = getValue(data,index,'l',endian,nd) elif (SH["DataSampleFormat"]==3): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 16bit INT",2) Data1 = getValue(data,index,'h',endian,nd) elif (SH["DataSampleFormat"]==5): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", IEEE",2) Data1 = getValue(data,index,'float',endian,nd) elif (SH["DataSampleFormat"]==8): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 8bit CHAR",2) Data1 = getValue(data,index,'B',endian,nd) else: printverbose("readSegy : DSF=" + str(SH["DataSampleFormat"]) + ", NOT SUPORTED",2) Data = Data1[0] printverbose("readSegy : - reshaping",2) Data=reshape(Data,(ntraces,SH['ns']+ndummy_samples)) printverbose("readSegy : - stripping header dummy data",2) Data=Data[:,ndummy_samples:(SH['ns']+ndummy_samples)] printverbose("readSegy : - transposing",2) Data=transpose(Data) # SOMEONE NEEDS TO IMPLEMENT A NICER WAY DO DEAL WITH DSF=8 if (SH["DataSampleFormat"]==8): for i in arange(ntraces): for j in arange(SH['ns']): if Data[i][j]>128: Data[i][j]=Data[i][j]-256 printverbose("readSegy : read data",2)
y_inlet, ] * n_nodes) for i in range(1, n_nodes): iparam = i - 1 if iparam < len(parameter_list): y[i] = parameter_list[iparam] else: # the last y-node is at the same height as the # second-last y-node to get a zero-slope exit. y[i] = parameter_list[-1] return x, y #------------------------------------------------------------------------ if __name__ == '__main__': print "# Begin demo of wall_definition for X2 nozzle..." p_list = [0.040496, 0.065839, 0.051086, 0.089875, 0.103871] x, y = bezier_nodes_for_wall(p_list) print "#---------------------" print "# Bezier nodes..." for i in range(len(x)): print x[i], y[i] print "#---------------------" print "# Sample points..." for t in arange(0.0, 1.001, 0.02): xp, yp, zp = bezier3D_eval(t, Bx=x, By=y) print xp, yp print "#---------------------" print "Done."
#!/usr/bin/python # basado en # http://lists.canonical.org/pipermail/kragen-hacks/2007-November/000465.html from pygame import mixer, sndarray, time, init from Numeric import arange, Int16, sin, pi tasa = 22050 # de muestreo mixer.pre_init(tasa, -16, 1) # 16bit, un canal init() # necesario para mixer hz, pico, n_muestras = 440, 16384, tasa theta = arange(n_muestras) * (2*pi * hz / tasa) sndarray.make_sound((pico * sin(theta)).astype(Int16) ).play(-1, 0, 20) # 20ms fadein time.wait(1000) # un segundo
right = left + width assert(left==1) assert(right==6) assert(width==5) assert(bottom==-1) assert(top==12) assert(height==13) b = Bound1D(-1, 1) closeto(b.scale(1.9).bounds(), (-1.9, 1.9) ) b = Bound1D(-1, 1) closeto(b.scale(0.9).bounds(), (-0.9, 0.9) ) print 'passed bounding box tests ...' # test positive bounding box x = arange(-1.0001, 1.0, 0.01) bpos = Bound1D(.1, 1, isPos=True) bpos.update(x) assert(bpos.min()>0) bpos.is_positive(False) bpos.update(x) assert(bpos.min()==-1.0001) print 'passed positive bounding box tests ...' # testing transforms i1 = Bound1D(0,1) i2 = Bound1D(-6,6) identityTrans = Transform() linearTrans = Transform(i1,i2) logTrans = Transform(Bound1D(0.1,1), i2, funcs=(log10, pow10))
right = left + width assert (left == 1) assert (right == 6) assert (width == 5) assert (bottom == -1) assert (top == 12) assert (height == 13) b = Bound1D(-1, 1) closeto(b.scale(1.9).bounds(), (-1.9, 1.9)) b = Bound1D(-1, 1) closeto(b.scale(0.9).bounds(), (-0.9, 0.9)) print 'passed bounding box tests ...' # test positive bounding box x = arange(-1.0001, 1.0, 0.01) bpos = Bound1D(.1, 1, isPos=True) bpos.update(x) assert (bpos.min() > 0) bpos.is_positive(False) bpos.update(x) assert (bpos.min() == -1.0001) print 'passed positive bounding box tests ...' # testing transforms i1 = Bound1D(0, 1) i2 = Bound1D(-6, 6) identityTrans = Transform() linearTrans = Transform(i1, i2) logTrans = Transform(Bound1D(0.1, 1), i2, funcs=(log10, pow10))
def csd(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hamming, noverlap=0): """ The cross spectral density Pxy by Welches average periodogram method. The vectors x and y are divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The product of the direct FFTs of x and y are averaged over each segment to compute Pxy, with a scaling to correct for power loss due to windowing. Fs is the sampling frequency. NFFT must be a power of 2 Refs: Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986) """ if NFFT % 2: raise ValueError, 'NFFT must be a power of 2' # zero pad x and y up to NFFT if they are shorter than NFFT if len(x) < NFFT: n = len(x) x = resize(x, (NFFT, )) x[n:] = 0 if len(y) < NFFT: n = len(y) y = resize(y, (NFFT, )) y[n:] = 0 # for real x, ignore the negative frequencies # if x.typecode()==Complex: numFreqs = NFFT if any(numpy.iscomplex(x)): numFreqs = NFFT else: numFreqs = NFFT // 2 + 1 # windowVals = window(ones((NFFT,),x.typecode())) windowVals = window(numpy.ones(NFFT)) step = NFFT - noverlap ind = range(0, len(x) - NFFT + 1, step) n = len(ind) # Pxy = zeros((numFreqs,n), Complex) Pxy = numpy.zeros([numFreqs, n]) # do the ffts of the slices for i in range(n): thisX = x[ind[i]:ind[i] + NFFT] thisX = windowVals * detrend(thisX) thisY = y[ind[i]:ind[i] + NFFT] thisY = windowVals * detrend(thisY) fx = fft(thisX) fy = fft(thisY) Pxy[:, i] = fy[:numFreqs] * conjugate(fx[:numFreqs]) # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2 if n > 1: Pxy = mean(Pxy, 1) Pxy = divide(Pxy, norm(windowVals)**2) freqs = Fs / NFFT * arange(0, numFreqs) return Pxy, freqs
from matplotlib.axes import Subplot from matplotlib.figure import Figure 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() fig = Figure(figsize=(5,4), dpi=100) ax = Subplot(fig, 111) t = arange(0.0,3.0,0.01) s = sin(2*pi*t) ax.plot(t,s) fig.add_axis(ax) canvas = FigureCanvasGTK(fig) # a gtk.DrawingArea canvas.show() vbox.pack_start(canvas) toolbar = NavigationToolbar(canvas, win) toolbar.show() vbox.pack_start(toolbar, gtk.FALSE, gtk.FALSE) buttonQuit = gtk.Button('Quit')
def GetBasis(self): """ Returns the basis i.e. the unitmatrix of the right dimension. """ return equal.outer(arange(self.__dimension__),arange(self.__dimension__))
#!/usr/bin/python # -*- coding: utf-8 -*- from scipy.signal.ltisys import lti, lsim from matplotlib.pylab import save, randn from Numeric import sqrt, array, arange n = 128 Q = 1. R = 1. w = 0.3 * sqrt(Q) * randn(n) v = 0.2 * sqrt(R) * randn(n) ureq = array([[-1.743] * n]) t = arange(0, 0.9999, 1. / 128) #Generator().generateSin(n, 3, 33) #-0.37727 u = ureq + w #A, B, C, D = [[-6.,-25.], [1.,0.]], [[1.],[0.]], [[0., 1.]], [[0.]] #sys=lti(A, B, C, D) #y = lsim(sys, u, t) yv = u + v ##save('Q.txt', Q) ##save('R.txt', R) save('w.txt', w) save('v.txt', v) save('yv.txt', yv) save('u.txt', u) save('ureq.txt', ureq)
def GetBasis(self): """ Returns the basis i.e. the unitmatrix of the right dimension. """ return equal.outer(arange(self.__dimension__), arange(self.__dimension__))
# N-5817 Bergen, NORWAY # This script tries to recreate the heat tables from pp 37, 41, and 45 # in the UNESCO 1983 report. The functions tested are heatcap, adtgrad, # and temppot. # Reference: # UNESCO 1983 # N.P. Fofonoff and R.C. Millard Jr., # Algorithms for computation of fundamental properties of seawater, # Unesco technical papers in marine science 44. from Numeric import array, arange from seawater import heatcap, adtgrad, temppot T = 10.0*arange(5) P = 1000.0*arange(11) S = array([0., 30., 35., 40.]) deg = chr(176) # degree symbol in iso-latin1 encoding # ------------------------------------------------------ def printheatcap(): S = array([0., 30., 35., 40.]) entry = " %6.1f" print print " SPECIFIC HEAT SEAWATER Cp [ J/(Kg K) ]" print "PRESSURE TEMPERATURE", print deg+"C IPTS-68 SALINTY:", "%2.0f" % S[0] print "DECIBARS %8d %11d %11d %11d %11d" % tuple(T)
def readSegy(filename): # printverbose("readSegy : Trying to read "+filename,0) data = open(filename).read() filesize=len(data) SH=getSegyHeader(filename) bps=getBytePerSample(SH) ntraces = (filesize-3600)/(SH['ns']*bps+240) # ntraces = 100 printverbose("readSegy : Length of data : " + str(filesize),2) SH["ntraces"]=ntraces; ndummy_samples=240/bps printverbose("readSegy : ndummy_samples="+str(ndummy_samples),6) printverbose("readSegy : ntraces=" + str(ntraces) + " nsamples="+str(SH['ns']),2) # GET TRACE index=3600; nd=(filesize-3600)/bps # READ ALL SEGY TRACE HEADRES SegyTraceHeaders = getAllSegyTraceHeaders(SH,data) printverbose("readSegy : reading segy data",2) # READ ALL DATA EXCEPT FOR SEGY HEADER #Data = zeros((SH['ns'],ntraces)) revision=SH["SegyFormatRevisionNumber"] if (revision==256): revision=1 dsf=SH["DataSampleFormat"] DataDescr=SH_def["DataSampleFormat"]["descr"][revision][dsf] printverbose("readSegy : SEG-Y revision = "+str(revision),1) printverbose("readSegy : DataSampleFormat="+str(dsf)+"("+DataDescr+")",1) if (SH["DataSampleFormat"]==1): printverbose("readSegy : Assuming DSF=1, IBM FLOATS",2) Data1 = getValue(data,index,'ibm',endian,nd) elif (SH["DataSampleFormat"]==2): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 32bit INT",2) Data1 = getValue(data,index,'l',endian,nd) elif (SH["DataSampleFormat"]==3): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 16bit INT",2) Data1 = getValue(data,index,'h',endian,nd) elif (SH["DataSampleFormat"]==5): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", IEEE",2) Data1 = getValue(data,index,'float',endian,nd) elif (SH["DataSampleFormat"]==8): printverbose("readSegy : Assuming DSF=" + str(SH["DataSampleFormat"]) + ", 8bit CHAR",2) Data1 = getValue(data,index,'B',endian,nd) else: printverbose("readSegy : DSF=" + str(SH["DataSampleFormat"]) + ", NOT SUPORTED",2) Data = Data1[0] printverbose("readSegy : - reshaping",2) Data=reshape(Data,(ntraces,SH['ns']+ndummy_samples)) printverbose("readSegy : - stripping header dummy data",2) Data=Data[:,ndummy_samples:(SH['ns']+ndummy_samples)] printverbose("readSegy : - transposing",2) Data=transpose(Data) # SOMEONE NEEDS TO IMPLEMENT A NICER WAY DO DEAL WITH DSF=8 if (SH["DataSampleFormat"]==8): for i in arange(ntraces): for j in arange(SH['ns']): if Data[i][j]>128: Data[i][j]=Data[i][j]-256 printverbose("readSegy : read data",2) return Data,SH,SegyTraceHeaders
def psd(x, NFFT=256, Fs=2, detrend=detrend_none, window=window_hamming, noverlap=0): """ The power spectral density by Welches average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noperlap gives the length of the overlap between segments. The absolute(fft(segment))**2 of each segment are averaged to compute Pxx, with a scaling to correct for power loss due to windowing. Fs is the sampling frequency. -- NFFT must be a power of 2 -- detrend and window are functions, unlike in matlab where they are vectors. -- if length x < NFFT, it will be zero padded to NFFT Refs: Bendat & Piersol -- Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986) """ if NFFT % 2: raise ValueError, 'NFFT must be a power of 2' # zero pad x up to NFFT if it is shorter than NFFT if len(x) < NFFT: n = len(x) x = resize(x, (NFFT, )) x[n:] = 0 # for real x, ignore the negative frequencies # if x.typecode()==Complex: numFreqs = NFFT if any(numpy.iscomplex(x)): numFreqs = NFFT else: numFreqs = NFFT // 2 + 1 # windowVals = window(ones((NFFT,),x.typecode())) windowVals = window(numpy.ones(NFFT)) step = NFFT - noverlap ind = range(0, len(x) - NFFT + 1, step) n = len(ind) # Pxx = zeros((numFreqs,n), Float) Pxx = numpy.zeros([numFreqs, n]) # do the ffts of the slices for i in range(n): thisX = x[ind[i]:ind[i] + NFFT] thisX = windowVals * detrend(thisX) fx = absolute(fft(thisX))**2 #print("numFreqs={0:f}".format(numFreqs)) #print("len of fx slice={0:d}".format(len(fx[:int(numFreqs)]))) #print("len of destination in Pxx={0:d}") Pxx[:, i] = fx[:int(numFreqs)] # Scale the spectrum by the norm of the window to compensate for # windowing loss; see Bendat & Piersol Sec 11.5.2 if n > 1: Pxx = mean(Pxx, 1) Pxx = divide(Pxx, norm(windowVals)**2) freqs = Fs / NFFT * arange(0, numFreqs) return Pxx, freqs
from math import sqrt mmat = MapMatSparse() mmat.load('../../../data/A.m') A = DegMatSparse(mmat) B = FastMatSparse(mmat) print "Done reading stuff" n = B.n print n x = arange(n, typecode='d') b = arange(n, typecode='d') x *= 0; x += 1 b *= 0; b += 2 t = -time.time() #for i in range(10): # x=A*x #t += time.time() #print t print "Start timer" t = -time.time() for i in range(10):
def iagaussian(s,mu,sigma): """ o Purpose Generate a 2D Gaussian image. o Synopsis g = iagaussian(s,mu,sigma) o Input s: [rows columns] mu: Mean vector. 2D point (x;y). Point of maximum value. sigma: covariance matrix (square). [ Sx^2 Sxy; Syx Sy^2] o Output g: o Description A 2D Gaussian image is an image with a Gaussian distribution. It can be used to generate test patterns or Gaussian filters both for spatial and frequency domain. The integral of the gaussian function is 1.0. o Examples import Numeric f = iagaussian([8,4], [3,1], [[1,0],[0,1]]) print Numeric.array2string(f, precision=4, suppress_small=1) g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8) print g f = iagaussian(100, 50, 10*10) g = ianormalize(f, [0,1]) g,d = iaplot(g) showfig(g) f = iagaussian([50,50], [25,10], [[10*10,0],[0,20*20]]) g = ianormalize(f, [0,255]).astype(Numeric.UnsignedInt8) iashow(g) """ from Numeric import asarray,product,arange,NewAxis,transpose,matrixmultiply,reshape,concatenate,resize,sum,zeros,Float,ravel,pi,sqrt,exp from LinearAlgebra import inverse,determinant if type(sigma).__name__ in ['int', 'float', 'complex']: sigma = [sigma] s, mu, sigma = asarray(s), asarray(mu), asarray(sigma) if (product(s) == max(s)): x = arange(product(s)) d = x - mu if len(d.shape) == 1: tmp1 = d[:,NewAxis] tmp3 = d else: tmp1 = transpose(d) tmp3 = tmp1 if len(sigma) == 1: tmp2 = 1./sigma else: tmp2 = inverse(sigma) k = matrixmultiply(tmp1, tmp2) * tmp3 else: aux = arange(product(s)) x, y = iaind2sub(s, aux) xx = reshape(concatenate((x,y)), (2, product(x.shape))) d = transpose(xx) - resize(reshape(mu,(len(mu),1)), (s[0]*s[1],len(mu))) if len(sigma) == 1: tmp = 1./sigma else: tmp = inverse(sigma) k = matrixmultiply(d, tmp) * d k = sum(transpose(k)) g = zeros(s, Float) aux = ravel(g) if len(sigma) == 1: tmp = sigma else: tmp = determinant(sigma) aux[:] = 1./(2*pi*sqrt(tmp)) * exp(-1./2 * k) return g