Predicate Functors

Functors that return bool are an important special case. A unary function whose return type is bool is called a predicate.

In OEChem TK, these functors are often passed into another function. The functors are then called from inside the second function. This is the concept of a callback, because the second function provides the argument and ‘call’s back’ to the functor which was passed into the function. Generator method such as OEMolBase.GetAtoms can take a functor as an argument and use the callback mechanism to iterate over atoms that satisfy the functor passed to it. See example in Atom or Bond Subset Iteration section.

In the example below, the function CountAtoms loops over the atoms and performs a call-back to the predicate functor pred for each atom. If the predicate returns true, a counter is incremented. The main function passes OEIsOxygen predefined atom predicates to the CountAtoms function that counts the number of oxygen atoms in the molecule. (Please note that this function is already implemented in OEChem TK and called OECount.)

Listing 1: Using functor callbacks

using System;
using System.IO;
using OpenEye.OEChem;

public class Functors 
{
    public static void Main(string[] argv) 
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");
        Console.WriteLine("Number of oxygen atoms = " + CountAtoms(mol, new OEIsOxygen()));
    }

    private static int CountAtoms(OEMolBase mol, OEUnaryAtomPred pred) 
    {
        int counts = 0;

        foreach (OEAtomBase atom in mol.GetAtoms())
        {
            if (pred.Call(atom))
            {
                counts++;
            }
        }

        return counts;
    }
}

Built-in Functors

There are many useful functors already defined in OEChem TK. These can be used by programmers with little or no understanding of the details of how functors work. A programmer can simply pass them to one of the many OEChem TK functions and methods which take predicates as arguments.

Atom Functors

Access

Functor Name

ring atoms

OEAtomIsInRing

chain atoms

OEAtomIsInChain

atom with specified atom index

OEHasAtomIdx

atom with selected atom index

OEAtomIdxSelected

atom with specified atom name

OEHasAtomName

atoms with specified atom stereo

OEHasAtomStereoSpecified

atoms with specified formal charge

OEHasFormalCharge

atoms with specified number of heavy atom neighbors

OEHasHvyDegree

aromatic atoms

OEIsAromaticAtom

atoms with specific hybridization

OEIsAtomHybridization

chiral atoms

OEIsChiralAtom

atoms with anisotropic B-factor parameters

OEHasAnisou

atoms with specified map index

OEHasMapIdx

atoms representing R-Groups

OEIsRGroup

valid atoms (by OpenEye valence conventions)

OEIsValidAtomValence

valid atoms (by MDL valence conventions)

OEIsValidMDLAtomValence

\(n^{th}\) atom

OENthAtom

atoms that are both terminal and heavy

OEIsTermHeavyAtom

atom membership in a set of atoms

OEIsAtomMember

Listing 2: Using predefined atom functors

using System;
using OpenEye.OEChem;

public class FunctorsAtom 
{
    public static void Main(string[] argv) 
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");
        Console.WriteLine("Number of heavy atoms = " + 
                          OEChem.OECount(mol, new OEIsHeavy()));
        Console.WriteLine("Number of ring atoms  = " + 
                          OEChem.OECount(mol, new OEAtomIsInRing()));
    }
}

The output of the preceding program is the following:

Number of heavy atoms = 12
Number of ring atoms  = 11

Atomic Number Functors

Access

Functor Name

atoms with specified atomic number

OEHasAtomicNum

carbon atoms

OEIsCarbon

halogen atoms

OEIsHalogen

heavy atoms

OEIsHeavy

hetero atoms

OEIsHetero

explicit hydrogen atoms

OEIsHydrogen

metal atoms

OEIsMetal

nitrogen atoms

OEIsNitrogen

oxygen atoms

OEIsOxygen

sulfur atoms

OEIsSulfur

phosphorus atoms

OEIsPhosphorus

non-carbon atoms

OEIsPolar

polar hydrogen atoms

OEIsPolarHydrogen

Please note that the following two lines produce the same result.

        Console.WriteLine("Number of oxygen atoms = " + 
                          OEChem.OECount(mol, new OEHasAtomicNum(OEElemNo.O)));
        Console.WriteLine("Number of oxygen atoms = " + 
                          OEChem.OECount(mol, new OEIsOxygen()));

Bond Functors

Access

Functor Name

ring bonds

OEBondIsInRing

chain bonds

