Exemple #1
0
 /// <summary>  Checks for single atom cases before doing subgraph/isomorphism search
 ///
 /// </summary>
 /// <param name="g1"> AtomContainer to match on
 /// </param>
 /// <param name="g2"> AtomContainer as query
 /// </param>
 /// <returns>     List of List of RMap objects for the Atoms (not Bonds!), null if no single atom case
 /// </returns>
 public static System.Collections.ArrayList checkSingleAtomCases(IAtomContainer g1, IAtomContainer g2)
 {
     if (g2.AtomCount == 1)
     {
         System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
         IAtom atom = g2.getAtomAt(0);
         if (atom is IQueryAtom)
         {
             IQueryAtom qAtom = (IQueryAtom)atom;
             for (int i = 0; i < g1.AtomCount; i++)
             {
                 if (qAtom.matches(g1.getAtomAt(i)))
                 {
                     arrayList.Add(new RMap(i, 0));
                 }
             }
         }
         else
         {
             System.String atomSymbol = atom.Symbol;
             for (int i = 0; i < g1.AtomCount; i++)
             {
                 if (g1.getAtomAt(i).Symbol.Equals(atomSymbol))
                 {
                     arrayList.Add(new RMap(i, 0));
                 }
             }
         }
         return(arrayList);
     }
     else if (g1.AtomCount == 1)
     {
         System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
         IAtom atom = g1.getAtomAt(0);
         for (int i = 0; i < g2.AtomCount; i++)
         {
             IAtom atom2 = g2.getAtomAt(i);
             if (atom2 is IQueryAtom)
             {
                 IQueryAtom qAtom = (IQueryAtom)atom2;
                 if (qAtom.matches(atom))
                 {
                     arrayList.Add(new RMap(0, i));
                 }
             }
             else
             {
                 if (atom2.Symbol.Equals(atom.Symbol))
                 {
                     arrayList.Add(new RMap(0, i));
                 }
             }
         }
         return(arrayList);
     }
     else
     {
         return(null);
     }
 }
        /// <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);
        }
Exemple #3
0
        ///////////////////////////////////////////////////////////////////////////
        //                            Query Methods
        //
        // This methods are simple applications of the RGraph model on atom containers
        // using different constrains and search options. They give an exemple of the
        // most common queries but of course it is possible to define other type of
        // queries exploiting the constrain and option combinations
        //

        ////
        // Isomorphism search

        /// <summary>  Tests if  g1 and g2 are isomorph
        ///
        /// </summary>
        /// <param name="g1"> first molecule
        /// </param>
        /// <param name="g2"> second molecule
        /// </param>
        /// <returns>     true if the 2 molecule are isomorph
        /// </returns>
        public static bool isIsomorph(IAtomContainer g1, IAtomContainer g2)
        {
            if (g2.AtomCount != g1.AtomCount)
            {
                return(false);
            }
            // check single atom case
            if (g2.AtomCount == 1)
            {
                IAtom atom  = g1.getAtomAt(0);
                IAtom atom2 = g2.getAtomAt(0);
                if (atom is IQueryAtom)
                {
                    IQueryAtom qAtom = (IQueryAtom)atom;
                    return(qAtom.matches(g2.getAtomAt(0)));
                }
                else if (atom2 is IQueryAtom)
                {
                    IQueryAtom qAtom = (IQueryAtom)atom2;
                    return(qAtom.matches(g1.getAtomAt(0)));
                }
                else
                {
                    System.String atomSymbol = atom.Symbol;
                    return(g1.getAtomAt(0).Symbol.Equals(atomSymbol));
                }
            }
            return(getIsomorphMap(g1, g2) != null);
        }
 /// <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;
 }
        public virtual void  saturateRingSystems(IAtomContainer atomContainer)
        {
            IRingSet rs = new SSSRFinder(atomContainer.Builder.newMolecule(atomContainer)).findSSSR();

            System.Collections.ArrayList ringSets = RingPartitioner.partitionRings(rs);
            IAtomContainer ac   = null;
            IAtom          atom = null;

            int[] temp;
            for (int f = 0; f < ringSets.Count; f++)
            {
                rs   = (IRingSet)ringSets[f];
                ac   = RingSetManipulator.getAllInOneContainer(rs);
                temp = new int[ac.AtomCount];
                for (int g = 0; g < ac.AtomCount; g++)
                {
                    atom    = ac.getAtomAt(g);
                    temp[g] = atom.getHydrogenCount();
                    atom.setHydrogenCount(atomContainer.getBondCount(atom) - ac.getBondCount(atom) - temp[g]);
                }
                saturate(ac);
                for (int g = 0; g < ac.AtomCount; g++)
                {
                    atom = ac.getAtomAt(g);
                    atom.setHydrogenCount(temp[g]);
                }
            }
        }
 /// <summary> Returna an atom in an atomcontainer identified by id
 /// 
 /// </summary>
 /// <param name="ac">The AtomContainer to search in
 /// </param>
 /// <param name="id">The id to search for
 /// </param>
 /// <returns> An atom having id id
 /// </returns>
 /// <throws>  CDKException There is no such atom </throws>
 public static IAtom getAtomById(IAtomContainer ac, System.String id)
 {
     for (int i = 0; i < ac.AtomCount; i++)
     {
         if (ac.getAtomAt(i).ID != null && ac.getAtomAt(i).ID.Equals(id))
             return ac.getAtomAt(i);
     }
     throw new CDKException("no suc atom");
 }
Exemple #7
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;
                    }
                }
            }
        }
Exemple #8
0
 /// <summary> Returna an atom in an atomcontainer identified by id
 ///
 /// </summary>
 /// <param name="ac">The AtomContainer to search in
 /// </param>
 /// <param name="id">The id to search for
 /// </param>
 /// <returns> An atom having id id
 /// </returns>
 /// <throws>  CDKException There is no such atom </throws>
 public static IAtom getAtomById(IAtomContainer ac, System.String id)
 {
     for (int i = 0; i < ac.AtomCount; i++)
     {
         if (ac.getAtomAt(i).ID != null && ac.getAtomAt(i).ID.Equals(id))
         {
             return(ac.getAtomAt(i));
         }
     }
     throw new CDKException("no suc atom");
 }
        /// <summary> Partitions the atoms in an AtomContainer into covalently connected components.
        ///
        /// </summary>
        /// <param name="atomContainer"> The AtomContainer to be partitioned into connected components, i.e. molecules
        /// </param>
        /// <returns>                 A SetOfMolecules.
        ///
        /// </returns>
        /// <cdk.dictref>    blue-obelisk:graphPartitioning </cdk.dictref>
        public static ISetOfMolecules partitionIntoMolecules(IAtomContainer atomContainer)
        {
            IAtomContainer     ac         = atomContainer.Builder.newAtomContainer();
            IAtom              atom       = null;
            IElectronContainer eContainer = null;
            IMolecule          molecule   = null;
            ISetOfMolecules    molecules  = atomContainer.Builder.newSetOfMolecules();

            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);
                atom.setFlag(CDKConstants.VISITED, false);
                ac.addAtom(atom);
            }
            IElectronContainer[] eContainers = atomContainer.ElectronContainers;
            for (int f = 0; f < eContainers.Length; f++)
            {
                eContainer = eContainers[f];
                eContainer.setFlag(CDKConstants.VISITED, false);
                ac.addElectronContainer(eContainer);
            }
            while (ac.AtomCount > 0)
            {
                atom     = ac.getAtomAt(0);
                molecule = atomContainer.Builder.newMolecule();
                sphere.Clear();
                sphere.Add(atom);
                atom.setFlag(CDKConstants.VISITED, true);
                PathTools.breadthFirstSearch(ac, sphere, molecule);
                molecules.addMolecule(molecule);
                ac.remove(molecule);
            }
            return(molecules);
        }
 /// <summary>  Makes an array containing the morgan numbers of the atoms of atomContainer.
 /// 
 /// </summary>
 /// <param name="atomContainer"> The atomContainer to analyse.
 /// </param>
 /// <returns>                The morgan numbers value.
 /// </returns>
 public static int[] getMorganNumbers(IAtomContainer atomContainer)
 {
     int[] morganMatrix;
     int[] tempMorganMatrix;
     int N = atomContainer.AtomCount;
     morganMatrix = new int[N];
     tempMorganMatrix = new int[N];
     IAtom[] atoms = null;
     for (int f = 0; f < N; f++)
     {
         morganMatrix[f] = atomContainer.getBondCount(f);
         tempMorganMatrix[f] = atomContainer.getBondCount(f);
     }
     for (int e = 0; e < N; e++)
     {
         for (int f = 0; f < N; f++)
         {
             morganMatrix[f] = 0;
             atoms = atomContainer.getConnectedAtoms(atomContainer.getAtomAt(f));
             for (int g = 0; g < atoms.Length; g++)
             {
                 morganMatrix[f] += tempMorganMatrix[atomContainer.getAtomNumber(atoms[g])];
             }
         }
         Array.Copy(morganMatrix, 0, tempMorganMatrix, 0, N);
     }
     return tempMorganMatrix;
 }
        /// <summary>  Makes an array containing the morgan numbers of the atoms of atomContainer.
        ///
        /// </summary>
        /// <param name="atomContainer"> The atomContainer to analyse.
        /// </param>
        /// <returns>                The morgan numbers value.
        /// </returns>
        public static int[] getMorganNumbers(IAtomContainer atomContainer)
        {
            int[] morganMatrix;
            int[] tempMorganMatrix;
            int   N = atomContainer.AtomCount;

            morganMatrix     = new int[N];
            tempMorganMatrix = new int[N];
            IAtom[] atoms = null;
            for (int f = 0; f < N; f++)
            {
                morganMatrix[f]     = atomContainer.getBondCount(f);
                tempMorganMatrix[f] = atomContainer.getBondCount(f);
            }
            for (int e = 0; e < N; e++)
            {
                for (int f = 0; f < N; f++)
                {
                    morganMatrix[f] = 0;
                    atoms           = atomContainer.getConnectedAtoms(atomContainer.getAtomAt(f));
                    for (int g = 0; g < atoms.Length; g++)
                    {
                        morganMatrix[f] += tempMorganMatrix[atomContainer.getAtomNumber(atoms[g])];
                    }
                }
                Array.Copy(morganMatrix, 0, tempMorganMatrix, 0, N);
            }
            return(tempMorganMatrix);
        }
