public static int getBondCount(IChemFile file)
 {
     int count = 0;
     for (int i = 0; i < file.ChemSequenceCount; i++)
     {
         count += ChemSequenceManipulator.getBondCount(file.getChemSequence(i));
     }
     return count;
 }
 /// <summary> Puts all the Molecules of this container together in one 
 /// AtomCcntainer.
 /// 
 /// </summary>
 /// <returns>  The AtomContainer with all the Molecules of this container
 /// 
 /// </returns>
 /// <deprecated> This method has a serious performace impact. Try to use
 /// other methods.
 /// </deprecated>
 public static IAtomContainer getAllInOneContainer(IChemFile file)
 {
     IAtomContainer container = file.Builder.newAtomContainer();
     for (int i = 0; i < file.ChemSequenceCount; i++)
     {
         IChemSequence sequence = file.getChemSequence(i);
         container.add(ChemSequenceManipulator.getAllInOneContainer(sequence));
     }
     return container;
 }
Esempio n. 3
0
        // private procedures

        /// <summary>
        ///  Private method that actually parses the input to read a <see cref="IChemFile"/>  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;

            try
            {
                string line;
                while ((line = input.ReadLine()) != null)
                {
                    // parse frame by frame
                    string token = line.Split('\t', ' ', ',', ';')[0];
                    number_of_atoms = int.Parse(token, NumberFormatInfo.InvariantInfo);
                    string info = input.ReadLine();

                    IChemModel chemModel      = file.Builder.NewChemModel();
                    var        setOfMolecules = file.Builder.NewAtomContainerSet();

                    IAtomContainer m = file.Builder.NewAtomContainer();
                    m.Title = info;

                    for (int i = 0; i < number_of_atoms; i++)
                    {
                        line = input.ReadLine();
                        if (line == null)
                        {
                            break;
                        }
                        if (line.StartsWithChar('#') && line.Length > 1)
                        {
                            var comment = m.GetProperty(CDKPropertyName.Comment, "");
                            comment = comment + line.Substring(1).Trim();
                            m.SetProperty(CDKPropertyName.Comment, comment);
                            Debug.WriteLine($"Found and set comment: {comment}");
                            i--; // a comment line does not count as an atom
                        }
                        else
                        {
                            double x = 0.0f, y = 0.0f, z = 0.0f;
                            double charge    = 0.0f;
                            var    tokenizer = Strings.Tokenize(line, '\t', ' ', ',', ';');
                            int    fields    = tokenizer.Count;

                            if (fields < 4)
                            {
                                // this is an error but cannot throw exception
                            }
                            else
                            {
                                string atomtype = tokenizer[0];
                                x = double.Parse(tokenizer[1], NumberFormatInfo.InvariantInfo);
                                y = double.Parse(tokenizer[2], NumberFormatInfo.InvariantInfo);
                                z = double.Parse(tokenizer[3], NumberFormatInfo.InvariantInfo);
                                if (fields == 8)
                                {
                                    charge = double.Parse(tokenizer[4], NumberFormatInfo.InvariantInfo);
                                }

                                IAtom atom = file.Builder.NewAtom(atomtype, new Vector3(x, y, z));
                                atom.Charge = charge;
                                m.Atoms.Add(atom);
                            }
                        }
                    }

                    setOfMolecules.Add(m);
                    chemModel.MoleculeSet = setOfMolecules;
                    chemSequence.Add(chemModel);
                    line = input.ReadLine();
                }
                file.Add(chemSequence);
            }
            catch (IOException e)
            {
                // should make some noise now
                file = null;
                Trace.TraceError($"Error while reading file: {e.Message}");
                Debug.WriteLine(e);
            }
            return(file);
        }
Esempio n. 4
0
 public CMLCml CDKChemFileToCMLList(IChemFile file)
 {
     return(CDKChemFileToCMLList(file, true));
 }
