Esempio n. 1
0
def rtrun(cmd, selection, suffix):
    f = tempfile.NamedTemporaryFile(delete=False)  # True)
    output = os.path.dirname(f.name) + os.sep + selection + '.pdb'
    output2 = os.path.dirname(f.name) + os.sep + selection + '_mut.pdb'
    exe(cmdline)
    print(cmdline)
    cmd.save(output, selection)
Esempio n. 2
0
 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())
Esempio n. 3
0
def save_surface(arg1):
    cmd.disable()
    cmd.enable(arg1)
    cmd.hide("everything", arg1)
    cmd.show("surface", arg1)
    cmd.save("%s.obj" % arg1, arg1)
    cmd.enable()
Esempio n. 4
0
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"
Esempio n. 5
0
 def ForceSaveObject(self, file, objname, objtype):
     
     basepath, filename = os.path.split(file)
     filebasename, fileextname = os.path.splitext(filename)
     
     self.Set_Object_Variables(objtype)
     
     if self.savepath != basepath:
     
         newfile = os.path.join(self.savepath,filebasename + '.pdb')
         
         if os.path.isfile(newfile):
             answer = tkMessageBox.askquestion("Question", 
                                               message=  "An object with that name already exists in your '" + \
                                                         objtype + "' folder. Would you like to overwrite it?",
                                               icon='warning')
             if str(answer) == 'no':
                 return 2
         
         try:
             cmd.save(newfile, objname, state=1)
         except:
             self.DisplayMessage("  ERROR: The file could not be saved in your '" + objtype + "' folder.", 2)
             return 1
         
         self.VarPath.set(newfile)
         
     return 0
Esempio n. 6
0
 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))
Esempio n. 7
0
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")
Esempio n. 8
0
def mutate_atoms(desired_sequence):
    # Acquire the lock once you execute this program
    lock.acquire()
    cmd.reset()
    # Check the length of peptide sequence
    # If the sequence does not match the MHC structure, the program will terminate.
    try:
        if len(desired_sequence) != 9:
            raise AssertionError
    except AssertionError:
        sys.exit(
            "Please input a peptide sequence with exactly 9 residues (in short abbreviation, no space)!"
        )

    # Execute the mutation command based on the PyMOL API.
    # For each round, we construct a new PyMOL object to avoid the problem of different mutation affecting each other.
    cmd.wizard("mutagenesis")
    cmd.load("structures/3pwn_clear_original.pdb")
    new_sequence = translate_sequence(desired_sequence)
    for i in range(len(new_sequence)):
        cmd.refresh_wizard()
        cmd.get_wizard().set_mode(new_sequence[i])
        cmd.get_wizard().do_select("C/%d/" % (i + 1))
        cmd.get_wizard().apply()
    cmd.save("structures/mutated_intermediate/mutated_pmhc_complex.pdb")
    cmd.quit()
    # Release the lock when the program ends
    lock.release()
Esempio n. 9
0
    def reload_system(self, ln: str, smis: oechem.OEMol, old_pdb: str, is_oe_already: bool = False):
        with self.logger("reload_system") as logger:
            logger.log("Loading {} with new smiles {}".format(old_pdb, ln))
            with tempfile.TemporaryDirectory() as dirpath:
                ofs = oechem.oemolostream("{}/newlig.mol2".format(dirpath))
                oechem.OEWriteMolecule(ofs, smis)
                ofs.close()
                cmd.reinitialize()
                cmd.load(old_pdb)
                cmd.remove("not polymer")
                cmd.load("{}/newlig.mol2".format(dirpath), "UNL")
                cmd.alter("UNL", "resn='UNL'")
                cmd.alter("UNL", "chain='A'")
                self.config.pdb_file_name = self.config.tempdir() + "reloaded.pdb"
                cmd.save(self.config.pdb_file_name)
                cmd.save(self.config.tempdir() + "apo.pdb")

                with open(self.config.pdb_file_name, 'r') as f:
                    self.pdb = app.PDBFile(f)
                self.positions, self.topology = self.pdb.getPositions(), self.pdb.getTopology()

                if self.config.explicit and self.config.method == 'amber':
                    self.system, self.topology, self.positions = self.__setup_system_ex_amber(
                        pdbfile=self.config.pdb_file_name)
                elif self.config.explicit:
                    self.system, self.topology, self.positions = self.__setup_system_ex_mm()
                else:
                    self.system, self.topology, self.positions = self.__setup_system_im( pdbfile=self.config.pdb_file_name)

        return self.system
Esempio n. 10
0
def writePdb(sel, prefix=""):
    pdbfn = prefix + sel + ".pdb"
    npdbfn = pdbfn.replace(" or ", "")
    npdbfn = npdbfn.replace(" and ", "")
    npdbfn = npdbfn.translate(None, string.whitespace)
    cmd.save(npdbfn, sel)
    return npdbfn
Esempio n. 11
0
    def test(self):
        cmd.viewport(100, 100)

        # make map
        cmd.fragment('gly', 'm1')
        cmd.set('gaussian_b_floor', 30)
        cmd.set('mesh_width', 5)
        cmd.map_new('map')
        cmd.delete('m1')

        # make mesh 
        cmd.isomesh('mesh', 'map')

        # check mesh presence by color
        meshcolor = 'red'
        cmd.color(meshcolor, 'mesh')
        self.ambientOnly()
        self.assertImageHasColor(meshcolor)

        # continue without map
        cmd.delete('map')

        with testing.mktemp('.pse') as filename:
            cmd.save(filename)

            cmd.delete('*')
            self.assertImageHasNotColor(meshcolor)

            cmd.load(filename)
            self.assertImageHasColor(meshcolor)
Esempio n. 12
0
def torsion_drive(atom1, atom2, atom3, atom4, interval, selection, path, mol_name,):
    """
    This function generates input pdbs of dihedral angles selected of intervals specified with interval
    :param atom1: name of atom 1 of dihedral
    :param atom2: name of atom 2 of dihedral
    :param atom3: name of atom 3 of dihedral
    :param atom4: name of atom 4 of dihedral
    :param interval: int or float (in degrees) of intervals to generate torsion scan for
    :param selection: name of selection for molecule
    :param path: path to where pdb files should be saved
    :param mole_name: name of molecule to append to filenamen
    """

    atom1 = selection + " and name " + atom1
    atom2 = selection + " and name " + atom2
    atom3 = selection + " and name " + atom3
    atom4 = selection + " and name " + atom4
    for angle in range(0, 360 + int(interval), int(interval)):
        try:
            os.makedirs('%s/%i' % (path, angle))
        except OSError as exc:
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise

        cmd.set_dihedral(atom1, atom2, atom3, atom4, angle)
        filename = '%s/%i/%s_%i.pdb' % (path, angle, mol_name, angle)
        cmd.save(filename, selection, 1)
