Esempio n. 1
0
 /// <summary> Takes an object which subclasses IChemObject, e.g.Molecule, and will read
 /// this from from the Reader. If the specific implementation
 /// does not support a specific IChemObject it will throw an Exception.
 ///
 /// </summary>
 /// <param name="object">The object that subclasses IChemObject
 /// </param>
 /// <returns>        The IChemObject read
 /// </returns>
 /// <exception cref="CDKException">
 /// </exception>
 public override IChemObject read(IChemObject object_Renamed)
 {
     if (object_Renamed is IChemFile)
     {
         IChemFile       file        = (IChemFile)object_Renamed;
         IChemSequence   sequence    = file.Builder.newChemSequence();
         IChemModel      model       = file.Builder.newChemModel();
         ISetOfMolecules moleculeSet = file.Builder.newSetOfMolecules();
         moleculeSet.addMolecule(readMolecule(model.Builder.newMolecule()));
         model.SetOfMolecules = moleculeSet;
         sequence.addChemModel(model);
         file.addChemSequence(sequence);
         return(file);
     }
     else if (object_Renamed is IChemModel)
     {
         IChemModel      model       = (IChemModel)object_Renamed;
         ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules();
         moleculeSet.addMolecule(readMolecule(model.Builder.newMolecule()));
         model.SetOfMolecules = moleculeSet;
         return(model);
     }
     else
     {
         throw new CDKException("Only supported is ChemModel, and not " + object_Renamed.GetType().FullName + ".");
     }
 }
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
        public static ISetOfMolecules getAllMolecules(IReaction reaction)
        {
            ISetOfMolecules moleculeSet = reaction.Builder.newSetOfMolecules();

            IMolecule[] reactants = reaction.Reactants.Molecules;
            for (int i = 0; i < reactants.Length; i++)
            {
                moleculeSet.addMolecule(reactants[i]);
            }
            IMolecule[] products = reaction.Products.Molecules;
            for (int i = 0; i < products.Length; i++)
            {
                moleculeSet.addMolecule(products[i]);
            }
            return(moleculeSet);
        }
Esempio n. 4
0
 public override void write(IChemObject object_Renamed)
 {
     if (object_Renamed is IMolecule)
     {
         try
         {
             ISetOfMolecules som = object_Renamed.Builder.newSetOfMolecules();
             som.addMolecule((IMolecule)object_Renamed);
             writeMolecule(som);
         }
         catch (System.Exception ex)
         {
             //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'"
             throw new CDKException("Error while writing HIN file: " + ex.Message, ex);
         }
     }
     else if (object_Renamed is ISetOfMolecules)
     {
         try
         {
             writeMolecule((ISetOfMolecules)object_Renamed);
         }
         catch (System.IO.IOException ex)
         {
             //
         }
     }
     else
     {
         throw new CDKException("HINWriter only supports output of Molecule or SetOfMolecule classes.");
     }
 }
