8.4 Looping over subsets of Atoms or Bonds

It can sometimes be useful to loop over a subset of the atoms or bonds of a molecule. Traditionally this can be done with "if" statements inside a loop, but it can sometimes be cleaner and more convenient to subset the members being looped over inside the iterator. To do this, many of OEChem's iterator generation functions (such as OEMolBase.GetAtoms) can take an argument which determines which subset of the object to loop over (these functions are called predicates as detailed in the chapter below). The details of these functions are not important here. Instead, a programmer can simply use the predefined functors to control their loops.

The following example shows the use of the predicate OEHasAtomicNum() to loop over only carbon atoms in a molecule.

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class CarbonOnly {
 8   public static void main(String argv[]) {
 9     OEGraphMol mol = new OEGraphMol();
10     oechem.OEParseSmiles(mol, "c1c(Br)occ1CCC");
11     oechem.OEAssignAromaticFlags(mol);
12
13     System.out.println("carbon atoms:");
14     OEAtomBaseIter aiter = mol.GetAtoms(new OEHasAtomicNum(6));
15     while (aiter.hasNext()) {
16       System.out.print(aiter.next().GetIdx()+" ");
17     }
18   }
19 }

Listing:8.5 Looping over carbon atoms only

Predefined predicates in OEChem are list in section . These predicates can be particularly helpful when used in conjunction with functions which take OEIters as arguments as seen in the example below. This use of predicates allows factorization of the loop in a way not easily possible with if statements.

 1 /**************************************************************
 2  * Copyright 2005,2008 OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class AtomPredicateExamples {
 8     static private void PrintAtoms(OEAtomBaseIter aiter, String title) {
 9         System.out.println(title+":");
10         for (aiter.ToFirst();aiter.hasNext();) {
11             System.out.println(" "+aiter.next().GetIdx());
12         }
13         System.out.println();
14     }
15     public static void main(String argv[]) {
16         OEGraphMol mol = new OEGraphMol();
17         oechem.OEParseSmiles(mol, "c1c(O)c(O)c(Cl)cc1CCCBr");
18
19         OEAtomBaseIter aiter;
20
21         aiter = mol.GetAtoms(new OEAtomIsInRing());
22         PrintAtoms(aiter, "Ring Atoms");
23
24         aiter = mol.GetAtoms(new OEHasAtomicNum(8));
25         PrintAtoms(aiter, "Oxygens");
26
27         aiter = mol.GetAtoms(new OEIsHalogen());
28         PrintAtoms(aiter, "Halogens");
29     }
30 }

Listing:8.6 Using iterators with Atom predicates