Ejemplo n.º 1
0
def option2():

    vinacomd = str(checkutilities())
    A = inputdata2()

    global proteinfile, ligandfile

    import addwater
    addwater.main(ligandfile)

    waterfile()
    #Writes the water.pdbqt file

    import dockcheck
    dockcheck.main(proteinfile, ligandfile, vinacomd)

    os.remove('waterdetails.txt')
    os.remove('placedwaters.pdb')
    os.remove('water.pdbqt')

    cmd.set("retain_order", 1)
    cmd.set("pdb_use_ter_records", 0)
    cmd.load(proteinfile, 'pro')
    cmd.show_as('cartoon', 'pro')
    cmd.color('blue', 'pro')
    cmd.load('predictedwaters.pdb', 'wats')
    cmd.color('red', 'wats')
    cmd.load(ligandfile, 'lig')
    cmd.show_as('sticks', 'lig')
    cmd.center('lig')
Ejemplo n.º 2
0
def option2():

	vinacomd = str(checkutilities())
	A = inputdata2()

	global proteinfile, ligandfile

	import addwater
	addwater.main(ligandfile)

	waterfile()
	#Writes the water.pdbqt file

	import dockcheck
	dockcheck.main(proteinfile, ligandfile, vinacomd)

	os.remove('waterdetails.txt')
	os.remove('placedwaters.pdb')
	os.remove('water.pdbqt')


	cmd.set("retain_order", 1)
	cmd.set("pdb_use_ter_records", 0)
	cmd.load(proteinfile, 'pro')
	cmd.show_as('cartoon', 'pro')
	cmd.color('blue','pro')
	cmd.load('predictedwaters.pdb','wats')
	cmd.color('red','wats')
	cmd.load(ligandfile,'lig')
	cmd.show_as('sticks','lig')
	cmd.center('lig')
Ejemplo n.º 3
0
	def centeractive(self):
		if self.toggle['view']:
			cmd.set_view(self.toggle['view'])
			self.toggle['view'] = None
		else:
			self.toggle['view'] = cmd.get_view()			
			cmd.center(self.m.rdes.sel())
Ejemplo n.º 4
0
def show_motif(interaction, domain1, domain2, residues1, residues2):
    cmd.load("PDBFiles/%s.pdb" % domain1)
    cmd.load("PDBFiles/%s.pdb" % domain2)
    cmd.bg_color("white")

    cmd.hide("all")
    cmd.show("cartoon", "all")
    cmd.select("motif1", "none")
    cmd.select("motif1",
               "motif1 or (%s and n. CA and resi %s)" % (domain1, residues1))
    cmd.select("motif2", "none")
    cmd.select("motif2",
               "motif2 or (%s and n. CA and resi %s)" % (domain2, residues2))
    cmd.select("none")
    cmd.color("gray80", domain1)
    cmd.color("gray60", domain2)
    cmd.color("cyan", "motif1")
    cmd.color("magenta", "motif2")
    try:
        cmd.pair_fit("motif1", "motif2")
        cmd.center(domain1)
        cmd.png("PNGs/%s_%s_%s_PF.png" % (interaction, domain1, domain2),
                dpi=300)
    except CmdException:
        pass

    try:
        cmd.cealign("motif1", "motif2")
        cmd.center(domain1)
        cmd.png("PNGs/%s_%s_%s_CE.png" % (interaction, domain1, domain2),
                dpi=300)
    except CmdException:
        pass
Ejemplo n.º 5
0
def take_screenshot(params, pdb_file_name, protein_number, step_number):
    print("")
    print("SCREENSHOT! protein #", protein_number, pdb_file_name, " step ", step_number, " with ", cmd.count_atoms("all"), " atoms")
    screenshot_path = "./results/{}/screenshots/{}-{}/{}-{}.png".format(params.run_time_stamp, pdb_file_name, protein_number, pdb_file_name, step_number)
    cmd.ray()
    # cmd.zoom("all")
    cmd.center("all")
    cmd.png(screenshot_path)
Ejemplo n.º 6
0
def showcenters(res, crad="2", rad="5"):
    cmd.hide("all")
    sel = "centers within %(crad)s of %(res)s/sd05" % vars()
    cmd.show("spheres", sel)
    cmd.color("purple", sel)
    cmd.show("spheres", "(not centers within %(rad)s of (%(sel)s)) or (%(sel)s)" % vars())
    cmd.show("lines", "(name CA,N,C,O)")
    cmd.center("%(res)s/sd05" % vars())
Ejemplo n.º 7
0
def centers():
    while 1:
        try:
            resi = int(random.random() * 150)
            cmd.center("(resi %d)" % resi)
            time.sleep(random.random() * 0.30)
        except:
            print "exception"
Ejemplo n.º 8
0
def detect_distance(conformation, path_dock, path_poche):

    #DOSSIER QUI CONTIENT LES POCHES
    dossier_poche = os.listdir(path_poche)

    #DOSSIER QUI CONTIENT LES RESULTATS DE DOCKING
    dossier_dock = os.listdir(path_dock)

    #DOSSIER QUI CONTIENT LES CONFORMATIONS
    dossier_conf = os.listdir("{}/{}".format(path_poche, conformation))

    #ON CHARGE DANS PYMOL LA CONFORMATION ET LE LIGAND
    cmd.load("{}/{}/{}.pdbqt".format(path_dock, conformation, conformation),
             "conf")
    cmd.load(
        "{}/{}/out_{}.pdbqt".format(path_dock, conformation, conformation),
        "lig")

    #ON SE FOCALISE SUR LA PREMIERE POSE DU LIGAND
    cmd.create("obj", "lig", 1)
    cmd.center("obj")

    #ON SAUVEGARDE LA POSITION DU CENTRE D'INERTIE DU LIGAND
    poz_lig = cmd.get_position()

    #VALEUR DE REFERENCE POUR LA DISTANCE QUI CHANGE AU FUR ET A MESURE
    D_ref = 100
    pock = ''

    #POUR TOUTES LES POCHES DE LA CONFORMATION
    for i in range(len(dossier_conf) - 1):

        #ON CHARGE LA POCHE DANS PYMOL
        nom = "pocket{}".format(i)
        cmd.load('{}/{}/{}_atm.pdb'.format(path_poche, conformation, nom), nom)
        cmd.center(nom)

        #ON SAUVEGARDE LA POSITION DU CENTRE D'INERTIE DE LA POCHE
        poz_pock = cmd.get_position()

        #ON CALCULE LA DISTANCE ENTRE LE CENTRE D'INERTIE DE LA POCHE ET DU LIGAND
        D = sqrt((poz_lig[0] - poz_pock[0])**2 +
                 (poz_lig[1] - poz_pock[1])**2 + (poz_lig[2] - poz_pock[2])**2)

        #ON RETIENT LES POCHES QUI ONT UNE DISTANCE PAR RAPPORT AU LIGAND INFERIEUR A UNE DISTANCE REFERENCE
        if (D < D_ref):

            #ON ACTUALISE LA DISTANCE DE REFERENCE A LA DISTANCE LA PLUS FAIBLE
            D_ref = D
            pock = nom

        cmd.delete(nom)

    cmd.delete("conf")
    cmd.delete("lig")
    #print("La meilleure poche : {} pour le docking {}".format(pock,conformation))

    return {conformation: pock}
Ejemplo n.º 9
0
    def _do_mutation(self):
        '''
        After selection, propose what the fragment will look like where
        applied.
        Exception: _do_mutation should be wrapped in a try-exception block
                   when called
        '''
        cmd = self.cmd

        cmd.delete(FRAG_NAME)
        cmd.refresh_wizard()

        if any(
                cmd.count_atoms("(%s) & name %s" % (SRC_SELE, name)) != 1
                for name in ("C1'", "C2'", "C3'", "C4'", "O4'")):
            self.clear()
            raise pymol.wizarding.WizardError(
                'Improper selection of nucleic acid.')

        frag_type_lower = self._mode_labels[self.mode].lower()
        cmd.fragment(frag_type_lower, FRAG_NAME, origin=0)
        self._update_reps()
        cmd.color("white", "%s & elem C" % FRAG_NAME)
        cmd.iterate("first (%s)" % SRC_SELE,
                    'stored.name = model+"/"+segi+"/"+chain+"/"+resn+"`"+resi',
                    space=self._space)
        self.res_text = self._space['stored'].name

        cmd.alter("?%s & name C1'" % SRC_SELE,
                  "stored.identifiers = (segi, chain, resi, ss, color)",
                  space=self._space)
        self._status = Status.MUTAGENIZING
        self.get_prompt()

        cmd.iterate("(%s & name C1')" % SRC_SELE,
                    "stored.resn = resn",
                    space=self._space)
        src_type_lower = self._space['stored'].resn.lower()
        self._src_O_atom_name, self._src_Cp_atom_name, self._src_N_atom_name, \
        self._src_C_atom_name = self._get_chi_dihedral_atoms(src_type_lower)

        self._frag_O_atom_name, self._frag_Cp_atom_name, self._frag_N_atom_name, \
        self._frag_C_atom_name = self._get_chi_dihedral_atoms(frag_type_lower)

        cmd.pair_fit("(%s & name %s)" % (FRAG_NAME, self._frag_O_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_O_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_Cp_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_Cp_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_N_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_N_atom_name))

        self._transfer_dihedral()

        for a in self._sugar_phos_atoms:
            cmd.remove("(%s & name %s)" % (FRAG_NAME, a))

        if self._auto_center == "ON":
            cmd.center(FRAG_NAME, animate=1)
Ejemplo n.º 10
0
def load_ligands(ligand_file):
    print(ligand_file)
    cmd.load(os.path.dirname(__file__) + '/' + ligand_file)
    cmd.show("sticks", "resn HIS")
    cmd.center()
    cmd.zoom()
    pymol_module = diswiz.Restraints_Wizard()
    cmd.set_wizard(pymol_module)
    return pymol_module
Ejemplo n.º 11
0
 def click_residue_with_right_button(self, residue_tags):  # center residue
     sel = self.pymol_selection + " and resn " + residue_tags[
         "resname"] + " and resi " + residue_tags["position"]
     try:
         cmd.center(sel, animate=1)
         cmd.delete("pymod_selection")
         cmd.refresh(
         )  # causes the scene to be refresh as soon as it is safe to do so.
     except:
         pass
Ejemplo n.º 12
0
 def zoom_to_ligand(self):
     """Zoom in too ligand and its interactions."""
     cmd.center(self.ligname)
     cmd.orient(self.ligname)
     cmd.turn('x', 110)  # If the ligand is aligned with the longest axis, aromatic rings are hidden
     if 'AllBSRes' in cmd.get_names("selections"):
         cmd.zoom('%s or AllBSRes' % self.ligname, 3)
     else:
         if self.object_exists(self.ligname):
             cmd.zoom(self.ligname, 3)
     cmd.origin(self.ligname)
Ejemplo n.º 13
0
 def click_residue_with_middle_button(
         self, residue_tags):  # center & select residue
     sel = self.pymol_selection + " and resn " + residue_tags[
         "resname"] + " and resi " + residue_tags["position"]
     try:
         cmd.center(sel)
         cmd.select("pymod_selection", sel)
         cmd.refresh(
         )  # causes the scene to be refresh as soon as it is safe to do so.
     except:
         pass
