def read_types_table(filename): f = open(filename) typestab = {} nrow, ncol = list(map(int, string.split(f.readline()))) typeFormats = string.split(f.readline()) for t in typeFormats: typestab[t] = [] for i in range(nrow - 1): typeNames = string.split(f.readline()) for j in range(ncol): typestab[typeFormats[j]].append(typeNames[j]) f.close() return typestab
def splitInput(filename): """ Split the parallel input file into multiple async file names Parameters filename: The path to the original parallel input file (string) """ nproc = 0 file = open(filename) text = "" while 1: line = file.readline() if line == "": break text += line line = string.strip(line) if line.startswith("pdime"): # Get # Procs words = string.split(line) nproc = int(words[1]) * int(words[2]) * int(words[3]) if nproc == 0: sys.stderr.write("%s is not a valid APBS parallel input file!\n" % filename) sys.stderr.write("The inputgen script was unable to asynchronize this file!\n") sys.exit(2) period = string.find(filename,".") for i in range(nproc): outname = filename[0:period] + "-PE%i.in" % i outtext = string.replace(text, "mg-para\n","mg-para\n async %i\n" % i) outfile = open(outname, "w") outfile.write(outtext) outfile.close()
def set_receptor(self, receptor_filename, gpf_filename=None): self.receptor_filename = os.path.basename(receptor_filename) self.receptor_stem = string.split(self.receptor_filename, '.')[0] self.gpo.set_receptor(receptor_filename) #FIX THIS #self.gpo['mset']['value'] = self.receptor.types self.gpo['types']['value'] = self.ligand.types
def entryV_cb(self, event=None): v = self.entryVTk.get() try: val = string.split(v) except: self.setEntries() return if val is None or len(val) != 3: self.setEntries() return try: valX = float(val[0]) valY = float(val[1]) valZ = float(val[2]) except: self.setEntries() return # compute normalized vector n = math.sqrt(valX * valX + valY * valY + valZ * valZ) if n == 0.0: v = [0.0, 0.0, 1.0] else: v = [valX / n, valY / n, valZ / n] self.vector = v self.setEntries() self.drawVector() if self.continuous: self.callbacks.CallCallbacks(self.vector)
def __makeTree(self, lineList, flexRes=False): # initialize nodeStack = [] atomToParentNode = 0 # first atom after BRANCH goes to parent tor_number = 1 atomIndex = 0 self.activeInFile = [] self.inactiveInFile = [] # process lines/build tree for lineStr in lineList: if debug: print(lineStr) wordList = string.split(lineStr) if not wordList: continue # skip the loop # # Here lies the main switch for the PDBQ tags # if wordList[0] == 'HETATM' or wordList[0] == 'ATOM': # pdb is one-based; we are zero-based if atomToParentNode or flexRes: # The first atom after the BRANCH goes to the parent nodeStack[-1].parent.atomList.append(atomIndex) atomToParentNode = None # unset; set in BRANCH (below) if debug: print("add atom (parent): ", atomIndex, nodeStack[-1].parent) flexRes = False else: nodeStack[-1].atomList.append(atomIndex) if debug: print("add atom: ", atomIndex, nodeStack[-1]) atomIndex = atomIndex + 1 elif (wordList[0] == 'TORS' or wordList[0] == 'BRANCH'): atomToParentNode = 1 # set; unset in HETATM (above) newNode = TreeNode(parent=nodeStack[-1]) newNode.number = tor_number newNode.bond = (int(wordList[1]) - 1, int(wordList[2]) - 1) newNode.atomList = [] tor_number = tor_number + 1 nodeStack.append(newNode) if debug: print("push node: ", newNode) elif (wordList[0] == 'ENDTORS' or wordList[0] == 'ENDBRANCH'): nodeStack.pop() elif wordList[0] == 'ROOT': rootNode = TreeNode() rootNode.number = 0 rootNode.bond = (None, None) rootNode.atomList = [] nodeStack.append(rootNode) if debug: print("push root: ", rootNode) elif wordList[0] == 'ENDROOT': pass elif wordList[0] == 'REMARK' and 'between' in wordList: # record state of each torsion if 'I' in wordList: self.inactiveInFile.append(wordList) if 'A' in wordList: self.activeInFile.append(wordList) else: # ignore it pass return rootNode
def __init__(self, ff, lig_instance): """ Initialize the class by parsing the definition file Parameters ff: The name of the forcefield (string) Additionally, ligands can be considered within this class """ print("lig_instance", lig_instance) self.residues = {} self.name = ff defpath = "" if ff == "amber": defpath = AMBER_FILE elif ff == "charmm": defpath = CHARMM_FILE elif ff == "parse": defpath = PARSE_FILE else: raise ValueError("Invalid forcefield %s!" % ff) if not os.path.isfile(defpath): for path in sys.path: testpath = "%s/%s" % (path, defpath) if os.path.isfile(testpath): defpath = testpath break if not os.path.isfile(defpath): raise ValueError("Unable to find forcefield %s!" % defpath) file = open(defpath) lines = file.readlines() for line in lines: if not line.startswith("#"): fields = string.split(line) resname = fields[0] atomname = fields[1] charge = float(fields[2]) radius = float(fields[3]) atom = ForcefieldAtom(atomname, charge, radius) myResidue = self.getResidue(resname) if myResidue == None: myResidue = ForcefieldResidue(resname) self.residues[resname] = myResidue myResidue.addAtom(atom) # ### PC - charge assignment on ligand ### #self.lig = MOL2MOLECULE() self.lig=lig_instance #lig_shit() #self.lig.read(ligfilename) return
def setArguments(self, **kw): for k, v in list(kw.items()): if type(v) in (float, int, int, bytes): self.arguments[k] = v else: import numpy pat = re.compile("[\[,\]\012]") arrayStr = re.sub(pat, '', str(numpy.array(v).ravel())) c = string.split(arrayStr) c = list(map(float, c)) c = re.sub(pat, '', str(c)) self.arguments[k] = c
def readQConvex(self, filename): """QConvex: http://www.qhull.org/html/qconvex.htm Read a QConvex output file, output a DejaVu IndexedPolygon. Data Format: [...]print vertices and facets of the convex hull in OFF format. The first line is the dimension. The second line is the number of vertices, facets, and ridges. The vertex coordinates are next, followed by the facets. Each facet starts with the number of vertices. The cube example has four vertices per facet.""" try: f = open(os.path.join(self.tmpPath, filename), 'r') data = f.readlines() f.close() except: print('QCONVEX ERROR! Temp. file not found in %s' % self.tmpPath) return # get more header info header = string.split(data[1]) lenVerts = int(header[0]) lenFaces = int(header[1]) vertices = [] faces = [] for d in data[2:lenVerts + 2]: # offset of 2 because of file header spl = string.split(d) vertices.append([float(spl[0]), float(spl[1]), float(spl[2])]) for d in data[lenVerts + 2:]: # offset of 2 because of file header spl = list(map(int, string.split(d))) for i in range(3, len(spl)): faces.append([spl[1], spl[i], spl[i - 1]]) self.geom.Set(vertices=vertices, faces=faces)
def __init__(self, ff): """ Initialize the class by parsing the definition file Parameters ff: The name of the forcefield (string) """ self.residues = {} self.name = ff defpath = "" if ff == "amber": defpath = AMBER_FILE elif ff == "charmm": defpath = CHARMM_FILE elif ff == "parse": defpath = PARSE_FILE else: raise ValueError("Invalid forcefield %s!" % ff) if not os.path.isfile(defpath): for path in sys.path: testpath = "%s/%s" % (path, defpath) if os.path.isfile(testpath): defpath = testpath break if not os.path.isfile(defpath): raise ValueError("Unable to find forcefield %s!" % defpath) file = open(defpath) lines = file.readlines() for line in lines: if not line.startswith("#"): fields = string.split(line) resname = fields[0] atomname = fields[1] charge = float(fields[2]) radius = float(fields[3]) atom = ForcefieldAtom(atomname, charge, radius) myResidue = self.getResidue(resname) if myResidue == None: myResidue = ForcefieldResidue(resname) self.residues[resname] = myResidue myResidue.addAtom(atom)
def parseline(self, line): """Parse the given line and return append a dictionary onto self.clist, the superclass-declared list of conformations. """ line_list = string.split(line) # make a heuristic decision about which keys to use!! if line_list[2] == repr(1.01) or line_list[2][:3] == repr(1.0): # version 1.01 Entropia result file dict = self._parseStateLineList(line_list, self.result_keys_v101) elif float(line_list[9]) == 1.0: # version 1.0 Entropia result file dict = self._parseStateLineList(line_list) else: print("Unparsable result file line: %s" % (line)) return # without doing anything self.clist.append(dict)
def set_ligand(self, ligand_filename): self.ligand_filename = os.path.basename(ligand_filename) if self.verbose: print("set ligand_filename to", self.ligand_filename) self.gpo.set_ligand(ligand_filename) #expect a filename like ind.out.pdbq: get 'ind' from it self.ligand_stem = string.split(self.ligand_filename, '.')[0] if self.verbose: print("set ligand_stem to", self.ligand_stem) self.ligand = Read(ligand_filename)[0] #IS THIS USEFUL??? self.gpo.ligand = self.ligand if self.verbose: print("read ", self.ligand.name) #set gpo: #types d = {} for a in self.ligand.allAtoms: d[a.autodock_element] = 1 sortKeyList = [ 'C', 'A', 'N', 'O', 'S', 'H', 'P', 'n', 'f', 'F', 'c', 'b', 'I', 'M' ] lig_types = "" for t in sortKeyList: if t in list(d.keys()): lig_types = lig_types + t self.ligand.types = lig_types self.gpo['types']['value'] = self.ligand.types if self.verbose: print("set types to ", self.gpo['types']['value']) #gridcenter self.ligand.center = self.ligand.getCenter() if self.size_box_to_include_ligand: self.getSideLengths(self.ligand) #sets ligand.center cen = self.ligand.center self.gpo['gridcenter']['value'] = [round(cen[0],4), round(cen[1],4),\ round(cen[2],4)] self.gpo['gridcenterAuto']['value'] = 0 if self.verbose: print("set gridcenter to ", self.gpo['gridcenter']['value']) #only make the box bigger from npts, do not make it smaller for ix, val in enumerate(self.gpo['npts']['value']): if hasattr(self.ligand, 'npts'): npts = self.ligand.npts if npts[ix] > val: if self.verbose: print("increasing ", ix, " grid dimension to ", val) self.gpo['npts']['value'][ix] = npts[ix]
def write41(self, filename, param_list=grid_parameter_list4): """Write the current state to a file for AutoGrid41 file is a writeable file param_list is a list of parameter strings. For best results use the parameter_lists supplied by this class. """ if filename == '': gpf_ptr = sys.stdout else: gpf_ptr = open(filename, 'w') for p in param_list: if p == 'custom_parameter_file': #old_custom_parameter_file_value = self['custom_parameter_file']['value'] #if old_parameter_file_value=='AD4_parameters.dat': # self['parameter_file']['value'] = 'AD4.1_bound.dat' if self['custom_parameter_file']['value']: old_parameter_file_value = self['parameter_file']['value'] gpf_ptr.write(self.make_param_string('parameter_file')) self['parameter_file']['value'] = old_parameter_file_value elif p == 'map': # maps are a special case for s in string.split(self['ligand_types']['value']): gpf_ptr.write(self.make_map_string(p, s)) # all the other parameters handle themselves elif p == 'gridcenter' and self['gridcenterAuto']['value'] == 1: #if gridcenterAuto is true, reset p to 'auto' and write it self['gridcenter']['value'] = 'auto' gpf_ptr.write(self.make_param_string(p)) elif p == 'dsolvmap': outstring = "dsolvmap %s # desolvation potential map\n" % self[ 'dsolvmap']['value'] gpf_ptr.write(outstring) elif p == 'dielectric4': #now dielectric value can only be set in parameter file #val = self['dielectric4']['value'] outstring = 'dielectric -0.1465 # <0, AD4 distance-dep.diel;>0, constant\n' gpf_ptr.write(outstring) elif p == 'covalentmap' and len(self['covalent_coords']['value']): gpf_ptr.write(self.make_covalentmap_string()) else: gpf_ptr.write(self.make_param_string(p)) if gpf_ptr != sys.stdout: gpf_ptr.close() self.gpf_filename = filename self.gpf_written_filename = filename
def build2LevelsTree(self, atomlines): """ Function to build a two level tree. """ print('try to build a 2 level tree') self.mol = Molecule() self.mol.allAtoms = AtomSet() self.mol.atmNum = {} self.mol.parser = self if self.mol.name == 'NoName': self.mol.name = os.path.basename( os.path.splitext(self.filename)[0]) self.mol.children = AtomSet([]) self.mol.childrenName = 'atoms' self.mol.childrenSetClass = AtomSet self.mol.elementType = Atom self.mol.levels = [Molecule, Atom] ##1/18:self.mol.levels = [Protein, Atom] for atmline in atomlines: atom = Atom(atmline[1], self.mol, chemicalElement=string.split(atmline[5], '.')[0], top=self.mol) #atom.element = atmline[5][0] atom.element = atom.chemElem atom.number = int(atmline[0]) self.mol.atmNum[atom.number] = atom atom._coords = [[ float(atmline[2]), float(atmline[3]), float(atmline[4]) ]] if len(atmline) >= 9: atom._charges['mol2'] = float(atmline[8]) atom.chargeSet = 'mol2' # atom.conformation = 0 atom.hetatm = 0 #add altname so buildBondsByDist doesn't croak atom.altname = None self.mol.allAtoms.append(atom) self.mol.atoms = self.mol.children
def getLoads(): """ Get the system load information for output and logging Returns loads: A three entry list containing the 1, 5, and 15 minute loads. If the load file is not found, return None. """ if LOADPATH == "": return None try: file = open(LOADPATH) except IOError: return None line = file.readline() words = string.split(line) loads = words[:3] return loads
def parseLines(self, lines): """ Parse the lines """ for line in lines: if string.find(line, "ATOM") == 0: subline = string.replace(line[30:], "-", " -") words = string.split(subline) if len(words) < 4: #sys.stderr.write("Can't parse following line:\n") #sys.stderr.write("%s\n" % line) #sys.exit(2) continue self.gotatom = self.gotatom + 1 self.q = self.q + float(words[3]) rad = float(words[4]) center = [] for word in words[0:3]: center.append(float(word)) for i in range(3): self.minlen[i] = min(center[i] - rad, self.minlen[i]) self.maxlen[i] = max(center[i] + rad, self.maxlen[i]) elif string.find(line, "HETATM") == 0: self.gothet = self.gothet + 1
def read_element_table(filename): """void <- read_element_table(filename) populates the elementsTable dictionary from the a given file. the file provides: line number, element string, cov_rad, bond_ord_rad, vdw_rad, bs_rad, max_bonds, red, green, blue """ f = open(filename) lines = f.readlines() f.close() elemTable = {} for i in range(len(lines)): dd = string.split(lines[i]) elemTable[dd[1]] = { 'num': i, 'cov_rad': float(dd[2]), 'bond_ord_rad': float(dd[3]), 'vdw_rad': float(dd[4]), 'bs_rad': float(dd[5]), 'max_bonds': int(dd[6]), 'rgb': (float(dd[7]), float(dd[8]), float(dd[9])) } return elemTable
def Read(filename): from MolKit.pdbParser import PdbParser, PdbqParser, PdbqsParser, PQRParser from MolKit.mol2Parser import Mol2Parser ext = string.split(filename, '.') if ext[-1] == 'pdb': parser = PdbParser(filename) elif ext[-1] == 'pdbq': parser = PdbqParser(filename) elif ext[-1] == 'pdbqs': parser = PdbqsParser(filename) elif ext[-1] == 'pqr': parser = PQRParser(filename) elif ext[-1] == 'mol2': parser = Mol2Parser(filename) else: print("File Format unknown can't parse it") return [] molecules = parser.parse() return molecules
def rundependencychecker(self, pack, v=True, V=False, loc=None): cwd = os.getcwd() import _py2k_string as string packages = {} pn = [] for i in sys.path: s = i.split('/') if s[-1] == "MGLToolsPckgs" or s[-1] == 'site-packages': #if s[-1]=='FDepPackages' or s[-1]=='RDepPackages' or s[-1]=='FSharedPackages' or s[-1]=='RSharedPackages' or s[-1]== 'site-packages': pn.append(i) for p in pn: os.chdir(p) files = os.listdir(p) for f in files: if not os.path.isdir(f): continue pwdir = os.path.join(p, f) if os.path.exists(os.path.join(pwdir, '__init__.py')): if f not in packages: packages[f] = pwdir elif os.path.exists(os.path.join(p, '.pth')): if f not in packages: packages[f] = pwdir os.chdir(cwd) ################################################################ # packages in site-packages ################################################################### pack_site = list(packages.keys()) ########################################################################## # Finding list of import statements used in all packages ########################################################################### Total_packs = [] if V == True: if pack != None: packn = string.split(pack, '.') pack = packn[0] exec('packages={"%s":"%s"}' % (pack, packages[pack])) if packn[-1] != 'py': pack_file = packn[-1] if packn[-1] == 'py': pack_file = packn[-2] else: pack_file = None for pack in packages: files = [] pat = re.compile('import') print("please wait ....") for root, dirs, files in os.walk(packages[pack]): # remove directories not to visit for rem in [ 'CVS', 'regression', 'Tutorial', 'test', 'Doc', 'doc' ]: if rem in dirs: dirs.remove(rem) # look for files that contain the string 'import' for fi in files: if fi[-3:] != '.py': continue if fi[-3:] == '.py': #finds pattern "import" match in that particular file if pack_file != pack: if pack_file != None: if fi != pack_file + '.py': continue else: candidates = [] f = open(os.path.join(root, fi)) data = f.readlines() f.close() found = 0 for line in data: match = pat.search(line) if match: candidates.append( (root, fi, line)) #finds pattern "import" for packages given with option p at file level if pack_file == pack: candidates = [] f = open(os.path.join(root, fi)) data = f.readlines() f.close() found = 0 for line in data: match = pat.search(line) if match: candidates.append((root, fi, line)) #finds pattern "import" match for all packages at file level else: candidates = [] f = open(os.path.join(root, fi)) data = f.readlines() f.close() found = 0 for line in data: match = pat.search(line) if match: candidates.append((root, fi, line)) ####################################### #finding dependencies ####################################### result = [] if len(candidates) > 0: for candidate_num in candidates: p, f, imp = candidate_num path = string.split(p, 'site-packages')[-1] implist = [] fromlist = [] y = string.split(imp) #omitting commemted imports if '.' not in imp and y[0] == "import": len_space = len(imp.split(' ')) len_comma = len(imp.split(',')) if (len_space - 1) > len_comma: continue # as im import statement if "as" in y: for a in y: if a == 'as': aind = y.index(a) if '.' not in y[aind - 1]: implist.append(y[aind - 1]) continue else: newa = y[aind - 1].split('.') implist.append(newa[0]) continue if '#' in y: continue #if first word is import in the list if y[0] == 'import': for i in range(1, len(y)): if y[i][-1] == ";": y[i] = y[i][:-1] if y[i] not in implist: implist.append(y[i]) break if 'as' in y: break if y[i][-1] == ',': y[i] = y[i][:-1] if ',' in y[i]: srg = string.split( y[i], ',') for j in srg: if j not in implist: implist.append(j) continue elif len(y[i]) <= 2: continue #if import statement is like a.q elif len( string.split( y[i], '.')) != 1: sr = string.split( y[i], '.') if sr[0] not in implist: #if module doesn't starts with __ #append to list if sr[0][0] != '__': implist.append( sr[0]) #if import statement with out '.' else: if y[i] not in implist: #print y[i] if y[i][0] != '__': implist.append( y[i]) #import statement with out ',' in the end else: if len(y[i]) == 1: continue elif ',' in y[i]: srg = string.split( y[i], ',') for j in srg: if j not in implist: implist.append(j) continue #import statement as a.b.c.d elif len( string.split( y[i], '.')) > 1: sr = string.split( y[i], '.') if sr[0] not in implist: if sr[0][0] != '__': implist.append( sr[0]) continue #import statement without '.' elif y[i] not in implist: if y[i][0] != '__': implist.append(y[i]) continue for im in implist: #try importing module in implist try: exec('import %s' % im) if im == 'Pmw': if im not in result: if im != pack: result.append(im) continue else: continue #if module.__file__ exists check in #site-packages and append to result exec('fi = %s.__file__' % im) fil = os.path.abspath('%s' % fi) if os.path.exists(fil): file = string.split( str(fil), '/') if file[-2] in pack_site: if file[-2] not in result: if file[-2] != pack: result.append( file[-2]) elif file[-2] == 'Numeric': if 'Numeric' not in result: if 'Numeric' != pack: result.append( 'Numeric') elif file[-2] not in [ 'lib-dynload', pythonv, 'lib-tk' ]: if im not in result: if im != pack: result.append( im) except: if im in [ 'sys', 'gc', 'thread', 'exceptions', 'signal' ]: continue else: if im not in result: result.append(im) #if first word is from in list if y[0] == 'from': #if from statement is like a.b.c if len(string.split(y[1], '.')) != 1: sr = string.split(y[1], '.') if sr[0] not in fromlist: fromlist.append(sr[0]) else: if y[1] != pack: if y[1] not in fromlist: if y[1][0] != '__': fromlist.append(y[1]) for i in fromlist: #checks importing module try: exec('import %s' % i) if i == 'Pmw': if i not in result: if i != pack: result.append(i) continue else: continue #if __file exixts check in site-pacakges #and append to result exec('fi = %s.__file__' % i) fil = os.path.abspath('%s' % fi) if os.path.exists(fil): file = string.split( str(fil), '/') if file[-2] in pack_site: if file[-2] not in result: if file[-2] != pack: result.append( file[-2]) elif file[-2] == 'Numeric': if 'Numeric' not in result: if 'Numeric' != pack: result.append( 'Numeric') elif file[-2] not in [ 'lib-dynload', pythonv, 'lib-tk' ]: if i not in result: if i != pack: result.append( i) except: if i in [ 'sys', 'gc', 'thread', 'exceptions', 'signal' ]: continue else: if i not in result: result.append(i) listdf = [] for r, d, lf in os.walk(packages[pack]): for rem in [ 'CVS', 'regression', 'Tutorial', 'test', 'Doc', 'doc' ]: if rem in d: d.remove(rem) #when files in pack are imported listd = os.listdir(r) for ld in listd: if ld.endswith( '.py') == True or ld.endswith( '.so') == True: for res in result: if res == ld[:-3]: if res in result: result.remove(res) for files in lf: for res in result: pat1 = re.compile('"%s"' % res) pat2 = re.compile("%s.py" % res) fptr = open("%s/%s" % (r, files)) lines = fptr.readlines() for line in lines: match1 = pat1.search(line) match2 = pat2.search(line) if match1 or match2: if res in result: ind = result.index(res) if result[ ind] not in pack_site: del result[ind] continue #In case of Pmv multires,pdb2qr etc if res in files: if res in result: ind = result.index(res) if result[ ind] not in pack_site: del result[ind] for res in result: if res[:3] in ['tmp', 'TMP', 'win']: result.remove(res) continue exec('l = len("%s")' % f) if l > 60: exec('md = string.split("%s",",")[0]' % f) exec( 'f = string.split("%s","/")[-1][:-1]' % md) Total_packs.append('result_%s %s %s %s' % (pack, path, f, result)) #return Total_packs else: Total_packs.append('result_%s %s %s %s' % (pack, path, f, result)) print("result_%s %s %s %s" % (pack, path, f, result)) if Total_packs: return Total_packs else: if pack != None: #print pack pack_list = pack.split(',') if len(pack_list) >= 1: packs = {} for p in pack_list: packs[p] = packages[p] packages = packs print("please wait .......") for pack in packages: files = [] pat = re.compile('import') candidates = [] for root, dirs, files in os.walk(packages[pack]): # remove directories not to visit for rem in [ 'CVS', 'regression', 'Tutorial', 'test', 'Doc', 'doc' ]: if rem in dirs: dirs.remove(rem) # look for files that contain the string 'import' for fi in files: if fi[-3:] != '.py': continue #finding pattern "import" match if fi[-3:] == '.py': f = open(os.path.join(root, fi)) data = f.readlines() f.close() found = 0 for line in data: match = pat.search(line) if match: candidates.append((root, fi, line)) ############################## #finding dependencies ############################## result = [] for candidate_num in candidates: #print candidate_num p, f, imp = candidate_num implist = [] fromlist = [] y = string.split(imp) #omitting commemted imports if '.' not in imp and y[0] == "import": len_space = len(imp.split(' ')) len_comma = len(imp.split(',')) if (len_space - 1) > len_comma: continue if "as" in y: for a in y: if a == 'as': aind = y.index(a) if '.' not in y[aind - 1]: if y[aind - 1] not in implist: implist.append(y[aind - 1]) continue else: newa = y[aind - 1].split('.') if newa[0] not in implist: implist.append(newa[0]) continue if '#' in y: continue #if first word is import in the list if y[0] == 'import': for i in range(1, len(y)): if y[i][-1] == ";": y[i] = y[i][:-1] if y[i] not in implist: implist.append(y[i]) break if "as" in y: break if y[i][-1] == ',': y[i] = y[i][:-1] if ',' in y[i]: srg = string.split(y[i], ',') for j in srg: if j not in implist: implist.append(j) continue elif len(y[i]) <= 2: continue elif len(string.split(y[i], '.')) != 1: sr = string.split(y[i], '.') if sr[0] != pack: if sr[0] not in implist: if sr[0][0] != '__': implist.append(sr[0]) else: if y[i] != pack: if y[i] not in implist: if y[i][0] != '__': implist.append(y[i]) else: if len(y[i]) == 1: continue if len(string.split(y[i], ',')) != 1: srg = string.split(y[i], ',') for j in range(0, len(srg)): if srg[j] not in implist: implist.append(srg[j]) else: continue elif len(string.split(y[i], '.')) != 1: sr = string.split(y[i], '.') if sr[0] not in implist: if sr[0][0] != '__': implist.append(sr[0]) elif y[i] not in implist: if y[i][0] != '__': implist.append(y[i]) for im in implist: try: exec('import %s' % im) if im == 'Pmw': if im not in result: if im != pack: result.append(im) continue else: continue exec('fi = %s.__file__' % im) fil = os.path.abspath('%s' % fi) if os.path.exists(fil): file = string.split(str(fil), '/') if file[-2] in pack_site: if file[-2] not in result: if file[-2] != pack: result.append(file[-2]) elif file[-2] == 'Numeric': if 'Numeric' not in result: if 'Numeric' != pack: result.append('Numeric') elif file[-2] not in [ 'lib-dynload', pythonv, 'lib-tk' ]: if im not in result: if im != pack: result.append(im) except: if im in [ 'sys', 'gc', 'thread', 'exceptions', 'signal' ]: continue if im not in result: if im != pack: result.append(im) #if first word is from in list if y[0] == 'from': if len(string.split(y[1], '.')) != 1: sr = string.split(y[1], '.') if sr[0] != pack: if sr[0] not in fromlist: fromlist.append(sr[0]) else: if y[1] != pack: if y[1] not in fromlist: fromlist.append(y[1]) for i in fromlist: try: exec('import %s' % i) if i == 'Pmw': if i not in result: if i != pack: result.append(i) continue else: continue exec('fi = %s.__file__' % i) fil = os.path.abspath('%s' % fi) if os.path.exists(fil): file = string.split(str(fil), '/') if file[-2] in pack_site: if file[-2] not in result: if file[-2] != pack: result.append(file[-2]) elif file[-2] == 'Numeric': if 'Numeric' not in result: if 'Numeric' != pack: result.append('Numeric') elif file[-2] not in [ 'lib-dynload', pythonv, 'lib-tk' ]: if i not in result: if i != pack: result.append(i) except: if i in [ 'sys', 'gc', 'thread', 'exceptions', 'signal' ]: continue if i not in result: if i != pack: result.append(i) listdf = [] for r, d, lf in os.walk(packages[pack]): for rem in [ 'CVS', 'regression', 'Tutorial', 'test', 'Doc', 'doc' ]: if rem in d: d.remove(rem) #when directory is imported eg: import extent(opengltk/extent) for res in result: if res in d: if res in result: result.remove(res) continue #when files in pack are imported listd = os.listdir(r) for ld in listd: if ld.endswith('.py') == True or ld.endswith( '.so') == True: for res in result: if res == ld[:-3]: if res in result: result.remove(res) #This is for cases in which (mainly tests) some file is created and #for tests purpose and removed .but imported in testfile #like tmpSourceDial.py in mglutil for files in lf: if files[-3:] != ".py": lf.remove(files) continue for res in result: pat1 = re.compile('%s' % res) pat2 = re.compile('%s.py' % res) fptr = open("%s/%s" % (r, files)) lines = fptr.readlines() for line in lines: match1 = pat1.search(line) match2 = pat2.search(line) if match1 or match2: if res in result: ind = result.index(res) if result[ind] not in pack_site: del result[ind] continue #In case of Pmv multires,pdb2qr etc if res in files: if res in result: ind = result.index(res) if result[ind] not in pack_site: del result[ind] continue for res in result: if res[:3] in ['tmp', 'TMP', 'win']: result.remove(res) continue print("result_%s %s" % (pack, result)) Total_packs.append('result_%s %s' % (pack, result)) return Total_packs
def getTestSummaryResults(testroot, testreportdir): """Parse the test report files created by tester. testroot - directory containing the MGLTools packages ; testreportdir - directory containing testreports """ #print "testreportdir:", testreportdir assert os.path.exists(testreportdir) assert os.path.exists(testroot) # list of directories containing Tests ( created when the tests ran last for this platform) cwd = os.getcwd() testdirs = [] os.chdir(testroot) for p in mglpacks: os.path.walk(p, getTestsDirs, testdirs) #print "testdirs" ,testdirs os.chdir(cwd) reports = [] for p in testdirs: reports.append(p.replace(os.sep, '.')) # a dictionary containing the names of test reports rantests = {} # a dictionary containing the names of test reports (with -s option) rantestsS = {} # a list of test modules for which we did not get a report noreports = [] modules = [] # string containing time when the directory was last modified reporttime = time.asctime( time.localtime(os.stat(testreportdir)[stat.ST_MTIME])) # remove time (##:##:##) from reporttime string (leave only the date) rd = string.split(reporttime) rd.pop(-2) reportdate = "%s %s %s %s" % tuple(rd) import sys for r in reports: f1 = os.path.join(testroot, testreportdir, "report-" + r + sys.platform + ".txt") f2 = os.path.join(testroot, testreportdir, "sReport-" + r + sys.platform + ".txt") if os.path.exists(f1): rantests[f1] = r elif os.path.exists(f2): rantestsS[f2] = r else: noreports.append(r) numtests = 0 numerrors = 0 results = {} for file in list(rantestsS.keys()): test = None ntests = 0 testerrors = 0 f = open(file, "r") st = f.readline() l = string.split(st) if len(l) == 5: if l[0] == "RAN": test = rantestsS[file] ntests = float(l[1]) numtests = numtests + ntests modules.append(test) results[test] = {} results[test]['ntests'] = ntests txt = f.readlines() f.close() testname = None errlist = [] errtxt = "" for line in txt: if string.find(line, "Tests.test_") > 0: if string.find(line, "ERROR:") == 0 or string.find( line, "FAIL:") == 0: errlist.append(line) continue testname = line if len(errlist) > 0: errtxt = errtxt + "\n" + testname for err in errlist: errtxt = errtxt + err testerrors = testerrors + len(errlist) errlist = [] continue elif string.find(line, "ERROR:") == 0 or string.find( line, "FAIL:") == 0: errlist.append(line) elif line.startswith("RAN "): if test == None: test = rantestsS[file] modules.append(test) results[test] = {} #print test, file, ntests, numtests, nt = float(line.split()[1]) ntests = ntests + nt numtests = numtests + nt #print ntests, numtests results[test]['ntests'] = ntests #this is for the case when error is in the last test: if len(errlist) > 0: errtxt = errtxt + "\n" + testname for err in errlist: errtxt = errtxt + err testerrors = testerrors + len(errlist) errlist = [] if testerrors: numerrors = numerrors + testerrors results[test]['failed'] = testerrors results[test]['errtxt'] = errtxt for file in list(rantests.keys()): testerrors = 0 f = open(file, "r") st = f.readline() l = string.split(st) if len(l) == 5: if l[0] == "RAN": test = rantests[file] modules.append(test) ntests = float(l[1]) numtests = numtests + ntests results[test] = {} results[test]['ntests'] = ntests txt = f.readlines() f.close() testname = None errlist = [] errtxt = "" for line in txt: if string.find(line, "FAILED (") == 0: if len(errlist) > 0: for err in errlist: errtxt = errtxt + err testerrors = testerrors + len(errlist) errlist = [] continue elif string.find(line, "ERROR:") == 0 or string.find( line, "FAIL:") == 0: errlist.append(line) if testerrors: numerrors = numerrors + testerrors results[test]['failed'] = testerrors results[test]['errtxt'] = errtxt perc = numerrors / numtests * 100.0 if len(noreports): endstr = "No test report for the following module(s) (tests possibly crashed): \n" for f in noreports: endstr = endstr + "%s \n" % f results['tail'] = endstr results['reportdate'] = reportdate results['numtests'] = numtests results['numerrors'] = numerrors results['perc'] = perc return results, modules
def runAPBS(PQR, INPUT): """ Run APBS using PQR and INPUT strings! """ # Initialize the MALOC library startVio() # Initialize variables, arrays com = Vcom_ctor(1) rank = Vcom_rank(com) size = Vcom_size(com) mgparm = MGparm() pbeparm = PBEparm() mem = Vmem_ctor("Main") pbe = new_pbelist(NOSH_MAXMOL) pmg = new_pmglist(NOSH_MAXMOL) pmgp = new_pmgplist(NOSH_MAXMOL) realCenter = double_array(3) totEnergy = [] x = [] y = [] z = [] chg = [] rad = [] # Start the main timer main_timer_start = time.clock() # Parse the input file nosh = NOsh_ctor(rank, size) if not parseInputFromString(nosh, INPUT): stderr.write("main: Error while parsing input file.\n") raise APBSError("Error occurred!") # Load the molecules using Valist_load routine alist = new_valist(NOSH_MAXMOL) #atoms = protein.getAtoms() #protsize = len(atoms) atoms = string.split(PQR, "\n") for i in range(len(atoms)): atom = atoms[i] params = string.split(atom) x.append(float(params[5])) y.append(float(params[6])) z.append(float(params[7])) chg.append(float(params[8])) rad.append(float(params[9])) myAlist = make_Valist(alist, 0) Valist_load(myAlist, len(atoms), x, y, z, chg, rad) # Initialize the energy holders for i in range(nosh.ncalc): totEnergy.append(0.0) potList = [] # Initialize the force holders forceList = [] # Load the dieletric maps dielXMap = new_gridlist(NOSH_MAXMOL) dielYMap = new_gridlist(NOSH_MAXMOL) dielZMap = new_gridlist(NOSH_MAXMOL) # Load the kappa maps kappaMap = new_gridlist(NOSH_MAXMOL) # Load the charge maps chargeMap = new_gridlist(NOSH_MAXMOL) # Do the calculations sys.stdout.write("Preparing to run %d PBE calculations. \n" % nosh.ncalc) for icalc in range(nosh.ncalc): sys.stdout.write("---------------------------------------------\n") calc = NOsh_getCalc(nosh, icalc) mgparm = calc.mgparm pbeparm = calc.pbeparm if calc.calctype != 0: sys.stderr.write("main: Only multigrid calculations supported!\n") raise APBSError("Only multigrid calculations supported!") for k in range(0, nosh.nelec): if NOsh_elec2calc(nosh, k) >= icalc: break name = NOsh_elecname(nosh, k + 1) if name == "": sys.stdout.write("CALCULATION #%d: MULTIGRID\n" % (icalc + 1)) else: sys.stdout.write("CALCULATION #%d (%s): MULTIGRID\n" % ((icalc + 1), name)) sys.stdout.write("Setting up problem...\n") # Routine initMG if initMG(icalc, nosh, mgparm, pbeparm, realCenter, pbe, alist, dielXMap, dielYMap, dielZMap, kappaMap, chargeMap, pmgp, pmg) != 1: sys.stderr.write("Error setting up MG calculation!\n") raise APBSError("Error setting up MG calculation!") # Print problem parameters printMGPARM(mgparm, realCenter) printPBEPARM(pbeparm) # Solve the problem : Routine solveMG thispmg = get_Vpmg(pmg, icalc) if solveMG(nosh, thispmg, mgparm.type) != 1: stderr.write("Error solving PDE! \n") raise APBSError("Error Solving PDE!") # Set partition information : Routine setPartMG if setPartMG(nosh, mgparm, thispmg) != 1: sys.stderr.write("Error setting partition info!\n") raise APBSError("Error setting partition info!") ret, totEnergy[icalc] = energyMG(nosh, icalc, thispmg, 0, totEnergy[icalc], 0.0, 0.0, 0.0) # Set partition information # Write out data from MG calculations : Routine writedataMG writedataMG(rank, nosh, pbeparm, thispmg) # Write out matrix from MG calculations writematMG(rank, nosh, pbeparm, thispmg) # GET THE POTENTIALS potentials = getPotentials(nosh, pbeparm, thispmg, myAlist) potList.append(potentials) # Handle print statements if nosh.nprint > 0: sys.stdout.write("---------------------------------------------\n") sys.stdout.write("PRINT STATEMENTS\n") for iprint in range(nosh.nprint): if NOsh_printWhat(nosh, iprint) == NPT_ENERGY: printEnergy(com, nosh, totEnergy, iprint) elif NOsh_printWhat(nosh, iprint) == NPT_FORCE: printForce(com, nosh, nforce, atomforce, iprint) else: sys.stdout.write("Undefined PRINT keyword!\n") break sys.stdout.write("----------------------------------------\n") sys.stdout.write("CLEANING UP AND SHUTTING DOWN...\n") # Clean up APBS structures #killForce(mem, nosh, nforce, atomforce) killEnergy() killMG(nosh, pbe, pmgp, pmg) killChargeMaps(nosh, chargeMap) killKappaMaps(nosh, kappaMap) killDielMaps(nosh, dielXMap, dielYMap, dielZMap) killMolecules(nosh, alist) delete_Nosh(nosh) # Clean up Python structures #ptrfree(nfor) delete_double_array(realCenter) #delete_int_array(nforce) #delete_atomforcelist(atomforce) delete_valist(alist) delete_gridlist(dielXMap) delete_gridlist(dielYMap) delete_gridlist(dielZMap) delete_gridlist(kappaMap) delete_gridlist(chargeMap) delete_pmglist(pmg) delete_pmgplist(pmgp) delete_pbelist(pbe) # Clean up MALOC structures delete_Com(com) delete_Mem(mem) sys.stdout.write("\n") sys.stdout.write("Thanks for using APBS!\n\n") # Stop the main timer main_timer_stop = time.clock() sys.stdout.write("Total execution time: %1.6e sec\n" % (main_timer_stop - main_timer_start)) #Return potentials return potList
def initialize(definition, ligdesc, pdblist, verbose=0): """ Initialize a ligand calculation by adding ligand atoms to the definition. This code adapted from pdb2pka/pka.py to work with existing PDB2PQR code. Parameters definition: The definition object for PDB2PQR ligdesc: A file desciptor the desired ligand file (string) pdblist: A list of objects from the PDB module in the original protein (list) verbose: When 1, script will print information to stdout Returns protein: The protein created by the original atoms and the ligand definition: The updated definition for this protein Lig: The ligand_charge_handler object """ Lig = ligand_charge_handler() Lig.read(ligdesc) # Create the ligand definition from the mol2 data MOL2FLAG = True X=NEWligand_topology.get_ligand_topology(Lig.lAtoms,True) # Add it to the 'official' definition ligresidue = DefinitionResidue() ligresidue.name = "LIG" i = 1 atommap = {} for line in X.lines[:-2]: obj = DefinitionAtom() entries = string.split(line) if len(entries) != 4: raise ValueError("Invalid line for MOL2 definition!") name = entries[0] obj.name = name obj.x = float(entries[1]) obj.y = float(entries[2]) obj.z = float(entries[3]) atommap[i] = name ligresidue.map[name] = obj i += 1 # The second to last line has a list of bonded partners line = X.lines[-2] bonds = string.split(line) for i in range(0,len(bonds),2): bondA = int(bonds[i]) bondB = int(bonds[i+1]) atomA = ligresidue.getAtom(atommap[bondA]) atomB = ligresidue.getAtom(atommap[bondB]) atomA.bonds.append(atommap[bondB]) atomB.bonds.append(atommap[bondA]) # The last line is not yet supported - dihedrals definition.map["LIG"] = ligresidue # Look for titratable groups in the ligand ligand_titratable_groups=X.find_titratable_groups() if verbose: print("ligand_titratable_groups", ligand_titratable_groups) # Append the ligand data to the end of the PDB data newpdblist=[] # First the protein nummodels = 0 for line in pdblist: if isinstance(line, END) or isinstance(line,MASTER): continue elif isinstance(line, MODEL): nummodels += 1 if nummodels > 1: break else: newpdblist.append(line) # Now the ligand for e in Lig.lAtoms: e.resName = "LIG" newpdblist.append(e) protein = Protein(newpdblist, definition) for rrres in protein.chainmap['L'].residues: for aaat in rrres.atoms: for ligatoms in Lig.lAtoms: if ligatoms.name == aaat.name: aaat.sybylType = ligatoms.sybylType # setting the formal charges if ligatoms.sybylType == "O.co2": aaat.formalcharge = -0.5 else: aaat.formalcharge = 0.0 xxxlll = [] #for xxx in ligatoms.lBondedAtoms: for bond in ligresidue.getAtom(aaat.name).bonds: xxxlll.append(bond) aaat.intrabonds = xxxlll # charge initialisation must happen somewhere else aaat.charge = 0.0 #print aaat.name, aaat.charge, aaat.formalcharge, aaat.intrabonds return protein, definition, Lig
import sys import _py2k_string as string VERSION = string.split(sys.version)[0] if VERSION >= '2.1': from . import testplus else: from . import testplus_before_2_1 testplus = testplus_before_2_1
def __init__(self, ff, definition, userff): """ Initialize the class by parsing the definition file Parameters ff: The name of the forcefield (string) definition: The definition objects userff: A link to the file for CGI based user-defined forcefields """ self.map = {} self.name = ff defpath = "" if userff == None: defpath = getFFfile(ff) if defpath == "": raise ValueError( "Unable to find forcefield parameter file %s!" % path) file = open(defpath) else: file = userff lines = file.readlines() for line in lines: if not line.startswith("#"): fields = string.split(line) if fields == []: continue try: resname = fields[0] atomname = fields[1] charge = float(fields[2]) radius = float(fields[3]) except ValueError: txt = "Unable to recognize user-defined forcefield file" if defpath != "": txt += " %s!" % defpath else: txt += "!" txt += " Please use a valid parameter file." raise ValueError(txt) try: group = fields[4] atom = ForcefieldAtom(atomname, charge, radius, resname, group) except: atom = ForcefieldAtom(atomname, charge, radius, resname) myResidue = self.getResidue(resname) if myResidue == None: myResidue = ForcefieldResidue(resname) self.map[resname] = myResidue myResidue.addAtom(atom) file.close() # Now parse the XML file, associating with FF objects - # This is not necessary (if canonical names match ff names) defpath = getNamesFile(ff) if defpath != "": handler = ForcefieldHandler(self.map, definition.map) sax.make_parser() namesfile = open(defpath) sax.parseString(namesfile.read(), handler) namesfile.close()
def read(self, filename): """ 1.5 2.0 binding 0 0 0 0 0.000 0.000 0.000 -14.645 1 0 1 0 2.449 0.000 0.000 -14.636 0 1 0 1 1.281 1.281 1.281 -14.424 1 1 1 1 2.548 1.014 1.014 -14.210 | | | | | |-rmsd from cluster seed @ 2.0 tolerance | |-rmsd from cluster seed @ 1.0 tolerance |-rmsd from overall reference structure """ file_ptr = open(filename) lines = file_ptr.readlines() # read the file file_ptr.close() d = self.clustering_dict # local copy # see if there's the last char is a 'd' or 'b' or 'e'to denote energy word_list = string.split(lines[0]) if word_list[-1][0] in ['b', 'd', 'e']: file_energy_used = word_list[-1] ind = string.find(lines[0], file_energy_used) lines[0] = lines[0][:ind] # strip energy symbol else: file_energy_used = 'binding' # ??? make sure we're consistent with the argsort #check that self has done some clustering before this if len(self.clustering_dict)>0: assert file_energy_used[0] == self.energy_used[0], 'Cluster energy mismatch' else: #here the dlg had no clustering in it self.energy_used = file_energy_used #redo argsort with file_energy_used if file_energy_used[0] == 'd': energy_list = [conf.docking_energy for conf in self.data] else: energy_list = [conf.binding_energy for conf in self.data] # sort the conformations by energy self.argsort = numpy.argsort(energy_list) #print "self.argsort=", self.argsort t_list = list(map(float, string.split(lines[0]))) #t_list for the example is [0.5, 2.0] num_t = len(t_list) #number of clusterings for tolerance in t_list: # initialize the keys if tolerance in d: raise RuntimeError("overwriting existing clustering") c = d[tolerance] = Clustering() c.tolerance = tolerance # cx is the index into self.data, the list of conformatons # NEW FORMAT: # 0 0 0 0 0.000 0.000 0.000 -14.645 #first line has list of tolerances for cx, l in enumerate(lines[1:]): ll = l.split() #eg: 2 tolerances gives [ 0, 0, 0, 0, 0.000, 0.000, 0.000,-14.645] #num_t *2 c_list = list(map(int, ll[:num_t*2])) data_list = list(map(float, ll[num_t*2:])) for t, i in zip(t_list, range(len(c_list)/2)): cluster_index = c_list[2*i] cluster_rank = c_list[2*i+1] conf = self.data[int(self.argsort[cx])] if cluster_rank == 0: assert len(d[t]) == cluster_index d[t].append(Cluster(conf)) else: # add conformation to its cluster assert len(d[t][cluster_index]) == cluster_rank d[t][cluster_index].append(conf) # tell the conformation what cluster(s) it belongs to... conf.cluster_dict[t] = (cluster_index, cluster_rank) conf.refRMS = data_list[0] conf.clRMS = data_list[1]
def build3LevelsTree(self, atomlines): """ Function to build a 3 levels hierarchy Molecule-substructure-atoms.""" self.mol = Protein() self.mol.allAtoms = AtomSet() self.mol.atmNum = {} self.mol.parser = self if self.mol.name == 'NoName': self.mol.name = os.path.basename( os.path.splitext(self.filename)[0]) self.mol.children = ResidueSet([]) self.mol.childrenName = 'residues' self.mol.childrenSetClass = ResidueSet self.mol.elementType = Residue self.mol.curRes = Residue() self.mol.curRes.hasCA = 0 self.mol.curRes.hasO = 0 self.mol.curRes.CAatom = None self.mol.curRes.Oatom = None self.mol.curRes.C1atom = None self.mol.levels = [Protein, Residue, Atom] for atmline in atomlines: if len(atmline) >= 10: status = string.split(atmline[9], '|') else: status = None resName = atmline[7][:3] resSeq = atmline[7][3:] if resSeq != self.mol.curRes.number or \ resName != self.mol.curRes.type: # check if this residue already exists na = string.strip(resName) + string.strip(resSeq) res = self.mol.get(na) if res: self.mol.curRes = res[0] else: self.mol.curRes = Residue(resName, resSeq, '', self.mol, top=self.mol) name = atmline[1] atom = Atom(name, self.mol.curRes, top=self.mol, chemicalElement=string.split(atmline[5], '.')[0]) #atom.element = atmline[5][0] atom.element = atom.chemElem atom.number = int(atmline[0]) if name == 'CA' or name[:3] == 'CA@': self.mol.curRes.hasCA = 1 self.mol.curRes.CAatom = atom if name == 'O': self.mol.curRes.hasO = 2 self.mol.curRes.Oatom = atom self.mol.atmNum[atom.number] = atom atom._coords = [[ float(atmline[2]), float(atmline[3]), float(atmline[4]) ]] atom._charges['mol2'] = float(atmline[8]) atom.chargeSet = mol2 # atom.conformation = 0 atom.hetatm = 0 #Add a data member containing a list of string describing # the Sybyl status bis of the atoms. atom.status = status #add altname so buildBondsByDist doesn't croak atom.altname = None self.mol.allAtoms.append(atom) self.mol.residues = self.mol.children assert hasattr(self.mol, 'chains') delattr(self.mol, 'chains') delattr(self.mol, 'curRes')
) usage() sys.exit() # make sure directory exists try: os.stat(directory) except OSError as msg: log.error("summarize_docking_directory: %s: %s", msg.strerror, msg.filename) sys.exit() # get absolute, normalized directory_path directory_pathname = os.path.abspath(directory) + "/" docking_pathname = os.path.dirname(directory_pathname) docking_name = string.split(docking_pathname, '/')[-1] log.debug("directory: %s" % directory) log.debug("directory_pathname: %s" % directory_pathname) log.debug("docking_pathname: %s" % docking_pathname) log.debug("docking_name: %s" % docking_name) output_fileptr = sys.stdout if output_filename: output_filepath = os.path.join(docking_pathname, output_filename) output_fileptr = open(output_filepath, 'w') log.info("Writing to %s" % output_filepath) else: if write_to_file: # create output filename from directory and rms_tolerance output_filepath = os.path.join(docking_pathname, docking_name) + \
def parse_PDB_ATOM_record(self, rec): """Parse PDB ATOM records using the pdb columns specifications""" self.atomCounter = self.atomCounter + 1 # not sure about altLoc if self.specType=='i': rec = string.split(rec) # Handle the alternate location using a flag. altLoc = self.get_Field_Value(rec, 'altLoc') if altLoc!= ' ': self.altLoc = altLoc else: self.altLoc = '' # changed from None to '' # check for chains break #self.modlflag = modlflag #chainID = rec[21]+ modlflag hascid = 1 chainID = self.get_Field_Value(rec, 'chainID') if not chainID: hascid = 0 chainID = str(self.chaincounter) ## should be unk??? if chainID != self.mol.curChain.id : # has to check if the chain exists already or not !!! if not self.mol.chains.id or not chainID in self.mol.chains.id or \ hascid==0: self.chaincounter = self.chaincounter + 1 if hascid==0: chainID = str(self.chaincounter) self.mol.curChain = Chain(chainID, self.mol, top=self.mol) self.residueCounter = 0 else: self.mol.curChain = self.mol.chains.get(chainID)[0] # check for residue break resName = self.get_Field_Value(rec, 'resName') resSeq = string.strip(self.get_Field_Value(rec, 'resSeq')) #WARNING reSeq is a STRING noresSeq = 0 if not resSeq and resName==self.mol.curRes.type and resName!='HOH': noresSeq = 1 resSeq = self.mol.curRes.number if resSeq != self.mol.curRes.number or \ resName != self.mol.curRes.type: # check if this residue already exists na = string.strip(resName) + string.strip(resSeq) res = self.mol.curChain.get( na ) if res: self.mol.curRes = res[0] else: self.residueCounter = self.residueCounter + 1 if resName=='HOH': self.HOHCounter = self.HOHCounter + 1 if not resSeq: if resName=='HOH': resSeq = self.HOHCounter else: resSeq = self.residueCounter ## FIXME icodes are ignored self.mol.curRes = Residue(resName, resSeq, '', self.mol.curChain, top=self.mol) icode = self.get_Field_Value(rec, 'iCode') if not icode: pass elif icode != ' ': self.mol.curRes.icode = icode # parse atom info # handle atom names (calcium, hydrogen) and find element type # check validity of chemical element column and charge column ## only works if 'name' is in the pdb format! FIX! n = self.get_Field_Value(rec, 'name') el = self.get_Field_Value(rec, 'element') if n: name, element = self.getPDBAtomName(n, el) # if there is not resSeq spec, use first N to figure out new res if noresSeq and name=='N': At = self.mol.curRes.get('N') if At: self.residueCounter = self.residueCounter + 1 resSeq = self.residueCounter self.mol.curRes = Residue(resName, resSeq, self.mol.curChain, top=self.mol) atom = Atom(name, self.mol.curRes, element, top=self.mol) else: element = el if element: atom = Atom(parent = self.mol.curRes, chemicalElement = element, top=self.mol) else: atom = Atom(parent = self.mol.curRes, top=self.mol) ## elem = string.lower(element) # moved to getPDBAtomName ## if elem =='lp' or elem =='ld': ## element = 'Xx' atom.charge = self.get_Field_Value(rec, 'charge') #should have atom.charge if no charge? # coords are required; where to set default or check? xcoord = self.get_Field_Value(rec, 'x') ycoord = self.get_Field_Value(rec, 'y') zcoord = self.get_Field_Value(rec, 'z') assert xcoord and ycoord and zcoord atom._coords = [ [ float(xcoord), float(ycoord), float(zcoord) ] ] atom.segID = string.strip(self.get_Field_Value(rec, 'segID')) if rec[:4]=='ATOM' or rec[0]=='ATOM': atom.hetatm = 0 else: atom.hetatm = 1 #atom.alternate = [] atom.element = element num = self.get_Field_Value(rec, 'serial') if num: atom.number = int(num) else: atom.number = self.atomCounter occupancy = self.get_Field_Value(rec, 'occupancy') if occupancy: atom.occupancy = float(occupancy) # must check that it is a number atom.conformation = 0 tempFactor = self.get_Field_Value(rec, 'tempFactor') if tempFactor: atom.temperatureFactor = float(tempFactor) # add in user defined fields to atom attributes for field_name in list(self.recSpecs.UserFieldsDict.keys()): value = self.get_Field_Value(rec, field_name) type = self.recSpecs.get(field_name, 'var_type') if value: if type=='int': atom.__setattr__(field_name, int(value)) elif type=='float': atom.__setattr__(field_name, float(value)) else: atom.__setattr__(field_name, value) else: atom.__setattr__(field_name, value) if self.altLoc : # check if the name of the atom is the same than the #name of the previous atom . name = name + '@'+self.altLoc atom.name = name if len(self.mol.curRes.atoms)>1: # the new atom has been add to the current residue # You have to go to the one before. lastAtom = self.mol.curRes.atoms[-2] altname = string.split(lastAtom.name, '@')[0] if string.split(name, '@')[0] == altname: # Add the new alternate atom to the LastAtom.alternate and # add the lastAtom to the atom.alternate. lastAtom.alternate.append(atom) atom.alternate.append(lastAtom) for l in lastAtom.alternate: if atom.name != l.name: atom.alternate.append(l) l.alternate.append(atom) return atom
lig_types = gpfm.gpo['ligand_types']['value'].split() all_types = lig_types for t in flexres_types: if t not in all_types: all_types.append(t) all_types_string = all_types[0] if len(all_types) > 1: for t in all_types[1:]: all_types_string = all_types_string + " " + t gpfm.gpo['ligand_types']['value'] = all_types_string for param_str in parameters: if param_str.find("parameter_file") > -1: parameters.append("custom_parameter_file=1") break for p in parameters: key, newvalue = string.split(p, '=') if key == 'gridcenter' and newvalue.find(',') > -1: newvalue = newvalue.split(',') newvalue = string.join(newvalue) kw = {key: newvalue} gpfm.set_grid_parameters(*(), **kw) #gpfm.set_grid_parameters(spacing=1.0) if center_on_ligand is True: gpfm.gpo['gridcenterAuto']['value'] = 0 cenx, ceny, cenz = gpfm.ligand.getCenter() gpfm.gpo['gridcenter']['value'] = "%.3f %.3f %.3f" % (cenx, ceny, cenz) if npts_increment: orig_npts = gpfm.gpo['npts']['value'] #[40,40,40] if verbose: print("before increment npts=", orig_npts) for ind in range(3): gpfm.gpo['npts']['value'][ind] += npts_increment
def read4(self, filename): """Read from and set the current state according to the AutoGrid4 file. """ self.gpf_filename = filename gpf_ptr = open(filename) lines = gpf_ptr.readlines() gpf_ptr.close() keys = list(self.keys()) self.file_params = [] for line in lines: #print "reading ", line words = string.split(string.replace(line, '\t', ' ')) #print "words=", words if words != [] and words[0][0] != '#': p = words[0] if p not in keys: print("WARNING: unrecognized parameter in ", filename, ":\n", p) continue #print "p=", p # maintain a list of the parameters read from the file if self.file_params == [] or p != self.file_params[-1]: self.file_params.append(p) # parse the line l = len(words) for i in range(l): if words[i][0] == '#': l = i break values = words[1:l] if p == 'parameter_file': self['custom_parameter_file']['value'] = 1 self['parameter_file']['value'] = values[0] elif ((len(values) == 1) and (type(self[p]['default']) != list)): self[p]['value'] = self._get_val(values[0]) #print " value=", self[p]['value'] #if words[0]=='types': # #in this case have to set flags for possible new type # extraLigandTypes = self.checkLigTypes(values[0]) #setting dielectric from a gpf is no longer supported #instead must be set in a parameter library file #elif p=='dielectric': # self['dielectric4']['value'] = self._get_val(values[0]) elif p == 'ligand_types': self['ligand_types']['value'] = string.join(words[1:l]) elif p == 'receptor_types': self['receptor_types']['value'] = string.join(words[1:l]) elif words[0] == 'covalentmap': #in this case set: #covalent_ coords,constant,energy_barrier,half_width self['covalentmap']['value'] = 1 self['covalent_half_width']['value'] = float(values[1]) self['covalent_energy_barrier']['value'] = float(values[2]) self['covalent_coords']['value'] = [float(values[3]),\ float(values[4]), float(values[5])] self[p]['value'] = [] elif words[0] == 'gridcenter' and l > 1: #need to convert to float newvalue = [ float(values[0]), float(values[1]), float(values[2]) ] self['gridcenterAuto']['value'] = 0 self[p]['value'] = newvalue else: #print "in else for ", p self[p]['value'] = [] for v in values: self[p]['value'].append(self._get_val(v))
def compute(self): spl=[] coordflag = 0 indexflag = 0 scaleflag = 0 coords = [] indices = [] scale=[] llc = [] lli = [] result = [] ind = [] length = 0 for i in range(len(self.data)): d = self.data[i] spl = string.split(d) for k in range(len(spl)): if spl[k] == 'coord' and spl[k+1] == 'Coordinate': coordflag = 1 if spl[k] == 'coordIndex': indexflag = 1 if spl[k] == 'scale': scaleflag = 1 if coordflag == 1: if spl[0]=='}': # we reach the end of 'coords' coordflag=0 continue if spl[0] == 'coord': #this is the first line which we dont continue #want to parse if spl[-1] == ']': #this is the last line where we want lc = spl[-4:-1] #to get rid of the ']' else: lc = spl[-3:] lc[-1] = lc[-1][:-1] llc=[] for n in range(len(lc)): llc.append(float(lc[n])) coords.append(llc) if indexflag == 1: testEnd = string.split(d) # if testEnd[0]=='texCoord': # indexflag=0 # continue if spl[-1] == ']': #this is the last line where we want li = spl[-9:-1] #to get rid of the ']' li[-1] = li[-1]+',' #and add a ',' to the last number indexflag=0 else: li = spl[-8:] ind.extend(li) lli = [] if scaleflag == 1: sc = string.split(d) scale.append( float(sc[1]) ) scale.append( float(sc[2]) ) scale.append( float(sc[3]) ) scaleflag = 0 # make index list. Note that we add -1 as many times as needed # to each index entry in order to make them all the same length lenght=0 # this is the variable that tells us how many -1 we will ad for n in range(len(ind)): if ind[n] != '-1,': lli.append(int(ind[n][:-1])) else: lli.reverse() # index list has to be inverted lli.append(-1) if len(lli) > length: length = len(lli) indices.append(lli) lli = [] # here we go again over the indices and add the -1 if necessary for m in range(len(indices)): if len(indices[m]) < length: for o in range(length-len(indices[m])): indices[m].append(-1) # apply scale to coords if len(scale): coords = numpy.multiply(coords, scale) result = [coords]+[indices] return result