Exemple #12
0
 /// <summary>  Configures atoms in an AtomContainer to
 /// carry all the correct data according to their element type.
 ///
 /// </summary>
 /// <param name="container"> The AtomContainer to be configured
 /// </param>
 public virtual void configureAtoms(IAtomContainer container)
 {
     for (int f = 0; f < container.AtomCount; f++)
     {
         configure(container.getAtomAt(f));
     }
 }
Exemple #13
0
 /// <summary>  A method to remove AtomListeners.
 /// AtomListeners are used to detect changes
 /// in Atom objects within this AtomContainer and to notifiy
 /// registered Listeners in the event of a change.
 /// If an object looses interest in such changes, it should
 /// unregister with this AtomContainer in order to improve
 /// performance of this class.
 /// </summary>
 public static void unregisterAtomListeners(IAtomContainer container)
 {
     for (int f = 0; f < container.AtomCount; f++)
     {
         container.getAtomAt(f).removeListener(container);
     }
 }
        /// <summary>  Uses precomputed set of ALL rings and performs an aromaticity detection
        /// based on Hueckels 4n + 2 rule.
        ///
        /// </summary>
        /// <param name="ringSet">                set of ALL rings
        /// </param>
        /// <param name="removeAromaticityFlags"> Leaves ChemObjects that are already marked as
        /// aromatic as they are
        /// </param>
        /// <param name="atomContainer">          AtomContainer to be searched for rings
        /// </param>
        /// <returns>                         True, if molecules contains an
        /// aromatic feature
        /// </returns>
        public static bool detectAromaticity(IAtomContainer atomContainer, IRingSet ringSet, bool removeAromaticityFlags)
        {
            bool foundSomething = false;

            if (removeAromaticityFlags)
            {
                for (int f = 0; f < atomContainer.AtomCount; f++)
                {
                    atomContainer.getAtomAt(f).setFlag(CDKConstants.ISAROMATIC, false);
                }
                for (int f = 0; f < atomContainer.ElectronContainerCount; f++)
                {
                    IElectronContainer electronContainer = atomContainer.getElectronContainerAt(f);
                    if (electronContainer is IBond)
                    {
                        electronContainer.setFlag(CDKConstants.ISAROMATIC, false);
                    }
                }
                for (int f = 0; f < ringSet.AtomContainerCount; f++)
                {
                    ((IRing)ringSet.getAtomContainer(f)).setFlag(CDKConstants.ISAROMATIC, false);
                }
            }

            IRing ring = null;

            RingSetManipulator.sort(ringSet);
            for (int f = 0; f < ringSet.AtomContainerCount; f++)
            {
                ring = (IRing)ringSet.getAtomContainer(f);
                //logger.debug("Testing for aromaticity in ring no ", f);
                if (AromaticityCalculator.isAromatic(ring, atomContainer))
                {
                    ring.setFlag(CDKConstants.ISAROMATIC, true);

                    for (int g = 0; g < ring.AtomCount; g++)
                    {
                        ring.getAtomAt(g).setFlag(CDKConstants.ISAROMATIC, true);
                    }

                    for (int g = 0; g < ring.ElectronContainerCount; g++)
                    {
                        IElectronContainer electronContainer = ring.getElectronContainerAt(g);
                        if (electronContainer is IBond)
                        {
                            electronContainer.setFlag(CDKConstants.ISAROMATIC, true);
                        }
                    }

                    foundSomething = true;
                    //logger.debug("This ring is aromatic: ", f);
                }
                else
                {
                    //logger.debug("This ring is *not* aromatic: ", f);
                }
            }
            return(foundSomething);
        }
Exemple #15
0
 public virtual void printAtoms(IAtomContainer ac)
 {
     for (int i = 0; i < ac.AtomCount; i++)
     {
         //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'"
         System.Console.Out.Write(ac.getAtomAt(i).getProperty("ST_ATOMNO").ToString() + ",");
     }
 }
Exemple #16
0
        /// <returns> The summed charges of all atoms in this AtomContainer.
        /// </returns>
        public static double getTotalCharge(IAtomContainer atomContainer)
        {
            double charge = 0.0;

            for (int i = 0; i < atomContainer.AtomCount; i++)
            {
                charge += atomContainer.getAtomAt(i).getCharge();
            }
            return(charge);
        }
Exemple #17
0
        /// <returns> The summed implicit hydrogens of all atoms in this AtomContainer.
        /// </returns>
        public static int getTotalHydrogenCount(IAtomContainer atomContainer)
        {
            int hCount = 0;

            for (int i = 0; i < atomContainer.AtomCount; i++)
            {
                hCount += atomContainer.getAtomAt(i).getHydrogenCount();
            }
            return(hCount);
        }
 /// <summary>  Makes an array containing the morgan numbers+element symbol of the atoms of atomContainer. This method
 /// puts the element symbol before the morgan number, usefull for finding out how many different rests are connected to an atom.
 ///
 /// </summary>
 /// <param name="atomContainer"> The atomContainer to analyse.
 /// </param>
 /// <returns>                The morgan numbers value.
 /// </returns>
 public static System.String[] getMorganNumbersWithElementSymbol(IAtomContainer atomContainer)
 {
     int[]           morgannumbers            = getMorganNumbers(atomContainer);
     System.String[] morgannumberswithelement = new System.String[morgannumbers.Length];
     for (int i = 0; i < morgannumbers.Length; i++)
     {
         morgannumberswithelement[i] = atomContainer.getAtomAt(i).Symbol + "-" + morgannumbers[i];
     }
     return(morgannumberswithelement);
 }
Exemple #19
0
 public static void resetFlags(IAtomContainer ac)
 {
     for (int f = 0; f < ac.AtomCount; f++)
     {
         ac.getAtomAt(f).setFlag(CDKConstants.VISITED, false);
     }
     for (int f = 0; f < ac.ElectronContainerCount; f++)
     {
         ac.getElectronContainerAt(f).setFlag(CDKConstants.VISITED, false);
     }
 }
 public virtual bool allSaturated(IAtomContainer ac)
 {
     //logger.debug("Are all atoms saturated?");
     for (int f = 0; f < ac.AtomCount; f++)
     {
         if (!isSaturated(ac.getAtomAt(f), ac))
         {
             return(false);
         }
     }
     return(true);
 }
Exemple #21
0
        /// <returns> The summed positive formal charges of all atoms in this AtomContainer.
        /// </returns>
        public static int getTotalPositiveFormalCharge(IAtomContainer atomContainer)
        {
            int charge = 0;

            for (int i = 0; i < atomContainer.AtomCount; i++)
            {
                double chargeI = atomContainer.getAtomAt(i).getFormalCharge();
                if (chargeI > 0)
                {
                    charge = (int)(charge + chargeI);
                }
            }
            return(charge);
        }
Exemple #22
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);
        }
Exemple #23
0
 /// <summary>  Tests if g2 a subgraph of g1
 ///
 /// </summary>
 /// <param name="g1"> first molecule
 /// </param>
 /// <param name="g2"> second molecule
 /// </param>
 /// <returns>     true if g2 a subgraph on g1
 /// </returns>
 public static bool isSubgraph(IAtomContainer g1, IAtomContainer g2)
 {
     if (g2.AtomCount > g1.AtomCount)
     {
         return(false);
     }
     // test for single atom case
     if (g2.AtomCount == 1)
     {
         IAtom atom = g2.getAtomAt(0);
         for (int i = 0; i < g1.AtomCount; i++)
         {
             IAtom atom2 = g1.getAtomAt(i);
             if (atom is IQueryAtom)
             {
                 IQueryAtom qAtom = (IQueryAtom)atom;
                 if (qAtom.matches(atom2))
                 {
                     return(true);
                 }
             }
             else if (atom2 is IQueryAtom)
             {
                 IQueryAtom qAtom = (IQueryAtom)atom2;
                 if (qAtom.matches(atom))
                 {
                     return(true);
                 }
             }
             else
             {
                 if (atom2.Symbol.Equals(atom.Symbol))
                 {
                     return(true);
                 }
             }
         }
         return(false);
     }
     if (!testSubgraphHeuristics(g1, g2))
     {
         return(false);
     }
     return(getSubgraphMap(g1, g2) != null);
 }
Exemple #24
0
        /// <summary>  Selects an optimal atom for removal
        /// See {@cdk.cite HAN96} for details
        ///
        /// </summary>
        /// <param name="ac"> The AtomContainer to search
        /// </param>
        /// <returns>     The selected Atom
        /// </returns>
        private IAtom selectAtom(IAtomContainer ac)
        {
            int minDegree = 999;
            // :-)
            int   degree  = minDegree;
            IAtom minAtom = null;
            IAtom atom    = null;

            for (int f = 0; f < ac.AtomCount; f++)
            {
                atom   = ac.getAtomAt(f);
                degree = ac.getBondCount(atom);

                if (degree < minDegree)
                {
                    minAtom   = atom;
                    minDegree = degree;
                }
            }

            return(minAtom);
        }
