Пример #1
0
        public static Molecule ReadNative(System.IO.StreamReader in_Renamed)
        {
            Molecule mol = new Molecule();

            //UPGRADE_NOTE: Final was removed from the declaration of 'GENERIC_ERROR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
            System.String GENERIC_ERROR = "Invalid SketchEl file.";

            try
            {
                System.String line = in_Renamed.ReadLine();
                if (!line.StartsWith("SketchEl!"))
                {
                    throw new System.IO.IOException("Not a SketchEl file.");
                }
                int p1 = line.IndexOf('('), p2 = line.IndexOf(','), p3 = line.IndexOf(')');
                if (p1 == 0 || p2 == 0 || p3 == 0)
                {
                    throw new System.IO.IOException(GENERIC_ERROR);
                }

                int numAtoms = System.Int32.Parse(line.Substring(p1 + 1, (p2) - (p1 + 1)).Trim());
                int numBonds = System.Int32.Parse(line.Substring(p2 + 1, (p3) - (p2 + 1)).Trim());
                for (int n = 0; n < numAtoms; n++)
                {
                    line = in_Renamed.ReadLine();
                    // TODO: verify java's split method syntax: "[\\=\\,\\;]"
                    System.String[] bits = line.Split('=', ',', ';');
                    if (bits.Length < 5)
                    {
                        throw new System.IO.IOException(GENERIC_ERROR);
                    }
                    int num = mol.AddAtom(bits[0], System.Double.Parse(bits[1].Trim()), System.Double.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim()), System.Int32.Parse(bits[4].Trim()));
                    if (bits.Length >= 6 && bits[5].Length > 0 && bits[5][0] == 'e')
                    {
                        mol.SetAtomHExplicit(num, System.Int32.Parse(bits[5].Substring(1)));
                    }
                }
                for (int n = 0; n < numBonds; n++)
                {
                    line = in_Renamed.ReadLine();
                    System.String[] bits = line.Split('-', '=', ',');                     // "[\\-\\=\\,]");
                    if (bits.Length < 4)
                    {
                        throw new System.IO.IOException(GENERIC_ERROR);
                    }
                    mol.AddBond(System.Int32.Parse(bits[0].Trim()), System.Int32.Parse(bits[1].Trim()), System.Int32.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim()));
                }
                line = in_Renamed.ReadLine();
                if (String.CompareOrdinal(line, "!End") != 0)
                {
                    throw new System.IO.IOException(GENERIC_ERROR);
                }
            }
            catch (System.Exception)
            {
                throw new System.IO.IOException(GENERIC_ERROR);
            }

            return(mol);
        }
Пример #2
0
        public void Mr2()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var o  = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Double, o);

            var mass = float.Parse(mole.GetMolecularMass());

            Assert.AreEqual(72, mass);
        }
Пример #3
0
        public void Formula2()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var o  = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Double, o);

            var formula = mole.GetMolecularFormula();

            Assert.AreEqual("C4H8O", formula);
        }
Пример #4
0
        public void Smiles2()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var o  = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Double, o);

            var smiles = mole.ToSMILES();

            Assert.AreEqual("CCCC=O", smiles);
        }
Пример #5
0
        public void Formula5()
        {
            var c0 = new AtomNode("C");
            var p  = new AtomNode("P");
            var h  = new AtomNode("H");
            var n  = new AtomNode("N");
            var o  = new AtomNode("O");
            var cl = new AtomNode("Cl");
            var o2 = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, p);
            mole.AddBondToLast(BondOrder.Single, cl);
            mole.AddBond(BondOrder.Single, c0, h);
            mole.AddBond(BondOrder.Single, p, n);
            mole.AddBondToLast(BondOrder.Double, o);
            mole.AddBond(BondOrder.Single, n, o2);

            var formula = mole.GetMolecularFormula();

            Assert.AreEqual("CH4PClNO2", formula);
        }
Пример #6
0
        public void Mr5()
        {
            var c0 = new AtomNode("C");
            var p  = new AtomNode("P");
            var h  = new AtomNode("H");
            var n  = new AtomNode("N");
            var o  = new AtomNode("O");
            var cl = new AtomNode("Cl");
            var o2 = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, p);
            mole.AddBondToLast(BondOrder.Single, cl);
            mole.AddBond(BondOrder.Single, c0, h);
            mole.AddBond(BondOrder.Single, p, n);
            mole.AddBondToLast(BondOrder.Double, o);
            mole.AddBond(BondOrder.Single, n, o2);

            var mass = float.Parse(mole.GetMolecularMass());

            Assert.AreEqual(128.5, mass);
        }
Пример #7
0
        public void Smiles5()
        {
            var c0 = new AtomNode("C");
            var p  = new AtomNode("P");
            var h  = new AtomNode("H");
            var n  = new AtomNode("N");
            var o  = new AtomNode("O");
            var cl = new AtomNode("Cl");
            var o2 = new AtomNode("O");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, p);
            mole.AddBondToLast(BondOrder.Single, cl);
            mole.AddBond(BondOrder.Single, c0, h);
            mole.AddBond(BondOrder.Single, p, n);
            mole.AddBondToLast(BondOrder.Double, o);
            mole.AddBond(BondOrder.Single, n, o2);

            var smiles = mole.ToSMILES();

            Assert.AreEqual("CP(Cl)(N(=O)(O))", smiles);
        }
Пример #8
0
        public void Formula1()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var c4 = new AtomNode("C");
            var c5 = new AtomNode("C");
            var h  = new AtomNode("H");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Single, c4);
            mole.AddBondToLast(BondOrder.Single, c5);
            mole.AddBondToLast(BondOrder.Single, c0);
            mole.AddBondToLast(BondOrder.Single, h);

            var formula = mole.GetMolecularFormula();

            Assert.AreEqual("C6H12", formula);
        }
Пример #9
0
        public void Mr1()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var c4 = new AtomNode("C");
            var c5 = new AtomNode("C");
            var h  = new AtomNode("H");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Single, c4);
            mole.AddBondToLast(BondOrder.Single, c5);
            mole.AddBondToLast(BondOrder.Single, c0);
            mole.AddBondToLast(BondOrder.Single, h);

            var mass = float.Parse(mole.GetMolecularMass());

            Assert.AreEqual(84, mass);
        }
