.. _chapter_atombondindices:

********************************************************************************
Atom, Bond, and Conformer Indices
********************************************************************************

The following methods return the unique index assigned to its
associated object upon creation.

 - :oe:meth:`OEChem::OEAtomBase::GetIdx`
 - :oe:meth:`OEChem::OEBondBase::GetIdx`
 - :oe:meth:`OEChem::OEConfBase::GetIdx`

.. note::

   There is a parallel method `SetIdx` as well.  This is
   an advanced API that should never be used.

.. warning::

   Atoms, bonds and conformers are stored inside the molecule. If the 
   molecule is deallocated, the cached atoms, bonds, and conformers can 
   not be accessed any longer.

.. _section_atombondindices_uniqueidentifiers:

Unique Identifiers
================================================================================

This index can be used to distinguish one object from another, as it
is unique amongst all objects of the same type of the same molecule.
Indices are also stable, meaning a given object will have the same
index throughout its lifetime, independent of any other molecule
manipulations, *e.g.*, reordering the molecule
(:oe:meth:`OEChem::OEMolBase::OrderAtoms`), or the creation or deletion
of other objects (:oe:meth:`OEChem::OEMolBase::NewAtom` or
:oe:meth:`OEChem::OEMolBase::DeleteAtom`). The exception is the
following methods.

 - :oe:meth:`OEChem::OEMolBase::Sweep`
 - :oe:meth:`OEChem::OEMolBase::Compress`
 - :oe:meth:`OEChem::OEMolBase::UnCompress`
 - :oe:meth:`OEChem::OEMCMolBase::SweepConfs`

These methods were designed with the intent of changing something
about the underlying structure of the molecule, and thus are allowed
to invalidate indices if they deem it necessary.

Indices can be assumed to be dense small integers greater than or
equal to zero and less than the values returned by the following
methods.

 - :oe:meth:`OEChem::OEMolBase::GetMaxAtomIdx` for atoms
 - :oe:meth:`OEChem::OEMolBase::GetMaxBondIdx` for bonds
 - :oe:meth:`OEChem::OEMCMolBase::GetMaxConfIdx` for conformers

The index created on a new atom, bond, or conformer using
:oe:meth:`OEChem::OEMolBase::NewAtom`,
:oe:meth:`OEChem::OEMolBase::NewBond`, or
:oe:meth:`OEChem::OEMCMolBase::NewConf` respectively is guaranteed to
be greater than or equal to the index returned by the above methods.

.. _section_atombondindices_paralleldatastructures:

Parallel Data Structures
================================================================================

Indices are ideal for indexing into densely packed arrays of
information about the molecule. Many **OEChem TK** functions use them to
this end, *e.g.*, :oe:func:`OEChem::OEAddMols`,
:oe:func:`OEChem::OESubsetMol`, or
:oe:func:`OEChem::OEDetermineComponents`. The coordinates of a molecule
are retrieved as an array of floating point values indexed by the atom
indices. The following example demonstrates how to use the atom
indices for a rudimentary XYZ file format writer.

.. oe:source:: XYZWriter.cpp
   :language: c++
   :caption:  Rudimentary XYZ writer
   :refnum:   1
   :frag:     SNIPPET

.. oe:source:: XYZWriter.py
   :language: python
   :caption:  Rudimentary XYZ writer
   :refnum:   1
   :frag:     SNIPPET

.. oe:source:: XYZWriter.java
   :language: java
   :caption:  Rudimentary XYZ writer
   :refnum:   1
   :frag:     SNIPPET

.. oe:source:: XYZWriter.cs
   :language: csharp
   :caption:  Rudimentary XYZ writer
   :refnum:   1
   :frag:     SNIPPET

Computers are very efficient at doing this sort of sequential
lookup. Whenever an efficient temporary data structure is needed to
track information about a molecule indices should be used.

.. seealso: COMMENTED OUT

   The example :ref:`section_example_oechem_scaffoldextraction`
   demonstrates the use of atom indices to determine which atoms were
   already visited in a depth first search.

.. _section_atombondindices_dontdothis:

Indices for Molecule Lookup Considered Harmful
================================================================================

Note that atom, bond, and conformer indices are not guaranteed to be
sequential, or even created sequentially, and hence atom indices can
not and should not be used to retrieve all of the atoms of a molecule.
Even typing the following idiom may invalidate any chance of support
and eliminate any glimmer of respect from *OpenEye, Cadence Molecular Sciences*
or the computational chemistry/cheminformatics community.