Exemple #25
0
 public static void makeUpDownBonds(IAtomContainer container)
 {
     for (int i = 0; i < container.AtomCount; i++)
     {
         IAtom a = container.getAtomAt(i);
         if (container.getConnectedAtoms(a).Length == 4)
         {
             int   up   = 0;
             int   down = 0;
             int   hs   = 0;
             IAtom h    = null;
             for (int k = 0; k < 4; k++)
             {
                 if (container.getBond(a, container.getConnectedAtoms(a)[k]).Stereo == CDKConstants.STEREO_BOND_UP)
                 {
                     up++;
                 }
                 if (container.getBond(a, container.getConnectedAtoms(a)[k]).Stereo == CDKConstants.STEREO_BOND_DOWN)
                 {
                     down++;
                 }
                 if (container.getBond(a, container.getConnectedAtoms(a)[k]).Stereo == CDKConstants.STEREO_BOND_NONE && container.getConnectedAtoms(a)[k].Symbol.Equals("H"))
                 {
                     h = container.getConnectedAtoms(a)[k];
                     hs++;
                 }
             }
             if (up == 0 && down == 1 && h != null && hs == 1)
             {
                 container.getBond(a, h).Stereo = CDKConstants.STEREO_BOND_UP;
             }
             if (up == 1 && down == 0 && h != null && hs == 1)
             {
                 container.getBond(a, h).Stereo = CDKConstants.STEREO_BOND_DOWN;
             }
         }
     }
 }
 public virtual void printAtoms(IAtomContainer ac)
 {
     for (int i = 0; i < ac.AtomCount; i++)
     {
         //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'"
         System.Console.Out.Write(ac.getAtomAt(i).getProperty("ST_ATOMNO").ToString() + ",");
     }
 }
 public static void resetFlags(IAtomContainer ac)
 {
     for (int f = 0; f < ac.AtomCount; f++)
     {
         ac.getAtomAt(f).setFlag(CDKConstants.VISITED, false);
     }
     for (int f = 0; f < ac.ElectronContainerCount; f++)
     {
         ac.getElectronContainerAt(f).setFlag(CDKConstants.VISITED, false);
     }
 }
        /// <summary> Reads labels.</summary>
        public virtual void readSGroup(IAtomContainer readData)
        {
            bool foundEND = false;
            while (Ready && !foundEND)
            {
                System.String command = readCommand();
                if ("END SGROUP".Equals(command))
                {
                    foundEND = true;
                }
                else
                {
                    //logger.debug("Parsing Sgroup line: " + command);
                    SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(command);
                    // parse the index
                    System.String indexString = tokenizer.NextToken();
                    //logger.warn("Skipping external index: " + indexString);
                    // parse command type
                    System.String type = tokenizer.NextToken();
                    // parse the external index
                    System.String externalIndexString = tokenizer.NextToken();
                    //logger.warn("Skipping external index: " + externalIndexString);

                    // the rest are key=value fields
                    System.Collections.Hashtable options = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
                    if (command.IndexOf("=") != -1)
                    {
                        options = parseOptions(exhaustStringTokenizer(tokenizer));
                    }

                    // now interpret line
                    if (type.StartsWith("SUP"))
                    {
                        System.Collections.IEnumerator keys = options.Keys.GetEnumerator();
                        int atomID = -1;
                        System.String label = "";
                        //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("ATOMS"))
                                {
                                    SupportClass.Tokenizer atomsTokenizer = new SupportClass.Tokenizer(value_Renamed);
                                    System.Int32.Parse(atomsTokenizer.NextToken()); // should be 1, int atomCount = 
                                    atomID = System.Int32.Parse(atomsTokenizer.NextToken());
                                }
                                else if (key.Equals("LABEL"))
                                {
                                    label = value_Renamed;
                                }
                                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);
                            }
                            if (atomID != -1 && label.Length > 0)
                            {
                                IAtom atom = readData.getAtomAt(atomID - 1);
                                if (!(atom is IPseudoAtom))
                                {
                                    atom = readData.Builder.newPseudoAtom(atom);
                                }
                                ((IPseudoAtom)atom).Label = label;
                                readData.setAtomAt(atomID - 1, atom);
                            }
                        }
                    }
                    else
                    {
                        //logger.warn("Skipping unrecognized SGROUP type: " + type);
                    }
                }
            }
        }
 /// <summary>  Return the RMSD of the heavy atoms between the 2 aligned molecules.
 /// 
 /// </summary>
 /// <param name="firstAtomContainer">               the (largest) first aligned AtomContainer which is the reference
 /// </param>
 /// <param name="secondAtomContainer">              the second aligned AtomContainer
 /// </param>
 /// <param name="mappedAtoms">            			Map: a Map of the mapped atoms
 /// </param>
 /// <param name="Coords3d">           			    boolean: true if moecules has 3D coords, false if molecules has 2D coords
 /// </param>
 /// <returns>                   				double: the value of the RMSD 
 /// </returns>
 /// <exception cref="CDK">*
 /// 
 /// </exception>
 public static double getHeavyAtomRMSD(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, System.Collections.IDictionary mappedAtoms, bool Coords3d)
 {
     //System.out.println("**** GT getAllAtomRMSD ****");
     double sum = 0;
     double RMSD = 0;
     //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'"
     System.Collections.IEnumerator firstAtoms = new CSGraphT.SupportClass.HashSetSupport(mappedAtoms.Keys).GetEnumerator();
     int firstAtomNumber = 0;
     int secondAtomNumber = 0;
     int n = 0;
     //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'"
     while (firstAtoms.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'"
         firstAtomNumber = ((System.Int32)firstAtoms.Current);
         try
         {
             secondAtomNumber = ((System.Int32)mappedAtoms[(System.Int32)firstAtomNumber]);
             IAtom firstAtom = firstAtomContainer.getAtomAt(firstAtomNumber);
             if (!firstAtom.Symbol.Equals("H"))
             {
                 if (Coords3d)
                 {
                     sum = sum + System.Math.Pow(((Point3d)firstAtom.getPoint3d()).distance(secondAtomContainer.getAtomAt(secondAtomNumber).getPoint3d()), 2);
                     n++;
                 }
                 else
                 {
                     sum = sum + System.Math.Pow(((Point2d)firstAtom.getPoint2d()).distance(secondAtomContainer.getAtomAt(secondAtomNumber).getPoint2d()), 2);
                     n++;
                 }
             }
         }
         catch (System.Exception ex)
         {
         }
     }
     RMSD = System.Math.Sqrt(sum / n);
     return RMSD;
 }
 /// <summary>  Return the RMSD of bonds length between the 2 aligned molecules.
 /// 
 /// </summary>
 /// <param name="firstAtomContainer">               the (largest) first aligned AtomContainer which is the reference
 /// </param>
 /// <param name="secondAtomContainer">              the second aligned AtomContainer
 /// </param>
 /// <param name="mappedAtoms">            			Map: a Map of the mapped atoms
 /// </param>
 /// <param name="Coords3d">           			    boolean: true if moecules has 3D coords, false if molecules has 2D coords
 /// </param>
 /// <returns>                   				double: all the RMSD of bonds length
 /// </returns>
 /// <exception cref="CDK">*
 /// 
 /// </exception>
 public static double getBondLengthRMSD(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, System.Collections.IDictionary mappedAtoms, bool Coords3d)
 {
     //System.out.println("**** GT getBondLengthRMSD ****");
     //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'"
     System.Collections.IEnumerator firstAtoms = new CSGraphT.SupportClass.HashSetSupport(mappedAtoms.Keys).GetEnumerator();
     IAtom centerAtomFirstMolecule = null;
     IAtom centerAtomSecondMolecule = null;
     IAtom[] connectedAtoms = null;
     double sum = 0;
     double n = 0;
     double distance1 = 0;
     double distance2 = 0;
     setVisitedFlagsToFalse(firstAtomContainer);
     setVisitedFlagsToFalse(secondAtomContainer);
     //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'"
     while (firstAtoms.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'"
         centerAtomFirstMolecule = firstAtomContainer.getAtomAt(((System.Int32)firstAtoms.Current));
         centerAtomFirstMolecule.setFlag(CDKConstants.VISITED, true);
         centerAtomSecondMolecule = secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(centerAtomFirstMolecule)]));
         connectedAtoms = firstAtomContainer.getConnectedAtoms(centerAtomFirstMolecule);
         for (int i = 0; i < connectedAtoms.Length; i++)
         {
             //this step is built to know if the program has already calculate a bond length (so as not to have duplicate values)
             if (!connectedAtoms[i].getFlag(CDKConstants.VISITED))
             {
                 if (Coords3d)
                 {
                     distance1 = ((Point3d)centerAtomFirstMolecule.getPoint3d()).distance(connectedAtoms[i].getPoint3d());
                     distance2 = ((Point3d)centerAtomSecondMolecule.getPoint3d()).distance(secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(connectedAtoms[i])])).getPoint3d());
                     sum = sum + System.Math.Pow((distance1 - distance2), 2);
                     n++;
                 }
                 else
                 {
                     distance1 = ((Point2d)centerAtomFirstMolecule.getPoint2d()).distance(connectedAtoms[i].getPoint2d());
                     distance2 = ((Point2d)centerAtomSecondMolecule.getPoint2d()).distance(secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(connectedAtoms[i])])).getPoint2d());
                     sum = sum + System.Math.Pow((distance1 - distance2), 2);
                     n++;
                 }
             }
         }
     }
     setVisitedFlagsToFalse(firstAtomContainer);
     setVisitedFlagsToFalse(secondAtomContainer);
     return System.Math.Sqrt(sum / n);
 }