Ejemplo n.º 14
0
def split_chains(obj=None, color=1):
    if obj is None:
        obj = cmd.get_object_list()[0]
    chains = cmd.get_chains(obj)
    for chain in chains:
        new_obj = obj+"_"+chain
        cmd.create(new_obj, f"{obj} and chain {chain}")
        cmd.color('atomic', new_obj)
    cmd.center(obj)
    cmd.delete(obj)
    if int(color) == 1:
        util.color_objs(f"elem c and {obj}_*")
Ejemplo n.º 15
0
def rotation_series(axis, increment, width, height, filename, with_centering):
    if (increment == 0):
        max_turns = 1
    else:
        max_turns = (360/increment) + 1

    for x in range(max_turns):    
        if x > 0: cmd.rotate(axis, increment)
        if with_centering: cmd.center("(all)")
        cmd.ray(width, height)
        cmd.png(filename + "_" + str(x * increment) + ".png", dpi=dpi())
    return
Ejemplo n.º 16
0
def sets():
    while 1:
        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        resi = int(random.random() * 150)
        cmd.center("(resi %d)" % resi)
        cmd.set('cartoon_fancy_helices', str(value))

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('cartoon_smooth_loop', str(value))

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('cartoon_round_helices', str(value))

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('cartoon_smooth_loops', str(value))

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('cartoon_flat_sheets', str(value))

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('stick_radius', random.random() * 0.2 + 0.1)

        time.sleep(random.random() * 0.02)
        if random.random() > 0.5:
            value = 1
        else:
            value = 0
        cmd.set('sphere_scale', random.random() * 0.5 + 0.75)
Ejemplo n.º 17
0
    def pickWhich(self,event):
 
        # Find closest data point               
        x = event.widget.canvasx(event.x)
        y = event.widget.canvasx(event.y)
        spot = event.widget.find_closest(x,y)
 
        # Print the shape's meta information corresponding with the shape that was picked
        if spot[0] in self.shapes:
            cmd.select('sele', '(%s`%d)' % self.shapes[spot[0]][5])
            cmd.iterate('sele', 'print " You clicked /%s/%s/%s/%s`%s/%s (DynoPlot)" %' + \
                    ' (model, segi, chain, resn, resi, name)')
            cmd.center('byres sele', animate=1)
Ejemplo n.º 18
0
    def pickWhich(self, event):

        # Find closest data point
        x = event.widget.canvasx(event.x)
        y = event.widget.canvasx(event.y)
        spot = event.widget.find_closest(x, y)

        # Print the shape's meta information corresponding with the shape that was picked
        if spot[0] in self.shapes:
            cmd.select('sele', '(%s`%d)' % self.shapes[spot[0]][5])
            cmd.iterate('sele', 'print " You clicked /%s/%s/%s/%s`%s/%s (DynoPlot)" %' + \
                        ' (model, segi, chain, resn, resi, name)')
            cmd.center('byres sele', animate=1)
Ejemplo n.º 19
0
	def showpack(self):
		print self.toggle['sph']
		#cmd.hide('spheres','not '+self.manager.d.bupsel)
		cmd.hide('spheres')
		if self.toggle['sph']:
			self.toggle['sph'] = False
			return
		fr = self.rnat.obj+" and name n+ca+c and resi %i-%i"%(self.rnat.resi-10,self.rnat.resi+10)		
		to = self.rdes.obj+" and name n+ca+c and resi %i-%i"%(self.rdes.resi-10,self.rdes.resi+10)
		cmd.align(fr,to)
		cmd.center(self.rdes.sel()+" or "+self.rnat.sel())
		#cmd.show('sticks',self.rnat.sel())
		cmd.show('spheres',"byres ((not "+self.rnat.obj+") within 6 of "+self.rdes.sel()+")")
		self.toggle['sph'] = True
Ejemplo n.º 20
0
	def focus(self):
		self.manager.m = self
		if self.manager.prevm: cmd.hide('sticks',self.manager.prevm.rdes.sel())
		if self.manager.prevm: cmd.color('green',self.manager.prevm.rdes.sel()+" and elem C")
		fr = self.rnat.obj+" and name n+ca+c and resi %i-%i"%(self.rnat.resi-10,self.rnat.resi+10)		
		to = self.rdes.obj+" and name n+ca+c and resi %i-%i"%(self.rdes.resi-10,self.rdes.resi+10)
		cmd.align(fr,to)
		cmd.show('sticks',self.rdes.sel())
		cmd.color('white',self.rdes.sel()+" and elem C")
		cmd.center(self.rdes.sel())
		v = list(cmd.get_view())
		v[11] = -80.0
		cmd.set_view(tuple(v))
		cmd.clip('slab',50,self.rdes.sel())
Ejemplo n.º 21
0
def prepare_pymol():
    cmd.set("ray_trace_color", "black")
    cmd.set("ray_trace_gain", 0)
    cmd.set("ray_trace_mode", 3)
    cmd.set("depth_cue", 0)
    cmd.clip("near", 100000)
    cmd.clip("slab", 100000)
    cmd.clip("far", -100000)
    cmd.hide("all")
    util.cbc()
    cmd.show('surface')
    cmd.bg_color("black")
    cmd.zoom("all", buffer=2.0) # buffer might help clipping problem
    cmd.center("all")
    cmd.deselect()
Ejemplo n.º 22
0
def detect_res38(path_dock, distance, pic=0):

    dossier_dock = os.listdir(path_dock)
    ok = {}

    for conformation in dossier_dock:

        cmd.load(
            "{}/{}/{}.pdbqt".format(path_dock, conformation, conformation),
            "conf")
        cmd.load(
            "{}/{}/out_{}.pdbqt".format(path_dock, conformation, conformation),
            "lig")

        cmd.create("obj", "lig", 1)

        cmd.center("obj")
        poz_lig = cmd.get_position()

        cmd.select("r38", "res 38")
        cmd.center("r38")

        poz_38 = cmd.get_position()

        D = sqrt((poz_lig[0] - poz_38[0])**2 + (poz_lig[1] - poz_38[1])**2 +
                 (poz_lig[2] - poz_38[2])**2)

        if (D < distance):

            if (pic == 1):
                cmd.show("surface", "r38")
                cmd.set_view("\
				    -0.298310757,    0.680330575,   -0.669443905,\
				     0.016840594,    0.705018342,    0.708981633,\
				     0.954314768,    0.200224459,   -0.221768484,\
				    -0.000218070,   -0.000902027,  -86.197776794,\
				    40.384254456,   78.192932129,   43.972404480,\
				    -5.481759548,  177.321334839,  -20.000000000")
                cmd.png(conformation, width=1700, height=750)
            ok.update({conformation: D})

        cmd.delete("conf")
        cmd.delete("lig")

    ok = sorted(ok.items(), key=lambda t: t[1])

    return ok
Ejemplo n.º 23
0
def loadcomplex(system, dataset, flexdist=3, pdbbindpath="../PDBbind18"):

    # Clear everything
    cmd.reinitialize("everything")

    print(f"Loading {dataset}/{system}")

    ligand = os.path.join(pdbbindpath, dataset, system,
                          f"{system}_ligand.mol2")
    receptor = os.path.join(pdbbindpath, dataset, system,
                            f"{system}_protein.pdb")

    # Load ligand and receptor
    cmd.load(ligand, "ligand")  # Selection name: ligand
    cmd.load(receptor, "receptor")  # Selection name: receptor

    # Center and zoom to ligand
    cmd.center("ligand")
    cmd.zoom("ligand", 8)

    # Remove solvent
    cmd.remove("solvent")

    # Receptor rendering
    cmd.color("grey", "receptor")

    # Get residue index of atoms within FLEXDIST from the ligand
    noflex = ["ALA", "GLY", "PRO"]
    recsel = "receptor and not hydro " + " ".join(
        [f"and not resn {resn}" for resn in noflex])
    stored.list = []
    cmd.iterate(
        f"({recsel}) within {flexdist} of ligand",  # Selection
        "stored.list.append((resn, resi, chain))",  # Action
    )

    # Remove redundancies
    flexres = set(stored.list)  # Set of flexible residues

    # Outline flexible residues
    for resn, resi, chain in flexres:
        if chain != "":  # ???
            sel = f"receptor and (resi {resi} in chain {chain})"
            cmd.show("licorice", sel)
            cmd.color("red", sel)
            cmd.remove(f"hydro in ({sel})")
Ejemplo n.º 24
0
 def load_element_in_pymol(self, element, as_hedgehog=True):
     """
     Loads the PDB structure of the chain into PyMol.
     """
     file_to_load = element.get_structure_file(basename_only=False)
     pymol_object_name = element.get_pymol_selector()
     cmd.load(file_to_load, pymol_object_name)
     cmd.color(element.my_color, pymol_object_name)
     cmd.hide("everything", pymol_object_name)
     cmd.show("cartoon",
              pymol_object_name)  # Show the new chain as a cartoon.
     if as_hedgehog:
         cmd.show(
             "sticks", "(%s and name cb) or (%s and name ca)" %
             (pymol_object_name, pymol_object_name))
     cmd.util.cnc(pymol_object_name)  # Colors by atom.
     cmd.zoom(pymol_object_name)
     cmd.center(pymol_object_name)
Ejemplo n.º 25
0
def visualize(pdbid, method):
    assert method in ["gradient", "atomic"]

    # Clear everything
    cmd.reinitialize("everything")

    ligname = f"{pdbid}_ligand_{method}"
    recname = f"{pdbid}_protein_{method}"

    ligfile = ligname + ".pdb"
    recfile = recname + ".pdb"

    cmd.load(ligfile, "lig")
    cmd.load(recfile, "rec")

    # Hide everything
    cmd.hide("all")

    # Show ligand
    cmd.show("sticks", "lig")
    # cmd.show("spheres", "lig")
    # cmd.set("sphere_scale", 0.1, "lig")
    # cmd.set("stick_radius", 0.1, "lig")

    # Show protein
    cmd.select("residues", "byres (rec within 3.5 of lig)")
    cmd.show("cartoon", "rec")
    cmd.color("grey", "rec")
    cmd.show("sticks", "residues")

    # Extract max/min b-factors
    stored.bfs = []
    cmd.iterate("all", "stored.bfs.append(b)")  # Selection

    Bmax = max(max(stored.bfs), abs(min(stored.bfs)))

    cmd.spectrum("b", "orange_white_blue", "lig", -Bmax, Bmax)
    cmd.spectrum("b", "red_white_green", "residues", -Bmax, Bmax)

    cmd.remove("(hydro)")
    cmd.remove("solvent")

    cmd.center("lig")
    cmd.zoom("lig", 5)
def beautify_images(protein_name, residue_sets):
    cmd.delete("all")

    cmd.fetch(protein_name, async_=0)
    cmd.color(
        "0xFFFFFF"
    )  # colors the entire protein white (so that the predictions can be colored)

    cmd.hide("lines")
    cmd.hide("spheres")
    cmd.show("cartoon")

    sphere_size = f"vdw={SPHERE_SIZE}"  # the size of the rendered sphere

    for res_set in residue_sets:
        cmd.color(res_set.color,
                  res_set.selection_string)  # colors annotated blue
        cmd.show("spheres", res_set.selection_string)
        cmd.alter(res_set.selection_string,
                  sphere_size)  # changes the sphere size

    cmd.rebuild()  # rerenders the spheres to the new size

    # cmd.color(annotated.color, annotated.selection_string) # colors annotated blue
    # cmd.color(wrong.color, wrong.selection_string) # colors wrongly predicted red
    # cmd.color(correct.color, correct.selection_string) # colors correctly predicted green

    # cmd.show("spheres", annotated.selection_string)
    # cmd.show("spheres", correct.selection_string)
    # cmd.show("spheres", wrong.selection_string)

    # cmd.alter(wrong.selection_string, sphere_size)    # changes the sphere size
    # cmd.alter(correct.selection_string, sphere_size)
    # cmd.alter(annotated.selection_string, sphere_size)
    # cmd.rebuild() # rerenders the spheres to the new size

    cmd.remove("resn hoh")  # removes the HOH's from image
    cmd.orient(residue_sets[0].selection_string)
    cmd.zoom(complete=1)
    cmd.set("depth_cue", "0")  # removes shadows of depth
    cmd.center(protein_name)
