예제 #1
0
        public virtual void TestGetChemModelCount()
        {
            IChemSequence cs = (IChemSequence)NewChemObject();

            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            Assert.AreEqual(3, cs.Count);
        }
예제 #2
0
        public virtual void TestRemoveChemModel_int()
        {
            IChemSequence cs = (IChemSequence)NewChemObject();

            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            Assert.AreEqual(3, cs.Count);
            cs.RemoveAt(1);
            Assert.AreEqual(2, cs.Count);
        }
예제 #3
0
        public virtual void TestGetChemModel_int()
        {
            IChemSequence cs = (IChemSequence)NewChemObject();

            cs.Add(cs.Builder.NewChemModel());
            IChemModel second = cs.Builder.NewChemModel();

            cs.Add(second);
            cs.Add(cs.Builder.NewChemModel());

            Assert.AreEqual(second, cs[1]);
        }
예제 #4
0
 /// <summary>
 /// Takes an object which subclasses IChemObject, e.g.Molecule, and will read
 /// this (from file, database, Internet etc). If the specific implementation
 /// does not support a specific IChemObject it will throw an Exception.
 /// </summary>
 /// <param name="obj">The object that subclasses <see cref="IChemObject"/></param>
 /// <returns>The <see cref="IChemObject"/> read</returns>
 /// <exception cref="CDKException"></exception>
 public override T Read <T>(T obj)
 {
     if (obj is IReaction)
     {
         return((T)ReadReaction(obj.Builder));
     }
     else if (obj is IReactionSet)
     {
         IReactionSet reactionSet = obj.Builder.NewReactionSet();
         reactionSet.Add(ReadReaction(obj.Builder));
         return((T)reactionSet);
     }
     else if (obj is IChemModel)
     {
         IChemModel   model       = obj.Builder.NewChemModel();
         IReactionSet reactionSet = obj.Builder.NewReactionSet();
         reactionSet.Add(ReadReaction(obj.Builder));
         model.ReactionSet = reactionSet;
         return((T)model);
     }
     else if (obj is IChemFile)
     {
         IChemFile     chemFile = obj.Builder.NewChemFile();
         IChemSequence sequence = obj.Builder.NewChemSequence();
         sequence.Add((IChemModel)Read(obj.Builder.NewChemModel()));
         chemFile.Add(sequence);
         return((T)chemFile);
     }
     else
     {
         throw new CDKException($"Only supported are Reaction and ChemModel, and not {obj.GetType().Name}.");
     }
 }
예제 #5
0
 public void SetUp()
 {
     molecule1  = builder.NewAtomContainer();
     atomInMol1 = builder.NewAtom("Cl");
     molecule1.Atoms.Add(atomInMol1);
     molecule1.Atoms.Add(builder.NewAtom("Cl"));
     bondInMol1 = builder.NewBond(atomInMol1, molecule1.Atoms[1]);
     molecule1.Bonds.Add(bondInMol1);
     molecule2  = builder.NewAtomContainer();
     atomInMol2 = builder.NewAtom("O");
     atomInMol2.ImplicitHydrogenCount = 2;
     molecule2.Atoms.Add(atomInMol2);
     moleculeSet = builder.NewChemObjectSet <IAtomContainer>();
     moleculeSet.Add(molecule1);
     moleculeSet.Add(molecule2);
     reaction = builder.NewReaction();
     reaction.Reactants.Add(molecule1);
     reaction.Products.Add(molecule2);
     reactionSet = builder.NewReactionSet();
     reactionSet.Add(reaction);
     chemModel             = builder.NewChemModel();
     chemModel.MoleculeSet = moleculeSet;
     chemModel.ReactionSet = reactionSet;
     chemSequence1         = builder.NewChemSequence();
     chemSequence1.Add(chemModel);
     chemSequence2 = builder.NewChemSequence();
     chemFile      = builder.NewChemFile();
     chemFile.Add(chemSequence1);
     chemFile.Add(chemSequence2);
 }
