def make_objects(self,chain): for epitope in self.interest_epitope: if self.interest_epitope[epitope]: name = epitope selection = ",".join(str(x) for x in self.interest_epitope[epitope]) cmd.select("{}_{}".format(chain.lower(),name),"chain {} and resi {}".format(chain,selection)) cmd.group("chain_{}".format(chain),"{}_*".format(chain.lower()))
def testGroupAction(self): self._make_objects() sele = 'g1' cmd.group(sele, 'm*') m = menu.group_action(cmd, sele) d = self._to_dict(m) self.assertTrue('rename group' in d)
def testDoNotDuplicateGroup(self): cmd.pseudoatom("m3") cmd.group("g1", "m3") cmd.load("PYMOL-772-example.pse.gz", partial=1) v = cmd.get_names() self.assertEqual(v, ["m3", "g1", "m1", "m2"])
def loadall(pattern, group="", quiet=1, **kwargs): """ DESCRIPTION Load all files matching given globbing pattern """ import glob, os filenames = glob.glob(cmd.exp_path(pattern)) for filename in filenames: if not quiet: print " Loading", filename cmd.load(filename, **kwargs) if len(group): if kwargs.get("object", "") != "": print " Warning: group and object arguments given" members = [kwargs["object"]] else: from pymol.cmd import file_ext_re, gz_ext_re, safe_oname_re members = [ gz_ext_re.sub("", file_ext_re.sub("", safe_oname_re.sub("_", os.path.split(filename)[-1]))) for filename in filenames ] cmd.group(group, " ".join(members))
def testDirtyDelete(self): cmd.pseudoatom('m1') cmd.pseudoatom('m2') cmd.group('g1', 'm1 m2') cmd.set_wizard(MockWizard()) cmd.draw() v = cmd.get_object_list('(g1)') self.assertEqual(v, ['m1', 'm2'])
def testGroup(self): cmd.pseudoatom('m1') cmd.pseudoatom('m2') cmd.pseudoatom('m3') m_list = [] cmd.group('g1', 'm1 m2') cmd.iterate('g1', 'm_list.append(model)', space=locals()) self.assertItemsEqual(m_list, ['m1', 'm2']) m_list = [] cmd.ungroup('m2') cmd.iterate('g1', 'm_list.append(model)', space=locals()) self.assertItemsEqual(m_list, ['m1'])
def _load_example(self): # object in hidden group cmd.fragment('ile', 'm1') cmd.fragment('his', 'm2') cmd.group('g1', 'm1') cmd.disable('g1') # testable styling self.ambientOnly() cmd.orient() cmd.color('red', 'm1') cmd.color('blue', 'm2') cmd.show_as('spheres')
def test(self): names_ungrouped = ['a0', 'a1', 'b0', 'b1', 'c0', 'c1', 'g1'] names_grouped = ['a0', 'a1', 'c0', 'c1', 'b0', 'g1', 'b1'] for name in names_ungrouped[:-1]: cmd.pseudoatom(name) cmd.group(names_ungrouped[-1]) self.assertEqual(cmd.get_names(), names_ungrouped) cmd.group('g1', 'b*') cmd.order('b0 g1', location="upper") self.assertEqual(cmd.get_names(), names_grouped)
def test(self): cmd.pseudoatom('m1') cmd.pseudoatom('m2') cmd.pseudoatom('m3') cmd.group('g1', 'm1') cmd.disable('g1') cmd.disable('m2') cmd.ray(1, 1) # force scene update cmd.scene('s1', 'store') self._test_recall() cmd.disable('*') self._test_recall() cmd.enable('*') self._test_recall()
def get_resis_from_resn(target_sel="all", resn="lys", atom_name="CA", verb=True): # Make uppercase resn = resn.upper() # Check if one letter residue name if len(resn) == 1: resn = aa_1_3[resn] atom_name = atom_name.upper() # Prepare for storing and make expression stored.infolist = [] # resv (int): the residue identifier (residue number), ss (str): secondary structure, name (str): the atom name expression = "stored.infolist.append([model, chain, resv, resn, ss, name])" # Iterate over selection, storing info cmd.iterate(target_sel, expression) # Store info return_list_resn_resi = [] return_list_resn_resi_sel = [] group = "Find_%s_%s"%(resn, target_sel) for info in stored.infolist: cur_model, cur_chain, cur_resv, cur_resn, cur_ss, cur_name = info if cur_resn == resn and cur_name == atom_name: # Convert residue name to one letter cur_aa_3_1 = aa_3_1[resn] # Do selection and group #sel_str = "/%s/%s//%s"%(cur_model, cur_chain, cur_resv) sel_str = "%s and chain %s and resi %s"%(cur_model, cur_chain, cur_resv) resn_resi = "%s%s"%(cur_aa_3_1, cur_resv) sel_str_text = "%s_%s"%(group, resn_resi) cmd.select(sel_str_text, sel_str) # Store return_list_resn_resi.append(resn_resi) return_list_resn_resi_sel.append(sel_str) # If verbose if verb: print("%s , sel: %s"%(resn_resi, sel_str)) # Group selections cmd.group(group, "%s_*"%group) cmd.select("%s_sel"%group, "%s_*"%group) cmd.show("lines", group) # If verbose if verb: print("\nThere are %i hits, in target_sel=%s, with resn=%s\n"%(len(return_list_resn_resi), target_sel, resn)) return return_list_resn_resi, return_list_resn_resi_sel
def toGroup(groupName,sel,prefix="",delOrig=True): """ DESCRIPTION toGroup will take a multistate object and extract it to a group with N objects all in state #1. It essentially performs the following: split_states myObj, prefix=somePrefix group newGroup, somePrefix* delete myObj PARAMETERS: groupName (string) The name of the group to create sel (string) The name of the selection/object from which to make the group prefix (string) The prefix of the names of each of split states. For example, if your prefix is ''obj'' and is in states 1 through 100 then the states will be labeled obj1, obj2, obj3, ..., obj100. delOrig (string/boolean) If true then delete the original selection, otherwise not. RETURN Nothing, it makes a new group. """ if prefix=="": prefix=sel + "_grouped" cmd.split_states(sel, prefix=prefix) cmd.group(groupName,prefix+"*") if delOrig: cmd.delete(sel)
def loadall(pattern, group='', quiet=1, **kwargs): ''' DESCRIPTION Load all files matching given globbing pattern ''' import glob, os filenames = glob.glob(cmd.exp_path(pattern)) for filename in filenames: if not quiet: print ' Loading', filename cmd.load(filename, **kwargs) if len(group): if kwargs.get('object', '') != '': print ' Warning: group and object arguments given' members = [kwargs['object']] else: from pymol.cmd import file_ext_re, gz_ext_re, safe_oname_re members = [gz_ext_re.sub('', file_ext_re.sub('', safe_oname_re.sub('_', os.path.split(filename)[-1]))) for filename in filenames] cmd.group(group, ' '.join(members))
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"16.3969993591": [], "16.3969993591_arrows": []}
def spl_extract(): for name in cmd.get_names("all"): #if name in ['5zwo', '5gm6', '5lj3', '5mps', '6exn', '5ylz', '5y88', '3jb9', '6icz', '6ff7', '5yzg', '5xjc', '5mq0', '5lj5', '6g90', '6n7r', '6n7p']: # this should be auto print(" \ Extracting mode for %s" % name) if '5zwo' in name.lower(): cmd.extract("PRP8_B5zwo", "chain A and 5zwo") cmd.extract("BRR2_B5zwo", "chain D and 5zwo") cmd.extract("LEA1_B5zwo", "chain o and 5zwo") cmd.extract("Msl1_B5zwo", "chain p and 5zwo") cmd.extract("SNU114_B5zwo", "chain C and 5zwo") cmd.extract("U2_B5zwo", "chain H and 5zwo") cmd.extract("U5_B5zwo", "chain B and 5zwo") cmd.extract("U6_B5zwo", "chain F and 5zwo") cmd.extract("U4_B5zwo", "chain I and 5zwo") cmd.extract("Intron_B5zwo", "chain G and 5zwo") cmd.extract("PRP4_B5zwo", "chain K and 5zwo") cmd.extract("PRP31_B5zwo", "chain L and 5zwo") cmd.extract("PRP6_B5zwo", "chain N and 5zwo") cmd.extract("PRP3_B5zwo", "chain J and 5zwo") cmd.extract("DIB1_B5zwo", "chain E and 5zwo") cmd.extract("SNU13_B5zwo", "chain M and 5zwo") cmd.extract("LSM8_B5zwo", "chain z and 5zwo") cmd.extract("LSM2_B5zwo", "chain q and 5zwo") cmd.extract("LSM3_B5zwo", "chain r and 5zwo") cmd.extract("LSM6_B5zwo", "chain x and 5zwo") cmd.extract("LSM5_B5zwo", "chain t and 5zwo") cmd.extract("LSM7_B5zwo", "chain y and 5zwo") cmd.extract("LSM4_B5zwo", "chain s and 5zwo") cmd.extract("SNU66_B5zwo", "chain O and 5zwo") cmd.extract("BUD13_B5zwo", "chain Y and 5zwo") cmd.extract("Cus1_B5zwo", "chain 2 and 5zwo") cmd.extract("HSH155_B5zwo", "chain 1 and 5zwo") cmd.extract("HSH49_B5zwo", "chain 4 and 5zwo") cmd.extract("PML1_B5zwo", "chain Z and 5zwo") cmd.extract("PRP11_B5zwo", "chain v and 5zwo") cmd.extract("RDS3_B5zwo", "chain 5 and 5zwo") cmd.extract("RSE1_B5zwo", "chain 3 and 5zwo") cmd.extract("SNU17_B5zwo", "chain X and 5zwo") cmd.extract("Ysf3_B5zwo", "chain 6 and 5zwo") cmd.extract("SMB1_1_B5zwo", "chain a and 5zwo") cmd.extract("SMB1_2_B5zwo", "chain P and 5zwo") cmd.extract("SMB1_3_B5zwo", "chain h and 5zwo") cmd.extract("SME1_1_B5zwo", "chain e and 5zwo") cmd.extract("SME1_2_B5zwo", "chain T and 5zwo") cmd.extract("SME1_3_B5zwo", "chain i and 5zwo") cmd.extract("SMX3_1_B5zwo", "chain f and 5zwo") cmd.extract("SMX3_2_B5zwo", "chain U and 5zwo") cmd.extract("SMX3_3_B5zwo", "chain j and 5zwo") cmd.extract("SMX2_1_B5zwo", "chain g and 5zwo") cmd.extract("SMX2_2_B5zwo", "chain V and 5zwo") cmd.extract("SMX2_3_B5zwo", "chain k and 5zwo") cmd.extract("SMD3_1_B5zwo", "chain d and 5zwo") cmd.extract("SMD3_2_B5zwo", "chain S and 5zwo") cmd.extract("SMD3_3_B5zwo", "chain l and 5zwo") cmd.extract("SMD1_1_B5zwo", "chain b and 5zwo") cmd.extract("SMD1_2_B5zwo", "chain Q and 5zwo") cmd.extract("SMD1_3_B5zwo", "chain m and 5zwo") cmd.extract("SMD2_1_B5zwo", "chain c and 5zwo") cmd.extract("SMD2_2_B5zwo", "chain R and 5zwo") cmd.extract("SMD2_3_B5zwo", "chain n and 5zwo") cmd.extract("PRP9_B5zwo", "chain u and 5zwo") cmd.extract("PRP21_B5zwo", "chain w and 5zwo") cmd.extract("SNU23_B5zwo", "chain W and 5zwo") cmd.extract("PRP38_B5zwo", "chain 0 and 5zwo") cmd.extract("SPP381_B5zwo", "chain 9 and 5zwo") cmd.set_name("5zwo", "unknown_other_B5zwo") cmd.group("B5zwo", "*_B5zwo") cmd.do("order *, yes") if '5gm6' in name.lower(): cmd.extract("PRP8_Ba5gm6", "chain A and 5gm6") cmd.extract("BRR2_Ba5gm6", "chain B and 5gm6") cmd.extract("BUD31_Ba5gm6", "chain T and 5gm6") cmd.extract("CEF1_Ba5gm6", "chain c and 5gm6") cmd.extract("CWC15_Ba5gm6", "chain S and 5gm6") cmd.extract("CWC2_hRBM22_Ba5gm6", "chain R and 5gm6") cmd.extract("CWC21_Ba5gm6", "chain X and 5gm6") cmd.extract("CWC22_Ba5gm6", "chain Z and 5gm6") cmd.extract("PRP45_Ba5gm6", "chain P and 5gm6") cmd.extract("CDC40_Ba5gm6", "chain n and 5gm6") cmd.extract("PRP19_Ba5gm6", "chain f and 5gm6") cmd.extract("PRP46_Ba5gm6", "chain O and 5gm6") cmd.extract("SLT11/ECM2_Ba5gm6", "chain Q and 5gm6") cmd.extract("SNT309_Ba5gm6", "chain t and 5gm6") cmd.extract("SNU114_Ba5gm6", "chain C and 5gm6") cmd.extract("SYF2_Ba5gm6", "chain f and 5gm6") cmd.extract("SYF1_Ba5gm6", "chain v and 5gm6") cmd.extract("U2_Ba5gm6", "chain 2 and 5gm6") cmd.extract("U5_Ba5gm6", "chain 5 and 5gm6") cmd.extract("U6_Ba5gm6", "chain 6 and 5gm6") cmd.extract("Intron_Ba5gm6", "chain M and 5gm6") cmd.extract("Exon_Ba5gm6", "chain N and 5gm6") cmd.extract("BUD13_Ba5gm6", "chain W and 5gm6") cmd.extract("CLF2_Ba5gm6", "chain d and 5gm6") cmd.extract("Cus1_Ba5gm6", "chain H and 5gm6") cmd.extract("CWC24_Ba5gm6", "chain a and 5gm6") cmd.extract("CWC27_Ba5gm6", "chain b and 5gm6") cmd.extract("HSH155_Ba5gm6", "chain G and 5gm6") cmd.extract("HSH49_Ba5gm6", "chain e and 5gm6") cmd.extract("PML1_Ba5gm6", "chain U and 5gm6") cmd.extract("PRP11_Ba5gm6", "chain I and 5gm6") cmd.extract("PRP2_Ba5gm6", "chain Y and 5gm6") cmd.extract("RDS3_Ba5gm6", "chain J and 5gm6") cmd.extract("RSE1_Ba5gm6", "chain F and 5gm6") cmd.extract("SNU17_Ba5gm6", "chain V and 5gm6") cmd.extract("Ysf3_Ba5gm6", "chain K and 5gm6") cmd.set_name("5gm6", "unknown_other_Ba5gm6") cmd.group("Ba5gm6", "*_Ba5gm6") cmd.do("order *, yes") if '5lj3' in name.lower(): cmd.extract("PRP8_C5lj3", "chain A and 5lj3") cmd.extract("BUD31_C5lj3", "chain L and 5lj3") cmd.extract("CEF1_C5lj3", "chain O and 5lj3") cmd.extract("CLF1_C5lj3", "chain S and 5lj3") cmd.extract("CWC15_C5lj3", "chain P and 5lj3") cmd.extract("CWC16/YJU2_C5lj3", "chain D and 5lj3") cmd.extract("CWC2_hRBM22_C5lj3", "chain M and 5lj3") cmd.extract("CWC21_C5lj3", "chain R and 5lj3") cmd.extract("CWC22_C5lj3", "chain H and 5lj3") cmd.extract("CWC25_C5lj3", "chain F and 5lj3") cmd.extract("ISY1_C5lj3", "chain G and 5lj3") cmd.extract("LEA1_C5lj3", "chain W and 5lj3") cmd.extract("Msl1_C5lj3", "chain Y and 5lj3") cmd.extract("PRP45_C5lj3", "chain K and 5lj3") cmd.extract("PRP46_C5lj3", "chain J and 5lj3") cmd.extract("SLT11/ECM2_C5lj3", "chain N and 5lj3") cmd.extract("SNU114_C5lj3", "chain C and 5lj3") cmd.extract("SYF1_C5lj3", "chain T and 5lj3") cmd.extract("U2_C5lj3", "chain Z and 5lj3") cmd.extract("U5_C5lj3", "chain U and 5lj3") cmd.extract("U6_C5lj3", "chain V and 5lj3") cmd.extract("Intron_C5lj3", "chain I and 5lj3") cmd.extract("Exon_C5lj3", "chain E and 5lj3") cmd.extract("SMB1_1_C5lj3", "chain b and 5lj3") cmd.extract("SMB1_2_C5lj3", "chain k and 5lj3") cmd.extract("SME1_1_C5lj3", "chain e and 5lj3") cmd.extract("SME1_2_C5lj3", "chain p and 5lj3") cmd.extract("SMX3_1_C5lj3", "chain f and 5lj3") cmd.extract("SMX3_2_C5lj3", "chain q and 5lj3") cmd.extract("SMX2_1_C5lj3", "chain g and 5lj3") cmd.extract("SMX2_2_C5lj3", "chain r and 5lj3") cmd.extract("SMD3_1_C5lj3", "chain d and 5lj3") cmd.extract("SMD3_2_C5lj3", "chain n and 5lj3") cmd.extract("SMD1_1_C5lj3", "chain h and 5lj3") cmd.extract("SMD1_2_C5lj3", "chain l and 5lj3") cmd.extract("SMD2_1_C5lj3", "chain j and 5lj3") cmd.extract("SMD2_2_C5lj3", "chain m and 5lj3") cmd.set_name("5lj3", "unknown_other_C5lj3") cmd.group("C5lj3", "*_C5lj3") cmd.do("order *, yes") if '5mps' in name.lower(): cmd.extract("PRP8_Cs5mps", "chain A and 5mps") cmd.extract("BUD31_Cs5mps", "chain L and 5mps") cmd.extract("CEF1_Cs5mps", "chain O and 5mps") cmd.extract("CLF1_Cs5mps", "chain S and 5mps") cmd.extract("CWC15_Cs5mps", "chain P and 5mps") cmd.extract("CWC2_hRBM22_Cs5mps", "chain M and 5mps") cmd.extract("CWC21_Cs5mps", "chain R and 5mps") cmd.extract("CWC22_Cs5mps", "chain H and 5mps") cmd.extract("PRP45_Cs5mps", "chain K and 5mps") cmd.extract("CDC40_Cs5mps", "chain o and 5mps") cmd.extract("PRP46_Cs5mps", "chain J and 5mps") cmd.extract("SLT11/ECM2_Cs5mps", "chain N and 5mps") cmd.extract("SNU114_Cs5mps", "chain C and 5mps") cmd.extract("SYF2_Cs5mps", "chain y and 5mps") cmd.extract("SYF1_Cs5mps", "chain T and 5mps") cmd.extract("U2_Cs5mps", "chain 2 and 5mps") cmd.extract("U5_Cs5mps", "chain 5 and 5mps") cmd.extract("U6_Cs5mps", "chain 6 and 5mps") cmd.extract("5EXON_Cs5mps", "chain E and 5mps") cmd.extract("Intron_Cs5mps", "chain I and 5mps") cmd.extract("Exon_Cs5mps", "chain E and 5mps") cmd.extract("SMB1_Cs5mps", "chain b and 5mps") cmd.extract("SME1_Cs5mps", "chain e and 5mps") cmd.extract("SMX3_Cs5mps", "chain f and 5mps") cmd.extract("SMX2_Cs5mps", "chain g and 5mps") cmd.extract("SMD3_Cs5mps", "chain d and 5mps") cmd.extract("SMD1_Cs5mps", "chain h and 5mps") cmd.extract("SMD2_Cs5mps", "chain j and 5mps") cmd.extract("PRP18_Cs5mps", "chain a and 5mps") cmd.extract("SLU7_Cs5mps", "chain c and 5mps") cmd.set_name("5mps", "unknown_other_Cs5mps") cmd.group("Cs5mps", "*_Cs5mps") cmd.do("order *, yes") if '6exn' in name.lower(): cmd.extract("PRP8_P6exn", "chain A and 6exn") cmd.extract("BUD31_P6exn", "chain L and 6exn") cmd.extract("CEF1_P6exn", "chain O and 6exn") cmd.extract("CLF1_P6exn", "chain S and 6exn") cmd.extract("CWC15_P6exn", "chain P and 6exn") cmd.extract("CWC16/YJU2_P6exn", "chain D and 6exn") cmd.extract("CWC2_hRBM22_P6exn", "chain M and 6exn") cmd.extract("CWC21_P6exn", "chain R and 6exn") cmd.extract("CWC22_P6exn", "chain H and 6exn") cmd.extract("LEA1_P6exn", "chain W and 6exn") cmd.extract("Msl1_P6exn", "chain Y and 6exn") cmd.extract("PRP45_P6exn", "chain K and 6exn") cmd.extract("CDC40_P6exn", "chain o and 6exn") cmd.extract("PRP19_1_P6exn", "chain t and 6exn") cmd.extract("PRP19_2_P6exn", "chain u and 6exn") cmd.extract("PRP19_3_P6exn", "chain v and 6exn") cmd.extract("PRP19_4_P6exn", "chain w and 6exn") cmd.extract("PRP46_P6exn", "chain J and 6exn") cmd.extract("SLT11/ECM2_P6exn", "chain N and 6exn") cmd.extract("SNU114_P6exn", "chain C and 6exn") cmd.extract("SYF1_P6exn", "chain T and 6exn") cmd.extract("U2_P6exn", "chain 2 and 6exn") cmd.extract("U5_P6exn", "chain 5 and 6exn") cmd.extract("U6_P6exn", "chain 6 and 6exn") cmd.extract("Intron_P6exn", "chain I and 6exn") cmd.extract("Exon_P6exn", "chain E and 6exn") cmd.extract("SMB1_1_P6exn", "chain b and 6exn") cmd.extract("SMB1_2_P6exn", "chain k and 6exn") cmd.extract("SME1_1_P6exn", "chain e and 6exn") cmd.extract("SME1_2_P6exn", "chain p and 6exn") cmd.extract("SMX3_1_P6exn", "chain f and 6exn") cmd.extract("SMX3_2_P6exn", "chain q and 6exn") cmd.extract("SMX2_1_P6exn", "chain g and 6exn") cmd.extract("SMX2_2_P6exn", "chain r and 6exn") cmd.extract("SMD3_1_P6exn", "chain d and 6exn") cmd.extract("SMD3_2_P6exn", "chain n and 6exn") cmd.extract("SMD1_1_P6exn", "chain h and 6exn") cmd.extract("SMD1_2_P6exn", "chain l and 6exn") cmd.extract("SMD2_1_P6exn", "chain j and 6exn") cmd.extract("SMD2_2_P6exn", "chain m and 6exn") cmd.extract("PRP22_P6exn", "chain V and 6exn") cmd.extract("PRP18_P6exn", "chain a and 6exn") cmd.extract("SLU7_P6exn", "chain c and 6exn") cmd.extract("unassigned_P6exn", "chain X and 6exn") cmd.set_name("6exn", "unknown_other_P6exn") cmd.group("P6exn", "*_P6exn") cmd.do("order *, yes") if '5ylz' in name.lower(): cmd.extract("PRP8_P5ylz", "chain A and 5ylz") cmd.extract("BUD31_P5ylz", "chain L and 5ylz") cmd.extract("CEF1_P5ylz", "chain J and 5ylz") cmd.extract("CLF1_P5ylz", "chain I and 5ylz") cmd.extract("CWC15_P5ylz", "chain P and 5ylz") cmd.extract("CWC2_hRBM22_P5ylz", "chain N and 5ylz") cmd.extract("CWC21_P5ylz", "chain R and 5ylz") cmd.extract("CWC22_P5ylz", "chain S and 5ylz") cmd.extract("LEA1_P5ylz", "chain o and 5ylz") cmd.extract("Msl1_P5ylz", "chain p and 5ylz") cmd.extract("PRP45_P5ylz", "chain Q and 5ylz") cmd.extract("CDC40_P5ylz", "chain T and 5ylz") cmd.extract("PRP19_1_P5ylz", "chain q and 5ylz") cmd.extract("PRP19_2_P5ylz", "chain r and 5ylz") cmd.extract("PRP19_3_P5ylz", "chain s and 5ylz") cmd.extract("PRP19_4_P5ylz", "chain t and 5ylz") cmd.extract("PRP46_P5ylz", "chain O and 5ylz") cmd.extract("SLT11/ECM2_P5ylz", "chain M and 5ylz") cmd.extract("SNT309_P5ylz", "chain G and 5ylz") cmd.extract("SNU114_P5ylz", "chain C and 5ylz") cmd.extract("SYF2_P5ylz", "chain K and 5ylz") cmd.extract("SYF1_P5ylz", "chain H and 5ylz") cmd.extract("U2_P5ylz", "chain F and 5ylz") cmd.extract("U5_P5ylz", "chain B and 5ylz") cmd.extract("U6_P5ylz", "chain D and 5ylz") cmd.extract("Intron_P5ylz", "chain E and 5ylz") cmd.extract("SMB1_1_P5ylz", "chain a and 5ylz") cmd.extract("SMB1_2_P5ylz", "chain h and 5ylz") cmd.extract("SME1_1_P5ylz", "chain b and 5ylz") cmd.extract("SME1_2_P5ylz", "chain i and 5ylz") cmd.extract("SMX3_1_P5ylz", "chain c and 5ylz") cmd.extract("SMX3_2_P5ylz", "chain j and 5ylz") cmd.extract("SMX2_1_P5ylz", "chain d and 5ylz") cmd.extract("SMX2_2_P5ylz", "chain k and 5ylz") cmd.extract("SMD3_1_P5ylz", "chain e and 5ylz") cmd.extract("SMD3_2_P5ylz", "chain l and 5ylz") cmd.extract("SMD1_1_P5ylz", "chain f and 5ylz") cmd.extract("SMD1_2_P5ylz", "chain m and 5ylz") cmd.extract("SMD2_1_P5ylz", "chain g and 5ylz") cmd.extract("SMD2_2_P5ylz", "chain n and 5ylz") cmd.extract("PRP22_P5ylz", "chain W and 5ylz") cmd.extract("PRP18_P5ylz", "chain U and 5ylz") cmd.extract("SLU7_P5ylz", "chain V and 5ylz") cmd.set_name("5ylz", "unknown_other_P5ylz") cmd.group("P5ylz", "*_P5ylz") cmd.do("order *, yes") if '5y88' in name.lower(): cmd.extract("PRP8_I5y88", "chain A and 5y88") cmd.extract("BUD31_I5y88", "chain L and 5y88") cmd.extract("CLF1_I5y88", "chain I and 5y88") cmd.extract("CWC15_I5y88", "chain P and 5y88") cmd.extract("CWC16/YJU2_I5y88", "chain R and 5y88") cmd.extract("CWC2_hRBM22_I5y88", "chain N and 5y88") cmd.extract("CWC25_I5y88", "chain G and 5y88") cmd.extract("Intron_2_I5y88", "chain E and 5y88") cmd.extract("LEA1_I5y88", "chain o and 5y88") cmd.extract("Msl1_I5y88", "chain p and 5y88") cmd.extract("PRP45_I5y88", "chain Q and 5y88") cmd.extract("CDC40_I5y88", "chain S and 5y88") cmd.extract("PRP19_1_I5y88", "chain q and 5y88") cmd.extract("PRP19_2_I5y88", "chain r and 5y88") cmd.extract("PRP19_3_I5y88", "chain s and 5y88") cmd.extract("PRP19_4_I5y88", "chain t and 5y88") cmd.extract("PRP46_I5y88", "chain O and 5y88") cmd.extract("SLT11/ECM2_I5y88", "chain M and 5y88") cmd.extract("SNT309_I5y88", "chain G and 5y88") cmd.extract("SNU114_I5y88", "chain C and 5y88") cmd.extract("SYF2_I5y88", "chain K and 5y88") cmd.extract("SYF1_I5y88", "chain H and 5y88") cmd.extract("U2_I5y88", "chain F and 5y88") cmd.extract("U5_I5y88", "chain B and 5y88") cmd.extract("U6_I5y88", "chain D and 5y88") cmd.extract("Intron_I5y88", "chain x and 5y88") cmd.extract("RNA_I5y88", "chain x and 5y88") cmd.extract("cwc23_I5y88", "chain T and 5y88") cmd.extract("SPP382_I5y88", "chain U and 5y88") cmd.extract("NTR2_I5y88", "chain V and 5y88") cmd.extract("PRP43_I5y88", "chain W and 5y88") cmd.extract("SMB1_1_I5y88", "chain a and 5y88") cmd.extract("SMB1_2_I5y88", "chain h and 5y88") cmd.extract("SME1_1_I5y88", "chain b and 5y88") cmd.extract("SME1_2_I5y88", "chain i and 5y88") cmd.extract("SMX3_1_I5y88", "chain c and 5y88") cmd.extract("SMX3_2_I5y88", "chain j and 5y88") cmd.extract("SMX2_1_I5y88", "chain d and 5y88") cmd.extract("SMX2_2_I5y88", "chain k and 5y88") cmd.extract("SMD3_1_I5y88", "chain e and 5y88") cmd.extract("SMD3_2_I5y88", "chain l and 5y88") cmd.extract("SMD1_1_I5y88", "chain f and 5y88") cmd.extract("SMD1_2_I5y88", "chain m and 5y88") cmd.extract("SMD2_1_I5y88", "chain g and 5y88") cmd.extract("SMD2_2_I5y88", "chain n and 5y88") cmd.set_name("5y88", "unknown_other_I5y88") cmd.group("I5y88", "*_I5y88") cmd.do("order *, yes") if '3jb9' in name.lower(): cmd.extract("U2_3jb9", "chain P and 3jb9") cmd.extract("U5_3jb9", "chain C and 3jb9") cmd.extract("U6_3jb9", "chain N and 3jb9") cmd.extract("Intron_1_3jb9", "chain O and 3jb9") cmd.extract("Intron_2_3jb9", "chain Q and 3jb9") cmd.extract("Spp42_yPrp8_3jb9", "chain A and 3jb9") cmd.extract("CWF15_yCWC15_3jb9", "chain h and 3jb9") cmd.set_name("3jb9", "unknown_other_3jb9") cmd.group("3jb9", "*_3jb9") cmd.do("order *, yes") if '6icz' in name.lower(): cmd.extract("CWC15_hP_6icz", "chain P and 6icz") cmd.extract("U2_hP_6icz", "chain H and 6icz") cmd.extract("U5_hP_6icz", "chain B and 6icz") cmd.extract("U6_hP_6icz", "chain F and 6icz") cmd.extract("Intron_hP_6icz", "chain G and 6icz") cmd.extract("cwc23_hP_6icz", "chain 6ICZ and 6icz") cmd.set_name("6icz", "unknown_other_hP_6icz") cmd.group("hP6icz", "*_hP_6icz") cmd.do("order *, yes") if '6ff7' in name.lower(): cmd.extract("CWC15_hBa_6ff7", "chain R and 6ff7") cmd.extract("CWC2_hRBM22_hBa_6ff7", "chain P and 6ff7") cmd.extract("U2_hBa_6ff7", "chain 2 and 6ff7") cmd.extract("U5_hBa_6ff7", "chain 5 and 6ff7") cmd.extract("U6_hBa_6ff7", "chain 6 and 6ff7") cmd.extract("Intron_hBa_6ff7", "chain Z and 6ff7") cmd.set_name("6ff7", "unknown_other_hBa_6ff7") cmd.group("hBa6ff7", "*_hBa_6ff7") cmd.do("order *, yes") if '5yzg' in name.lower(): cmd.extract("CWC15_hC_5yzg", "chain P and 5yzg") cmd.extract("CWC2_hRBM22_hC_5yzg", "chain O and 5yzg") cmd.extract("CWC25_hC_5yzg", "chain X and 5yzg") cmd.extract("PRP16_hDHX38_hC_5yzg", "chain Z and 5yzg") cmd.extract("U2_hC_5yzg", "chain H and 5yzg") cmd.extract("U5_hC_5yzg", "chain B and 5yzg") cmd.extract("U6_hC_5yzg", "chain F and 5yzg") cmd.extract("Intron_hC_5yzg", "chain G and 5yzg") cmd.set_name("5yzg", "unknown_other_hC_5yzg") cmd.group("hC5yzg", "*_hC_5yzg") cmd.do("order *, yes") if '5xjc' in name.lower(): cmd.extract("CWC15_hX_5xjc", "chain P and 5xjc") cmd.extract("CWC25_hX_5xjc", "chain X and 5xjc") cmd.extract("U2_hX_5xjc", "chain H and 5xjc") cmd.extract("U5_hX_5xjc", "chain B and 5xjc") cmd.extract("U6_hX_5xjc", "chain F and 5xjc") cmd.extract("Intron_hX_5xjc", "chain G and 5xjc") cmd.extract("PRKRIP1_hX_5xjc", "chain X and 5xjc") cmd.set_name("5xjc", "unknown_other_hX_5xjc") cmd.group("hX5xjc", "*_hX_5xjc") cmd.do("order *, yes") if '5mq0' in name.lower(): cmd.extract("CWC15_yCs_5mq0", "chain P and 5mq0") cmd.extract("CWC2_hRBM22_yCs_5mq0", "chain M and 5mq0") cmd.extract("U2_yCs_5mq0", "chain 2 and 5mq0") cmd.extract("U5_yCs_5mq0", "chain 5 and 5mq0") cmd.extract("U6_yCs_5mq0", "chain 6 and 5mq0") cmd.extract("5EXON_yCs_5mq0", "chain E and 5mq0") cmd.extract("Intron_yCs_5mq0", "chain I and 5mq0") cmd.extract("exon-3_yCs_5mq0", "chain 3 and 5mq0") cmd.set_name("5mq0", "unknown_other_yCs_5mq0") cmd.group("yCs5mq0", "*_yCs_5mq0") cmd.do("order *, yes") if '5lj5' in name.lower(): cmd.extract("PRP8_yC_5lj5", "chain A and 5lj5") cmd.extract("BRR2_yC_5lj5", "chain B and 5lj5") cmd.extract("BUD31_yC_5lj5", "chain L and 5lj5") cmd.extract("CEF1_yC_5lj5", "chain O and 5lj5") cmd.extract("CLF1_yC_5lj5", "chain S and 5lj5") cmd.extract("CWC15_yC_5lj5", "chain P and 5lj5") cmd.extract("CWC16/YJU2_yC_5lj5", "chain D and 5lj5") cmd.extract("CWC2_hRBM22_yC_5lj5", "chain M and 5lj5") cmd.extract("CWC21_yC_5lj5", "chain R and 5lj5") cmd.extract("CWC22_yC_5lj5", "chain H and 5lj5") cmd.extract("CWC25_yC_5lj5", "chain F and 5lj5") cmd.extract("ISY1_yC_5lj5", "chain G and 5lj5") cmd.extract("Msl1_yC_5lj5", "chain Y and 5lj5") cmd.extract("PRP45_yC_5lj5", "chain K and 5lj5") cmd.extract("PRP16_hDHX38_yC_5lj5", "chain Q and 5lj5") cmd.extract("PRP19_1_yC_5lj5", "chain t and 5lj5") cmd.extract("PRP19_2_yC_5lj5", "chain u and 5lj5") cmd.extract("PRP19_3_yC_5lj5", "chain v and 5lj5") cmd.extract("PRP19_4_yC_5lj5", "chain w and 5lj5") cmd.extract("PRP46_yC_5lj5", "chain J and 5lj5") cmd.extract("SLT11/ECM2_yC_5lj5", "chain N and 5lj5") cmd.extract("SNT309_yC_5lj5", "chain s and 5lj5") cmd.extract("SNU114_yC_5lj5", "chain C and 5lj5") cmd.extract("SYF1_yC_5lj5", "chain T and 5lj5") cmd.extract("U2_yC_5lj5", "chain Z and 5lj5") cmd.extract("U5_yC_5lj5", "chain U and 5lj5") cmd.extract("U6_yC_5lj5", "chain V and 5lj5") cmd.extract("5EXON_yC_5lj5", "chain E and 5lj5") cmd.extract("Intron_yC_5lj5", "chain I and 5lj5") cmd.extract("SMB1_1_yC_5lj5", "chain b and 5lj5") cmd.extract("SMB1_2_yC_5lj5", "chain k and 5lj5") cmd.extract("SME1_1_yC_5lj5", "chain e and 5lj5") cmd.extract("SME1_2_yC_5lj5", "chain p and 5lj5") cmd.extract("SMX3_1_yC_5lj5", "chain f and 5lj5") cmd.extract("SMX3_2_yC_5lj5", "chain q and 5lj5") cmd.extract("SMX2_1_yC_5lj5", "chain g and 5lj5") cmd.extract("SMX2_2_yC_5lj5", "chain r and 5lj5") cmd.extract("SMD3_1_yC_5lj5", "chain d and 5lj5") cmd.extract("SMD3_2_yC_5lj5", "chain n and 5lj5") cmd.extract("SMD1_1_yC_5lj5", "chain h and 5lj5") cmd.extract("SMD1_2_yC_5lj5", "chain l and 5lj5") cmd.extract("SMD2_1_yC_5lj5", "chain j and 5lj5") cmd.extract("SMD2_2_yC_5lj5", "chain m and 5lj5") cmd.extract("unassigned_yC_5lj5", "chain x and 5lj5") cmd.set_name("5lj5", "unknown_other_yC_5lj5") cmd.group("yC5lj5", "*_yC_5lj5") cmd.do("order *, yes") if '6g90' in name.lower(): cmd.extract("LEA1_yPre_6g90", "chain W and 6g90") cmd.extract("Msl1_yPre_6g90", "chain Y and 6g90") cmd.extract("Ysf3_yPre_6g90", "chain Z and 6g90") cmd.extract("SMB1_1_yPre_6g90", "chain b and 6g90") cmd.extract("SMB1_2_yPre_6g90", "chain s and 6g90") cmd.extract("SME1_1_yPre_6g90", "chain e and 6g90") cmd.extract("SME1_2_yPre_6g90", "chain w and 6g90") cmd.extract("SMX3_1_yPre_6g90", "chain f and 6g90") cmd.extract("SMX3_2_yPre_6g90", "chain x and 6g90") cmd.extract("SMX2_1_yPre_6g90", "chain g and 6g90") cmd.extract("SMX2_2_yPre_6g90", "chain y and 6g90") cmd.extract("SMD3_1_yPre_6g90", "chain d and 6g90") cmd.extract("SMD3_2_yPre_6g90", "chain v and 6g90") cmd.extract("SMD1_1_yPre_6g90", "chain h and 6g90") cmd.extract("SMD1_2_yPre_6g90", "chain t and 6g90") cmd.extract("SMD2_1_yPre_6g90", "chain i and 6g90") cmd.extract("SMD2_2_yPre_6g90", "chain u and 6g90") cmd.extract("unassigned_yPre_6g90", "chain X and 6g90") cmd.extract("MUD1_yPre_6g90", "chain A and 6g90") cmd.extract("SNP1_yPre_6g90", "chain B and 6g90") cmd.extract("YHC1_yPre_6g90", "chain C and 6g90") cmd.extract("PRP39_yPre_6g90", "chain D and 6g90") cmd.extract("PRP42_yPre_6g90", "chain E and 6g90") cmd.extract("NAM8_yPre_6g90", "chain F and 6g90") cmd.extract("SNU56_yPre_6g90", "chain G and 6g90") cmd.extract("LUC7_yPre_6g90", "chain H and 6g90") cmd.extract("SNU71_yPre_6g90", "chain J and 6g90") cmd.extract("HSH155_yPre_6g90", "chain O and 6g90") cmd.extract("RSE1_yPre_6g90", "chain P and 6g90") cmd.extract("CUS1_yPre_6g90", "chain Q and 6g90") cmd.extract("HSH49_yPre_6g90", "chain R and 6g90") cmd.extract("RDS3_yPre_6g90", "chain S and 6g90") cmd.extract("PRP9_yPre_6g90", "chain T and 6g90") cmd.extract("PRP11_yPre_6g90", "chain U and 6g90") cmd.extract("PRP21_yPre_6g90", "chain V and 6g90") cmd.set_name("6g90", "unknown_other_yPre_6g90") cmd.group("yPre6g90", "*_yPre_6g90") cmd.do("order *, yes") if '6n7r' in name.lower(): cmd.extract("Intron_yE_6n7r", "chain r and 6n7r") cmd.extract("SMB1_yE_6n7r", "chain K and 6n7r") cmd.extract("SME1_yE_6n7r", "chain O and 6n7r") cmd.extract("SMX3_yE_6n7r", "chain P and 6n7r") cmd.extract("SMX2_yE_6n7r", "chain Q and 6n7r") cmd.extract("SMD3_yE_6n7r", "chain N and 6n7r") cmd.extract("SMD1_yE_6n7r", "chain L and 6n7r") cmd.extract("SMD2_yE_6n7r", "chain M and 6n7r") cmd.extract("MUD1_yE_6n7r", "chain C and 6n7r") cmd.extract("SNP1_yE_6n7r", "chain A and 6n7r") cmd.extract("YHC1_yE_6n7r", "chain B and 6n7r") cmd.extract("PRP39_yE_6n7r", "chain E and 6n7r") cmd.extract("PRP42_yE_6n7r", "chain D and 6n7r") cmd.extract("NAM8_yE_6n7r", "chain F and 6n7r") cmd.extract("SNU56_yE_6n7r", "chain G and 6n7r") cmd.extract("LUC7_yE_6n7r", "chain I and 6n7r") cmd.extract("SNU71_yE_6n7r", "chain H and 6n7r") cmd.extract("U1_yE_6n7r", "chain R and 6n7r") cmd.set_name("6n7r", "unknown_other_yE_6n7r") cmd.group("yE6n7r", "*_yE_6n7r") cmd.do("order *, yes") if '6n7p' in name.lower(): cmd.extract("Intron_yE_6n7p", "chain r and 6n7p") cmd.extract("SMB1_yE_6n7p", "chain K and 6n7p") cmd.extract("SME1_yE_6n7p", "chain O and 6n7p") cmd.extract("SMX3_yE_6n7p", "chain P and 6n7p") cmd.extract("SMX2_yE_6n7p", "chain Q and 6n7p") cmd.extract("SMD3_yE_6n7p", "chain N and 6n7p") cmd.extract("SMD1_yE_6n7p", "chain L and 6n7p") cmd.extract("SMD2_yE_6n7p", "chain M and 6n7p") cmd.extract("MUD1_yE_6n7p", "chain C and 6n7p") cmd.extract("SNP1_yE_6n7p", "chain A and 6n7p") cmd.extract("YHC1_yE_6n7p", "chain B and 6n7p") cmd.extract("PRP39_yE_6n7p", "chain E and 6n7p") cmd.extract("PRP42_yE_6n7p", "chain D and 6n7p") cmd.extract("NAM8_yE_6n7p", "chain F and 6n7p") cmd.extract("SNU56_yE_6n7p", "chain G and 6n7p") cmd.extract("LUC7_yE_6n7p", "chain I and 6n7p") cmd.extract("SNU71_yE_6n7p", "chain H and 6n7p") cmd.extract("U1_yE_6n7p", "chain R and 6n7p") cmd.extract("PRP40_yE_6n7p", "chain J and 6n7p") cmd.extract("STO1_yE_6n7p", "chain X and 6n7p") cmd.extract("CBC2_yE_6n7p", "chain Y and 6n7p") cmd.set_name("6n7p", "unknown_other_yE_6n7p") cmd.group("yE6n7p", "*_yE_6n7p") cmd.do("order *, yes")
gfiles = ['donor.grd', 'apolar.grd', 'acceptor.grd'] grids = ['donor', 'apolar', 'acceptor'] num = 0 surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s'%(gfiles[i]), '%s_%s'%(grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s'%(grids[i], t, num), '%s_%s'%(grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s'%(grids[i], t, num)) cmd.color(colour_dict['%s'%(grids[i])], 'surface_%s_%s_%s'%(grids[i], t, num)) cmd.group('threshold_%s'%(t), members = 'surface_%s_%s_%s'%(grids[i],t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g,num))
cmd.load("hotspot_1/apolar.grd", "apolar_hotspot_1") cmd.isosurface(name="surface_apolar_hotspot_1", map="apolar_hotspot_1", level="5") cmd.color("yellow", "surface_apolar_hotspot_1") cmd.set("transparency", 0.2, "surface_apolar_hotspot_1") cmd.load("hotspot_1/donor.grd", "donor_hotspot_1") cmd.isosurface(name="surface_donor_hotspot_1", map="donor_hotspot_1", level="5") cmd.color("blue", "surface_donor_hotspot_1") cmd.set("transparency", 0.2, "surface_donor_hotspot_1") cmd.load("hotspot_1/acceptor.grd", "acceptor_hotspot_1") cmd.isosurface(name="surface_acceptor_hotspot_1", map="acceptor_hotspot_1", level="5") cmd.color("red", "surface_acceptor_hotspot_1") cmd.set("transparency", 0.2, "surface_acceptor_hotspot_1") cmd.group("hotspot_1", members="apolar_hotspot_1") cmd.group("hotspot_1", members="donor_hotspot_1") cmd.group("hotspot_1", members="acceptor_hotspot_1") cmd.group("hotspot_1", members="surface_apolar_hotspot_1") cmd.group("hotspot_1", members="surface_donor_hotspot_1") cmd.group("hotspot_1", members="surface_acceptor_hotspot_1") cmd.pseudoatom(object="PS_apolar_hotspot_1_0", pos=(3.0, 16.5, -29.5), color=(1, 1, 1), label=19.0) cmd.pseudoatom(object="PS_apolar_hotspot_1_1", pos=(2.5, 17.5, -30.5), color=(1, 1, 1), label=19.0) cmd.pseudoatom(object="PS_apolar_hotspot_1_2", pos=(1.6666666666666714, 13.25, -34.0), color=(1, 1, 1), label=16.0) cmd.pseudoatom(object="PS_apolar_hotspot_1_3", pos=(2.0, 16.0, -30.5), color=(1, 1, 1), label=19.0) cmd.pseudoatom(object="PS_apolar_hotspot_1_4", pos=(0.75, 18.333333333333336, -18.75), color=(1, 1, 1), label=23.1)
def selections_group(self): """Group all selections""" cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname)) cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT ' 'Saltbridges MetalComplexes') cmd.group('Atoms', '') cmd.group('Atoms.Protein', 'Hydrophobic-P HBondAccept-P HBondDonor-P HalogenAccept Centroids-P PiCatRing-P ' 'StackRings-P PosCharge-P NegCharge-P AllBSRes Chargecenter-P Metal-P') cmd.group('Atoms.Ligand', 'Hydrophobic-L HBondAccept-L HBondDonor-L HalogenDonor Centroids-L NegCharge-L ' 'PosCharge-L NegCharge-L ChargeCenter-L StackRings-L PiCatRing-L Metal-L Metal-M ' 'Unpaired-HBA Unpaired-HBD Unpaired-HAL Unpaired-RINGS') cmd.group('Atoms.Other', 'Water Metal-W') cmd.order('*', 'y')
def get_resi_stats(target_sel="all", residues=[], group_id="X", atom="NZ", atom_dist=8, resi_n_term=8, resi_c_term=8, verb=True): # The distance in angstrom to look for var_dist = 12 if type(residues) != list: print("\nERROR: The residues should be supplied as a list\n") return # Get current setting ini_setting = cmd.get("dot_solvent") ini_setting2 = cmd.get("dot_density") # Increasing dot_density makes calculation slower, but not a big difference #cmd.set('dot_density', 3) # Make groups group = "Stats_%s_%s" % (target_sel, group_id) group_atom = "Stats_%s_%s_%s" % (atom, target_sel, group_id) group_chain = "Stats_%s_%s_%s" % ("chain", target_sel, group_id) group_3dweb = "Stats_%s_%s_%s" % ("3dweb", target_sel, group_id) # Make list for storing slist = [] # Make file for writing wfileweblogo = open("resi_stats_weblogo_%s_%s.txt" % (target_sel, group_id), 'w') for residue in residues: residue = residue.strip() resn_1 = residue[0].upper() resn_3 = aa_1_3[resn_1] resi = int(residue[1:]) # Check input if resn_1.isdigit(): print("\nERROR: The residue should be in format of ex: K10\n") return # Do selection and group sel_str = "%s and resn %s and resi %s" % (target_sel, resn_3, resi) resn_resi = "%s%s" % (resn_1, resi) sel_str_text = "%s_%s_%s" % (target_sel, group_id, resn_resi) cmd.select(sel_str_text, sel_str) # Make quick test, to see if the atom is there sel_str_atom_test = "%s and name %s" % (sel_str_text, atom) test_str = "Test_nr_atoms" cmd.select(test_str, sel_str_atom_test) nr_test = cmd.count_atoms(test_str) if nr_test != 1: print("\nERROR: The selection '%s', has only nr of atoms:%s. SKIPPING"%(sel_str_atom_test, nr_test)) continue # MSA = Molecular Surface Area cmd.set("dot_solvent", "off") MSA = cmd.get_area(sel_str) # SASA = Solvent Accessible Surface Area cmd.set("dot_solvent", "on") SASA = cmd.get_area(sel_str) # Get the chain residues chain = "."*(resi_n_term + resi_c_term + 1) chain_sec = "."*(resi_n_term + resi_c_term + 1) resi_sel_min = resi-resi_n_term if resi_sel_min < 1: resi_sel_min = 1 resi_sel_max = resi+resi_c_term resi_sel = "%i-%i" % (resi_sel_min, resi_sel_max) # Make selection sel_str_chain = "%s and resi %s and name CA" % (target_sel, resi_sel) sel_str_text_chain = "%s_%s_%s_%s" % ("chain", target_sel, group_id, resn_resi) cmd.select(sel_str_text_chain, sel_str_chain) # Get the chain info stored.list_chain = [] expression_chain="stored.list_chain.append([resi, resn, name, ss])" cmd.iterate(sel_str_text_chain, expression_chain) for chain_resi_info in stored.list_chain: chain_resi, chain_resn, chain_name, chain_ss = chain_resi_info # Convert ss, secondary structure, if ss=S (Sheet), or ss='' (Not Helix or Sheet) if chain_ss == '': chain_ss = 'L' chain_resi = int(chain_resi) try: chain_resn_1 = aa_3_1[chain_resn] except KeyError: chain_resn_1 = "." # Calculate index index = resi_n_term - (resi - chain_resi) # Replace in string for residue names chain = chain[:index] + chain_resn_1 + chain[index + 1:] # Replace in string for secondary structyre chain_sec = chain_sec[:index] + chain_ss + chain_sec[index + 1:] # Get number of neighbour atoms # Make selection for NZ atoms sel_str_atom = "%s and name %s" % (sel_str_text, atom) sel_str_text_atom = "%s_%s_%s_%s" % (atom, target_sel, group_id, resn_resi) cmd.select(sel_str_text_atom, sel_str_atom) # Make selection around NZ atom for fixed distance, and count sel_str_atom_around = "%s around %s and not (%s)" % (sel_str_text_atom, atom_dist, sel_str) sel_str_text_atom_around = "%s_around_%s_%s_%s" % (atom, target_sel, group_id, resn_resi) cmd.select(sel_str_text_atom_around, sel_str_atom_around) # Count around stored.list = [] expression="stored.list.append([resi, resn, name])" cmd.iterate(sel_str_text_atom_around, expression) nr_atoms_around = len(stored.list) # Make selection around NZ atom for variable distance #for i in range(2, var_dist+1): for i in range(2, var_dist+1, 2): dist = i dist_pre = dist - 1 # Select for an angstrom shorter sel_str_atom_3dweb_pre = "byres %s around %s" % (sel_str_text_atom, dist_pre) sel_str_text_atom_3dweb_pre = "%s_3dweb_pre_%s_%s_%s_%s_%s" % (atom, target_sel, group_id, resn_resi, dist, dist_pre) cmd.select(sel_str_text_atom_3dweb_pre, sel_str_atom_3dweb_pre) # Select at distance sel_str_atom_3dweb_post = "byres %s around %s" % (sel_str_text_atom, dist) sel_str_text_atom_3dweb_post = "%s_3dweb_post_%s_%s_%s_%s_%s" % (atom, target_sel, group_id, resn_resi, dist, dist) cmd.select(sel_str_text_atom_3dweb_post, sel_str_atom_3dweb_post) # Make selection for uniq residues with shell sel_str_text_atom_3dweb_sel = "%s_3dweb_sel_%s_%s_%s_%s" % (atom, target_sel, group_id, resn_resi, dist) cmd.select(sel_str_text_atom_3dweb_sel, "(%s and not %s) and name CA" % (sel_str_atom_3dweb_post, sel_str_atom_3dweb_pre)) # delete cmd.delete(sel_str_text_atom_3dweb_pre) cmd.delete(sel_str_text_atom_3dweb_post) # Loop through selecion stored.list_3dweb = [] expression_3dweb="stored.list_3dweb.append([resi, resn, name])" cmd.iterate(sel_str_text_atom_3dweb_sel, expression_3dweb) for web3d_residues in stored.list_3dweb: web3d_resi, web3d_resn, web3d_name = web3d_residues try: web3d_resn_1 = aa_3_1[web3d_resn] except KeyError: web3d_resn_1 = "." # Write http://weblogo.threeplusone.com/ file FASTA_text = "> %s %s %s %s %s, dist=%s resi=%s resn=%s %s" %(target_sel, group_id, resi, resn_1, resn_3, dist, web3d_resi, web3d_resn_1, web3d_resn) weblogo = "."*(var_dist) weblogo = weblogo[:i-1] + web3d_resn_1 + weblogo[i:] # Write wfileweblogo.write(FASTA_text + "\n") wfileweblogo.write(weblogo + "\n") # Store info slist.append([target_sel, group_id, resn_resi, resn_1, resi, MSA, SASA, nr_atoms_around, chain, chain_sec]) # Group selections cmd.group(group, "%s_%s_*" % (target_sel, group_id)) cmd.select("%s_sel"%group, "%s_%s_*" % (target_sel, group_id)) # Group around cmd.group(group_chain, "%s_%s_%s*" % ("chain",target_sel, group_id) ) cmd.group(group_atom, "%s_%s_%s_*" % (atom, target_sel, group_id)) cmd.group(group_atom, "%s_around_%s_%s_*" % (atom, target_sel, group_id)) cmd.group(group_3dweb, "%s_3dweb_sel_%s_%s_*" % (atom, target_sel, group_id)) # Write output wfile = open("resi_stats_%s_%s.csv" % (target_sel, group_id), 'w') wfile.write("target_sel;group_id;resn_resi;resn;resi;MSA;SASA;nr_atoms_around;chain;chain_sec"+"\n") for i in slist: wfile.write("%s;%s;%s;%s;%i;%3.0f;%3.0f;%i;%s;%s" % (i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]) + "\n") wfile.close() wfileweblogo.close() # Back to before cmd.set("dot_solvent", ini_setting) cmd.set('dot_density', ini_setting2)
def dock(self): #setup tables with distances, errors and weights expDistances = [] expErrors = [] weights = [] constraintNames = [] for restraint in self.restraints: constraintNames.append( "%s-%s" % (restraint["anchorAname"], restraint["anchorBname"])) expDistances.append(restraint["distance"]) expErrors.append(restraint["width"]) weights.append(restraint["weight"]) expDistances = numpy.array(expDistances) expErrors = numpy.array(expErrors) weights = numpy.array(weights) # setup Proteins anchorAcoords = [] for restraint in self.restraints: anchorAcoords.append(restraint["anchorAcoord"]) proteinAname = self.restraints[0]["proteinAname"] anchorAcalphas = self.restraints[0]["proteinAcalpha"] proteinA = Protein(anchorAcoords, anchorAcalphas, proteinAname) anchorBcoords = [] for restraint in self.restraints: anchorBcoords.append(restraint["anchorBcoord"]) proteinBname = self.restraints[0]["proteinBname"] anchorBcalphas = self.restraints[0]["proteinBcalpha"] proteinB = Protein(anchorBcoords, anchorBcalphas, proteinBname) # move both to origin proteinA.moveToOrigin(proteinA.labelAtomsCog) proteinB.moveToOrigin(proteinB.labelAtomsCog) ####### # evolve ####### zeroChromosome = Chromosome("None") zeroChromosome.genes = numpy.array([0, 0, 0, 0, 0, 0]) # setup populations print "setting up populations..." populations = [] for i in range(0, self.numberOfPopulations): if self.symmetry == "C2": population = Population(self.numberOfChromosomes, "C2") elif self.symmetry == "None": population = Population(self.numberOfChromosomes, "None") population.name = "%i" % (i + 1) populations.append(population) # put them into an environment and evolve environment1 = Environment(populations, proteinA, proteinB, expDistances, expErrors, weights, False, False, False) environment1.constraintNames = constraintNames #environment1.applySelectionPressure() #for population in environment1.populations: # population.log += population.chromosomes[0].printChromosomeWithoutClashes() self.processes = [] resultQueue = multiprocessing.Queue() progressQueue = multiprocessing.Queue() numberOfProcesses = len(environment1.populations) for idx, population in enumerate(environment1.populations): environment = copy.deepcopy(environment1) p = multiprocessing.Process(target=self.worker1, args=(environment, idx, resultQueue, progressQueue)) p.start() self.processes.append(p) cycles = 0 maxCycles = numberOfProcesses * (self.numberOfGenerations + self.numberOfRigidBodyCycles) #while True: # cycles += progressQueue.get() # progress = cycles/(numberOfProcesses*(self.numberOfGenerations+self.numberOfRigidBodyCycles)) # #send message to main thread # wx.CallAfter(pub.sendMessage, "docking.update", progress=progress) # if cycles >= maxCycles: # break resultsList = [resultQueue.get() for p in self.processes] for p in self.processes: p.join() environment1.populations = resultsList # create solutions print "" print "Solutions:" nonClashingSolution = 1 clashingSolution = 1 for population in environment1.populations: #createPseudoatom(self.labelPositionsProteinB, "tmpSolution-labels", 1) tmpProtein = Protein(proteinB.originalLabelAtoms, proteinB.originalLabelAtoms, "tmpSolution-labels") solution = population.chromosomes[0] # print solution.printChromosomeWithClashes() if solution.clashes <= 5: nameOfSolution = "%s-%i_sol-%i" % (self.objectPrefix, self.dockingRunNumber, nonClashingSolution) solution.name = nameOfSolution proteinB.moveInPymol(nameOfSolution, solution, 1) #tmpProtein.moveInPymol("%s-labels" % nameOfSolution, solution, 1) cmd.translate(list(proteinA.labelAtomsCog.reshape(-1, )), nameOfSolution, 1, 0, None) #cmd.translate(list(proteinA.labelAtomsCog.reshape(-1,)), "%s-labels" % nameOfSolution, 1, 0, None) nonClashingSolution += 1 elif solution.clashes > 5: nameOfSolution = "%s-%i_clash-%i" % ( self.objectPrefix, self.dockingRunNumber, clashingSolution) solution.name = nameOfSolution proteinB.moveInPymol(nameOfSolution, solution, 1) #tmpProtein.moveInPymol("%s-labels" % nameOfSolution, solution, 1) cmd.translate(list(proteinA.labelAtomsCog.reshape(-1, )), nameOfSolution, 1, 0, None) #cmd.translate(list(proteinA.labelAtomsCog.reshape(-1,)), "%s-labels" % nameOfSolution, 1, 0, None) clashingSolution += 1 cmd.group("%s-%i" % (self.objectPrefix, self.dockingRunNumber), "%s-%i*" % (self.objectPrefix, self.dockingRunNumber)) #cmd.set_view(myView) return environment1, self.settings
def pyTwister(selection, chains): ''' DESCRIPTION Brief description what this function does goes here ''' #some preliminary stuff #cmd.reinitialize() #cmd.load("Helix-coot-0.pdb") #cmd.delete("Alpha*") #cmd.delete("Axis*") #cmd.delete("coiledCoil*") cmd.set("dash_gap","0") cmd.set("dash_radius","0.2") #make list of residueNames stored.residueNumbersInSelection=[] cmd.iterate(selection + " & name ca", "stored.residueNumbersInSelection.append(resi)") stored.residuesInSelection=[] cmd.iterate(selection + " & name ca", "stored.residuesInSelection.append(resn)") stored.residueOneLetterCodes=[] helicesInSelection=[] #calculate alphaHelixParameters for i in range (0, len(chains)): dict={} #get ca positions dict['caPositions']=getCaPositions(selection + " & chain " + chains[i] + " & name ca") #reverse ca dictionary for the reverse calculations C-term to N-term will be averaged later dict['reverseCaPositions']=dict['caPositions'][::-1] #calculate bisections dict['bisections']=calculateBisections(dict['caPositions']) dict['reverseBisections']=calculateBisections(dict['reverseCaPositions']) #calculate helix axis points by adjusting the length of the bisection vectors dict['helixAxisPoints']=calculateHelixAxisPoints(dict['caPositions'], dict['bisections']) dict['reverseHelixAxisPoints']=calculateHelixAxisPoints(dict['reverseCaPositions'], dict['reverseBisections']) #some artistics to get the reversedReversed helixAxisPoints #dict['reverseHelixAxisPoints'].append([0,0,0]) #appends trailing 0,0,0 before turning #dict['reverseHelixAxisPoints'].remove([0,0,0]) #removes leading 0,0,0 before turning dict['reversedReverseHelixAxisPoints']=dict['reverseHelixAxisPoints'][::-1] #average helixAxisPoints from forward and reverse calculation dict['avgHelixAxisPoints']=(numpy.array(dict['helixAxisPoints'])+numpy.array(dict['reversedReverseHelixAxisPoints']))/2 #calculate alphaHelix parameters with averaged helix axis dict['alphaHelicalRadiusPerResidue']=calculateAlphaHelicalRadius(dict['caPositions'], dict['avgHelixAxisPoints']) dict['alphaHelicalRisesPerResidue']=calculateAlphaHelicalRisePerResidue(dict['avgHelixAxisPoints']) dict['alphaHelicalPhaseYieldsPerResidue']=calculateAlphaHelicalPhaseYieldPerResidue(dict['caPositions'], dict['avgHelixAxisPoints'],0) dict['alphaHelicalResiduesPerTurn']=calculateAlphaHelicalPitchPerResidue(dict['avgHelixAxisPoints'],dict['alphaHelicalRisesPerResidue'],dict['alphaHelicalPhaseYieldsPerResidue']) helicesInSelection.append(dict) #calculate average of alpha helical parameters - average of AxisPoints is coiledCoilAxis averageAlphaHelicalParameters={} for key in ['avgHelixAxisPoints','alphaHelicalRadiusPerResidue', 'alphaHelicalRisesPerResidue', 'alphaHelicalPhaseYieldsPerResidue', 'alphaHelicalResiduesPerTurn']: average=0 i=0 while (i < len(helicesInSelection)): #print key average+=numpy.array(helicesInSelection[i][key]) #print helicesInSelection[i][key], key i+=1 average/=len(helicesInSelection) #print average averageAlphaHelicalParameters[key]=average #calculate coiled coil parameters coiledCoils=[] for i in range (0, len(chains)-1): coiledCoilParameters={} coiledCoilParameters['coiledCoilAxisPoints']=averageAlphaHelicalParameters['avgHelixAxisPoints'] coiledCoilParameters['coiledCoilRadiusPerResidue']=calculateAlphaHelicalRadius(helicesInSelection[i]['avgHelixAxisPoints'], coiledCoilParameters['coiledCoilAxisPoints']) coiledCoilParameters['coiledCoilRisesPerResidue']=calculateAlphaHelicalRisePerResidue(coiledCoilParameters['coiledCoilAxisPoints']) coiledCoilParameters['coiledCoilPhaseYieldsPerResidue']=calculateAlphaHelicalPhaseYieldPerResidue(helicesInSelection[i]['avgHelixAxisPoints'], coiledCoilParameters['coiledCoilAxisPoints'],0) coiledCoilParameters['coiledCoilPitch']=numpy.array(calculateAlphaHelicalPitchPerResidue(coiledCoilParameters['coiledCoilAxisPoints'],coiledCoilParameters['coiledCoilRisesPerResidue'],numpy.absolute(numpy.array(coiledCoilParameters['coiledCoilPhaseYieldsPerResidue']))))*numpy.array(coiledCoilParameters['coiledCoilRisesPerResidue']) coiledCoils.append(coiledCoilParameters) #calculate average of coiled coil parameters averageCoiledCoilParameters={} for key in ['coiledCoilAxisPoints','coiledCoilRadiusPerResidue', 'coiledCoilRisesPerResidue', 'coiledCoilPhaseYieldsPerResidue', 'coiledCoilPitch']: average=0 i=0 while (i < len(coiledCoils)): average+=numpy.array(coiledCoils[i][key]) i+=1 average/=len(coiledCoils) averageCoiledCoilParameters[key]=average #calculate Crick angle and assign positions crickAnglesForAllHelices=[] i=0 while (i < len(chains)): #print i crickAngles=[] crickAngles.append(0) #crickAngles.append(0) for j in range (1,len(helicesInSelection[i]["avgHelixAxisPoints"])-1): angle=calculateCrickAngle(helicesInSelection[i]['caPositions'][j], helicesInSelection[i]["avgHelixAxisPoints"][j], averageCoiledCoilParameters['coiledCoilAxisPoints'][j]) crickAngles.append(angle) crickAnglesForAllHelices.append(crickAngles) i+=1 avgCrickAngles=[] for i in range (0, len(crickAngles)): avg=0 x=0 y=0 for j in range(0, len(chains)): x+=math.cos(crickAnglesForAllHelices[j][i]*numpy.pi/180) y+=math.sin(crickAnglesForAllHelices[j][i]*numpy.pi/180) avg=math.atan2(y,x)*180/numpy.pi avgCrickAngles.append(avg) avgCrickAngles.append(0)#print avgCrickAngles pos=[] pos.append("x") #pos.append("x") i = 1 while (i < len(helicesInSelection[0]["avgHelixAxisPoints"])): #print avgCrickAngles[i] addUp=0 if (avgCrickAngles[i-1] < 0 and avgCrickAngles[i] > 0 and math.fabs(avgCrickAngles[i-1]) > math.fabs(avgCrickAngles[i]) and math.fabs(avgCrickAngles[i]) < 50): #print avgCrickAngles[i] pos.append("a") cmd.color("red", selection+" & resi "+str(stored.residueNumbersInSelection[i])) if i+1<len(helicesInSelection[0]["avgHelixAxisPoints"])-1: pos.append("b") addUp+=1 if i+2<len(helicesInSelection[0]["avgHelixAxisPoints"])-1: pos.append("c") addUp+=1 elif (avgCrickAngles[i] < 0 and avgCrickAngles[i+1] > 0 and math.fabs(avgCrickAngles[i]) < math.fabs(avgCrickAngles[i+1]) and math.fabs(avgCrickAngles[i]) < 50): pos.append("d") cmd.color("blue", selection+" & resi "+str(stored.residueNumbersInSelection[i])) if i+1<len(helicesInSelection[0]["avgHelixAxisPoints"])-1: pos.append("e") addUp+=1 if i+2<len(helicesInSelection[0]["avgHelixAxisPoints"])-1: pos.append("f") addUp+=1 if i+3<len(helicesInSelection[0]["avgHelixAxisPoints"])-1: pos.append("g") addUp+=1 else: pos.append("?") #print addUp i+=addUp i+=1 #make a nice table of results table = [["Res.", "cc-rad", "cc-rise", "cc-pitch", "cc-phaseYield", "pos","Crick-angle", "a-radius", "a-rise", "a-res/turn", "a-phaseYield"]] for i in range (1,len(helicesInSelection[0]["avgHelixAxisPoints"])-1): #print i list=[] list.append(stored.residuesInSelection[i]+ " " +stored.residueNumbersInSelection[i]) list.append(averageCoiledCoilParameters['coiledCoilRadiusPerResidue'][i]) list.append(averageCoiledCoilParameters['coiledCoilRisesPerResidue'][i]) list.append(averageCoiledCoilParameters['coiledCoilPitch'][i]) list.append(averageCoiledCoilParameters['coiledCoilPhaseYieldsPerResidue'][i]) list.append(pos[i]) list.append(avgCrickAngles[i]) list.append(averageAlphaHelicalParameters['alphaHelicalRadiusPerResidue'][i]) list.append(averageAlphaHelicalParameters['alphaHelicalRisesPerResidue'][i]) list.append(averageAlphaHelicalParameters['alphaHelicalResiduesPerTurn'][i]) list.append(averageAlphaHelicalParameters['alphaHelicalPhaseYieldsPerResidue'][i]) table.append(list) averages = [] stdevs = [] avgCoiledCoilRadius = numpy.mean(averageCoiledCoilParameters['coiledCoilRadiusPerResidue']) stdevCoiledCoilRadius = numpy.std(averageCoiledCoilParameters['coiledCoilRadiusPerResidue']) avgCoiledCoilRise = numpy.mean(averageCoiledCoilParameters['coiledCoilRisesPerResidue']) stdevCoiledCoilRise = numpy.std(averageCoiledCoilParameters['coiledCoilRisesPerResidue']) avgCoiledCoilPitch = numpy.mean(averageCoiledCoilParameters['coiledCoilPitch']) stdevCoiledCoilPitch = numpy.std(averageCoiledCoilParameters['coiledCoilPitch']) avgCoiledCoilPhaseYield = numpy.mean(averageCoiledCoilParameters['coiledCoilPhaseYieldsPerResidue']) stdevCoiledCoilPhaseYield = numpy.std(averageCoiledCoilParameters['coiledCoilPhaseYieldsPerResidue']) avgAlphaHelicalRadius = numpy.mean(averageAlphaHelicalParameters['alphaHelicalRadiusPerResidue']) stdevAlphaHelicalRadius = numpy.std(averageAlphaHelicalParameters['alphaHelicalRadiusPerResidue']) avgAlphaHelicalRise = numpy.mean(averageAlphaHelicalParameters['alphaHelicalRisesPerResidue']) stdevAlphaHelicalRise = numpy.std(averageAlphaHelicalParameters['alphaHelicalRisesPerResidue']) avgResPerTurn = numpy.mean(averageAlphaHelicalParameters['alphaHelicalResiduesPerTurn']) stdevResPerTurn = numpy.std(averageAlphaHelicalParameters['alphaHelicalResiduesPerTurn']) avgAlphaHelicalPhaseYield = numpy.mean(averageAlphaHelicalParameters['alphaHelicalPhaseYieldsPerResidue']) stdevAlphaHelicalPhaseYield = numpy.std(averageAlphaHelicalParameters['alphaHelicalPhaseYieldsPerResidue']) averages = ["Avg", avgCoiledCoilRadius, avgCoiledCoilRise, avgCoiledCoilPitch, avgCoiledCoilPhaseYield, "-","-", avgAlphaHelicalRadius, avgAlphaHelicalRise, avgResPerTurn, avgAlphaHelicalPhaseYield] stdevs = ["Std", stdevCoiledCoilRadius, stdevCoiledCoilRise, stdevCoiledCoilPitch, stdevCoiledCoilPhaseYield, "-","-", stdevAlphaHelicalRadius, stdevAlphaHelicalRise, stdevResPerTurn, stdevAlphaHelicalPhaseYield] empty = ["","","","","","","","","","",""] table.append(empty) table.append(averages) table.append(stdevs) #print table pprint_table(out, table) #show axes in pymol for i in range (0, len(helicesInSelection)): #print len(helicesInSelection),i for j in range (0,len(helicesInSelection[i]["avgHelixAxisPoints"])): createPseudoatom(coiledCoilParameters["coiledCoilAxisPoints"][j],"coiledCoilAxisPoint_"+str(i)+"_"+str(j)) createPseudoatom(helicesInSelection[i]["avgHelixAxisPoints"][j],"AxisPoint_"+str(i)+"_"+str(j)) if j > 0: cmd.distance("AxisLine_"+str(i)+"_"+str(j),"AxisPoint_"+str(i)+"_"+str(j-1),"AxisPoint_"+str(i)+"_"+str(j)) cmd.distance("CoiledCoilAxisLine_"+str(i)+"_"+str(j),"coiledCoilAxisPoint_"+str(i)+"_"+str(j-1),"coiledCoilAxisPoint_"+str(i)+"_"+str(j)) cmd.group("AlphaAxis_"+str(i), "AxisLine_"+str(i)+"*") cmd.group("AlphaAxisPoints_"+str(i), "AxisPoint_"+str(i)+"*") cmd.group("coiledCoil", "coiledCoil*") cmd.set("dash_color","yellow", "Alpha*") cmd.set("dash_color","red", "Coiled*") #print i cmd.hide("labels") cmd.hide("nonbonded")
def set_atom_level(level, selection='*', state=None, rec_map=None, lig_map=None): if rec_map is None: rec_channels = atom_types.get_default_rec_channels() else: rec_channels = atom_types.get_channels_from_file( rec_map, name_prefix='Receptor') if lig_map is None: lig_channels = atom_types.get_default_lig_channels() else: lig_channels = atom_types.get_channels_from_file(lig_map, name_prefix='Ligand') channels = rec_channels + lig_channels channels_by_name = dict((c.name, c) for c in channels) for c in channels: cmd.set_color(c.name + '$', atom_types.get_channel_color(c)) dx_regex = re.compile(r'(.*)_(\d+)_({})\.dx'.format( '|'.join(channels_by_name))) surface_groups = OrderedDict() for dx_object in sorted(cmd.get_names('objects')): if not fnmatch.fnmatch(dx_object, selection): continue m = dx_regex.match(dx_object) if not m: continue grid_prefix = m.group(1) sample_idx = int(m.group(2)) channel = channels_by_name[m.group(3)] if state is None: surface_state = sample_idx + 1 else: surface_state = state surface_object = '{}_{}_surface'.format(grid_prefix, channel.name) cmd.isosurface(surface_object, dx_object, level=level, state=surface_state) cmd.color(channel.name + '$', surface_object) if grid_prefix not in surface_groups: surface_groups[grid_prefix] = [] if surface_object not in surface_groups[grid_prefix]: surface_groups[grid_prefix].append(surface_object) for grid_prefix, surface_objects in surface_groups.items(): surface_group = '{}_surfaces'.format(grid_prefix) cmd.group(surface_group, ' '.join(surface_objects))
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"9.60299968719": [], "9.60299968719_arrows": []}
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 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
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"7.20800018311": [], "7.20800018311_arrows": []}
cmd.color("yellow", "surface_apolar_hotspot") cmd.set("transparency", 0.2, "surface_apolar_hotspot") cmd.load("hotspot/donor.grd", "donor_hotspot") cmd.isosurface(name="surface_donor_hotspot", map="donor_hotspot", level="5") cmd.color("blue", "surface_donor_hotspot") cmd.set("transparency", 0.2, "surface_donor_hotspot") cmd.load("hotspot/acceptor.grd", "acceptor_hotspot") cmd.isosurface(name="surface_acceptor_hotspot", map="acceptor_hotspot", level="5") cmd.color("red", "surface_acceptor_hotspot") cmd.set("transparency", 0.2, "surface_acceptor_hotspot") cmd.group("hotspot", members="apolar_hotspot") cmd.group("hotspot", members="surface_apolar_hotspot") cmd.group("hotspot", members="donor_hotspot") cmd.group("hotspot", members="surface_donor_hotspot") cmd.group("hotspot", members="acceptor_hotspot") cmd.group("hotspot", members="surface_acceptor_hotspot") cmd.group("hotspot", members="buriedness_hotspot") cmd.group("hotspot", members="surface_buriedness_hotspot") cmd.pseudoatom(object="PS_apolar_hotspot_0", pos=(21.0, 15.0, 107.0), color=(1, 1, 1), label=13.9) cmd.pseudoatom(object="PS_apolar_hotspot_1", pos=(18.5, 15.0, 109.0), color=(1, 1, 1),
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"17.5049991608": [], "17.5049991608_arrows": []}
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))
def supercell(a=1, b=1, c=1, object=None, color='green', name='supercell', withmates=1): ''' DESCRIPTION Draw a supercell, as requested by Nicolas Bock on the pymol-users mailing list (Subject: [PyMOL] feature request: supercell construction Date: 04/12/2010 10:12:17 PM (Mon, 12 Apr 2010 14:12:17 -0600)) USAGE supercell a, b, c [, object [, color [, name [, withmates]]]] ARGUMENTS a, b, c = integer: repeat cell in x,y,z direction a,b,c times {default: 1,1,1} object = string: name of object to take cell definition from color = string: color of cell {default: blue} name = string: name of the cgo object to create {default: supercell} withmates = bool: also create symmetry mates in displayed cells {default: 1} SEE ALSO show cell ''' import numpy from pymol import cgo if object is None: object = cmd.get_object_list()[0] withmates = int(withmates) sym = cmd.get_symmetry(object) cell_edges = sym[0:3] cell_angles = sym[3:6] basis = cellbasis(cell_angles, cell_edges) assert isinstance(basis, numpy.ndarray) ts = list() for i in range(int(a)): for j in range(int(b)): for k in range(int(c)): ts.append([i,j,k]) obj = [ cgo.BEGIN, cgo.LINES, cgo.COLOR, ] obj.extend(cmd.get_color_tuple(color)) for t in ts: shift = basis[0:3,0:3] * t shift = shift[:,0] + shift[:,1] + shift[:,2] for i in range(3): vi = basis[0:3,i] vj = [ numpy.array([0.,0.,0.]), basis[0:3,(i+1)%3], basis[0:3,(i+2)%3], basis[0:3,(i+1)%3] + basis[0:3,(i+2)%3] ] for j in range(4): obj.append(cgo.VERTEX) obj.extend((shift + vj[j]).tolist()) obj.append(cgo.VERTEX) obj.extend((shift + vj[j] + vi).tolist()) if withmates: groupname = 'm%d%d%d' % tuple(t) symexpcell(groupname + '_', object, *t) cmd.group(groupname, groupname + '_*') obj.append(cgo.END) cmd.delete(name) cmd.load_cgo(obj, name)
cmd.orient(prefix) colors = np.array([np.random.choice(np.arange(256, dtype=float), size=3) for dummy in range(binding_site_id)]) colors /= 255.0 residue_set = np.array(residue_set, dtype=str) residue_rank_set = np.array(residue_rank_set, dtype=int) binding_site_identifiers = np.array(binding_site_identifiers, dtype=int) residue_identifiers = list(residue_identifiers) for bs_id in np.arange(binding_site_id): cmd.set_color("tmp_{}".format(bs_id), list(colors[bs_id])) for entry_id in np.where(binding_site_identifiers == bs_id)[0]: selected_residue = residue_set[entry_id] selected_residue_rank = residue_rank_set[entry_id] identifier_from_pdb = residue_identifiers[selected_residue_rank] if re.findall("[a-zA-Z]+$", selected_residue)[0] != identifier_from_pdb[1]: raise IndexError("The {}th residue in the provided pdb file ({}{}) is different from that in the simulations ({})!".format(entry_id+1, identifier_from_pdb[0], identifier_from_pdb[1], selected_residue)) if identifier_from_pdb[2] != " ": cmd.select("BSid{}_{}".format(bs_id, selected_residue), "chain {} and resid {} and (not name C+O+N)".format(identifier_from_pdb[2], identifier_from_pdb[0])) else: cmd.select("BSid{}_{}".format(bs_id, selected_residue), "resid {} and (not name C+O+N)".format(identifier_from_pdb[0])) cmd.show("spheres", "BSid{}_{}".format(bs_id, selected_residue)) cmd.set("sphere_scale", SCALES[entry_id], selection="BSid{}_{}".format(bs_id, selected_residue)) cmd.color("tmp_{}".format(bs_id), "BSid{}_{}".format(bs_id, selected_residue)) cmd.group("BSid{}".format(bs_id), "BSid{}_*".format(bs_id))
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"11.0475001335": [], "11.0475001335_arrows": []}
def select_sites(selection='all', filename=None, prefix=None, nice=1, quiet=0): ''' DESCRIPTION Make named selections from SITE records. ARGUMENTS name = string: molecular object {default: all} filename = string: PDB file name with SITE records {default: look in current directory and fetch_path for <name>.pdb} prefix = string: prefix for named selections {default: site_} nice = 0 or 1: make colored sticks representation for sites {default :1} ''' nice, quiet = int(nice), int(quiet) names = cmd.get_names('public_objects', 1, '(' + selection + ')') selenames = set() cysselenames = set() hetselenames = set() for name in names: pfx = prefix or name + '_' fname = filename grpselenames = set() if fname is None: for fname in ['%s.pdb' % (name), '%s/%s.pdb' % (cmd.get('fetch_path'), name)]: if os.path.exists(fname): break else: print ' Error: please provide filename' raise CmdException if not quiet: print 'loading from %s' % (fname) for line in open(fname): if line.startswith('SITE '): siteID = line[11:14].strip() selename = pfx + siteID selenames.add(selename) grpselenames.add(selename) for i in range(4): res = line[18+11*i:29+11*i] if res.strip(): chain = res[4] resi = res[5:].strip() selestr = '%s and chain %s and resi %s' % (name, chain, resi) cmd.select(selename, selestr, 0, 1, 1) elif line.startswith('LINK '): siteID = line[12:16].strip() distname = pfx + 'LINK_' + siteID s1 = '/%s//%s/%s/%s' % (name, line[21], line[22:27].strip(), line[12:16].strip()) s2 = '/%s//%s/%s/%s' % (name, line[51], line[52:57].strip(), line[42:46].strip()) cmd.distance(distname, s1, s2) elif line.startswith('SSBOND'): selename = pfx + 'SSBOND' selenames.add(selename) grpselenames.add(selename) cysselenames.add(selename) selestr = '%s & (chain %s & resi %s | chain %s & resi %s) & name CA+CB+SG' selestr = selestr % (name, line[15], line[17:22], line[29], line[31:36]) cmd.select(selename, selestr, 0, 1, 1) elif line.startswith('HET '): siteID = line[7:10].strip() selename = pfx + 'HET_' + siteID selenames.add(selename) grpselenames.add(selename) hetselenames.add(selename) selestr = '%s & (chain %s & resi %s)' % (name, line[12], line[13:17]) cmd.select(selename, selestr, 0, 1, 1) # Make selection for solvent selename = pfx + 'solv' selestr = '%s & solvent' % (name) grpselenames.add(selename) cmd.select(selename, selestr, 0, 1, 1) cmd.group(name + '_sites', ' '.join(grpselenames)) if nice: allsites = ' '.join(selenames) cmd.show_as('cartoon', selection) cmd.show('lines', '(%s) and not polymer' % (selection)) cmd.show('nonbonded', '(%s) and not polymer' % (selection)) cmd.show('sticks', '(%s) and (%s)' % (selection, allsites)) cmd.show('nb_spheres', '(%s) and (%s)' % (selection, allsites)) cmd.show('dashes', '*LINK*') cmd.show('labels', '*LINK*') cmd.color('gray', selection) for i, selename in enumerate(selenames): cmd.color(i+2, '(%s) and (%s)' % (selection, selename)) #for i, selename in enumerate(cysselenames): # cmd.color('sulfur', '(%s) and (%s)' % (selection, selename)) for i, selename in enumerate(hetselenames): cmd.show('spheres','%s and inorganic' % (selename)) cmd.util.cnc('%s' % (allsites))
cmd.pseudoatom(object="acceptor_projected_point_0_proj_score", pos=(27.0, 6.75, 12.5), color=(1, 1, 1), label=12.4) acceptor_projected_projection_0 = [COLOR, 1.0, 0.6, 0.6] + [ALPHA, 0.8] + [SPHERE, float(27.0), float(6.75), float(12.5), float(1)] cmd.load_cgo(acceptor_projected_projection_0, "acceptor_projected_projection_0_obj", 1) cmd.pseudoatom(object="acceptor_projected_line_0pa1", pos=(25.0, 6.5, 13.0), color=(1, 1, 1)) cmd.pseudoatom(object="acceptor_projected_line_0pa2", pos=(27.0, 6.75, 12.5), color=(1, 1, 1)) cmd.distance(name="acceptor_projected_line_0", selection1="acceptor_projected_line_0pa1", selection2="acceptor_projected_line_0pa2", width=0.5, gap=0.2, label=0, state=1) cmd.set("dash_color", (1.0, 0.6, 0.6), selection="acceptor_projected_line_0") cmd.set("dash_width", 4.0) cmd.delete("acceptor_projected_line_0pa1") cmd.delete("acceptor_projected_line_0pa2") cmd.group("acceptor_projected_0", members="acceptor_projected_point_0_obj") cmd.group("acceptor_projected_0", members="acceptor_projected_point_0_score") cmd.group("acceptor_projected_0", members="acceptor_projected_projection_0") cmd.group("acceptor_projected_0", members="acceptor_projected_line_0") cmd.group("acceptor_projected_0", members="acceptor_projected_point_0_proj_score") donor_projected_point_1 = [COLOR, 0.0, 0.0, 1.0] + [ALPHA, 0.8] + [SPHERE, float(24.5), float(6.0), float(14.5), float(1)] cmd.load_cgo(donor_projected_point_1, "donor_projected_point_1_obj", 1) cmd.pseudoatom(object="donor_projected_point_1_score", pos=(24.5, 6.0, 14.5), color=(1, 1, 1), label=20.5) cmd.group("donor_projected_1", members="donor_projected_point_1_obj") cmd.group("donor_projected_1", members="donor_projected_point_1_score") ring_point_2 = [COLOR, 0.33, 1.0, 0.0] + [ALPHA, 0.8] + [SPHERE, float(22.0), float(5.5), float(11.5), float(2.0)] cmd.load_cgo(ring_point_2, "ring_point_2_obj", 1) cmd.pseudoatom(object="ring_point_2_score", pos=(22.0, 5.5, 11.5), color=(1, 1, 1), label=18.1)
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"16.5699996948": [], "16.5699996948_arrows": []}
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"15.8459997177": [], "15.8459997177_arrows": []}
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 match_peptides(target_sel="all", peptides=[], verb=True): if type(peptides) != list: print("\nERROR: The peptides should be supplied as a list\n") return # Store info return_list_resn_resi = [] return_list_resn_resi_sel = [] group = "Match_%s"%(target_sel) for peptide in peptides: sequence, modification = peptide sequence = sequence.strip() modification = modification.strip() # Check input if modification[0].isdigit() or not modification[1:].isdigit(): print("\nERROR: The modificaions should be in format of ex: K10\n") return #sel_str = "findseq" sel_str = sequence findseq.findseq(needle=sequence, haystack=target_sel, selName=sel_str) # Limit the selection to atom name CA atom_name = "CA" sel_str_atom = "%s_%s"%(sel_str, atom_name) # Make a sub selection with atom name, and delete old selection cmd.select(sel_str_atom, "%s and name %s"%(sel_str, atom_name)) cmd.delete(sel_str) # Iterate stored.infolist = [] # resv (int): the residue identifier (residue number), ss (str): secondary structure, name (str): the atom name expression = "stored.infolist.append([model, chain, resv, resn, ss, name])" # Iterate over selection, storing info cmd.iterate(sel_str_atom, expression) cmd.delete(sel_str_atom) # Check for results. Is there any found? if len(stored.infolist) == 0: print("\n#####################################################################") print("ERROR: The following sequence cannot be found: %s %s"%(sequence, modification)) print("\n#####################################################################\n") continue # Find resn and index for search. This is for the peptide resn = modification[0].upper() index = int(modification[1:]) - 1 # This is for the mathc selection peptide_match_modification = stored.infolist[index] peptide_match_modification_model, peptide_match_modification_chain, peptide_match_modification_resv, peptide_match_modification_resn, \ peptide_match_modification_ss, peptide_match_modification_name = peptide_match_modification # Convert to single aa peptide_match_modification_resn = aa_3_1[peptide_match_modification_resn] # Convert ss, secondary structure, if ss=S (Sheet), or ss='' (Not Helix or Sheet) if peptide_match_modification_ss == '': peptide_match_modification_ss = 'L' # Check if the residue type match if peptide_match_modification_resn != resn: print("\n#####################################################################") print("ERROR: The match is not equal: %s=%s != %s"%(modification[0], resn, peptide_match_modification_resn)) print("\n#####################################################################\n") continue # Do selection and group #peptide_match_modification_sel_str = "/%s/%s//%s"%(peptide_match_modification_model, peptide_match_modification_chain, peptide_match_modification_resv) peptide_match_modification_sel_str = "%s and chain %s and resi %s"%(peptide_match_modification_model, peptide_match_modification_chain, peptide_match_modification_resv) peptide_match_modification_resn_resi = "%s%s"%(peptide_match_modification_resn, peptide_match_modification_resv) peptide_match_modification_sel_str_text = "%s_%s_%s_%s"%(group, peptide_match_modification_resn_resi, modification, sequence) cmd.select(peptide_match_modification_sel_str_text, peptide_match_modification_sel_str) # Store if peptide_match_modification_resn_resi not in return_list_resn_resi: return_list_resn_resi.append(peptide_match_modification_resn_resi) return_list_resn_resi_sel.append(peptide_match_modification_sel_str) # Print if verb: print("The peptide=%s, with modification=%s, corresponds to resi=%s"%(sequence, modification, peptide_match_modification_resn_resi)) # Group selections cmd.group(group, "%s_*"%group) cmd.select("%s_sel"%group, "%s_*"%group) cmd.show("lines", group) # If verbose if verb: print("\nThere are %i uniq matches, in target_sel=%s\n"%(len(return_list_resn_resi), target_sel)) return return_list_resn_resi, return_list_resn_resi_sel
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"13.0880002975": [], "13.0880002975_arrows": []}
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"14.0630002022": [], "14.0630002022_arrows": []}
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"11.7354998589": [], "11.7354998589_arrows": []}
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"26.8719997406": [], "26.8719997406_arrows": []}
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"12.0150003433": [], "12.0150003433_arrows": []}
def scanDamage(nucleosome, uvddb, cutoff=2, clashKeep=1, writeModels=False): """ USAGE scanDamage nucleosome object (DNA in chains I and J), UVDDB probe object (containing appropriately positioned 2 bp ssDNA in chain Z as residues 1-2 for superpositioning), distance in Ångstrom closer than which atoms are considered clashing, keep models with fewer than the specified number of clashes, write all models (for scoring externally for instance) """ chains = ['I', 'J'] results = [] if writeModels: dirName = None dirName = ("%s_%s_models" % (nucleosome, uvddb)) if not os.path.exists(dirName): os.mkdir("%s" % (dirName)) for chain in chains: chainLength = (len( cmd.get_model("polymer and %s and chain %s" % (nucleosome, chain)).get_residues())) for i in range(0, chainLength + 1): # for i in range(130, 146): j = (i + 1) if chain == 'I': comnplementaryChain = 'J' elif chain == 'J': matchedChain = 'I' # Handle lack of 5' phosphate on first nucleotide if i == 0: cmd.select( "moving", "%s and chain Z and resi 2 and backbone and not (n. P or n. OP1 or n. OP2)" % (uvddb)) cmd.select( "target", "%s and chain %s and resi %d and backbone and not (n. P or n. OP1 or n. OP2)" % (nucleosome, chain, j)) elif i == 1: cmd.select( "moving", "%s and chain Z and resi 1-2 and backbone and not (n. P or n. OP1 or n. OP2)" % (uvddb)) cmd.select( "target", "%s and chain %s and resi %d-%d and backbone and not (n. P or n. OP1 or n. OP2)" % (nucleosome, chain, i, j)) # Handle final base elif i == chainLength: cmd.select("moving", "%s and chain Z and resi 1 and backbone" % (uvddb)) cmd.select( "target", "%s and chain %s and resi %d and backbone" % (nucleosome, chain, i)) else: cmd.select( "moving", "%s and chain Z and resi 1-2 and backbone" % (uvddb)) cmd.select( "target", "%s and chain %s and resi %d-%d and backbone" % (nucleosome, chain, i, j)) #numAtomMoving=(cmd.count_atoms("moving")) #print ("\nNumber of moving atoms: %d" % (numAtomMoving) ) #numAtomTarget=(cmd.count_atoms("target")) #print ("Number of target atoms: %d" % (numAtomTarget) ) alignResult = [] alignResult = cmd.pair_fit("moving", "target") # alignResult = cmd.super("moving", "target") # print ("RMSD after refinement %.4f with %d atoms in alignhment after %d refinement cycles" % (alignResult[0],alignResult[1],alignResult[2]) ) # print(" ".join('%s' % x for x in alignResult)) clashes = ("clashes") # Calculate clashes excluding DNA portion (chain Z resi 1-2) of UV-DDB probe cmd.select( "%s" % (clashes), "(%s and not chain Z) within %d of %s" % (uvddb, float(cutoff), nucleosome)) scoreAtoms = (cmd.count_atoms("%s" % (clashes))) cmd.select("%s" % (clashes), "clashes byres clashes") scoreRes = (cmd.count_atoms("%s" % (clashes) + " and name CA")) # Write out models (nucleosome + current superimposed UV-DDB probe) for Rosetta scoring if writeModels: modelName = None modelName = ("%s_uvddb_%s_%d-%d" % (nucleosome, chain, i, j)) editing.copy_to("%s" % (modelName), "(%s or %s)" % (nucleosome, uvddb)) cmd.save("%s/%s.pdb" % (dirName, modelName), "(%s)" % (modelName)) cmd.delete("%s" % (modelName)) # Retain models with no. residue clashes less than or equal to 'clashKeep' if scoreRes < (int(clashKeep) + 1): editing.copy_to("uvddb_%s_%d-%d" % (chain, i, j), "%s" % (uvddb)) cmd.group("ClashKeep %s)" % (clashKeep), "nonclashing + uvddb_%s_%d-%d" % (chain, i, j)) cmd.order("uvddb_*", "yes") print( "DNA chain %s bases %d - %d : UV-DDB clashes atoms %d residues %d " % (chain, i, j, scoreAtoms, scoreRes)) clashes = ("%s,%d,%d,%d,%d" % (chain, i, j, scoreAtoms, scoreRes)) results.append((clashes)) with open('%s_scanDamage.csv' % (nucleosome), 'w') as output: output.write("DNAchain,start,end,atomClashes,residueClashes\n") for i in results: output.write("%s\n" % i) print("\nOutput saved to %s_scanDamage.csv\n" % (nucleosome))
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cluster_dict = {"18.218000412": [], "18.218000412_arrows": []}
def read_moestr(contents, object, state=0, finish=1, discrete=1, quiet=1, zoom=-1, _self=cmd): moestr = contents name = object import sys if sys.version_info[0] > 2 and isinstance(moestr, bytes): moestr = moestr.decode() cmd = _self mr = MOEReader() mr.appendFromStr(moestr) split_chains = cmd.get_setting_int("moe_separate_chains") cmd.group(name) if hasattr(mr, 'system'): have_valences = 0 chain_count = 0 cmd.set_color("_aseg0", [1.0, 1.0, 1.0]) aseg_color = cmd.get_color_index("_aseg0") aseg_flag = 0 aseg_rep = {} model = Indexed() molecule = mr.system['molecule'] if 'atoms' in molecule: n_atom = molecule['atoms'] model.atom = [Atom() for x in range(n_atom)] residues = {} chains = {} for columns, data in molecule['attr']: for row in data: cur_atom = None for key, value in zip(columns, row): key = key[0] if key == 'ID': ID = value else: aProp = _atom_prop_map.get(key, None) if aProp != None: setattr(model.atom[ID - 1], aProp, value) else: xyz = _atom_coord_map.get(key, None) if xyz != None: coord = list(model.atom[ID - 1].coord) coord[xyz] = value model.atom[ID - 1].coord = coord elif key in _atom_vis_map: atom = model.atom[ID - 1] if hasattr(atom, 'visible'): visible = atom.visible else: visible = _default_visible if key == 'aBondLook': if value == 'cylinder': atom.visible = 0x00000001 | visible elif value == 'line': atom.visible = 0x00000080 | visible elif value == 'none': atom.visible = -129 & Visible # 0xFFFFFF7F elif key == 'aNucleusLook': if value == 'sphere': atom.visible = 0x00000002 | visible elif value == 'small-sphere': # need to set sphere_scale=0.2 for these atoms atom.visible = 0x00000002 | visible atom.sphere_scale = 0.2 elif value == 'point': # nonbonded atom.visible = 0x00000800 | visible elif value == 'none': atom.visible = -2067 & visible # 0xFFFFF7ED elif key == 'aHidden': atom.visible = 0 atom.hidden = 1 if hasattr( atom, 'hidden' ): # be sure that hidden atoms aren't shown atom.visible = 0 elif key in _atom_color_map: if key == 'aRGB': model.atom[ID - 1].trgb = value elif key == 'aColorBy': model.atom[ID - 1].aColorBy = value elif key in _atom_label_map: atom = model.atom[ID - 1] if hasattr(atom, 'label_dict'): atom.label_dict[key] = None else: atom.label_dict = {key: None} elif key in _residue_prop_map: resi_dict = residues.get(ID, {}) resi_dict[key] = value residues[ID] = resi_dict elif key in _chain_prop_map: chain_dict = chains.get(ID, {}) if ID not in chains: chain_count = chain_count + 1 chain_dict['count'] = chain_count chain_dict[key] = value chains[ID] = chain_dict chn_keys = list(chains.keys()) chn_keys.sort() res_keys = list(residues.keys()) res_keys.sort() # map chain properties onto residues chn_resi = 0 ch_colors = copy.deepcopy(_ch_colors) unique_chain_names = {} for chn_idx in chn_keys: chain_dict = chains[chn_idx] cName = make_valid_name(chain_dict.get('cName', '')) segi = cName[0:4] chain = cName[-1:] if not len(cName): if 'count' in chain_dict: cName = "chain_" + str(chain_dict['count']) else: cName = str(chn_idx) if cName not in unique_chain_names: unique_chain_names[cName] = cName else: cnt = 2 while (cName + "_" + str(cnt)) in unique_chain_names: cnt = cnt + 1 newCName = cName + "_" + str(cnt) unique_chain_names[newCName] = cName cName = newCName chain_dict['chain_color'] = ch_colors[0] ch_colors = ch_colors[1:] + [ch_colors[0]] cResCount = chain_dict.get('cResidueCount', 0) for res_idx in range(chn_resi, chn_resi + cResCount): resi_dict = residues[res_keys[res_idx]] resi_dict['chain'] = chain resi_dict['segi'] = segi resi_dict['cName'] = cName resi_dict['chain_dict'] = chain_dict chn_resi = chn_resi + cResCount # map residue properties onto atoms res_atom = 0 for res_idx in res_keys: resi_dict = residues[res_idx] rRibbonMode = resi_dict.get('rRibbonMode', 'none') rAtomCount = resi_dict['rAtomCount'] rType = resi_dict.get('rType', '') if rAtomCount > 0: for at_idx in range(res_atom, res_atom + rAtomCount): atom = model.atom[at_idx] setattr( atom, 'resi', string.strip( str(resi_dict.get('rUID', '')) + resi_dict.get('rINS', ''))) setattr(atom, 'resn', resi_dict.get('rName', '')) setattr(atom, 'chain', resi_dict.get('chain', '')) setattr(atom, 'segi', resi_dict.get('segi', '')) setattr(atom, 'custom', resi_dict.get('cName', '')) # add labels if hasattr(atom, 'label_dict'): label = '' label_dict = atom.label_dict if 'aLabelElement' in label_dict: label = atom.symbol if 'aLabelRes' in label_dict: if len(label): label = label + "," label = label + atom.resn + "_" + atom.resi if 'aLabelName' in label_dict: if len(label): label = label + "." label = label + atom.name atom.label = label if rType not in ['none', 'heme']: atom.hetatm = 0 # all normal atoms else: atom.flags = 0x02000000 # hetatom or ligand -- ignore when surfacing if rRibbonMode != 'none': if hasattr(atom, 'visible'): visible = atom.visible else: visible = _default_visible rRibbonColorBy = resi_dict['rRibbonColorBy'] repeat = 1 while repeat: repeat = 0 if rRibbonColorBy in ['rgb', 'r:rgb' ]: # handled automatically pass elif rRibbonColorBy == 'chain': chain_dict = resi_dict['chain_dict'] cColorBy = chain_dict['cColorBy'] if cColorBy == 'rgb': cColorBy = 'c:rgb' rRibbonColorBy = cColorBy repeat = 1 rRibbon_color = 0 rRibbon_trgb = 0xFFFFFF # default -- white # now color ribbon if rRibbonColorBy == 'r:rgb': rRibbon_trgb = resi_dict.get('rRGB', 0xFFFFFF) elif rRibbonColorBy == 'rgb': rRibbon_trgb = resi_dict.get( 'rRibbonRGB', 0xFFFFFF) elif rRibbonColorBy == 'c:rgb': chain_dict = resi_dict['chain_dict'] rRibbon_trgb = chain_dict.get('cRGB', 0xFFFFFF) elif rRibbonColorBy == 'r:aseg': rRibbon_trgb = None rRibbon_color = aseg_color aseg_flag = 1 elif rRibbonColorBy == 'tempfactor': pass # TO DO elif rRibbonColorBy == 'c:number': # per chain colors rRibbon_trgb = chain_dict['chain_color'] if rRibbonMode in ['line', 'trace']: atom.visible = 0x00000040 | visible # PyMOL ribbon if rRibbon_trgb != None: atom.ribbon_trgb = rRibbon_trgb else: atom.ribbon_color = rRibbon_color aseg_rep['ribbon'] = 1 else: atom.visible = 0x00000020 | visible # PyMOL cartoon if rRibbon_trgb != None: atom.cartoon_trgb = rRibbon_trgb else: atom.cartoon_color = rRibbon_color aseg_rep['cartoon'] = 1 if hasattr(atom, 'label'): if hasattr(atom, 'visible'): visible = atom.visible else: visible = _default_visible atom.visible = 0x00000028 | visible # labels if not hasattr(atom, 'aColorBy'): atom.aColorBy = 'element' if hasattr(atom, 'aColorBy'): aColorBy = atom.aColorBy repeat = 1 while repeat: repeat = 0 if aColorBy == 'ribbon': aColorBy = resi_dict.get('rRibbonColorBy') if aColorBy == 'rgb': aColorBy = 'rib:rgb' else: repeat = 1 # TO DO still need to handle "cartoon_color", "ribbon_color" elif aColorBy == 'element': if hasattr(atom, 'trgb'): del atom.trgb elif aColorBy in ['rgb', 'a:rgb' ]: # handled automatically pass elif aColorBy == 'residue': rColorBy = resi_dict.get('rColorBy') if rColorBy == 'rgb': rColorBy = 'r:rgb' aColorBy = rColorBy repeat = 1 elif aColorBy == 'chain': chain_dict = resi_dict['chain_dict'] cColorBy = chain_dict['cColorBy'] if cColorBy == 'rgb': cColorBy = 'c:rgb' aColorBy = cColorBy repeat = 1 # now color atom... if aColorBy == 'r:rgb': atom.trgb = resi_dict.get('rRGB', 0xFFFFFF) elif aColorBy == 'rib:rgb': atom.trgb = resi_dict.get('rRibbonRGB', 0xFFFFFF) elif aColorBy == 'c:rgb': chain_dict = resi_dict['chain_dict'] atom.trgb = chain_dict.get('cRGB', 0xFFFFFF) elif aColorBy == 'r:aseg': pass # TO DO elif aColorBy == 'tempfactor': pass # TO DO elif aColorBy == 'c:number': # per chain colors atom.trgb = chain_dict['chain_color'] res_atom = res_atom + rAtomCount bond_list = molecule.get('bond', []) for bond in bond_list: new_bond = Bond() new_bond.index = [bond[0] - 1, bond[1] - 1] if len(bond) > 2: new_bond.order = bond[2] if bond[2] == 2: # work around .MOE bug with triple bonds if model.atom[new_bond.index[0]].hybridization == 'sp': if model.atom[new_bond.index[1]].hybridization == 'sp': new_bond.order = 3 have_valences = 1 model.bond.append(new_bond) if 'ViewOrientationY' in mr.system: vy = mr.system['ViewOrientationY'] vz = mr.system['ViewOrientationZ'] pos = mr.system['ViewLookAt'] scale = mr.system['ViewScale'] vx = cpv.cross_product(vy, vz) m = [cpv.normalize(vx), cpv.normalize(vy), cpv.normalize(vz)] m = cpv.transpose(m) asp_rat = 0.8 # MOE default (versus 0.75 for PyMOL) cmd.set("field_of_view", 25.0) fov = float(cmd.get("field_of_view")) window_height = scale * asp_rat dist = (0.5 * window_height) / math.atan(3.1415 * (0.5 * fov) / 180.0) new_view = tuple(m[0] + m[1] + m[2] + [0.0, 0.0, -dist] + pos + [dist * 0.5, dist * 1.5, 0.0]) cmd.set_view(new_view) zoom = 0 cmd.set("auto_color", 0) cmd.set_color("carbon", [0.5, 0.5, 0.5]) # default MOE grey obj_name = name + ".system" if split_chains < 0: # by default, don't split chains if over 50 objects would be created if len(unique_chain_names) > 50: split_chains = 0 if not split_chains: cmd.load_model(model, obj_name, state=state, finish=finish, discrete=discrete, quiet=quiet, zoom=zoom) obj_name_list = [obj_name] else: cmd.load_model(model, obj_name, state=state, finish=finish, discrete=discrete, quiet=1, zoom=zoom) obj_name_list = [] system_name = obj_name for chain in unique_chain_names.keys(): obj_name = name + "." + chain obj_name_list.append(obj_name) cmd.select("_moe_ext_tmp", "custom %s" % chain, domain=system_name) cmd.extract(obj_name, "_moe_ext_tmp", quiet=quiet, zoom=0) # cmd.extract(obj_name,system_name+" and text_type %s"%chain,quiet=quiet) cmd.delete("_moe_ext_tmp") if not cmd.count_atoms(system_name): cmd.delete(system_name) else: obj_name_list.append(system_name) cmd.order(name + ".*", sort=1) for obj_name in obj_name_list: cmd.set("stick_radius", 0.1, obj_name) cmd.set("line_width", 2.0, obj_name) cmd.set("label_color", "white", obj_name) cmd.set("nonbonded_size", 0.05, obj_name) # temporary workaround... if have_valences: # if this MOE file has valences, then show em! cmd.set("valence", 1, obj_name) cmd.set("stick_valence_scale", 1.25, obj_name) if aseg_flag: cmd.dss(obj_name) if 'cartoon' in aseg_rep: cmd.set("cartoon_color", "red", obj_name + " and cartoon_color _aseg0 and ss h") cmd.set("cartoon_color", "yellow", obj_name + " and cartoon_color _aseg0 and ss s") cmd.set( "cartoon_color", "cyan", obj_name + " and cartoon_color _aseg0 and not ss h+s") if 'ribbon' in aseg_rep: cmd.set("ribbon_color", "red", obj_name + " and ribbon_color _aseg0 and ss h" ) # need selection op ribbon_color cmd.set("ribbon_color", "yellow", obj_name + " and ribbon_color _aseg0 and ss s") cmd.set( "ribbon_color", "cyan", obj_name + " and ribbon_color _aseg0 and not ss h+s") if 'ViewZFront' in mr.system: moe_front = mr.system['ViewZFront'] moe_width = mr.system['ViewZWidth'] extent = cmd.get_extent( name) # will this work with groups? TO DO: check! dx = (extent[0][0] - extent[1][0]) dy = (extent[0][1] - extent[1][1]) dz = (extent[0][2] - extent[1][2]) half_width = 0.5 * math.sqrt(dx * dx + dy * dy + dz * dz) cmd.clip("atoms", 0.0, name) cur_view = cmd.get_view() center = (cur_view[-3] + cur_view[-2]) * 0.5 # center of clipping slab front = center - half_width back = center + half_width width = half_width * 2 new_view = tuple( list(cur_view[0:15]) + [ front + width * moe_front, front + width * (moe_front + moe_width), 0.0 ]) cmd.set_view(new_view) if 'graphics' in mr.system: cgo_cnt = 1 lab_cnt = 1 unique_cgo_names = {} for graphics in mr.system['graphics']: cgo = [] for gvertex in graphics.get('gvertex', []): vrt = gvertex[0] seg_list = gvertex[1]['seg'] idx = gvertex[1]['idx'] len_idx = len(idx) if not cmd.is_list(seg_list): seg_list = [seg_list] * (len_idx / seg_list) last_seg = None ix_start = 0 for seg in seg_list: if seg != last_seg: if last_seg != None: cgo.append(END) if seg == 3: cgo.extend([BEGIN, TRIANGLES]) elif seg == 2: cgo.extend([BEGIN, LINES]) elif seg == 1: cgo.extend([BEGIN, POINTS]) ix_stop = seg + ix_start if seg == 3: for s in idx[ix_start:ix_stop]: v = vrt[s - 1] cgo.extend([ COLOR, (0xFF & (v[0] >> 16)) / 255.0, (0xFF & (v[0] >> 8)) / 255.0, (0xFF & (v[0])) / 255.0 ]) if len(v) > 4: cgo.extend([NORMAL, v[4], v[5], v[6]]) cgo.extend([VERTEX, v[1], v[2], v[3]]) elif seg == 2: for s in idx[ix_start:ix_stop]: v = vrt[s - 1] cgo.extend([ COLOR, (0xFF & (v[0] >> 16)) / 255.0, (0xFF & (v[0] >> 8)) / 255.0, (0xFF & (v[0])) / 255.0 ]) if len(v) > 4: cgo.extend([NORMAL, v[4], v[5], v[6]]) cgo.extend([VERTEX, v[1], v[2], v[3]]) elif seg == 1: for s in idx[ix_start:ix_stop]: v = vrt[s - 1] cgo.extend([ COLOR, (0xFF & (v[0] >> 16)) / 255.0, (0xFF & (v[0] >> 8)) / 255.0, (0xFF & (v[0])) / 255.0 ]) if len(v) > 4: cgo.extend([NORMAL, v[4], v[5], v[6]]) cgo.extend([VERTEX, v[1], v[2], v[3]]) ix_start = ix_stop last_seg = seg if last_seg != None: cgo.append(END) for gtext in graphics.get('gtext', []): lab_name = name + ".label_%02d" % lab_cnt exists = 0 for entry in gtext: exists = 1 cmd.pseudoatom(lab_name, pos=[ float(entry[1]), float(entry[2]), float(entry[3]) ], color="0x%06x" % entry[0], label=entry[4]) if exists: cmd.set('label_color', -1, lab_name) lab_cnt = lab_cnt + 1 # TO DO -- via CGO's? if len(cgo): cgo_name = name + "." + make_valid_name( graphics.get('GTitle', 'graphics')) if cgo_name not in unique_cgo_names: unique_cgo_names[cgo_name] = cgo_name else: cnt = 2 while cgo_name + "_" + str(cnt) in unique_cgo_names: cnt = cnt + 1 new_name = cgo_name + "_" + str(cnt) unique_cgo_names[new_name] = new_name cgo_name = new_name cmd.load_cgo(cgo, cgo_name, state=state, quiet=quiet, zoom=0) cgo_cnt = cgo_cnt + 1 cmd.set("two_sided_lighting", 1) # global setting... cmd.set("cgo_line_width", 2, cgo_name) if 'GTransparency' in graphics: g_trans = graphics['GTransparency'] if len(g_trans) >= 2: if g_trans[0] != 0: cmd.set('cgo_transparency', '%1.6f' % (g_trans[0] / 255.0), cgo_name) cmd.set('transparency_global_sort') if 'meter' in mr.system: meter_name = name + ".meter" exists = 0 for meter_block in mr.system['meter']: if meter_block[0][0:2] == ['type', 'atoms']: for meter in meter_block[1]: (type, atoms) = meter[0:2] arg = tuple([meter_name] + list( map(lambda x, o=name: o + " and id " + str(x - 1), atoms))) getattr(cmd, type)(*arg) exists = 1 if exists: cmd.color("green", meter_name) # print mr.system['meter'] elif hasattr(mr, 'feature'): model = Indexed() cols = mr.feature[0] rows = mr.feature[1] col = {} cnt = 0 for a in cols: col[a] = cnt cnt = cnt + 1 for row in rows: atom = Atom() atom.coord = [row[col['x']], row[col['y']], row[col['z']]] atom.vdw = row[col['r']] atom.custom = row[col['expr']] model.atom.append(atom) obj_name = name + ".feature" cmd.load_model(model, obj_name, state=state, finish=finish, discrete=discrete, quiet=quiet, zoom=zoom) rank = 1 for row in rows: cmd.color("0x%06x" % row[col['color']], obj_name + " & id %d" % (rank - 1)) rank = rank + 1 cmd.show("mesh", obj_name) cmd.set("min_mesh_spacing", 0.55, obj_name) cmd.label(obj_name, "' '+custom") cmd.set("label_color", "yellow", obj_name) else: print(dir(mr))
def biomolecule(name=None, filename=None, prefix=None, number=1, suffix=None, quiet=0): ''' DESCRIPTION Create biological unit (quaternary structure) as annotated by the REMARK 350 BIOMOLECULE record. USAGE biomolecule name [, filename [, prefix [, number ]]] ARGUMENTS name = string: name of object and basename of PDB file, if filename is not given {default: first loaded object} filename = string: file to read remarks from {default: <name>.pdb} prefix = string: prefix for new objects {default: <name>} EXAMPLE fetch 1rmv, async=0 biomolecule 1rmv ''' import os from .importing import local_mirror_pdb try: import numpy except ImportError: numpy = None number, quiet = int(number), int(quiet) if name is None: name = cmd.get_object_list()[0] if prefix is None: prefix = name if suffix is None: suffix = str(number) if filename is None: candidates = [ '%s.pdb' % (name), '%s/%s.pdb' % (cmd.get('fetch_path'), name), local_mirror_pdb(name), ] for filename in candidates: if os.path.exists(filename): break else: print('please provide filename') raise CmdException if not quiet: print('loading from %s' % (filename)) remarks = pdbremarks(filename) if 350 not in remarks: print('There is no REMARK 350 in', filename) raise CmdException current = 1 biomt = {current: {}} chains = tuple() for line in remarks[350]: if line.startswith('BIOMOLECULE:'): current = int(line[12:]) biomt[current] = {} elif line.startswith('APPLY THE FOLLOWING TO CHAINS:'): chains = tuple(chain.strip() for chain in line[30:].split(',')) elif line.startswith(' AND CHAINS:'): chains += tuple(chain.strip() for chain in line[30:].split(',')) elif line.startswith(' BIOMT'): row = int(line[7]) num = int(line[8:12]) vec = line[12:].split() vec = list(map(float, vec)) biomt[current].setdefault(chains, dict()).setdefault(num, []).extend(vec) if number not in biomt or len(biomt[number]) == 0: print(' Error: no BIOMOLECULE number %d' % (number)) raise CmdException if numpy is not None: mat_source = numpy.reshape(cmd.get_object_matrix(name), (4,4)) mat_source = numpy.matrix(mat_source) for chains, matrices in biomt[number].items(): for num in matrices: mat = matrices[num][0:12] mat.extend([0,0,0,1]) copy = '%s_%s_%d' % (prefix, suffix, num) if not quiet: print('creating %s' % (copy)) cmd.create(copy, 'model %s and chain %s' % (name, '+'.join(chains))) cmd.alter(copy, 'segi="%d"' % (num)) if numpy is not None: mat = mat_source * numpy.reshape(mat, (4,4)) * mat_source.I mat = list(mat.flat) cmd.transform_object(copy, mat) cmd.disable(name) cmd.group('%s_%s' % (prefix, suffix), '%s_%s_*' % (prefix, suffix))
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') return True
def elbow_angle(obj, light='L', heavy='H', limit_l=107, limit_h=113, draw=0): """ DESCRIPTION Calculates the integer elbow angle of an antibody Fab complex and optionally draws a graphical representation of the vectors used to determine the angle. ARGUMENTS obj = string: object light/heavy = strings: chain ID of light and heavy chains, respectively limit_l/limit_h = integers: residue numbers of the last residue in the light and heavy chain variable domains, respectively draw = boolean: Choose whether or not to draw the angle visualization REQUIRES: com.py, transformations.py, numpy (see above) """ # store current view orig_view = cmd.get_view() limit_l = int(limit_l) limit_h = int(limit_h) draw = int(draw) # for temp object names tmp_prefix = "tmp_elbow_" prefix = tmp_prefix + obj + '_' # names vl = prefix + 'VL' vh = prefix + 'VH' cl = prefix + 'CL' ch = prefix + 'CH' # selections vl_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, light, limit_l) vh_sel = 'polymer and %s and chain %s and resi 1-%i' % (obj, heavy, limit_h) cl_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, light, limit_l) ch_sel = 'polymer and %s and chain %s and not resi 1-%i' % (obj, heavy, limit_h) v_sel = '((' + vl_sel + ') or (' + vh_sel + '))' c_sel = '((' + cl_sel + ') or (' + ch_sel + '))' # create temp objects cmd.create(vl, vl_sel) cmd.create(vh, vh_sel) cmd.create(cl, cl_sel) cmd.create(ch, ch_sel) # superimpose vl onto vh, calculate axis and angle Rv = calc_super_matrix(vl, vh) angle_v, direction_v, point_v = transformations.rotation_from_matrix(Rv) # superimpose cl onto ch, calculate axis and angle Rc = calc_super_matrix(cl, ch) angle_c, direction_c, point_c = transformations.rotation_from_matrix(Rc) # delete temporary objects cmd.delete(vl) cmd.delete(vh) cmd.delete(cl) cmd.delete(ch) # if dot product is positive, angle is acute if (numpy.dot(direction_v, direction_c) > 0): direction_c = direction_c * -1 # ensure angle is > 90 (need to standardize this) # TODO: make both directions point away from the elbow axis. elbow = int(numpy.degrees(numpy.arccos(numpy.dot(direction_v, direction_c)))) # while (elbow < 90): # elbow = 180 - elbow # limit to physically reasonable range # compare the direction_v and direction_c axes to the vector defined by # the C-alpha atoms of limit_l and limit_h of the original fab hinge_l_sel = "%s//%s/%s/CA" % (obj, light, limit_l) hinge_h_sel = "%s//%s/%s/CA" % (obj, heavy, limit_h) hinge_l = cmd.get_atom_coords(hinge_l_sel) hinge_h = cmd.get_atom_coords(hinge_h_sel) hinge_vec = numpy.array(hinge_h) - numpy.array(hinge_l) test = numpy.dot(hinge_vec, numpy.cross(direction_v, direction_c)) if (test > 0): elbow = 360 - elbow print " Elbow angle: %i degrees" % elbow if (draw == 1): # there is probably a more elegant way to do this, but # it works so I'm not going to mess with it for now pre = obj + '_elbow_' # draw hinge vector cmd.pseudoatom(pre + "hinge_l", pos=hinge_l) cmd.pseudoatom(pre + "hinge_h", pos=hinge_h) cmd.distance(pre + "hinge_vec", pre + "hinge_l", pre + "hinge_h") cmd.set("dash_gap", 0) # draw the variable domain axis com_v = com.COM(v_sel) start_v = [a - 10 * b for a, b in zip(com_v, direction_v)] end_v = [a + 10 * b for a, b in zip(com_v, direction_v)] cmd.pseudoatom(pre + "start_v", pos=start_v) cmd.pseudoatom(pre + "end_v", pos=end_v) cmd.distance(pre + "v_vec", pre + "start_v", pre + "end_v") # draw the constant domain axis com_c = com.COM(c_sel) start_c = [a - 10 * b for a, b in zip(com_c, direction_c)] end_c = [a + 10 * b for a, b in zip(com_c, direction_c)] cmd.pseudoatom(pre + "start_c", pos=start_c) cmd.pseudoatom(pre + "end_c", pos=end_c) cmd.distance(pre + "c_vec", pre + "start_c", pre + "end_c") # customize appearance cmd.hide("labels", pre + "hinge_vec") cmd.hide("labels", pre + "v_vec") cmd.hide("labels", pre + "c_vec") cmd.color("green", pre + "hinge_l") cmd.color("red", pre + "hinge_h") cmd.color("black", pre + "hinge_vec") cmd.color("black", pre + "start_v") cmd.color("black", pre + "end_v") cmd.color("black", pre + "v_vec") cmd.color("black", pre + "start_c") cmd.color("black", pre + "end_c") cmd.color("black", pre + "c_vec") # draw spheres cmd.show("spheres", pre + "hinge_l or " + pre + "hinge_h") cmd.show("spheres", pre + "start_v or " + pre + "start_c") cmd.show("spheres", pre + "end_v or " + pre + "end_c") cmd.set("sphere_scale", 2) cmd.set("dash_gap", 0, pre + "hinge_vec") cmd.set("dash_width", 5) cmd.set("dash_radius", 0.3) # group drawing objects cmd.group(pre, pre + "*") # restore original view cmd.set_view(orig_view) return 0
def quat(name=None, filename=None, prefix=None, quiet=0): ''' DESCRIPTION Read REMARK 350 from `filename` and create biological unit (quaternary structure) USAGE quat [name [, filename [, prefix]]] ARGUMENTS name = string: name of object and basename of PDB file, if filename is not given {default: first loaded object} filename = string: file path {default: <name>.pdb} prefix = string: prefix for new objects {default: <name>} EXAMPLE fetch 1rmv quat 1rmv ''' quiet = int(quiet) if name is None: name = cmd.get_object_list()[0] if prefix is None: prefix = name if filename is None: candidates = [ '%s.pdb' % (name), '%s/%s.pdb' % (cmd.get('fetch_path'), name), '%s/%s/pdb%s.ent.gz' % (local_mirror_divided, name[1:3], name), ] for filename in candidates: if os.path.exists(filename): break else: print 'please provide filename' return if not quiet: print 'loading from %s' % (filename) remarks = pdbremarks(filename) if 350 not in remarks: print 'There is no REMARK 350 in', filename return quat = quat350(remarks[350]) for chains in quat: matrices = quat[chains] for num in matrices: mat = matrices[num][0:12] mat.extend([0,0,0,1]) copy = '%s_%d' % (prefix, num) if not quiet: print 'creating %s' % (copy) cmd.create(copy, '/%s//%s' % (name, '+'.join(chains))) cmd.alter(copy, 'segi="%d"' % (num)) cmd.transform_object(copy, mat) cmd.disable(name) cmd.group('%s_quat' % (prefix), '%s_*' % (prefix))
surf_transparency = 0.2 if dirpath: gfiles = [join(dirpath, g) for g in gfiles] for t in threshold_list: for i in range(len(grids)): try: cmd.load(r'%s' % (gfiles[i]), '%s_%s' % (grids[i], str(num))) cmd.isosurface('surface_%s_%s_%s' % (grids[i], t, num), '%s_%s' % (grids[i], num), t) cmd.set('transparency', surf_transparency, 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.color(colour_dict['%s' % (grids[i])], 'surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='surface_%s_%s_%s' % (grids[i], t, num)) cmd.group('threshold_%s' % (t), members='label_threshold_%s' % (t)) except: continue try: cmd.group('hotspot_%s' % (num), members='threshold_%s' % (t)) except: continue for g in grids: cmd.group('hotspot_%s' % (num), members='%s_%s' % (g, num)) cmd.bg_color("white") cmd.show("cartoon", "protein")
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