Exemple #31
0
        /// <summary> Kruskal algorithm</summary>
        /// <param name="atomContainer">
        /// </param>
        public virtual void buildSpanningTree(IAtomContainer atomContainer)
        {
            disconnected = false;
            molecule     = atomContainer;

            V = atomContainer.AtomCount;
            E = atomContainer.getBondCount();

            sptSize = 0; edrSize = 0;
            fastFindInit(V);
            for (int i = 0; i < V; i++)
            {
                (atomContainer.getAtomAt(i)).setProperty("ST_ATOMNO", System.Convert.ToString(i + 1));
            }
            IBond bond;
            int   v1, v2;

            bondsInTree = new bool[E];

            for (int b = 0; b < E; b++)
            {
                bondsInTree[b] = false;
                bond           = atomContainer.getBondAt(b);
                //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'"
                v1 = System.Int32.Parse((bond.getAtomAt(0)).getProperty("ST_ATOMNO").ToString());
                //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'"
                v2 = System.Int32.Parse((bond.getAtomAt(1)).getProperty("ST_ATOMNO").ToString());
                //this below is a little bit  slower
                //v1 = atomContainer.getAtomNumber(bond.getAtomAt(0))+1;
                //v2 = atomContainer.getAtomNumber(bond.getAtomAt(1))+1;
                if (fastfind(v1, v2, true))
                {
                    bondsInTree[b] = true;
                    sptSize++;
                    //System.out.println("ST : includes bond between atoms "+v1+","+v2);
                }
                if (sptSize >= (V - 1))
                {
                    break;
                }
            }
            // if atomcontainer is connected then the number of bonds in the spanning tree = (No atoms-1)
            //i.e.  edgesRings = new Bond[E-V+1];
            //but to hold all bonds if atomContainer was disconnected then  edgesRings = new Bond[E-sptSize];
            if (sptSize != (V - 1))
            {
                disconnected = true;
            }
            for (int b = 0; b < E; b++)
            {
                if (!bondsInTree[b])
                {
                    //			edgesRings[edrSize] = atomContainer.getBondAt(b);
                    edrSize++;
                }
            }
            cb = new int[edrSize][];
            for (int i2 = 0; i2 < edrSize; i2++)
            {
                cb[i2] = new int[E];
            }
            for (int i = 0; i < edrSize; i++)
            {
                for (int a = 0; a < E; a++)
                {
                    cb[i][a] = 0;
                }
            }
        }
 /// <summary>  Makes an array containing the morgan numbers+element symbol of the atoms of atomContainer. This method
 /// puts the element symbol before the morgan number, usefull for finding out how many different rests are connected to an atom.
 /// 
 /// </summary>
 /// <param name="atomContainer"> The atomContainer to analyse.
 /// </param>
 /// <returns>                The morgan numbers value.
 /// </returns>
 public static System.String[] getMorganNumbersWithElementSymbol(IAtomContainer atomContainer)
 {
     int[] morgannumbers = getMorganNumbers(atomContainer);
     System.String[] morgannumberswithelement = new System.String[morgannumbers.Length];
     for (int i = 0; i < morgannumbers.Length; i++)
     {
         morgannumberswithelement[i] = atomContainer.getAtomAt(i).Symbol + "-" + morgannumbers[i];
     }
     return (morgannumberswithelement);
 }
 /// <summary>  Returns the atom of the given molecule that is closest to the given
 /// coordinates.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="xPosition"> The x coordinate
 /// </param>
 /// <param name="yPosition"> The y coordinate
 /// </param>
 /// <param name="atomCon">   The molecule that is searched for the closest atom
 /// </param>
 /// <returns>            The atom that is closest to the given coordinates
 /// </returns>
 public static IAtom getClosestAtom(int xPosition, int yPosition, IAtomContainer atomCon)
 {
     IAtom closestAtom = null;
     IAtom currentAtom;
     double smallestMouseDistance = -1;
     double mouseDistance;
     double atomX;
     double atomY;
     for (int i = 0; i < atomCon.AtomCount; i++)
     {
         currentAtom = atomCon.getAtomAt(i);
         atomX = currentAtom.X2d;
         atomY = currentAtom.Y2d;
         mouseDistance = System.Math.Sqrt(System.Math.Pow(atomX - xPosition, 2) + System.Math.Pow(atomY - yPosition, 2));
         if (mouseDistance < smallestMouseDistance || smallestMouseDistance == -1)
         {
             smallestMouseDistance = mouseDistance;
             closestAtom = currentAtom;
         }
     }
     return closestAtom;
 }
 /// <summary>  Returns the minimum and maximum X and Y coordinates of the atoms in the
 /// AtomContainer. The output is returned as: <pre>
 /// minmax[0] = minX;
 /// minmax[1] = minY;
 /// minmax[2] = maxX;
 /// minmax[3] = maxY;
 /// </pre>
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="container"> Description of the Parameter
 /// </param>
 /// <returns>            An four int array as defined above.
 /// </returns>
 //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
 public static double[] getMinMax(IAtomContainer container, System.Collections.Hashtable renderingCoordinates)
 {
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MIN_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double maxX = System.Double.MinValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MIN_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double maxY = System.Double.MinValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double minX = System.Double.MaxValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double minY = System.Double.MaxValue;
     for (int i = 0; i < container.AtomCount; i++)
     {
         IAtom atom = container.getAtomAt(i);
         //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
         if (renderingCoordinates[atom] != null)
         {
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             if (((Point2d)renderingCoordinates[atom]).x > maxX)
             {
                 //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
                 maxX = ((Point2d)renderingCoordinates[atom]).x;
             }
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             if (((Point2d)renderingCoordinates[atom]).x < minX)
             {
                 //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
                 minX = ((Point2d)renderingCoordinates[atom]).x;
             }
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             if (((Point2d)renderingCoordinates[atom]).y > maxY)
             {
                 //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
                 maxY = ((Point2d)renderingCoordinates[atom]).y;
             }
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             if (((Point2d)renderingCoordinates[atom]).y < minY)
             {
                 //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
                 minY = ((Point2d)renderingCoordinates[atom]).y;
             }
         }
     }
     double[] minmax = new double[4];
     minmax[0] = minX;
     minmax[1] = minY;
     minmax[2] = maxX;
     minmax[3] = maxY;
     return minmax;
 }
 /// <summary>  Tests if g2 a subgraph of g1
 /// 
 /// </summary>
 /// <param name="g1"> first molecule
 /// </param>
 /// <param name="g2"> second molecule
 /// </param>
 /// <returns>     true if g2 a subgraph on g1
 /// </returns>
 public static bool isSubgraph(IAtomContainer g1, IAtomContainer g2)
 {
     if (g2.AtomCount > g1.AtomCount)
         return false;
     // test for single atom case
     if (g2.AtomCount == 1)
     {
         IAtom atom = g2.getAtomAt(0);
         for (int i = 0; i < g1.AtomCount; i++)
         {
             IAtom atom2 = g1.getAtomAt(i);
             if (atom is IQueryAtom)
             {
                 IQueryAtom qAtom = (IQueryAtom)atom;
                 if (qAtom.matches(atom2))
                     return true;
             }
             else if (atom2 is IQueryAtom)
             {
                 IQueryAtom qAtom = (IQueryAtom)atom2;
                 if (qAtom.matches(atom))
                     return true;
             }
             else
             {
                 if (atom2.Symbol.Equals(atom.Symbol))
                     return true;
             }
         }
         return false;
     }
     if (!testSubgraphHeuristics(g1, g2))
         return false;
     return (getSubgraphMap(g1, g2) != null);
 }
 /// <summary>  Rotates a molecule around a given center by a given angle
 /// 
 /// </summary>
 /// <param name="atomCon"> The molecule to be rotated
 /// </param>
 /// <param name="center">  A point giving the rotation center
 /// </param>
 /// <param name="angle">   The angle by which to rotate the molecule
 /// </param>
 public static void rotate(IAtomContainer atomCon, Point2d center, double angle)
 {
     Point2d p = null;
     double distance;
     double offsetAngle;
     IAtom atom = null;
     for (int i = 0; i < atomCon.AtomCount; i++)
     {
         atom = atomCon.getAtomAt(i);
         p = atom.getPoint2d();
         offsetAngle = GeometryTools.getAngle(p.x - center.x, p.y - center.y);
         distance = p.distance(center);
         p.x = center.x + (System.Math.Sin(angle + offsetAngle) * distance);
         p.y = center.y - (System.Math.Cos(angle + offsetAngle) * distance);
     }
 }
        /// <summary>  Checks for single atom cases before doing subgraph/isomorphism search
        /// 
        /// </summary>
        /// <param name="g1"> AtomContainer to match on
        /// </param>
        /// <param name="g2"> AtomContainer as query
        /// </param>
        /// <returns>     List of List of RMap objects for the Atoms (not Bonds!), null if no single atom case
        /// </returns>
        public static System.Collections.ArrayList checkSingleAtomCases(IAtomContainer g1, IAtomContainer g2)
        {

            if (g2.AtomCount == 1)
            {
                System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
                IAtom atom = g2.getAtomAt(0);
                if (atom is IQueryAtom)
                {
                    IQueryAtom qAtom = (IQueryAtom)atom;
                    for (int i = 0; i < g1.AtomCount; i++)
                    {
                        if (qAtom.matches(g1.getAtomAt(i)))
                            arrayList.Add(new RMap(i, 0));
                    }
                }
                else
                {
                    System.String atomSymbol = atom.Symbol;
                    for (int i = 0; i < g1.AtomCount; i++)
                    {
                        if (g1.getAtomAt(i).Symbol.Equals(atomSymbol))
                            arrayList.Add(new RMap(i, 0));
                    }
                }
                return arrayList;
            }
            else if (g1.AtomCount == 1)
            {
                System.Collections.ArrayList arrayList = new System.Collections.ArrayList();
                IAtom atom = g1.getAtomAt(0);
                for (int i = 0; i < g2.AtomCount; i++)
                {
                    IAtom atom2 = g2.getAtomAt(i);
                    if (atom2 is IQueryAtom)
                    {
                        IQueryAtom qAtom = (IQueryAtom)atom2;
                        if (qAtom.matches(atom))
                            arrayList.Add(new RMap(0, i));
                    }
                    else
                    {
                        if (atom2.Symbol.Equals(atom.Symbol))
                            arrayList.Add(new RMap(0, i));
                    }
                }
                return arrayList;
            }
            else
            {
                return null;
            }
        }
        /// <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);
                }
            }
        }