예제 #6
0
        public override void TestStateChanged_IChemObjectChangeEvent()
        {
            ChemObjectListenerImpl listener   = new ChemObjectListenerImpl();
            IChemSequence          chemObject = (IChemSequence)NewChemObject();

            chemObject.Listeners.Add(listener);

            chemObject.Add(chemObject.Builder.NewChemModel());
            Assert.IsTrue(listener.Changed);
        }
예제 #7
0
        /// <summary>
        /// Read a ChemFile from a file in MDL RDF format.
        /// </summary>
        /// <param name="chemFile">The IChemFile</param>
        /// <returns>The IChemFile that was read from the RDF file.</returns>
        private IChemFile ReadChemFile(IChemFile chemFile)
        {
            IChemSequence chemSequence = chemFile.Builder.NewChemSequence();

            IChemModel chemModel = chemFile.Builder.NewChemModel();

            chemSequence.Add(ReadChemModel(chemModel));
            chemFile.Add(chemSequence);
            return(chemFile);
        }
예제 #8
0
        public virtual void TestChemModels()
        {
            IChemSequence cs = (IChemSequence)NewChemObject();

            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());

            Assert.AreEqual(3, cs.Count);
            IEnumerator <IChemModel> models = cs.GetEnumerator();
            int count = 0;

            while (models.MoveNext())
            {
                Assert.IsNotNull(models.Current);
                ++count;
            }
            Assert.AreEqual(3, count);
        }
예제 #9
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();
            ICrystal      crystal = ReadCrystal(file.Builder.NewCrystal());

            model.Crystal = crystal;
            seq.Add(model);
            file.Add(seq);
            return(file);
        }
예제 #10
0
        public virtual void TestClone_IChemModel()
        {
            IChemSequence sequence = (IChemSequence)NewChemObject();

            sequence.Add(sequence.Builder.NewChemModel()); // 1
            sequence.Add(sequence.Builder.NewChemModel()); // 2
            sequence.Add(sequence.Builder.NewChemModel()); // 3
            sequence.Add(sequence.Builder.NewChemModel()); // 4

            IChemSequence clone = (IChemSequence)sequence.Clone();

            Assert.AreEqual(sequence.Count, clone.Count);
            for (int f = 0; f < sequence.Count; f++)
            {
                for (int g = 0; g < clone.Count; g++)
                {
                    Assert.IsNotNull(sequence[f]);
                    Assert.IsNotNull(clone[g]);
                    Assert.AreNotSame(sequence[f], clone[g]);
                }
            }
        }
예제 #11
0
        public override void EndElement(XElement element)
        {
            Debug.WriteLine($"end element: {element.ToString()}");
            switch (element.Name.LocalName)
            {
            case "identifier":
                if (tautomer != null)
                {
                    // ok, add tautomer
                    setOfMolecules.Add(tautomer);
                    chemModel.MoleculeSet = setOfMolecules;
                    chemSequence.Add(chemModel);
                }
                break;

            case "formula":
                if (tautomer != null)
                {
                    Trace.TraceInformation("Parsing <formula> chars: ", element.Value);
                    tautomer = CDK.Builder.NewAtomContainer(InChIContentProcessorTool.ProcessFormula(
                                                                setOfMolecules.Builder.NewAtomContainer(), element.Value));
                }
                else
                {
                    Trace.TraceWarning("Cannot set atom info for empty tautomer");
                }
                break;

            case "connections":
                if (tautomer != null)
                {
                    Trace.TraceInformation("Parsing <connections> chars: ", element.Value);
                    InChIContentProcessorTool.ProcessConnections(element.Value, tautomer, -1);
                }
                else
                {
                    Trace.TraceWarning("Cannot set dbond info for empty tautomer");
                }
                break;

            default:
                // skip all other elements
                break;
            }
        }
