Beispiel #1
0
        private static string F_ANGLE_FORMAT(double angle) => angle.ToString("F3", NumberFormatInfo.InvariantInfo).PadLeft(7);    //"%3.3f";

        public void WriteCrystal(ICrystal crystal)
        {
            try
            {
                WriteHeader();
                Vector3  a        = crystal.A;
                Vector3  b        = crystal.B;
                Vector3  c        = crystal.C;
                double[] ucParams = CrystalGeometryTools.CartesianToNotional(a, b, c);
                writer.Write("CRYST1 " + F_LENGTH_FORMAT(ucParams[0]));
                writer.Write(F_LENGTH_FORMAT(ucParams[1]));
                writer.Write(F_LENGTH_FORMAT(ucParams[2]));
                writer.Write(F_ANGLE_FORMAT(ucParams[3]));
                writer.Write(F_ANGLE_FORMAT(ucParams[4]));
                writer.Write('\n');

                // before saving the atoms, we need to create cartesian coordinates
                foreach (var atom in crystal.Atoms)
                {
                    //                Debug.WriteLine($"PDBWriter: atom -> {atom}");
                    // if it got 3D coordinates, use that. If not, try fractional coordinates
                    if (atom.Point3D == null && atom.FractionalPoint3D != null)
                    {
                        Vector3 frac = atom.FractionalPoint3D.Value;
                        Vector3 cart = CrystalGeometryTools.FractionalToCartesian(a, b, c, frac);
                        atom.Point3D = cart;
                    }
                }
                WriteMolecule(crystal.Builder.NewAtomContainer(crystal));
            }
            catch (IOException exception)
            {
                throw new CDKException("Error while writing file: " + exception.Message, exception);
            }
        }
Beispiel #2
0
        /// <summary>
        /// Determines the features present in the given <see cref="IAtomContainer"/>.
        /// </summary>
        /// <param name="molecule">IAtomContainer to determine the features off</param>
        /// <returns>integer representation of the present features</returns>
        public static DataFeatures GetSupportedDataFeatures(IAtomContainer molecule)
        {
            DataFeatures features = DataFeatures.None;

            if (MoleculeFeaturesTool.HasElementSymbols(molecule))
            {
                features = features | DataFeatures.HasAtomElementSymbol;
            }
            if (GeometryUtil.Has2DCoordinates(molecule))
            {
                features = features | DataFeatures.Has2DCoordinates;
            }
            if (GeometryUtil.Has3DCoordinates(molecule))
            {
                features = features | DataFeatures.Has3DCoordinates;
            }
            if (CrystalGeometryTools.HasCrystalCoordinates(molecule))
            {
                features = features | DataFeatures.HasFractionalCrystalCoordinates;
            }
            if (MoleculeFeaturesTool.HasFormalCharges(molecule))
            {
                features = features | DataFeatures.HasAtomFormalCharges;
            }
            if (MoleculeFeaturesTool.HasPartialCharges(molecule))
            {
                features = features | DataFeatures.HasAtomPartialCharges;
            }
            if (MoleculeFeaturesTool.HasGraphRepresentation(molecule))
            {
                features = features | DataFeatures.HasGraphRepresentation;
            }
            return(features);
        }
Beispiel #3
0
        private void possiblySetCellParams(double a, double b, double c, double alpha, double beta, double gamma)
        {
            if (a != 0.0 && b != 0.0 && c != 0.0 && alpha != 0.0 && beta != 0.0 && gamma != 0.0)
            {
                //logger.info("Found and set crystal cell parameters");
                Vector3d[] axes = CrystalGeometryTools.notionalToCartesian(a, b, c, alpha, beta, gamma);

                crystal.A = axes[0];
                crystal.B = axes[1];
                crystal.C = axes[2];
            }
        }