Esempio n. 5
0
        /// <summary> Reads data from the "file system" file through the use of the "input"
        /// field, parses data and feeds the ChemFile object with the extracted data.
        ///
        /// </summary>
        /// <returns> A ChemFile containing the data parsed from input.
        ///
        /// </returns>
        /// <throws	IOException	may>  be thrown buy the <code>this.input.readLine()</code> instruction. </throws	IOException	may>
        /// <summary>
        /// </summary>
        /// <seealso cref="org.openscience.cdk.io.GamessReader.input">
        /// </seealso>
        //TODO Answer the question : Is this method's name appropriate (given the fact that it do not read a ChemFile object, but return it)?
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence   sequence    = file.Builder.newChemSequence(); // TODO Answer the question : Is this line needed ?
            IChemModel      model       = file.Builder.newChemModel();    // TODO Answer the question : Is this line needed ?
            ISetOfMolecules moleculeSet = file.Builder.newSetOfMolecules();

            model.SetOfMolecules = moleculeSet; //TODO Answer the question : Should I do this?
            sequence.addChemModel(model);       //TODO Answer the question : Should I do this?
            file.addChemSequence(sequence);     //TODO Answer the question : Should I do this?

            System.String currentReadLine = this.input.ReadLine();
            while (this.input.Peek() != -1 == true && (currentReadLine != null))
            {
                /*
                 * There are 2 types of coordinate sets:
                 * - bohr coordinates sets		(if statement)
                 * - angstr???m coordinates sets	(else statement)
                 */
                if (currentReadLine.IndexOf("COORDINATES (BOHR)") >= 0)
                {
                    /*
                     * The following line do no contain data, so it is ignored.
                     */
                    this.input.ReadLine();
                    moleculeSet.addMolecule(this.readCoordinates(file.Builder.newMolecule(), GamessReader.BOHR_UNIT));
                    //break; //<- stops when the first set of coordinates is found.
                }
                else if (currentReadLine.IndexOf(" COORDINATES OF ALL ATOMS ARE (ANGS)") >= 0)
                {
                    /*
                     * The following 2 lines do no contain data, so it are ignored.
                     */
                    this.input.ReadLine();
                    this.input.ReadLine();

                    moleculeSet.addMolecule(this.readCoordinates(file.Builder.newMolecule(), GamessReader.ANGSTROM_UNIT));
                    //break; //<- stops when the first set of coordinates is found.
                }
                currentReadLine = this.input.ReadLine();
            }
            return(file);
        }
        // private functions

        /// <summary> Reads a ChemFile object from input.
        ///
        /// </summary>
        /// <returns> ChemFile with the content read from the input
        /// </returns>
        private IChemFile readChemFile(IChemFile cf)
        {
            // have to do stuff here
            try
            {
                System.String line = input.ReadLine();
                while (line != null)
                {
                    if (line.StartsWith("INChI="))
                    {
                        // ok, the fun starts
                        cf = cf.Builder.newChemFile();
                        // ok, we need to parse things like:
                        // INChI=1.12Beta/C6H6/c1-2-4-6-5-3-1/h1-6H
                        //UPGRADE_NOTE: Final was removed from the declaration of 'INChI '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String          INChI     = line.Substring(6);
                        SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(INChI, "/");
                        // ok, we expect 4 tokens
                        //UPGRADE_NOTE: Final was removed from the declaration of 'version '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String version = tokenizer.NextToken();                  // 1.12Beta
                        //UPGRADE_NOTE: Final was removed from the declaration of 'formula '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String formula = tokenizer.NextToken();                  // C6H6
                        //UPGRADE_NOTE: Final was removed from the declaration of 'connections '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String connections = tokenizer.NextToken().Substring(1); // 1-2-4-6-5-3-1
                        //UPGRADE_NOTE: Final was removed from the declaration of 'hydrogens '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
                        System.String hydrogens = tokenizer.NextToken().Substring(1);   // 1-6H

                        IAtomContainer parsedContent = inchiTool.processFormula(cf.Builder.newAtomContainer(), formula);
                        inchiTool.processConnections(connections, parsedContent, -1);

                        ISetOfMolecules moleculeSet = cf.Builder.newSetOfMolecules();
                        moleculeSet.addMolecule(cf.Builder.newMolecule(parsedContent));
                        IChemModel model = cf.Builder.newChemModel();
                        model.SetOfMolecules = moleculeSet;
                        IChemSequence sequence = cf.Builder.newChemSequence();
                        sequence.addChemModel(model);
                        cf.addChemSequence(sequence);
                    }
                    line = input.ReadLine();
                }
            }
            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'"
                throw new CDKException("Error while reading INChI file: " + exception.Message, exception);
            }
            return(cf);
        }
Esempio n. 7
0
        private IChemModel readChemModel(IChemModel chemModel)
        {
            ISetOfMolecules setOfMolecules = chemModel.SetOfMolecules;

            if (setOfMolecules == null)
            {
                setOfMolecules = chemModel.Builder.newSetOfMolecules();
            }
            IMolecule m = readMolecule(chemModel.Builder.newMolecule());

            if (m != null)
            {
                setOfMolecules.addMolecule(m);
            }
            chemModel.SetOfMolecules = setOfMolecules;
            return(chemModel);
        }
        public static IAtomContainer createNewMolecule(IChemModel chemModel)
        {
            // Add a new molecule either the set of molecules
            IMolecule molecule = chemModel.Builder.newMolecule();

            if (chemModel.SetOfMolecules != null)
            {
                ISetOfMolecules moleculeSet = chemModel.SetOfMolecules;
                moleculeSet.addMolecule(molecule);
            }
            else
            {
                ISetOfMolecules moleculeSet = chemModel.Builder.newSetOfMolecules();
                moleculeSet.addMolecule(molecule);
                chemModel.SetOfMolecules = moleculeSet;
            }
            return(molecule);
        }
Esempio n. 9
0
        private IChemModel readChemModel(IChemModel model)
        {
            int[]    atoms       = new int[1];
            double[] atomxs      = new double[1];
            double[] atomys      = new double[1];
            double[] atomzs      = new double[1];
            double[] atomcharges = new double[1];

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

            int numberOfAtoms = 0;
            int numberOfBonds = 0;

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

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

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

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

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

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

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

            // this should not happen, file is lacking !End command
            return(null);
        }
Esempio n. 10
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);
     }
 }