예제 #12
0
 public override T Read <T>(T obj)
 {
     if (obj is IChemModel)
     {
         return((T)ReadChemModel((IChemModel)obj));
     }
     else if (obj is IChemFile)
     {
         IChemSequence sequence = obj.Builder.NewChemSequence();
         sequence.Add((IChemModel)this.ReadChemModel(obj.Builder.NewChemModel()));
         ((IChemFile)obj).Add(sequence);
         return(obj);
     }
     else
     {
         throw new CDKException("Only supported is ChemModel.");
     }
 }
예제 #13
0
        public virtual void TestGrowChemModelArray()
        {
            IChemSequence cs = (IChemSequence)NewChemObject();

            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            Assert.AreEqual(3, cs.Count);
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel());
            cs.Add(cs.Builder.NewChemModel()); // this one should enfore array grow
            Assert.AreEqual(6, cs.Count);
        }
예제 #14
0
 public override void EndElement(XElement element)
 {
     Debug.WriteLine($"end element: {element.ToString()}");
     if (string.Equals("identifier", element.Name.LocalName, StringComparison.Ordinal))
     {
         if (tautomer != null)
         {
             // ok, add tautomer
             setOfMolecules.Add(tautomer);
             chemModel.MoleculeSet = setOfMolecules;
             chemSequence.Add(chemModel);
         }
     }
     else if (string.Equals("formula", element.Name.LocalName, StringComparison.Ordinal))
     {
         if (tautomer != null)
         {
             Trace.TraceInformation("Parsing <formula> chars: ", element.Value);
             tautomer = builder.NewAtomContainer(
                 InChIContentProcessorTool.ProcessFormula(setOfMolecules.Builder.NewAtomContainer(), element.Value));
         }
         else
         {
             Trace.TraceWarning("Cannot set atom info for empty tautomer");
         }
     }
     else if (string.Equals("connections", element.Name.LocalName, StringComparison.Ordinal))
     {
         if (tautomer != null)
         {
             Trace.TraceInformation("Parsing <connections> chars: ", element.Value);
             InChIContentProcessorTool.ProcessConnections(element.Value, tautomer, -1);
         }
         else
         {
             Trace.TraceWarning("Cannot set dbond info for empty tautomer");
         }
     }
     else
     {
         // skip all other elements
     }
 }
예제 #15
0
 /// <summary>
 /// Writes a <see cref="IChemObject"/> to the MDL SD file formated output. It can only
 /// output <see cref="IChemObject"/> of type <see cref="IChemFile"/>, <see cref="IAtomContainerSet"/>
 /// and <see cref="IAtomContainerSet"/>.
 /// </summary>
 /// <param name="obj">an acceptable <see cref="IChemObject"/></param>
 /// <seealso cref="Accepts(Type)"/>
 public override void Write(IChemObject obj)
 {
     try
     {
         if (obj is IEnumerableChemObject <IAtomContainer> )
         {
             WriteMoleculeSet((IEnumerableChemObject <IAtomContainer>)obj);
             return;
         }
         else if (obj is IChemFile)
         {
             WriteChemFile((IChemFile)obj);
             return;
         }
         else if (obj is IChemModel)
         {
             IChemFile     file     = obj.Builder.NewChemFile();
             IChemSequence sequence = obj.Builder.NewChemSequence();
             sequence.Add((IChemModel)obj);
             file.Add(sequence);
             WriteChemFile((IChemFile)file);
             return;
         }
         else if (obj is IAtomContainer)
         {
             WriteMolecule((IAtomContainer)obj);
             return;
         }
     }
     catch (Exception ex)
     {
         Trace.TraceError(ex.Message);
         Debug.WriteLine(ex);
         throw new CDKException("Exception while writing MDL file: " + ex.Message, ex);
     }
     throw new CDKException(
               "Only supported is writing of ChemFile, MoleculeSet, AtomContainer and Molecule objects.");
 }