Beispiel #4
0
        private void PossiblySetCellParams(double a, double b, double c, double alpha, double beta, double gamma)
        {
            if (a != 0.0 && b != 0.0 && c != 0.0 && alpha != 0.0 && beta != 0.0 && gamma != 0.0)
            {
                Trace.TraceInformation("Found and set crystal cell parameters");
                var axes = CrystalGeometryTools.NotionalToCartesian(a, b, c, alpha, beta, gamma);

                crystal.A = axes[0];
                crystal.B = axes[1];
                crystal.C = axes[2];
            }
        }
Beispiel #5
0
        public void TestReading()
        {
            var filename = "NCDK.Data.ShelX.frame_1.res";

            Trace.TraceInformation("Testing: " + filename);
            var         ins     = ResourceLoader.GetAsStream(filename);
            ShelXReader reader  = new ShelXReader(ins);
            Crystal     crystal = (Crystal)reader.Read(new Crystal());

            reader.Close();
            Assert.IsNotNull(crystal);
            Assert.AreEqual(42, crystal.Atoms.Count);
            var notional = CrystalGeometryTools.CartesianToNotional(crystal.A, crystal.B, crystal.C);

            Assert.AreEqual(7.97103, notional[0], 0.001);
            Assert.AreEqual(18.77220, notional[1], 0.001);
            Assert.AreEqual(10.26222, notional[2], 0.001);
            Assert.AreEqual(90.0000, notional[3], 0.001);
            Assert.AreEqual(90.0000, notional[4], 0.001);
            Assert.AreEqual(90.0000, notional[5], 0.001);
        }
Beispiel #6
0
        public void TestRoundTrip()
        {
            Crystal crystal = new Crystal();
            double  a       = 3.0;
            double  b       = 5.0;
            double  c       = 7.0;
            double  alpha   = 90.0;
            double  beta    = 110.0;
            double  gamma   = 100.0;
            var     axes    = CrystalGeometryTools.NotionalToCartesian(a, b, c, alpha, beta, gamma);

            crystal.A = axes[0];
            crystal.B = axes[1];
            crystal.C = axes[2];

            // serialazing
            StringWriter sWriter   = new StringWriter();
            ShelXWriter  resWriter = new ShelXWriter(sWriter);

            resWriter.Write(crystal);
            resWriter.Close();
            string resContent = sWriter.ToString();

            // deserialazing
            ShelXReader resReader = new ShelXReader(new StringReader(resContent));
            ICrystal    rCrystal  = (ICrystal)resReader.Read(new Crystal());

            // OK, do checking
            Assert.IsNotNull(rCrystal);
            Assert.AreEqual(crystal.A.X, rCrystal.A.X, 0.001);
            Assert.AreEqual(crystal.A.Y, rCrystal.A.Y, 0.001);
            Assert.AreEqual(crystal.A.Z, rCrystal.A.Z, 0.001);
            Assert.AreEqual(crystal.B.X, rCrystal.B.X, 0.001);
            Assert.AreEqual(crystal.B.Y, rCrystal.B.Y, 0.001);
            Assert.AreEqual(crystal.B.Z, rCrystal.B.Z, 0.001);
            Assert.AreEqual(crystal.C.X, rCrystal.C.X, 0.001);
            Assert.AreEqual(crystal.C.Y, rCrystal.C.Y, 0.001);
            Assert.AreEqual(crystal.C.Z, rCrystal.C.Z, 0.001);
        }
Beispiel #7
0
        private CMLMolecule CDKCrystalToCMLMolecule(ICrystal crystal, bool setIDs)
        {
            var molecule   = CDKAtomContainerToCMLMolecule(crystal, false, false);
            var cmlCrystal = new CMLCrystal();

            if (useCMLIDs && setIDs)
            {
                IDCreator.CreateIDs(crystal);
            }
            if (!string.IsNullOrEmpty(crystal.Id))
            {
                cmlCrystal.Id = crystal.Id;
            }

            this.CheckPrefix(cmlCrystal);
            cmlCrystal.Z = crystal.Z.Value;
            var params_ = CrystalGeometryTools.CartesianToNotional(crystal.A, crystal.B, crystal.C);

            Debug.WriteLine($"Number of cell params: {params_.Length}");
            cmlCrystal.SetCellParameters(params_);
            molecule.Add(cmlCrystal);
            return(molecule);
        }