Esempio n. 5
0
        // private functions

        private IChemFile readChemFile(IChemFile file)
        {
            //logger.debug("Started parsing from input...");
            ChemFileCDO cdo = new ChemFileCDO(file);

            try
            {
                parser.setFeature("http://xml.org/sax/features/validation", false);
                //logger.info("Deactivated validation");
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            catch (System.Xml.XmlException e)
            {
                //logger.warn("Cannot deactivate validation.");
                return(cdo);
            }
            parser.setContentHandler(new CMLHandler((IChemicalDocumentObject)cdo));
            parser.setEntityResolver(new CMLResolver());
            //UPGRADE_TODO: Method 'org.xml.sax.XMLReader.setErrorHandler' was converted to 'XmlSAXDocumentManager.SetErrorHandler' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_orgxmlsaxXMLReadersetErrorHandler_orgxmlsaxErrorHandler'"
            parser.setErrorHandler(new CMLErrorHandler());
            try
            {
                if (input == null)
                {
                    //logger.debug("Parsing from URL: ", url);
                    parser.parse(url);
                }
                else
                {
                    //logger.debug("Parsing from Reader");
                    input.BaseStream.Seek(0, SeekOrigin.Begin);
                    parser.parse(new XmlSourceSupport(input));
                }
            }
            catch (System.IO.IOException e)
            {
                //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 reading file: " + e.Message;
                //logger.error(error);
                //logger.debug(e);
                throw new CDKException(error, e);
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXParseException' was converted to 'System.xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            catch (System.Xml.XmlException saxe)
            {
                //UPGRADE_TODO: Class 'org.xml.sax.SAXParseException' was converted to 'System.xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                System.Xml.XmlException spe   = (System.Xml.XmlException)saxe;
                System.String           error = "Found well-formedness error in line " + spe.LineNumber;
                //logger.error(error);
                //logger.debug(saxe);
                throw new CDKException(error, saxe);
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            //catch (System.Xml.XmlException saxe)
            //{
            //    System.String error = "Error while parsing XML: " + saxe.Message;
            //    //logger.error(error);
            //    //logger.debug(saxe);
            //    throw new CDKException(error, saxe);
            //}
            return(cdo);
        }
Esempio n. 6
0
 private void writeChemFile(IChemFile file)
 {
     IAtomContainer[] molecules = ChemFileManipulator.getAllAtomContainers(file);
     for (int i = 0; i < molecules.Length; i++)
     {
         try
         {
             bool[] isVisible = new bool[molecules[i].AtomCount];
             for (int k = 0; k < isVisible.Length; k++)
             {
                 isVisible[k] = true;
             }
             writeMolecule(file.Builder.newMolecule(molecules[i]), isVisible);
         }
         catch (System.Exception exc)
         {
         }
     }
 }
Esempio n. 7
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;
        }
Esempio n. 8
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;
        }
Esempio n. 9
0
 public MDMoleculeConvention(IChemFile chemFile)
     : base(chemFile)
 {
 }
Esempio n. 10
0
 public override ValidationReport ValidateChemFile(IChemFile subject)
 {
     return(ValidateChemFileNulls(subject));
 }
Esempio n. 11
0
        public void TestMDMoleculeCustomizationRoundtripping()
        {
            StringWriter writer = new StringWriter();

            CMLWriter cmlWriter = new CMLWriter(writer);

            cmlWriter.RegisterCustomizer(new MDMoleculeCustomizer());
            MDMolecule molecule = MakeMDBenzene();

            cmlWriter.Write(molecule);
            cmlWriter.Close();

            string serializedMol = writer.ToString();

            Debug.WriteLine("****************************** TestMDMoleculeCustomizationRoundtripping()");
            Debug.WriteLine(serializedMol);
            Debug.WriteLine("******************************");
            Debug.WriteLine("****************************** testMDMoleculeCustomization Write first");
            Debug.WriteLine(serializedMol);
            Debug.WriteLine("******************************");

            CMLReader reader = new CMLReader(new MemoryStream(Encoding.UTF8.GetBytes(serializedMol)));

            reader.RegisterConvention("md:mdMolecule", new MDMoleculeConvention(builder.NewChemFile()));
            IChemFile file = (IChemFile)reader.Read(builder.NewChemFile());

            reader.Close();
            var containers = ChemFileManipulator.GetAllAtomContainers(file).ToReadOnlyList();

            Assert.AreEqual(1, containers.Count);

            var molecule2 = containers[0];

            Assert.IsTrue(molecule2 is MDMolecule);
            MDMolecule mdMol = (MDMolecule)molecule2;

            Assert.AreEqual(6, mdMol.Atoms.Count);
            Assert.AreEqual(6, mdMol.Bonds.Count);

            var residues = mdMol.GetResidues();

            Assert.AreEqual(2, residues.Count);
            Assert.AreEqual(3, ((Residue)residues[0]).Atoms.Count);
            Assert.AreEqual(3, ((Residue)residues[1]).Atoms.Count);
            Assert.AreEqual("myResidue1", ((Residue)residues[0]).Name);
            Assert.AreEqual("myResidue2", ((Residue)residues[1]).Name);
            Assert.AreEqual(0, ((Residue)residues[0]).GetNumber());
            Assert.AreEqual(1, ((Residue)residues[1]).GetNumber());

            var chargeGroup = mdMol.GetChargeGroups();

            Assert.AreEqual(2, chargeGroup.Count);
            Assert.AreEqual(2, ((ChargeGroup)chargeGroup[0]).Atoms.Count);
            Assert.AreEqual(4, ((ChargeGroup)chargeGroup[1]).Atoms.Count);
            Assert.IsNotNull(((ChargeGroup)chargeGroup[0]).GetSwitchingAtom());
            Assert.AreEqual("a2", ((ChargeGroup)chargeGroup[0]).GetSwitchingAtom().Id);
            Assert.IsNotNull(((ChargeGroup)chargeGroup[1]).GetSwitchingAtom());
            Assert.AreEqual("a5", ((ChargeGroup)chargeGroup[1]).GetSwitchingAtom().Id);

            Assert.AreEqual(2, ((ChargeGroup)chargeGroup[0]).GetNumber());
            Assert.AreEqual(3, ((ChargeGroup)chargeGroup[1]).GetNumber());

            writer = new StringWriter();

            cmlWriter = new CMLWriter(writer);
            cmlWriter.RegisterCustomizer(new MDMoleculeCustomizer());
            cmlWriter.Write(mdMol);
            cmlWriter.Close();

            string serializedMDMol = writer.ToString();

            Debug.WriteLine("****************************** TestMDMoleculeCustomizationRoundtripping()");
            Debug.WriteLine(serializedMol);
            Debug.WriteLine("******************************");
            Debug.WriteLine("****************************** testMDMoleculeCustomization Write second");
            Debug.WriteLine(serializedMDMol);
            Debug.WriteLine("******************************");

            Assert.AreEqual(serializedMol, serializedMDMol);
        }
Esempio n. 12
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 MoleculeSet 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)
        {
            var    chemSequence   = file.Builder.NewChemSequence();
            var    chemModel      = file.Builder.NewChemModel();
            var    setOfMolecules = file.Builder.NewAtomContainerSet();
            string info;

            var aroringText = new List <string>();
            var mols        = new List <IAtomContainer>();

            try
            {
                string line;

                // read in header info
                while (true)
                {
                    line = input.ReadLine();
                    if (line.StartsWith("mol", StringComparison.Ordinal))
                    {
                        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.StartsWithChar(';'))
                    {
                        continue; // comment line
                    }
                    if (line.StartsWith("mol", StringComparison.Ordinal))
                    {
                        info = GetMolName(line);
                        line = input.ReadLine();
                    }
                    var m = file.Builder.NewAtomContainer();
                    m.Title = info;

                    // Each element of cons is an List 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
                    List <List <Object> > cons = new List <List <Object> >();

                    // read data for current molecule
                    int atomSerial = 0;
                    while (true)
                    {
                        if (line == null || line.Contains("endmol"))
                        {
                            break;
                        }
                        if (line.StartsWithChar(';'))
                        {
                            continue; // comment line
                        }
                        var toks = line.Split(' ');

                        var sym    = toks[3];
                        var charge = double.Parse(toks[6], NumberFormatInfo.InvariantInfo);
                        var x      = double.Parse(toks[7], NumberFormatInfo.InvariantInfo);
                        var y      = double.Parse(toks[8], NumberFormatInfo.InvariantInfo);
                        var z      = double.Parse(toks[9], NumberFormatInfo.InvariantInfo);
                        var nbond  = int.Parse(toks[10], NumberFormatInfo.InvariantInfo);

                        var atom = file.Builder.NewAtom(sym, new Vector3(x, y, z));
                        atom.Charge = charge;

                        var bo = BondOrder.Single;

                        for (int j = 11; j < (11 + nbond * 2); j += 2)
                        {
                            var s  = int.Parse(toks[j], NumberFormatInfo.InvariantInfo) - 1; // since atoms start from 1 in the file
                            var bt = toks[j + 1][0];
                            switch (bt)
                            {
                            case 's':
                                bo = BondOrder.Single;
                                break;

                            case 'd':
                                bo = BondOrder.Double;
                                break;

                            case 't':
                                bo = BondOrder.Triple;
                                break;

                            case 'a':
                                bo = BondOrder.Quadruple;
                                break;
                            }
                            var ar = new List <object>(3)
                            {
                                atomSerial,
                                s,
                                bo
                            };
                            cons.Add(ar);
                        }
                        m.Atoms.Add(atom);
                        atomSerial++;
                        line = input.ReadLine();
                    }

                    // now just store all the bonds we have
                    foreach (var ar in cons)
                    {
                        var s  = m.Atoms[(int)ar[0]];
                        var e  = m.Atoms[(int)ar[1]];
                        var bo = (BondOrder)ar[2];
                        if (!IsConnected(m, s, e))
                        {
                            m.Bonds.Add(file.Builder.NewBond(s, e, bo));
                        }
                    }
                    mols.Add(m);

                    // we may not get a 'mol N' immediately since
                    // the aromaticring keyword might be present
                    // and doesn't seem to be located within the molecule
                    // block. However, if we do see this keyword we save this
                    // since it can contain aromatic specs for any molecule
                    // listed in the file
                    //
                    // The docs do not explicitly state the the keyword comes
                    // after *all* molecules. So we save and then reprocess
                    // all the molecules in a second pass
                    while (true)
                    {
                        line = input.ReadLine();
                        if (line == null || line.StartsWith("mol", StringComparison.Ordinal))
                        {
                            break;
                        }
                        if (line.StartsWith("aromaticring", StringComparison.Ordinal))
                        {
                            aroringText.Add(line.Trim());
                        }
                    }
                }
            }
            catch (IOException)
            {
                // FIXME: should make some noise now
                file = null;
            }

            if (aroringText.Count > 0)
            { // process aromaticring annotations
                foreach (var line in aroringText)
                {
                    var toks  = line.Split(' ');
                    var natom = int.Parse(toks[1], NumberFormatInfo.InvariantInfo);
                    int n     = 0;
                    for (int i = 2; i < toks.Length; i += 2)
                    {
                        var molnum = int.Parse(toks[i], NumberFormatInfo.InvariantInfo);     // starts from 1
                        var atnum  = int.Parse(toks[i + 1], NumberFormatInfo.InvariantInfo); // starts from 1
                        mols[molnum - 1].Atoms[atnum - 1].IsAromatic = true;
                        n++;
                    }
                    Trace.Assert(n == natom);
                }
            }

            foreach (var mol in mols)
            {
                setOfMolecules.Add(mol);
            }
            chemModel.MoleculeSet = setOfMolecules;
            chemSequence.Add(chemModel);
            file.Add(chemSequence);

            return(file);
        }