Esempio n. 13
0
    def testMMTFExportEmpty(self):
        with testing.mktemp('.mmtf') as filename:
            cmd.save(filename)
            cmd.load(filename, 'm1')

        self.assertEqual(cmd.count_atoms(), 0)
        self.assertEqual(cmd.get_names(), ['m1'])
Esempio n. 14
0
    def testMMTF(self):
        '''Styled MMTF export/import'''
        S = 0b10            # 1 << 1 spheres
        D = 0b1000000000    # 1 << 9 dots
        B = 2 # blue
        R = 4 # red

        cmd.fragment('gly')
        cmd.color(B)
        cmd.color(R, 'elem C')
        cmd.show_as('spheres')
        cmd.show_as('dots', 'elem C')

        with testing.mktemp('.mmtf') as filename:
            cmd.save(filename)
            cmd.delete('*')
            cmd.load(filename)

        color_list = []
        reps_list = []

        cmd.iterate('*', 'color_list.append(color)', space=locals())
        cmd.iterate('*', 'reps_list.append(reps)', space=locals())

        self.assertEqual(color_list, [B, R, R, B, B, B, B])
        self.assertEqual(reps_list, [S, D, D, S, S, S, S])
Esempio n. 15
0
    def testSaveRef(self, format):
        # for rms_cur (not all formats save all identifiers)
        m = -1
        cmd.set('retain_order')

        cmd.fragment('ala', 'm1')
        cmd.copy('m2', 'm1')
        cmd.copy('m3', 'm1')

        cmd.rotate('y', 90, 'm2')
        cmd.align('m3', 'm2')

        # with ref=m3
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2', ref='m3')
            cmd.load(filename, 'm4')
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm1', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m4', 'm2', matchmaker=m), 1.87, delta=1e-2)

        # without ref
        with testing.mktemp('.' + format) as filename:
            cmd.save(filename, 'm2')
            cmd.load(filename, 'm5')
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm2', matchmaker=m), 0.00, delta=1e-2)
            self.assertAlmostEqual(cmd.rms_cur('m5', 'm1', matchmaker=m), 1.87, delta=1e-2)
Esempio n. 16
0
def builderNanodisc(protein, membrane, scaffold, prefixName, runNumber, x=0, y=0, refine=False):
    """
    builds a MP-nanodisc systems
    scaffold in this case is a double belt of MSP
    """
    # Checking time of builder function execution
    if protein != None:
        print('protein is: ' + protein)
    print('scaffold is: ' + scaffold)
    print('membrane is: ' + membrane)
    empty = False
    if protein is None: empty = True
    if not empty:
        tmp_prot = "tmp_prot" + str(runNumber)
        cmd.copy(tmp_prot, protein)  # store initial
        cmd.translate("[{},{},0]".format(x, y), tmp_prot)
    print("State of empty/not-empty: {}".format(empty))
    # copies to delete later
    tmp_scaffold = "tmp_scaffold" + str(runNumber)
    tmp_memb = "tmp_memb" + str(runNumber)
    tmp_origin = "origin" + str(runNumber)
    cmd.copy(tmp_scaffold, scaffold)  # store initial
    cmd.copy(tmp_memb, membrane)  # store initial

    center(tmp_memb)
    center(tmp_scaffold)
    cmd.pseudoatom(tmp_origin, pos=[0, 0, 0])
    cmd.origin(tmp_origin)
    #outRadius = findAverDist(tmp_scaffold) #doubles time for each run
    outRadius = TMdistCheck(tmp_scaffold, 0.2)
    print("Max distance from origin to scaffold in xy plane: {}".format(outRadius))
    # remove lipids beyond border encased by MSP
    cmd.remove("br. org and {} beyond {} of {}".format(tmp_memb, outRadius, tmp_origin))

    # remove lipids clashing with tmp_protein core
    if not empty:
        avXY = TMdistCheck(tmp_prot, 0.2)
        if avXY == -1: return "bad model"
        minXY = avXY / 2.0
        # remove lipids inside pore
        cmd.remove("br. org and {} within {} of {}".format(tmp_memb, minXY, tmp_origin))
        print("Mean distance if TM cross-section in xy plane: {}".format(avXY))

    if empty:
        cmd.remove("br. org and {} within 0.4 of {} and not hydro".format(tmp_memb, tmp_scaffold))
        s = "empty_{}_{}".format(membrane, scaffold)
    else:
        cmd.remove("br. org and {} within 0.3 of pol. and not hydro".format(tmp_memb))
        s = "{}_{}_{}".format(protein, membrane, scaffold)
    if refine: s += "{}_{}".format(int(x), int(y))
    if prefixName:
        s = "{}{}".format(prefixName, s)
    cmd.create(s, "({},{}, {})".format(protein, tmp_scaffold, tmp_memb))
    cmd.save(s + ".pdb", s)

    cmd.delete(tmp_memb)
    cmd.delete(tmp_scaffold)
    cmd.delete(tmp_prot)
    cmd.delete(tmp_origin)
    return s
Esempio n. 17
0
    def plot(self, outfile):
        ctrl_id, case_id, snp_df_sub = self.score_on_var()
        df = pd.merge(snp_df_sub, self.snps2aa, on='id')

        #pymol.finish_launching()
        cmd.reinitialize()
        cmd.fetch(self.pdb)
        cmd.alter(self.pdb, 'b = 0.5')
        cmd.show_as('cartoon', self.pdb)
        cmd.color('white', self.pdb)

        for i, row in df.iterrows():
            resi = row['structure_position']
            chain = row['chain']
            pheno = row['es']
            selec = 'snp%s' % i
            selec_atom = 'snp_atom%s' % i
            cmd.select(selec,
                       'name ca and resi %s and chain %s' % (resi, chain))
            cmd.create(selec_atom, selec)
            cmd.set("sphere_scale", 0.8)
            cmd.show('sphere', selec_atom)
            cmd.alter(selec_atom, 'b=%s' % pheno)
            cmd.spectrum("b",
                         "blue_white_red",
                         selec_atom,
                         maximum=1.0,
                         minimum=0.0)
        cmd.bg_color("white")
        cmd.zoom()
        cmd.orient()
        cmd.save('%s.pse' % outfile)
        cmd.png('%s.png' % outfile, width=2400, height=2400, dpi=300, ray=1)
