def com(selection,state=None,mass=None,object=None, quiet=1, **kwargs): """ DESCRIPTION Places a pseudoatom at the center of mass Author: Sean Law Michigan State University slaw (at) msu . edu SEE ALSO pseudoatom, get_com """ quiet = int(quiet) if (object == None): object = cmd.get_legal_name(selection) object = cmd.get_unused_name(object + "_COM", 0) cmd.delete(object) if (state != None): x, y, z=get_com(selection,mass=mass, quiet=quiet) if not quiet: print "%f %f %f" % (x, y, z) cmd.pseudoatom(object,pos=[x, y, z], **kwargs) cmd.show("spheres",object) else: for i in range(cmd.count_states()): x, y, z=get_com(selection,mass=mass,state=i+1, quiet=quiet) if not quiet: print "State %d:%f %f %f" % (i+1, x, y, z) cmd.pseudoatom(object,pos=[x, y, z],state=i+1, **kwargs) cmd.show("spheres", 'last ' + object)
def minimize(selection='all', forcefield='MMFF94s', method='conjugate gradients', nsteps=500, conv=0.0001, cutoff=False, cut_vdw=6.0, cut_elec=8.0): pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('pdb', 'pdb') mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) mol.AddHydrogens() ff = ob.OBForceField.FindForceField(forcefield) # GAFF, MMFF94s, MMFF94, UFF, Ghemical ff.Setup(mol) if cutoff == True: ff.EnableCutOff(True) ff.SetVDWCutOff(cut_vdw) ff.SetElectrostaticCutOff(cut_elec) if method == 'conjugate gradients': ff.ConjugateGradients(nsteps, conv) else: ff.SteepestDescent(nsteps, conv) ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) if name == 'all': name = 'all_' cmd.read_pdbstr(pdb_string, name) print '#########################################' print 'The Energy of %s is %8.2f %s ' % (name, nrg, ff.GetUnit()) print '#########################################'
def minimize(selection='all', forcefield='MMFF94s', method='Conjugate Gradients', nsteps0=500, conv=0.0001, cutoff=False, cut_vdw=6.0, cut_elec=8.0): mol_string = cmd.get_str('mol', selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('mol', 'mol') mol = ob.OBMol() obconversion.ReadString(mol, mol_string) ff = ob.OBForceField.FindForceField( forcefield) ## GAFF, MMFF94s, MMFF94, UFF, Ghemical ff.Setup(mol) if cutoff == True: ff.EnableCutOff(True) ff.SetVDWCutOff(cut_vdw) ff.SetElectrostaticCutOff(cut_elec) if method == 'Conjugate Gradients': ff.ConjugateGradients(nsteps0, conv) else: ff.SteepestDescent(nsteps0, conv) ff.GetCoordinates(mol) nrg = ff.Energy() mol_string = obconversion.WriteString(mol) cmd.delete(name) if name == 'all': name = 'all_' cmd.read_molstr(mol_string, name, state=0, finish=1, discrete=1) print('#########################################') print('The Energy of %s is %8.2f %s ' % (name, nrg, ff.GetUnit())) print('#########################################')
def minimize(selection='all', forcefield='MMFF94s', method='cg', nsteps=2000, conv=1E-6, cutoff=False, cut_vdw=6.0, cut_elec=8.0): pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('pdb', 'pdb') mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) ff = ob.OBForceField.FindForceField(forcefield) ff.Setup(mol) if cutoff == True: ff.EnableCutOff(True) ff.SetVDWCutOff(cut_vdw) ff.SetElectrostaticCutOff(cut_elec) if method == 'cg': ff.ConjugateGradients(nsteps, conv) else: ff.SteepestDescent(nsteps, conv) ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) if name == 'all': name = 'all_' cmd.read_pdbstr(pdb_string, name) return nrg
def dehydron(selection='all', angle_range=40, max_distance=3.5, desolv=6.5, min_wrappers=19, quiet=0): ''' DESCRIPTION dehydron calculator USAGE dehydron [ selection [, angle_range [, max_distance [, desolv [, min_wrappers ]]]]] ''' angle, max_distance = float(angle_range), float(max_distance) desolv, min_wrappers = float(desolv), int(min_wrappers) quiet = int(quiet) name = cmd.get_legal_name('DH_%s' % selection) cmd.delete(name) selection_hb = '((%s) and polymer)' % (selection) hb = cmd.find_pairs("((byres "+selection_hb+") and n. n)","((byres "+selection_hb+") and n. o)",mode=1,cutoff=max_distance,angle=angle_range) if not quiet: hb.sort(lambda x,y:(cmp(x[0][1],y[0][1]))) print "--------------------------------------------------------------------" print "--------------------------Dehydron Results--------------------------" print "--------------------------------------------------------------------" print " Donor | Aceptor |" print " Object Chain Residue | Object Chain Residue | # wrappers" cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0) try: cmd.select('_selection', '%s' % selection, 0) except: pass sel = [] for pairs in hb: wrappers = cmd.count_atoms('((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' % ((pairs[0][0], desolv) + pairs[0] + pairs[1])) if wrappers < min_wrappers: cmd.distance(name, pairs[0], pairs[1]) if not quiet: cmd.iterate(pairs[0], 'stored.nitro = chain, resi, resn') cmd.iterate(pairs[1], 'stored.oxy = chain, resi, resn') print ' %12s%4s%6s%5d | %12s%4s%6s%5d |%7s' % (pairs[0][0], stored.nitro[0], stored.nitro[2], int(stored.nitro[1]), pairs[1][0], stored.oxy[0], stored.oxy[2], int(stored.oxy[1]), wrappers) sel.append(pairs[0]) sel.append(pairs[1]) cmd.delete('_nonpolar') cmd.delete('_selection') if len(sel) > 0: cmd.show_as('dashes', name) elif not quiet and len(hb) != 0: print ' - no dehydrons were found - ' else: print ' - no hydrogen bonds were found - '
def conf_search(selection="all", forcefield="MMFF94s", method="Weighted", nsteps=500, conformers=25, lowest_conf=5): pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats("pdb", "pdb") mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) mol.AddHydrogens() ff = ob.OBForceField.FindForceField(forcefield) ## GAFF, MMFF94s, MMFF94, UFF, Ghemical ff.Setup(mol) if method == "Weighted": ff.WeightedRotorSearch(conformers, nsteps) elif method == "Random": ff.RandomRotorSearch(conformers, nsteps) else: ff.SystematicRotorSearch(nsteps) if name == "all": name = "all_" if method in ["Weighted", "Random"]: ff.GetConformers(mol) print "##############################################" print " Conformer | Energy | RMSD" nrg_unit = ff.GetUnit() rmsd = 0 ff.GetCoordinates(mol) nrg = ff.Energy() conf_list = [] for i in range(conformers): mol.SetConformer(i) ff.Setup(mol) nrg = ff.Energy() conf_list.append((nrg, i)) conf_list.sort() lenght_conf_list = len(conf_list) if lowest_conf > lenght_conf_list: lowest_conf = lenght_conf_list for i in range(lowest_conf): nrg, orden = conf_list[i] name_n = "%s%02d" % (name, i) cmd.delete(name_n) mol.SetConformer(orden) pdb_string = obconversion.WriteString(mol) cmd.read_pdbstr(pdb_string, name_n) if i != 0: rmsd = cmd.fit(name_n, "%s00" % name, quiet=1) print "%15s | %10.2f%9s |%6.1f" % (name_n, nrg, nrg_unit, rmsd) print "##############################################" else: ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) cmd.read_pdbstr(pdb_string, name) print "#########################################" print "The Energy of %s is %8.2f %s " % (name, nrg, ff.GetUnit()) print "#########################################"
def conf_search(selection='all', forcefield='MMFF94s', method='Weighted', nsteps=500, conformers=25, lowest_conf=5): pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('pdb', 'pdb') mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) mol.AddHydrogens() ff = ob.OBForceField.FindForceField(forcefield) # GAFF, MMFF94s, MMFF94, UFF, Ghemical ff.Setup(mol) if method == 'Weighted': ff.WeightedRotorSearch(conformers, nsteps) elif method == 'Random': ff.RandomRotorSearch(conformers, nsteps) else: ff.SystematicRotorSearch(nsteps) if name == 'all': name = 'all_' if method in ['Weighted', 'Random']: ff.GetConformers(mol) print '##############################################' print ' Conformer | Energy | RMSD' nrg_unit = ff.GetUnit() rmsd = 0 ff.GetCoordinates(mol) nrg = ff.Energy() conf_list = [] for i in range(conformers): mol.SetConformer(i) ff.Setup(mol) nrg = ff.Energy() conf_list.append((nrg, i)) conf_list.sort() lenght_conf_list = len(conf_list) if lowest_conf > lenght_conf_list: lowest_conf = lenght_conf_list for i in range(lowest_conf): nrg, orden = conf_list[i] name_n = '%s%02d' % (name, i) cmd.delete(name_n) mol.SetConformer(orden) pdb_string = obconversion.WriteString(mol) cmd.read_pdbstr(pdb_string, name_n) if i != 0: rmsd = cmd.fit(name_n, '%s00' % name, quiet=1) print '%15s | %10.2f%9s |%6.1f' % (name_n, nrg, nrg_unit, rmsd) print '##############################################' else: ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) cmd.read_pdbstr(pdb_string, name) print '#########################################' print 'The Energy of %s is %8.2f %s ' % (name, nrg, ff.GetUnit()) print '#########################################'
def minimize(selection='tmp', forcefield='MMFF94', method='steepest descent', nsteps=2000, conv=1E-6, cutoff=False, cut_vdw=6.0, cut_elec=8.0, rigid_geometry=True): """ Use openbabel to minimize the energy of a molecule. """ pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('pdb', 'pdb') mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) if rigid_geometry: constraints = ob.OBFFConstraints() for angle in ob.OBMolAngleIter(mol): b, a, c = [mol.GetAtom(x + 1) for x in angle] value = mol.GetAngle(a, b, c) b, a, c = [x + 1 for x in angle] constraints.AddAngleConstraint(a, b, c, value) for i in ob.OBMolBondIter(mol): a, b = (i.GetBeginAtomIdx(), i.GetEndAtomIdx()) value = i.GetLength() constraints.AddDistanceConstraint(a, b, value) ff = ob.OBForceField.FindForceField(forcefield) ff.Setup(mol, constraints) ff.SetConstraints(constraints) else: ff = ob.OBForceField.FindForceField(forcefield) ff.Setup(mol) if cutoff: ff.EnableCutOff(True) ff.SetVDWCutOff(cut_vdw) ff.SetElectrostaticCutOff(cut_elec) if method == 'conjugate gradients': ff.ConjugateGradients(nsteps, conv) else: ff.SteepestDescent(nsteps, conv) ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) if name == 'all': name = 'all_' cmd.delete(selection) cmd.read_pdbstr(pdb_string, selection) return nrg
def sketch_pseudo_coc(selection, state=None, name=None, prefix='', suffix='_coc', **kwargs): """Create a pseudo atom which indicate the center of coordinate of the selection USAGE sketch_pseudo_coc selection, state=state, name=name, prefix=prefix, suffix=suffix ARGUMENTS selection a selection-expression state a state-index if positive number or 0 to all, -1 to current name a name of the pseudoatom, it will automatically specified if None is specified (Default) prefix a prefix of the pseudoatom. it will used only when name is not specified suffix a suffix of the pseudoatom. it will used only when name is not specified EXAMPLE sketch_pcoc (resn PHE), state=10 """ if name is None: try: name = cmd.get_legal_name(selection) name = cmd.get_unused_name('{}{}{}'.format(prefix, name, suffix), 0) except: name = '%s%s' % (prefix, suffix) if state is not None: com = geometry.find_center_of_coordinates(selection) cmd.pseudoatom(name, pos=com, **kwargs) else: for state in range(1, cmd.count_states() + 1): com = geometry.find_center_of_coordinates(selection, state=state) cmd.pseudoatom(name, pos=com, state=state, **kwargs)
def minimize(selection='tmp', forcefield='MMFF94', method='steepest descent', nsteps= 2000, conv=1E-6, cutoff=False, cut_vdw=6.0, cut_elec=8.0, rigid_geometry=True): """ Write Me! """ pdb_string = cmd.get_pdbstr(selection) name = cmd.get_legal_name(selection) obconversion = ob.OBConversion() obconversion.SetInAndOutFormats('pdb', 'pdb') mol = ob.OBMol() obconversion.ReadString(mol, pdb_string) if rigid_geometry: constraints = ob.OBFFConstraints() for angle in ob.OBMolAngleIter(mol): b, a, c = [mol.GetAtom(x+1) for x in angle] value = mol.GetAngle(a, b, c) b, a, c = [x+1 for x in angle] constraints.AddAngleConstraint(a, b, c, value) for i in ob.OBMolBondIter(mol): a, b = (i.GetBeginAtomIdx(), i.GetEndAtomIdx()) value = i.GetLength() constraints.AddDistanceConstraint(a, b, value) ff = ob.OBForceField.FindForceField(forcefield) ff.Setup(mol, constraints) ff.SetConstraints(constraints) else: ff = ob.OBForceField.FindForceField(forcefield) ff.Setup(mol) if cutoff: ff.EnableCutOff(True) ff.SetVDWCutOff(cut_vdw) ff.SetElectrostaticCutOff(cut_elec) if method == 'conjugate gradients': ff.ConjugateGradients(nsteps, conv) else: ff.SteepestDescent(nsteps, conv) ff.GetCoordinates(mol) nrg = ff.Energy() pdb_string = obconversion.WriteString(mol) cmd.delete(name) if name == 'all': name = 'all_' cmd.delete(selection) cmd.read_pdbstr(pdb_string, selection) return nrg
def sketch_pseudo_coc(selection, state=None, name=None, prefix='', suffix='_coc', **kwargs): """Create a pseudo atom which indicate the center of coordinate of the selection USAGE sketch_pseudo_coc selection, state=state, name=name, prefix=prefix, suffix=suffix ARGUMENTS selection a selection-expression state a state-index if positive number or 0 to all, -1 to current name a name of the pseudoatom, it will automatically specified if None is specified (Default) prefix a prefix of the pseudoatom. it will used only when name is not specified suffix a suffix of the pseudoatom. it will used only when name is not specified EXAMPLE sketch_pcoc (resn PHE), state=10 """ if name is None: try: name = cmd.get_legal_name(selection) name = cmd.get_unused_name( '{}{}{}'.format(prefix, name, suffix), 0 ) except: name = '%s%s' % (prefix, suffix) if state is not None: com = geometry.find_center_of_coordinates(selection) cmd.pseudoatom(name, pos=com, **kwargs) else: for state in range(1, cmd.count_states()+1): com = geometry.find_center_of_coordinates(selection, state=state) cmd.pseudoatom(name, pos=com, state=state, **kwargs)
def com(selection, state=None, mass=None, object=None, quiet=1, **kwargs): quiet = int(quiet) if (object == None): try: object = cmd.get_legal_name(selection) object = cmd.get_unused_name(object + "_COM", 0) except AttributeError: object = 'COM' cmd.delete(object) if (state != None): x, y, z = get_com(selection, mass=mass, quiet=quiet) if not quiet: print("%f %f %f" % (x, y, z)) cmd.pseudoatom(object, pos=[x, y, z], **kwargs) cmd.show("spheres", object) else: for i in range(cmd.count_states()): x, y, z = get_com(selection, mass=mass, state=i + 1, quiet=quiet) if not quiet: print("State %d:%f %f %f" % (i + 1, x, y, z)) cmd.pseudoatom(object, pos=[x, y, z], state=i + 1, **kwargs) cmd.show("spheres", 'last ' + object)
def uniprot_features(uniprot_id, selection='(all)', withss=0, prefix='feature_', quiet=1): ''' DESCRIPTION Fetch feature list from uniprot.org and create named selections. Requires residue numbering (resi) to match uniprot sequence! ARGUMENTS uniprot_id = string: UniProtKB name or accession selection = string: atom selection {default: all} withss = 0/1: update secondary structure {default: 0} ''' import xml.etree.ElementTree as etree from urllib import urlopen withss, quiet = int(withss), int(quiet) url = 'http://www.uniprot.org/uniprot/%s.xml' % uniprot_id if not quiet: print 'Downloading', url doc = etree.parse(urlopen(url)) ns = 'http://uniprot.org/uniprot' NS = {'u': ns} if not quiet: print 'Parsing Features' features = doc.findall('{%s}entry/{%s}feature' % (ns, ns)) if withss == 1: cmd.alter(selection, 'ss="L"') ssmap = {'helix': 'H', 'strand': 'S', 'turn': 'L'} norange_types = ['disulfide bond'] count = 0 for feature in features: type = feature.get('type') begin = feature.find('{%s}location/{%s}begin' % (ns, ns)) if begin is not None: end = feature.find('{%s}location/{%s}end' % (ns, ns)) values = (selection, begin.get('position'), end.get('position')) if type in norange_types: sel = '(%s) and resi %s+%s' % values else: sel = '(%s) and resi %s-%s' % values else: position = feature.find('{%s}location/{%s}position' % (ns, ns)) sel = '(%s) and resi %s' % (selection, position.get('position')) if type in ['helix', 'strand', 'turn'] and withss < 2: if withss == 1: cmd.alter(sel, 'ss="%s"' % ssmap.get(type, 'L')) else: count += 1 name = cmd.get_legal_name('%s%03d_%s' % (prefix, count, feature.get('description', '').replace('.', ''))) groupname = cmd.get_legal_name('%s%s' % (prefix, type)) cmd.select(name, sel) cmd.group(groupname, name, 'add') if not quiet: print 'Found %d feature records (without secondary structures)' % count
def show_contacts(selection='*', selection2='*', result="contacts", cutoff=3.6, bigcutoff = 4.0, labels=False, SC_DEBUG = DEBUG): """ USAGE show_contacts selection, selection2, [result=contacts],[cutoff=3.6],[bigcutoff=4.0] Show various polar contacts, the good, the bad, and the ugly. Edit MPB 6-26-14: The distances are heavy atom distances, so I upped the default cutoff to 4.0 Returns: True/False - if False, something went wrong """ if SC_DEBUG > 4: print('Starting show_contacts') print('selection = "' + selection + '"') print('selection2 = "' + selection2 + '"') result = cmd.get_legal_name(result) #if the group of contacts already exist, delete them cmd.delete(result) # ensure only N and O atoms are in the selection all_don_acc1 = selection + " and (donor or acceptor)" all_don_acc2 = selection2 + " and (donor or acceptor)" if SC_DEBUG > 4: print('all_don_acc1 = "' + all_don_acc1 + '"') print('all_don_acc2 = "' + all_don_acc2 + '"') #if theses selections turn out not to have any atoms in them, pymol throws cryptic errors when calling the dist function like: #'Selector-Error: Invalid selection name' #So for each one, manually perform the selection and then pass the reference to the distance command and at the end, clean up the selections #the return values are the count of the number of atoms all1_sele_count = cmd.select('all_don_acc1_sele', all_don_acc1) all2_sele_count = cmd.select('all_don_acc2_sele', all_don_acc2) #print out some warnings if DEBUG > 3: if not all1_sele_count: print('Warning: all_don_acc1 selection empty!') if not all2_sele_count: print('Warning: all_don_acc2 selection empty!') ######################################## allres = result + "_all" if all1_sele_count and all2_sele_count: #print(allres) #print(cmd.get_distance(allres, 'all_don_acc1_sele', 'all_don_acc2_sele', bigcutoff, mode = 0)) any = cmd.distance(allres, 'all_don_acc1_sele', 'all_don_acc2_sele', bigcutoff, mode = 0) # if any is 0 it seems that there is no distance! if any: cmd.set("dash_radius", "0.05", allres) if not labels: cmd.hide("labels", allres) else: # just do nothing and clena up print('no contacts') cmd.delete('all_don_acc1_sele') cmd.delete('all_don_acc2_sele') cmd.delete(result + "_all") return None ######################################## # compute good polar interactions according to pymol polres = result + "_polar" if all1_sele_count and all2_sele_count: cmd.distance(polres, 'all_don_acc1_sele', 'all_don_acc2_sele', cutoff, mode = 2) #hopefully this checks angles? Yes #cmd.set("dash_color", "marine", allres) #cmd.set('dash_gap', '0') cmd.set("dash_radius","0.2", polres) #"0.126" #cmd.set("dash_color", "marine", allres) if not labels: cmd.hide("labels", polres) ######################################## # When running distance in mode=2, the cutoff parameter is ignored if set higher then the default of 3.6 # so set it to the passed in cutoff and change it back when you are done. old_h_bond_cutoff_center = cmd.get('h_bond_cutoff_center') # ideal geometry old_h_bond_cutoff_edge = cmd.get('h_bond_cutoff_edge') # minimally acceptable geometry cmd.set('h_bond_cutoff_center', bigcutoff) cmd.set('h_bond_cutoff_edge', bigcutoff) # compute possibly suboptimal polar interactions using the user specified distance pol_ok_res = result + "_polar_ok" if all1_sele_count and all2_sele_count: cmd.distance(pol_ok_res, 'all_don_acc1_sele', 'all_don_acc2_sele', bigcutoff, mode = 2) cmd.set("dash_radius", "0.06", pol_ok_res) if not labels: cmd.hide("labels", pol_ok_res) #now reset the h_bond cutoffs cmd.set('h_bond_cutoff_center', old_h_bond_cutoff_center) cmd.set('h_bond_cutoff_edge', old_h_bond_cutoff_edge) ######################################## onlyacceptors1 = selection + " and (acceptor and !donor)" onlyacceptors2 = selection2 + " and (acceptor and !donor)" onlydonors1 = selection + " and (!acceptor and donor)" onlydonors2 = selection2 + " and (!acceptor and donor)" #perform the selections onlyacceptors1_sele_count = cmd.select('onlyacceptors1_sele', onlyacceptors1) onlyacceptors2_sele_count = cmd.select('onlyacceptors2_sele', onlyacceptors2) onlydonors1_sele_count = cmd.select('onlydonors1_sele', onlydonors1) onlydonors2_sele_count = cmd.select('onlydonors2_sele', onlydonors2) #print out some warnings if SC_DEBUG > 2: if not onlyacceptors1_sele_count: print('Warning: onlyacceptors1 selection empty!') if not onlyacceptors2_sele_count: print('Warning: onlyacceptors2 selection empty!') if not onlydonors1_sele_count: print('Warning: onlydonors1 selection empty!') if not onlydonors2_sele_count: print('Warning: onlydonors2 selection empty!') # acceptors acceptors accres = result+"_aa" if onlyacceptors1_sele_count and onlyacceptors2_sele_count: aa_dist_out = cmd.distance(accres, 'onlyacceptors1_sele', 'onlyacceptors2_sele', cutoff, 0) if aa_dist_out < 0: print('\n\nCaught a pymol selection error in acceptor-acceptor selection of show_contacts') print('accres:', accres) print('onlyacceptors1', onlyacceptors1) print('onlyacceptors2', onlyacceptors2) return False cmd.set("dash_color","red",accres) cmd.set("dash_radius","0.125",accres) if not labels: cmd.hide("labels", accres) ######################################## # donors donors donres = result+"_dd" if onlydonors1_sele_count and onlydonors2_sele_count: dd_dist_out = cmd.distance(donres, 'onlydonors1_sele', 'onlydonors2_sele', cutoff, 0) #try to catch the error state if dd_dist_out < 0: print('\n\nCaught a pymol selection error in dd selection of show_contacts') print('donres:', donres) print('onlydonors1', onlydonors1) print('onlydonors2', onlydonors2) print("cmd.distance('" + donres + "', '" + onlydonors1 + "', '" + onlydonors2 + "', " + str(cutoff) + ", 0)") return False cmd.set("dash_color","red",donres) cmd.set("dash_radius","0.125",donres) if not labels: cmd.hide("labels", donres) ########################################################## ##### find the buried unpaired atoms of the receptor ##### ########################################################## #initialize the variable for when CALC_SASA is False unpaired_atoms = '' ## Group print(allres) # contacts_all cmd.group(result,"%s %s %s %s %s %s" % (polres, allres, accres, donres, pol_ok_res, unpaired_atoms)) ## Clean up the selection objects #if the show_contacts debug level is high enough, don't delete them. if SC_DEBUG < 5: cmd.delete('all_don_acc1_sele') cmd.delete('all_don_acc2_sele') cmd.delete('onlyacceptors1_sele') cmd.delete('onlyacceptors2_sele') cmd.delete('onlydonors1_sele') cmd.delete('onlydonors2_sele') cmd.disable('contacts_all') cmd.disable('contacts_polar_ok') cmd.disable('contacts_aa') cmd.disable('contacts_dd') return True
def testGetLegalName(self): self.assertEqual(cmd.get_legal_name("foo bar baz"), "foo_bar_baz")
def dehydron(selection='all', angle_range=40, max_distance=3.5, desolv=6.5, min_wrappers=19, quiet=0): ''' DESCRIPTION dehydron calculator USAGE dehydron [ selection [, angle_range [, max_distance [, desolv [, min_wrappers ]]]]] ''' angle, max_distance = float(angle_range), float(max_distance) desolv, min_wrappers = float(desolv), int(min_wrappers) quiet = int(quiet) name = cmd.get_legal_name('DH_%s' % selection) cmd.delete(name) selection_hb = '((%s) and polymer)' % (selection) hb = cmd.find_pairs("((byres " + selection_hb + ") and n. n)", "((byres " + selection_hb + ") and n. o)", mode=1, cutoff=max_distance, angle=angle_range) if not quiet: hb.sort(lambda x, y: (cmp(x[0][1], y[0][1]))) print "--------------------------------------------------------------------" print "--------------------------Dehydron Results--------------------------" print "--------------------------------------------------------------------" print " Donor | Aceptor |" print " Object Chain Residue | Object Chain Residue | # wrappers" cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0) try: cmd.select('_selection', '%s' % selection, 0) except: pass sel = [] total_wrappers = 0 for pairs in hb: wrappers = cmd.count_atoms( '((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' % ((pairs[0][0], desolv) + pairs[0] + pairs[1])) total_wrappers = total_wrappers + wrappers if wrappers < min_wrappers: cmd.distance(name, pairs[0], pairs[1]) if not quiet: cmd.iterate(pairs[0], 'stored.nitro = chain, resi, resn') cmd.iterate(pairs[1], 'stored.oxy = chain, resi, resn') print ' %12s%4s%6s%6s | %12s%4s%6s%6s |%7s' % ( pairs[0][0], stored.nitro[0], stored.nitro[2], stored.nitro[1], pairs[1][0], stored.oxy[0], stored.oxy[2], stored.oxy[1], wrappers) sel.append(pairs[0]) sel.append(pairs[1]) cmd.delete('_nonpolar') cmd.delete('_selection') #compute the z_scores for validation porpoises. stored.ResiduesNames = [] cmd.iterate('(name ca)', 'stored.ResiduesNames.append((resn))') total_residues = float(len(stored.ResiduesNames)) z_score_wrappers = ((total_wrappers / total_residues) - 17) / 2 z_score_hb = ((len(hb) / total_residues) - 0.62) / 0.06 if len(sel) > 0: cmd.show_as('dashes', name) print '\nz-score wrappers = %6.2f\nz-score hydrogen bonds = %6.2f\n' % ( z_score_wrappers, z_score_hb) elif not quiet and len(hb) != 0: print '\n - no dehydrons were found - ' print '\nz-score hydrogen bonds = %6.2f\n' % (z_score_hb) else: print '\n - no hydrogen bonds were found - '
def uniprot_features(uniprot_id, selection='(all)', withss=0, prefix='feature_', sm=None, quiet=1): ''' DESCRIPTION Fetch feature list from uniprot.org and create named selections. Requires residue numbering (resi) to match uniprot sequence! ARGUMENTS uniprot_id = string: UniProtKB name or accession selection = string: atom selection {default: all} withss = 0/1: update secondary structure {default: 0} ''' import xml.etree.ElementTree as etree try: from urllib import urlopen except ImportError: from urllib.request import urlopen withss, quiet = int(withss), int(quiet) url = 'http://www.uniprot.org/uniprot/%s.xml' % uniprot_id if not quiet: print('Downloading', url) doc = etree.parse(urlopen(url)) ns = 'http://uniprot.org/uniprot' NS = {'u': ns} if not quiet: print('Parsing Features') features = doc.findall('{%s}entry/{%s}feature' % (ns, ns)) sequence = doc.findtext('{%s}entry/{%s}sequence' % (ns, ns)) sequence = ''.join(sequence.split()) try: if sm is None: sm = resid_mapper.from_seq_sel(sequence, selection) except: print(' Warning: sequence mapping failed') sm = lambda x: x if withss == 1: cmd.alter(selection, 'ss="L"') ssmap = {'helix': 'H', 'strand': 'S', 'turn': 'L'} norange_types = ['disulfide bond'] count = 0 for feature in features: type_ = feature.get('type') begin = feature.find('{%s}location/{%s}begin' % (ns, ns)) if begin is not None: end = feature.find('{%s}location/{%s}end' % (ns, ns)) values = begin.get('position'), end.get('position') if type_ in norange_types: try: values = sm(values[0]), sm(values[1]) sel = '(' + selection + ') and resi %s+%s' % values except KeyError: print(' Warning: could not map', values) sel = 'none' else: try: values = sm(values) sel = '(' + selection + ') and resi %s-%s' % values except KeyError: print(' Warning: could not map', values) sel = 'none' else: position = feature.find('{%s}location/{%s}position' % (ns, ns)) try: value = sm(position.get('position')) sel = '(%s) and resi %s' % (selection, value) except KeyError: sel = 'none' if type_ in ['helix', 'strand', 'turn'] and withss < 2: if withss == 1: cmd.alter(sel, 'ss="%s"' % ssmap.get(type_, 'L')) else: count += 1 name = cmd.get_legal_name('%s%03d_%s' % (prefix, count, feature.get('description', '').replace('.', ''))) groupname = cmd.get_legal_name('%s%s' % (prefix, type_)) cmd.select(name, sel) cmd.group(groupname, name, 'add') if not quiet: print('Found %d feature records (without secondary structures)' % count)
def uniprot_features(uniprot_id, selection="(all)", withss=0, prefix="feature_", sm=None, quiet=1): """ DESCRIPTION Fetch feature list from uniprot.org and create named selections. Requires residue numbering (resi) to match uniprot sequence! ARGUMENTS uniprot_id = string: UniProtKB name or accession selection = string: atom selection {default: all} withss = 0/1: update secondary structure {default: 0} """ import xml.etree.ElementTree as etree from urllib import urlopen withss, quiet = int(withss), int(quiet) url = "http://www.uniprot.org/uniprot/%s.xml" % uniprot_id if not quiet: print "Downloading", url doc = etree.parse(urlopen(url)) ns = "http://uniprot.org/uniprot" NS = {"u": ns} if not quiet: print "Parsing Features" features = doc.findall("{%s}entry/{%s}feature" % (ns, ns)) sequence = doc.findtext("{%s}entry/{%s}sequence" % (ns, ns)) sequence = "".join(sequence.split()) try: if sm is None: sm = resid_mapper.from_seq_sel(sequence, selection) except: print " Warning: sequence mapping failed" sm = lambda x: x if withss == 1: cmd.alter(selection, 'ss="L"') ssmap = {"helix": "H", "strand": "S", "turn": "L"} norange_types = ["disulfide bond"] count = 0 for feature in features: type = feature.get("type") begin = feature.find("{%s}location/{%s}begin" % (ns, ns)) if begin is not None: end = feature.find("{%s}location/{%s}end" % (ns, ns)) values = begin.get("position"), end.get("position") if type in norange_types: try: values = sm(values[0]), sm(values[1]) sel = "(" + selection + ") and resi %s+%s" % values except KeyError: print " Warning: could not map", values sel = "none" else: try: values = sm(values) sel = "(" + selection + ") and resi %s-%s" % values except KeyError: print " Warning: could not map", values sel = "none" else: position = feature.find("{%s}location/{%s}position" % (ns, ns)) try: value = sm(position.get("position")) sel = "(%s) and resi %s" % (selection, value) except KeyError: sel = "none" if type in ["helix", "strand", "turn"] and withss < 2: if withss == 1: cmd.alter(sel, 'ss="%s"' % ssmap.get(type, "L")) else: count += 1 name = cmd.get_legal_name("%s%03d_%s" % (prefix, count, feature.get("description", "").replace(".", ""))) groupname = cmd.get_legal_name("%s%s" % (prefix, type)) cmd.select(name, sel) cmd.group(groupname, name, "add") if not quiet: print "Found %d feature records (without secondary structures)" % count
def dehydron(selection='all', angle_range=40., max_distance=3.5, desolv=6.5, min_wrappers=19, max_wrappers=35, quiet=0): ''' DESCRIPTION dehydron calculator USAGE wrappy [ selection [, angle_range [, max_distance [, desolv [, min_wrappers [, max_wrappers ]]]]]] ''' angle, max_distance = float(angle_range), float(max_distance) desolv, min_wrappers, max_wrappers = float(desolv), int(min_wrappers), int( max_wrappers) quiet = int(quiet) DH_name = cmd.get_legal_name('DH_%s' % selection) cmd.delete(DH_name) HBA_name = cmd.get_legal_name('HBA_%s' % selection) cmd.delete(HBA_name) HBO_name = cmd.get_legal_name('HBO_%s' % selection) cmd.delete(HBO_name) selection_hb = '((%s) and polymer)' % (selection) hb = cmd.find_pairs("((byres " + selection_hb + ") and n. n)", "((byres " + selection_hb + ") and n. o)", mode=1, cutoff=max_distance, angle=angle_range) cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0) try: cmd.select('_selection', '%s' % selection, 0) except: pass low_sel = [] mean_sel = [] high_sel = [] total_wrappers = 0 for pairs in hb: wrappers = cmd.count_atoms( '((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' % ((pairs[0][0], desolv) + pairs[0] + pairs[1])) total_wrappers = total_wrappers + wrappers cmd.iterate(pairs[0], 'stored.donor = chain, resi, resn') cmd.iterate(pairs[1], 'stored.aceptor = chain, resi, resn') if wrappers < min_wrappers: cmd.distance(DH_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s below' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) low_sel.append(line) elif wrappers < max_wrappers: cmd.distance(HBA_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s average' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) mean_sel.append(line) else: cmd.distance(HBO_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s over' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) high_sel.append(line) cmd.delete('_nonpolar') cmd.delete('_selection') # compute the z_scores. Useful for protein structure validation. stored.ResiduesNames = [] cmd.iterate('(name ca)', 'stored.ResiduesNames.append((resn))') total_residues = float(len(stored.ResiduesNames)) z_score_wrappers = ((total_wrappers / total_residues) - 17) / 2 z_score_hb = ((len(hb) / total_residues) - 0.62) / 0.06 if len(low_sel) > 0: cmd.show_as('dashes', DH_name) cmd.color('red', DH_name) low_sel.sort() if len(mean_sel) > 0: cmd.show_as('dashes', HBA_name) cmd.color('yellow', HBA_name) mean_sel.sort() if len(high_sel) > 0: cmd.show_as('dashes', HBO_name) cmd.color('green', HBO_name) high_sel.sort() if not quiet: hb.sort() print "--------------------------------------------------------------------" print "------------------------------Results ------------------------------" print "--------------------------------------------------------------------" print " Donor | Aceptor |" print " Object Chain Residue | Object Chain Residue | # wrappers wrapping" for line in low_sel: print line[1] for line in mean_sel: print line[1] for line in high_sel: print line[1] print '\nProtein global statistics:' print '\nz-score wrappers = %6.2f\nz-score hydrogen bonds = %6.2f\n' % ( z_score_wrappers, z_score_hb) elif not quiet and len(hb) != 0: print '\n - no dehydrons were found - ' print '\nz-score hydrogen bonds = %6.2f\n' % (z_score_hb) else: print '\n - no hydrogen bonds were found - '
def process_session( ensemble_collector, patterns, group, max_size, plot, plot_annot, plot_class, plot_method, table, base_root=None, ): """Main plugin code.""" results = {} for pattern in sorted(patterns): for path in glob(pattern): if base_root is None: root = pm.get_legal_name(splitext(basename(path))[0]) else: root = base_root results[root] = [], [] ensembles, clusters = results[root] if group: root = f"{group}.{root}" else: root = root with disable_feedback("all", "warnings"): with settings(group_auto_mode=1): pm.load(path) try: collected_ensembles = list(ensemble_collector(max_size)) if len(collected_ensembles) == 0: raise Exception("No ensembles found.") except: raise CmdException(f"File {path} is invalid.") with settings(group_auto_mode=2): pm.create(f"{root}.protein", "protein") pm.delete("protein") i = 0 for ensemble in collected_ensembles: klass = ensemble.klass if klass: i += 1 pm.hide("sticks", ensemble.selection) pm.show("line", ensemble.selection) pm.util.cbas(ensemble.selection) obj = f"{root}.{klass}.{i:03}" pm.create(obj, ensemble.selection) if hasattr(pm, "set_property"): pm.set_property("Class", ensemble.klass, obj) pm.set_property("S", ensemble.strength, obj) pm.set_property("S (CS0)", ensemble.clusters[0].strength, obj) pm.set_property("CD", ensemble.max_center_to_center, obj) pm.set_property("MD", ensemble.max_dist, obj) ensemble.selection = obj ensembles.append(ensemble) for i, cluster in enumerate(Cluster.collect_atlas()): pm.hide("sticks", cluster.selection) pm.show("line", cluster.selection) pm.util.cbay(cluster.selection) obj = f"{root}.CS.{i:03}_{cluster.strength:03}" pm.create(obj, cluster.selection) pm.delete(cluster.selection) cluster.selection = obj clusters.append(cluster) pm.color("yellow", f"{root}.CS.*") pm.color("salmon", f"{root}.B.* or {root}.Bs.* {root}.Bl.*") pm.color("red", f"{root}.D.* or {root}.Ds.* {root}.Dl.*") pm.hide("lines", f"{root}.*") pm.disable(f"{root}.CS") pm.show("mesh", f"{root}.B.* or {root}.Bs.* {root}.Bl.*") pm.show("mesh", f"{root}.D.* or {root}.Ds.* {root}.Dl.*") pm.show("mesh", f"{root}.CS.*") pm.hide("nb_spheres", "*label") pm.orient(root) if plot: roots = [] selections = [] for root in sorted(results): for ensemble in results[root][0]: roots.append(root) selections.append(ensemble.selection) if plot_class: selections = [s for s in selections if "." + plot_class + "." in s] matrix_sim = np.zeros((len(selections), len(selections))) matrix_over = np.zeros((len(selections), len(selections))) for i, (root1, selection1) in enumerate(zip(roots, selections)): for j, (root2, selection2) in enumerate(zip(roots, selections)): matrix_sim[i][j] = nearby_aminoacids_similarity( selection1, selection2, polymer1=root1 + ".protein", polymer2=root2 + ".protein", method=plot_method, verbose=False, ) matrix_over[i][j] = get_fractional_overlap(selection1, selection2, verbose=0) fig, ax = plt.subplots(1, 2) sb.heatmap( matrix_sim, vmax=1, vmin=0, xticklabels=selections, yticklabels=selections, annot=plot_annot, cmap="YlGnBu", ax=ax[0], ) sb.heatmap( matrix_over, vmax=1, vmin=0, yticklabels=selections, xticklabels=selections, annot=plot_annot, cmap="YlGnBu", ax=ax[1], ) ax[0].set_title(plot_method + " coefficient") ax[0].set_xticklabels(selections, rotation=45, ha="right") ax[1].set_title("fractional overlap") ax[1].set_xticklabels(selections, rotation=45, ha="right") plt.show() if table: tmpl = Template(""" <table> <tr> <th>Object</th> <th>Class</th> <th>S</th> <th>S0</th> <th>CD</th> <th>MD</th> </tr> {% for root in results %} {% for e in results[root][0] %} <tr> <td>{{ e.selection }}</td> <td>{{ e.klass }}</td> <td>{{ e.strength }}</td> <td>{{ e.strength0 }}</td> <td>{{ e.max_center_to_center | round(2) }}</td> <td>{{ e.max_dist | round(2) }}</td> </tr> {% endfor %} {% endfor %} </table> """) _, path = tempfile.mkstemp(suffix=".html") with open(path, "w") as fd: fd.write(tmpl.render(results=results)) webbrowser.open(path) return results
def dehydron(selection='all', angle_range=40., max_distance=3.5, desolv=6.5, min_wrappers=19, max_wrappers=35, quiet=0): ''' DESCRIPTION dehydron calculator USAGE wrappy [ selection [, angle_range [, max_distance [, desolv [, min_wrappers [, max_wrappers ]]]]]] ''' angle, max_distance = float(angle_range), float(max_distance) desolv, min_wrappers, max_wrappers = float(desolv), int(min_wrappers), int(max_wrappers) quiet = int(quiet) DH_name = cmd.get_legal_name('DH_%s' % selection) cmd.delete(DH_name) HBA_name = cmd.get_legal_name('HBA_%s' % selection) cmd.delete(HBA_name) HBO_name = cmd.get_legal_name('HBO_%s' % selection) cmd.delete(HBO_name) selection_hb = '((%s) and polymer)' % (selection) hb = cmd.find_pairs("((byres " + selection_hb + ") and n. n)", "((byres " + selection_hb + ") and n. o)", mode=1, cutoff=max_distance, angle=angle_range) cmd.select('_nonpolar', '(elem C) and not (solvent or (elem N+O) extend 1)', 0) try: cmd.select('_selection', '%s' % selection, 0) except: pass low_sel = [] mean_sel = [] high_sel = [] total_wrappers = 0 for pairs in hb: wrappers = cmd.count_atoms('((%s and _nonpolar and _selection) within %f of byca (%s`%d %s`%d))' % ((pairs[0][0], desolv) + pairs[0] + pairs[1])) total_wrappers = total_wrappers + wrappers cmd.iterate(pairs[0], 'stored.donor = chain, resi, resn') cmd.iterate(pairs[1], 'stored.aceptor = chain, resi, resn') if wrappers < min_wrappers: cmd.distance(DH_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s below' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) low_sel.append(line) elif wrappers < max_wrappers: cmd.distance(HBA_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s average' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) mean_sel.append(line) else: cmd.distance(HBO_name, pairs[0], pairs[1]) line = (wrappers, '%12s%4s%6s%6s | %12s%4s%6s%6s |%7s over' % (pairs[0][0], stored.donor[0], stored.donor[2], stored.donor[1], pairs[1][0], stored.aceptor[0], stored.aceptor[2], stored.aceptor[1], wrappers)) high_sel.append(line) cmd.delete('_nonpolar') cmd.delete('_selection') # compute the z_scores. Useful for protein structure validation. stored.ResiduesNames = [] cmd.iterate('(name ca)', 'stored.ResiduesNames.append((resn))') total_residues = float(len(stored.ResiduesNames)) z_score_wrappers = ((total_wrappers / total_residues) - 17) / 2 z_score_hb = ((len(hb) / total_residues) - 0.62) / 0.06 if len(low_sel) > 0: cmd.show_as('dashes', DH_name) cmd.color('red', DH_name) low_sel.sort() if len(mean_sel) > 0: cmd.show_as('dashes', HBA_name) cmd.color('yellow', HBA_name) mean_sel.sort() if len(high_sel) > 0: cmd.show_as('dashes', HBO_name) cmd.color('green', HBO_name) high_sel.sort() if not quiet: hb.sort() print "--------------------------------------------------------------------" print "------------------------------Results ------------------------------" print "--------------------------------------------------------------------" print " Donor | Aceptor |" print " Object Chain Residue | Object Chain Residue | # wrappers wrapping" for line in low_sel: print line[1] for line in mean_sel: print line[1] for line in high_sel: print line[1] print '\nProtein global statistics:' print '\nz-score wrappers = %6.2f\nz-score hydrogen bonds = %6.2f\n' % (z_score_wrappers, z_score_hb) elif not quiet and len(hb) != 0: print '\n - no dehydrons were found - ' print '\nz-score hydrogen bonds = %6.2f\n' % (z_score_hb) else: print '\n - no hydrogen bonds were found - '
def show_contacts(selection,selection2,result="contacts",cutoff=3.6, bigcutoff = 4.0, SC_DEBUG = DEBUG): """ USAGE show_contacts selection, selection2, [result=contacts],[cutoff=3.6],[bigcutoff=4.0] Show various polar contacts, the good, the bad, and the ugly. Edit MPB 6-26-14: The distances are heavy atom distances, so I upped the default cutoff to 4.0 Returns: True/False - if False, something went wrong """ if SC_DEBUG > 4: print('Starting show_contacts') print('selection = "' + selection + '"') print('selection2 = "' + selection2 + '"') result = cmd.get_legal_name(result) #if the group of contacts already exist, delete them cmd.delete(result) # ensure only N and O atoms are in the selection all_don_acc1 = selection + " and (donor or acceptor)" all_don_acc2 = selection2 + " and (donor or acceptor)" if SC_DEBUG > 4: print('all_don_acc1 = "' + all_don_acc1 + '"') print('all_don_acc2 = "' + all_don_acc2 + '"') #if theses selections turn out not to have any atoms in them, pymol throws cryptic errors when calling the dist function like: #'Selector-Error: Invalid selection name' #So for each one, manually perform the selection and then pass the reference to the distance command and at the end, clean up the selections #the return values are the count of the number of atoms all1_sele_count = cmd.select('all_don_acc1_sele', all_don_acc1) all2_sele_count = cmd.select('all_don_acc2_sele', all_don_acc2) #print out some warnings if DEBUG > 3: if not all1_sele_count: print('Warning: all_don_acc1 selection empty!') if not all2_sele_count: print('Warning: all_don_acc2 selection empty!') ######################################## allres = result + "_all" if all1_sele_count and all2_sele_count: cmd.distance(allres, 'all_don_acc1_sele', 'all_don_acc2_sele', bigcutoff, mode = 0) cmd.set("dash_radius", "0.05", allres) cmd.set("dash_color", "purple", allres) cmd.hide("labels", allres) ######################################## #compute good polar interactions according to pymol polres = result + "_polar" if all1_sele_count and all2_sele_count: cmd.distance(polres, 'all_don_acc1_sele', 'all_don_acc2_sele', cutoff, mode = 2) #hopefully this checks angles? Yes cmd.set("dash_radius","0.126",polres) ######################################## #When running distance in mode=2, the cutoff parameter is ignored if set higher then the default of 3.6 #so set it to the passed in cutoff and change it back when you are done. old_h_bond_cutoff_center = cmd.get('h_bond_cutoff_center') # ideal geometry old_h_bond_cutoff_edge = cmd.get('h_bond_cutoff_edge') # minimally acceptable geometry cmd.set('h_bond_cutoff_center', bigcutoff) cmd.set('h_bond_cutoff_edge', bigcutoff) #compute possibly suboptimal polar interactions using the user specified distance pol_ok_res = result + "_polar_ok" if all1_sele_count and all2_sele_count: cmd.distance(pol_ok_res, 'all_don_acc1_sele', 'all_don_acc2_sele', bigcutoff, mode = 2) cmd.set("dash_radius", "0.06", pol_ok_res) #now reset the h_bond cutoffs cmd.set('h_bond_cutoff_center', old_h_bond_cutoff_center) cmd.set('h_bond_cutoff_edge', old_h_bond_cutoff_edge) ######################################## onlyacceptors1 = selection + " and (acceptor and !donor)" onlyacceptors2 = selection2 + " and (acceptor and !donor)" onlydonors1 = selection + " and (!acceptor and donor)" onlydonors2 = selection2 + " and (!acceptor and donor)" #perform the selections onlyacceptors1_sele_count = cmd.select('onlyacceptors1_sele', onlyacceptors1) onlyacceptors2_sele_count = cmd.select('onlyacceptors2_sele', onlyacceptors2) onlydonors1_sele_count = cmd.select('onlydonors1_sele', onlydonors1) onlydonors2_sele_count = cmd.select('onlydonors2_sele', onlydonors2) #print out some warnings if SC_DEBUG > 2: if not onlyacceptors1_sele_count: print('Warning: onlyacceptors1 selection empty!') if not onlyacceptors2_sele_count: print('Warning: onlyacceptors2 selection empty!') if not onlydonors1_sele_count: print('Warning: onlydonors1 selection empty!') if not onlydonors2_sele_count: print('Warning: onlydonors2 selection empty!') accres = result+"_aa" if onlyacceptors1_sele_count and onlyacceptors2_sele_count: aa_dist_out = cmd.distance(accres, 'onlyacceptors1_sele', 'onlyacceptors2_sele', cutoff, 0) if aa_dist_out < 0: print('\n\nCaught a pymol selection error in acceptor-acceptor selection of show_contacts') print('accres:', accres) print('onlyacceptors1', onlyacceptors1) print('onlyacceptors2', onlyacceptors2) return False cmd.set("dash_color","red",accres) cmd.set("dash_radius","0.125",accres) ######################################## donres = result+"_dd" if onlydonors1_sele_count and onlydonors2_sele_count: dd_dist_out = cmd.distance(donres, 'onlydonors1_sele', 'onlydonors2_sele', cutoff, 0) #try to catch the error state if dd_dist_out < 0: print('\n\nCaught a pymol selection error in dd selection of show_contacts') print('donres:', donres) print('onlydonors1', onlydonors1) print('onlydonors2', onlydonors2) print("cmd.distance('" + donres + "', '" + onlydonors1 + "', '" + onlydonors2 + "', " + str(cutoff) + ", 0)") return False cmd.set("dash_color","red",donres) cmd.set("dash_radius","0.125",donres) ########################################################## ##### find the buried unpaired atoms of the receptor ##### ########################################################## #initialize the variable for when CALC_SASA is False unpaired_atoms = '' ## Group cmd.group(result,"%s %s %s %s %s %s" % (polres, allres, accres, donres, pol_ok_res, unpaired_atoms)) ## Clean up the selection objects #if the show_contacts debug level is high enough, don't delete them. if SC_DEBUG < 5: cmd.delete('all_don_acc1_sele') cmd.delete('all_don_acc2_sele') cmd.delete('onlyacceptors1_sele') cmd.delete('onlyacceptors2_sele') cmd.delete('onlydonors1_sele') cmd.delete('onlydonors2_sele') return True
def uniprot_features(uniprot_id, selection='(all)', withss=0, prefix='feature_', sm=None, quiet=1): ''' DESCRIPTION Fetch feature list from uniprot.org and create named selections. Requires residue numbering (resi) to match uniprot sequence! ARGUMENTS uniprot_id = string: UniProtKB name or accession selection = string: atom selection {default: all} withss = 0/1: update secondary structure {default: 0} ''' import xml.etree.ElementTree as etree try: from urllib import urlopen except ImportError: from urllib.request import urlopen withss, quiet = int(withss), int(quiet) url = 'http://www.uniprot.org/uniprot/%s.xml' % uniprot_id if not quiet: print('Downloading', url) doc = etree.parse(urlopen(url)) ns = 'http://uniprot.org/uniprot' NS = {'u': ns} if not quiet: print('Parsing Features') features = doc.findall('{%s}entry/{%s}feature' % (ns, ns)) sequence = doc.findtext('{%s}entry/{%s}sequence' % (ns, ns)) sequence = ''.join(sequence.split()) try: if sm is None: sm = resid_mapper.from_seq_sel(sequence, selection) except: print(' Warning: sequence mapping failed') sm = lambda x: x if withss == 1: cmd.alter(selection, 'ss="L"') ssmap = {'helix': 'H', 'strand': 'S', 'turn': 'L'} norange_types = ['disulfide bond'] count = 0 for feature in features: type_ = feature.get('type') begin = feature.find('{%s}location/{%s}begin' % (ns, ns)) if begin is not None: end = feature.find('{%s}location/{%s}end' % (ns, ns)) values = begin.get('position'), end.get('position') if type_ in norange_types: try: values = sm(values[0]), sm(values[1]) sel = '(' + selection + ') and resi %s+%s' % values except KeyError: print(' Warning: could not map', values) sel = 'none' else: try: values = sm(values) sel = '(' + selection + ') and resi %s-%s' % values except KeyError: print(' Warning: could not map', values) sel = 'none' else: position = feature.find('{%s}location/{%s}position' % (ns, ns)) try: value = sm(position.get('position')) sel = '(%s) and resi %s' % (selection, value) except KeyError: sel = 'none' if type_ in ['helix', 'strand', 'turn'] and withss < 2: if withss == 1: cmd.alter(sel, 'ss="%s"' % ssmap.get(type_, 'L')) else: count += 1 name = cmd.get_legal_name( '%s%03d_%s' % (prefix, count, feature.get( 'description', '').replace('.', ''))) groupname = cmd.get_legal_name('%s%s' % (prefix, type_)) cmd.select(name, sel) cmd.group(groupname, name, 'add') if not quiet: print('Found %d feature records (without secondary structures)' % count)
def read_maestr(maestr,name,state=0,finish=1,discrete=-1, quiet=1,zoom=-1,multiplex=-1,mimic=1, object_props=None, atom_props=None, _self=cmd): import sys if sys.version_info[0] > 2 and isinstance(maestr, bytes): maestr = maestr.decode() cmd = _self mimic = int(mimic) if not quiet: print(" Load: Processing Schrodinger .MAE file...") if object_props is None: object_props = _self.get('load_object_props_default') if atom_props is None: atom_props = _self.get('load_atom_props_default') mr = MAEReader(mimic, object_props, atom_props) list = mr.listFromStr(maestr) if list and getattr(list[0], 'ct_type', None) == 'full_system': if not quiet: print(" Desmond CMS file detected, only loading first CT") list = list[:1] len_list = len(list); if len_list<2: # MAE contains no more than one molecule if discrete<0: discrete = 0 else: # MAE contains multiple molecules if multiplex > 0: if len_list > mr.full_count: multiplex = 2 # multiplex at the record level (break out conformers, etc.) if multiplex < 0: if len_list == mr.full_count: # file only contains full records multiplex = 1 # then multiplex at the object level elif multiplex == 0: if mr.full_count>1: # multiple full records present if discrete<0: discrete = 1 # use discrete object to prevent collisions if discrete < 0: discrete = 0 preserve_chempy_ids=cmd.get('preserve_chempy_ids') cmd.set('preserve_chempy_ids') # nest p_m_ct behind f_m_ct nested_list = [] for mdl in list: mdl.molecule.title = getattr(mdl, 'title', None) or getattr(mdl, 'name', '') if (mdl.mae_record == 'f_m_ct') or not nested_list: nested_list.append( [mdl] ) else: nested_list[-1].append(mdl) if multiplex < 0: multiplex = 1 if (len(nested_list) > 1) else 0 if multiplex: cmd.group(name) unnamed_cnt = itertools.count(1) object_name_dict = {} nested_list.reverse() while nested_list: mdl_list = nested_list.pop() len_mdl_list = len(mdl_list) if len_mdl_list: mdl = mdl_list[0] mdl_name = name if multiplex: mdl_name += "." + (mdl.molecule.title or str(next(unnamed_cnt))) mdl_name = cmd.get_legal_name(mdl_name) if mdl_name in object_name_dict and multiplex == 1: mdl_name = cmd.get_unused_name(mdl_name + "_") if multiplex > 0: name_dict = {} if multiplex > 1: # break coordinate sets into separate objects cnt = 0 for mdl in mdl_list: cnt = cnt + 1 mr.fix_bond_reps(mdl) state_name = mdl_name if len_mdl_list>1: state_name += "_" + str(cnt) _self.load_model(mdl,state_name,state,zoom=zoom, discrete=discrete,quiet=quiet, _self=_self) object_name_dict[state_name] = 1 else: # only break objects for mdl in mdl_list: mr.fix_bond_reps(mdl) _self.load_model(mdl,mdl_name,state,zoom=zoom, discrete=discrete,quiet=quiet, _self=_self) object_name_dict[mdl_name] = 1 else: # multiplex = 0 , so stuff everything into a single object for mdl in mdl_list: mr.fix_bond_reps(mdl) _self.load_model(mdl,mdl_name,state,zoom=zoom, discrete=discrete,quiet=quiet, _self=_self) object_name_dict[mdl_name] = 1 cmd.set('preserve_chempy_ids',preserve_chempy_ids) if mimic: for name in object_name_dict.keys(): # maestro-like settings _self.flag("ignore",name+" and not polymer","set") _self.set("stick_radius",0.18,name) _self.set("line_width",1.2,name) _self.set("valence_size",0.075,name) _self.set("valence", 1, name) _self.set("light",[0.4,-0.4,-1.0]) _self.set("shininess",100) _self.set("light2",[-0.5,-0.7,-0.2]) _self.set("light_count",3) _self.set("label_position",[1,0,2]) _self.set("label_font_id",7)
def load_vina_results(project_file, group, max_load, max_rank, interactions_check): # Load project data with open(project_file) as _project_file: project_data = json.load(_project_file) # Load target target_name = f"{group}.target" if project_data["flexible"]: cmd.load(project_data["rigid_pdbqt"], target_name) else: cmd.load(project_data["target_pdbqt"], target_name) cmd.group(group) cmd.group(group, target_name) # Show box box_name = f"{group}.box" display_box( box_name, ( project_data["center_x"] + project_data["size_x"] / 2, project_data["center_y"] + project_data["size_y"] / 2, project_data["center_z"] + project_data["size_z"] / 2, ), ( project_data["center_x"] - project_data["size_x"] / 2, project_data["center_y"] - project_data["size_y"] / 2, project_data["center_z"] - project_data["size_z"] / 2, ), ) cmd.group(group, box_name) # Parse results results_dir = project_data["results_dir"] results = itertools.chain.from_iterable( map(parse_vina_log, glob(f"{results_dir}/poses/*.pdbqt")) ) results = sorted(results, key=itemgetter("affinity")) cache = set() objects = set() count = 0 for pose in results: # Ignore poses which mode is greater than max if pose["mode"] > max_rank: continue # Load molecule into cache cache_name = cmd.get_legal_name(pose["filename"].replace(".", "_")) if cache_name not in cache: cmd.load(pose["filename"], cache_name) cache.add(cache_name) # Compute object names score = int(-10 * pose["affinity"]) state = pose["mode"] base_name = f'{group}.{pose["name"]}_{pose["mode"]}_{score}' obj_name = f"{base_name}.mol" polar_name = f"{base_name}.polar" # Create group cmd.group(base_name) # Create molecule object cmd.create(obj_name, cache_name, state, 1) cmd.group(base_name, obj_name) if interactions_check: cmd.distance(polar_name, target_name, obj_name, 2) cmd.group(base_name, polar_name) objects.add(obj_name) count += 1 if count >= max_load: break cmd.delete("delete " + " ".join(cache))