Esempio n. 13
0
 /// <summary>
 /// Tests whether the file is indeed a single reaction file
 /// </summary>
 private IReaction CheckForSingleReactionFile(IChemFile chemFile)
 {
     return(CheckForXReactionFile(chemFile, 1));
 }
Esempio n. 14
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. 15
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);
        }
Esempio n. 16
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. 17
0
        /// <summary> Read the ShelX from input. Each ShelX document is expected to contain
        /// one crystal structure.
        /// 
        /// </summary>
        /// <returns> a ChemFile with the coordinates, charges, vectors, etc.
        /// </returns>
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence seq = file.Builder.newChemSequence();
            IChemModel model = file.Builder.newChemModel();
            crystal = file.Builder.newCrystal();

            System.String line = input.ReadLine();
            bool end_found = false;
            while (input.Peek() != -1 && line != null && !end_found)
            {
                if (line.StartsWith("#"))
                {
                    //logger.warn("Skipping comment: " + line);
                    // skip comment lines
                }
                else if (line.Length == 0)
                {
                    //logger.debug("Skipping empty line");
                    // skip empty lines
                }
                else if (!(line.StartsWith("_") || line.StartsWith("loop_")))
                {
                    //logger.warn("Skipping unrecognized line: " + line);
                    // skip line
                }
                else
                {

                    /* determine CIF command */
                    System.String command = "";
                    int spaceIndex = line.IndexOf(" ");
                    if (spaceIndex != -1)
                    {
                        // everything upto space is command
                        try
                        {
                            command = new System.Text.StringBuilder(line.Substring(0, (spaceIndex) - (0))).ToString();
                        }
                        catch (System.ArgumentOutOfRangeException sioobe)
                        {
                            // disregard this line
                            break;
                        }
                    }
                    else
                    {
                        // complete line is command
                        command = line;
                    }

                    //logger.debug("command: " + command);
                    if (command.StartsWith("_cell"))
                    {
                        processCellParameter(command, line);
                    }
                    else if (command.Equals("loop_"))
                    {
                        processLoopBlock();
                    }
                    else if (command.Equals("_symmetry_space_group_name_H-M"))
                    {
                        System.String value_Renamed = line.Substring(29).Trim();
                        crystal.SpaceGroup = value_Renamed;
                    }
                    else
                    {
                        // skip command
                        //logger.warn("Skipping command: " + command);
                        line = input.ReadLine();
                        if (line.StartsWith(";"))
                        {
                            //logger.debug("Skipping block content");
                            line = input.ReadLine().Trim();
                            while (!line.Equals(";"))
                            {
                                line = input.ReadLine().Trim();
                                //logger.debug("Skipping block line: " + line);
                            }
                            line = input.ReadLine();
                        }
                    }
                }
                line = input.ReadLine();
            }
            //logger.info("Adding crystal to file with #atoms: " + crystal.AtomCount);
            model.Crystal = crystal;
            seq.addChemModel(model);
            file.addChemSequence(seq);
            return file;
        }
Esempio n. 18
0
 public JMOLANIMATIONConvention(IChemFile chemFile)
     : base(chemFile)
 {
     current = Unknown;
 }
Esempio n. 19
0
 private IChemFile readChemFile(IChemFile file)
 {
     IChemSequence seq = readChemSequence(file.Builder.newChemSequence());
     file.addChemSequence(seq);
     return file;
 }
Esempio n. 20
0
        /// <summary> Read the Gaussian98 output.
        /// 
        /// </summary>
        /// <returns> a ChemFile with the coordinates, energies, and
        /// vibrations.
        /// </returns>
        /// <throws>  IOException  if an I/O error occurs </throws>
        /// <throws>  CDKException Description of the Exception </throws>
        private IChemFile readChemFile(IChemFile chemFile)
        {
            IChemSequence sequence = chemFile.Builder.newChemSequence();
            IChemModel model = null;
            System.String line = input.ReadLine();
            System.String levelOfTheory;
            System.String description;
            int modelCounter = 0;

            // Find first set of coordinates by skipping all before "Standard orientation"
            while (input.Peek() != -1 && (line != null))
            {
                if (line.IndexOf("Standard orientation:") >= 0)
                {

                    // Found a set of coordinates
                    model = chemFile.Builder.newChemModel();
                    readCoordinates(model);
                    break;
                }
                line = input.ReadLine();
            }
            if (model != null)
            {

                // Read all other data
                line = input.ReadLine().Trim();
                while (input.Peek() != -1 && (line != null))
                {
                    if (line.IndexOf("#") == 0)
                    {
                        // Found the route section
                        // Memorizing this for the description of the chemmodel
                        lastRoute = line;
                        modelCounter = 0;
                    }
                    else if (line.IndexOf("Standard orientation:") >= 0)
                    {

                        // Found a set of coordinates
                        // Add current frame to file and create a new one.
                        if (!readOptimizedStructureOnly.Set)
                        {
                            sequence.addChemModel(model);
                        }
                        else
                        {
                            //logger.info("Skipping frame, because I was told to do");
                        }
                        fireFrameRead();
                        model = chemFile.Builder.newChemModel();
                        modelCounter++;
                        readCoordinates(model);
                    }
                    else if (line.IndexOf("SCF Done:") >= 0)
                    {

                        // Found an energy
                        model.setProperty(CDKConstants.REMARK, line.Trim());
                    }
                    else if (line.IndexOf("Harmonic frequencies") >= 0)
                    {

                        // Found a set of vibrations
                        // readFrequencies(frame);
                    }
                    else if (line.IndexOf("Total atomic charges") >= 0)
                    {
                        readPartialCharges(model);
                    }
                    else if (line.IndexOf("Magnetic shielding") >= 0)
                    {

                        // Found NMR data
                        readNMRData(model, line);
                    }
                    else if (line.IndexOf("GINC") >= 0)
                    {

                        // Found calculation level of theory
                        levelOfTheory = parseLevelOfTheory(line);
                        //logger.debug("Level of Theory for this model: " + levelOfTheory);
                        description = lastRoute + ", model no. " + modelCounter;
                        model.setProperty(CDKConstants.DESCRIPTION, description);
                    }
                    else
                    {
                        ////logger.debug("Skipping line: " + line);
                    }
                    line = input.ReadLine();
                }

                // Add last frame to file
                sequence.addChemModel(model);
                fireFrameRead();
            }
            chemFile.addChemSequence(sequence);

            return chemFile;
        }
 /// <summary> Returns all the AtomContainer's of a ChemFile.</summary>
 public static IAtomContainer[] getAllAtomContainers(IChemFile file)
 {
     IChemSequence[] sequences = file.ChemSequences;
     int acCount = 0;
     System.Collections.ArrayList acArrays = System.Collections.ArrayList.Synchronized(new System.Collections.ArrayList(10));
     for (int i = 0; i < sequences.Length; i++)
     {
         IAtomContainer[] sequenceContainers = ChemSequenceManipulator.getAllAtomContainers(sequences[i]);
         acArrays.Add(sequenceContainers);
         acCount += sequenceContainers.Length;
     }
     IAtomContainer[] containers = new IAtomContainer[acCount];
     int arrayOffset = 0;
     //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'"
     for (System.Collections.IEnumerator acArraysElements = acArrays.GetEnumerator(); acArraysElements.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'"
         IAtomContainer[] modelContainers = (IAtomContainer[])acArraysElements.Current;
         Array.Copy(modelContainers, 0, containers, arrayOffset, modelContainers.Length);
         arrayOffset += modelContainers.Length;
     }
     return containers;
 }
