Search in sources :

Example 6 with CDKException

use of org.openscience.cdk.exception.CDKException in project Smiles2Monomers by yoann-dufresne.

the class SmilesGenerator method createSMILESWithoutCheckForMultipleMolecules.

/**
 *  Generate canonical SMILES from the <code>molecule</code>. This method
 *  canonicaly lables the molecule but dose not perform any checks on the
 *  chemical validity of the molecule. Does not care about multiple molecules.
 *  IMPORTANT: A precomputed Set of All Rings (SAR) can be passed to this
 *  SmilesGenerator in order to avoid recomputing it. Use setRings() to
 *  assign the SAR.
 *
 * @param  molecule                 The molecule to evaluate.
 * @param  chiral                   true=SMILES will be chiral, false=SMILES
 *      will not be chiral.
 * @param  doubleBondConfiguration  Should E/Z configurations be read at these positions? If the flag at position X is set to true,
 *                                  an E/Z configuration will be written from coordinates around bond X, if false, it will be ignored.
 *                                  If flag is true for a bond which does not constitute a valid double bond configuration, it will be
 *                                  ignored (meaning setting all to true will create E/Z indication will be pu in the smiles wherever
 *                                  possible, but note the coordinates might be arbitrary).
 * @exception  CDKException         At least one atom has no Point2D;
 *      coordinates are needed for creating the chiral smiles. This excpetion
 *      can only be thrown if chiral smiles is created, ignore it if you want a
 *      non-chiral smiles (createSMILES(AtomContainer) does not throw an
 *      exception).
 *@see                             org.openscience.cdk.graph.invariant.CanonicalLabeler#canonLabel(IAtomContainer)
 * @return the SMILES representation of the molecule
 */
@TestMethod("testCreateSMILESWithoutCheckForMultipleMolecules_withDetectAromaticity,testCreateSMILESWithoutCheckForMultipleMolecules_withoutDetectAromaticity")
public synchronized String createSMILESWithoutCheckForMultipleMolecules(IAtomContainer molecule, boolean chiral, boolean[] doubleBondConfiguration) throws CDKException {
    if (molecule.getAtomCount() == 0) {
        return "";
    }
    canLabler.canonLabel(molecule);
    brokenBonds.clear();
    ringMarker = 0;
    IAtom start = null;
    for (int i = 0; i < molecule.getAtomCount(); i++) {
        IAtom atom = molecule.getAtom(i);
        if (chiral && atom.getPoint2d() == null) {
            throw new CDKException("Atom number " + i + " has no 2D coordinates, but 2D coordinates are needed for creating chiral smiles");
        }
        // logger.debug("Setting all VISITED flags to false");
        atom.setFlag(CDKConstants.VISITED, false);
        if ((Long) atom.getProperty("CanonicalLable") == 1) {
            start = atom;
        }
    }
    // detect aromaticity
    if (useAromaticityFlag || chiral) {
        if (rings == null) {
            if (ringFinder == null) {
                ringFinder = new AllRingsFinder();
            }
            rings = ringFinder.findAllRings(molecule);
        }
        AtomContainerManipulator.percieveAtomTypesAndConfigureAtoms(molecule);
        CDKHueckelAromaticityDetector.detectAromaticity(molecule);
    }
    if (chiral && rings.getAtomContainerCount() > 0) {
        List<?> v = RingPartitioner.partitionRings(rings);
        // logger.debug("RingSystems: " + v.size());
        for (int i = 0; i < v.size(); i++) {
            int counter = 0;
            Iterator<IAtomContainer> containers = RingSetManipulator.getAllAtomContainers((IRingSet) v.get(i)).iterator();
            while (containers.hasNext()) {
                IAtomContainer allrings = (IAtomContainer) containers.next();
                for (int k = 0; k < allrings.getAtomCount(); k++) {
                    if (!BondTools.isStereo(molecule, allrings.getAtom(k)) && hasWedges(molecule, allrings.getAtom(k)) != null) {
                        IBond bond = molecule.getBond(allrings.getAtom(k), hasWedges(molecule, allrings.getAtom(k)));
                        if (bond.getStereo() == IBond.Stereo.UP) {
                            allrings.getAtom(k).setProperty(RING_CONFIG, UP);
                        } else {
                            allrings.getAtom(k).setProperty(RING_CONFIG, DOWN);
                        }
                        counter++;
                    }
                }
                if (counter == 1) {
                    for (int k = 0; k < allrings.getAtomCount(); k++) {
                        IBond bond = molecule.getBond(allrings.getAtom(k), hasWedges(molecule, allrings.getAtom(k)));
                        if (bond != null) {
                            if (bond.getStereo() == IBond.Stereo.UP) {
                                allrings.getAtom(k).setProperty(RING_CONFIG, UP);
                            } else {
                                allrings.getAtom(k).setProperty(RING_CONFIG, DOWN);
                            }
                        }
                    }
                }
            }
        }
    }
    StringBuffer l = new StringBuffer();
    createSMILES(start, l, molecule, chiral, doubleBondConfiguration, useAromaticityFlag);
    rings = null;
    // remove all CanonicalLable/InvariancePair props
    for (int k = 0; k < molecule.getAtomCount(); k++) {
        molecule.getAtom(k).removeProperty("CanonicalLable");
        molecule.getAtom(k).removeProperty("InvariancePair");
    }
    return l.toString();
}
Also used : IAtomContainer(org.openscience.cdk.interfaces.IAtomContainer) CDKException(org.openscience.cdk.exception.CDKException) IRingSet(org.openscience.cdk.interfaces.IRingSet) IBond(org.openscience.cdk.interfaces.IBond) AllRingsFinder(org.openscience.cdk.ringsearch.AllRingsFinder) IAtom(org.openscience.cdk.interfaces.IAtom) TestMethod(org.openscience.cdk.annotations.TestMethod)

