OEChem Examples

Convert molecule files

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Program to convert from one molecule format to another
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class Convert {

    public static void processFile(oemolistream ifs, oemolostream ofs) {
        OEMol mol = new OEMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OEWriteMolecule(ofs, mol);
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("Convert <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        oemolostream ofs = new oemolostream();

        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
        if (!ofs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }

        processFile(ifs, ofs);
        ofs.close(); // make sure to flush output stream
    }
}

See also

Concatenating molecules

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * This program concatenates molecules into one file.
 * It can be useful for generating ROCS queries or reattach ligands to an
 * protein structure
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class CatMols {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void main(String argv[]) {
        URL fileURL = CatMols.class.getResource("CatMols.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "CatMols", argv);

            OEGraphMol omol = new OEGraphMol();
            for (String filename : itf.GetStringList("-i")) {
                oemolistream ifs = new oemolistream();
                if (ifs.open(filename)) {
                    OEGraphMol imol = new OEGraphMol();
                    while (oechem.OEReadMolecule(ifs, imol)) {
                        oechem.OEAddMols(omol, imol);
                    }
                }
                else {
                    oechem.OEThrow.Fatal("Unable to open " + filename + " for reading");
                }
                ifs.close();
            }
            oemolostream ofs = new oemolostream();
            if (!ofs.open(itf.GetString("-o"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
            }
            oechem.OEWriteMolecule(ofs, omol);
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Splitting multicomponent molecules

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Writes each component of a molecule as a separate molecule
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class Parts2Mols {

    public static void main(String argv[]) {
        if (argv.length < 1 || argv.length > 2) {
            oechem.OEThrow.Usage("Parts2Mols <infile> [<outfile>]");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        oemolostream ofs = new oemolostream(".ism");
        if (argv.length == 2) {
            if (!ofs.open(argv[1])) {
                oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
            }
        }

        int incount = 0;
        int outcount = 0;
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            incount++;
            int[] parts = new int[mol.GetMaxAtomIdx()];
            int pcount = oechem.OEDetermineComponents(mol, parts);
            OEPartPredAtom pred = new OEPartPredAtom(parts);
            for (int i = 1; i <= pcount; ++i) {
                outcount++;
                pred.SelectPart(i);
                OEGraphMol partmol = new OEGraphMol();
                oechem.OESubsetMol(partmol, mol, pred, true);
                oechem.OEWriteMolecule(ofs, partmol);
            }
        }
        ifs.close();
        ofs.close();
        System.err.println("results:  in: " + incount + "  out: " + outcount);
    }
}

Extract molecules by title

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Extract compound(s) from a file based on molecule title
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class MolExtract {

    private static Set fillTitleSet(OEInterface itf) {
        Set<String> titles = new HashSet<String>();

        if (itf.HasString("-title")) {
            titles.add(itf.GetString("-title"));
        } else if (itf.HasString("-list")) {
            oeifstream ifs = new oeifstream();
            if (!ifs.open(itf.GetString("-list"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-list") + " for reading");
            }
            StringBuffer line = new StringBuffer();
            while (ifs.getline(line)) {
                titles.add(line.toString().trim());
            }
            ifs.close();
        } else {
            oechem.OEThrow.Usage("Must give either -list or -title");
        }
        return titles;
    }

    private static void extract(OEInterface itf) {
        Set titleSet = fillTitleSet(itf);
        if (titleSet.size() == 0) {
            oechem.OEThrow.Fatal("No titles requested");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(itf.GetString("-i"))) {
            oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(itf.GetString("-o"))) {
            oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
        }

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            if (titleSet.contains(mol.GetTitle())) {
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
        ifs.close();
        ofs.close();
    }

    public static void main(String argv[]) {
        URL fileURL = MolExtract.class.getResource("MolExtract.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "MolExtract", argv);
            extract(itf);
        } catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Write out unique molecules

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Read molecules and write out the unique ones. Two molecules are considered
 * identical if their canonical isomeric smiles are identical.
 ****************************************************************************/
package openeye.examples.oechem;

import java.util.Set;
import java.util.HashSet;
import openeye.oechem.*;

public class UniqMol {

    public static void processFile(oemolistream ifs, oemolostream ofs) {
        OEGraphMol mol = new OEGraphMol();

        Set<String> uniqSmiles = new HashSet<String>();
        while (oechem.OEReadMolecule(ifs, mol)) {
            String smi = oechem.OECreateIsoSmiString(mol);
            if (uniqSmiles.add(smi)) {
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("UniqMol <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }

        processFile(ifs, ofs);
        ifs.close();
        ofs.close();
    }
}
/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Read molecules and write out the unique ones. Two molecules are considered
 * identical if their InChIs are identical.
 ****************************************************************************/
package openeye.examples.oechem;

import java.util.Set;
import java.util.HashSet;
import openeye.oechem.*;

public class UniqInChI {

    public static void processFile(oemolistream ifs, oemolostream ofs) {
        OEGraphMol mol = new OEGraphMol();

        Set<String> uniqInChIs = new HashSet<String>();
        while (oechem.OEReadMolecule(ifs, mol)) {
            String inchi = oechem.OECreateInChI(mol);
            if (uniqInChIs.add(inchi)) {
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("UniqInChI <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }

        processFile(ifs, ofs);
        ifs.close();
        ofs.close();
    }
}

See also

Randomize atoms of molecules

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Demonstrates how to randomly reorder atoms and bonds of a molecule
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class RandomizeAtoms {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("RandomizeAtoms <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OEScrambleMolecule(mol);
            oechem.OEWriteMolecule(ofs, mol);
        }
        ifs.close();
        ofs.close();
    }
}

See also

Generate canonical smiles

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Generate canonical smiles of various flavors
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import java.io.*;
import openeye.oechem.*;

/***************************************************************************
 To create unique Kekule smiles, must reperceive bond orders from
 scratch to avoid arbitrary nondeterministic variations, e.g.,
 CC1=C(O)C=CC=C1 vs. CC1=CC=CC=C1O
 This is why OESMILESFlag_Kekule is not sufficient and not used.
 ***************************************************************************/

public class CanSmi {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static String canSmi(OEGraphMol mol, boolean isomeric, boolean kekule) {
        oechem.OEFindRingAtomsAndBonds(mol);
        oechem.OEAssignAromaticFlags(mol, OEAroModel.OpenEye);
        int smiflag = OESMILESFlag.Canonical;
        if (isomeric) {
            smiflag |= OESMILESFlag.ISOMERIC;
        }
        if (kekule) {
            for (OEBondBase bond : mol.GetBonds(new OEIsAromaticBond())) {
                bond.SetIntType(5);
            }
            oechem.OECanonicalOrderAtoms(mol);
            oechem.OECanonicalOrderBonds(mol);
            oechem.OEClearAromaticFlags(mol);
            oechem.OEKekulize(mol);
        }
        String smi = oechem.OECreateSmiString(mol, smiflag);
        return smi;
    }

    public static void main(String argv[]) {
        URL fileURL = CanSmi.class.getResource("CanSmi.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "CanSmi", argv);

            boolean isomeric = itf.GetBool("-isomeric");
            boolean kekule   = itf.GetBool("-kekule");
            boolean from3d   = itf.GetBool("-from3d");

            if (from3d) {
                isomeric = true;
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            PrintStream out = System.out;
            if (itf.HasString("-o")) {
                try {
                    out = new PrintStream(itf.GetString("-o"));
                }
                catch(java.io.IOException e) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                if (from3d) {
                    oechem.OE3DToInternalStereo(mol);
                }
                String smi = canSmi(mol, isomeric, kekule);
                String title = mol.GetTitle();
                if ((title != null) && (!title.equals(""))) {
                    smi += " " + title;
                }
                out.println(smi);
            }
            ifs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Filter molecules by weight or heavy atom count

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Filter out molecules by their molecular weight or heavy atom count
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class SizeFilter {

    public static boolean isBetween(int min, int max, int val) {
        if (val >= min && val <= max) {
            return true;
        }
        return false;
    }

    public static boolean isBetween(double min, double max, double val) {
        if (val >= min && val <= max) {
            return true;
        }
        return false;
    }

    public static boolean isMoleculeInHeavyAtomCountRange(int minhac, int maxhac, OEMol mol) {

        int count = oechem.OECount(mol, new OEIsHeavy());
        return isBetween(minhac, maxhac, count);
    }

    public static boolean isMoleculeInMolWtRange(double minwt, double maxwt, OEMol mol) {

        double molwt = oechem.OECalculateMolecularWeight(mol);
        return isBetween(minwt, maxwt, molwt);
    }

    public static void main(String argv[]) {
        URL fileURL = SizeFilter.class.getResource("SizeFilter.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "SizeFilter", argv);

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream(".ism");
            if (itf.HasString("-o")) {
                if (!ofs.open(itf.GetString("-o"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }

            int minhac = Integer.MIN_VALUE;
            if (itf.HasInt("-minhac")) {
                minhac = itf.GetInt("-minhac");
            }

            int maxhac = Integer.MAX_VALUE;
            if (itf.HasInt("-maxhac")) {
                maxhac = itf.GetInt("-maxhac");
            }

            double minwt = Double.MIN_VALUE;
            if (itf.HasDouble("-minwt")) {
                minwt = itf.GetDouble("-minwt");
            }

            double maxwt = Double.MAX_VALUE;
            if (itf.HasDouble("-maxwt")) {
                maxwt = itf.GetDouble("-maxwt");
            }

            OEMol mol = new OEMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                if (!isMoleculeInHeavyAtomCountRange(minhac, maxhac, mol)) {
                    continue;
                }

                if (!isMoleculeInMolWtRange(minwt, maxwt, mol)) {
                    continue;
                }

                oechem.OEWriteMolecule(ofs, mol);
                ofs.close();
            }
            ifs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Strip salts

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Remove salts and/or remove all but the largest molecule
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class StripSalts {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("StripSalts <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }

        OEMol mol = new OEMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OETheFunctionFormerlyKnownAsStripSalts(mol);
            oechem.OEWriteMolecule(ofs, mol);
        }
        ifs.close();
        ofs.close();
    }
}

Extract rings

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Extracting rings/ring systems from input molecules
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class RingSubset {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void RingSubSet(oemolistream ifs, oemolostream ofs, boolean exo) {
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            OEGraphMol submol = new OEGraphMol();
            OEUnaryAtomPred pred = new OEAtomIsInRing();
            if (exo) {
                pred = new OEOrAtom(pred, new OEIsNonRingAtomDoubleBondedToRing());
            }
            boolean adjustHCount = true;
            oechem.OESubsetMol(submol, mol, pred, adjustHCount);

            String title = mol.GetTitle() + "_rings";
            submol.SetTitle(title);
            if (submol.NumAtoms() != 0) {
                oechem.OEWriteMolecule(ofs, submol);
            }
        }
    }

    public static void main(String argv[]) {
        URL fileURL = RingSubset.class.getResource("RingSubset.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "RingSubset", argv);

            boolean exo_dbl_bonds = itf.GetBool("-exo");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream(".ism");
            if (itf.HasString("-o")) {
                if (!ofs.open(itf.GetString("-o"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }
            RingSubSet(ifs, ofs, exo_dbl_bonds);
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Extract molecule scaffolds

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Extract the ring scaffold of a molecule
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class ExtractScaffold {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    static boolean TraverseForRing(boolean[] visited, OEAtomBase atom) {
        visited[atom.GetIdx()] = true;

        for (OEAtomBase nbor : atom.GetAtoms()) {
            if (!visited[nbor.GetIdx()]) {
                if (nbor.IsInRing()) {
                    return true;
                }

                if (TraverseForRing(visited, nbor)) {
                    return true;
                }
            }
        }
        return false;
    }

    static boolean DepthFirstSearchForRing(OEAtomBase root, OEAtomBase nbor) {
        boolean[] visited = new boolean[root.GetParent().GetMaxAtomIdx()];

        visited[root.GetIdx()] = true;

        return TraverseForRing(visited, nbor);
    }

    static class IsInScaffold extends OEUnaryAtomPred {
        @Override
        public boolean constCall(OEAtomBase atom) {
            if (atom.IsInRing()) {
                return true;
            }

            int count = 0;
            for (OEAtomBase nbor : atom.GetAtoms()) {
                if (DepthFirstSearchForRing(atom, nbor)) {
                    ++count;
                }
            }
            return count > 1;
        }

        @Override
        public OEUnaryAtomBoolFunc CreateCopy() {
            OEUnaryAtomBoolFunc copy = new IsInScaffold();
            copy.swigReleaseOwnership();
            return copy;
        }
    }

    public static void main(String argv[]) {
        URL fileURL = ExtractScaffold.class.getResource("ExtractScaffold.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "ExtractScaffold", argv);

            boolean exo_dbl_bonds = itf.GetBool("-exo");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream();
            if (!ofs.open(itf.GetString("-o"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
            }

            OEMol src = new OEMol();
            OEMol dst = new OEMol();
            while (oechem.OEReadMolecule(ifs, src)) {
                OEUnaryAtomPred pred = new IsInScaffold();
                if (exo_dbl_bonds) {
                    pred = new OEOrAtom(pred, new OEIsNonRingAtomDoubleBondedToRing());
                }
                boolean adjustHCount = true;
                oechem.OESubsetMol(dst, src, pred, adjustHCount);

                if (dst.IsValid()) {
                    oechem.OEWriteMolecule(ofs, dst);
                }
            }
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Extract random molecule subset

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Randomly reorder molecules and optionally obtain a random subset
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import openeye.oechem.*;

public class RandomSample {

    public static void LoadDatabase(oemolistream ifs, List<OEMol> mList, int count) {
        int readcount = 0;
        OEMol mol = new OEMol(OEMCMolType.OEDBMCMol);
        while (oechem.OEReadMolecule(ifs, mol)) {
            readcount++;
            mol.Compress();
            mList.add(mol);
            mol = new OEMol();
            if (readcount == count) {
                break;
            }
        }
    }

    public static void WriteDatabase(oemolostream ofs, List<OEMol> mList, int count) {
        int outcount = 0;
        for (OEMol dbmol : mList) {
            dbmol.UnCompress();
            oechem.OEWriteMolecule(ofs, dbmol);
            outcount++;
            if (outcount == count) {
                break;
            }
        }
    }

    public static void RandomizePercent(oemolistream ifs, oemolostream ofs, float percent, Random r) {
        List<OEMol> mList = new ArrayList<OEMol>();
        LoadDatabase(ifs, mList, 0);

        Collections.shuffle(mList, r);

        int size = mList.size();
        int count = (int)(percent * 0.01 * size);
        if (count < 1) {
            count = 1;
        }
        WriteDatabase(ofs, mList, count);
    }

    public static void Randomize(oemolistream ifs, oemolostream ofs, Random r) {
        float wholedb = 100;
        RandomizePercent(ifs, ofs, wholedb, r);
    }

    public static void RandomizeN(oemolistream ifs, oemolostream ofs, int count, Random r) {
        List<OEMol> mList = new ArrayList<OEMol>();
        LoadDatabase(ifs, mList, count);

        int readcount = 0;
        OEMol mol = new OEMol(OEMCMolType.OEDBMCMol);
        while (oechem.OEReadMolecule(ifs, mol)) {
            if ((float)count/(count + readcount + 1) > r.nextFloat()) {
                int idx = (int) ((float)count * r.nextFloat());
                mol.Compress();
                mList.set(idx, mol);
                mol = new OEMol();
            }
            readcount++;
        }

        Collections.shuffle(mList, r);
        WriteDatabase(ofs, mList, count);
    }

    public static void main(String argv[]) {
        URL fileURL = RandomSample.class.getResource("RandomSample.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "RandomSample", argv);

            if (itf.HasFloat("-p") && itf.HasInt("-n")) {
                oechem.OEThrow.Usage("Give only one option, -p or -n");
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream(".ism");
            if (itf.HasString("-o")) {
                if (!ofs.open(itf.GetString("-o"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }

            Random r = null;
            if (itf.HasInt("-seed")) {
                r = new Random(itf.GetInt("-seed"));
            }
            else {
                r = new Random();
            }

            if (itf.HasInt("-n")) {
                RandomizeN(ifs, ofs, itf.GetInt("-n"), r);
            }
            else if (itf.HasFloat("-p")) {
                RandomizePercent(ifs, ofs, itf.GetFloat("-p"), r);
            }
            else {
                Randomize(ifs, ofs, r);
            }
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Performing a reaction

/****************************************************************************
 * Copyright 2004-2017 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Perform reactions on the given compounds
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class UniMolRxn {

    public static void uniMolRxn (oemolistream ifs,
            oemolostream ofs,
            OEUniMolecularRxn umr) {

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            if (umr.constCall(mol)) {
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
    }

    public static void main(String argv[]) {
        if (argv.length < 2 || argv.length > 3) {
            oechem.OEThrow.Usage("UniMolRxn SMIRKS <infile> [<outfile>]");
        }

        OEQMol qmol = new OEQMol();
        if (!oechem.OEParseSmirks(qmol, argv[0])) {
            oechem.OEThrow.Fatal("Unable to parse SMIRKS: " + argv[0]);
        }

        OEUniMolecularRxn umr = new OEUniMolecularRxn();
        if (!umr.Init(qmol)) {
            oechem.OEThrow.Fatal("Failed to initialize reaction with " + argv[0] + " SMIRKS");
        }
        umr.SetClearCoordinates(true);

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
        }

        oemolostream ofs = new oemolostream(".ism");
        if (argv.length == 3) {
            if (!ofs.open(argv[2])) {
                oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
            }
        }

        uniMolRxn(ifs, ofs, umr);
        ifs.close();
        ofs.close();
    }
}

See also

Library generation

/****************************************************************************
 * Copyright 2004-2017 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Perform library generation with SMIRKS
 ****************************************************************************/
package openeye.examples.oechem;

import java.util.Set;
import java.util.HashSet;
import java.net.URL;
import openeye.oechem.*;

public class LibGen {

    public static void libGen(OELibraryGen libgen, oemolostream ofs,
            boolean isomeric, boolean unique) {
        int smiflag = OESMILESFlag.DEFAULT;
        if (isomeric) {
            smiflag |= OESMILESFlag.ISOMERIC;
        }
        Set<String> uniqueProducts = new HashSet<String>();
        for (OEMolBase mol : libgen.GetProducts()) {
            String smiles = oechem.OECreateSmiString(mol, smiflag);
            if (!unique || !uniqueProducts.contains(smiles)) {
                uniqueProducts.add(smiles);
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
    }

    public static void main(String argv[]) {
        URL fileURL = LibGen.class.getResource("LibGen.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "LibGen", argv);
            if (!(itf.HasString("-smirks") ^ itf.HasString("-rxn"))) {
                oechem.OEThrow.Fatal("Please provide SMIRKS string or MDL reaction file");
            }

            OEQMol reaction = new OEQMol();
            if (itf.HasString("-smirks")) {
                String smirks = itf.GetString("-smirks");
                if (!oechem.OEParseSmirks(reaction, smirks)) {
                    oechem.OEThrow.Fatal("Unable to parse SMIRKS: " + smirks);
                }
            }
            else {
                String rxn = itf.GetString("-rxn");
                oemolistream rfile = new oemolistream(rxn);
                int opt = OEMDLQueryOpts.ReactionQuery|OEMDLQueryOpts.SuppressExplicitH;
                if (!oechem.OEReadMDLReactionQueryFile(rfile, reaction, opt)) {
                    oechem.OEThrow.Fatal("Unable to read reaction file: " + rxn);
                }
            }
            boolean relax      = itf.GetBool("-relax");
            boolean unique     = itf.GetBool("-unique");
            boolean implicitH  = itf.GetBool("-implicitH");
            boolean valCorrect = itf.GetBool("-valence");
            boolean isomeric   = itf.GetBool("-isomeric");

            OELibraryGen libgen = new OELibraryGen();

            // Initialize library generation
            if (!libgen.Init(reaction, !relax)) {
                oechem.OEThrow.Fatal("failed to initialize library generator");
            }
            libgen.SetValenceCorrection(valCorrect);
            libgen.SetExplicitHydrogens(!implicitH);
            libgen.SetClearCoordinates(true);

            int nrReacts = 0;
            for (String filename : itf.GetStringList("-reactants")) {
                if (nrReacts >= libgen.NumReactants()) {
                    oechem.OEThrow.Fatal("Number of reactant files exceeds number of reactants specified in reaction");
                }
                oemolistream ifs = new oemolistream();
                if (!ifs.open(filename)) {
                    oechem.OEThrow.Fatal("Unable to open " + filename + " for reading");
                }
                OEGraphMol mol = new OEGraphMol();
                while (oechem.OEReadMolecule(ifs, mol)) {
                    libgen.AddStartingMaterial(mol, nrReacts, unique);
                }
                nrReacts++;
                ifs.close();
            }
            if (nrReacts != libgen.NumReactants()) {
                oechem.OEThrow.Fatal("Reactions requires " + libgen.NumReactants() + " reactant files!");
            }

            oemolostream ofs = new oemolostream(".ism");
            if (itf.HasString("-product")) {
                if (!ofs.open(itf.GetString("-product"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-product") + " for writing");
                }
            }
            libGen(libgen, ofs, isomeric, unique);
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Perform substructure searches

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Perform substructure search on molecule file
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class MolGrep {

    public static void subSearch(OEInterface itf, OESubSearch ss,
            oemolistream ifs, oemolostream ofs) {

        boolean reverseflag = itf.GetBool("-r");
        boolean countflag   = itf.GetBool("-c");
        int count = 0;
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OEPrepareSearch(mol, ss);
            if (ss.SingleMatch(mol) != reverseflag) {
                if (countflag) {
                    count++;
                }
                else {
                    oechem.OEWriteMolecule(ofs, mol);
                }
            }
        }
        if (countflag) {
            System.out.println(count + " matching molecules");
        }
    }

    public static void main(String argv[]) {
        URL fileURL = MolGrep.class.getResource("MolGrep.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "MolGrep", argv);
            if (!(itf.GetBool("-c") ^ itf.HasString("-o"))) {
                oechem.OEThrow.Fatal("Counting (-c) or output (-o) must be specified and are mutually exclusive.");
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream();
            if (!itf.GetBool("-c")) {
                if (!ofs.open(itf.GetString("-o"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }

            String smarts = itf.GetString("-p");
            OESubSearch ss = new OESubSearch();
            if (!ss.Init(smarts)) {
                oechem.OEThrow.Fatal("Unable to parse SMARTS: " + smarts);
            }

            subSearch(itf, ss, ifs, ofs);
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Align molecules by maximum common substructure

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Align two compounds based on the maximum common substructure
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class MCS3DAlign {

    public static void mcsAlign(OEMolBase refmol, OEMolBase fitmol,
            oemolostream ofs) {
        int atomexpr = OEExprOpts.AtomicNumber|OEExprOpts.Aromaticity;
        int bondexpr =  0; // ignore bond order
        int mcsstype = OEMCSType.Exhaustive;
        OEMCSSearch mcss = new OEMCSSearch(refmol, atomexpr, bondexpr, mcsstype);
        mcss.SetMCSFunc(new OEMCSMaxBondsCompleteCycles());

        boolean unique = true;
        for (OEMatchBase match : mcss.Match(fitmol, unique)) {
            double rmat[] = new double[9];
            double trans[] = new double[3];
            boolean overlay = true;
            double rms = oechem.OERMSD(mcss.GetPattern(), fitmol, match, overlay, rmat, trans);
            if (rms < 0.0) {
                oechem.OEThrow.Warning("RMS overlay failure");
                continue;
            }
            oechem.OERotate(fitmol, rmat);
            oechem.OETranslate(fitmol, trans);
            oechem.OEWriteMolecule(ofs, fitmol);
        }
    }

    public static boolean is3DFormat(int fmt) {
        if (fmt == OEFormat.SMI || fmt == OEFormat.ISM ||
                fmt == OEFormat.CAN || fmt == OEFormat.MF) {
            return false;
        }
        return true;
    }

    public static void main(String argv[]) {
        if (argv.length != 3) {
            oechem.OEThrow.Usage("MCS3DAlign <refmol> <fitmol> <outfile>");
        }

        oemolistream reffs = new oemolistream();
        if (!reffs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
        if (!is3DFormat(reffs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }
        OEGraphMol refmol = new OEGraphMol();
        if (!oechem.OEReadMolecule(reffs, refmol)) {
            oechem.OEThrow.Fatal("Unable to read molecule in " + argv[0]);
        }
        if (refmol.GetDimension() != 3) {
            oechem.OEThrow.Fatal(refmol.GetTitle() + " doesn't have 3D coordinates");
        }
        reffs.close();

        oemolistream fitfs = new oemolistream();
        if (!fitfs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
        }
        if (!is3DFormat(fitfs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[2])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
        }
        if (!is3DFormat(ofs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");
        }

        oechem.OEWriteConstMolecule(ofs, refmol);
        oechem.OESuppressHydrogens(refmol);

        OEGraphMol fitmol = new OEGraphMol();
        while (oechem.OEReadMolecule(fitfs, fitmol)) {
            if (fitmol.GetDimension() != 3) {
                oechem.OEThrow.Warning(fitmol.GetTitle() + " doesn't have 3D coordinates");
                continue;
            }
            mcsAlign(refmol, fitmol, ofs);
        }
        fitfs.close();
        ofs.close();
    }
}

See also

Align molecules by clique match

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Align two compounds based on the clique match
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class CliqueAlign {

    public static void cliqueAlign(OEMolBase refmol, OEMolBase fitmol,
            oemolostream ofs) {
        int atomexpr = OEExprOpts.DefaultAtoms;
        int bondexpr = OEExprOpts.DefaultBonds;
        OECliqueSearch cs = new OECliqueSearch(refmol, atomexpr, bondexpr);
        cs.SetSaveRange(5);
        cs.SetMinAtoms(6);
        for (OEMatchBase match : cs.Match(fitmol)) {
            double rmat[] = new double[9];
            double trans[] = new double[3];
            boolean overlay = true;
            oechem.OERMSD(cs.GetPattern(), fitmol, match, overlay, rmat, trans);
            oechem.OERotate(fitmol, rmat);
            oechem.OETranslate(fitmol, trans);
            oechem.OEWriteMolecule(ofs, fitmol);
        }
    }

    public static boolean is3DFormat(int fmt) {
        if (fmt == OEFormat.SMI || fmt == OEFormat.ISM ||
                fmt == OEFormat.CAN || fmt == OEFormat.MF) {
            return false;
        }
        return true;
    }

    public static void main(String argv[]) {
        if (argv.length != 3) {
            oechem.OEThrow.Usage("CliqueAlign <refmol> <fitmol> <outfile>");
        }

        oemolistream reffs = new oemolistream();
        if (!reffs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
        if (!is3DFormat(reffs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }
        OEGraphMol refmol = new OEGraphMol();
        if (!oechem.OEReadMolecule(reffs, refmol)) {
            oechem.OEThrow.Fatal("Unable to read molecule in " + argv[0]);
        }
        if (refmol.GetDimension() != 3) {
            oechem.OEThrow.Fatal(refmol.GetTitle() + " doesn't have 3D coordinates");
        }
        reffs.close();

        oemolistream fitfs = new oemolistream();
        if (!fitfs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
        }
        if (!is3DFormat(fitfs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[2])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
        }
        if (!is3DFormat(ofs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");
        }

        oechem.OEWriteConstMolecule(ofs, refmol);
        oechem.OESuppressHydrogens(refmol);

        OEGraphMol fitmol = new OEGraphMol();
        while (oechem.OEReadMolecule(fitfs, fitmol)) {
            if (fitmol.GetDimension() != 3) {
                oechem.OEThrow.Warning(fitmol.GetTitle() + " doesn't have 3D coordinates");
                continue;
            }
            cliqueAlign(refmol, fitmol, ofs);
        }
        fitfs.close();
        ofs.close();
    }
}

See also

Align molecules by SMARTS

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Align two compounds based on smarts match
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class SMARTSAlign {

    public static void smartsAlign(OEMolBase refmol, OEMolBase fitmol,
            OESubSearch ss, oemolostream ofs) {
        boolean unique = true;
        for (OEMatchBase match1 : ss.Match(refmol, unique)) {
            for (OEMatchBase match2 : ss.Match(fitmol, unique)) {
                OEMatch match = new OEMatch();
                OEMatchPairAtomIter mbi1 = match1.GetAtoms();
                OEMatchPairAtomIter mbi2 = match2.GetAtoms();
                while (mbi1.hasNext() && mbi2.hasNext()) {
                    match.AddPair(mbi1.next().getTarget(), mbi2.next().getTarget());
                }
                boolean overlay = true;
                double rmat[] = new double[9];
                double trans[] = new double[3];
                oechem.OERMSD(refmol, fitmol, match, overlay, rmat, trans);
                oechem.OERotate(fitmol, rmat);
                oechem.OETranslate(fitmol, trans);
                oechem.OEWriteConstMolecule(ofs, fitmol);
            }
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 4) {
            oechem.OEThrow.Usage("SMARTSAlign <refmol> <fitmol> <outfile> <smarts>");
        }

        oemolistream reffs = new oemolistream();
        if (!reffs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
        if (!oechem.OEIs3DFormat(reffs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }
        OEGraphMol refmol = new OEGraphMol();
        if (!oechem.OEReadMolecule(reffs, refmol)) {
            oechem.OEThrow.Fatal("Unable to read molecule in " + argv[0]);
        }
        if (refmol.GetDimension() != 3) {
            oechem.OEThrow.Fatal(refmol.GetTitle() + " doesn't have 3D coordinates");
        }
        reffs.close();

        oemolistream fitfs = new oemolistream();
        if (!fitfs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
        }
        if (!oechem.OEIs3DFormat(fitfs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[2])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
        }
        if (!oechem.OEIs3DFormat(ofs.GetFormat())) {
            oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates");
        }

        oechem.OEWriteConstMolecule(ofs, refmol);

        OESubSearch ss = new OESubSearch();
        if (!ss.Init(argv[3])) {
            oechem.OEThrow.Fatal("Unable to parse SMARTS: " + argv[3]);
        }

        oechem.OEPrepareSearch(refmol, ss);
        if (!ss.SingleMatch(refmol)) {
            oechem.OEThrow.Fatal("SMARTS fails to match refmol");
        }

        OEGraphMol fitmol = new OEGraphMol();
        while (oechem.OEReadMolecule(fitfs, fitmol)) {
            if (fitmol.GetDimension() != 3) {
                oechem.OEThrow.Warning(fitmol.GetTitle() + " doesn't have 3D coordinates");
                continue;
            }
            oechem.OEPrepareSearch(fitmol, ss);
            if (!ss.SingleMatch(fitmol))
            {
                oechem.OEThrow.Warning("SMARTS fails to match fitmol " + fitmol.GetTitle());
                continue;
            }

            smartsAlign(refmol, fitmol, ss, ofs);
        }
        fitfs.close();
        ofs.close();
    }
}

See also

Align multi-conformer molecules

/****************************************************************************
 * Copyright 2004-2015 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Using the OERMSD() function.
 * Performing RMSD calculation between a 3D reference molecule and
 * multi-conformation molecules
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;
import openeye.oebio.*;
import java.net.URL;
import java.io.IOException;

public class RMSD {
        public static void main(String[] args) {
            URL fileURL = RMSD.class.getResource("RMSD.txt");
            OEInterface itf  = null;
            try {
                itf = new OEInterface(fileURL, "RMSD", args);
            } catch (IOException e) {
                System.err.println("Unable to open interface file");
            }

            if (!itf.GetBool("-verbose")) {
                oechem.OEThrow.SetLevel(OEErrorLevel.Warning);
            }

            String rfname = itf.GetString("-ref");
            String ifname = itf.GetString("-in");

            boolean automorph = itf.GetBool("-automorph");
            boolean heavy = itf.GetBool("-heavyonly");
            boolean overlay = itf.GetBool("-overlay");

            oemolistream refifs = new oemolistream();
            if (!refifs.open(rfname))
                oechem.OEThrow.Fatal("Unable to open " + rfname + " for reading");

            OEGraphMol rmol = new OEGraphMol();
            if (!oechem.OEReadMolecule(refifs, rmol))
                oechem.OEThrow.Fatal("Unable to read reference molecule");
            refifs.close();

            oemolistream ifs = new oemolistream();
            if (!ifs.open(ifname))
                oechem.OEThrow.Fatal("Unable to open " + ifname + " for reading");

            oemolostream ofs = null;
            if (itf.HasString("-out")) {
                String ofname = itf.GetString("-out");
                ofs = new oemolostream();
                if (!ofs.open(ofname))
                    oechem.OEThrow.Fatal("Unable to open "+ ofname +" for writing");
                if (!overlay)
                    oechem.OEThrow.Warning("Output is the same as input when overlay is false");
            }

            for (OEMCMolBase mol : ifs.GetMCMolBases()) {
                oechem.OEThrow.Info(mol.GetTitle());

                int maxIdx = mol.GetMaxConfIdx();
                OEDoubleArray rmsds = new OEDoubleArray(maxIdx);
                OEDoubleArray rmtx = new OEDoubleArray(9*maxIdx);
                OEDoubleArray tmtx = new OEDoubleArray(3*maxIdx);

                // performing RMSD for all conformers
                oechem.OERMSD(rmol, mol, rmsds, automorph, heavy, overlay, rmtx, tmtx);

                for( OEConfBase conf : mol.GetConfs()) {
                    int cidx = conf.GetIdx();
                    oechem.OEThrow.Info("Conformer " + cidx + ": rmsd = " + rmsds.getItem(cidx));

                    if (itf.GetBool("-overlay")) {
                        oechem.OERotate(conf, RMSD.slice(rmtx, cidx*9, cidx*9+9));
                        oechem.OETranslate(conf, RMSD.slice(tmtx, cidx*3, cidx*3+3));
                    }
                }

                if (ofs != null) {
                    oechem.OEWriteMolecule(ofs, mol);
                }
            } // end for
            if (ofs != null) {
                ofs.close();
            }
        }

    private static OEDoubleArray slice(OEDoubleArray src, int begin, int end) {
        OEDoubleArray ret = new OEDoubleArray(end - begin);
        int cnt = 0;
        for(int i=begin; i!=end; i++,cnt++) {
            ret.setItem(cnt, src.getItem(i));
        }
        return ret;
    }
}

See also

Modifying SD tags

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Modifies the SD data of a set of input molecules by clearing all tags,
 * defining which tags to keep or defining which tags to remove
 ****************************************************************************/
package openeye.examples.oechem;

import java.util.Set;
import java.util.HashSet;
import java.net.URL;
import openeye.oechem.*;

public class SDFModProps {

    public static void clearProps(oemolistream ifs,
            oemolostream ofs) {
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OEClearSDData(mol);
            oechem.OEWriteMolecule(ofs, mol);
        }
    }

    public static void keepProps(OEStringIter proplist,
            oemolistream ifs,
            oemolostream ofs) {
        Set<String> props = new HashSet<String>();
        proplist.ToFirst();
        for (String prop : proplist) {
            props.add(prop);
        }

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            for (OESDDataPair dp : oechem.OEGetSDDataPairs(mol)) {
                if (!props.contains(dp.GetTag())) {
                    oechem.OEDeleteSDData(mol, dp.GetTag());
                }
            }
            oechem.OEWriteMolecule(ofs, mol);
        }
    }

    public static void removeProps(OEStringIter proplist,
            oemolistream ifs,
            oemolostream ofs) {
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            proplist.ToFirst();
            for (String prop : proplist) {
                oechem.OEDeleteSDData(mol, prop);
            }
            oechem.OEWriteMolecule(ofs, mol);
        }
    }

    public static void modProps(OEInterface itf,
            oemolistream ifs,
            oemolostream ofs) {
        if (itf.HasString("-keep")) {
            OEStringIter proplist = itf.GetStringList("-keep");
            keepProps(proplist, ifs, ofs);
        }
        else if (itf.HasString("-remove")) {
            OEStringIter proplist = itf.GetStringList("-remove");
            removeProps(proplist, ifs, ofs);
        }
        else if (itf.GetBool("-clearAll")) {
            clearProps(ifs, ofs);
        }
    }

    public static void main(String argv[]) {
        URL fileURL = SDFModProps.class.getResource("SDFModProps.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "SDFModProps", argv);

            int numoption = 0;
            if (itf.HasString("-keep")) {
                numoption++;
            }
            if (itf.HasString("-remove")) {
                numoption++;
            }
            if (itf.GetBool("-clearAll")) {
                numoption++;
            }
            if (numoption != 1) {
                oechem.OEThrow.Usage("Need to pick one from -keep, -remove, or -clearAll");
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }
            if (!oechem.OEIsSDDataFormat(ifs.GetFormat()))
            {
                oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)");
            }

            oemolostream ofs = new oemolostream();
            if (!ofs.open(itf.GetString("-o"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
            }
            if (!oechem.OEIsSDDataFormat(ofs.GetFormat()))
            {
                oechem.OEThrow.Fatal("Only works for output file formats that support SD data (sdf,oeb,csv)");
            }

            modProps(itf, ifs, ofs);
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Exporting SD data to a csv file

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Extract properties from SD file and save as CSV
 ****************************************************************************/
package openeye.examples.oechem;

import java.io.PrintStream;
import java.util.ArrayList;
import openeye.oechem.*;

public class SDF2CSV {

    public static void sdf2CSV(oemolistream ifs,
            PrintStream csv) {
        ArrayList<String> tagList = new ArrayList<String>();
        OEGraphMol mol = new OEGraphMol();
        // read through once to find all unique tags
        while (oechem.OEReadMolecule(ifs, mol)) {
            for (OESDDataPair dp : oechem.OEGetSDDataPairs(mol)) {
                if (!tagList.contains(dp.GetTag())) {
                    tagList.add(dp.GetTag());
                }
            }
        }

        // output the header row
        csv.print("Title");
        for (String tag : tagList) {
            csv.printf(",%s", tag);
        }
        csv.println();

        // read through again filling rows for each molecule
        ifs.rewind();
        while (oechem.OEReadMolecule(ifs, mol)) {
            csv.printf("%s", mol.GetTitle());
            for (String tag : tagList) {
                csv.printf(",%s", oechem.OEGetSDData(mol, tag));
            }
            csv.println();
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 2) {
            oechem.OEThrow.Usage("SDF2CSV <infile> <csvfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
        int fmt = ifs.GetFormat();
        if (fmt != OEFormat.SDF && fmt != OEFormat.OEB) {
            oechem.OEThrow.Fatal("Only works for sdf or oeb input files");
        }

        PrintStream csv;
        try {
            csv = new PrintStream(argv[1]);
            sdf2CSV(ifs, csv);
            csv.close();
            ifs.close();
        }
        catch(java.io.IOException e) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
        }
    }
}

See also

Adding csv data as SD tags

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Merge a CSV file of data/properties, key on compound name in first column
 * and use column titles as keys.  All data is read/written as strings
 ****************************************************************************/
package openeye.examples.oechem;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
import openeye.oechem.*;

public class CSV2SDF {

    public static void csv2SDF(BufferedReader csv,
            oemolistream ifs,
            oemolostream ofs) {
        try {
            String line = csv.readLine();
            String[] propNames = line.split(",");
            List<String> propNamesList = new LinkedList<String>(Arrays.asList(propNames));
            propNamesList.remove(0);
            Map<String, List<String>> values = new HashMap<String, List<String>>();
            while ( (line = csv.readLine()) != null ) {
                String[] tokens = line.split(",");
                List<String> tokenList = new LinkedList<String>(Arrays.asList(tokens));
                if (tokenList.size() > 1) {
                    String title = tokenList.get(0);
                    if (title == null || title.equals("")) {
                        oechem.OEThrow.Warning("Skipping entry with no title");
                        continue;
                    }
                    tokenList.remove(0);
                    values.put(title, tokenList);
                }
            }

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                if (values.containsKey(mol.GetTitle())) {
                    List<String> valList = values.get(mol.GetTitle());
                    for (int p = 0; p < valList.size() && p < propNamesList.size(); ++p) {
                        String sdVal = valList.get(p);
                        if (sdVal == null || sdVal.equals("")) {
                            continue;
                        }
                        else {
                            oechem.OESetSDData(mol, propNamesList.get(p), sdVal);
                        }
                    }
                }
                oechem.OEWriteMolecule(ofs, mol);
            }
        }
        catch(java.io.IOException e) {
            oechem.OEThrow.Fatal("Failed to read from csv file");
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 3) {
            oechem.OEThrow.Usage("CSV2SDF <csvfile> <infile> <outsdfile>");
        }

        try {
            BufferedReader csv = new BufferedReader(new FileReader(argv[0]));

            oemolistream ifs = new oemolistream();
            if (!ifs.open(argv[1])) {
                oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
            }

            oemolostream ofs = new oemolostream();
            if (!ofs.open(argv[2])) {
                oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
            }
            int fmt = ofs.GetFormat();
            if (fmt != OEFormat.SDF && fmt != OEFormat.OEB) {
                oechem.OEThrow.Fatal("Only works for sdf or oeb output files");
            }

            csv2SDF(csv, ifs, ofs);
            ifs.close();
            ofs.close();
        }
        catch(java.io.IOException e) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }
    }
}

See also

Renaming molecules by SD field

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Rename SDF molecules by specified field
 ****************************************************************************/
package openeye.examples.oechem;

import openeye.oechem.*;

public class SDFRename {

    public static void processFile(String field, oemolistream ifs, oemolostream ofs) {
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            if (oechem.OEHasSDData(mol, field)) {
                mol.SetTitle(oechem.OEGetSDData(mol, field));
            }
            else {
                oechem.OEThrow.Warning("Renaming of molecule " + mol.GetTitle() + " failed; no field " + field);
            }

            oechem.OEWriteMolecule(ofs, mol);
        }
    }

    public static void main(String argv[]) {
        if (argv.length != 3) {
            oechem.OEThrow.Usage("SDFRename <fieldname> <infile> <outfile>");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[1])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for reading");
        }

        if (!oechem.OEIsSDDataFormat(ifs.GetFormat()))
        {
            oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)");
        }

        oemolostream ofs = new oemolostream();
        if (!ofs.open(argv[2])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[2] + " for writing");
        }

        processFile(argv[0], ifs, ofs);
        ifs.close();
        ofs.close();
    }
}

See also

Filter molecules by SD data

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Filter molecules by SD data
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import openeye.oechem.*;

public class SDFilter {

    public static void main(String argv[]) {
        URL fileURL = SDFilter.class.getResource("SDFilter.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "SDFilter", argv);
            if (!(itf.HasDouble("-min") || itf.HasDouble("-max"))) {
                oechem.OEThrow.Fatal("Please set a filter value with -min or -max");
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }
            if (!oechem.OEIsSDDataFormat(ifs.GetFormat()))
            {
                oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)");
            }

            oemolostream ofs = new oemolostream();
            if (!ofs.open(itf.GetString("-o"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
            }
            if (!oechem.OEIsSDDataFormat(ofs.GetFormat()))
            {
                oechem.OEThrow.Fatal("Only works for output file formats that support SD data (sdf,oeb,csv)");
            }

            String tag = itf.GetString("-tag");

            double minval = Double.MIN_VALUE;
            if (itf.HasDouble("-min")) {
                minval = itf.GetDouble("-min");
            }

            double maxval = Double.MAX_VALUE;
            if (itf.HasDouble("-max")) {
                maxval= itf.GetDouble("-max");
            }

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                if (!oechem.OEHasSDData(mol, tag)) {
                    oechem.OEThrow.Warning("Unable to find " + tag + " on " + mol.GetTitle());
                    continue;
                }
                double tagvalue;
                String value = oechem.OEGetSDData(mol, tag);
                try {
                    tagvalue = Double.valueOf(value.trim()).doubleValue();
                }
                catch (NumberFormatException nfe) {
                    oechem.OEThrow.Warning("Failed to convert (" + value + ") to a number in " + mol.GetTitle());
                    continue;
                }
                if (tagvalue < minval) {
                    continue;
                }
                if (tagvalue > maxval) {
                    continue;
                }

                oechem.OEWriteMolecule(ofs, mol);

            }
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Counting molecules

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Counts molecule (and conformers) in input files
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class MolCount {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void main(String argv[]) {
        URL fileURL = MolCount.class.getResource("MolCount.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "MolCount", argv);

            boolean confs = itf.GetBool("-conf");

            long total = 0;
            long totconfs = 0;
            long nfiles = 0;

            for (String filename : itf.GetStringList("-i")) {
                oemolistream ifs = new oemolistream();
                if (!ifs.open(filename)) {
                    oechem.OEThrow.Warning("Unable to open " + filename + " for reading");
                    continue;
                }
                else {
                    nfiles++;
                    long count = 0;
                    long nconfs = 0;

                    OEMol mol = new OEMol();
                    while (oechem.OEReadMolecule(ifs, mol)) {
                        count++;
                        if (confs) {
                            nconfs += mol.NumConfs();
                        }
                    }
                    ifs.close();
                    System.out.println(filename + " contains " + count + " molecule(s).");
                    if (confs) {
                        System.out.println("Total # of conformers:   " + nconfs);
                        System.out.println("Average # of conformers: " + (float)nconfs / (float)count);
                        System.out.println("-----------------------------------------------------------");
                    }

                    total += count;
                    totconfs += nconfs;
                }
            }
            System.out.println("===========================================================");
            System.out.println("Total " + total + " molecules");
            if (confs && (nfiles > 0) ) {
                System.out.println("Total # of conformers:   " + totconfs);
                System.out.println("Average # of conformers: " + (float)totconfs / (float)total);
            }
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Get molecule titles

/****************************************************************************
 * Copyright 2004-2013 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Output all molecule titles
 ****************************************************************************/
package openeye.examples.oechem;

import java.io.*;
import openeye.oechem.*;

public class GetTitles {
    static { 
        oechem.OEThrow.SetStrict(true);
    }

    public static void main(String argv[]) {
        if (argv.length != 1 && argv.length != 2) {
            oechem.OEThrow.Usage("GetTitles <infile> [<outfile>]");
        }

        oemolistream ifs = new oemolistream();
        if (!ifs.open(argv[0])) {
            oechem.OEThrow.Fatal("Unable to open " + argv[0] + " for reading");
        }

        PrintStream out = System.out;
        if (argv.length > 1) {
            try {
                out = new PrintStream(argv[1]);
            }
            catch(java.io.IOException e) {
                oechem.OEThrow.Fatal("Unable to open " + argv[1] + " for writing");
            }
        }
        OEMol mol = new OEMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            String title = mol.GetTitle();
            if (title == null || title.equals("")) {
                title = "untitled";
            }
            out.println(title);
        }
        ifs.close();
    }
}

See also

Find minimum path in a molecule

/****************************************************************************
 * Copyright 2004-2014 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Find the minimum path length between 2 smarts patterns
 * or the path length between 2 named atoms
 ****************************************************************************/
package openeye.examples.oechem;

import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import java.util.HashSet;
import java.net.URL;
import openeye.oechem.*;

public class MinPath {

    private static class Pair<L,R> {

        private final L left;
        private final R right;

        public Pair(L left, R right) {
            this.left = left;
            this.right = right;
        }

        public L getLeft() {
            return left;
        }
        public R getRight() {
            return right;
        }

        public int hashCode() {
            return left.hashCode() ^ right.hashCode();
        }

        public boolean equals(Object o) {
            if (o == null) return false;
            if (!(o instanceof Pair)) return false;
            Pair pairo = (Pair) o;
            return this.left.equals(pairo.getLeft()) &&
                    this.right.equals(pairo.getRight());
        }
    }

    public static void AtomPathLength(oemolistream ifs, oemolostream ofs,
            OEInterface itf,
            String atm1, String atm2) {

        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OETriposAtomNames(mol);

            OEAtomBase a1 = null;
            OEAtomBase a2 = null;
            for (OEAtomBase atm : mol.GetAtoms()) {
                if (atm1.equals(atm.GetName())) {
                    a1 = atm;
                }
                if (atm2.equals(atm.GetName())) {
                    a2 = atm;
                }
                if (a1 != null && a2 != null) {
                    break;
                }
            }
            if (a1 == null || a2 == null) {
                oechem.OEThrow.Warning("Failed to find atoms " + atm1 + " and " + atm2 + " in molecule");
                continue;
            }

            int pathlen = oechem.OEGetPathLength(a1, a2);
            if (itf.GetBool("-verbose") || !itf.HasString("-o"))
            {
                String smiles = oechem.OECreateIsoSmiString(mol);
                System.out.println("Path length: " + pathlen + " in " + smiles);
            }

            OEAtomBaseIter spath = oechem.OEShortestPath(a1, a2);
            OEGraphMol spathmol = new OEGraphMol();
            boolean adjustHCount = true;
            oechem.OESubsetMol(spathmol, mol, new OEIsAtomMember(spath), adjustHCount);
            String spathsmiles = oechem.OECreateIsoSmiString(spathmol);

            if (itf.HasString("-o")) {
                oechem.OEWriteMolecule(ofs, spathmol);
            }
            else if (itf.GetBool("-verbose")) {
                System.out.println(spathsmiles);
            }
        }
    }

    public static void SmartsPathLength(oemolistream ifs, oemolostream ofs,
            OEInterface itf, OESubSearch ss1, OESubSearch ss2) {
        OEGraphMol mol = new OEGraphMol();
        while (oechem.OEReadMolecule(ifs, mol)) {
            oechem.OEPrepareSearch(mol, ss1);
            oechem.OEPrepareSearch(mol, ss2);
            if (!(ss1.SingleMatch(mol) && ss2.SingleMatch(mol))) {
                oechem.OEThrow.Warning("Unable to find SMARTS matches in "
                        + mol.GetTitle() + ", skipping");
                continue;
            }

            List<Pair> allatompairs = new LinkedList<Pair>();
            boolean unique = true;
            int allminlen = Integer.MAX_VALUE;
            for (OEMatchBase match1 : ss1.Match(mol, unique)) {
                for (OEMatchBase match2 : ss2.Match(mol, unique)) {
                    List<Pair> atompairs = new LinkedList<Pair>();
                    int minlen = Integer.MAX_VALUE;
                    for (OEMatchPairAtom mp1 : match1.GetAtoms()) {
                        for (OEMatchPairAtom mp2 : match2.GetAtoms()) {
                            int pathlen = oechem.OEGetPathLength(mp1.getTarget(), mp2.getTarget());
                            if (minlen > pathlen) {
                                minlen = pathlen;
                                atompairs.clear();
                                atompairs.add(new Pair<OEAtomBase, OEAtomBase>(mp1.getTarget(), mp2.getTarget()));
                            }
                            else if (minlen == pathlen) {
                                atompairs.add(new Pair<OEAtomBase, OEAtomBase>(mp1.getTarget(), mp2.getTarget()));
                            }
                        }
                    }
                    if (minlen < allminlen) {
                        allminlen = minlen;
                        allatompairs = atompairs;
                    }
                    else if (minlen == allminlen) {
                        allatompairs.addAll(atompairs);
                    }
                }
            }

            if (itf.GetBool("-verbose") || !itf.HasString("-o"))
            {
                System.out.println("Shortest path length: " + allminlen + " in " + oechem.OECreateIsoSmiString(mol));
            }

            Set<String> spathlist = new HashSet<String>();
            for (Pair pair : allatompairs) {
                OEAtomBaseIter spath = oechem.OEShortestPath((OEAtomBase)pair.getLeft(), (OEAtomBase)pair.getRight());
                OEGraphMol spathmol = new OEGraphMol();
                oechem.OESubsetMol(spathmol, mol, new OEIsAtomMember(spath));
                String spathsmiles = oechem.OECreateIsoSmiString(spathmol);
                if (!spathlist.add(spathsmiles)) {
                    continue;
                }
                if (itf.HasString("-o")) {
                    oechem.OEWriteMolecule(ofs, spathmol);
                }
                else if (itf.GetBool("-verbose")) {
                    System.out.println(spathsmiles);
                }
            }
        }
    }

    public static void main(String argv[]) {
        URL fileURL = MinPath.class.getResource("MinPath.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "MinPath", argv);

            if (!((itf.HasString("-smarts1") && itf.HasString("-smarts2"))
                    ^ (itf.HasString("-atom1") && itf.HasString("-atom2")))) {
                oechem.OEThrow.Fatal("-smarts1 and -smarts2 or -atom1 and -atom2 must be set");
            }

            oemolistream ifs = new oemolistream();
            if (!ifs.open(itf.GetString("-i"))) {
                oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-i") + " for reading");
            }

            oemolostream ofs = new oemolostream();
            if (itf.HasString("-o")) {
                if (!ofs.open(itf.GetString("-o"))) {
                    oechem.OEThrow.Fatal("Unable to open " + itf.GetString("-o") + " for writing");
                }
            }

            if (itf.HasString("-smarts1") && itf.HasString("-smarts2")) {
                OESubSearch ss1 = new OESubSearch();
                String smarts1 = itf.GetString("-smarts1");
                if (!ss1.Init(smarts1)) {
                    oechem.OEThrow.Fatal("Unable to parse SMARTS1: " + smarts1);
                }

                OESubSearch ss2 = new OESubSearch();
                String smarts2 = itf.GetString("-smarts2");
                if (!ss2.Init(smarts2)) {
                    oechem.OEThrow.Fatal("Unable to parse SMARTS2: " + smarts2);
                }

                SmartsPathLength(ifs, ofs, itf, ss1, ss2);
                ifs.close();
                ofs.close();
            }
            else {
                String atom1 = itf.GetString("-atom1");
                String atom2 = itf.GetString("-atom2");
                AtomPathLength(ifs, ofs, itf, atom1, atom2);
            }
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

See also

Extract ring templates

/****************************************************************************
 * Copyright 2014 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Extract ring templates for 2D coordinate generation
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;
import openeye.oechem.*;

public class ExtractRingTemplates {

    public static void main(String argv[]) {
        URL fileURL = ExtractRingTemplates.class.getResource("ExtractRingTemplates.txt");
        try {
            OEInterface itf = new OEInterface(fileURL, "ExtractRingTemplates", argv);

            String ifname = itf.GetString("-in");
            String ofname = itf.GetString("-out");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(ifname))
                oechem.OEThrow.Fatal("Unable to open " + ifname + " for reading");

            if (!oechem.OEIs2DFormat(ifs.GetFormat()))
                oechem.OEThrow.Fatal("Invalid input format: need 2D coordinates");

            oemolostream ofs = new oemolostream();
            if (!ofs.open(ofname))
                oechem.OEThrow.Fatal("Unable to open " + ofname + " for writing");

            if (!oechem.OEIs2DFormat(ofs.GetFormat()))
                oechem.OEThrow.Fatal("Invalid output format: unable to write 2D coordinates");

            int nrrings = 0;
            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                for (OEMolBase ring : oechem.OEExtractRingTemplates(mol)) {
                    nrrings++; 
                    oechem.OEWriteMolecule(ofs, ring);
                }
            }  
            oechem.OEThrow.Info(nrrings + " number of ring templates extracted");
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Create 2D ring dictionary

/****************************************************************************
 * Copyright 2015 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Creates a new 2D ring dictionary
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;

import openeye.oechem.*;

public class CreateRingDict {

    public static void main(String argv[]) {
        URL fileURL = CreateRingDict.class.getResource("CreateRingDict.txt");
        try {
            OEInterface itf = new OEInterface();
            oechem.OEConfigureFromURL(itf, fileURL);

            if (!oechem.OEParseCommandLine(itf, argv, "CreateRingDict"))
                oechem.OEThrow.Fatal("Unable to interpret command line!");

            String ifname = itf.GetString("-in");
            String ofname = itf.GetString("-ringdict");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(ifname))
                oechem.OEThrow.Fatal("Cannot open input file for reading!");

            if (!oechem.OEIs2DFormat(ifs.GetFormat()))
                oechem.OEThrow.Fatal("Invalid input file format for 2D coordinates!");

            oemolostream ofs = new oemolostream();
            if (!ofs.open(ofname))
                oechem.OEThrow.Fatal("Unable to open output file for writing!");

            if (ofs.GetFormat() != OEFormat.OEB)
                oechem.OEThrow.Fatal("Output file has to have OEB format!");

            OE2DRingDictionary ringdict = new OE2DRingDictionary();

            OEDots dots = new OEDots(10000, 100, "molecules");

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                dots.Update();
                ringdict.AddRings(mol);
            }

            dots.Total();

            int nrrings = ringdict.NumRings();
            oechem.OEThrow.Info(Integer.toString(nrrings) + " number of ring templates have been extracted!");

            oechem.OEWrite2DRingDictionary(ofname, ringdict);

            ifs.close();

        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Append to 2D ring dictionary

/****************************************************************************
 * Copyright 2015, 2016 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Appends rings to an existing 2D rings dictionary
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;

import openeye.oechem.*;

public class AppendRingDict {

    public static void main(String argv[]) {
        URL fileURL = AppendRingDict.class.getResource("AppendRingDict.txt");
        try {
            OEInterface itf = new OEInterface();
            oechem.OEConfigureFromURL(itf, fileURL);

            if (!oechem.OEParseCommandLine(itf, argv, "AppendRingDict"))
                oechem.OEThrow.Fatal("Unable to interpret command line!");

            String ifname = itf.GetString("-in");
            String irdfname = itf.GetString("-inringdict");
            String ordfname = itf.GetString("-outringdict");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(ifname))
                oechem.OEThrow.Fatal("Cannot open input file for reading!");

            if (!oechem.OEIs2DFormat(ifs.GetFormat()))
                oechem.OEThrow.Fatal("Invalid input file format for 2D coordinates!");

            if (!oechem.OEIsValid2DRingDictionary(irdfname))
                oechem.OEThrow.Fatal("Invalid ring dictionary file!");

            OE2DRingDictionary ringdict = new OE2DRingDictionary(irdfname);

            int nrrings = ringdict.NumRings();

            OEDots dots = new OEDots(10000, 100, "molecules");

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                dots.Update();
                ringdict.AddRings(mol);
            }

            dots.Total();

            int nrnewrings = ringdict.NumRings() - nrrings;
            oechem.OEThrow.Info(Integer.toString(nrnewrings) + " new ring templates have been added!");

            oechem.OEWrite2DRingDictionary(ordfname, ringdict);

            ifs.close();

        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}

Generate 2D coordinates with user-defined ring templates

/****************************************************************************
 * Copyright 2015 OpenEye Scientific Software, Inc.
 *****************************************************************************
 * Generates 2D coordinates using user-defined ring templates
 ****************************************************************************/
package openeye.examples.oechem;

import java.net.URL;
import java.util.*;

import openeye.oechem.*;

public class Generate2D {

    public static void main(String argv[]) {
        URL fileURL = Generate2D.class.getResource("Generate2D.txt");
        try {
            OEInterface itf = new OEInterface();
            oechem.OEConfigureFromURL(itf, fileURL);

            if (!oechem.OEParseCommandLine(itf, argv, "Generate2D"))
                oechem.OEThrow.Fatal("Unable to interpret command line!");

            String ifname = itf.GetString("-in");
            String ofname = itf.GetString("-out");

            oemolistream ifs = new oemolistream();
            if (!ifs.open(ifname))
                oechem.OEThrow.Fatal("Cannot open input file for reading!");

            oemolostream ofs = new oemolostream();
            if (!ofs.open(ofname))
                oechem.OEThrow.Fatal("Cannot open output file for writing!");

            if (!oechem.OEIs2DFormat(ofs.GetFormat()))
                oechem.OEThrow.Fatal("Invalid output file format for 2D coordinates!");

            if (itf.HasString("-ringdict")) {
                String rdfname = itf.GetString("-ringdict");

                if (!oechem.OEIsValid2DRingDictionary(rdfname))
                    oechem.OEThrow.Warning("Invalid 2D ring dictionary file!");
                else
                    oechem.OEInit2DRingDictionary(rdfname);
            }

            OEGraphMol mol = new OEGraphMol();
            while (oechem.OEReadMolecule(ifs, mol)) {
                oechem.OEGenerate2DCoordinates(mol);
                oechem.OEWriteMolecule(ofs, mol);
            }
            ifs.close();
            ofs.close();
        }
        catch (java.io.IOException e) {
            System.err.println("Unable to open interface file");
        }
    }
}