Пример #10
0
        public void Smiles1()
        {
            var c0 = new AtomNode("C");
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("C");
            var c3 = new AtomNode("C");
            var c4 = new AtomNode("C");
            var c5 = new AtomNode("C");
            var h  = new AtomNode("H");

            var mole = new Molecule(c0);

            mole.AddBondToLast(BondOrder.Single, c1);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBondToLast(BondOrder.Single, c4);
            mole.AddBondToLast(BondOrder.Single, c5);
            mole.AddBondToLast(BondOrder.Single, c0);
            mole.AddBondToLast(BondOrder.Single, h);

            var smiles = mole.ToSMILES();

            Assert.AreEqual("C1CCCCC1", smiles);
        }
Пример #11
0
        private void AddHBonds(Molecule molecule, Atom atom, int bonds)
        {
            for (int i = 0; i < bonds; i++)
            {
                Atom h = new Atom();
                h.Element = Globals.PeriodicTable.H;

                molecule.AddAtom(h);
                h.Parent = molecule;

                Bond bond = new Bond(atom, h);
                bond.Order = "S";
                molecule.AddBond(bond);
                bond.Parent = molecule;
            }
        }
Пример #12
0
        public void PermuteOCCCSC()
        {
            Molecule molecule = new Molecule();

            molecule.AddAtom("O");
            molecule.AddAtom("C");
            molecule.AddAtom("C");
            molecule.AddAtom("C");
            molecule.AddAtom("S");
            molecule.AddAtom("C");
            molecule.AddBond(0, 1, Molecule.BondOrder.Double);
            molecule.AddSingleBond(1, 2);
            molecule.AddSingleBond(2, 3);
            molecule.AddSingleBond(3, 4);
            molecule.AddSingleBond(4, 5);
            PermuteCompletely(molecule);
        }
Пример #13
0
        public void DoubleBondChainTest()
        {
            Molecule molecule    = new Molecule();
            int      chainLength = 6;

            molecule.AddAtom("O");
            molecule.AddAtom("C");
            molecule.AddAtom("C");
            molecule.AddAtom("O");
            molecule.AddAtom("C");
            molecule.AddAtom("O");
            for (int i = 0; i < chainLength - 2; i++)
            {
                molecule.AddSingleBond(i, i + 1);
            }
            molecule.AddBond(chainLength - 2, chainLength - 1, Molecule.BondOrder.Double);
            string sigA = ToSignatureString(molecule);
            //        PermuteCompletely(molecule);
            //        TestSpecificPermutation(molecule, new int[] {0,1,3,4,2,5});
            Molecule moleculeB = new Molecule();

            moleculeB.AddAtom("O");
            moleculeB.AddAtom("C");
            moleculeB.AddAtom("C");
            moleculeB.AddAtom("C");
            moleculeB.AddAtom("O");
            moleculeB.AddAtom("O");
            moleculeB.AddSingleBond(0, 1);
            moleculeB.AddSingleBond(1, 3);
            moleculeB.AddSingleBond(2, 4);
            moleculeB.AddBond(2, 5, Molecule.BondOrder.Double);
            moleculeB.AddSingleBond(3, 4);

            string sigB = ToSignatureString(moleculeB);

            //        MoleculeSignature molSig = new MoleculeSignature(moleculeB);
            //        molSig.SignatureStringForVertex(1);
            Assert.AreEqual(sigA, sigB);
        }