Exemple #39
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);
     }
 }
 /// <summary>  Returns a Map with the AtomNumbers, the first number corresponds to the first (or the largest
 /// AtomContainer) atomContainer. 
 /// 
 /// Only for similar and aligned molecules with coordinates!
 /// 
 /// </summary>
 /// <param name="firstAtomContainer">               the (largest) first aligned AtomContainer which is the reference
 /// </param>
 /// <param name="secondAtomContainer">              the second aligned AtomContainer
 /// </param>
 /// <returns>                   				a Map of the mapped atoms
 /// </returns>
 /// <exception cref="CDKException"> Description of the Exception
 /// </exception>
 public static System.Collections.IDictionary mapAtomsOfAlignedStructures(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, System.Collections.IDictionary mappedAtoms)
 {
     //System.out.println("**** GT MAP ATOMS ****");
     //Map atoms onto each other
     if (firstAtomContainer.AtomCount < 1 & secondAtomContainer.AtomCount < 1)
     {
         return mappedAtoms;
     }
     RMap map;
     IAtom atom1;
     IAtom atom2;
     int countMappedAtoms = 0;
     System.Collections.IList list;
     try
     {
         list = UniversalIsomorphismTester.getSubgraphAtomsMap(firstAtomContainer, secondAtomContainer);
         //System.out.println("ListSize:"+list.size());
         for (int i = 0; i < list.Count; i++)
         {
             map = (RMap)list[i];
             atom1 = firstAtomContainer.getAtomAt(map.Id1);
             atom2 = secondAtomContainer.getAtomAt(map.Id2);
             if (checkAtomMapping(firstAtomContainer, secondAtomContainer, firstAtomContainer.getAtomNumber(atom1), secondAtomContainer.getAtomNumber(atom2)))
             {
                 mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(atom1)] = (System.Int32)secondAtomContainer.getAtomNumber(atom2);
                 countMappedAtoms++;
                 //System.out.println("#:"+countMappedAtoms+" Atom:"+firstAtomContainer.getAtomNumber(atom1)+" is mapped to Atom:"+secondAtomContainer.getAtomNumber(atom2));
             }
             else
             {
                 System.Console.Out.WriteLine("Error: Atoms are not similar !!");
             }
         }
     }
     catch (CDKException e)
     {
         // TODO Auto-generated catch block
         System.Console.Out.WriteLine("Error in UniversalIsomorphismTester due to:");
         SupportClass.WriteStackTrace(e, Console.Error);
     }
     return mappedAtoms;
 }
        /// <summary>  Uses precomputed set of ALL rings and performs an aromaticity detection
        /// based on Hueckels 4n + 2 rule.
        /// 
        /// </summary>
        /// <param name="ringSet">                set of ALL rings
        /// </param>
        /// <param name="removeAromaticityFlags"> Leaves ChemObjects that are already marked as
        /// aromatic as they are
        /// </param>
        /// <param name="atomContainer">          AtomContainer to be searched for rings
        /// </param>
        /// <returns>                         True, if molecules contains an
        /// aromatic feature
        /// </returns>
        public static bool detectAromaticity(IAtomContainer atomContainer, IRingSet ringSet, bool removeAromaticityFlags)
        {
            bool foundSomething = false;
            if (removeAromaticityFlags)
            {
                for (int f = 0; f < atomContainer.AtomCount; f++)
                {
                    atomContainer.getAtomAt(f).setFlag(CDKConstants.ISAROMATIC, false);
                }
                for (int f = 0; f < atomContainer.ElectronContainerCount; f++)
                {
                    IElectronContainer electronContainer = atomContainer.getElectronContainerAt(f);
                    if (electronContainer is IBond)
                    {
                        electronContainer.setFlag(CDKConstants.ISAROMATIC, false);
                    }
                }
                for (int f = 0; f < ringSet.AtomContainerCount; f++)
                {
                    ((IRing)ringSet.getAtomContainer(f)).setFlag(CDKConstants.ISAROMATIC, false);
                }
            }

            IRing ring = null;
            RingSetManipulator.sort(ringSet);
            for (int f = 0; f < ringSet.AtomContainerCount; f++)
            {
                ring = (IRing)ringSet.getAtomContainer(f);
                //logger.debug("Testing for aromaticity in ring no ", f);
                if (AromaticityCalculator.isAromatic(ring, atomContainer))
                {
                    ring.setFlag(CDKConstants.ISAROMATIC, true);

                    for (int g = 0; g < ring.AtomCount; g++)
                    {
                        ring.getAtomAt(g).setFlag(CDKConstants.ISAROMATIC, true);
                    }

                    for (int g = 0; g < ring.ElectronContainerCount; g++)
                    {
                        IElectronContainer electronContainer = ring.getElectronContainerAt(g);
                        if (electronContainer is IBond)
                        {
                            electronContainer.setFlag(CDKConstants.ISAROMATIC, true);
                        }
                    }

                    foundSomething = true;
                    //logger.debug("This ring is aromatic: ", f);
                }
                else
                {
                    //logger.debug("This ring is *not* aromatic: ", f);
                }
            }
            return foundSomething;
        }
 private static bool checkAtomMapping(IAtomContainer firstAC, IAtomContainer secondAC, int posFirstAtom, int posSecondAtom)
 {
     IAtom firstAtom = firstAC.getAtomAt(posFirstAtom);
     IAtom secondAtom = secondAC.getAtomAt(posSecondAtom);
     if (firstAtom.Symbol.Equals(secondAtom.Symbol) && firstAC.getConnectedAtoms(firstAtom).Length == secondAC.getConnectedAtoms(secondAtom).Length && firstAtom.BondOrderSum == secondAtom.BondOrderSum && firstAtom.MaxBondOrder == secondAtom.MaxBondOrder)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
Exemple #43
0
        /// <summary> Reads labels.</summary>
        public virtual void readSGroup(IAtomContainer readData)
        {
            bool foundEND = false;

            while (Ready && !foundEND)
            {
                System.String command = readCommand();
                if ("END SGROUP".Equals(command))
                {
                    foundEND = true;
                }
                else
                {
                    //logger.debug("Parsing Sgroup line: " + command);
                    SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(command);
                    // parse the index
                    System.String indexString = tokenizer.NextToken();
                    //logger.warn("Skipping external index: " + indexString);
                    // parse command type
                    System.String type = tokenizer.NextToken();
                    // parse the external index
                    System.String externalIndexString = tokenizer.NextToken();
                    //logger.warn("Skipping external index: " + externalIndexString);

                    // the rest are key=value fields
                    System.Collections.Hashtable options = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
                    if (command.IndexOf("=") != -1)
                    {
                        options = parseOptions(exhaustStringTokenizer(tokenizer));
                    }

                    // now interpret line
                    if (type.StartsWith("SUP"))
                    {
                        System.Collections.IEnumerator keys = options.Keys.GetEnumerator();
                        int           atomID = -1;
                        System.String label  = "";
                        //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("ATOMS"))
                                {
                                    SupportClass.Tokenizer atomsTokenizer = new SupportClass.Tokenizer(value_Renamed);
                                    System.Int32.Parse(atomsTokenizer.NextToken()); // should be 1, int atomCount =
                                    atomID = System.Int32.Parse(atomsTokenizer.NextToken());
                                }
                                else if (key.Equals("LABEL"))
                                {
                                    label = value_Renamed;
                                }
                                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);
                            }
                            if (atomID != -1 && label.Length > 0)
                            {
                                IAtom atom = readData.getAtomAt(atomID - 1);
                                if (!(atom is IPseudoAtom))
                                {
                                    atom = readData.Builder.newPseudoAtom(atom);
                                }
                                ((IPseudoAtom)atom).Label = label;
                                readData.setAtomAt(atomID - 1, atom);
                            }
                        }
                    }
                    else
                    {
                        //logger.warn("Skipping unrecognized SGROUP type: " + type);
                    }
                }
            }
        }