예제 #16
0
 /// <summary>
 /// Read a <see cref="IChemObjectSet{T}"/> from the input source.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="obj">object an <see cref="IChemObjectSet{T}"/> into which the data is stored.</param>
 /// <returns>the content in a <see cref="IChemObjectSet{T}"/> object</returns>
 public override T Read <T>(T obj)
 {
     if (obj is IChemObjectSet <IAtomContainer> cf)
     {
         try
         {
             cf = ReadAtomContainerSet(cf);
         }
         catch (IOException)
         {
             Trace.TraceError("Input/Output error while reading from input.");
         }
         return((T)cf);
     }
     else if (obj is IChemFile chemFile)
     {
         IChemSequence chemSeq   = obj.Builder.NewChemSequence();
         IChemModel    chemModel = obj.Builder.NewChemModel();
         IChemObjectSet <IAtomContainer> molSet = obj.Builder.NewAtomContainerSet();
         try
         {
             molSet = ReadAtomContainerSet(molSet);
         }
         catch (IOException)
         {
             Trace.TraceError("Input/Output error while reading from input.");
         }
         chemModel.MoleculeSet = molSet;
         chemSeq.Add(chemModel);
         chemFile.Add(chemSeq);
         return((T)chemFile);
     }
     else
     {
         throw new CDKException("Only supported is reading of IAtomContainerSet.");
     }
 }
예제 #17
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>
        /// <exception cref="IOException">may be thrown buy the <c>this.input.ReadLine()</c> instruction.</exception>
        /// <seealso cref="GamessReader.input"/>
        //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 ?
            var           moleculeSet = file.Builder.NewAtomContainerSet();

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

            string currentReadLine = this.input.ReadLine();

            while (currentReadLine != null)
            {
                // There are 2 types of coordinate sets: - bohr coordinates sets (if statement) - angstr???m coordinates sets (else statement)
                if (currentReadLine.Contains("COORDINATES (BOHR)"))
                {
                    // The following line do no contain data, so it is ignored.
                    this.input.ReadLine();
                    moleculeSet.Add(this.ReadCoordinates(file.Builder.NewAtomContainer(),
                                                         GamessReader.BohrUnit));
                    //break; //<- stops when the first set of coordinates is found.
                }
                else if (currentReadLine.Contains(" COORDINATES OF ALL ATOMS ARE (ANGS)"))
                {
                    // The following 2 lines do no contain data, so it are ignored.
                    this.input.ReadLine();
                    this.input.ReadLine();

                    moleculeSet.Add(this.ReadCoordinates(file.Builder.NewAtomContainer(),
                                                         GamessReader.AngstromUnit));
                    //break; //<- stops when the first set of coordinates is found.
                }
                currentReadLine = this.input.ReadLine();
            }
            return(file);
        }
예제 #18
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();
            IChemObjectSet <IAtomContainer> setOfMolecules = chemFile.Builder.NewAtomContainerSet();
            IAtomContainer 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();
            string str;

            try
            {
                string line;
                while ((line = input.ReadLine()) != null)
                {
                    Debug.WriteLine($"line: {line}");
                    // apparently, this is a SDF file, continue with
                    // reading mol files
                    str = line;
                    if (string.Equals(line, "M  END", StringComparison.Ordinal))
                    {
                        continue;
                    }
                    if (string.Equals(str, "$$$$", StringComparison.Ordinal))
                    {
                        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();
                        }
                    }
                    else
                    {
                        // here the stuff between 'M  END' and '$$$$'
                        if (m != null)
                        {
                            // ok, the first lines should start with '>'
                            string fieldName = null;
                            if (str.StartsWith("> ", StringComparison.Ordinal))
                            {
                                // ok, should extract the field name
                                int index = str.IndexOf('<', 2);
                                if (index != -1)
                                {
                                    int index2 = str.Substring(index).IndexOf('>');
                                    if (index2 != -1)
                                    {
                                        fieldName = str.Substring(index + 1, index2 - 1);
                                    }
                                }
                                // end skip all other lines
                                while ((line = input.ReadLine()) != null && line.StartsWithChar('>'))
                                {
                                    Debug.WriteLine($"data header line: {line}");
                                }
                            }
                            if (line == null)
                            {
                                throw new CDKException("Expecting data line here, but found null!");
                            }
                            string data = line;
                            while ((line = input.ReadLine()) != null && line.Trim().Length > 0)
                            {
                                if (string.Equals(line, "$$$$", StringComparison.Ordinal))
                                {
                                    Trace.TraceError($"Expecting data line here, but found end of molecule: {line}");
                                    break;
                                }
                                Debug.WriteLine($"data line: {line}");
                                data += line;
                                // preserve newlines, unless the line is exactly 80 chars; in that case it
                                // is assumed to continue on the next line. See MDL documentation.
                                if (line.Length < 80)
                                {
                                    data += "\n";
                                }
                            }
                            if (fieldName != null)
                            {
                                Trace.TraceInformation($"fieldName, data: {fieldName}, {data}");
                                m.SetProperty(fieldName, data);
                            }
                        }
                    }
                }
            }
            catch (CDKException)
            {
                throw;
            }
            catch (Exception exception)
            {
                if (!(exception is IOException || exception is ArgumentException))
                {
                    throw;
                }
                string error = "Error while parsing SDF";
                Trace.TraceError(error);
                Debug.WriteLine(exception);
                throw new CDKException(error, exception);
            }
            try
            {
                input.Close();
            }
            catch (Exception exc)
            {
                string error = "Error while closing file: " + exc.Message;
                Trace.TraceError(error);
                throw new CDKException(error, exc);
            }

            chemFile.Add(chemSequence);
            return(chemFile);
        }
