示例#1
0
 private void markEnzymeResidueLocatorAtoms(Reaction currentReaction)
 {
     IAtom[] atoms = ReactionManipulator.getAllInOneContainer(currentReaction).Atoms;
     for (int i = 0; i < atoms.Length; i++)
     {
         if (atoms[i] is EnzymeResidueLocator)
         {
             // skip atom
         }
         else if (atoms[i] is PseudoAtom)
         {
             PseudoAtom pseudo = (PseudoAtom)atoms[i];
             //logger.debug("pseudo atom label: ", pseudo.Label);
             //logger.debug("pseudo class: ", pseudo.GetType().FullName);
             Match residueLocatorMatcher = residueLocator.Match(pseudo.Label);
             if (residueLocatorMatcher.Success)
             {
                 //logger.debug("Found residueLocator: ", pseudo.Label);
                 // replace atom with enzymeResidueLocator
                 IAtomContainer container = ReactionManipulator.getRelevantAtomContainer(currentReaction, pseudo);
                 //logger.debug("Replacing the pseudo atom with a ezymeResidueLocator atom");
                 AtomContainerManipulator.replaceAtomByAtom(container, pseudo, new EnzymeResidueLocator(pseudo));
             }
         }
     }
 }
示例#2
0
        public void UnknownSymbol_Pseudo()
        {
            var a = new PseudoAtom("R1")
            {
                ImplicitHydrogenCount = 0
            };

            Assert.AreEqual(Beam.Element.Unknown, new CDKToBeam().ToBeamAtom(a).Element);
        }
示例#3
0
        public void TestGetDefaultAtomColor()
        {
            CDKAtomColors colors = new CDKAtomColors();

            Assert.IsNotNull(colors);
            IAtom imaginary = new PseudoAtom("Ix");

            Assert.AreEqual(WPF::Media.Colors.Orange, colors.GetAtomColor(imaginary, WPF::Media.Colors.Orange));
        }
示例#4
0
        public void TestGetDefaultAtomColor()
        {
            CDK2DAtomColors colors = new CDK2DAtomColors();

            Assert.IsNotNull(colors);
            IAtom imaginary = new PseudoAtom("Ix");

            Assert.AreEqual(Color.FromRgb(0, 0, 0), colors.GetAtomColor(imaginary, WPF::Media.Colors.Black));
        }
示例#5
0
        public void TestPseudoAtom()
        {
            var        mol  = new AtomContainer();
            PseudoAtom atom = new PseudoAtom("N")
            {
                Label = "Glu55"
            };

            mol.Atoms.Add(atom);

            IAtomContainer roundTrippedMol = CMLRoundTripTool.RoundTripMolecule(convertor, mol);

            Assert.AreEqual(1, roundTrippedMol.Atoms.Count);
            IAtom roundTrippedAtom = roundTrippedMol.Atoms[0];

            Assert.IsNotNull(roundTrippedAtom);
            Assert.IsTrue(roundTrippedAtom is IPseudoAtom);
            Assert.AreEqual("Glu55", ((IPseudoAtom)roundTrippedAtom).Label);
        }
示例#6
0
        public void TestChemModel()
        {
            ChemModel  model       = new ChemModel();
            var        moleculeSet = new ChemObjectSet <IAtomContainer>();
            var        mol         = new AtomContainer();
            PseudoAtom atom        = new PseudoAtom("N");

            mol.Atoms.Add(atom);
            moleculeSet.Add(mol);
            model.MoleculeSet = moleculeSet;

            IChemModel roundTrippedModel = CMLRoundTripTool.RoundTripChemModel(convertor, model);

            var roundTrippedMolSet = roundTrippedModel.MoleculeSet;

            Assert.IsNotNull(roundTrippedMolSet);
            Assert.AreEqual(1, roundTrippedMolSet.Count);
            IAtomContainer roundTrippedMolecule = roundTrippedMolSet[0];

            Assert.IsNotNull(roundTrippedMolecule);
            Assert.AreEqual(1, roundTrippedMolecule.Atoms.Count);
        }