.. oe:language:: c++

   .. warning::

      .. code-block:: c++

         // Never never, ever do this!!!
         OEAtomBase *aptr;
         unsigned int i;

         for (i=0; i<mol.NumAtoms(); ++i)
         {
            aptr = mol.GetAtom(OEHasAtomIdx(i));
            // Pretend that aptr is valid
         }

.. oe:language:: python

   .. warning::

      .. code-block:: python

         # Never ever, ever do this!!!
         for i in xrange(mol.NumAtoms()):
            atom = mol.GetAtom(OEHasAtomIdx(i))
            # pretend atom is valid

.. oe:language:: java

   .. warning::

      .. code-block:: java

         // Never ever, ever do this!!!
         for (int i=0;i<=mol.NumAtoms();++i) {
            OEAtomBase atom = mol.GetAtom(new OEHasAtomIdx(i));
            // pretend atom is valid
         }

.. oe:language:: csharp

   .. warning::

      .. code-block:: csharp

         // Never ever, ever do this!!!
         for (uint i=0; i<=mol.NumAtoms(); ++i)
         {
            OEAtomBase atom = mol.GetAtom(new OEHasAtomIdx(i));
            // pretend atom is valid
         }

There are far more efficient methods of crashing computer software
that should be used instead.

The common misconception is that **OEChem TK** indices should be stored in
order to reference back to an atom in the molecule. This leads to the
idiom used in :oe:src:`Listing 2<SNIPPET-AtomSubsetEvil>` which is technically
legal **OEChem TK**, however, is just as insidious as the previous code
snippet. The code is supposed to mimic a common technique to cache
particular atoms based on some expensive to calculate property. The
property in this instance is whether the atom is alpha beta
unsaturated.

.. warning::

   .. oe:source:: AtomSubsetEvil.cpp
      :language: c++
      :caption:  Evil atom cache
      :refnum:   2
      :frag:     SNIPPET

   .. oe:source:: AtomSubsetEvil.py
      :language: python
      :caption:  Evil atom cache
      :refnum:   2
      :frag:     SNIPPET

   .. oe:source:: AtomSubsetEvil.java
      :language: java
      :caption:  Evil atom cache
      :refnum:   2
      :frag:     SNIPPET

   .. oe:source:: AtomSubsetEvil.cs
      :language: csharp
      :caption:  Evil atom cache
      :refnum:   2
      :frag:     SNIPPET

The :oe:meth:`OEChem::OEMolBase::GetAtom` method performs a linear,
:math:`O(mol.NumAtoms())`, search over the molecule looking for the
first atom that matches the predicate. This leads to a multiplicative
effect when looping over multiple atoms, calling
:oe:meth:`GetAtom<OEChem::OEMolBase::GetAtom>` for each atom. The
resulting algorithm is quadratic :math:`O(mol.NumAtoms()^2)`, possibly
destroying any benefits of caching the user's expensive per atom
calculation.

.. oe:language:: c++

   The proper way to store references to atoms for later use is to
   store pointers to the :ref:`OEAtomBase <OEChem_OEAtomBase>` itself. It is
   guaranteed that the atoms will not be moved to another location in
   memory for the lifetime of the molecule.

.. oe:language:: python java csharp

   The proper way to store references to atoms for later use is to
   store the :ref:`OEAtomBase <OEChem_OEAtomBase>` itself. It is guaranteed that
   these atoms will be valid for the lifetime of the molecule.

This is regardless of molecule manipulations, *e.g.*, reordering the
molecule (:oe:meth:`OEChem::OEMolBase::OrderAtoms`), or the creation or
deletion of other atoms (:oe:meth:`OEChem::OEMolBase::NewAtom` or
:oe:meth:`OEChem::OEMolBase::DeleteAtom`). The ``Sweep`` and
``Compress`` methods are again exceptions to this rule.

:oe:src:`Listing 3<SNIPPET-AtomSubsetGood>` demonstrates the proper way to
create a cache of atoms. It is important to remember that the
:oe:cls:`OEAtomBases<OEChem::OEAtomBase>` in the container are only
valid while the molecule exists. Using the atoms after the molecule is
destroyed is undefined behavior (usually a segmentation fault).

.. oe:source:: AtomSubsetGood.cpp
   :language: c++
   :caption:  Atom caching
   :refnum:   3
   :frag:     SNIPPET

.. oe:source:: AtomSubsetGood.py
   :language: python
   :caption:  Atom caching
   :refnum:   3
   :frag:     SNIPPET

.. oe:source:: AtomSubsetGood.java
   :language: java
   :caption:  Atom caching
   :refnum:   3
   :frag:     SNIPPET

.. oe:source:: AtomSubsetGood.cs
   :language: csharp
   :caption:  Atom caching
   :refnum:   3
   :frag:     SNIPPET