Beispiel #8
0
        private ICrystal ReadCrystal(ICrystal crystal)
        {
            string line      = input.ReadLine();
            bool   end_found = false;

            while (line != null && !end_found)
            {
                /* is line continued? */
                if (line.Length > 0 && line.Substring(line.Length - 1).Equals("=", StringComparison.Ordinal))
                {
                    /* yes, line is continued */
                    line = line + input.ReadLine();
                }

                /* determine ShelX command */
                string command;
                try
                {
                    command = line.Substring(0, 4);
                }
                catch (ArgumentOutOfRangeException)
                {
                    // disregard this line
                    break;
                }

                Debug.WriteLine($"command: {command}");
                var u_command = command.ToUpperInvariant();
                if (u_command.StartsWith("REM", StringComparison.Ordinal))
                {
                    /* line is comment, disregard */

                    /* 7.1 Crystal data and general instructions */
                }
                else if (u_command.StartsWith("END", StringComparison.Ordinal))
                {
                    end_found = true;
                }
                else
                {
                    switch (u_command)
                    {
                    case "TITL":
                        break;

                    case "CELL":
                    {
                        // example: CELL 1.54184 23.56421 7.13203 18.68928 90.0000
                        // 109.3799 90.0000 CELL 1.54184 7.11174 21.71704 30.95857
                        // 90.000 90.000 90.000
                        var st = Strings.Tokenize(line);
                        //st[0]; // string command_again
                        //st[1]; // string wavelength
                        string sa     = st[2];
                        string sb     = st[3];
                        string sc     = st[4];
                        string salpha = st[5];
                        string sbeta  = st[6];
                        string sgamma = st[7];
                        Debug.WriteLine($"a: {sa}");
                        Debug.WriteLine($"b: {sb}");
                        Debug.WriteLine($"c: {sc}");
                        Debug.WriteLine($"alpha: {salpha}");
                        Debug.WriteLine($"beta : {sbeta}");
                        Debug.WriteLine($"gamma: {sgamma}");

                        double a     = FortranFormat.Atof(sa);
                        double b     = FortranFormat.Atof(sb);
                        double c     = FortranFormat.Atof(sc);
                        double alpha = FortranFormat.Atof(salpha);
                        double beta  = FortranFormat.Atof(sbeta);
                        double gamma = FortranFormat.Atof(sgamma);

                        Vector3[] axes = CrystalGeometryTools.NotionalToCartesian(a, b, c, alpha, beta, gamma);

                        crystal.A = axes[0];
                        crystal.B = axes[1];
                        crystal.C = axes[2];
                    }
                    break;

                    case "ZERR":
                    case "LATT":
                    case "SYMM":
                    case "SFAC":
                    case "DISP":
                    case "UNIT":
                    case "LAUE":
                    case "REM ":
                    case "MORE":
                    case "TIME":
                    /* 7.2 Reflection data input */
                    case "HKLF":
                    case "OMIT":
                    case "SHEL":
                    case "BASF":
                    case "TWIN":
                    case "EXTI":
                    case "SWAT":
                    case "HOPE":
                    case "MERG":
                    /* 7.3 Atom list and least-squares constraints */
                    case "SPEC":
                    case "RESI":
                    case "MOVE":
                    case "ANIS":
                    case "AFIX":
                    case "HFIX":
                    case "FRAG":
                    case "FEND":
                    case "EXYZ":
                    //case "EXTI":
                    case "EADP":
                    case "EQIV":
                    /* 7.4 The connectivity list */
                    case "CONN":
                    case "PART":
                    case "BIND":
                    case "FREE":
                    /* 7.5 Least-squares restraints */
                    case "DFIX":
                    case "DANG":
                    case "BUMP":
                    case "SAME":
                    case "SADI":
                    case "CHIV":
                    case "FLAT":
                    case "DELU":
                    case "SIMU":
                    case "DEFS":
                    case "ISOR":
                    case "NCSY":
                    case "SUMP":
                    /* 7.6 Least-squares organization */
                    case "L.S.":
                    case "CGLS":
                    case "BLOC":
                    case "DAMP":
                    case "STIR":
                    case "WGHT":
                    case "FVAR":
                    /* 7.7 Lists and tables */
                    case "BOND":
                    case "CONF":
                    case "MPLA":
                    case "RTAB":
                    case "HTAB":
                    case "LIST":
                    case "ACTA":
                    case "SIZE":
                    case "TEMP":
                    case "WPDB":
                    /* 7.8 Fouriers, peak search and lineprinter plots */
                    case "FMAP":
                    case "GRID":
                    case "PLAN":
                        break;

                    case "MOLE":
                        /* NOT DOCUMENTED BUT USED BY PLATON */
                        break;

                    case "SPGR":
                    {
                        // Line added by PLATON stating the spacegroup
                        var st = Strings.Tokenize(line);
                        //st[0]; // string command_again
                        string spacegroup = st[1];
                        crystal.SpaceGroup = spacegroup;
                    }
                    break;

                    case "    ":
                    {
                        Debug.WriteLine($"Disrgarding line assumed to be added by PLATON: {line}");

                        /* All other is atom */
                    }
                    break;

                    default:
                    {
                        //Debug.WriteLine($"Assumed to contain an atom: {line}");

                        // this line gives an atom, because all lines not starting with
                        // a ShelX command is an atom (that sucks!)
                        var    st    = Strings.Tokenize(line);
                        string atype = st[0];
                        //st[1]; // string scatt_factor
                        string sa = st[2];
                        string sb = st[3];
                        string sc = st[4];
                        // skip the rest

                        if (char.IsDigit(atype[1]))
                        {
                            // atom type has a one letter code
                            atype = atype.Substring(0, 1);
                        }
                        else
                        {
                            var sb2 = new StringBuilder();
                            sb2.Append(atype[1]);
                            atype = atype.Substring(0, 1) + sb2.ToString().ToLowerInvariant();
                        }

                        double[] frac = new double[3];
                        frac[0] = FortranFormat.Atof(sa);         // fractional coordinates
                        frac[1] = FortranFormat.Atof(sb);
                        frac[2] = FortranFormat.Atof(sc);
                        Debug.WriteLine("fa,fb,fc: " + frac[0] + ", " + frac[1] + ", " + frac[2]);

                        if (string.Equals(atype, "Q", StringComparison.OrdinalIgnoreCase))
                        {
                            // ingore atoms named Q
                        }
                        else
                        {
                            Trace.TraceInformation("Adding atom: " + atype + ", " + frac[0] + ", " + frac[1] + ", " + frac[2]);
                            IAtom atom = crystal.Builder.NewAtom(atype);
                            atom.FractionalPoint3D = new Vector3(frac[0], frac[1], frac[2]);
                            crystal.Atoms.Add(atom);
                            Debug.WriteLine($"Atom added: {atom}");
                        }
                    }
                    break;
                    }
                }
                line = input.ReadLine();
            }
            return(crystal);
        }
