8.3 Looping over the Neighbors of an Atom

Often it is not the bonds around the atoms that you wish to loop over, but the neighboring atoms. One way to do this would be to use the GetBonds method described in the previous section and use the GetNbr method of each OEBondBase to get the atom across the bond from the input atom.

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class AtomNeighborsV1 {
 8   private static void ShowNeighbors(OEAtomBase atom) {
 9     System.out.print("Atom #"+atom.GetIdx()+" nbrs -> ");
10     for (OEBondBaseIter iter = atom.GetBonds(); iter.hasNext();) {
11       OEBondBase bond = iter.next();
12       OEAtomBase nbr = bond.GetNbr(atom);
13       System.out.print(" "+nbr.GetIdx());
14     }
15     System.out.println();
16   }
17
18   public static void main(String argv[]) {
19     OEGraphMol mol = new OEGraphMol();
20     oechem.OEParseSmiles(mol, "c1cocc1Br");
21     oechem.OEAssignAromaticFlags(mol);
22
23     for (OEAtomBaseIter aiter = mol.GetAtoms();aiter.hasNext();) {
24       OEAtomBase atom = aiter.next();
25       ShowNeighbors(atom);
26     }
27   }
28 }

Listing:8.3 Finding the neighbors of an atom

However this can be done even more conveniently using the GetAtoms method of an OEAtomBase directly, which allows loops over the neighbor atoms.

 1 /**************************************************************
 2  * Copyright 2005, OpenEye Scientific Software, Inc.
 3  *************************************************************/
 4
 5 import openeye.oechem.*;
 6
 7 public class AtomNeighborsV2 {
 8   private static void ShowNeighbors(OEAtomBase atom) {
 9     System.out.print("Atom #"+atom.GetIdx()+" nbrs -> ");
10     for (OEAtomBaseIter iter = atom.GetAtoms(); iter.hasNext();) {
11       OEAtomBase nbr = iter.next();
12       System.out.print(" "+nbr.GetIdx());
13     }
14     System.out.println();
15   }
16
17   public static void main(String argv[]) {
18     OEGraphMol mol = new OEGraphMol();
19     oechem.OEParseSmiles(mol, "c1cocc1Br");
20     oechem.OEAssignAromaticFlags(mol);
21
22     for (OEAtomBaseIter aiter = mol.GetAtoms();aiter.hasNext();) {
23       OEAtomBase atom = aiter.next();
24       ShowNeighbors(atom);
25     }
26   }
27 }
28
29

Listing:8.4 Finding the neighbors of an atom