Search in sources :

Example 1 with AtomTypeFactory

use of org.openscience.cdk.config.AtomTypeFactory in project ambit-mirror by ideaconsult.

the class AtomEnvironmentMatrixDescriptor method setParameters.

/**
 * Sets the parameters attribute of the AtomEnvironmentDescriptor object
 *
 * @param params
 *            - parameters, as below params[0] MaxLevel, optional , default
 *            3 params[1] perceiveCyclicAtoms, optional , default false
 *            params[2] AtomTypeFactory factory, optional, default
 *            AtomTypeFactory.getInstance(
 *            "org/openscience/cdk/dict/data/sybyl-atom-types.owl")
 *            params[3] AtomTypeMatcher atm, optional , default
 *            HybridizationStateATMatcher
 */
public void setParameters(Object[] allParams) throws CDKException {
    AtomTypeFactory afactory = null;
    IAtomTypeMatcher amatcher = null;
    for (int i = 0; i < allParams.length; i++) {
        switch(i) {
            case 0:
                {
                    if (!(allParams[i] instanceof Integer))
                        throw new CDKException(String.format("The %d parameter must be of type Integer", i + 1));
                    setMaxLevel(((Integer) allParams[i]).intValue());
                    break;
                }
            case 1:
                {
                    if (!(allParams[i] instanceof Boolean))
                        throw new CDKException(String.format("The %d parameter must be of type AtomTypeFactory", i + 1));
                    afactory = (AtomTypeFactory) allParams[i];
                    break;
                }
            case 2:
                {
                    if (!(allParams[i] instanceof Boolean))
                        throw new CDKException(String.format("The %d parameter must be of type IAtomTypeMatcher", i + 1));
                    amatcher = (IAtomTypeMatcher) allParams[i];
                    break;
                }
            default:
                {
                    throw new CDKException(String.format("%s only expects %d parameters", getClass().getName(), allParams.length));
                }
        }
    }
    ;
    try {
        descriptorNames = initAtomTypes(afactory, amatcher);
    } catch (Exception x) {
        throw new CDKException(x.getMessage());
    }
}
Also used : CDKException(org.openscience.cdk.exception.CDKException) AtomTypeFactory(org.openscience.cdk.config.AtomTypeFactory) IAtomTypeMatcher(org.openscience.cdk.atomtype.IAtomTypeMatcher) CDKException(org.openscience.cdk.exception.CDKException)

Example 2 with AtomTypeFactory

use of org.openscience.cdk.config.AtomTypeFactory in project ambit-mirror by ideaconsult.

the class CdkJmolAdapter method openBufferedReader.

/* **************************************************************
	 * the file related methods
	 * **************************************************************/
public Object openBufferedReader(String name, BufferedReader bufferedReader) {
    IChemFile chemFile = null;
    try {
        ISimpleChemObjectReader chemObjectReader = null;
        try {
            chemObjectReader = new ReaderFactory().createReader(bufferedReader);
        } catch (IOException ex) {
            return "Jmol: Error determining input format: " + ex;
        }
        if (chemObjectReader == null) {
            return "Jmol: unrecognized input format";
        }
        chemFile = (IChemFile) chemObjectReader.read(new org.openscience.cdk.ChemFile());
    } catch (CDKException ex) {
        return "Error reading input:" + ex;
    }
    if (chemFile == null)
        return "unknown error reading file";
    try {
        AtomTypeFactory factory = AtomTypeFactory.getInstance("pdb_atomtypes.txt", chemFile.getBuilder());
        // IAtomContainer atomContainer = (IAtomContainer)ChemFileManipulator.getAllInOneContainer(chemFile);
        Iterator<IChemSequence> seq = chemFile.chemSequences().iterator();
        while (seq.hasNext()) {
            Iterator<IChemModel> model = seq.next().chemModels().iterator();
            while (model.hasNext()) {
                Iterator<IAtomContainer> c = model.next().getMoleculeSet().atomContainers().iterator();
                while (c.hasNext()) {
                    Iterator<IAtom> it = c.next().atoms().iterator();
                    while (it.hasNext()) {
                        IAtom atom = it.next();
                        try {
                            factory.configure(atom);
                        } catch (CDKException exception) {
                            bcLogger.severe("Could not configure atom: " + atom);
                            bcLogger.log(Level.SEVERE, "  because: " + exception.getMessage(), exception);
                        }
                    }
                }
            }
        }
        return chemFile;
    } catch (Exception x) {
        return "Error configuring atoms input:" + x;
    }
}
Also used : IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) CDKException(org.openscience.cdk.exception.CDKException) IChemFile(org.openscience.cdk.interfaces.IChemFile) ReaderFactory(org.openscience.cdk.io.ReaderFactory) IChemModel(org.openscience.cdk.interfaces.IChemModel) IOException(java.io.IOException) AtomTypeFactory(org.openscience.cdk.config.AtomTypeFactory) CDKException(org.openscience.cdk.exception.CDKException) IOException(java.io.IOException) ISimpleChemObjectReader(org.openscience.cdk.io.ISimpleChemObjectReader) IChemSequence(org.openscience.cdk.interfaces.IChemSequence) IAtom(org.openscience.cdk.interfaces.IAtom)