Пример #14
0
        private void ReadBonds(StreamReader reader, int bonds)
        {
            int idx = 0;

            while (!reader.EndOfStream && idx < bonds)
            {
                string line = SdFileConverter.GetNextLine(reader);
                if (!string.IsNullOrEmpty(line))
                {
                    // create bond

                    int  atomNumber1 = ParseInteger(line, 0, 3);
                    Atom atom1       = atomByNumber[atomNumber1];

                    if (atom1 == null)
                    {
                        _molecule.Warnings.Add($"Cannot resolve atomNumber {atomNumber1} at line {SdFileConverter.LineNumber}");
                        _molecule.Warnings.Add($"{line}");
                    }

                    int  atomNumber2 = ParseInteger(line, 3, 3);
                    Atom atom2       = atomByNumber[atomNumber2];

                    if (atom2 == null)
                    {
                        _molecule.Warnings.Add($"Cannot resolve atomNumber {atomNumber2} at line {SdFileConverter.LineNumber}");
                        _molecule.Warnings.Add($"{line}");
                    }
                    idx++;

                    Bond thisBond = new Bond();
                    thisBond.StartAtomInternalId = atom1?.InternalId;
                    thisBond.EndAtomInternalId   = atom2?.InternalId;

                    // Bond Order
                    string order = GetSubString(line, 6, 3);
                    if (!string.IsNullOrEmpty(order))
                    {
                        int bondOrder = ParseInteger(order);
                        if (bondOrder <= 4)
                        {
                            thisBond.Order = BondOrder(bondOrder);
                        }
                        else
                        {
                            thisBond.Order = BondOrder(bondOrder);
                            _molecule.Warnings.Add($"Unsupported Bond Type of {order} at Line {SdFileConverter.LineNumber}");
                        }
                    }

                    // stereo
                    string stereo = GetSubString(line, 9, 3);
                    if (!string.IsNullOrEmpty(stereo))
                    {
                        thisBond.Stereo = BondStereoFromMolfile(ParseInteger(stereo));
                    }

                    // add bond to molecule
                    _molecule.AddBond(thisBond);
                    thisBond.Parent = _molecule;
                    bondByNumber.Add(idx, thisBond);
                }
            }
        }
        //static Molecule ReadMoleFile(string filename)
        //{
        //    using (var reader = new System.IO.StreamReader(filename))
        //    {
        //        string s = reader.ReadToEnd();
        //        if (s.Contains("V2000")) return MoleFileReader.ParseMoleFile2(s);
        //        if (s.Contains("V3000")) throw new Exception("Version 3000 Mol file is currently not supported.");
        //        throw new Exception("Mol file type not recognized. It is does not contain a version number.");
        //    }
        //}

        static Molecule ParseMoleFile2(string moleFile)
        {
            Molecule molecule = new Molecule();
            //atoms.Clear();
            //cycles.Clear();
            //fusedRings.Clear();

            int numAtoms = 0;
            int numBonds = 0;

            // This information is contained in the header (first 3 lines) of the mol file. It is currently not being used, but code has been created for
            // future use.
            string name    = string.Empty;
            string program = string.Empty;
            string user    = string.Empty;
            //// used to test Line 2 reading below.
            //string MM = string.Empty;
            //string DD = string.Empty;
            //string YY = string.Empty;
            //string HH = string.Empty;
            //string mm = string.Empty;
            int    MM = 1;
            int    DD = 1;
            int    YY = 0;
            int    HH = 0;
            int    mm = 0;
            string dimensionalCodes = string.Empty;
            //// used to test Line 2 reading below.
            //string scalingFactor1 = string.Empty;
            int scalingFactor1 = 0;
            //// used to test Line 2 reading below.
            //string scalingFactor2 = string.Empty;
            double scalingFactor2 = 0;
            // used to test Line 2 reading below.
            string energy         = string.Empty;
            string registryNumber = string.Empty;
            string comments       = string.Empty;

            string[] lines = moleFile.Split('\n');
            // Line 1 contains the compound name. It can not be longer than 80 characters, and is allowed to be empty.
            // The length of the line is not relevant in how this is read, so it is not checked.
            name = lines[0];
            //// used to test Line 2 reading below.
            //lines[1] = "IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR";
            // Line 2 is optional. Skip this if it is not there.
            if (lines[1] != string.Empty)
            {
                // Line format: IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR
                //              A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6->
                //User's first and last initials (l), program name (P), date/time (M/D/Y,H:m),
                //dimensional codes (d), scaling factors (S, s), energy (E) if modeling program input,
                //internal registry number (R) if input through MDL form.
                if (lines[1].Length > 2)
                {
                    user = lines[1].Substring(0, 2);                      // II
                }
                if (lines[1].Length > 10)
                {
                    program = lines[1].Substring(2, 8);                       // PPPPPPPP
                }
                if (lines[1].Length > 20)
                {
                    //// used to test Line 2 reading below.
                    //MM = lines[1].Substring(10, 2); // MMDDYYHHmm
                    //DD = lines[1].Substring(12, 2); // MMDDYYHHmm
                    //YY = lines[1].Substring(14, 2); // MMDDYYHHmm
                    //HH = lines[1].Substring(16, 2); // MMDDYYHHmm
                    //mm = lines[1].Substring(18, 2); // MMDDYYHHmm
                    MM = Convert.ToInt32(lines[1].Substring(10, 2)); // MMDDYYHHmm
                    DD = Convert.ToInt32(lines[1].Substring(12, 2)); // MMDDYYHHmm
                    YY = Convert.ToInt32(lines[1].Substring(14, 2)); // MMDDYYHHmm
                    HH = Convert.ToInt32(lines[1].Substring(16, 2)); // MMDDYYHHmm
                    mm = Convert.ToInt32(lines[1].Substring(18, 2)); // MMDDYYHHmm
                }
                if (lines[1].Length > 22)
                {
                    dimensionalCodes = lines[1].Substring(20, 2);                       // dd
                }
                //// used to test Line 2 reading below.
                // if (lines[1].Length > 24) scalingFactor1 = lines[1].Substring(22, 2); //SS
                if (lines[1].Length > 24)
                {
                    scalingFactor1 = Convert.ToInt32(lines[1].Substring(22, 2));                       //SS
                }
                //// used to test Line 2 reading below.
                // if (lines[1].Length > 34) scalingFactor2 = lines[1].Substring(24, 10); //ss
                if (lines[1].Length > 34)
                {
                    scalingFactor2 = Convert.ToDouble(lines[1].Substring(24, 10));                       //ss
                }
                if (lines[1].Length > 46)
                {
                    energy = lines[1].Substring(34, 12);                       //EEEEEEEEEEEE
                }
                if (lines[1].Length == 52)
                {
                    registryNumber = lines[1].Substring(46, 6);                        //RRRRRR
                }
            }
            comments = lines[2];

            // Counts Line
            // aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv
            numAtoms = Convert.ToInt32(lines[3].Substring(0, 3));
            numBonds = Convert.ToInt32(lines[3].Substring(3, 3));
            int atomLists = Convert.ToInt32(lines[3].Substring(6, 3));
            //int fObsolete = Convert.ToInt32(lines[3].Substring(9, 3));
            bool chiral = false;

            if (Convert.ToInt32(lines[3].Substring(12, 3)) == 1)
            {
                chiral = true;
            }
            int sText = Convert.ToInt32(lines[3].Substring(15, 3));
            //int xObsolete = Convert.ToInt32(lines[3].Substring(18, 3));
            //int rObsolete = Convert.ToInt32(lines[3].Substring(21, 3));
            //int pObsolete = Convert.ToInt32(lines[3].Substring(24, 3));
            //int iObsolete = Convert.ToInt32(lines[3].Substring(27, 3));
            int    properties = Convert.ToInt32(lines[3].Substring(30, 3));
            string version    = lines[3].Substring(33, 6);

            for (int i = 0; i < numAtoms; i++)
            {
                Atom a = new ChemInfo.Atom(lines[4 + i].Substring(31, 3).Trim());
                molecule.AddAtom(a);
                // xxxxx.xxxxyyyyy.yyyyzzzzz.zzzz aaaddcccssshhhbbbvvvHHHrrriiimmmnnneee
                //a.x = Convert.ToDouble(lines[4 + i].Substring(0, 10));
                //a.y = Convert.ToDouble(lines[4 + i].Substring(10, 10));
                //a.z = Convert.ToDouble(lines[4 + i].Substring(20, 10));
                string text = lines[4 + i].Substring(34, 2);
                a.MassDiff      = Convert.ToInt32(lines[4 + i].Substring(34, 2));
                a.Charge        = Convert.ToInt32(lines[4 + i].Substring(36, 3));
                a.StereoParity  = Convert.ToInt32(lines[4 + i].Substring(39, 3));
                a.HydrogenCount = Convert.ToInt32(lines[4 + i].Substring(42, 3));
                a.StereoCareBox = Convert.ToInt32(lines[4 + i].Substring(45, 3));
                //a.Valence = Convert.ToInt32(lines[4 + i].Substring(48, 3));
                // string H0 = lines[4 + i].Substring(51, 3);
                // a.HO = Convert.ToInt32(lines[4 + i].Substring(51, 3));
                a.RNotUsed           = lines[4 + i].Substring(54, 3);
                a.INotUsed           = lines[4 + i].Substring(57, 3);
                a.AtomMapping        = Convert.ToInt32(lines[4 + i].Substring(60, 3));
                a.InversionRetension = Convert.ToInt32(lines[4 + i].Substring(63, 3));
                a.ExactChange        = Convert.ToInt32(lines[4 + i].Substring(66, 3));
            }
            for (int i = 0; i < numBonds; i++)
            {
                //Bond b = new Bond();
                // 111222tttsssxxxrrrccc
                string                   line           = lines[4 + numAtoms + i];
                int                      firstAtom      = Convert.ToInt32(lines[4 + numAtoms + i].Substring(0, 3));
                int                      secondAtom     = Convert.ToInt32(lines[4 + numAtoms + i].Substring(3, 3));
                BondType                 bondType       = (BondType)Convert.ToInt32(lines[4 + numAtoms + i].Substring(6, 3));
                BondStereo               bondStereo     = (BondStereo)Convert.ToInt32(lines[4 + numAtoms + i].Substring(9, 3));
                string                   xNotUsed       = lines[4 + numAtoms + i].Substring(12, 3);
                BondTopology             bondTopology   = (BondTopology)Convert.ToInt32(lines[4 + numAtoms + i].Substring(15, 3));
                int                      rc             = Convert.ToInt32(lines[4 + numAtoms + i].Substring(18, 3));
                BondReactingCenterStatus reactingCenter = BondReactingCenterStatus.Unmarked;
                if (rc == 13)
                {
                    reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.bondOrderChanges | BondReactingCenterStatus.aCenter;
                }
                else if (rc == 12)
                {
                    reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.bondOrderChanges;
                }
                else if (rc == 9)
                {
                    reactingCenter = BondReactingCenterStatus.bondOrderChanges | BondReactingCenterStatus.aCenter;
                }
                else if (rc == 5)
                {
                    reactingCenter = BondReactingCenterStatus.bondMadeOrBroken | BondReactingCenterStatus.aCenter;
                }
                else
                {
                    reactingCenter = (BondReactingCenterStatus)rc;
                }
                molecule.AddBond(molecule.Atoms[firstAtom - 1], molecule.Atoms[secondAtom - 1], bondType, bondStereo, bondTopology, reactingCenter);
            }
            molecule.FindRings();
            return(molecule);
        }