Beispiel #9
0
        private string ProcessAtomLoopBlock(string firstLine)
        {
            int    atomLabel              = -1; // -1 means not found in this block
            int    atomSymbol             = -1;
            int    atomFractX             = -1;
            int    atomFractY             = -1;
            int    atomFractZ             = -1;
            int    atomRealX              = -1;
            int    atomRealY              = -1;
            int    atomRealZ              = -1;
            string line                   = firstLine.Trim();
            int    headerCount            = 0;
            bool   hasParsableInformation = false;

            while (line != null && line[0] == '_')
            {
                headerCount++;
                if (line.Equals("_atom_site_label", StringComparison.Ordinal) || line.Equals("_atom_site_label_atom_id", StringComparison.Ordinal))
                {
                    atomLabel = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation($"label found in col: {atomLabel}");
                }
                else if (line.StartsWith("_atom_site_fract_x", StringComparison.Ordinal))
                {
                    atomFractX             = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("frac x found in col: " + atomFractX);
                }
                else if (line.StartsWith("_atom_site_fract_y", StringComparison.Ordinal))
                {
                    atomFractY             = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("frac y found in col: " + atomFractY);
                }
                else if (line.StartsWith("_atom_site_fract_z", StringComparison.Ordinal))
                {
                    atomFractZ             = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("frac z found in col: " + atomFractZ);
                }
                else if (string.Equals(line, "_atom_site.Cartn_x", StringComparison.Ordinal))
                {
                    atomRealX = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("cart x found in col: " + atomRealX);
                }
                else if (string.Equals(line, "_atom_site.Cartn_y", StringComparison.Ordinal))
                {
                    atomRealY = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("cart y found in col: " + atomRealY);
                }
                else if (string.Equals(line, "_atom_site.Cartn_z", StringComparison.Ordinal))
                {
                    atomRealZ = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("cart z found in col: " + atomRealZ);
                }
                else if (string.Equals(line, "_atom_site.type_symbol", StringComparison.Ordinal))
                {
                    atomSymbol             = headerCount;
                    hasParsableInformation = true;
                    Trace.TraceInformation("type_symbol found in col: " + atomSymbol);
                }
                else
                {
                    Trace.TraceWarning("Ignoring atom loop block field: " + line);
                }
                line = input.ReadLine().Trim();
            }
            if (!hasParsableInformation)
            {
                Trace.TraceInformation("No parsable info found");
                return(SkipLoopBody(line));
            }
            else
            {
                // now that headers are parsed, read the data
                while (line != null && line.Length > 0 &&
                       line[0] != '#' &&
                       line[0] != '_' &&
                       !line.StartsWith("loop_", StringComparison.Ordinal) &&
                       !line.StartsWith("data_", StringComparison.Ordinal))
                {
                    Debug.WriteLine("new row");
                    var tokenizer = Strings.Tokenize(line);
                    if (tokenizer.Count < headerCount)
                    {
                        Trace.TraceWarning("Column count mismatch; assuming continued on next line");
                        Debug.WriteLine($"Found #expected, #found:{headerCount}, {tokenizer.Count}");
                        tokenizer = Strings.Tokenize(line + input.ReadLine());
                    }
                    int colIndex = 0;
                    // process one row
                    IAtom   atom          = crystal.Builder.NewAtom("C");
                    Vector3 frac          = new Vector3();
                    Vector3 real          = new Vector3();
                    bool    hasFractional = false;
                    bool    hasCartesian  = false;
                    foreach (var field in tokenizer)
                    {
                        colIndex++;
                        Debug.WriteLine("Parsing col,token: " + colIndex + "=" + field);
                        if (colIndex == atomLabel)
                        {
                            if (atomSymbol == -1)
                            {
                                // no atom symbol found, use label
                                string element = ExtractFirstLetters(field);
                                atom.Symbol = element;
                            }
                            atom.Id = field;
                        }
                        else if (colIndex == atomFractX)
                        {
                            hasFractional = true;
                            frac.X        = ParseIntoDouble(field);
                        }
                        else if (colIndex == atomFractY)
                        {
                            hasFractional = true;
                            frac.Y        = ParseIntoDouble(field);
                        }
                        else if (colIndex == atomFractZ)
                        {
                            hasFractional = true;
                            frac.Z        = ParseIntoDouble(field);
                        }
                        else if (colIndex == atomSymbol)
                        {
                            atom.Symbol = field;
                        }
                        else if (colIndex == atomRealX)
                        {
                            hasCartesian = true;
                            Debug.WriteLine("Adding x3: " + ParseIntoDouble(field));
                            real.X = ParseIntoDouble(field);
                        }
                        else if (colIndex == atomRealY)
                        {
                            hasCartesian = true;
                            Debug.WriteLine("Adding y3: " + ParseIntoDouble(field));
                            real.Y = ParseIntoDouble(field);
                        }
                        else if (colIndex == atomRealZ)
                        {
                            hasCartesian = true;
                            Debug.WriteLine("Adding x3: " + ParseIntoDouble(field));
                            real.Z = ParseIntoDouble(field);
                        }
                    }
                    if (hasCartesian)
                    {
                        Vector3 a = crystal.A;
                        Vector3 b = crystal.B;
                        Vector3 c = crystal.C;
                        frac = CrystalGeometryTools.CartesianToFractional(a, b, c, real);
                        atom.FractionalPoint3D = frac;
                    }
                    if (hasFractional)
                    {
                        atom.FractionalPoint3D = frac;
                    }
                    Debug.WriteLine($"Adding atom: {atom}");
                    crystal.Atoms.Add(atom);

                    // look up next row
                    line = input.ReadLine();
                    if (line != null)
                    {
                        line = line.Trim();
                    }
                }
            }
            return(line);
        }