Ejemplo n.º 27
0
def show_motif(value):
    cmd.delete("*")
    domain1 = align_pairs[value][0]
    domain2 = align_pairs[value][1]
    residues1 = align_pairs[value][2]
    residues2 = align_pairs[value][3]

    cmd.load("PDBFiles/%s.pdb" % domain1)
    cmd.load("PDBFiles/%s.pdb" % domain2)
    cmd.bg_color("white")

    cmd.hide("all")
    cmd.show("cartoon", "all")
    cmd.select("motif1", "none")
    cmd.select("motif1",
               "motif1 or (%s and n. CA and resi %s)" % (domain1, residues1))
    cmd.select("motif2", "none")
    cmd.select("motif2",
               "motif2 or (%s and n. CA and resi %s)" % (domain2, residues2))
    cmd.select("none")
    cmd.color("gray80", domain1)
    cmd.color("gray60", domain2)
    cmd.color("cyan", "motif1")
    cmd.color("magenta", "motif2")
    #cmd.seqview("on")
    try:
        cmd.pair_fit("motif1", "motif2", object="alignment")
        cmd.center(domain1)
        #cmd.png("PNGsRenumb/%s_%s_PF.png"%(domain1, domain2), dpi = 300)
    except CmdException:
        pass

    try:
        cmd.cealign("motif1", "motif2", object="alignment")
        cmd.center(domain1)
        #cmd.png("PNGsRenumb/%s_%s_CE.png"%(domain1, domain2), dpi = 300)
    except CmdException:
        pass
Ejemplo n.º 28
0
def princ_align(selection='(all)'):

    model = cmd.get_model(f"{selection} and name CA")
    coords = np.array([at.coord for at in model.atom])
    try:
        center = np.mean(coords, axis=0)
    except NameError:
        print(
            "This command will not work without numpy.\nConsider installing numpy (or anaconda, provides numpy)."
        )
        return
    coords -= center

    eig_vec = get_principal_axes(coords)
    # Now i have to calculate angles...
    # largest should be aligned with Z-axis
    x0 = np.array([1, 0, 0])
    y0 = np.array([0, 1, 0])
    z0 = np.array([0, 0, 1])

    # Transform everything such that it is centered around
    # selection's center, and rotated
    # Such that the principal axes of the selection
    # align with those of the frame of reference
    # For some reason x0 is the right one to align with the z-axis
    rot_mat = rotation_matrix_from_vectors(eig_vec[0], x0)

    TTT = [
        *rot_mat[0], -center[0], *rot_mat[1], -center[1], *rot_mat[2],
        -center[2], 0, 0, 0, 1
    ]

    cmd.transform_selection('(all)', TTT, transpose=1)

    # Finally center all
    cmd.center()

    return eig_vec  # Just in case i need them later
Ejemplo n.º 29
0
def color_by_mutation(obj1, obj2, waters=0, labels=0):
    '''
    DESCRIPTION
 
        Creates an alignment of two proteins and superimposes them. 
        Aligned residues that are different in the two (i.e. mutations) are highlighted and 
        colored according to their difference in the BLOSUM90 matrix. 
        Is meant to be used for similar proteins, e.g. close homologs or point mutants, 
        to visualize their differences.      
 
    USAGE
 
        color_by_mutation selection1, selection2 [,waters [,labels ]]
 
    ARGUMENTS
 
        obj1: object or selection
 
        obj2: object or selection    
 
        waters: bool (0 or 1). If 1, waters are included in the view, colored
                differently for the both input structures.
                default = 0
 
        labels: bool (0 or 1). If 1, the possibly mutated sidechains are 
                labeled by their chain, name and id
                default = 0
 
    EXAMPLE
 
        color_by_mutation protein1, protein2
 
    SEE ALSO
 
        super
    '''
    from pymol import stored, CmdException

    if cmd.count_atoms(obj1) == 0:
        print '%s is empty' % obj1
        return
    if cmd.count_atoms(obj2) == 0:
        print '%s is empty' % obj2
        return
    waters = int(waters)
    labels = int(labels)

    # align the two proteins
    aln = '__aln'

    # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues)
    # for some mutations in the same protein this works fine). This is essentially done to get a
    # sequence alignment
    cmd.super(obj1, obj2, object=aln, cycles=0)

    # superimpose the the object using the default parameters to get a slightly better superimposition,
    # i.e. get the best structural alignment
    cmd.super(obj1, obj2)

    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []

    # store residue ids, residue names and chains of aligned residues
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)')

    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resi1.append(resi)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resi2.append(resi)')

    cmd.iterate(obj1 + ' and name CA and ' + aln,
                'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA and ' + aln,
                'stored.chain2.append(chain)')

    mutant_selection = ''
    non_mutant_selection = 'none or '
    colors = []

    # loop over the aligned residues
    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2, stored.resi1,
                                      stored.resi2, stored.chain1,
                                      stored.chain2):
        # take care of 'empty' chain names
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        if n1 == n2:
            non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % (
                obj1, i1, c1, obj2, i2, c2)
        else:
            mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or ' % (
                obj1, i1, c1, obj2, i2, c2)
            # get the similarity (according to the blosum matrix) of the two residues and
            c = getBlosum90ColorName(n1, n2)
            colors.append(
                (c, '%s and resi %s and chain %s and elem C' % (obj2, i2, c2)))

    if mutant_selection == '':
        print ' Error: No mutations found'
        raise CmdException

    # create selections
    cmd.select('mutations', mutant_selection[:-4])
    cmd.select('non_mutations', non_mutant_selection[:-4])
    cmd.select(
        'not_aligned',
        '(%s or %s) and not mutations and not non_mutations' % (obj1, obj2))

    # create the view and coloring
    cmd.hide('everything', '%s or %s' % (obj1, obj2))
    cmd.show('cartoon', '%s or %s' % (obj1, obj2))
    cmd.show(
        'lines',
        '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)' %
        (obj1, obj2))
    cmd.show('sticks',
             '(%s or %s) and mutations and not name c+o+n' % (obj1, obj2))
    cmd.color('gray', 'elem C and not_aligned')
    cmd.color('white', 'elem C and non_mutations')
    cmd.color('blue', 'elem C and mutations and %s' % obj1)
    for (col, sel) in colors:
        cmd.color(col, sel)

    cmd.hide('everything', '(hydro) and (%s or %s)' % (obj1, obj2))
    cmd.center('%s or %s' % (obj1, obj2))
    if labels:
        cmd.label('mutations and name CA', '"(%s-%s-%s)"%(chain, resi, resn)')
    if waters:
        cmd.set('sphere_scale', '0.1')
        cmd.show('spheres', 'resn HOH and (%s or %s)' % (obj1, obj2))
        cmd.color('red', 'resn HOH and %s' % obj1)
        cmd.color('salmon', 'resn HOH and %s' % obj2)
    print '''
             Mutations are highlighted in blue and red.
             All mutated sidechains of %s are colored blue, the corresponding ones from %s are
             colored on a spectrum from blue to red according to how similar the two amino acids are
             (as measured by the BLOSUM90 substitution matrix).
             Aligned regions without mutations are colored white.
             Regions not used for the alignment are gray.
             NOTE: There could be mutations in the gray regions that were not detected.''' % (
        obj1, obj2)
    cmd.delete(aln)
    cmd.deselect()
Ejemplo n.º 30
0
 def center_residue_in_pymol_from_sequence_text(self,
                                                alignment_id,
                                                event=None):
     res = self.get_highlighted_residue(alignment_id)
     cmd.center(res.get_pymol_selector())
Ejemplo n.º 31
0
pairs = [[int(i.split()[0]), int(i.split()[1])] for i in pairlines]

prefix = "DistHelix_"
cmd.select(prefix, "none")
selected = []
residues = [int(i) for i in getPymolResnums()]
for i in pairs:
    j = i[0]
    k = i[1]
    if j in residues and k in residues:
        for at1 in cmd.index("name O2' in resi " + str(j)):
            for at2 in cmd.index("name O2' in resi " + str(k)):
                cmd.distance(prefix + str(j), "%s`%d" % at1, "%s`%d" % at2)
                cmd.color('red', prefix + str(j))
            # create selections containing relevant nts
        if j not in selected:
            selected.append(j)
            cmd.select(prefix, prefix + " + resi " + str(j))
        if k not in selected:
            selected.append(k)
            cmd.select(prefix, prefix + " + resi " + str(k))

cmd.show("spheres", "name O2\' in Link_*")
cmd.set('opaque_background', 'off')
cmd.center()
#create a file name with percentiles included
fileName = args.ContactFile[:-4]
fileName += ".pse"
print "Stuff Drawn!"
print fileName
cmd.save(fileName)
Ejemplo n.º 32
0
def std( selection ):
    cmd.hide("all")
    cmd.show("cartoon",selection)
    cmd.center(selection)
    cmd.zoom(selection)
    cmd.spectrum('count','rainbow',selection)