Esempio n. 18
0
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")
Esempio n. 19
0
    def testExportStyle(self):
        cmd.fab('ACDEF', 'm1')
        cmd.hide()
        cmd.show('cartoon', 'resi 1-3')
        cmd.show('lines', 'resn CYS')
        cmd.show('sticks', 'resn ASP+PHE')
        cmd.show('spheres', 'resn GLU')
        cmd.set('stick_ball', 1, 'resn PHE')
        cmd.set('stick_ball_ratio', 1.5, 'm1')
        testlabel = 'Hello "World"'
        cmd.label('name SG', repr(testlabel))

        with testing.mktemp('.mae') as filename:
            cmd.save(filename)
            cmd.delete('*')
            cmd.load(filename, 'm2')

        g_labels = []
        cmd.iterate('name SG', 'g_labels.append(label)', space=locals())
        cmd.alter('*', 'b = 1 if s.stick_ball else 0')

        self._assertCountEqual('rep cartoon & guide', 'resi 1-3 & guide')
        self._assertCountEqual('rep lines', 'resn CYS', delta=1)
        self._assertCountEqual('rep sticks', 'resn ASP+PHE')
        self._assertCountEqual('rep spheres', 'resn GLU')
        self._assertCountEqual('b > 0.5', 'resn PHE')
        self.assertTrue(cmd.get_setting_float('stick_ball_ratio', 'm2') > 1.1)
        self.assertEqual(g_labels[0], testlabel)
Esempio n. 20
0
def stride(selection="(all)", exe="stride", raw="", state=-1, quiet=1):
    """
DESCRIPTION

    Secondary structure assignment with STRIDE.
    http://webclu.bio.wzw.tum.de/stride/

SEE ALSO

    dss, dssp
    """
    from subprocess import Popen, PIPE
    import tempfile, os

    state, quiet = int(state), int(quiet)

    ss_map = {"C": "L", "B": "S", "b": "S", "E": "S", "T": "L", "G": "H", "H": "H"}
    tmpfilepdb = tempfile.mktemp(".pdb")
    ss_dict = dict()
    for model in cmd.get_object_list(selection):
        cmd.save(tmpfilepdb, "%s and (%s)" % (model, selection), state)
        try:
            process = Popen([exe, tmpfilepdb], stdout=PIPE)
        except OSError:
            print "Error: Cannot execute exe=" + exe
            raise CmdException
        for line in process.stdout:
            if not line.startswith("ASG"):
                continue
            chain = line[9].strip("-")
            resi = line[11:16].strip()
            ss = line[24]
            ss_dict[model, chain, resi] = ss
    os.remove(tmpfilepdb)
    _common_ss_alter(selection, ss_dict, ss_map, raw)
Esempio n. 21
0
def get_group_env(file_name, group, output_name):
    pymol.finish_launching()
    cmd.delete('all')
    cmd.load(file_name)
    cmd.load(group)
    cmd.select('group_env', 'br. ' + group.split('.')[0] + ' around 4 and poly')
    cmd.save(output_name, 'group_env')
def sav_tmp():
    from shutil import copyfile
    import datetime
    try:
        TMP_FOLDER + ' '
    except:
        print(
            "Error: Set up TMP_FOLDER in your ~/.pymolrc, e.g. TMP_FOLDER = '/home/magnus/Desktop/PyMOL/'"
        )
        return

    try:
        os.mkdir(TMP_FOLDER)
    except:
        pass

    date = datetime.datetime.today().strftime('%Y-%m-%d.%S')
    try:
        fn = TMP_FOLDER + os.sep + id + '_' + date + '.pse'
    except TypeError:
        fn = TMP_FOLDER + os.sep + '_' + date + '.pse'
    cmd.save(fn)
    print('Save...' + fn)
    cmd.save(fn.replace('.pse', '.png'))
    copyfile(fn, TMP_FOLDER + '/last.pse')
Esempio n. 23
0
def pymol_mutate(file_name, chain, res_index):
    pymol.finish_launching()
    cmd.delete('all')
    selection = chain + '/' + res_index + '/'
    mutant = 'CYS'
    cmd.wizard("mutagenesis")
    pdb = file_name[:-4]
    cmd.load(file_name)
    cmd.remove('not (alt ''+A)')

    cmd.select('mut', 'resi ' + res_index + ' and chain ' + chain)
    if cmd.count_atoms('mut') == 0:
        return False

    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])
    return True
Esempio n. 24
0
    def test(self):
        cmd.viewport(100, 100)

        # make map
        cmd.fragment('gly', 'm1')
        cmd.set('gaussian_b_floor', 30)
        cmd.set('mesh_width', 5)
        cmd.map_new('map')
        cmd.delete('m1')

        # make mesh
        cmd.isomesh('mesh', 'map')

        # check mesh presence by color
        meshcolor = 'red'
        cmd.color(meshcolor, 'mesh')
        self.ambientOnly()
        self.assertImageHasColor(meshcolor)

        # continue without map
        cmd.delete('map')

        with testing.mktemp('.pse') as filename:
            cmd.save(filename)

            cmd.delete('*')
            self.assertImageHasNotColor(meshcolor)

            cmd.load(filename)
            self.assertImageHasColor(meshcolor)
def interface_area(rec_file, lig_file):
    cmd.set('dot_solvent', 1)
    cmd.set('dot_density', 3)

    #==============================================================================
    # rec_file = sys.argv[1]
    # lig_file = sys.argv[2]
    #
    #==============================================================================

    #==============================================================================
    #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')
    cmd.load(lig_file)
    lig_area = cmd.get_area('lig.2')
    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
Esempio n. 26
0
def crysolRefinementNanodisc(z_min, z_max, z_step, \
                              protName, membName, scafName, dataName, prefixName):
    '''Refine the membrane protein detergent complex against experimental data'''
    zs = np.arange(z_min, z_max, z_step)
    res = {"angle": -9999, "number-of-scaffolds": -9999, "chi2": 9999}
    with tempdir.TemporaryDirectory() as tmpdir:
        # copy data file
        tmpdir.copy_in(dataName)
        best = ""
        fitBest = ""

        for counter1, z in enumerate(zs):
            cmd.refresh()
            modelName = builderNanodisc(protName, membName, scafName,
                                        prefixName, z, True)
            cmd.save(modelName + ".pdb", modelName)
            fit, fitResult = fitcrysol(modelName, dataName, "yes", False)
            cmd.wizard(
                "message", f"Refinement: {counter1 } out of {len(zs)} steps."
                f"Chi2: {fitResult['chi2']}")
            # if model fits better - store it
            if float(fitResult['chi2']) < float(res['chi2']):
                if best != "": cmd.delete(best)
                res['chi2'] = fitResult['chi2']
                res['vertical-offset'] = z
                best = modelName
                fitBest = fit
            else:
                cmd.delete(modelName)
        tmpdir.move_out(best + ".pdb")
        tmpdir.move_out(fitBest)
    print(f"Best model: Vertical Offset : {res['vertical-offset']}")
    print(f"Chi^2 : {res['chi2']} Best model name : {best}")
    return best, fitBest