Beispiel #10
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);
        }
Beispiel #11
0
        private void processAtomLoopBlock(System.String firstLine)
        {
            int atomLabel  = -1; // -1 means not found in this block
            int atomSymbol = -1;
            int atomFractX = -1;
            int atomFractY = -1;
            int atomFractZ = -1;
            int atomRealX  = -1;
            int atomRealY  = -1;
            int atomRealZ  = -1;

            System.String line                   = firstLine.Trim();
            int           headerCount            = 0;
            bool          hasParsableInformation = false;

            while (line != null && line[0] == '_')
            {
                headerCount++;
                if (line.Equals("_atom_site_label") || line.Equals("_atom_site_label_atom_id"))
                {
                    atomLabel = headerCount;
                    hasParsableInformation = true;
                    //logger.info("label found in col: " + atomLabel);
                }
                else if (line.StartsWith("_atom_site_fract_x"))
                {
                    atomFractX             = headerCount;
                    hasParsableInformation = true;
                    //logger.info("frac x found in col: " + atomFractX);
                }
                else if (line.StartsWith("_atom_site_fract_y"))
                {
                    atomFractY             = headerCount;
                    hasParsableInformation = true;
                    //logger.info("frac y found in col: " + atomFractY);
                }
                else if (line.StartsWith("_atom_site_fract_z"))
                {
                    atomFractZ             = headerCount;
                    hasParsableInformation = true;
                    //logger.info("frac z found in col: " + atomFractZ);
                }
                else if (line.Equals("_atom_site.Cartn_x"))
                {
                    atomRealX = headerCount;
                    hasParsableInformation = true;
                    //logger.info("cart x found in col: " + atomRealX);
                }
                else if (line.Equals("_atom_site.Cartn_y"))
                {
                    atomRealY = headerCount;
                    hasParsableInformation = true;
                    //logger.info("cart y found in col: " + atomRealY);
                }
                else if (line.Equals("_atom_site.Cartn_z"))
                {
                    atomRealZ = headerCount;
                    hasParsableInformation = true;
                    //logger.info("cart z found in col: " + atomRealZ);
                }
                else if (line.Equals("_atom_site.type_symbol"))
                {
                    atomSymbol             = headerCount;
                    hasParsableInformation = true;
                    //logger.info("type_symbol found in col: " + atomSymbol);
                }
                else
                {
                    //logger.warn("Ignoring atom loop block field: " + line);
                }
                line = input.ReadLine().Trim();
            }
            if (hasParsableInformation == false)
            {
                //logger.info("No parsable info found");
                skipUntilEmptyOrCommentLine(line);
            }
            else
            {
                // now that headers are parsed, read the data
                while (line != null && line.Length > 0 && line[0] != '#')
                {
                    //logger.debug("new row");
                    SupportClass.Tokenizer tokenizer = new SupportClass.Tokenizer(line);
                    if (tokenizer.Count < headerCount)
                    {
                        //logger.warn("Column count mismatch; assuming continued on next line");
                        //logger.debug("Found #expected, #found: " + headerCount + ", " + tokenizer.Count);
                        tokenizer = new SupportClass.Tokenizer(line + input.ReadLine());
                    }
                    int colIndex = 0;
                    // process one row
                    IAtom   atom          = crystal.Builder.newAtom("C");
                    Point3d frac          = new Point3d();
                    Point3d real          = new Point3d();
                    bool    hasFractional = false;
                    bool    hasCartesian  = false;
                    while (tokenizer.HasMoreTokens())
                    {
                        colIndex++;
                        System.String field = tokenizer.NextToken();
                        //logger.debug("Parsing col,token: " + colIndex + "=" + field);
                        if (colIndex == atomLabel)
                        {
                            if (atomSymbol == -1)
                            {
                                // no atom symbol found, use label
                                System.String element = extractFirstLetters(field);
                                atom.Symbol = element;
                            }
                            atom.ID = field;
                        }
                        else if (colIndex == atomFractX)
                        {
                            hasFractional = true;
                            frac.x        = parseIntoDouble(field);
                        }
                        else if (colIndex == atomFractY)
                        {
                            hasFractional = true;
                            frac.y        = parseIntoDouble(field);
                        }
                        else if (colIndex == atomFractZ)
                        {
                            hasFractional = true;
                            frac.z        = parseIntoDouble(field);
                        }
                        else if (colIndex == atomSymbol)
                        {
                            atom.Symbol = field;
                        }
                        else if (colIndex == atomRealX)
                        {
                            hasCartesian = true;
                            //logger.debug("Adding x3: " + parseIntoDouble(field));
                            real.x = parseIntoDouble(field);
                        }
                        else if (colIndex == atomRealY)
                        {
                            hasCartesian = true;
                            //logger.debug("Adding y3: " + parseIntoDouble(field));
                            real.y = parseIntoDouble(field);
                        }
                        else if (colIndex == atomRealZ)
                        {
                            hasCartesian = true;
                            //logger.debug("Adding x3: " + parseIntoDouble(field));
                            real.z = parseIntoDouble(field);
                        }
                    }
                    if (hasCartesian)
                    {
                        Vector3d a = crystal.A;
                        Vector3d b = crystal.B;
                        Vector3d c = crystal.C;
                        frac = CrystalGeometryTools.cartesianToFractional(a, b, c, real);
                        atom.setFractionalPoint3d(frac);
                    }
                    if (hasFractional)
                    {
                        atom.setFractionalPoint3d(frac);
                    }
                    //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Object.toString' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
                    //logger.debug("Adding atom: " + atom);
                    crystal.addAtom(atom);

                    // look up next row
                    line = input.ReadLine().Trim();
                }
            }
        }
