def test_IcmCad( self ): """IcmCad test""" from Biskit import PDBModel if self.local: print 'Loading PDB...' self.f = T.testRoot() + '/lig/1A19.pdb' self.m1 = PDBModel(self.f) self.m1 = self.m1.compress( self.m1.maskProtein() ) self.ms = [] self.lig_traj = T.load( T.testRoot() + '/lig_pcr_00/traj.dat' ) for m in self.lig_traj[:3]: m = m.compress( m.maskProtein() ) self.ms.append(m) if self.local: print 'Starting ICM' self.x = IcmCad( self.m1, self.ms, debug=self.DEBUG, verbose=self.local ) if self.local: print 'Running' self.r = self.x.run() if self.local: print "Result: ", self.r self.assertEqual( self.r, [8.8603529999999999, 9.0315890000000003, 8.5055429999999994] )
def load_locked(self, fname): """ wait with unpickling until another Entropist has finished. @param fname: file name @type fname: str @return: trajectroy @rtype: Trajectroy """ flock = fname + '__locked' while os.path.exists(flock): if self.verbose: self.log.write('~') time.sleep(random.random() * 10) if self.verbose: self.log.add('') try: f = open(flock, 'w') f.write('1') f.close() r = t.load(fname) finally: t.tryRemove(flock) return r
def test_reduce( self ): """Reduce test""" if self.local: self.log.add('Loading PDB...') self.m1 = PDBModel( T.testRoot( 'lig/1A19_dry.model' ) ) self.m2 = T.load( T.testRoot( 'com/ref.complex' ) ) self.m2 = self.m2.model() if self.local: self.log.add('Starting Reduce') self.x = Reduce( self.m1, debug=self.DEBUG, verbose=self.local ) if self.local: self.log.add( 'Running') self.r = self.x.run() if self.local: self.log.add("Result: ") self.log.add(self.r.report(prnt=False)) if self.local: self.log.add('Reduce protein complex') self.x = Reduce( self.m2, debug=self.DEBUG, verbose=self.local, autocap=True ) self.r2 = self.x.run()
def test_ComplexEvolving(self): """Dock.ComplexEvolving test""" import time from Biskit.Dock import ComplexEvolving c = t.load( t.testRoot() + '/com/ref.complex' ) self.ce= ComplexEvolving( c.rec_model, c.lig(), c, info={'comment':'test'} ) time.sleep( 2 ) lig = self.ce.lig().transform( MU.randomRotation(), [0,0,0] ) self.ce2 = ComplexEvolving( self.ce.rec_model, lig, self.ce, info={'comment':'test2'}) if self.local: print '\nGenerations: ' for x in self.ce2: print x['date'] print 'Comments: ', self.ce2.valuesOf('comment') self.assertEqual( self.ce2.valuesOf('comment'), [None, 'test', 'test2'])
def test_Analyzer( self): """Dock.Analyzer test """ from Biskit import Trajectory from Biskit.Dock import ComplexList ## create a minimal 1-frame receptor trajectory from a pdb file self.t_rec = Trajectory( [t.testRoot()+'/rec/1A2P.pdb'], verbose=self.local) t.dump( self.t_rec, self.f_out ) ## load a complex list cl = t.load( t.testRoot() + '/dock/hex/complexes.cl') self.a= Analyzer( rec = self.f_out, lig = t.testRoot()+'/lig_pcr_00/traj.dat', ref = t.testRoot()+'/com/ref.complex', verbose = self.local) ## shuffle this list five times shuff_lst = self.a.shuffledLists( 5, range(8) ) ## create two random contact matrices rand_mat = self.a.random_contacts( cl[0].atomContacts(), 2 ) self.assertEqual( N0.shape(rand_mat[1]), (1075, 876) )
def test_reduce(self): """Reduce test""" if self.local: self.log.add('Loading PDB...') self.m1 = PDBModel(T.testRoot('lig/1A19_dry.model')) self.m2 = T.load(T.testRoot('com/ref.complex')) self.m2 = self.m2.model() if self.local: self.log.add('Starting Reduce') self.x = Reduce(self.m1, debug=self.DEBUG, verbose=self.local) if self.local: self.log.add('Running') self.r = self.x.run() if self.local: self.log.add("Result: ") self.log.add(self.r.report(prnt=False)) if self.local: self.log.add('Reduce protein complex') self.x = Reduce(self.m2, debug=self.DEBUG, verbose=self.local, autocap=True) self.r2 = self.x.run()
def loadTraj( self, fname, outliers=[], refname=None ): """ Load trajectory from file. @param fname: path to trajectory @type fname: str @param outliers: Identify outlier trajectories (default: [], identify) @type outliers: [int] OR [] @param refname: name of reference (efault: None) @type refname: str @return: t, outliers, members @rtype: trajectoty, [int], [int] """ self.log.add('Loading ' + fname ) t = T.load( fname ) t.ref.addChainId() t = t.compressAtoms( t.ref.maskProtein() ) outliers = self.getOutliers( t, outliers ) if refname: self.dumpMissing( t.ref, refname ) members = None if not self.all: members = self.dumpMembers( t, self.rec ) return t, outliers, members
def loadResContacts( self ): """ Uncompress residue contact matrix if necessary. @return: dict with contact matrix and parameters OR None @rtype: dict OR None """ ## Backwards compatibility if self.contacts != None and type( self.contacts ) == str: self.contacts = t.load( self.contacts ) EHandler.warning("loading old-style pickled contacts.") return self.contacts ## New, uncompression from list of indices into raveled array if self.contacts != None and \ len( N.shape( self.contacts['result'])) == 1: try: lenRec, lenLig = self.contacts['shape'] except: EHandler.warning("uncompressing contacts without shape") lenRec = self.rec().lenResidues() lenLig = self.lig().lenResidues() m = N.zeros( lenRec * lenLig ) N.put( m, self.contacts['result'], 1 ) self.contacts['result'] = N.reshape( m, (lenRec, lenLig) ) return self.contacts
def test_IcmCad(self): """IcmCad test""" from Biskit import PDBModel if self.local: print 'Loading PDB...' self.f = T.testRoot() + '/lig/1A19.pdb' self.m1 = PDBModel(self.f) self.m1 = self.m1.compress(self.m1.maskProtein()) self.ms = [] self.lig_traj = T.load(T.testRoot() + '/lig_pcr_00/traj.dat') for m in self.lig_traj[:3]: m = m.compress(m.maskProtein()) self.ms.append(m) if self.local: print 'Starting ICM' self.x = IcmCad(self.m1, self.ms, debug=self.DEBUG, verbose=self.local) if self.local: print 'Running' self.r = self.x.run() if self.local: print "Result: ", self.r self.assertEqual( self.r, [8.8603529999999999, 9.0315890000000003, 8.5055429999999994])
def test_ComplexEvolvingList(self): """Dock.ComplexEvolvingList test""" import Biskit.tools as t from Biskit.Dock import ComplexEvolving from Biskit.Dock import ComplexEvolvingList ## original complex cl = t.load( t.testRoot() + "/dock/hex/complexes.cl" ) ## first evolution step c = ComplexEvolving( cl[0].rec(), cl[0].lig(), cl[0], info={'comment':'test1'}) ## second evolution step c = ComplexEvolving( c.rec(), c.lig(), c, info={'comment':'test2'}) ## create an evolving complex list cl = ComplexEvolvingList( [c, c] ) if self.local: ## last version of all complexes in list print cl.valuesOf('comment') ## version 1 print cl.valuesOf('comment', version=1) ## the first complex in the list print cl[0].valuesOf('comment') globals().update( locals() ) self.assertEqual( (cl.valuesOf('comment'), cl[0].valuesOf('comment')), (['test2', 'test2'], [None, 'test1', 'test2']) )
def loadTraj(self, fname, outliers=[], refname=None): """ Load trajectory from file. @param fname: path to trajectory @type fname: str @param outliers: Identify outlier trajectories (default: [], identify) @type outliers: [int] OR [] @param refname: name of reference (efault: None) @type refname: str @return: t, outliers, members @rtype: trajectoty, [int], [int] """ self.log.add('Loading ' + fname) t = T.load(fname) t.ref.addChainId() t = t.compressAtoms(t.ref.maskProtein()) outliers = self.getOutliers(t, outliers) if refname: self.dumpMissing(t.ref, refname) members = None if not self.all: members = self.dumpMembers(t, self.rec) return t, outliers, members
def load_locked( self, fname ): """ wait with unpickling until another Entropist has finished. @param fname: file name @type fname: str @return: trajectroy @rtype: Trajectroy """ flock = fname + '__locked' while os.path.exists( flock ): if self.verbose: self.log.write('~') time.sleep( random.random() * 10 ) if self.verbose: self.log.add('') try: f = open( flock, 'w' ) f.write('1') f.close() r = t.load(fname) finally: t.tryRemove( flock ) return r
def test_ComplexEvolving(self): """Dock.ComplexEvolving test""" import time from Biskit.Dock import ComplexEvolving c = t.load(t.testRoot() + '/com/ref.complex') self.ce = ComplexEvolving(c.rec_model, c.lig(), c, info={'comment': 'test'}) time.sleep(2) lig = self.ce.lig().transform(MU.randomRotation(), [0, 0, 0]) self.ce2 = ComplexEvolving(self.ce.rec_model, lig, self.ce, info={'comment': 'test2'}) if self.local: print '\nGenerations: ' for x in self.ce2: print x['date'] print 'Comments: ', self.ce2.valuesOf('comment') self.assertEqual(self.ce2.valuesOf('comment'), [None, 'test', 'test2'])
def dry_or_wet_run(self, run=True): """ """ import time, os import os.path ligDic = t.load(t.testRoot() + '/multidock/lig/1A19_models.dic') ## in the test root the directories "multidock/rec" and ## "multidock/com" are symbolic links from "dock/rec" and ## "dock/com". If this is a fleshly checked out project ## they will not exist, so we will have to create them. rec_dir = t.testRoot() + '/dock/rec' com_dir = t.testRoot() + '/dock/com' if not os.path.exists(rec_dir): ## remove old invalid links if os.path.lexists(rec_dir): os.unlink(rec_dir) os.symlink(t.testRoot() + '/dock/rec', rec_dir) if not os.path.exists(com_dir): ## remove old invalid links if os.path.lexists(com_dir): os.unlink(com_dir) os.symlink(t.testRoot() + '/dock/com', com_dir) recDic = t.load(t.testRoot() + '/dock/rec/1A2P_model.dic') self.d = Docker(recDic, ligDic, out=self.out_folder, verbose=self.local) # dock rec 1 vs. lig 2 on localhost fmac1, fout = self.d.createHexInp(1, 2) if run: self.d.runHex(fmac1, log=1, ncpu=2, host='localhost') self.d.waitForLastHex() ## dock receptor 1 vs. ligand one on remote host # fmac2, fout2= d.createHexInp( 1, 1 ) # d.runHex( fmac2, log=0, ncpu=2, host='remote_host_name' ) if self.local: print "ALL jobs submitted."
def dry_or_wet_run( self, run=True ): """ """ import time, os import os.path ligDic = t.load( t.testRoot() + '/multidock/lig/1A19_models.dic' ) ## in the test root the directories "multidock/rec" and ## "multidock/com" are symbolic links from "dock/rec" and ## "dock/com". If this is a fleshly checked out project ## they will not exist, so we will have to create them. rec_dir = t.testRoot() + '/dock/rec' com_dir = t.testRoot() + '/dock/com' if not os.path.exists( rec_dir ): ## remove old invalid links if os.path.lexists( rec_dir ): os.unlink( rec_dir ) os.symlink( t.testRoot() + '/dock/rec', rec_dir ) if not os.path.exists( com_dir ): ## remove old invalid links if os.path.lexists( com_dir ): os.unlink( com_dir ) os.symlink( t.testRoot() + '/dock/com', com_dir ) recDic = t.load( t.testRoot() + '/dock/rec/1A2P_model.dic' ) self.d = Docker( recDic, ligDic, out=self.out_folder, verbose=self.local ) # dock rec 1 vs. lig 2 on localhost fmac1, fout = self.d.createHexInp( 1, 2 ) if run: self.d.runHex( fmac1, log=1, ncpu=2, host='localhost' ) self.d.waitForLastHex() ## dock receptor 1 vs. ligand one on remote host # fmac2, fout2= d.createHexInp( 1, 1 ) # d.runHex( fmac2, log=0, ncpu=2, host='remote_host_name' ) if self.local: print "ALL jobs submitted."
def test_tmalignTransform(self): """TMAlign.applyTransformation test""" m = T.load(T.testRoot('tmalign/1huy_citrine.model')) ref = T.load(T.testRoot('tmalign/1zgp_dsred_dimer.model')) ref = ref.takeChains([0]) tm = TMAlign(m, ref) tm.run() self.maligned = tm.applyTransformation() diff = self.maligned.centerOfMass() - ref.centerOfMass() if self.VERBOSITY > 2 or self.local: print 'center of mass deviation: \n%r' % diff self.maligned.concat(ref).plot() self.assert_(N.all(N.absolute(diff) < 1), 'superposition failed: \n%r' % diff)
def test_tmalignTransform( self ): """TMAlign.applyTransformation test""" m = T.load( T.testRoot( 'tmalign/1huy_citrine.model' ) ) ref = T.load( T.testRoot( 'tmalign/1zgp_dsred_dimer.model' ) ) ref = ref.takeChains( [0] ) tm = TMAlign( m, ref ) tm.run() self.maligned = tm.applyTransformation() diff = self.maligned.centerOfMass() - ref.centerOfMass() if self.VERBOSITY > 2 or self.local: print 'center of mass deviation: \n%r' % diff self.maligned.concat( ref ).plot() self.assert_( N.all( N.absolute(diff) < 1 ), 'superposition failed: \n%r' % diff)
def prepare(self): import Biskit.tools as T self.cl = T.load(T.testRoot() + '/dock/hex/complexes.cl') self.score = self.cl.valuesOf('hex_eshape') ## ## convert hex energies into positive score ## self.score = N.array(self.cl.valuesOf('hex_etotal')) * -1 ## define complexes with less the 6 A rmsd from reference as positives self.hits = N.less(self.cl.valuesOf('rms'), 6)
def test_hexParser(self): """Dock.hexParser test""" rec_dic = t.load( t.testRoot() + "/dock/rec/1A2P_model.dic" ) lig_dic = t.load( t.testRoot() + "/dock/lig/1A19_model.dic" ) self.h = HexParser( t.testRoot() + "/dock/hex/1A2P-1A19_hex.out", rec_dic, lig_dic) c_lst = self.h.parseHex() if self.local: print c_lst[1].info globals().update( locals() ) self.assertEqual( c_lst[1].info.keys(), ['soln', 'rms', 'hex_clst', 'hex_eshape', 'model2', 'model1', 'hex_etotal', 'date'] )
def prepare( self ): import Biskit.tools as T self.cl = T.load( T.testRoot()+'/dock/hex/complexes.cl') self.score = self.cl.valuesOf('hex_eshape') ## ## convert hex energies into positive score ## self.score = N.array(self.cl.valuesOf('hex_etotal')) * -1 ## define complexes with less the 6 A rmsd from reference as positives self.hits = N.less( self.cl.valuesOf('rms'), 6 )
def test_hexParser(self): """Dock.hexParser test""" rec_dic = t.load(t.testRoot() + "/dock/rec/1A2P_model.dic") lig_dic = t.load(t.testRoot() + "/dock/lig/1A19_model.dic") self.h = HexParser(t.testRoot() + "/dock/hex/1A2P-1A19_hex.out", rec_dic, lig_dic) c_lst = self.h.parseHex() if self.local: print c_lst[1].info globals().update(locals()) self.assertEqual(c_lst[1].info.keys(), [ 'soln', 'rms', 'hex_clst', 'hex_eshape', 'model2', 'model1', 'hex_etotal', 'date' ])
def test_bindingE( self ): """bindingEnergyDelphi test (Barnase:Barstar)""" self.com = T.load( T.testRoot() + '/com/ref.complex' ) self.dG = DelphiBindingEnergy( self.com, log=self.log, scale=1.2, verbose=self.local ) self.r = self.dG.run() self.assertAlmostEqual( self.r['dG_kt'], 21., 0 ) if self.local: self.log.add( '\nFinal result: dG = %3.2f kcal/mol'%self.r['dG_kcal'])
def loadTraj(f, trajIndex, start=0, end=None, step=1): """Load traj from file, add frame names, extract portion if requested""" t = T.load(T.absfile(f)) addFrameNames(t, trajIndex) e = end or len(t) if start or end or (step != 1): t = t.takeFrames(range(start, e, step)) return t
def loadTraj( f, trajIndex, start=0, end=None, step=1 ): """Load traj from file, add frame names, extract portion if requested""" t = T.load( T.absfile( f ) ) addFrameNames( t, trajIndex ) e = end or len( t ) if start or end or (step != 1): t = t.takeFrames( range( start, e, step ) ) return t
def updateModelDic( f ): """ Call update() on all models in a dict to make them aware of the new profiles.""" print 'Updating ', f d = T.load( T.absfile( f ) ) for m in d.values(): m.update( updateMissing=1 ) T.dump( d, T.absfile( f ) )
def updateModelDic(f): """ Call update() on all models in a dict to make them aware of the new profiles.""" print 'Updating ', f d = T.load(T.absfile(f)) for m in d.values(): m.update(updateMissing=1) T.dump(d, T.absfile(f))
def test_ContactSlave(self): """Dock.ContactSlave test (local)""" import os from Biskit.Dock.ContactMaster import ContactMaster ## load complex list (docking result) and reference complex lst = T.load(T.testRoot() + "/dock/hex/complexes.cl") lst = lst[:3] refcom = T.load(T.testRoot() + "/com/ref.complex") ## let ContactMaster prepare everything but don't run it self.master = ContactMaster(lst, verbose=self.local, log=self.log, refComplex=refcom, outFile=self.cl_out) jobs = self.master.data self.slave = ContactSlave() self.slave.initialize(self.master.getInitParameters(1)) if self.local or self.VERBOSITY > 2: self.log.writeln("Currently available info records (from hex):") self.log.writeln(repr(jobs[0].info.keys())) self.log.writeln( "Calculating all scores for %i complexes..." \ % len(jobs) ) self.result = self.slave.go(jobs) if self.local or self.VERBOSITY > 2: self.log.writeln("info records after contacting: ") self.log.writeln(repr(jobs[0].info.keys())) if self.local: print "new scores are available in 'result[0-2].info'" ## verify fraction of native atom contacts for third complex self.assertAlmostEqual(self.result[2]['fnac_10'], 0.11533600168527491, 7)
def test_reduce(self): """AtomCharger test""" if self.local: self.log.add('\nLoading PDB...') self.m1 = PDBModel(T.testRoot('lig/1A19_dry.model')) self.m2 = T.load(T.testRoot('com/ref.complex')) self.m2 = self.m2.model() if self.local: self.log.add('\nRunning Reduce...') self.x = Reduce(self.m1, debug=self.DEBUG, verbose=self.local, log=self.log, autocap=True) self.m1 = self.x.run() if self.local: self.log.add('\nReduce protein complex') self.x = Reduce(self.m2, debug=self.DEBUG, verbose=self.local, log=self.log, autocap=True) self.m2 = self.x.run() if self.local: self.log.add('\nSetup Residue Library\n') ac = AtomCharger(log=self.log, verbose=self.local) if self.local: self.log.add('match residues to Amber topology') ac.charge(self.m1) ac.charge(self.m2) self.assertAlmostEqual(N.sum(self.m1['partial_charge']), -6, 2) self.assertAlmostEqual(N.sum(self.m2['partial_charge']), -4, 2) self.assert_(N.all(self.m1['partial_charge'] != 0), 'unmatched atoms 1') self.assert_(N.all(self.m2['partial_charge'] != 0), 'unmatched atoms 2') if self.local: self.log.add('\nNow test handling of atom miss-matches:\n') self.m3 = PDBModel(self.m1.clone()) self.m3.remove([0, 3, 100, 101, 102, 200]) ac.charge(self.m3) self.assertAlmostEqual(N.sum(self.m3['partial_charge']), -8.21, 2)
def test_ContactSlave(self): """Dock.ContactSlave test (local)""" import os from Biskit.Dock.ContactMaster import ContactMaster ## load complex list (docking result) and reference complex lst = T.load( T.testRoot() + "/dock/hex/complexes.cl") lst = lst[:3] refcom = T.load( T.testRoot() + "/com/ref.complex") ## let ContactMaster prepare everything but don't run it self.master = ContactMaster( lst, verbose = self.local, log=self.log, refComplex = refcom, outFile = self.cl_out ) jobs = self.master.data self.slave = ContactSlave() self.slave.initialize( self.master.getInitParameters(1) ) if self.local or self.VERBOSITY > 2: self.log.writeln("Currently available info records (from hex):") self.log.writeln( repr(jobs[0].info.keys()) ) self.log.writeln( "Calculating all scores for %i complexes..." \ % len(jobs) ) self.result = self.slave.go( jobs ) if self.local or self.VERBOSITY > 2: self.log.writeln("info records after contacting: ") self.log.writeln( repr(jobs[0].info.keys()) ) if self.local: print "new scores are available in 'result[0-2].info'" ## verify fraction of native atom contacts for third complex self.assertAlmostEqual( self.result[2]['fnac_10'], 0.11533600168527491, 7 )
def sloppyload( f ): """ f - str, file name -> any, unpickled object """ try: T.flushPrint( "Loading " + str(f) + '\n' ) return T.load( T.absfile( f ) ) except cPickle.UnpicklingError: print "Trying to load %s in sloppy mode..." % f return PickleUpgrader(open(T.absfile(f))).load()
def test_bindingE(self): """bindingEnergyDelphi test (Barnase:Barstar)""" self.com = T.load(T.testRoot() + '/com/ref.complex') self.dG = DelphiBindingEnergy(self.com, log=self.log, scale=1.2, verbose=self.local) self.r = self.dG.run() self.assertAlmostEqual(self.r['dG_kt'], 21., 0) if self.local: self.log.add('\nFinal result: dG = %3.2f kcal/mol' % self.r['dG_kcal'])
def load( self ): """ Try to unpickle an object from the currently valid path. @return: unpickled object @rtype: any @raise IOError: if file can not be found """ try: return T.load( self.local( existing=1 ) ) except LocalPathError, why: raise IOError, "Cannot find file %s (constructed from %s)" %\ self.local(), str( self )
def load(self): """ Try to unpickle an object from the currently valid path. @return: unpickled object @rtype: any @raise IOError: if file can not be found """ try: return T.load(self.local(existing=1)) except LocalPathError, why: raise IOError, "Cannot find file %s (constructed from %s)" %\ self.local(), str( self )
def test_ComplexList(self): """Dock.ComplexList test""" self.cl = t.load( t.testRoot() + "/dock/hex/complexes.cl" ) ## number of clusters among the 100 best (lowest rmsd) solutions self.cl_sorted = self.cl.sortBy( 'rms' ) self.hex_clst = self.cl_sorted.valuesOf( 'hex_clst', indices=range(100), unique=1 ) if self.local: self.p = self.cl.plot( 'rms', 'hex_eshape', 'hex_etotal' ) self.p.show() self.assertEqual( len( self.hex_clst ), 36)
def test_ComplexModelRegistry(self): """Dock.ComplexModelRegistry test""" from Biskit.Dock import ComplexList self.cl = T.load( T.testRoot() +'/dock/hex/complexes.cl' ) self.cl = self.cl.toList() self.r = ComplexModelRegistry() for c in self.cl[:500]: self.r.addComplex( c ) check = self.r.getLigComplexes( self.r.ligModels()[0] ) self.assertEqual( len(check), 500 )
def test_ComplexModelRegistry(self): """Dock.ComplexModelRegistry test""" from Biskit.Dock import ComplexList self.cl = T.load(T.testRoot() + '/dock/hex/complexes.cl') self.cl = self.cl.toList() self.r = ComplexModelRegistry() for c in self.cl[:500]: self.r.addComplex(c) check = self.r.getLigComplexes(self.r.ligModels()[0]) self.assertEqual(len(check), 500)
def test_rmsFit(self): """rmsFit test""" import Biskit.tools as T self.traj = T.load(T.testRoot() + '/lig_pcr_00/traj.dat') rt, rmsdLst = match(self.traj.ref.xyz, self.traj[-1].xyz) if self.local: print 'RMSD: %.2f' % rmsdLst[0][1] # return rotation matrix r = abs(N0.sum(N0.ravel(rt[0]))) e = abs(N0.sum(N0.ravel(self.EXPECT))) self.assertAlmostEqual(r, e, 6)
def inputComplex(options): if 'c' in options: return T.load(T.absfile(options['c'])) m = PDBModel(T.absfile(options['i'])) ## extract rec and lig chains rec_chains = T.toIntList(options['r']) lig_chains = T.toIntList(options['l']) rec = m.takeChains(rec_chains) lig = m.takeChains(lig_chains) ## create Protein complex com = Complex(rec, lig) return com
def test_rmsFit( self ): """rmsFit test""" import Biskit.tools as T self.traj = T.load( T.testRoot() + '/lig_pcr_00/traj.dat' ) rt, rmsdLst = match( self.traj.ref.xyz, self.traj[-1].xyz) if self.local: print 'RMSD: %.2f' % rmsdLst[0][1] # return rotation matrix r = abs( N.sum( N.ravel( rt[0] ))) e = abs( N.sum( N.ravel( self.EXPECT ))) self.assertAlmostEqual(r, e, 6)
def __getFrames(self, f ): """ Load coordinate frames from file or take them from own cache @param f: file name @type f: str @return: coordiante frames @rtype: array """ if f in self.frame_cache: return self.frame_cache[ f ] self.frame_cache[f] = T.load(f) return self.frame_cache[ f ]
def inputComplex( options ): if 'c' in options: return T.load( T.absfile( options['c'] ) ) m = PDBModel( T.absfile( options['i'] ) ) ## extract rec and lig chains rec_chains = T.toIntList( options['r'] ) lig_chains = T.toIntList( options['l'] ) rec = m.takeChains( rec_chains ) lig = m.takeChains( lig_chains ) ## create Protein complex com = Complex( rec, lig ) return com
def go(self, output_folder = None, template_folder = None): """ Run analysis of models. @param output_folder: folder for result files (default: None S{->} outFolder/L{F_RESULT_FOLDER}) @type output_folder: str @param template_folder: folder with template structures (default: None S{->} outFolder/L{VS.F_RESULT_FOLDER}) @type template_folder: str """ ## pdb_list = T.load(self.outFolder + self.F_MODELS) model = PDBModel(pdb_list[0]) ## output_folder = output_folder or self.outFolder + self.F_RESULT_FOLDER template_folder = template_folder or self.outFolder +VS.F_RESULT_FOLDER templates = self.__listDir(template_folder) ## global_rmsd_aa_wo_if, global_rmsd_aa_if = self.global_rmsd_aa() global_rmsd_ca_wo_if, global_rmsd_ca_if = self.global_rmsd_ca() nb_templates = len(templates)-1 identities = self.get_identities(nb_templates) score = self.get_score() self.output_values(global_rmsd_aa_wo_if, global_rmsd_aa_if, global_rmsd_ca_wo_if, global_rmsd_ca_if, identities, score, nb_templates) ## aln_dic = self.get_aln_info(output_folder=self.outFolder) template_rmsd_dic = self.get_templates_rmsd(templates) templates_profiles = self.templates_profiles(templates, aln_dic, template_rmsd_dic) mean_rmsd = self.output_cross_val(aln_dic, templates_profiles, templates, model) ## mean_rmsd_atoms = model.res2atomProfile(mean_rmsd) self.updatePDBs_charge(mean_rmsd_atoms, model)
def test_reduce( self ): """AtomCharger test""" if self.local: self.log.add('\nLoading PDB...') self.m1 = PDBModel( T.testRoot( 'lig/1A19_dry.model' ) ) self.m2 = T.load( T.testRoot( 'com/ref.complex' ) ) self.m2 = self.m2.model() if self.local: self.log.add('\nRunning Reduce...') self.x = Reduce( self.m1, debug=self.DEBUG, verbose=self.local, log=self.log, autocap=True ) self.m1 = self.x.run() if self.local: self.log.add('\nReduce protein complex') self.x = Reduce( self.m2, debug=self.DEBUG, verbose=self.local, log=self.log, autocap=True ) self.m2 = self.x.run() if self.local: self.log.add('\nSetup Residue Library\n') ac = AtomCharger(log=self.log, verbose=self.local) if self.local: self.log.add('match residues to Amber topology') ac.charge( self.m1 ) ac.charge( self.m2 ) self.assertAlmostEqual( N.sum(self.m1['partial_charge']), -6, 2 ) self.assertAlmostEqual( N.sum(self.m2['partial_charge']), -4, 2 ) self.assert_(N.all(self.m1['partial_charge'] != 0),'unmatched atoms 1') self.assert_(N.all(self.m2['partial_charge'] != 0),'unmatched atoms 2') if self.local: self.log.add('\nNow test handling of atom miss-matches:\n') self.m3 = PDBModel(self.m1.clone()) self.m3.remove( [0,3,100,101,102,200] ) ac.charge( self.m3 ) self.assertAlmostEqual( N.sum(self.m3['partial_charge']),-8.21, 2)
def go(self, output_folder=None, template_folder=None): """ Run analysis of models. @param output_folder: folder for result files (default: None S{->} outFolder/L{F_RESULT_FOLDER}) @type output_folder: str @param template_folder: folder with template structures (default: None S{->} outFolder/L{VS.F_RESULT_FOLDER}) @type template_folder: str """ ## pdb_list = T.load(self.outFolder + self.F_MODELS) model = PDBModel(pdb_list[0]) ## output_folder = output_folder or self.outFolder + self.F_RESULT_FOLDER template_folder = template_folder or self.outFolder + VS.F_RESULT_FOLDER templates = self.__listDir(template_folder) ## global_rmsd_aa_wo_if, global_rmsd_aa_if = self.global_rmsd_aa() global_rmsd_ca_wo_if, global_rmsd_ca_if = self.global_rmsd_ca() nb_templates = len(templates) - 1 identities = self.get_identities(nb_templates) score = self.get_score() self.output_values(global_rmsd_aa_wo_if, global_rmsd_aa_if, global_rmsd_ca_wo_if, global_rmsd_ca_if, identities, score, nb_templates) ## aln_dic = self.get_aln_info(output_folder=self.outFolder) template_rmsd_dic = self.get_templates_rmsd(templates) templates_profiles = self.templates_profiles(templates, aln_dic, template_rmsd_dic) mean_rmsd = self.output_cross_val(aln_dic, templates_profiles, templates, model) ## mean_rmsd_atoms = model.res2atomProfile(mean_rmsd) self.updatePDBs_charge(mean_rmsd_atoms, model)
def repair( f, old, new ): """ Load and repickle with corrected path """ try: o = load( f ) print 'working on %s...' % f if isinstance( o, PDBModel) : replace_in_PDBModel( o, old, new ) if isinstance( o, Complex ) : replace_in_Complex( o, old, new ) if isinstance( o, Trajectory): replace_in_Traj( o, old, new ) if isinstance( o, dict ) : replace_in_dict( o, old, new ) if isinstance( o, list ) : replace_in_list( o, old, new ) if isinstance( o, ComplexList): o = replace_in_ComplexList(o,old,new) dump( o, f ) print except InvalidTargetPath, e: print e
def test_Ramachandran(self): """Ramachandran test""" self.traj = T.load(T.testRoot() + '/lig_pcr_00/traj.dat') self.traj.ref.atoms.set('mass', self.traj.ref.masses()) self.mdl = [self.traj[0], self.traj[11]] self.mdl = [md.compress(md.maskProtein()) for md in self.mdl] self.rama = Ramachandran(self.mdl, name='test', profileName='mass', verbose=self.local) self.psi = N.array(self.rama.psi) if self.local: self.rama.show() r = N.sum(N.compress(N.logical_not(N.equal(self.psi, None)), self.psi)) self.assertAlmostEqual(r, -11717.909796797909, 2)
def test_match2seq(self): """match2seq test""" ## Reading pdb files lig_traj = T.load( T.testRoot() + '/lig_pcr_00/traj.dat' )[:2] m = [ m.compress( m.maskProtein() ) for m in lig_traj ] ## make the models different m[1].removeRes(['ALA']) mask1, mask2 = compareModels( m[0], m[1] ) if self.local: print 'Reading and comparing two models' print '\nResidue masks to make the two maodels equal' print 'mask1\n', mask1 print 'mask2\n', mask2 globals().update( locals() ) self.assert_( N.all(mask1 == self.EXPECT[0] ) ) self.assert_( N.all(mask2 == self.EXPECT[1] ) )
def test_match2seq(self): """match2seq test""" ## Reading pdb files lig_traj = T.load(T.testRoot() + '/lig_pcr_00/traj.dat')[:2] m = [m.compress(m.maskProtein()) for m in lig_traj] ## make the models different m[1].removeRes(['ALA']) mask1, mask2 = compareModels(m[0], m[1]) if self.local: print 'Reading and comparing two models' print '\nResidue masks to make the two maodels equal' print 'mask1\n', mask1 print 'mask2\n', mask2 globals().update(locals()) self.assert_(N.all(mask1 == self.EXPECT[0])) self.assert_(N.all(mask2 == self.EXPECT[1]))
def test_FlexMaster(self): """TrajFlexMaster test""" from Biskit.MatrixPlot import MatrixPlot from numpy.random.mtrand import random_sample as random assert len(hosts.cpus_all) > 0,\ 'Master requires at least 1 PVM node for initialisation.' traj_1 = T.load(T.testRoot() + '/lig_pcr_00/traj.dat') traj_1 = traj2ensemble(traj_1) ## create fake second trajectory by adding ## increasing noise to first frames = [] for i in range(len(traj_1)): f = traj_1.frames[i] d = N0.zeros(N0.shape(f), N0.Float32) if i > 0: d = random(N0.shape(f)) * ((i / 10) + 1) frames += [f + d] traj_2 = traj_1.clone() traj_2.frames = frames master = TrajFlexMaster(traj_1, traj_2, hosts=hosts.cpus_all, show_output=self.local, add_hosts=1, log=None, slaveLog=None, verbose=self.local, only_cross_member=0) r = master.calculateResult(mirror=0) if self.local: p = MatrixPlot(r, palette='plasma2', legend=1) p.show()
def test_FlexMaster(self): """TrajFlexMaster test""" from Biskit.MatrixPlot import MatrixPlot from numpy.oldnumeric.random_array import random assert len(hosts.cpus_all) > 0,\ 'Master requires at least 1 PVM node for initialisation.' traj_1 = T.load( T.testRoot() + '/lig_pcr_00/traj.dat' ) traj_1 = traj2ensemble( traj_1 ) ## create fake second trajectory by adding ## increasing noise to first frames = [] for i in range( len( traj_1 ) ): f = traj_1.frames[i] d = N.zeros( N.shape( f ), N.Float32) if i > 0: d = random( N.shape( f ) ) * ((i / 10) + 1) frames += [f + d] traj_2 = traj_1.clone() traj_2.frames = frames master = TrajFlexMaster( traj_1, traj_2, hosts=hosts.cpus_all, show_output= self.local, add_hosts=1, log=None, slaveLog=None, verbose= self.local, only_cross_member=0 ) r = master.calculateResult( mirror=0 ) if self.local: p = MatrixPlot( r, palette='plasma2', legend=1 ) p.show()
def update(self, model, source, skipRes=None, updateMissing=0, force=0, headPatterns=[]): """ Update empty or missing fields of model from the source. The model will be connected to the source via model.source. Profiles that are taken from the source are labeled 'changed'=0. The same holds for coordinates (xyzChanged=0). However, existing profiles or coordinates or fields remain untouched. @param model: existing model @type model: PDBModel @param source: source PDB file or pickled PDBModel or PDBModel object @type source: str || file || PDBModel @param skipRes: list residue names that should not be parsed @type skipRes: [ str ] @param updateMissing: check source for additional profiles [0] @type updateMissing: 1|0 """ try: if force or updateMissing or self.needsUpdate(model): s = T.load(source) super(PDBParsePickle, self).update(model, s, skipRes=skipRes, updateMissing=updateMissing, force=force) except Exception, why: print T.lastErrorTrace() raise PDBParserError, "Cannot unpickle source model from %s, "\ % str(source) + "Reason:\n" + str(why)
def load( options ): f_traj = options['i'] start = int( options['s'] ) traj = T.load( f_traj ) if traj.__class__ != EnsembleTraj: traj = traj2ensemble( traj ) end = traj.lenFrames() if options.has_key('e'): end = int( options['e'] ) step = int( options['step'] ) traj = traj.takeFrames( range( start, end ) ) if step != 1: traj = traj.thin( step ) traj.fit() return TrajCluster( traj )
def get_templates_rmsd(self, templates): """ Collect RMSD values between all the templates. @param templates: name of the different templates @type templates: [str] @return: template_rmsd_dic, contains all the rmsd per residues of all the templates @rtype: dict """ template_rmsd_dic = {} for template in templates: pdb_list = self.outFolder + self.F_TEMPLATE_FOLDER \ + "/%s"%template + self.F_PDBModels pdb_list = T.load(pdb_list) template_rmsd_dic[template] = \ pdb_list[0].compress(pdb_list[0].maskCA()).atoms["rmsd2ref_if"] return template_rmsd_dic
def prepareRef( self, fname ): """ Prepare reference model. @param fname: file name @type fname: str @return: reference structure @rtype: PDBModel|Complex @raise EntropistError: if unknown reference type """ if not fname: return None if self.__splitFilenames( fname ): f1, f2 = self.__splitFilenames( fname ) m1, m2 = PDBModel( self.__getModel(f1) ), \ PDBModel( self.__getModel(f2) ) ref = Complex( m1, m2 ) else: ref = t.load( fname ) if isinstance( ref, Trajectory ): ref = ref.ref if isinstance( ref, PDBModel ): return self.__cleanAtoms( ref ) if isinstance( ref, Complex ): self.__cleanAtoms( ref.rec_model ) self.__cleanAtoms( ref.lig_model ) ref.lig_model_transformed = None return ref raise EntropistError, 'unknown reference type'