示例#7
0
        /// <summary>  Description of the Method
        ///
        /// </summary>
        /// <param name="s">                          Description of the Parameter
        /// </param>
        /// <returns>                             Description of the Return Value
        /// </returns>
        /// <exception cref="InvalidSmilesException"> Description of the Exception
        /// </exception>
        private Atom assembleAtom(System.String s)
        {
            //logger.debug("assembleAtom(): Assembling atom from: ", s);
            Atom atom     = null;
            int  position = 0;

            System.String             currentSymbol  = null;
            System.Text.StringBuilder isotopicNumber = new System.Text.StringBuilder();
            char mychar;

            //logger.debug("Parse everythings before and including element symbol");
            do
            {
                try
                {
                    mychar = s[position];
                    //logger.debug("Parsing char: " + mychar);
                    if ((mychar >= 'A' && mychar <= 'Z') || (mychar >= 'a' && mychar <= 'z'))
                    {
                        currentSymbol = getElementSymbol(s, position);
                        if (currentSymbol == null)
                        {
                            throw new InvalidSmilesException("Expected element symbol, found null!");
                        }
                        else
                        {
                            //logger.debug("Found element symbol: ", currentSymbol);
                            position = position + currentSymbol.Length;
                            if (currentSymbol.Length == 1)
                            {
                                if (!(currentSymbol.ToUpper()).Equals(currentSymbol))
                                {
                                    currentSymbol      = currentSymbol.ToUpper();
                                    atom               = new Atom(currentSymbol);
                                    atom.Hybridization = CDKConstants.HYBRIDIZATION_SP2;
                                    if (atom.getHydrogenCount() > 0)
                                    {
                                        atom.setHydrogenCount(atom.getHydrogenCount() - 1);
                                    }
                                }
                                else
                                {
                                    atom = new Atom(currentSymbol);
                                }
                            }
                            else
                            {
                                atom = new Atom(currentSymbol);
                            }
                            //logger.debug("Made atom: ", atom);
                        }
                        break;
                    }
                    else if (mychar >= '0' && mychar <= '9')
                    {
                        isotopicNumber.Append(mychar);
                        position++;
                    }
                    else if (mychar == '*')
                    {
                        currentSymbol = "*";
                        atom          = new PseudoAtom(currentSymbol);
                        //logger.debug("Made atom: ", atom);
                        position++;
                        break;
                    }
                    else
                    {
                        throw new InvalidSmilesException("Found unexpected char: " + mychar);
                    }
                }
                catch (InvalidSmilesException exc)
                {
                    //logger.error("InvalidSmilesException while parsing atom string: " + s);
                    //logger.debug(exc);
                    throw exc;
                }
                catch (System.Exception exception)
                {
                    //logger.error("Could not parse atom string: ", s);
                    //logger.debug(exception);
                    throw new InvalidSmilesException("Could not parse atom string: " + s);
                }
            }while (position < s.Length);
            if (isotopicNumber.ToString().Length > 0)
            {
                try
                {
                    atom.MassNumber = System.Int32.Parse(isotopicNumber.ToString());
                }
                catch (System.Exception exception)
                {
                    //logger.error("Could not set atom's atom number.");
                    //logger.debug(exception);
                }
            }
            //logger.debug("Parsing part after element symbol (like charge): ", s.Substring(position));
            int charge            = 0;
            int implicitHydrogens = 0;

            while (position < s.Length)
            {
                try
                {
                    mychar = s[position];
                    //logger.debug("Parsing char: " + mychar);
                    if (mychar == 'H')
                    {
                        // count implicit hydrogens
                        implicitHydrogens = getImplicitHydrogenCount(s, position);
                        position++;
                        if (implicitHydrogens > 1)
                        {
                            position++;
                        }
                        atom.setHydrogenCount(implicitHydrogens);
                    }
                    else if (mychar == '+' || mychar == '-')
                    {
                        charge = getCharge(s, position);
                        position++;
                        if (charge < -1 || charge > 1)
                        {
                            position++;
                        }
                        atom.setFormalCharge(charge);
                    }
                    else if (mychar == '@')
                    {
                        if (position < s.Length - 1 && s[position + 1] == '@')
                        {
                            position++;
                        }
                        //logger.warn("Ignoring stereo information for atom");
                        position++;
                    }
                    else
                    {
                        throw new InvalidSmilesException("Found unexpected char: " + mychar);
                    }
                }
                catch (InvalidSmilesException exc)
                {
                    //logger.error("InvalidSmilesException while parsing atom string: ", s);
                    //logger.debug(exc);
                    throw exc;
                }
                catch (System.Exception exception)
                {
                    //logger.error("Could not parse atom string: ", s);
                    //logger.debug(exception);
                    throw new InvalidSmilesException("Could not parse atom string: " + s);
                }
            }
            return(atom);
        }