OEBondIsInChain

bond with specified bond index

OEHasBondIdx

bond with selected bond index

OEBondIdxSelected

bonds with specified bond order

OEHasOrder

rotatable bonds

OEIsRotor

chiral bonds

OEIsChiralBond

bonds with specific bond stereo

OEHasBondStereoSpecified

aromatic bonds

OEIsAromaticBond

bond membership in a set of bonds

OEIsBondMember

Listing 3: Using predefined bond functors

using System;
using OpenEye.OEChem;

public class FunctorsBond 
{
    public static void Main(string[] argv) 
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "CC(=O)Nc1c[nH]cc1");

        Console.WriteLine("Number of ring bonds  = " + 
                          OEChem.OECount(mol, new OEBondIsInRing()));
        Console.WriteLine("Number of rotor bonds = " + 
                          OEChem.OECount(mol, new OEIsRotor()));
    }
}

The output of the preceding program is the following:

Number of ring bonds  = 5
Number of rotor bonds = 2

Group Functors

Access

Functor Name

groups with a specific atom

OEHasAtomInGroup

groups with a specific bond

OEHasBondInGroup

groups with a specific type

OEHasGroupType

groups that store MDL stereo information

OEIsMDLStereoGroup

Reaction Component Functors

Access

Functor Name

atoms of the catalysts or solvents of a reaction

OEAtomIsInAgent

atoms of the product molecule(s)

OEAtomIsInProduct

atoms of the reactant molecule(s)

OEAtomIsInReactant

Conformer Functors

Access

Functor Name

conformer with specified index

OEHasConfIdx

conformer with selected index

OEConfIdxSelected

Residue Data Functors

Access

Functor Name

atoms with specified residue properties

OEAtomMatchResidue

atoms with specified chain id

OEHasChainID

atoms with specified residue number

OEHasResidueNumber

atoms with an alternate location

OEHasAlternateLocation

atoms with specified fragment number

OEHasFragmentNumber

atoms with specified PDB index

OEHasPDBAtomIndex

alpha carbon

OEIsCAlpha

backbone atom

OEIsBackboneAtom

water

OEIsWater

nucleic acid base

OEIsNucleicAcidBase

nucleic acid sugar

OEIsNucleicAcidSugar

nucleic acid phosphate

OEIsNucleicAcidPhosphate

Composite Functors

Occasionally, one may want to use a logical operator to join two or more functors. The following table shows the composite functors defined in OEChem TK.

Composite Functors

Logical Not

Logical or

Logical and

Description

OENotAtom

OEOrAtom

OEAndAtom

atom composite functors

OENotBond

OEOrBond

OEAndBond

bond composite functors

OENotConf

OEOrConf

OEAndConf

conformation composite functors

OENotGroup

OEOrGroup

OEAndGroup

group composite functors

OENotRoleSet

OEOrRoleSet

OEAndRoleSet

roleset composite functors

Each composite functor takes the appropriate number of predicates as arguments and generates a single unary predicate. The following example demonstrates how to use composite functors to build expressions from OEChem TK’s predefined atom predicates.

Listing 4: Combining predefined atom predicates

using System;
using OpenEye.OEChem;

public class CompositionFunctorsAtom
{
    public static void Main(string[] argv) 
    {
        OEGraphMol mol = new OEGraphMol();    
        OEChem.OESmilesToMol(mol, "c1cnc(O)cc1CCCBr");
        Console.WriteLine("Number of chain atoms = " + 
                           OEChem.OECount(mol, 
                                          new OENotAtom(new OEAtomIsInRing())));
        Console.WriteLine("Number of aromatic nitrogens = " + 
                           OEChem.OECount(mol, 
                                          new OEAndAtom(new OEIsNitrogen(), new OEIsAromaticAtom())));
        Console.WriteLine("Number of non-carbons = " +
                           OEChem.OECount(mol, 
                                          new OENotAtom(new OEHasAtomicNum(OEElemNo.C))));
        Console.WriteLine("Number of nitrogen and oxygen atoms = " +
                           OEChem.OECount(mol, new OEOrAtom(new OEHasAtomicNum(OEElemNo.N), new OEHasAtomicNum(OEElemNo.O))));
    }
}

The OECount function returns the number or objects (in this case atoms) matching the given predicate argument.

The output of the preceding program is the following:

Number of chain atoms = 5
Number of aromatic nitrogens = 1
Number of non-carbons = 3
Number of nitrogen and oxygen atoms = 2

Composite functors can be used similarly to combine predefined bond predicates.

Listing 5: Combining predefined bond predicates

using System;
using OpenEye.OEChem;

public class CompositionFunctorsBond
{
    public static void Main(string[] argv)
    {
        OEGraphMol mol = new OEGraphMol();    
        OEChem.OESmilesToMol(mol, "N#CCC1CCNC=C1");
        Console.WriteLine("Number of non-rotatable bonds = " +
                           OEChem.OECount(mol,
                                          new OENotBond(new OEIsRotor())));
        Console.WriteLine("Number of ring double bonds = " +
                           OEChem.OECount(mol,
                                          new OEAndBond(new OEBondIsInRing(), new OEHasOrder(2))));
        Console.WriteLine("Number of double or triple bonds = " +
                           OEChem.OECount(mol,
                                          new OEOrBond(new OEHasOrder(2), new OEHasOrder(3))));
    }
}

The output of the preceding program is the following:

Number of non-rotatable bonds = 8
Number of ring double bonds = 1
Number of double or triple bonds = 2

User Defined Functors

While many predefined functors exist in OEChem TK, it is not difficult to find a situation which calls for a new user-defined functor.

User-defined functor can be written by deriving from either the OEUnaryAtomPred or the OEUnaryBondPred class.

The following example shows a user defined atom functor which returns true for aliphatic nitrogens.

Listing 6: User defined atom predicate

using System;
using OpenEye.OEChem;

public class UserPredAtom
{
    public static void Main(string[] argv)
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");
        Console.WriteLine("Number of aliphatic N atoms = " +
                          OEChem.OECount(mol, new PredAliphaticNitrogen()));
    }

    private class PredAliphaticNitrogen : OEUnaryAtomPred
    {
        public override bool Call(OEAtomBase atom)
        {
            return atom.IsNitrogen() && !atom.IsAromatic();
        }

        public override OEUnaryAtomBoolFunc CreateCopy()
        {
            OEUnaryAtomBoolFunc copy = new PredAliphaticNitrogen();
            copy.ReleaseOwnership();
            return copy;
        }
    }
}

The output of the preceding program is the following:

Number of aliphatic N atoms = 1

A bond predicate can be similarly defined by deriving from the OEUnaryBondPred class.

Listing 7: User defined bond predicate

using System;
using OpenEye.OEChem;

public class UserPredBond
{
    public static void Main(string[] argv)
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "CC(=O)Nc1c[nH]cc1");
        Console.WriteLine("Number of amide bonds = " +
                          OEChem.OECount(mol, new PredAmideBond()));
    }

    private class PredHasDoubleBondO : OEUnaryAtomPred
    {
        public override bool Call(OEAtomBase atom)
        {
            foreach (OEBondBase bond in atom.GetBonds())
            {
                if (bond.GetOrder() == 2 && bond.GetNbr(atom).IsOxygen())
                {
                    return true;
                }
            }

            return false;
        }

        public override OEUnaryAtomBoolFunc CreateCopy()
        {
            OEUnaryAtomBoolFunc copy = new PredHasDoubleBondO();
            copy.ReleaseOwnership();
            return copy;
        }
    }

    private class PredAmideBond : OEUnaryBondPred
    {
        public override bool Call(OEBondBase bond)
        {
            if (bond.GetOrder() != 1)
            {
                return false;
            }

            OEAtomBase atomB = bond.GetBgn();
            OEAtomBase atomE = bond.GetEnd();
            OEUnaryAtomBoolFunc pred = new PredHasDoubleBondO();

            if (atomB.IsCarbon() && atomE.IsNitrogen() && pred.Call(atomB))
            {
                return true;
            }

            if (atomB.IsNitrogen() && atomE.IsCarbon() && pred.Call(atomE))
            {
                return true;
            }

            return false;
        }

        public override OEUnaryBondBoolFunc CreateCopy()
        {
            OEUnaryBondBoolFunc copy = new PredAmideBond();
            copy.ReleaseOwnership();
            return copy;
        }
    }
}

The output of the preceding program is the following:

Number of amide bonds = 1