Esempio n. 11
0
        // private procedures

        /// <summary>  Private method that actually parses the input to read a ChemFile
        /// object.
        ///
        /// </summary>
        /// <returns> A ChemFile containing the data parsed from input.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence chemSequence = file.Builder.newChemSequence();

            int number_of_atoms = 0;

            SupportClass.Tokenizer tokenizer;

            try
            {
                System.String line = input.ReadLine();
                while (input.Peek() != -1 && line != null)
                {
                    // parse frame by frame
                    tokenizer = new SupportClass.Tokenizer(line, "\t ,;");

                    System.String token = tokenizer.NextToken();
                    number_of_atoms = System.Int32.Parse(token);
                    System.String info = input.ReadLine();

                    IChemModel      chemModel      = file.Builder.newChemModel();
                    ISetOfMolecules setOfMolecules = file.Builder.newSetOfMolecules();

                    IMolecule m = file.Builder.newMolecule();
                    m.setProperty(CDKConstants.TITLE, info);

                    for (int i = 0; i < number_of_atoms; i++)
                    {
                        line = input.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        if (line.StartsWith("#") && line.Length > 1)
                        {
                            System.Object comment = m.getProperty(CDKConstants.COMMENT);
                            if (comment == null)
                            {
                                comment = "";
                            }
                            //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'"
                            comment = comment.ToString() + line.Substring(1).Trim();
                            m.setProperty(CDKConstants.COMMENT, comment);
                            //logger.debug("Found and set comment: ", comment);
                        }
                        else
                        {
                            double x = 0.0f, y = 0.0f, z = 0.0f;
                            double charge = 0.0f;
                            tokenizer = new SupportClass.Tokenizer(line, "\t ,;");
                            int fields = tokenizer.Count;

                            if (fields < 4)
                            {
                                // this is an error but cannot throw exception
                            }
                            else
                            {
                                System.String atomtype = tokenizer.NextToken();
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                x = (System.Double.Parse(tokenizer.NextToken()));
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                y = (System.Double.Parse(tokenizer.NextToken()));
                                //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                z = (System.Double.Parse(tokenizer.NextToken()));

                                if (fields == 8)
                                {
                                    //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                                    charge = (System.Double.Parse(tokenizer.NextToken()));
                                }

                                IAtom atom = file.Builder.newAtom(atomtype, new Point3d(x, y, z));
                                atom.setCharge(charge);
                                m.addAtom(atom);
                            }
                        }
                    }

                    setOfMolecules.addMolecule(m);
                    chemModel.SetOfMolecules = setOfMolecules;
                    chemSequence.addChemModel(chemModel);
                    line = input.ReadLine();
                }
                file.addChemSequence(chemSequence);
            }
            catch (System.IO.IOException e)
            {
                // should make some noise now
                file = null;
                //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 reading file: ", e.Message);
                //logger.debug(e);
            }
            return(file);
        }
Esempio n. 12
0
        /// <summary> Reads a set of coordinates into ChemFrame.
        ///
        /// </summary>
        /// <param name="model">Description of the Parameter
        /// </param>
        /// <throws>  IOException  if an I/O error occurs </throws>
        /// <throws>  CDKException Description of the Exception </throws>
        private void readCoordinates(IChemModel model)
        {
            ISetOfMolecules moleculeSet = model.Builder.newSetOfMolecules();
            IMolecule       molecule    = model.Builder.newMolecule();

            System.String line = input.ReadLine();
            line = input.ReadLine();
            line = input.ReadLine();
            line = input.ReadLine();
            while (input.Peek() != -1)
            {
                line = input.ReadLine();
                if ((line == null) || (line.IndexOf("-----") >= 0))
                {
                    break;
                }
                int atomicNumber;
                System.IO.StringReader sr = new System.IO.StringReader(line);
                SupportClass.StreamTokenizerSupport token = new SupportClass.StreamTokenizerSupport(sr);
                token.NextToken();

                // ignore first token
                if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER)
                {
                    //UPGRADE_WARNING: Data types in Visual C# might be different.  Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'"
                    atomicNumber = (int)token.nval;
                    if (atomicNumber == 0)
                    {
                        // Skip dummy atoms. Dummy atoms must be skipped
                        // if frequencies are to be read because Gaussian
                        // does not report dummy atoms in frequencies, and
                        // the number of atoms is used for reading frequencies.
                        continue;
                    }
                }
                else
                {
                    throw new CDKException("Error while reading coordinates: expected integer.");
                }
                token.NextToken();

                // ignore third token
                double x;
                double y;
                double z;
                if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER)
                {
                    x = token.nval;
                }
                else
                {
                    throw new System.IO.IOException("Error reading x coordinate");
                }
                if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER)
                {
                    y = token.nval;
                }
                else
                {
                    throw new System.IO.IOException("Error reading y coordinate");
                }
                if (token.NextToken() == SupportClass.StreamTokenizerSupport.TT_NUMBER)
                {
                    z = token.nval;
                }
                else
                {
                    throw new System.IO.IOException("Error reading z coordinate");
                }
                System.String symbol = "Du";
                try
                {
                    symbol = IsotopeFactory.getInstance(model.Builder).getElementSymbol(atomicNumber);
                }
                catch (System.Exception exception)
                {
                    throw new CDKException("Could not determine element symbol!", exception);
                }
                IAtom atom = model.Builder.newAtom(symbol);
                atom.setPoint3d(new Point3d(x, y, z));
                molecule.addAtom(atom);
            }

            /*
             *  this is the place where we store the atomcount to
             *  be used as a counter in the nmr reading
             */
            atomCount = molecule.AtomCount;
            moleculeSet.addMolecule(molecule);
            model.SetOfMolecules = moleculeSet;
        }