Ejemplo n.º 33
0
def color_by_mutation(obj1, obj2, waters=0, labels=0):
    '''
    DESCRIPTION
 
        Creates an alignment of two proteins and superimposes them. 
        Aligned residues that are different in the two (i.e. mutations) are highlighted and 
        colored according to their difference in the BLOSUM90 matrix. 
        Is meant to be used for similar proteins, e.g. close homologs or point mutants, 
        to visualize their differences.      
 
    USAGE
 
        color_by_mutation selection1, selection2 [,waters [,labels ]]
 
    ARGUMENTS
 
        obj1: object or selection
 
        obj2: object or selection    
 
        waters: bool (0 or 1). If 1, waters are included in the view, colored
                differently for the both input structures.
                default = 0
 
        labels: bool (0 or 1). If 1, the possibly mutated sidechains are 
                labeled by their chain, name and id
                default = 0
 
    EXAMPLE
 
        color_by_mutation protein1, protein2
 
    SEE ALSO
 
        super
    '''
    from pymol import stored, CmdException
 
    if cmd.count_atoms(obj1) == 0:
        print '%s is empty'%obj1
        return
    if cmd.count_atoms(obj2) == 0:
        print '%s is empty'%obj2
        return
    waters = int(waters)
    labels = int(labels)
 
    # align the two proteins
    aln = '__aln'
 
    # first, an alignment with 0 cycles (no atoms are rejected, which maximized the number of aligned residues)
    # for some mutations in the same protein this works fine). This is essentially done to get a
    # sequence alignment
    cmd.super(obj1, obj2, object=aln, cycles=0)
 
    # superimpose the the object using the default parameters to get a slightly better superimposition,
    # i.e. get the best structural alignment    
    cmd.super(obj1, obj2)
 
    stored.resn1, stored.resn2 = [], []
    stored.resi1, stored.resi2 = [], []
    stored.chain1, stored.chain2 = [], []
 
    # store residue ids, residue names and chains of aligned residues
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resn1.append(resn)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resn2.append(resn)')
 
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.resi1.append(resi)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.resi2.append(resi)')
 
    cmd.iterate(obj1 + ' and name CA and ' + aln, 'stored.chain1.append(chain)')
    cmd.iterate(obj2 + ' and name CA and ' + aln, 'stored.chain2.append(chain)')
 
 
    mutant_selection = '' 
    non_mutant_selection = 'none or '
    colors = []
 
    # loop over the aligned residues
    for n1, n2, i1, i2, c1, c2 in zip(stored.resn1, stored.resn2,
                                      stored.resi1, stored.resi2,
                                      stored.chain1, stored.chain2):
        # take care of 'empty' chain names
        if c1 == '':
            c1 = '""'
        if c2 == '':
            c2 = '""'
        if n1 == n2:
            non_mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )            
        else:
            mutant_selection += '((%s and resi %s and chain %s) or (%s and resi %s and chain %s)) or '%(obj1, i1, c1, obj2, i2, c2 )
            # get the similarity (according to the blosum matrix) of the two residues and
            c = getBlosum90ColorName(n1, n2)
            colors.append((c, '%s and resi %s and chain %s and elem C'%(obj2, i2, c2)))
 
    if mutant_selection == '':
        print ' Error: No mutations found'
        raise CmdException
 
    # create selections        
    cmd.select('mutations', mutant_selection[:-4])
    cmd.select('non_mutations', non_mutant_selection[:-4])
    cmd.select('not_aligned', '(%s or %s) and not mutations and not non_mutations'%(obj1, obj2))
 
    # create the view and coloring
    cmd.hide('everything', '%s or %s'%(obj1, obj2))
    cmd.show('cartoon', '%s or %s'%(obj1, obj2))
    cmd.show('lines', '(%s or %s) and ((non_mutations or not_aligned) and not name c+o+n)'%(obj1, obj2))
    cmd.show('sticks', '(%s or %s) and mutations and not name c+o+n'%(obj1, obj2))
    cmd.color('gray', 'elem C and not_aligned')
    cmd.color('white', 'elem C and non_mutations')
    cmd.color('blue', 'elem C and mutations and %s'%obj1)
    for (col, sel) in colors:
        cmd.color(col, sel)
 
    cmd.hide('everything', '(hydro) and (%s or %s)'%(obj1, obj2))        
    cmd.center('%s or %s'%(obj1, obj2))
    if labels:
        cmd.label('mutations and name CA','"(%s-%s-%s)"%(chain, resi, resn)')    
    if waters:
        cmd.set('sphere_scale', '0.1')
        cmd.show('spheres', 'resn HOH and (%s or %s)'%(obj1, obj2))
        cmd.color('red', 'resn HOH and %s'%obj1)
        cmd.color('salmon', 'resn HOH and %s'%obj2)
    print '''
             Mutations are highlighted in blue and red.
             All mutated sidechains of %s are colored blue, the corresponding ones from %s are
             colored on a spectrum from blue to red according to how similar the two amino acids are
             (as measured by the BLOSUM90 substitution matrix).
             Aligned regions without mutations are colored white.
             Regions not used for the alignment are gray.
             NOTE: There could be mutations in the gray regions that were not detected.'''%(obj1, obj2)
    cmd.delete(aln)
    cmd.deselect()
Ejemplo n.º 34
0
    struct = os.path.splitext(struct_name)[0].upper()
    try:
        routine = routines[struct]
    except KeyError, e:
        print('Routine not defined for this structure')
        raise e
    
    h = hypergraph.Hypergraph(routine.file)
    h.hyper_analyze(*routine[1:])
    
    if load_struct:
        cmd.load(routine.file)
        cmd.select('A', 'chain a')
        cmd.hide('all')
        cmd.show('cartoon', 'A')
        cmd.center('A')
    return h

#Holo structure
holo = get_struct_hypergraph('3eyc', load_struct=True)
#Apo structure
apo = get_struct_hypergraph('1xki', load_struct=False)
#Rudimentary summation of the two sequences
h_seq = holo.unaligned_edge_weights_by_seq
a_seq = apo.unaligned_edge_weights_by_seq
seq_scores = [i + j for i, j in zip(h_seq, a_seq)]

#Modify these to use different colors, use valid PyMOL named colors
start_color= 'yelloworange'
end_color = 'density'
Ejemplo n.º 35
0
def colorDialog(app, mode):
    prefix = tkSimpleDialog.askstring('Prefix',
    'Enter the prefix of symmetry partners to color', parent = app.root)
    if mode == 0: #standard rainbow by symmetry operation
        colors = ["red", "orange", "yellow", "green", "blue", "purple",
              "salmon", "grey", "pink", "teal", "brown", "br0", "aquamarine", 
              "deepolive", "dirtyviolet", "slate", "br4", "darksalmon", "br7",
              "chocolate", "firebrick", "brightorange"]
        for i in range(10):
            try: #required because PyMOL inappropriately throws an exception
                 #when the cmd.color() function colors no objects
                cmd.color(colors[i], prefix + "0" + str(i) + "*")
            except:
                pass #allows us to move on to next symmetry operator
        for i in range(10,20):
            try: #required because PyMOL inappropriately throws an exception
                 #when the cmd.color() function colors no objects
                cmd.color(colors[i], prefix + str(i) + "*")
            except:
                pass #allows us to move on to next symmetry operator
    if mode == 1: #specify for each symmetry operation
        cmd.iterate_state(1, prefix + "*", "stored.tmpObject = model")
        ops = get_operations(stored.tmpObject)
        opString = ""
        for i in range(len(ops)):
            opString = opString + str(i) + " : " + ops[i] + "\n"
        opIndeces = tkSimpleDialog.askstring("Symmetry Operations", opString +
        "Enter numbers of desired operations separated by commas (ex:0,2,9) or all", parent = app.root) 
        if opIndeces == "all":
            opList = []
            for i in range(len(ops)):
                opList.append(i)
        else:
            opList = opIndeces.split(",")
        opStringList = opString.split("\n")
        for i in opList:
            try:
                if int(i) < 10:
                    cmd.color("white", prefix + "0" + str(i) + "*")
                    cmd.center(prefix + "0" + str(i) + "*")
                if int(i) > 9:
                    cmd.color("white", prefix + str(i) + "*")
                    cmd.center(prefix + str(i) + "*")
                
            except:
                pass
            tempColor = tkColorChooser.askcolor(title = "Color for " + opStringList[int(i)] + " (currently white)",
                                                parent = app.root)[0]
            rgb = []
            for value in tempColor:
                value = float(value)
                value = value/255
                rgb.append(value)
            cmd.set_color("tempColor", rgb)
            try:
                if int(i) < 10:
                    cmd.color("tempColor", prefix + "0" + str(i) + "*")
                if int(i) > 9:
                    cmd.color("tempColor", prefix + str(i) + "*")
            except:
                pass
    if mode == 2: #monochrome for a set of operations
        cmd.iterate_state(1, prefix + "*", "stored.tmpObject = model")
        ops = get_operations(stored.tmpObject)
        opString = ""
        for i in range(len(ops)):
            opString = opString + str(i) + " : " + ops[i] + "\n"
        opIndeces = tkSimpleDialog.askstring("Symmetry Operations", opString +
        "Enter numbers of desired operations separated by commas (ex:0,2,9) or all", parent = app.root) 
        if opIndeces == 'all':
            opList = []
            for i in range(len(ops)):
                opList.append(i)
        else:
            opList = opIndeces.split(",")
        opStringList = opString.split("\n")
        tempColor = tkColorChooser.askcolor(parent = app.root)[0]
        rgb = []
        for value in tempColor:
            value = float(value)
            value = value/255
            rgb.append(value)
        cmd.set_color("tempColor", rgb)
        for i in opList:
            try:
                if int(i) < 10:
                    cmd.color("tempColor", prefix + "0" + str(i) + "*")
                if int(i) > 9:
                    cmd.color("tempColor", prefix + str(i) + "*")
            except:
                pass
Ejemplo n.º 36
0
X = (values_to_show - np.percentile(np.unique(values_to_show), 50))/(MAX - MIN)
SCALES = 1/(0.5 + np.exp(-X * 5))

######## some pymol settings #########
cmd.set("retain_order", 1)
cmd.set("cartoon_oval_length", 1.0)
cmd.set("cartoon_oval_width", 0.3)
cmd.set("cartoon_color", "white")
cmd.set("stick_radius", 0.35)

##################################
cmd.load("./A2a_active_renumbered.pdb", "Prot_DOPS")
prefix = "Prot_DOPS"
cmd.hide("everything")
cmd.show("cartoon", prefix)
cmd.center(prefix)
cmd.orient(prefix)
colors = np.array([np.random.choice(np.arange(256, dtype=float), size=3) for dummy in range(binding_site_id)])
colors /= 255.0

residue_set = np.array(residue_set, dtype=str)
residue_rank_set = np.array(residue_rank_set, dtype=int)
binding_site_identifiers = np.array(binding_site_identifiers, dtype=int)
residue_identifiers = list(residue_identifiers)
for bs_id in np.arange(binding_site_id):
    cmd.set_color("tmp_{}".format(bs_id), list(colors[bs_id]))
    for entry_id in np.where(binding_site_identifiers == bs_id)[0]:
        selected_residue = residue_set[entry_id]
        selected_residue_rank = residue_rank_set[entry_id]
        identifier_from_pdb = residue_identifiers[selected_residue_rank]
        if re.findall("[a-zA-Z]+$", selected_residue)[0] != identifier_from_pdb[1]:
Ejemplo n.º 37
0
    def do_library(self):
        cmd = self.cmd
        pymol = cmd._pymol
        if not (
            (cmd.count_atoms("(%s) and name n" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name c" % src_sele) == 1)
            and (cmd.count_atoms("(%s) and name o" % src_sele) == 1)
        ):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable", "selector", "everythin")
        cmd.feedback("disable", "editor", "actions")
        self.prompt = ["Loading rotamers..."]

        pymol.stored.name = "residue"
        cmd.iterate("first (%s)" % src_sele, 'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight", src_sele)

        auto_zoom = cmd.get_setting_text("auto_zoom")
        cmd.set("auto_zoom", "0", quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele, animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode == "current":
            pymol.stored.resn = ""
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn, pymol.stored.resn)
            if (self.c_cap != "none") or (self.n_cap != "none") or (self.hyd != "auto"):
                self.lib_mode = rot_type  # force fragment-based load
            else:
                cmd.create(frag_name, src_sele, 1, 1)
                if self.c_cap == "open":
                    cmd.remove("%s and name OXT" % frag_name)

        if self.lib_mode != "current":
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == "posi") and (frag_type[0:3] != "NT_"):
                if not (cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) &! r. ace" % (src_sele, src_sele))):
                    # use N-terminal fragment
                    frag_type = "NT_" + frag_type
            if (self.c_cap == "nega") and (frag_type[0:3] != "CT_"):
                if not (cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele))):
                    # use C-terminal fragment
                    frag_type = "CT_" + frag_type
            if rot_type[0:3] in ["NT_", "CT_"]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(string.lower(frag_type), frag_name)
            # trim off hydrogens
            if self.hyd == "none":
                cmd.remove("(" + frag_name + " and hydro)")
            elif self.hyd == "auto":
                if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                    cmd.remove("(" + frag_name + " and hydro)")
            # copy identifying information
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.chain=chain")
            cmd.alter("(%s)" % frag_name, "chain=stored.chain")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.resi=resi")
            cmd.alter("(%s)" % frag_name, "resi=stored.resi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.segi=segi")
            cmd.alter("(%s)" % frag_name, "segi=stored.segi")
            cmd.iterate("(%s and n;ca)" % src_sele, "stored.ss=ss")
            cmd.alter("(%s)" % frag_name, "ss=stored.ss")
            # move the fragment
            if (cmd.count_atoms("(%s and n;cb)" % frag_name) == 1) and (
                cmd.count_atoms("(%s and n;cb)" % src_sele) == 1
            ):
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;cb)" % frag_name,
                    "(%s and n;cb)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )
            else:
                cmd.pair_fit(
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;ca)" % src_sele,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;c)" % src_sele,
                    "(%s and n;n)" % frag_name,
                    "(%s and n;n)" % src_sele,
                )

            # fix the carbonyl position...
            cmd.iterate_state(1, "(%s and n;o)" % src_sele, "stored.list=[x,y,z]")
            cmd.alter_state(1, "(%s and n;o)" % frag_name, "(x,y,z)=stored.list")
            if cmd.count_atoms("(%s and n;oxt)" % src_sele):
                cmd.iterate_state(1, "(%s and n;oxt)" % src_sele, "stored.list=[x,y,z]")
                cmd.alter_state(1, "(%s and n;oxt)" % frag_name, "(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s and n;oxt)" % frag_name):  # place OXT if no template exists
                angle = cmd.get_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;o)" % frag_name,
                )
                cmd.protect("(%s and n;o)" % frag_name)
                cmd.set_dihedral(
                    "(%s and n;n)" % frag_name,
                    "(%s and n;ca)" % frag_name,
                    "(%s and n;c)" % frag_name,
                    "(%s and n;oxt)" % frag_name,
                    180.0 + angle,
                )
                cmd.deprotect(frag_name)

            # fix the hydrogen position (if any)
            if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % frag_name) == 1:
                if cmd.count_atoms("(elem h and bound_to (n;n and (%s)))" % src_sele) == 1:
                    cmd.iterate_state(1, "(elem h and bound_to (n;n and (%s)))" % src_sele, "stored.list=[x,y,z]")
                    cmd.alter_state(1, "(elem h and bound_to (n;n and (%s)))" % frag_name, "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1, "(n;c and bound_to (%s and e;n))" % src_sele) == 1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral(
                        "(%s and n;c)" % frag_name, "(%s and n;ca)" % frag_name, "(%s and n;n)" % frag_name, tmp_sele1
                    )
                    cmd.set_dihedral(
                        "(%s and n;c)" % frag_name,
                        "(%s and n;ca)" % frag_name,
                        "(%s and n;n)" % frag_name,
                        "(%s and n;h)" % frag_name,
                        180.0 + angle,
                    )
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in ["amin", "nmet"]:
                if not cmd.count_atoms("elem n & !(%s) & (bto. (n;c & (%s))) & !r. nme+nhh" % (src_sele, src_sele)):
                    if cmd.count_atoms("n;c & (%s)" % (frag_name)) == 1:
                        if self.c_cap == "amin":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nhh")
                        elif self.c_cap == "nmet":
                            editor.attach_amino_acid("n;c & (%s)" % (frag_name), "nme")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & bound_to (n;c & (%s))" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

            # add n-cap (if appropriate)
            if self.n_cap in ["acet"]:
                if not cmd.count_atoms("elem c & !(%s) & (bto. (n;n & (%s))) & !r. ace " % (src_sele, src_sele)):
                    if cmd.count_atoms("n;n & (%s)" % (frag_name)) == 1:
                        if self.n_cap == "acet":
                            editor.attach_amino_acid("n;n & (%s)" % (frag_name), "ace")
                        if cmd.count_atoms("hydro & bound_to (n;n & bound_to (n;c & (%s)))" % frag_name):
                            cmd.h_fix("n;n & (%s)" % frag_name)
                        # trim hydrogens
                        if self.hyd == "none":
                            cmd.remove("(" + frag_name + " and hydro)")
                        elif self.hyd == "auto":
                            if cmd.count_atoms("(" + src_sele + ") and hydro") == 0:
                                cmd.remove("(" + frag_name + " and hydro)")

        cartoon = cmd.count_atoms("(%s and n;ca and rep cartoon)" % src_sele) > 0
        sticks = cmd.count_atoms("(%s and n;ca and rep sticks)" % src_sele) > 0

        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == "dep":
            try:
                result = cmd.phi_psi("%s" % src_sele)
                if len(result) == 1:
                    (phi, psi) = result[result.keys()[0]]
                    (phi, psi) = (int(10 * round(phi / 10)), int(10 * (round(psi / 10))))
                    key = (rot_type, phi, psi)
                    if not self.dep_library.has_key(key):
                        (phi, psi) = (int(20 * round(phi / 20)), int(20 * (round(psi / 20))))
                        key = (rot_type, phi, psi)
                        if not self.dep_library.has_key(key):
                            (phi, psi) = (int(60 * round(phi / 60)), int(60 * (round(psi / 60))))
                            key = (rot_type, phi, psi)
                    lib = self.dep_library.get(key, None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key, None)
            if (lib != None) and self.dep == "dep":
                print " Mutagenesis: no phi/psi, using backbone-independent rotamers."
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name, frag_name, 1, state)
                if state == 1:
                    cmd.select(mut_sele, "(byres (%s like %s))" % (obj_name, src_sele))
                if rot_type == "PRO":
                    cmd.unbond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                for b in a.keys():
                    if b != "FREQ":
                        cmd.set_dihedral(
                            "(%s & n;%s)" % (mut_sele, b[0]),
                            "(%s & n;%s)" % (mut_sele, b[1]),
                            "(%s & n;%s)" % (mut_sele, b[2]),
                            "(%s & n;%s)" % (mut_sele, b[3]),
                            a[b],
                            state=state,
                        )
                    else:
                        cmd.set_title(obj_name, state, "%1.1f%%" % (a[b] * 100))
                if rot_type == "PRO":
                    cmd.bond("(%s & name N)" % mut_sele, "(%s & name CD)" % mut_sele)
                state = state + 1
            cmd.delete(frag_name)
            print " Mutagenesis: %d rotamers loaded." % len(lib)
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(
                    bump_name,
                    "(((byobj %s) within 6 of (%s and not name n+c+ca+o+h+ha)) and (not (%s)))|(%s)"
                    % (src_sele, mut_sele, src_sele, mut_sele),
                    singletons=1,
                )
                cmd.color("gray50", bump_name + " and elem c")
                cmd.set("seq_view", 0, bump_name, quiet=1)
                cmd.hide("everything", bump_name)
                if (cmd.select(tmp_sele1, "(n;N and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;C and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                if (cmd.select(tmp_sele1, "(n;C and (%s in (neighbor %s)))" % (bump_name, src_sele)) == 1) and (
                    cmd.select(tmp_sele2, "(n;N and (%s in %s))" % (bump_name, mut_sele)) == 1
                ):
                    cmd.bond(tmp_sele1, tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)

                cmd.protect("%s and not (%s in (%s and not name n+c+ca+o+h+ha))" % (bump_name, bump_name, mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo", bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode", 1, bump_name)
                state = 1
                for a in lib:
                    cmd.sculpt_iterate(bump_name, state=state)
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name, frag_name, 1, 1)
            print " Mutagenesis: no rotamers found in library."
        cmd.set("seq_view", 0, obj_name, quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("(" + obj_name + ")")
        cmd.show(self.rep, obj_name)
        cmd.show("lines", obj_name)  # neighbor  always show lines
        if cartoon:
            cmd.show("cartoon", obj_name)
        if sticks:
            cmd.show("sticks", obj_name)
        cmd.set("auto_zoom", auto_zoom, quiet=1)
        cmd.delete(frag_name)
        cmd.frame(0)
        cmd.unpick()
        cmd.feedback("pop")
Ejemplo n.º 38
0
    def _do_mutation(self):
        '''
        After selection, propose what the fragment will look like where
        applied.
        Exception: _do_mutation should be wrapped in a try-exception block
                   when called
        '''
        cmd = self.cmd

        cmd.delete(FRAG_NAME)
        cmd.refresh_wizard()

        if any(
                cmd.count_atoms("(%s) & name %s" % (SRC_SELE, name)) != 1
                for name in ("C1'", "C2'", "C3'", "C4'", "O4'")):
            self.clear()
            raise pymol.wizarding.WizardError(
                'Improper selection of nucleic acid.')

        frag_type_lower = self._mode_labels[self.mode].lower()
        cmd.fragment(frag_type_lower, FRAG_NAME, origin=0)
        self._update_reps()
        cmd.color("white", "%s & elem C" % FRAG_NAME)
        cmd.iterate(
            "first (%s)" % SRC_SELE,
            'stored.name = model+"/"+segi+"/"+chain+"/"+resn+"`"+resi',
            space=self._space)
        self.res_text = self._space['stored'].name

        cmd.alter(
            "?%s & name C1'" % SRC_SELE,
            "stored.identifiers = (segi, chain, resi, ss, color)",
            space=self._space)
        self._status = Status.MUTAGENIZING
        self.get_prompt()

        cmd.iterate(
            "(%s & name C1')" % SRC_SELE,
            "stored.resn = resn",
            space=self._space)
        src_type_lower = self._space['stored'].resn.lower()
        self._src_O_atom_name, self._src_Cp_atom_name, self._src_N_atom_name, \
        self._src_C_atom_name = self._get_chi_dihedral_atoms(src_type_lower)

        self._frag_O_atom_name, self._frag_Cp_atom_name, self._frag_N_atom_name, \
        self._frag_C_atom_name = self._get_chi_dihedral_atoms(frag_type_lower)

        cmd.pair_fit("(%s & name %s)" % (FRAG_NAME, self._frag_O_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_O_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_Cp_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_Cp_atom_name),
                     "(%s & name %s)" % (FRAG_NAME, self._frag_N_atom_name),
                     "(%s & name %s)" % (SRC_SELE, self._src_N_atom_name))

        self._transfer_dihedral()

        for a in self._sugar_phos_atoms:
            cmd.remove("(%s & name %s)" % (FRAG_NAME, a))

        if self._auto_center == "ON":
            cmd.center(FRAG_NAME, animate=1)
Ejemplo n.º 39
0
def optAlign( sel1, sel2 ):
	"""
	optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections.
	Example:   optAlign MOL1 and i. 20-40, MOL2 and i. 102-122
	Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA
	
	Two RMSDs are returned.  One comes from the Kabsch algorithm and the other from
	PyMol based upon your selections.

	By default, this program will optimally align the ALPHA CARBONS of the selections provided.
	To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below.
	
	@param sel1: First PyMol selection with N-atoms
	@param sel2: Second PyMol selection with N-atoms
	"""
	cmd.reset()

	# make the lists for holding coordinates
	# partial lists
	stored.sel1 = []
	stored.sel2 = []
	# full lists
	stored.mol1 = []
	stored.mol2 = []

	# now put the coordinates into a list
	# partials

	# -- REMOVE ALPHA CARBONS
	sel1 = sel1 + " and N. CA"
	sel2 = sel2 + " and N. CA"
	# -- REMOVE ALPHA CARBONS

	cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")
	cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")
	# full molecule
	mol1 = cmd.identify(sel1,1)[0][0]
	mol2 = cmd.identify(sel2,1)[0][0]
	cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")
	cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")

	K = kabsch()
	U, T1, T2, RMSD, c1, c2 = K.align(stored.sel1, stored.sel2, [])

	stored.mol2 = map(lambda v:[T2[0]+((v[0]*U[0][0])+(v[1]*U[1][0])+(v[2]*U[2][0])),T2[1]+((v[0]*U[0][1])+(v[1]*U[1][1])+(v[2]*U[2][1])),T2[2]+((v[0]*U[0][2])+(v[1]*U[1][2])+(v[2]*U[2][2]))],stored.mol2)
	#stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1)
	stored.mol1 = map(lambda v:[ v[0]+T1[0], v[1]+T1[1], v[2]+T1[2] ], stored.mol1)

	cmd.alter_state(1,mol1,"(x,y,z)=stored.mol1.pop(0)")
	cmd.alter_state(1,mol2,"(x,y,z)=stored.mol2.pop(0)")
	cmd.alter( 'all',"segi=''")
	cmd.alter('all', "chain=''")
	print "RMSD=%f" % cmd.rms_cur(sel1, sel2)
	print "MY RMSD=%f" % RMSD
	cmd.hide('everything')
	cmd.show('ribbon', sel1 + ' or ' + sel2)
	cmd.color('gray70', mol1 )
	cmd.color('paleyellow', mol2 )
	cmd.color('red', 'visible')
	cmd.show('ribbon', 'not visible')
	cmd.center('visible')
	cmd.orient()
	cmd.zoom('visible')
Ejemplo n.º 40
0
def option1():

	vinacomd = str(checkutilities())
	A = inputdata1()
	
	global proteinfile, ligandoption, ligandfile, centerx, centery, centerz

	if ligandoption == '2':

		UL = MDAnalysis.Universe(ligandfile)
		if ligandfile[-5:] == 'pdbqt':
			heavylig = UL.select_atoms('not type HD')
		else:
			heavylig = UL.select_atoms('not type H')

		com = np.mean(heavylig.positions, axis = 0)
		centerx = com[0]
		centery = com[1]
		centerz = com[2]


	waterfile()
	proteinpdbqtfile = proteinfile

	f1 = open('vinaconfig.txt','w')
	f1.write('receptor = ')
	f1.write(str(proteinpdbqtfile))
	f1.write('\nligand = water.pdbqt')
	f1.write('\nexhaustiveness = 20')
	f1.write('\nnum_modes = 20')
	f1.write('\ncenter_x = ')
	f1.write(str(centerx))
	f1.write('\ncenter_y = ')
	f1.write(str(centery))
	f1.write('\ncenter_z = ')
	f1.write(str(centerz))
	f1.write('\nsize_x = 15')
	f1.write('\nsize_y = 15')
	f1.write('\nsize_z = 15')
	f1.write('\nenergy_range = 100')
	f1.write('\nlog = outputlog.txt')
	f1.write('\nout = waterout.pdbqt')
	f1.close()

	for i in range(1,4):
		tempcomd = vinacomd + ' --config vinaconfig.txt'
		os.system(tempcomd)
		os.system("grep 'OW' waterout.pdbqt >> allwater.pdbqt")
		os.system("grep 'RESULT' waterout.pdbqt >> result.log")
		os.remove('outputlog.txt')
		os.remove('waterout.pdbqt')

	os.remove('vinaconfig.txt')
	coods = np.genfromtxt('allwater.pdbqt', usecols = (5,6,7), dtype = float)
	energy = np.genfromtxt('result.log', usecols = 3, dtype = float)

	selectcoods = np.compress(energy < -0.5, coods, axis = 0)
		
	fit1 = scipy.cluster.hierarchy.fclusterdata(selectcoods, 0.5, criterion = 'distance', metric = 'euclidean')
	fit1 = fit1.astype(int)
	numclust1 = np.max(fit1)

	clustcoods = np.zeros((numclust1,3), dtype = float)
	for i in xrange(1,numclust1+1):

		temp = np.compress(fit1 == i, selectcoods, axis = 0)
		tempavg = np.mean(temp, axis = 0)
		clustcoods[i-1,:] = tempavg

	fit2 = scipy.cluster.hierarchy.fclusterdata(clustcoods, 1.6, criterion = 'distance', metric = 'euclidean')
	fit2 = fit2.astype(int)
	numclust2 = np.max(fit2)

	finalcoods = np.zeros((numclust2,3), dtype = float)
	for i in xrange(1,numclust2+1):

		temp = np.compress(fit2 == i, clustcoods, axis = 0)
		tempavg = np.mean(temp, axis = 0)
		finalcoods[i-1,:] = tempavg

	if os.path.isfile('predictedwaters.pdb'):
		os.rename('predictedwaters.pdb','#predictedwaters.pdb')
	write_waterpdb('predictedwaters.pdb',finalcoods)

	os.remove('allwater.pdbqt')
	os.remove('result.log')
	os.remove('water.pdbqt')

	cmd.set("retain_order", 1)
	cmd.set("pdb_use_ter_records", 0)
	cmd.load(proteinfile, 'pro')
	cmd.show_as('cartoon', 'pro')
	cmd.color('blue','pro')
	cmd.load('predictedwaters.pdb','wats')
	cmd.color('red','wats')
	cmd.center('wats')
def _contact_map_visualizer(image_file, selection, screenshots, quiet, **kwargs):
    from datetime import datetime

    try:
        import pygame as pg
    except ImportError:
        print(' Error: This plugin requires the "pygame" module')
        raise CmdException

    screenshots, quiet = int(screenshots), int(quiet)

    cmd.set('sphere_scale', 0.25)

    idx_list = []
    cmd.iterate('(%s) and name CA' % (selection),
                'idx_list.append(((model,index),chain,resi))', space=locals())
    cmd.color("white", selection)

    # General variables
    count = 0
    sel = 0
    ntime = datetime.now()
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    if screenshots:
        outputname = "%s_selectedPoints_%d-%d-%d_%d%d.png" % (os.path.basename(image_file),
                                                              ntime.day, ntime.month, ntime.year, ntime.hour, ntime.minute)

    # Text related arrays nd variables
    text = []
    textRect = []
    textcount = -1

    # screen height
    try:
        screen_height = cmd.pymol._ext_gui.root.winfo_screenheight()
    except:
        print(' Warning: could not determine screen height')
        screen_height = 700

    # use an image you have (.bmp  .jpg  .png  .gif)
    image = pg.image.load(image_file)
    image_height = image.get_height()

    factor = max((screen_height - 100) / image_height, 1)
    height = image_height * factor
    factor = 1.0 / factor

    if image_height != len(idx_list):
        print(' Warning: Dimension of image and number of CA atoms in selection', end=' ')
        print('differ! (%d vs. %d)' % (image_height, len(idx_list)))

    # initialize pygame
    pg.init()
    screen = pg.display.set_mode((height, height))
    pg.display.set_caption('Choose the location by clicking')
    image = pg.transform.scale(image.convert(), (height, height))
    image_rect = image.get_rect()

    while True:
        event = pg.event.poll()
        keyinput = pg.key.get_pressed()

        # exit on corner 'x' click or escape key press
        if keyinput[pg.K_ESCAPE] or event.type == pg.QUIT:
            break

        if event.type == pg.MOUSEBUTTONDOWN:
            coor = [event.pos[0] * factor, (height - event.pos[1]) * factor]

            try:
                idx1, chain1, resi1 = idx_list[int(coor[0])]
                idx2, chain2, resi2 = idx_list[int(coor[1])]
            except IndexError:
                print(' Error: selection to small')
                continue

            print(' You clicked %s/%s/ %s/%s/' % (chain1, resi1, chain2, resi2))

            sel = 1
            textcount += 1

            selectionname = '%s%s_%s%s' % (resi1, chain1, resi2, chain2)
            cmd.select(selectionname, 'byres (%s`%d %s`%d)' % tuple(idx1 + idx2))

            cmd.show('sticks', selectionname)
            cmd.show('spheres', selectionname)

            cmd.color(colors[count], selectionname)
            cmd.center(selectionname, animate=1)

            pg.draw.circle(image, colors_value[count], event.pos, 3, 0)

            # set up fonts
            basicFont = pg.font.SysFont('Arial', 12)
            name = '(%s%s, %s%s)' % (resi1, chain1, resi2, chain2)

            # set up the text
            text.append(basicFont.render(name, True, WHITE, BLACK))
            textRect.append(text[textcount].get_rect())
            textRect[textcount][0] = event.pos[0] + 5
            textRect[textcount][1] = event.pos[1] + 5

            screen.blit(image, image_rect)
            for a in range(textcount + 1):
                screen.blit(text[a], textRect[a])
            pg.display.flip()

            if screenshots:
                if not quiet:
                    print(' Writing image to', outputname)
                pg.image.save(screen, outputname)

            count += 1
            if count >= len(colors):
                count = 0

        # update screen
        screen.blit(image, image_rect)
        if sel == 1:
            for a in range(textcount + 1):
                screen.blit(text[a], textRect[a])
        pg.display.flip()

    pg.quit()
Ejemplo n.º 42
0
    def do_library(self):
        cmd=self.cmd
        pymol=cmd._pymol
        if not ((cmd.count_atoms("(%s) and name N"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name C"%src_sele)==1) and
                (cmd.count_atoms("(%s) and name O"%src_sele)==1)):
            self.clear()
            return 1
        cmd.feedback("push")
        cmd.feedback("disable","selector","everythin")
        cmd.feedback("disable","editor","actions")
        self.prompt = [ 'Loading rotamers...']
        self.bump_scores = []
        state_best = 0

        pymol.stored.name = 'residue'
        cmd.iterate("first (%s)"%src_sele,'stored.name=model+"/"+segi+"/"+chain+"/"+resn+"`"+resi')
        self.res_text = pymol.stored.name
        cmd.select("_seeker_hilight",src_sele)
        
        auto_zoom = cmd.get_setting_text('auto_zoom')
        cmd.set('auto_zoom',"0",quiet=1)
        cmd.frame(0)
        cmd.delete(frag_name)
        if self.auto_center:
            cmd.center(src_sele,animate=-1)

        self.lib_mode = self.mode
        if self.lib_mode=="current":
            pymol.stored.resn=""
            cmd.iterate("(%s & name CA)"%src_sele,"stored.resn=resn")
            rot_type = _rot_type_xref.get(pymol.stored.resn,pymol.stored.resn)
            if (self.c_cap!='none') or (self.n_cap!='none') or (self.hyd != 'auto'):
                self.lib_mode = rot_type # force fragment-based load
            else:
                cmd.create(frag_name,src_sele,1,1)
                if self.c_cap=='open':
                    cmd.remove("%s and name OXT"%frag_name)
                    
        if self.lib_mode!='current':
            rot_type = self.lib_mode
            frag_type = self.lib_mode
            if (self.n_cap == 'posi') and (frag_type[0:3]!='NT_'):
                if not ( cmd.count_atoms(
                    "elem C & !(%s) & (bto. (name N & (%s))) &! resn ACE"%
                                     (src_sele,src_sele))):
                    # use N-terminal fragment
                    frag_type ="NT_"+frag_type
            if (self.c_cap == 'nega') and (frag_type[0:3]!='CT_'):
                if not ( cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                     (src_sele,src_sele))):
                    # use C-terminal fragment
                    frag_type ="CT_"+frag_type
            if rot_type[0:3] in [ 'NT_', 'CT_' ]:
                rot_type = rot_type[3:]
            rot_type = _rot_type_xref.get(rot_type, rot_type)
            cmd.fragment(frag_type.lower(), frag_name, origin=0)
            # trim off hydrogens
            if (self.hyd == 'none'):
                cmd.remove("("+frag_name+" and hydro)")
            elif (self.hyd == 'auto'):
                if cmd.count_atoms("("+src_sele+") and hydro")==0:
                    cmd.remove("("+frag_name+" and hydro)")
            # copy identifying information
            cmd.alter("?%s & name CA" % src_sele, "stored.identifiers = (segi, chain, resi, ss, color)", space=self.space)
            cmd.alter("?%s" % frag_name, "(segi, chain, resi, ss) = stored.identifiers[:4]", space=self.space)
            # move the fragment
            if ((cmd.count_atoms("(%s & name CB)"%frag_name)==1) and
                 (cmd.count_atoms("(%s & name CB)"%src_sele)==1)):
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name CB)"%frag_name,
                             "(%s & name CB)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)
            else:
                cmd.pair_fit("(%s & name CA)"%frag_name,
                             "(%s & name CA)"%src_sele,
                             "(%s & name C)"%frag_name,
                             "(%s & name C)"%src_sele,
                             "(%s & name N)"%frag_name,
                             "(%s & name N)"%src_sele)

            # fix the carbonyl position...
            cmd.iterate_state(1,"(%s & name O)"%src_sele,"stored.list=[x,y,z]")
            cmd.alter_state(1,"(%s & name O)"%frag_name,"(x,y,z)=stored.list")
            if cmd.count_atoms("(%s & name OXT)"%src_sele):
                cmd.iterate_state(1,"(%s & name OXT)"%src_sele,"stored.list=[x,y,z]")
                cmd.alter_state(1,"(%s & name OXT)"%frag_name,"(x,y,z)=stored.list")
            elif cmd.count_atoms("(%s & name OXT)"%frag_name): # place OXT if no template exists
                angle = cmd.get_dihedral("(%s & name N)"%frag_name,
                                         "(%s & name CA)"%frag_name,
                                         "(%s & name C)"%frag_name,
                                         "(%s & name O)"%frag_name)
                cmd.protect("(%s & name O)"%frag_name)
                cmd.set_dihedral("(%s & name N)"%frag_name,
                                 "(%s & name CA)"%frag_name,
                                 "(%s & name C)"%frag_name,
                                 "(%s & name OXT)"%frag_name,180.0+angle)
                cmd.deprotect(frag_name)

                
            # fix the hydrogen position (if any)
            if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%frag_name)==1:
                if cmd.count_atoms("(hydro and bound_to (name N & (%s)))"%src_sele)==1:
                    cmd.iterate_state(1,"(hydro and bound_to (name N & (%s)))"%src_sele,
                                      "stored.list=[x,y,z]")
                    cmd.alter_state(1,"(hydro and bound_to (name N & (%s)))"%frag_name,
                                    "(x,y,z)=stored.list")
                elif cmd.select(tmp_sele1,"(name C & bound_to (%s and elem N))"%src_sele)==1:
                    # position hydro based on location of the carbonyl
                    angle = cmd.get_dihedral("(%s & name C)"%frag_name,
                                             "(%s & name CA)"%frag_name,
                                             "(%s & name N)"%frag_name,
                                             tmp_sele1)
                    cmd.set_dihedral("(%s & name C)"%frag_name,
                                     "(%s & name CA)"%frag_name,
                                     "(%s & name N)"%frag_name,
                                     "(%s & name H)"%frag_name,180.0+angle)
                    cmd.delete(tmp_sele1)

            # add c-cap (if appropriate)
            if self.c_cap in [ 'amin', 'nmet' ]:
                if not cmd.count_atoms("elem N & !(%s) & (bto. (name C & (%s))) & !resn NME+NHH"%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name C & (%s)"%(frag_name))==1:
                        if self.c_cap == 'amin':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nhh')
                        elif self.c_cap == 'nmet':
                            editor.attach_amino_acid("name C & (%s)"%(frag_name), 'nme')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & bound_to (name C & (%s))"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
                         
            # add n-cap (if appropriate)
            if self.n_cap in [ 'acet' ]:
                if not cmd.count_atoms("elem C & !(%s) & (bto. (name N & (%s))) & !resn ACE "%
                                       (src_sele,src_sele)):
                    if cmd.count_atoms("name N & (%s)"%(frag_name))==1:
                        if self.n_cap == 'acet':
                            editor.attach_amino_acid("name N & (%s)"%(frag_name), 'ace')
                        if cmd.count_atoms("hydro & bound_to (name N & bound_to (name C & (%s)))"%frag_name):
                            cmd.h_fix("name N & (%s)"%frag_name)
                        # trim hydrogens
                        if (self.hyd == 'none'):
                            cmd.remove("("+frag_name+" and hydro)")
                        elif (self.hyd == 'auto'):
                            if cmd.count_atoms("("+src_sele+") and hydro")==0:
                                cmd.remove("("+frag_name+" and hydro)")
 

                    

        cartoon = (cmd.count_atoms("(%s & name CA & rep cartoon)"%src_sele)>0)
        sticks = (cmd.count_atoms("(%s & name CA & rep sticks)"%src_sele)>0)
            
        cmd.delete(obj_name)
        key = rot_type
        lib = None
        if self.dep == 'dep':
            try:
                result = cmd.phi_psi("%s"%src_sele)
                if len(result)==1:
                    (phi,psi) = list(result.values())[0]
                    (phi,psi) = (int(10*round(phi/10)),int(10*(round(psi/10))))
                    key = (rot_type,phi,psi)
                    if key not in self.dep_library:
                        (phi,psi) = (int(20*round(phi/20)),int(20*(round(psi/20))))
                        key = (rot_type,phi,psi)                    
                        if key not in self.dep_library:
                            (phi,psi) = (int(60*round(phi/60)),int(60*(round(psi/60))))
                            key = (rot_type,phi,psi)
                    lib = self.dep_library.get(key,None)
            except:
                pass
        if lib == None:
            key = rot_type
            lib = self.ind_library.get(key,None)
            if (lib!= None) and self.dep == 'dep':
                print(' Mutagenesis: no phi/psi, using backbone-independent rotamers.')
        if lib != None:
            state = 1
            for a in lib:
                cmd.create(obj_name,frag_name,1,state)
                if state == 1:
                    cmd.select(mut_sele,"(byres (%s like %s))"%(obj_name,src_sele)) 
                if rot_type=='PRO':
                    cmd.unbond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)
                for b in a.keys():
                    if b!='FREQ':
                        cmd.set_dihedral("(%s & n;%s)"%(mut_sele,b[0]),
                                         "(%s & n;%s)"%(mut_sele,b[1]),
                                         "(%s & n;%s)"%(mut_sele,b[2]),
                                         "(%s & n;%s)"%(mut_sele,b[3]),
                                         a[b],state=state)
                    else:
                        cmd.set_title(obj_name,state,"%1.1f%%"%(a[b]*100))
                if rot_type=='PRO':
                    cmd.bond("(%s & name N)"%mut_sele,"(%s & name CD)"%mut_sele)                
                state = state + 1
            cmd.delete(frag_name)
            print(" Mutagenesis: %d rotamers loaded."%len(lib))
            if self.bump_check:
                cmd.delete(bump_name)
                cmd.create(bump_name,
                "(((byobj %s) within 6 of (%s and not name N+C+CA+O+H+HA)) and (not (%s)))|(%s)"%
                           (src_sele,mut_sele,src_sele,mut_sele),singletons=1)
                cmd.color("gray50",bump_name+" and elem C")
                cmd.set("seq_view",0,bump_name,quiet=1)
                cmd.hide("everything",bump_name)
                if ((cmd.select(tmp_sele1, "(name N & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2, "(name C & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                if ((cmd.select(tmp_sele1,"(name C & (%s in (neighbor %s)))"%
                                (bump_name,src_sele)) == 1) and
                    (cmd.select(tmp_sele2,"(name N & (%s in %s))"%
                                (bump_name,mut_sele)) == 1)):
                    cmd.bond(tmp_sele1,tmp_sele2)
                cmd.delete(tmp_sele1)
                cmd.delete(tmp_sele2)
                
                cmd.protect("%s and not (%s in (%s and not name N+C+CA+O+H+HA))"%
                            (bump_name,bump_name,mut_sele))
                cmd.sculpt_activate(bump_name)
                cmd.show("cgo",bump_name)
                # draw the bumps
                cmd.set("sculpt_vdw_vis_mode",1,bump_name)
                state = 1
                score_best = 1e6
                for a in lib:
                    score = cmd.sculpt_iterate(bump_name, state, 1)
                    self.bump_scores.append(score)
                    if score < score_best:
                        state_best = state
                        score_best = score
                    state = state + 1
            cmd.delete(mut_sele)
        else:
            cmd.create(obj_name,frag_name,1,1)
            print(" Mutagenesis: no rotamers found in library.")
        cmd.set("seq_view",0,obj_name,quiet=1)
        pymol.util.cbaw(obj_name)
        cmd.hide("("+obj_name+")")
        cmd.show(self.rep,obj_name)
        cmd.show('lines',obj_name) #neighbor  always show lines
        if cartoon:
            cmd.show("cartoon",obj_name)
        if sticks:
            cmd.show("sticks",obj_name)
        cmd.set('auto_zoom',auto_zoom,quiet=1)
        cmd.delete(frag_name)
        cmd.frame(state_best)
        cmd.unpick()
        cmd.feedback("pop")
def _contact_map_visualizer(image_file, selection, screenshots, quiet,
                            **kwargs):
    from datetime import datetime

    try:
        import pygame as pg
    except ImportError:
        print ' Error: This plugin requires the "pygame" module'
        raise CmdException

    screenshots, quiet = int(screenshots), int(quiet)

    cmd.set('sphere_scale', 0.25)

    idx_list = []
    cmd.iterate('(%s) and name CA' % (selection),
                'idx_list.append(((model,index),chain,resi))',
                space=locals())
    cmd.color("white", selection)

    # General variables
    count = 0
    sel = 0
    ntime = datetime.now()
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)

    if screenshots:
        outputname = "%s_selectedPoints_%d-%d-%d_%d%d.png" % (
            os.path.basename(image_file), ntime.day, ntime.month, ntime.year,
            ntime.hour, ntime.minute)

    # Text related arrays nd variables
    text = []
    textRect = []
    textcount = -1

    # screen height
    try:
        screen_height = cmd.pymol._ext_gui.root.winfo_screenheight()
    except:
        print ' Warning: could not determine screen height'
        screen_height = 700

    # use an image you have (.bmp  .jpg  .png  .gif)
    image = pg.image.load(image_file)
    image_height = image.get_height()

    factor = max((screen_height - 100) / image_height, 1)
    height = image_height * factor
    factor = 1.0 / factor

    if image_height != len(idx_list):
        print ' Warning: Dimension of image and number of CA atoms in selection',
        print 'differ! (%d vs. %d)' % (image_height, len(idx_list))

    # initialize pygame
    pg.init()
    screen = pg.display.set_mode((height, height))
    pg.display.set_caption('Choose the location by clicking')
    image = pg.transform.scale(image.convert(), (height, height))
    image_rect = image.get_rect()

    while True:
        event = pg.event.poll()
        keyinput = pg.key.get_pressed()

        # exit on corner 'x' click or escape key press
        if keyinput[pg.K_ESCAPE] or event.type == pg.QUIT:
            break

        if event.type == pg.MOUSEBUTTONDOWN:
            coor = [event.pos[0] * factor, (height - event.pos[1]) * factor]

            try:
                idx1, chain1, resi1 = idx_list[int(coor[0])]
                idx2, chain2, resi2 = idx_list[int(coor[1])]
            except IndexError:
                print ' Error: selection to small'
                continue

            print ' You clicked %s/%s/ %s/%s/' % (chain1, resi1, chain2, resi2)

            sel = 1
            textcount += 1

            selectionname = '%s%s_%s%s' % (resi1, chain1, resi2, chain2)
            cmd.select(selectionname,
                       'byres (%s`%d %s`%d)' % tuple(idx1 + idx2))

            cmd.show('sticks', selectionname)
            cmd.show('spheres', selectionname)

            cmd.color(colors[count], selectionname)
            cmd.center(selectionname, animate=1)

            pg.draw.circle(image, colors_value[count], event.pos, 3, 0)

            # set up fonts
            basicFont = pg.font.SysFont('Arial', 12)
            name = '(%s%s, %s%s)' % (resi1, chain1, resi2, chain2)

            # set up the text
            text.append(basicFont.render(name, True, WHITE, BLACK))
            textRect.append(text[textcount].get_rect())
            textRect[textcount][0] = event.pos[0] + 5
            textRect[textcount][1] = event.pos[1] + 5

            screen.blit(image, image_rect)
            for a in range(textcount + 1):
                screen.blit(text[a], textRect[a])
            pg.display.flip()

            if screenshots:
                if not quiet:
                    print ' Writing image to', outputname
                pg.image.save(screen, outputname)

            count += 1
            if count >= len(colors):
                count = 0

        # update screen
        screen.blit(image, image_rect)
        if sel == 1:
            for a in range(textcount + 1):
                screen.blit(text[a], textRect[a])
        pg.display.flip()

    pg.quit()
Ejemplo n.º 44
0
def optAlign( sel1, sel2 ):
	"""
	optAlign performs the Kabsch alignment algorithm upon the alpha-carbons of two selections.
	Example:   optAlign MOL1 and i. 20-40, MOL2 and i. 102-122
	Example 2: optAlign 1GGZ and i. 4-146 and n. CA, 1CLL and i. 4-146 and n. CA
 
	Two RMSDs are returned.  One comes from the Kabsch algorithm and the other from
	PyMol based upon your selections.
 
	By default, this program will optimally align the ALPHA CARBONS of the selections provided.
	To turn off this feature remove the lines between the commented "REMOVE ALPHA CARBONS" below.
 
	@param sel1: First PyMol selection with N-atoms
	@param sel2: Second PyMol selection with N-atoms
	"""
	cmd.reset()
 
	# make the lists for holding coordinates
	# partial lists
	stored.sel1 = []
	stored.sel2 = []
	# full lists
	stored.mol1 = []
	stored.mol2 = []
 
	# -- CUT HERE
	sel1 += " and N. CA"
	sel2 += " and N. CA"
	# -- CUT HERE
 
	# Get the selected coordinates.  We
	# align these coords.
	cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")
	cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")
 
	# get molecule name
	mol1 = cmd.identify(sel1,1)[0][0]
	mol2 = cmd.identify(sel2,1)[0][0]
 
	# Get all molecule coords.  We do this because
	# we have to rotate the whole molcule, not just
	# the aligned selection
	cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")
	cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")
 
	# check for consistency
	assert len(stored.sel1) == len(stored.sel2)
	L = len(stored.sel1)
	assert L > 0
 
	# must alway center the two proteins to avoid
	# affine transformations.  Center the two proteins
	# to their selections.
	COM1 = numpy.sum(stored.sel1,axis=0) / float(L)
	COM2 = numpy.sum(stored.sel2,axis=0) / float(L)
	stored.sel1 -= COM1
	stored.sel2 -= COM2
 
	# Initial residual, see Kabsch.
	E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0),axis=0)
 
	#
	# This beautiful step provides the answer.  V and Wt are the orthonormal
	# bases that when multiplied by each other give us the rotation matrix, U.
	# S, (Sigma, from SVD) provides us with the error!  Isn't SVD great!
	V, S, Wt = numpy.linalg.svd( numpy.dot( numpy.transpose(stored.sel2), stored.sel1))
 
	# we already have our solution, in the results from SVD.
	# we just need to check for reflections and then produce
	# the rotation.  V and Wt are orthonormal, so their det's
	# are +/-1.
	reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))
 
	if reflect == -1.0:
		S[-1] = -S[-1]
		V[:,-1] = -V[:,-1]
 
	RMSD = E0 - (2.0 * sum(S))
	RMSD = numpy.sqrt(abs(RMSD / L))
 
	#U is simply V*Wt
	U = numpy.dot(V, Wt)
 
	# rotate and translate the molecule
	stored.sel2 = numpy.dot((stored.mol2 - COM2), U)
	stored.sel2 = stored.sel2.tolist()
	# center the molecule
	stored.sel1 = stored.mol1 - COM1
	stored.sel1 = stored.sel1.tolist()
 
	# let PyMol know about the changes to the coordinates
	cmd.alter_state(1,mol1,"(x,y,z)=stored.sel1.pop(0)")
	cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")
 
	print "RMSD=%f" % RMSD
 
	# make the alignment OBVIOUS
	cmd.hide('everything')
	cmd.show('ribbon', sel1 + ' or ' + sel2)
	cmd.color('gray70', mol1 )
	cmd.color('paleyellow', mol2 )
	cmd.color('red', 'visible')
	cmd.show('ribbon', 'not visible')
	cmd.center('visible')
	cmd.orient()
	cmd.zoom('visible')