Пример #16
0
        public static void DoPropertyEdit(MouseButtonEventArgs e, EditorCanvas currentEditor)
        {
            EditViewModel evm = (EditViewModel)currentEditor.Chemistry;

            var position       = e.GetPosition(currentEditor);
            var screenPosition = currentEditor.PointToScreen(position);

            // Did RightClick occur on a Molecule Selection Adorner?
            var moleculeAdorner = currentEditor.GetMoleculeAdorner(position);

            if (moleculeAdorner != null)
            {
                if (moleculeAdorner.AdornedMolecules.Count == 1)
                {
                    screenPosition = GetDpiAwareScaledPosition(screenPosition, moleculeAdorner);

                    var mode = Application.Current.ShutdownMode;
                    Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

                    var model = new MoleculePropertiesModel();
                    model.Centre           = screenPosition;
                    model.Path             = moleculeAdorner.AdornedMolecules[0].Path;
                    model.Used1DProperties = evm.Used1DProperties;

                    model.Data = new Model();
                    Molecule mol = moleculeAdorner.AdornedMolecules[0].Copy();
                    model.Data.AddMolecule(mol);
                    mol.Parent = model.Data;

                    model.Charge               = mol.FormalCharge;
                    model.Count                = mol.Count;
                    model.SpinMultiplicity     = mol.SpinMultiplicity;
                    model.ShowMoleculeBrackets = mol.ShowMoleculeBrackets;

                    var pe = new MoleculePropertyEditor(model);
                    ShowDialog(pe, currentEditor);

                    if (model.Save)
                    {
                        var thisMolecule = model.Data.Molecules.First().Value;
                        evm.UpdateMolecule(moleculeAdorner.AdornedMolecules[0], thisMolecule);
                    }

                    Application.Current.ShutdownMode = mode;
                }
            }
            else
            {
                // Did RightClick occur on a ChemicalVisual?
                var activeVisual = currentEditor.GetTargetedVisual(position);
                if (activeVisual != null)
                {
                    screenPosition = GetDpiAwareScaledPosition(screenPosition, activeVisual);

                    // Did RightClick occur on an AtomVisual?
                    if (activeVisual is AtomVisual av)
                    {
                        var mode = Application.Current.ShutdownMode;

                        Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

                        var atom  = av.ParentAtom;
                        var model = new AtomPropertiesModel
                        {
                            Centre  = screenPosition,
                            Path    = atom.Path,
                            Element = atom.Element
                        };

                        if (atom.Element is Element)
                        {
                            model.IsFunctionalGroup = false;
                            model.IsElement         = true;

                            model.Charge     = atom.FormalCharge ?? 0;
                            model.Isotope    = atom.IsotopeNumber.ToString();
                            model.ShowSymbol = atom.ShowSymbol;
                        }

                        if (atom.Element is FunctionalGroup)
                        {
                            model.IsElement         = false;
                            model.IsFunctionalGroup = true;
                        }

                        model.MicroModel = new Model();

                        Molecule m = new Molecule();
                        model.MicroModel.AddMolecule(m);
                        m.Parent = model.MicroModel;

                        Atom a = new Atom();
                        a.Element       = atom.Element;
                        a.Position      = atom.Position;
                        a.FormalCharge  = atom.FormalCharge;
                        a.IsotopeNumber = atom.IsotopeNumber;
                        m.AddAtom(a);
                        a.Parent = m;

                        foreach (var bond in atom.Bonds)
                        {
                            Atom ac = new Atom();
                            ac.Element    = Globals.PeriodicTable.C;
                            ac.ShowSymbol = false;
                            ac.Position   = bond.OtherAtom(atom).Position;
                            m.AddAtom(ac);
                            ac.Parent = m;
                            Bond b = new Bond(a, ac);
                            b.Order = bond.Order;
                            if (bond.Stereo != Globals.BondStereo.None)
                            {
                                b.Stereo = bond.Stereo;
                                if (bond.Stereo == Globals.BondStereo.Wedge || bond.Stereo == Globals.BondStereo.Hatch)
                                {
                                    if (atom.Path.Equals(bond.StartAtom.Path))
                                    {
                                        b.StartAtomInternalId = a.InternalId;
                                        b.EndAtomInternalId   = ac.InternalId;
                                    }
                                    else
                                    {
                                        b.StartAtomInternalId = ac.InternalId;
                                        b.EndAtomInternalId   = a.InternalId;
                                    }
                                }
                            }
                            m.AddBond(b);
                            b.Parent = m;
                        }
                        model.MicroModel.ScaleToAverageBondLength(20);

                        var pe = new AtomPropertyEditor(model);
                        ShowDialog(pe, currentEditor);
                        Application.Current.ShutdownMode = mode;

                        if (model.Save)
                        {
                            evm.UpdateAtom(atom, model);

                            evm.ClearSelection();
                            evm.AddToSelection(atom);

                            if (model.AddedElement != null)
                            {
                                AddOptionIfNeeded(model);
                            }
                            evm.SelectedElement = model.Element;
                        }
                    }

                    // Did RightClick occur on a BondVisual?
                    if (activeVisual is BondVisual bv)
                    {
                        var mode = Application.Current.ShutdownMode;

                        Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;

                        var bond  = bv.ParentBond;
                        var model = new BondPropertiesModel
                        {
                            Centre         = screenPosition,
                            Path           = bond.Path,
                            Angle          = bond.Angle,
                            BondOrderValue = bond.OrderValue.Value,
                            IsSingle       = bond.Order.Equals(Globals.OrderSingle),
                            IsDouble       = bond.Order.Equals(Globals.OrderDouble),
                            Is1Point5      = bond.Order.Equals(Globals.OrderPartial12),
                            Is2Point5      = bond.Order.Equals(Globals.OrderPartial23)
                        };

                        model.DoubleBondChoice = DoubleBondType.Auto;

                        if (model.IsDouble | model.Is1Point5 | model.Is2Point5)
                        {
                            if (bond.ExplicitPlacement != null)
                            {
                                model.DoubleBondChoice = (DoubleBondType)bond.ExplicitPlacement.Value;
                            }
                            else
                            {
                                if (model.IsDouble)
                                {
                                    if (bond.Stereo == Globals.BondStereo.Indeterminate)
                                    {
                                        model.DoubleBondChoice = DoubleBondType.Indeterminate;
                                    }
                                }
                            }
                        }

                        if (model.IsSingle)
                        {
                            model.SingleBondChoice = SingleBondType.None;

                            switch (bond.Stereo)
                            {
                            case Globals.BondStereo.Wedge:
                                model.SingleBondChoice = SingleBondType.Wedge;
                                break;

                            case Globals.BondStereo.Hatch:
                                model.SingleBondChoice = SingleBondType.Hatch;
                                break;

                            case Globals.BondStereo.Indeterminate:
                                model.SingleBondChoice = SingleBondType.Indeterminate;
                                break;

                            default:
                                model.SingleBondChoice = SingleBondType.None;
                                break;
                            }
                        }

                        var pe = new BondPropertyEditor(model);
                        ShowDialog(pe, currentEditor);
                        Application.Current.ShutdownMode = mode;

                        if (model.Save)
                        {
                            evm.UpdateBond(bond, model);
                            evm.ClearSelection();

                            bond.Order = Globals.OrderValueToOrder(model.BondOrderValue);
                            evm.AddToSelection(bond);
                        }
                    }
                }
            }

            void AddOptionIfNeeded(AtomPropertiesModel model)
            {
                if (!evm.AtomOptions.Any(ao => ao.Element.Symbol == model.AddedElement.Symbol))
                {
                    AtomOption newOption = null;
                    switch (model.AddedElement)
                    {
                    case Element elem:
                        newOption = new AtomOption(elem);
                        break;

                    case FunctionalGroup group:
                        newOption = new AtomOption(group);
                        break;
                    }
                    evm.AtomOptions.Add(newOption);
                }
            }
        }