示例#8
0
        /// <summary>  Parses a SMILES string and returns a Molecule object.
        ///
        /// </summary>
        /// <param name="smiles">                     A SMILES string
        /// </param>
        /// <returns>                             A Molecule representing the constitution
        /// given in the SMILES string
        /// </returns>
        /// <exception cref="InvalidSmilesException"> Exception thrown when the SMILES string
        /// is invalid
        /// </exception>
        public virtual Molecule parseSmiles(System.String smiles)
        {
            //logger.debug("parseSmiles()...");
            Bond bond = null;

            nodeCounter    = 0;
            bondStatus     = 0;
            bondIsAromatic = false;
            bool bondExists = true;

            thisRing      = -1;
            currentSymbol = null;
            molecule      = new Molecule();
            position      = 0;
            // we don't want more than 1024 rings
            rings     = new Atom[1024];
            ringbonds = new double[1024];
            for (int f = 0; f < 1024; f++)
            {
                rings[f]     = null;
                ringbonds[f] = -1;
            }

            char mychar = 'X';

            char[] chars    = new char[1];
            Atom   lastNode = null;

            System.Collections.ArrayList atomStack = new System.Collections.ArrayList();
            System.Collections.ArrayList bondStack = new System.Collections.ArrayList();
            Atom atom = null;

            do
            {
                try
                {
                    mychar = smiles[position];
                    //logger.debug("");
                    //logger.debug("Processing: " + mychar);
                    if (lastNode != null)
                    {
                        //logger.debug("Lastnode: ", lastNode.GetHashCode());
                    }
                    if ((mychar >= 'A' && mychar <= 'Z') || (mychar >= 'a' && mychar <= 'z') || (mychar == '*'))
                    {
                        status = 1;
                        //logger.debug("Found a must-be 'organic subset' element");
                        // only 'organic subset' elements allowed
                        atom = null;
                        if (mychar == '*')
                        {
                            currentSymbol = "*";
                            atom          = new PseudoAtom("*");
                        }
                        else
                        {
                            currentSymbol = getSymbolForOrganicSubsetElement(smiles, position);
                            if (currentSymbol != null)
                            {
                                if (currentSymbol.Length == 1)
                                {
                                    if (!(currentSymbol.ToUpper()).Equals(currentSymbol))
                                    {
                                        currentSymbol      = currentSymbol.ToUpper();
                                        atom               = new Atom(currentSymbol);
                                        atom.Hybridization = CDKConstants.HYBRIDIZATION_SP2;
                                    }
                                    else
                                    {
                                        atom = new Atom(currentSymbol);
                                    }
                                }
                                else
                                {
                                    atom = new Atom(currentSymbol);
                                }
                                //logger.debug("Made atom: ", atom);
                            }
                            else
                            {
                                throw new InvalidSmilesException("Found element which is not a 'organic subset' element. You must " + "use [" + mychar + "].");
                            }
                        }

                        molecule.addAtom(atom);
                        //logger.debug("Adding atom ", atom.GetHashCode());
                        if ((lastNode != null) && bondExists)
                        {
                            //logger.debug("Creating bond between ", atom.Symbol, " and ", lastNode.Symbol);
                            bond = new Bond(atom, lastNode, bondStatus);
                            if (bondIsAromatic)
                            {
                                bond.setFlag(CDKConstants.ISAROMATIC, true);
                            }
                            molecule.addBond(bond);
                        }
                        bondStatus = CDKConstants.BONDORDER_SINGLE;
                        lastNode   = atom;
                        nodeCounter++;
                        position       = position + currentSymbol.Length;
                        bondExists     = true;
                        bondIsAromatic = false;
                    }
                    else if (mychar == '=')
                    {
                        position++;
                        if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9'))
                        {
                            bondStatus = CDKConstants.BONDORDER_DOUBLE;
                        }
                        else
                        {
                            bondStatusForRingClosure = CDKConstants.BONDORDER_DOUBLE;
                        }
                    }
                    else if (mychar == '#')
                    {
                        position++;
                        if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9'))
                        {
                            bondStatus = CDKConstants.BONDORDER_TRIPLE;
                        }
                        else
                        {
                            bondStatusForRingClosure = CDKConstants.BONDORDER_TRIPLE;
                        }
                    }
                    else if (mychar == '(')
                    {
                        atomStack.Add(lastNode);
                        //logger.debug("Stack:");
                        System.Collections.IEnumerator ses = atomStack.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 (ses.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'"
                            Atom a = (Atom)ses.Current;
                            //logger.debug("", a.GetHashCode());
                        }
                        //logger.debug("------");
                        bondStack.Add((double)bondStatus);
                        position++;
                    }
                    else if (mychar == ')')
                    {
                        lastNode = (Atom)SupportClass.StackSupport.Pop(atomStack);
                        //logger.debug("Stack:");
                        System.Collections.IEnumerator ses = atomStack.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 (ses.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'"
                            Atom a = (Atom)ses.Current;
                            //logger.debug("", a.GetHashCode());
                        }
                        //logger.debug("------");
                        bondStatus = ((System.Double)SupportClass.StackSupport.Pop(bondStack));
                        position++;
                    }
                    else if (mychar >= '0' && mychar <= '9')
                    {
                        status        = 2;
                        chars[0]      = mychar;
                        currentSymbol = new System.String(chars);
                        thisRing      = (System.Int32.Parse(currentSymbol));
                        handleRing(lastNode);
                        position++;
                    }
                    else if (mychar == '%')
                    {
                        currentSymbol = getRingNumber(smiles, position);
                        thisRing      = (System.Int32.Parse(currentSymbol));
                        handleRing(lastNode);
                        position += currentSymbol.Length + 1;
                    }
                    else if (mychar == '[')
                    {
                        currentSymbol = getAtomString(smiles, position);
                        atom          = assembleAtom(currentSymbol);
                        molecule.addAtom(atom);
                        //logger.debug("Added atom: ", atom);
                        if (lastNode != null && bondExists)
                        {
                            bond = new Bond(atom, lastNode, bondStatus);
                            if (bondIsAromatic)
                            {
                                bond.setFlag(CDKConstants.ISAROMATIC, true);
                            }
                            molecule.addBond(bond);
                            //logger.debug("Added bond: ", bond);
                        }
                        bondStatus     = CDKConstants.BONDORDER_SINGLE;
                        bondIsAromatic = false;
                        lastNode       = atom;
                        nodeCounter++;
                        position = position + currentSymbol.Length + 2;
                        // plus two for [ and ]
                        bondExists = true;
                    }
                    else if (mychar == '.')
                    {
                        bondExists = false;
                        position++;
                    }
                    else if (mychar == '-')
                    {
                        bondExists = true;
                        // a simple single bond
                        position++;
                    }
                    else if (mychar == ':')
                    {
                        bondExists     = true;
                        bondIsAromatic = true;
                        position++;
                    }
                    else if (mychar == '/' || mychar == '\\')
                    {
                        //logger.warn("Ignoring stereo information for double bond");
                        position++;
                    }
                    else if (mychar == '@')
                    {
                        if (position < smiles.Length - 1 && smiles[position + 1] == '@')
                        {
                            position++;
                        }
                        //logger.warn("Ignoring stereo information for atom");
                        position++;
                    }
                    else
                    {
                        throw new InvalidSmilesException("Unexpected character found: " + mychar);
                    }
                }
                catch (InvalidSmilesException exc)
                {
                    //logger.error("InvalidSmilesException while parsing char (in parseSmiles()): " + mychar);
                    //logger.debug(exc);
                    throw exc;
                }
                catch (System.Exception exception)
                {
                    //logger.error("Error while parsing char: " + mychar);
                    //logger.debug(exception);
                    throw new InvalidSmilesException("Error while parsing char: " + mychar);
                }
                //logger.debug("Parsing next char");
            }while (position < smiles.Length);

            // add implicit hydrogens
            try
            {
                //logger.debug("before H-adding: ", molecule);
                hAdder.addImplicitHydrogensToSatisfyValency(molecule);
                //logger.debug("after H-adding: ", molecule);
            }
            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'"
                //logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message);
            }

            // setup missing bond orders
            try
            {
                valencyChecker.saturate(molecule);
                //logger.debug("after adding missing bond orders: ", molecule);
            }
            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'"
                //logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message);
            }

            // conceive aromatic perception
            IMolecule[] moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule).Molecules;
            //logger.debug("#mols ", moleculeSet.Length);
            for (int i = 0; i < moleculeSet.Length; i++)
            {
                //logger.debug("mol: ", moleculeSet[i]);
                try
                {
                    valencyChecker.saturate(moleculeSet[i]);
                    //logger.debug(" after saturation: ", moleculeSet[i]);
                    if (HueckelAromaticityDetector.detectAromaticity(moleculeSet[i]))
                    {
                        //logger.debug("Structure is aromatic...");
                    }
                }
                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'"
                    //logger.error("Could not perceive aromaticity: ", exception.Message);
                    //logger.debug(exception);
                }
            }

            return(molecule);
        }