Example 7 with CDKException

use of org.openscience.cdk.exception.CDKException in project Smiles2Monomers by yoann-dufresne.

the class SmilesGenerator method parseAtom.

/**
 *  Generates the SMILES string for the atom
 *
 *@param  a                        the atom to generate the SMILES for.
 *@param  buffer                   the string buffer that the atom is to be
 *      apended to.
 *@param  container                the AtomContainer to analyze.
 *@param  chiral                   is a chiral smiles wished?
 *@param  parent                   the atom we came from.
 *@param  atomsInOrderOfSmiles     a vector containing the atoms in the order
 *      they are in the smiles.
 *@param  currentChain             The chain we currently deal with.
 *@param useAromaticity				true=aromaticity or sp2 will trigger lower case letters, wrong=only sp2
 */
private void parseAtom(IAtom a, StringBuffer buffer, IAtomContainer container, boolean chiral, boolean[] doubleBondConfiguration, IAtom parent, List<IAtom> atomsInOrderOfSmiles, List<Object> currentChain, boolean useAromaticity) {
    if (!"H".equals(a.getSymbol()))
        this.order.add(a);
    String symbol = a.getSymbol();
    if (a instanceof PseudoAtom)
        symbol = "*";
    boolean stereo = false;
    if (chiral)
        stereo = BondTools.isStereo(container, a);
    boolean brackets = symbol.equals("B") || symbol.equals("C") || symbol.equals("N") || symbol.equals("O") || symbol.equals("P") || symbol.equals("S") || symbol.equals("F") || symbol.equals("Br") || symbol.equals("I") || symbol.equals("Cl");
    brackets = !brackets;
    // Deal with the start of a double bond configuration
    if (chiral && isStartOfDoubleBond(container, a, parent, doubleBondConfiguration)) {
        buffer.append('/');
    }
    String mass = generateMassString(a);
    brackets = brackets | !mass.equals("");
    String charge = generateChargeString(a);
    brackets = brackets | !charge.equals("");
    // we put in a special check for N.planar3 cases such
    // as for indole and pyrrole, which require an explicit
    // H on the nitrogen. However this only makes sense when
    // the connectivity is not 3 - so for a case such as n1ncn(c1)CC
    // the PLANAR3 N already has 3 bonds, so don't add a H for this case
    boolean isSpecialNitrogen = a.getSymbol().equals("N") && a.getHybridization() == IAtomType.Hybridization.PLANAR3 && container.getConnectedAtomsList(a).size() != 3 && (a.getFormalCharge() == null || a.getFormalCharge() == 0);
    brackets = brackets | isSpecialNitrogen;
    if (chiral && stereo && (BondTools.isTrigonalBipyramidalOrOctahedral(container, a) != 0 || BondTools.isSquarePlanar(container, a) || BondTools.isTetrahedral(container, a, false) != 0 || BondTools.isSquarePlanar(container, a))) {
        brackets = true;
    }
    if (brackets) {
        buffer.append('[');
    }
    buffer.append(mass);
    if ((useAromaticity && a.getFlag(CDKConstants.ISAROMATIC))) {
        // the PLANAR3 N already has 3 bonds, so don't add a H for this case
        if (isSpecialNitrogen) {
            buffer.append(a.getSymbol().toLowerCase()).append("H");
        } else
            buffer.append(a.getSymbol().toLowerCase());
    } else {
        buffer.append(symbol);
        if (symbol.equals("*") && a.getImplicitHydrogenCount() != null && a.getImplicitHydrogenCount() > 0)
            buffer.append("H").append(a.getImplicitHydrogenCount());
    }
    if (a.getProperty(RING_CONFIG) != null && a.getProperty(RING_CONFIG).equals(UP)) {
        buffer.append('/');
    }
    if (a.getProperty(RING_CONFIG) != null && a.getProperty(RING_CONFIG).equals(DOWN)) {
        buffer.append('\\');
    }
    if (chiral && stereo && (BondTools.isTrigonalBipyramidalOrOctahedral(container, a) != 0 || BondTools.isSquarePlanar(container, a) || BondTools.isTetrahedral(container, a, false) != 0)) {
        buffer.append('@');
    }
    if (chiral && stereo && BondTools.isSquarePlanar(container, a)) {
        buffer.append("SP1");
    }
    // chiral
    // hcount
    buffer.append(charge);
    if (brackets) {
        buffer.append(']');
    }
    // Deal with the end of a double bond configuration
    if (chiral && isEndOfDoubleBond(container, a, parent, doubleBondConfiguration)) {
        IAtom viewFrom = null;
        for (int i = 0; i < currentChain.size(); i++) {
            if (currentChain.get(i) == parent) {
                int k = i - 1;
                while (k > -1) {
                    if (currentChain.get(k) instanceof IAtom) {
                        viewFrom = (IAtom) currentChain.get(k);
                        break;
                    }
                    k--;
                }
            }
        }
        if (viewFrom == null) {
            for (int i = 0; i < atomsInOrderOfSmiles.size(); i++) {
                if (atomsInOrderOfSmiles.get(i) == parent) {
                    viewFrom = (IAtom) atomsInOrderOfSmiles.get(i - 1);
                }
            }
        }
        boolean afterThisAtom = false;
        IAtom viewTo = null;
        for (int i = 0; i < currentChain.size(); i++) {
            if (afterThisAtom && currentChain.get(i) instanceof IAtom) {
                viewTo = (IAtom) currentChain.get(i);
                break;
            }
            if (afterThisAtom && currentChain.get(i) instanceof List) {
                viewTo = (IAtom) ((List<?>) currentChain.get(i)).get(0);
                break;
            }
            if (a == currentChain.get(i)) {
                afterThisAtom = true;
            }
        }
        try {
            if (BondTools.isCisTrans(viewFrom, a, parent, viewTo, container)) {
                buffer.append('\\');
            } else {
                buffer.append('/');
            }
        } catch (CDKException ex) {
        // If the user wants a double bond configuration, where there is none, we ignore this.
        }
    }
    List<IAtom> v = new Vector<IAtom>();
    Iterator<Integer> it = getRingOpenings(a, v).iterator();
    Iterator<IAtom> it2 = v.iterator();
    // logger.debug("in parseAtom() after checking for Ring openings");
    while (it.hasNext()) {
        Integer integer = (Integer) it.next();
        IAtom a2 = (IAtom) it2.next();
        IBond b = container.getBond(a2, a);
        IBond.Order type = b.getOrder();
        if (!(useAromaticity && a.getFlag(CDKConstants.ISAROMATIC) && a2.getFlag(CDKConstants.ISAROMATIC))) {
            if (type == IBond.Order.DOUBLE) {
                buffer.append("=");
            } else if (type == IBond.Order.TRIPLE) {
                buffer.append("#");
            }
        }
        if (integer >= 10)
            buffer.append("%" + integer);
        else
            buffer.append(integer);
    }
    atomsInOrderOfSmiles.add(a);
// logger.debug("End of parseAtom()");
}
Also used : CDKException(org.openscience.cdk.exception.CDKException) IBond(org.openscience.cdk.interfaces.IBond) IPseudoAtom(org.openscience.cdk.interfaces.IPseudoAtom) PseudoAtom(org.openscience.cdk.PseudoAtom) ArrayList(java.util.ArrayList) List(java.util.List) Vector(java.util.Vector) IAtom(org.openscience.cdk.interfaces.IAtom)

