def render(self): s = self.svgDrawing if not s: return x, y, z = self.body.getPosition() modelview = glGetDoublev(GL_MODELVIEW_MATRIX) projection = glGetDoublev(GL_PROJECTION_MATRIX) viewport = glGetIntegerv(GL_VIEWPORT) # calculate the z coordinate m = transpose(reshape(modelview, (4, 4))) wz = -matrixmultiply(m, reshape((x, y, z, 1), (4, 1)))[2][0] # don't draw anything if we're behind the viewer if wz < 0.1: return # calculate the screen-space x and y coordinates x, y, z = gluProject(x, y, z, modelview, projection, viewport) scale = self.scale / wz s.transform.reset() s.transform.translate(x, y) s.transform.scale(scale, -scale) s.transform.rotate(self.rotation) s.draw()
def _asarray1d(arr): """Ensure 1d array for one array. """ m = asarray(arr) if len(m.shape)==0: m = reshape(m,(1,)) return m
def learn_step(self, input, output): if rank(input) == 1: input = reshape(input, (len(input), 1)) X = join((input, [[1]])) self._fn.learn_step(X, output)
def learn_step(self, input, output): if rank(input) == 1: input = reshape(input, (self.num_inputs, 1)) if rank(output) == 1: output = reshape(output, (self.num_outputs, 1)) result = self(input) err = output - result self.MSE = norm(err.flat**2) / self.num_outputs self.debug("MSE =", self.MSE) alpha = self.alpha / sum(input**2) self.w += alpha * transpose(dot(input, transpose(err))) self.debug("update ratio =", norm(self(input) - result) / norm(err))
def learn_step(self,input,output): if rank(input) == 1: input = reshape(input,(len(input),1)) X = join((input,[[1]])) self._fn.learn_step(X,output)
def learn_step(self,input,output): if rank(input) == 1: input = reshape(input,(self.num_inputs,1)) if rank(output) == 1: output = reshape(output,(self.num_outputs,1)) result = self(input) err = output - result self.MSE = norm(err.flat**2)/self.num_outputs self.debug("MSE =",self.MSE) alpha = self.alpha/sum(input**2) self.w += alpha*transpose(dot(input,transpose(err))) self.debug( "update ratio =", norm(self(input)-result)/norm(err))
def _asarray1d(arr): """Ensure 1d array for one array. """ m = asarray(arr) if len(m.shape) == 0: m = reshape(m, (1, )) return m
def mvmul(A, x): """Multiply matrix A onto vector x """ from Numeric import dot, reshape x = reshape(x, (A.shape[1], 1)) #Make x a column vector return dot(A, x)
def drawsurf1(self,steplist=None): 'drawsurf1(self,steplist=None) - draw spectrum surface cell by stepwise' self.clearcanvas() self.createAxis() # use color table if ctable is set if self.ctable: p = reshape(self.CT[self.ct],(256,3)) spec=[] for i in range(256): pp = p[i] st = '#%02x%02x%02x' % (int(pp[0]),int(pp[1]),int(pp[2])) spec.append(st) self.ctc = spec da = self.data dv = self.vmax-self.vmin if dv != 0.: data = divide(subtract(da,self.vmin),dv/self.maxY) da1 = divide(subtract(da,self.vmin),dv/255) else: data = da da1 = divide(da,self.vmin/255) rows= len(data) steps= len(data[0]) lasthv = self.maxY*self.yfac xadj = float(self.xincr)/4.0 if xadj < 2: xadj=2 if steplist == None: steplist = range(steps-1) # for cidx in range(steps-1): for cidx in steplist: for row in range(rows-1): rootx = self.xorg + cidx*self.xincr - row*self.hoff/self.rows rooty = self.yorg + row*self.voff/self.rows datum = [data[rows-1-row][cidx+1],data[rows-1-row][cidx],data[rows-1-row-1][cidx],data[rows-1-row-1][cidx+1]] lside = multiply(datum,self.yfac) if self.ctable: if not(self.average): ind = int(da1[rows-1-row,cidx]) else: ind = int((da1[rows-1-row,cidx]+da1[rows-1-row-1,cidx]+ da1[rows-1-row,cidx+1]+da1[rows-1-row-1,cidx+1])/4) color = self.ctc[ind] else: color = self.spectrum[cidx] self.canvas.create_polygon( rootx+self.xincr,rooty-lside[0], rootx,rooty-lside[1], rootx-self.hroff,rooty-lside[2]+self.vroff, rootx+self.xincr-self.hroff,rooty-lside[3]+self.vroff, fill=color, outline=color, width=xadj) self.root.update()
def apply(self): rts = self.dialog.curselection() index = string.atoi(rts[0]) from Numeric import reshape rgb = reshape(self.CT[index],(256,3)) for i in range(256): pp = rgb[i] col = '#%02x%02x%02x' % (int(pp[0]),int(pp[1]),int(pp[2])) self.canvas.create_line(i,0,i,self.cheight,fill=col) fo = open('1.txt','w') fo.write(str(index)) fo.close
def applyAttributes(self, attrs, key = "transform"): transform = attrs.get(key) if transform: m = re.match(r"translate\(\s*(.+?)\s*,(.+?)\s*\)", transform) if m: dx, dy = [float(c) for c in m.groups()] self.matrix[0, 2] += dx self.matrix[1, 2] += dy m = re.match(r"matrix\(\s*" + "\s*,\s*".join(["(.+?)"] * 6) + r"\s*\)", transform) if m: e = [float(c) for c in m.groups()] e = [e[0], e[2], e[4], e[1], e[3], e[5], 0, 0, 1] m = reshape(e, (3, 3)) self.matrix = matrixmultiply(self.matrix, m)
def applyAttributes(self, attrs, key="transform"): transform = attrs.get(key) if transform: m = re.match(r"translate\(\s*(.+?)\s*,(.+?)\s*\)", transform) if m: dx, dy = [float(c) for c in m.groups()] self.matrix[0, 2] += dx self.matrix[1, 2] += dy m = re.match(r"matrix\(\s*" + "\s*,\s*".join(["(.+?)"] * 6) + r"\s*\)", transform) if m: e = [float(c) for c in m.groups()] e = [e[0], e[2], e[4], e[1], e[3], e[5], 0, 0, 1] m = reshape(e, (3, 3)) self.matrix = matrixmultiply(self.matrix, m)
def __init__(self, iter): QObject.__init__(self) limits = [] d = _all(_ithird_column(_isave_limits(_isplit(_inon_empty_lines(iter)), limits))) droot = int(sqrt(len(d))) if len(d) != droot * droot: raise AttributeError("data must be square") self.xmin, self.xmax = 0, droot self.ymin, self.ymax = 0, droot self.zmin, self.zmax = limits[2].min, limits[2].max self.data = reshape(array(d), (droot, droot)) self.x = 0 self.y = 0 self.s = 30 self.r = 1
def Map(function, array, coordinates): """Return a mapped array This method can be used to map an array along with the coordinates corresponding to each grid point. The arrangement of the arguments in the input function is expected to be of the form 'function(' *arrayvalue* , *coordinate* ')' where *coordinate* is a NumPy array having a length correspoding to the dimension. """ from Numeric import reshape, swapaxes, asarray # Finding the dimension of the array dim = coordinates.shape[0] spatialshape = array.shape[-dim:] # Reshaping array shape=(indices,) flatarray = reshape(array, (array.shape[:-dim] + (-1, ))) # Reshaping coordinates (indices,dim) flatcoordinates = swapaxes(reshape(coordinates, (dim, -1)), 0, 1) maparray = asarray(map(function, flatarray, flatcoordinates)) # Reshaping back again return reshape(maparray, spatialshape)
def _ksi(self,obsIndices,alpha,beta): N = self.N A = self.A B = self.B ksi = [] for t in range(len(obsIndices)-1): ksi_t = zeros((N,N),Float) obs = obsIndices[t+1] for i in range(N): for j in range(N): #print t,i,j,alpha[t][i],A[i,j],B[obs][j],beta[t+1][j],alpha[t][i]*A[i,j]*B[obs][j]*beta[t+1][j] #print t,i,j,len(obsIndices),len(alpha) ksi_t[i,j] = alpha[t][i]*A[i,j]*B[obs][j]*beta[t+1][j] # numerator of (37) ksi_t /= sum(reshape(ksi_t,(N*N,))) # normalization of (37) ksi.append(ksi_t) return ksi
def norm_project_posns(self, posns): """ [Private helper for getrotation] Given a Numeric array of position vectors relative to self.center, project them along self.axis and normalize them (and return that -- but we take ownership of posns passed to us, so we might or might not modify it and might or might not return the same (modified) object. """ axis = self.axis dots = dot(posns, axis) ## axis_times_dots = axis * dots # guess from this line: exceptions.ValueError: frames are not aligned axis_times_dots = A(len(dots) * [axis]) * reshape(dots,(len(dots),1)) #k would it be ok to just use axis * ... instead? posns -= axis_times_dots ##posns = norm(posns) # some exception from this posns = A(map(norm, posns)) # assumes no posns are right on the axis! now we think they are on a unit circle perp to the axis... # posns are now projected to a plane perp to axis and centered on self.center, and turned into unit-length vectors. return posns # (note: in this implem, we did modify the mutable argument posns, but are returning a different object anyway.)
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 isnan(a): """y = isnan(x) returns True where x is Not-A-Number""" return reshape(array([_isnan(i) for i in ravel(a)],'b'), shape(a))
def drawsurf1(self, steplist=None): 'drawsurf1(self,steplist=None) - draw spectrum surface cell by stepwise' self.clearcanvas() self.createAxis() # use color table if ctable is set if self.ctable: p = reshape(self.CT[self.ct], (256, 3)) spec = [] for i in range(256): pp = p[i] st = '#%02x%02x%02x' % (int(pp[0]), int(pp[1]), int(pp[2])) spec.append(st) self.ctc = spec da = self.data dv = self.vmax - self.vmin if dv != 0.: data = divide(subtract(da, self.vmin), dv / self.maxY) da1 = divide(subtract(da, self.vmin), dv / 255) else: data = da da1 = divide(da, self.vmin / 255) rows = len(data) steps = len(data[0]) lasthv = self.maxY * self.yfac xadj = float(self.xincr) / 4.0 if xadj < 2: xadj = 2 if steplist == None: steplist = range(steps - 1) # for cidx in range(steps-1): for cidx in steplist: for row in range(rows - 1): rootx = self.xorg + cidx * self.xincr - row * self.hoff / self.rows rooty = self.yorg + row * self.voff / self.rows datum = [ data[rows - 1 - row][cidx + 1], data[rows - 1 - row][cidx], data[rows - 1 - row - 1][cidx], data[rows - 1 - row - 1][cidx + 1] ] lside = multiply(datum, self.yfac) if self.ctable: if not (self.average): ind = int(da1[rows - 1 - row, cidx]) else: ind = int((da1[rows - 1 - row, cidx] + da1[rows - 1 - row - 1, cidx] + da1[rows - 1 - row, cidx + 1] + da1[rows - 1 - row - 1, cidx + 1]) / 4) color = self.ctc[ind] else: color = self.spectrum[cidx] self.canvas.create_polygon(rootx + self.xincr, rooty - lside[0], rootx, rooty - lside[1], rootx - self.hroff, rooty - lside[2] + self.vroff, rootx + self.xincr - self.hroff, rooty - lside[3] + self.vroff, fill=color, outline=color, width=xadj) self.root.update()
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
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)
def isnan(a): """y = isnan(x) returns True where x is Not-A-Number""" return reshape(array([_isnan(i) for i in ravel(a)], 'b'), shape(a))