Ejemplo n.º 45
0
def colorDialog(app, mode):
    prefix = tkSimpleDialog.askstring(
        'Prefix',
        'Enter the prefix of symmetry partners to color',
        parent=app.root)
    if mode == 0:  #standard rainbow by symmetry operation
        colors = [
            "red", "orange", "yellow", "green", "blue", "purple", "salmon",
            "grey", "pink", "teal", "brown", "br0", "aquamarine", "deepolive",
            "dirtyviolet", "slate", "br4", "darksalmon", "br7", "chocolate",
            "firebrick", "brightorange"
        ]
        for i in range(20):
            try:  #required because PyMOL inappropriately throws an exception
                #when the cmd.color() function colors no objects
                cmd.color(colors[i], "%s%02d*" % (prefix, i))
            except:
                pass  #allows us to move on to next symmetry operator
    if mode == 1:  #specify for each symmetry operation
        cmd.iterate_state(1, prefix + "*", "stored.tmpObject = model")
        ops = get_operations(stored.tmpObject)
        opString = ""
        for i, x in enumerate(ops):
            opString += str(i) + " : " + x + "\n"
        opIndeces = tkSimpleDialog.askstring(
            "Symmetry Operations",
            opString +
            "Enter numbers of desired operations separated by commas (ex:0,2,9) or all",
            parent=app.root)
        if opIndeces == "all":
            opList = []
            for i in range(len(ops)):
                opList.append(i)
        else:
            opList = opIndeces.split(",")
        opStringList = opString.split("\n")
        for i in opList:
            try:
                cmd.color("white", "%s%02d*" % (prefix, i))
                cmd.center("%s%02d*" % (prefix, i))

            except:
                pass
            tempColor = tkColorChooser.askcolor(title="Color for " +
                                                opStringList[int(i)] +
                                                " (currently white)",
                                                parent=app.root)[0]
            rgb = []
            for value in tempColor:
                value = float(value)
                value = value / 255
                rgb.append(value)
            cmd.set_color("tempColor", rgb)
            try:
                cmd.color("tempColor", "%s%02d*" % (prefix, i))
            except:
                pass
    if mode == 2:  #monochrome for a set of operations
        cmd.iterate_state(1, prefix + "*", "stored.tmpObject = model")
        ops = get_operations(stored.tmpObject)
        opString = ""
        for i, x in enumerate(ops):
            opString += str(i) + " : " + x + "\n"
        opIndeces = tkSimpleDialog.askstring(
            "Symmetry Operations",
            opString +
            "Enter numbers of desired operations separated by commas (ex:0,2,9) or all",
            parent=app.root)
        if opIndeces == 'all':
            opList = []
            for i in range(len(ops)):
                opList.append(i)
        else:
            opList = opIndeces.split(",")
        opStringList = opString.split("\n")
        tempColor = tkColorChooser.askcolor(parent=app.root)[0]
        rgb = []
        for value in tempColor:
            value = float(value)
            value = value / 255
            rgb.append(value)
        cmd.set_color("tempColor", rgb)
        for i in opList:
            try:
                cmd.color("tempColor", "%s%02d*" % (prefix, i))
            except:
                pass