Example 8 with CDKException

use of org.openscience.cdk.exception.CDKException in project Smiles2Monomers by yoann-dufresne.

the class SmilesConverter method transform.

public Molecule transform(String smiles, boolean addHydrogens, boolean calculateCoordinate, boolean expliciteHydrogens) throws InvalidSmilesException {
    Molecule imol = null;
    try {
        imol = new Molecule(sp.parseSmiles(smiles));
        // Add hydrogens
        if (addHydrogens) {
            CDKHydrogenAdder adder = CDKHydrogenAdder.getInstance(imol.getBuilder());
            try {
                adder.addImplicitHydrogens(imol);
                if (expliciteHydrogens)
                    AtomContainerManipulator.convertImplicitToExplicitHydrogens(imol);
            } catch (CDKException e) {
                e.printStackTrace();
            }
        } else {
            for (IAtom a : imol.atoms()) a.setImplicitHydrogenCount(0);
            if (!expliciteHydrogens)
                imol = new Molecule(AtomContainerManipulator.removeHydrogens(imol));
        }
        if (calculateCoordinate) {
            StructureDiagramGenerator sdg = new StructureDiagramGenerator(imol);
            try {
                sdg.generateCoordinates();
            } catch (CDKException e) {
                System.err.println(smiles);
                e.printStackTrace();
            }
            imol = new Molecule(sdg.getMolecule());
        }
    } catch (InvalidSmilesException e) {
        throw e;
    }
    return imol;
}
Also used : Molecule(org.openscience.cdk.Molecule) IMolecule(org.openscience.cdk.interfaces.IMolecule) CDKException(org.openscience.cdk.exception.CDKException) CDKHydrogenAdder(org.openscience.cdk.tools.CDKHydrogenAdder) InvalidSmilesException(org.openscience.cdk.exception.InvalidSmilesException) IAtom(org.openscience.cdk.interfaces.IAtom) StructureDiagramGenerator(org.openscience.cdk.layout.StructureDiagramGenerator)