예제 #19
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);
        }
예제 #20
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 != null && line.StartsWithChar(';'))
                        {
                            Debug.WriteLine("Skipping block content");
                            line = input.ReadLine();
                            if (line != null)
                            {
                                line = line.Trim();
                            }
                            while ((line = input.ReadLine()) != null &&
                                   !line.StartsWith(";"))
                            {
                                Debug.WriteLine($"Skipping block line: {line}");
                            }
                        }
                    }
                }
                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);
        }
예제 #21
0
        private IChemSequence ReadChemSequence(IChemSequence sequence)
        {
            IChemModel chemModel = sequence.Builder.NewChemModel();
            ICrystal   crystal   = null;

            string buf = inputBuffer.ReadToEnd();

            inputBuffer = new StringReader(buf);

            // Get the info line (first token of the first line)
            info = NextVASPToken(false);
            //Debug.WriteLine(info);
            inputBuffer = new StringReader(buf);

            // Get the number of different atom "NCLASS=X"
            NextVASPTokenFollowing("NCLASS");
            ntype = int.Parse(fieldVal, NumberFormatInfo.InvariantInfo);
            //Debug.WriteLine($"NCLASS= {ntype}");
            inputBuffer = new StringReader(buf);

            // Get the different atom names
            anames = new string[ntype];

            NextVASPTokenFollowing("ATOM");
            for (int i = 0; i < ntype; i++)
            {
                anames[i] = fieldVal;
                NextVASPToken(false);
            }

            // Get the number of atom of each type
            int[] natom_type = new int[ntype];
            natom = 0;
            for (int i = 0; i < ntype; i++)
            {
                natom_type[i] = int.Parse(fieldVal, NumberFormatInfo.InvariantInfo);
                NextVASPToken(false);
                natom = natom + natom_type[i];
            }

            // Get the representation type of the primitive vectors
            // only "Direct" is recognize now.
            representation = fieldVal;
            if (string.Equals(representation, "Direct", StringComparison.Ordinal))
            {
                Trace.TraceInformation("Direct representation");
                // DO NOTHING
            }
            else
            {
                throw new CDKException("This VASP file is not supported. Please contact the Jmol developpers");
            }

            while (NextVASPToken(false) != null)
            {
                Debug.WriteLine("New crystal started...");

                crystal   = sequence.Builder.NewCrystal();
                chemModel = sequence.Builder.NewChemModel();

                // Get acell
                for (int i = 0; i < 3; i++)
                {
                    // TODO: supoort FORTRA format
                    acell[i] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo); //all the same FIX?
                }

                // Get primitive vectors
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        NextVASPToken(false);
                        // TODO: supoort FORTRA format
                        rprim[i][j] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo);
                    }
                }

                // Get atomic position
                var atomType  = new int[natom];
                var xred      = Arrays.CreateJagged <double>(natom, 3);
                int atomIndex = 0;

                for (int i = 0; i < ntype; i++)
                {
                    for (int j = 0; j < natom_type[i]; j++)
                    {
                        try
                        {
                            atomType[atomIndex] = CDK.IsotopeFactory.GetElement(anames[i]).AtomicNumber;
                        }
                        catch (Exception exception)
                        {
                            throw new CDKException("Could not determine atomic number!", exception);
                        }
                        Debug.WriteLine($"aname: {anames[i]}");
                        Debug.WriteLine($"atomType: {atomType[atomIndex]}");

                        NextVASPToken(false);
                        xred[atomIndex][0] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo);
                        NextVASPToken(false);
                        xred[atomIndex][1] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo);
                        NextVASPToken(false);
                        xred[atomIndex][2] = double.Parse(fieldVal, NumberFormatInfo.InvariantInfo);

                        atomIndex = atomIndex + 1;
                        // FIXME: store atom
                    }
                }

                crystal.A = new Vector3(rprim[0][0] * acell[0], rprim[0][1] * acell[0], rprim[0][2] * acell[0]);
                crystal.B = new Vector3(rprim[1][0] * acell[1], rprim[1][1] * acell[1], rprim[1][2] * acell[1]);
                crystal.C = new Vector3(rprim[2][0] * acell[2], rprim[2][1] * acell[2], rprim[2][2] * acell[2]);
                for (int i = 0; i < atomType.Length; i++)
                {
                    string symbol = "Du";
                    try
                    {
                        symbol = CDK.IsotopeFactory.GetElement(atomType[i]).Symbol;
                    }
                    catch (Exception exception)
                    {
                        throw new CDKException("Could not determine element symbol!", exception);
                    }
                    var atom = sequence.Builder.NewAtom(symbol);
                    atom.AtomicNumber = atomType[i];
                    // convert fractional to cartesian
                    var frac = new double[3];
                    frac[0] = xred[i][0];
                    frac[1] = xred[i][1];
                    frac[2] = xred[i][2];
                    atom.FractionalPoint3D = new Vector3(frac[0], frac[1], frac[2]);
                    crystal.Atoms.Add(atom);
                }
                crystal.SetProperty(CDKPropertyName.Remark, info);
                chemModel.Crystal = crystal;

                Trace.TraceInformation("New Frame set!");

                sequence.Add(chemModel);
            } //end while

            return(sequence);
        }