One advantage of functors over function pointers is that they can hold state. Since this state is held by the instance of the object it can be thread safe (unlike static-variables inside functions used with function pointers). The state of a functor can be initialized at construction. For instance, OEHasAtomicNum functor takes an argument on construction which defines which atomic number is required for the functor to return true.

Listing 8: User defined atom predicate with state

using System;
using OpenEye.OEChem;

public class UserPredAtomArg
{
    public static void Main(string[] argv)
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");
        uint[] alist = new uint[2];
        alist[0] = OEElemNo.O;
        alist[1] = OEElemNo.N;
        Console.WriteLine("Number of oxygen or nitrogen atoms = " +
                          OEChem.OECount(mol, new PredAtomicNumList(alist)));
    }

    private class PredAtomicNumList : OEUnaryAtomPred
    {
        private uint[] alist;

        public PredAtomicNumList(uint[] a)
        {
            this.alist = (uint[])a.Clone();
        }

        public override bool Call(OEAtomBase atom)
        {
            foreach (uint i in this.alist)
            {
                if (atom.GetAtomicNum() == i)
                {
                    return true;
                }
            }

            return false;
        }

        public override OEUnaryAtomBoolFunc CreateCopy()
        {
            OEUnaryAtomBoolFunc copy = new PredAtomicNumList(this.alist);
            copy.ReleaseOwnership();
            return copy;
        }
    }
}

Functor substructure-based matching

The Listing 6 shows an example how to create a user-defined atom predicate. OEChem TK also provides a functor template, called OEMatchFunc, that allows convenient substructure-based atom matching.

In the following example functors are initialized with a SMARTS string. These functors return true only if the atom matches the substructure pattern specified in construction.

Listing 9: Functor substructure-based matching

using System;
using OpenEye.OEChem;

public class FunctorsOEMatch
{
    public static int Main(string[] args)
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "C1(Cl)C(N)C(F)OC1C(=O)NCCCN");
        Console.WriteLine("Number of non-amide nitrogen = " +
                          OEChem.OECount(mol, new OEMatchAtom("[N;!$(NC=O)]")));
        Console.WriteLine("Number of 5-membered ring oxygen = " +
                          OEChem.OECount(mol, new OEMatchAtom("[O;r5]")));
        Console.WriteLine("Number of carbon attached to halogen = " +
                          OEChem.OECount(mol, new OEMatchAtom("[#6][Cl,Br,F]")));
        return 0;
    }
}

The output of Listing 9 is the following:

Number of non-amide nitrogen = 2
Number of 5-membered ring oxygen = 1
Number of carbon attached to halogen = 2

Molecule Partitioning

The OESubsetMol function can take any atom predicate as an argument and generate a subset molecule from only atoms for which the specified predicate returns true. In the following example, ring atoms are extracted from a molecule by using the OEAtomIsInRing atom functor.

Listing 10: Ring system extraction

using System;
using OpenEye.OEChem;

public class FunctorsOESubsetMol 
{
    public static void Main(string[] argv) 
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");
        OEGraphMol submol = new OEGraphMol();
        OEChem.OESubsetMol(submol, mol, new OEAtomIsInRing(), true);
        Console.WriteLine(OEChem.OEMolToSmiles(submol));
    }
}

The output of Listing 10 is the following:

c1cc[nH]c1.C1CNCOC1

In the following example, ring systems are extracted from a molecule by using OEPartPred functor.

Listing 11: Ring system extraction

using System;
using OpenEye.OEChem;

public class FunctorsOEPartPred
{
    public static int Main(string[] args)
    {
        OEGraphMol mol = new OEGraphMol();
        OEChem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2");

        uint[] rings = new uint[mol.GetMaxAtomIdx()];
        uint nrrings = OEChem.OEDetermineRingSystems(mol, rings);
        OEPartPredAtom pred = new OEPartPredAtom(rings, (uint)rings.Length);
        Console.WriteLine("Number of rings = " + nrrings);
        for (uint r = 1; r < nrrings + 1; ++r)
        {
            pred.SelectPart(r);
            OEGraphMol ringmol = new OEGraphMol();
            OEChem.OESubsetMol(ringmol, mol, pred, true);
            Console.WriteLine(r + " -> " + OEChem.OEMolToSmiles(ringmol));
        }
        return 0;
    }
}

The output of Listing 11 is the following:

Number of rings = 2
1 -> c1cc[nH]c1
2 -> C1CNCOC1