Esempio n. 22
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);
        }
 /// <summary> Returns a List of all IChemObject in this ChemFile.
 /// 
 /// </summary>
 /// <returns>  A list of all ChemObjects
 /// </returns>
 public static System.Collections.IList getAllChemObjects(IChemFile file)
 {
     System.Collections.ArrayList list = new System.Collections.ArrayList();
     list.Add(file);
     for (int i = 0; i < file.ChemSequenceCount; i++)
     {
         list.AddRange(ChemSequenceManipulator.getAllChemObjects(file.getChemSequence(i)));
     }
     return list;
 }
Esempio n. 24
0
 private void LoadOutline(IChemFile root)
 {
     outlineTreeView.Nodes.Clear();
     TreeNode rootNode = new TreeNode(root.GetType().Name + ":" + root.ID);
     BuildNodes(rootNode, root.ChemSequences);
     outlineTreeView.Nodes.Add(rootNode);
 }
Esempio n. 25
0
        /// <summary>
        /// Read the ShelX from input. Each ShelX document is expected to contain one crystal structure.
        /// </summary>
        /// <param name="file"></param>
        /// <returns>a ChemFile with the coordinates, charges, vectors, etc.</returns>
        private IChemFile ReadChemFile(IChemFile file)
        {
            IChemSequence seq   = file.Builder.NewChemSequence();
            IChemModel    model = file.Builder.NewChemModel();

            crystal = file.Builder.NewCrystal();

            string line      = input.ReadLine();
            bool   end_found = false;

            while (input.Ready() && line != null && !end_found)
            {
                if (line.Length == 0)
                {
                    Debug.WriteLine("Skipping empty line");
                    // skip empty lines
                }
                else if (line[0] == '#')
                {
                    Trace.TraceWarning("Skipping comment: " + line);
                    // skip comment lines
                }
                else if (!(line[0] == '_' || line.StartsWith("loop_", StringComparison.Ordinal)))
                {
                    Trace.TraceWarning("Skipping unrecognized line: " + line);
                    // skip line
                }
                else
                {
                    /* determine CIF command */
                    string command    = "";
                    int    spaceIndex = line.IndexOf(' ');
                    if (spaceIndex != -1)
                    {
                        // everything upto space is command
                        try
                        {
                            command = line.Substring(0, spaceIndex);
                        }
                        catch (ArgumentOutOfRangeException)
                        {
                            // disregard this line
                            break;
                        }
                    }
                    else
                    {
                        // complete line is command
                        command = line;
                    }

                    Debug.WriteLine($"command: {command}");
                    if (command.StartsWith("_cell", StringComparison.Ordinal))
                    {
                        ProcessCellParameter(command, line);
                    }
                    else if (string.Equals(command, "loop_", StringComparison.Ordinal))
                    {
                        line = ProcessLoopBlock();
                        continue;
                    }
                    else if (string.Equals(command, "_symmetry_space_group_name_H-M", StringComparison.Ordinal))
                    {
                        string value = line.Substring(29).Trim();
                        crystal.SpaceGroup = value;
                    }
                    else
                    {
                        // skip command
                        Trace.TraceWarning("Skipping command: " + command);
                        line = input.ReadLine();
                        if (line.StartsWithChar(';'))
                        {
                            Debug.WriteLine("Skipping block content");
                            line = input.ReadLine();
                            if (line != null)
                            {
                                line = line.Trim();
                            }
                            while (!string.Equals(line, ";", StringComparison.Ordinal))
                            {
                                line = input.ReadLine();
                                if (line != null)
                                {
                                    line = line.Trim();
                                }
                                Debug.WriteLine($"Skipping block line: {line}");
                            }
                            line = input.ReadLine();
                        }
                    }
                }
                line = input.ReadLine();
            }
            Trace.TraceInformation("Adding crystal to file with #atoms: " + crystal.Atoms.Count);
            model.Crystal = crystal;
            seq.Add(model);
            file.Add(seq);
            return(file);
        }
Esempio n. 26
0
        /// <summary>
        ///  Private method that actually parses the input to read a <see cref="IChemFile"/> object.
        /// </summary>
        /// <param name="file">the file to read from</param>
        /// <returns>A ChemFile containing the data parsed from input.</returns>
        private IChemFile ReadChemFile(IChemFile file)
        {
            IChemSequence chemSequence = file.Builder.NewChemSequence();

            int number_of_atoms;

            try
            {
                string line = input.ReadLine();
                while (line.StartsWithChar('#'))
                {
                    line = input.ReadLine();
                }

                // while (input.Ready() && line != null) {
                //        Debug.WriteLine("lauf");
                // parse frame by frame
                string token = Strings.Tokenize(line, '\t', ' ', ',', ';')[0];
                number_of_atoms = int.Parse(token, NumberFormatInfo.InvariantInfo);
                string info = input.ReadLine();

                IChemModel chemModel      = file.Builder.NewChemModel();
                var        setOfMolecules = file.Builder.NewAtomContainerSet();

                IAtomContainer m = file.Builder.NewAtomContainer();
                m.Title = info;

                string[] types   = new 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
                                                             //Vector3[] pos = new Vector3[number_of_atoms]; // calculated positions

                int i = 0;
                while (i < number_of_atoms)
                {
                    line = input.ReadLine();
                    //          Debug.WriteLine("line:\""+line+"\"");
                    if (line == null)
                    {
                        break;
                    }
                    if (line.StartsWithChar('#'))
                    {
                        // 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;

                        var tokens = Strings.Tokenize(line, '\t', ' ', ',', ';');
                        int fields = int.Parse(tokens[0], NumberFormatInfo.InvariantInfo);

                        if (fields < Math.Min(i * 2 + 1, 7))
                        {
                            // this is an error but cannot throw exception
                        }
                        else if (i == 0)
                        {
                            types[i] = tokens[1];
                            i++;
                        }
                        else if (i == 1)
                        {
                            types[i]  = tokens[1];
                            d_atom[i] = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1;
                            d[i]      = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                            i++;
                        }
                        else if (i == 2)
                        {
                            types[i]  = tokens[1];
                            d_atom[i] = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1;
                            d[i]      = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                            a_atom[i] = int.Parse(tokens[4], NumberFormatInfo.InvariantInfo) - 1;
                            a[i]      = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
                            i++;
                        }
                        else
                        {
                            types[i]   = tokens[1];
                            d_atom[i]  = int.Parse(tokens[2], NumberFormatInfo.InvariantInfo) - 1;
                            d[i]       = double.Parse(tokens[3], NumberFormatInfo.InvariantInfo);
                            a_atom[i]  = int.Parse(tokens[4], NumberFormatInfo.InvariantInfo) - 1;
                            a[i]       = double.Parse(tokens[5], NumberFormatInfo.InvariantInfo);
                            da_atom[i] = int.Parse(tokens[6], NumberFormatInfo.InvariantInfo) - 1;
                            da[i]      = double.Parse(tokens[7], NumberFormatInfo.InvariantInfo);
                            i++;
                        }
                    }
                }

                // calculate cartesian coordinates
                var cartCoords = ZMatrixTools.ZMatrixToCartesian(d, d_atom, a, a_atom, da, da_atom);

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

                //        Debug.WriteLine("molecule:"+m);

                setOfMolecules.Add(m);
                chemModel.MoleculeSet = setOfMolecules;
                chemSequence.Add(chemModel);
                line = input.ReadLine();
                file.Add(chemSequence);
            }
            catch (IOException)
            {
                // should make some noise now
                file = null;
            }
            return(file);
        }