Ejemplo n.º 46
0
 
def centerOfMass(selection):
   ## assumes equal weights (best called with "and name ca" suffix)
   model = cmd.get_model(selection)
   x,y,z=0,0,0
   for a in model.atom:
       x+= a.coord[0]
       y+= a.coord[1]
       z+= a.coord[2]
   return (x/len(model.atom), y/len(model.atom), z/len(model.atom))
 
cmd.load("/group/bioinf/Data/PDBLinks/1c7c.pdb")
cmd.select("domain", "/1c7c//A/143-283/ and name ca") ## selecting a domain
 
domainCenter=centerOfMass("domain")
 
print "Center of mass: (%.1f,%.1f,%.1f)"% domainCenter
cmd.as("cartoon", "all")
cmd.show("spheres", "domain")
 
## Creating a sphere CGO
com = [COLOR, 1.0, 1.0, 1.0, SPHERE]+list(domainCenter) + [3.0] ## white sphere with 3A radius
cmd.load_cgo(com, "CoM")
 
cmd.zoom("1c7c", 1.0)
cmd.center("domain")
 
#ah@bioinfws19:~/Projects/PyMOL$ pymol -qc centerOfMass4.py
#Center of mass: (-1.0,24.5,48.2)
#ah@bioinfws19:~/Projects/PyMOL$
Ejemplo n.º 47
0
if not os.path.exists(outdir):
    os.makedirs(outdir)

