Tuesday, January 10, 2012

New removeAtomIf() method added to chemkit

A post by Andrew Dalke on the molcore-devel list gave an interesting idea to implement a remove_atoms() method which took a predicate and removed all atoms in a molecule that satisfy the predicate.

This lead me to add the removeAtomIf() method to the chemkit::Molecule class. The declaration is:

template<typename Predicate> removeAtomIf(Predicate predicate)

The predicate is any function object which takes a const Atom* and returns a bool. Using the boost::bind library makes it very easy to wrap various functions up as function objects that can be passed as predicates. For example, to remove every terminal hydrogen atom from a molecule one could simply:

molecule.removeAtomIf(boost::bind(&Atom::isTerminalHydrogen, _1));

This can even be used with the new C++11 lambdas. Code such as the following will remove all atoms that have an element symbol other than "C" (i.e. any non-carbon atom):

molecule.removeAtomIf([](const Atom *atom) { return atom->symbol() != "C"; });

Lambdas allows for arbitrarily complicated predicates to be defined at the point
removeAtomIf() is called. I, for one, cannot wait until C++11 features are widely supported.

No comments:

Post a Comment