Example 9 with CDKException

use of org.openscience.cdk.exception.CDKException in project Smiles2Monomers by yoann-dufresne.

the class IsomorphismFamilyMatcher method matchFamilly.

@Override
public Coverage matchFamilly(Family family) {
    // Initialization
    Coverage cov = new Coverage(co);
    IMolecule mol = co.getMolecule();
    Set<Residue> markSet = new HashSet<>();
    Stack<Residue> searchSet = new Stack<>();
    searchSet.addAll(family.getRoots());
    // For all the nodes in the search group.
    while (!searchSet.isEmpty()) {
        Residue currentRes = searchSet.pop();
        // Search the current residue in mol.
        try {
            this.sqt.setSmarts(currentRes.getSmiles());
        } catch (CDKException e) {
            e.printStackTrace();
        }
        boolean isMatching = false;
        try {
            long time = System.currentTimeMillis();
            isMatching = this.sqt.matches(mol);
            if (verbose)
                System.out.println("    Search for " + currentRes.getName() + " in " + (System.currentTimeMillis() - time));
        } catch (CDKException e) {
            e.printStackTrace();
        }
        // If there is at least one occurrence.
        if (isMatching) {
            // Add matches to the coverage
            List<Match> matches = new ArrayList<>();
            for (List<Integer> lMatch : sqt.getMatchingAtoms()) {
                Match match = new Match(currentRes);
                for (int i : lMatch) match.addAtom(i);
                matches.add(match);
            }
            // Change to compare.
            cov.addListMatches(currentRes, matches);
            // Mark current residue to possibly add children.
            markSet.add(currentRes);
            // Add children with all parents marked
            Set<Residue> children = family.getChildrenOf(currentRes);
            for (Residue child : children) {
                boolean canBeAdded = true;
                for (Link dependance : family.getDepandances()) if (dependance.getTo().equals(child))
                    if (!markSet.contains(dependance.getFrom())) {
                        canBeAdded = false;
                        break;
                    }
                if (canBeAdded)
                    searchSet.add(child);
            }
        }
    }
    return cov;
}
Also used : CDKException(org.openscience.cdk.exception.CDKException) ArrayList(java.util.ArrayList) Coverage(algorithms.utils.Coverage) Stack(java.util.Stack) Match(algorithms.utils.Match) IMolecule(org.openscience.cdk.interfaces.IMolecule) Residue(model.Residue) Link(model.Family.Link) HashSet(java.util.HashSet)