Esempio n. 13
0
        /// <summary> Read a <code>ChemFile</code> from a file in PDB format. The molecules
        /// in the file are stored as <code>BioPolymer</code>s in the
        /// <code>ChemFile</code>. The residues are the monomers of the
        /// <code>BioPolymer</code>, and their names are the concatenation of the
        /// residue, chain id, and the sequence number. Separate chains (denoted by
        /// TER records) are stored as separate <code>BioPolymer</code> molecules.
        ///
        /// <p>Connectivity information is not currently read.
        ///
        /// </summary>
        /// <returns> The ChemFile that was read from the PDB file.
        /// </returns>
        private IChemFile readChemFile(IChemFile oFile)
        {
            int bonds = 0;
            // initialize all containers
            IChemSequence   oSeq   = oFile.Builder.newChemSequence();
            IChemModel      oModel = oFile.Builder.newChemModel();
            ISetOfMolecules oSet   = oFile.Builder.newSetOfMolecules();

            // some variables needed
            string     cCol;
            PDBAtom    oAtom;
            PDBPolymer oBP = new PDBPolymer();

            System.Text.StringBuilder cResidue;
            string   oObj;
            IMonomer oMonomer;
            string   cRead = "";
            char     chain = 'A'; // To ensure stringent name giving of monomers
            IStrand  oStrand;
            int      lineLength = 0;

            atomNumberMap = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());

            // do the reading of the Input
            try
            {
                do
                {
                    cRead = _oInput.ReadLine();
                    //logger.debug("Read line: ", cRead);
                    if (cRead != null)
                    {
                        lineLength = cRead.Length;

                        if (lineLength < 80)
                        {
                            //logger.warn("Line is not of the expected length 80!");
                        }

                        // make sure the record name is 6 characters long
                        if (lineLength < 6)
                        {
                            cRead = cRead + "      ";
                        }
                        // check the first column to decide what to do
                        cCol = cRead.Substring(0, (6) - (0));
                        if ("ATOM  ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // read an atom record
                            oAtom = readAtom(cRead, lineLength);

                            // construct a string describing the residue
                            cResidue = new System.Text.StringBuilder(8);
                            oObj     = oAtom.ResName;
                            if (oObj != null)
                            {
                                cResidue = cResidue.Append(oObj.Trim());
                            }
                            oObj = oAtom.ChainID;
                            if (oObj != null)
                            {
                                // cResidue = cResidue.append(((String)oObj).trim());
                                cResidue = cResidue.Append(System.Convert.ToString(chain));
                            }
                            oObj = oAtom.ResSeq;
                            if (oObj != null)
                            {
                                cResidue = cResidue.Append(oObj.Trim());
                            }

                            // search for an existing strand or create a new one.
                            oStrand = oBP.getStrand(System.Convert.ToString(chain));
                            if (oStrand == null)
                            {
                                oStrand            = new PDBStrand();
                                oStrand.StrandName = System.Convert.ToString(chain);
                            }

                            // search for an existing monomer or create a new one.
                            oMonomer = oBP.getMonomer(cResidue.ToString(), System.Convert.ToString(chain));
                            if (oMonomer == null)
                            {
                                PDBMonomer monomer = new PDBMonomer();
                                monomer.MonomerName = cResidue.ToString();
                                monomer.MonomerType = oAtom.ResName;
                                monomer.ChainID     = oAtom.ChainID;
                                monomer.ICode       = oAtom.ICode;
                                oMonomer            = monomer;
                            }

                            // add the atom
                            oBP.addAtom(oAtom, oMonomer, oStrand);
                            System.Object tempObject;
                            //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                            tempObject = atomNumberMap[(System.Int32)oAtom.Serial];
                            atomNumberMap[(System.Int32)oAtom.Serial] = oAtom;
                            if (readConnect.Set && tempObject != null)
                            {
                                //logger.warn("Duplicate serial ID found for atom: ", oAtom);
                            }
                            //						//logger.debug("Added ATOM: ", oAtom);

                            /** As HETATMs cannot be considered to either belong to a certain monomer or strand,
                             * they are dealt with seperately.*/
                        }
                        else if ("HETATM".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // read an atom record
                            oAtom         = readAtom(cRead, lineLength);
                            oAtom.HetAtom = true;
                            oBP.addAtom(oAtom);
                            System.Object tempObject2;
                            //UPGRADE_WARNING: At least one expression was used more than once in the target code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1181'"
                            tempObject2 = atomNumberMap[(System.Int32)oAtom.Serial];
                            atomNumberMap[(System.Int32)oAtom.Serial] = oAtom;
                            if (tempObject2 != null)
                            {
                                //logger.warn("Duplicate serial ID found for atom: ", oAtom);
                            }
                            //logger.debug("Added HETATM: ", oAtom);
                        }
                        else if ("TER   ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            // start new strand
                            chain++;
                            oStrand            = new PDBStrand();
                            oStrand.StrandName = System.Convert.ToString(chain);
                            //logger.debug("Added new STRAND");
                        }
                        else if ("END   ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            atomNumberMap.Clear();
                            // create bonds and finish the molecule
                            if (deduceBonding.Set)
                            {
                                // OK, try to deduce the bonding patterns
                                if (oBP.AtomCount != 0)
                                {
                                    // Create bonds. If bonds could not be created, all bonds are deleted.
                                    try
                                    {
                                        if (useRebondTool.Set)
                                        {
                                            if (!createBondsWithRebondTool(oBP))
                                            {
                                                // Get rid of all potentially created bonds.
                                                //logger.info("Bonds could not be created using the RebondTool when PDB file was read.");
                                                oBP.removeAllBonds();
                                            }
                                        }
                                        else
                                        {
                                            if (!createBonds(oBP))
                                            {
                                                // Get rid of all potentially created bonds.
                                                //logger.info("Bonds could not be created when PDB file was read.");
                                                oBP.removeAllBonds();
                                            }
                                        }
                                    }
                                    catch (System.Exception exception)
                                    {
                                        //logger.info("Bonds could not be created when PDB file was read.");
                                        //logger.debug(exception);
                                    }
                                }
                            }
                            oSet.addMolecule(oBP);
                            //						oBP = new BioPolymer();
                            //				} else if (cCol.equals("USER  ")) {
                            //						System.out.println(cLine);
                            //					System.out.println(cLine);
                            //				} else if (cCol.equals("ENDMDL")) {
                            //					System.out.println(cLine);
                        }
                        else if (cCol.Equals("MODEL "))
                        {
                            // OK, start a new model and save the current one first *if* it contains atoms
                            if (oBP.AtomCount > 0)
                            {
                                // save the model
                                oSet.addAtomContainer(oBP);
                                oModel.SetOfMolecules = oSet;
                                oSeq.addChemModel(oModel);
                                // setup a new one
                                oBP    = new PDBPolymer();
                                oModel = oFile.Builder.newChemModel();
                                oSet   = oFile.Builder.newSetOfMolecules();
                            }
                        }
                        else if ("REMARK".ToUpper().Equals(cCol.ToUpper()))
                        {
                            System.Object comment = oFile.getProperty(CDKConstants.COMMENT);
                            if (comment == null)
                            {
                                comment = "";
                            }
                            if (lineLength > 12)
                            {
                                //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'"
                                comment = comment.ToString() + cRead.Substring(11).Trim() + "\n";
                                oFile.setProperty(CDKConstants.COMMENT, comment);
                            }
                            else
                            {
                                //logger.warn("REMARK line found without any comment!");
                            }
                        }
                        else if ("COMPND".ToUpper().Equals(cCol.ToUpper()))
                        {
                            string title = cRead.Substring(10).Trim();
                            oFile.setProperty(CDKConstants.TITLE, title);
                        }

                        /*************************************************************
                         * Read connectivity information from CONECT records.
                         * Only covalent bonds are dealt with. Perhaps salt bridges
                         * should be dealt with in the same way..?
                         */
                        else if (readConnect.Set && "CONECT".ToUpper().Equals(cCol.ToUpper()))
                        {
                            cRead.Trim();
                            if (cRead.Length < 16)
                            {
                                //logger.debug("Skipping unexpected empty CONECT line! : ", cRead);
                            }
                            else
                            {
                                string bondAtom   = cRead.Substring(7, 5).Trim();
                                int    bondAtomNo = System.Int32.Parse(bondAtom);

                                for (int b = 0; b < 9; b += (b == 5 ? 2 : 1))
                                {
                                    string bondedAtom = cRead.Substring((b * 5) + 11, 5).Trim();
                                    int    bondedAtomNo;
                                    if (int.TryParse(bondedAtom, out bondedAtomNo))
                                    {
                                        bonds++;
                                        addBond(oBP, bondAtomNo, bondedAtomNo);
                                    }
                                }

                                //string bondedAtom = cRead.Substring(12, 5).Trim();
                                //int bondedAtomNo = -1;

                                //try
                                //{
                                //    bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //}
                                //catch (System.Exception e)
                                //{
                                //    bondedAtomNo = -1;
                                //}

                                //if (bondedAtomNo != -1)
                                //{
                                //    bonds++;
                                //    addBond(oBP, bondAtomNo, bondedAtomNo);
                                //    //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //}
                                //else
                                //{
                                //}

                                //if (cRead.Length > 17)
                                //{
                                //    bondedAtom = cRead.Substring(16, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}

                                //if (cRead.Length > 22)
                                //{
                                //    bondedAtom = cRead.Substring(22, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}

                                //if (cRead.Length > 27)
                                //{
                                //    bondedAtom = cRead.Substring(27, 5);
                                //    bondedAtom = bondedAtom.Trim();
                                //    try
                                //    {
                                //        bondedAtomNo = System.Int32.Parse(bondedAtom);
                                //    }
                                //    catch (System.Exception e)
                                //    {
                                //        bondedAtomNo = -1;
                                //    }

                                //    if (bondedAtomNo != -1)
                                //    {
                                //        bonds++;
                                //        addBond(oBP, bondAtomNo, bondedAtomNo);
                                //        //logger.warn("Bonded " + bondAtomNo + " with " + bondedAtomNo);
                                //    }
                                //}
                            }
                        }
                        /*************************************************************/
                        else if ("HELIX ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            //						HELIX    1 H1A CYS A   11  LYS A   18  1 RESIDUE 18 HAS POSITIVE PHI    1D66  72
                            //						          1         2         3         4         5         6         7
                            //						01234567890123456789012345678901234567890123456789012345678901234567890123456789
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.HELIX;
                            structure.StartChainID        = cRead[19];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(21, (25) - (21)).Trim());
                            structure.StartInsertionCode  = cRead[25];
                            structure.EndChainID          = cRead[31];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(33, (37) - (33)).Trim());
                            structure.EndInsertionCode    = cRead[37];
                            oBP.addStructure(structure);
                        }
                        else if ("SHEET ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.SHEET;
                            structure.StartChainID        = cRead[21];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(22, (26) - (22)).Trim());
                            structure.StartInsertionCode  = cRead[26];
                            structure.EndChainID          = cRead[32];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(33, (37) - (33)).Trim());
                            structure.EndInsertionCode    = cRead[37];
                            oBP.addStructure(structure);
                        }
                        else if ("TURN  ".ToUpper().Equals(cCol.ToUpper()))
                        {
                            PDBStructure structure = new PDBStructure();
                            structure.StructureType       = PDBStructure.TURN;
                            structure.StartChainID        = cRead[19];
                            structure.StartSequenceNumber = System.Int32.Parse(cRead.Substring(20, (24) - (20)).Trim());
                            structure.StartInsertionCode  = cRead[24];
                            structure.EndChainID          = cRead[30];
                            structure.EndSequenceNumber   = System.Int32.Parse(cRead.Substring(31, (35) - (31)).Trim());
                            structure.EndInsertionCode    = cRead[35];
                            oBP.addStructure(structure);
                        } // ignore all other commands
                    }
                }while (_oInput.Peek() != -1 && (cRead != null));
            }
            catch (System.Exception e)
            {
                //logger.error("Found a problem at line:\n");
                //logger.error(cRead);
                //logger.error("01234567890123456789012345678901234567890123456789012345678901234567890123456789");
                //logger.error("          1         2         3         4         5         6         7         ");
                //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: " + e.Message);
                //logger.debug(e);
            }

            // try to close the Input
            try
            {
                _oInput.Close();
            }
            catch (System.Exception e)
            {
                //logger.debug(e);
            }

            // Set all the dependencies
            oModel.SetOfMolecules = oSet;
            oSeq.addChemModel(oModel);
            oFile.addChemSequence(oSeq);

            return(oFile);
        }