예제 #22
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 = chemFile.Builder.NewChemSequence();
            IChemModel    chemModel    = chemFile.Builder.NewChemModel();
            ICrystal      crystal      = chemFile.Builder.NewCrystal();

            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)
                            {
                                string obj = objHeaderMatcher.Groups[2].Value;
                                ConstructObject(chemFile.Builder, obj);
                                int 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)
                                    {
                                        string format  = objCommandMatcher.Groups[1].Value;
                                        string command = objCommandMatcher.Groups[2].Value;
                                        string 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;
                                    atomZOrders[int.Parse(chemObject.GetProperty <string>(PMP_ZORDER), NumberFormatInfo.InvariantInfo)] = id;
                                    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();
                        }
                        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]}");
                                IAtom atom1 = modelStructure.Atoms[atomids[bondAtomOnes[index]]];
                                IAtom atom2 = modelStructure.Atoms[atomids[bondAtomTwos[index]]];
                                IBond 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";
                                        }
                                    }
                                    else
                                    {
                                    }
                                    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);
        }
예제 #23
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);
        }
예제 #24
0
        private IChemSequence ReadChemSequence(IChemSequence sequence)
        {
            IChemModel model = null;

            try
            {
                string line = input.ReadLine();

                // Find first set of coordinates
                while (line != null)
                {
                    if (line.Contains("Standard orientation:"))
                    {
                        // Found a set of coordinates
                        model = sequence.Builder.NewChemModel();
                        try
                        {
                            ReadCoordinates(model);
                        }
                        catch (IOException exception)
                        {
                            throw new CDKException("Error while reading coordinates: " + exception.ToString(), exception);
                        }
                        break;
                    }
                    line = input.ReadLine();
                }
                if (model != null)
                {
                    // Read all other data
                    line = input.ReadLine();
                    while (line != null)
                    {
                        if (line.Contains("Standard orientation:"))
                        {
                            // Found a set of coordinates
                            // Add current frame to file and create a new one.
                            sequence.Add(model);
                            FrameRead();
                            model = sequence.Builder.NewChemModel();
                            ReadCoordinates(model);
                        }
                        else if (line.Contains("SCF Done:"))
                        {
                            // Found an energy
                            model.SetProperty("NCDK.IO.Gaussian03Reaer:SCF Done", line.Trim());
                        }
                        else if (line.Contains("Harmonic frequencies"))
                        {
                            // Found a set of vibrations
                        }
                        else if (line.Contains("Mulliken atomic charges"))
                        {
                            ReadPartialCharges(model);
                        }
                        else if (line.Contains("Magnetic shielding"))
                        {
                            // Found NMR data
                        }
                        else if (line.Contains("GINC"))
                        {
                            // Found calculation level of theory
                            // FIXME: is doing anything with it?
                        }
                        line = input.ReadLine();
                    }

                    // Add current frame to file
                    sequence.Add(model);
                    FrameRead();
                }
            }
            catch (IOException exception)
            {
                throw new CDKException("Error while reading general structure: " + exception.ToString(), exception);
            }
            return(sequence);
        }
