/// <summary> Check whether a set of atoms in an atomcontainer is connected
        ///
        /// </summary>
        /// <param name="atomContainer"> The AtomContainer to be check for connectedness
        /// </param>
        /// <returns>                 true if the AtomContainer is connected
        /// </returns>
        public static bool isConnected(IAtomContainer atomContainer)
        {
            IAtomContainer ac       = atomContainer.Builder.newAtomContainer();
            IAtom          atom     = null;
            IMolecule      molecule = atomContainer.Builder.newMolecule();

            System.Collections.ArrayList sphere = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
            for (int f = 0; f < atomContainer.AtomCount; f++)
            {
                atom = atomContainer.getAtomAt(f);
                atomContainer.getAtomAt(f).setFlag(CDKConstants.VISITED, false);
                ac.addAtom(atomContainer.getAtomAt(f));
            }
            IBond[] bonds = atomContainer.Bonds;
            for (int f = 0; f < bonds.Length; f++)
            {
                bonds[f].setFlag(CDKConstants.VISITED, false);
                ac.addBond(bonds[f]);
            }
            atom = ac.getAtomAt(0);
            sphere.Add(atom);
            atom.setFlag(CDKConstants.VISITED, true);
            PathTools.breadthFirstSearch(ac, sphere, molecule);
            if (molecule.AtomCount == atomContainer.AtomCount)
            {
                return(true);
            }
            return(false);
        }
Example #2
0
        /// <summary>  Converts a RingSet to an AtomContainer.
        ///
        /// </summary>
        /// <param name="ringSet"> The RingSet to be converted.
        /// </param>
        /// <returns>          The AtomContainer containing the bonds and atoms of the ringSet.
        /// </returns>
        public static IAtomContainer convertToAtomContainer(IRingSet ringSet)
        {
            IRing ring = (IRing)ringSet.getAtomContainer(0);

            if (ring == null)
            {
                return(null);
            }
            IAtomContainer ac = ring.Builder.newAtomContainer();

            for (int i = 0; i < ringSet.AtomContainerCount; i++)
            {
                ring = (IRing)ringSet.getAtomContainer(i);
                for (int r = 0; r < ring.getBondCount(); r++)
                {
                    IBond bond = ring.getBondAt(r);
                    if (!ac.contains(bond))
                    {
                        for (int j = 0; j < bond.AtomCount; j++)
                        {
                            ac.addAtom(bond.getAtomAt(j));
                        }
                        ac.addBond(bond);
                    }
                }
            }
            return(ac);
        }