Esempio n. 14
0
        /// <summary> Read a ChemFile from a file in MDL SDF format.
        ///
        /// </summary>
        /// <returns>    The ChemFile that was read from the MDL file.
        /// </returns>
        private IChemFile readChemFile(IChemFile chemFile)
        {
            IChemSequence chemSequence = chemFile.Builder.newChemSequence();

            IChemModel      chemModel      = chemFile.Builder.newChemModel();
            ISetOfMolecules setOfMolecules = chemFile.Builder.newSetOfMolecules();
            IMolecule       m = readMolecule(chemFile.Builder.newMolecule());

            if (m != null)
            {
                setOfMolecules.addMolecule(m);
            }
            chemModel.SetOfMolecules = setOfMolecules;
            chemSequence.addChemModel(chemModel);

            setOfMolecules = chemFile.Builder.newSetOfMolecules();
            chemModel      = chemFile.Builder.newChemModel();
            System.String str;
            try
            {
                System.String line;
                while ((line = input.ReadLine()) != null)
                {
                    //logger.debug("line: ", line);
                    // apparently, this is a SDF file, continue with
                    // reading mol files
                    str = new System.Text.StringBuilder(line).ToString();
                    if (str.Equals("$$$$"))
                    {
                        m = readMolecule(chemFile.Builder.newMolecule());

                        if (m != null)
                        {
                            setOfMolecules.addMolecule(m);

                            chemModel.SetOfMolecules = setOfMolecules;
                            chemSequence.addChemModel(chemModel);

                            setOfMolecules = chemFile.Builder.newSetOfMolecules();
                            chemModel      = chemFile.Builder.newChemModel();
                        }
                    }
                    else
                    {
                        // here the stuff between 'M  END' and '$$$$'
                        if (m != null)
                        {
                            // ok, the first lines should start with '>'
                            System.String fieldName = null;
                            if (str.StartsWith("> "))
                            {
                                // ok, should extract the field name
                                str.Substring(2); // String content =
                                int index = str.IndexOf("<");
                                if (index != -1)
                                {
                                    int index2 = str.Substring(index).IndexOf(">");
                                    if (index2 != -1)
                                    {
                                        fieldName = str.Substring(index + 1, (index + index2) - (index + 1));
                                    }
                                }
                                // end skip all other lines
                                while ((line = input.ReadLine()) != null && line.StartsWith(">"))
                                {
                                    //logger.debug("data header line: ", line);
                                }
                            }
                            if (line == null)
                            {
                                throw new CDKException("Expecting data line here, but found null!");
                            }
                            System.String data = line;
                            while ((line = input.ReadLine()) != null && line.Trim().Length > 0)
                            {
                                if (line.Equals("$$$$"))
                                {
                                    //logger.error("Expecting data line here, but found end of molecule: ", line);
                                    break;
                                }
                                //logger.debug("data line: ", line);
                                data += line;
                            }
                            if (fieldName != null)
                            {
                                //logger.info("fieldName, data: ", fieldName, ", ", data);
                                m.setProperty(fieldName, data);
                            }
                        }
                    }
                }
            }
            catch (CDKException cdkexc)
            {
                throw cdkexc;
            }
            catch (System.Exception exception)
            {
                System.String error = "Error while parsing SDF";
                //logger.error(error);
                //logger.debug(exception);
                throw new CDKException(error, exception);
            }
            try
            {
                input.Close();
            }
            catch (System.Exception exc)
            {
                //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 closing file: " + exc.Message;
                //logger.error(error);
                throw new CDKException(error, exc);
            }

            chemFile.addChemSequence(chemSequence);
            return(chemFile);
        }