Esempio n. 27
0
        // private functions

        private IChemFile readChemFile(IChemFile file)
        {
            //logger.debug("Started parsing from input...");
            ChemFileCDO cdo = new ChemFileCDO(file);
            try
            {
                parser.setFeature("http://xml.org/sax/features/validation", false);
                //logger.info("Deactivated validation");
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            catch (System.Xml.XmlException e)
            {
                //logger.warn("Cannot deactivate validation.");
                return cdo;
            }
            parser.setContentHandler(new CMLHandler((IChemicalDocumentObject)cdo));
            parser.setEntityResolver(new CMLResolver());
            //UPGRADE_TODO: Method 'org.xml.sax.XMLReader.setErrorHandler' was converted to 'XmlSAXDocumentManager.SetErrorHandler' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_orgxmlsaxXMLReadersetErrorHandler_orgxmlsaxErrorHandler'"
            parser.setErrorHandler(new CMLErrorHandler());
            try
            {
                if (input == null)
                {
                    //logger.debug("Parsing from URL: ", url);
                    parser.parse(url);
                }
                else
                {
                    //logger.debug("Parsing from Reader");
                    input.BaseStream.Seek(0, SeekOrigin.Begin);
                    parser.parse(new XmlSourceSupport(input));
                }
            }
            catch (System.IO.IOException e)
            {
                //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 reading file: " + e.Message;
                //logger.error(error);
                //logger.debug(e);
                throw new CDKException(error, e);
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXParseException' was converted to 'System.xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            catch (System.Xml.XmlException saxe)
            {
                //UPGRADE_TODO: Class 'org.xml.sax.SAXParseException' was converted to 'System.xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
                System.Xml.XmlException spe = (System.Xml.XmlException)saxe;
                System.String error = "Found well-formedness error in line " + spe.LineNumber;
                //logger.error(error);
                //logger.debug(saxe);
                throw new CDKException(error, saxe);
            }
            //UPGRADE_TODO: Class 'org.xml.sax.SAXException' was converted to 'System.Xml.XmlException' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073'"
            //catch (System.Xml.XmlException saxe)
            //{
            //    System.String error = "Error while parsing XML: " + saxe.Message;
            //    //logger.error(error);
            //    //logger.debug(saxe);
            //    throw new CDKException(error, saxe);
            //}
            return cdo;
        }
Esempio n. 28
0
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence seq     = file.Builder.newChemSequence();
            IChemModel    model   = file.Builder.newChemModel();
            ICrystal      crystal = null;

            int      lineNumber = 0;
            Vector3d a, b, c;

            try
            {
                System.String line = input.ReadLine();
                while (input.Peek() != -1 && line != null)
                {
                    //logger.debug((lineNumber++) + ": ", line);
                    if (line.StartsWith("frame:"))
                    {
                        //logger.debug("found new frame");
                        model   = file.Builder.newChemModel();
                        crystal = file.Builder.newCrystal();

                        // assume the file format is correct

                        //logger.debug("reading spacegroup");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        crystal.SpaceGroup = line;

                        //logger.debug("reading unit cell axes");
                        Vector3d axis = new Vector3d();
                        //logger.debug("parsing A: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z    = FortranFormat.atof(line);
                        crystal.A = axis;
                        axis      = new Vector3d();
                        //logger.debug("parsing B: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z    = FortranFormat.atof(line);
                        crystal.B = axis;
                        axis      = new Vector3d();
                        //logger.debug("parsing C: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line   = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z    = FortranFormat.atof(line);
                        crystal.C = axis;
                        //logger.debug("Crystal: ", crystal);
                        a = crystal.A;
                        b = crystal.B;
                        c = crystal.C;

                        //logger.debug("Reading number of atoms");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        int atomsToRead = System.Int32.Parse(line);

                        //logger.debug("Reading no molecules in assym unit cell");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        int Z = System.Int32.Parse(line);
                        crystal.Z = Z;

                        System.String symbol;
                        double        charge;
                        Point3d       cart;
                        for (int i = 1; i <= atomsToRead; i++)
                        {
                            cart = new Point3d();
                            line = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            symbol = line.Substring(0, (line.IndexOf(":")) - (0));
                            charge = System.Double.Parse(line.Substring(line.IndexOf(":") + 1));
                            line   = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.x = System.Double.Parse(line); // x
                            line   = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.y = System.Double.Parse(line); // y
                            line   = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.z = System.Double.Parse(line); // z
                            IAtom atom = file.Builder.newAtom(symbol);
                            atom.setCharge(charge);
                            // convert cartesian coords to fractional
                            Point3d frac = CrystalGeometryTools.cartesianToFractional(a, b, c, cart);
                            atom.setFractionalPoint3d(frac);
                            crystal.addAtom(atom);
                            //logger.debug("Added atom: ", atom);
                        }

                        model.Crystal = crystal;
                        seq.addChemModel(model);
                    }
                    else
                    {
                        //logger.debug("Format seems broken. Skipping these lines:");
                        while (!line.StartsWith("frame:") && input.Peek() != -1 && line != null)
                        {
                            line = input.ReadLine();
                            //logger.debug(lineNumber++ + ": ", line);
                        }
                        //logger.debug("Ok, resynched: found new frame");
                    }
                }
                file.addChemSequence(seq);
            }
            catch (System.Exception exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                System.String message = "Error while parsing CrystClust file: " + exception.Message;
                //logger.error(message);
                //logger.debug(exception);
                throw new CDKException(message, exception);
            }
            return(file);
        }
Esempio n. 29
0
#pragma warning disable CA1810 // Initialize reference type static fields inline
        static AminoAcids()
#pragma warning restore CA1810 // Initialize reference type static fields inline
        {
            // Create set of AtomContainers
            proteinogenics = new IAminoAcid[20];

            #region Create proteinogenics
            {
                IChemFile list = CDK.Builder.NewChemFile();
                using (var reader = new CMLReader(ResourceLoader.GetAsStream("NCDK.Templates.Data.list_aminoacids.cml")))
                {
                    try
                    {
                        list = (IChemFile)reader.Read(list);
                        var containersList = ChemFileManipulator.GetAllAtomContainers(list);
                        int counter        = 0;
                        foreach (var ac in containersList)
                        {
                            Debug.WriteLine($"Adding AA: {ac}");
                            // convert into an AminoAcid
                            var aminoAcid = CDK.Builder.NewAminoAcid();
                            foreach (var next in ac.GetProperties().Keys)
                            {
                                Debug.WriteLine("Prop: " + next.ToString());
                                if (next is DictRef dictRef)
                                {
                                    // Debug.WriteLine("DictRef type: " + dictRef.Type}");
                                    if (string.Equals(dictRef.Type, "pdb:residueName", StringComparison.Ordinal))
                                    {
                                        aminoAcid.SetProperty(ResidueNameKey, ac.GetProperty <string>(next).ToUpperInvariant());
                                        aminoAcid.MonomerName = ac.GetProperty <string>(next);
                                    }
                                    else if (string.Equals(dictRef.Type, "pdb:oneLetterCode", StringComparison.Ordinal))
                                    {
                                        aminoAcid.SetProperty(ResidueNameShortKey, ac.GetProperty <string>(next));
                                    }
                                    else if (string.Equals(dictRef.Type, "pdb:id", StringComparison.Ordinal))
                                    {
                                        aminoAcid.SetProperty(IdKey, ac.GetProperty <string>(next));
                                        Debug.WriteLine($"Set AA ID to: {ac.GetProperty<string>(next)}");
                                    }
                                    else
                                    {
                                        Trace.TraceError("Cannot deal with dictRef!");
                                    }
                                }
                            }
                            foreach (var atom in ac.Atoms)
                            {
                                string dictRef = atom.GetProperty <string>("org.openscience.cdk.dict");
                                switch (dictRef)
                                {
                                case "pdb:nTerminus":
                                    aminoAcid.AddNTerminus(atom);
                                    break;

                                case "pdb:cTerminus":
                                    aminoAcid.AddCTerminus(atom);
                                    break;

                                default:
                                    aminoAcid.Atoms.Add(atom);
                                    break;
                                }
                            }
                            foreach (var bond in ac.Bonds)
                            {
                                aminoAcid.Bonds.Add(bond);
                            }
                            AminoAcidManipulator.RemoveAcidicOxygen(aminoAcid);
                            aminoAcid.SetProperty(NoAtomsKey, "" + aminoAcid.Atoms.Count);
                            aminoAcid.SetProperty(NoBoundsKey, "" + aminoAcid.Bonds.Count);
                            if (counter < proteinogenics.Length)
                            {
                                proteinogenics[counter] = aminoAcid;
                            }
                            else
                            {
                                Trace.TraceError("Could not store AminoAcid! Array too short!");
                            }
                            counter++;
                        }
                    }
                    catch (Exception exception)
                    {
                        if (exception is CDKException | exception is IOException)
                        {
                            Trace.TraceError($"Failed reading file: {exception.Message}");
                            Debug.WriteLine(exception);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            #endregion

            int count = proteinogenics.Length;
            singleLetterCodeMap       = new Dictionary <string, IAminoAcid>(count);
            threeLetterCodeMap        = new Dictionary <string, IAminoAcid>(count);
            singleLetterToThreeLetter = new Dictionary <string, string>(count);
            threeLetterToSingleLetter = new Dictionary <string, string>(count);

            foreach (IAminoAcid aa in proteinogenics)
            {
                var single = aa.GetProperty <string>(ResidueNameShortKey);
                var three  = aa.GetProperty <string>(ResidueNameKey);
                singleLetterCodeMap[single]       = aa;
                threeLetterCodeMap[three]         = aa;
                singleLetterToThreeLetter[single] = three;
                threeLetterToSingleLetter[three]  = single;
            }
        }
Esempio n. 30
0
 public MDLMolConvention(IChemFile chemFile)
     : base(chemFile)
 {
 }
Esempio n. 31
0
        //protected internal LoggingTool logger;

        /// <summary> Basic contructor</summary>
        public ChemFileCDO(IChemFile file)
        {
            //logger = new LoggingTool(this);
            currentChemFile = file;
            currentChemSequence = file.Builder.newChemSequence();
            currentChemModel = file.Builder.newChemModel();
            currentSetOfMolecules = file.Builder.newSetOfMolecules();
            currentSetOfReactions = null;
            currentReaction = null;
            currentMolecule = file.Builder.newMolecule();
            atomEnumeration = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
        }
Esempio n. 32
0
 public PDBConvention(IChemFile chemFile)
     : base(chemFile)
 {
 }
 public ChemRenderingSource3D(IChemFile file)
 {
     this.file = file;
     SourceModified();
 }
Esempio n. 34
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. 35
0
        private IChemFile readChemFile(IChemFile file)
        {
            IChemSequence seq = file.Builder.newChemSequence();
            IChemModel model = file.Builder.newChemModel();
            ICrystal crystal = null;

            int lineNumber = 0;
            Vector3d a, b, c;

            try
            {
                System.String line = input.ReadLine();
                while (input.Peek() != -1 && line != null)
                {
                    //logger.debug((lineNumber++) + ": ", line);
                    if (line.StartsWith("frame:"))
                    {
                        //logger.debug("found new frame");
                        model = file.Builder.newChemModel();
                        crystal = file.Builder.newCrystal();

                        // assume the file format is correct

                        //logger.debug("reading spacegroup");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        crystal.SpaceGroup = line;

                        //logger.debug("reading unit cell axes");
                        Vector3d axis = new Vector3d();
                        //logger.debug("parsing A: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z = FortranFormat.atof(line);
                        crystal.A = axis;
                        axis = new Vector3d();
                        //logger.debug("parsing B: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z = FortranFormat.atof(line);
                        crystal.B = axis;
                        axis = new Vector3d();
                        //logger.debug("parsing C: ");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.x = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.y = FortranFormat.atof(line);
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        axis.z = FortranFormat.atof(line);
                        crystal.C = axis;
                        //logger.debug("Crystal: ", crystal);
                        a = crystal.A;
                        b = crystal.B;
                        c = crystal.C;

                        //logger.debug("Reading number of atoms");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        int atomsToRead = System.Int32.Parse(line);

                        //logger.debug("Reading no molecules in assym unit cell");
                        line = input.ReadLine();
                        //logger.debug((lineNumber++) + ": ", line);
                        int Z = System.Int32.Parse(line);
                        crystal.Z = Z;

                        System.String symbol;
                        double charge;
                        Point3d cart;
                        for (int i = 1; i <= atomsToRead; i++)
                        {
                            cart = new Point3d();
                            line = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            symbol = line.Substring(0, (line.IndexOf(":")) - (0));
                            charge = System.Double.Parse(line.Substring(line.IndexOf(":") + 1));
                            line = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.x = System.Double.Parse(line); // x
                            line = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.y = System.Double.Parse(line); // y
                            line = input.ReadLine();
                            //logger.debug((lineNumber++) + ": ", line);
                            cart.z = System.Double.Parse(line); // z
                            IAtom atom = file.Builder.newAtom(symbol);
                            atom.setCharge(charge);
                            // convert cartesian coords to fractional
                            Point3d frac = CrystalGeometryTools.cartesianToFractional(a, b, c, cart);
                            atom.setFractionalPoint3d(frac);
                            crystal.addAtom(atom);
                            //logger.debug("Added atom: ", atom);
                        }

                        model.Crystal = crystal;
                        seq.addChemModel(model);
                    }
                    else
                    {
                        //logger.debug("Format seems broken. Skipping these lines:");
                        while (!line.StartsWith("frame:") && input.Peek() != -1 && line != null)
                        {
                            line = input.ReadLine();
                            //logger.debug(lineNumber++ + ": ", line);
                        }
                        //logger.debug("Ok, resynched: found new frame");
                    }
                }
                file.addChemSequence(seq);
            }
            catch (System.Exception exception)
            {
                //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                System.String message = "Error while parsing CrystClust file: " + exception.Message;
                //logger.error(message);
                //logger.debug(exception);
                throw new CDKException(message, exception);
            }
            return file;
        }
Esempio n. 36
0
 public ChemRenderingSource3D(IChemFile file)
 {
     this.file = file;
     SourceModified();
 }
Esempio n. 37
0
 private IChemFile readChemFile(IChemFile chemFile)
 {
     IChemSequence sequence = readChemSequence(chemFile.Builder.newChemSequence());
     chemFile.addChemSequence(sequence);
     return chemFile;
 }
Esempio n. 38
0
 public CMLReactionModule(IChemFile chemFile)
     : base(chemFile)
 {
 }
 public ChemRenderingSource2D(IChemFile file)
 {
     this.file = file;
 }
Esempio n. 40
0
 /// <summary>
 /// Tests whether the file is indeed a single molecule file
 /// </summary>
 private IAtomContainer CheckForSingleMoleculeFile(IChemFile chemFile)
 {
     return(CheckForXMoleculeFile(chemFile, 1));
 }
Esempio n. 41
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. 42
0
        /// <summary>
        /// Read the Gaussian98 output.
        /// </summary>
        /// <param name="chemFile"></param>
        /// <returns>a ChemFile with the coordinates, energies, and vibrations.</returns>
        private IChemFile ReadChemFile(IChemFile chemFile)
        {
            IChemSequence sequence = chemFile.Builder.NewChemSequence();
            IChemModel    model    = null;
            string        line     = input.ReadLine();
            string        levelOfTheory;
            string        description;
            int           modelCounter = 0;

            // Find first set of coordinates by skipping all before "Standard orientation"
            while (line != null)
            {
                if (line.Contains("Standard orientation:"))
                {
                    // Found a set of coordinates
                    model = chemFile.Builder.NewChemModel();
                    ReadCoordinates(model);
                    break;
                }
                line = input.ReadLine();
            }
            if (model != null)
            {
                // Read all other data
                line = input.ReadLine().Trim();
                while (line != null)
                {
                    if (line.IndexOf('#') == 0)
                    {
                        // Found the route section
                        // Memorizing this for the description of the chemmodel
                        lastRoute    = line;
                        modelCounter = 0;
                    }
                    else if (line.Contains("Standard orientation:"))
                    {
                        // Found a set of coordinates
                        // Add current frame to file and create a new one.
                        if (!readOptimizedStructureOnly.IsSet)
                        {
                            sequence.Add(model);
                        }
                        else
                        {
                            Trace.TraceInformation("Skipping frame, because I was told to do");
                        }
                        FrameRead();
                        model = chemFile.Builder.NewChemModel();
                        modelCounter++;
                        ReadCoordinates(model);
                    }
                    else if (line.Contains("SCF Done:"))
                    {
                        // Found an energy
                        model.SetProperty(CDKPropertyName.Remark, line.Trim());
                    }
                    else if (line.Contains("Harmonic frequencies"))
                    {
                        // Found a set of vibrations
                        // ReadFrequencies(frame);
                    }
                    else if (line.Contains("Total atomic charges"))
                    {
                        ReadPartialCharges(model);
                    }
                    else if (line.Contains("Magnetic shielding"))
                    {
                        // Found NMR data
                        ReadNMRData(model, line);
                    }
                    else if (line.Contains("GINC"))
                    {
                        // Found calculation level of theory
                        levelOfTheory = ParseLevelOfTheory(line);
                        Debug.WriteLine($"Level of Theory for this model: {levelOfTheory}");
                        description = lastRoute + ", model no. " + modelCounter;
                        model.SetProperty(CDKPropertyName.Description, description);
                    }
                    else
                    {
                    }
                    line = input.ReadLine();
                }

                // Add last frame to file
                sequence.Add(model);
                FrameRead();
            }
            chemFile.Add(sequence);

            return(chemFile);
        }
 public static IChemModel[] getAllChemModels(IChemFile file)
 {
     IChemSequence[] sequences = file.ChemSequences;
     int modelCounter = 0;
     int counter = 0;
     IChemModel[] tempModels = null;
     for (int f = 0; f < sequences.Length; f++)
     {
         modelCounter += sequences[f].ChemModelCount;
     }
     IChemModel[] models = new IChemModel[modelCounter];
     for (int f = 0; f < sequences.Length; f++)
     {
         tempModels = sequences[f].ChemModels;
         for (int g = 0; g < tempModels.Length; g++)
         {
             models[counter] = tempModels[g];
             counter++;
         }
     }
     return models;
 }
Esempio n. 44
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. 45
0
        /// <summary>
        ///  Private method that actually parses the input to read a ChemFile
        ///  object.
        ///
        ///  Each PMP frame is stored as a Crystal in a ChemModel. The PMP
        ///  file is stored as a ChemSequence of ChemModels.
        /// </summary>
        /// <returns>A ChemFile containing the data parsed from input.</returns>
        private IChemFile ReadChemFile(IChemFile chemFile)
        {
            IChemSequence chemSequence;
            IChemModel    chemModel;
            ICrystal      crystal;

            try
            {
                string line = ReadLine();
                while (line != null)
                {
                    if (line.StartsWith("%%Header Start", StringComparison.Ordinal))
                    {
                        // parse Header section
                        while (line != null && !(line.StartsWith("%%Header End", StringComparison.Ordinal)))
                        {
                            if (line.StartsWith("%%Version Number", StringComparison.Ordinal))
                            {
                                string version = ReadLine().Trim();
                                if (!string.Equals(version, "3.00", StringComparison.Ordinal))
                                {
                                    Trace.TraceError("The PMPReader only supports PMP files with version 3.00");
                                    return(null);
                                }
                            }
                            line = ReadLine();
                        }
                    }
                    else if (line.StartsWith("%%Model Start", StringComparison.Ordinal))
                    {
                        // parse Model section
                        modelStructure = chemFile.Builder.NewAtomContainer();
                        while (line != null && !(line.StartsWith("%%Model End", StringComparison.Ordinal)))
                        {
                            var objHeaderMatcher = objHeader.Match(line);
                            if (objHeaderMatcher.Success)
                            {
                                var obj = objHeaderMatcher.Groups[2].Value;
                                ConstructObject(chemFile.Builder, obj);
                                var id = int.Parse(objHeaderMatcher.Groups[1].Value, NumberFormatInfo.InvariantInfo);
                                // Debug.WriteLine(object + " id: " + id);
                                line = ReadLine();
                                while (line != null && !(string.Equals(line.Trim(), ")", StringComparison.Ordinal)))
                                {
                                    // parse object command (or new object header)
                                    var objCommandMatcher = objCommand.Match(line);
                                    objHeaderMatcher = objHeader.Match(line);
                                    if (objHeaderMatcher.Success)
                                    {
                                        // ok, forget about nesting and hope for the best
                                        obj = objHeaderMatcher.Groups[2].Value;
                                        id  = int.Parse(objHeaderMatcher.Groups[1].Value, NumberFormatInfo.InvariantInfo);
                                        ConstructObject(chemFile.Builder, obj);
                                    }
                                    else if (objCommandMatcher.Success)
                                    {
                                        var format  = objCommandMatcher.Groups[1].Value;
                                        var command = objCommandMatcher.Groups[2].Value;
                                        var field   = objCommandMatcher.Groups[3].Value;

                                        ProcessModelCommand(obj, command, format, field);
                                    }
                                    else
                                    {
                                        Trace.TraceWarning("Skipping line: " + line);
                                    }
                                    line = ReadLine();
                                }
                                if (chemObject is IAtom)
                                {
                                    atomids[id] = modelStructure.Atoms.Count;
                                    atomGivenIds[int.Parse(chemObject.GetProperty <string>(PMP_ID), NumberFormatInfo.InvariantInfo)] = id;
                                    modelStructure.Atoms.Add((IAtom)chemObject);
                                }
                                else if (chemObject is IBond)
                                {
                                    // ignored: bonds may be defined before their
                                    // atoms so their handling is deferred until the
                                    // end of the model
                                }
                                else
                                {
                                    Trace.TraceError("chemObject is not initialized or of bad class type");
                                }
                            }
                            line = ReadLine();
                        }
                        Trace.Assert(line != null);
                        if (line.StartsWith("%%Model End", StringComparison.Ordinal))
                        {
                            // during the Model Start, all bonds are cached as PMP files might
                            // define bonds *before* the involved atoms :(
                            // the next lines dump the cache into the atom container

                            int bondsFound = bondids.Count;
                            Debug.WriteLine($"Found #bonds: {bondsFound}");
                            Debug.WriteLine($"#atom ones: {bondAtomOnes.Count}");
                            Debug.WriteLine($"#atom twos: {bondAtomTwos.Count}");
                            Debug.WriteLine($"#orders: {bondOrders.Count}");
                            foreach (var index in bondids.Keys)
                            {
                                if (!bondOrders.TryGetValue(index, out double order))
                                {
                                    order = 1;
                                }
                                Debug.WriteLine($"index: {index}");
                                Debug.WriteLine($"ones: {bondAtomOnes[index]}");
                                var atom1 = modelStructure.Atoms[atomids[bondAtomOnes[index]]];
                                var atom2 = modelStructure.Atoms[atomids[bondAtomTwos[index]]];
                                var bond  = modelStructure.Builder.NewBond(atom1, atom2);
                                if (order == 1.0)
                                {
                                    bond.Order = BondOrder.Single;
                                }
                                else if (order == 2.0)
                                {
                                    bond.Order = BondOrder.Double;
                                }
                                else if (order == 3.0)
                                {
                                    bond.Order = BondOrder.Triple;
                                }
                                else if (order == 4.0)
                                {
                                    bond.Order = BondOrder.Quadruple;
                                }
                                modelStructure.Bonds.Add(bond);
                            }
                        }
                    }
                    else if (line.StartsWith("%%Traj Start", StringComparison.Ordinal))
                    {
                        chemSequence = chemFile.Builder.NewChemSequence();
                        double energyFragment = 0.0;
                        double energyTotal    = 0.0;
                        int    Z = 1;
                        while (line != null && !(line.StartsWith("%%Traj End", StringComparison.Ordinal)))
                        {
                            if (line.StartsWith("%%Start Frame", StringComparison.Ordinal))
                            {
                                chemModel = chemFile.Builder.NewChemModel();
                                crystal   = chemFile.Builder.NewCrystal();
                                while (line != null && !(line.StartsWith("%%End Frame", StringComparison.Ordinal)))
                                {
                                    // process frame data
                                    if (line.StartsWith("%%Atom Coords", StringComparison.Ordinal))
                                    {
                                        // calculate Z: as it is not explicitely given, try to derive it from the
                                        // energy per fragment and the total energy
                                        if (energyFragment != 0.0 && energyTotal != 0.0)
                                        {
                                            Z = (int)Math.Round(energyTotal / energyFragment);
                                            Debug.WriteLine($"Z derived from energies: {Z}");
                                        }
                                        // add atomC as atoms to crystal
                                        int expatoms = modelStructure.Atoms.Count;
                                        for (int molCount = 1; molCount <= Z; molCount++)
                                        {
                                            IAtomContainer clone = modelStructure.Builder.NewAtomContainer();
                                            for (int i = 0; i < expatoms; i++)
                                            {
                                                line = ReadLine();
                                                IAtom a  = clone.Builder.NewAtom();
                                                var   st = Strings.Tokenize(line, ' ');
                                                a.Point3D        = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo));
                                                a.CovalentRadius = 0.6;
                                                IAtom modelAtom = modelStructure.Atoms[atomids[atomGivenIds[i + 1]]];
                                                a.Symbol = modelAtom.Symbol;
                                                clone.Atoms.Add(a);
                                            }
                                            rebonder.Rebond(clone);
                                            crystal.Add(clone);
                                        }
                                    }
                                    else if (line.StartsWith("%%E/Frag", StringComparison.Ordinal))
                                    {
                                        line           = ReadLine().Trim();
                                        energyFragment = double.Parse(line, NumberFormatInfo.InvariantInfo);
                                    }
                                    else if (line.StartsWith("%%Tot E", StringComparison.Ordinal))
                                    {
                                        line        = ReadLine().Trim();
                                        energyTotal = double.Parse(line, NumberFormatInfo.InvariantInfo);
                                    }
                                    else if (line.StartsWith("%%Lat Vects", StringComparison.Ordinal))
                                    {
                                        line = ReadLine();
                                        IList <string> st;
                                        st        = Strings.Tokenize(line, ' ');
                                        crystal.A = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo));
                                        line      = ReadLine();
                                        st        = Strings.Tokenize(line, ' ');
                                        crystal.B = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo));
                                        line      = ReadLine();
                                        st        = Strings.Tokenize(line, ' ');
                                        crystal.C = new Vector3(double.Parse(st[0], NumberFormatInfo.InvariantInfo), double.Parse(st[1], NumberFormatInfo.InvariantInfo), double.Parse(st[2], NumberFormatInfo.InvariantInfo));
                                    }
                                    else if (line.StartsWith("%%Space Group", StringComparison.Ordinal))
                                    {
                                        line = ReadLine().Trim();

                                        // standardize space group name. See Crystal.SetSpaceGroup()
                                        if (string.Equals("P 21 21 21 (1)", line, StringComparison.Ordinal))
                                        {
                                            crystal.SpaceGroup = "P 2_1 2_1 2_1";
                                        }
                                        else
                                        {
                                            crystal.SpaceGroup = "P1";
                                        }
                                    }
                                    line = ReadLine();
                                }
                                chemModel.Crystal = crystal;
                                chemSequence.Add(chemModel);
                            }
                            line = ReadLine();
                        }
                        chemFile.Add(chemSequence);
                    }
                    // else disregard line

                    // read next line
                    line = ReadLine();
                }
            }
            catch (IOException e)
            {
                Trace.TraceError($"An IOException happened: {e.Message}");
                Debug.WriteLine(e);
                chemFile = null;
            }
            catch (CDKException e)
            {
                Trace.TraceError($"An CDKException happened: {e.Message}");
                Debug.WriteLine(e);
                chemFile = null;
            }

            return(chemFile);
        }