Example 10 with CDKException

use of org.openscience.cdk.exception.CDKException in project Smiles2Monomers by yoann-dufresne.

the class Chain method getPrevArity.

public int getPrevArity() {
    IAtom a = null;
    if (this.atoms == null)
        this.getMolecule();
    if (this.position1 == -1 && this.position2 == -1)
        return 1;
    else if (this.position1 != -1) {
        a = this.atoms.get(this.position1);
    } else {
        a = this.atoms.get(this.position2);
    }
    IMolecule mol = this.getMolecule();
    int valency = 1;
    try {
        valency = sc.calculateNumberOfImplicitHydrogens(a);
    } catch (CDKException e) {
        e.printStackTrace();
    }
    int hydrogens = a.getImplicitHydrogenCount();
    int connected = mol.getConnectedAtomsCount(a);
    int arity = valency - connected - hydrogens + 1;
    return arity < 1 ? 1 : arity;
}
Also used : IMolecule(org.openscience.cdk.interfaces.IMolecule) CDKException(org.openscience.cdk.exception.CDKException) IAtom(org.openscience.cdk.interfaces.IAtom)

Aggregations

CDKException (org.openscience.cdk.exception.CDKException)11 IMolecule (org.openscience.cdk.interfaces.IMolecule)7 IAtom (org.openscience.cdk.interfaces.IAtom)5 ArrayList (java.util.ArrayList)4 InvalidSmilesException (org.openscience.cdk.exception.InvalidSmilesException)4 HashSet (java.util.HashSet)3 List (java.util.List)3 IAtomContainer (org.openscience.cdk.interfaces.IAtomContainer)3 StructureDiagramGenerator (org.openscience.cdk.layout.StructureDiagramGenerator)3 Residue (model.Residue)2 Molecule (org.openscience.cdk.Molecule)2 IBond (org.openscience.cdk.interfaces.IBond)2 RMap (org.openscience.cdk.isomorphism.mcss.RMap)2 Coverage (algorithms.utils.Coverage)1 Match (algorithms.utils.Match)1 BufferedReader (java.io.BufferedReader)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileReader (java.io.FileReader)1 FileWriter (java.io.FileWriter)1