Esempio n. 15
0
        /// <summary>  Private method that actually parses the input to read a ChemFile
        /// object.
        ///
        /// </summary>
        /// <returns> A ChemFile containing the data parsed from input.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence chemSequence = file.Builder.newChemSequence();

            int number_of_atoms = 0;

            SupportClass.Tokenizer tokenizer;

            try
            {
                System.String line = input.ReadLine();
                while (line.StartsWith("#"))
                {
                    line = input.ReadLine();
                }

                /*while (input.ready() && line != null)
                 * {*/
                //        System.out.println("lauf");
                // parse frame by frame
                tokenizer = new SupportClass.Tokenizer(line, "\t ,;");

                System.String token = tokenizer.NextToken();
                number_of_atoms = System.Int32.Parse(token);
                System.String info = input.ReadLine();

                IChemModel      chemModel      = file.Builder.newChemModel();
                ISetOfMolecules setOfMolecules = file.Builder.newSetOfMolecules();

                IMolecule m = file.Builder.newMolecule();
                m.setProperty(CDKConstants.TITLE, info);

                System.String[] types = new System.String[number_of_atoms];
                double[]        d = new double[number_of_atoms]; int[] d_atom = new int[number_of_atoms];   // Distances
                double[]        a = new double[number_of_atoms]; int[] a_atom = new int[number_of_atoms];   // Angles
                double[]        da = new double[number_of_atoms]; int[] da_atom = new int[number_of_atoms]; // Diederangles
                //Point3d[] pos = new Point3d[number_of_atoms]; // calculated positions

                int i = 0;
                while (i < number_of_atoms)
                {
                    line = input.ReadLine();
                    //          System.out.println("line:\""+line+"\"");
                    if (line == null)
                    {
                        break;
                    }
                    if (line.StartsWith("#"))
                    {
                        // skip comment in file
                    }
                    else
                    {
                        d[i]  = 0d; d_atom[i] = -1;
                        a[i]  = 0d; a_atom[i] = -1;
                        da[i] = 0d; da_atom[i] = -1;

                        tokenizer = new SupportClass.Tokenizer(line, "\t ,;");
                        int fields = tokenizer.Count;

                        if (fields < System.Math.Min(i * 2 + 1, 7))
                        {
                            // this is an error but cannot throw exception
                        }
                        else if (i == 0)
                        {
                            types[i] = tokenizer.NextToken();
                            i++;
                        }
                        else if (i == 1)
                        {
                            types[i]  = tokenizer.NextToken();
                            d_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            d[i] = (System.Double.Parse(tokenizer.NextToken()));
                            i++;
                        }
                        else if (i == 2)
                        {
                            types[i]  = tokenizer.NextToken();
                            d_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            d[i]      = (System.Double.Parse(tokenizer.NextToken()));
                            a_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            a[i] = (System.Double.Parse(tokenizer.NextToken()));
                            i++;
                        }
                        else
                        {
                            types[i]  = tokenizer.NextToken();
                            d_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            d[i]      = (System.Double.Parse(tokenizer.NextToken()));
                            a_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            a[i]       = (System.Double.Parse(tokenizer.NextToken()));
                            da_atom[i] = (System.Int32.Parse(tokenizer.NextToken())) - 1;
                            //UPGRADE_TODO: The differences in the format  of parameters for constructor 'java.lang.Double.Double'  may cause compilation errors.  "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1092'"
                            da[i] = (System.Double.Parse(tokenizer.NextToken()));
                            i++;
                        }
                    }
                }

                // calculate cartesian coordinates
                Point3d[] cartCoords = ZMatrixTools.zmatrixToCartesian(d, d_atom, a, a_atom, da, da_atom);

                for (i = 0; i < number_of_atoms; i++)
                {
                    m.addAtom(file.Builder.newAtom(types[i], cartCoords[i]));
                }

                //        System.out.println("molecule:\n"+m);

                setOfMolecules.addMolecule(m);
                chemModel.SetOfMolecules = setOfMolecules;
                chemSequence.addChemModel(chemModel);
                line = input.ReadLine();
                file.addChemSequence(chemSequence);
            }
            catch (System.IO.IOException e)
            {
                // should make some noise now
                file = null;
            }
            return(file);
        }
