https://wiki.pymol.org/api.php?action=feedcontributions&user=Gilleain&feedformat=atomPyMOL Wiki - User contributions [en]2024-03-29T10:43:19ZUser contributionsMediaWiki 1.35.1https://wiki.pymol.org/index.php?title=CreateAtom&diff=3515CreateAtom2008-10-23T16:05:03Z<p>Gilleain: </p>
<hr />
<div>A script to create an atom C at a point some distance d from a pair of atoms (A, B), along the line of the bond A-B. The main function takes a modelName (usually, the name of the file loaded, like "1pqr" or "peptide"), a distance, and some parameters to identify the atoms A, B.<br />
<br />
Use like: <pre>createAtomAlongBond("gly", 3, 23, "H", 23, "N", "O")</pre>.<br />
<br />
<source lang="python"><br />
import cmd<br />
from chempy import models, cpv<br />
<br />
"""<br />
Create an atom at a distance 'distance' along the bond between atomA and atomB<br />
"""<br />
def createAtomAlongBond(modelName, distance, resiA, atomNameA, resiB, atomNameB, atomNameC):<br />
model = cmd.get_model(modelName)<br />
p1 = getAtomCoords(model, str(resiA), atomNameA)<br />
p2 = getAtomCoords(model, str(resiB), atomNameB)<br />
if p1 is None:<br />
print "atom not found!", modelName, resiA, atomNameA<br />
elif p2 is None:<br />
print "atom not found!", modelName, resiB, atomNameB<br />
else:<br />
p3 = calculateNewPoint(p1, p2, distance)<br />
<br />
# the details of the new atom<br />
atomDetails = {}<br />
atomDetails['residueName'] = "HOH"<br />
atomDetails['residueNumber'] = "1"<br />
atomDetails['symbol'] = "O"<br />
atomDetails['name'] = atomNameC<br />
atomDetails['coords'] = p3<br />
<br />
# make an atom with index n+1 and chain "X"<br />
newAtom = makeAtom(model.nAtom + 1, atomDetails, "X")<br />
model.add_atom(newAtom)<br />
model.update_index()<br />
cmd.load_model(model, "newpeptide")<br />
<br />
def getAtomCoords(model, resi, atomName):<br />
for a in model.atom:<br />
if a.resi == resi and a.name == atomName:<br />
return a.coord<br />
return None<br />
<br />
def calculateNewPoint(p1, p2, distance):<br />
v1 = cpv.normalize(cpv.sub(p1, p2))<br />
return cpv.add(p1, cpv.scale(v1, distance))<br />
<br />
def makeAtom(index, atomDetails, chain):<br />
atom = chempy.Atom()<br />
atom.index = index<br />
atom.name = atomDetails['name']<br />
atom.symbol = atomDetails['symbol']<br />
atom.resn = atomDetails['residueName']<br />
atom.chain = chain<br />
atom.resi = atomDetails['residueNumber']<br />
atom.resi_number = int(atomDetails['residueNumber'])<br />
atom.coord = atomDetails['coords']<br />
atom.hetatm = False<br />
return atom<br />
<br />
cmd.extend("createAtomAlongBond", createAtomAlongBond)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=CreateAtom&diff=3514CreateAtom2008-10-22T08:35:21Z<p>Gilleain: </p>
<hr />
<div>A script to create an atom C at a point some distance d from a pair of atoms (A, B), along the line of the bond A-B. The main function takes a modelName (usually, the name of the file loaded, like "1pqr" or "peptide"), a distance, and some parameters to identify the atoms A, B.<br />
<br />
Use like: <pre>createAtomAlongBond("gly", 3, 23, "H", 23, "N", "O")</pre>.<br />
<br />
<source lang="python"><br />
import cmd<br />
from chempy import models, cpv<br />
<br />
"""<br />
Create an atom at a distance 'distance' along the bond between atomA and atomB<br />
"""<br />
def createAtomAlongBond(modelName, distance, resiA, atomNameA, resiB, atomNameB, atomNameC):<br />
model = cmd.get_model(modelName)<br />
p1 = getAtomCoords(model, str(resiA), atomNameA)<br />
p2 = getAtomCoords(model, str(resiB), atomNameB)<br />
if p1 is None:<br />
print "atom not found!", modelName, resiA, atomNameA<br />
elif p2 is None:<br />
print "atom not found!", modelName, resiB, atomNameB<br />
else:<br />
p3 = calculateNewPoint(p1, p2, distance)<br />
<br />
# the details of the new atom<br />
atomDetails = {}<br />
atomDetails['residueName'] = "HOH"<br />
atomDetails['residueNumber'] = "1"<br />
atomDetails['symbol'] = "O"<br />
atomDetails['name'] = atomNameC<br />
atomDetails['coords'] = p3<br />
<br />
# make an atom with index n+1 and chain "X"<br />
newAtom = makeAtom(model.nAtom + 1, atomDetails, "X")<br />
model.add_atom(newAtom)<br />
model.update_index()<br />
cmd.load_model(model, "newpeptide")<br />
<br />
def getAtomCoords(model, resi, atomName):<br />
for a in model.atom:<br />
if a.resi == resi and a.name == atomName:<br />
return a.coord<br />
return None<br />
<br />
def calculateNewPoint(p1, p2, distance):<br />
v1 = cpv.sub(p1, p2)<br />
return cpv.add(p2, cpv.scale(v1, distance))<br />
<br />
def makeAtom(index, atomDetails, chain):<br />
atom = chempy.Atom()<br />
atom.index = index<br />
atom.name = atomDetails['name']<br />
atom.symbol = atomDetails['symbol']<br />
atom.resn = atomDetails['residueName']<br />
atom.chain = chain<br />
atom.resi = atomDetails['residueNumber']<br />
atom.resi_number = int(atomDetails['residueNumber'])<br />
atom.coord = atomDetails['coords']<br />
atom.hetatm = False<br />
return atom<br />
<br />
cmd.extend("createAtomAlongBond", createAtomAlongBond)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=CreateAtom&diff=3513CreateAtom2008-10-22T08:32:48Z<p>Gilleain: </p>
<hr />
<div>A script to create an atom C at a point some distance d from a pair of atoms (A, B), along the line of the bond A-B. The main function takes a modelName (usually, the name of the file loaded, like "1pqr" or "peptide"), a distance, and some parameters to identify the atoms A, B.<br />
<br />
Use like: <pre>createAtomAlongBond("gly", 3, 23, "H", 23, "N", "O")</pre>.<br />
<br />
<source lang="python"><br />
import cmd<br />
from chempy import models, protein_residues, cpv<br />
<br />
"""<br />
Create an atom at a distance 'distance' along the bond between atomA and atomB<br />
"""<br />
def createAtomAlongBond(modelName, distance, resiA, atomNameA, resiB, atomNameB, atomNameC):<br />
model = cmd.get_model(modelName)<br />
p1 = getAtomCoords(model, str(resiA), atomNameA)<br />
p2 = getAtomCoords(model, str(resiB), atomNameB)<br />
if p1 is None:<br />
print "atom not found!", modelName, resiA, atomNameA<br />
elif p2 is None:<br />
print "atom not found!", modelName, resiB, atomNameB<br />
else:<br />
p3 = calculateNewPoint(p1, p2, distance)<br />
<br />
# the details of the new atom<br />
atomDetails = {}<br />
atomDetails['residueName'] = "HOH"<br />
atomDetails['residueNumber'] = "1"<br />
atomDetails['symbol'] = "O"<br />
atomDetails['name'] = atomNameC<br />
atomDetails['coords'] = p3<br />
<br />
# make an atom with index n+1 and chain "X"<br />
newAtom = makeAtom(model.nAtom + 1, atomDetails, "X")<br />
model.add_atom(newAtom)<br />
model.update_index()<br />
cmd.load_model(model, "newpeptide")<br />
<br />
def getAtomCoords(model, resi, atomName):<br />
for a in model.atom:<br />
if a.resi == resi and a.name == atomName:<br />
return a.coord<br />
return None<br />
<br />
def calculateNewPoint(p1, p2, distance):<br />
v1 = cpv.sub(p1, p2)<br />
return cpv.add(p2, cpv.scale(v1, distance))<br />
<br />
def makeAtom(index, atomDetails, chain):<br />
atom = chempy.Atom()<br />
atom.index = index<br />
atom.name = atomDetails['name']<br />
atom.symbol = atomDetails['symbol']<br />
atom.resn = atomDetails['residueName']<br />
atom.chain = chain<br />
atom.resi = atomDetails['residueNumber']<br />
atom.resi_number = int(atomDetails['residueNumber'])<br />
atom.coord = atomDetails['coords']<br />
atom.hetatm = False<br />
return atom<br />
<br />
cmd.extend("createAtomAlongBond", createAtomAlongBond)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=CreateAtom&diff=3512CreateAtom2008-10-20T12:31:13Z<p>Gilleain: New page: A script to create an atom C at a point some distance d from a pair of atoms (A, B), along the line of the bond A-B. The main function takes a modelName (usually, the name of the file load...</p>
<hr />
<div>A script to create an atom C at a point some distance d from a pair of atoms (A, B), along the line of the bond A-B. The main function takes a modelName (usually, the name of the file loaded, like "1pqr" or "peptide"), a distance, and some parameters to identify the atoms A, B.<br />
<br />
Use like: <pre>createAtomAlongBond("gly", 3, 23, "H", 23, "N", "O")</pre>.<br />
<br />
<source lang="python"><br />
import cmd<br />
from chempy import models, protein_residues<br />
<br />
"""<br />
Create an atom at a distance 'distance' along the bond between atomA and atomB<br />
"""<br />
def createAtomAlongBond(modelName, distance, resiA, atomNameA, resiB, atomNameB, atomNameC):<br />
model = cmd.get_model(modelName)<br />
p1 = getAtomCoords(model, str(resiA), atomNameA)<br />
p2 = getAtomCoords(model, str(resiB), atomNameB)<br />
if p1 is None:<br />
print "atom not found!", modelName, resiA, atomNameA<br />
elif p2 is None:<br />
print "atom not found!", modelName, resiB, atomNameB<br />
else:<br />
p3 = calculateNewPoint(p1, p2, distance)<br />
<br />
# the details of the new atom<br />
atomDetails = {}<br />
atomDetails['residueName'] = "GLY"<br />
atomDetails['residueNumber'] = "1"<br />
atomDetails['symbol'] = "O"<br />
atomDetails['name'] = atomNameC<br />
atomDetails['coords'] = p3<br />
<br />
# make an atom with index n+1 and chain "X"<br />
newAtom = makeAtom(model.nAtom + 1, atomDetails, "X")<br />
model.add_atom(newAtom)<br />
model.update_index()<br />
cmd.load_model(model, "newpeptide")<br />
<br />
def getAtomCoords(model, resi, atomName):<br />
for a in model.atom:<br />
if a.resi == resi and a.name == atomName:<br />
return a.coord<br />
return None<br />
<br />
def calculateNewPoint(p1, p2, distance):<br />
v1 = cpv.sub(p1, p2)<br />
return cpv.add(p2, cpv.scale(v1, distance))<br />
<br />
def makeAtom(index, atomDetails, chain):<br />
atom = chempy.Atom()<br />
atom.index = index<br />
atom.name = atomDetails['name']<br />
atom.symbol = atomDetails['symbol']<br />
atom.resn = atomDetails['residueName']<br />
atom.chain = chain<br />
atom.resi = atomDetails['residueNumber']<br />
atom.resi_number = int(atomDetails['residueNumber'])<br />
atom.coord = atomDetails['coords']<br />
atom.hetatm = False<br />
return atom<br />
<br />
cmd.extend("createAtomAlongBond", createAtomAlongBond)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Category:Script_Library&diff=3895Category:Script Library2008-10-20T12:23:33Z<p>Gilleain: /* Descriptions */</p>
<hr />
<div>= Overview =<br />
Here we provide a trove of scripts. The descriptions immediately follow. For the entire category, please see the bottom of this page.<br />
<br />
= Descriptions =<br />
<br />
* [[LigAlign]] -- Ligand-based active site alignment and comparison.<br />
<br />
* [[ImmersiveViz]] -- A script used in conjunction with head tracking software to provide an immersive virtual experience.<br />
<br />
* [[Rasmolify]] -- A work in progress - a script to map Rasmol commands onto the equivalent PyMOL commands.<br />
<br />
* [[Zero_residues]] -- Renumber residues such that the first residue is 0. Useful for alignments.<br />
<br />
* [[Cealign]] -- Implementation of the CE Structure Alignment algorithm as a PyMOL plugin.<br />
<br />
* [[WriteSS]] -- Writes secondary structural elements, for each residues, to a file.<br />
<br />
* [[Process_All_Files_In_Directory]] -- Do something to all files in a directory. The examples show how to print the disulfide bond lengths, then in general all sulfur distances (not necessarily bound).<br />
<br />
* [[Kabsch]] -- Kabsch alignment of two sets of vectors. (Part 2 of a protein alignment.)<br />
<br />
* [[Transform_odb]] -- Transform a selection of an existing object and output as a new object. The transformation matrix is read from an "O"-style tranformation matrix file (.odb) written by "O" or by any of the Uppsala Software Factory programs (from Gerard Klegweit) such as LSQMAN.<br />
<br />
* [[Stereo_Ray]] -- This script will create two resolution specific ray traced images rotated appropriately for inclusion into a single file to represent a stereo view of the desired macromolecule.<br />
<br />
* [[Translate_And_Measure]] -- prints '''overlap''' if any of the atoms in molA or molB were within 4 Angstrom after translating by 1 along X<br />
<br />
* [[Show aromatics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for aromatic residues displayed as green "sticks". Usage: Save this as "show_aromatics.pml", load your protein in PyMOL, and run the script (select "Run" from the "File" menu). (PyMOL script; TStout)<br />
<br />
* [[Show hydrophobics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophobic residues displayed as orange "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show charged]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for charged residues displayed as red (negative) or blue (posititve) "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show hydrophilic]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophilic residues displayed as green "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show NMR constrains]] -- This script will display the NMR constrains used for a structure calculation atop a structure. Usage: Save this as "NMRcnstr.py" load your protein in PyMOL, and run the script. type upl('fname') or cns('fname') where fname is the filename with the NMR constrains you want to display. <br />
<br />
* [[Perp Maker]] -- Creates a perpendicular plane through the center of your protein with respect to the camera's current position. (If you translate the protein towards the camera a bit, you get a nice surface, sometimes.) A stupid little script I wrote in response to a request a few months ago (and it doesn't even conform to the request!) Load a protein, run the script (read the documentation in the script). (Jason Vertrees/[[User:Tree|Tree]])<br />
<br />
* [[PythonTerminal]] -- Allows execution of python commands from the PyMOL command line.<br />
<br />
* [[Axes]] -- Creates a 3D-CGO object that shows the three coordinate axes.<br />
<br />
* [[Symmetry Axis]] -- Draw a 3D-CGO line given a point and a direction. <br />
<br />
* [[CGO Text]] -- Creates a 3D-CGO text object.<br />
<br />
* [[List Selection]] -- Prints a list of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Colors]] -- Lists the color of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Secondary Structures]] -- Secondary structures (both predefined and those calculated with the 'dss' command) can be exported as a long string ('HHHHLLLLSSS').<br />
<br />
* [[Split Movement]] -- Moves two parts of one object into different directions.<br />
<br />
* [[Selection Exists]] -- Python method that returns true if a selection of a given name exists.<br />
<br />
* [[Get Coordinates I]] -- Retrieves atom coordinates as Python objects.<br />
<br />
* [[Get Coordinates II]] -- Retrieves atom coordinates as Python array (list object).<br />
<br />
* [[grepset]] -- List all settings matching a given keyword. - ''by EHP''<br />
<br />
* [[apropos]] -- List all commands matching a given keyword or whose docs contain the keyword. - ''by EHP''<br />
<br />
* [[mouse_modes]] -- customize the default mouse bindings for Viewing or Editing modes. - ''by EHP''<br />
<br />
* [[Measure Distance]] -- Measures the distance between two atoms (Python script).<br />
<br />
* [[Read PDB-String]] -- Parses a string in PDB format to a PyMOL object.<br />
<br />
* [[Color Objects]] -- Colors all objects differently (Python script).<br />
<br />
* [[Key Wait]] -- Process key events in a Python script.<br />
<br />
* [[Bounding Box]] -- Create a bounding box around a selection (Python script; requires numarray and Scientific; gilleain)<br />
<br />
* [[Ellipsoid]] -- Create callback object (opengl) ellipsoids. (Python script; gilleain)<br />
<br />
* [[pdbsurvey]] -- Surveys the pdb for recently added structures that are relevant to a user-specified keywords list (in a text file)<br />
<br />
* [[resicolor]] -- Colors proteins according to residue type.<br />
<br />
* [[TransformSelectionByCameraView]] -- Transforms the selection by the camera view.<br />
<br />
* [[WFMesh]] -- Imports wavefront object mesh files; Starwars as an example!<br />
<br />
* [[grepsel]] -- Make named selections using regular expressions (protein sequence).<br />
<br />
* [[PowerMate Dial OS X]] -- Script and instructions to use the PowerMate dial on Mac OS X.<br />
<br />
* [[Plane Wizard]] -- Wizard to draw planes between three picked points.<br />
<br />
* [[Slerpy]] -- Pymol command extensions for key frame animation movie making.<br />
<br />
* [[Helicity_check]] -- helicity_check show the evolution of O - N distances over an amino acid sequence<br />
<br />
* [[Center Of Mass]] -- Given a selection of atoms (of equal weight) - Calculates the center of mass and represents it with a CGO sphere<br />
<br />
* [[ss]] -- Simple command to summarise the Secondary Structure as a list of "start-end type" like sses.<br />
<br />
* [[iterate_sses]] -- Slightly more complex version of "ss" that allows the user to pass in a function to act on the sse list.<br />
<br />
* [[motif]] -- Designed for easy display of backbone motifs (nests, catgrips, etc).<br />
<br />
* [[createAtom]] -- Make an atom at a distance along the line of a bond.<br />
<br />
[[Category:Scripting|Script Library]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Script_Tutorial&diff=8746Script Tutorial2008-03-05T17:04:11Z<p>Gilleain: /* Getting PyMOL Data into your Script */</p>
<hr />
<div>= Introduction =<br />
One of the more powerful features of PyMOL is that it supports Python scripting. That gives you the power of using all the Python libraries, especially the [http://docs.python.org/api/api.html the Python API] to write programs in other languages and then send the results back into PyMOL (this is what [[cealign]] does). <br />
<br />
The PyMOLWiki has a rather extensive [[script_library]] full of useful scripts (feel free to add your own).<br />
<br />
Here I intend to provide the necessary details to get you coding PyMOL scripts as quickly as possible. I provide the basic information as well as code and links to the Python API.<br />
<br />
= General Scripts =<br />
Scripting in the Python language follows a simple recipe, in PyMOL.<br />
<br />
'''To write them''':<br />
#Write the function, let's call it '''doSimpleThing''', in a Python file, let's call the file '''pyProgram.py'''.<br />
#Add the following command to the end of the '''pyProgram.py''' file <source lang="python">cmd.extend(doSimpleThing,doSimpleThing)</source><br />
<br />
'''To use them''':<br />
# simply import the script into PyMOL: <source lang="python">run /home/userName/path/toscript/pyProgram.py</source><br />
# Then, just type the name of the command: ''doSimpleThing'' and pass any needed arguments.<br />
<br />
That's it. Your script can, through Python, import any modules you need and also edit modify objects in PyMOL.<br />
<br />
== Getting PyMOL Data into your Script ==<br />
To get PyMOL data into your script you will need to somehow get access to the PyMOL objects and pull out the data. For example, if you want the atomic coordinates of a selection of alpha carbon atoms your Python function may do something like this (all PyMOL functions are referenced in the See Also section, below):<br />
<source lang="python"><br />
# Import PyMOL's stored module. This will allow us with a <br />
# way to pull out the PyMOL data and modify it in our script.<br />
# See below.<br />
from pymol import stored<br />
<br />
def functionName( userSelection ):<br />
# this array will be used to hold the coordinates. It<br />
# has access to PyMOL objects and, we have access to it.<br />
stored.alphaCarbons = []<br />
<br />
# let's just get the alpha carbons, so make the<br />
# selection just for them<br />
userSelection = userSelection + " and n. CA"<br />
<br />
# iterate over state 1, or the userSelection -- this just means<br />
# for each item in the selection do what the next parameter says.<br />
# And, that is to append the (x,y,z) coordinates to the stored.alphaCarbon<br />
# array.<br />
cmd.iterate_state(1, selector.process(userSelection), "stored.alphaCarbons.append([x,y,z])")<br />
<br />
# stored.alphaCarbons now has the data you want.<br />
<br />
... do something to your coordinates ...<br />
</source><br />
<br />
=== Getting Data From your Script into PyMOL ===<br />
Usually this step is easier. To get your data into PyMOL, it's usually through modifying some object, rotating a molecule, for example. To do that, you can use the [[alter]] or [[alter_state]] commands. Let's say for example, that we have translated the molecular coordinates from the last example by some vector (we moved the alpha carbons). Now, we want to make the change and see it in PyMOL. To write the coordinates back we do:<br />
<source lang="python"><br />
# we need to know which PyMOL object to modify. There could be many molecules and objects<br />
# in the session, and we don't want to ruin them. The following line, gets the object<br />
# name from PyMOL<br />
objName = cmd.identify(sel2,1)[0][0]<br />
<br />
# Now, we alter each (x,y,z) array for the object, by popping out the values<br />
# in stored.alphaCarbons. PyMOL should now reflect the changed coordinates.<br />
cmd.alter_state(1,objName,"(x,y,z)=stored.alphaCarbons.pop(0)")<br />
</source><br />
<br />
== Example ==<br />
Here's a script I wrote for [[cealign]]. It takes two selections '''of equal length''' and computes the optimal overlap, and aligns them. See [[Kabsch]] for the original code. Because this tutorial is for scripting and not optimal superposition, the original comments have been removed.<br />
<br />
<source lang="python"><br />
def optAlign( sel1, sel2 ):<br />
"""<br />
@param sel1: First PyMol selection with N-atoms<br />
@param sel2: Second PyMol selection with N-atoms<br />
"""<br />
<br />
# make the lists for holding coordinates<br />
# partial lists<br />
stored.sel1 = []<br />
stored.sel2 = []<br />
# full lists<br />
stored.mol1 = []<br />
stored.mol2 = []<br />
<br />
# -- CUT HERE<br />
sel1 = sel1 + " and N. CA"<br />
sel2 = sel2 + " and N. CA"<br />
# -- CUT HERE<br />
<br />
# This gets the coordinates from the PyMOL objects<br />
cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])")<br />
cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])")<br />
<br />
# ...begin math that does stuff to the coordinates...<br />
mol1 = cmd.identify(sel1,1)[0][0]<br />
mol2 = cmd.identify(sel2,1)[0][0]<br />
cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])")<br />
cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])")<br />
assert( len(stored.sel1) == len(stored.sel2))<br />
L = len(stored.sel1)<br />
assert( L > 0 )<br />
COM1 = numpy.sum(stored.sel1,axis=0) / float(L)<br />
COM2 = numpy.sum(stored.sel2,axis=0) / float(L)<br />
stored.sel1 = stored.sel1 - COM1<br />
stored.sel2 = stored.sel2 - COM2<br />
E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0)<br />
,axis=0)<br />
reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt))))<br />
if reflect == -1.0:<br />
S[-1] = -S[-1]<br />
V[:,-1] = -V[:,-1]<br />
RMSD = E0 - (2.0 * sum(S))<br />
RMSD = numpy.sqrt(abs(RMSD / L))<br />
U = numpy.dot(V, Wt)<br />
# ...end math that does stuff to the coordinates...<br />
<br />
# update the _array_ of coordinates; not PyMOL the coords in the PyMOL object<br />
stored.sel2 = numpy.dot((stored.mol2 - COM2), U) + COM1<br />
stored.sel2 = stored.sel2.tolist()<br />
<br />
# This updates PyMOL. It is removing the elements in <br />
# stored.sel2 and putting them into the (x,y,z) coordinates<br />
# of mol2.<br />
cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)")<br />
<br />
print "RMSD=%f" % RMSD<br />
<br />
cmd.orient(sel1 + " and " + sel2)<br />
<br />
# The extend command makes this runnable as a command, from PyMOL.<br />
cmd.extend("optAlign", optAlign)<br />
</source><br />
<br />
= Advanced Scripts =<br />
Let's consider a more complicated script. Python while incredibly useful, is much slower at math than is C/C++, FORTRAN, etc. It's faster for complicated problems to package your data, send it to C, do some math, and pass the results back to Python than to just do everything in Python. () The beauty of the Python API, is that we can do just that.<br />
<br />
Python is a great language, but sometimes we have libraries built in other languages, or Python's math is just too slow to be useful. (I tested a structure alignment problem, using equivalent code, in C and Python. The C code was about 10x slower.) So, we can export our PyMOL data to the other language, do the math/problem, and import the changes back into PyMOL. This is shown below using the Python API and C. (This example code comes from [[cealign]].)<br />
<br />
This is more advanced scripting, and requires some knowledge of the [http://docs.python.org/api/api.html Python API].<br />
<br />
<br />
=== Python, PyMOL and C ===<br />
Here, I will show you how to write a C-module that plugs into Python and talks nicely with PyMOL. To follow this, you should have some programming experience in both Python and C. The example actually shows how to make a generic C-function and use it in Python.<br />
<br />
First, let's assume that we want to call a function, let's call it '''funName'''. Let's assume '''funName''' will take a Python list of lists and return a list. I will also assume we have '''funName.h''' and '''funName.c''' for C code files. (This is a more complex example to show a real-world problem. If you were just sending an integer or float instead of packaged lists, the code is simpler.) So, to start, let's look at the Python code that will call the C-function:<br />
<source lang="python"><br />
#<br />
# -- in someCode.py<br />
#<br />
# Call funName. Pass it a list () of lists. (sel1 and sel2 are lists.)<br />
# Get the return value into rValFromC.<br />
#<br />
rValFromC = funName( (sel1, sel2) );<br />
</source><br />
where '''sel1''' and '''sel2''' could be any list of atom coordinates, say, from PyMOL. (See above.)<br />
<br />
Ok, this isn't hard. Now, we need to see what the code that receives this function call in C, looks like. Well, first we need to let C know we're integrating with Python. So, in your [http://docs.python.org/api/includes.html header file] of '''funName.h''' we put:<br />
<source lang="c"><br />
// in funName.h<br />
#include <Python.h><br />
</source><br />
<br />
Next, by default your C-function's name is '''funName_funName''' (and that needs to be setup, I'll show how, later). So, let's define funName:<br />
<source lang="c"><br />
static PyObject*<br />
funName_funName(PyObject* self, PyObject* args)<br />
{<br />
...more code...<br />
</source><br />
This is the generic call. '''funName''' is taking two pointers to PyObjects. It also returns a PyObject. This is how you get the Python data into and out of C. It shows up in "args," and we then unpackage it into C. Then we tinker with the data, package it up using the Python API, and send it back to Python/PyMOL.<br />
<br />
Let's unpack the data in '''args'''. Remember, '''args''' has a Python list of lists. So, to unpackage that we do the following inside of funName:<br />
<source lang="c" line="1"><br />
static PyObject*<br />
funName_funName(PyObject* self, PyObject* args)<br />
{<br />
PyObject *listA, *listB;<br />
<br />
if ( ! PyArg_ParseTuple(args, "(OO)", &listA, &listB) ) {<br />
printf("Could not unparse objects\n");<br />
return NULL;<br />
}<br />
<br />
// let Python know we made two lists<br />
Py_INCREF(listA);<br />
Py_INCREF(listB);<br />
... more code ...<br />
</source><br />
Line 4 creates the two C objects that we will unpackage the lists into. They are pointers to PyObjects.<br />
Line 6 is where the magic happens. We call, '''[ PyArg_ParseTuple]''' passing it the args we got from Python. The '''(OO)''' is Python's code for ''I'm expecting two <u>O</u>bjects inside a list <u>()</u>''. Were it three objects, then '''(OOO)'''. The first object will be put into '''&listA''' and the second into '''&listB'''. The exact [http://docs.python.org/api/arg-parsing.html argument building specifications] are very useful. <br />
Next, we check for success. Unpacking could fail. If it does, complain and quit. Else, '''listA''' and '''listB''' now have data in them. To avoid memory leaks we need to manually keep track of PyObjects we're tooling around with. That is, I can create PyObjects in C (being sneaky and not telling Python) and then when Python quits later on, it'll not know it was supposed to clean up after those objects (making a leak). To, we let Python know about each list with '''Py_INCREF(listA)''' and '''Py_INCREF(listB)'''. This is [http://docs.python.org/api/countingRefs.html reference counting].<br />
<br />
Now, just for safety, let's check the lists to make sure they actually were passed something. A tricky user could have given us empty lists, looking to hose the program. So, we do:<br />
<source lang="c"><br />
// handle empty selections (should probably do this in Python)<br />
const int lenA = PyList_Size(listA);<br />
if ( lenA < 1 ) {<br />
printf("CEALIGN ERROR: First selection didn't have any atoms. Please check your selection.\n");<br />
// let Python remove the lists<br />
Py_DECREF(listA);<br />
Py_DECREF(listB);<br />
return NULL;<br />
}<br />
<br />
</source><br />
We check the list size with, '''[http://docs.python.org/api/listObjects.html PyList_Size]''' and if it's 0 -- we quit. But, before quitting we give control of the lists back to Python so it can clean up after itself. We do that with '''Py_DECREF'''.<br />
<br />
Now, we should have access to the data the user sent us, in '''listA''' and '''listB,''' and it should be there and be clean. But, not forgetting that '''listA''' and '''listB''' are list of 3D coordinates, let's unpack them further into sets of coordinates. Because we know the length of the lists, we can do something like the following:<br />
<source lang="c" line="1"><br />
// make space for the current coords<br />
pcePoint coords = (pcePoint) malloc(sizeof(cePoint)*length);<br />
<br />
// loop through the arguments, pulling out the<br />
// XYZ coordinates.<br />
int i;<br />
for ( i = 0; i < length; i++ ) {<br />
PyObject* curCoord = PyList_GetItem(listA,i);<br />
Py_INCREF(curCoord);<br />
<br />
PyObject* curVal = PyList_GetItem(curCoord,0);<br />
Py_INCREF(curVal);<br />
coords[i].x = PyFloat_AsDouble(curVal);<br />
Py_DECREF(curVal);<br />
<br />
curVal = PyList_GetItem(curCoord,1);<br />
Py_INCREF(curVal);<br />
coords[i].y = PyFloat_AsDouble(curVal);<br />
Py_DECREF(curVal);<br />
<br />
curVal = PyList_GetItem(curCoord,2);<br />
Py_INCREF(curVal);<br />
coords[i].z = PyFloat_AsDouble(curVal);<br />
Py_DECREF(curVal);<br />
<br />
Py_DECREF(curCoord);<br />
}<br />
<br />
... more code ...<br />
</source><br />
Where, '''pcePoint''' is just a float[3]. Line 2 just gets some memory ready for the 3xlenght list of coordinates. Then, for each item for 1..length, we unpack the list using '''[http://docs.python.org/api/listObjects.html PyList_GetItem]''', into '''curCoord'''. This then gets further unpacked into the float[3], '''coords'''.<br />
<br />
... More later ...<br />
<br />
=== Getting Your Data from C back into Python/PyMOL ===<br />
Once you're done with your calculations and want to send your data back to PyMOL, you need to package it up into a Python object, using the Python API, and then return it. You should be aware of the expected return value and how you're packaging the results. If you user calls,<br />
<source lang="python"><br />
(results1,results2) = someCFunction(parameters1,parameters2)<br />
</source><br />
then you need to package a list with two values. To build values for returning to PyMOL, use '''[ Py_BuildValue]'''. Py_BuildValue takes a string indicating the type, and then a list of values. [http://docs.python.org/ext/buildValue.html Building values] for return has been documented very well. Consider an example: if I want to package an array of integers, the type specifier for two intsPy_BuildValue is, "[i,i]", so my call could be:<br />
<source lang="c"><br />
# Package the two ints into a Python pair of ints.<br />
PyObject* thePair = Py_BuildValue( "[i,i]", int1, in2 );<br />
<br />
# Don't forget to tell Python about the object.<br />
Py_INCREF(thePair);<br />
</source><br />
<br />
If you need to make a list of things to return, you iterate through a list and make a bunch of '''thePairs''' and add them to a Python list as follows:<br />
<source lang="c"><br />
# Make the python list<br />
PyObject* theList = PyList_New(0);<br />
# Tell Python about it<br />
Py_INCREF(theList);<br />
<br />
for ( int i = 0; i < someLim; i++ ) {<br />
PyObject* thePair = Py_BuildValue( "[i,i]", int1, in2 );<br />
Py_INCREF(thePair);<br />
PyList_Append(theList,thePair);<br />
</source><br />
To add a list of lists, just make an outer list, <source lang="c">PyObject* outerList = PyList_New(0);</source> and iteratively add to it your inner lists:<br />
<source lang="c"><br />
PyObject* outerList = PyList_New(0);<br />
Py_INCREF(outerList);<br />
<br />
for ( int i = 0; i < someLim; i++ ) {<br />
// make the inner list, called curList;<br />
curList = PyObject* curList = PyList_New(0);<br />
Py_INCREF(curList);<br />
<br />
// fill the inner list, using PyList_Append with some data, shown above<br />
...<br />
<br />
PyList_Append(outerList,curList);<br />
</source><br />
<br />
=== Initialization ===<br />
We need to discuss how our functions will be called from Python. First, we need to create a [http://docs.python.org/ext/methodTable.html method table].<br />
<source lang="c"><br />
static PyMethodDef CEMethods[] = {<br />
{"ccealign", ccealign_ccealign, METH_VARARGS, "Align two proteins using the CE Algorithm."},<br />
{NULL, NULL, 0, NULL}<br />
};<br />
</source><br />
<br />
Each module undergoes initialization. By default the modules init. function is: '''initNAME()'''. So, in our example above, '''initccealign()". During this initialization step, we need to call [Py_InitModule]. For or above example, we'd have<br />
<source lang="c"><br />
PyMODINIT_FUNC<br />
initccealign(void)<br />
{<br />
(void) Py_InitModule("ccealign", CEMethods);<br />
}<br />
</source><br />
<br />
Finally, the main function that starts the whole shebang should look something like:<br />
<source lang="c"><br />
int<br />
main(int argc, char* argv[])<br />
{<br />
Py_SetProgramName(argv[0]);<br />
Py_Initialize();<br />
initccealign();<br />
return(EXIT_SUCCESS);<br />
}<br />
</source><br />
<br />
This will be cleaned up later.<br />
<br />
=== Installing Your Module ===<br />
<br />
You can use python's setuptools. For example, I have cealign setup to install as simply as:<br />
<source lang="bash"><br />
python setup.py build cealign<br />
python setup.py install cealign<br />
</source><br />
and I'm set.<br />
<br />
==== Notes ====<br />
I'll finish this soon.<br />
[[User:Inchoate|Tree]]<br />
<br />
* Add the calling functions in C<br />
* discuss installation<br />
<br />
== Example ==<br />
See the source code for [[cealign]].<br />
<br />
<br />
<br />
== See Also ==<br />
[[stored]], [[iterate_state]], [[identify]].<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
[[Category:Development|Script_Tutorial]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Talk:Rasmolify&diff=122Talk:Rasmolify2008-02-29T04:10:22Z<p>Gilleain: </p>
<hr />
<div>Thanks to scripts found here; http://www.ebi.ac.uk/~gareth/pymol/ --[[User:Dan|Dan]] 07:44, 20 February 2008 (CST)<br />
<br />
I altered this slightly, but I didn't want to just replace the code (it uses a nested function, which isn't great, but makes some things clearer, I think):<br />
<br />
<source lang="python"><br />
selectionMap = {<br />
"water" : "r. hoh",<br />
"protein" : "all and not hetatm",<br />
"ligand" : "organic"<br />
}<br />
<br />
def processSelection(selection):<br />
if selection in selectionMap:<br />
print "selecting '%s' = '%s'" % (selection, selectionMap[selection])<br />
return selectionMap[selection]<br />
else:<br />
return selection<br />
<br />
def rselect(selection):<br />
cmd.select("_selection", processSelection(selection))<br />
cmd.extend("rselect", rselect)<br />
<br />
def displayFunctionGenerator(representation, rasmolName=None):<br />
if rasmolName is not None:<br />
representation = rasmolName<br />
def innerFunction(arg=None):<br />
if arg == 'off':<br />
cmd.hide(representation, "_selection")<br />
elif arg is None:<br />
cmd.show(representation, "_selection")<br />
return innerFunction<br />
<br />
def makeDisplayFunction(representation, rasmolName=None):<br />
cmd.extend(representation, displayFunctionGenerator(representation, rasmolName))<br />
<br />
makeDisplayFunction("spacefill", "spheres")<br />
makeDisplayFunction("cartoon")<br />
makeDisplayFunction("wireframe", "lines")<br />
makeDisplayFunction("sticks")<br />
makeDisplayFunction("dots")<br />
<br />
cmd.alias("quit", "exit")<br />
cmd.alias("zap", "delete all")<br />
</source><br />
--[[User:Gilleain|Gilleain]] 22:10, 28 February 2008 (CST)</div>Gilleainhttps://wiki.pymol.org/index.php?title=Category_talk:Script_Library&diff=4121Category talk:Script Library2008-02-19T01:27:53Z<p>Gilleain: </p>
<hr />
<div>Cant you make this using a DPL? --[[User:Dan|Dan]] 10:39, 18 February 2008 (CST)<br />
<br />
About the rasmolify script, there's a project to translate between the languages [http://arcib.dowling.edu/sbevsl/].<br />
It's in pre-alpha, apparently, but this kind of language translation seems like a tricky problem. It's on my list of things to do...--[[User:Gilleain|Gilleain]] 19:27, 18 February 2008 (CST)</div>Gilleainhttps://wiki.pymol.org/index.php?title=User:Gilleain&diff=3027User:Gilleain2007-10-09T20:57:59Z<p>Gilleain: </p>
<hr />
<div>Been using PyMol on OSX for a while now, I do a lot of python programming now so it's great to write scripts for ([http://cobra.mih.unibas.ch/dino/ dino] is also nice, but has a more tcl-like syntax).<br />
<br />
Currently doing a PhD in structural bioinformatics at Glasgow University. I used to work on the [http://www.tops.leeds.ac.uk TOPS] project.<br />
<br />
Scripts by me:<br />
<br />
* [[Translate_And_Measure]] : Move and report distances.<br />
* [[Bounding_Box]] : CGO box around a selection.<br />
* [[Ellipsoid]] : Callback ellipsoids.<br />
* [[Plane_Wizard]] : Wizard of the planes.<br />
* [[ss]] : List secondary structures as "start-end type".<br />
* [[iterate_sses]] : Advanced version of [[ss]], allows user to pass a function to be applied to each sse.<br />
* [[motif]] : Easy display of backbone motifs like nests and catgrips (or, of course, helices or strands). Also lists phi/psi.</div>Gilleainhttps://wiki.pymol.org/index.php?title=Category:Script_Library&diff=3889Category:Script Library2007-10-09T20:47:45Z<p>Gilleain: </p>
<hr />
<div>* [[Zero_residues]] -- Renumber residues such that the first residue is 0. Useful for alignments.<br />
<br />
* [[Cealign]] -- Implementation of the CE Structure Alignment algorithm as a PyMOL plugin.<br />
<br />
* [[WriteSS]] -- Writes secondary structural elements, for each residues, to a file.<br />
<br />
* [[Process_All_Files_In_Directory]] -- Do something to all files in a directory. The examples show how to print the disulfide bond lengths, then in general all sulfur distances (not necessarily bound).<br />
<br />
* [[Kabsch]] -- Kabsch alignment of two sets of vectors. (Part 2 of a protein alignment.)<br />
<br />
* [[Transform_odb]] -- Transform a selection of an existing object and output as a new object. The transformation matrix is read from an "O"-style tranformation matrix file (.odb) written by "O" or by any of the Uppsala Software Factory programs (from Gerard Klegweit) such as LSQMAN.<br />
<br />
* [[Stereo_Ray]] -- This script will create two resolution specific ray traced images rotated appropriately for inclusion into a single file to represent a stereo view of the desired macromolecule.<br />
<br />
* [[Translate_And_Measure]] -- prints '''overlap''' if any of the atoms in molA or molB were within 4 Angstrom after translating by 1 along X<br />
<br />
* [[Show aromatics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for aromatic residues displayed as green "sticks". Usage: Save this as "show_aromatics.pml", load your protein in PyMOL, and run the script (select "Run" from the "File" menu). (PyMOL script; TStout)<br />
<br />
* [[Show hydrophobics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophobic residues displayed as orange "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show charged]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for charged residues displayed as red (negative) or blue (posititve) "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show hydrophilic]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophilic residues displayed as green "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show NMR constrains]] -- This script will display the NMR constrains used for a structure calculation atop a structure. Usage: Save this as "NMRcnstr.py" load your protein in PyMOL, and run the script. type upl('fname') or cns('fname') where fname is the filename with the NMR constrains you want to display. <br />
<br />
* [[Perp Maker]] -- Creates a perpendicular plane through the center of your protein with respect to the camera's current position. (If you translate the protein towards the camera a bit, you get a nice surface, sometimes.) A stupid little script I wrote in response to a request a few months ago (and it doesn't even conform to the request!) Load a protein, run the script (read the documentation in the script). (Jason Vertrees/[[User:Tree|Tree]])<br />
<br />
* [[PythonTerminal]] -- Allows execution of python commands from the PyMOL command line.<br />
<br />
* [[Axes]] -- Creates a 3D-CGO object that shows the three coordinate axes.<br />
<br />
* [[CGO Text]] -- Creates a 3D-CGO text object.<br />
<br />
* [[List Selection]] -- Prints a list of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Colors]] -- Lists the color of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Secondary Structures]] -- Secondary structures (both predefined and those calculated with the 'dss' command) can be exported as a long string ('HHHHLLLLSSS').<br />
<br />
* [[Split Movement]] -- Moves two parts of one object into different directions.<br />
<br />
* [[Selection Exists]] -- Python method that returns true if a selection of a given name exists.<br />
<br />
* [[Get Coordinates I]] -- Retrieves atom coordinates as Python objects.<br />
<br />
* [[Get Coordinates II]] -- Retrieves atom coordinates as Python array (list object).<br />
<br />
* [[grepset]] -- List all settings matching a given keyword. - ''by EHP''<br />
<br />
* [[apropos]] -- List all commands matching a given keyword or whose docs contain the keyword. - ''by EHP''<br />
<br />
* [[mouse_modes]] -- customize the default mouse bindings for Viewing or Editing modes. - ''by EHP''<br />
<br />
* [[Measure Distance]] -- Measures the distance between two atoms (Python script).<br />
<br />
* [[Read PDB-String]] -- Parses a string in PDB format to a PyMOL object.<br />
<br />
* [[Color Objects]] -- Colors all objects differently (Python script).<br />
<br />
* [[Key Wait]] -- Process key events in a Python script.<br />
<br />
* [[Bounding Box]] -- Create a bounding box around a selection (Python script; requires numarray and Scientific; gilleain)<br />
<br />
* [[Ellipsoid]] -- Create callback object (opengl) ellipsoids. (Python script; gilleain)<br />
<br />
* [[pdbsurvey]] -- Surveys the pdb for recently added structures that are relevant to a user-specified keywords list (in a text file)<br />
<br />
* [[resicolor]] -- Colors proteins according to residue type.<br />
<br />
* [[TransformSelectionByCameraView]] -- Transforms the selection by the camera view.<br />
<br />
* [[WFMesh]] -- Imports wavefront object mesh files; Starwars as an example!<br />
<br />
* [[grepsel]] -- Make named selections using regular expressions (protein sequence).<br />
<br />
* [[PowerMate Dial OS X]] -- Script and instructions to use the PowerMate dial on Mac OS X.<br />
<br />
* [[Plane Wizard]] -- Wizard to draw planes between three picked points.<br />
<br />
* [[Slerpy]] -- Pymol command extensions for key frame animation movie making.<br />
<br />
* [[Helicity_check]] -- helicity_check show the evolution of O - N distances over an amino acid sequence<br />
<br />
* [[Center Of Mass]] -- Given a selection of atoms (of equal weight) - Calculates the center of mass and represents it with a CGO sphere<br />
<br />
* [[ss]] -- Simple command to summarise the Secondary Structure as a list of "start-end type" like sses.<br />
<br />
* [[iterate_sses]] -- Slightly more complex version of "ss" that allows the user to pass in a function to act on the sse list.<br />
<br />
* [[motif]] -- Designed for easy display of backbone motifs (nests, catgrips, etc).<br />
<br />
[[Category:Scripting|Script Library]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Iterate_sses&diff=8389Iterate sses2007-10-09T16:57:18Z<p>Gilleain: same change as for the ss command.</p>
<hr />
<div>A slightly more complex version of [[ss]] that allows the user to pass in a function to act on the sse list. Of course, this requires the user to know about the internals of the sse class, but since this code is all open I doubt that matters..<br />
<br />
<source lang="python"><br />
def iterate_sses(selection, action):<br />
<br />
class SSE(object):<br />
<br />
def __init__(self, start, typ, sseNumber):<br />
self.start, self.typ = start, typ<br />
self.end = -1<br />
self.sseNumber = sseNumber<br />
<br />
def __repr__(self):<br />
return "%s-%s %s" % (self.start, self.end, self.typ)<br />
<br />
stored.pairs = []<br />
cmd.iterate(selection, "stored.pairs.append((resi, ss))")<br />
num, currentType = stored.pairs[0]<br />
<br />
sseNumber = 1<br />
sses = [SSE(num, currentType, sseNumber)]<br />
currentSSE = sses[0]<br />
for resi, ssType in stored.pairs:<br />
if ssType == currentType:<br />
currentSSE.end = resi<br />
else:<br />
sseNumber += 1<br />
sses.append(SSE(resi, ssType, sseNumber))<br />
currentSSE = sses[-1]<br />
currentType = ssType<br />
<br />
for sse in sses:<br />
action(sse)<br />
<br />
cmd.extend("iterate_sses", iterate_sses)<br />
</source><br />
<br />
As an example, here is a function that makes a series of selections, one for each sse, called "H1", "E2", and so on. Use it like: "iterate_sses('my_protein', doSelect)".<br />
<source lang="python"><br />
def doSelect(sse):<br />
cmd.select("%s%s" % (sse.typ, sse.sseNumber), "i. %s-%s" % (sse.start, sse.end))<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Ss&diff=10350Ss2007-10-09T16:56:06Z<p>Gilleain: changed a loop variable to avoid name clashes.</p>
<hr />
<div>A command to list a summary of the secondary structure for a selection. Use like "ss my_protein" where "my_protein" is the name of the chain or structure in view.<br />
<br />
<source lang="python"><br />
def ss(selection):<br />
<br />
class SSE(object):<br />
<br />
def __init__(self, start, typ):<br />
self.start, self.typ = start, typ<br />
self.end = -1<br />
<br />
def __repr__(self):<br />
return "%s-%s %s" % (self.start, self.end, self.typ)<br />
<br />
stored.pairs = []<br />
cmd.iterate(selection, "stored.pairs.append((resi, ss))")<br />
num, currentType = stored.pairs[0]<br />
<br />
sses = [SSE(num, currentType)]<br />
currentSSE = sses[0]<br />
for resi, ssType in stored.pairs:<br />
if ssType == currentType:<br />
currentSSE.end = resi<br />
else:<br />
sses.append(SSE(resi, ssType))<br />
currentSSE = sses[-1]<br />
currentType = ssType<br />
<br />
for sse in sses:<br />
print sse<br />
<br />
cmd.extend("ss", ss)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Iterate_sses&diff=8388Iterate sses2007-10-09T10:25:41Z<p>Gilleain: New page: A slightly more complex version of ss that allows the user to pass in a function to act on the sse list. Of course, this requires the user to know about the internals of the sse class,...</p>
<hr />
<div>A slightly more complex version of [[ss]] that allows the user to pass in a function to act on the sse list. Of course, this requires the user to know about the internals of the sse class, but since this code is all open I doubt that matters..<br />
<br />
<source lang="python"><br />
def iterate_sses(selection, action):<br />
<br />
class SSE(object):<br />
<br />
def __init__(self, start, typ, sseNumber):<br />
self.start, self.typ = start, typ<br />
self.end = -1<br />
self.sseNumber = sseNumber<br />
<br />
def __repr__(self):<br />
return "%s-%s %s" % (self.start, self.end, self.typ)<br />
<br />
stored.pairs = []<br />
cmd.iterate(selection, "stored.pairs.append((resi, ss))")<br />
num, currentType = stored.pairs[0]<br />
<br />
sseNumber = 1<br />
sses = [SSE(num, currentType, sseNumber)]<br />
currentSSE = sses[0]<br />
for resi, ss in stored.pairs:<br />
if ss == currentType:<br />
currentSSE.end = resi<br />
else:<br />
sseNumber += 1<br />
sses.append(SSE(resi, ss, sseNumber))<br />
currentSSE = sses[-1]<br />
currentType = ss<br />
<br />
for sse in sses:<br />
action(sse)<br />
<br />
cmd.extend("iterate_sses", iterate_sses)<br />
</source><br />
<br />
As an example, here is a function that makes a series of selections, one for each sse, called "H1", "E2", and so on. Use it like: "iterate_sses('my_protein', doSelect)".<br />
<source lang="python"><br />
def doSelect(sse):<br />
cmd.select("%s%s" % (sse.typ, sse.sseNumber), "i. %s-%s" % (sse.start, sse.end))<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Ss&diff=10349Ss2007-10-09T10:20:07Z<p>Gilleain: New page: A command to list a summary of the secondary structure for a selection. Use like "ss my_protein" where "my_protein" is the name of the chain or structure in view. <source lang="python"> def ss(selectio...</p>
<hr />
<div>A command to list a summary of the secondary structure for a selection. Use like "ss my_protein" where "my_protein" is the name of the chain or structure in view.<br />
<br />
<source lang="python"><br />
def ss(selection):<br />
<br />
class SSE(object):<br />
<br />
def __init__(self, start, typ):<br />
self.start, self.typ = start, typ<br />
self.end = -1<br />
<br />
def __repr__(self):<br />
return "%s-%s %s" % (self.start, self.end, self.typ)<br />
<br />
stored.pairs = []<br />
cmd.iterate(selection, "stored.pairs.append((resi, ss))")<br />
num, currentType = stored.pairs[0]<br />
<br />
sses = [SSE(num, currentType)]<br />
currentSSE = sses[0]<br />
for resi, ss in stored.pairs:<br />
if ss == currentType:<br />
currentSSE.end = resi<br />
else:<br />
sses.append(SSE(resi, ss))<br />
currentSSE = sses[-1]<br />
currentType = ss<br />
<br />
for sse in sses:<br />
print sse<br />
<br />
cmd.extend("ss", ss)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Category:Script_Library&diff=3888Category:Script Library2007-10-09T10:15:34Z<p>Gilleain: </p>
<hr />
<div>* [[Zero_residues]] -- Renumber residues such that the first residue is 0. Useful for alignments.<br />
<br />
* [[Cealign]] -- Implementation of the CE Structure Alignment algorithm as a PyMOL plugin.<br />
<br />
* [[WriteSS]] -- Writes secondary structural elements, for each residues, to a file.<br />
<br />
* [[Process_All_Files_In_Directory]] -- Do something to all files in a directory. The examples show how to print the disulfide bond lengths, then in general all sulfur distances (not necessarily bound).<br />
<br />
* [[Kabsch]] -- Kabsch alignment of two sets of vectors. (Part 2 of a protein alignment.)<br />
<br />
* [[Transform_odb]] -- Transform a selection of an existing object and output as a new object. The transformation matrix is read from an "O"-style tranformation matrix file (.odb) written by "O" or by any of the Uppsala Software Factory programs (from Gerard Klegweit) such as LSQMAN.<br />
<br />
* [[Stereo_Ray]] -- This script will create two resolution specific ray traced images rotated appropriately for inclusion into a single file to represent a stereo view of the desired macromolecule.<br />
<br />
* [[Translate_And_Measure]] -- prints '''overlap''' if any of the atoms in molA or molB were within 4 Angstrom after translating by 1 along X<br />
<br />
* [[Show aromatics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for aromatic residues displayed as green "sticks". Usage: Save this as "show_aromatics.pml", load your protein in PyMOL, and run the script (select "Run" from the "File" menu). (PyMOL script; TStout)<br />
<br />
* [[Show hydrophobics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophobic residues displayed as orange "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show charged]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for charged residues displayed as red (negative) or blue (posititve) "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show hydrophilic]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophilic residues displayed as green "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show NMR constrains]] -- This script will display the NMR constrains used for a structure calculation atop a structure. Usage: Save this as "NMRcnstr.py" load your protein in PyMOL, and run the script. type upl('fname') or cns('fname') where fname is the filename with the NMR constrains you want to display. <br />
<br />
* [[Perp Maker]] -- Creates a perpendicular plane through the center of your protein with respect to the camera's current position. (If you translate the protein towards the camera a bit, you get a nice surface, sometimes.) A stupid little script I wrote in response to a request a few months ago (and it doesn't even conform to the request!) Load a protein, run the script (read the documentation in the script). (Jason Vertrees/[[User:Tree|Tree]])<br />
<br />
* [[PythonTerminal]] -- Allows execution of python commands from the PyMOL command line.<br />
<br />
* [[Axes]] -- Creates a 3D-CGO object that shows the three coordinate axes.<br />
<br />
* [[CGO Text]] -- Creates a 3D-CGO text object.<br />
<br />
* [[List Selection]] -- Prints a list of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Colors]] -- Lists the color of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Secondary Structures]] -- Secondary structures (both predefined and those calculated with the 'dss' command) can be exported as a long string ('HHHHLLLLSSS').<br />
<br />
* [[Split Movement]] -- Moves two parts of one object into different directions.<br />
<br />
* [[Selection Exists]] -- Python method that returns true if a selection of a given name exists.<br />
<br />
* [[Get Coordinates I]] -- Retrieves atom coordinates as Python objects.<br />
<br />
* [[Get Coordinates II]] -- Retrieves atom coordinates as Python array (list object).<br />
<br />
* [[grepset]] -- List all settings matching a given keyword. - ''by EHP''<br />
<br />
* [[apropos]] -- List all commands matching a given keyword or whose docs contain the keyword. - ''by EHP''<br />
<br />
* [[mouse_modes]] -- customize the default mouse bindings for Viewing or Editing modes. - ''by EHP''<br />
<br />
* [[Measure Distance]] -- Measures the distance between two atoms (Python script).<br />
<br />
* [[Read PDB-String]] -- Parses a string in PDB format to a PyMOL object.<br />
<br />
* [[Color Objects]] -- Colors all objects differently (Python script).<br />
<br />
* [[Key Wait]] -- Process key events in a Python script.<br />
<br />
* [[Bounding Box]] -- Create a bounding box around a selection (Python script; requires numarray and Scientific; gilleain)<br />
<br />
* [[Ellipsoid]] -- Create callback object (opengl) ellipsoids. (Python script; gilleain)<br />
<br />
* [[pdbsurvey]] -- Surveys the pdb for recently added structures that are relevant to a user-specified keywords list (in a text file)<br />
<br />
* [[resicolor]] -- Colors proteins according to residue type.<br />
<br />
* [[TransformSelectionByCameraView]] -- Transforms the selection by the camera view.<br />
<br />
* [[WFMesh]] -- Imports wavefront object mesh files; Starwars as an example!<br />
<br />
* [[grepsel]] -- Make named selections using regular expressions (protein sequence).<br />
<br />
* [[PowerMate Dial OS X]] -- Script and instructions to use the PowerMate dial on Mac OS X.<br />
<br />
* [[Plane Wizard]] -- Wizard to draw planes between three picked points.<br />
<br />
* [[Slerpy]] -- Pymol command extensions for key frame animation movie making.<br />
<br />
* [[Helicity_check]] -- helicity_check show the evolution of O - N distances over an amino acid sequence<br />
<br />
* [[Center Of Mass]] -- Given a selection of atoms (of equal weight) - Calculates the center of mass and represents it with a CGO sphere<br />
<br />
* [[ss]] -- Simple command to summarise the Secondary Structure as a list of "start-end type" like sses.<br />
<br />
* [[iterate_sses]] -- Slightly more complex version of "ss" that allows the user to pass in a function to act on the sse list.<br />
<br />
[[Category:Scripting|Script Library]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Talk:Plane_Wizard&diff=111Talk:Plane Wizard2006-09-26T15:25:28Z<p>Gilleain: </p>
<hr />
<div>I tried this out - it's pretty neat - good job!<br />
<br />
Two minor comments:<br />
- any plane created goes away when exiting the wizard. Is this intended?<br />
- I found a typo in the code (spacing) on line 112 & corrected it<br />
<br />
Hmm. For my purposes when I made it, cleaning up on exit was the right thing to do, but I guess other people might want it not to. Wizards are a little too simple for preferences...<br />
<br />
If I ever manage to make plugins on OSX, then a plane (or geometry!) plugin would be more flexible.</div>Gilleainhttps://wiki.pymol.org/index.php?title=Plane_Wizard&diff=12931Plane Wizard2006-09-22T09:22:22Z<p>Gilleain: /* '''Plane Wizard''' */</p>
<hr />
<div>This wizard has a simple purpose - to draw a cgo plane that passes through three points picked by the user. Most of the wizard itself was copied from the measure wizard.<br />
<br />
To use, put it in the same directory as the other wizards. This is not quality code, and there may be bugs, but it seems to work okay.<br />
<br />
<source lang="python"><br />
import pymol<br />
from pymol import cmd<br />
from pymol.wizard import Wizard<br />
from chempy import cpv<br />
from cgo import *<br />
<br />
def makePrimitive(cgo, name):<br />
cmd.set('auto_zoom', 0, quiet=1)<br />
cmd.load_cgo(cgo, name)<br />
cmd.set('auto_zoom', 1, quiet=1)<br />
<br />
def point(p):<br />
x, y, z = p<br />
return [COLOR, 1, 1, 1, SPHERE, float(x), float(y), float(z), 0.5]<br />
<br />
def line(p1, p2):<br />
x1, y1, z1 = p1<br />
x2, y2, z2 = p2<br />
return [CYLINDER, float(x1), float(y1), float(z1), float(x2), float(y2), float(z2), 0.25, 1, 1, 1, 1, 1, 1]<br />
<br />
def plane(corner1, corner2, corner3, corner4, normal):<br />
planeObj = []<br />
planeObj.extend(point(corner1))<br />
planeObj.extend(point(corner2))<br />
planeObj.extend(point(corner3))<br />
planeObj.extend(point(corner4))<br />
planeObj.extend(line(corner1, corner2))<br />
planeObj.extend(line(corner2, corner3))<br />
planeObj.extend(line(corner3, corner4))<br />
planeObj.extend(line(corner4, corner1))<br />
<br />
planeObj.extend([COLOR, 0.8, 0.8, 0.8])<br />
planeObj.extend([BEGIN, TRIANGLE_STRIP])<br />
planeObj.append(NORMAL)<br />
planeObj.extend(normal)<br />
for corner in [corner1, corner2, corner3, corner4, corner1]:<br />
planeObj.append(VERTEX)<br />
planeObj.extend(corner)<br />
planeObj.append(END)<br />
return planeObj<br />
<br />
def planeFromPoints(point1, point2, point3, facetSize):<br />
v1 = cpv.normalize(cpv.sub(point2, point1))<br />
v2 = cpv.normalize(cpv.sub(point3, point1))<br />
normal = cpv.cross_product(v1, v2)<br />
v2 = cpv.cross_product(normal, v1)<br />
x = cpv.scale(v1, facetSize)<br />
y = cpv.scale(v2, facetSize)<br />
center = point2<br />
corner1 = cpv.add(cpv.add(center, x), y)<br />
corner2 = cpv.sub(cpv.add(center, x), y)<br />
corner3 = cpv.sub(cpv.sub(center, x), y)<br />
corner4 = cpv.add(cpv.sub(center, x), y)<br />
return plane(corner1, corner2, corner3, corner4, normal)<br />
<br />
<br />
class PlaneWizard(Wizard):<br />
<br />
def __init__(self):<br />
Wizard.__init__(self)<br />
<br />
# some attributes to do with picking<br />
self.pick_count = 0<br />
self.object_count = 0<br />
self.object_prefix = "pw"<br />
<br />
# the plane facet size (the 'radius' of the section of plane we show)<br />
self.facetSize = 5<br />
<br />
self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")<br />
cmd.set("mouse_selection_mode",0) # set selection mode to atomic<br />
cmd.deselect()<br />
<br />
def reset(self):<br />
cmd.delete(self.object_prefix + "*")<br />
cmd.delete("sele*")<br />
cmd.delete("_indicate*")<br />
cmd.unpick()<br />
cmd.refresh_wizard()<br />
<br />
def delete_all(self):<br />
cmd.delete("plane*")<br />
<br />
def cleanup(self):<br />
cmd.set("mouse_selection_mode",self.selection_mode) # restore selection mode<br />
self.reset()<br />
self.delete_all()<br />
<br />
def get_prompt(self):<br />
self.prompt = None<br />
if self.pick_count == 0:<br />
self.prompt = [ 'Please click on the first atom...']<br />
elif self.pick_count == 1:<br />
self.prompt = [ 'Please click on the second atom...' ]<br />
elif self.pick_count == 2:<br />
self.prompt = [ 'Please click on the third atom...' ]<br />
return self.prompt<br />
<br />
def do_select(self, name):<br />
# "edit" only this atom, and not others with the object prefix<br />
try:<br />
cmd.edit("%s and not %s*" % (name, self.object_prefix))<br />
self.do_pick(0)<br />
except pymol.CmdException, pmce:<br />
print pmce<br />
<br />
def pickNextAtom(self, atom_name):<br />
# transfer the click selection to a named selection<br />
cmd.select(atom_name, "(pk1)")<br />
<br />
# delete the click selection<br />
cmd.unpick()<br />
<br />
# using the magic of indicate, highlight stuff<br />
indicate_selection = "_indicate" + self.object_prefix<br />
cmd.select(indicate_selection, atom_name)<br />
cmd.enable(indicate_selection)<br />
<br />
self.pick_count += 1<br />
self.error = None<br />
<br />
# necessary to force update of the prompt<br />
cmd.refresh_wizard()<br />
<br />
def do_pick(self, picked_bond):<br />
<br />
# this shouldn't actually happen if going through the "do_select"<br />
if picked_bond:<br />
self.error = "Error: please select bonds, not atoms"<br />
print self.error<br />
return<br />
<br />
atom_name = self.object_prefix + str(self.pick_count)<br />
if self.pick_count < 2:<br />
self.pickNextAtom(atom_name)<br />
else:<br />
self.pickNextAtom(atom_name)<br />
<br />
point1 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "0"))<br />
point2 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "1"))<br />
point3 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "2"))<br />
plane = planeFromPoints(point1, point2, point3, self.facetSize)<br />
<br />
planeName = "plane-%02d" % self.object_count<br />
self.object_count += 1<br />
makePrimitive(plane, planeName)<br />
cmd.show("cgo", "plane*")<br />
<br />
self.pick_count = 0<br />
self.reset()<br />
<br />
def get_panel(self):<br />
return [<br />
[ 1, 'Plane Wizard',''],<br />
[ 2, 'Reset','cmd.get_wizard().reset()'],<br />
[ 2, 'Delete All Planes' , 'cmd.get_wizard().delete_all()'],<br />
[ 2, 'Done','cmd.set_wizard()'],<br />
]<br />
<br />
# create an instance<br />
<br />
wiz = PlaneWizard()<br />
<br />
# make this the active wizard<br />
<br />
cmd.set_wizard(wiz)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Plane_Wizard&diff=12930Plane Wizard2006-09-22T09:21:39Z<p>Gilleain: </p>
<hr />
<div>=='''Plane Wizard'''==<br />
<br />
This wizard has a simple purpose - to draw a cgo plane that passes through three points picked by the user. Most of the wizard itself was copied from the measure wizard.<br />
<br />
To use, put it in the same directory as the other wizards. This is not quality code, and there may be bugs, but it seems to work okay.<br />
<br />
<source lang="python"><br />
import pymol<br />
from pymol import cmd<br />
from pymol.wizard import Wizard<br />
from chempy import cpv<br />
from cgo import *<br />
<br />
def makePrimitive(cgo, name):<br />
cmd.set('auto_zoom', 0, quiet=1)<br />
cmd.load_cgo(cgo, name)<br />
cmd.set('auto_zoom', 1, quiet=1)<br />
<br />
def point(p):<br />
x, y, z = p<br />
return [COLOR, 1, 1, 1, SPHERE, float(x), float(y), float(z), 0.5]<br />
<br />
def line(p1, p2):<br />
x1, y1, z1 = p1<br />
x2, y2, z2 = p2<br />
return [CYLINDER, float(x1), float(y1), float(z1), float(x2), float(y2), float(z2), 0.25, 1, 1, 1, 1, 1, 1]<br />
<br />
def plane(corner1, corner2, corner3, corner4, normal):<br />
planeObj = []<br />
planeObj.extend(point(corner1))<br />
planeObj.extend(point(corner2))<br />
planeObj.extend(point(corner3))<br />
planeObj.extend(point(corner4))<br />
planeObj.extend(line(corner1, corner2))<br />
planeObj.extend(line(corner2, corner3))<br />
planeObj.extend(line(corner3, corner4))<br />
planeObj.extend(line(corner4, corner1))<br />
<br />
planeObj.extend([COLOR, 0.8, 0.8, 0.8])<br />
planeObj.extend([BEGIN, TRIANGLE_STRIP])<br />
planeObj.append(NORMAL)<br />
planeObj.extend(normal)<br />
for corner in [corner1, corner2, corner3, corner4, corner1]:<br />
planeObj.append(VERTEX)<br />
planeObj.extend(corner)<br />
planeObj.append(END)<br />
return planeObj<br />
<br />
def planeFromPoints(point1, point2, point3, facetSize):<br />
v1 = cpv.normalize(cpv.sub(point2, point1))<br />
v2 = cpv.normalize(cpv.sub(point3, point1))<br />
normal = cpv.cross_product(v1, v2)<br />
v2 = cpv.cross_product(normal, v1)<br />
x = cpv.scale(v1, facetSize)<br />
y = cpv.scale(v2, facetSize)<br />
center = point2<br />
corner1 = cpv.add(cpv.add(center, x), y)<br />
corner2 = cpv.sub(cpv.add(center, x), y)<br />
corner3 = cpv.sub(cpv.sub(center, x), y)<br />
corner4 = cpv.add(cpv.sub(center, x), y)<br />
return plane(corner1, corner2, corner3, corner4, normal)<br />
<br />
<br />
class PlaneWizard(Wizard):<br />
<br />
def __init__(self):<br />
Wizard.__init__(self)<br />
<br />
# some attributes to do with picking<br />
self.pick_count = 0<br />
self.object_count = 0<br />
self.object_prefix = "pw"<br />
<br />
# the plane facet size (the 'radius' of the section of plane we show)<br />
self.facetSize = 5<br />
<br />
self.selection_mode = cmd.get_setting_legacy("mouse_selection_mode")<br />
cmd.set("mouse_selection_mode",0) # set selection mode to atomic<br />
cmd.deselect()<br />
<br />
def reset(self):<br />
cmd.delete(self.object_prefix + "*")<br />
cmd.delete("sele*")<br />
cmd.delete("_indicate*")<br />
cmd.unpick()<br />
cmd.refresh_wizard()<br />
<br />
def delete_all(self):<br />
cmd.delete("plane*")<br />
<br />
def cleanup(self):<br />
cmd.set("mouse_selection_mode",self.selection_mode) # restore selection mode<br />
self.reset()<br />
self.delete_all()<br />
<br />
def get_prompt(self):<br />
self.prompt = None<br />
if self.pick_count == 0:<br />
self.prompt = [ 'Please click on the first atom...']<br />
elif self.pick_count == 1:<br />
self.prompt = [ 'Please click on the second atom...' ]<br />
elif self.pick_count == 2:<br />
self.prompt = [ 'Please click on the third atom...' ]<br />
return self.prompt<br />
<br />
def do_select(self, name):<br />
# "edit" only this atom, and not others with the object prefix<br />
try:<br />
cmd.edit("%s and not %s*" % (name, self.object_prefix))<br />
self.do_pick(0)<br />
except pymol.CmdException, pmce:<br />
print pmce<br />
<br />
def pickNextAtom(self, atom_name):<br />
# transfer the click selection to a named selection<br />
cmd.select(atom_name, "(pk1)")<br />
<br />
# delete the click selection<br />
cmd.unpick()<br />
<br />
# using the magic of indicate, highlight stuff<br />
indicate_selection = "_indicate" + self.object_prefix<br />
cmd.select(indicate_selection, atom_name)<br />
cmd.enable(indicate_selection)<br />
<br />
self.pick_count += 1<br />
self.error = None<br />
<br />
# necessary to force update of the prompt<br />
cmd.refresh_wizard()<br />
<br />
def do_pick(self, picked_bond):<br />
<br />
# this shouldn't actually happen if going through the "do_select"<br />
if picked_bond:<br />
self.error = "Error: please select bonds, not atoms"<br />
print self.error<br />
return<br />
<br />
atom_name = self.object_prefix + str(self.pick_count)<br />
if self.pick_count < 2:<br />
self.pickNextAtom(atom_name)<br />
else:<br />
self.pickNextAtom(atom_name)<br />
<br />
point1 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "0"))<br />
point2 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "1"))<br />
point3 = cmd.get_atom_coords("(%s%s)" % (self.object_prefix, "2"))<br />
plane = planeFromPoints(point1, point2, point3, self.facetSize)<br />
<br />
planeName = "plane-%02d" % self.object_count<br />
self.object_count += 1<br />
makePrimitive(plane, planeName)<br />
cmd.show("cgo", "plane*")<br />
<br />
self.pick_count = 0<br />
self.reset()<br />
<br />
def get_panel(self):<br />
return [<br />
[ 1, 'Plane Wizard',''],<br />
[ 2, 'Reset','cmd.get_wizard().reset()'],<br />
[ 2, 'Delete All Planes' , 'cmd.get_wizard().delete_all()'],<br />
[ 2, 'Done','cmd.set_wizard()'],<br />
]<br />
<br />
# create an instance<br />
<br />
wiz = PlaneWizard()<br />
<br />
# make this the active wizard<br />
<br />
cmd.set_wizard(wiz)<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Category:Script_Library&diff=3879Category:Script Library2006-09-22T09:14:45Z<p>Gilleain: </p>
<hr />
<div>* [[Process_All_Files_In_Directory]] -- Do something to all files in a directory. The examples show how to print the disulfide bond lengths, then in general all sulfur distances (not necessarily bound).<br />
<br />
* [[Kabsch]] -- Kabsch alignment of two sets of vectors. (Part 2 of a protein alignment.)<br />
<br />
* [[Transform_odb]] -- Transform a selection of an existing object and output as a new object. The transformation matrix is read from an "O"-style tranformation matrix file (.odb) written by "O" or by any of the Uppsala Software Factory programs (from Gerard Klegweit) such as LSQMAN.<br />
<br />
* [[Stereo_Ray]] -- This script will create two resolution specific ray traced images rotated appropriately for inclusion into a single file to represent a stereo view of the desired macromolecule.<br />
<br />
* [[Translate_And_Measure]] -- prints '''overlap''' if any of the atoms in molA or molB were within 4 Angstrom after translating by 1 along X<br />
<br />
* [[Show aromatics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for aromatic residues displayed as green "sticks". Usage: Save this as "show_aromatics.pml", load your protein in PyMOL, and run the script (select "Run" from the "File" menu). (PyMOL script; TStout)<br />
<br />
* [[Show hydrophobics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophobic residues displayed as orange "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show charged]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for charged residues displayed as red (negative) or blue (posititve) "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show hydrophilic]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophilic residues displayed as green "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show NMR constrains]] -- This script will display the NMR constrains used for a structure calculation atop a structure. Usage: Save this as "NMRcnstr.py" load your protein in PyMOL, and run the script. type upl('fname') or cns('fname') where fname is the filename with the NMR constrains you want to display. <br />
<br />
* [[Perp Maker]] -- Creates a perpendicular plane through the center of your protein with respect to the camera's current position. (If you translate the protein towards the camera a bit, you get a nice surface, sometimes.) A stupid little script I wrote in response to a request a few months ago (and it doesn't even conform to the request!) Load a protein, run the script (read the documentation in the script). (Jason Vertrees/[[User:Tree|Tree]])<br />
<br />
* [[PythonTerminal]] -- Allows execution of python commands from the PyMOL command line.<br />
<br />
* [[Axes]] -- Creates a 3D-CGO object that shows the three coordinate axes.<br />
<br />
* [[CGO Text]] -- Creates a 3D-CGO text object.<br />
<br />
* [[List Selection]] -- Prints a list of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Colors]] -- Lists the color of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Secondary Structures]] -- Secondary structures (both predefined and those calculated with the 'dss' command) can be exported as a long string ('HHHHLLLLSSS').<br />
<br />
* [[Split Movement]] -- Moves two parts of one object into different directions.<br />
<br />
* [[Selection Exists]] -- Python method that returns true if a selection of a given name exists.<br />
<br />
* [[Get Coordinates I]] -- Retrieves atom coordinates as Python objects.<br />
<br />
* [[Get Coordinates II]] -- Retrieves atom coordinates as Python array (list object).<br />
<br />
* [[grepset]] -- List all settings matching a given keyword. - ''by EHP''<br />
<br />
* [[apropos]] -- List all commands matching a given keyword or whose docs contain the keyword. - ''by EHP''<br />
<br />
* [[mouse_modes]] -- customize the default mouse bindings for Viewing or Editing modes. - ''by EHP''<br />
<br />
* [[Measure Distance]] -- Measures the distance between two atoms (Python script).<br />
<br />
* [[Read PDB-String]] -- Parses a string in PDB format to a PyMOL object.<br />
<br />
* [[Color Objects]] -- Colors all objects differently (Python script).<br />
<br />
* [[Key Wait]] -- Process key events in a Python script.<br />
<br />
* [[Bounding Box]] -- Create a bounding box around a selection (Python script; requires numarray and Scientific; gilleain)<br />
<br />
* [[Ellipsoid]] -- Create callback object (opengl) ellipsoids. (Python script; gilleain)<br />
<br />
* [[pdbsurvey]] -- Surveys the pdb for recently added structures that are relevant to a user-specified keywords list (in a text file)<br />
<br />
* [[TransformSelectionByCameraView]] -- Transforms the selection by the camera view.<br />
<br />
* [[WFMesh]] -- Imports wavefront object mesh files; Starwars as an example!<br />
<br />
* [[grepsel]] -- Make named selections using regular expressions (protein sequence).<br />
<br />
* [[PowerMate Dial OS X]] -- Script and instructions to use the PowerMate dial on Mac OS X.<br />
<br />
* [[Plane Wizard]] -- Wizard to draw planes between three picked points.<br />
<br />
[[Category:Scripting|Script Library]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Talk:Main_Page&diff=392Talk:Main Page2005-12-08T14:58:19Z<p>Gilleain: Removed spam links</p>
<hr />
<div></div>Gilleainhttps://wiki.pymol.org/index.php?title=Bounding_Box&diff=6497Bounding Box2005-10-20T04:25:20Z<p>Gilleain: fixed to work again. not sure what has changed!</p>
<hr />
<div><source lang="python"><br />
import math<br />
from pymol import querying<br />
from pymol.cgo import *<br />
from pymol import cmd<br />
<br />
#NOTE!! : These packages (numarray, Scientific) must be present in pymol's <br />
#'$PYMOLDIR/py23/lib/python2.3/site-packages/' directory!!<br />
# OR..if you are using Mac PyMOL 0.99beta19 or later then the system installs will be used<br />
from numarray import *<br />
from numarray.ma import average<br />
from numarray import linear_algebra as la<br />
<br />
from Scientific.Geometry import Vector, Tensor, Transformation<br />
<br />
def boundingBox(selectionName, colourRGB=[1,1,1]):<br />
"""<br />
The main function to call : <br />
<br />
run "box.py"<br />
boundingBox("peptide")<br />
<br />
Should make a box around "peptide" (assuming it exists!). For a different colour use:<br />
<br />
boundingBox("peptide", colourRGB=[1, 0, 1])<br />
<br />
Or whatever. The box should be a cgo called 'peptide-box' (for this example).<br />
"""<br />
model = querying.get_model(selectionName)<br />
coords = model.get_coord_list()<br />
<br />
#find the least square plane through the coordinates<br />
eigenvalues, eigenvectors, centroid = findPlaneWithEigenVectors(coords)<br />
normal = eigenvectors[eigenvalues.argmin()]<br />
eigenvectors.remove(normal)<br />
<br />
#orient the axes correctly<br />
x, y, normal = orientAxes(eigenvectors[0], eigenvectors[1], normal)<br />
<br />
#determine the dimensions and the structure's orientation wrt the origin<br />
minDimensions, rotation = findMinDimensionsAndRotation(coords, centroid, x, y, normal)<br />
<br />
#'create' the box(IE: make the corners) and 'draw' it (IE: make a cgo)<br />
box = makeBox(minDimensions, rotation, centroid)<br />
drawBox(box, selectionName, colourRGB)<br />
<br />
def findPlaneWithEigenVectors(coords):<br />
centroid = average(coords)<br />
coords -= centroid<br />
B = matrixmultiply(transpose(coords), coords)<br />
eigenvalues, eigenvectors = la.eigenvectors(B)<br />
#return eigenvalues, [Vector(e) for e in eigenvectors], Vector(centroid)<br />
return eigenvalues, [Vector([i for i in e]) for e in eigenvectors], Vector(centroid) #not sure why I had to make this change!<br />
<br />
def orientAxes(x, y, z):<br />
XcrossY = x.cross(y)<br />
#ZXY = around(math.degrees(z.angle(XcrossY)))<br />
ZXY = int(around(math.degrees(z.angle(XcrossY)))) #again, a bit of a hack!<br />
if (ZXY == 180): x, y = y, x<br />
return x, y, z<br />
<br />
def makeBox(dimensions, rotation, centroid):<br />
x, y, z = dimensions<br />
v = [[]] * 8<br />
<br />
#make a cuboid with the lower corner on the origin<br />
v[0] = [0, 0, 0] # [0, 0, 0]<br />
v[1] = [x, 0, 0] # [1, 0, 0]<br />
v[2] = [x, y, 0] # [1, 1, 0]<br />
v[3] = [x, 0, z] # [1, 0, 1]<br />
v[4] = [0, y, 0] # [0, 1, 0]<br />
v[5] = [0, 0, z] # [0, 0, 1]<br />
v[6] = [0, y, z] # [0, 1, 1]<br />
v[7] = [x, y, z] # [1, 1, 1]<br />
<br />
#move to the origin, THEN move to the centroid of the points, then rotate<br />
translationToOrigin = Transformation.Translation(-Vector(x/2, y/2, z/2))<br />
translationToCentroid = Transformation.Translation(centroid)<br />
transform = translationToCentroid * rotation * translationToOrigin<br />
<br />
#use the Transformation to transform the corners of the box<br />
v = [transform(Vector(i)) for i in v]<br />
<br />
bot = [v[0], v[1], v[2], v[4]] # O, x, xy, y<br />
top = [v[7], v[3], v[5], v[6]] # xyz, xz, z, yz<br />
minL = [v[0], v[4], v[6], v[5]] # O, y, yz, z<br />
minR = [v[0], v[5], v[3], v[1]] # O, z, xz, x<br />
maxL = [v[4], v[2], v[7], v[6]] # y, xy, xyz, yz<br />
maxR = [v[3], v[1], v[2], v[7]] # xz, x, xy, xyz<br />
box = [bot, minR, minL, maxR, maxL, top]<br />
<br />
return box<br />
<br />
def drawBox(box, name, colourRGB):<br />
boxObj = []<br />
for side in box:<br />
boxObj.append(BEGIN)<br />
boxObj.append(LINE_STRIP)<br />
boxObj.append(COLOR)<br />
boxObj.extend(colourRGB)<br />
for point in side:<br />
boxObj.append(VERTEX)<br />
boxObj.extend(point)<br />
boxObj.append(END)<br />
<br />
cmd.set('auto_zoom', 0)<br />
cmd.load_cgo(boxObj, "%s-box" % name)<br />
cmd.set('auto_zoom', 1)<br />
<br />
def findMinDimensionsAndRotation(coords, centroid, x, y, z):<br />
O = Vector(0, 0, 0)<br />
X = Vector(1, 0, 0)<br />
Y = Vector(0, 1, 0)<br />
Z = Vector(0, 0, 1)<br />
<br />
#Create a Transformation t = |x, y, z| . |X, Y, Z| ^ -1<br />
mfinal = array([array(X), array(Y), array(Z)])<br />
morig = array([array(x), array(y), array(z)])<br />
rotmatrix = matrixmultiply(morig, transpose(mfinal))<br />
tTotal = Transformation.Rotation(Tensor(rotmatrix))<br />
<br />
#Transform the coordinates and find the min, max dimensions<br />
coordArray = array([array(tTotal(Vector(c))) for c in coords])<br />
minDimensions = [max(coordArray[:,i]) - min(coordArray[:,i]) for i in range(3)]<br />
<br />
#Now, compose the inverse rotation used to move the bounding box to the right place<br />
tForward = Transformation.Rotation(Tensor(matrixmultiply(mfinal, transpose(morig))))<br />
<br />
return minDimensions, tForward<br />
</source><br />
<br />
[[Category:Script_Library|Bounding Box]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Translate_And_Measure&diff=9058Translate And Measure2005-10-08T12:06:50Z<p>Gilleain: removed the '3D' after all '=3D' - not sure why they were there!</p>
<hr />
<div>To use, you would call it like :<br />
<source lang="python"><br />
print translateAndMeasure("molA", "molB", [1,0,0], 4)<br />
</source><br />
which would print "overlap" if any of the atoms in molA or molB were within<br />
4 Angstrom after translating by 1 along X.<br />
<br />
Of course, this could be improved to report exactly ''which'' atoms were<br />
overlapping, or to make distance objects (using cmd.distance) to show them.<br />
<br />
<source lang="python"><br />
def translateAndMeasure(selection, other, translationVector, cutoff):<br />
cmd.translate(translationVector, selection)<br />
return checkDistances(selection, other, cutoff)<br />
<br />
def checkDistances(moleculeA, moleculeB, cutoff):<br />
ids_A = getIds(moleculeA)<br />
ids_B = getIds(moleculeB)<br />
for idA in ids_A:<br />
for idB in idsB:<br />
d = distance(moleculeA, idA, moleculeB, idB)<br />
if d > cutoff: return "overlap"<br />
return "no overlap"<br />
<br />
def distance(a, idA, b, idB):<br />
atomA = "%s and id %s" % (a, idA)<br />
atomB = "%s and id %s" % (b, idB)<br />
return cmd.get_distance(atomA, atomB)<br />
<br />
def getIds(selection):<br />
my_dict = { 'my_list' : [] }<br />
cmd.iterate(selection, "my_list.append(ID)", space=my_dict)<br />
return my_dict['my_list']<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Delete&diff=7695Delete2005-08-10T18:25:53Z<p>Gilleain: copied the format of [create] to create a delete. delete if you like.</p>
<hr />
<div>===DESCRIPTION===<br />
'''delete''' removes an object or a selection. <br />
<br />
===USAGE===<br />
<source lang="python"><br />
delete name <br />
delete all # deletes all objects<br />
</source><br />
<br />
name = name of object or selection <br />
<br />
===PYMOL API===<br />
<source lang="python"><br />
cmd.delete(string name = object-or-selection-name )<br />
</source><br />
<br />
===SEE ALSO===<br />
[[Cmd remove|remove]]<br />
<br />
[[Category:Commands|delete]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Split_states&diff=8947Split states2005-08-03T11:31:00Z<p>Gilleain: </p>
<hr />
<div>=Overview=<br />
'''Split_States''' splits and orients multiple models and multimers from the biological unit file.<br />
<br />
==Using==<br />
To use '''split_states''' simply<br />
Load your molecule<br />
<source lang="python"><br />
load fileName.pdb1, name<br />
split_states name<br />
delete name<br />
</source><br />
<br />
==Example==<br />
'''1VLS''': A dimer.<br />
<source lang="python"><br />
load 1vls.pdb1, 1vls<br />
split_states 1vls<br />
dele 1vls<br />
</source><br />
[[Image:1vls1.png|thumb|left|1VLS as a monomer. This is the state of 1VLS when I load the molecule (and select cartoon representation).]]<br />
[[Image:1vls1_dimer.png|left|thumb|1VLS as a dimer using the split_states command.]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=Ellipsoid&diff=13616Ellipsoid2005-07-20T02:28:35Z<p>Gilleain: </p>
<hr />
<div>This script provides methods that create [[cgo]]s as triangles. It uses code that is ported from [http://www.gamedev.net/reference/articles/article1172.asp this c++ code] and seems to be correct! <br />
<br />
Here is the script. The last four lines show this in use, by making an ellipse and a toroid and loading them into pymol. This is done most easily by something like "cmd.load_cgo(makeEllipsoid(1, 1, 1, 2, 3, 4), 'ellipsoid')" which makes an ellipsoid at x, y, z = 1, 1, 1 and dimensions 2, 3, 4 and called 'ellipsoid'.<br />
<br />
<source lang="python"><br />
from pymol.cgo import BEGIN, COLOR, TRIANGLES, VERTEX, NORMAL, END<br />
from pymol import cmd<br />
<br />
def signOfFloat(f):<br />
if f < 0: return -1<br />
if f > 0: return 1<br />
return 0<br />
<br />
def sqC(v, n):<br />
return signOfFloat(math.cos(v)) * math.pow(math.fabs(math.cos(v)), n)<br />
<br />
def sqCT(v, n, alpha):<br />
return alpha + sqC(v, n)<br />
<br />
def sqS(v, n):<br />
return signOfFloat(math.sin(v)) * math.pow(math.fabs(math.sin(v)), n)<br />
<br />
def sqEllipsoid(x, y, z, a1, a2, a3, u, v, n, e):<br />
x = a1 * sqC(u, n) * sqC(v, e) + x<br />
y = a2 * sqC(u, n) * sqS(v, e) + y<br />
z = a3 * sqS(u, n) + z<br />
nx = sqC(u, 2 - n) * sqC(v, 2 - e) / a1<br />
ny = sqC(u, 2 - n) * sqS(v, 2 - e) / a2<br />
nz = sqS(u, 2 - n) / a3<br />
return x, y, z, nx, ny, nz<br />
<br />
def sqToroid(x, y, z, a1, a2, a3, u, v, n, e, alpha):<br />
a1prime = 1.0 / (a1 + alpha)<br />
a2prime = 1.0 / (a2 + alpha)<br />
a3prime = 1.0 / (a3 + alpha)<br />
x = a1prime * sqCT(u, e, alpha) * sqC(v, n)<br />
y = a2prime * sqCT(u, e, alpha) * sqS(v, n)<br />
z = a3prime * sqS(u, e)<br />
nx = sqC(u, 2 - e) * sqC(v, 2 - n) / a1prime<br />
ny = sqC(u, 2 - e) * sqS(v, 2 - n) / a2prime<br />
nz = sqS(u, 2 - e) / a3prime<br />
return x, y, z, nx, ny, nz<br />
<br />
def makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, n, e, u1, u2, v1, v2, u_segs, v_segs, color=[0.5, 0.5, 0.5]):<br />
<br />
r, g, b = color<br />
<br />
# Calculate delta variables */<br />
dU = (u2 - u1) / u_segs<br />
dV = (v2 - v1) / v_segs<br />
<br />
o = [ BEGIN, TRIANGLES ]<br />
<br />
U = u1<br />
for Y in range(0, u_segs):<br />
# Initialize variables for loop */<br />
V = v1<br />
for X in range(0, v_segs):<br />
# VERTEX #1 */<br />
x1, y1, z1, n1x, n1y, n1z = sqEllipsoid(x, y, z, a1, a2, a3, U, V, n, e)<br />
x2, y2, z2, n2x, n2y, n2z = sqEllipsoid(x, y, z, a1, a2, a3, U + dU, V, n, e)<br />
x3, y3, z3, n3x, n3y, n3z = sqEllipsoid(x, y, z, a1, a2, a3, U + dU, V + dV, n, e)<br />
x4, y4, z4, n4x, n4y, n4z = sqEllipsoid(x, y, z, a1, a2, a3, U, V + dV, n, e)<br />
<br />
o.extend([COLOR, r, g, b, NORMAL, n1x, n1y, n1z, VERTEX, x1, y1, z1])<br />
o.extend([COLOR, r, g, b, NORMAL, n2x, n2y, n2z, VERTEX, x2, y2, z2])<br />
o.extend([COLOR, r, g, b, NORMAL, n4x, n4y, n4z, VERTEX, x4, y4, z4])<br />
o.extend([COLOR, r, g, b, NORMAL, n2x, n2y, n2z, VERTEX, x2, y2, z2])<br />
o.extend([COLOR, r, g, b, NORMAL, n3x, n3y, n3z, VERTEX, x3, y3, z3])<br />
o.extend([COLOR, r, g, b, NORMAL, n4x, n4y, n4z, VERTEX, x4, y4, z4])<br />
<br />
# Update variables for next loop */<br />
V += dV<br />
# Update variables for next loop */<br />
U += dU<br />
o.append(END)<br />
return o<br />
<br />
def makeSuperQuadricToroid(x, y, z, a1, a2, a3, alpha, n, e, u1, u2, v1, v2, u_segs, v_segs, color=[0.5, 0.5, 0.5]):<br />
<br />
r, g, b = color<br />
<br />
# Calculate delta variables */<br />
dU = (u2 - u1) / u_segs<br />
dV = (v2 - v1) / v_segs<br />
<br />
o = [ BEGIN, TRIANGLES ]<br />
<br />
U = u1<br />
for Y in range(0, u_segs):<br />
# Initialize variables for loop */<br />
V = v1<br />
for X in range(0, v_segs):<br />
# VERTEX #1 */<br />
x1, y1, z1, n1x, n1y, n1z = sqToroid(x, y, z, a1, a2, a3, U, V, n, e, alpha)<br />
x2, y2, z2, n2x, n2y, n2z = sqToroid(x, y, z, a1, a2, a3, U + dU, V, n, e, alpha)<br />
x3, y3, z3, n3x, n3y, n3z = sqToroid(x, y, z, a1, a2, a3, U + dU, V + dV, n, e, alpha)<br />
x4, y4, z4, n4x, n4y, n4z = sqToroid(x, y, z, a1, a2, a3, U, V + dV, n, e, alpha)<br />
<br />
o.extend([COLOR, r, g, b, NORMAL, n1x, n1y, n1z, VERTEX, x1, y1, z1])<br />
o.extend([COLOR, r, g, b, NORMAL, n2x, n2y, n2z, VERTEX, x2, y2, z2])<br />
o.extend([COLOR, r, g, b, NORMAL, n4x, n4y, n4z, VERTEX, x4, y4, z4])<br />
o.extend([COLOR, r, g, b, NORMAL, n2x, n2y, n2z, VERTEX, x2, y2, z2])<br />
o.extend([COLOR, r, g, b, NORMAL, n3x, n3y, n3z, VERTEX, x3, y3, z3])<br />
o.extend([COLOR, r, g, b, NORMAL, n4x, n4y, n4z, VERTEX, x4, y4, z4])<br />
<br />
# Update variables for next loop */<br />
V += dV<br />
# Update variables for next loop */<br />
U += dU<br />
o.append(END)<br />
return o<br />
<br />
def makeEllipsoid(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 1.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
def makeCylinder(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 0.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
def makeSpindle(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 2.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
def makeDoublePyramid(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 2.0, 2.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
def makePillow(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 1.0, 0.0, -math.pi, math.pi, -math.pi, math.pi, 10, 10)<br />
<br />
def makeRoundCube(x, y, z, a1, a2, a3):<br />
return makeSuperQuadricEllipsoid(x, y, z, a1, a2, a3, 0.2, 0.2, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
def makeToroid(x, y, z, a1, a2, a3, alpha):<br />
return makeSuperQuadricToroid(x, y, z, a1, a2, a3, alpha, 1.0, 1.0, -math.pi, math.pi, -math.pi, math.pi, 10, 10)<br />
<br />
x, y, z, rx, ry, rz = 1, 1, 1, 1, 2, 3<br />
cmd.load_cgo(makeEllipsoid(x, y, z, rx, ry, rz), 'ellipsoid-cgo')<br />
x, y, z, rx, ry, rz = 1, 1, 1, 8, 2, 2<br />
cmd.load_cgo(makeToroid(x, y, z, rx, ry, rz, 3), 'toroid-cgo')<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Ellipsoid&diff=13615Ellipsoid2005-07-11T22:03:07Z<p>Gilleain: </p>
<hr />
<div>This script provides a class called "SimpleEllipsoid" that can be created and [[load]]ed into pymol as a [[callback object]]. It uses code that is ported from [http://www.gamedev.net/reference/articles/article1172.asp this c++ code] and seems to be correct! In theory, this could be extended to make toroidal objects, as well as cylinders, spheres, and 'pillows'. Probably not very useful, though.<br />
<br />
Here is the script. The last four lines show this in use, by making two ellipses and loading them into pymol.<br />
<br />
<source lang="python"><br />
from pymol.opengl.gl import *<br />
from pymol.callback import Callback<br />
from pymol import cmd<br />
<br />
def signOfFloat(f):<br />
if f < 0: return -1<br />
if f > 0: return 1<br />
return 0<br />
<br />
def sqC(v, n):<br />
return signOfFloat(math.cos(v)) * math.pow(math.fabs(math.cos(v)), n)<br />
<br />
def sqCT(v, n, alpha):<br />
return alpha + sqC(v, n)<br />
<br />
def sqS(v, n):<br />
return signOfFloat(math.sin(v)) * math.pow(math.fabs(math.sin(v)), n)<br />
<br />
def sqEllipsoid(a1, a2, a3, u, v, n, e):<br />
x = a1 * sqC(u, n) * sqC(v, e)<br />
y = a2 * sqC(u, n) * sqS(v, e)<br />
z = a3 * sqS(u, n)<br />
nx = sqC(u, 2 - n) * sqC(v, 2 - e) / a1<br />
ny = sqC(u, 2 - n) * sqS(v, 2 - e) / a2<br />
nz = sqS(u, 2 - n) / a3<br />
return x, y, z, nx, ny, nz<br />
<br />
def sqToroid(a1, a2, a3, u, v, n, e, alpha):<br />
a1prime = 1 / (a1 + alpha)<br />
a2prime = 1 / (a2 + alpha)<br />
a3prime = 1 / (a3 + alpha)<br />
x = a1prime * sqCT(u, e, alpha) * sqC(v, n)<br />
y = a2prime * sqCT(u, e, alpha) * sqS(v, n)<br />
z = a3prime * sqS(u, e)<br />
nx = sqC(u, 2 - e) * sqC(v, 2 - n) / a1prime<br />
ny = sqC(u, 2 - e) * sqS(v, 2 - n) / a2prime<br />
nz = sqS(u, 2 - e) / a3prime<br />
return x, y, z, nx, ny, nz<br />
<br />
class SuperQuadricEllipsoid(Callback):<br />
<br />
def __init__(self, x, y, z, a1, a2, a3, n, e, u1, u2, v1, v2, u_segs, v_segs, alpha=0):<br />
<br />
# Calculate delta variables<br />
dU = (u2 - u1) / u_segs<br />
dV = (v2 - v1) / v_segs<br />
<br />
# Setup storage for data<br />
self.points = []<br />
self.normals = []<br />
<br />
# Store the position<br />
self.x, self.y, self.z = x, y, z<br />
<br />
# Initialize variables for loop<br />
U = u1<br />
for Y in range(0, u_segs):<br />
# Initialize variables for loop<br />
V = v1<br />
for X in range(0, v_segs):<br />
# VERTEX #1 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #2 */ <br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #3 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #4 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# Update variables for next loop */<br />
V += dV<br />
# Update variables for next loop */<br />
U += dU<br />
<br />
def get_extent(self):<br />
return [[-10.0, -10.0, -10.0], [10.0, 10.0, 10.0]]<br />
<br />
def __call__(self):<br />
glPushMatrix()<br />
glTranslatef(self.x, self.y, self.z)<br />
glBegin(GL_QUADS)<br />
glColor3f(1.0, 1.0, 0.0)<br />
for i in range(0, u_segs * v_segs * 4):<br />
x, y, z = self.points[i]<br />
nx, ny, nz = self.normals[i]<br />
glNormal3f(nx, ny, nz)<br />
glVertex3f(x, y, z)<br />
glEnd()<br />
glPopMatrix()<br />
<br />
class SimpleEllipsoid(SuperQuadricEllipsoid):<br />
<br />
def __init__(self, x, y, z, a1, a2, a3):<br />
SuperQuadricEllipsoid.__init__(self, x, y, z, a1, a2, a3, 1.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
x, y, z = 1, 1, 1<br />
rx, ry, rz = 1, 2, 3<br />
cmd.load_callback(SimpleEllipsoid(x, y, z, rx, ry, rz), 'ellipsoid1')<br />
x, y, z = 2, 2, 2<br />
rx, ry, rz = 2, 1, 3<br />
cmd.load_callback(SimpleEllipsoid(x, y, z, rx, ry, rz), 'ellipsoid2')<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Ellipsoid&diff=13614Ellipsoid2005-07-11T22:02:26Z<p>Gilleain: </p>
<hr />
<div>This script provides a class called "SimpleEllipsoid" that can be created and [[load]]ed into pymol as a [[callback object]]. It uses code that is ported from [http://www.gamedev.net/reference/articles/article1172.asp this c++ code] and seems to be correct! In theory, this could be extended to make toroidal objects, as well as cylinders, spheres, and 'pillows'. Probably not very useful, though.<br />
<br />
Here is the script. The last four lines show this in use, by making two ellipses and loading them into pymol.<br />
<br />
<source lang="python"><br />
from pymol.opengl.gl import *<br />
from pymol.callback import Callback<br />
from pymol import cmd<br />
<br />
def signOfFloat(f):<br />
if f < 0: return -1<br />
if f > 0: return 1<br />
return 0<br />
<br />
def sqC(v, n):<br />
return signOfFloat(math.cos(v)) * math.pow(math.fabs(math.cos(v)), n)<br />
<br />
def sqCT(v, n, alpha):<br />
return alpha + sqC(v, n)<br />
<br />
def sqS(v, n):<br />
return signOfFloat(math.sin(v)) * math.pow(math.fabs(math.sin(v)), n)<br />
<br />
def sqEllipsoid(a1, a2, a3, u, v, n, e):<br />
x = a1 * sqC(u, n) * sqC(v, e)<br />
y = a2 * sqC(u, n) * sqS(v, e)<br />
z = a3 * sqS(u, n)<br />
nx = sqC(u, 2 - n) * sqC(v, 2 - e) / a1<br />
ny = sqC(u, 2 - n) * sqS(v, 2 - e) / a2<br />
nz = sqS(u, 2 - n) / a3<br />
return x, y, z, nx, ny, nz<br />
<br />
def sqToroid(a1, a2, a3, u, v, n, e, alpha):<br />
a1prime = 1 / (a1 + alpha)<br />
a2prime = 1 / (a2 + alpha)<br />
a3prime = 1 / (a3 + alpha)<br />
x = a1prime * sqCT(u, e, alpha) * sqC(v, n)<br />
y = a2prime * sqCT(u, e, alpha) * sqS(v, n)<br />
z = a3prime * sqS(u, e)<br />
nx = sqC(u, 2 - e) * sqC(v, 2 - n) / a1prime<br />
ny = sqC(u, 2 - e) * sqS(v, 2 - n) / a2prime<br />
nz = sqS(u, 2 - e) / a3prime<br />
return x, y, z, nx, ny, nz<br />
<br />
class SuperQuadricEllipsoid(Callback):<br />
<br />
def __init__(self, x, y, z, a1, a2, a3, n, e, u1, u2, v1, v2, u_segs, v_segs, alpha=0):<br />
<br />
# Calculate delta variables<br />
dU = (u2 - u1) / u_segs<br />
dV = (v2 - v1) / v_segs<br />
<br />
# Setup storage for data<br />
self.points = []<br />
self.normals = []<br />
<br />
# Store the position<br />
self.x, self.y, self.z = x, y, z<br />
<br />
# Initialize variables for loop<br />
U = u1<br />
for Y in range(0, u_segs):<br />
# Initialize variables for loop<br />
V = v1<br />
for X in range(0, v_segs):<br />
# VERTEX #1 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #2 */ <br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #3 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #4 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# Update variables for next loop */<br />
V += dV<br />
# Update variables for next loop */<br />
U += dU<br />
<br />
def get_extent(self):<br />
return [[-10.0, -10.0, -10.0], [10.0, 10.0, 10.0]]<br />
<br />
def __call__(self):<br />
glPushMatrix()<br />
glTranslatef(self.x, self.y, self.z)<br />
glBegin(GL_QUADS)<br />
glColor3f(1.0, 1.0, 0.0)<br />
for i in range(0, u_segs * v_segs * 4):<br />
x, y, z = self.points[i]<br />
nx, ny, nz = self.normals[i]<br />
glNormal3f(nx, ny, nz)<br />
glVertex3f(x, y, z)<br />
glEnd()<br />
glPopMatrix()<br />
<br />
class SimpleEllipsoid(SuperQuadricEllipsoid):<br />
<br />
def __init__(self, x, y, z, a1, a2, a3):<br />
SuperQuadricEllipsoid.__init__(self, x, y, z, a1, a2, a3, 1.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
x, y, z = 1, 1, 1<br />
rx, ry, rz = 1, 2, 3<br />
cmd.load_callback(SimpleEllipsoid(rx, ry, rz), 'ellipsoid1')<br />
x, y, z = 2, 2, 2<br />
rx, ry, rz = 2, 1, 3<br />
cmd.load_callback(SimpleEllipsoid(rx, ry, rz), 'ellipsoid2')<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Ellipsoid&diff=13613Ellipsoid2005-07-11T21:27:42Z<p>Gilleain: </p>
<hr />
<div>This script provides a class called "SimpleEllipsoid" that can be created and [[load]]ed into pymol as a [[callback object]]. It uses code that is ported from [http://www.gamedev.net/reference/articles/article1172.asp this c++ code] and seems to be correct! In theory, this could be extended to make toroidal objects, as well as cylinders, spheres, and 'pillows'. Probably not very useful, though.<br />
<br />
Here is the script. The last four lines show this in use, by making two ellipses and loading them into pymol.<br />
<br />
<source lang="python"><br />
from pymol.opengl.gl import *<br />
from pymol.callback import Callback<br />
from pymol import cmd<br />
<br />
def signOfFloat(f):<br />
if f < 0: return -1<br />
if f > 0: return 1<br />
return 0<br />
<br />
def sqC(v, n):<br />
return signOfFloat(math.cos(v)) * math.pow(math.fabs(math.cos(v)), n)<br />
<br />
def sqCT(v, n, alpha):<br />
return alpha + sqC(v, n)<br />
<br />
def sqS(v, n):<br />
return signOfFloat(math.sin(v)) * math.pow(math.fabs(math.sin(v)), n)<br />
<br />
def sqEllipsoid(a1, a2, a3, u, v, n, e):<br />
x = a1 * sqC(u, n) * sqC(v, e)<br />
y = a2 * sqC(u, n) * sqS(v, e)<br />
z = a3 * sqS(u, n)<br />
nx = sqC(u, 2 - n) * sqC(v, 2 - e) / a1<br />
ny = sqC(u, 2 - n) * sqS(v, 2 - e) / a2<br />
nz = sqS(u, 2 - n) / a3<br />
return x, y, z, nx, ny, nz<br />
<br />
def sqToroid(a1, a2, a3, u, v, n, e, alpha):<br />
a1prime = 1 / (a1 + alpha)<br />
a2prime = 1 / (a2 + alpha)<br />
a3prime = 1 / (a3 + alpha)<br />
x = a1prime * sqCT(u, e, alpha) * sqC(v, n)<br />
y = a2prime * sqCT(u, e, alpha) * sqS(v, n)<br />
z = a3prime * sqS(u, e)<br />
nx = sqC(u, 2 - e) * sqC(v, 2 - n) / a1prime<br />
ny = sqC(u, 2 - e) * sqS(v, 2 - n) / a2prime<br />
nz = sqS(u, 2 - e) / a3prime<br />
return x, y, z, nx, ny, nz<br />
<br />
class SuperQuadricEllipsoid(Callback):<br />
<br />
def __init__(self, a1, a2, a3, n, e, u1, u2, v1, v2, u_segs, v_segs, alpha=0):<br />
<br />
# Calculate delta variables */<br />
dU = (u2 - u1) / u_segs<br />
dV = (v2 - v1) / v_segs<br />
<br />
# Initialize variables for loop */<br />
U = u1<br />
self.points = []<br />
self.normals = []<br />
for Y in range(0, u_segs):<br />
# Initialize variables for loop */<br />
V = v1<br />
for X in range(0, v_segs):<br />
# VERTEX #1 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #2 */ <br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #3 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U + dU, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# VERTEX #4 */<br />
x, y, z, nx, ny, nz = sqEllipsoid(a1, a2, a3, U, V + dV, n, e)<br />
self.points.append((x, y, z))<br />
self.normals.append((nx, ny, nz))<br />
<br />
# Update variables for next loop */<br />
V += dV<br />
# Update variables for next loop */<br />
U += dU<br />
<br />
def get_extent(self):<br />
return [[-10.0, -10.0, -10.0], [10.0, 10.0, 10.0]]<br />
<br />
def __call__(self):<br />
glBegin(GL_QUADS)<br />
glColor3f(1.0, 1.0, 0.0)<br />
for i in range(0, u_segs * v_segs * 4):<br />
x, y, z = self.points[i]<br />
nx, ny, nz = self.normals[i]<br />
glNormal3f(nx, ny, nz)<br />
glVertex3f(x, y, z)<br />
glEnd()<br />
<br />
class SimpleEllipsoid(SuperQuadricEllipsoid):<br />
<br />
def __init__(self, a1, a2, a3):<br />
SuperQuadricEllipsoid.__init__(self, a1, a2, a3, 1.0, 1.0, -math.pi / 2, math.pi / 2, -math.pi, math.pi, 10, 10)<br />
<br />
rx, ry, rz = 1, 2, 3<br />
cmd.load_callback(SimpleEllipsoid(rx, ry, rz), 'ellipsoid1')<br />
rx, ry, rz = 2, 1, 3<br />
cmd.load_callback(SimpleEllipsoid(rx, ry, rz), 'ellipsoid2')<br />
</source></div>Gilleainhttps://wiki.pymol.org/index.php?title=Category:Script_Library&diff=3868Category:Script Library2005-07-11T21:16:26Z<p>Gilleain: </p>
<hr />
<div>* [[Stereo_Ray]] -- This script will create two resolution specific ray traced images rotated appropriately for inclusion into a single file to represent a stereo view of the desired macromolecule.<br />
<br />
* [[Translate_And_Measure]] -- prints '''overlap''' if any of the atoms in molA or molB were within 4 Angstrom after translating by 1 along X<br />
<br />
* [[Show aromatics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for aromatic residues displayed as green "sticks". Usage: Save this as "show_aromatics.pml", load your protein in PyMOL, and run the script (select "Run" from the "File" menu). (PyMOL script; TStout)<br />
<br />
* [[Show hydrophobics]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophobic residues displayed as orange "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show charged]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for charged residues displayed as red (negative) or blue (posititve) "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Show hydrophilic]] -- This script will display a backbone "worm" for your protein, with all of the sidechains for hydrophilic residues displayed as green "sticks". Usage: Same as "show aromatics". (PyMOL script; TStout)<br />
<br />
* [[Perp Maker]] -- Creates a perpendicular plane through the center of your protein with respect to the camera's current position. (If you translate the protein towards the camera a bit, you get a nice surface, sometimes.) A stupid little script I wrote in response to a request a few months ago (and it doesn't even conform to the request!) Load a protein, run the script (read the documentation in the script). (Jason Vertrees/[[User:Tree|Tree]])<br />
<br />
* [[Axes]] -- Creates a 3D-CGO object that shows the three coordinate axes.<br />
<br />
* [[CGO Text]] -- Creates a 3D-CGO text object.<br />
<br />
* [[List Selection]] -- Prints a list of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Colors]] -- Lists the color of all residues in a selection (both Python and .pml).<br />
<br />
* [[List Secondary Structures]] -- Secondary structures (both predefined and those calculated with the 'dss' command) can be exported as a long string ('HHHHLLLLSSS').<br />
<br />
* [[Split Movement]] -- Moves two parts of one object into different directions.<br />
<br />
* [[Selection Exists]] -- Python method that returns true if a selection of a given name exists.<br />
<br />
* [[Get Coordinates I]] -- Retrieves atom coordinates as Python objects.<br />
<br />
* [[Get Coordinates II]] -- Retrieves atom coordinates as Python array (list object).<br />
<br />
* [[grepset]] -- List all settings matching a given keyword. - ''by EHP''<br />
<br />
* [[disconnect]] -- unbond a single atom from its neighbors. - ''by EHP''<br />
<br />
* [[mouse_modes]] -- customize the default mouse bindings for Viewing or Editing modes. - ''by EHP''<br />
<br />
* [[Measure Distance]] -- Measures the distance between two atoms (Python script).<br />
<br />
* [[Read PDB-String]] -- Parses a string in PDB format to a PyMOL object.<br />
<br />
* [[Color Objects]] -- Colors all objects differently (Python script).<br />
<br />
* [[Key Wait]] -- Process key events in a Python script.<br />
<br />
* [[Bounding Box]] -- Create a bounding box around a selection (Python script; requires numarray and Scientific; gilleain)<br />
<br />
* [[Ellipsoid]] -- Create callback object (opengl) ellipsoids. (Python script; gilleain)<br />
<br />
* [[pdbsurvey]] -- Surveys the pdb for recently added structures that are relevant to a user-specified keywords list (in a text file)<br />
<br />
* [[TransformSelectionByCameraView]] -- Transforms the selection by the camera view.<br />
<br />
* [[WFMesh]] -- Imports wavefront object mesh files; Starwars as an example!<br />
<br />
[[Category:Scripting|Script Library]]</div>Gilleainhttps://wiki.pymol.org/index.php?title=User:Gilleain&diff=3026User:Gilleain2005-03-08T19:52:12Z<p>Gilleain: </p>
<hr />
<div>Been using PyMol on OSX for a while now, I do a lot of python programming now so it's great to write scripts for ([http://cobra.mih.unibas.ch/dino/ dino] is also nice, but has a more tcl-like syntax).<br />
<br />
Currently doing a PhD in structural bioinformatics at Glasgow University. I used to work on the [http://www.tops.leeds.ac.uk TOPS] project.</div>Gilleainhttps://wiki.pymol.org/index.php?title=Bounding_Box&diff=6493Bounding Box2005-03-08T19:46:07Z<p>Gilleain: </p>
<hr />
<div><source lang="python"><br />
import math<br />
from pymol import querying<br />
from pymol.cgo import *<br />
from pymol import cmd<br />
<br />
#NOTE!! : These packages (numarray, Scientific) must be present in pymol's <br />
#'$PYMOLDIR/py23/lib/python2.3/site-packages/' directory!!<br />
from numarray import *<br />
from numarray.ma import average<br />
from numarray import linear_algebra as la<br />
<br />
from Scientific.Geometry import Vector, Tensor, Transformation<br />
<br />
def boundingBox(selectionName, colourRGB=[1,1,1]):<br />
"""<br />
The main function to call : <br />
<br />
run "box.py"<br />
boundingBox("peptide")<br />
<br />
Should make a box around "peptide" (assuming it exists!). For a different colour use:<br />
<br />
boundingBox("peptide", colourRGB=[1, 0, 1])<br />
<br />
Or whatever. The box should be a cgo called 'peptide-box' (for this example).<br />
"""<br />
model = querying.get_model(selectionName)<br />
coords = model.get_coord_list()<br />
<br />
#find the least square plane through the coordinates<br />
eigenvalues, eigenvectors, centroid = findPlaneWithEigenVectors(coords)<br />
normal = eigenvectors[eigenvalues.argmin()]<br />
eigenvectors.remove(normal)<br />
<br />
#orient the axes correctly<br />
x, y, normal = orientAxes(eigenvectors[0], eigenvectors[1], normal)<br />
<br />
#determine the dimensions and the structure's orientation wrt the origin<br />
minDimensions, rotation = findMinDimensionsAndRotation(coords, centroid, x, y, normal)<br />
<br />
#'create' the box(IE: make the corners) and 'draw' it (IE: make a cgo)<br />
box = makeBox(minDimensions, rotation, centroid)<br />
drawBox(box, selectionName, colourRGB)<br />
<br />
def findPlaneWithEigenVectors(coords):<br />
centroid = average(coords)<br />
coords -= centroid<br />
B = matrixmultiply(transpose(coords), coords)<br />
eigenvalues, eigenvectors = la.eigenvectors(B)<br />
return eigenvalues, [Vector(e) for e in eigenvectors], Vector(centroid)<br />
<br />
def orientAxes(x, y, z):<br />
XcrossY = x.cross(y)<br />
ZXY = around(math.degrees(z.angle(XcrossY)))<br />
if (ZXY == 180): x, y = y, x<br />
return x, y, z<br />
<br />
def makeBox(dimensions, rotation, centroid):<br />
x, y, z = dimensions<br />
v = [[]] * 8<br />
<br />
#make a cuboid with the lower corner on the origin<br />
v[0] = [0, 0, 0] # [0, 0, 0]<br />
v[1] = [x, 0, 0] # [1, 0, 0]<br />
v[2] = [x, y, 0] # [1, 1, 0]<br />
v[3] = [x, 0, z] # [1, 0, 1]<br />
v[4] = [0, y, 0] # [0, 1, 0]<br />
v[5] = [0, 0, z] # [0, 0, 1]<br />
v[6] = [0, y, z] # [0, 1, 1]<br />
v[7] = [x, y, z] # [1, 1, 1]<br />
<br />
#move to the origin, THEN move to the centroid of the points, then rotate<br />
translationToOrigin = Transformation.Translation(-Vector(x/2, y/2, z/2))<br />
translationToCentroid = Transformation.Translation(centroid)<br />
transform = translationToCentroid * rotation * translationToOrigin<br />
<br />
#use the Transformation to transform the corners of the box<br />
v = [transform(Vector(i)) for i in v]<br />
<br />
bot = [v[0], v[1], v[2], v[4]] # O, x, xy, y<br />
top = [v[7], v[3], v[5], v[6]] # xyz, xz, z, yz<br />
minL = [v[0], v[4], v[6], v[5]] # O, y, yz, z<br />
minR = [v[0], v[5], v[3], v[1]] # O, z, xz, x<br />
maxL = [v[4], v[2], v[7], v[6]] # y, xy, xyz, yz<br />
maxR = [v[3], v[1], v[2], v[7]] # xz, x, xy, xyz<br />
box = [bot, minR, minL, maxR, maxL, top]<br />
<br />
return box<br />
<br />
def drawBox(box, name, colourRGB):<br />
boxObj = []<br />
for side in box:<br />
boxObj.append(BEGIN)<br />
boxObj.append(LINE_STRIP)<br />
boxObj.append(COLOR)<br />
boxObj.extend(colourRGB)<br />
for point in side:<br />
boxObj.append(VERTEX)<br />
boxObj.extend(point)<br />
boxObj.append(END)<br />
<br />
cmd.set('auto_zoom', 0)<br />
cmd.load_cgo(boxObj, "%s-box" % name)<br />
cmd.set('auto_zoom', 1)<br />
<br />
def findMinDimensionsAndRotation(coords, centroid, x, y, z):<br />
O = Vector(0, 0, 0)<br />
X = Vector(1, 0, 0)<br />
Y = Vector(0, 1, 0)<br />
Z = Vector(0, 0, 1)<br />
<br />
#Create a Transformation t = |x, y, z| . |X, Y, Z| ^ -1<br />
mfinal = array([array(X), array(Y), array(Z)])<br />
morig = array([array(x), array(y), array(z)])<br />
rotmatrix = matrixmultiply(morig, transpose(mfinal))<br />
tTotal = Transformation.Rotation(Tensor(rotmatrix))<br />
<br />
#Transform the coordinates and find the min, max dimensions<br />
coordArray = array([array(tTotal(Vector(c))) for c in coords])<br />
minDimensions = [max(coordArray[:,i]) - min(coordArray[:,i]) for i in range(3)]<br />
<br />
#Now, compose the inverse rotation used to move the bounding box to the right place<br />
tForward = Transformation.Rotation(Tensor(matrixmultiply(mfinal, transpose(morig))))<br />
<br />
return minDimensions, tForward<br />
</source></div>Gilleain