def __init__(self,debug=0): #look for PYMOL_PATH import os import sys if sys.platform == "win32" : os.environ['PYMOL_PATH'] = "C:\Python26\lib\site-packages\pymol" import pymol print("ok launch pymol") pymol.pymol_argv[1] = '-qcGi' import __main__ # __main__.pymol = pymol print(dir(__main__)) print(__name__) pymol.finish_launching() import sys print("done") self.cmd = pymol.cmd self.Mols = {} self.pymol = pymol self.debug = debug self.viewmat = None#numpy.array(self.cmd.get_view(quiet=1)) self.fragments = {'formamide':(3,1), 'acetylene':(2,0), 'formamide':(3,1), 'cyclobutane':(4,0), 'cyclopentane':(5,0), 'cyclopentadiene':(5,0), 'cyclohexane':(7,0), 'cycloheptane':(8,0), 'methane':(1,0), 'benzene':(6,0), 'sulfone':(6,0) }
def main(): parser=argparse.ArgumentParser() parser.add_argument('-f', action='store', required=True, dest='pdbfile', help='PDB file of protein-antibody complex') parser.add_argument('-d', action='store', required=True, dest='distance', help='distance is more than 0') parser.add_argument('-c1', action='store', required=True, dest='chain_a', help='distance is more than 0') parser.add_argument('-c2', action='store', required=True, dest='chain_b', help='distance is more than 0') inputs=parser.parse_args() from os import path,access,R_OK chain_a='chain '+inputs.chain_a chain_b='chain '+inputs.chain_b pdbfile=os.getcwd()+'/interface_analyzer/pdbdata/'+inputs.pdbfile distance=inputs.distance if path.exists(pdbfile) and path.isfile(pdbfile) and access(pdbfile,R_OK): pass else: print "Your PDB file does not exist. Please check the path of your PDB file." sys.exit(1) print "Extracting out the residues with cut off with 4" pymol.finish_launching() pymol.cmd.load(pdbfile) pymol.cmd.remove('hydrogens') pymol.cmd.remove('solvent') pairwise_dist(inputs.pdbfile,chain_a,chain_b,float(distance),'P') pymol.cmd.delete(all) pymol.cmd.quit()
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 open_gui(self): """Open the PyMOL GUI.""" # Use the PyMOL python modules. if self.exec_mode == 'module': # Open the GUI. pymol.finish_launching() self.open = True # Otherwise execute PyMOL on the command line. if self.exec_mode == 'external': # Test that the PyMOL binary exists. test_binary('pymol') # Python 2.3 and earlier. if Popen == None: raise RelaxError("The subprocess module is not available in this version of Python.") # Open PyMOL as a pipe. self.pymol = Popen(['pymol', '-qpK'], stdin=PIPE).stdin # Execute the command history. if len(self.command_history) > 0: self.exec_cmd(self.command_history, store_command=0) return # Test if the PDB file has been loaded. if hasattr(cdp, 'structure'): self.open_pdb()
def cartoon( filename, name ): pymol.finish_launching() pymol.cmd.read_pdbstr( *name_check( filename, name ) ) pymol.cmd.hide( "everything" ) pymol.cmd.show( "cartoon" ) pymol.cmd.spectrum()
def calc_rmsd_pymol(pdb1, pdb2, method): """Calculate rmsd using PyMOL. Two methods are available: align and fit See: - Align: http://www.pymolwiki.org/index.php/Align - Fit: http://www.pymolwiki.org/index.php/Fit Align can return a list with 7 items: RMSD after refinement Number of aligned atoms after refinement Number of refinement cycles RMSD before refinement Number of aligned atoms before refinement Raw alignment score Number of residues aligned in this version of function, the function returns `RMSD before refinement`. Install on OSX: ``brew install homebrew/science/pymol`` and set ``PYTHONPATH`` to your PyMOL packages, .e.g :: PYTHONPATH=$PYTHONPATH:/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages If problem:: Match-Error: unable to open matrix file '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/data/pymol/matrices/BLOSUM62'. then define ``PYMOL_PATH`` in your .bashrc, e.g.:: export PYMOL_PATH=/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pymol/ """ try: import __main__ __main__.pymol_argv = ['pymol', '-qc'] import pymol # import cmd, finish_launching pymol.finish_launching() except ImportError: print('calc_rmsd_pymol: you need to have installed PyMOL') sys.exit(0) # no error pymol.cmd.reinitialize() pymol.cmd.delete('all') pymol.cmd.load(pdb1, 's1') pymol.cmd.load(pdb2, 's2') if method == 'align': # experiments with align <https://pymolwiki.org/index.php/Align> # quiet = 0/1: suppress output {default: 0 in command mode, 1 in API} return (pymol.cmd.align('s1', 's2',quiet=1, object='aln')[3],0) #, pymol.cmd.align('s1','s2')[4]) #raw_aln = pymol.cmd.get_raw_alignment('aln') #print raw_aln #for idx1, idx2 in raw_aln: # print '%s`%d -> %s`%d' % tuple(idx1 + idx2) #pymol.cmd.save('aln.aln', 'aln') if method == 'fit': return (pymol.cmd.fit('s1', 's2'), 'fit')
def main(sys_argv=sys.argv): #pdbCode = '1XFH'.lower() pdbCode = '2NWL'.lower() pymol.finish_launching() cmd.fetch(pdbCode) xml = get_pdbtm_xml(pdbCode) chains_dict = get_pdbtm_annotation(pdbCode, xml) highlight_molecule(chains_dict, pdbCode.lower())
def export_png(self, rel_path, pdb_id, infos): """Uses pymol to export a png representing a PDB structure. The image displays the chains that contains the domains (cartoon) and the interacting residues (surface). THE CHOICE HAS BEEN MADE TO NOT HIGHLIGHT THE DOMAINS. """ # extracts informations for the chain and the residues domain_1 = self._extract_info(infos, '1') domain_2 = self._extract_info(infos, '2') # gets informations chain_1 = domain_1['chain'] chain_2 = domain_2['chain'] residues_1 = '+'.join(domain_1['ids']) residues_2 = '+'.join(domain_2['ids']) # build the select command for pymol chain_1_obj = 'chain '+chain_1+' and (not resi '+residues_1+')' chain_2_obj = 'chain '+chain_2+' and (not resi '+residues_2+')' residues_1_obj = 'chain '+chain_1+' and resi '+residues_1 residues_2_obj = 'chain '+chain_1+' and resi '+residues_2 # run pymol without its gui pymol.pymol_argv = ['pymol','-qc'] pymol.finish_launching() # the file pymol.cmd.load(rel_path, pdb_id) pymol.cmd.disable('all') pymol.cmd.enable(pdb_id) # background pymol.cmd.bg_color(color='white') pymol.cmd.hide('all') pymol.cmd.deselect() # objects pymol.cmd.create('chain_1', chain_1_obj) pymol.cmd.create('chain_2', chain_2_obj) pymol.cmd.create('res_1', residues_1_obj) pymol.cmd.create('res_2', residues_2_obj) # colors pymol.cmd.color('lightblue', 'chain_1') pymol.cmd.color('nitrogen', 'res_1') pymol.cmd.color('yelloworange', 'chain_2') pymol.cmd.color('red', 'res_2') # representation type pymol.cmd.show('cartoon', 'chain_1') pymol.cmd.show('cartoon', 'chain_2') pymol.cmd.show('surface', 'res_1') pymol.cmd.show('surface', 'res_2') # zoom pymol.cmd.create('final', 'chain_1 or chain_2 or res_1 or res_2') pymol.cmd.zoom('final') # export pymol.cmd.png(re.sub('.ent$', '.png', rel_path)) # quit pymol.cmd.quit()
def loadPymol(): sys.path.append('/share/apps/pymol/1.6.0.0/lib/python') import __main__ __main__.pymol_argv = [ 'pymol', '-c'] # Quiet and no GUI import pymol pymol.finish_launching() cmd = pymol.cmd util = pymol.util return cmd, util
def launchPyMol(self, pdbfile): """Open pdb in PyMOL""" import pymol # Call the function below before using any PyMOL modules. pymol.finish_launching() from pymol import cmd cmd.load(pdbfile) cmd.show_as('sticks') return
def startPyMOL(pdb): '''starts PyMOL for us. Only for testing. PyMOL should already be opened by InteractiveROSETTA''' import __main__ __main__.pymol_argv = ["pymol", "-qhxi"] import pymol pymol.finish_launching() pymol.cmd.load(pdb) pymol.cmd.show_as('cartoon') pymol.cmd.color('purple') return pymol
def renamechain(pdbfile,chainbefore,chainafter): dirname=os.getcwd()+'/interface_analyzer/'+pdbfile pdbfileselect=pdbfile.split('.') print "rename the chain name of pdb i order to make antibody'chain is H ro L" pymol.finish_launching() pymol.cmd.load(dirname) pymol.cmd.alter((chainbefore),chain=chainafter) pymol.cmd.save(dirname,((pdbfileselect[0]))) pymol.cmd.delete('all') pymol.cmd.quit() print "rename name of chain has been done"
def setup_pymol(): """Sets up PyMOL for making animations.""" pymol.finish_launching() # Prevent threading errors # Configure global settings cmd.set('scene_buttons', 1) cmd.set('matrix_mode', 1) cmd.set('movie_panel', 1) # Configure quality settings cmd.mset("1 x500") cmd.set('ray_trace_frames', 1) cmd.viewport(800, 800)
def removesolvent(pdbfile): dirname=os.getcwd()+'/interface_analyzer/pdbdata/'+pdbfile pdbfileselect=pdbfile.split('.') print "remove solvent for pdb" pymol.finish_launching() pymol.cmd.load(dirname) pymol.cmd.remove('solvent') pymol.cmd.select('target',pdbfileselect[0]) pymol.cmd.save(dirname,(('target'))) pymol.cmd.delete('all') pymol.cmd.quit() print "remove solvent done"
def InitPymol(): ''' setup pymol so that it works right and plays nice with this program ''' import pymol pymol.pymol_argv = ['pymol', '-q'] #c=command line (no gui), q=quiet (no messages) pymol.finish_launching() from pymol import cmd for switchon in ['retain_order','pdb_no_end_record','cartoon_cylindrical_helices']: #'pdb_retain_ids', cmd.set(switchon, 1) for switchoff in ['pdb_use_ter_records']: cmd.set(switchoff, 0) cmd.show_as('cartoon')
def __init__(self, load_coords_pymol): # mp.Process.__init__(self) # self.conn = conn # import pymol print "finishing launching pymol" pymol.finish_launching() # must do this before anything else print "done launching pymol" self.load_coords_pymol = load_coords_pymol self.oname1 = "molecule1" # name of the object self.oname2 = "molecule2" # name of the object
def removechainHL(pdbfile): dirname=os.getcwd()+'/interface_analyzer/'+pdbfile pdbfileselect=pdbfile.split('.') savefile=os.getcwd()+'/interface_analyzer/'+pdbfileselect[0]+'_antigen.pdb' print "remove antibody of complex,so can caculate the value of antigen sasa " pymol.finish_launching() pymol.cmd.load(dirname) pymol.cmd.remove('hydrogens') pymol.cmd.remove('solvent') pymol.cmd.remove('chain L+H') pymol.cmd.select('target',pdbfileselect[0]) pymol.cmd.save(savefile,(('target'))) pymol.cmd.delete('all') pymol.cmd.quit() print "remove the antibody of complex have done" return savefile
def auto_pymol(pdb_list): import time import pymol import sys pymol_argv = ['pymol', '-qc'] OutDir = "./png/" num_lines = len(pdb_list) print "No. of pdbs: ",num_lines for i in xrange(num_lines): pdb_name = pdb_list[i].split("/")[-1].split(".")[0] print "pdb name which will be oriented: ", pdb_name ## opening pymol pymol.finish_launching() pymol.cmd.load(pdb_list[i]) pymol.cmd.enable(pdb_list[i]) ##Arrange conformation pymol.cmd.hide('lines', pdb_name) # lines pymol.cmd.show('cartoon', pdb_name) # cartoon #pymol.cmd.hide('lines', pdb_name[0]) # lines #pymol.cmd.show('cartoon', pdb_name[0]) # cartoon pymol.cmd.util.chainbow(pdb_name) # rainbow #pymol.cmd.util.cbac(pdb[0]) #pymol.cmd.util.cbc('all') # each chain coloerd pymol.cmd.orient(pdb_name) #pymol.cmd.orient(pdb_name[0]) #pymol.cmd.set("ray_opaque_background","off") #pymol.cmd.bg_color(color="white") #pymol.cmd.do("run ") #pymol.cmd.ray(0,0) ##Make png fig #time.sleep(1) #out_png = OutDir+pdb_name+".png" #pymol.cmd.png(out_png) #pymol.cmd.do('png ' + out_png) ## End pymol pymol.cmd.refresh()
def main(argv=sys.argv): logging.getLogger().setLevel(logging.INFO) args = _arguments() score_file_path = os.path.abspath(args.score_file) model_dir = os.path.dirname(score_file_path) target_dir, base_dir_name = os.path.split(os.path.abspath(os.path.join(model_dir, '..'))) target_dir_name = os.path.basename(target_dir) field_dict_list = _read_scorefile(score_file_path) # plot gdt vs. energy field_dict_list.sort(key=lambda d: float(d["score"])) # smaller score better energy_gdt_list = [(float(d["score"]), float(d["gdtmm_full"])) for d in field_dict_list] energy_list, gdt_list = zip(*energy_gdt_list) plt.plot(gdt_list[:5], energy_list[:5], 'ro') # 5 best in red plt.plot(gdt_list[5:], energy_list[5:], 'ko') # else in black #plt.title("title") plt.xlabel("GDT_mm") plt.ylabel("energy") plt.axis(xmin=0, xmax=1) fname = os.path.join(os.getcwd(), target_dir_name+'_'+base_dir_name+'_energy_gdt.png') plt.savefig(fname) #plt.show() # args for PymolLauncher gdts, scores, pdbs = gdt_list, energy_list, [d["description"] for d in field_dict_list] """ Code that links the data to the PymolLauncher Object Uncomment this if you have edited this file and are ready to link the PymolLauncher to the scatter plot""" pl1 = PymolLauncher(gdts, scores, pdbs) pl1.set_native(args.native_pdb) pdb_dir = model_dir print('pdb_dir: '+pdb_dir) pl1.set_pdb_dir(pdb_dir) connect('button_press_event', pl1) gca().set_autoscale_on(False) import pymol pymol.finish_launching() #from pymol import cmd pl1.select_best() show() print("DONE!")
def create_pymol_movie(): """create pymol movie """ from glob import glob import pymol file_list = glob("refinement*.pdb") pymol.finish_launching() pymol.cmd.bg_color('white') for i,fn in enumerate(file_list): # pymol.cmd.load(fn,"mov",state=i) # pymol.cmd.load('full_asu.pdb',"mov",state=i) pymol.cmd.load(fn) pymol.cmd.load('full_asu.pdb') pymol.cmd.frame(1) pymol.cmd.mview('store') # pymol.cmd.mset("1 -%d"%len(file_list))
def view(self, name=None): tmp = copy.deepcopy(self) if qtk.imported('pymol'): qtk.report("Molecule", "initializing pymol...", color=None) import pymol pymol.finish_launching() else: pymol.cmd.reinitialize() sleep(0.5) if name: tmp_file = name + "_tmp_" + str(Molecule.mol_id) + '.xyz' else: tmp_file = 'pymol_tmp_' + str(Molecule.mol_id) + '.xyz' Molecule.mol_id = Molecule.mol_id + 1 tmp.write_xyz(tmp_file) pymol.cmd.load(tmp_file) os.remove(tmp_file)
def __init__(self, pdb, pdbpath, fastaSequences, interactionRadius=4.5, surfMethod='mmtk', surfaceArea=2.5, solventRadius=1.4, pointDensity=1026, logger=logging.getLogger()): """ Creates a new PPIBitstrings instance. Processes the pdb, calculates the surface residues, the distance matrix and the bitstrings for the surface residues. Args: pdb: A BioPython structure object fastaSequences: Sequences as returned by PPI.extractSequenceFromPDBFile(pdbfile) interactionRadius: Interaction radius used for PPI/NPPI determination (default: 4.5) surfMethod: The method used to calculate the surface residues. Can be mmtk or pymol (default: mmtk) surfaceArea: Minimum surface area required to be treated as surface residue (default: 2.5) solventRadius: Solvent radius used by MMTK (default: 1.4) pointDensity: Point density used by MMTK (default: 1026) logger: Logging instance to use as logger (default: logging.getLogger()) """ self._df = None self._distMatrix = None self._peptideChains = None self._phosphateChains = None self._logger = logger if surfMethod == 'pymol': surfFunc = self._getSurfaceResiduesPyMOL logger.info('Loading PyMol') import pymol pymol.finish_launching() self._cmd = pymol.cmd self._stored = pymol.stored else: surfFunc = self._getSurfaceResiduesMMTK self._pdbpath = pdbpath self._interactionRadius = interactionRadius self._surfaceArea = surfaceArea self._solventRadius = solventRadius self._pointDensity = pointDensity self._pdb = pdb self._periodicTable = Chem.GetPeriodicTable() self._sequences = fastaSequences self._processPDB() self._logger.info('Using %s for surface calculation' % surfMethod) self._surfaceResidues = surfFunc() self._calcDistMatrix() self._calcNeighbours()
def build_images(methods, path_execution): """ Build images from PDB files using PyMol package. @type self: koala.CalculateGDTTS.CalculateGDTTS """ import __main__ __main__.pymol_argv = ['pymol', '-qc'] import pymol __main__.pymol = pymol pymol.finish_launching() try: os.chdir(path_execution) limit = 20 if len(methods) < 20: limit = len(methods) for i in range(0, limit): pdb = methods[i] arq = os.path.join(path_execution, pdb) name, ext = os.path.splitext(pdb) # Load Structures pymol.cmd.load(arq, pdb) pymol.cmd.disable("all") pymol.cmd.set('ray_opaque_background', 0) pymol.cmd.set('antialias', 1) pymol.cmd.hide("everything") pymol.cmd.show("cartoon") pymol.cmd.show("ribbon") pymol.cmd.enable(pdb) pymol.cmd.ray() pymol.cmd.png("%s.png" % name, dpi=300) sleep(0.25) # (in seconds) pymol.cmd.reinitialize() except Exception, e: show_error_message("Erro on build_images method:\n%s" % e)
def __initialize_pymol(self): #Si no estamos depurando, hacemos comprobaciones y ajustes de resolución y orientación de pantalla if not self.debug: #Se comprueba que la resolución actual sea 1920 X 1080 en caso contrario se imprime un mensaje y el programa termina (la visualización no funciona bien si el Oculus no trabaja a esta resolución) if GetSystemMetrics(0) != 1920 or GetSystemMetrics(1) != 1080: print("La resolución actual no es compatible, debe trabajarse con 1920 X 1080") exit(1) #Se rota la pantalla a la izquierda (el Oculus trabaja en una orientación portrait) #rotate_screen('left') #Se inicializa PyMOL pymol.finish_launching() #Se activa el modo estéreo con wall-eye pymol.cmd.set('stereo_mode',3) pymol.cmd.stereo() #Se desactiva la interfaz interna para tener una vista limpia en el Oculus pymol.cmd.set('internal_gui',0) #Si no estamos depurando, lanzamos PyMOL a máxima resolución en pantalla completa if not self.debug: pymol.cmd.viewport(1920,1080) pymol.cmd.full_screen('on')
def pymol_mutate(file_name, chain, res_index, number): pymol.finish_launching() cmd.delete(file_name[:-4]) selection = chain + '/' + res_index + '/' mutant = 'CYS' cmd.wizard("mutagenesis") pdb = file_name[:-4] cmd.load(file_name) cmd.refresh_wizard() cmd.get_wizard().set_mode(mutant) cmd.get_wizard().do_select(selection) nStates = cmd.count_states("mutation") for i in range(1, nStates + 1): cmd.get_wizard().do_select(selection) cmd.frame(i) cmd.get_wizard().apply() cmd.save("rec_" + str(res_index) + "_" + str(i) + ".pdb") cmd.set_wizard() cmd.remove(file_name[:-4])
def searchDatabase(): ch1 = input("1)Search by PDB ID\n2)Search by Organism") if ch1 == 1: id = raw_input("Enter PDBID") # sql = "SELECT * FROM Proteins WHERE accessid='%s'" % (id) # if cur.execute(sql)== 0: # for row in cur.fetchall(): # print row # file1=row[1]+".pdb" # else: sql = "SELECT * FROM Proteins WHERE PDBID='%s'" % (id) file1 = id + ".pdb" # print "\n\n\n" # subprocess.Popen('menu-func.py',shell=True) hyperlink = "http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId=" + id print hyperlink pymol.finish_launching() pymol.cmd.load(file1) # urllib.urlretrieve (hyperlink, file1) print "1)Perform functions on your PDB ." ch = raw_input("Give your choice!") if ch == 1: execfile("test2.py") if ch1 == 2: orgname = raw_input("Enter Organism Name") sql = "SELECT * FROM Proteins WHERE orgname='%s'" % (orgname) cur.execute(sql) for row in cur.fetchall(): print row file1 = row[1] + ".pdb" # print file1 # hyperlink="http://www.rcsb.org/pdb/download/downloadFile.do?fileFormat=pdb&compression=NO&structureId="+row[1] # urllib.urlretrieve (hyperlink, file1) pymol.finish_launching() pymol.cmd.load(file1)
def main(): from argparse import ArgumentParser from sys import argv parser = ArgumentParser( description="Open and display a WORDOM PSN and cross correlation " + "analysis as an correlated interaction Allosteric " + "Communication Graph (ciACG) in PyMOL.") parser.add_argument( "-c", nargs='*', default=[0.0], metavar="float", help="Cutoff to use for showing connections in graph, provide" + " white space separated list for a series of cutoffs." ", default=0.0") parser.add_argument("-avg", nargs=1, metavar="AVGfile", help="Wordom PSN avg file") parser.add_argument("-cor", nargs=1, metavar="CORRfile", help="Wordom cross-correlation file") parser.add_argument("-pdb", nargs=1, metavar="PDBfile", help="PDB file to draw") parser.add_argument("-plot", action="store_true", default=False, help="Plot ciACG value distribution") parser.add_argument("-acg", nargs=1, default=[None], metavar="ACGOUTfile", help="ACG file to write (.frm)") parser.add_argument("-rmp", nargs=1, default=[None], metavar="RESOUTfile", help="ResidueMap output file to write (.rmp)") arguments = parser.parse_args(argv[1:]) # Finish pymol launch pymol.finish_launching(['pymol']) # Set variables here pdb = arguments.pdb[0] avg = arguments.avg[0] cor = arguments.cor[0] cutoffs = [float(c) for c in arguments.c] ciplot = arguments.plot acgout = arguments.acg[0] rmpout = arguments.rmp[0] interactions = {} with open(avg, 'r') as infile: residuemap = read_avg_residuemap(infile) mapping = Map([int(i.split(':')[-1][1:]) for i in residuemap.keys()], inverse_sequence=list(range(len(residuemap)))) infile.seek(0) interactions, frequencies = read_avg_strength(infile) strength_table = dataframe_from_dictionary(interactions, indexmap=residuemap) with open(cor, 'r') as infile: correlation_table = read_correlations(infile) cigraph_table = strength_table.multiply(correlation_table, fill_value=0.0) dump_pyobject(cigraph_table, acgout, suffix="frm") # if acgout is not None: # outfilename = acgout # # Add proper file ending if not present # if acgout.split('.')[-1] != "frm": # outfilename += ".frm" # with open(outfilename, 'wb') as output: # dump(cigraph_table, output, HIGHEST_PROTOCOL) dump_pyobject(residuemap, rmpout, suffix="rmp") # if rmpout is not None: # outfilename = rmpout # # Add proper file ending if not present # if rmpout.split('.')[-1] != "rmp": # outfilename += ".rmp" # with open(outfilename, 'wb') as output: # dump(residuemap, output, HIGHEST_PROTOCOL) cigraph = matrix_from_pandas_dataframe(cigraph_table) if ciplot: plt.figure() df = DataFrame( {'a': cigraph.reshape(cigraph.shape[0] * cigraph.shape[1])}, columns=['a']) df.plot.hist(stacked=True) plt.show() cmd.load(pdb) cmd.hide("everything") cmd.show("ribbon") # Create bindings and selections, and color them levels = [] for cutoff in cutoffs: residues = bond_connections_from_array(cigraph, residuemap, cutoff=cutoff) levels.append(residues) selections = select_clusters(levels) colors = color_selections(selections) # Show clusters show_cluster(levels)
def start(): pymol.finish_launching()
def get_seq(file_name, chain): pymol.finish_launching() cmd.delete('all') cmd.load(file_name) cmd.select('seq_chain', 'chain ' + chain) return cmd.get_fastastr('seq_chain')
def initialize_pymol(options): """Initializes PyMOL""" import pymol # Pass standard arguments of function to prevent PyMOL from printing out PDB headers (workaround) pymol.finish_launching(args=['pymol', options, '-K']) pymol.cmd.reinitialize()
import FindPyMol import sys import AtomScripts import DockingBox import FindSASA try: from pymol import finish_launching, cmd, selector, stored import pymol2 import numpy as np except ImportError: FindPyMol.pymol_not_found() sys.exit() if __name__ == '__main__': finish_launching(['pymol', '-q']) # open pymol in quiet mode pdbCode = AtomScripts.fetch_pdb('1azm') AtomScripts.select_user_selection('organic', 'ligand') centerPointLigand = AtomScripts.generate_center_point('ligand') myBox = DockingBox.Box(x_buff=6.5, y_buff=6.5, z_buff=6.5, center_point=centerPointLigand) myBox.get_residues_inside() atoms = AtomScripts.get_atoms() FindSASA.combo(atoms, myBox, threshold=5)
def calc_rmsd_pymol(pdb1, pdb2, method): """Calculate rmsd using PyMOL. Two methods are available: align and fit See: - Align: <http://www.pymolwiki.org/index.php/Align> - Fit: <http://www.pymolwiki.org/index.php/Fit> Align can return a list with 7 items: - RMSD after refinement - Number of aligned atoms after refinement - Number of refinement cycles - RMSD before refinement - Number of aligned atoms before refinement - Raw alignment score - Number of residues aligned in this version of function, the function returns `RMSD before refinement`. Install on OSX: ``brew install brewsci/bio/pymol`` or get If you have a problem:: Match-Error: unable to open matrix file '/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/data/pymol/matrices/BLOSUM62'. then find BLOSUM62, e.g.:: mdfind -name BLOSUM62 | grep pymol /Users/magnus/miniconda2/envs/py37/lib/python3.7/site-packages/pymol/pymol_path/data/pymol/matrices/BLOSUM62 /usr/local/Cellar/pymol/2.4.0_3/libexec/lib/python3.9/site-packages/pymol/pymol_path/data/pymol/matrices/BLOSUM62 /Users/magnus/miniconda2/pkgs/pymol-2.4.2-py37h06d7bae_0/share/pymol/data/pymol/matrices/BLOSUM62 /Users/magnus/work/opt/pymol-open-source/data/pymol/matrices/BLOSUM62 and then define ``PYMOL_DATA`` in your .bashrc/.zshrc, e.g.:: export PYMOL_DATA="/Users/magnus/work/opt/pymol-open-source/data/pymol" """ try: import __main__ __main__.pymol_argv = ['pymol', '-qc'] import pymol # import cmd, finish_launching pymol.finish_launching() except ImportError: print('calc_rmsd_pymol: you need to have installed PyMOL') sys.exit(0) # no error pymol.cmd.reinitialize() pymol.cmd.delete('all') pymol.cmd.load(pdb1, 's1') pymol.cmd.load(pdb2, 's2') if method == 'align': # experiments with align <https://pymolwiki.org/index.php/Align> # quiet = 0/1: suppress output {default: 0 in command mode, 1 in API} # (4.130036354064941, 60, 3, 4.813207626342773, 64, 30.0, 3) values = pymol.cmd.align('s1', 's2', quiet=1, object='aln') return values[0], values[3] # (,#0) #, pymol.cmd.align('s1','s2')[4]) #raw_aln = pymol.cmd.get_raw_alignment('aln') #print raw_aln #for idx1, idx2 in raw_aln: # print '%s`%d -> %s`%d' % tuple(idx1 + idx2) #pymol.cmd.save('aln.aln', 'aln') if method == 'fit': return (pymol.cmd.fit('s1', 's2'), 'fit')
from os.path import join import tempfile import zipfile from pymol import cmd, finish_launching from pymol.cgo import * finish_launching() dirpath = None def cgo_arrow(atom1='pk1', atom2='pk2', radius=0.07, gap=0.0, hlength=-1, hradius=-1, color='blue red', name=''): from chempy import cpv radius, gap = float(radius), float(gap) hlength, hradius = float(hlength), float(hradius) try: color1, color2 = color.split() except: color1 = color2 = color color1 = list(cmd.get_color_tuple(color1)) color2 = list(cmd.get_color_tuple(color2)) def get_coord(v):
def main(*args, **kwargs): parser = argparse.ArgumentParser(prog='mt_pymol') parser.add_argument( dest='struct', type=valid_str, help='gro or similar file containing a martini structure') parser.add_argument(dest='topol', type=valid_top, default=None, nargs='?', help='top or tpr file with the topology of the system') parser.add_argument( dest='traj', type=valid_traj, default=None, nargs='*', help='corresponding trajectory file. If multiple files are given, ' 'they are concatenated') parser.add_argument( '-s', '--skip', dest='skip', type=int, default=1, help='when loading a trajectory, load frames with this rate') parser.add_argument('-g', '--gmx', dest='gmx', type=str, default=None, help='path to the gromacs executable') parser.add_argument( '--keepwater', dest='keepwater', action='store_true', help='do not delete waters from the system. Decreases performance') # TODO: add more options (load_traj start/end...) # TODO: passing arguments to pymol args = parser.parse_args() # check if there's enough memory to load the requested traj and warn the user if needed if args.traj: freemem = psutil.virtual_memory().available traj_size = 0 for traj in args.traj: traj_size += os.path.getsize(clean_path(traj)) water_ratio = 1 if not args.keepwater: # TODO: VERY arbitrary number. When garnish's parsing is a module, use that! # EDIT: I will probably leave it like this. Unnecessary and complex to use parse_tpr water_ratio = 1 / 2 # check if there's enough free memory: 5 is based on some testing if freemem < 5 * (traj_size / args.skip): ok = False inp = input( 'WARNING: You may not have enough free memory to open this big trajectory.\n' 'Consider using the trajectory options (-s, ...).\n' 'Otherwise, continue at your own risk ;) [y/N] ') while not ok: if inp.lower() in ['yes', 'y']: ok = True elif inp.lower() in ['no', 'n']: parser.print_help() exit(0) else: print(f'"{inp}" is not a valid choice. [y/N]') # initialize pymol __main__.pymol_argv = ['pymol'] pymol.finish_launching() # run pymolrc and load all the mtools config.pymolrc() mt_nice.load() mt_supercell.load() mt_movie.load() # load garnish garnish.extend_garnish() cmd.sync() # open the structure cmd.load(clean_path(args.struct)) cmd.sync() # get the loaded object's name, so we can load the traj into it as new states sys_obj = cmd.get_object_list()[0] # load trajectories if args.traj: config.trajectory() for traj in args.traj: cmd.sync() cmd.load_traj(clean_path(traj), sys_obj, interval=args.skip) cmd.sync() # TODO: "selection" in load_traj seems not to work as planned. Can we get it to work? # Other option: call trjconv to get rid of the waters before loading # delete waters, unless they are needed if not args.keepwater: cmd.remove('resname W or resname WN') cmd.sync() # run garnish with as many arguments as we got garnish_args = [] if args.topol: garnish_args.append(clean_path(args.topol)) if args.gmx: garnish_args.append(f'gmx={args.gmx}') garnish_args = ', '.join(garnish_args) cmd.do(f'garnish {garnish_args}') cmd.sync() # run mt_nice with the `clean` setting cmd.do(f'mt_nice not *_elastics') cmd.sync() # print some help after everything is loaded mt_help = ''' Martini Tools functions: - garnish - mt_nice, mt_sele, mt_color - mt_supercell - mt_movie ''' cmd.sync() print(mt_help)
# Tell PyMOL we don't want any GUI features and # that we don't even want the command line. import pymol # THIS DOES NOT WORK ON macOS pymol.finish_launching(['pymol', '-qxif', '0'])
def initiate(): import __main__ __main__.pymol_argv = ['pymol', '-qc'] py.finish_launching() py.cmd.set('group_auto_mode', 2)
def init_pymol(): print("\nInitialising pymol...\n") pymol.finish_launching(['pymol', '-nqc']) pymol.cmd.reinitialize() return np.array([float(x), float(y), float(z)])
if args.open_tolerances: args.rmsd = 100 args.length = 10000 args.clash_percentage = 100 args.loop_percentage = 100 print 'tolerances have been set to maximum' # start pymol if appropriate if args.visualize: print 'importing pymol...' sys.path.append( '/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/' ) import pymol silence = pymol.finish_launching() silence = pymol.cmd.do( 'run ~/Desktop/PyRosetta/PyMOLPyRosettaServer.py') time.sleep(2) if True: #with open( 'thorp-log', 'w') as loggy, open('matching_domains.'+str(time.strftime("%Y%m%d-%H%M%S")), 'w') as matchy: orig_pdb_file = args.ref_pdb # ./path/to/aaaa.pdb orig_pdb_id = orig_pdb_file.split('/')[-1] # aaaa.pdb residue1 = args.ref_res_1 residue2 = args.ref_res_2 # DEBUG OUTPUT #output_string = '\n\n#######################################\n'+ \ # 'This file contains debugging output for thorp.py\n'+ \ # 'invoked at: '+str(time.strftime("%Y/%m/%d %H:%M:%S"))+'\n\n\n'+ \
'--frame_nb', required=True, help='the frame number') parser.add_argument('-i', '--idx_aa', required=True, help='the AA idx in PDB') parser.add_argument('--color_aa', required=False, action='store_true', help='color in red the AA specified by "--idx_aa".') parser.add_argument('pdb_AN', help='the PDB accession number') args = parser.parse_args() # open pymol and retrieve the protein with PDB accession number pymol.finish_launching(['pymol', '-qc']) # Pymol: quiet and no GUI # set the path to download the PDB data # pymol.cmd.set('fetch_path', pymol.cmd.exp_path(fn_arg['pdb_dir']), quiet=1) # print('Fetching PDB accession number: {}'.format(fn_arg['pdb_AN'])) pymol.cmd.load( os.path.join(args.pdb_dir, '{}.cif'.format(args.pdb_AN.lower()))) pymol.cmd.disable('all') pymol.cmd.enable(args.pdb_AN) pymol.stored_list = [] pymol.cmd.iterate('(name ca) and (chain {})'.format(args.chain), 'pymol.stored_list.append((resi, oneletter))') pymol.cmd.hide('all') pymol.cmd.show('cartoon') pymol.cmd.set('ray_opaque_background', 1) if args.color_aa:
def make_pse(pre_smotif,map_route): import pymol pymol.pymol_argv = [ 'pymol', '-qc'] # Quiet and no GUI pymol.finish_launching() # Disable Pymol's output # pymol.cmd.feedback("disable","all","actions") # pymol.cmd.feedback("disable","all","results") # pymol.cmd.feedback("disable","all","errors") topin=open("top_"+str(pre_smotif[0])+"_"+str(pre_smotif[1])+".dict",'r') t10=pickle.load(topin) tchi=t10.keys() tchi.sort() # for i in range (len(tchi)): for i in range (0,1): chi=tchi[i] log = t10[chi][2] print log route=map_route['map_route'] sname2='2lf2' spath2='./idealized_2lf2.pdb' pymol.cmd.load(spath2, sname2) for j in range(len(route)-1): print route[j] if j==0: entry=log[route[j][0]] # ['9_8_8', ['strand', 8, 4, 3, 125, 132], ['3fkiK00', 'ARG', '70', 'THR', '77', 'PRO', '83', 'LEU', '111']] dir_name=entry[0] s1_struct=entry[1] cath_smotif=entry[2] sname1=cath_smotif[0] spath1=dir_name+"/"+sname1+".pdb" print spath1 pymol.cmd.load(spath1, sname1) arg2 = "("+cath_smotif[0]+" and name ca and resi "+str(cath_smotif[2])+"-"+str(cath_smotif[4])+")" arg1 = "("+sname2 +" and name ca and resi "+str(s1_struct[4]) +"-"+str(s1_struct[5]) +")" rmsd= pymol.cmd.pair_fit(arg1,arg2) select="not resi "+str(cath_smotif[2])+"-"+str(cath_smotif[4])+"+"+str(cath_smotif[6])+"-"+str(cath_smotif[8])+" in "+sname1 #print rmsd,select pymol.cmd.remove(select) else: index=route[j] # [8, 9, 'left'] if index[2]=='left': entry=log[index[0]] else: entry=log[index[1]] dir_name=entry[0] s1_struct=entry[1] cath_smotif=entry[2] sname1=cath_smotif[0] spath1=dir_name+"/"+sname1+".pdb" obj_name="obj"+str(j) print spath1, obj_name print s1_struct,cath_smotif pymol.cmd.load(spath1, sname1) arg1 = "("+sname1+" and name ca and resi "+str(cath_smotif[2])+"-"+str(cath_smotif[4])+")" arg2 = "("+sname2 +" and name ca and resi "+str(s1_struct[4]) +"-"+str(s1_struct[5]) +")" print arg1 print arg2 rmsd= pymol.cmd.pair_fit(arg1,arg2) select="not resi "+str(cath_smotif[2])+"-"+str(cath_smotif[4])+"+"+str(cath_smotif[6])+"-"+str(cath_smotif[8])+" in "+sname1 #print rmsd,select pymol.cmd.remove(select) hide_select="lines" pymol.cmd.hide(hide_select) pymol.cmd.show("cartoon") save_pse="test"+str(i)+".pse" pymol.cmd.save(save_pse) pymol.cmd.reinitialize()
import __main__ __main__.pymol_argv = [ 'pymol', '-qc'] # Quiet and no GUI import sys, time, os import pymol pymol.finish_launching() ## # Read User Input spath = os.path.abspath(sys.argv[1]) sname = spath.split('/')[-1].split('.')[0] # Load Structures pymol.cmd.load(spath, sname) pymol.cmd.disable("all") pymol.cmd.enable(sname) pymol.cmd.png("my_image.png") # Get out! pymol.cmd.quit()
def __init__(self): self.loacts = ['helping', 'cluster'] self.parser = argparse.ArgumentParser(description="This is measure.py") self.parser.add_argument("act", help="run something main/etc...", choices=self.loacts) self.parser.add_argument("--gbs", help="load the gbest txt files.", nargs="*", default=[], type=str) self.parser.add_argument("--eps", help="The maximum distance between two samples for them to be considered as in the same neighborhood.", default=0.3, type=float) self.parser.add_argument("--minn", help="MIN", default=1, type=int) self.parser.add_argument("--out-dir", help="output directory", type=str, default="cluster") self.parser.add_argument("--no-plot", help="skip the plotting", action="store_true", default=False) self.args = self.parser.parse_args() # pymol environment TODO: only for MacOS, pymol was installed from MacPort self.moddir='/usr/lib64/python2.7/site-packages' self.moddir='/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/' sys.path.insert(0, self.moddir) os.environ['PYMOL_PATH'] = os.path.join(self.moddir, 'pymol/pymol_path') # pymol launching import pymol #pymol.pymol_argv = ['pymol','-qc'] + sys.argv[1:] pymol.pymol_argv = ['pymol','-qc'] pymol.finish_launching() self.cmd = pymol.cmd self.cmd.set("retain_order", 1) self.cmd.set("pdb_retain_ids", 1) #self.cmd.do('print("Hajimaru yo ~♪")') #self.hello("はじまるよ~♪ \n") self.crank = -1 self.cthem = blind10 self.clenf = len(self.cthem) self.curc = "" #current color code self.ylimp = -7777777 self.ylimn = +7777777 """ initialized variables, data structure: index: *gbest_id* #for each gbest result self.labels = [ "gbest_filename", ... ] #gbest filename list self.Hnums = [ [ 1.0, 2.0, 3.0, ... ], #the residue height ... ] self.dbresult = [ *cluster_id*, ... ] self.clusters = { *cluster_id* : { coden : "01", #codename, ordered by lowest energy gbest : [ *gbest_id*, ... ], #list of gbest id englt : [ -100.0, ... ], #list of gbest energy adsit : [ 1, 2, 3, ...], #common adsorption site adslt : [ 1, 2, 3, ...], #all adsorption site list adsle : [ -100.00, ...], #the energy values of each in adslt fpath : "path/to/cluster.pdf" #cluster plotting file elwid : 1, #lowest energy gbest id englw : -900, #loewst energy value engmd : -800 #cluster median energy value }, ... } #Clusters id ordered by lowest energy index: *byenergy_id* self.cs_eid = [ *cluster_id*, ... ] """ self.Hnums = [] self.labels = [] self.clusters = {} self.clusters_byenergy = [] self.parametbar = ["pso50", "pso50-200", "pso100", "pso150", "pso200", "pso250"] self.pp = pprint.PrettyPrinter(indent=2)
import sys import renumber ''' Will be using mixedCaps style ''' os.system('rm -rf pdbFiles') # launch pymol without gui pymol.finish_launching(['pymol', '-c']) t0 = time.time() destfile = "output.csv" cmd.do("run renumber.py") # clistAb1 = ['H', 'L'] # clistAb2 = ['M', 'N'] calphaCutoff = str(round(5)) os.system("mkdir pdbFiles") cmd.load("3_ab_test.mae") fullList=cmd.get_object_list('all') #Making empty lists stored.residues1 = [] stored.residues2 = []
ligand = os.path.abspath(args.lig_file) pdb.set_trace() subprocess.call([obabel, ligand, "-O{}".format(ligand)]) temperature, N = args.temperature, args.num_of_decoys ft_options = glob.glob(os.path.join(DOCKING_RESULTS_PATH,\ dock_jobs[0],'ft.*.*')) ft_coef_opts = [os.path.basename(i).split('.')[1] for i in ft_options] recs_and_mask_info = dict() for ft_coef in ft_coef_opts: case_temp_cont_list = [] for job in dock_jobs: job_path = os.path.join(DOCKING_RESULTS_PATH, job) os.chdir(job_path) print('Process job #' + job + ':') print ('job_path: ', job_path) pymol.finish_launching(["pymol", "-qc"]) #receptor = '../../' +job_complex_dict[job][0] #rec_mask = '../../'+job_complex_dict[job][1] #UNCOMMEND THE FOLLOWING FOR SCC #pdbfiles = glob.glob('*.pdb.gz') if job not in recs_and_mask_info: pdbfiles = glob.glob('*.pdb') recs_and_mask_info[job] = dict() if len(pdbfiles) == 2: # mask file and recpdb inside the path #mask_zipped = [i for i in pdbfiles if 'mask.pdb.gz' in i][0] #rec_mask = mask_zipped[:-3] #pdbfiles.remove(mask_zipped) rec_mask = [i for i in pdbfiles if 'mask.pdb' in i][0] pdbfiles.remove(rec_mask) #rec_zipped, receptor = pdbfiles[0], pdbfiles[0][:-3] receptor = pdbfiles[0]
def generate_hybrid_pymol_viz(self, key='centroid'): import pymol from time import sleep pymol.finish_launching() pymol.cmd.reinitialize() # Set background color to white pymol.cmd.bg_color("white") receptor_file = self.receptor_file_viz pymol.cmd.load(receptor_file, 'receptorFile') pymol.cmd.publication('receptorFile') centroid_data = self.full_data_mdtraj_analysis['reshape'] self.pymol_objects = {} for centroid_data_index in centroid_data: curr_index = centroid_data_index correct_file_pymol_name = 'reshape' + '_{0}'.format(curr_index) correct_topol_filepath = centroid_data[curr_index][ 'correct_topol_filepath'] pymol.cmd.load(correct_topol_filepath, correct_file_pymol_name) pymol.cmd.publication(correct_file_pymol_name) curr_color = 'reshape_cluster_color_{0}'.format( centroid_data_index) pymol.cmd.set_color(curr_color, centroid_data[curr_index]['colorOriginal']) pymol.cmd.color(curr_color, correct_file_pymol_name) self.pymol_objects.update( {centroid_data_index: { 'topol': correct_file_pymol_name }}) centroid_data = self.full_data_mdtraj_analysis['centroid'] for centroid_data_index in centroid_data: curr_index = centroid_data_index simplified_object = centroid_data[curr_index]['simplified_file'] correct_file_pymol_simple_name = 'centroid' + '_simple_{0}'.format( curr_index) pymol.cmd.load(simplified_object, correct_file_pymol_simple_name) pymol.cmd.show_as(representation='dots', selection=correct_file_pymol_simple_name) curr_color = 'centroid_cluster_color_{0}'.format( centroid_data_index) pymol.cmd.set_color(curr_color, centroid_data[curr_index]['colorOriginal']) pymol.cmd.color(curr_color, correct_file_pymol_simple_name) self.pymol_objects.update({ centroid_data_index: { 'simple': correct_file_pymol_simple_name } }) sleep(0.5) test = 1 # in the future # pymol.cmd.cealign() # This works save_state_name = self.receptor_name + '_' + self.molecule_name + '_' + 'hybrid' + '_pymolViz.pse' pymol.cmd.save(save_state_name) sleep(0.5) pymol.cmd.quit()
def launch_pymol(doit, args='-qei'): # pymol doesn't seem to get these args __main__.pymol_argv = ['pymol', args] pymol.finish_launching() doit()
def save_residue(file_name, resi, save_file): pymol.finish_launching() cmd.delete('all') cmd.load(file_name) cmd.select('res', 'resi ' + str(resi)) cmd.save(save_file, 'res')
def __init__(self, struct_names, type="all", grain="allatom"): # The cmd object is equivalent to the PyMol command line, and refers to the # object which has functions corresponding to PyMol's API (poorly documented) # See: https://pymol.org/dokuwiki/doku.php?id=api:cmd:alpha self.cmd = pymol.cmd cmd = pymol.cmd self.stored = pymol.stored stored = pymol.stored # Catches common argument errors assert type in ["aa", "nt", "li", "all"] assert grain in ["allatom", "ca"] # Generates coordinate-generating PyMol Selection if grain is "allatom": self.nt_sel = "resn a+t+c+g+u and !(hetatm)" self.aa_sel = "byres name ca and !(hetatm)" else: self.nt_sel = "name C1' and resn a+t+c+g+u and !(hetatm)'" self.aa_sel = "name ca and !(hetatm)" # Note: This is guaranteed to contain all ligand atoms # TODO: Ask KMT whether or not this is reasonable behaviour self.li_sel = "not((resn a+t+c+g+u) | (byres name ca)) or hetatm" for struct_name in struct_names: actual_name = struct_name.split('/')[-1] print(actual_name) print("> Opening {}".format(struct_name)) # Launches headless PyMol quietly pymol.finish_launching(['pymol', '-qc']) # Opens structure in headless PyMol cmd.load(struct_name) # Assigns default values to amino acid, nucleotide parameters, to # deal with cases in which we don't want to include whole network # data. aa_x, aa_y, aa_z, aa_chains, aa_index, aa_resi, aa_resn = [ tuple([]) ] * 7 nt_x, nt_y, nt_z, nt_chains, nt_index, nt_resi, nt_resn = [ tuple([]) ] * 7 li_x, li_y, li_z, li_chains, li_index, li_resi, li_resn = [ tuple([]) ] * 7 if type in ["aa", "all"]: # Gets Euclidean position, chain name, PyMol index for amino acids aa_xyz, aa_chains, aa_index, aa_resi, aa_resn = self.get_aa_data( ) aa_x, aa_y, aa_z = zip(*aa_xyz) chain_resi = list( map(lambda x: x[0] + str(x[1]), zip(aa_chains, aa_resi))) num_aa = len(set(chain_resi)) print("There are {} amino acids in the network".format(num_aa)) print("There are {} amino acid atoms".format(len( set(aa_index)))) if type in ["nt", "all"]: # Gets Euclidean position, chain name, PyMol index for nucleotides nt_xyz, nt_chains, nt_index, nt_resi, nt_resn = self.get_nt_data( ) nt_x, nt_y, nt_z = zip(*nt_xyz) chain_resi = list( map(lambda x: x[0] + str(x[1]), zip(nt_chains, nt_resi))) num_nt = len(set(chain_resi)) print("There are {} nucleotides in the network".format(num_nt)) print("There are {} nucleotide atoms".format(len( set(nt_index)))) if type in ["li", "all"]: # Gets Euclidean position, chain name, PyMol index for nucleotides li_xyz, li_chains, li_index, li_resi, li_resn = self.get_li_data( ) li_x, li_y, li_z = zip(*li_xyz) chain_resi = list( map(lambda x: x[0] + str(x[1]), zip(li_chains, li_resi))) num_li = len(set(chain_resi)) print("There are {} ligands in the network".format(num_li)) print("There are {} ligand atoms".format(len(set(li_index)))) # Constructs DataFrame from the above PyMol gleaned data df = pd.DataFrame({ 'x': nt_x + aa_x + li_x, 'y': nt_y + aa_y + li_y, 'z': nt_z + aa_z + li_z, 'chain': list(nt_chains) + list(aa_chains) + list(li_chains), 'index': list(nt_index) + list(aa_index) + list(li_index), 'resi': list(nt_resi) + list(aa_resi) + list(li_resi), 'resn': list(nt_resn) + list(aa_resn) + list(li_resn), 'type': ['nucleotide'] * len(nt_x) + ['amino acid'] * len(aa_x) + ['ligand'] * len(li_x) }) print("Writing positional CSV to `data/positions/`") df.to_csv("data/positions/{}.csv".format(actual_name[:-4])) # Deletes the molecule from PyMol, preventing memory issues cmd.delete("all")
def seperate_lig(file_name, mol, chain, output_name): pymol.finish_launching() cmd.delete('all') cmd.load(file_name) cmd.select('lig', 'resn ' + mol + ' and chain ' + chain) cmd.save(output_name, 'lig')
def get_image(ind, pdb_name, mol, chain, res, original=True): data_folder = 'Data/' father_folder = data_folder + 'PNG_' + str(original) + '/' #if not os.path.exists(father_folder): # os.mkdir(father_folder) folder = father_folder + ind + '_' + pdb_name + '/' if not os.path.exists(folder): os.mkdir(folder) ugly_id = 'cand4' true_id = 'cand1' docking_folder = 'RosettaDock/' file_name = docking_folder + ind + '_' + pdb_name + '/rec1.pdb' ugly_rec = docking_folder + ind + '_' + pdb_name + '/rec4.pdb' ugly_name = docking_folder + ind + '_' + pdb_name + '/' + ugly_id + '.mol2' xtal = docking_folder + ind + '_' + pdb_name + '/' + true_id + '.mol2' steps = 3 step_angle = 360.0 / steps pixels = 100 num_rand = 9 #This is done for negative of random rotation in the pocket '''if not original: fake_rotation = [] for _ in range(3): fake_rotation.append(random.random() * 360)''' pymol.finish_launching() cmd.delete('all') if original: cmd.load(file_name, 'protein') else: if not os.path.exists(ugly_rec): os.rmdir(folder) return 0 cmd.load(ugly_rec, 'protein') cmd.load(xtal) #cmd.select('lig', 'resn ' + mol + ' and chain ' + chain + ' and resi ' + res) cmd.select('lig', true_id) obj_name = true_id if not original: if not os.path.exists(ugly_name): os.rmdir(folder) return 0 cmd.load(ugly_name) cmd.select('lig', ugly_id) obj_name = ugly_id delete_hetero('lig') cmd.remove('hydrogen') if cmd.count_atoms('lig') == 0: os.rmdir(folder) return 0 #cmd.select('rec', 'not lig') cmd.select('rec', 'br. lig around 4 and poly') cmd.hide("all") cmd.color('white', 'rec') cmd.color('green', 'lig') cmd.util.cnc("all") cmd.show("sticks", 'lig') #Show H bonds cmd.set('h_bond_cutoff_center', 3.5) cmd.distance('hbonds', 'lig', 'rec', mode=2) cmd.hide('labels') #Show double bonds #cmd.set('valence', 1, obj_name) cmd.orient('lig') cmd.zoom('lig', 3) #Slab move -5 cmd.clip('move', -5) cmd.set('ray_opaque_background', 0) cmd.set('ray_shadows', 0) #This is done for negative of random rotation in the pocket '''if not original: cmd.rotate('x', fake_rotation[0], 'lig') cmd.rotate('y', fake_rotation[1], 'lig') cmd.rotate('z', fake_rotation[2], 'lig')''' #Transperent surface '''cmd.set('surface_carve_cutoff', 4.5) cmd.set('surface_carve_selection', 'lig') cmd.set('surface_carve_normal_cutoff', -0.1) cmd.set('surface_color', 'white') cmd.set('surface_type', 3) cmd.set('transparency', 0.5)''' for show in ['sticks']: #['surface', 'sticks']: #Set transparency # tra = 0 # if show == 'surface': # tra = 0.5 # cmd.set('transparency', tra) cmd.show(show, 'rec') refresh() for x in range(steps): for y in range(steps): refresh() cmd.png(folder + show + '_' + str(x) + '_' + str(y) + '.png', pixels, pixels) refresh() cmd.turn('y', step_angle) refresh() cmd.turn('x', step_angle) refresh() '''for x in range(num_rand): refresh() for ax in ['x', 'y', 'z']: cmd.turn(ax, random.random() * 360) refresh() cmd.png(folder + show + '_' + str(x) + '.png', pixels, pixels) refresh()''' cmd.hide(show, 'rec') refresh() return 1
def Pymol(): '''Visualization program''' #LAUNCH PYMOL readline.parse_and_bind( 'tab: complete' ) # Set up path to pymol environment (in case is not installed) # pymol launching: quiet (-q), without GUI (-c) and with arguments from command line pymol.pymol_argv = ['pymol', '-q'] + sys.argv[1:] pymol.finish_launching() # Read User Input sname = ntpath.basename(PDB_file) # Extract the filename without the path # Dataframe_path = os.path.abspath(sys.argv[2]) # Dataframe generated by LYS.py # Load Structures pymol.cmd.load(PDB_file, sname) pymol.cmd.disable( "all" ) # toggles off the display of all currently visible representations of an object. It is the equivalent of deselecting the object pymol.cmd.enable(sname) def Colour_by_Selection( selection="all", Selected="orange", Not='grey50', Domain='lime', Selected_and_Domain='magenta', ): colors = { 'Selected': Selected, 'Not': Not, 'Domain': Domain, 'Selected_and_Domain': Selected_and_Domain } #BACKGROUND & SHAPES cmd.bg_color('white') cmd.show_as('cartoon', 'all') cmd.color('gray', 'all') #ROTATION cmd.rotate( [0, 1, 0], angle=210, selection="all" ) # Commands to rotate the structures to visualize some specific side of the protein [x,y,z] cmd.rotate([1, 0, 0], angle=-50, selection="all") #-20 for HRT2B #ELIMINATING CHAINS # Eliminating chains in the structure if desired # cmd.select('chainA', 'chain A') # cmd.remove('chain A') #LEGEND ###The text that appears in the image, change placement accordingly cgo = [] axes = [[5.0, 0.0, 0.0], [0.0, 5.0, 0.0], [ 0.0, 0.0, 5.0 ]] # Change the values if the protein does not quite fall into place cyl_text(cgo, plain, [70.0, 50.0, 80.0], '%s' % (sname.split('.')[0]), radius=0.6, color=[0.0, 0.0, 0.0], axes=axes) # x=60 for RIOK2, x=40 and z=60 for ROS1 cyl_text(cgo, plain, [70.0, 40.0, 80.0], 'Positively Selected', radius=0.6, color=[1.0, 0.5, 0.0], axes=axes) cyl_text(cgo, plain, [70.0, 30.0, 80.0], 'Not selected', radius=0.6, color=[0.5, 0.5, 0.5], axes=axes) cyl_text(cgo, plain, [70.0, 20.0, 80.0], 'Functional Domain', radius=0.6, color=[0.5, 1.0, 0.5], axes=axes) cyl_text(cgo, plain, [70.0, 10.0, 80.0], 'Both', radius=0.6, color=[1.0, 0.0, 1.0], axes=axes) cmd.set("cgo_line_radius", 0.03) # 0.03 cmd.load_cgo(cgo, 'txt') #ZOOM cmd.zoom( "all", -5.0 ) # Higher and positive values zoom out, it accepts negative values #READ PREVIOUSLY CREATED DATAFRAME: Data = Wrapper_of_all_functions(PDB_file, Gene, Full_PDB_sequence, M8, List_domains, Gene_file_format, prob, sequence_number, missing_data, print_alignment, chains) #Option A: best alternative Data['PDB_Position'] = Data['PDB_Position'].astype( np.float64) #Need to convert to float to use isfinite Data = Data[np.isfinite( Data['PDB_Position'] )] # Remove the Residues that got 'nan' value in their equivalent positions position_phenotype_dict = Series(Data.Label.values, index=Data.PDB_Position).to_dict() #Option B: Not working sometimes # position_phenotype_dict = Series(Data.Label, index=Data.PDB_Position).to_dict() #suboption B # print(position_phenotype_dict) # from math import isnan # position_phenotype_dict = {k: position_phenotype_dict[k] for k in position_phenotype_dict if not isnan(k)} # position_phenotype_dict= {key: value for key, value in position_phenotype_dict.items() if not str(value) == 'nan'} # Colour the residues in the protein according to their label in the dataframe for key, value in position_phenotype_dict.items(): #print(int(key), value, colors[value]) cmd.color( colors[value], 'resi %s' % int(key) ) # --------->If it does not work (no colour shown) probably it has to do with the Residues ID being wrong ###LABEL if value == 'Selected_and_Domain': #Label the alpha carbon from positions selected and in the domain print(key) #cmd.select('Both','resi %s' % int(key)) #Create a selection #cmd.label('Both and n. CA', '" %s %s" % (resn,resi)') cmd.label('resi %s and n. CA' % int(key), '" %s %s" % (resn,resi)') #cmd.label('resi %s' % int(key), '" %s %s" % (resn,resi)') cmd.extend("Colour_by_Selection", Colour_by_Selection) print("Structure will be at %s" % (os.path.dirname(PDB_file))) Colour_by_Selection(sname) pymol.cmd.png( os.path.dirname(PDB_file) + "/%s_Local_cartoon" % (sname.split('.')[0]))
def get_dude_image(entry, mol, original=True): data_folder = 'Data/' father_folder = data_folder + 'PNG_' + str(original) + '/' if not os.path.exists(father_folder): os.mkdir(father_folder) folder = father_folder + entry + '/' if not os.path.exists(folder): os.mkdir(folder) mol_name = mol[:-5] folder += mol_name + '/' if not os.path.exists(folder): os.mkdir(folder) docking_folder = entry if original: docking_folder += '/actives_Dock/poses/' else: docking_folder += '/decoys_Dock2/poses/' file_name = entry + '/rec.pdb' xtal = docking_folder + mol steps = 3 step_angle = 360.0 / steps pixels = 100 num_rand = 9 pymol.finish_launching() cmd.delete('all') cmd.load(file_name, 'protein') cmd.load(xtal, mol_name) cmd.select('lig', mol_name) obj_name = mol_name delete_hetero('lig') cmd.remove('hydrogen') if cmd.count_atoms('lig') == 0: os.rmdir(folder) return 0 cmd.select('rec', 'br. lig around 4 and poly') cmd.hide("all") cmd.color('white', 'rec') cmd.color('green', 'lig') cmd.util.cnc("all") cmd.show("sticks", 'lig') #Show H bonds cmd.set('h_bond_cutoff_center', 3.5) cmd.distance('hbonds', 'lig', 'rec', mode=2) cmd.hide('labels') #Show double bonds #cmd.set('valence', 1, obj_name) cmd.orient('lig') cmd.zoom('lig', 3) #Slab move -5 cmd.clip('move', -5) cmd.set('ray_opaque_background', 0) cmd.set('ray_shadows', 0) for show in ['sticks']: #['surface', 'sticks']: #Set transparency # tra = 0 # if show == 'surface': # tra = 0.5 # cmd.set('transparency', tra) cmd.show(show, 'rec') refresh() for x in range(steps): for y in range(steps): refresh() cmd.png(folder + show + '_' + str(x) + '_' + str(y) + '.png', pixels, pixels) refresh() cmd.turn('y', step_angle) refresh() cmd.turn('x', step_angle) refresh() cmd.hide(show, 'rec') refresh() return 1
# Tell PyMOL we don't want its external Tcl/Tk GUI. import pymol # Call the function below before using any PyMOL modules. pymol.finish_launching([ 'pymol', '-qx' ])
def get_surface_area(file_name): pymol.finish_launching() cmd.load(file_name) area = cmd.get_area('resi 1') cmd.remove(file_name[:-5]) return area
def matchRdcToSmotif(s1_profile, s2_profile, domain, rdc_data): """ Parse co-ordinate from the cath domain and transfer observed RDCs return an array with atomtype, vector, RDC and scaling factor """ #********************************* # Load in PyMol to parse co-ordinates #********************************* import pymol pymol.pymol_argv = [ 'pymol', '-qc'] # Quiet and no GUI pymol.finish_launching() # Disable Pymol's output pymol.cmd.feedback("disable","all","actions") pymol.cmd.feedback("disable","all","results") pymol.cmd.feedback("disable","all","errors") pdbid=domain[0] # folder="/rsc/tungsten/data2/kala/v3_5_0/cath_sorted/sort_cath_"+pdbid[0]+"/" folder="/scratch/kala/cath_sorted/sort_cath_"+pdbid[0]+"/" fpath=folder+pdbid #print fpath #fpath= '/rsc/tungsten/data2/kala/test_SuperFragments/SuperRDC_frag/2z2iA00' pymol.cmd.load(fpath,pdbid) ss_profiles = [s1_profile, s2_profile] offset = 0 vec_data = [] data_error = False for ss_profile in ss_profiles: # ['helix', 6, 9, 4, 146, 151] ['helix', 23, 4, 1, 156, 178] # ['5gstB02', 'GLU', '90', 'MET', '112', 'ASP', '118', 'LEU', '141'] tprofile_res, tdomain_res = [], [] for i in range(ss_profile[4], ss_profile[5]+1): tprofile_res.append(i) for j in range(int(domain[2+offset]), int(domain[4+offset])+1): tdomain_res.append(j) offset=offset+4 if len(tprofile_res) != len(tdomain_res): data_error = True else: data_error = False for res in tprofile_res: for rdef in rdc_data[res]: # [146, 'N', 145, 'C', -0.763] # [178, 'H', 178, 'N', -6.593] res1, sp1 , res2, sp2, rdc = rdef[0], rdef[1], rdef[2], rdef[3], rdef[4] res1_index = tprofile_res.index(res1) d_res1= tdomain_res[res1_index] try: res2_index = tprofile_res.index(res2) d_res2 = tdomain_res[res2_index] except: if res2 == res1-1: d_res2 = d_res1-1 c1 = pymol.cmd.get_model('('+pdbid+' and name '+sp1+' and resi '+str(d_res1)+' )').get_coord_list() c2 = pymol.cmd.get_model('('+pdbid+' and name '+sp2+' and resi '+str(d_res2)+' )').get_coord_list() if c1 and c2: v1=getVector(c1,c2) vec_gm = getGMR(sp1, sp2) vec_data.append([v1,vec_gm,rdc]) else: continue # check this implementation pymol.cmd.reinitialize() return vec_data, data_error
def findSurfaceResidues(file_name, objSel="(all)", cutoff=2.5, doShow=False, verbose=False, only_cysteine=False): """ findSurfaceResidues finds those residues on the surface of a protein that have at least 'cutoff' exposed A**2 surface area. PARAMS objSel (string) the object or selection in which to find exposed residues DEFAULT: (all) cutoff (float) your cutoff of what is exposed or not. DEFAULT: 2.5 Ang**2 asSel (boolean) make a selection out of the residues found RETURNS (list: (chain, resv ) ) A Python list of residue numbers corresponding to those residues w/more exposure than the cutoff. """ pymol.finish_launching() cmd.delete('all') cmd.load(file_name) tmpObj = "__tmp" #if only_cysteine: # cmd.create( tmpObj, objSel + " and polymer and resn CYS"); #else: cmd.create(tmpObj, objSel + " and polymer") if verbose != False: print("WARNING: I'm setting dot_solvent. You may not care for this.") cmd.set("dot_solvent") cmd.get_area(selection=tmpObj, load_b=1) # threshold on what one considers an "exposed" atom (in A**2): if only_cysteine: cmd.remove(tmpObj + " and not resn CYS") cmd.remove(tmpObj + " and not elem S") cmd.remove(tmpObj + " and CYS/SG and bound_to CYS/SG") cmd.remove(tmpObj + " and b < " + str(cutoff)) cmd.iterate(tmpObj, "b") stored.tmp_dict = {} if only_cysteine: cmd.iterate(tmpObj + " and resn CYS", "stored.tmp_dict[(chain,resv)]=1") else: cmd.iterate(tmpObj, "stored.tmp_dict[(chain,resv)]=1") exposed = stored.tmp_dict.keys() exposed.sort() randstr = str(random.randint(0, 10000)) selName = "exposed_atm_" + randstr if verbose != False: print("Exposed residues are selected in: " + selName) cmd.select(selName, objSel + " in " + tmpObj) selNameRes = "exposed_res_" + randstr cmd.select(selNameRes, "byres " + selName) cmd.delete(tmpObj) exposed = [i[1] for i in exposed] return exposed
def publication_figure(session, pic_file_name, w=5000, h=5000): pymol.finish_launching() cmd.delete('all') cmd.load(session) pnghack(pic_file_name, w, h)
def init_pymol(): import __main__ __main__.pymol_argv = ['pymol', '-qc'] import pymol pymol.finish_launching() return pymol
# Importing the PyMOL module will create the window. import pymol # Call the function below before using any PyMOL modules. pymol.finish_launching()
def get_rec_plus_lig(pdb_id, lig, rec_file, lig_file, new_chain): print('pdb: ' + pdb_id + '\n') print('lig: ' + lig) print('lig_file: ' + lig_file) pymol.finish_launching() cmd.delete('all') sdf = '.sdf' in lig if sdf: with open(lig, 'r') as f: for i in [0, 1]: line = f.readline() if "ChemDraw" in line: return False, lig + ' was produced by ChemDraw. This is probably a mistake, since the .sdf file should be a valid 3D conformation of the molecule in regard to the protein. This file is probably an invalid \"flat\" conformation that was automaticaly generated by ChemDraw, and cannot be used here.' utils.sdf2sdf(lig) cmd.load(lig) lig_sele = lig.split('.')[0] + '_sele' else: lig_sele = 'lig' if '.pdb' in pdb_id: pdb_name = pdb_id.split('.')[0] cmd.load(pdb_id) center_coords_rec(pdb_name) rec_sele = pdb_name + '_sele' else: cmd.fetch(pdb_id) center_coords_rec(pdb_id) rec_sele = 'rec' cmd.remove('not (alt \'\'+A)') stored.list = [] if sdf: cmd.select(lig_sele, lig.split('.')[0]) cmd.select('env', 'poly and br. ' + lig_sele + ' around 5') cmd.iterate('env', "stored.list.append((chain))") chain = list(set(stored.list)) if len(chain) == 0: return False, 'The ligand in ' + lig + ' is not close to any protein chain in its appropriate .pdb file.' if len(chain) >= 2: return False, 'The ligand in ' + lig + ' is close to more than one protein chain in its appropriate .pdb file.' chain = chain[0] else: cmd.iterate('resn ' + lig, "stored.list.append((chain))") chain = list(set(stored.list)) if len(chain) == 0: return False, 'There are no chain assigned to ' + lig + ' in ' + pdb_id + '.' chain = chain[0] if chain == '': chain = "\'\'" print('resn ' + lig + ' and chain ' + chain + '\n') cmd.select(lig_sele, 'resn ' + lig + ' and chain ' + chain) cmd.select('heavy_atoms', lig_sele + ' and not elem H') lig_num_atoms = cmd.count_atoms('heavy_atoms') if lig_num_atoms < 10: return False, 'There are less then 10 heavy atoms in ' + lig + '. This is the lower threshold for the algorithm.' cmd.select(rec_sele, 'poly and chain ' + chain) rec_num_atoms = cmd.count_atoms(rec_sele) if rec_num_atoms == 0: return False, 'There are no residues in ' + pdb_id + ' with the same chain as ' + lig + '.' cmd.alter(rec_sele, 'chain=\'' + new_chain + '\'') cmd.alter(rec_sele, 'q=\'1.00\'') cmd.save(lig_file, lig_sele) cmd.save(rec_file, rec_sele) cif = glob.glob('*.cif') if len(cif) > 0: os.system('rm *.cif') return True, 'Seperation of ' + pdb_id + ' and ' + lig + ' was carried out successfully.'