Пример #17
0
        static void Main()
        {
            var c1 = new AtomNode("C");
            var c2 = new AtomNode("P");
            var c3 = new AtomNode("O");
            var c4 = new AtomNode("N");
            var c5 = new AtomNode("F");
            var c6 = new AtomNode("I");
            var c7 = new AtomNode("K");
            var c8 = new AtomNode("V");

            var mole = new Molecule(c1);

            mole.AddBond(BondOrder.Single, c1, c5);
            mole.AddBond(BondOrder.Single, c1, c2);
            mole.AddBond(BondOrder.Single, c1, c4);
            mole.AddBond(BondOrder.Single, c2, c3);
            mole.AddBond(BondOrder.Single, c2, c6);
            mole.AddBond(BondOrder.Single, c3, c4);
            mole.AddBond(BondOrder.Single, c3, c7);
            mole.AddBond(BondOrder.Single, c4, c8);
            mole.AddBond(BondOrder.Single, c5, c6);
            mole.AddBond(BondOrder.Single, c5, c8);
            mole.AddBond(BondOrder.Single, c6, c7);
            mole.AddBond(BondOrder.Single, c7, c8);

            /*var o0 = new AtomNode("O");
             * var o1 = new AtomNode("O");
             * var cb0 = new AtomNode("C");
             * var cb1 = new AtomNode("C");
             *
             * mole.AddBond(BondOrder.Single, c1, o0);
             * mole.AddBondToLast(BondOrder.Single,cb0);
             * mole.AddBondToLast(BondOrder.Single, cb1);
             * mole.AddBondToLast(BondOrder.Single, o1);
             * mole.AddBond(BondOrder.Single, o1, c2);
             *
             * /*mole.AddBond(BondOrder.Single, c1, o0);
             * mole.AddBondToLast(BondOrder.Single, cb0);
             * mole.AddBondToLast(BondOrder.Single, cb1);
             * mole.AddBondToLast(BondOrder.Single, o1);
             * mole.AddBondToLast(BondOrder.Single, o0);*/

            var smiles = mole.ToSMILES();

            /*var cy = mole.CyclePrint();
             *
             * foreach (var y in cy)
             * {
             *  Console.Write("\n" + Convert.ToString(y.Key) + ": ");
             *  foreach (var z in y.Value)
             *      Console.Write(z.Element.Symbol + "  ");
             * }*/

            Console.WriteLine(smiles);

            var prq = new PugRestQuery(smiles);

            try
            {
                var response    = prq.GetStringFromSmiles().Result;
                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(response);
                var c = xmlDocument.DocumentElement.FirstChild.ChildNodes;
                foreach (XmlNode x in c)
                {
                    if (x.Name == "CID")
                    {
                        continue;
                    }
                    Console.WriteLine(x.Name + ": " + x.InnerText);
                }
            }
            catch (System.Net.Http.HttpRequestException e)
            {
                Console.WriteLine(e.HResult);
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
Пример #18
0
        internal static Molecule ReadXML(FileStream istr)
        {
            Molecule mol = new Molecule();

            const string NAMESPACE   = "http://www.xml-cml.org/schema/cml2/core";
            const string ATTRIBUTENS = "";
            XmlDocument  xmlDoc      = new XmlDocument();

            xmlDoc.Load(istr);

            XPathNavigator navigator = xmlDoc.CreateNavigator();

            if (navigator.MoveToFirstChild())
            {
                navigator.MoveToChild("molecule", NAMESPACE);
                //navigator.MoveToFirstChild();

                if (navigator.MoveToChild("atomArray", NAMESPACE))
                {
                    if (navigator.MoveToChild("atom", NAMESPACE))
                    {
                        do
                        {
                            string elementType = navigator.GetAttribute("elementType", ATTRIBUTENS);

                            string x2String = navigator.GetAttribute("x2", ATTRIBUTENS);
                            if (!string.IsNullOrEmpty(x2String))
                            {
                                double x2            = Utility.SafeDouble(x2String);
                                double y2            = Utility.SafeDouble(navigator.GetAttribute("y2", ATTRIBUTENS));
                                int    hydrogenCount = Utility.SafeInt(navigator.GetAttribute("hydrogenCount", ATTRIBUTENS));

                                // TODO: How do we handle hydrogen count?
                                mol.AddAtom(elementType, x2, y2);
                            }
                            else
                            {
                                double x3            = Utility.SafeDouble(navigator.GetAttribute("x3", ATTRIBUTENS));
                                double y3            = Utility.SafeDouble(navigator.GetAttribute("y3", ATTRIBUTENS));
                                int    hydrogenCount = Utility.SafeInt(navigator.GetAttribute("hydrogenCount", ATTRIBUTENS));

                                // TODO: How do we handle hydrogen count?
                                mol.AddAtom(elementType, x3, y3);
                            }
                        } while (navigator.MoveToNext("atom", NAMESPACE));

                        navigator.MoveToParent();
                    }

                    navigator.MoveToParent();
                }
                if (navigator.MoveToChild("bondArray", NAMESPACE))
                {
                    if (navigator.MoveToChild("bond", NAMESPACE))
                    {
                        do
                        {
                            string   atomRefs = navigator.GetAttribute("atomRefs2", ATTRIBUTENS);
                            string[] parts    = atomRefs.Split(' ');

                            if (parts.Length == 2)
                            {
                                int from  = Utility.SafeInt(parts[0].Substring(1));
                                int to    = Utility.SafeInt(parts[1].Substring(1));
                                int order = Utility.SafeInt(navigator.GetAttribute("order", ATTRIBUTENS));
                                int type  = 0; // Where or is type stored?

                                // TODO: How do we handle hydrogen count?
                                mol.AddBond(from, to, order, type);
                            }
                        } while (navigator.MoveToNext("bond", NAMESPACE));

                        navigator.MoveToParent();
                    }

                    navigator.MoveToParent();
                }
            }

            return(mol);
        }
Пример #19
0
        public static Molecule ReadMDLMOL(StreamReader in_Renamed)
        {
            Molecule mol = new Molecule();

            //UPGRADE_NOTE: Final was removed from the declaration of 'GENERIC_ERROR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'"
            System.String GENERIC_ERROR = "Invalid MDL MOL file.";

            try
            {
                System.String line = null;
                for (int n = 0; n < 4; n++)
                {
                    line = in_Renamed.ReadLine();
                }
                if (line == null || !line.Substring(34, (39) - (34)).Equals("V2000"))
                {
                    throw new System.IO.IOException(GENERIC_ERROR);
                }
                int numAtoms = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim());
                int numBonds = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim());

                for (int n = 0; n < numAtoms; n++)
                {
                    line = in_Renamed.ReadLine();

                    double        x = System.Double.Parse(line.Substring(0, (10) - (0)).Trim());
                    double        y = System.Double.Parse(line.Substring(10, (20) - (10)).Trim());
                    System.String el = line.Substring(31, (33) - (31)).Trim();
                    int           chg = System.Int32.Parse(line.Substring(36, (39) - (36)).Trim()), rad = 0;

                    if (chg <= 3)
                    {
                    }
                    else if (chg == 4)
                    {
                        chg = 0; rad = 2;
                    }
                    else
                    {
                        chg = 4 - chg;
                    }

                    mol.AddAtom(el, x, y, chg, rad);
                }
                for (int n = 0; n < numBonds; n++)
                {
                    line = in_Renamed.ReadLine();

                    int from = System.Int32.Parse(line.Substring(0, (3) - (0)).Trim()), to = System.Int32.Parse(line.Substring(3, (6) - (3)).Trim());
                    int type = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim()), stereo = System.Int32.Parse(line.Substring(9, (12) - (9)).Trim());

                    if (from == to || from < 1 || from > numAtoms || to < 1 || to > numAtoms)
                    {
                        throw new System.IO.IOException(GENERIC_ERROR);
                    }

                    int order = type >= 1 && type <= 3?type:1;
                    int style = Molecule.BONDTYPE_NORMAL;
                    if (stereo == 1)
                    {
                        style = Molecule.BONDTYPE_INCLINED;
                    }
                    else if (stereo == 6)
                    {
                        style = Molecule.BONDTYPE_DECLINED;
                    }
                    else if (stereo == 3 || stereo == 4)
                    {
                        style = Molecule.BONDTYPE_UNKNOWN;
                    }

                    mol.AddBond(from, to, order, style);
                }
                while (true)
                {
                    line = in_Renamed.ReadLine();
                    if (line.StartsWith("M  END"))
                    {
                        break;
                    }

                    int type = 0;
                    if (line.StartsWith("M  CHG"))
                    {
                        type = 1;
                    }
                    else if (line.StartsWith("M  RAD"))
                    {
                        type = 2;
                    }
                    if (type > 0)
                    {
                        int len = System.Int32.Parse(line.Substring(6, (9) - (6)).Trim());
                        for (int n = 0; n < len; n++)
                        {
                            int apos = System.Int32.Parse(line.Substring(9 + 8 * n, (13 + 8 * n) - (9 + 8 * n)).Trim());
                            int aval = System.Int32.Parse(line.Substring(13 + 8 * n, (17 + 8 * n) - (13 + 8 * n)).Trim());
                            if (type == 1)
                            {
                                mol.SetAtomCharge(apos, aval);
                            }
                            else
                            {
                                mol.SetAtomUnpaired(apos, aval);
                            }
                        }
                    }
                }
            }
            catch (System.Exception)
            {
                throw new System.IO.IOException(GENERIC_ERROR);
            }


            return(mol);
        }
