def Load_ProcConvLigand(self, LigandFile, ObjectName, Zoom): Error = 0 try: cmd.delete(ObjectName) cmd.refresh() except: pass auto_zoom = cmd.get("auto_zoom") try: cmd.set("auto_zoom", 0) cmd.load(LigandFile, ObjectName, state=1) cmd.refresh() if Zoom: cmd.zoom(ObjectName) cmd.refresh() except: self.DisplayMessage(' ERROR: Could not load the ligand file in PyMOL', 1) Error = 1 cmd.set("auto_zoom", auto_zoom) return Error
def load(): r = 0 rep = [ "simple", "technical", "ligands", "ligand_sites","ligand_sites_trans","ligand_sites_mesh","pretty", "publication" ] list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: print file cmd.delete('pdb') cmd.load(file,'pdb') cmd.orient('pdb') cur_rep = rep.pop(0) rep = rep + [cur_rep] getattr(pymol.preset,cur_rep)('pdb') cmd.refresh() # give PyMOL a chance time.sleep(0.02) time.sleep(0.02) time.sleep(0.02) time.sleep(0.02) cmd.refresh() time.sleep(0.02) time.sleep(0.02) time.sleep(0.02) time.sleep(0.02) while(pymol.run==0): time.sleep(0.1)
def load_save2(): while 1: time.sleep(random.random()) cmd.delete("obj2") cmd.load("dat/water.pdb","obj2") time.sleep(random.random()) cmd.save("tmp/T01b.pdb","obj2")
def fatslim_apl_prot(): global REF_BEAD setup() FILENAME = BILAYER_PROT REF_BEAD = BILAYER_PROT_REF # Load file cmd.load("%s.pdb" % FILENAME) main_obj = "%s" % FILENAME cmd.disable(main_obj) traj = load_trajectory("%s.gro" % FILENAME, "%s.ndx" % FILENAME) traj.initialize() frame = traj[0] draw_pbc_box(main_obj) cmd.create("protein", "resi 1-160") cmd.hide("lines", "protein") cmd.color("yellow", "protein") cmd.show("cartoon", "protein") cmd.show("surface", "protein") cmd.set("transparency", 0.5, "protein") cmd.set("surface_color", "yelloworange", "protein") # Show leaflets show_leaflets(frame) # Show stuff related to APL show_apl(frame) print("Bilayer with protein loaded!")
def testPseSupport(self): cmd.load_callback(callback.Callback(), 'c1') with testing.mktemp('tmp.pse') as session_filename: cmd.save(session_filename) cmd.delete('*') cmd.load(session_filename) self.assertTrue('c1' in cmd.get_names())
def frag(state=state, obj=obj): pwd, mutations, orig_sequence = setup(obj) #get_positions_in_selection(sub, distance) # Run over all sites where to mutate, optionally add and retain hydrogens. for site in mutations.keys(): variants = mutations[site] # Run over all variants. for variant in variants: cmd.load(obj) cmd.do('wizard mutagenesis') cmd.do('refresh_wizard') cmd.get_wizard().set_hyd("keep") cmd.get_wizard().set_mode(variant) #cmd.get_wizard().do_select(site + '/') # Get the number of available rotamers at that site. # Introduce a condition here to check if rotamers are requested. # <<OPTIONAL>> nRots = getRots(site, variant) #if nRots > 3: # nRots = 3 nRots=1 cmd.rewind() for i in range(1, nRots + 1): cmd.get_wizard().do_select("(" + site + "/)") cmd.frame(i) cmd.get_wizard().apply() # Optimize the mutated sidechain #<<OPTION>> #print "Sculpting." local_sculpt(obj, variant, site) # Protonation of the N. #cmd.do("select n%d, name n and %d/" % (int(site), int(site))) #cmd.edit("n%d" % int(site), None, None, None, pkresi=0, pkbond=0) #cmd.do("h_fill") # Protonation of the C. #cmd.do("select c%d, name c and %d/" % (int(site), int(site))) #cmd.edit("c%d" % int(site), None, None, None, pkresi=0, pkbond=0) #cmd.do("h_fill") # Definition of saveString #saveString = '%s/' % pwd #saveString += 'frag-' + get_one(orig_sequence[site]).lower() +\ # site + get_one(variant).lower() + '-%s.pdb, ' % state +\ # '((%s/))' % site save_string_rot = '%s/' % pwd save_string_rot += 'frag-' + get_one(orig_sequence[site]).lower() +\ site + get_one(variant).lower() + '-%02d-%s.pdb, ' % (i, state) +\ '((%s/))' % site #print saveString #cmd.do('save %s' % saveString.lower()) cmd.do('save %s' % save_string_rot.lower()) cmd.do('delete all') cmd.set_wizard('done')
def load_save1(): while 1: time.sleep(random.random()) cmd.delete("obj1") cmd.load("dat/pept.pdb","obj1") time.sleep(random.random()) cmd.save("tmp/T01a.pdb","obj1")
def testLoadNoProperties(self, molfilename): cmd.set('load_object_props_default', '') cmd.load(self.datafile(molfilename), 'test') objs = cmd.get_object_list() for obj in objs: prop_list= cmd.get_property_list(obj) self.assertEquals(prop_list, None)
def testMAEchempy(self, molfilename): cmd.load(self.datafile(molfilename), 'test', object_props='*', atom_props='*') objs = cmd.get_object_list() for obj in objs: idxToVal = {} natoms = cmd.count_atoms(obj) for i in range(natoms): idxToVal[i+1] = i*10 cmd.set_atom_property('test_prop', i*10, "index %d and %s" % (i+1, obj)) model = cmd.get_model(obj) # test to make sure the properties that exist are the same prop_list= cmd.get_property_list(obj) mol_prop_list = [x[0] for x in model.molecule_properties] self.assertEqual(set(prop_list), set(mol_prop_list)) # need to test whether the values are the same for prop, val in model.molecule_properties: propval = cmd.get_property(prop, obj) self.assertEqual(propval, val) self.assertEqual(natoms, len(model.atom)) # need to test values of all atom properties, including the ones that were set above stored.prop_lookup = {} cmd.iterate(obj, "stored.prop_lookup[index-1] = properties.all") idx = 0 for at in model.atom: for prop in at.atom_properties.keys(): val = at.atom_properties[prop] self.assertEqual(val, stored.prop_lookup[idx][prop]) idx += 1
def loadBR(pdb, saveName=None, color=None): if not saveName: saveName = pdb.split('.')[0] cmd.load(pdb, saveName) if color: cmd.color(color, saveName) cmd.hide("lines") cmd.hide("nonbonded") # cmd.show("cartoon") cmd.show("ribbon") cmd.set("cartoon_transparency", 0.7) keyResidues = ["ASPA0085", "ARGA0082", "GLUA0194", "GLUA0204", "LYSA0216", "RET", "ASPA0212"] for eachRes in keyResidues: # retinal's residue sequence id can vary in different pdbs. selection = "" if eachRes == "RET": selection = "resn ret" else: selection = parseResidue(eachRes) selection += " and not name c+o+n" cmd.show("sticks", selection) util.cbag(selection)
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file,'pdb') cmd.set_title('pdb',1,os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.show_as("ribbon") cmd.refresh() cmd.show_as("sticks") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n>1: cmd.rewind() sys.__stderr__.write(file+"\n") sys.__stderr__.flush() for a in range(1,n+1): cmd.forward() cmd.refresh() except: traceback.print_exc()
def packing(pdb): "Derive mean packing density of pdb as pd.Series." cmd.delete('all') cmd.load(pdb) cmd.remove('solvent') # Only heavy atoms cmd.remove('hydro') # Compute SAS per atom cmd.set('dot_solvent', 1) cmd.get_area('all', load_b=1) cmd.select('interior', 'b = 0') counts = pd.Series(0, index=RADS) vest = pd.Series(0, index=RADS) # from biggest to smallest radius for r in RADS[::-1]: # Counting counts.loc[r] = cmd.select('extended', 'interior extend {}'.format(r)) cmd.remove('not extended') # moleculare area #cmd.set('dot_solvent', 0) vest[r] = cmd.get_area('all') # Results cvdens = counts / vest counts.index = ["{}_rawcount".format(i) for i in counts.index] vest.index = ["{}_volume estimate".format(i) for i in vest.index] cvdens.index = ["{}_cv density".format(i) for i in cvdens.index] return pd.concat(([counts, cvdens, vest]))
def slowpacking(pdb): "Derive mean packing density of pdb as pd.Series." cmd.delete('all') cmd.load(pdb) cmd.remove('solvent') # Only heavy atoms cmd.remove('hydro') # Compute SAS per atom cmd.set('dot_solvent') cmd.get_area('all', load_b=1) N = float(cmd.select('interior', 'b = 0')) internal_coords = [at.coord for at in cmd.get_model('interior').atom]#[1:50] all_coords = [at.coord for at in cmd.get_model('all').atom]#[1:50] # Count counts = pd.Series(0, index=RADS) for a, b in product(internal_coords, all_coords): es = euclid_step(a, b) if es is not None: counts.loc[es] += 1 counts = counts.cumsum() # Mean per center atom meancounts = counts / N # Normalize to density volumina = pd.Series(4 / 3.0 * sp.pi * (RADS ** 3), index=RADS) density = meancounts / volumina # Correct for center density -= 1 / (4/3 * sp.pi * RADS ** 3) # Results counts.index = ["{}_correctcount".format(i) for i in counts.index] density.index = ["{}_density".format(i) for i in density.index] return pd.concat(([counts, density]))
def cheshift(pdb_path,cs_path): """Conects to CheShift to send and receive data""" pdb_filename = pdb_path.split('/')[-1] pdb_filenamenoext = re.sub(r'[^A-Za-z0-9-.]', '', pdb_filename.split('.')[0]) cs_filename = cs_path.split('/')[-1] # Send data to CheShift.com and captures the name of the new web page. br = mechanize.Browser() br.set_handle_refresh(False) br.set_proxies(proxy_values) try: br.open('http://www.cheshift.com/visual_test.html') br.select_form(nr=0) br.form.add_file(open(pdb_path), "chemical/x-pdb", pdb_filename, name = 'uploaded') br.form.add_file(open(cs_path), "text/plain", cs_filename, name='CS_file') br.form.set_value([ref_value.get()],name='radiogroup') br.form.set_all_readonly(False) response = br.submit().geturl() subfix = response.split('/')[-1].split('.')[0] except: Pmw.MessageDialog(title='Error',message_text=('Something went wrong while processing your request\n Please check your files and try again\n\nIf you could not find the problem please send and e-mail to [email protected]')) # Checks if the colored PDB file was created or if something went wrong test = 0 while True: try:# If the colored PDB was created, creates a local temporal PDB file # and loads that file into PyMOL. result = br.open('http://www.cheshift.com/jobs/%s/%s_b.pdb?r=%d' % (subfix, pdb_filenamenoext, test)).read() fd = tempfile.NamedTemporaryFile(bufsize=0,delete=False) fd.write(result) fd.close() pdb_tmp = fd.name pdblist = [] for line in open(pdb_tmp).readlines(): if 'ATOM' in line: pdblist.append(line) first = int(pdblist[0][22:26]) last = int(pdblist[-1][22:26]) cmd.reinitialize() rename = ('%s_b.pdb' % (pdb_filenamenoext)) cmd.load(pdb_tmp, rename) #CheShift does not provide results for the first or last residue cmd.remove('resi %s' % first) cmd.remove('resi %s' % last) colorize() break except: test += 1 try:# check for posible errors result = br.open('http://www.cheshift.com/jobs/%s/error.txt?r=%d' % (subfix, test)).read().split() # behind a proxy you need to add a "dummy" modifier to the requested file (?r=%d'). Otherwise you will just be checking the cached file and not the actual file. if int(result[0]) == 0: Pmw.MessageDialog(title = 'Error',message_text=('The residue at position %s is missing from your PDB file\n Please fix the problem and try again' % (result[1]))) elif int(result[0]) == 1: Pmw.MessageDialog(title = 'Error',message_text = ('The residue %s%s in your PDB file does not match\n with residue %s%s in your chemical shift file.\n\n Please check your files and try again' % (result[1], result[3], result[2], result[3]))) else: Pmw.MessageDialog(title = 'Error',message_text=('Something went wrong while processing your request\n Please check your files and try again\n\nIf you could not find the problem please write to us')) break except: pass time.sleep(5)
def makeMovie(numClusts, frameRate): real = int(numClusts)+1; fr = int(frameRate) movieSetup = "1 x" + str(real*fr) cmd.mset(movieSetup) #Load in all the system data. for x in range(0, real): # load the next system. clustName = "system-" + str(x) system = clustName + ".xyz" cmd.load(system) # Set the sphere scale and view cmd.set("sphere_scale","0.5","all") #Set the right view cmd.set_view("0.910306633, -0.382467061, 0.158301696, 0.326706469, 0.898694992, 0.292592257, -0.254171938, -0.214630708, 0.943043232, 0.000000000, 0.000000000, -99.425979614, 10.461934090, 13.087766647, 11.786855698, 80.009132385, 118.842796326, -20.000000000") #Set all the frame data for x in range(0, real): # set the current frame. frameNum = (x*fr)+1 cmd.frame(frameNum) clustName = "system-" + str(x) movieState = "hide; show spheres, " + clustName cmd.mdo(frameNum,movieState) cmd.mview("store") cmd.mview("reinterpolate") cmd.mplay()
def test_cbss(self): cmd.load(self.datafile('1oky-frag.pdb')) c = [2, 13, 22] # blue orange forest pymol.util.cbss('*', *c) stored.colors = set() cmd.iterate('*', 'stored.colors.add((ss or "L", color))') self.assertEqual(stored.colors, set(zip('HSL', c)))
def sculpt(self,cleanup=0): if not cleanup: cmd.set("suspend_updates",1,quiet=1) cmd.disable() cmd.delete("sculpt") cmd.set("sphere_scale","1.0") cmd.set("sphere_mode",5) cmd.load("$PYMOL_DATA/demo/pept.pdb","sculpt") cmd.hide("lines","sculpt") # cmd.show("sticks","sculpt") cmd.show("spheres","sculpt") # cmd.set("sphere_transparency","0.75","sculpt") # cmd.set("sphere_color","grey","sculpt") cmd.frame(1) cmd.set("auto_sculpt",1) cmd.set("sculpting",1) cmd.sculpt_activate("sculpt") cmd.set("sculpting_cycles","100") cmd.do("edit_mode") cmd.set("valence","0.05") cmd.set("suspend_updates",0,quiet=0) cmd.sculpt_iterate("sculpt") cmd.alter_state(1,"sculpt","x=x*1.5;y=y*0.1;z=z*1.5") cmd.zoom() cmd.unpick() else: cmd.set("valence","0") cmd.set("sculpting",0) cmd.set("auto_sculpt",0) cmd.delete("sculpt") cmd.mouse()
def testMAEsaveLoadSessions(self): cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props='*') allpropdata = {} objs = cmd.get_object_list() for obj in objs: props = cmd.get_property_list(obj) allpropdata[obj] = {} for prop in props: allpropdata[obj][prop] = cmd.get_property(prop, obj) with testing.mktemp('.pse') as psefilename: cmd.save(psefilename) cmd.load(psefilename) # this is to fail the test on purpose # cmd.set_property('i_m_ct_format', 3, '1d_smiles.mol_13') objs = cmd.get_object_list() for obj in objs: props = cmd.get_property_list(obj) # test to make sure there are no extra properties or not enough properties self.assertEqual(set(props), set(allpropdata[obj].keys())) # test to make sure all property values are the same for prop in props: try: self.assertTrue(allpropdata[obj][prop] == cmd.get_property(prop, obj)) except: self.fail('properties are not the same: obj=%s prop=%s' % (obj, prop))
def testPDBLoad(self, dfile): tm = [] for i in range(1, 100): start = time.time() cmd.load(self.datafile(dfile)) tm.append(time.time() - start) print("min time('", dfile, "')=", min(tm))
def testMAEloadSomePropertiesDontExist(self): props = ['s_knime_origin_file_name', 's_knime_origin_hostname', 'dontexist'] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertIsNotNone(allprops)
def testMAEloadSomePropertiesEmptyList(self): props = [] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertIsNone(allprops)
def load(): cmd.set("valence") r = 0 list = glob("pdb/*/*") # while list[0]!="pdb/f8/pdb1f8u": # list.pop(0) for file in list: try: cmd.delete('pdb') cmd.load(file,'pdb') cmd.set_title('pdb',1,os.path.split(file)[-1]) cmd.rewind() cmd.orient('pdb') cmd.refresh() cmd.zoom('center',16) cmd.label("polymer and (name ca or elem P)","'//%s/%s/%s`%s/%s'%(segi,chain,resn,resi,name)") cmd.refresh() sys.__stderr__.write(".") sys.__stderr__.flush() n = cmd.count_states() if n>1: cmd.rewind() sys.__stderr__.write(file+"\n") sys.__stderr__.flush() for a in range(1,n+1): cmd.forward() cmd.refresh() except: traceback.print_exc()
def do_pymol(self): if "ray.pymol" in self.path: # send image self.send_response(200) self.send_header('Content-type', 'image/x-png') self.send_header('Cache-control', 'no-cache') self.send_header('Pragma', 'no-cache') self.end_headers() write_image(self.wfile,1) elif "draw.pymol" in self.path: self.send_response(200) self.send_header('Content-type', 'image/x-png') self.send_header('Cache-control', 'no-cache') self.send_header('Pragma', 'no-cache') self.end_headers() write_image(self.wfile) else: if "load" in self.path: # load a structure cmd.load("$TUT/1hpv.pdb") cmd.rock() self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() if "status.pymol" in self.path: get_status(self.wfile) elif "monitor.pymol" in self.path: get_monitor(self.wfile) elif "quit.pymol" in self.path: self.wfile.write('<html><body><p>Quitting...</p></body></html>') self.wfile.flush() _shutdown() else: # start page get_start(self.wfile) self.wfile.flush()
def loadMultiConf(): keyRes = ["ASPA0085", "HOHA0402", "HOHA0406", "ARGA0082", "HOHA0403", "GLUA0194"] for res in keyRes: for f in os.listdir("."): if res[3:] in f: cmd.load(f)
def testSuper(self): cmd.load(self.datafile("1oky-frag.pdb"), "m1") cmd.load(self.datafile("1t46-frag.pdb"), "m2") r = cmd.super("m1", "m2", object="aln") self.assertAlmostEqual(r[0], 0.9667, delta=1e-4) self.assertEqual(r[1], 172) self.assertEqual(r[1], cmd.count_atoms("aln") / 2)
def main(): parser=argparse.ArgumentParser() parser.add_argument('-p', action='store', required=True, dest='pdbfile', help='pathfile is a textfile of name of pdb') parser.add_argument('-l', action='store', required=True, dest='loop', help='loop is an int number') inputs=parser.parse_args() pdbfile=inputs.pdbfile loop=int(inputs.loop) print "loop is %s "% loop dirname=os.getcwd()+'/interface_analyzer/pdbdata/'+pdbfile pdbfileselect=pdbfile.split('.') savefile=os.getcwd()+'/interface_analyzer/pdbdata/'+pdbfileselect[0]+'_antigen.pdb' print "remove antibody of complex,so can caculate the value of antigen sasa " pymol.finish_launching() if loop!=0: pymol.cmd.reinitialize() cmd.load(dirname) cmd.remove('hetatm') cmd.select('target1',pdbfileselect[0]) cmd.save(dirname,(('target1'))) cmd.delete('target1') cmd.remove('solvent') cmd.remove('hydrogens') cmd.remove('chain L+H') cmd.select('target',pdbfileselect[0]) cmd.save(savefile,(('target'))) cmd.delete(all) cmd.sync() cmd.quit() print "remove the antibody of complex have done"
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 test_unc(self): ''' UNC-Paths (PYMOL-2954) ''' pymolwin = self._get_pymolwin() with testing.mkdtemp() as base: if base[1] != ':': self.skipTest('no drive letter: ' + base) return if base.startswith('\\\\'): uncpath = base else: uncpath = '\\\\localhost\\%s$%s' % (base[0], base[2:]) pml_filename = uncpath + '\\in.pml' out_filename = uncpath + '\\out.pdb' with open(pml_filename, 'w') as handle: handle.write('fragment gly\n') handle.write('save %s\n' % out_filename) subprocess.call([pymolwin, '+2', '-kcq', pml_filename]) # wait for spawned process time.sleep(0.5) cmd.load(out_filename) self.assertEqual(7, cmd.count_atoms())
def testCifMissing(self): N = 7 cmd.fragment('gly', 'm1') cmd.alter('all', '(chain, segi, resv, alt) = ("?", ".", 5, "")') s = cmd.get_str('cif') self.assertTrue("'?'" in s or '"?"' in s) # chain self.assertTrue("'.'" in s or '"."' in s) # segi self.assertTrue(' ? ' in s) # e.g. pdbx_PDB_ins_code self.assertTrue(' . ' in s) # e.g. label_alt_id cmd.delete('*') cmd.set('cif_keepinmemory') cmd.load(s, 'm2', format='cifstr') self.assertEqual(['?'], cmd.get_chains()) self.assertEqual(cmd.count_atoms('segi .'), N) self.assertEqual(cmd.count_atoms('alt ""'), N) # no alt self.assertEqual(cmd.count_atoms('resi 5'), N) # no ins_code from pymol.querying import cif_get_array self.assertEqual(cif_get_array("m2", "_atom_site.type_symbol"), list('NCCOHHH')) self.assertEqual(cif_get_array("m2", "_atom_site.id", "i"), list(range(1, N + 1))) self.assertEqual(cif_get_array("m2", "_atom_site.auth_asym_id"), ['?'] * N) self.assertEqual(cif_get_array("m2", "_atom_site.label_asym_id"), ['.'] * N) self.assertEqual(cif_get_array("m2", "_atom_site.pdbx_pdb_ins_code"), [None] * N) self.assertEqual(cif_get_array("m2", "_atom_site.label_alt_id"), [None] * N)
def testMAEloadSomeProperties(self): props = ['s_knime_origin_file_name', 's_knime_origin_hostname'] cmd.load(self.datafile('1d_smiles.mae'), '1d_smiles', object_props=' '.join(props)) objs = cmd.get_object_list() for obj in objs: allprops = cmd.get_property_list(obj) self.assertEqual(len(props), len(allprops))
def testPSEBulkImport(self): cmd.load(self.datafile('1rx1_1766_bulk.pse.gz')) m1 = cmd.get_model() cmd.load(self.datafile('1rx1_176.pse.gz')) m2 = cmd.get_model() self.assertModelsAreSame(m1, m2)
xyz2 = cpv.add(xyz2, diff) xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2) obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [ cgo.CONE ] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0] return obj dirpath = tempfile.mkdtemp() zip_dir = 'out.zip' with zipfile.ZipFile(zip_dir) as hs_zip: hs_zip.extractall(dirpath) cmd.load(join(dirpath, "protein.pdb"), "protein") cmd.show("cartoon", "protein") if dirpath: f = join(dirpath, "label_threshold_10.mol2") else: f = "label_threshold_10.mol2" cmd.load(f, 'label_threshold_10') cmd.hide('everything', 'label_threshold_10') cmd.label("label_threshold_10", "name") cmd.set("label_font_id", 7) cmd.set("label_size", -0.4) if dirpath: f = join(dirpath, "label_threshold_14.mol2")
def __init__(self, list_file): super(PDBListFileCyclerLite, self).__init__() self.pdbs = [l.strip() for l in open(list_file)] pdb = self.pdbs[0] cmd.load(pdb)
def loadpdbs(self): for pdb in self.pdbs: cmd.load(pdb) cmd.disable(objname(pdb)) cmd.enable(objname(self.pdbs[0]))
def pymol_load_pose(pose, name): from pymol import cmd tmpdir = tempfile.mkdtemp() fname = tmpdir + '/' + name + '.pdb' pose.dump_pdb(fname) cmd.load(fname)
from pymol import cmd, stored cmd.load( "/Users/meghan/Documents/PhD/GitProjects/v6_2018_Network/CompStrDefns/CompPDBs/2QTK.pdb" ) cmd.hide("everything", "all") cmd.color("wheat", "all") cmd.select("Astrand0", "resi 10-23 & chain A ") cmd.color("white", "Astrand0") cmd.select("Astrand1", "resi 34-50 & chain A ") cmd.color("red", "Astrand1") cmd.select("Astrand2", "resi 55-68 & chain A ") cmd.color("orange", "Astrand2") cmd.select("Astrand3", "resi 92-102 & chain A ") cmd.color("purple", "Astrand3") cmd.select("Astrand4", "resi 107-111 & chain A ") cmd.color("yellow", "Astrand4") cmd.select("Astrand5", "resi 133-139 & chain A ") cmd.color("green", "Astrand5") cmd.select("Astrand6", "resi 146-153 & chain A ") cmd.color("cyan", "Astrand6") cmd.select("Astrand7", "resi 178-186 & chain A ") cmd.color("blue", "Astrand7")
def pdb2pqr_cli(name, selection, options, state=-1, preserve=0, exe='pdb2pqr', quiet=1, fixrna=0, _proclist=None): import os, tempfile, subprocess, shutil state, preserve, quiet = int(state), int(preserve), int(quiet) if cmd.is_string(options): import shlex options = shlex.split(options) args = [cmd.exp_path(exe)] + list(options) tmpdir = tempfile.mkdtemp() # Input format should be PDB, but use PQR instead because we can support # multi-state assemblies by not writing MODEL records. infile = os.path.join(tmpdir, 'in.pqr') outfile = os.path.join(tmpdir, 'out.pqr') args.extend([infile, outfile]) # For some reason, catching stdout/stderr with PIPE and communicate() # blocks terminate() calls from terminating early. Using a file # redirect doesn't show this problem. f_stdout = open(os.path.join(tmpdir, 'stdout.txt'), 'w+') # RNA resdiue names must be RA, RC, RG, and RU tmpmodel = '' if int(fixrna) and cmd.count_atoms('(%s) & resn A+C+G+U' % (selection)): tmpmodel = cmd.get_unused_name('_tmp') cmd.create(tmpmodel, selection, zoom=0) cmd.alter(tmpmodel + ' & polymer.nucleic & resn A+C+G+U', 'resn = "R" + resn') selection = tmpmodel try: cmd.save(infile, selection, state) p = subprocess.Popen( args, cwd=tmpdir, stdin=subprocess.PIPE, # Windows pythonw fix stdout=f_stdout, stderr=f_stdout) p.stdin.close() # Windows pythonw fix if _proclist is not None: _proclist.append(p) p.wait() # This allows PyMOL to capture it and display the output in the GUI. f_stdout.seek(0) print(f_stdout.read().rstrip()) if p.returncode == -15: # SIGTERM raise CmdException('pdb2pqr terminated') if p.returncode != 0: raise CmdException('%s failed with exit status %d' % (args[0], p.returncode)) warnings = [ L[10:] for L in open(outfile) if L.startswith('REMARK 5') ] warnings = ''.join(warnings).strip() cmd.load(outfile, name) return warnings except OSError as e: print(e) raise CmdException('Cannot execute "%s"' % (exe)) finally: if tmpmodel: cmd.delete(tmpmodel) f_stdout.close() if not preserve: shutil.rmtree(tmpdir) elif not quiet: print(' Notice: not deleting', tmpdir)
import sys from pymol import cmd finput = sys.argv[1] # PDB cmd.load('protein_0ps_md_0mV_5000ps_NVT_After_prmd.pdb', 'MyProtein') cmd.select('caps', 'resn ace+nh2') cmd.alter('caps', "type='HETATM'") foutput = 'altered_' + finput cmd.save(foutput, 'MyProtein')
## ====== end input parameters ===== base=os.getcwd() print('base =',base) os.chdir(base) if not os.path.exists('splitted_pdbs'): os.mkdir('splitted_pdbs') #for f in glob.glob('????.pdb'): for f in glob.glob('*.pdb'): pdb_file = f f = f[:-4] path = '{}/{}.pdb'.format(base,f) if os.path.exists(path): cmd.delete('*') cmd.load(path, quiet=0) for x_chain in cmd.get_chains(): print('x_chain = ',x_chain) cmd.select('sele', 'chain {}'.format(x_chain)) new_file = '{}_{}.pdb'.format(f,x_chain) new_path = '{}/splitted_pdbs/{}'.format(base,new_file) print('new_file,new_path =',new_file,new_path) print('path,new_path,f,pdb_file =',path,new_path,f,pdb_file) cmd.save(new_path,'((sele))') os.chdir(base) for f in glob.glob('????.cif'): pdb_file = f f = f[:-4] path = '{}/{}.cif'.format(base,f) if os.path.exists(path):
def mini(f): #os.system('/home/magnus/opt/qrnas/QRNA02/QRNA -i ' + f + ' -c /home/magnus/opt/qrnas/QRNA02/configfile.txt -o out.pdb') os.system('~/opt/qrnas/QRNA02/QRNA -i ' + f + ' -c ~/opt/qrnas/QRNA02/configfile.txt -o out.pdb') cmd.delete('mini') cmd.load('out.pdb', 'mini') print('end')
def prepwizard(name, selection='all', options='', state=-1, preserve=0, exe='$SCHRODINGER/utilities/prepwizard', quiet=1, _proclist=None): ''' DESCRIPTION Run the SCHRODINGER Protein Preparation Wizard. Builds missing side chains and converts MSE to MET. Other non-default options need to be passed with the "options=" argument. USAGE prepwizard name [, selection [, options [, state ]]] ARGUMENTS name = str: name of object to create selection = str: atoms to send to the wizard {default: all} options = str: additional command line options for prepwizard state = int: object state {default: -1 (current)} ''' import os, tempfile, subprocess, shutil, shlex state, preserve, quiet = int(state), int(preserve), int(quiet) exe = cmd.exp_path(exe) if not _is_exe(exe): if 'SCHRODINGER' not in os.environ: print(' Warning: SCHRODINGER environment variable not set') raise CmdException('no such script: ' + exe) args = [exe, '-mse', '-fillsidechains', '-WAIT'] if options: if cmd.is_string(options): options = shlex.split(options) args.extend(options) tmpdir = tempfile.mkdtemp() infile = 'in.pdb' outfile = 'out.mae' args.extend([infile, outfile]) try: cmd.save(os.path.join(tmpdir, infile), selection, state) env = dict(os.environ) env.pop('PYTHONEXECUTABLE', '') # messes up Python on Mac p = subprocess.Popen( args, cwd=tmpdir, env=env, stdin=subprocess.PIPE, # Windows pythonw fix stdout=subprocess.PIPE, stderr=subprocess.STDOUT) if _proclist is not None: _proclist.append(p) print(p.communicate()[0].rstrip()) if p.wait() == -15: # SIGTERM raise CmdException('prepwizard terminated') if p.returncode != 0: logfile = os.path.join(tmpdir, 'in.log') if os.path.exists(logfile): with open(logfile) as handle: print(handle.read()) raise CmdException('%s failed with exit status %d' % (args[0], p.returncode)) cmd.load(os.path.join(tmpdir, outfile), name) except OSError as e: print(e) raise CmdException('Cannot execute "%s"' % (exe)) finally: if not preserve: shutil.rmtree(tmpdir) elif not quiet: print(' Notice: not deleting', tmpdir) if not quiet: print(' prepwizard: done')
import __main__ __main__.pymol_argv = ['pymol','-qc'] import pymol from pymol import cmd, stored pymol.finish_launching() cmd.set('dot_solvent', 1) cmd.set('dot_density', 4) cmd.load('2src_kinDom.pdb') # use the name of your pdb file stored.residues = [] cmd.iterate('name ca', 'stored.residues.append(resi)') sasa_per_residue = [] for i in stored.residues: sasa_per_residue.append(cmd.get_area('resi %s' % i)) with open('2src_SASA.txt', 'w') as f: for item in sasa_per_residue: f.write("%s\n" % item) print sum(sasa_per_residue) print cmd.get_area('all') # just to check that the sum of sasa per residue equals the total area
#Written by BSc. Gabriel Jimenez-Avalos for the "Ropon-Palacios" lab. #This script creates complexes (Protein-Ligand) of the 10 best compounds based on the results of the "redocking_adtgpu.py" tool from pymol import cmd import subprocess import pandas as pd import os subprocess.call('mkdir top10complexes', shell=True) allredocksum = pd.read_csv('allredocksum.csv') templist = allredocksum['ligand'].tolist() top10 = templist[0:10] for i in top10: os.chdir(i) subprocess.call('grep \'^DOCKED\' *.dlg | cut -c9- > ligand_out.pdbqt', shell=True) cmd.load('ligand_out.pdbqt', multiplex=1) run = int(allredocksum[allredocksum['ligand'] == i]['run']) if len(str(run)) == 1: cmd.delete('!' + 'ligand_out_' + '000' + str(run)) if len(str(run)) == 2: cmd.delete('!' + 'ligand_out_' + '00' + str(run)) if len(str(run)) == 3: cmd.delete('!' + 'ligand_out_' + '0' + str(run)) cmd.load('../receptor.pdbqt') cmd.save('../top10complexes/complex_' + i + '.pdb') cmd.delete('all') os.chdir('..')
def loadSurfaceInterfacePDB( file,name=None,native=None,wt=None): print " Loading interface PDB %s"%(file) if name is None: name = name = os.path.basename(file) if name.endswith('.pdb'): name = name[:-4] # Call Will's packing PDB loading function # Note: proteins will be cartoons, cavities will be spheres # Rosetta radii will be enabled name = loadPackingPDB(file,name,native) cavselname = name+"cavities" protselname = name+"protein" cmd.hide("lines",protselname) backbone_colorlist = [ 'forest','gold', 'violet', 'cyan', \ 'salmon', 'lime', 'slate', 'magenta', 'orange', 'marine', \ 'olive', 'forest', 'firebrick', 'chocolate' ] curr_bb_color = 0 carbon_colorlist = ['titanium', 'wheat', 'grey', 'pink' ] curr_carbon_color = 0 # Derive selections for the interface, color by chain cmd.select("interface", "none") cmd.select("heavy_interface", "none") selectPolarProtons("polar_protons") selectApolarProtons("apolar_protons") alphabet = list(('abcdefghijklmnopqrstuvwxyz').upper()) for letter in alphabet: chainname = "chain"+letter cmd.select( chainname, "chain %s and not hetatm and not symbol w"%(letter) ) # Check whether any protein atoms exist with this chain ID # JK Later, put in a special "non-interface" case for L/H antibody chains if cmd.count_atoms("chain%s"%(letter))>0: interfacename = "interface"+letter cmd.select("not_this_chain", "not hetatm and not symbol w and not %s"%(chainname) ) cmd.select(interfacename, "byres %s and (not_this_chain around 4.0)"%(chainname) ) cmd.select("heavy_%s"%(interfacename), "%s and not apolar_protons"%(interfacename)) cmd.select("interface", "interface or %s"%(interfacename) ) cmd.select("heavy_interface", "heavy_interface or heavy_%s"%(interfacename) ) cmd.delete("not_this_chain") cmd.color(backbone_colorlist[curr_bb_color], chainname) #changing.... colorCPK(interfacename,backbone_colorlist[curr_bb_color]) curr_bb_color = curr_bb_color+1 if(curr_bb_color == len(backbone_colorlist)): curr_bb_color = 0 #colorCPK(interfacename,carbon_colorlist[curr_carbon_color]) curr_carbon_color = curr_carbon_color+1 if(curr_carbon_color == len(carbon_colorlist)): curr_carbon_color = 0 cmd.color("white", "%s and polar_protons"%(interfacename)) else: cmd.delete(chainname) cmd.delete("apolar_protons") cmd.delete("polar_protons") # Show the interface in sticks, colored cpk #cmd.hide( "cartoon", "interface" ) cmd.show( "sticks", "heavy_interface" ) #cmd.zoom("interface") cmd.create("design", "chain B") cmd.create("target", "chain A") cmd.show( "surface", "target" ) cmd.show( "surface", "design" ) cmd.set( "transparency", 0 ) #if loaded together with wt cmd.load( wt, "wt" ) cmd.create( "wt_A", "wt and chain A" ) cmd.create( "wt_B", "wt and chain B" ) cmd.select("none") cmd.create( "des_A", "not wt and chain A" ) cmd.show( "surface", "des_A" ) cmd.create( "des_B", "not wt and chain B") cmd.show( "surface", "des_B" ) cmd.align( "wt_A", "des_A" ) cmd.align( "wt_B", "des_B" ) # cmd.show( "lines", "wt_A" ) # cmd.show( "lines", "wt_B" ) #cmd.show( "cartoon", "(interface) or byres(neighbor(interface)) or byres(neighbor(byres(neighbor(interface))))" ) cmd.show( "cartoon") # Show interface waters as small purple spheres cmd.select( "interface_water", "(symbol w or resn HOH) and (interface around 8.0)") if cmd.count_atoms("interface_water")>0: # Put the waters in a separate object, so that we can scale their radii newwatername = name+"waters" cmd.create(newwatername, "interface_water") cmd.remove("interface_water") cmd.color("purple", newwatername) cmd.show( "spheres", newwatername ) cmd.set( "sphere_scale", 0.1, newwatername ) else: cmd.delete("interface_water") # Show interface ligands as pink sticks cmd.select( "interface_hetero", "(not symbol w and not resn HOH) and (hetatm and not symbol w and not resn WSS) and (interface around 4.5)") if cmd.count_atoms("interface_hetero")>0: cmd.color("pink", "interface_hetero") cmd.show( "sticks", "interface_hetero" ) else: cmd.delete("interface_hetero") cmd.select("none") return name
def load_tmp(): print('Load...') cmd.load(TMP_FOLDER + '/last.pse')
xyz2 = cpv.add(xyz2, diff) xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2) obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [ cgo.CONE ] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0] return obj dirpath = tempfile.mkdtemp() zip_dir = 'hotspot_boundaries.zip' with zipfile.ZipFile(zip_dir) as hs_zip: hs_zip.extractall(dirpath) cmd.load(join(dirpath, "protein.pdb"), "protein") cmd.show("cartoon", "protein") if dirpath: f = join(dirpath, "0/label_threshold_3.7.mol2") else: f = "0/label_threshold_3.7.mol2" cmd.load(f, 'label_threshold_3.7') cmd.hide('everything', 'label_threshold_3.7') cmd.label("label_threshold_3.7", "name") cmd.set("label_font_id", 7) cmd.set("label_size", -0.4) colour_dict = { 'acceptor': 'red',
'--limit', type=int, help= f'Limit the size of the trajectory file to this limit in bytes. If the limit is reached the trajectory file is loaded by chunk accordingly. The default is {tfthreshold} B ({tfthreshold/1000000000} GB)', default=tfthreshold) args = parser.parse_args() # For memory efficiency: cmd.set('defer_builds_mode', 3) # To keep original atom order cmd.set('retain_order', 1) if args.fframes is not None: args.frames = list(numpy.genfromtxt(args.fframes, dtype=int)) cmd.load(args.top, 'inp') # Check the size of the input trajectory file trajfilesize = os.path.getsize(args.traj) tfthreshold = args.limit nchunks = int(numpy.ceil(trajfilesize / tfthreshold)) nframes = dcd_reader.get_nframes(args.traj) chunks = numpy.array_split(numpy.arange(1, nframes + 1), nchunks) if args.select is None: selection = 'inp' else: selection = f'inp and ({args.select})' if args.frames is not None: stop = max(args.frames)
xyz2 = cpv.add(xyz2, diff) xyz3 = cpv.add(cpv.scale(normal, hlength), xyz2) obj = [cgo.CYLINDER] + xyz1 + xyz3 + [radius] + color1 + color2 + [ cgo.CONE ] + xyz3 + xyz2 + [hradius, 0.0] + color2 + color2 + [1.0, 0.0] return obj dirpath = tempfile.mkdtemp() zip_dir = 'hotspot_boundaries.zip' with zipfile.ZipFile(zip_dir) as hs_zip: hs_zip.extractall(dirpath) cmd.load(join(dirpath, "protein.pdb"), "protein") cmd.show("cartoon", "protein") if dirpath: f = join(dirpath, "0/label_threshold_14.6.mol2") else: f = "0/label_threshold_14.6.mol2" cmd.load(f, 'label_threshold_14.6') cmd.hide('everything', 'label_threshold_14.6') cmd.label("label_threshold_14.6", "name") cmd.set("label_font_id", 7) cmd.set("label_size", -0.4) colour_dict = { 'acceptor': 'red',
import pymol from pymol import cmd, util from glob import glob import re cmd.reset() cmd.delete('all') path = "/Users/choderaj/github/foldingathome/covid-moonshot/receptors/monomer/" # Aim 1 : 3-aminopyridines (cyan) fragments = ['x2646', 'x10201', 'x10387', 'x10789', 'x10019', 'x10236', 'x10237', 'x10959'] for fragment in fragments: cmd.load(path + f'Mpro-{fragment}_0_bound-ligand.mol2', f'aminopyridines-{fragment}-ligand') cmd.load(path + f'Mpro-{fragment}_0_bound-protein.pdb', f'aminopyridines-{fragment}-protein') util.cbac(f'aminopyridines-*') # Aim 2 : quinolones (magenta) fragments = ['x2910', 'x3080', 'x3303'] for fragment in fragments: cmd.load(path + f'Mpro-{fragment}_0_bound-ligand.mol2', f'quinolones-{fragment}-ligand') cmd.load(path + f'Mpro-{fragment}_0_bound-protein.pdb', f'quinolones-{fragment}-protein') util.cbam(f'quinolones-*') # Aim 3 : benzotriazoles (green) fragments = ['x10820', 'x10871', 'x10876'] for fragment in fragments: cmd.load(path + f'Mpro-{fragment}_0_bound-ligand.mol2', f'benzotriazoles-{fragment}-ligand') cmd.load(path + f'Mpro-{fragment}_0_bound-protein.pdb', f'benzotriazoles-{fragment}-protein') util.cbag(f'benzotriazoles-*')
import pymol from pymol import cmd import sys structure = '4uad' cmd.reinitialize() cmd.set('bg_rgb', '[1,1,1]') # white cmd.set('antialias', '2') cmd.set('ray_opaque_background', 'off') cmd.set('depth_cue', 'off') ### Modify here url = 'https://files.rcsb.org/download/4UAD.pdb' cmd.load(url, 'orig') cmd.select('importin', 'chain A') cmd.select('origPB2', 'chain E') cmd.load('S009PB2_{0}.pdb'.format(structure, 'S009')) cmd.super('S009', 'origPB2') cmd.hide('everything') cmd.show('cartoon') # cmd.show('surface') for c in ['importin', 'S009']: cmd.show('surface', '{0}'.format(c)) # cmd.remove('origPB2') cmd.color('wheat', 'importin') cmd.color('white', 'S009')
def load_movie(filename_string, movie_name="mov"): lst = glob(filename_string) lst.sort() for fil in lst: cmd.load(fil, movie_name)
from pymol import cmd pymol.finish_launching() import sys cmd.set('dot_solvent', 1) cmd.set('dot_density', 3) rec_file = sys.argv[1] lig_file = sys.argv[2] lig_pymol = lig_file[:-4] #============================================================================== #rec_file = '/home/athar/Dimer/dock-std/true/12as/rec.pdb' #lig_file = '/home/athar/Dimer/dock-std/true/12as/lig.pdb' #============================================================================== #complex_file = sys.argv[3] cmd.load(rec_file) # use the name of your pdb file rec_area = cmd.get_area('rec_nmin') cmd.load(lig_file) #lig_area=cmd.get_area ('lig.2') lig_area = cmd.get_area(lig_pymol) cmd.save('complexfile.pdb') cmd.delete(all) cmd.load('complexfile.pdb') total_area = cmd.get_area('complexfile') area = (abs(rec_area + lig_area - total_area)) * 0.5 # using sasa area print area #return area
def parse_commandline_options(): # passed filename is first passed argument, but flags are also in argv print("python file loaded") for i, ele in enumerate(argv): print("argv[%s]" % i, ele) parser = argparse.ArgumentParser( description="Trying to parse some named parameters from shellscript") # parser.add_argument("-i", "--input", required=True) parser.add_argument("-i", "--input", required=True) # parser.add_argument("--ligand_name", required=True) parser.add_argument("--ligand_name", type=str) parser.add_argument("--chain_name", type=str, default="A") parser.add_argument("--color_blind_friendly", default=True) parser.add_argument("--binding_site_radius", type=float, default=4.0) parser.add_argument("--check_halogen_interaction", default=False) parser.add_argument("--water_in_binding_site", default=True) parser.add_argument("--color_carbon", type=str, default="yellow") parser.add_argument("--session_export_version", type=float, default=1.2) parser.add_argument("--color_polar_interactions", type=str, default="blue") parser.add_argument("--cofactor_name", type=str, default="") parser.add_argument("--color_carbon_cofactor", type=str, default="orange") # parser.add_argument("--", required=True) args = parser.parse_args() options = vars(args) # put variables into dictionary if args.input: if os.path.exists(args.input): input = args.input # Parse commandline arguments PDB_NAME = input.split(".")[0] PDB_FILENAME = PDB_NAME + ".pdb" # option for super basic mode if not args.ligand_name: options["no_ligand_selected"] = True if args.color_blind_friendly: if args.color_blind_friendly == "No": options["color_blind_friendly"] = False else: options["color_blind_friendly"] = True if args.check_halogen_interaction: if args.check_halogen_interaction == "No": options["check_halogen_interaction"] = False else: options["check_halogen_interaction"] = True if args.water_in_binding_site: if args.water_in_binding_site == "No": options["water_in_binding_site"] = False else: options["water_in_binding_site"] = True if args.color_carbon: # options are yellow, grey and orange, only need to change when color blind friendly if options['color_blind_friendly']: if args.color_carbon == "yellow": options["color_carbon"] = "cb_yellow" elif args.color_carbon == "orange": options["color_carbon"] = "cb_orange" allowed_polar_colors = set(["red", "blue", "yellow", "black", "hotpink"]) if args.color_polar_interactions and (args.color_polar_interactions in allowed_polar_colors): # options are yellow, red, blue, black and hotpink if options['color_blind_friendly']: if args.color_polar_interactions != "hotpink": options[ "color_polar_interactions"] = "cb_%s" % args.color_polar_interactions else: options["color_polar_interactions"] = "hot_pink" else: if options['color_blind_friendly']: options["color_polar_interactions"] = "cb_blue" else: options["color_polar_interactions"] = "blue" session_version = 1.2 if args.session_export_version: allowed_versions = {1.2, 1.72, 1.76, 1.84} if args.session_export_version in allowed_versions: session_version = args.session_export_version # set session_export to be of desired version cmd.set("pse_export_version", session_version) # --cofactor_name ${12} - -color_carbon_cofactor if args.cofactor_name: options['cofactor_in_binding_site'] = True options['cofactor_name'] = args.cofactor_name options['color_carbon_cofactor'] = args.color_carbon_cofactor else: options['cofactor_in_binding_site'] = False # load pdb file (first argument) # renaming the *.dat file to *.pdb, loading with pymol and renaming for galaxy os.rename(input, PDB_FILENAME) cmd.load(PDB_FILENAME) os.rename(PDB_FILENAME, input) # rename back to *.dat return options
def peptide_rebuild_modeller(name, selection='all', hetatm=0, sequence=None, nmodels=1, hydro=0, quiet=1): ''' DESCRIPTION Remodel the given selection using modeller. This is useful for example to build incomplete sidechains. More complicated modelling tasks are not the intention of this simple interface. Side effects: Alters "type" property for MSE residues in selection (workaround for bug #3512313). USAGE peptide_rebuild_modeller name [, selection [, hetatm [, sequence ]]] ARGUMENTS name = string: new object name selection = string: atom selection hetatm = 0/1: read and model HETATMs (ligands) {default: 0} sequence = string: if provided, use this sequence instead of the template sequence {default: None} nmodels = int: number of models (states) to generate {default: 1} ''' try: import modeller from modeller.automodel import automodel, allhmodel except ImportError: print(' Error: failed to import "modeller"') raise CmdException import tempfile, shutil, os _assert_package_import() from .editing import update_identifiers nmodels, hetatm, quiet = int(nmodels), int(hetatm), int(quiet) if int(hydro): automodel = allhmodel tempdir = tempfile.mkdtemp() pdbfile = os.path.join(tempdir, 'template.pdb') alnfile = os.path.join(tempdir, 'aln.pir') cwd = os.getcwd() os.chdir(tempdir) if not quiet: print(' Notice: PWD=%s' % (tempdir)) try: modeller.log.none() env = modeller.environ() env.io.hetatm = hetatm # prevent PyMOL to put TER records before MSE residues (bug #3512313) cmd.alter('(%s) and polymer' % (selection), 'type="ATOM"') cmd.save(pdbfile, selection) mdl = modeller.model(env, file=pdbfile) aln = modeller.alignment(env) aln.append_model(mdl, align_codes='foo', atom_files=pdbfile) # get sequence from non-present atoms if not sequence and cmd.count_atoms('(%s) & !present' % (selection)): sequence = get_seq(selection) if sequence: aln.append_sequence(sequence) aln[-1].code = 'bar' aln.malign() aln.write(alnfile) a = automodel( env, alnfile=alnfile, sequence=aln[-1].code, knowns=[s.code for s in aln if s.prottyp.startswith('structure')]) a.max_ca_ca_distance = 30.0 if nmodels > 1: a.ending_model = nmodels from multiprocessing import cpu_count ncpu = min(cpu_count(), nmodels) if ncpu > 1: from modeller import parallel job = parallel.job(parallel.local_slave() for _ in range(ncpu)) a.use_parallel_job(job) a.make() for output in a.outputs: cmd.load(output['name'], name, quiet=quiet) finally: os.chdir(cwd) shutil.rmtree(tempdir) cmd.align(name, selection, cycles=0) if not sequence: update_identifiers(name, selection) if not quiet: print(' peptide_rebuild_modeller: done')
from pymol import cmd cmd.load('ref/4ll3.pdb') # open dist.txt for writing f = open('analysis/dist.txt', 'w') for res1 in range(1, 100): for res2 in range(1, 100): # calculate the distance and store it in dst dst = cmd.distance('tmp', 'A/' + str(res1) + '/ca', 'A/' + str(res2) + '/ca') # write the formatted value of the distance (dst) # to the output file f.write(str(res1) + '\t' + str(res2) + '\t' + "%8.3f\n" % dst) # close the output file. f.close()
try: import tkinter as tk except ImportError: import Tkinter as tk from os.path import join import tempfile import zipfile import math from pymol import cmd, finish_launching, plugins from pymol.cgo import * finish_launching() cmd.load("ligands.mol2", "ligands") ring_point_0 = [COLOR, 0.33, 1.0, 0.0] + [ALPHA, 0.8] + [ SPHERE, float(27.5), float(5.0), float(64.5), float(2.0) ] cmd.load_cgo(ring_point_0, "ring_point_0_obj", 1) cmd.pseudoatom(object="ring_point_0_score", pos=(27.5, 5.0, 64.5), color=(1, 1, 1), label=191.4) cmd.group("ring_0", members="ring_point_0_obj") cmd.group("ring_0", members="ring_point_0_score") acceptor_projected_point_1 = [COLOR, 1.0, 0.0, 0.0] + [ALPHA, 0.8] + [ SPHERE, float(28.5),
####pymol script to calculate the RMSD between a thermophile with all of its mesophilic homologues import __main__ __main__.pymol_argv = ['pymol', '-qc'] # Pymol: quiet and no GUI from time import sleep import pymol pymol.finish_launching() from pymol import cmd from glob import glob thermofile = 'clean1pcz_A_100.pdb' cmd.load(thermofile, "thermo") mesofiles = 'mesos/*.pdb' for file in glob(mesofiles): print file cmd.load(file, "meso") rms = cmd.align("thermo", "meso")[0] print "%s rmsd: %s" % (file, rms) cmd.delete("meso")
def loadflexdock( system, dataset, idx="1", flexdist="3", pdbbindpath="../../PDBbind18", dockingpath="", ): # Clear everything cmd.reinitialize("everything") # Convert string of indices to numbers idx = int(idx) # Convert flexdist to float flexdist = float(flexdist) # Print informations print(f"Loading {dataset}/{system} (rank {idx})") print(f"flexdist = {flexdist}") # Build paths ligname = f"{system}_ligand-{idx}.pdb" ligandpath = os.path.join(dockingpath, dataset, system, ligname) # Docked ligand flexname = f"{system}_flex-{idx}.pdb" flexpath = os.path.join(dockingpath, dataset, system, flexname) # Flexible residues receptorname = f"{system}_protein-{idx}.pdb" receptorpath = os.path.join(dockingpath, dataset, system, receptorname) crystalname = f"{system}_protein.pdb" crystalpath = os.path.join( pdbbindpath, dataset, system, crystalname ) # Crystal receptor # Load ligand and receptor cmd.load(ligandpath, "ligand") # Selection name: ligand cmd.load(flexpath, "flex") # Selection name: flex cmd.load(receptorpath, "receptor") # Selection name: receptor cmd.load(crystalpath, "crystal") # Selection name: receptor # Hide everything cmd.hide("all") # Show receptor cmd.show("cartoon", "receptor") cmd.color("grey", "receptor") # Show docked ligand cmd.show("sticks", "ligand") cmd.show("spheres", "ligand") cmd.set("sphere_scale", 0.2, "ligand") cmd.color("marine", "ligand and name C*") # Show flexible residues cmd.show("licorice", "flex") cmd.set("stick_radius", 0.2, "flex") cmd.color("teal", "flex and name C*") # Center and zoom to ligand cmd.center("ligand") cmd.zoom("ligand", 10) # Remove solvent cmd.remove("solvent") # Get residues of receptor close to flexible residues stored.list = [] cmd.iterate( "receptor within 0.1 of flex", # Selection "stored.list.append((resn, resi, chain))", # Action ) # Remove redundancies flexres = set(stored.list) # Set of flexible residues # Outline flexible residues of the receptor for _, resi, chain in flexres: if chain != "": # ??? sel = f"receptor and (resi {resi} in chain {chain})" cmd.show("sphere", sel) cmd.set("sphere_scale", 0.2, sel) cmd.color("yellow", sel) cmd.remove(f"hydro in ({sel})") # Outline flexible residues of the crystal for _, resi, chain in flexres: if chain != "": # ??? sel = f"crystal and (resi {resi} in chain {chain})" cmd.show("licorice", sel) cmd.set("stick_radius", 0.15, sel) cmd.color("deeppurple", sel) cmd.remove(f"hydro in ({sel})") # Show metal atoms cmd.show("spheres", "metals") cmd.set("sphere_scale", 0.5, "metals")
__author__ = 'Shashank' # # -- basicCodeBlock.py # from pymol import cmd, stored def yourFunction(arg1, arg2): ''' DESCRIPTION Brief description what this function does goes here ''' # # Your code goes here # print "Hello, PyMOLers" print "You passed in %s and %s" % (arg1, arg2) print "I will return them to you in a list. Here you go." return (arg1, arg2) cmd.extend("yourFunction", yourFunction("Hello", "World")) cmd.load("../PDB/1JS1.pdb")