Example 3 with AtomTypeFactory

use of org.openscience.cdk.config.AtomTypeFactory in project cdk by cdk.

the class Mol2Reader method readMolecule.

/**
 * Read a Reaction from a file in MDL RXN format
 *
 * @return The Reaction that was read from the MDL file.
 */
private IAtomContainer readMolecule(IAtomContainer molecule) throws CDKException {
    AtomTypeFactory atFactory;
    try {
        atFactory = AtomTypeFactory.getInstance("org/openscience/cdk/config/data/mol2_atomtypes.xml", molecule.getBuilder());
    } catch (Exception exception) {
        String error = "Could not instantiate an AtomTypeFactory";
        logger.error(error);
        logger.debug(exception);
        throw new CDKException(error, exception);
    }
    try {
        int atomCount;
        int bondCount;
        String line;
        while (true) {
            line = input.readLine();
            if (line == null)
                return null;
            if (line.startsWith("@<TRIPOS>MOLECULE"))
                break;
            if (!line.startsWith("#") && line.trim().length() > 0)
                break;
        }
        // ok, if we're coming from the chemfile functoion, we've alreay read the molecule RTI
        if (firstLineisMolecule)
            molecule.setTitle(line);
        else {
            line = input.readLine();
            molecule.setTitle(line);
        }
        // get atom and bond counts
        String counts = input.readLine();
        StringTokenizer tokenizer = new StringTokenizer(counts);
        try {
            atomCount = Integer.parseInt(tokenizer.nextToken());
        } catch (NumberFormatException nfExc) {
            String error = "Error while reading atom count from MOLECULE block";
            logger.error(error);
            logger.debug(nfExc);
            throw new CDKException(error, nfExc);
        }
        if (tokenizer.hasMoreTokens()) {
            try {
                bondCount = Integer.parseInt(tokenizer.nextToken());
            } catch (NumberFormatException nfExc) {
                String error = "Error while reading atom and bond counts";
                logger.error(error);
                logger.debug(nfExc);
                throw new CDKException(error, nfExc);
            }
        } else {
            bondCount = 0;
        }
        logger.info("Reading #atoms: ", atomCount);
        logger.info("Reading #bonds: ", bondCount);
        // we skip mol type, charge type and status bit lines
        logger.warn("Not reading molecule qualifiers");
        line = input.readLine();
        boolean molend = false;
        while (line != null) {
            if (line.startsWith("@<TRIPOS>MOLECULE")) {
                molend = true;
                break;
            } else if (line.startsWith("@<TRIPOS>ATOM")) {
                logger.info("Reading atom block");
                for (int i = 0; i < atomCount; i++) {
                    line = input.readLine().trim();
                    if (line.startsWith("@<TRIPOS>MOLECULE")) {
                        molend = true;
                        break;
                    }
                    tokenizer = new StringTokenizer(line);
                    // disregard the id token
                    tokenizer.nextToken();
                    String nameStr = tokenizer.nextToken();
                    String xStr = tokenizer.nextToken();
                    String yStr = tokenizer.nextToken();
                    String zStr = tokenizer.nextToken();
                    String atomTypeStr = tokenizer.nextToken();
                    // replace unrecognised atom type
                    if (ATOM_TYPE_ALIASES.containsKey(atomTypeStr))
                        atomTypeStr = ATOM_TYPE_ALIASES.get(atomTypeStr);
                    IAtom atom = molecule.getBuilder().newInstance(IAtom.class);
                    IAtomType atomType;
                    try {
                        atomType = atFactory.getAtomType(atomTypeStr);
                    } catch (Exception exception) {
                        // ok, *not* an mol2 atom type
                        atomType = null;
                    }
                    // Maybe it is just an element
                    if (atomType == null && isElementSymbol(atomTypeStr)) {
                        atom.setSymbol(atomTypeStr);
                    } else {
                        if (atomType == null) {
                            atomType = atFactory.getAtomType("X");
                            logger.error("Could not find specified atom type: ", atomTypeStr);
                        }
                        AtomTypeManipulator.configure(atom, atomType);
                    }
                    atom.setAtomicNumber(Elements.ofString(atom.getSymbol()).number());
                    atom.setID(nameStr);
                    atom.setAtomTypeName(atomTypeStr);
                    try {
                        double x = Double.parseDouble(xStr);
                        double y = Double.parseDouble(yStr);
                        double z = Double.parseDouble(zStr);
                        atom.setPoint3d(new Point3d(x, y, z));
                    } catch (NumberFormatException nfExc) {
                        String error = "Error while reading atom coordinates";
                        logger.error(error);
                        logger.debug(nfExc);
                        throw new CDKException(error, nfExc);
                    }
                    molecule.addAtom(atom);
                }
            } else if (line.startsWith("@<TRIPOS>BOND")) {
                logger.info("Reading bond block");
                for (int i = 0; i < bondCount; i++) {
                    line = input.readLine();
                    if (line.startsWith("@<TRIPOS>MOLECULE")) {
                        molend = true;
                        break;
                    }
                    tokenizer = new StringTokenizer(line);
                    // disregard the id token
                    tokenizer.nextToken();
                    String atom1Str = tokenizer.nextToken();
                    String atom2Str = tokenizer.nextToken();
                    String orderStr = tokenizer.nextToken();
                    try {
                        int atom1 = Integer.parseInt(atom1Str);
                        int atom2 = Integer.parseInt(atom2Str);
                        if ("nc".equals(orderStr)) {
                        // do not connect the atoms
                        } else {
                            IBond bond = molecule.getBuilder().newInstance(IBond.class, molecule.getAtom(atom1 - 1), molecule.getAtom(atom2 - 1));
                            if ("1".equals(orderStr)) {
                                bond.setOrder(Order.SINGLE);
                            } else if ("2".equals(orderStr)) {
                                bond.setOrder(Order.DOUBLE);
                            } else if ("3".equals(orderStr)) {
                                bond.setOrder(Order.TRIPLE);
                            } else if ("am".equals(orderStr) || "ar".equals(orderStr)) {
                                bond.setOrder(Order.SINGLE);
                                bond.setFlag(CDKConstants.ISAROMATIC, true);
                                bond.getBegin().setFlag(CDKConstants.ISAROMATIC, true);
                                bond.getEnd().setFlag(CDKConstants.ISAROMATIC, true);
                            } else if ("du".equals(orderStr)) {
                                bond.setOrder(Order.SINGLE);
                            } else if ("un".equals(orderStr)) {
                                bond.setOrder(Order.SINGLE);
                            }
                            molecule.addBond(bond);
                        }
                    } catch (NumberFormatException nfExc) {
                        String error = "Error while reading bond information";
                        logger.error(error);
                        logger.debug(nfExc);
                        throw new CDKException(error, nfExc);
                    }
                }
            }
            if (molend)
                return molecule;
            line = input.readLine();
        }
    } catch (IOException exception) {
        String error = "Error while reading general structure";
        logger.error(error);
        logger.debug(exception);
        throw new CDKException(error, exception);
    }
    return molecule;
}
Also used : IAtomType(org.openscience.cdk.interfaces.IAtomType) CDKException(org.openscience.cdk.exception.CDKException) IBond(org.openscience.cdk.interfaces.IBond) AtomTypeFactory(org.openscience.cdk.config.AtomTypeFactory) IOException(java.io.IOException) CDKException(org.openscience.cdk.exception.CDKException) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) Point3d(javax.vecmath.Point3d) IAtom(org.openscience.cdk.interfaces.IAtom)