Пример #20
0
        private static void AddMolecule(dynamic data, Model newModel)
        {
            Dictionary <int, string> atoms = new Dictionary <int, string>();
            var         newMol             = new Molecule();
            ElementBase ce        = Globals.PeriodicTable.C;
            int         atomCount = 0;

            // GitHub: Issue #13 https://github.com/Chem4Word/Version3/issues/13
            if (data.a != null)
            {
                foreach (AtomJSON a in data.a)
                {
                    if (!string.IsNullOrEmpty(a.l))
                    {
                        ElementBase eb;
                        var         ok = AtomHelpers.TryParse(a.l, out eb);
                        if (ok)
                        {
                            if (eb is Element element)
                            {
                                ce = element;
                            }

                            if (eb is FunctionalGroup functionalGroup)
                            {
                                ce = functionalGroup;
                            }
                        }
                    }
                    else
                    {
                        ce = Globals.PeriodicTable.C;
                    }

                    Atom atom = new Atom()
                    {
                        Element  = ce,
                        Position = new Point(a.x, a.y)
                    };

                    if (a.c != null)
                    {
                        atom.FormalCharge = a.c.Value;
                    }

                    atoms.Add(atomCount++, atom.InternalId);
                    newMol.AddAtom(atom);
                    atom.Parent = newMol;
                }
            }

            if (data.b != null)
            {
                foreach (BondJSON b in data.b)
                {
                    string o;
                    if (b.o != null)
                    {
                        o = Globals.OrderValueToOrder(double.Parse(b.o.ToString()));
                    }
                    else
                    {
                        o = Globals.OrderSingle;
                    }

                    Globals.BondStereo s;
                    if (!string.IsNullOrEmpty(b.s))
                    {
                        if (o == Globals.OrderDouble)
                        {
                            if (b.s.Equals(Ambiguous))
                            {
                                s = Globals.BondStereo.Indeterminate;
                            }
                            else
                            {
                                s = Globals.BondStereo.None;
                            }
                        }
                        else
                        {
                            if (b.s.Equals(Recessed))
                            {
                                s = Globals.BondStereo.Hatch;
                            }
                            else if (b.s.Equals(Protruding))
                            {
                                s = Globals.BondStereo.Wedge;
                            }
                            else if (b.s.Equals(Ambiguous))
                            {
                                s = Globals.BondStereo.Indeterminate;
                            }
                            else
                            {
                                s = Globals.BondStereo.None;
                            }
                        }
                    }
                    else
                    {
                        s = Globals.BondStereo.None;
                    }

                    // Azure DevOps #715
                    if (b.b.HasValue && b.b.Value < atoms.Count && b.e.HasValue && b.e.Value < atoms.Count)
                    {
                        var  sa      = atoms[b.b.Value];
                        var  ea      = atoms[b.e.Value];
                        Bond newBond = new Bond()
                        {
                            StartAtomInternalId = sa,
                            EndAtomInternalId   = ea,
                            Stereo = s,
                            Order  = o
                        };
                        newMol.AddBond(newBond);
                        newBond.Parent = newMol;
                    }
                }
            }

            newModel.AddMolecule(newMol);
            newMol.Parent = newModel;
        }
