def concat( self, *traj ): """ Concatenate this with other trajectories. The ref model of the new Trajectory is a 'semi-deep' copy of this trajectorie's model. (see L{PDBModel.take()} ):: concat( traj [, traj2, traj3, ..] ) -> Trajectory @param traj: one or more Trajectory with identical atoms as this one @type traj: Trajectories @return: concatenated trajecties @rtype: Trajectory """ if len( traj ) == 0: return self r = self.__class__() r.frames = N.concatenate( (self.frames, traj[0].frames), 0 ) r.setRef( self.ref.clone()) if self.frameNames and traj[0].frameNames: r.frameNames = self.frameNames + traj[0].frameNames try: if self.pc is not None and traj[0].pc is not None: r.pc['p'] = N.concatenate( (self.pc['p'], traj[0].pc['p']),0) r.pc['u'] = N.concatenate( (self.pc['u'], traj[0].pc['u']),0) except TypeError, why: EHandler.error('cannot concat PC '+str(why) )
def __atom2residueMatrix( self, m ): """ Reduce binary matrix of n x k atoms to binary matrix of i x j residues. @param m: atom contact matrix, array n x k with 1(contact) or 0(no contact) @type m: array @return: residue contact matrix, 2-D numpy array(residues_receptor x residues_ligand) @rtype: array """ recInd = N.concatenate((self.rec().resIndex(), [ self.rec().lenAtoms()] )) ligInd = N.concatenate((self.lig_model.resIndex(), [ self.lig_model.lenAtoms() ] )) residueMatrix = N.zeros(( len(recInd)-1, len(ligInd)-1 ), N.Int) for r in range( len(recInd)-1 ): for l in range( len(ligInd)-1 ): res2res = m[ int(recInd[r]):int(recInd[r+1]), int(ligInd[l]):int(ligInd[l+1]) ] if N.any( res2res ): residueMatrix[r, l] = 1 return residueMatrix
def concat(self, *traj): """ Concatenate this with other trajectories. The ref model of the new Trajectory is a 'semi-deep' copy of this trajectorie's model. (see L{PDBModel.take()} ):: concat( traj [, traj2, traj3, ..] ) -> Trajectory @param traj: one or more Trajectory with identical atoms as this one @type traj: Trajectories @return: concatenated trajecties @rtype: Trajectory """ if len(traj) == 0: return self r = self.__class__() r.frames = N.concatenate((self.frames, traj[0].frames), 0) r.setRef(self.ref.clone()) if self.frameNames and traj[0].frameNames: r.frameNames = self.frameNames + traj[0].frameNames try: if self.pc is not None and traj[0].pc is not None: r.pc['p'] = N.concatenate((self.pc['p'], traj[0].pc['p']), 0) r.pc['u'] = N.concatenate((self.pc['u'], traj[0].pc['u']), 0) except TypeError, why: EHandler.error('cannot concat PC ' + str(why))
def glQuadNormals(self, vertices, faces): """ gets normals for quads by converting a quad face into two triangle faces and calling TriangleNormals. """ faces = Numeric.array(faces) f = Numeric.concatenate((faces[:,-2:], faces[:,:1]), 1) F = Numeric.concatenate((faces[:,:3], f), 0) n = TriangleNormals(vertices, F, 'PER_VERTEX') return n
def glQuadNormals(self, vertices, faces): """ gets normals for quads by converting a quad face into two triangle faces and calling TriangleNormals. """ faces = Numeric.array(faces) f = Numeric.concatenate((faces[:, -2:], faces[:, :1]), 1) F = Numeric.concatenate((faces[:, :3], f), 0) n = TriangleNormals(vertices, F, 'PER_VERTEX') return n
def End(self): import math # center the points around the origin sca = (1.0 / self.griddingSize) * self.gridToWorld points = Numeric.array(self.shape, 'f') * sca xsum, ysum = 0, 0 if points: repeat = 0 comp = points[-1] - points[0] if abs(comp[0]) < .01 and abs(comp[1]) < .01: repeat = -1 for i in range(len(points) + repeat): xsum = xsum + points[i][0] ysum = ysum + points[i][1] xcenter = xsum / (len(points) + repeat) ycenter = ysum / (len(points) + repeat) origin = (xcenter, ycenter) points = points - origin points[:, 1:] = points[:, 1:] * -1 # 3D o = Numeric.ones((len(points), 1)) points = Numeric.concatenate((points, o), 1) # calculate normals to each side normals = Numeric.zeros((len(points) - 1, 3), 'f') for i in range(len(points) - 1): diff = points[i + 1] - points[i] if diff[1] == 0: normals[i][0] = 0.0 normals[i][1] = diff[0] / abs(diff[0]) else: slope = -diff[0] / diff[1] size = -math.sqrt(1 + slope**2) * (diff[1] / abs(diff[1])) normals[i][0] = 1.0 / size normals[i][1] = slope / size # duplicate vertices if self.dup.get(): pts = Numeric.concatenate((points, points), 1) self.points = Numeric.reshape(pts, (2 * len(points), 3)) norms1 = Numeric.concatenate( (Numeric.reshape(normals[-1], (1, 3)), normals)) norms2 = Numeric.concatenate( (normals, Numeric.reshape(normals[0], (1, 3)))) norms = Numeric.concatenate((norms1, norms2), 1) self.normals = Numeric.reshape(norms, (2 * len(points), 3)) # single vertices: average normals else: self.points = points self.normals = Numeric.zeros((len(points), 3)).astype('f') for i in range(len(points) - 1): n = (normals[i - 1] + normals[i]) / 2 self.normals[i] = n.astype('f') self.normals[len(points) - 1] = self.normals[0] print self.points else: self.points, self.normals = [], []
def AddMaterial(self, values, prop=1): """Add materials to the current set""" assert prop in (0,1,2,3,4,5) values = array( values, 'f' ) if prop < self.shini: if values.shape[1] == 3: alpha = ones( (values.shape[0], 1), 'f' ) values = concatenate( (values, alpha), 1 ) self.prop[prop] = concatenate( (self.prop[prop], values) )
def AddMaterial(self, values, prop=1): """Add materials to the current set""" assert prop in (0, 1, 2, 3, 4, 5) values = array(values, 'f') if prop < self.shini: if values.shape[1] == 3: alpha = ones((values.shape[0], 1), 'f') values = concatenate((values, alpha), 1) self.prop[prop] = concatenate((self.prop[prop], values))
def compute(self): newCoords=[] if self.coords is not None: one = Numeric.ones( (self.coords.shape[0], 1), \ self.coords.dtype.char ) c = Numeric.concatenate( (self.coords, one), 1 ) for m in range(len(self.matrices)): newCoords.append(Numeric.dot(c, \ Numeric.transpose(self.matrices[m]))[:, :3]) return Numeric.concatenate(newCoords)
def concatAtoms( self, *traj ): """ Concatenate 2 trajectories of same (frame) length 'horizontally', i.e. for each frame the coordinates of one are appended to the coordinates of the other. The ref model of the new trajectory is a 'semi-deep' copy of this trajectory's model (see L{PDBModel.take()} ):: concatAtoms( traj1 [traj2, traj3..]) -> Trajectory @param traj: one or more Trajectory of the same number of frames @type traj: Trajectories @return: trajectory with concatenated atoms @rtype: Trajectory """ if len( traj ) == 0: return self r = self.__class__() r.frames = N.concatenate( (self.frames, traj[0].frames), 1 ) r.setRef( self.ref.concat( traj[0].getRef() ) ) r.profiles = self.profiles.clone() r.frameNames = self.frameNames return r.concatAtoms( *traj[1:] )
def concatAtoms(self, *traj): """ Concatenate 2 trajectories of same (frame) length 'horizontally', i.e. for each frame the coordinates of one are appended to the coordinates of the other. The ref model of the new trajectory is a 'semi-deep' copy of this trajectory's model (see L{PDBModel.take()} ):: concatAtoms( traj1 [traj2, traj3..]) -> Trajectory @param traj: one or more Trajectory of the same number of frames @type traj: Trajectories @return: trajectory with concatenated atoms @rtype: Trajectory """ if len(traj) == 0: return self r = self.__class__() r.frames = N.concatenate((self.frames, traj[0].frames), 1) r.setRef(self.ref.concat(traj[0].getRef())) r.profiles = self.profiles.clone() r.frameNames = self.frameNames return r.concatAtoms(*traj[1:])
def test_ComplexTraj(self): """Dock.ComplexTraj test""" import Biskit.tools as T ## there is no complex trajectory in the test folder so will have ## to create a fake trajectory with a complex f = [ T.testRoot()+ '/com/1BGS.pdb' ] * 5 t = Trajectory( f, verbose=self.local ) t = ComplexTraj( t, recChains=[0] ) #if self.local: #print 'plotting contact density...' #t.plotContactDensity( step=2 ) ## create a fake second chain in the ligand for i in range( 1093+98, 1968 ): t.ref.atoms['chain_id'][i] = 'B' t.ref.chainIndex( force=1, cache=1 ) t.cl = [1,2] r = N.concatenate((range(1093,1191), range(0,1093), range(1191,1968))) tt = t.takeAtoms( r ) contactMat = tt.atomContacts( 1 ) if self.local: print 'Receptor chains: %s Ligand chains: %s'%(t.cr, t.cl) self.assertEqual( N.sum(N.ravel(contactMat)), 308 )
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 update(self): vertices = self.geom.getVertices() normals = self.geom.getVNormals() pts = Numeric.concatenate( (vertices, vertices+normals), 1) pts = Numeric.reshape( pts, (len(vertices),2,-1) ).astype('f') self.normalsGeom.Set(vertices = pts) self.viewer.Redraw()
def update(self): vertices = self.geom.getVertices() normals = self.geom.getVNormals() pts = Numeric.concatenate((vertices, vertices + normals), 1) pts = Numeric.reshape(pts, (len(vertices), 2, -1)).astype('f') self.normalsGeom.Set(vertices=pts) self.viewer.Redraw()
def SetMaterial(self, values, prop=1, tagModified=True): """Set the materials WARNING: when back face colors are set, two sided lighting has to be enabled we set RGB values for all properties except for shininess and opacity If an alpha value are specified they will be ignored Since IndexedGeomDSPL requires alpha values for all properties we set them automatically to 1.0 for all properties except for diffuse. The alpha channel of the diffuse component will be set later in fixOpacity which should be called after all properties of the material have been updated. """ if tagModified: self._modified = True if prop is None: prop = self.diff elif type(prop) is types.StringType: prop = getattr(self, prop) assert prop in (0, 1, 2, 3, 4, 5) values = array(values, 'f') if prop < self.shini: assert len(values.shape) == 2 and values.shape[1] in [3, 4] alpha = ones((values.shape[0], 1), 'f') values = concatenate((values[:, :3], alpha), 1) else: if len(values.shape) != 1: values = array([values], 'f') self.prop[prop] = values
def doit(self, atom1, atom2, angle, mov_atoms, returnVal=0): mol = atom1.top if mov_atoms is None: mov_atoms = mol.subTree(atom1, atom2, mol.allAtoms) assert len(mov_atoms) mov_coords = Numeric.array(mov_atoms.coords) lenCoords = len(mov_coords) x = Numeric.array(atom1.coords) y = Numeric.array(atom2.coords) rot = (angle * 3.14159/180.)%(2 * Numeric.pi) matrix = rotax(x, y, rot) _ones = Numeric.ones(lenCoords, 'f') _ones.shape = (lenCoords,1) mov_coords = Numeric.concatenate((mov_coords, _ones),1) newcoords = Numeric.dot(mov_coords, matrix) nc = newcoords[:,:3].astype('f') for i in range(lenCoords): at = mov_atoms[i] at._coords[at.conformation] = nc[i].tolist() event = EditAtomsEvent('coords', mov_atoms) self.vf.dispatchEvent(event) #have to return nc for setTorsionGC if returnVal: return nc
def non_redundant_set(d, threshold): """ returns an array consisting of entries having a minimum pairwise distance of 'threshold'. Based on Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417 """ # import random d = Numeric.array(d).astype(Float32) d = less(d, threshold) s = shape(d) d = Numeric.concatenate((reshape(range(s[0]),(-1,1)),d),1) ok = 1 while ok: nNeighbours = Numeric.sum(d)-1 if len(nNeighbours) <= 1: break maxx = max(nNeighbours[1:]) others = nonzero(equal(nNeighbours[1:], maxx))+1 candidate = random.choice(others) ok = nNeighbours[candidate] if ok: d = deleteRowAndColumn(d, candidate-1, candidate) #end while return d[:,0]
def castHmmDic(self, hmmDic, repete, hmmGap, key): """ Blow up hmmDic to the number of repetes of the profile used. Correct scores for possible deletions in the search sequence. @param hmmDic: dictionary from L{getHmmProfile} @type hmmDic: dict @param repete: repete information from L{align} @type repete: int @param hmmGap: information about gaps from L{align} @type hmmGap: [int] @param key: name of scoring method to adjust for gaps and repetes @type key: str @return: dictionary with information about the profile @rtype: dict """ s = hmmDic[key] for i in range(repete): mask = N.ones(len(s)) N.put(mask, hmmGap[i], 0) if i == 0: score = N.compress(mask, s, 0) if i > 0: score = N.concatenate((N.compress(mask, s, 0), score)) hmmDic[key] = score return hmmDic
def doit(self, atom1, atom2, angle, mov_atoms, returnVal=0): mol = atom1.top if mov_atoms is None: mov_atoms = mol.subTree(atom1, atom2, mol.allAtoms) assert len(mov_atoms) mov_coords = Numeric.array(mov_atoms.coords) lenCoords = len(mov_coords) x = Numeric.array(atom1.coords) y = Numeric.array(atom2.coords) rot = (angle * 3.14159 / 180.) % (2 * Numeric.pi) matrix = rotax(x, y, rot) _ones = Numeric.ones(lenCoords, 'f') _ones.shape = (lenCoords, 1) mov_coords = Numeric.concatenate((mov_coords, _ones), 1) newcoords = Numeric.dot(mov_coords, matrix) nc = newcoords[:, :3].astype('f') for i in range(lenCoords): at = mov_atoms[i] at._coords[at.conformation] = nc[i].tolist() event = EditAtomsEvent('coords', mov_atoms) self.vf.dispatchEvent(event) #have to return nc for setTorsionGC if returnVal: return nc
def castHmmDic( self, hmmDic, repete, hmmGap, key ): """ Blow up hmmDic to the number of repetes of the profile used. Correct scores for possible deletions in the search sequence. @param hmmDic: dictionary from L{getHmmProfile} @type hmmDic: dict @param repete: repete information from L{align} @type repete: int @param hmmGap: information about gaps from L{align} @type hmmGap: [int] @param key: name of scoring method to adjust for gaps and repetes @type key: str @return: dictionary with information about the profile @rtype: dict """ s = hmmDic[key] for i in range( repete ): mask = N.ones( len(s) ) N.put( mask, hmmGap[i], 0 ) if i == 0: score = N.compress( mask, s, 0 ) if i > 0: score = N.concatenate( ( N.compress( mask, s, 0 ), score ) ) hmmDic[key] = score return hmmDic
def doit(self, mobAtoms): """ mobAtoms: AtomSet that is being frozen. Assuming the AtomSet are from same molecule """ # fixme: need checking for mat (matrix) and mobAtoms geomContainer = mobAtoms[0].top.geomContainer mGeom = geomContainer.masterGeom mat = mGeom.rotation mat = Numeric.reshape(mat, (4, 4)) # update coords mobAtoms = mobAtoms.findType(Atom) coords = mobAtoms.coords hCoords = Numeric.concatenate((coords,Numeric.ones((len(coords),1),\ 'd')), 1) tCoords = Numeric.dot(hCoords, mat)[:, :3] tCoords = tCoords.tolist() mobAtoms.updateCoords(tCoords, 0) # overwritten the original coords # reset the rotation matrix of masterGeom identity = Numeric.identity(4, 'f').ravel() mGeom.SetRotation(Numeric.identity(4, 'f').ravel()) event = EditAtomsEvent('coords', mobAtoms) self.vf.dispatchEvent(event) mGeom.viewer.Redraw() return
def atom_array_of_part(part): "Return an Array of all atoms in the Part. Try to be linear time." res = [] for m in part.molecules: res.append( array(m.atlist) ) # concatenate might fail for chunks with exactly 1 atom -- fix later ####@@@@ return concatenate(res) ###k
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 getAppxCoef2d_pVals(self, arr2d, maxNumCoef): """Returns[:,j] the probability that coef. j and all subsequent coef. are equal to 0. Reference: Ott, pp.606. Use only the first k appx. coef. with pvals below some alpha. The significance of the coef. estimated by comparing the variance drop of the model2 with the variance of the model1, where: model 1: complete model with maxNumCoef coef. different from 0 model 2: reduced model with coef. in range (0,k) different from 0 null hypothesis (H0): coef. k,k+1,...,maxNumCoef are equal to 0 if H0 rejected (pval below some alpha (e.g. 0.05) -> there exist an important coef. among coef. k,k+1,...,maxNumCoef repeat the test for k=0,1,...maxNumCoef-1 """ assert len(arr2d.shape) == 2, "2d array expected" assert 0 < maxNumCoef <= self.k coefMax = self.getAppxCoef(arr2d, maxNumCoef) curveMax = self.getAppxCurve(coefMax) SSE1 = Numeric.add.reduce((arr2d-curveMax)**2,1) MSE1 = SSE1 / (arr2d.shape[1]-maxNumCoef) #print "SSE1[0], MSE1[0]",SSE1[0], MSE1[0] pvals = Numeric.zeros((arr2d.shape[0], maxNumCoef), Numeric.Float) for k in range(maxNumCoef): # test cofInd: [maxNum-1, maxNum-2, ..., minNum] #print "Keeping %i coeff" % (k) shpk = list(coefMax.shape) shpk[1] -= k coefk = Numeric.concatenate((coefMax[:,:k], Numeric.zeros((shpk), Numeric.Float)),1) curvek = self.getAppxCurve(coefk) SSE2 = Numeric.add.reduce((arr2d-curvek)**2,1) MSdrop =(SSE2-SSE1) / (maxNumCoef-k) F = MSdrop / MSE1 #2007-10-11: F -> F.filled(???) pvals[:,k] = scipy.stats.fprob((maxNumCoef-k), arr2d.shape[1]-maxNumCoef, F.filled(ApproxOrthPolyBasis._F_fillValue)) return pvals
def SetMaterial(self, values, prop=1, tagModified=True): """Set the materials WARNING: when back face colors are set, two sided lighting has to be enabled we set RGB values for all properties except for shininess and opacity If an alpha value are specified they will be ignored Since IndexedGeomDSPL requires alpha values for all properties we set them automatically to 1.0 for all properties except for diffuse. The alpha channel of the diffuse component will be set later in fixOpacity which should be called after all properties of the material have been updated. """ if tagModified: self._modified = True if prop is None: prop = self.diff elif type(prop) is types.StringType: prop = getattr(self, prop) assert prop in (0,1,2,3,4,5) values = array( values, 'f' ) if prop < self.shini: assert len(values.shape)==2 and values.shape[1] in [3,4] alpha = ones( (values.shape[0], 1), 'f' ) values = concatenate( (values[:,:3], alpha), 1 ) else: if len(values.shape) != 1: values = array([values], 'f' ) self.prop[prop] = values
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 doit(self,mobAtoms): """ mobAtoms: AtomSet that is being frozen. Assuming the AtomSet are from same molecule """ # fixme: need checking for mat (matrix) and mobAtoms geomContainer = mobAtoms[0].top.geomContainer mGeom = geomContainer.masterGeom mat = mGeom.rotation mat = Numeric.reshape(mat, (4,4)) # update coords mobAtoms = mobAtoms.findType(Atom) coords = mobAtoms.coords hCoords = Numeric.concatenate((coords,Numeric.ones((len(coords),1),\ 'd')), 1) tCoords = Numeric.dot(hCoords, mat)[:,:3] tCoords = tCoords.tolist() mobAtoms.updateCoords(tCoords, 0) # overwritten the original coords # reset the rotation matrix of masterGeom identity = Numeric.identity(4,'f').ravel() mGeom.SetRotation(Numeric.identity(4,'f').ravel() ) event = EditAtomsEvent('coords', mobAtoms) self.vf.dispatchEvent(event) mGeom.viewer.Redraw() return
def addFirstLastPoints(self): last = self.smooth.shape[1] ar2 = self.interpolateSmoothArray(last-2, last-1, self.chords) self.smooth = Numeric.concatenate((self.smooth[:, :-2, :], ar2, self.smooth[:, -1:, :] ), 1)
def nonRedundantSet(d, threshold, distanceMatrix = 1): """ returns an array consisting of entries having a maximum similarity (or distance) of 'threshold'. distanceMatrix <> None means matrix elemens are similarities. Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417 gives somehow weired results. """ import whrandom #@UnresolvedImport d = Numeric.array(d).astype(Float32) if not distanceMatrix: d = less(d, threshold) else: d = greater(d, threshold) s = shape(d) d = Numeric.concatenate((reshape(range(s[0]),(-1,1)),d),1) ok = 1 while ok: nNeighbours = Numeric.sum(d) if len(nNeighbours) <= 1: break maxx = max(nNeighbours[1:]) others = Numeric.nonzero(equal(nNeighbours[1:], maxx))+1 candidate = whrandom.choice(others) ok = nNeighbours[candidate] if ok: d = deleteRowAndColumn(d, candidate-1, candidate) # end while return d[:,0]
def nonRedundantSet(d, threshold, distanceMatrix=1): """ returns an array consisting of entries having a maximum similarity (or distance) of 'threshold'. distanceMatrix <> None means matrix elemens are similarities. Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417 gives somehow weired results. """ import whrandom #@UnresolvedImport d = Numeric.array(d).astype(Float32) if not distanceMatrix: d = less(d, threshold) else: d = greater(d, threshold) s = shape(d) d = Numeric.concatenate((reshape(range(s[0]), (-1, 1)), d), 1) ok = 1 while ok: nNeighbours = Numeric.sum(d) if len(nNeighbours) <= 1: break maxx = max(nNeighbours[1:]) others = Numeric.nonzero(equal(nNeighbours[1:], maxx)) + 1 candidate = whrandom.choice(others) ok = nNeighbours[candidate] if ok: d = deleteRowAndColumn(d, candidate - 1, candidate) # end while return d[:, 0]
def non_redundant_set(d, threshold): """ returns an array consisting of entries having a minimum pairwise distance of 'threshold'. Based on Ref.: Hobohm et al. (1992). Prot. Sci. 1, 409-417 """ # import random d = Numeric.array(d).astype(Float32) d = less(d, threshold) s = shape(d) d = Numeric.concatenate((reshape(range(s[0]), (-1, 1)), d), 1) ok = 1 while ok: nNeighbours = Numeric.sum(d) - 1 if len(nNeighbours) <= 1: break maxx = max(nNeighbours[1:]) others = nonzero(equal(nNeighbours[1:], maxx)) + 1 candidate = random.choice(others) ok = nNeighbours[candidate] if ok: d = deleteRowAndColumn(d, candidate - 1, candidate) #end while return d[:, 0]
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 __parseBiomt(self, pdbFile, firstLine): """ """ line = firstLine biomtDict = {} moleculeNum = -1 while line[0] == 'REMARK' and line[1].startswith(' 350'): # 5 = len(' 350 ') biomtLine = line[1][5:].lstrip() if biomtLine.startswith('BIOMOLECULE:'): # start a new molecule if moleculeNum != -1: # lets update the dictionary with what we've got biomtDict[moleculeNum] = (targetChains, rtList) #12 = len('BIOMOLECULE:') moleculeNum = int(biomtLine[12:].strip()) targetChains = [] rotation = [] translation = [] rtList = [] matrixLine = 0 if biomtLine.startswith('APPLY THE FOLLOWING TO CHAINS:'): # parse targeted chains, we assume this comes after BIOMOLECULE line # 30 = len('APPLY THE FOLLOWING TO CHAINS:') targetChains.extend(c.strip() for c in biomtLine[30:].split(',')) if biomtLine.startswith('AND CHAINS:'): # 11 = len('AND CHAINS:') targetChains.extend(c.strip() for c in biomtLine[11:].split(',')) if biomtLine.startswith('BIOMT'): # parse rotate-translate matri{x/ces}, we assume this comes after BIOMOLECULE line matrixLine += 1 # 6 = len('BIOMT#') rawCoords = biomtLine[6:].split() rotation.append([float(x) for x in rawCoords[1:4]]) translation.append(float(rawCoords[4])) if matrixLine % 3 == 0: rotation = N.array(rotation) translation = N.transpose([translation]) rotation = N.concatenate((rotation, translation), axis=1) rtList.append(N.array(rotation)) ## rtList.append((rotation,translation)) rotation = [] translation = [] try: line = pdbFile.readLine() except ValueError, what: self.log.add('Warning: Error parsing line %i of %s' % (i, T.stripFilename(fname))) self.log.add('\tError: ' + str(what)) continue
def make_homogeneous_coord_rows(v): """Convert vertex (or row-wise vertices) into homogeneous coordinates.""" v = Numeric.array(v,typecode=Numeric.Float) # copy if len(v.shape) == 1: v = v[Numeric.NewAxis,:] # make a rank-2 array if v.shape[1] == 3: ws = Numeric.ones((v.shape[0],1),typecode=Numeric.Float) v = Numeric.concatenate( (v,ws), axis=1 ) return v
def getCoords(self, c): c = Numeric.array(c) x1 = c - (self.offset, 0, 0) x2 = c + (self.offset, 0, 0) y1 = c - (0, self.offset, 0) y2 = c + (0, self.offset, 0) z1 = c - (0, 0, self.offset) z2 = c + (0, 0, self.offset) return Numeric.concatenate((x1, x2, y1, y2, z1, z2))
def __random_matrix(self): """ Random rotation matrix. @return: 4 x 4 array of float, random rotation and translation matrix @rtype: array """ r = ma.randomRotation() ## r = N.array([[1,0,0],[0,1,0],[0,0,1]],'f') t = self.__random_translation() ## create 3 x 4 matrix: 0:3, 0:3 contains rot; 3,0:3 contains trans result = N.concatenate((r, N.transpose([t.tolist()])), 1) ## make it square result = N.concatenate((result, N.array([[0, 0, 0, 1]], N.Float32)), 0) return result
def __random_matrix( self ): """ Random rotation matrix. @return: 4 x 4 array of float, random rotation and translation matrix @rtype: array """ r = ma.randomRotation() ## r = N.array([[1,0,0],[0,1,0],[0,0,1]],'f') t = self.__random_translation() ## create 3 x 4 matrix: 0:3, 0:3 contains rot; 3,0:3 contains trans result = N.concatenate( (r, N.transpose( [ t.tolist() ] )), 1) ## make it square result = N.concatenate( (result, N.array([[0,0,0,1]], N.Float32)), 0 ) return result
def rtTuple2matrix( self, r, t): """ Put rotation and translation matrix into single 4x4 matrix. @param r: rotation matric, array 3x3 of float @type r: array @param t: translation vector, array 1x3 of float @type t: vector @return: rotation/translation matrix, array 4x4 of float @rtype: array """ ## create 3 x 4 matrix: 0:3, 0:3 contains rot; 3,0:3 contains trans result = N.concatenate( (r, N.transpose( [ t.tolist() ] )), 1) ## make it square result = N.concatenate( (result, N.array([[0,0,0,1]],N.Float32)), 0) return result.astype(N.Float32)
def __parseBiomt( self, pdbFile, firstLine): """ """ line = firstLine biomtDict = {} moleculeNum = -1 while line[0] == 'REMARK' and line[1].startswith(' 350'): # 5 = len(' 350 ') biomtLine = line[1][5:].lstrip() if biomtLine.startswith('BIOMOLECULE:'): # start a new molecule if moleculeNum != -1: # lets update the dictionary with what we've got biomtDict[moleculeNum] = (targetChains,rtList) #12 = len('BIOMOLECULE:') moleculeNum = int(biomtLine[12:].strip()) targetChains = [] rotation = [] translation = [] rtList = [] matrixLine = 0 if biomtLine.startswith('APPLY THE FOLLOWING TO CHAINS:'): # parse targeted chains, we assume this comes after BIOMOLECULE line # 30 = len('APPLY THE FOLLOWING TO CHAINS:') targetChains.extend(c.strip() for c in biomtLine[30:].split(',')) if biomtLine.startswith('AND CHAINS:'): # 11 = len('AND CHAINS:') targetChains.extend(c.strip() for c in biomtLine[11:].split(',')) if biomtLine.startswith('BIOMT'): # parse rotate-translate matri{x/ces}, we assume this comes after BIOMOLECULE line matrixLine += 1 # 6 = len('BIOMT#') rawCoords = biomtLine[6:].split() rotation.append([float(x) for x in rawCoords[1:4]]) translation.append(float(rawCoords[4])) if matrixLine % 3 == 0: rotation = N.array( rotation ) translation = N.transpose( [ translation ] ) rotation = N.concatenate( (rotation, translation), axis=1 ) rtList.append(N.array(rotation)) ## rtList.append((rotation,translation)) rotation = [] translation = [] try: line = pdbFile.readLine() except ValueError, what: self.log.add('Warning: Error parsing line %i of %s' % (i, T.stripFilename( fname )) ) self.log.add('\tError: '+str(what) ) continue
def rmsInterface( self, ref, cutoff=4.5, fit=1 ): """ Rmsd between this and reference interface. The interface is defined as any residue that has an atom which is within the distance given by |cutoff| from its partner. @param ref: reference complex @type ref: Complex @param cutoff: atom distance cutoff for interface residue definition (default: 4.5) @type cutoff: float @param fit: least-squares fit before calculating the rms (default: 1) @type fit: 1|0 @return: interface rmad @rtype: float """ ## casting this = self if not ref.rec_model.equals( self.rec_model )[1] \ or not ref.lig_model.equals( self.lig_model )[1]: m_rec, m_rec_ref, m_lig, m_lig_ref = self.equalAtoms( ref ) this = self.compress( m_rec, m_lig ) ref = ref.compress( m_rec_ref, m_lig_ref ) ## determine interface contacts = ref.resContacts( cutoff ) if_rec = ref.rec_model.res2atomMask( N.sum( contacts, 1 ) ) if_lig = ref.lig_model.res2atomMask( N.sum( contacts, 0 ) ) mask_interface = N.concatenate( (if_rec, if_lig) ) mask_heavy = N.concatenate( (ref.rec().maskHeavy(), ref.lig_model.maskHeavy()) ) mask_interface = mask_interface * mask_heavy ## rms ref_model = ref.model() this_model= this.model() return ref_model.rms( this_model, mask_interface, fit=fit)
def convertChainIdsCter( self, model, chains ): """ Convert normal chain ids to chain ids considering chain breaks. """ if len(chains) == 0: return chains ## fetch last atom of given chains index = N.concatenate( (model.chainIndex(), [len(model)]) ) i = N.take( index, N.array( chains ) + 1 ) - 1 ## convert back to chain indices but this time including chain breaks return model.atom2chainIndices( i, breaks=1 )
def __mul__(self, mat): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Apply the transformation matrix to the vertices""" assert self.array.shape[-1] == 3 self.Flatten() one = Numeric.ones((self.array.shape[0], 1), viewerConst.FPRECISION) c = Numeric.concatenate((self.array, one), 1) self.UnFlatten() return Numeric.dot(c, Numeric.transpose(mat))[:, :3]
def __mul__(self, mat): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Apply the transformation matrix to the vertices""" assert self.array.shape[-1]==3 self.Flatten() one = Numeric.ones( (self.array.shape[0], 1), viewerConst.FPRECISION ) c = Numeric.concatenate( (self.array, one), 1 ) self.UnFlatten() return Numeric.dot( c, Numeric.transpose(mat) )[:, :3]
def __init__(self, coords=None, radii=None, atnames=None, filename=None, name='msms', maxnat=0, surfflags=None, hdflags=None): """MSMS <- MSMS(coords=None, radii=None, atnames=None, filename=None, name='msms', maxnat=0, surfflags=None, hdflags=None) This class can be instantiated int a number of ways: - no arguments: m = MSMS() - with an array of Nx4 coordinates: m = MSMS(coords = c) - with an array of Nx3 centers and an array of radii: m = MSMS(coords = c, radii = r) - by specifying a filename from wich to load the xyzr and possibly names m = MSMS(filename) additional parameters are: name: string to name that surface atnames: array of N atom names maxnat: maximum number of atoms in the molecule. This number needs to be larger than largest number of atoms that surface will ever have. """ if filename: c, atnames, surfflags, hdflags = readxyzr(filename) nat = len(c) if name: self.surface_name = name else: self.surface_name = os.basename(filename) else: self.surface_name = name if coords: self.coords = Numeric.array(coords).astype('f') assert len(self.coords.shape)==2, "coordinates array of bad shape" if self.coords.shape[1] == 3: self.radii = Numeric.array(radii).astype('f') self.radii.shape = (self.radii.shape[0],1) c = Numeric.concatenate( (self.coords, self.radii), 1 ) else: assert self.coords.shape[1]==4, "coordinates array of bad shape" c = self.coords if not c.flags.contiguous or c.dtype.char!='f': c = Numeric.array(c).astype('f') nat = len(c) else: c=None nat=0 if surfflags: assert len(surfflags)==len(c) if hdflags: assert len(hdflags)==len(c) msms.MOLSRF.__init__(self, name=name, coords=c, nat=nat, maxat=maxnat, names=atnames, surfflags=surfflags, hdflags=hdflags) self.geometry = None
def AddValues(self, values): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Add values""" if values is None: return if len(self.array) == 0: self.SetValues(values) self.fixedShape = self.ashape[1:] else: self.array = Numeric.concatenate( (self.array, self._ShapeValues(values))) self.ashape = self.array.shape
def __init__(self, crv1, crv2): if not isinstance(crv1, Crv.Crv): raise NURBSError, 'Parameter crv1 not derived from Crv class!' if not isinstance(crv2, Crv.Crv): raise NURBSError, 'Parameter crv2 not derived from Crv class!' # ensure both curves have a common degree d = max(crv1.degree, crv2.degree) crv1.degelev(d - crv1.degree) crv2.degelev(d - crv2.degree) # merge the knot vectors, to obtain a common knot vector k1 = crv1.uknots k2 = crv2.uknots ku = [] for item in k1: if not numerix.sometrue(numerix.equal(k2, item)): if item not in ku: ku.append(item) for item in k2: if not numerix.sometrue(numerix.equal(k1, item)): if item not in ku: ku.append(item) ku = numerix.sort(numerix.asarray(ku, numerix.Float)) n = ku.shape[0] ka = numerix.array([], numerix.Float) kb = numerix.array([], numerix.Float) for i in range(0, n): i1 = numerix.compress(numerix.equal(k1, ku[i]), k1).shape[0] i2 = numerix.compress(numerix.equal(k2, ku[i]), k2).shape[0] m = max(i1, i2) ka = numerix.concatenate((ka, ku[i] * numerix.ones( (m - i1, ), numerix.Float))) kb = numerix.concatenate((kb, ku[i] * numerix.ones( (m - i2, ), numerix.Float))) crv1.kntins(ka) crv2.kntins(kb) coefs = numerix.zeros((4, crv1.cntrl.shape[1], 2), numerix.Float) coefs[:, :, 0] = crv1.cntrl coefs[:, :, 1] = crv2.cntrl Srf.__init__(self, coefs, crv1.uknots, [0., 0., 1., 1.])
def checkRamp(self, ramp): """Method to check the given ramp. If only rgb values given then 1 is added for the alpha values. """ #if no alpha values, add 1's if len(ramp[0]) == 4: return ramp if len(ramp[0]) == 3: lenRgb = len(ramp) _ones = Numeric.ones(lenRgb, 'f') _ones.shape = (lenRgb, 1) ramp = Numeric.concatenate((Numeric.array(ramp), _ones),1) return ramp.tolist()
def AddValues(self, values): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Add values""" if values is None: return if len(self.array)==0: self.SetValues(values) self.fixedShape = self.ashape[1:] else: self.array = Numeric.concatenate( (self.array, self._ShapeValues(values)) ) self.ashape = self.array.shape
def checkRamp(self, ramp): """Method to check the given ramp. If only rgb values given then 1 is added for the alpha values. """ #if no alpha values, add 1's if len(ramp[0]) == 4: return ramp if len(ramp[0]) == 3: lenRgb = len(ramp) _ones = Numeric.ones(lenRgb, 'f') _ones.shape = (lenRgb, 1) ramp = Numeric.concatenate((Numeric.array(ramp), _ones), 1) return ramp.tolist()
def __init__(self, refCoords, tolist=1): """refCoords is an nx3 list of n points resultCoords is set up and maintained as homogeneous coords if tolist then return the result coords as a python list """ try: self.refCoords = Numeric.array(Numeric.concatenate( (refCoords, Numeric.ones( (len(refCoords), 1), 'f')), 1)) except TypeError: raise ValueError, "invalid input array" self.resultCoords = self.refCoords self.tolist = tolist
def getMatrices(self): outMatrices=[] indicesComp = range(len(self.inMatrices)) if self.indices[0] == []: self.indices[0] = indicesComp fullList = [] else: fullList = Numeric.concatenate(self.indices) map( indicesComp.remove, fullList ) self.indices.insert(0,indicesComp) for i in range(len(self.indices)): outMatrices.append(Numeric.take(self.inMatrices, self.indices[i])) return outMatrices
def cat(a, b): """ concatenate two arrays (the Numeric Python version is a mess) """ #bruce comment 050518: these boolean tests look like bugs! # I bet they should be testing the number of entries being 0, or so. # So I added some debug code to warn us if this happens. if not a.any(): if (_DEBUG_QUATS or debug_flags.atom_debug): print "_DEBUG_QUATS: cat(a, b) with false a -- is it right?", a return b if not b.any(): if (_DEBUG_QUATS or debug_flags.atom_debug): print "_DEBUG_QUATS: cat(a, b) with false b -- is it right?", b return a r1 = Numeric.shape(a) r2 = Numeric.shape(b) if len(r1) == len(r2): return Numeric.concatenate((a, b)) if len(r1) < len(r2): return Numeric.concatenate((Numeric.reshape(a,(1,) + r1), b)) else: return Numeric.concatenate((a, Numeric.reshape(b,(1,) + r2)))
def __init__(self, crv1, crv2): if not isinstance(crv1, Crv.Crv): raise NURBSError, 'Parameter crv1 not derived from Crv class!' if not isinstance(crv2, Crv.Crv): raise NURBSError, 'Parameter crv2 not derived from Crv class!' # ensure both curves have a common degree d = max(crv1.degree, crv2.degree) crv1.degelev(d - crv1.degree) crv2.degelev(d - crv2.degree) # merge the knot vectors, to obtain a common knot vector k1 = crv1.uknots k2 = crv2.uknots ku = [] for item in k1: if not numerix.sometrue(numerix.equal(k2, item)): if item not in ku: ku.append(item) for item in k2: if not numerix.sometrue(numerix.equal(k1, item)): if item not in ku: ku.append(item) ku = numerix.sort(numerix.asarray(ku, numerix.Float)) n = ku.shape[0] ka = numerix.array([], numerix.Float) kb = numerix.array([], numerix.Float) for i in range(0, n): i1 = numerix.compress(numerix.equal(k1, ku[i]), k1).shape[0] i2 = numerix.compress(numerix.equal(k2, ku[i]), k2).shape[0] m = max(i1, i2) ka = numerix.concatenate((ka , ku[i] * numerix.ones((m - i1,), numerix.Float))) kb = numerix.concatenate((kb , ku[i] * numerix.ones((m - i2,), numerix.Float))) crv1.kntins(ka) crv2.kntins(kb) coefs = numerix.zeros((4, crv1.cntrl.shape[1], 2), numerix.Float) coefs[:,:,0] = crv1.cntrl coefs[:,:,1] = crv2.cntrl Srf.__init__(self, coefs, crv1.uknots, [0., 0., 1., 1.])
def __init__(self, refCoords, tolist=1): """refCoords is an nx3 list of n points resultCoords is set up and maintained as homogeneous coords if tolist then return the result coords as a python list """ try: self.refCoords = Numeric.array( Numeric.concatenate( (refCoords, Numeric.ones((len(refCoords), 1), 'f')), 1)) except TypeError: raise ValueError, "invalid input array" self.resultCoords = self.refCoords self.tolist = tolist
def GetMatrixInverse(self, root=None, instance=None): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Returns the inverse of the matrix used to transform this object""" if root is None: root = self.viewer.rootObject m = self.GetMatrix(root, instance) m = Numeric.reshape(Numeric.transpose(m), (16,)).astype('f') rot, transl, scale = self.Decompose4x4(m) sc = Numeric.concatenate((Numeric.reshape(scale,(3,1)), [[1]])) n = Numeric.reshape(rot, (4,4))/sc tr = Numeric.dot(n, (transl[0], transl[1], transl[2],1) ) n[:3,3] = -tr[:3].astype('f') return n