for i in range(5):
    cmd.load("./PDBs-%d/State%d-%d.pdb" % (p_id, stateid, i))

for i in range(5):
    cmd.align("State%d-%d" % (stateid, i),
              "State%d-%d" % (stateid, ref_state_id))

#alignto does the same thing as the above loop, but it sometimes could cause problem
#cmd.alignto("State%d-0"%stateid)
cmd.show("cartoon")
cmd.hide("lines", "!State%d-%d" % (stateid, ref_state_id))
cmd.center("all")
cmd.set("cartoon_transparency", 0.7, "all")
cmd.set("cartoon_transparency", 0, "State%d-%d" % (stateid, ref_state_id))
cmd.util.chainbow("all")
cmd.util.cnc("all")
cmd.orient()
cmd.util.performance(0)
cmd.set("ray_opaque_background", "off")
cmd.ray()
png_fn = os.path.join(outdir, "image-p%d-state-%d.png" % (p_id, stateid))
high_res_state = [0, 1, 2, 4, 11, 12, 13, 20, 28, 30]
if stateid in high_res_state:
    png_fn = os.path.join(outdir,
                          "image-p%d-state-%d-highres.png" % (p_id, stateid))
    cmd.ray(2400, 1800)
    cmd.png(png_fn, dpi=300)
Ejemplo n.º 48
0
	def cenall(self):
		cmd.center(self.d.muts[0].rdes.obj+" or pnt*")