Пример #21
0
        public void CheckClone()
        {
            Model model = new Model();

            Molecule molecule = new Molecule();

            molecule.Id = "m1";
            model.AddMolecule(molecule);
            molecule.Parent = model;

            Atom startAtom = new Atom();

            startAtom.Id       = "a1";
            startAtom.Element  = Globals.PeriodicTable.C;
            startAtom.Position = new Point(5, 5);
            molecule.AddAtom(startAtom);
            startAtom.Parent = molecule;

            Atom endAtom = new Atom();

            endAtom.Id       = "a2";
            endAtom.Element  = Globals.PeriodicTable.C;
            endAtom.Position = new Point(10, 10);
            molecule.AddAtom(endAtom);
            endAtom.Parent = molecule;

            Bond bond = new Bond(startAtom, endAtom);

            bond.Id    = "b1";
            bond.Order = Globals.OrderSingle;
            molecule.AddBond(bond);
            bond.Parent = molecule;

            Assert.True(model.Molecules.Count == 1, $"Expected 1 Molecule; Got {model.Molecules.Count}");

            var a1 = model.Molecules.Values.First().Atoms.Values.First();

            Assert.True(Math.Abs(a1.Position.X - 5.0) < 0.001, $"Expected a1.X = 5; Got {a1.Position.X}");
            Assert.True(Math.Abs(a1.Position.Y - 5.0) < 0.001, $"Expected a1.Y = 5; Got {a1.Position.Y}");

            Model clone = model.Copy();

            Assert.True(model.Molecules.Count == 1, $"Expected 1 Molecule; Got {model.Molecules.Count}");
            Assert.True(clone.Molecules.Count == 1, $"Expected 1 Molecule; Got {clone.Molecules.Count}");

            var a2 = clone.Molecules.Values.First().Atoms.Values.First();

            Assert.True(Math.Abs(a2.Position.X - 5.0) < 0.001, $"Expected a2.X = 5; Got {a2.Position.X}");
            Assert.True(Math.Abs(a2.Position.Y - 5.0) < 0.001, $"Expected a2.Y = 5; Got {a2.Position.Y}");

            clone.ScaleToAverageBondLength(5);

            var a3 = model.Molecules.Values.First().Atoms.Values.First();

            Assert.True(Math.Abs(a3.Position.X - 5.0) < 0.001, $"Expected a3.X = 5; Got {a3.Position.X}");
            Assert.True(Math.Abs(a3.Position.Y - 5.0) < 0.001, $"Expected a3.Y = 5; Got {a3.Position.Y}");

            var a4 = clone.Molecules.Values.First().Atoms.Values.First();

            Assert.True(Math.Abs(a4.Position.X - 3.535) < 0.001, $"Expected a4.X = 3.535; Got {a4.Position.X}");
            Assert.True(Math.Abs(a4.Position.Y - 3.535) < 0.001, $"Expected a4.Y = 3.535; Got {a4.Position.Y}");
        }