示例#9
0
 private void processAnnotation(System.String field, System.String value_Renamed, Reaction reaction)
 {
     //logger.debug("Annote: ", field, "=", value_Renamed);
     if (field.Equals("RxnAtts") || field.Equals("RxnType"))
     {
         // reaction attributes
         System.String dictionary = "macie";
         if (value_Renamed.Equals("Acid") || value_Renamed.Equals("Base"))
         {
             dictionary = "chemical";
         }
         addDictRefedAnnotation(reaction, "Attributes", value_Renamed);
     }
     else if (field.Equals("ResiduesPresent") || field.Equals("GroupTransferred") || field.Equals("BondFormed") || field.Equals("ReactiveCentres") || field.Equals("BondCleaved") || field.Equals("BondFormed") || field.Equals("Products") || field.Equals("ResiduesPresent"))
     {
         reaction.setProperty(new DictRef("macie:" + field, value_Renamed), value_Renamed);
     }
     else if (field.Equals("Reversible"))
     {
         if (value_Renamed.ToUpper().Equals("yes".ToUpper()))
         {
             reaction.Direction = IReaction_Fields.BIDIRECTIONAL;
             addDictRefedAnnotation(reaction, "ReactionType", "ReversibleReaction");
         }
     }
     else if (field.Equals("OverallReactionType"))
     {
         SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(value_Renamed, ",");
         int i = 0;
         while (tokenizer.HasMoreTokens())
         {
             System.String token = tokenizer.NextToken();
             i++;
             reaction.setProperty(DictionaryDatabase.DICTREFPROPERTYNAME + ":field:overallReactionType:" + i, "macie:" + token.ToLower());
         }
     }
     else
     {
         Match residueLocatorMatcher = residueLocator.Match(field);
         if (residueLocatorMatcher.Success)
         {
             //logger.debug("Found residueLocator: ", field);
             IAtom[] atoms = ReactionManipulator.getAllInOneContainer(reaction).Atoms;
             bool    found = false;
             //logger.debug("Searching for given residueLocator through #atom: ", atoms.Length);
             //logger.debug("Taken from reaction ", reaction.ID);
             for (int i = 0; (i < atoms.Length && !found); i++)
             {
                 if (atoms[i] is PseudoAtom)
                 {
                     // that is what we are looking for
                     PseudoAtom atom = (PseudoAtom)atoms[i];
                     if (atom.Label.Equals(field))
                     {
                         // we have a hit, now mark Atom with dict refs
                         addDictRefedAnnotation(atom, "ResidueRole", value_Renamed);
                         found = true;
                     }
                 }
             }
             if (!found)
             {
                 //logger.error("MACiE annotation mentions a residue that does not exist: " + field);
             }
         }
         else
         {
             //logger.error("Did not parse annotation: ", field);
         }
     }
 }
