def prepareOutFolder( self, fout ): """ Setup an output folder @param fout: outfile name @type fout: str @return: out path @rtype: str """ ## date stamp in folder name try: datestr = "%02i%02i" % (localtime()[1], localtime()[2]) fout = fout % ( datestr ) if not os.path.exists( t.absfile( fout ) ): os.mkdir( t.absfile( fout ) ) ## user provided folder name -> formatting fails except: if not os.path.exists( t.absfile( fout ) ): os.mkdir( t.absfile( fout ) ) ## create folders for rec / lig HEX pdbs if not os.path.exists( t.absfile( fout ) + '/rec' ): os.mkdir( t.absfile( fout ) + '/rec' ) if not os.path.exists( t.absfile( fout ) + '/lig' ): os.mkdir( t.absfile( fout ) + '/lig' ) return t.absfile( fout )
def prepareOutFolder(self, fout): """ Setup an output folder @param fout: outfile name @type fout: str @return: out path @rtype: str """ ## date stamp in folder name try: datestr = "%02i%02i" % (localtime()[1], localtime()[2]) fout = fout % (datestr) if not os.path.exists(t.absfile(fout)): os.mkdir(t.absfile(fout)) ## user provided folder name -> formatting fails except: if not os.path.exists(t.absfile(fout)): os.mkdir(t.absfile(fout)) ## create folders for rec / lig HEX pdbs if not os.path.exists(t.absfile(fout) + '/rec'): os.mkdir(t.absfile(fout) + '/rec') if not os.path.exists(t.absfile(fout) + '/lig'): os.mkdir(t.absfile(fout) + '/lig') return t.absfile(fout)
def createHexInp(self, nRec, nLig): """ Create a HEX macro file for docking a rec lig pair. @param nRec: model number rec in model dictionaries @type nRec: int @param nLig: model number lig in model dictionaries @type nLig: int @return: macro file name, future out file name @rtype: (str, str) @raise DockerError: if macro dock option is different from previous call """ ## fetch PDB file names for given model numbers recPdb, ligPdb = self.recHexPdbs[nRec], self.ligHexPdbs[nLig] ## fetch the according PDBModels rec, lig = self.recDic[nRec], self.ligDic[nLig] fout_base = self.out + '/%s_%i-%s_%i' % (rec.pdbCode, nRec, lig.pdbCode, nLig) if os.path.exists(t.absfile(fout_base + '_hex.mac')) and self.verbose: fmac = t.absfile(fout_base + '_hex.mac') fout = t.absfile(fout_base + '_hex.out') macro = self.macroDock print("Dock setup: using old ", os.path.split(fmac)[1]) else: silent = 1 if self.verbose: silent = 0 fmac, fout, macro = hextools.createHexInp(recPdb, rec, ligPdb, lig, self.comPdb, outFile=fout_base, macDock=self.macroDock, sol=self.soln, silent=silent) if self.macroDock is None: self.macroDock = macro else: if self.macroDock != macro: raise DockerError('MacroDock setting changed to %i: %i : %i' %\ ( macro, nRec, nLig) ) ## remember which models and which out file are used self.runDic[fmac] = (nRec, nLig, fout) return fmac, fout
def createHexInp( self, nRec, nLig ): """ Create a HEX macro file for docking a rec lig pair. @param nRec: model number rec in model dictionaries @type nRec: int @param nLig: model number lig in model dictionaries @type nLig: int @return: macro file name, future out file name @rtype: (str, str) @raise DockerError: if macro dock option is different from previous call """ ## fetch PDB file names for given model numbers recPdb, ligPdb = self.recHexPdbs[nRec], self.ligHexPdbs[nLig] ## fetch the according PDBModels rec, lig = self.recDic[ nRec ], self.ligDic[ nLig ] fout_base = self.out+'/%s_%i-%s_%i' % (rec.pdbCode, nRec, lig.pdbCode, nLig) if os.path.exists( t.absfile( fout_base + '_hex.mac' ) ) and self.verbose: fmac = t.absfile( fout_base + '_hex.mac' ) fout = t.absfile( fout_base + '_hex.out' ) macro = self.macroDock print("Dock setup: using old ", os.path.split( fmac )[1]) else: silent=1 if self.verbose: silent=0 fmac, fout, macro = hextools.createHexInp(recPdb,rec, ligPdb,lig, self.comPdb, outFile=fout_base, macDock=self.macroDock, sol=self.soln, silent=silent) if self.macroDock is None: self.macroDock = macro else: if self.macroDock != macro: raise DockerError('MacroDock setting changed to %i: %i : %i' %\ ( macro, nRec, nLig) ) ## remember which models and which out file are used self.runDic[ fmac ] = ( nRec, nLig, fout ) return fmac, fout
def __init__(self, fcrd, fref, box=0, rnAmber=0, pdbCode=None, log=StdLog(), verbose=0): """ :param fcrd: path to input coordinate file :type fcrd: str :param fref: PDB or pickled PDBModel with same atom content and order :type fref: str :param box: expect line with box info at the end of each frame (default: 0) :type box: 1|0 :param rnAmber: rename amber style residues into standard (default: 0) :type rnAmber: 1|0 :param pdbCode: pdb code to be put into the model (default: None) :type pdbCode: str :param log: LogFile instance [Biskit.StdLog] :type log: biskit.LogFile :param verbose: print progress to log [0] :type verbose: int """ self.fcrd = T.absfile(fcrd) self.crd = T.gzopen(self.fcrd) self.ref = PDBModel(T.absfile(fref), pdbCode=pdbCode) self.box = box self.n = self.ref.lenAtoms() self.log = log self.verbose = verbose if rnAmber: self.ref.renameAmberRes() ## pre-compile pattern for line2numbers xnumber = "-*\d+\.\d+" # optionally negtive number xspace = ' *' # one or more space char self.xnumbers = re.compile('(' + xspace + xnumber + ')') ## pre-compute lines expected per frame self.lines_per_frame = self.n * 3 // 10 if self.n % 10 != 0: self.lines_per_frame += 1 if self.box: self.lines_per_frame += 1
def test_Executor( self ): """Executor test (run python -c 'print(sys.version)')""" ExeConfigCache.reset() self.x = ExeConfigCache.get( 'python', strict=0 ) self.x.pipes = 1 args = '-c import sys; print(sys.version)' if not self.local: args = '-kill ' + args self.e = Executor( 'python', args=args, strict=0, f_in=None, f_out=self.fout, verbose=self.local, cwd=t.absfile('~'), tempdir=True, debug=self.DEBUG ) self.r = self.e.run() if self.local: print('Python process was running for %.2f seconds'%self.e.runTime) self.assertTrue( self.e.pid is not None ) if self.DEBUG: if self.verbose: self.log.add("DEBUGGING mode active") else: self.assertTrue( not os.path.exists(self.e.tempdir), 'tempfolder not removed')
def __init__(self, f_in=None ): """ :param f_in: amber "off" or "prep" file with residue definitions if not existing, we will look for a file with this name in the Biskit data folder (data/amber/residues) (default: 'all_amino03.in') :type f_in: str """ f_in = f_in or self.F_DEFAULT if not osp.exists( T.absfile( f_in ) ): f_in = T.dataRoot() + '/amber/residues/' + f_in self.firstrecord = re.compile( 'db[0-9]+\.dat' ) self.s = open( T.absfile( f_in ), 'r' ).read() self.s = self.firstrecord.split( self.s )[-1] #skip until first residue
def test_AmberCrdParser(self): """AmberCrdParser test""" self.p = AmberCrdParser(self.finp, self.fref, box=True, rnAmber=True, log=self.log, verbose=self.local) self.t = self.p.crd2traj() self.t.removeAtoms( lambda a: a['residue_name'] in ['WAT', 'Na+', 'Cl-']) self.t.removeAtoms(lambda a: a['element'] == 'H') if self.local: print("Dumping result to ", self.fout) T.dump(self.t, T.absfile(self.fout)) if self.local: print("Dumped Trajectory with %i frames and %i atoms." % \ (len(self.t), self.t.lenAtoms() )) self.assertEqual(len(self.t), 10) self.assertEqual(self.t.lenAtoms(), 440)
def test_Executor(self): """Executor test (run python -c 'print(sys.version)')""" ExeConfigCache.reset() self.x = ExeConfigCache.get('python', strict=0) self.x.pipes = 1 args = '-c import sys; print(sys.version)' if not self.local: args = '-kill ' + args self.e = Executor('python', args=args, strict=0, f_in=None, f_out=self.fout, verbose=self.local, cwd=t.absfile('~'), tempdir=True, debug=self.DEBUG) self.r = self.e.run() if self.local: print('Python process was running for %.2f seconds' % self.e.runTime) self.assertTrue(self.e.pid is not None) if self.DEBUG: if self.verbose: self.log.add("DEBUGGING mode active") else: self.assertTrue(not os.path.exists(self.e.tempdir), 'tempfolder not removed')
def __init__(self, f_in=None): """ :param f_in: amber "off" or "prep" file with residue definitions if not existing, we will look for a file with this name in the Biskit data folder (data/amber/residues) (default: 'all_amino03.in') :type f_in: str """ f_in = f_in or self.F_DEFAULT if not osp.exists(T.absfile(f_in)): f_in = T.dataRoot() + '/amber/residues/' + f_in self.firstrecord = re.compile('db[0-9]+\.dat') self.s = open(T.absfile(f_in), 'r').read() self.s = self.firstrecord.split(self.s)[-1] #skip until first residue
def writeCrd(self, fcrd, append=1, lastAtom=None): """ Write/Append Amber-formatted block of coordinates to a file. If a file handle is given, the file will not be closed. :param fcrd: file to write to :type fcrd: str or file object :param append: append to existing file (default: 1) :type append: 0|1 :param lastAtom: skip all atoms beyond this one (default: None) :type lastAtom: int """ if not self.xyz: self.getXyz() if type(fcrd) == file: ## take file handle f = fcrd else: ## create new file handle mode = 'w' if append: mode = 'a' f = open(T.absfile(fcrd), mode) newf = (mode == 'w' or not os.path.exists(T.absfile(fcrd))) if newf: f.write("\n") i = 0 for x in N0.ravel(self.xyz): i = i + 1 f.write("%8.3f" % x) if (i % 10) == 0: f.write("\n") if lastAtom and i / 3.0 == lastAtom: break if ((i % 10) != 0): f.write("\n") if type(fcrd) != file: ## don't close file that was already given f.close()
def writeCrd( self, fcrd, append=1, lastAtom=None ): """ Write/Append Amber-formatted block of coordinates to a file. If a file handle is given, the file will not be closed. :param fcrd: file to write to :type fcrd: str or file object :param append: append to existing file (default: 1) :type append: 0|1 :param lastAtom: skip all atoms beyond this one (default: None) :type lastAtom: int """ if not self.xyz: self.getXyz() if type( fcrd ) == file: ## take file handle f = fcrd else: ## create new file handle mode = 'w' if append: mode = 'a' f = open( T.absfile( fcrd ), mode ) newf = (mode=='w' or not os.path.exists( T.absfile(fcrd) )) if newf: f.write("\n") i = 0 for x in N0.ravel( self.xyz ): i = i + 1 f.write( "%8.3f" % x ) if (i % 10) == 0: f.write("\n") if lastAtom and i / 3.0 == lastAtom: break if ((i % 10) != 0): f.write("\n") if type( fcrd ) != file: ## don't close file that was already given f.close()
def findLeaprc(self, ff): """ Guess full path to an existing leaprc file name or fragment of it. We first take the file as is, then look in AMBERHOME, then look in AMBERHOME/dat/leap/cmd. :param ff: forcefield code (leaprc file ending, e.g. 'ff99', 'ff01') OR leaprc file name (e.g, 'leaprc.f99') OR leaprc path witin $AMBERHOME OR leaprc path :type ff: str :return: full path to an existing leaprc file :rtype: str :raise: LeapError, if no existing file can be found """ if P.exists(T.absfile(ff)): return T.absfile(ff) amberhome = self.exe.env['AMBERHOME'] ## interpret ff as file ending ('ff99', 'ff03', etc) r = P.join(amberhome, self.LEAPRC_PATH, self.LEAPRC + ff) if P.exists(r): return r ## interpret ff as file ending ('ff99', 'ff03', etc pointing to 'old' forcefield) r = P.join(amberhome, self.LEAPRC_PATH, 'oldff', self.LEAPRC + ff) if P.exists(r): return r ## interpret ff as file name (e.g. 'leaprc.ff99') r = P.join(amberhome, self.LEAPRC_PATH, ff) if P.exists(r): return r ## interpret ff as file name (e.g. 'leaprc.ff99') for 'old' forcefield r = P.join(amberhome, self.LEAPRC_PATH, 'oldff', ff) if P.exists(r): return r ## interpret ff as path within AMBERHOME ('dat/leap/cmd/leaprc.f99') r = P.join(amberhome, ff) if P.exists(r): return r raise LeapError('Could not find Forcefield definition %s. ' % ff +\ 'Check exe_tleap.dat or provide an explicit leaprc parameter!')
def __init__( self, f_parm, f_crd, f_template=None, s=0, e=None, step=1, **kw ): """ :param f_parm: path to amber topology file :type f_parm: str :param f_crd: path to amber trajectory file :type f_crd: str :param f_template: alternative ptraj input template (default: None) :type f_template: str :param s: start frame (default: 0, first) :type s: int :param e: end frame (default: None, last) :type e: int :param step: frame offset (default: 1, no offset ) :type step: int :param kw: additional key=value parameters for Executor: :type kw: key=value pairs :: debug - 0|1, keep all temporary files (default: 0) verbose - 0|1, print progress messages to log (log != STDOUT) node - str, host for calculation (None->local) NOT TESTED (default: None) nice - int, nice level (default: 0) log - biskit.LogFile, program log (None->STOUT) (default: None) """ template = f_template or self.ptraj_script Executor.__init__( self, 'ptraj', template=template, push_inp=0, **kw ) self.f_parm = T.absfile( f_parm ) self.f_crd = T.absfile( f_crd ) self.start = s self.stop = e or 10000000 self.step = step ## default result self.result = { 'T':None, 'mass':None, 'vibes':None, 'S_total':None, 'S_trans':None, 'S_rot':None, 'S_vibes':None, 'contributions':None, 'nframes':None, 'version':biskit.__version__, 'node':self.node }
def __init__(self, fname, mode='w'): """ :param fname: name of log file :type fname: str :param mode: mode (default: w) :type mode: str """ self.fname = T.absfile(fname) self.mode = mode self._f = None
def __init__( self, fcrd, fref, box=0, rnAmber=0, pdbCode=None, log=StdLog(), verbose=0 ): """ :param fcrd: path to input coordinate file :type fcrd: str :param fref: PDB or pickled PDBModel with same atom content and order :type fref: str :param box: expect line with box info at the end of each frame (default: 0) :type box: 1|0 :param rnAmber: rename amber style residues into standard (default: 0) :type rnAmber: 1|0 :param pdbCode: pdb code to be put into the model (default: None) :type pdbCode: str :param log: LogFile instance [Biskit.StdLog] :type log: biskit.LogFile :param verbose: print progress to log [0] :type verbose: int """ self.fcrd = T.absfile( fcrd ) self.crd = T.gzopen( self.fcrd ) self.ref = PDBModel( T.absfile(fref), pdbCode=pdbCode ) self.box = box self.n = self.ref.lenAtoms() self.log = log self.verbose = verbose if rnAmber: self.ref.renameAmberRes() ## pre-compile pattern for line2numbers xnumber = "-*\d+\.\d+" # optionally negtive number xspace = ' *' # one or more space char self.xnumbers = re.compile('('+xspace+xnumber+')') ## pre-compute lines expected per frame self.lines_per_frame = self.n * 3 // 10 if self.n % 10 != 0: self.lines_per_frame += 1 if self.box: self.lines_per_frame += 1
def get_local( self, existing=0 ): """ Return a valid, absolute path. Either the existing original or with all substitutions for which environment variables exist. This function is time consuming (absfile - os.realpath is the culprit). :param existing: don't return a non-existing path :type existing: 0|1 :return: valid absolute path in current environment :rtype: str :raise LocalPathError: if existing==1 and no existing path can be constructed via environment variables """ if self.fragments: result = os.path.join( *[ f[0] for f in self.fragments ] ) else: result = '' result = T.absfile( result ) if os.path.exists( result ): return result substitutions = self.get_substitution_dict() result = '' for abs, env in self.fragments: if env: result += substitutions.get( env, abs ) else: result += abs result = T.absfile( result ) if existing and not os.path.exists( result ): raise LocalPathError("Can't construct existing path from %s."%\ self.formatted()) return result
def writeComplex(self, fname, ter=0): """ Write single pdb containing both receptor and ligand separated by END but not TER (unless ter!=0). @param fname: filename of pdb @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains """ self.model().writePdb( t.absfile( fname ), ter )
def writeReceptor(self, fname, ter=0 ): """ Write receptor to pdb without TER statement (unless removeTer!=0). @param fname: output file name @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains @type ter: 0|1|2 """ self.rec().writePdb( t.absfile( fname), ter )
def get_local(self, existing=0): """ Return a valid, absolute path. Either the existing original or with all substitutions for which environment variables exist. This function is time consuming (absfile - os.realpath is the culprit). :param existing: don't return a non-existing path :type existing: 0|1 :return: valid absolute path in current environment :rtype: str :raise LocalPathError: if existing==1 and no existing path can be constructed via environment variables """ if self.fragments: result = os.path.join(*[f[0] for f in self.fragments]) else: result = '' result = T.absfile(result) if os.path.exists(result): return result substitutions = self.get_substitution_dict() result = '' for abs, env in self.fragments: if env: result += substitutions.get(env, abs) else: result += abs result = T.absfile(result) if existing and not os.path.exists(result): raise LocalPathError("Can't construct existing path from %s."%\ self.formatted()) return result
def writeComplex(self, fname, ter=0): """ Write single pdb containing both receptor and ligand separated by END but not TER (unless ter!=0). @param fname: filename of pdb @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains """ self.model().writePdb(t.absfile(fname), ter)
def writeReceptor(self, fname, ter=0): """ Write receptor to pdb without TER statement (unless removeTer!=0). @param fname: output file name @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains @type ter: 0|1|2 """ self.rec().writePdb(t.absfile(fname), ter)
def tofile(self, fname): if not self.resmap: self.prepare() fname = T.absfile(fname) f = open(fname, 'w') f.write('! charge file generated by Biskit.delphi.DelphiCharges\n') f.write('atom__resnumbc_charge_\n') try: for resname, akeys in self.resmap.items(): f.write(self.manyres2delphi(akeys)) finally: f.close()
def tofile( self, fname ): if not self.resmap: self.prepare() fname = T.absfile( fname ) f = open( fname, 'w' ) f.write('! charge file generated by Biskit.delphi.DelphiCharges\n') f.write('atom__resnumbc_charge_\n') try: for resname, akeys in self.resmap.items(): f.write( self.manyres2delphi( akeys ) ) finally: f.close()
def writeLigand(self, fname, ter=0 ): """ Write transformed ligand to pdb file. Remove TER record for xplor usage (unless removeTer!=0). @param fname: output filename @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains @type ter: 0|1|2 """ pdb = self.lig() pdb.writePdb( t.absfile( fname ), ter )
def saveXLog( self, fname ): """ Save the content of the XPlor log file to a new file. @param fname: target file name @type fname: str @raise XPlorerError: if logLines is empty (Xplor hasn't been run) """ if not self.logLines: raise XplorerError('Xplor log file is (yet) empty.') f = open( T.absfile(fname), 'w') f.writelines( self.logLines ) f.close()
def saveXLog(self, fname): """ Save the content of the XPlor log file to a new file. @param fname: target file name @type fname: str @raise XPlorerError: if logLines is empty (Xplor hasn't been run) """ if not self.logLines: raise XplorerError('Xplor log file is (yet) empty.') f = open(T.absfile(fname), 'w') f.writelines(self.logLines) f.close()
def writeLigand(self, fname, ter=0): """ Write transformed ligand to pdb file. Remove TER record for xplor usage (unless removeTer!=0). @param fname: output filename @type fname: str @param ter: option for how to treat the TER statement:: - 0, don't write any TER statements (default) - 1, restore original TER statements - 2, put TER between all detected chains @type ter: 0|1|2 """ pdb = self.lig() pdb.writePdb(t.absfile(fname), ter)
def loadTraj(f, trajIndex, start=0, end=None, step=1, prot=False): """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(list(range(start, e, step))) if prot: t.keepAtoms(N0.nonzero(t.ref.maskProtein())) return t
def createHexPdb_single(model, fout=None): """ Write PDB of one structure for hex. @param model: model @type model: PDBModel @param fout: out file name (default: pdbCode + _hex.pdb) @type fout: str @return: file name of result PDB @rtype: str """ fout = fout or model.pdbCode + '_hex.pdb' fout = t.absfile(fout) model.writePdb(fout) return fout
def __init__( self, frst ): """ :param frst: input restart file :type frst: str """ self.frst = T.absfile( frst ) self.crd = open( self.frst ) self.n = 0 #: number of atoms self.lines_per_frame = 0 self.xyz = None #: will hold coordinate array self.box = None #: will hold box array if any ## pre-compile pattern for line2numbers xnumber = "-*\d+\.\d+" # optionally negtive number xspace = ' *' # one or more space char self.xnumbers = re.compile('('+xspace+xnumber+')')
def __init__(self, frst): """ :param frst: input restart file :type frst: str """ self.frst = T.absfile(frst) self.crd = open(self.frst) self.n = 0 #: number of atoms self.lines_per_frame = 0 self.xyz = None #: will hold coordinate array self.box = None #: will hold box array if any ## pre-compile pattern for line2numbers xnumber = "-*\d+\.\d+" # optionally negtive number xspace = ' *' # one or more space char self.xnumbers = re.compile('(' + xspace + xnumber + ')')
def createHexPdb(modelDic, fout=None): """ Write pdb for hex with models separated by MODEL%i/ENDMODEL @param modelDic: dictionary mapping an integer to each model @type modelDic: dict {int:XplorModel} @param fout: output name, default is pdbCode + _hex.pdb @type fout: str @return: file name of result PDB @rtype: str """ fout = fout or modelDic[1].pdbCode + '_hex.pdb' fout = t.absfile(fout) ## open new file out = open(fout, 'w') ## fetch name for temporary file tmpFile = tempfile.mktemp('_pcr2hex.pdb') numbers = list(modelDic.keys()) numbers.sort() for n in numbers: ## write temporary pdb and open it modelDic[n].writePdb(tmpFile) pdb_temp = open(tmpFile) out.write("MODEL%6i\n" % n) lines = pdb_temp.readlines() # get all lines for line in lines: if line[:3] != 'END': # filter out END out.write(line) out.write("ENDMDL\n") ## remove temporary file pdb_temp.close() os.remove(tmpFile) out.write("END") out.close() return fout
def __is_path(self, o, minLen=3): """ Check whether an object is a path string (existing or not). :param minLen: minimal length of string o to be counted as path :type minLen: int :return: 1|0 :rtype: int """ r = ( type( o ) == str \ and (o.find(os.path.sep) != -1 or o.find('/') != -1)\ and len(o) >= minLen ) ## and o.find(':') == -1 ) if r: try: s = T.absfile(o) return 1 except: return 0 return 0
def __validPath( self, v ): """ :param v: potential path name :type v: str :return: validated absolute Path :rtype : str :raise InvalidPath: if path is not found """ try: v = T.absfile( v ) if not v or not os.path.exists( v ): raise InvalidPath('invalid path %r' % v) return v except InvalidPath as e: raise except Exception as e: raise InvalidPath('error during path validation: %r' % str(e))
def __is_path( self, o, minLen=3 ): """ Check whether an object is a path string (existing or not). :param minLen: minimal length of string o to be counted as path :type minLen: int :return: 1|0 :rtype: int """ r = ( type( o ) == str \ and (o.find(os.path.sep) != -1 or o.find('/') != -1)\ and len(o) >= minLen ) ## and o.find(':') == -1 ) if r: try: s = T.absfile( o ) return 1 except: return 0 return 0
def test_AmberCrdParser(self): """AmberCrdParser test""" self.p = AmberCrdParser( self.finp, self.fref, box=True, rnAmber=True, log=self.log, verbose=self.local ) self.t = self.p.crd2traj() self.t.removeAtoms(lambda a: a['residue_name'] in ['WAT','Na+','Cl-'] ) self.t.removeAtoms(lambda a: a['element'] == 'H' ) if self.local: print("Dumping result to ", self.fout) T.dump( self.t, T.absfile(self.fout) ) if self.local: print("Dumped Trajectory with %i frames and %i atoms." % \ (len(self.t), self.t.lenAtoms() )) self.assertEqual( len(self.t), 10 ) self.assertEqual( self.t.lenAtoms(), 440 )
def __validPath(self, v): """ :param v: potential path name :type v: str :return: validated absolute Path :rtype : str :raise InvalidPath: if path is not found """ try: v = T.absfile(v) if not v or not os.path.exists(v): raise InvalidPath('invalid path %r' % v) return v except InvalidPath as e: raise except Exception as e: raise InvalidPath('error during path validation: %r' % str(e))
def writeCrd( self, fname, frames=None ): """ Write frames to Amber crd file (w/o box info). :param fname: output file name :type fname: str :param frames: frame indices (default: all) :type frames: [int] """ if frames is None: frames = list(range( self.lenFrames())) template = " %7.3f" * 10 + '\n' ## open new file out = open( T.absfile(fname), 'wt') __write = out.write ## cache function address for speed __write('\n') n_lines = None for fi in frames: f = N0.ravel( self.frames[ fi ] ) if n_lines is None: n_lines = n_lines or len( f ) // 10 overhang= ( 0 != len( f ) % 10 ) i_lines = range( n_lines ) for i in i_lines: __write( template % tuple( f[10*i:10*i+10] ) ) if overhang: for x in f[i*10+10:]: __write(" %7.3f" % x ) __write('\n') out.close()
def __init__(self, source=None): """ @param source: path to EZD file @type source: str OR file handle """ ## Raik says: this is always overridden by the "self.source=source" if type(source) is str and os.path.isfile(source): self.source = LocalPath(source) self.source = source ## my suggestion (LocalPath is a bit overkill here): self.source = tools.absfile(source) #try : f = tools.gzopen(self.source) self.__jumpComment(f) cell = self.__readCell(f) self.a = cell[0] self.b = cell[1] self.c = cell[2] self.alpha = cell[3] self.beta = cell[4] self.gamma = cell[5] self.origin = self.__readOrigin(f) self.extent = self.__readExtent(f) self.gridsize = self.__readGridSize(f) self.scale = self.__readScale(f) self.EDGrid = self.__readGrid(f) self.__setCartesianCoords() self.sd = npy.std(self.EDGrid) self.mean = npy.mean(self.EDGrid) f.close()
def __init__( self, recDic, ligDic, recPdb=None, ligPdb=None, comPdb=None, out='hex_%s', soln=512, recChainId=None, ligChainId=None, macDock=None, bin='hex', verbose=1 ): ## use ExeConfig instead of bin=... """ @param recDic: receptor dictionary @type recDic: dict @param ligDic: ligand dictionary @type ligDic: dict @param recPdb: hex-formatted PDB with rec models @type recPdb: str @param ligPdb: hex-formatted PDB with lig models @type ligPdb: str @param comPdb: hex-formatted PDB with com models @type comPdb: str @param soln: number of solutions to keep from HEX (default 512) @type soln: int @param recChainId: force chain IDs only for HEX @type recChainId: [str] @param ligChainId: force chain IDs only for HEX @type ligChainId: [str] @param out: out folder name, will be formatted against date @type out: str @param macDock: force macro docking ON or OFF (default: size decides) @type macDock: 1|0 @param bin: path to HEX binary @type bin: str @param verbose: verbosity level (default: 1) @type verbose: 1|0 """ self.lock = RLock() self.lockMsg = Condition( self.lock ) t.ensure( macDock, int, [None] ) t.ensure( recDic, dict, ) t.ensure( ligDic, dict, ) self.verbose = verbose self.recDic = recDic self.ligDic = ligDic ## force chain IDs self.recChainId = recChainId self.ligChainId = ligChainId ## create folder if necessary self.out = self.prepareOutFolder( out ) self.comPdb = None if comPdb: self.comPdb = t.absfile( comPdb ) ## remember which HEX PDB was created for which model self.recHexPdbs = {} self.ligHexPdbs = {} ## remember which macrofile uses which models and which out file self.runDic = {} if recPdb: ## HEX PDB provided externally for k in self.recDic: self.recHexPdbs[ k ] = t.absfile( recPdb ) else: ## HEX PDB has to be created self.recHexPdbs = self.prepareHexPdbs( self.recDic, self.recChainId, 'rec') if ligPdb: for k in self.ligDic: self.ligHexPdbs[ k ] = t.absfile( recPdb ) else: self.ligHexPdbs = self.prepareHexPdbs( self.ligDic, self.ligChainId, 'lig') self.bin = bin self.call_when_done = None self.call_when_failed=None ## remember whether macro dock was used self.macroDock = macDock self.running = [] self.hexDone = 0 self.hexFailed = 0 self.result = ComplexList() self.soln = soln
t = t.takeFrames(list(range(start, e, step))) if prot: t.keepAtoms(N0.nonzero(t.ref.maskProtein())) return t ############ ### MAIN ### use() o = T.cmdDict({'o': 'traj_ensemble.dat'}) out = T.absfile(o['o']) inLst = T.toList(o['i']) start = int(o.get('s', '0')) end = o.get('e', None) if end: end = int(end) step = int(o.get('step', 1)) prot = 'prot' in o ref = o.get('ref', None) if ref: ref = PDBModel(T.absfile(ref)) if 'prot' in o: ref = ref.compress(ref.maskProtein()) T.flushPrint("Loading and appending trajectories...")
def parmSolvated( self, f_out, f_out_crd=None, f_out_pdb=None, hetatm=0, norun=0, cap=0, capN=[], capC=[], fmod=['frcmod.ionsjc_tip3p'], fprep=[], box=10.0, center=True, **kw ): """ :param f_out: target file for parm (topology) :type f_out: str :param f_out_crd: target file for crd (coordinates) (default:|f_out_base|.crd) :type f_out_crd: str :param f_out_pdb: target file for pdb (default:|f_out_base|.pdb) :type f_out_pdb: str :param hetatm: keep hetero atoms (default: 0) :type hetatm: 1|0 :param cap: put ACE and NME capping residue on chain breaks (default: 0) :type cap: 1|0 :param capN: indices of chains that should get ACE cap (default: []) :type capN: [int] :param capC: indices of chains that should get NME cap (default: []) :type capC: [int] :param box: minimal distance of solute from box edge (default: 10.0) :type box: float :param center: re-center coordinates (default: True) :type center: bool :param fmod: list of files with amber parameter modifications to be loaded into leap with loadAmberParams (default:['frcmod.ionsjc_tip3p'] ... mod file needed for default Amber ff10 ions -- topology saving will fail if this one is missing) :type fmod: [str] :param fprep: list of files with amber residue definitions (to be loaded into leap with loadAmberPrep) (default: []) :type fprep: [str] :param kw: additional key=value pairs for leap input template :type kw: key=value :raise IOError: """ f_out = t.absfile( f_out ) f_out_crd = t.absfile( f_out_crd ) or t.stripSuffix( f_out ) + '.crd' f_out_pdb = t.absfile( f_out_pdb ) or t.stripSuffix( f_out ) +\ '_leap.pdb' ## removed: (bugfix 3434136) #fmod = [ t.absfile( f ) for f in t.toList( fmod ) ] #fprep = [ t.absfile( f ) for f in t.toList( fprep ) ] try: if self.verbose: self.log.add( '\nCleaning PDB file for Amber:' ) m = self.leapModel( hetatm=hetatm, center=center ) if cap: end_broken = m.atom2chainIndices( m.chainBreaks() ) capC = MU.union( capC, end_broken ) capN = MU.union( capN, N0.array( end_broken ) + 1 ) for i in capN: if self.verbose: self.log.add( 'Adding ACE cap to chain %i' % i ) m = self.capACE( m, i ) for i in capC: if self.verbose: self.log.add( 'Adding NME cap to chain %i' % i ) m = self.capNME( m, i ) m.renumberResidues( addChainId=1 ) ## again, to accomodate capping template = open( self.leap_template ).read() leap_mod = self.__fLines( 'm = loadAmberParams %s\n', fmod ) leap_prep= self.__fLines( 'loadAmberPrep %s\n', fprep ) ss = self.__ssBonds( m, cutoff=4. ) self.__cys2cyx( m, ss ) leap_ss = self.__fLines( self.ss_bond, ss ) if self.verbose: self.log.add('Found %i disulfide bonds: %s' % (len(ss),str(ss))) if self.verbose: self.log.add( 'writing cleaned PDB to %s' % self.leap_pdb ) m.writePdb( self.leap_pdb, ter=3 ) self.__runLeap( template, in_pdb=self.leap_pdb, out_parm=f_out, out_crd=f_out_crd, ss_bonds=leap_ss, fmod=leap_mod, fprep=leap_prep, norun=norun, box=box, **kw ) if not norun: parm_pdb = self.parm2pdb( f_out, f_out_crd, f_out_pdb ) if not self.keep_leap_pdb and not self.debug: t.tryRemove( self.leap_pdb ) except IOError as why: raise IOError(why)
def parmMirror( self, f_out, f_out_crd=None, fmod=['frcmod.ionsjc_tip3p'], fprep=[], **kw ): """ Create a parm7 file whose atom content (and order) exactly mirrors the given PDBModel. This requires two leap runs. First we get a temporary topology, then we identify all atoms added by leap and build a final topology where these atoms are deleted. This parm is hence NOT suited for simulations but can be used to parse e.g. a trajectory or PDB into ptraj. :param f_out: target parm file :type f_out: str :param f_out_crd: target crd file (default: f_out but ending .crd) :type f_out_crd: str :param fmod : list of amber Mod files (loaded with loadAmberParams) :type fmod : [str] :param fmod : list of amber Prep files (loaded with loadAmberPrep) :type fmod : [str] """ f_out = t.absfile( f_out ) f_out_crd = t.absfile( f_out_crd ) or t.stripSuffix( f_out ) + '.crd' ## if there are hydrogens, recast them to standard amber names aatm = 'HA' in self.m.atomNames() ## 'HB2' in self.m.atomNames() ## First leap round ## m_ref = self.m.clone() m_ref.xplor2amber( aatm=aatm, parm10=True ) tmp_in = tempfile.mktemp( 'leap_in0.pdb' ) m_ref.writePdb( tmp_in, ter=3 ) tmp_parm = tempfile.mktemp( '_parm0' ) tmp_crd = tempfile.mktemp( '_crd0' ) leap_mod = self.__fLines( 'm = loadAmberParams %s\n', fmod ) leap_prep= self.__fLines( 'loadAmberPrep %s\n', fprep ) self.__runLeap( self.script_mirror_pdb, leaprc=self.leaprc, fmod=leap_mod, fprep=leap_prep, in_pdb=tmp_in, out_parm=tmp_parm, out_crd=tmp_crd, delete_atoms='' ) tmp_pdb = self.parm2pdb( tmp_parm, tmp_crd, tempfile.mktemp( 'leap_out.pdb' ), aatm=aatm ) if not self.debug: t.tryRemove( tmp_parm ) t.tryRemove( tmp_crd ) t.tryRemove( tmp_in ) ## load model with missing atoms added by leap m_leap = PDBModel( tmp_pdb ) ## compare atom content iLeap, iRef = m_leap.compareAtoms( m_ref ) ## check that ref model doesn't need any change if iRef != list(range( len( m_ref ))): uLeap, uRef = m_leap.unequalAtoms( m_ref, iLeap, iRef ) atms = m_ref.reportAtoms( uRef, n=6 ) raise AmberError("Cannot create exact mirror of %s.\n" % tmp_in +\ "Leap has renamed/deleted original atoms in %s:\n"% tmp_pdb+\ atms) ## indices of atoms that were added by leap delStr = self.__deleteAtoms( m_leap, self.__inverseIndices( m_leap, iLeap ) ) ## Second leap round ## self.__runLeap( self.script_mirror_pdb, leaprc=self.leaprc, in_pdb=tmp_pdb, fmod=leap_mod, fprep=leap_prep, out_parm=f_out, out_crd=f_out_crd, delete_atoms=delStr ) if not self.debug: t.tryRemove( tmp_pdb )
def __init__( self, name, args='', template=None, f_in=None, f_out=None, f_err=None, strict=True, catch_out=1, push_inp=1, catch_err=0, node=None, nice=0, cwd=None, tempdir=None, log=None, debug=0, verbose=None, validate=1, configpath=None, **kw ): """ Create Executor. *name* must point to an existing program configuration unless *strict*=0. Executor will create a program input from the template and its own fields and put it into f_in. If f_in but no template is given, the unchanged f_in is used as input. If neither is given, the program is called without input. If a node is given, the process is wrapped in a ssh call. If *nice* != 0, the process is preceeded by nice. *cwd* specifies the working directory. By default, this setting is taken from the configuration file which defaults to the current working directory. :param name: program name (configured in .biskit/exe_name.dat) :type name: str :param args: command line arguments :type args: str :param template: template for input file -- this can be the template itself or the path to a file containing it (default: None) :type template: str :param f_in: target for completed input file (default: None, discard) :type f_in: str :param f_out: target file for program output (default: None, discard) :type f_out: str :param f_err: target file for error messages (default: None, discard) :type f_err: str :param strict: strict check of environment and configuration file (default: True) :type strict: bool :param configpath: alternative paths for finding configuration file :type configpath: [str] :param catch_out: catch output in file (f_out or temporary) (default: 1) :type catch_out: 1|0 :param catch_err: catch errors in file (f_out or temporary) (default: 1) :type catch_err: 1|0 :param push_inp: push input file to process via stdin ('< f_in') [1] :type push_inp: 1|0 :param node: host for calculation (None->no ssh) (default: None) :type node: str :param nice: nice level (default: 0) :type nice: int :param cwd: working directory, overwrites ExeConfig.cwd (default: None) :type cwd: str :param tempdir: folder for temporary files, will be created if not existing (default: None ... use system default) if set to True: create a new tempdir within default :type tempdir: str | True :param log: execution log (None->STOUT) (default: None) :type log: biskit.LogFile :param debug: keep all temporary files (default: 0) :type debug: 0|1 :param verbose: print progress messages to log (default: log != STDOUT) :type verbose: 0|1 :param validate: validate binary and environment immedeatly (1=default) or only before execution (0) :type validate: 1|0 :param kw: key=value pairs with values for template file or string :type kw: key=value :raise ExeConfigError: if environment is not fit for running the program """ self.exe = ExeConfigCache.get( name, strict=strict, configpath=configpath ) if validate: self.exe.validate() ## see prepare() self.keep_tempdir = True ## set to False if tempdir created new self.tempdir = self.newtempfolder( tempdir ) ## repeat in child classes self.f_out = t.absfile( f_out ) if not f_out and catch_out: self.f_out = tempfile.mktemp( '.out', name+'_', self.tempdir) self.f_err = t.absfile( f_err ) if not f_err and catch_err: self.f_err = tempfile.mktemp( '.err', name+'_', self.tempdir) self.keep_out = f_out is not None self.keep_inp = f_in is not None #: do not clean up the input file self.catch_out = catch_out #: capture STDOUT into file self.catch_err = catch_err #: capture STDERR into file self.f_in = t.absfile( f_in ) ## pre-define name of input file that will be generated later if template and not f_in: self.f_in = tempfile.mktemp('.inp', name+'_', self.tempdir) self.push_inp = push_inp self.args = args self.template = template self.node = node ## or os.uname()[1] self.nice = nice self.debug = debug self.cwd = cwd or self.exe.cwd #: Log object for own messages; undocumented: capture string as well self.log = log or StdLog() if type(self.log) is str: self.log = B.LogFile( self.log ) self.verbose = verbose if self.verbose is None: self.verbose = (log is not None) ## these are set by self.run(): self.runTime = 0 #: time needed for last run self.output = None #: STDOUT returned by process self.error = None #: STDERR returned by process self.returncode = None #: int status returned by process self.pid = None #: process ID self.result = None #: set by self.finish() self.initVersion = B.__version__ self.__dict__.update( kw )
def __init__(self, recDic, ligDic, recPdb=None, ligPdb=None, comPdb=None, out='hex_%s', soln=512, recChainId=None, ligChainId=None, macDock=None, bin='hex', verbose=1): ## use ExeConfig instead of bin=... """ @param recDic: receptor dictionary @type recDic: dict @param ligDic: ligand dictionary @type ligDic: dict @param recPdb: hex-formatted PDB with rec models @type recPdb: str @param ligPdb: hex-formatted PDB with lig models @type ligPdb: str @param comPdb: hex-formatted PDB with com models @type comPdb: str @param soln: number of solutions to keep from HEX (default 512) @type soln: int @param recChainId: force chain IDs only for HEX @type recChainId: [str] @param ligChainId: force chain IDs only for HEX @type ligChainId: [str] @param out: out folder name, will be formatted against date @type out: str @param macDock: force macro docking ON or OFF (default: size decides) @type macDock: 1|0 @param bin: path to HEX binary @type bin: str @param verbose: verbosity level (default: 1) @type verbose: 1|0 """ self.lock = RLock() self.lockMsg = Condition(self.lock) t.ensure(macDock, int, [None]) t.ensure( recDic, dict, ) t.ensure( ligDic, dict, ) self.verbose = verbose self.recDic = recDic self.ligDic = ligDic ## force chain IDs self.recChainId = recChainId self.ligChainId = ligChainId ## create folder if necessary self.out = self.prepareOutFolder(out) self.comPdb = None if comPdb: self.comPdb = t.absfile(comPdb) ## remember which HEX PDB was created for which model self.recHexPdbs = {} self.ligHexPdbs = {} ## remember which macrofile uses which models and which out file self.runDic = {} if recPdb: ## HEX PDB provided externally for k in self.recDic: self.recHexPdbs[k] = t.absfile(recPdb) else: ## HEX PDB has to be created self.recHexPdbs = self.prepareHexPdbs(self.recDic, self.recChainId, 'rec') if ligPdb: for k in self.ligDic: self.ligHexPdbs[k] = t.absfile(recPdb) else: self.ligHexPdbs = self.prepareHexPdbs(self.ligDic, self.ligChainId, 'lig') self.bin = bin self.call_when_done = None self.call_when_failed = None ## remember whether macro dock was used self.macroDock = macDock self.running = [] self.hexDone = 0 self.hexFailed = 0 self.result = ComplexList() self.soln = soln
def createHexInp(recPdb, recModel, ligPdb, ligModel, comPdb=None, outFile=None, macDock=None, silent=0, sol=512): """ Prepare a Hex macro file for the docking of the receptor(s) against ligand(s). @param recPdb: hex-formatted PDB @type recPdb: str @param recModel: hex-formatted PDB @type recModel: str @param ligPdb: PDBModel, get distances from this one @type ligPdb: PDBModel @param ligModel: PDBModel, getdistances from this one @type ligModel: PDBModel @param comPdb: reference PDB @type comPdb: str @param outFile: base of file name for mac and out @type outFile: str @param macDock: None -> hex decides (from the size of the molecule), 1 -> force macroDock, 0-> force off (default: None) @type macDock: None|1|0 @param silent: don't print distances and macro warnings (default: 0) @type silent: 0|1 @param sol: number of solutions that HEx should save (default: 512) @type sol: int @return: HEX macro file name, HEX out generated bu the macro, macro docking status @rtype: str, str, boolean """ ## files and names recCode = t.stripFilename(recPdb)[0:4] ligCode = t.stripFilename(ligPdb)[0:4] outFile = outFile or recCode + '-' + ligCode ## hex macro name macName = t.absfile(outFile + '_hex.mac') ## hex rotation matrix output name outName_all = t.absfile(outFile + '_hex.out') outName_clust = t.absfile(outFile + '_hex_cluster.out') ## add surface profiles if not there if 'relAS' not in recModel.atoms: #t.flushPrint('\nCalculating receptor surface profile') rec_asa = PDBDope(recModel) rec_asa.addSurfaceRacer() if 'relAS' not in ligModel.atoms: #t.flushPrint('\nCalculating ligand surface profile') lig_asa = PDBDope(ligModel) lig_asa.addSurfaceRacer() ## surface masks, > 95% exposed rec_surf_mask = N0.greater(recModel.profile('relAS'), 95) lig_surf_mask = N0.greater(ligModel.profile('relAS'), 95) ## maximun and medisn distance from centre of mass to any surface atom recMax, recMin = centerSurfDist(recModel, rec_surf_mask) ligMax, ligMin = centerSurfDist(ligModel, lig_surf_mask) ## approxinate max and min center to centre distance maxDist = recMax + ligMax minDist = recMin + ligMin ## molecular separation and search range to be used in the docking molSep = (maxDist + minDist) / 2 molRange = 2 * (maxDist - molSep) if not silent: print( 'Docking setup: %s\nRecMax: %.1f RecMin: %.1f\nLigMax: %.1f LigMin: %.1f\nMaxDist: %.1f MinDist: %.1f\nmolecular_separation: %.1f r12_range: %.1f\n' % (outFile, recMax, recMin, ligMax, ligMin, maxDist, minDist, molSep, molRange)) if recMax > 30 and ligMax > 30 and not silent: print('\nWARNING! Both the receptor and ligand radius is ', end=' ') print('greater than 30A.\n') ## determine docking mode to use macroDocking = 0 if macDock == None: if recMax > 35 and not silent: print('\nReceptor has a radius that exceeds 35A ', end=' ') print('-> Macro docking will be used') macroDocking = 1 else: macroDocking = macDock ##################### ## write macro file macOpen = open(macName, 'w') macOpen.write('# -- ' + macName + ' --\n') macOpen.write(' \n') macOpen.write('open_receptor ' + t.absfile(recPdb) + '\n') macOpen.write('open_ligand ' + t.absfile(ligPdb) + '\n') if comPdb and comPdb[-4:] == '.pdb': macOpen.write('open_complex ' + comPdb + '\n') macOpen.write('\n') head = """ # -------------- general settings ---------------- disc_cache 1 # disc cache on (0 off) docking_sort_mode 1 # Sort solutions by cluster (0 by energy) docking_cluster_mode 1 # Display all clusters (0 display best) docking_cluster_threshold 2.00 # docking_cluster_bumps number # ------------ molecule orientation -------------- molecule_separation %(separation)i commit_view """ % ({ 'separation': round(molSep) }) macro = """ # -------------- macro docking ------------------- macro_min_coverage 25 macro_sphere_radius 15 macro_docking_separation 25 activate_macro_model""" tail = """ # -------------- docking setup ------------------- docking_search_mode 0 # full rotational search receptor_range_angle 180 # 0, 15, 30, 45, 60, 75, 90, 180 docking_receptor_samples 720 # 362, 492, 642, 720, 980, 1280 ligand_range_angle 180 docking_ligand_samples 720 twist_range_angle 360 # 0, 15, 30, 60, 90, 180, 360 docking_alpha_samples 128 # 64, 128, 256 r12_step 0.500000 # 0.1, 0.2, 0.25, 0.5, 0.75, 1, 1.5, 2 r12_range %(range)i docking_radial_filter 0 # Radial Envelope Filter - None grid_size 0.600 # 0.4, 0.5, 0.6, 0.75, 1.0 # docking_electrostatics 0 # use only surface complimentarity docking_electrostatics 1 # use electrostatic term for scoring clusters docking_main_scan 16 # docking_main_search 26 max_docking_solutions %(nr_sol)i # number of solutions to save # -------------- post-processing ---------------- docking_refine 0 # None # docking_refine 1 # Backbone Bumps # docking_refine 2 # MM energies # docking_refine 3 # MM minimization # ---------------- run docking ------------------ activate_docking # save_docking %(output_clust)s # save_range 1 512 ./ dock .pdb # ------------ also save all solutions ---------- docking_sort_mode 0 # Sort solutions by energy (1 by cluster) save_docking %(output_all)s""" \ %({'range':round(molRange), 'output_all':outName_all, 'nr_sol':int(sol), 'output_clust':outName_clust} ) macOpen.writelines(head) ## macro docking will not work with multiple models, if both are added to ## the hex macro file - macrodocking will be skipped during the docking run if macroDocking: macOpen.writelines(macro) macOpen.writelines(tail) macOpen.close() return macName, outName_all, macroDocking
def __init__( self, traj=None, parm=None, crd=None, ref=None, cast=0, chains=None, border=None, split=0, shift=0, shuffle=0, thin=None, s=0, e=None, ss=0, se=None, step=1, atoms=None, heavy=0, solvent=0, protein=0, ex=[], ex_n=0, ex3=None, ex1=None, fit_s=None, fit_e=None, memsave=1, **kw ): """ :param traj: path to 1 or 2 pickled Trajectory instances (2 separated by '+', e.g. 'rec.traj+lig.traj') :type traj: str :param parm: try using existing parm file & keep it [create+discard] :type parm: str :param crd: target file for amber crd & keep it (default: discard) :type crd: str :param ref: superimpose onto this structure :type ref: str|PDBModel|Complex :param cast: equalize atom content against ref (if given) (default: 1) :type cast: 0|1 :param chains: extract chains from traj (default: None, all chains) :type chains: [int] :param border: 1st chain of 2nd molecule; required for split, shift, shuffle if traj is not already a tuple of trajectories :type border: int :param split: split trajectory after *border* and fit the two halfs separately (default: 0) :type split: 1|0 :param shift: recombine rec and lig member trajectories, should disrupt correlations between rec and lig, requires *chains* or 2 traj files to identify rec (default: 0) :type shift: int :param shuffle: shuffle the order of frames for one trajectory half, requires *border* or 2 traj files to identify rec :type shuffle: 0|1 :param s: start frame of complete traj (default: 0) :type s: int :param e: stop frame of complete traj (default: None) :type e: int :param ss: start frame of single member trajectories (only works with EnsembleTraj; overrides s,e) (default: 0) :type ss: int :param se: stop frame of single member trajectories (only works with EnsembleTraj; overrides s,e) (default: None) :type se: int :param step: frame offset (default: 1, no offset) :type step: int :param thin: use only randomly distributed fraction of frames (default: all) :type thin: float :param atoms: atom names to consider (default: all) :type atoms: [str] :param heavy: remove hydrogens (default: 0) :type heavy: 1|0 :param protein: remove all non-protein atoms (default: don't) :type protein: 1|0 :param solvent: retain solvent and ions (default: 0) :type solvent: 1|0 :param ex: exclude member trajectories :type ex: [int] OR ([int],[int]) :param ex_n: exclude last n members OR... :type ex_n: int :param ex3: exclude *ex3*rd tripple of trajectories (default: 0) (index starts with 1! 0 to exclude nothing) OR.... :type ex3: int :param ex1: exclude *ex1*-th member remaining after applying *ex* (default: None)(index starts with 1! 0 to exclude nothing) :type ex1: int :param fit_s: fit to average of different frame slice :type fit_s: int|None :param fit_e: fit to average of different frame slice :type fit_e: int|None :param memsave: delete internal trajectory after writing crd (default: 1) :type memsave: 1|0 :param kw: additional key=value parameters for AmberCrdEntropist and Executor: :type kw: key=value pairs :: ... parameters for AmberCrdEntropist f_template - str, alternative ptraj input template ... and key=value parameters for Executor: f_out - str, target name for ptraj output file (default: discard) debug - 0|1, keep all temporary files (default: 0) verbose - 0|1, print progress messages to log (log != STDOUT) node - str, host for calculation (None->local) NOT TESTED (default: None) nice - int, nice level (default: 0) log - biskit.LogFile, program log (None->STOUT) (default: None) """ ## tempfile.tempdir = '/work' f_crd = crd or tempfile.mktemp('.crd') self.keep_crd = crd is not None f_parm = t.absfile( parm or tempfile.mktemp( '.parm' ) ) self.keep_parm = parm is not None self.parmcrd = tempfile.mktemp('_ref.crd') AmberCrdEntropist.__init__( self, f_parm, f_crd, s=s, e=e, step=step, **kw ) self.fit_s = fit_s ## if None, fit() will set it to 0 self.fit_e = fit_e ## if None, fit() will set it to len(traj) self.cast = cast self.chains = chains self.border = border self.split = split self.shift = shift self.shuffle= shuffle self.thin = thin self.thin_i = None ## extract same frames from all trajectories self.exclude= ex self.ex_n = ex_n self.sstart = ss ## self.start is assigned by AmberCrdEntropist self.sstop = se ## self.stop is assigned by AmberCrdEntropist self.heavy = heavy self.solvent = solvent self.protein = protein self.atoms = atoms self.memsave= memsave if ex3 in [0, None]: self.ex3 = None else: self.ex3 = ex3-1 if ex3 is not None: self.ex_n = 0 if ex1 is not None: self.ex3 = None self.ex_n = 0 if ex1 in [0, None]: self.ex1 = None else: self.ex1 = ex1-1 ## filter atoms self.ref = self.prepareRef( ref ) ## filter atoms, cast to ref, fit to average and ref self.traj = self.prepareTraj( traj, self.ref, cast=self.cast ) self.nframes = len( self.traj ) ## reset frame limits for AmberCrdEntropist self.start = 0 self.stop = len( self.traj ) self.step = 1
def __init__(self, ini): self.f_ini = T.absfile( ini ) self.result = {}
def absfile( self, fname, resolveLinks=0 ): return T.absfile( fname, resolveLinks=resolveLinks )
traj2ensemble.py -i |in_traj| -n |n_members| -o |out_traj| -pdb |PDBCode| ] o - out file name (default: replace input file) n - number of ensemble members to expect (default: 10) pdb - PDB code to be stored in trajectory """) sys.exit(0) ########## ## MAIN ## use() o = T.cmdDict( {'n':10} ) f_in = T.absfile( o['i'] ) f_out = T.absfile( o.get('o', f_in) ) n = int( o['n'] ) T.flushPrint("Loading...") t = T.load( f_in ) T.flushPrint("Converting %i frames..." % len(t) ) if isinstance(t, EnsembleTraj ): T.flushPrint( "Nothing to be done!\n") sys.exit(0) t = traj2ensemble( t, n ) if 'pdb' in o: t.ref.pdbCode = o['pdb']