Esempio n. 46
0
        private IChemFile ReadChemFile(IChemFile chemFile)
        {
            var chemSequence = chemFile.Builder.NewChemSequence();

            var chemModel      = chemFile.Builder.NewChemModel();
            var setOfMolecules = chemFile.Builder.NewAtomContainerSet();
            var m = ReadMolecule(chemFile.Builder.NewAtomContainer());

            if (m != null)
            {
                setOfMolecules.Add(m);
            }
            chemModel.MoleculeSet = setOfMolecules;
            chemSequence.Add(chemModel);
            setOfMolecules = chemFile.Builder.NewAtomContainerSet();
            chemModel      = chemFile.Builder.NewChemModel();
            try
            {
                firstLineisMolecule = true;
                while (m != null)
                {
                    m = ReadMolecule(chemFile.Builder.NewAtomContainer());
                    if (m != null)
                    {
                        setOfMolecules.Add(m);
                        chemModel.MoleculeSet = setOfMolecules;
                        chemSequence.Add(chemModel);
                        setOfMolecules = chemFile.Builder.NewAtomContainerSet();
                        chemModel      = chemFile.Builder.NewChemModel();
                    }
                }
            }
            catch (CDKException)
            {
                throw;
            }
            catch (ArgumentException exception)
            {
                var error = "Error while parsing MOL2";
                Trace.TraceError(error);
                Debug.WriteLine(exception);
                throw new CDKException(error, exception);
            }
            try
            {
                input.Close();
            }
            catch (Exception exc)
            {
                var error = "Error while closing file: " + exc.Message;
                Trace.TraceError(error);
                throw new CDKException(error, exc);
            }

            chemFile.Add(chemSequence);

            // reset it to false so that other read methods called later do not get confused
            firstLineisMolecule = false;

            return(chemFile);
        }
Esempio n. 47
0
 public virtual void createIDs(IChemFile file)
 {
     IChemSequence[] sequences = file.ChemSequences;
     for (int i = 0; i < sequences.Length; i++)
     {
         createIDs(sequences[i]);
     }
 }
Esempio n. 48
0
 public CTXReader(TextReader input)
 {
     this.input = input;
     file       = null;
 }