示例#10
0
		/// <summary>  Description of the Method
		/// 
		/// </summary>
		/// <param name="s">                          Description of the Parameter
		/// </param>
		/// <returns>                             Description of the Return Value
		/// </returns>
		/// <exception cref="InvalidSmilesException"> Description of the Exception
		/// </exception>
		private Atom assembleAtom(System.String s)
		{
			//logger.debug("assembleAtom(): Assembling atom from: ", s);
			Atom atom = null;
			int position = 0;
			System.String currentSymbol = null;
			System.Text.StringBuilder isotopicNumber = new System.Text.StringBuilder();
			char mychar;
			//logger.debug("Parse everythings before and including element symbol");
			do 
			{
				try
				{
					mychar = s[position];
					//logger.debug("Parsing char: " + mychar);
					if ((mychar >= 'A' && mychar <= 'Z') || (mychar >= 'a' && mychar <= 'z'))
					{
						currentSymbol = getElementSymbol(s, position);
						if (currentSymbol == null)
						{
							throw new InvalidSmilesException("Expected element symbol, found null!");
						}
						else
						{
							//logger.debug("Found element symbol: ", currentSymbol);
							position = position + currentSymbol.Length;
							if (currentSymbol.Length == 1)
							{
								if (!(currentSymbol.ToUpper()).Equals(currentSymbol))
								{
									currentSymbol = currentSymbol.ToUpper();
									atom = new Atom(currentSymbol);
									atom.Hybridization = CDKConstants.HYBRIDIZATION_SP2;
									if (atom.getHydrogenCount() > 0)
									{
										atom.setHydrogenCount(atom.getHydrogenCount() - 1);
									}
								}
								else
								{
									atom = new Atom(currentSymbol);
								}
							}
							else
							{
								atom = new Atom(currentSymbol);
							}
							//logger.debug("Made atom: ", atom);
						}
						break;
					}
					else if (mychar >= '0' && mychar <= '9')
					{
						isotopicNumber.Append(mychar);
						position++;
					}
					else if (mychar == '*')
					{
						currentSymbol = "*";
						atom = new PseudoAtom(currentSymbol);
						//logger.debug("Made atom: ", atom);
						position++;
						break;
					}
					else
					{
						throw new InvalidSmilesException("Found unexpected char: " + mychar);
					}
				}
				catch (InvalidSmilesException exc)
				{
					//logger.error("InvalidSmilesException while parsing atom string: " + s);
					//logger.debug(exc);
					throw exc;
				}
				catch (System.Exception exception)
				{
					//logger.error("Could not parse atom string: ", s);
					//logger.debug(exception);
					throw new InvalidSmilesException("Could not parse atom string: " + s);
				}
			}
			while (position < s.Length);
			if (isotopicNumber.ToString().Length > 0)
			{
				try
				{
					atom.MassNumber = System.Int32.Parse(isotopicNumber.ToString());
				}
				catch (System.Exception exception)
				{
					//logger.error("Could not set atom's atom number.");
					//logger.debug(exception);
				}
			}
			//logger.debug("Parsing part after element symbol (like charge): ", s.Substring(position));
			int charge = 0;
			int implicitHydrogens = 0;
			while (position < s.Length)
			{
				try
				{
					mychar = s[position];
					//logger.debug("Parsing char: " + mychar);
					if (mychar == 'H')
					{
						// count implicit hydrogens
						implicitHydrogens = getImplicitHydrogenCount(s, position);
						position++;
						if (implicitHydrogens > 1)
						{
							position++;
						}
						atom.setHydrogenCount(implicitHydrogens);
					}
					else if (mychar == '+' || mychar == '-')
					{
						charge = getCharge(s, position);
						position++;
						if (charge < - 1 || charge > 1)
						{
							position++;
						}
						atom.setFormalCharge(charge);
					}
					else if (mychar == '@')
					{
						if (position < s.Length - 1 && s[position + 1] == '@')
						{
							position++;
						}
						//logger.warn("Ignoring stereo information for atom");
						position++;
					}
					else
					{
						throw new InvalidSmilesException("Found unexpected char: " + mychar);
					}
				}
				catch (InvalidSmilesException exc)
				{
					//logger.error("InvalidSmilesException while parsing atom string: ", s);
					//logger.debug(exc);
					throw exc;
				}
				catch (System.Exception exception)
				{
					//logger.error("Could not parse atom string: ", s);
					//logger.debug(exception);
					throw new InvalidSmilesException("Could not parse atom string: " + s);
				}
			}
			return atom;
		}
