def getObjFromName(self, name, module=None, testDirName='Tests'): if name[-3:] == '.py': name = name[:-3] if '/' in name: parts = name.split('/') parts = [x for x in parts if x] else: parts = name.split('.') parts = [x for x in parts if x] if module is None: if not parts: raise ValueError("incomplete test name: %s" % name) else: parts_copy = parts[:] while parts_copy: try: module = __import__(string.join(parts_copy,'.')) break except ImportError: del parts_copy[-1] if not parts_copy: raise parts = parts[1:] obj = module for part in parts: obj = getattr(obj, part) if part==testDirName: if 'ignore' in obj.__dict__: self.ignore = getattr(obj,'ignore') return obj
def _rc_find(self,codes, pattern): """_rc_find(codes, pat_obj) - find a endpoints of a regexp Given a list of mesostate codes, this function identifies a endpoints of a match <pattern>. <pat_obj> is a compiled regular expression pattern whose matches will be returned as pairs indicated start, end in <codes> """ CODE_LENGTH = self.MSDEFS['CODE_LENGTH'] if not type(codes) == type(''): codes = string.join(codes, '') matches = [] it = pattern.finditer(codes) try: while 1: mat = next(it) matches.append((mat.start()/CODE_LENGTH, mat.end()/CODE_LENGTH)) except StopIteration: pass return matches
def write(self, dpo, style='GALS'): #one file per ligand dpffiles = [] receptor_stem = self.dpo.receptor_stem parm_list = self.parm_list_dict[style] if not len(self.ligandfilenames): self.getligands(self.extension) #print "len(self.ligandfilenames)=", len(self.ligandfilenames) for ligand_file in self.ligandfilenames: #get the types typeDict = {} m = Read(ligand_file)[0] for a in m.allAtoms: typeDict[a.autodock_element] = 1 type_list = list(typeDict.keys()) #check that there is a map for each type ok = 1 for t in type_list: mapfile = receptor_stem + '.' + t + '.map' try: assert os.path.exists(mapfile) except: ok = 0 ostr = ligand_file + " missing map " + t + "\n" self.error_file.write(ostr) break #try to continue 'for' statement with next filename #update dpo with ligand specific values if not ok: if self.verbose: print("problem with ", ligand_file) continue types = string.join(type_list,'') self.dpo['move']['value'] = ligand_file if self.verbose: print("set types to ", types) self.dpo['types']['value'] = types #CAUTION: dpo['torsdof']['value'] is [0,0.3113] self.dpo['torsdof']['value'][0] = m.TORSDOF if hasattr(m, 'ndihe'): ndihe = m.ndihe elif hasattr(m, 'torscount'): ndihe = m.torscount elif hasattr(m, 'torTree'): ndihe = len(m.torTree.torsionMap) else: msg = ligand_file + " is not properly formatted: no torsions!" raise AttributeError(msg) self.dpo['ndihe']['value'] = ndihe outputfilename = self.prefix + m.name + "_" + style + ".dpf" if self.verbose: print("writing ", outputfilename) self.dpo.write(outputfilename, parm_list) dpffiles.append(outputfilename) return dpffiles
def write(self, gpo): #set types in groups of 6 + write outputlist = [] number_of_files = len(self.alltypes)/6 + 1 ctr = 0 last = 6 for i in range(number_of_files): if i == number_of_files-1: current_types = self.alltypes[ctr*6:] elif last>len(self.alltypes): current_types = self.alltypes[ctr*6:] else: current_types = self.alltypes[ctr*6:last] gpo['types']['value'] = string.join(current_types,'') if not gpo.receptor_stem: gpo.receptor_stem = os.path.splitext(gpo['receptor']['value'])[0] outputfilename = self.prefix + gpo.receptor_stem + '_'+ str(ctr) + '_library.gpf' gpo.write(outputfilename, grid_parameter_list) ctr = ctr + 1 last = last + 6 outputlist.append(outputfilename) return outputlist
def loadTestsFromFunctions(self, functions, setUp=None, tearDown=None): """ The functions needs to be from the same module. creates a FunctionTestCase for each function in the sequence and returns a TestSuite. """ ftc = [] if not type(functions) in [tuple, list] and \ type(functions) is types.FunctionType: functions = [functions,] m = functions[0].__module__ modName = m.split('.')[-1] parts = m.split(".")[:-1] p = string.join(parts, '/') modPath = os.path.abspath(p) for func in functions: if not type(func) is types.FunctionType:continue ftc.append(unittest.FunctionTestCase(func, setUp=setUp, tearDown=tearDown)) return (modPath, self.suiteClass(ftc))
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 if verbose: print("after increment npts =", gpfm.gpo['npts']['value']) gpfm.write_gpf(output_gpf_filename)
lig = Read(ligandfilename)[0] ext = os.path.splitext(ligandfilename)[1] if outputfilename is None: outputfilename = lig.name + "_rigid" + ext if verbose: print('set outputfilename to ', outputfilename) parser = lig.parser optr = open(outputfilename, 'w') #have to add newline character to lines read from dlg for l in parser.allLines: if l.find("active torsions:") > -1: nl = "REMARK 0 active torsions:\n" optr.write(nl) elif l.find("A between atoms:") > -1: ll = l.split() #REMARK,1,A,between,atoms:,N1_1517,and,C31_1555" nl = ll[0] + " I " + string.join(ll[3:]) + "\n" optr.write(nl) elif l.find("TORSDOF") == 0: nl = "ENDROOT\n" optr.write(nl) optr.write(l) elif l.find("BRANCH") == -1 and l.find("ENDBRANCH") == -1 and l.find( "ENDROOT") == -1: optr.write(l) if verbose: print('wrote %s' % outputfilename) # To execute this command type: # write_rigid_ligand.py -l ligandfilename [-o outputfilename] -v
def loadTestsFromName(self, name, recursive=False, module=None, testDirName='Tests', modPrefix=None, funcPrefix=None): """ Returns a suite of all tests cases given a string specifier. The name may resolve either a package, a module, a test case class, a test method within a test case class, a test function or a callable object which returns a TestCase or TestSuite instance. The metod optionally resolves the names relative to a given module. """ if funcPrefix: self.testMethodPrefix=funcPrefix ## if name[-3:] == '.py': ## name = name[:-3] ## if '/' in name: ## parts = name.split('/') ## else: ## parts = name.split('.') obj = self.getObjFromName(name, module=module, testDirName=testDirName) import unittest if type(obj) == types.ModuleType: # Can either be a python module or a python package. if hasattr(obj,'__path__') and os.path.isdir(obj.__path__[0]): if recursive: return self.loadTestsFromPackageRecur(obj, testDirName=testDirName, modPrefix=modPrefix ) else: return self.loadTestsFromPackage(obj, testDirName=testDirName, modPrefix=modPrefix) else: return self.loadTestsFromModule(obj) elif (isinstance(obj, type) and issubclass(obj, unittest.TestCase)): m = obj.__module__ parts = m.split(".")[:-1] p = string.join(parts, "/") return (p, self.loadTestsFromTestCase(obj)) elif type(obj) == types.FunctionType: # need to get the setUp and tearDown method. m = obj.__module__ module = __import__(m) parts = m.split('.') p = string.join(parts[:-1], '/') modPath = os.path.abspath(p) for part in parts[1:]: module = getattr(module , part) setUp = None tearDown = None setUpSuite = None tearDownSuite = None if 'setUp' in module .__dict__: setUp = getattr(module , 'setUp') if 'tearDown' in module .__dict__: tearDown = getattr(module , 'tearDown') if 'setUpSuite' in module .__dict__: setUpSuite = getattr(module, 'setUpSuite') if not type(setUpSuite) is types.FunctionType: setUpSuite=None if 'tearDownSuite' in module .__dict__: tearDownSuite = getattr(module, 'tearDownSuite') if not type(tearDownSuite) is types.FunctionType: tearDownSuite=None tfc = unittest.FunctionTestCase(obj, setUp=setUp, tearDown=tearDown) ts = self.suiteClass(tests = [tfc,], setUpSuite=setUpSuite, tearDownSuite=tearDownSuite) return (modPath, ts) elif type(obj) == types.UnboundMethodType: newobj = obj.__self__.__class__(obj.__name__) m = newobj.__module__ parts = m.split(".")[:-1] p = string.join(parts, "/") #return (p, obj.im_class(obj.__name__)) ts = self.suiteClass(tests=list(map(obj.__self__.__class__, [obj.__name__,]))) return (p, ts) elif callable(obj): test = obj() if not isinstance(test, unittest.TestCase) and \ not isinstance(test, unittest.TestSuite): raise ValueError("calling %s returned %s, not a test" % (obj,test)) return (None,test) else: raise ValueError("don't know how to make test from: %s" % obj)
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 read(self, filename): """Read from and set the current state according to the file. """ self.gpf_filename = filename gpf_ptr = open(filename) lines = gpf_ptr.readlines() gpf_ptr.close() self.file_params = [] checkedTypes = [] extraLigandTypes = [] keys = list(self.keys()) for line in lines: words = string.split(string.replace(line, '\t', ' ')) if words != [] and words[0][0] != '#': p = words[0] if p not in keys: print("WARNING: unrecognized parameter in ", filename, ":\n", p) continue # 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 ((len(values) == 1) and (type(self[p]['default']) != list)): self[p]['value'] = self._get_val(values[0]) if words[0] == 'types': #in this case have to set flags for possible new type extraLigandTypes = self.checkLigTypes(values[0]) elif words[0] == 'ligand_types': self[p]['value'] = string.join(words[1:l]) elif words[0] == 'receptor_types': self[p]['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[0]) self['covalent_energy_barrier']['value'] = float(values[1]) self['covalent_coords']['value'] = [float(values[2]),\ float(values[3]), float(values[4])] self[p]['value'] = [] elif words[0] == 'nbp_r_eps': #in this case have to check for nhb,ohb,shb +mset #in this case have to check for new type constants ptype = words[-1] if len(words[l]) == 1: keyWord = words[l + 1] else: keyWord = words[l][1:] mtype = string.split(keyWord, '-')[0] ntype = string.split(keyWord, '-')[1] if mtype in checkedTypes: continue if mtype in ['N', 'O', 'S'] and ntype == 'H': #check for 12 6 vs 12 10 here ind = mtype + 'HB' if values[3] == '10': self[ind]['value'] = 1 else: self[ind]['value'] = 0 checkedTypes.append(mtype) if mtype in extraLigandTypes: i = ptype + mtype + ntype Rij[i] = float(words[1]) epsij[i] = float(words[2]) elif words[0] == 'sol_par': if len(words[l]) == 1: mtype = words[l + 1] else: mtype = words[l][1] if mtype in extraLigandTypes: SolVol[mtype] = float(values[0]) SolPar[mtype] = float(values[1]) elif words[0] == 'constant': if len(words[l]) == 1: mtype = words[l + 1] else: mtype = words[l][1] SolCon[mtype] = float(values[0]) 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: self[p]['value'] = [] for v in values: self[p]['value'].append(self._get_val(v))