Esempio n. 27
0
def writeKeyViewFile(filename):
    global views
    global frames
    global scenes
    global actions
    global settings
    global models
    global fades

    keyviewfile = open(filename + ".key", "w")
    for i, view in enumerate(views):
        keyviewfile.write("VIEW: %4d " % i)
        for v in view:
            keyviewfile.write(str(v) + " ")
        keyviewfile.write("\n")
        keyviewfile.write("FRAMES: %d\n" % frames[i])
        if i in actions:
            keyviewfile.write("ACTIONS: %s\n" % actions[i])
        if i in scenes:
            keyviewfile.write("SCENES: %s\n" % scenes[i])
        if i in models:
            keyviewfile.write("MODELS: %s\n" % models[i])
        if i in settings:
            settingName, selection, startVal, endVal = settings[i]
            keyviewfile.write("SETTINGS: %s, %s, %f, %f\n" % (settingName, selection, startVal, endVal))
        if i in fades:
            startVisSelection, endVisSelection, sticksOnly = fades[i]
            keyviewfile.write("FADES: %s, %s, %d\n" % (startVisSelection, endVisSelection, sticksOnly))
        keyviewfile.write("\n")
    keyviewfile.close()
    cmd.save(filename + ".pse")
    print "Wrote files ", filename + ".key", filename + ".pse"
Esempio n. 28
0
def writePdb(sel, prefix = ""):
    pdbfn = prefix + sel + ".pdb"
    npdbfn = pdbfn.replace(" or ", "");
    npdbfn = npdbfn.replace(" and ", "");
    npdbfn = npdbfn.translate(None, string.whitespace)
    cmd.save(npdbfn, sel)
    return npdbfn
Esempio n. 29
0
def project(model, resi1_str, resi2_str, resi3_str, \
		symQ, syms_for_use, syms_for_del, sym_d=3, \
		segis_for_save='all', segis_for_del=''):
	all_segis = prepare(model, resi1_str, resi2_str, resi3_str, segis_for_save, segis_for_del)
	
	new_model, segi_count = make_segis(model, resi1, resi2, resi3, all_segis)
	cmd.alter(new_model, \
			'segi = new_segi(segi, sorted(all_segis))', \
			space={'new_segi': new_segi, 'all_segis': all_segis, 'sorted': sorted})

	if symQ:
		cmd.symexp('{}_sym'.format(model), \
				'{}_save'.format(model), \
				'({}_save)'.format(model), \
				sym_d)

		for i in range(len(syms_for_use)):
			cmd.alter('{}_sym{}'.format(model, syms_for_use[i]), 'segi=segi+"mod{}"'.format(i + 1))

		merge(model, ['{}_save'.format(model)] + ['{}_sym{}'.format(model, s) for s in syms_for_use])
	
	else: merge(model, ['{}_save'.format(model)])
	
	for sym in syms_for_del:
		cmd.delete('{}_sym{}'.format(model, sym))
	
	cmd.alter('all', 'chain="A"')

	cmd.save('{}_calc.cif'.format(model), '{}_calc'.format(model))
	print(cmd.rms_cur('{}_calc'.format(model), '{}_sym'.format(model)))
Esempio n. 30
0
def saveMultiplepng(pnamein, nbstates):

    finish_launching()
    for state in range(0,nbstates):
        print(state, nbstates)
        finish_launching()

        pfilin = pnamein + "_state" + str(state) + ".pdb"
        print (pfilin)
        cmd.load(pfilin, "state" + str(state))
        cmd.hide("everything", "all")



    for state in range(0, nbstates):
        cmd.show("surface", selection="state" + str(state))
        cmd.set("transparency", value=0.4)
        cmd.show("cartoon", selection="state" + str(state))
        cmd.spectrum("b", "chocolate_firebrick_red_tv_red_deepsalmon_darksalmon_salmon_lightpink_white",
                     selection="all", minimum=0, maximum=100)
        cmd.select("lig" + str(state), "resn UNK and state" + str(state))
        cmd.show("stick", selection="lig" + str(state))
        cmd.bg_color("white")

        cmd.ray(2000, 2000)
        cmd.save(pnamein + "_state" + str(state) + ".png", selection="state" + str(state))
        cmd.hide("everything", "all")

    cmd.quit()
Esempio n. 31
0
def get_pdb():
    """ """
    tmpfn = '/tmp/pymol_get_pdb.pdb'
    cmd.save(tmpfn, '(sele)')
    s = RNAStructure(tmpfn)
    for l in s.lines:
        print(l)
Esempio n. 32
0
def main():
    """Main function.
	"""
    parser = argparse.ArgumentParser(
        description=
        "Take a selection of chains from a set of structures and save them as new structures."
    )
    parser.add_argument('structure',
                        nargs='+',
                        help='Any format supported by Pymol.')
    parser.add_argument(
        '-c',
        '--chains',
        default='A',
        help=
        'Chain string containing all the chains to be get, no space between chain IDs. Only single letter chain IDs are supported [default: %(default)s].'
    )
    parser.add_argument(
        '--hetatm',
        action='store_true',
        default=False,
        help="Include hetatm in the output files [default: %(default)s].")
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='1.0',
                        help="Show program's version number and exit.")

    args = parser.parse_args()

    chains = "".join(sorted(set(args.chains)))

    cmd.reinitialize()  # Just to print Pymol usage as a module waring in here.

    for f in args.structure:
        try:
            cmd.load(f)

        except:
            sys.stderr.write(
                "WARNING: Can not load file {}. Ignoring it.\n".format(f))
            continue

        if not has_chains(f, chains):
            sys.stderr.write(
                "WARNING: Structure {} does not have all requested chains: {}. Ignoring it.\n"
                .format(f, chains))
            continue

        if args.hetatm:
            cmd.save("{}_{}.pdb".format(rootname(f), chains),
                     "{} and chain {}".format(rootname(f), "+".join(chains)))

        else:
            cmd.save(
                "{}_{}.pdb".format(rootname(f), chains),
                "{} and not hetatm and chain {}".format(
                    rootname(f), "+".join(chains)))

        cmd.delete(rootname(f))
def clarna(selection):
    """Get contacts classification of the selected fragment based on ClaRNA (for each object).

    Example::

        PyMOL>clarna sele
        rna_clarna_run.py -ipdb /var/folders/yc/ssr9692s5fzf7k165grnhpk80000gp/T/tmp1h_bwvtx.pdb -bp+stack
        chains:  X 15 16
        X   15   X   16          bp A A                      ><   0.9427

    .. image:: ../../rna_tools/tools/PyMOL4RNA/doc/clarna.png
    """
    f = tempfile.NamedTemporaryFile(delete=False)  # True)
    output = f.name + '_clarna.pdb'
    cmd.save(output, selection)
    CLARNA_RUN = 'rna_clarna_run.py'
    cmdline = CLARNA_RUN + " -ipdb " + output + ' -bp+stack'
    print(cmdline)
    out, err = exe(cmdline)
    print('\n'.join(
        out.split('\n')[1:]))  # to remove first line of py3dna /tmp/xxx
    if err:
        print(err)
    cmd.load(output)
    f.close()