Esempio n. 16
0
        /// <summary>  Private method that actually parses the input to read a ChemFile
        /// object. In its current state it is able to read all the molecules
        /// (if more than one is present) in the specified HIN file. These are
        /// placed in a SetOfMolecules object which in turn is placed in a ChemModel
        /// which in turn is placed in a ChemSequence object and which is finally
        /// placed in a ChemFile object and returned to the user.
        ///
        /// </summary>
        /// <returns> A ChemFile containing the data parsed from input.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence   chemSequence   = file.Builder.newChemSequence();
            IChemModel      chemModel      = file.Builder.newChemModel();
            ISetOfMolecules setOfMolecules = file.Builder.newSetOfMolecules();

            System.String info;

            SupportClass.Tokenizer tokenizer;

            try
            {
                System.String line;

                // read in header info
                while (true)
                {
                    line = input.ReadLine();
                    if (line.IndexOf("mol ") == 0)
                    {
                        info = getMolName(line);
                        break;
                    }
                }


                // start the actual molecule data - may be multiple molecule
                line = input.ReadLine();
                while (true)
                {
                    if (line == null)
                    {
                        break; // end of file
                    }
                    if (line.IndexOf(';') == 0)
                    {
                        continue; // comment line
                    }
                    if (line.IndexOf("mol ") == 0)
                    {
                        info = getMolName(line);
                        line = input.ReadLine();
                    }
                    IMolecule m = file.Builder.newMolecule();
                    m.setProperty(CDKConstants.TITLE, info);

                    // Each elemnt of cons is an ArrayList of length 3 which stores
                    // the start and end indices and bond order of each bond
                    // found in the HIN file. Before adding bonds we need to reduce
                    // the number of bonds so as not to count the same bond twice
                    System.Collections.ArrayList cons = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));

                    // read data for current molecule
                    int atomSerial = 0;
                    while (true)
                    {
                        if (line.IndexOf("endmol ") >= 0)
                        {
                            break;
                        }
                        if (line.IndexOf(';') == 0)
                        {
                            continue; // comment line
                        }
                        tokenizer = new SupportClass.Tokenizer(line, " ");

                        int             ntoken = tokenizer.Count;
                        System.String[] toks   = new System.String[ntoken];
                        for (int i = 0; i < ntoken; i++)
                        {
                            toks[i] = tokenizer.NextToken();
                        }

                        System.String sym    = new System.Text.StringBuilder(toks[3]).ToString();
                        double        charge = System.Double.Parse(toks[6]);
                        double        x      = System.Double.Parse(toks[7]);
                        double        y      = System.Double.Parse(toks[8]);
                        double        z      = System.Double.Parse(toks[9]);
                        int           nbond  = System.Int32.Parse(toks[10]);

                        IAtom atom = file.Builder.newAtom(sym, new Point3d(x, y, z));
                        atom.setCharge(charge);

                        for (int j = 11; j < (11 + nbond * 2); j += 2)
                        {
                            double bo = 1;
                            int    s  = System.Int32.Parse(toks[j]) - 1; // since atoms start from 1 in the file
                            char   bt = toks[j + 1][0];
                            switch (bt)
                            {
                            case 's':
                                bo = 1;
                                break;

                            case 'd':
                                bo = 2;
                                break;

                            case 't':
                                bo = 3;
                                break;

                            case 'a':
                                bo = 1.5;
                                break;
                            }
                            System.Collections.ArrayList ar = new System.Collections.ArrayList(3);
                            ar.Add((System.Int32)atomSerial);
                            ar.Add((System.Int32)s);
                            ar.Add((double)bo);
                            cons.Add(ar);
                        }
                        m.addAtom(atom);
                        atomSerial++;
                        line = input.ReadLine();
                    }

                    // before storing the molecule lets include the connections
                    // First we reduce the number of bonds stored, since we have
                    // stored both, say, C1-H1 and H1-C1.
                    System.Collections.ArrayList blist = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
                    for (int i = 0; i < cons.Count; i++)
                    {
                        System.Collections.ArrayList ar = (System.Collections.ArrayList)cons[i];

                        // make a reversed list
                        System.Collections.ArrayList arev = new System.Collections.ArrayList(3);
                        arev.Add(ar[1]);
                        arev.Add(ar[0]);
                        arev.Add(ar[2]);

                        // Now see if ar or arev are already in blist
                        if (blist.Contains(ar) || blist.Contains(arev))
                        {
                            continue;
                        }
                        else
                        {
                            blist.Add(ar);
                        }
                    }

                    // now just store all the bonds we have
                    for (int i = 0; i < blist.Count; i++)
                    {
                        System.Collections.ArrayList ar = (System.Collections.ArrayList)blist[i];
                        int    s  = ((System.Int32)ar[0]);
                        int    e  = ((System.Int32)ar[1]);
                        double bo = ((System.Double)ar[2]);
                        m.addBond(s, e, bo);
                    }

                    setOfMolecules.addMolecule(m);
                    line = input.ReadLine(); // read in the 'mol N'
                }

                // got all the molecule in the HIN file (hopefully!)
                chemModel.SetOfMolecules = setOfMolecules;
                chemSequence.addChemModel(chemModel);
                file.addChemSequence(chemSequence);
            }
            catch (System.IO.IOException e)
            {
                // should make some noise now
                file = null;
            }
            return(file);
        }