Пример #22
0
 public override object VisitBranched_atom([NotNull] smilesParser.Branched_atomContext context)
 {
     foreach (IParseTree tree in context.children)
     {
         if (typeof(smilesParser.AtomContext).IsAssignableFrom(tree.GetType()))
         {
             Atom current = (Atom)VisitAtom((smilesParser.AtomContext)tree);
             if (current.Element != ELEMENTS.H)
             {
                 retVal.AddAtom(current);
                 if (addExplicitHToNext)
                 {
                     current.ExplicitHydrogens++;
                     addExplicitHToNext = false;
                 }
                 if (last != null)
                 {
                     if (last.AtomType == AtomType.AROMATIC && current.AtomType == AtomType.AROMATIC)
                     {
                         nextBond = BondType.Aromatic;
                     }
                 }
                 Bond b = retVal.AddBond(last, current, nextBond, BondStereo.NotStereoOrUseXYZ, BondTopology.Either, BondReactingCenterStatus.Unmarked);
                 if (!string.IsNullOrEmpty(cisTrans) && nextBond == BondType.Double)
                 {
                     doubleBonds.Add(b);
                 }
                 nextBond = BondType.Single;
                 last     = current;
             }
             else
             {
                 if (last != null)
                 {
                     last.ExplicitHydrogens++;
                 }
                 else
                 {
                     addExplicitHToNext = true;
                 }
             }
         }
         else if (typeof(smilesParser.RingbondContext).IsAssignableFrom(tree.GetType()))
         {
             int ring = (int)VisitRingbond((smilesParser.RingbondContext)tree);
             if (ringAtoms.ContainsKey(ring))
             {
                 BondType nextType = (BondType)ringbonds[ring];
                 if (nextType != BondType.Single && (nextBond == BondType.Single || nextBond == nextType))
                 {
                     nextBond = nextType;
                 }
                 Bond b = retVal.AddBond(last, (Atom)ringAtoms[ring], nextBond, BondStereo.NotStereoOrUseXYZ, BondTopology.Either, BondReactingCenterStatus.Unmarked);
                 if (!string.IsNullOrEmpty(cisTrans) && nextBond == BondType.Double)
                 {
                     doubleBonds.Add(b);
                 }
                 nextBond = BondType.Single;
                 ringAtoms.Remove(ring);
                 ringbonds.Remove(ring);
             }
             else
             {
                 ringAtoms.Add(ring, last);
                 ringbonds.Add(ring, nextBond);
                 nextBond = BondType.Single;
             }
         }
         else if (typeof(smilesParser.BranchContext).IsAssignableFrom(tree.GetType()))
         {
             Atom temp = last;
             VisitBranch((smilesParser.BranchContext)tree);
             last = temp;
         }
         else if (typeof(smilesParser.BondContext).IsAssignableFrom(tree.GetType()))
         {
             nextBond = (BondType)VisitBond((smilesParser.BondContext)context.GetChild(1));
         }
         else
         {
             throw new System.InvalidOperationException("uhoh");
         }
     }
     return(null);
 }
Пример #23
0
        public static Molecule GetMolecule(XElement cmlElement)
        {
            Molecule molecule = new Molecule();

            string showBracketsValue = cmlElement.Attribute(CMLNamespaces.c4w + CMLConstants.AttributeShowMoleculeBrackets)?.Value;

            if (!string.IsNullOrEmpty(showBracketsValue))
            {
                molecule.ShowMoleculeBrackets = bool.Parse(showBracketsValue);
            }

            string idValue = cmlElement.Attribute(CMLConstants.AttributeId)?.Value;

            if (!string.IsNullOrEmpty(idValue))
            {
                molecule.Id = idValue;
            }

            string countValue = cmlElement.Attribute(CMLConstants.AttributeCount)?.Value;

            if (!string.IsNullOrEmpty(countValue))
            {
                molecule.Count = int.Parse(countValue);
            }

            string chargeValue = cmlElement.Attribute(CMLConstants.AttributeFormalCharge)?.Value;

            if (!string.IsNullOrEmpty(chargeValue))
            {
                molecule.FormalCharge = int.Parse(chargeValue);
            }

            string spinValue = cmlElement.Attribute(CMLConstants.AttributeSpinMultiplicity)?.Value;

            if (!string.IsNullOrEmpty(spinValue))
            {
                molecule.SpinMultiplicity = int.Parse(spinValue);
            }

            molecule.Errors   = new List <string>();
            molecule.Warnings = new List <string>();

            List <XElement> childMolecules = CMLHelper.GetMolecules(cmlElement);

            List <XElement> atomElements    = CMLHelper.GetAtoms(cmlElement);
            List <XElement> bondElements    = CMLHelper.GetBonds(cmlElement);
            List <XElement> nameElements    = CMLHelper.GetNames(cmlElement);
            List <XElement> formulaElements = CMLHelper.GetFormulas(cmlElement);
            List <XElement> labelElements   = CMLHelper.GetLabels(cmlElement);

            foreach (XElement childElement in childMolecules)
            {
                Molecule newMol = GetMolecule(childElement);
                molecule.AddMolecule(newMol);
                newMol.Parent = molecule;
            }

            Dictionary <string, string> reverseAtomLookup = new Dictionary <string, string>();

            foreach (XElement atomElement in atomElements)
            {
                Atom newAtom = GetAtom(atomElement);
                if (newAtom.Messages.Count > 0)
                {
                    molecule.Errors.AddRange(newAtom.Messages);
                }

                molecule.AddAtom(newAtom);
                reverseAtomLookup[newAtom.Id] = newAtom.InternalId;
                newAtom.Parent = molecule;
            }

            foreach (XElement bondElement in bondElements)
            {
                Bond newBond = GetBond(bondElement, reverseAtomLookup);

                if (newBond.Messages.Count > 0)
                {
                    molecule.Errors.AddRange(newBond.Messages);
                }

                molecule.AddBond(newBond);
                newBond.Parent = molecule;
            }

            foreach (XElement formulaElement in formulaElements)
            {
                var formula = GetFormula(formulaElement);
                if (formula.IsValid)
                {
                    molecule.Formulas.Add(formula);
                }
            }

            foreach (XElement nameElement in nameElements)
            {
                var name = GetName(nameElement);
                if (name.IsValid)
                {
                    molecule.Names.Add(name);
                }
            }

            Molecule copy = molecule.Copy();

            copy.SplitIntoChildren();

            // If copy now contains (child) molecules, replace original
            if (copy.Molecules.Count > 1)
            {
                molecule = copy;
            }

            foreach (var labelElement in labelElements)
            {
                var label = GetLabel(labelElement);
                if (label.IsValid)
                {
                    molecule.Labels.Add(label);
                }
            }

            // Fix Invalid data; If only one atom
            if (molecule.Atoms.Count == 1)
            {
                // Remove ExplicitC flag
                molecule.Atoms.First().Value.ExplicitC = null;

                // Remove invalid molecule properties
                molecule.ShowMoleculeBrackets = false;
                molecule.SpinMultiplicity     = null;
                molecule.FormalCharge         = null;
                molecule.Count = null;
            }

            molecule.RebuildRings();

            return(molecule);
        }