Esempio n. 34
0
def scene_photo(rec, xtal, covalentized, photo_name):
    pymol.finish_launching()
    cmd.delete('all')
    for file_name in [rec, xtal, covalentized]:
        cmd.load(file_name)
    cmd.select('lig', 'org')
    if cmd.count_atoms('lig') == 0:
        return 0
    cmd.set('valence', 0)
    cmd.color('cyan', xtal.split('.')[0])
    cmd.select('cov', covalentized.split('.')[0])
    cmd.select('cysteine', 'br. ' + covalentized.split('.')[0] + ' around 2 and resn CYS')
    cmd.select('cys_cov', 'cysteine or cov')
    cmd.save('tmp.pdb', 'cys_cov')
    cmd.load('tmp.pdb')
    cmd.hide('(hydro)')
    cmd.delete('cov')
    cmd.select('cov', 'tmp and org')
    cmd.select('cysteine', 'tmp and resn cys')
    cmd.color('white', 'cysteine')
    cmd.color('magenta', 'cov')
    cmd.color('green', rec.split('.')[0])
    cmd.util.cnc('all')
    cmd.select('all_mols', 'tmp or ' + xtal.split('.')[0])
    cmd.orient('all_mols')
    pnghack('./tmp.png')
    os.rename('tmp0001.png', photo_name)
    os.remove('tmp.pdb')
Esempio n. 35
0
def ross_load(molecule):
    '''
    for Jennifer Ross.
    '''
    # if pic == 0:
    cmd.reinitialize()
    # cmd.depth_cue(1) # fails
    # cmd.set_depth_cue("off") # fails
    cmd.set("depth_cue","off")
    cmd.bg_color('white')


    fasta = molecule + '.fasta'
    pdb = molecule + '.pdb'

    print molecule
    print fasta
    print pdb

    cmd.load(fasta)

    if not os.path.exists(pdb):
        cmd.save(pdb)


    # cmd.show( string representation="", string selection="" )
    cmd.show('spheres','all')
Esempio n. 36
0
    def Btn_ExtractLigand_Clicked(self):

        state = cmd.get_state()

        # Get the Drop Down List Selection Name
        ddlSelection = self.defaultOption.get()

        if ddlSelection == '' or self.Validate_ObjectSelection(
                ddlSelection, 'Ligand', state):
            return

        LigandPath = tkFileDialog.asksaveasfilename(
            filetypes=[('PDB File', '*.pdb')],
            initialdir=self.top.FlexAIDLigandProject_Dir,
            title='Save the PDB File',
            initialfile=ddlSelection,
            defaultextension='.pdb')

        if len(LigandPath) > 0:

            LigandPath = os.path.normpath(LigandPath)

            if General.validate_String(LigandPath, '.pdb', True, False, True):
                self.DisplayMessage(
                    "  ERROR: Could not save the file because you entered an invalid name.",
                    2)
                return

            if self.top.ValidateSaveProject(LigandPath, 'Ligand'):
                self.DisplayMessage(
                    "  ERROR: The file can only be saved at its default location",
                    2)
                return

            try:
                cmd.save(LigandPath, ddlSelection, state)
                LigandName = os.path.basename(os.path.splitext(LigandPath)[0])

                cmd.extract(self.ExtractObject, ddlSelection)
                cmd.set_name(self.ExtractObject, LigandName)

                if ddlSelection != LigandName:
                    # as if the object was renamed, delete the object
                    cmd.delete(ddlSelection)

            except:
                self.DisplayMessage(
                    "  ERROR: An error occured while extracting the ligand object.",
                    1)
                return

            self.LigandPath.set(os.path.normpath(LigandPath))
            self.LigandName.set(LigandName)
            #self.LigandMD5.set(General.hashfile(self.LigandPath.get()))

            self.Reset_Ligand()

            self.DisplayMessage(
                '  Successfully extracted the ligand:  ' +
                self.LigandName.get() + "'", 0)
Esempio n. 37
0
    def ForceSaveObject(self, file, objname, objtype):

        basepath, filename = os.path.split(file)
        filebasename, fileextname = os.path.splitext(filename)

        self.Set_Object_Variables(objtype)

        if self.savepath != basepath:

            newfile = os.path.join(self.savepath, filebasename + '.pdb')

            if os.path.isfile(newfile):
                answer = tkMessageBox.askquestion("Question",
                                                  message=  "An object with that name already exists in your '" + \
                                                            objtype + "' folder. Would you like to overwrite it?",
                                                  icon='warning')
                if str(answer) == 'no':
                    return 2

            try:
                cmd.save(newfile, objname, state=1)
            except:
                self.DisplayMessage(
                    "  ERROR: The file could not be saved in your '" +
                    objtype + "' folder.", 2)
                return 1

            self.VarPath.set(newfile)

        return 0
Esempio n. 38
0
 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))
Esempio n. 39
0
def writeKeyViewFile( filename ):
    global views
    global frames
    global scenes
    global actions
    global settings
    global models
    global fades
 
    keyviewfile = open( filename + ".key", 'w' )
    i=0
    for view in views:
        keyviewfile.write( "VIEW: %4d " % i )
        for v in view:
            keyviewfile.write( str(v) + " " )
        keyviewfile.write('\n')
        keyviewfile.write( "FRAMES: %d\n" % frames[i] )
        if actions.has_key( i ):
            keyviewfile.write( "ACTIONS: %s\n" % actions[i] )
        if scenes.has_key( i ):
            keyviewfile.write( "SCENES: %s\n" % scenes[i] )
        if models.has_key( i ):
            keyviewfile.write( "MODELS: %s\n" % models[i] )
        if settings.has_key( i ):
            settingName, selection, startVal, endVal = settings[i]
            keyviewfile.write( "SETTINGS: %s, %s, %f, %f\n" % (settingName, selection, startVal, endVal))
        if fades.has_key( i ):
            startVisSelection, endVisSelection, sticksOnly = fades[i]
            keyviewfile.write( "FADES: %s, %s, %d\n" % (startVisSelection, endVisSelection, sticksOnly))            
        i += 1
        keyviewfile.write("\n")
    keyviewfile.close()
    cmd.save( filename + ".pse" )
    print "Wrote files " , filename + ".key", filename + ".pse"