Exemple #44
0
        /// <summary>  Checks some simple heuristics for whether the subgraph query can
        /// realistically be a subgraph of the supergraph. If, for example, the
        /// number of nitrogen atoms in the query is larger than that of the supergraph
        /// it cannot be part of it.
        ///
        /// </summary>
        /// <param name="ac1"> the supergraph to be checked
        /// </param>
        /// <param name="ac2"> the subgraph to be tested for
        /// </param>
        /// <returns>    true if the subgraph ac2 has a chance to be a subgraph of ac1
        ///
        /// </returns>

        private static bool testSubgraphHeuristics(IAtomContainer ac1, IAtomContainer ac2)
        {
            int ac1SingleBondCount   = 0;
            int ac1DoubleBondCount   = 0;
            int ac1TripleBondCount   = 0;
            int ac1AromaticBondCount = 0;
            int ac2SingleBondCount   = 0;
            int ac2DoubleBondCount   = 0;
            int ac2TripleBondCount   = 0;
            int ac2AromaticBondCount = 0;
            int ac1SCount            = 0;
            int ac1OCount            = 0;
            int ac1NCount            = 0;
            int ac1FCount            = 0;
            int ac1ClCount           = 0;
            int ac1BrCount           = 0;
            int ac1ICount            = 0;
            int ac1CCount            = 0;

            int ac2SCount  = 0;
            int ac2OCount  = 0;
            int ac2NCount  = 0;
            int ac2FCount  = 0;
            int ac2ClCount = 0;
            int ac2BrCount = 0;
            int ac2ICount  = 0;
            int ac2CCount  = 0;

            IBond bond;
            IAtom atom;

            for (int i = 0; i < ac1.getBondCount(); i++)
            {
                bond = ac1.getBondAt(i);
                if (bond.getFlag(CDKConstants.ISAROMATIC))
                {
                    ac1AromaticBondCount++;
                }
                else if (bond.Order == 1)
                {
                    ac1SingleBondCount++;
                }
                else if (bond.Order == 2)
                {
                    ac1DoubleBondCount++;
                }
                else if (bond.Order == 3)
                {
                    ac1TripleBondCount++;
                }
            }
            for (int i = 0; i < ac2.getBondCount(); i++)
            {
                bond = ac2.getBondAt(i);
                if (bond is IQueryBond)
                {
                    continue;
                }
                if (bond.getFlag(CDKConstants.ISAROMATIC))
                {
                    ac2AromaticBondCount++;
                }
                else if (bond.Order == 1)
                {
                    ac2SingleBondCount++;
                }
                else if (bond.Order == 2)
                {
                    ac2DoubleBondCount++;
                }
                else if (bond.Order == 3)
                {
                    ac2TripleBondCount++;
                }
            }

            if (ac2SingleBondCount > ac1SingleBondCount)
            {
                return(false);
            }
            if (ac2AromaticBondCount > ac1AromaticBondCount)
            {
                return(false);
            }
            if (ac2DoubleBondCount > ac1DoubleBondCount)
            {
                return(false);
            }
            if (ac2TripleBondCount > ac1TripleBondCount)
            {
                return(false);
            }

            for (int i = 0; i < ac1.AtomCount; i++)
            {
                atom = ac1.getAtomAt(i);
                if (atom.Symbol.Equals("S"))
                {
                    ac1SCount++;
                }
                else if (atom.Symbol.Equals("N"))
                {
                    ac1NCount++;
                }
                else if (atom.Symbol.Equals("O"))
                {
                    ac1OCount++;
                }
                else if (atom.Symbol.Equals("F"))
                {
                    ac1FCount++;
                }
                else if (atom.Symbol.Equals("Cl"))
                {
                    ac1ClCount++;
                }
                else if (atom.Symbol.Equals("Br"))
                {
                    ac1BrCount++;
                }
                else if (atom.Symbol.Equals("I"))
                {
                    ac1ICount++;
                }
                else if (atom.Symbol.Equals("C"))
                {
                    ac1CCount++;
                }
            }
            for (int i = 0; i < ac2.AtomCount; i++)
            {
                atom = ac2.getAtomAt(i);
                if (atom is IQueryAtom)
                {
                    continue;
                }
                if (atom.Symbol.Equals("S"))
                {
                    ac2SCount++;
                }
                else if (atom.Symbol.Equals("N"))
                {
                    ac2NCount++;
                }
                else if (atom.Symbol.Equals("O"))
                {
                    ac2OCount++;
                }
                else if (atom.Symbol.Equals("F"))
                {
                    ac2FCount++;
                }
                else if (atom.Symbol.Equals("Cl"))
                {
                    ac2ClCount++;
                }
                else if (atom.Symbol.Equals("Br"))
                {
                    ac2BrCount++;
                }
                else if (atom.Symbol.Equals("I"))
                {
                    ac2ICount++;
                }
                else if (atom.Symbol.Equals("C"))
                {
                    ac2CCount++;
                }
            }

            if (ac1SCount < ac2SCount)
            {
                return(false);
            }
            if (ac1NCount < ac2NCount)
            {
                return(false);
            }
            if (ac1OCount < ac2OCount)
            {
                return(false);
            }
            if (ac1FCount < ac2FCount)
            {
                return(false);
            }
            if (ac1ClCount < ac2ClCount)
            {
                return(false);
            }
            if (ac1BrCount < ac2BrCount)
            {
                return(false);
            }
            if (ac1ICount < ac2ICount)
            {
                return(false);
            }
            if (ac1CCount < ac2CCount)
            {
                return(false);
            }


            return(true);
        }
        /// <summary>  Selects an optimal atom for removal
        /// See {@cdk.cite HAN96} for details
        /// 
        /// </summary>
        /// <param name="ac"> The AtomContainer to search
        /// </param>
        /// <returns>     The selected Atom
        /// </returns>
        private IAtom selectAtom(IAtomContainer ac)
        {
            int minDegree = 999;
            // :-)
            int degree = minDegree;
            IAtom minAtom = null;
            IAtom atom = null;
            for (int f = 0; f < ac.AtomCount; f++)
            {
                atom = ac.getAtomAt(f);
                degree = ac.getBondCount(atom);

                if (degree < minDegree)
                {
                    minAtom = atom;
                    minDegree = degree;
                }
            }

            return minAtom;
        }
 /// <summary>  Configures atoms in an AtomContainer to 
 /// carry all the correct data according to their element type.
 /// 
 /// </summary>
 /// <param name="container"> The AtomContainer to be configured
 /// </param>
 public virtual void configureAtoms(IAtomContainer container)
 {
     for (int f = 0; f < container.AtomCount; f++)
     {
         configure(container.getAtomAt(f));
     }
 }
        /// <summary>  Returns a Map with the AtomNumbers, the first number corresponds to the first (or the largest
        /// AtomContainer) atomcontainer. It is recommend to sort the atomContainer due to their number of atoms before
        /// calling this function.
        /// 
        /// The molecules needs to be aligned before! (coordinates are needed)
        /// 
        /// </summary>
        /// <param name="firstAtomContainer">               the (largest) first aligned AtomContainer which is the reference
        /// </param>
        /// <param name="secondAtomContainer">              the second aligned AtomContainer
        /// </param>
        /// <param name="searchRadius">              		the radius of space search from each atom
        /// </param>
        /// <returns>                   				a Map of the mapped atoms
        /// </returns>
        /// <exception cref="CDKException"> Description of the Exception
        /// </exception>
        public static System.Collections.IDictionary mapAtomsOfAlignedStructures(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, double searchRadius, System.Collections.IDictionary mappedAtoms)
        {
            //to return the mapping setProperty("MappedAtom",AtomNumber)
            //System.out.println("**** MAP ATOMS ****");
            getLargestAtomContainer(firstAtomContainer, secondAtomContainer);
            double[][] distanceMatrix = new double[firstAtomContainer.AtomCount][];
            for (int i = 0; i < firstAtomContainer.AtomCount; i++)
            {
                distanceMatrix[i] = new double[secondAtomContainer.AtomCount];
            }
            for (int i = 0; i < firstAtomContainer.AtomCount; i++)
            {
                Point3d firstAtomPoint = firstAtomContainer.getAtomAt(i).getPoint3d();
                //System.out.println("Closest atoms of "+firstAtomContainer.getAtoms()[i].getSymbol()+" :");
                for (int j = 0; j < secondAtomContainer.AtomCount; j++)
                {
                    distanceMatrix[i][j] = firstAtomPoint.distance(secondAtomContainer.getAtomAt(j).getPoint3d());
                    //System.out.println("Distance "+i+" "+j+":"+distanceMatrix[i][j]);
                }
                //System.out.println(" Atoms from the secondAtomContainer");
            }

            //System.out.println();
            //System.out.print("\t");
            //for (int j=0;j<secondAtomContainer.getAtomCount();j++){
            //System.out.print(j+" "+secondAtomContainer.getAtomAt(j).getSymbol()+"\t");
            //}
            double tmp = 0;
            for (int i = 0; i < firstAtomContainer.AtomCount; i++)
            {
                //System.out.print(i+" "+firstAtomContainer.getAtomAt(i).getSymbol()+"\t");
                for (int j = 0; j < secondAtomContainer.AtomCount; j++)
                {
                    tmp = System.Math.Floor(distanceMatrix[i][j] * 10);
                    //System.out.println(tmp/10+"\t");
                }
            }

            double minimumDistance = searchRadius;
            int countMappedAtoms = 0;
            for (int i = 0; i < firstAtomContainer.AtomCount; i++)
            {
                minimumDistance = searchRadius;
                for (int j = 0; j < secondAtomContainer.AtomCount; j++)
                {
                    if (distanceMatrix[i][j] < searchRadius && distanceMatrix[i][j] < minimumDistance)
                    {
                        //System.out.println("Distance OK "+i+" "+j+":"+distanceMatrix[i][j]+" AtomCheck:"+checkAtomMapping(firstAtomContainer,secondAtomContainer, i, j));
                        //check atom properties
                        if (checkAtomMapping(firstAtomContainer, secondAtomContainer, i, j))
                        {
                            minimumDistance = distanceMatrix[i][j];
                            mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(firstAtomContainer.getAtomAt(i))] = (System.Int32)secondAtomContainer.getAtomNumber(secondAtomContainer.getAtomAt(j));
                            //firstAtomContainer.getAtomAt(i).setProperty("MappedAtom",new Integer(secondAtomContainer.getAtomNumber(secondAtomContainer.getAtomAt(j))));
                            countMappedAtoms++;
                            //System.out.println("#:"+countMappedAtoms+" Atom:"+i+" is mapped to Atom"+j);
                            //System.out.println(firstAtomContainer.getConnectedAtoms(firstAtomContainer.getAtomAt(i)).length);
                        }
                    }
                }
            }
            return mappedAtoms;
        }
        /// <summary>  Reads a set of vibrations into ChemFrame.
        ///
        /// </summary>
        /// <param name="model">           Description of the Parameter
        /// </param>
        /// <exception cref="IOException"> if an I/O error occurs
        /// </exception>
        //	private void readFrequencies(IChemModel model) throws IOException
        //	{

        /*
         *  FIXME: this is yet to be ported
         *  String line;
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  while ((line != null) && line.startsWith(" Frequencies --")) {
         *  Vector currentVibs = new Vector();
         *  StringReader vibValRead = new StringReader(line.substring(15));
         *  StreamTokenizer token = new StreamTokenizer(vibValRead);
         *  while (token.nextToken() != StreamTokenizer.TT_EOF) {
         *  Vibration vib = new Vibration(Double.toString(token.nval));
         *  currentVibs.addElement(vib);
         *  }
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  for (int i = 0; i < frame.getAtomCount(); ++i) {
         *  line = input.readLine();
         *  StringReader vectorRead = new StringReader(line);
         *  token = new StreamTokenizer(vectorRead);
         *  token.nextToken();
         *  / ignore first token
         *  token.nextToken();
         *  / ignore second token
         *  for (int j = 0; j < currentVibs.size(); ++j) {
         *  double[] v = new double[3];
         *  if (token.nextToken() == StreamTokenizer.TT_NUMBER) {
         *  v[0] = token.nval;
         *  } else {
         *  throw new IOException("Error reading frequency");
         *  }
         *  if (token.nextToken() == StreamTokenizer.TT_NUMBER) {
         *  v[1] = token.nval;
         *  } else {
         *  throw new IOException("Error reading frequency");
         *  }
         *  if (token.nextToken() == StreamTokenizer.TT_NUMBER) {
         *  v[2] = token.nval;
         *  } else {
         *  throw new IOException("Error reading frequency");
         *  }
         *  ((Vibration) currentVibs.elementAt(j)).addAtomVector(v);
         *  }
         *  }
         *  for (int i = 0; i < currentVibs.size(); ++i) {
         *  frame.addVibration((Vibration) currentVibs.elementAt(i));
         *  }
         *  line = input.readLine();
         *  line = input.readLine();
         *  line = input.readLine();
         *  }
         */
        //	}


        /// <summary> Reads NMR nuclear shieldings.
        ///
        /// </summary>
        /// <param name="model">    Description of the Parameter
        /// </param>
        /// <param name="labelLine">Description of the Parameter
        /// </param>
        /// <throws>  CDKException Description of the Exception </throws>
        private void readNMRData(IChemModel model, System.String labelLine)
        {
            IAtomContainer ac = ChemModelManipulator.getAllInOneContainer(model);

            // Determine label for properties
            System.String label;
            if (labelLine.IndexOf("Diamagnetic") >= 0)
            {
                label = "Diamagnetic Magnetic shielding (Isotropic)";
            }
            else if (labelLine.IndexOf("Paramagnetic") >= 0)
            {
                label = "Paramagnetic Magnetic shielding (Isotropic)";
            }
            else
            {
                label = "Magnetic shielding (Isotropic)";
            }
            int atomIndex = 0;

            for (int i = 0; i < atomCount; ++i)
            {
                try
                {
                    System.String line = input.ReadLine().Trim();
                    while (line.IndexOf("Isotropic") < 0)
                    {
                        if (line == null)
                        {
                            return;
                        }
                        line = input.ReadLine().Trim();
                    }
                    SupportClass.Tokenizer st1 = new SupportClass.Tokenizer(line);

                    // Find Isotropic label
                    while (st1.HasMoreTokens())
                    {
                        if (st1.NextToken().Equals("Isotropic"))
                        {
                            break;
                        }
                    }

                    // Find Isotropic value
                    while (st1.HasMoreTokens())
                    {
                        if (st1.NextToken().Equals("="))
                        {
                            break;
                        }
                    }
                    double shielding = System.Double.Parse(st1.NextToken());
                    //logger.info("Type of shielding: " + label);
                    ac.getAtomAt(atomIndex).setProperty(CDKConstants.ISOTROPIC_SHIELDING, (System.Object)shielding);
                    ++atomIndex;
                }
                catch (System.Exception exc)
                {
                    //logger.debug("failed to read line from gaussian98 file where I expected one.");
                }
            }
        }
 /// <summary>  Multiplies all the coordinates of the atoms of the given molecule with the
 /// scalefactor.
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="atomCon">     The molecule to be scaled
 /// </param>
 /// <param name="scaleFactor"> Description of the Parameter
 /// </param>
 public static void scaleMolecule(IAtomContainer atomCon, double scaleFactor)
 {
     for (int i = 0; i < atomCon.AtomCount; i++)
     {
         if (atomCon.getAtomAt(i).getPoint2d() != null)
         {
             atomCon.getAtomAt(i).getPoint2d().x *= scaleFactor;
             atomCon.getAtomAt(i).getPoint2d().y *= scaleFactor;
         }
     }
 }
		public virtual bool allSaturated(IAtomContainer ac)
		{
			//logger.debug("Are all atoms saturated?");
			for (int f = 0; f < ac.AtomCount; f++)
			{
				if (!isSaturated(ac.getAtomAt(f), ac))
				{
					return false;
				}
			}
			return true;
		}
 private static IAtomContainer setVisitedFlagsToFalse(IAtomContainer atomContainer)
 {
     for (int i = 0; i < atomContainer.AtomCount; i++)
     {
         atomContainer.getAtomAt(i).setFlag(CDKConstants.VISITED, false);
     }
     return atomContainer;
 }
