Skip to content

IterateOverAllAtomsOfAMolecule

dstoeckel edited this page Mar 16, 2015 · 2 revisions

How can I iterate over all atoms of a molecule or atomContainer?

Iterate over all atoms of a molecule or atomContainer using BALL's AtomIterator:

C++

#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/PTE.h>

using namespace BALL;
...
Molecule mol;
...
AtomIterator ait = mol.beginAtom();
for (; +ait; ++ait)
{
  std::cout << ait->getElement().getSymbol() << std::endl;

  // Get a pointer to the current atom by
  Atom* atom = &*ait;
}

Note that _+ait _ equals ait != mol.endAtom() !

Note also: Never try to add or remove atoms from the molecule while iterating over it! Your program will crash!

A more elegant way to iterate over all atoms is to use the FOREACH-macro:

#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/PTE.h>

using namespace BALL;
...
AtomContainer* ac = RTTI::castTo<AtomContainer>(mol);
AtomIterator ait;
BALL_FOREACH_ATOM(*ac, ait)
{
   std::cout << ait->getElement().getSymbol() << std::endl;
}

Note: the FOREACH-macro gets an AtomContainer. BALL-objects, that can be runtime-cast to an AtomContainer are for example a Chain, a Residue, a Molecule, a Protein, or a System.

python

import sys
from BALL import *

# read the PDB-file into a BALL::System
f = PDBFile(sys.argv[1])
S = System()
f.read(S)
 
# check the first molecule
mol = S.getMolecule(0)

for atom in atoms(mol):
  print "Atom: ", atom.getElement().getSymbol()
Clone this wiki locally