Difference between revisions of "Iterate"

From PyMOLWiki
Jump to navigation Jump to search
(geom etc.)
 
(17 intermediate revisions by 6 users not shown)
Line 1: Line 1:
'''iterate''' iterates over an expression with a separate name space for each atom. However, unlike the "alter" command, atomic properties can not be altered. Thus, '''iterate''' is more efficient than '''alter'''.
+
The '''iterate''' command executes a Python expression for all atoms in a selection. The local namespace exposes all atomic identifiers and properties as read-only Python variables. The global namespace by default is the '''pymol''' module namespace, and thus exposes objects like '''cmd''' and '''[[pymol.stored|stored]]'''. The order of iteration is that of the internal atom ordering.
  
= Details =
+
The '''alter''' command is equivalent to '''iterate''', but provides read-write access to the exposed variables. This can for example be used to rename a chain or to assign new b-factors. If changing identifiers which would affect atom ordering, calling [[sort]] is necessary to reorder based on the new identifiers.
Iterate is a powerful tool that can be used to perform operations and aggregations using atomic selections, and store the results in any global object, such as the predefined '''stored''' object (see [[#PYMOL API]] below for usage of local objects).  For example, one could iterate over all of the alpha carbons and record their B Factors, or print out all of the secondary structure classifications of all the residues.
 
  
The '''iterate''' command only has access to certain properties. Those properties are:
+
The '''iterate_state''' command is similar to '''iterate''', but iterates over the coordinates in the given state and selection, and exposes '''x, y, z''' in addition to the atomic identifiers and properties.
*'''name''': the atom name
+
 
*'''resn''': the residue name
+
The '''alter_state''' command is equivalent to '''iterate_state''', but allows modification of '''x, y, z''' (and atom-state level settings in Incentive PyMOL 1.7+).
*'''resi''': the residue identifier (residue number)
+
 
*'''chain''': the chain name
+
== Exposed Variables ==
*'''alt'''
+
 
*'''elem''': the chemical element
+
All commands in the '''iterate'''-family expose the following variables:
*'''q'''
+
 
*'''b''': the B Factor
+
*'''model''' (str): the object name (appearing in the selection panel on the right) (cannot be altered)
*'''segi'''
+
*'''name''' (str): the atom name
*'''type''' (ATOM,HETATM): the atom type
+
*'''resn''' (str): the residue name
*'''formal_charge''': the formal charge of the atom
+
*'''oneletter''' (str): '''resn''' translated to one letter code, like it's displayed in the sequence viewer (cannot be altered, alter '''resn''' instead) (PyMOL 1.8.7+)
*'''partial_charge''': the partial charge of the atom
+
*'''resi''' (str): the residue identifier (residue number) as a string, including optional insertion code
 +
*'''resv''' (int): the residue identifier (residue number) as an integer, excluding insertion code
 +
*'''chain''' (str): the chain name
 +
*'''alt''' (str): alternate location identifier
 +
*'''elem''' (str): the chemical element
 +
*'''q''' (float): occupancy
 +
*'''b''' (float): the B Factor
 +
*'''segi''' (str): segment identifier (columns 73-76 in PDB file)
 +
*'''type''' (str: ATOM,HETATM): the atom type (PDB convention for canonical polymer residues)
 +
*'''formal_charge''' (int): the formal charge of the atom
 +
*'''partial_charge''' (float): the partial charge of the atom
 
*'''numeric_type'''
 
*'''numeric_type'''
*'''text_type '''
+
*'''text_type''' (str): automatic mol2 atom typing (Incentive PyMOL 1.4+)
*'''ID'''
+
*'''stereo''' (str): automatic stereochemical R/S label (Incentive PyMOL 1.4+)
*'''vdw'''
+
*'''ID''' (int): PDB atom id (not guaranteed to be unique)
 +
*'''rank''' (int): atom index from original file import (not guaranteed to be unique)
 +
*'''index''' (int): internal atom index (unique per object, sensitive to [[sort|sorting]] and [[remove|removing]] of atoms, cannot be altered)
 +
*'''vdw''' (float): Van der Waals radius
 +
*'''ss''' (str): secondary structure
 +
*'''color''' (int): color index
 +
*'''reps''' (int): numeric mask of shown representations (PyMOL 1.7.4+)
 +
*'''protons''' (int): (PyMOL 1.7.4+)
 +
*'''p''' (object): property object to access user-defined properties like '''p.abc''' (Incentive PyMOL 1.7+)
 +
*'''s''' (object): settings object to access settings, e.g. '''s.sphere_scale''' (Incentive PyMOL 1.7+, Open-Source PyMOL 1.8.1+)
 +
*'''label''' (str): see [[label]]
 +
*'''geom''' (int): 1=single, 2=linear, 3=planar, 4=tetrahedral (see [[set_geometry]])
 +
*'''valence''' (int): expected number of bonds (?)
 +
*'''flags''' (int): bitmask, see [[flag]]
 +
*'''cartoon''' (int): see [[cartoon]]
 +
 
 +
The '''iterate_state''' and '''alter_state''' commands in addition expose:
 +
 
 +
*'''x''' (float): x-coordinate
 +
*'''y''' (float): y-coordinate
 +
*'''z''' (float): z-coordinate
 +
*'''state''' (int): (PyMOL 1.7.0+)
  
All strings in the expression must be explicitly quoted.  This operation typically takes a second per thousand atoms.
+
== Usage ==
  
===Note about Atom Coordinates===
+
iterate (selection), expression
  
The coordinates of the atom are not accessible via '''iterate'''. To inspect the coordinates of the atoms, see [[Iterate_State]].
+
iterate_state state, (selection), expression
  
===USAGE===
+
alter (selection), expression
iterate (selection),expression
+
 
 +
alter_state state, (selection), expression
 +
 
 +
=== Arguments ===
 +
 
 +
* '''state''' = int: object state, -1 for current state, 0 for all states
 +
* '''selection''' = str: atom selection
 +
* '''expression''' = str: expression in Python language
 +
 
 +
== Examples ==
 +
 
 +
=== Example: Print b-factors ===
 +
 
 +
The following prints the atom names ('''name''' variable) and b-factors ('''b''' variable) for residue #1.
  
===EXAMPLES===
 
====Example====
 
*The following example calculates the net charge on an object.
 
 
<source lang="python">
 
<source lang="python">
# create the global variable between Python and PyMOL
+
iterate (resi 1), print(name + " %.2f" % b)
stored.net_charge = 0
 
# sum up the stored charges of all the atoms
 
iterate (all),stored.net_charge = stored.net_charge + partial_charge
 
 
</source>
 
</source>
  
====Example====
+
=== Example: Get b-factor list ===
*The following example fills an array, '''stored.names''' with the names of all the residues.
+
 
 +
The following example fills a list, '''[[pymol.stored|stored]].bfactors''' with the f-factors ('''b''' variable) from residue #1.
 +
 
 
<source lang="python">
 
<source lang="python">
# create the global variable between Python and PyMOL
+
stored.bfactors = []
stored.names = []
+
iterate (resi 1), stored.bfactors.append(b)
# get all of the names
+
print(stored.bfactors)
iterate (all),stored.names.append(name)
 
 
</source>
 
</source>
  
====Example====
+
=== Example: Get coordinates ===
*The following prints the b-factors for all atoms around residue #1.
+
 
 
<source lang="python">
 
<source lang="python">
iterate resi 1, print round(b,2)
+
stored.coords = []
 +
iterate_state 1, (all), stored.coords.append([x,y,z])
 
</source>
 
</source>
====Example - b and resi ====
+
 
Just copy and paste this directly into command line
+
=== Example: Modify coordinates ===
 +
 
 +
This example shifts the selection by 10 Angstrom along the model x-axis.
 +
 
 
<source lang="python">
 
<source lang="python">
show_as cartoon ;
+
alter_state 1, (all), x += 10.0
cmd.spectrum("b", "blue_white_red", "n. CA") ;
+
rebuild
m1 = [] ;
 
iterate (all and n. CA),m1.append((b,resi)) ;
 
m2 = m1 ;
 
zero = [] ;
 
[zero.append(i) for i,val in enumerate(m1) if val[0]==0] ;
 
m2 = [i for j,i in enumerate(m1) if j not in zero] ;
 
bmax,resimax =  max(m2, key=lambda p: p[0]) ;
 
bmin,resimin = min(m2, key=lambda p: p[0]) ;
 
cmd.ramp_new("My b", "* n. CA", range=[0, bmin, bmax], color="[blue, white, red ]") ;
 
for b,resi in m2: cmd.label("resi %s and n. CA"%resi, "b=%3.2f"%b)
 
 
</source>
 
</source>
  
====Example====
+
=== Example: Rename chain ===
*The following example shows a common task in PyMOL, changing the B-factor column to display some other property. Let's assume you have a file with a list of numbers, one per line, for each alpha carbon in the protein.  Furthermore, assume you want to map these values to the alpha carbons in the protein.
+
 
 +
This renames chain '''A''' to '''C'''. Note the difference between the selection syntax (first argument) and the Python syntax with the quoted string (second argument). The [[sort]] call is necessary if let's say there is also a chain B, and you expect chain B to appear before chain C (formerly A) in the sequence viewer.
 +
 
 
<source lang="python">
 
<source lang="python">
# set ALL b-factors to 0.
+
alter chain A, chain="C"
alter protName, b=0
+
sort
 +
</source>
  
# read the new bfactors from disk
+
=== Example: Sequence numbering offset ===
f = open('fileName','r').readlines()
 
  
# set the alpha carbon bfactors.
+
Assume the residue numbering in a PDB file starts at 100, then the following updates the residue numbers to start at 1.
alter protName and n. CA, b=f.pop(0)
 
  
# Spectrum color bfactors by alpha carbons.
+
<source lang="python">
spectrum b, selection=(protName and n. CA)
+
alter (chain A), resv -= 99
 +
sort
 
</source>
 
</source>
  
====Example b -values====
+
=== Example: Net Charge ===
 +
 
 +
The following example calculates the net charge of an object.
 +
 
 
<source lang="python">
 
<source lang="python">
m1 = []
+
stored.net_charge = 0
iterate (all and n. CA),m1.append((b,resi))
+
iterate (all), stored.net_charge += partial_charge
m2 = m1
+
print('Net charge: ' + str(stored.net_charge))
zero = []
+
</source>
[zero.append(i) for i,val in enumerate(m1) if val[0]==0]
+
 
m2 = [i for j,i in enumerate(m1) if j not in zero]
+
=== Example: Color transfer ===
 +
 
 +
Copy (transfer) the color from one object to another
  
bmax,resimax = max(m2, key=lambda p: p[0])
+
<source lang="python">
bmin,resimin = min(m2, key=lambda p: p[0])
+
stored.colors = {}
print bmax,resimax,bmin,resimin
+
iterate obj1, stored.colors[chain,resi,name] = color
 +
alter obj2, color = stored.colors.get((chain,resi,name), color)
 +
recolor
 
</source>
 
</source>
  
=== PYMOL API ===
+
== PYMOL API ==
  
 
<source lang="python">
 
<source lang="python">
cmd.iterate(string selection, string expression, int quiet=1, dict space=None)
+
cmd.iterate(str selection, str expression, int quiet=1, dict space=None)
 +
 
 +
cmd.iterate_state(int state, str selection, str expression, int quiet=1, dict space=None)
 +
 
 +
cmd.alter(str selection, str expression, int quiet=1, dict space=None)
 +
 
 +
cmd.alter_state(int state, str selection, str expression, int quiet=1, dict space=None)
 
</source>
 
</source>
  
When calling iterate, iterate_state, alter or alter_state from a python script, you can use the 'space' argument to pass local objects into the expression namespace.
+
=== Arguments ===
  
The second example from above but without the global pymol.stored variable:
+
* '''state''' = int: state-index if positive number or any of these:
 +
** '''state''' = 0: all states
 +
** '''state''' = -1: current state
 +
* '''selection''' = str: atom selection
 +
* '''expression''' = str: expression in valid [http://en.wikipedia.org/wiki/Python_syntax_and_semantics python syntax]
 +
* '''space''' = dict: namespace dictionary {default: pymol namespace}
 +
* '''atomic''' = 0/1: provide atomic properties as variables if 1, or only x/y/z if 0 (in older PyMOL versions, atomic=0 gives some speed improvement) {default: 1}
 +
 
 +
=== "space" argument ===
 +
 
 +
The '''space''' argument can be used to pass local objects into the expression namespace, instead of evaluating the expression in the global '''pymol''' module namespace.
 +
 
 +
The b-factor list example from above but without the global [[pymol.stored]] variable:
  
 
<source lang="python">
 
<source lang="python">
myspace = {'names': []}
+
myspace = {'bfactors': []}
cmd.iterate('(all)', 'names.append(name)', space=myspace)
+
cmd.iterate('(all)', 'bfactors.append(b)', space=myspace)
 
</source>
 
</source>
  
Line 121: Line 180:
 
<source lang="python">
 
<source lang="python">
 
def myfunc(resi,resn,name):
 
def myfunc(resi,resn,name):
     print '%s`%s/%s' % (resn ,resi, name)
+
     print('%s`%s/%s' % (resn ,resi, name))
  
 
myspace = {'myfunc': myfunc}
 
myspace = {'myfunc': myfunc}
Line 127: Line 186:
 
</source>
 
</source>
  
===SEE ALSO===
+
== See Also ==
[[Iterate_State]], [[Alter]], [[Alter_State]], [[Color]], [[Color#Color_by_Spectrum_Example|Coloring with different color sprectrums]].
+
 
 +
* [[sort]]
 +
* [[Get_Model|get_model]]
  
 
[[Category:Commands|Iterate]]
 
[[Category:Commands|Iterate]]

Latest revision as of 13:08, 17 December 2017

The iterate command executes a Python expression for all atoms in a selection. The local namespace exposes all atomic identifiers and properties as read-only Python variables. The global namespace by default is the pymol module namespace, and thus exposes objects like cmd and stored. The order of iteration is that of the internal atom ordering.

The alter command is equivalent to iterate, but provides read-write access to the exposed variables. This can for example be used to rename a chain or to assign new b-factors. If changing identifiers which would affect atom ordering, calling sort is necessary to reorder based on the new identifiers.

The iterate_state command is similar to iterate, but iterates over the coordinates in the given state and selection, and exposes x, y, z in addition to the atomic identifiers and properties.

The alter_state command is equivalent to iterate_state, but allows modification of x, y, z (and atom-state level settings in Incentive PyMOL 1.7+).

Exposed Variables

All commands in the iterate-family expose the following variables:

  • model (str): the object name (appearing in the selection panel on the right) (cannot be altered)
  • name (str): the atom name
  • resn (str): the residue name
  • oneletter (str): resn translated to one letter code, like it's displayed in the sequence viewer (cannot be altered, alter resn instead) (PyMOL 1.8.7+)
  • resi (str): the residue identifier (residue number) as a string, including optional insertion code
  • resv (int): the residue identifier (residue number) as an integer, excluding insertion code
  • chain (str): the chain name
  • alt (str): alternate location identifier
  • elem (str): the chemical element
  • q (float): occupancy
  • b (float): the B Factor
  • segi (str): segment identifier (columns 73-76 in PDB file)
  • type (str: ATOM,HETATM): the atom type (PDB convention for canonical polymer residues)
  • formal_charge (int): the formal charge of the atom
  • partial_charge (float): the partial charge of the atom
  • numeric_type
  • text_type (str): automatic mol2 atom typing (Incentive PyMOL 1.4+)
  • stereo (str): automatic stereochemical R/S label (Incentive PyMOL 1.4+)
  • ID (int): PDB atom id (not guaranteed to be unique)
  • rank (int): atom index from original file import (not guaranteed to be unique)
  • index (int): internal atom index (unique per object, sensitive to sorting and removing of atoms, cannot be altered)
  • vdw (float): Van der Waals radius
  • ss (str): secondary structure
  • color (int): color index
  • reps (int): numeric mask of shown representations (PyMOL 1.7.4+)
  • protons (int): (PyMOL 1.7.4+)
  • p (object): property object to access user-defined properties like p.abc (Incentive PyMOL 1.7+)
  • s (object): settings object to access settings, e.g. s.sphere_scale (Incentive PyMOL 1.7+, Open-Source PyMOL 1.8.1+)
  • label (str): see label
  • geom (int): 1=single, 2=linear, 3=planar, 4=tetrahedral (see set_geometry)
  • valence (int): expected number of bonds (?)
  • flags (int): bitmask, see flag
  • cartoon (int): see cartoon

The iterate_state and alter_state commands in addition expose:

  • x (float): x-coordinate
  • y (float): y-coordinate
  • z (float): z-coordinate
  • state (int): (PyMOL 1.7.0+)

Usage

iterate (selection), expression
iterate_state state, (selection), expression
alter (selection), expression
alter_state state, (selection), expression

Arguments

  • state = int: object state, -1 for current state, 0 for all states
  • selection = str: atom selection
  • expression = str: expression in Python language

Examples

Example: Print b-factors

The following prints the atom names (name variable) and b-factors (b variable) for residue #1.

iterate (resi 1), print(name + " %.2f" % b)

Example: Get b-factor list

The following example fills a list, stored.bfactors with the f-factors (b variable) from residue #1.

stored.bfactors = []
iterate (resi 1), stored.bfactors.append(b)
print(stored.bfactors)

Example: Get coordinates

stored.coords = []
iterate_state 1, (all), stored.coords.append([x,y,z])

Example: Modify coordinates

This example shifts the selection by 10 Angstrom along the model x-axis.

alter_state 1, (all), x += 10.0
rebuild

Example: Rename chain

This renames chain A to C. Note the difference between the selection syntax (first argument) and the Python syntax with the quoted string (second argument). The sort call is necessary if let's say there is also a chain B, and you expect chain B to appear before chain C (formerly A) in the sequence viewer.

alter chain A, chain="C"
sort

Example: Sequence numbering offset

Assume the residue numbering in a PDB file starts at 100, then the following updates the residue numbers to start at 1.

alter (chain A), resv -= 99
sort

Example: Net Charge

The following example calculates the net charge of an object.

stored.net_charge = 0
iterate (all), stored.net_charge += partial_charge
print('Net charge: ' + str(stored.net_charge))

Example: Color transfer

Copy (transfer) the color from one object to another

stored.colors = {}
iterate obj1, stored.colors[chain,resi,name] = color
alter obj2, color = stored.colors.get((chain,resi,name), color)
recolor

PYMOL API

cmd.iterate(str selection, str expression, int quiet=1, dict space=None)

cmd.iterate_state(int state, str selection, str expression, int quiet=1, dict space=None)

cmd.alter(str selection, str expression, int quiet=1, dict space=None)

cmd.alter_state(int state, str selection, str expression, int quiet=1, dict space=None)

Arguments

  • state = int: state-index if positive number or any of these:
    • state = 0: all states
    • state = -1: current state
  • selection = str: atom selection
  • expression = str: expression in valid python syntax
  • space = dict: namespace dictionary {default: pymol namespace}
  • atomic = 0/1: provide atomic properties as variables if 1, or only x/y/z if 0 (in older PyMOL versions, atomic=0 gives some speed improvement) {default: 1}

"space" argument

The space argument can be used to pass local objects into the expression namespace, instead of evaluating the expression in the global pymol module namespace.

The b-factor list example from above but without the global pymol.stored variable:

myspace = {'bfactors': []}
cmd.iterate('(all)', 'bfactors.append(b)', space=myspace)

User defined functions can also be included in the namespace:

def myfunc(resi,resn,name):
    print('%s`%s/%s' % (resn ,resi, name))

myspace = {'myfunc': myfunc}
cmd.iterate('(all)', 'myfunc(resi,resn,name)', space=myspace)

See Also