Exemple #52
0
        /// <summary> Produces an AtomContainer without explicit Hs but with H count from one with Hs.
        /// The new molecule is a deep copy.
        ///
        /// </summary>
        /// <param name="atomContainer">The AtomContainer from which to remove the hydrogens
        /// </param>
        /// <returns>              The molecule without Hs.
        /// </returns>
        /// <cdk.keyword>          hydrogen, removal </cdk.keyword>
        public static IAtomContainer removeHydrogens(IAtomContainer atomContainer)
        {
            //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
            System.Collections.IDictionary map    = new System.Collections.Hashtable(); // maps original atoms to clones.
            System.Collections.IList       remove = new System.Collections.ArrayList(); // lists removed Hs.

            // Clone atoms except those to be removed.
            IMolecule mol   = atomContainer.Builder.newMolecule();
            int       count = atomContainer.AtomCount;

            for (int i = 0; i < count; i++)
            {
                // Clone/remove this atom?
                IAtom atom = atomContainer.getAtomAt(i);
                if (!atom.Symbol.Equals("H"))
                {
                    IAtom clonedAtom = null;
                    try
                    {
                        clonedAtom = (IAtom)atom.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)
                    {
                        // TODO Auto-generated catch block
                        SupportClass.WriteStackTrace(e, Console.Error);
                    }
                    clonedAtom.setHydrogenCount(0);
                    mol.addAtom(clonedAtom);
                    map[atom] = clonedAtom;
                }
                else
                {
                    remove.Add(atom); // maintain list of removed H.
                }
            }

            // Clone bonds except those involving removed atoms.
            count = atomContainer.getBondCount();
            for (int i = 0; i < count; i++)
            {
                // Check bond.
                //UPGRADE_NOTE: Final was removed from the declaration of 'bond '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                IBond   bond        = atomContainer.getBondAt(i);
                IAtom[] atoms       = bond.getAtoms();
                bool    removedBond = false;
                //UPGRADE_NOTE: Final was removed from the declaration of 'length '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                int length = atoms.Length;
                for (int k = 0; k < length; k++)
                {
                    if (remove.Contains(atoms[k]))
                    {
                        removedBond = true;
                        break;
                    }
                }

                // Clone/remove this bond?
                if (!removedBond)
                // if (!remove.contains(atoms[0]) && !remove.contains(atoms[1]))
                {
                    IBond clone = null;
                    try
                    {
                        clone = (IBond)atomContainer.getBondAt(i).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)
                    {
                        // TODO Auto-generated catch block
                        SupportClass.WriteStackTrace(e, Console.Error);
                    }
                    clone.setAtoms(new IAtom[] { (IAtom)map[atoms[0]], (IAtom)map[atoms[1]] });
                    mol.addBond(clone);
                }
            }

            // Recompute hydrogen counts of neighbours of removed Hydrogens.
            //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 = remove.GetEnumerator(); i.MoveNext();)
            {
                // Process neighbours.
                //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'"
                //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 n = atomContainer.getConnectedAtomsVector((IAtom)i.Current).GetEnumerator(); n.MoveNext();)
                {
                    //UPGRADE_NOTE: Final was removed from the declaration of 'neighb '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                    //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'"
                    IAtom neighb = (IAtom)map[n.Current];
                    neighb.setHydrogenCount(neighb.getHydrogenCount() + 1);
                }
            }
            mol.Properties = atomContainer.Properties;
            mol.Flags      = atomContainer.Flags;

            return(mol);
        }
 /// <summary>  Return the variation of each angle value between the 2 aligned molecules.
 /// 
 /// </summary>
 /// <param name="firstAtomContainer">               the (largest) first aligned AtomContainer which is the reference
 /// </param>
 /// <param name="secondAtomContainer">              the second aligned AtomContainer
 /// </param>
 /// <param name="mappedAtoms">            			Map: a Map of the mapped atoms
 /// </param>
 /// <returns>                   				double: the value of the RMSD 
 /// </returns>
 /// <exception cref="CDK">*
 /// 
 /// </exception>
 public static double getAngleRMSD(IAtomContainer firstAtomContainer, IAtomContainer secondAtomContainer, System.Collections.IDictionary mappedAtoms)
 {
     //System.out.println("**** GT getAngleRMSD ****");
     //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'CSGraphT.SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'"
     System.Collections.IEnumerator firstAtoms = new CSGraphT.SupportClass.HashSetSupport(mappedAtoms.Keys).GetEnumerator();
     //System.out.println("mappedAtoms:"+mappedAtoms.toString());
     IAtom firstAtomfirstAC = null;
     IAtom centerAtomfirstAC = null;
     IAtom firstAtomsecondAC = null;
     IAtom secondAtomsecondAC = null;
     IAtom centerAtomsecondAC = null;
     double angleFirstMolecule = 0;
     double angleSecondMolecule = 0;
     double sum = 0;
     double n = 0;
     //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'"
     while (firstAtoms.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'"
         int firstAtomNumber = ((System.Int32)firstAtoms.Current);
         centerAtomfirstAC = firstAtomContainer.getAtomAt(firstAtomNumber);
         IAtom[] connectedAtoms = firstAtomContainer.getConnectedAtoms(centerAtomfirstAC);
         if (connectedAtoms.Length > 1)
         {
             //System.out.println("If "+centerAtomfirstAC.getSymbol()+" is the center atom :");
             for (int i = 0; i < connectedAtoms.Length - 1; i++)
             {
                 firstAtomfirstAC = connectedAtoms[i];
                 for (int j = i + 1; j < connectedAtoms.Length; j++)
                 {
                     angleFirstMolecule = getAngle(centerAtomfirstAC, firstAtomfirstAC, connectedAtoms[j]);
                     centerAtomsecondAC = secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(centerAtomfirstAC)]));
                     firstAtomsecondAC = secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(firstAtomfirstAC)]));
                     secondAtomsecondAC = secondAtomContainer.getAtomAt(((System.Int32)mappedAtoms[(System.Int32)firstAtomContainer.getAtomNumber(connectedAtoms[j])]));
                     angleSecondMolecule = getAngle(centerAtomsecondAC, firstAtomsecondAC, secondAtomsecondAC);
                     sum = sum + System.Math.Pow(angleFirstMolecule - angleSecondMolecule, 2);
                     n++;
                     //System.out.println("Error for the "+firstAtomfirstAC.getSymbol().toLowerCase()+"-"+centerAtomfirstAC.getSymbol()+"-"+connectedAtoms[j].getSymbol().toLowerCase()+" Angle :"+deltaAngle+" degrees");
                 }
             }
         } //if
     }
     return System.Math.Sqrt(sum / n);
 }
        /// <summary> Kruskal algorithm</summary>
        /// <param name="atomContainer">
        /// </param>
        public virtual void buildSpanningTree(IAtomContainer atomContainer)
        {
            disconnected = false;
            molecule = atomContainer;

            V = atomContainer.AtomCount;
            E = atomContainer.getBondCount();

            sptSize = 0; edrSize = 0;
            fastFindInit(V);
            for (int i = 0; i < V; i++)
            {
                (atomContainer.getAtomAt(i)).setProperty("ST_ATOMNO", System.Convert.ToString(i + 1));
            }
            IBond bond;
            int v1, v2;
            bondsInTree = new bool[E];

            for (int b = 0; b < E; b++)
            {
                bondsInTree[b] = false;
                bond = atomContainer.getBondAt(b);
                //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'"
                v1 = System.Int32.Parse((bond.getAtomAt(0)).getProperty("ST_ATOMNO").ToString());
                //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'"
                v2 = System.Int32.Parse((bond.getAtomAt(1)).getProperty("ST_ATOMNO").ToString());
                //this below is a little bit  slower
                //v1 = atomContainer.getAtomNumber(bond.getAtomAt(0))+1; 
                //v2 = atomContainer.getAtomNumber(bond.getAtomAt(1))+1;
                if (fastfind(v1, v2, true))
                {
                    bondsInTree[b] = true;
                    sptSize++;
                    //System.out.println("ST : includes bond between atoms "+v1+","+v2);
                }
                if (sptSize >= (V - 1))
                    break;
            }
            // if atomcontainer is connected then the number of bonds in the spanning tree = (No atoms-1)
            //i.e.  edgesRings = new Bond[E-V+1];
            //but to hold all bonds if atomContainer was disconnected then  edgesRings = new Bond[E-sptSize]; 
            if (sptSize != (V - 1))
                disconnected = true;
            for (int b = 0; b < E; b++)
                if (!bondsInTree[b])
                {
                    //			edgesRings[edrSize] = atomContainer.getBondAt(b);
                    edrSize++;
                }
            cb = new int[edrSize][];
            for (int i2 = 0; i2 < edrSize; i2++)
            {
                cb[i2] = new int[E];
            }
            for (int i = 0; i < edrSize; i++)
                for (int a = 0; a < E; a++)
                    cb[i][a] = 0;
        }
 /// <summary>  Multiplies all the coordinates of the atoms of the given molecule with the
 /// scalefactor, using an external set of coordinates..
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="atomCon">     The molecule to be scaled
 /// </param>
 /// <param name="scaleFactor"> Description of the Parameter
 /// </param>
 /// <param name="renderingCoordinates"> The set of coordinates to use coming from RendererModel2D
 /// </param>
 //UPGRADE_TODO: Class 'java.util.HashMap' was converted to 'System.Collections.Hashtable' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMap'"
 public static void scaleMolecule(IAtomContainer atomCon, double scaleFactor, System.Collections.Hashtable renderingCoordinates)
 {
     for (int i = 0; i < atomCon.AtomCount; i++)
     {
         //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
         if (renderingCoordinates[atomCon.getAtomAt(i)] != null)
         {
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             ((Point2d)renderingCoordinates[atomCon.getAtomAt(i)]).x *= scaleFactor;
             //UPGRADE_TODO: Method 'java.util.HashMap.get' was converted to 'System.Collections.Hashtable.Item' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilHashMapget_javalangObject'"
             ((Point2d)renderingCoordinates[atomCon.getAtomAt(i)]).y *= scaleFactor;
         }
     }
 }
		/// <summary> The method is known to fail for certain compounds. For more information, see
		/// cdk.test.limitations package.
		/// 
		/// </summary>
		public virtual void  saturate(IAtomContainer atomContainer)
		{
			/* newSaturate(atomContainer);
			}
			public void oldSaturate(AtomContainer atomContainer) throws CDKException { */
			IAtom partner = null;
			IAtom atom = null;
			IAtom[] partners = null;
			IAtomType[] atomTypes1 = null;
			IAtomType[] atomTypes2 = null;
			IBond bond = null;
			for (int i = 1; i < 4; i++)
			{
				// handle atoms with degree 1 first and then proceed to higher order
				for (int f = 0; f < atomContainer.AtomCount; f++)
				{
					atom = atomContainer.getAtomAt(f);
					//logger.debug("symbol: ", atom.Symbol);
					atomTypes1 = getAtomTypeFactory(atom.Builder).getAtomTypes(atom.Symbol);
					if (atomTypes1.Length > 0)
					{
						//logger.debug("first atom type: ", atomTypes1[0]);
						if (atomContainer.getBondCount(atom) == i)
						{
							if (atom.getFlag(CDKConstants.ISAROMATIC) && atomContainer.getBondOrderSum(atom) < atomTypes1[0].BondOrderSum - atom.getHydrogenCount())
							{
								partners = atomContainer.getConnectedAtoms(atom);
								for (int g = 0; g < partners.Length; g++)
								{
									partner = partners[g];
									//logger.debug("Atom has " + partners.Length + " partners");
									atomTypes2 = getAtomTypeFactory(atom.Builder).getAtomTypes(partner.Symbol);
									if (atomTypes2.Length == 0)
										return ;
									if (atomContainer.getBond(partner, atom).getFlag(CDKConstants.ISAROMATIC) && atomContainer.getBondOrderSum(partner) < atomTypes2[0].BondOrderSum - partner.getHydrogenCount())
									{
										//logger.debug("Partner has " + atomContainer.getBondOrderSum(partner) + ", may have: " + atomTypes2[0].BondOrderSum);
										bond = atomContainer.getBond(atom, partner);
										//logger.debug("Bond order was " + bond.Order);
										bond.Order = bond.Order + 1;
										//logger.debug("Bond order now " + bond.Order);
										break;
									}
								}
							}
							if (atomContainer.getBondOrderSum(atom) < atomTypes1[0].BondOrderSum - atom.getHydrogenCount())
							{
								//logger.debug("Atom has " + atomContainer.getBondOrderSum(atom) + ", may have: " + atomTypes1[0].BondOrderSum);
								partners = atomContainer.getConnectedAtoms(atom);
								for (int g = 0; g < partners.Length; g++)
								{
									partner = partners[g];
									//logger.debug("Atom has " + partners.Length + " partners");
									atomTypes2 = getAtomTypeFactory(atom.Builder).getAtomTypes(partner.Symbol);
									if (atomTypes2.Length == 0)
										return ;
									if (atomContainer.getBondOrderSum(partner) < atomTypes2[0].BondOrderSum - partner.getHydrogenCount())
									{
										//logger.debug("Partner has " + atomContainer.getBondOrderSum(partner) + ", may have: " + atomTypes2[0].BondOrderSum);
										bond = atomContainer.getBond(atom, partner);
										//logger.debug("Bond order was " + bond.Order);
										bond.Order = bond.Order + 1;
										//logger.debug("Bond order now " + bond.Order);
										break;
									}
								}
							}
						}
					}
				}
			}
		}
 /// <summary>  Returns the minimum and maximum X and Y coordinates of the atoms in the
 /// AtomContainer. The output is returned as: <pre>
 /// minmax[0] = minX;
 /// minmax[1] = minY;
 /// minmax[2] = maxX;
 /// minmax[3] = maxY;
 /// </pre>
 /// See comment for center(IAtomContainer atomCon, Dimension areaDim, HashMap renderingCoordinates) for details on coordinate sets
 /// 
 /// </summary>
 /// <param name="container"> Description of the Parameter
 /// </param>
 /// <returns>            An four int array as defined above.
 /// </returns>
 public static double[] getMinMax(IAtomContainer container)
 {
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MIN_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double maxX = System.Double.MinValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MIN_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double maxY = System.Double.MinValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double minX = System.Double.MaxValue;
     //UPGRADE_TODO: The equivalent in .NET for field 'java.lang.Double.MAX_VALUE' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
     double minY = System.Double.MaxValue;
     for (int i = 0; i < container.AtomCount; i++)
     {
         IAtom atom = container.getAtomAt(i);
         if (atom.getPoint2d() != null)
         {
             if (atom.X2d > maxX)
             {
                 maxX = atom.X2d;
             }
             if (atom.X2d < minX)
             {
                 minX = atom.X2d;
             }
             if (atom.Y2d > maxY)
             {
                 maxY = atom.Y2d;
             }
             if (atom.Y2d < minY)
             {
                 minY = atom.Y2d;
             }
         }
     }
     double[] minmax = new double[4];
     minmax[0] = minX;
     minmax[1] = minY;
     minmax[2] = maxX;
     minmax[3] = maxY;
     return minmax;
 }
