def degelev(self, utimes, vtimes=None): """Degree elevate the surface. utimes - degree elevate utimes along u direction. vtimes - degree elevate vtimes along v direction.""" if vtimes: if vtimes < 0: raise NURBSError, 'Degree must be positive' coefs = numerix.resize( self.cntrl, (4 * self.cntrl.shape[1], self.cntrl.shape[2])) coefs, vknots, nh = bspdegelev(self.degree[1], coefs, self.vknots, vtimes) coefs = coefs[:, :nh + 1] self.vknots = vknots[:nh + self.degree[1] + vtimes + 2] self.degree[1] += vtimes self.cntrl = numerix.resize( coefs, (4, self.cntrl.shape[1], coefs.shape[1])) if utimes: if utimes < 0: raise NURBSError, 'Degree must be positive' coefs = numerix.transpose(self.cntrl, (0, 2, 1)) coefs = numerix.resize( coefs, (4 * self.cntrl.shape[2], self.cntrl.shape[1])) coefs, uknots, nh = bspdegelev(self.degree[0], coefs, self.uknots, utimes) coefs = coefs[:, :nh + 1] self.uknots = uknots[:nh + self.degree[0] + utimes + 2] self.degree[0] += utimes coefs = numerix.resize(coefs, (4, self.cntrl.shape[2], coefs.shape[1])) self.cntrl = numerix.transpose(coefs, (0, 2, 1))
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5, weights=None, dims=None, padding = 0.0): """blur a set of coordinates with radii """ # Setup grid resX = resY = resZ = res if not dims: minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding) Xdim = int(round( (maxb[0] - minb[0])/resX + 1)) Ydim = int(round( (maxb[1] - minb[1])/resY + 1)) Zdim = int(round( (maxb[2] - minb[2])/resZ + 1)) else: Xdim, Ydim, Zdim = dims print "Xdim = %d, Ydim =%d, Zdim = %d"%(Xdim, Ydim, Zdim) # Generate blur map volarr, origin, span = blur.generateBlurmap( coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding) # Take data from blur map volarr.shape = [Zdim, Ydim, Xdim] volarr = Numeric.transpose(volarr).astype('f') origin = Numeric.array(origin).astype('f') stepsize = Numeric.array(span).astype('f') arrayf = Numeric.reshape( Numeric.transpose(volarr), (1, 1)+tuple(volarr.shape) ) # Return data return arrayf, origin, stepsize
def display(self): GL.glClearColor( 0.0, 0.0, 0.0, 0.0) GL.glClear( GL.GL_COLOR_BUFFER_BIT) GL.glColor3f( 1.0,1.0,0.0) self.x = self.x + self.move_x self.y = self.y + self.move_y self.age = self.age + 1 which = Numeric.greater( self.age, MAX_AGE) self.x = Numeric.choose( which, (self.x, RandomArray.random( NUMDOTS))) selfy = Numeric.choose( which, (self.y, RandomArray.random( NUMDOTS))) self.age = Numeric.choose( which, (self.age, 0)) self.x = Numeric.choose( Numeric.greater( self.x, 1.0), (self.x, self.x - 1.0)) self.y = Numeric.choose( Numeric.greater( self.y, 1.0), (self.y, self.y - 1.0)) x2 = RandomArray.random( NUMDOTS2) y2 = RandomArray.random( NUMDOTS2) v = Numeric.concatenate( (Numeric.transpose( Numeric.array( [self.x, self.y])), Numeric.transpose( Numeric.array( [self.x - 0.005, self.y + 0.005])), Numeric.transpose( Numeric.array( [self.x + 0.005, self.y - 0.005])), Numeric.transpose( Numeric.array( [x2, y2])))) #from opengltk.util import GLdouble #av = bufarray.readArray( v, GLdouble) #GL.glVertexPointer( 2, av) GL.glVertexPointer( 2, v) GL.glEnableClientState( GL.GL_VERTEX_ARRAY) #glplus.DrawArrays( GL.POINTS, len( av)) from opengltk import glplus glplus.DrawArrays( GL.GL_POINTS, len( v)) #GL.glDisableClientState( GL.VERTEX_ARRAY) GL.glFlush() GLUT.glutSwapBuffers()
def extractV(self, u): "Extract curve in v-direction at parameter u." if numerix.any(u < 0.) or numerix.any(u > 1.): raise NURBSError, 'Out of parameter range [0,1]' if u == 0.: cntrl = self.cntrl[:, 0, :] knots = self.vknots[:] elif u == 1.: cntrl = self.cntrl[:, -1, :] knots = self.vknots[:] else: uknots = numerix.repeat( numerix.asarray([u], numerix.Float), [self.degree[1] * (self.cntrl.shape[2] + 1)]) coefs = numerix.transpose(self.cntrl, (0, 2, 1)) coefs = numerix.resize( coefs, (4 * self.cntrl.shape[2], self.cntrl.shape[1])) coefs, knots = bspkntins(self.degree[0], coefs, self.uknots, uknots) coefs = numerix.resize(coefs, (4, self.cntrl.shape[2], coefs.shape[1])) cntrl = numerix.transpose(coefs, (0, 2, 1)) i = 0 j = knots[0] for k in knots[1:]: if k == u: break elif k != j: i += 1 j = k return Crv.Crv(cntrl[:, i, :], self.vknots[:])
def blurCoordsRadii(coords, radii, blobbyness=-0.1, res=0.5, weights=None, dims=None, padding=0.0): """blur a set of coordinates with radii """ # Setup grid resX = resY = resZ = res if not dims: minb, maxb = blur.getBoundingBox(coords, radii, blobbyness, padding) Xdim = int(round((maxb[0] - minb[0]) / resX + 1)) Ydim = int(round((maxb[1] - minb[1]) / resY + 1)) Zdim = int(round((maxb[2] - minb[2]) / resZ + 1)) else: Xdim, Ydim, Zdim = dims print "Xdim = %d, Ydim =%d, Zdim = %d" % (Xdim, Ydim, Zdim) # Generate blur map volarr, origin, span = blur.generateBlurmap(coords, radii, [Xdim, Ydim, Zdim], blobbyness, weights=weights, padding=padding) # Take data from blur map volarr.shape = [Zdim, Ydim, Xdim] volarr = Numeric.transpose(volarr).astype('f') origin = Numeric.array(origin).astype('f') stepsize = Numeric.array(span).astype('f') arrayf = Numeric.reshape(Numeric.transpose(volarr), (1, 1) + tuple(volarr.shape)) # Return data return arrayf, origin, stepsize
def __exposedResidues(self, ASA_values, sidechainCut=0.0, backboneCut=0.0, totalCut=0.0): """ Decide what is a surface exposed residue and what is not. sidechainCut, backboneCut, totalCut - float, cutoff value for what will be considered as a exposed residue. All three values have to pass the test. @param ASA_values: array with ASA values for side chains, backbone and total calculated in L{__read_residueASA}. @type ASA_values: array @param sidechainCut: cutoff ASA value for considering the side chain to consider thew residue being exposed (default: 0.0) @type sidechainCut: float @param backboneCut: cutoffvalue for back bone ASA @type backboneCut: float @param totalCut: cutoff for total ASA @type totalCut: float @return: residue mask, where 0 = burried @rtype: [1|0] """ col_0 = N.greater(N.transpose(ASA_values)[0], totalCut) col_1 = N.greater(N.transpose(ASA_values)[1], backboneCut) col_2 = N.greater(N.transpose(ASA_values)[2], sidechainCut) col_012 = N.concatenate(([col_0], [col_1], [col_2])) exposedList = N.greater(N.sum(col_012), 0) return exposedList
def FrameTransform(self, camera=None): """Build the R an RI, the object's frame transformation and inverse""" GL.glPushMatrix() self.Si = Numeric.ones((3, )) GL.glLoadIdentity() m = Numeric.reshape(self.object.rotation, (4, 4)) upd = Numeric.reshape(Numeric.transpose(m), (16, )) GL.glMultMatrixf(self.object.Ri) GL.glMultMatrixf(upd) GL.glMultMatrixf(self.object.MatrixRotInv) self.Si = self.Si * self.object.Si / (self.object.scale * self.object.MatrixScale) self.Ri = Numeric.array(GL.glGetDoublev( GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() #self.Ri = Numeric.reshape(glCleanRotMat(self.Ri), (4,4) ) self.Ri = glCleanRotMat(self.Ri) self.R = Numeric.reshape(Numeric.transpose(self.Ri), (16, )).astype('f') self.Ri = Numeric.reshape(self.Ri, (16, )).astype('f') if self.redirectXform: self.redirectXform.FrameTransform(camera) for o in self.copyXform: o.FrameTransform(camera)
def __exposedResidues( self, ASA_values, sidechainCut=0.0, backboneCut=0.0, totalCut=0.0 ): """ Decide what is a surface exposed residue and what is not. sidechainCut, backboneCut, totalCut - float, cutoff value for what will be considered as a exposed residue. All three values have to pass the test. @param ASA_values: array with ASA values for side chains, backbone and total calculated in L{__read_residueASA}. @type ASA_values: array @param sidechainCut: cutoff ASA value for considering the side chain to consider thew residue being exposed (default: 0.0) @type sidechainCut: float @param backboneCut: cutoffvalue for back bone ASA @type backboneCut: float @param totalCut: cutoff for total ASA @type totalCut: float @return: residue mask, where 0 = burried @rtype: [1|0] """ col_0 = N.greater( N.transpose(ASA_values)[0], totalCut ) col_1 = N.greater( N.transpose(ASA_values)[1], backboneCut ) col_2 = N.greater( N.transpose(ASA_values)[2], sidechainCut ) col_012 = N.concatenate( ([col_0],[col_1],[col_2]) ) exposedList = N.greater(N.sum(col_012), 0) return exposedList
def extractV(self, u): "Extract curve in v-direction at parameter u." if numerix.any(u < 0.) or numerix.any(u > 1.): raise NURBSError, 'Out of parameter range [0,1]' if u == 0.: cntrl = self.cntrl[:,0,:] knots = self.vknots[:] elif u == 1.: cntrl = self.cntrl[:,-1,:] knots = self.vknots[:] else: uknots = numerix.repeat(numerix.asarray([u], numerix.Float),[self.degree[1]*(self.cntrl.shape[2] + 1)]) coefs = numerix.transpose(self.cntrl,(0, 2, 1)) coefs = numerix.resize(coefs,(4*self.cntrl.shape[2], self.cntrl.shape[1])) coefs, knots = bspkntins(self.degree[0], coefs, self.uknots, uknots) coefs = numerix.resize(coefs, (4, self.cntrl.shape[2], coefs.shape[1])) cntrl = numerix.transpose(coefs,(0,2,1)) i = 0 j = knots[0] for k in knots[1:]: if k == u: break elif k != j: i += 1 j = k return Crv.Crv(cntrl[:,i,:], self.vknots[:])
def kntins(self, uknots, vknots=None): """Insert new knots into the surface uknots - knots to be inserted along u direction vknots - knots to be inserted along v direction NOTE: No knot multiplicity will be increased beyond the order of the spline""" if len(vknots): # Force the v knot sequence to be a vector in ascending order vknots = numerix.sort(numerix.asarray(vknots, numerix.Float)) if numerix.any(vknots < 0.) or numerix.any(vknots > 1.): raise NURBSError, 'Illegal vknots sequence' coefs = numerix.resize( self.cntrl, (4 * self.cntrl.shape[1], self.cntrl.shape[2])) coefs, self.vknots = bspkntins(self.degree[1], coefs, self.vknots, vknots) self.cntrl = numerix.resize( coefs, (4, self.cntrl.shape[1], coefs.shape[1])) if len(uknots): # Force the u knot sequence to be a vector in ascending order uknots = numerix.sort(numerix.asarray(uknots, numerix.Float)) if numerix.any(uknots < 0.) or numerix.any(uknots > 1.): raise NURBSError, 'Illegal uknots sequence' coefs = numerix.transpose(self.cntrl, (0, 2, 1)) coefs = numerix.resize( coefs, (4 * self.cntrl.shape[2], self.cntrl.shape[1])) coefs, self.uknots = bspkntins(self.degree[0], coefs, self.uknots, uknots) coefs = numerix.resize(coefs, (4, self.cntrl.shape[2], coefs.shape[1])) self.cntrl = numerix.transpose(coefs, (0, 2, 1))
def squared_distance_matrix(x, y): d1 = N.diagonal(N.dot(x, N.transpose(x))) d2 = N.diagonal(N.dot(y, N.transpose(y))) a1 = N.add.outer(d1, d2) a2 = N.dot(x, N.transpose(y)) return a1 - 2 * a2
def squared_distance_matrix(x, y): d1 = N.diagonal(N.dot(x, N.transpose(x))) d2 = N.diagonal(N.dot(y, N.transpose(y))) a1 = N.add.outer(d1,d2) a2 = N.dot(x, N.transpose(y)) return a1 - 2 * a2
def test_plot(self): """gnuplot.plot test""" # List of (x, y) pairs # plot([(0.,1),(1.,5),(2.,3),(3.,4)]) # plot( zip( range(10), range(10) ) ) # Two plots; each given by a 2d array import numpy.oldnumeric as N x = N.arange(10) y1 = x**2 y2 = (10 - x)**2 plot(N.transpose(N.array([x, y1])), N.transpose(N.array([x, y2])))
def lowess2(x, y, xest, f=2./3., iter=3): """Returns estimated values of y in data points xest (or None if estimation fails). Lowess smoother: Robust locally weighted regression. The lowess function fits a nonparametric regression curve to a scatterplot. The arrays x and y contain an equal number of elements; each pair (x[i], y[i]) defines a data point in the scatterplot. The function returns the estimated (smooth) values of y. The smoothing span is given by f. A larger value for f will result in a smoother curve. The number of robustifying iterations is given by iter. The function will run faster with a smaller number of iterations.""" x = Numeric.asarray(x, 'd') y = Numeric.asarray(y, 'd') xest = Numeric.asarray(xest, 'd') n = len(x) nest = len(xest) r = min(int(Numeric.ceil(f*n)),n-1) # radius: num. of points to take into LR h = [Numeric.sort(abs(x-x[i]))[r] for i in range(n)] # distance of the r-th point from x[i] w = Numeric.clip(abs(([x]-Numeric.transpose([x]))/h),0.0,1.0) w = 1-w*w*w w = w*w*w hest = [Numeric.sort(abs(x-xest[i]))[r] for i in range(nest)] # r-th min. distance from xest[i] to x west = Numeric.clip(abs(([xest]-Numeric.transpose([x]))/hest),0.0,1.0) # shape: (len(x), len(xest) west = 1-west*west*west west = west*west*west yest = Numeric.zeros(n,'d') yest2 = Numeric.zeros(nest,'d') delta = Numeric.ones(n,'d') try: for iteration in range(iter): # fit xest for i in range(nest): weights = delta * west[:,i] b = Numeric.array([sum(weights*y), sum(weights*y*x)]) A = Numeric.array([[sum(weights), sum(weights*x)], [sum(weights*x), sum(weights*x*x)]]) beta = LinearAlgebra.solve_linear_equations(A,b) yest2[i] = beta[0] + beta[1]*xest[i] # fit x (to calculate residuals and delta) for i in range(n): weights = delta * w[:,i] b = Numeric.array([sum(weights*y), sum(weights*y*x)]) A = Numeric.array([[sum(weights), sum(weights*x)], [sum(weights*x), sum(weights*x*x)]]) beta = LinearAlgebra.solve_linear_equations(A,b) yest[i] = beta[0] + beta[1]*x[i] residuals = y-yest s = MLab.median(abs(residuals)) delta = Numeric.clip(residuals/(6*s),-1,1) delta = 1-delta*delta delta = delta*delta except LinearAlgebra.LinAlgError: print "Warning: NumExtn.lowess2: LinearAlgebra.solve_linear_equations: Singular matrix" yest2 = None return yest2
def test_plot( self ): """gnuplot.plot test""" # List of (x, y) pairs # plot([(0.,1),(1.,5),(2.,3),(3.,4)]) # plot( zip( range(10), range(10) ) ) # Two plots; each given by a 2d array import numpy.oldnumeric as N x = N.arange(10) y1 = x**2 y2 = (10-x)**2 plot( N.transpose(N.array([x, y1])), N.transpose(N.array([x, y2])))
def bezier(self, update = None): "Decompose surface to bezier patches and return overlaping control points." if update or not self._bezier: cntrl = numerix.resize(self.cntrl,(4*self.cntrl.shape[1], self.cntrl.shape[2])) cntrl = bspbezdecom(self.degree[1], cntrl, self.vknots) cntrl = numerix.resize(cntrl, (4, self.cntrl.shape[1], cntrl.shape[1])) temp1 = cntrl.shape[1] temp2 = cntrl.shape[2] cntrl = numerix.transpose(cntrl,(0, 2, 1)) cntrl = numerix.resize(cntrl,(4*temp2, temp1)) cntrl = bspbezdecom(self.degree[0], cntrl, self.uknots) cntrl = numerix.resize(cntrl, (4, temp2, cntrl.shape[1])) self._bezier = numerix.transpose(cntrl,(0, 2, 1)) return self._bezier
def __pairwiseDistances(self, u, v): """ pairwise distance between 2 3-D numpy arrays of atom coordinates. @param u: coordinates @type u: array @param v: coordinates @type v: array @return: Numpy array len(u) x len(v) @rtype:array @author: Wolfgang Rieping. """ ## check input if not type( u ) == arraytype or\ not type( v ) == arraytype: raise ComplexError('unsupported argument type ' + \ str( type(u) ) + ' or ' + str( type(v) ) ) diag1= N.diagonal(N.dot(u,N.transpose(u))) diag2= N.diagonal(N.dot(v,N.transpose(v))) dist= -N.dot(v,N.transpose(u))-N.transpose(N.dot(u,N.transpose(v))) dist= N.transpose(N.asarray(map(lambda column,a:column+a, \ N.transpose(dist), diag1))) return N.transpose(N.sqrt(N.asarray( map(lambda row,a: row+a, dist, diag2))))
def _getBasisCoef(self, x, T): """returns coefficients of basis polynomials given T, i.e. their values at x: (poly0, xi) where polynomials in rows, coefficients [a0,a1,...ak] where k=len(x)-1 similar goes for T """ numPoints = T.shape[1] # number of points that polynomials are calculated == len(x) assert len(x) == numPoints, "len(x)=" + str(x) + ", T.shape[1]=" + str(numPoints) + " do not match" numLinSys = T.shape[0] # number of polynomials lin_sys_b = Numeric.transpose(T) lin_sys_a = Numeric.ones((numPoints, numPoints), Numeric.Float) lin_sys_a[:,1] = x for idx in range(2,numPoints): lin_sys_a[:,idx] = lin_sys_a[:,idx-1] * x return Numeric.transpose(LinearAlgebra.solve_linear_equations(lin_sys_a, lin_sys_b))
def pca(data): transposed = 0 if shape(data)[0] < shape(data)[1]: transposed = 1 data = transpose(data) cov = dot(transpose(data), data) ## eigenvectors are row vectors val, vec = eigenvectors(cov) try: val = val.real except: pass try: vec = vec.real except: pass order = argsort(val) val = Numeric.take(val, order) vec = Numeric.take(vec, order) pc = Numeric.dot(data, transpose(vec)) if transposed: pc = Numeric.transpose(pc) return val, vec, pc
def histogram(data, nbins, range = None): """ Comes from Konrad Hinsen: Scientific Python """ data = Numeric.array(data, Numeric.Float) if range is None: min = Numeric.minimum.reduce(data) max = Numeric.maximum.reduce(data) else: min, max = range data = Numeric.repeat(data, Numeric.logical_and(Numeric.less_equal(data, max), Numeric.greater_equal(data, min))) # end if bin_width = (max-min)/nbins data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int) histo = Numeric.add.reduce(Numeric.equal( Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1) histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) bins = min + bin_width*(Numeric.arange(nbins)+0.5) return Numeric.transpose(Numeric.array([bins, histo]))
def inverse4X4(matrix): """ returns the inverse of the given 4x4 transformation matrix t_1: the negetive of Translation vector r_1: the inverse of rotation matrix inversed transformation is 1) t_1 applied first 2) then r_1 is applied to validate the result, N.dot(matrix, mat_inverse)==N.identity(4,'f') """ # check the shape if matrix.shape !=(4,4) and matrix.shape !=(16,) : raise ValueError("Argument must Numeric array of shape (4,4) or (16,)") return None if matrix.shape ==(16,): matrix=N.array(matrix,'f') matrix=N.reshape(matrix,(4,4)) # force the matrix to be (4,4) t_1=N.identity(4,'f') t_1[:2,3]= - matrix[:2, 3] r_1=N.identity(4,'f') r_1[:3,:3] = N.transpose(matrix[:3,:3]) mat_inverse=N.dot(r_1, t_1) #asert N.dot(matrix, mat_inverse) is N.identity(4,'f') return mat_inverse
def rotate(self, rot, coords): """Apply rotation to the coordinates. Rotation can be a 3x3 matrix or 3 Euler angles""" if isinstance(rot[0], types.FloatType): rot = EulerAnglesToMat(rot) return Numeric.dot(coords, Numeric.transpose(rot))
def trim(self): """get rid of any universal gaps in the alignment. """ #make sure we have an alignment if len(self)==0: return #make sure we have an up-to-date matrix if not hasattr(self,'matrix'): self.makeMatrix() nsequences,nresidues = Numeric.shape(self.matrix) if (nsequences != len(self.sequences) or nresidues != len(self)): self.makeMatrix() transpose = Numeric.transpose(self.matrix) gaplist = [] #any row with sum=0 in the transpose corresponds to a column in the alignment #which is all gaps. So add the positions of these columns to the gaplist for x in range(len(transpose)): line = transpose[x] if Numeric.sum(line)==0: gaplist.append(x) #now can simply pop the unwanted gaps out of each sequence. gaplist.reverse() for sequence in self: for gap in gaplist: junk=sequence.sequence.pop(gap) junk=sequence.gappednumbers.pop(gap)
def takeMembers(self, mIndices): """ Take all frames belonging to the members in mIndices:: takeMembers( mIndices ) -> EnsembleTraj with frames of given members @param mIndices: list of member indices @type mIndices: [int] OR array('i') @return: EnsembleTraj with specified members @rtype: EnsembleTraj @todo: return self.__class__ instead of EnsembleTraj """ try: ## assumes that each member traj has same number of frames fi = N.array([self.memberIndices(i) for i in mIndices]) fi = N.ravel(N.transpose(fi)) n_members = len(mIndices) ## has wrong n_members and member order t = self.takeFrames(fi) result = EnsembleTraj(n_members=n_members) result.__dict__.update(t.__dict__) result.n_members = n_members result.resetFrameNames() return result except TypeError: raise EnsembleTrajError, 'takeMembers TypeError '+\ str(mIndices)+\ "\nlenFrames: %i; n_members: %i" %(len(self), self.n_members)
def histogram(data, nbins, range=None): """ Create a histogram. Comes from Konrad Hinsen: Scientific Python @param data: data list or array @type data: [any] @param nbins: number of bins @type nbins: int @param range: data range to create histogram from (min val, max val) @type range: (float, float) OR None @return: array (2 x len(data) ) with start of bin and witdh of bin. @rtype: array """ data = Numeric.array(data, Numeric.Float) if range is None: min = Numeric.minimum.reduce(data) max = Numeric.maximum.reduce(data) else: min, max = range data = Numeric.repeat( data, Numeric.logical_and(Numeric.less_equal(data, max), Numeric.greater_equal(data, min))) bin_width = (max - min) / nbins data = Numeric.floor((data - min) / bin_width).astype(Numeric.Int) histo = Numeric.add.reduce( Numeric.equal(Numeric.arange(nbins)[:, Numeric.NewAxis], data), -1) histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) bins = min + bin_width * (Numeric.arange(nbins) + 0.5) return Numeric.transpose(Numeric.array([bins, histo]))
def findTransformation(x, y): """ Match two arrays by rotation and translation. Returns the rotation matrix and the translation vector. @param x: first set of coordinates @type x: array('f') @param y: second set of coordinates @type y: array('f') @return: rotation matrix (3x3) and translation vector (1x3) @rtype: array, array """ ## center configurations x_av = N.average(x) y_av = N.average(y) x = x - x_av y = y - y_av ## svd of correlation matrix v, l, u = svd(N.dot(N.transpose(x), y)) ## build rotation matrix and translation vector r = N.dot(v, u) t = x_av - N.dot(r, y_av) return r, t
def grayRamp(self): self.byte_map = Numeric.transpose( Numeric.array([range(256), range(256), range(256), range(256)])).astype(Numeric.UnsignedInt8) self.volume.uploadColorMap(self.byte_map)
def loessMA(m, windowSize, axis=0, approxMasked=True, verbose=False, callback=None): """Returns a new array with values at the given axis smoothed by loess; if approxMasked==True: the masked values are approximated by loess; assumes equidistant spacing of points on the given axis. """ assert 0 < windowSize <= m.shape[axis]+0.1, "0 < windowSize[%s] <= 1 OR windowSize in range(1.1,m.shape[axis]+1) expected, got %f" % ("%", windowSize) m = MA.asarray(m) if m.dtype.char <> Numeric.Float: m = m.astype(Numeric.Float) shp_other = list(m.shape) shp_other.pop(axis) # get a transposed and reshaped mask and data from m; if m.mask() == None, construct a new array of zeros mask = Numeric.reshape(Numeric.transpose(MA.getmaskarray(m), [axis] + range(0,axis) + range(axis+1,len(m.shape))), (m.shape[axis], Numeric.multiply.reduce(shp_other))) data = MA.reshape(MA.transpose(m, [axis] + range(0,axis) + range(axis+1,len(m.shape))), (m.shape[axis], Numeric.multiply.reduce(shp_other))) maskInv = -1*(mask-1) xall = Numeric.arange(data.shape[0]) xallList = xall.tolist() for ii in Numeric.compress(Numeric.add.reduce(maskInv,0) > 1, range(data.shape[1])): # run loess if the profile contains more than 2 values try: data[:,ii] = MA.array(statc.loess(zip(MA.compress(maskInv[:,ii], xall).tolist(), MA.compress(maskInv[:,ii], data[:,ii]).tolist()), xallList, windowSize))[:,1] except: if verbose: print "Warning: loessMA: could not loess axis %i index %i" % (axis, ii) if callback: callback() if not approxMasked: data = MA.array(data, mask=mask) return MA.transpose(MA.reshape(data, [m.shape[axis]] + shp_other), [axis] + range(0,axis) + range(axis+1,len(m.shape)))
def contactResDistribution( self, cm=None ): """ Count occurrence of residues in protein-protein interface. @param cm: pre-calculated contact matrix (default: None) @type cm: matrix @return: dict {'A':3, 'C':1, .. } (20 standard amino acids) @rtype: dict """ if cm == None: cm = self.resContacts() ## get mask for residues involved in contacts maskLig = N.sum( cm ) maskRec = N.sum( N.transpose( cm )) ## get sequence of contact residues only seqLig = N.compress( maskLig, self.lig().sequence() ) seqRec = N.compress( maskRec, self.rec().sequence() ) seq = ''.join( seqLig ) + ''.join(seqRec) ## convert back to string ## count occurrence of letters result = {} for aa in molUtils.allAA(): result[aa] = seq.count( aa ) return result
def takeMembers( self, mIndices ): """ Take all frames belonging to the members in mIndices:: takeMembers( mIndices ) -> EnsembleTraj with frames of given members @param mIndices: list of member indices @type mIndices: [int] OR array('i') @return: EnsembleTraj with specified members @rtype: EnsembleTraj @todo: return self.__class__ instead of EnsembleTraj """ try: ## assumes that each member traj has same number of frames fi = N.array( [ self.memberIndices( i ) for i in mIndices ] ) fi = N.ravel( N.transpose( fi ) ) n_members = len( mIndices ) ## has wrong n_members and member order t = self.takeFrames( fi ) result = EnsembleTraj( n_members=n_members ) result.__dict__.update( t.__dict__ ) result.n_members = n_members result.resetFrameNames() return result except TypeError: raise EnsembleTrajError, 'takeMembers TypeError '+\ str(mIndices)+\ "\nlenFrames: %i; n_members: %i" %(len(self), self.n_members)
def buildTexture(self): """Build a 2D Texture object and compute texture coordinates for self.array, using self.colormap to colorize the texture. """ width, height = self.array.shape # find smallest power of 2 larger than shape dim1=dim2=1 while dim1<width: dim1 = dim1<<1 while dim2<height: dim2 = dim2<<1 # compute texture indices r1=float(width)/float(dim1) r2=float(height)/float(dim2) textCoords = ((0,0), (r1,0), (r1, r2), (0, r2)) # build texture object for DejaVu sl = Numeric.array(Numeric.transpose(self.array)) # use this line when new color map will be used colors = self.colormap.Map(sl.ravel()) colors.shape = (height, width, -1) colors = colors*255 colors = colors.astype('B') tex2DimageArr = Numeric.zeros((dim2,dim1,colors.shape[2]), 'B') tex2DimageArr[:height,:width] = colors tex = Texture() tex.Set(enable=1, image=tex2DimageArr, auto=0) tex.width = dim1 tex.height = dim2 return tex, textCoords
def histogram(data, nbins, range = None): """ Create a histogram. Comes from Konrad Hinsen: Scientific Python @param data: data list or array @type data: [any] @param nbins: number of bins @type nbins: int @param range: data range to create histogram from (min val, max val) @type range: (float, float) OR None @return: array (2 x len(data) ) with start of bin and witdh of bin. @rtype: array """ data = Numeric.array(data, Numeric.Float) if range is None: min = Numeric.minimum.reduce(data) max = Numeric.maximum.reduce(data) else: min, max = range data = Numeric.repeat(data, Numeric.logical_and(Numeric.less_equal(data, max), Numeric.greater_equal(data, min))) bin_width = (max-min)/nbins data = Numeric.floor((data - min)/bin_width).astype(Numeric.Int) histo = Numeric.add.reduce(Numeric.equal( Numeric.arange(nbins)[:,Numeric.NewAxis], data), -1) histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) bins = min + bin_width*(Numeric.arange(nbins)+0.5) return Numeric.transpose(Numeric.array([bins, histo]))
def view(*args, **kwargs): import NumTut import graphics from numpy.oldnumeric import transpose rgb = apply(Graphics.get_image_display_data, args, kwargs) NumTut.view(transpose(rgb, (1, 0, 2)))
def histogram(data, nbins, range=None): """ Comes from Konrad Hinsen: Scientific Python """ data = Numeric.array(data, Numeric.Float) if range is None: min = Numeric.minimum.reduce(data) max = Numeric.maximum.reduce(data) else: min, max = range data = Numeric.repeat( data, Numeric.logical_and(Numeric.less_equal(data, max), Numeric.greater_equal(data, min))) # end if bin_width = (max - min) / nbins data = Numeric.floor((data - min) / bin_width).astype(Numeric.Int) histo = Numeric.add.reduce( Numeric.equal(Numeric.arange(nbins)[:, Numeric.NewAxis], data), -1) histo[-1] = histo[-1] + Numeric.add.reduce(Numeric.equal(nbins, data)) bins = min + bin_width * (Numeric.arange(nbins) + 0.5) return Numeric.transpose(Numeric.array([bins, histo]))
def vunrot(self, v): # for use with row vectors # [bruce comment 050518: the above old comment by Josh seems to contradict # the comment about 'matrix' in __getattr__ (also old and by Josh) # that it's the transpose of the normal form so it can be used for row vectors. # See the other comment for more info.] return Numeric.matrixmultiply(v, Numeric.transpose(self.matrix))
def __findTransformation(self, x, y): """ Match two arrays by rotation and translation. Returns the rotation matrix and the translation vector. Back transformation: for atom i new coordinates will be:: y_new[i] = N.dot(r, y[i]) + t for all atoms in one step:: y_new = N.dot(y, N.transpose(r)) + t @param x: coordinates @type x: array @param y: coordinates @type y: array @return: rotation matrix, translation vector @rtype: array, array @author: Michael Habeck """ from numpy.oldnumeric.linear_algebra import singular_value_decomposition as svd ## center configurations x_av = N.sum(x) / len(x) y_av = N.sum(y) / len(y) x = x - x_av y = y - y_av ## svd of correlation matrix v, l, u = svd(N.dot(N.transpose(x), y)) ## build rotation matrix and translation vector r = N.dot(v, u) t = x_av - N.dot(r, y_av) return r, t
def mad(m,axis=0): """Returns Median Absolute Deviation of the given array along the given axis. """ m = Numeric.asarray(m) mx = Numeric.asarray(median(m,axis),Numeric.Float) xt = Numeric.transpose(m, [axis]+range(axis)+range(axis+1,Numeric.rank(m))) # do not use swapaxes: (0,1,2) -swap-> (2,1,0); (0,1,2) -transpose-> (2,0,1) return MLab.median(Numeric.absolute(xt-mx))
def prepareBillboardAndNormalForAllTextLines(self): if self.billboard: m = self.GetMatrix() m = Numeric.reshape(m, (16, )) rot = glCleanRotMat(m) #much faster than self.Decompose4x4(m) if self.includeCameraRotationInBillboard: # this permit billboarding even if the camera is not in the Z axis lCameraTransformation = self.viewer.currentCamera.GetMatrix() lCameraTransformation = Numeric.reshape( lCameraTransformation, (16, )) lCameraRotation = glCleanRotMat( lCameraTransformation ) #much faster than self.Decompose4x4(m) lCameraRotation = Numeric.transpose(lCameraRotation) rot = Numeric.dot(lCameraRotation, rot) rot = Numeric.reshape(rot, (16, )) self.billboardRotation = rot.astype('f') else: c = self.vertexSet.vertices.array n = self.vertexSet.normals.array lenn = len(n) if lenn > 0 and lenn != len(c): lMat = rotax.rotVectToVect(n[0], (0, 0, 1)) self.orientation = [ lMat[0][0], lMat[0][1], lMat[0][2], lMat[0][3], lMat[1][0], lMat[1][1], lMat[1][2], lMat[1][3], lMat[2][0], lMat[2][1], lMat[2][2], lMat[2][3], lMat[3][0], lMat[3][1], lMat[3][2], lMat[3][3] ]
def inverse4X4(matrix): """ returns the inverse of the given 4x4 transformation matrix t_1: the negetive of Translation vector r_1: the inverse of rotation matrix inversed transformation is 1) t_1 applied first 2) then r_1 is applied to validate the result, N.dot(matrix, mat_inverse)==N.identity(4,'f') """ # check the shape if matrix.shape != (4, 4) and matrix.shape != (16, ): raise ValueError("Argument must Numeric array of shape (4,4) or (16,)") return None if matrix.shape == (16, ): matrix = N.array(matrix, 'f') matrix = N.reshape(matrix, (4, 4)) # force the matrix to be (4,4) t_1 = N.identity(4, 'f') t_1[:2, 3] = -matrix[:2, 3] r_1 = N.identity(4, 'f') r_1[:3, :3] = N.transpose(matrix[:3, :3]) mat_inverse = N.dot(r_1, t_1) #asert N.dot(matrix, mat_inverse) is N.identity(4,'f') return mat_inverse
def GetMatrix(self, root=None, instance=None, scale=True, transpose=True): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Returns the matrix by which this object is transformed scale = False: returns the rotation and translation. no scaling info included Used to save the transformed geom --> coords --> new pdb file instance is a list of integer instance indices for all parents """ if root is None: root = self.viewer.rootObject if instance is None: instance = [0] p = self.parent while p: instance.append(0) p = p.parent GL.glPushMatrix() GL.glLoadIdentity() #print 'GetMatrix', instance self.BuildMat(self, root, scale, instance) #GL.glMultMatrixf(self.instanceMatricesFortran[instanceList[0]]]) m = Numeric.array(GL.glGetDoublev(GL.GL_MODELVIEW_MATRIX)).astype('f') GL.glPopMatrix() if Numeric.alltrue(m==Numeric.zeros(16).astype('f')): # this happens when Pmv has no GUI m = Numeric.identity(4) if transpose: return Numeric.transpose(Numeric.reshape(m, (4,4))) else: return Numeric.reshape(m, (4,4))
def setMatrixComponents(self, rot=None, trans=None, scale=None, redo=1): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Define MatrixRot, MatrixTransl, MatrixScale and MatrixRotInv from a rotation, translation and scale. rot should be a 4x4 matrix defining a 3D 3x3 rotation trans should be a 3D translation vector scale should be 3-vector of positive number larger than 0.0 """ self._modified = True if rot is not None: assert rot.shape==(4,4) self.MatrixRot = rot.ravel() RotInv = Numeric.transpose(rot) self.MatrixRotInv = Numeric.reshape(RotInv, (16,)) if trans is not None: assert len(trans)==3 self.MatrixTransl = trans if scale is not None: assert len(scale)==3 and scale[0]>0. and scale[1]>0. and scale[2]>0. self.MatrixScale = scale if redo: self.RedoDisplayList() self.viewer.Redraw()
def mul(self, coords, mat): shape = coords.shape assert shape[-1]==3 #coords = Numeric.reshape(coords, (-1, shape[-1])) one = Numeric.ones((shape[0],1),'f') c = Numeric.concatenate((coords, one),1) coords = Numeric.array(Numeric.reshape(coords, shape)) return Numeric.array(Numeric.dot(c, Numeric.transpose(mat))[:,:3])
def dot(self, other): "Returns the contraction with |other|." if isTensor(other): a = self.array b = Numeric.transpose(other.array, range(1, other.rank)+[0]) return Tensor(Numeric.innerproduct(a, b), 1) else: return Tensor(self.array*other, 1)
def getCTCSS(tone, sampleRate=44100, peak=0.9): if tone in CTCSSTones: tone = CTCSSTones[tone] length = sampleRate / float(tone) omega = Numeric.pi * 2 / length xvalues = Numeric.arange(int(length)) * omega oneCycle = ((peak * 32767) * Numeric.sin(xvalues)).astype(Numeric.Int16) return Numeric.transpose(Numeric.array((oneCycle,oneCycle)))
def matrix_is_symplectic(self, m, tolerance=1.0e-12): """ Confirm that a given matrix $M$ is symplectic to within numerical tolerance. This is done by taking the 4 submatrices: 1. $A = M[0::2, 0::2]$, i.e., configuration coordinates only, 2. $B = M[0::2, 1::2]$, i.e., configuration rows, momenta cols, 3. $C = M[1::2, 0::2]$, i.e., momenta rows, configuration cols, 4. $D = M[1::2, 1::2]$, i.e., momenta only, and verifying the following symplectic identities:- 1. $MJM^{T} = J$, the $2n\\times 2n$ sympletic matrix, 2. $AD^{T}-BC^{T} = I$, the $n\\times n$ identity, 3. $AB^{T}-BA^{T} = Z$, the $n\\times n$ zero, 4. $CD^{T}-DC^{T} = Z$. Finally, we confirm that $\\det{M} = 1$. """ det = determinant(m) j = self.skew_symmetric_matrix() approx_j = matrixmultiply(m, matrixmultiply(j, transpose(m))) a = m[0::2, 0::2] #even, even b = m[0::2, 1::2] #even, odd c = m[1::2, 0::2] #odd, even d = m[1::2, 1::2] #odd, odd i = self.identity_matrix(self.dof()) approx_i = matrixmultiply(a, transpose(d)) - matrixmultiply(b, transpose(c)) approx_z0 = matrixmultiply(a, transpose(b)) - matrixmultiply(b, transpose(a)) approx_z1 = matrixmultiply(c, transpose(d)) - matrixmultiply(d, transpose(c)) norm = self.matrix_norm logger.info('Matrix from diagonal to equilibrium coordinates:') logger.info('[output supressed]') #logger.info(m) logger.info('error in determinant: %s', abs(det-1.0)) logger.info('error in symplectic identity #1: %s', norm(approx_j - j)) logger.info('error in symplectic identity #2: %s', norm(approx_i - i)) logger.info('error in symplectic identity #3: %s', norm(approx_z0)) logger.info('error in symplectic identity #4: %s', norm(approx_z1)) okay = True if not (abs(det-1.0) < tolerance): okay = False if not (norm(approx_j - j) < tolerance): okay = False if not (norm(approx_i - i) < tolerance): okay = False if not (norm(approx_z0) < tolerance): okay = False if not (norm(approx_z1) < tolerance): okay = False return okay
def covarianceMatrix(data, normalize = 1): npoints, dimension = shape(data) if normalize: data = data - Numeric.sum(data)/npoints if dimension > npoints: return dot(data, Numeric.transpose(data)) / (npoints-1) return dot(transpose(data), data)/(npoints-1)
def asymmetricalPart(self): "Returns the asymmetrical part of a rank-2 tensor." if self.rank == 2: return Tensor(0.5*(self.array - \ Numeric.transpose(self.array, Numeric.array([1,0]))), 1) else: raise ValueError, 'Not yet implemented'