Esempio n. 40
0
	def revert(self):
		v = cmd.get_view()
		cmd.remove(self.rdes.obj+" and not chain A")
		m = cmd.get_model(self.rdes.obj)
		n = self.oldcrd
		if not n:
			cmd.create("tmp12345",self.rnat.sel())
			cmd.align("tmp12345",self.rdes.sel())
			n = cmd.get_model("tmp12345").atom
			cmd.delete("tmp12345")
		di,ni = 0,0
		while m.atom[di].resi != str(self.rdes.resi): di += 1
		dj = di
		while m.atom[dj].resi == str(self.rdes.resi): dj += 1
		if self.oldcrd: self.oldcrd = None
		else:           self.oldcrd = m.atom[di:dj]
		m.atom = m.atom[:di] + n + m.atom[dj:]
		for i in range(di,di+len(n)):
			m.atom[i].resi  = str(self.rdes.resi)
			m.atom[i].chain = str(self.rdes.chain)
		cmd.load_model(m,self.rdes.obj,1)
		cmd.save("tmp.pdb",self.rdes.obj)
		cmd.delete(self.rdes.obj)
		cmd.load("tmp.pdb",self.rdes.obj,1)
		cmd.show('car',self.rdes.obj)
		cmd.show('lines')		
		redopent(self.rdes.obj)
		cmd.set_view(v)
		print "revert removing "+"".join(self.aas)+" from aas!"
		self.aas = [getaa('A',self.rdes.resi,self.manager.d.obj)]
def draw_ENM(structure_filepath, script_filepath, structure_name="CAonly", output_dir='.', view=None):
    """ Draws elastic network model of a structure and saves image.
    """

    cmd.delete('all')
    cmd.load(structure_filepath, "CAonly")
    cmd.run(script_filepath)

    # Set name
    if structure_name == "CAonly":
        pass
    else:
        cmd.set_name("CAonly", structure_name)

    # Set view
    if view == None:
        cmd.orient()
    else:
        cmd.set_view(view)
    
    cmd.viewport(width=1200, height=1200)
    cmd.zoom(complete=1)

    png_filepath = os.path.join(output_dir, structure_name) + ".png"
    pse_filepath = os.path.join(output_dir, structure_name) + ".pse"

    cmd.save(pse_filepath)
    cmd.set('ray_opaque_background', 0)
    cmd.png(png_filepath, width=1200, height=1200, ray=1)

    return (pse_filepath, png_filepath)
Esempio n. 42
0
    def testIsosurface(self):
        cmd.viewport(100, 100)

        cmd.fragment('gly', 'm1')
        cmd.set('gaussian_b_floor', 30)
        cmd.set('mesh_width', 5)
        cmd.map_new('map')
        cmd.delete('m1')

        # make mesh
        cmd.isosurface('surface', 'map')
        cmd.isosurface('surface', 'map', source_state=1, state=-2)

        ## check mesh presence by color
        meshcolor = 'red'
        cmd.color(meshcolor, 'surface')
        self.ambientOnly()
        self.assertImageHasColor(meshcolor)
        cmd.frame(2)
        self.assertEqual(cmd.get_state(), 2)
        self.assertImageHasColor(meshcolor)

        with testing.mktemp('.pse') as filename:
            cmd.save(filename)

            cmd.delete('*')
            self.assertImageHasNotColor(meshcolor)

            cmd.load(filename)
            self.assertImageHasColor(meshcolor)
            cmd.frame(2)
            self.assertEqual(cmd.get_state(), 2)
            self.assertImageHasColor(meshcolor)