Exemple #58
0
        /// <summary> Returns a list of atoms in the shortest path between two atoms.
        ///
        /// This method uses the Djikstra algorithm to find all the atoms in the shortest
        /// path between the two specified atoms. The start and end atoms are also included
        /// in the path returned
        ///
        /// </summary>
        /// <param name="atomContainer">The molecule to search in
        /// </param>
        /// <param name="start">The starting atom
        /// </param>
        /// <param name="end">The ending atom
        /// </param>
        /// <returns> A <code>List</code> containing the atoms in the shortest path between <code>start</code> and
        /// <code>end</code> inclusive
        /// </returns>
        public static System.Collections.IList getShortestPath(IAtomContainer atomContainer, IAtom start, IAtom end)
        {
            int natom       = atomContainer.AtomCount;
            int endNumber   = atomContainer.getAtomNumber(end);
            int startNumber = atomContainer.getAtomNumber(start);

            int[] d        = new int[natom];
            int[] previous = new int[natom];
            for (int i = 0; i < natom; i++)
            {
                d[i]        = 99999999;
                previous[i] = -1;
            }
            d[atomContainer.getAtomNumber(start)] = 0;

            System.Collections.ArrayList S = new System.Collections.ArrayList();
            System.Collections.ArrayList Q = new System.Collections.ArrayList();
            for (int i = 0; i < natom; i++)
            {
                Q.Add((System.Int32)i);
            }

            while (true)
            {
                if (Q.Count == 0)
                {
                    break;
                }

                // extract min
                int u     = 999999;
                int index = 0;
                for (int i = 0; i < Q.Count; i++)
                {
                    int tmp = ((System.Int32)Q[i]);
                    if (d[tmp] < u)
                    {
                        u     = d[tmp];
                        index = i;
                    }
                }
                Q.RemoveAt(index);
                S.Add(atomContainer.getAtomAt(u));
                if (u == endNumber)
                {
                    break;
                }

                // relaxation
                IAtom[] connected = atomContainer.getConnectedAtoms(atomContainer.getAtomAt(u));
                for (int i = 0; i < connected.Length; i++)
                {
                    int anum = atomContainer.getAtomNumber(connected[i]);
                    if (d[anum] > d[u] + 1)
                    {
                        // all edges have equals weights
                        d[anum]        = d[u] + 1;
                        previous[anum] = u;
                    }
                }
            }

            System.Collections.ArrayList tmp2 = new System.Collections.ArrayList();
            int u2 = endNumber;

            while (true)
            {
                tmp2.Insert(0, atomContainer.getAtomAt(u2));
                u2 = previous[u2];
                if (u2 == startNumber)
                {
                    tmp2.Insert(0, atomContainer.getAtomAt(u2));
                    break;
                }
            }
            return(tmp2);
        }
        /// <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;
                    }
                }
            }
        }
Exemple #60
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);
                }
            }
        }