Example #3
0
        /// <summary> Recursivly perfoms a depth first search in a molecular graphs contained in
        /// the AtomContainer molecule, starting at the root atom and returning when it
        /// hits the target atom.
        /// CAUTION: This recursive method sets the VISITED flag of each atom
        /// does not reset it after finishing the search. If you want to do the
        /// operation on the same collection of atoms more than once, you have
        /// to set all the VISITED flags to false before each operation
        /// by looping of the atoms and doing a
        /// "atom.setFlag((CDKConstants.VISITED, false));"
        ///
        /// </summary>
        /// <param name="molecule">The
        /// AtomContainer to be searched
        /// </param>
        /// <param name="root">    The root atom
        /// to start the search at
        /// </param>
        /// <param name="target">  The target
        /// </param>
        /// <param name="path">    An
        /// AtomContainer to be filled with the path
        /// </param>
        /// <returns> true if the
        /// target atom was found during this function call
        /// </returns>
        public static bool depthFirstTargetSearch(IAtomContainer molecule, IAtom root, IAtom target, IAtomContainer path)
        {
            IBond[] bonds = molecule.getConnectedBonds(root);
            IAtom   nextAtom;

            root.setFlag(CDKConstants.VISITED, true);
            for (int f = 0; f < bonds.Length; f++)
            {
                nextAtom = bonds[f].getConnectedAtom(root);
                if (!nextAtom.getFlag(CDKConstants.VISITED))
                {
                    path.addAtom(nextAtom);
                    path.addBond(bonds[f]);
                    if (nextAtom == target)
                    {
                        return(true);
                    }
                    else
                    {
                        if (!depthFirstTargetSearch(molecule, nextAtom, target, path))
                        {
                            // we did not find the target
                            path.removeAtom(nextAtom);
                            path.removeElectronContainer(bonds[f]);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
Example #4
0
        /// <summary> Converts a Jmol <i>model</i> to a CDK AtomContainer.
        ///
        /// </summary>
        /// <param name="model">A Jmol model as returned by the method ModelAdapter.openBufferedReader()
        /// </param>
        public virtual IAtomContainer convert(System.Object model)
        {
            IAtomContainer     atomContainer = builder.newAtomContainer();
            SmarterJmolAdapter adapter       = new SmarterJmolAdapter();

            // use this hashtable to map the ModelAdapter Unique IDs to
            // our CDK Atom's
            System.Collections.Hashtable          htMapUidsToAtoms = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
            Org.Jmol.Api.JmolAdapter.AtomIterator atomIterator     = adapter.getAtomIterator(model);
            while (atomIterator.hasNext())
            {
                IAtom atom = builder.newAtom(atomIterator.ElementSymbol);
                atom.X3d = atomIterator.X;
                atom.Y3d = atomIterator.Y;
                atom.Z3d = atomIterator.Z;
                htMapUidsToAtoms[atomIterator.UniqueID] = atom;
                atomContainer.addAtom(atom);
            }
            Org.Jmol.Api.JmolAdapter.BondIterator bondIterator = adapter.getBondIterator(model);
            while (bondIterator.hasNext())
            {
                System.Object uid1  = bondIterator.AtomUniqueID1;
                System.Object uid2  = bondIterator.AtomUniqueID2;
                int           order = bondIterator.EncodedOrder;
                // now, look up the uids in our atom map.
                IAtom atom1 = (IAtom)htMapUidsToAtoms[uid1];
                IAtom atom2 = (IAtom)htMapUidsToAtoms[uid2];
                IBond bond  = builder.newBond(atom1, atom2, (double)order);
                atomContainer.addBond(bond);
            }
            return(atomContainer);
        }
Example #5
0
        /// <summary> Processes the content from the connections field of the INChI.
        /// Typical values look like 1-2-4-6-5-3-1, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H.
        ///
        /// </summary>
        /// <param name="bondsEncoding">the content of the INChI connections field
        /// </param>
        /// <param name="container">    the atomContainer parsed from the formula field
        /// </param>
        /// <param name="source">       the atom to build the path upon. If -1, then start new path
        ///
        /// </param>
        /// <seealso cref="processFormula">
        /// </seealso>
        public virtual void processConnections(System.String bondsEncoding, IAtomContainer container, int source)
        {
            //logger.debug("Parsing bond data: ", bondsEncoding);

            IBond bondToAdd = null;

            /* Fixme: treatment of branching is too limited! */
            System.String remainder = bondsEncoding;
            while (remainder.Length > 0)
            {
                //logger.debug("Bond part: ", remainder);
                if (remainder[0] == '(')
                {
                    System.String branch = chopBranch(remainder);
                    processConnections(branch, container, source);
                    if (branch.Length + 2 <= remainder.Length)
                    {
                        remainder = remainder.Substring(branch.Length + 2);
                    }
                    else
                    {
                        remainder = "";
                    }
                }
                else
                {
                    Regex pattern = new Regex("^(\\d+)-?(.*)");
                    //Pattern pattern = Pattern.compile("^(\\d+)-?(.*)");
                    //Matcher matcher = pattern.matcher(remainder);
                    Match matcher = pattern.Match(remainder);
                    //if (matcher.matches())
                    if (matcher != null && matcher.Success)
                    {
                        System.String targetStr = matcher.Groups[1].Value;
                        int           target    = System.Int32.Parse(targetStr);
                        //logger.debug("Source atom: ", source);
                        //logger.debug("Target atom: ", targetStr);
                        IAtom targetAtom = container.getAtomAt(target - 1);
                        if (source != -1)
                        {
                            IAtom sourceAtom = container.getAtomAt(source - 1);
                            bondToAdd = container.Builder.newBond(sourceAtom, targetAtom, 1.0);
                            container.addBond(bondToAdd);
                        }
                        remainder = matcher.Groups[2].Value;
                        source    = target;
                        //logger.debug("  remainder: ", remainder);
                    }
                    else
                    {
                        //logger.error("Could not get next bond info part");
                        return;
                    }
                }
            }
        }
Example #6
0
        public virtual IAtomContainer getSpanningTree()
        {
            IAtomContainer ac = molecule.Builder.newAtomContainer();

            for (int a = 0; a < V; a++)
            {
                ac.addAtom(molecule.getAtomAt(a));
            }
            for (int b = 0; b < E; b++)
            {
                if (bondsInTree[b])
                {
                    ac.addBond(molecule.getBondAt(b));
                }
            }
            return(ac);
        }
Example #7
0
        /// <summary> Method that saturates an atom in a molecule by adding explicit hydrogens.
        ///
        /// </summary>
        /// <param name="atom">     Atom to saturate
        /// </param>
        /// <param name="container">AtomContainer containing the atom
        /// </param>
        /// <param name="count">    Number of hydrogens to add
        /// </param>
        /// <param name="totalContainer">In case you have a container containing multiple structures, this is the total container, whereas container is a partial structure
        ///
        /// </param>
        /// <cdk.keyword>           hydrogen, adding </cdk.keyword>
        /// <cdk.keyword>           explicit hydrogen </cdk.keyword>
        public virtual IAtomContainer addExplicitHydrogensToSatisfyValency(IAtomContainer container, IAtom atom, int count, IAtomContainer totalContainer)
        {
            //boolean create2DCoordinates = GeometryTools.has2DCoordinates(container);

            IIsotope isotope = IsotopeFactory.getInstance(container.Builder).getMajorIsotope("H");

            atom.setHydrogenCount(0);
            IAtomContainer changedAtomsAndBonds = container.Builder.newAtomContainer();

            for (int i = 1; i <= count; i++)
            {
                IAtom hydrogen = container.Builder.newAtom("H");
                IsotopeFactory.getInstance(container.Builder).configure(hydrogen, isotope);
                totalContainer.addAtom(hydrogen);
                IBond newBond = container.Builder.newBond((IAtom)atom, hydrogen, 1.0);
                totalContainer.addBond(newBond);
                changedAtomsAndBonds.addAtom(hydrogen);
                changedAtomsAndBonds.addBond(newBond);
            }
            return(changedAtomsAndBonds);
        }
Example #8
0
        /// <summary>
        /// Rebonds one atom by looking up nearby atom using the binary space partition tree.
        /// </summary>
        private void bondAtom(IAtomContainer container, IAtom atom)
        {
            double myCovalentRadius = atom.CovalentRadius;
            double searchRadius     = myCovalentRadius + maxCovalentRadius + bondTolerance;
            Point  tupleAtom        = new Point(atom.X3d, atom.Y3d, atom.Z3d);

            Bspt.EnumerateSphere e = bspt.enumHemiSphere(tupleAtom, searchRadius);
            while (e.MoveNext())
            {
                IAtom atomNear = ((TupleAtom)e.Current).Atom;
                if (atomNear != atom && container.getBond(atom, atomNear) == null)
                {
                    bool isBonded_ = isBonded(myCovalentRadius, atomNear.CovalentRadius, e.foundDistance2());
                    if (isBonded_)
                    {
                        IBond bond = atom.Builder.newBond(atom, atomNear, 1.0);
                        container.addBond(bond);
                    }
                }
            }
        }
Example #9
0
        static bool JoinMmpFragments(
            IAtomContainer mol,
            string commonFragSmiles,
            int attachmentNo)
        {
            IAtomContainer cfMol = SmilesToAtomContainer(commonFragSmiles);

            //AtomContainerManipulator.removeHydrogens(cfMol);

            mol.add(cfMol);

            List <IAtom> atoms = GetAttachmentAtoms(mol, attachmentNo);

            if (atoms.Count != 2)
            {
                return(false);
            }

            Bond b = new Bond(atoms[0], atoms[1], IBond.Order.SINGLE);

            mol.addBond(b);

            return(true);
        }
Example #10
0
		/// <summary> Method that saturates an atom in a molecule by adding explicit hydrogens.
		/// 
		/// </summary>
		/// <param name="atom">     Atom to saturate
		/// </param>
		/// <param name="container">AtomContainer containing the atom
		/// </param>
		/// <param name="count">    Number of hydrogens to add
		/// </param>
		/// <param name="totalContainer">In case you have a container containing multiple structures, this is the total container, whereas container is a partial structure
		/// 
		/// </param>
		/// <cdk.keyword>           hydrogen, adding </cdk.keyword>
		/// <cdk.keyword>           explicit hydrogen </cdk.keyword>
		public virtual IAtomContainer addExplicitHydrogensToSatisfyValency(IAtomContainer container, IAtom atom, int count, IAtomContainer totalContainer)
		{
			//boolean create2DCoordinates = GeometryTools.has2DCoordinates(container);
			
			IIsotope isotope = IsotopeFactory.getInstance(container.Builder).getMajorIsotope("H");
			atom.setHydrogenCount(0);
			IAtomContainer changedAtomsAndBonds = container.Builder.newAtomContainer();
			for (int i = 1; i <= count; i++)
			{
				IAtom hydrogen = container.Builder.newAtom("H");
				IsotopeFactory.getInstance(container.Builder).configure(hydrogen, isotope);
				totalContainer.addAtom(hydrogen);
				IBond newBond = container.Builder.newBond((IAtom) atom, hydrogen, 1.0);
				totalContainer.addBond(newBond);
				changedAtomsAndBonds.addAtom(hydrogen);
				changedAtomsAndBonds.addBond(newBond);
			}
			return changedAtomsAndBonds;
		}
Example #11
0
        private IChemModel readChemModel(IChemModel model)
        {
            int[]    atoms       = new int[1];
            double[] atomxs      = new double[1];
            double[] atomys      = new double[1];
            double[] atomzs      = new double[1];
            double[] atomcharges = new double[1];

            int[] bondatomid1 = new int[1];
            int[] bondatomid2 = new int[1];
            int[] bondorder   = new int[1];

            int numberOfAtoms = 0;
            int numberOfBonds = 0;

            try
            {
                System.String line = input.ReadLine();
                while (line != null)
                {
                    SupportClass.Tokenizer st      = new SupportClass.Tokenizer(line);
                    System.String          command = st.NextToken();
                    if ("!Header".Equals(command))
                    {
                        //logger.warn("Ignoring header");
                    }
                    else if ("!Info".Equals(command))
                    {
                        //logger.warn("Ignoring info");
                    }
                    else if ("!Atoms".Equals(command))
                    {
                        //logger.info("Reading atom block");
                        // determine number of atoms to read
                        try
                        {
                            numberOfAtoms = System.Int32.Parse(st.NextToken());
                            //logger.debug("  #atoms: " + numberOfAtoms);
                            atoms       = new int[numberOfAtoms];
                            atomxs      = new double[numberOfAtoms];
                            atomys      = new double[numberOfAtoms];
                            atomzs      = new double[numberOfAtoms];
                            atomcharges = new double[numberOfAtoms];

                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                atoms[atomID] = System.Int32.Parse(atomInfoFields.NextToken());
                                //logger.debug("Set atomic number of atom (" + atomID + ") to: " + atoms[atomID]);
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Atoms block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Bonds".Equals(command))
                    {
                        //logger.info("Reading bond block");
                        try
                        {
                            // determine number of bonds to read
                            numberOfBonds = System.Int32.Parse(st.NextToken());
                            bondatomid1   = new int[numberOfAtoms];
                            bondatomid2   = new int[numberOfAtoms];
                            bondorder     = new int[numberOfAtoms];

                            for (int i = 0; i < numberOfBonds; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer bondInfoFields = new SupportClass.Tokenizer(line);
                                bondatomid1[i] = System.Int32.Parse(bondInfoFields.NextToken());
                                bondatomid2[i] = System.Int32.Parse(bondInfoFields.NextToken());
                                System.String order = bondInfoFields.NextToken();
                                if ("D".Equals(order))
                                {
                                    bondorder[i] = 2;
                                }
                                else if ("S".Equals(order))
                                {
                                    bondorder[i] = 1;
                                }
                                else if ("T".Equals(order))
                                {
                                    bondorder[i] = 3;
                                }
                                else
                                {
                                    // ignore order, i.e. set to single
                                    //logger.warn("Unrecognized bond order, using single bond instead. Found: " + order);
                                    bondorder[i] = 1;
                                }
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Bonds block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Coord".Equals(command))
                    {
                        //logger.info("Reading coordinate block");
                        try
                        {
                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int    atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                double x      = System.Double.Parse(atomInfoFields.NextToken());
                                double y      = System.Double.Parse(atomInfoFields.NextToken());
                                double z      = System.Double.Parse(atomInfoFields.NextToken());
                                atomxs[atomID] = x;
                                atomys[atomID] = y;
                                atomzs[atomID] = z;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Coord block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!Charges".Equals(command))
                    {
                        //logger.info("Reading charges block");
                        try
                        {
                            for (int i = 0; i < numberOfAtoms; i++)
                            {
                                line = input.ReadLine();
                                SupportClass.Tokenizer atomInfoFields = new SupportClass.Tokenizer(line);
                                int    atomID = System.Int32.Parse(atomInfoFields.NextToken());
                                double charge = System.Double.Parse(atomInfoFields.NextToken());
                                atomcharges[atomID] = charge;
                            }
                        }
                        catch (System.Exception exception)
                        {
                            //logger.error("Error while reading Charges block");
                            //logger.debug(exception);
                        }
                    }
                    else if ("!End".Equals(command))
                    {
                        //logger.info("Found end of file");
                        // Store atoms
                        IAtomContainer container = model.Builder.newAtomContainer();
                        for (int i = 0; i < numberOfAtoms; i++)
                        {
                            try
                            {
                                IAtom atom = model.Builder.newAtom(IsotopeFactory.getInstance(container.Builder).getElementSymbol(atoms[i]));
                                atom.AtomicNumber = atoms[i];
                                atom.setPoint3d(new Point3d(atomxs[i], atomys[i], atomzs[i]));
                                atom.setCharge(atomcharges[i]);
                                container.addAtom(atom);
                                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                                //logger.debug("Stored atom: " + atom);
                            }
                            catch (System.Exception exception)
                            {
                                //logger.error("Cannot create an atom with atomic number: " + atoms[i]);
                                //logger.debug(exception);
                            }
                        }

                        // Store bonds
                        for (int i = 0; i < numberOfBonds; i++)
                        {
                            container.addBond(bondatomid1[i], bondatomid2[i], bondorder[i]);
                        }

                        ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules();
                        moleculeSet.addMolecule(model.Builder.newMolecule(container));
                        model.SetOfMolecules = moleculeSet;

                        return(model);
                    }
                    else
                    {
                        //logger.warn("Skipping line: " + line);
                    }

                    line = input.ReadLine();
                }
            }
            catch (System.Exception exception)
            {
                //logger.error("Error while reading file");
                //logger.debug(exception);
            }

            // this should not happen, file is lacking !End command
            return(null);
        }
Example #12
0
 /// <summary> Procedure required by the CDOInterface. This function is only
 /// supposed to be called by the JCFL library
 /// </summary>
 public virtual void endObject(System.String objectType)
 {
     //logger.debug("END: " + objectType);
     if (objectType.Equals("Molecule"))
     {
         if (currentMolecule is IMolecule)
         {
             //logger.debug("Adding molecule to set");
             currentSetOfMolecules.addMolecule((IMolecule)currentMolecule);
             //logger.debug("#mols in set: " + currentSetOfMolecules.MoleculeCount);
         }
         else if (currentMolecule is ICrystal)
         {
             //logger.debug("Adding crystal to chemModel");
             currentChemModel.Crystal = (ICrystal)currentMolecule;
             currentChemSequence.addChemModel(currentChemModel);
         }
     }
     else if (objectType.Equals("SetOfMolecules"))
     {
         currentChemModel.SetOfMolecules = currentSetOfMolecules;
         currentChemSequence.addChemModel(currentChemModel);
     }
     else if (objectType.Equals("Frame"))
     {
         // endObject("Molecule");
     }
     else if (objectType.Equals("Animation"))
     {
         addChemSequence(currentChemSequence);
         //logger.info("This file has " + ChemSequenceCount + " sequence(s).");
     }
     else if (objectType.Equals("Atom"))
     {
         currentMolecule.addAtom(currentAtom);
     }
     else if (objectType.Equals("Bond"))
     {
         //logger.debug("Bond(" + bond_id + "): " + bond_a1 + ", " + bond_a2 + ", " + bond_order);
         if (bond_a1 > currentMolecule.AtomCount || bond_a2 > currentMolecule.AtomCount)
         {
             //logger.error("Cannot add bond between at least one non-existant atom: " + bond_a1 + " and " + bond_a2);
         }
         else
         {
             IAtom a1 = currentMolecule.getAtomAt(bond_a1);
             IAtom a2 = currentMolecule.getAtomAt(bond_a2);
             IBond b  = currentChemFile.Builder.newBond(a1, a2, bond_order);
             if (bond_id != null)
             {
                 b.ID = bond_id;
             }
             if (bond_stereo != -99)
             {
                 b.Stereo = bond_stereo;
             }
             if (bond_order == CDKConstants.BONDORDER_AROMATIC)
             {
                 b.setFlag(CDKConstants.ISAROMATIC, true);
             }
             currentMolecule.addBond(b);
         }
     }
     else if (objectType.Equals("a-axis"))
     {
         // set these variables
         if (currentMolecule is ICrystal)
         {
             ICrystal current = (ICrystal)currentMolecule;
             current.A = new Vector3d(crystal_axis_x, crystal_axis_y, crystal_axis_z);
         }
         else
         {
             //logger.warn("Current object is not a crystal");
         }
     }
     else if (objectType.Equals("b-axis"))
     {
         if (currentMolecule is ICrystal)
         {
             ICrystal current = (ICrystal)currentMolecule;
             current.B = new Vector3d(crystal_axis_x, crystal_axis_y, crystal_axis_z);
         }
         else
         {
             //logger.warn("Current object is not a crystal");
         }
     }
     else if (objectType.Equals("c-axis"))
     {
         if (currentMolecule is ICrystal)
         {
             ICrystal current = (ICrystal)currentMolecule;
             current.C = new Vector3d(crystal_axis_x, crystal_axis_y, crystal_axis_z);
         }
         else
         {
             //logger.warn("Current object is not a crystal");
         }
     }
     else if (objectType.Equals("SetOfReactions"))
     {
         currentChemModel.SetOfReactions = currentSetOfReactions;
         currentChemSequence.addChemModel(currentChemModel);
         /* FIXME: this should be when document is closed! */
     }
     else if (objectType.Equals("Reaction"))
     {
         //logger.debug("Adding reaction to SOR");
         currentSetOfReactions.addReaction(currentReaction);
     }
     else if (objectType.Equals("Reactant"))
     {
         currentReaction.addReactant((IMolecule)currentMolecule);
     }
     else if (objectType.Equals("Product"))
     {
         currentReaction.addProduct((IMolecule)currentMolecule);
     }
     else if (objectType.Equals("Crystal"))
     {
         //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
         //logger.debug("Crystal: " + currentMolecule);
     }
 }
Example #13
0
        /// <summary> Reads the bond atoms, order and stereo configuration.</summary>
        public virtual void readBondBlock(IAtomContainer readData)
        {
            bool foundEND = false;
            while (Ready && !foundEND)
            {
                System.String command = readCommand();
                if ("END BOND".Equals(command))
                {
                    foundEND = true;
                }
                else
                {
                    //logger.debug("Parsing bond from: " + command);
                    SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(command);
                    IBond bond = readData.Builder.newBond();
                    // parse the index
                    try
                    {
                        System.String indexString = tokenizer.NextToken();
                        bond.ID = indexString;
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing bond index";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse the order
                    try
                    {
                        System.String orderString = tokenizer.NextToken();
                        int order = System.Int32.Parse(orderString);
                        if (order >= 4)
                        {
                            //logger.warn("Query order types are not supported (yet). File a bug if you need it");
                        }
                        else
                        {
                            bond.Order = (double)order;
                        }
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing bond index";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse index atom 1
                    try
                    {
                        System.String indexAtom1String = tokenizer.NextToken();
                        int indexAtom1 = System.Int32.Parse(indexAtom1String);
                        IAtom atom1 = readData.getAtomAt(indexAtom1 - 1);
                        bond.setAtomAt(atom1, 0);
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing index atom 1 in bond";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse index atom 2
                    try
                    {
                        System.String indexAtom2String = tokenizer.NextToken();
                        int indexAtom2 = System.Int32.Parse(indexAtom2String);
                        IAtom atom2 = readData.getAtomAt(indexAtom2 - 1);
                        bond.setAtomAt(atom2, 1);
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing index atom 2 in bond";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // the rest are key=value fields
                    if (command.IndexOf("=") != -1)
                    {
                        System.Collections.Hashtable options = parseOptions(exhaustStringTokenizer(tokenizer));
                        System.Collections.IEnumerator keys = options.Keys.GetEnumerator();
                        //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
                        while (keys.MoveNext())
                        {
                            //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                            System.String key = (System.String)keys.Current;
                            System.String value_Renamed = (System.String)options[key];
                            try
                            {
                                if (key.Equals("CFG"))
                                {
                                    int configuration = System.Int32.Parse(value_Renamed);
                                    if (configuration == 0)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_NONE;
                                    }
                                    else if (configuration == 1)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_UP;
                                    }
                                    else if (configuration == 2)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_UNDEFINED;
                                    }
                                    else if (configuration == 3)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_DOWN;
                                    }
                                }
                                else
                                {
                                    //logger.warn("Not parsing key: " + key);
                                }
                            }
                            catch (System.Exception exception)
                            {
                                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                                System.String error = "Error while parsing key/value " + key + "=" + value_Renamed + ": " + exception.Message;
                                //logger.error(error);
                                //logger.debug(exception);
                                throw new CDKException(error, exception);
                            }
                        }
                    }

                    // storing bond
                    readData.addBond(bond);
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    //logger.debug("Added bond: " + bond);
                }
            }
        }
Example #14
0
        //////////////////////////////////////
        //    Manipulation tools

        /// <summary>  Projects a list of RMap on a molecule
        ///
        /// </summary>
        /// <param name="rMapList"> the list to project
        /// </param>
        /// <param name="g">        the molecule on which project
        /// </param>
        /// <param name="id">       the id in the RMap of the molecule g
        /// </param>
        /// <returns>           an AtomContainer
        /// </returns>
        public static IAtomContainer project(System.Collections.IList rMapList, IAtomContainer g, int id)
        {
            IAtomContainer ac = g.Builder.newAtomContainer();

            IBond[] bondList = g.Bonds;

            System.Collections.Hashtable table = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
            IAtom a1;
            IAtom a2;
            IAtom a;
            IBond bond;

            //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'"
            for (System.Collections.IEnumerator i = rMapList.GetEnumerator(); i.MoveNext();)
            {
                //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'"
                RMap rMap = (RMap)i.Current;
                if (id == UniversalIsomorphismTester.ID1)
                {
                    bond = bondList[rMap.Id1];
                }
                else
                {
                    bond = bondList[rMap.Id2];
                }

                a  = bond.getAtomAt(0);
                a1 = (IAtom)table[a];

                if (a1 == null)
                {
                    try
                    {
                        a1 = (IAtom)a.Clone();
                    }
                    //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
                    catch (System.Exception e)
                    {
                        SupportClass.WriteStackTrace(e, Console.Error);
                    }
                    ac.addAtom(a1);
                    table[a] = a1;
                }

                a  = bond.getAtomAt(1);
                a2 = (IAtom)table[a];

                if (a2 == null)
                {
                    try
                    {
                        a2 = (IAtom)a.Clone();
                    }
                    //UPGRADE_NOTE: Exception 'java.lang.CloneNotSupportedException' was converted to 'System.Exception' which has different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1100'"
                    catch (System.Exception e)
                    {
                        SupportClass.WriteStackTrace(e, Console.Error);
                    }
                    ac.addAtom(a2);
                    table[a] = a2;
                }
                IBond newBond = g.Builder.newBond(a1, a2, bond.Order);
                newBond.setFlag(CDKConstants.ISAROMATIC, bond.getFlag(CDKConstants.ISAROMATIC));
                ac.addBond(newBond);
            }
            return(ac);
        }
        /// <summary> Processes the content from the connections field of the INChI.
        /// Typical values look like 1-2-4-6-5-3-1, from INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H.
        /// 
        /// </summary>
        /// <param name="bondsEncoding">the content of the INChI connections field
        /// </param>
        /// <param name="container">    the atomContainer parsed from the formula field
        /// </param>
        /// <param name="source">       the atom to build the path upon. If -1, then start new path
        /// 
        /// </param>
        /// <seealso cref="processFormula">
        /// </seealso>
        public virtual void processConnections(System.String bondsEncoding, IAtomContainer container, int source)
        {
            //logger.debug("Parsing bond data: ", bondsEncoding);

            IBond bondToAdd = null;
            /* Fixme: treatment of branching is too limited! */
            System.String remainder = bondsEncoding;
            while (remainder.Length > 0)
            {
                //logger.debug("Bond part: ", remainder);
                if (remainder[0] == '(')
                {
                    System.String branch = chopBranch(remainder);
                    processConnections(branch, container, source);
                    if (branch.Length + 2 <= remainder.Length)
                    {
                        remainder = remainder.Substring(branch.Length + 2);
                    }
                    else
                    {
                        remainder = "";
                    }
                }
                else
                {
                    Regex pattern = new Regex("^(\\d+)-?(.*)");
                    //Pattern pattern = Pattern.compile("^(\\d+)-?(.*)");
                    //Matcher matcher = pattern.matcher(remainder);
                    Match matcher = pattern.Match(remainder);
                    //if (matcher.matches())
                    if (matcher != null && matcher.Success)
                    {
                        System.String targetStr = matcher.Groups[1].Value;
                        int target = System.Int32.Parse(targetStr);
                        //logger.debug("Source atom: ", source);
                        //logger.debug("Target atom: ", targetStr);
                        IAtom targetAtom = container.getAtomAt(target - 1);
                        if (source != -1)
                        {
                            IAtom sourceAtom = container.getAtomAt(source - 1);
                            bondToAdd = container.Builder.newBond(sourceAtom, targetAtom, 1.0);
                            container.addBond(bondToAdd);
                        }
                        remainder = matcher.Groups[2].Value;
                        source = target;
                        //logger.debug("  remainder: ", remainder);
                    }
                    else
                    {
                        //logger.error("Could not get next bond info part");
                        return;
                    }
                }
            }
        }
Example #16
0
        /// <summary> Reads the bond atoms, order and stereo configuration.</summary>
        public virtual void readBondBlock(IAtomContainer readData)
        {
            bool foundEND = false;

            while (Ready && !foundEND)
            {
                System.String command = readCommand();
                if ("END BOND".Equals(command))
                {
                    foundEND = true;
                }
                else
                {
                    //logger.debug("Parsing bond from: " + command);
                    SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(command);
                    IBond bond = readData.Builder.newBond();
                    // parse the index
                    try
                    {
                        System.String indexString = tokenizer.NextToken();
                        bond.ID = indexString;
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing bond index";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse the order
                    try
                    {
                        System.String orderString = tokenizer.NextToken();
                        int           order       = System.Int32.Parse(orderString);
                        if (order >= 4)
                        {
                            //logger.warn("Query order types are not supported (yet). File a bug if you need it");
                        }
                        else
                        {
                            bond.Order = (double)order;
                        }
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing bond index";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse index atom 1
                    try
                    {
                        System.String indexAtom1String = tokenizer.NextToken();
                        int           indexAtom1       = System.Int32.Parse(indexAtom1String);
                        IAtom         atom1            = readData.getAtomAt(indexAtom1 - 1);
                        bond.setAtomAt(atom1, 0);
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing index atom 1 in bond";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // parse index atom 2
                    try
                    {
                        System.String indexAtom2String = tokenizer.NextToken();
                        int           indexAtom2       = System.Int32.Parse(indexAtom2String);
                        IAtom         atom2            = readData.getAtomAt(indexAtom2 - 1);
                        bond.setAtomAt(atom2, 1);
                    }
                    catch (System.Exception exception)
                    {
                        System.String error = "Error while parsing index atom 2 in bond";
                        //logger.error(error);
                        //logger.debug(exception);
                        throw new CDKException(error, exception);
                    }
                    // the rest are key=value fields
                    if (command.IndexOf("=") != -1)
                    {
                        System.Collections.Hashtable   options = parseOptions(exhaustStringTokenizer(tokenizer));
                        System.Collections.IEnumerator keys    = options.Keys.GetEnumerator();
                        //UPGRADE_TODO: Method 'java.util.Enumeration.hasMoreElements' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationhasMoreElements'"
                        while (keys.MoveNext())
                        {
                            //UPGRADE_TODO: Method 'java.util.Enumeration.nextElement' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilEnumerationnextElement'"
                            System.String key           = (System.String)keys.Current;
                            System.String value_Renamed = (System.String)options[key];
                            try
                            {
                                if (key.Equals("CFG"))
                                {
                                    int configuration = System.Int32.Parse(value_Renamed);
                                    if (configuration == 0)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_NONE;
                                    }
                                    else if (configuration == 1)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_UP;
                                    }
                                    else if (configuration == 2)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_UNDEFINED;
                                    }
                                    else if (configuration == 3)
                                    {
                                        bond.Stereo = CDKConstants.STEREO_BOND_DOWN;
                                    }
                                }
                                else
                                {
                                    //logger.warn("Not parsing key: " + key);
                                }
                            }
                            catch (System.Exception exception)
                            {
                                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                                System.String error = "Error while parsing key/value " + key + "=" + value_Renamed + ": " + exception.Message;
                                //logger.error(error);
                                //logger.debug(exception);
                                throw new CDKException(error, exception);
                            }
                        }
                    }

                    // storing bond
                    readData.addBond(bond);
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    //logger.debug("Added bond: " + bond);
                }
            }
        }
Example #17
0
 /// <summary>
 /// Rebonds one atom by looking up nearby atom using the binary space partition tree.
 /// </summary>
 private void bondAtom(IAtomContainer container, IAtom atom)
 {
     double myCovalentRadius = atom.CovalentRadius;
     double searchRadius = myCovalentRadius + maxCovalentRadius + bondTolerance;
     Point tupleAtom = new Point(atom.X3d, atom.Y3d, atom.Z3d);
     Bspt.EnumerateSphere e = bspt.enumHemiSphere(tupleAtom, searchRadius);
     while (e.MoveNext())
     {
         IAtom atomNear = ((TupleAtom)e.Current).Atom;
         if (atomNear != atom && container.getBond(atom, atomNear) == null)
         {
             bool isBonded_ = isBonded(myCovalentRadius, atomNear.CovalentRadius, e.foundDistance2());
             if (isBonded_)
             {
                 IBond bond = atom.Builder.newBond(atom, atomNear, 1.0);
                 container.addBond(bond);
             }
         }
     }
 }
Example #18
0
 /// <summary> Recursivly perfoms a depth first search in a molecular graphs contained in
 /// the AtomContainer molecule, starting at the root atom and returning when it
 /// hits the target atom.
 /// CAUTION: This recursive method sets the VISITED flag of each atom
 /// does not reset it after finishing the search. If you want to do the
 /// operation on the same collection of atoms more than once, you have
 /// to set all the VISITED flags to false before each operation
 /// by looping of the atoms and doing a
 /// "atom.setFlag((CDKConstants.VISITED, false));"
 /// 
 /// </summary>
 /// <param name="molecule">The
 /// AtomContainer to be searched
 /// </param>
 /// <param name="root">    The root atom
 /// to start the search at
 /// </param>
 /// <param name="target">  The target
 /// </param>
 /// <param name="path">    An
 /// AtomContainer to be filled with the path
 /// </param>
 /// <returns> true if the
 /// target atom was found during this function call
 /// </returns>
 public static bool depthFirstTargetSearch(IAtomContainer molecule, IAtom root, IAtom target, IAtomContainer path)
 {
     IBond[] bonds = molecule.getConnectedBonds(root);
     IAtom nextAtom;
     root.setFlag(CDKConstants.VISITED, true);
     for (int f = 0; f < bonds.Length; f++)
     {
         nextAtom = bonds[f].getConnectedAtom(root);
         if (!nextAtom.getFlag(CDKConstants.VISITED))
         {
             path.addAtom(nextAtom);
             path.addBond(bonds[f]);
             if (nextAtom == target)
             {
                 return true;
             }
             else
             {
                 if (!depthFirstTargetSearch(molecule, nextAtom, target, path))
                 {
                     // we did not find the target
                     path.removeAtom(nextAtom);
                     path.removeElectronContainer(bonds[f]);
                 }
                 else
                 {
                     return true;
                 }
             }
         }
     }
     return false;
 }