예제 #25
0
        private IChemFile ReadChemFile()
        {
            IChemSequence  seq          = file.Builder.NewChemSequence();
            IChemModel     model        = file.Builder.NewChemModel();
            var            containerSet = file.Builder.NewAtomContainerSet();
            IAtomContainer container    = file.Builder.NewAtomContainer();

            int lineNumber = 0;

            try
            {
                string line = input.ReadLine();
                while (line != null)
                {
                    Debug.WriteLine((lineNumber++) + ": ", line);
                    string command = null;
                    if (IsCommand(line))
                    {
                        command = GetCommand(line);
                        int lineCount = GetContentLinesCount(line);
                        if (string.Equals("ATOMS", command, StringComparison.Ordinal))
                        {
                            ProcessAtomsBlock(lineCount, container);
                        }
                        else if (string.Equals("BONDS", command, StringComparison.Ordinal))
                        {
                            ProcessBondsBlock(lineCount, container);
                        }
                        else if (string.Equals("IDENT", command, StringComparison.Ordinal))
                        {
                            ProcessIdentBlock(lineCount, container);
                        }
                        else if (string.Equals("NAME", command, StringComparison.Ordinal))
                        {
                            ProcessNameBlock(lineCount, container);
                        }
                        else
                        {
                            // skip lines
                            Trace.TraceWarning("Dropping block: ", command);
                            for (int i = 0; i < lineCount; i++)
                            {
                                input.ReadLine();
                            }
                        }
                    }
                    else
                    {
                        Trace.TraceWarning("Unexpected content at line: ", lineNumber);
                    }
                    line = input.ReadLine();
                }
                containerSet.Add(container);
                model.MoleculeSet = containerSet;
                seq.Add(model);
                file.Add(seq);
            }
            catch (Exception exception)
            {
                string message = "Error while parsing CTX file: " + exception.Message;
                Trace.TraceError(message);
                Debug.WriteLine(exception);
                throw new CDKException(message, exception);
            }
            return(file);
        }
예제 #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);
        }