Example 4 with AtomTypeFactory

use of org.openscience.cdk.config.AtomTypeFactory in project cdk by cdk.

the class StructGenMatcherTest method utestCountTestedAtomTypes.

/**
 * The test seems to be run by JUnit in order in which they found
 * in the source. Ugly, but @AfterClass does not work because that
 * methods does cannot assert anything.
 *
 * ...not anymore. Bad idea to do have such a test in the first place
 * but we can hack it by sorting by test name (see fix method order
 * annotation).
 */
@Test
public void utestCountTestedAtomTypes() {
    AtomTypeFactory factory = AtomTypeFactory.getInstance("org/openscience/cdk/config/data/structgen_atomtypes.xml", SilentChemObjectBuilder.getInstance());
    IAtomType[] expectedTypes = factory.getAllAtomTypes();
    if (expectedTypes.length != testedAtomTypes.size()) {
        String errorMessage = "Atom types not tested:";
        for (IAtomType expectedType : expectedTypes) {
            if (!testedAtomTypes.containsKey(expectedType.getAtomTypeName()))
                errorMessage += " " + expectedType.getAtomTypeName();
        }
        Assert.assertEquals(errorMessage, factory.getAllAtomTypes().length, testedAtomTypes.size());
    }
}
Also used : IAtomType(org.openscience.cdk.interfaces.IAtomType) AtomTypeFactory(org.openscience.cdk.config.AtomTypeFactory) Test(org.junit.Test) AbstractAtomTypeTest(org.openscience.cdk.test.atomtype.AbstractAtomTypeTest)