Esempio n. 43
0
def output_PNG(this_PDB_file, OUTPUT_FOLDER_PNG, OUTPUT_FOLDER_SESSION):
  # show complex
  cmd.hide("all")
  cmd.bg_color("white")
  cmd.show("cartoon", "this_complex")
  # show protein A
  cmd.set_color("A_interface_color", [167, 244, 66]) # lightgreen
  cmd.set_color("A_C_term_color", [252, 245, 146])   # pale yellow
  cmd.color("yellow", "chain A")
  cmd.color("A_interface_color", "A_interface")
  cmd.alter("A_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "A_center_pseudoatom")
  cmd.color("green", "A_center_pseudoatom")
  cmd.show("sphere", "A_N_term")
  cmd.color("yellow", "A_N_term")
  cmd.show("sphere", "A_C_term")
  cmd.color("A_C_term_color", "A_C_term")
  # show protein B
  cmd.set_color("B_interface_color", [80, 181, 244]) # medium blue
  cmd.set_color("B_C_term_color", [179, 229, 229])   # pale cyan
  cmd.color("cyan", "chain B")
  cmd.color("B_interface_color", "B_interface")
  cmd.alter("B_center_pseudoatom", "vdw=2")
  cmd.show("sphere", "B_center_pseudoatom")
  cmd.color("blue", "B_center_pseudoatom")
  cmd.show("sphere", "B_N_term")
  cmd.color("cyan", "B_N_term")
  cmd.show("sphere", "B_C_term")
  cmd.color("B_C_term_color", "B_C_term")
  # nice output
  cmd.rebuild()
  cmd.zoom("all")
  cmd.png("%s/%s.png" % (OUTPUT_FOLDER_PNG, this_PDB_file), quiet=1)
  # save session
  cmd.save("%s/%s.pse" % (OUTPUT_FOLDER_SESSION, this_PDB_file))
Esempio n. 44
0
 def save_session(self, outfolder, override=None):
     """Saves a PyMOL session file."""
     filename = '%s_%s' % (self.protname.upper(), "_".join(
         [self.hetid, self.plcomplex.chain, self.plcomplex.position]))
     if override is not None:
         filename = override
     cmd.save("/".join([outfolder, "%s.pse" % filename]))
Esempio n. 45
0
def intra_theseus(selection, state=1, cov=0, cycles=200,
        exe='theseus', preserve=0, quiet=1):
    '''
DESCRIPTION

    Fits all states of an object to an atom selection with maximum likelihood.

    THESEUS: Maximum likelihood multiple superpositioning
    http://www.theseus3d.org

ARGUMENTS

    selection = string: atoms to fit

    state = integer: keep transformation of this state unchanged {default: 1}

    cov = 0/1: 0 is variance weighting, 1 is covariance weighting (slower)
    {default: 0}

SEE ALSO

    intra_fit, intra_rms_cur
    '''
    import tempfile, os

    state, cov, cycles = int(state), int(cov), int(cycles)
    preserve, quiet = int(preserve), int(quiet)

    tempdir = tempfile.mkdtemp()
    filename = os.path.join(tempdir, 'mobile.pdb')

    cmd.save(filename, selection, 0)

    exe = cmd.exp_path(exe)
    args = [exe, '-a0', '-c' if cov else '-v', '-i%d' % cycles, filename]

    translations = []
    rotations = []

    translations, rotations = _run_theseus(args, tempdir, preserve, quiet)
    matrices = [R[0:3] + [-t[0]] + R[3:6] + [-t[1]] + R[6:9] + [-t[2], 0,0,0, 1]
            for (R, t) in zip(rotations, translations)]

    # intra fit states
    obj_list = cmd.get_object_list('(' + selection + ')')
    for i, m in enumerate(matrices):
        for obj in obj_list:
            cmd.transform_object(obj, m, i+1, transpose=1)

    # fit back to given state
    if 0 < state <= len(matrices):
        m = list(matrices[state-1])
        for i in [3,7,11]:
            m[i] *= -1
        for obj in obj_list:
            cmd.transform_object(obj, m, 0)

    if not quiet:
        print(' intra_theseus: %d states aligned' % (len(matrices)))
Esempio n. 46
0
    def prepareinput(self, selection='(all)', startpoint='(0,0,0)'):
        if self.varremovewater.get():
            selection = '(%s) and not resn HOH and not resn H2O and not resn WAT' % (selection)

        print selection
        outdir = self.pymol_outdir.getvalue()
        tmppdb = os.path.join(outdir, "tmp.pdb")
        cmd.save(tmppdb, selection)
Esempio n. 47
0
 def testCOLLADA(self):
     cmd.fragment('gly')
     for rep in ['spheres', 'sticks', 'surface']:
         cmd.show_as(rep)
         with testing.mktemp('.dae') as filename:
             cmd.save(filename)
             contents = file_get_contents(filename)
             self.assertTrue('<COLLADA' in contents)
Esempio n. 48
0
 def testVRML(self):
     cmd.fragment('gly')
     for rep in ['spheres', 'sticks', 'surface']:
         cmd.show_as(rep)
         with testing.mktemp('.wrl') as filename:
             cmd.save(filename)
             contents = file_get_contents(filename)
             self.assertTrue(contents.startswith('#VRML V2'))
Esempio n. 49
0
def prosmart(mobile, target, mobile_state=1, target_state=1,
        exe='prosmart', transform=1, object=None, quiet=0):
    '''
DESCRIPTION

    ProSMART wrapper.

    http://www2.mrc-lmb.cam.ac.uk/groups/murshudov/
    '''
    import subprocess, tempfile, os, shutil, glob

    quiet = int(quiet)

    tempdir = tempfile.mkdtemp()
    mobile_filename = os.path.join(tempdir, 'mobile.pdb')
    target_filename = os.path.join(tempdir, 'target.pdb')

    cmd.save(mobile_filename, mobile, state=mobile_state)
    cmd.save(target_filename, target, state=target_state)

    exe = cmd.exp_path(exe)
    args = [exe, '-p1', mobile_filename, '-p2', target_filename, '-a']

    xglob = lambda x: glob.glob(os.path.join(tempdir, 'ProSMART_Output/Output_Files', x))

    try:
        subprocess.check_call(args, cwd=tempdir)

        transfiles = xglob('Superposition/Transformations/*/*.txt')
        with open(transfiles[0]) as f:
            f = iter(f)
            for line in f:
                if line.startswith('ROTATION'):
                    matrix = [list(map(float, next(f).split())) + [0] for _ in range(3)]
                elif line.startswith('TRANSLATION'):
                    matrix.append([-float(v) for v in next(f).split()] + [1])
                    break

        if int(transform):
            matrix = [v for m in matrix for v in m]
            assert len(matrix) == 4*4
            for model in cmd.get_object_list('(' + mobile + ')'):
                cmd.transform_object(model, matrix, state=0)

        if object:
            from .importing import load_aln
            alnfiles = xglob('Residue_Alignment_Scores/*/*.txt')
            alnfiles = [x for x in alnfiles if not x.endswith('_clusters.txt')]
            load_aln(alnfiles[0], object, mobile, target)

    except OSError:
        print(' Error: Cannot execute "%s", please provide full path to prosmart executable' % (exe))
        raise CmdException
    finally:
        shutil.rmtree(tempdir)

    if not quiet:
        print(' prosmart: done')
Esempio n. 50
0
def propka(molecule="NIL",chain="*",resi="0",resn="NIL",method="upload",logtime=time.strftime("%m%d",time.localtime()),server_wait=3.0,version="v3.1",verbose="no",showresult="no",pkafile="NIL",makebonds="yes"):
	Script_Version="20110823"
	### First we have to be sure, we give reasonable arguments
	if pkafile!="NIL":
		method='file'
	assert method in ['upload', 'file'], "'method' has to be either: method=upload or method=file"
	### If molecule="all", then try to get the last molecule
	##assert molecule not in ['NIL'], "You always have to provide molecule name. Example: molecule=4ins"
	if molecule=="NIL":
		assert len(cmd.get_names())!=0, "Did you forget to load a molecule? There are no objects in pymol."
		molecule=cmd.get_names()[-1]
	### To print out to screen for selected residues. Can be separated with "." or make ranges with "-". Example: resi="4-8.10"
	if resi != "0": resi_range = ResiRange(resi)
	else: resi_range=[]
	### Also works for residue names. They are all converted to bigger letters. Example: resn="cys.Tyr"
	if resn != "NIL": resn_range = ResnRange(resn)
	else: resn_range = resn
	### Make chain range, and upper case.
	chain = ChainRange(chain)
	### Make result directory. We also the absolut path to the new directory.
	Newdir = createdirs()
	if method=="upload":
		### We try to load mechanize. If this fail, one can always get the .pka file manual and the run: method=file
		try: from modules import mechanize; importedmechanize='yes'
		except ImportError: print("Import error. Is a module missing?"); print(sys.exc_info()); print("Look if missing module is in your python path\n%s")%sys.path;importedmechanize='no'; import modules.mechanize as mechanize
		### The name for the new molecule
		newmolecule = "%s%s"%(molecule,logtime)
		### Create the new molecule from original loaded and for the specified chains. Save it, and disable the old molecule.
		cmd.create("%s"%newmolecule, "%s and chain %s"%(molecule,chain))
		cmd.save("%s%s.pdb"%(Newdir,newmolecule), "%s"%newmolecule)
		cmd.disable("%s"%molecule)
		if molecule=="all": cmd.enable("%s"%molecule); cmd.show("cartoon", "%s"%molecule)
		### Let the new molecule be shown in cartoon.
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### Make the absolut path to the newly created .pdb file.
		PDB="%s%s.pdb"%(Newdir,newmolecule);source="upload"; PDBID=""
		### Request server, and get the absolut path to the result file.
		pkafile = getpropka(PDB,chain,resi,resn,source,PDBID,logtime,server_wait,version,verbose,showresult)
		### Open the result file and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
	if method=="file":
		assert pkafile not in ['NIL'], "You have to provide path to file. Example: pkafile=./Results_propka/4ins_2011.pka"
		assert ".pka" in pkafile, 'The propka result file should end with ".pka" \nExample: pkafile=./Results_propka/4ins_2011.pka \npkafile=%s'%(pkafile)
		### The name for the molecule we pass to the writing script of pymol commands
		newmolecule = "%s"%molecule
		cmd.hide("everything", "%s"%newmolecule)
		cmd.show("cartoon", "%s"%newmolecule)
		### We open the result file we have got in the manual way and put in into a handy list.
		list_results,ligands_results = importpropkaresult(pkafile)
		### Then we print the interesting residues to the screen.
		printpropkaresult(list_results, resi, resi_range, resn, resn_range, showresult, ligands_results)
	### Now create the pymol command file. This should label the protein. We get back the absolut path to the file, so we can execute it.
	result_pka_pymol_name = writepymolcmd(newmolecule,pkafile,verbose,makebonds)
	### Now run our command file. But only if we are running pymol.
	if runningpymol=='yes': cmd.do("run %s"%result_pka_pymol_name)
	##if runningpymol=='yes': cmd.do("@%s"%result_pka_pymol_name)
	return(list_results)
Esempio n. 51
0
def pdb():
    """Get PDB content of selection.

    .. image:: ../../rna_tools/utils/PyMOL4RNA/doc/pdb.png"""
    tmpfn = '/tmp/pymol_get_pdb.pdb'
    cmd.save(tmpfn, '(sele)')
    s = RNAStructure(tmpfn)
    for l in s.lines:
        print(l)
Esempio n. 52
0
def dss_promotif(selection="all", exe="", raw="", state=-1, quiet=1):
    """
DESCRIPTION

    Secondary structure assignment with PROMOTIF.
    http://www.rubic.rdg.ac.uk/~gail/#Software

SEE ALSO

    dss, dssp, stride
    """
    from subprocess import Popen, PIPE
    import tempfile, os, shutil

    state, quiet = int(state), int(quiet)

    ss_map = {"B": "S", "E": "S", "H": "H", "G": "H"}

    exe = cmd.exp_path(exe)
    if not exe:
        from . import which

        motifdir = os.environ.get("motifdir")
        exe = which("p_sstruc3", "p_sstruc2", "promotif.scr", path=[motifdir] if motifdir else None)

    tmpdir = tempfile.mkdtemp()
    tmpfilepdb = os.path.join(tmpdir, "xxxx.pdb")
    tmpfilesst = os.path.join(tmpdir, "xxxx.sst")
    ss_dict = dict()

    try:
        for model in cmd.get_object_list("(" + selection + ")"):
            cmd.save(tmpfilepdb, "model %s and (%s)" % (model, selection), state)

            process = Popen([exe, tmpfilepdb], cwd=tmpdir, stdin=PIPE)
            process.communicate(tmpfilepdb + os.linesep)

            with open(tmpfilesst) as handle:
                for line in handle:
                    if line.startswith(" num  seq.no"):
                        break
                for line in handle:
                    if not line.strip():
                        break
                    chain = line[6].strip("-")
                    resi = line[7:12].strip()
                    ss = line[23]
                    ss_dict[model, chain, resi] = ss

            os.remove(tmpfilesst)
    except OSError:
        print " Error: Cannot execute exe=" + exe
        raise CmdException
    finally:
        shutil.rmtree(tmpdir)
    _common_ss_alter(selection, ss_dict, ss_map, raw)
Esempio n. 53
0
 def testSTL(self):
     cmd.fragment('gly')
     for rep in ['spheres', 'sticks', 'surface']:
         cmd.show_as(rep)
         with testing.mktemp('.stl') as filename:
             cmd.save(filename)
             contents = file_get_contents(filename, 'rb')
             # 80 bytes header
             # 4 bytes (uint32) number of triangles
             self.assertTrue(len(contents) > 84)
Esempio n. 54
0
def PyMOL_export_PDB_to_file(obj, data_path, file_out, state = -1):   # Export an PDB file from a PyMOL object
	tmp         = data_path+"/tmp"                          
	if not os.path.exists ( tmp ): os.mkdir ( tmp )         
	file_path   = os.path.join (tmp, file_out)
	
	
	FILE        = file_path 
	#  cmd.save("/home/fernando/Desktop/gordo.pdb", "obj01", -1, "pdb")
	cmd.save(FILE, obj, state, "pdb")
	return FILE
Esempio n. 55
0
def theseus(mobile, target, match='align', cov=0, cycles=200,
        mobile_state=1, target_state=1, exe='theseus', preserve=0, quiet=1):
    '''
DESCRIPTION

    Structural superposition of two molecules with maximum likelihood.

    THESEUS: Maximum likelihood multiple superpositioning
    http://www.theseus3d.org

ARGUMENTS

    mobile = string: atom selection for mobile atoms

    target = string: atom selection for target atoms

    match = string: in, like, align, none or the name of an alignment object
    (see "local_rms" help for details) {default: align}

    cov = 0/1: 0 is variance weighting, 1 is covariance weighting (slower)
    {default: 0}

SEE ALSO

    align, super, cealign
    '''
    import tempfile, os

    cov, cycles = int(cov), int(cycles)
    mobile_state, target_state = int(mobile_state), int(target_state)
    preserve, quiet = int(preserve), int(quiet)

    tempdir = tempfile.mkdtemp()
    mobile_filename = os.path.join(tempdir, 'mobile.pdb')
    target_filename = os.path.join(tempdir, 'target.pdb')

    mm = MatchMaker(mobile, target, match)
    cmd.save(mobile_filename, mm.mobile, mobile_state)
    cmd.save(target_filename, mm.target, target_state)

    exe = cmd.exp_path(exe)
    args = [exe, '-a0', '-c' if cov else '-v', '-i%d' % cycles,
            mobile_filename, target_filename]

    translations, rotations = _run_theseus(args, tempdir, preserve, quiet)
    matrices = [R[0:3] + [i*t[0]] + R[3:6] + [i*t[1]] + R[6:9] + [i*t[2], 0,0,0, 1]
            for (R, t, i) in zip(rotations, translations, [-1,1])]

    obj_list = cmd.get_object_list('(' + mobile + ')')
    for obj in obj_list:
        cmd.transform_object(obj, matrices[0], 0, transpose=1)
        cmd.transform_object(obj, matrices[1], 0)

    if not quiet:
        print(' theseus: done')
Esempio n. 56
0
    def testMol2FormalChargeAssignment(self):
        cmd.fragment('lys')
        cmd.fragment('lys')

        with testing.mktemp('.mol2') as filename:
            cmd.save(filename, state=0)
            cmd.delete('*')
            cmd.load(filename)

        self.assertEqual(cmd.get_model('name NZ', state=1).atom[0].formal_charge, 1)
        self.assertEqual(cmd.get_model('name NZ', state=2).atom[0].formal_charge, 1)