예제 #27
0
        private IChemFile ReadChemFile(IChemFile file)
        {
            IChemSequence seq     = file.Builder.NewChemSequence();
            IChemModel    model   = file.Builder.NewChemModel();
            ICrystal      crystal = null;

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

            try
            {
                string line = input.ReadLine();
                while (line != null)
                {
                    Debug.WriteLine($"{lineNumber++}: {line}");
                    if (line.StartsWith("frame:", StringComparison.Ordinal))
                    {
                        Debug.WriteLine("found new frame");
                        model   = file.Builder.NewChemModel();
                        crystal = file.Builder.NewCrystal();

                        // assume the file format is correct

                        Debug.WriteLine("reading spacegroup");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        crystal.SpaceGroup = line;

                        Debug.WriteLine("reading unit cell axes");
                        Vector3 axis = new Vector3();
                        Debug.WriteLine("parsing A: ");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.X = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Y = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Z    = FortranFormat.Atof(line);
                        crystal.A = axis;
                        axis      = new Vector3();
                        Debug.WriteLine("parsing B: ");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.X = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Y = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Z    = FortranFormat.Atof(line);
                        crystal.B = axis;
                        axis      = new Vector3();
                        Debug.WriteLine("parsing C: ");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.X = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Y = FortranFormat.Atof(line);
                        line   = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        axis.Z    = FortranFormat.Atof(line);
                        crystal.C = axis;
                        Debug.WriteLine($"Crystal: {crystal}");
                        a = crystal.A;
                        b = crystal.B;
                        c = crystal.C;

                        Debug.WriteLine("Reading number of atoms");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        int atomsToRead = int.Parse(line, NumberFormatInfo.InvariantInfo);

                        Debug.WriteLine("Reading no molecules in assym unit cell");
                        line = input.ReadLine();
                        Debug.WriteLine($"{lineNumber++}: {line}");
                        int Z = int.Parse(line, NumberFormatInfo.InvariantInfo);
                        crystal.Z = Z;

                        string  symbol;
                        double  charge;
                        Vector3 cart;
                        for (int i = 1; i <= atomsToRead; i++)
                        {
                            cart = new Vector3();
                            line = input.ReadLine();
                            Debug.WriteLine($"{lineNumber++}: {line}");
                            symbol = line.Substring(0, line.IndexOf(':'));
                            charge = double.Parse(line.Substring(line.IndexOf(':') + 1), NumberFormatInfo.InvariantInfo);
                            line   = input.ReadLine();
                            Debug.WriteLine($"{lineNumber++}: {line}");
                            cart.X = double.Parse(line, NumberFormatInfo.InvariantInfo); // x
                            line   = input.ReadLine();
                            Debug.WriteLine($"{lineNumber++}: {line}");
                            cart.Y = double.Parse(line, NumberFormatInfo.InvariantInfo); // y
                            line   = input.ReadLine();
                            Debug.WriteLine($"{lineNumber++}: {line}");
                            cart.Z = double.Parse(line, NumberFormatInfo.InvariantInfo); // z
                            IAtom atom = file.Builder.NewAtom(symbol);
                            atom.Charge = charge;
                            // convert Cartesian coords to fractional
                            Vector3 frac = CrystalGeometryTools.CartesianToFractional(a, b, c, cart);
                            atom.FractionalPoint3D = frac;
                            crystal.Atoms.Add(atom);
                            Debug.WriteLine($"Added atom: {atom}");
                        }

                        model.Crystal = crystal;
                        seq.Add(model);
                    }
                    else
                    {
                        Debug.WriteLine("Format seems broken. Skipping these lines:");
                        while (line != null && !line.StartsWith("frame:", StringComparison.Ordinal))
                        {
                            line = input.ReadLine();
                            Debug.WriteLine($"{lineNumber++}: {line}");
                        }
                        Debug.WriteLine("Ok, resynched: found new frame");
                    }
                }
                file.Add(seq);
            }
            catch (Exception exception)
            {
                if (!(exception is IOException || exception is ArgumentException))
                {
                    throw;
                }
                string message = "Error while parsing CrystClust file: " + exception.Message;
                Trace.TraceError(message);
                Debug.WriteLine(exception);
                throw new CDKException(message, exception);
            }
            return(file);
        }