Beispiel #12
0
        // Private procedures

        private void WriteCrystal(ICrystal crystal)
        {
            var title = crystal.Title;

            if (title != null && title.Trim().Length > 0)
            {
                Writeln($"TITL {title.Trim()}");
            }
            else
            {
                Writeln("TITL Produced with CDK (http://cdk.sf.net/)");
            }
            Vector3 a       = crystal.A;
            Vector3 b       = crystal.B;
            Vector3 c       = crystal.C;
            double  alength = a.Length();
            double  blength = b.Length();
            double  clength = c.Length();
            double  alpha   = Vectors.RadianToDegree(Vectors.Angle(b, c));
            double  beta    = Vectors.RadianToDegree(Vectors.Angle(a, c));
            double  gamma   = Vectors.RadianToDegree(Vectors.Angle(a, b));

            Write("CELL " + 1.54184.ToString("F5", NumberFormatInfo.InvariantInfo) + "   ");
            Write(alength.ToString("F5", NumberFormatInfo.InvariantInfo) + "  ");
            Write(blength.ToString("F5", NumberFormatInfo.InvariantInfo) + "  ");
            Write(clength.ToString("F5", NumberFormatInfo.InvariantInfo) + "  ");
            Write(alpha.ToString("F4", NumberFormatInfo.InvariantInfo) + "  ");
            Write(beta.ToString("F4", NumberFormatInfo.InvariantInfo) + "  ");
            Write(gamma.ToString("F4", NumberFormatInfo.InvariantInfo) + "  ");
            Writeln("ZERR " + ((double)crystal.Z).ToString("F5", NumberFormatInfo.InvariantInfo)
                    + "    0.01000  0.01000   0.01000   0.0100   0.0100   0.0100");
            string spaceGroup = crystal.SpaceGroup;

            if (string.Equals("P1", spaceGroup, StringComparison.Ordinal))
            {
                Writeln("LATT  -1");
            }
            else if (string.Equals("P 2_1 2_1 2_1", spaceGroup, StringComparison.Ordinal))
            {
                Writeln("LATT  -1");
                Writeln("SYMM  1/2+X   , 1/2-Y   ,    -Z");
                Writeln("SYMM     -X   , 1/2+Y   , 1/2-Z");
                Writeln("SYMM  1/2-X   ,    -Y   , 1/2+Z");
            }
            string            elemNames  = "";
            string            elemCounts = "";
            IMolecularFormula formula    = MolecularFormulaManipulator.GetMolecularFormula(crystal);
            var asortedElements          = MolecularFormulaManipulator.Elements(formula).ToReadOnlyList();

            foreach (var element in asortedElements)
            {
                string symbol = element.Symbol;
                elemNames += symbol + "    ".Substring(symbol.Length);
                string countS = MolecularFormulaManipulator.GetElementCount(formula, element).ToString(NumberFormatInfo.InvariantInfo);
                elemCounts += countS + "    ".Substring(countS.Length);
            }
            Writeln("SFAC  " + elemNames);
            Writeln("UNIT  " + elemCounts);
            /* write atoms */
            for (int i = 0; i < crystal.Atoms.Count; i++)
            {
                IAtom   atom      = crystal.Atoms[i];
                Vector3 cartCoord = atom.Point3D.Value;
                Vector3 fracCoord = CrystalGeometryTools.CartesianToFractional(a, b, c, cartCoord);
                string  symbol    = atom.Symbol;
                string  output    = symbol + (i + 1);
                Write(output);
                for (int j = 1; j < 5 - output.Length; j++)
                {
                    Write(" ");
                }
                Write("     ");
                string elemID = null;
                for (int elemidx = 0; elemidx < asortedElements.Count; elemidx++)
                {
                    var elem = asortedElements[elemidx];
                    if (elem.Symbol.Equals(symbol, StringComparison.Ordinal))
                    {
                        elemID = (elemidx + 1).ToString(NumberFormatInfo.InvariantInfo);
                        break;
                    }
                }
                Write(elemID);
                Write("    ".Substring(elemID.Length));
                Write(fracCoord.X.ToString("F5", NumberFormatInfo.InvariantInfo) + "   ");
                Write(fracCoord.Y.ToString("F5", NumberFormatInfo.InvariantInfo) + "   ");
                Writeln(fracCoord.Y.ToString("F5", NumberFormatInfo.InvariantInfo) + "    11.00000    0.05000");
            }
            Writeln("END");
        }
Beispiel #13
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);
        }