示例#11
0
		/// <summary>  Parses a SMILES string and returns a Molecule object.
		/// 
		/// </summary>
		/// <param name="smiles">                     A SMILES string
		/// </param>
		/// <returns>                             A Molecule representing the constitution
		/// given in the SMILES string
		/// </returns>
		/// <exception cref="InvalidSmilesException"> Exception thrown when the SMILES string
		/// is invalid
		/// </exception>
		public virtual Molecule parseSmiles(System.String smiles)
		{
			//logger.debug("parseSmiles()...");
			Bond bond = null;
			nodeCounter = 0;
			bondStatus = 0;
			bondIsAromatic = false;
			bool bondExists = true;
			thisRing = - 1;
			currentSymbol = null;
			molecule = new Molecule();
			position = 0;
			// we don't want more than 1024 rings
			rings = new Atom[1024];
			ringbonds = new double[1024];
			for (int f = 0; f < 1024; f++)
			{
				rings[f] = null;
				ringbonds[f] = - 1;
			}
			
			char mychar = 'X';
			char[] chars = new char[1];
			Atom lastNode = null;
			System.Collections.ArrayList atomStack = new System.Collections.ArrayList();
			System.Collections.ArrayList bondStack = new System.Collections.ArrayList();
			Atom atom = null;
			do 
			{
				try
				{
					mychar = smiles[position];
					//logger.debug("");
					//logger.debug("Processing: " + mychar);
					if (lastNode != null)
					{
						//logger.debug("Lastnode: ", lastNode.GetHashCode());
					}
					if ((mychar >= 'A' && mychar <= 'Z') || (mychar >= 'a' && mychar <= 'z') || (mychar == '*'))
					{
						status = 1;
						//logger.debug("Found a must-be 'organic subset' element");
						// only 'organic subset' elements allowed
						atom = null;
						if (mychar == '*')
						{
							currentSymbol = "*";
							atom = new PseudoAtom("*");
						}
						else
						{
							currentSymbol = getSymbolForOrganicSubsetElement(smiles, position);
							if (currentSymbol != null)
							{
								if (currentSymbol.Length == 1)
								{
									if (!(currentSymbol.ToUpper()).Equals(currentSymbol))
									{
										currentSymbol = currentSymbol.ToUpper();
										atom = new Atom(currentSymbol);
										atom.Hybridization = CDKConstants.HYBRIDIZATION_SP2;
									}
									else
									{
										atom = new Atom(currentSymbol);
									}
								}
								else
								{
									atom = new Atom(currentSymbol);
								}
								//logger.debug("Made atom: ", atom);
							}
							else
							{
								throw new InvalidSmilesException("Found element which is not a 'organic subset' element. You must " + "use [" + mychar + "].");
							}
						}
						
						molecule.addAtom(atom);
						//logger.debug("Adding atom ", atom.GetHashCode());
						if ((lastNode != null) && bondExists)
						{
							//logger.debug("Creating bond between ", atom.Symbol, " and ", lastNode.Symbol);
							bond = new Bond(atom, lastNode, bondStatus);
							if (bondIsAromatic)
							{
								bond.setFlag(CDKConstants.ISAROMATIC, true);
							}
							molecule.addBond(bond);
						}
						bondStatus = CDKConstants.BONDORDER_SINGLE;
						lastNode = atom;
						nodeCounter++;
						position = position + currentSymbol.Length;
						bondExists = true;
						bondIsAromatic = false;
					}
					else if (mychar == '=')
					{
						position++;
						if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9'))
						{
							bondStatus = CDKConstants.BONDORDER_DOUBLE;
						}
						else
						{
							bondStatusForRingClosure = CDKConstants.BONDORDER_DOUBLE;
						}
					}
					else if (mychar == '#')
					{
						position++;
						if (status == 2 || smiles.Length == position + 1 || !(smiles[position] >= '0' && smiles[position] <= '9'))
						{
							bondStatus = CDKConstants.BONDORDER_TRIPLE;
						}
						else
						{
							bondStatusForRingClosure = CDKConstants.BONDORDER_TRIPLE;
						}
					}
					else if (mychar == '(')
					{
						atomStack.Add(lastNode);
						//logger.debug("Stack:");
						System.Collections.IEnumerator ses = atomStack.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 (ses.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'"
							Atom a = (Atom) ses.Current;
							//logger.debug("", a.GetHashCode());
						}
						//logger.debug("------");
						bondStack.Add((double) bondStatus);
						position++;
					}
					else if (mychar == ')')
					{
						lastNode = (Atom) SupportClass.StackSupport.Pop(atomStack);
						//logger.debug("Stack:");
						System.Collections.IEnumerator ses = atomStack.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 (ses.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'"
							Atom a = (Atom) ses.Current;
							//logger.debug("", a.GetHashCode());
						}
						//logger.debug("------");
						bondStatus = ((System.Double) SupportClass.StackSupport.Pop(bondStack));
						position++;
					}
					else if (mychar >= '0' && mychar <= '9')
					{
						status = 2;
						chars[0] = mychar;
						currentSymbol = new System.String(chars);
						thisRing = (System.Int32.Parse(currentSymbol));
						handleRing(lastNode);
						position++;
					}
					else if (mychar == '%')
					{
						currentSymbol = getRingNumber(smiles, position);
						thisRing = (System.Int32.Parse(currentSymbol));
						handleRing(lastNode);
						position += currentSymbol.Length + 1;
					}
					else if (mychar == '[')
					{
						currentSymbol = getAtomString(smiles, position);
						atom = assembleAtom(currentSymbol);
						molecule.addAtom(atom);
						//logger.debug("Added atom: ", atom);
						if (lastNode != null && bondExists)
						{
							bond = new Bond(atom, lastNode, bondStatus);
							if (bondIsAromatic)
							{
								bond.setFlag(CDKConstants.ISAROMATIC, true);
							}
							molecule.addBond(bond);
							//logger.debug("Added bond: ", bond);
						}
						bondStatus = CDKConstants.BONDORDER_SINGLE;
						bondIsAromatic = false;
						lastNode = atom;
						nodeCounter++;
						position = position + currentSymbol.Length + 2;
						// plus two for [ and ]
						bondExists = true;
					}
					else if (mychar == '.')
					{
						bondExists = false;
						position++;
					}
					else if (mychar == '-')
					{
						bondExists = true;
						// a simple single bond
						position++;
					}
					else if (mychar == ':')
					{
						bondExists = true;
						bondIsAromatic = true;
						position++;
					}
					else if (mychar == '/' || mychar == '\\')
					{
						//logger.warn("Ignoring stereo information for double bond");
						position++;
					}
					else if (mychar == '@')
					{
						if (position < smiles.Length - 1 && smiles[position + 1] == '@')
						{
							position++;
						}
						//logger.warn("Ignoring stereo information for atom");
						position++;
					}
					else
					{
						throw new InvalidSmilesException("Unexpected character found: " + mychar);
					}
				}
				catch (InvalidSmilesException exc)
				{
					//logger.error("InvalidSmilesException while parsing char (in parseSmiles()): " + mychar);
					//logger.debug(exc);
					throw exc;
				}
				catch (System.Exception exception)
				{
					//logger.error("Error while parsing char: " + mychar);
					//logger.debug(exception);
					throw new InvalidSmilesException("Error while parsing char: " + mychar);
				}
				//logger.debug("Parsing next char");
			}
			while (position < smiles.Length);
			
			// add implicit hydrogens
			try
			{
				//logger.debug("before H-adding: ", molecule);
				hAdder.addImplicitHydrogensToSatisfyValency(molecule);
				//logger.debug("after H-adding: ", molecule);
			}
			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'"
				//logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message);
			}
			
			// setup missing bond orders
			try
			{
				valencyChecker.saturate(molecule);
				//logger.debug("after adding missing bond orders: ", molecule);
			}
			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'"
				//logger.error("Error while calculation Hcount for SMILES atom: ", exception.Message);
			}
			
			// conceive aromatic perception
			IMolecule[] moleculeSet = ConnectivityChecker.partitionIntoMolecules(molecule).Molecules;
			//logger.debug("#mols ", moleculeSet.Length);
			for (int i = 0; i < moleculeSet.Length; i++)
			{
				//logger.debug("mol: ", moleculeSet[i]);
				try
				{
					valencyChecker.saturate(moleculeSet[i]);
					//logger.debug(" after saturation: ", moleculeSet[i]);
					if (HueckelAromaticityDetector.detectAromaticity(moleculeSet[i]))
					{
						//logger.debug("Structure is aromatic...");
					}
				}
				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'"
					//logger.error("Could not perceive aromaticity: ", exception.Message);
					//logger.debug(exception);
				}
			}
			
			return molecule;
		}