Example 5 with AtomTypeFactory

use of org.openscience.cdk.config.AtomTypeFactory in project cdk by cdk.

the class BasicValidator method validateBondOrderSum.

// the Molecule tests
private ValidationReport validateBondOrderSum(IAtom atom, IAtomContainer molecule) {
    ValidationReport report = new ValidationReport();
    ValidationTest checkBondSum = new ValidationTest(atom, "The atom's total bond order is too high.");
    try {
        AtomTypeFactory structgenATF = AtomTypeFactory.getInstance("org/openscience/cdk/dict/data/cdk-atom-types.owl", atom.getBuilder());
        int bos = (int) molecule.getBondOrderSum(atom);
        IAtomType[] atomTypes = structgenATF.getAtomTypes(atom.getSymbol());
        if (atomTypes.length == 0) {
            checkBondSum.setDetails("Cannot validate bond order sum for atom not in valency atom type list: " + atom.getSymbol());
            report.addWarning(checkBondSum);
        } else {
            IAtomType failedOn = null;
            boolean foundMatchingAtomType = false;
            for (IAtomType type : atomTypes) {
                if (Objects.equals(atom.getFormalCharge(), type.getFormalCharge())) {
                    if (bos == type.getBondOrderSum()) {
                        foundMatchingAtomType = true;
                    // skip this atom type
                    } else {
                        failedOn = type;
                    }
                }
            }
            if (foundMatchingAtomType) {
                report.addOK(checkBondSum);
            } else {
                if (failedOn != null) {
                    checkBondSum.setDetails("Bond order exceeds the one allowed for atom " + atom.getSymbol() + " for which the total bond order is " + failedOn.getBondOrderSum());
                }
                report.addError(checkBondSum);
            }
        }
    } catch (Exception exception) {
        logger.error("Error while performing atom bos validation: ", exception.getMessage());
        logger.debug(exception);
    }
    return report;
}
Also used : IAtomType(org.openscience.cdk.interfaces.IAtomType) AtomTypeFactory(org.openscience.cdk.config.AtomTypeFactory)

Aggregations

AtomTypeFactory (org.openscience.cdk.config.AtomTypeFactory)16 IAtomType (org.openscience.cdk.interfaces.IAtomType)9 CDKException (org.openscience.cdk.exception.CDKException)7 Test (org.junit.Test)6 IAtom (org.openscience.cdk.interfaces.IAtom)6 IOException (java.io.IOException)4 IAtomContainer (org.openscience.cdk.interfaces.IAtomContainer)4 Point3d (javax.vecmath.Point3d)2 Ignore (org.junit.Ignore)2 IAtomTypeMatcher (org.openscience.cdk.atomtype.IAtomTypeMatcher)2 AbstractAtomTypeTest (org.openscience.cdk.test.atomtype.AbstractAtomTypeTest)2 AtomConfigurator (ambit2.core.processors.structure.AtomConfigurator)1 SmilesParserWrapper (ambit2.core.smiles.SmilesParserWrapper)1 AtomEnvironmentDescriptor (ambit2.descriptors.AtomEnvironmentDescriptor)1 InputStream (java.io.InputStream)1 StringTokenizer (java.util.StringTokenizer)1 Atom (org.openscience.cdk.Atom)1 AtomContainer (org.openscience.cdk.AtomContainer)1 ChemFile (org.openscience.cdk.ChemFile)1 ChemObject (org.openscience.cdk.ChemObject)1