Пример #1
0
        private void HandleDataContextChanged()
        {
            ChemistryModel chemistryModel = null;

            if (Chemistry is string)
            {
                var data = Chemistry as string;
                if (!string.IsNullOrEmpty(data))
                {
                    if (data.StartsWith("<"))
                    {
                        var conv = new CMLConverter();
                        chemistryModel = conv.Import(data);
                    }
                    if (data.Contains("M  END"))
                    {
                        var conv = new SdFileConverter();
                        chemistryModel = conv.Import(data);
                    }
                }
            }
            else
            {
                if (Chemistry != null && !(Chemistry is ChemistryModel))
                {
                    throw new ArgumentException("Object must be of type 'Chem4Word.Model.Model'.");
                }
                chemistryModel = Chemistry as ChemistryModel;
            }

            if (chemistryModel != null)
            {
                if (chemistryModel.AllAtoms.Count > 0)
                {
                    chemistryModel.RescaleForXaml(Constants.StandardBondLength * 2);

                    Debug.WriteLine($"Ring count == {chemistryModel.Molecules.SelectMany(m => m.Rings).Count()}");

                    if (ShowCarbonLabels)
                    {
                        foreach (var atom in chemistryModel.AllAtoms)
                        {
                            if (atom.Element.Equals(Globals.PeriodicTable.C))
                            {
                                atom.ShowSymbol = true;
                            }
                        }
                    }
                    Placeholder.DataContext = chemistryModel;
                }
                else
                {
                    Placeholder.DataContext = null;
                }
            }
            else
            {
                Placeholder.DataContext = null;
            }
        }
Пример #2
0
        public void SdfImportBasicParafuchsin()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("BasicParafuchsin.txt"));

            // Basic sanity checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");

            var mol = m.Molecules.Values.First();

            Assert.True(mol.Molecules.Count == 2,
                        $"Expected 2 Child Molecules; Got {mol.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 41, $"Expected 41 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 42, $"Expected 42 Bonds; Got {m.TotalBondsCount}");

            // Check that we got three rings
            var mol2 = mol.Molecules.Values.Skip(1).First();

            Assert.True(mol2.Rings.Count == 3,
                        $"Expected 3 Rings; Got {mol2.Rings.Count}");

            string molstring = mc.Export(m);

            mc = new SdFileConverter();
            Model m2 = mc.Import(molstring);
        }
Пример #3
0
        private void ExportAs_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lastModel != null)
            {
                string result = string.Empty;

                switch (ExportAs.SelectedIndex)
                {
                case 1:
                    var cmlConverter = new CMLConverter();
                    result = cmlConverter.Export(lastModel);
                    break;

                case 2:
                    var sdFileConverter = new SdFileConverter();
                    result = sdFileConverter.Export(lastModel);
                    break;

                case 3:
                    var jsonConverter = new JSONConverter();
                    result = jsonConverter.Export(lastModel);
                    break;
                }

                if (!string.IsNullOrEmpty(result))
                {
                    //Clipboard.SetText(result);
                    //MessageBox.Show("Last loaded model exported to clipboard as CML");
                    textBox1.Text = result + Environment.NewLine;
                }
            }
            ExportAs.SelectedIndex = 0;
            LoadStructure.Focus();
        }
Пример #4
0
        private void UpdateDisplay()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            ErrorsAndWarnings.Text = "";

            using (new WaitCursor())
            {
                var tag = ResultsListView.SelectedItems[0]?.Tag;

                if (tag is LiteEntity le && !string.IsNullOrEmpty(le.chebiId))
                {
                    ChebiId = le.chebiId;
                    var chemStructure = GetChemStructure(le);

                    if (!string.IsNullOrEmpty(chemStructure))
                    {
                        _lastMolfile = ConvertToWindows(chemStructure);

                        SdFileConverter sdConverter = new SdFileConverter();
                        _lastModel = sdConverter.Import(chemStructure);
                        if (_lastModel.AllWarnings.Count > 0 || _lastModel.AllErrors.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", chemStructure);
                            List <string> lines = new List <string>();
                            if (_lastModel.AllErrors.Count > 0)
                            {
                                Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllErrors));
                                lines.Add("Errors(s)");
                                lines.AddRange(_lastModel.AllErrors);
                            }
                            if (_lastModel.AllWarnings.Count > 0)
                            {
                                Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllWarnings));
                                lines.Add("Warnings(s)");
                                lines.AddRange(_lastModel.AllWarnings);
                            }
                            ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                        }
                        if (_lastModel.MeanBondLength < Core.Helpers.Constants.MinimumBondLength - Core.Helpers.Constants.BondLengthTolerance ||
                            _lastModel.MeanBondLength > Core.Helpers.Constants.MaximumBondLength + Core.Helpers.Constants.BondLengthTolerance)
                        {
                            _lastModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                        }
                        display1.Chemistry = _lastModel;
                    }
                    else
                    {
                        _lastModel             = null;
                        _lastMolfile           = String.Empty;
                        display1.Chemistry     = null;
                        ErrorsAndWarnings.Text = "No structure available.";
                    }

                    EnableImport();
                }
            }
        }
Пример #5
0
        private void SaveStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                CMLConverter cmlConverter = new CMLConverter();
                Model        m            = cmlConverter.Import(_lastCml);
                m.CustomXmlPartGuid = "";

                string filter = "CML molecule files (*.cml, *.xml)|*.cml;*.xml|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf";
                using (SaveFileDialog sfd = new SaveFileDialog {
                    Filter = filter
                })
                {
                    DialogResult dr = sfd.ShowDialog();
                    if (dr == DialogResult.OK)
                    {
                        FileInfo fi = new FileInfo(sfd.FileName);
                        _telemetry.Write(module, "Information", $"Exporting to '{fi.Name}'");
                        string fileType = Path.GetExtension(sfd.FileName).ToLower();
                        switch (fileType)
                        {
                        case ".cml":
                        case ".xml":
                            string temp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                                          + Environment.NewLine
                                          + cmlConverter.Export(m);
                            File.WriteAllText(sfd.FileName, temp);
                            break;

                        case ".mol":
                        case ".sdf":
                            // https://www.chemaxon.com/marvin-archive/6.0.2/marvin/help/formats/mol-csmol-doc.html
                            double before = m.MeanBondLength;
                            // Set bond length to 1.54 angstroms (Å)
                            m.ScaleToAverageBondLength(1.54);
                            double after = m.MeanBondLength;
                            _telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                            SdFileConverter converter = new SdFileConverter();
                            File.WriteAllText(sfd.FileName, converter.Export(m));
                            break;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }
Пример #6
0
        private void HandleDataContextChanged()
        {
            Model chemistryModel = null;

            if (Chemistry is string)
            {
                var data = Chemistry as string;
                if (!string.IsNullOrEmpty(data))
                {
                    if (data.StartsWith("<"))
                    {
                        var conv = new CMLConverter();
                        chemistryModel = conv.Import(data);
                        chemistryModel.EnsureBondLength(20, false);
                    }
                    if (data.Contains("M  END"))
                    {
                        var conv = new SdFileConverter();
                        chemistryModel = conv.Import(data);
                        chemistryModel.EnsureBondLength(20, false);
                    }
                }
            }
            else
            {
                if (Chemistry != null && !(Chemistry is Model))
                {
                    Debugger.Break();
                    throw new ArgumentException($"Object must be of type {nameof(Model)}.");
                }
                chemistryModel = Chemistry as Model;
                if (chemistryModel != null)
                {
                    chemistryModel.EnsureBondLength(20, false);
                }
            }

            //assuming we've got this far, we should have something we can draw
            if (chemistryModel != null)
            {
                if (chemistryModel.TotalAtomsCount > 0)
                {
                    chemistryModel.RescaleForXaml(true, Constants.StandardBondLength);

                    CurrentViewModel = new ViewModel(chemistryModel);
                    CurrentViewModel.SetTextParams(chemistryModel.XamlBondLength);
                    DrawChemistry(CurrentViewModel);
                }
            }
        }
Пример #7
0
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("All molecule files (*.mol, *.sdf, *.cml)|*.mol;*.sdf;*.cml");
            sb.Append("|CML molecule files (*.cml)|*.cml");
            sb.Append("|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf");

            openFileDialog1.FileName = "*.*";
            openFileDialog1.Filter   = sb.ToString();

            DialogResult dr = openFileDialog1.ShowDialog();

            if (dr == DialogResult.OK)
            {
                string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower();
                string filename = Path.GetFileName(openFileDialog1.FileName);
                string mol      = File.ReadAllText(openFileDialog1.FileName);
                string cml      = "";

                CMLConverter    cmlConvertor    = new CMLConverter();
                SdFileConverter sdFileConverter = new SdFileConverter();
                Model           model           = null;

                switch (fileType)
                {
                case ".mol":
                case ".sdf":
                    model = sdFileConverter.Import(mol);
                    model.RefreshMolecules();
                    model.Relabel();
                    cml = cmlConvertor.Export(model);
                    //model.DumpModel("After Import");

                    break;

                case ".cml":
                case ".xml":
                    model = cmlConvertor.Import(mol);
                    model.RefreshMolecules();
                    model.Relabel();
                    cml = cmlConvertor.Export(model);
                    break;
                }

                this.Text = filename;
                this.display1.Chemistry = cml;
            }
        }
Пример #8
0
        private void UpdateDisplay()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            ErrorsAndWarnings.Text = "";

            using (new WaitCursor())
            {
                var tag = ResultsListView.SelectedItems[0]?.Tag;

                LiteEntity le            = (LiteEntity)tag;
                var        chemStructure = GetChemStructure(le);

                if (!string.IsNullOrEmpty(chemStructure))
                {
                    _lastMolfile = ConvertToWindows(chemStructure);

                    SdFileConverter sdConverter = new SdFileConverter();
                    _lastModel = sdConverter.Import(chemStructure);
                    if (_lastModel.AllWarnings.Count > 0 || _lastModel.AllErrors.Count > 0)
                    {
                        Telemetry.Write(module, "Exception(Data)", chemStructure);
                        List <string> lines = new List <string>();
                        if (_lastModel.AllErrors.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllErrors));
                            lines.Add("Errors(s)");
                            lines.AddRange(_lastModel.AllErrors);
                        }
                        if (_lastModel.AllWarnings.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllWarnings));
                            lines.Add("Warnings(s)");
                            lines.AddRange(_lastModel.AllWarnings);
                        }
                        ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                    }
                    ChebiId = le.chebiId;
                    flexDisplayControl1.Chemistry = _lastModel;
                }
                else
                {
                    flexDisplayControl1.Chemistry = null;
                    ErrorsAndWarnings.Text        = "No structure available.";
                }

                EnableImport();
            }
        }
Пример #9
0
        public override void Execute(object parameter)
        {
            CMLConverter    cmlConverter = new CMLConverter();
            SdFileConverter sdfConverter = new SdFileConverter();

            if (Clipboard.ContainsData(Globals.FormatCML))
            {
                string pastedCML = (string)Clipboard.GetData(Globals.FormatCML);
                EditViewModel.PasteCML(pastedCML);
            }
            else if (Clipboard.ContainsText())
            {
                bool   failedCML  = false;
                bool   failedSDF  = false;
                string pastedText = Clipboard.GetText();
                Model  buffer     = null;
                //try to convert the pasted text with the CML converter first
                try
                {
                    buffer = cmlConverter.Import(pastedText);
                }
                catch
                {
                    failedCML = true;
                }

                if (failedCML)
                {
                    buffer    = sdfConverter.Import(pastedText);
                    failedSDF = buffer.GeneralErrors.Any();
                }

                if (failedCML & failedSDF)
                {
                    if (buffer.GeneralErrors.Any())
                    {
                        Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: " + buffer.GeneralErrors[0]);
                    }
                    else
                    {
                        Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: unknown error.");
                    }
                }
                else
                {
                    EditViewModel.PasteModel(buffer);
                }
            }
        }
Пример #10
0
        public void SdfImportBenzene()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("Benzene.txt"));

            // Basic sanity checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 6, $"Expected 6 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 6, $"Expected 6 Bonds; Got {m.TotalBondsCount}");

            // Check that names and formulae have not been trashed
            Assert.True(m.Molecules.Values.First().Names.Count == 2, $"Expected 2 Chemical Names; Got {m.Molecules.Values.First().Names.Count}");
            Assert.True(m.Molecules.Values.First().Formulas.Count == 2, $"Expected 2 Formulae; Got {m.Molecules.Values.First().Formulas.Count }");

            // Check that we have one ring
            Assert.True(m.Molecules.Values.First().Rings.Count == 1, $"Expected 1 Ring; Got {m.Molecules.Values.First().Rings.Count}");
        }
Пример #11
0
        public void SdfImportBenzene()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("Benzene.txt"));

            // Basic sanity checks
            Assert.IsTrue(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");
            Assert.IsTrue(m.AllAtoms.Count == 6, $"Expected 6 Atoms; Got {m.AllAtoms.Count}");
            Assert.IsTrue(m.AllBonds.Count == 6, $"Expected 6 Bonds; Got {m.AllBonds.Count}");

            // Check that names and formulae have not been trashed
            Assert.IsTrue(m.Molecules[0].ChemicalNames.Count == 2, $"Expected 2 Chemical Names; Got {m.Molecules[0].ChemicalNames.Count}");
            Assert.IsTrue(m.Molecules[0].Formulas.Count == 2, $"Expected 2 Formulae; Got {m.Molecules[0].Formulas.Count }");

            // Check that we have one ring
            Assert.IsTrue(m.Molecules.SelectMany(m1 => m1.Rings).Count() == 1, $"Expected 1 Ring; Got {m.Molecules.SelectMany(m1 => m1.Rings).Count()}");
        }
Пример #12
0
        public void SdfImportBasicParafuchsin()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("BasicParafuchsin.txt"));

            // Basic sanity checks
            Assert.IsTrue(m.Molecules.Count == 2, $"Expected 2 Molecules; Got {m.Molecules.Count}");
            Assert.IsTrue(m.AllAtoms.Count == 41, $"Expected 41 Atoms; Got {m.AllAtoms.Count}");
            Assert.IsTrue(m.AllBonds.Count == 42, $"Expected 42 Bonds; Got {m.AllBonds.Count}");

            // Check that we got two rings
            Assert.IsTrue(m.Molecules.SelectMany(m1 => m1.Rings).Count() == 3, $"Expected 2 Rings; Got {m.Molecules.SelectMany(m1 => m1.Rings).Count()}");

            string molstring = mc.Export(m);

            mc = new SdFileConverter();
            Model m2 = mc.Import(molstring);
        }
Пример #13
0
        public Library()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            string libraryTarget = Path.Combine(Globals.Chem4WordV3.AddInInfo.ProgramDataPath, Constants.LibraryFileName);

            _sdFileConverter = new SdFileConverter();
            _cmlConverter    = new CMLConverter();

            if (!File.Exists(libraryTarget))
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", "Copying initial Library database");
                Stream stream = ResourceHelper.GetBinaryResource(Assembly.GetExecutingAssembly(), "Library.zip");
                using (ZipFile zip = ZipFile.Read(stream))
                {
                    zip.ExtractAll(Globals.Chem4WordV3.AddInInfo.ProgramDataPath, ExtractExistingFileAction.OverwriteSilently);
                }
            }
        }
Пример #14
0
        private void btnConvertModel_Click(object sender, EventArgs e)
        {
            TextBoxFormat format = GetTextBoxFormat(txtStructure);

            switch (format)
            {
            case TextBoxFormat.Json:
                JSONConverter converter1 = new JSONConverter();
                Model         model1     = converter1.Import((object)txtStructure.Text);
                model1.RebuildMolecules();
                model1.Relabel();
                model1.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                CMLConverter converter2 = new CMLConverter();
                txtStructure.Text = converter2.Export(model1);
                break;

            case TextBoxFormat.Cml:
                CMLConverter converter3 = new CMLConverter();
                Model        model2     = converter3.Import((object)txtStructure.Text);
                model2.RebuildMolecules();
                model2.Relabel();
                JSONConverter converter4 = new JSONConverter();
                txtStructure.Text = converter4.Export(model2);
                break;

            case TextBoxFormat.MolFile:
                SdFileConverter converter5 = new SdFileConverter();
                Model           model3     = converter5.Import((object)txtStructure.Text);
                model3.RebuildMolecules();
                model3.Relabel();
                CMLConverter converter6 = new CMLConverter();
                txtStructure.Text = converter6.Export(model3);
                break;
            }

            EnableButtons();
        }
Пример #15
0
        private void LayoutStructure_Click(object sender, EventArgs e)
        {
            var data = new LayoutResult();

            var    cc      = new CMLConverter();
            var    sc      = new SdFileConverter();
            string molfile = sc.Export(cc.Import(_lastCml));

            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    var formData = new List <KeyValuePair <string, string> >();

                    formData.Add(new KeyValuePair <string, string>("mol", molfile));
                    formData.Add(new KeyValuePair <string, string>("machine", SystemHelper.GetMachineId()));
                    formData.Add(new KeyValuePair <string, string>("version", "1.2.3.4"));
#if DEBUG
                    formData.Add(new KeyValuePair <string, string>("debug", "true"));
#endif

                    var content = new FormUrlEncodedContent(formData);

                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Add("user-agent", "Chem4Word");

                    try
                    {
                        var response = httpClient.PostAsync("https://chemicalservices-staging.azurewebsites.net/api/Layout", content).Result;
                        if (response.Content != null)
                        {
                            var responseContent = response.Content;
                            var jsonContent     = responseContent.ReadAsStringAsync().Result;

                            try
                            {
                                data = JsonConvert.DeserializeObject <LayoutResult>(jsonContent);
                            }
                            catch (Exception e3)
                            {
                                //Telemetry.Write(module, "Exception", e3.Message);
                                //Telemetry.Write(module, "Exception(Data)", jsonContent);
                                Debug.WriteLine(e3.Message);
                            }

                            if (data != null)
                            {
                                if (data.Messages.Any())
                                {
                                    //Telemetry.Write(module, "Timing", string.Join(Environment.NewLine, data.Messages));
                                }
                                if (data.Errors.Any())
                                {
                                    //Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, data.Errors));
                                }

                                if (!string.IsNullOrEmpty(data.Molecule))
                                {
                                    var model = sc.Import(data.Molecule);
                                    model.EnsureBondLength(20, false);
                                    if (string.IsNullOrEmpty(model.CustomXmlPartGuid))
                                    {
                                        model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                                    }

                                    var clone = cc.Import(_lastCml);
                                    _undoStack.Push(clone);

                                    _lastCml = cc.Export(model);
                                    ShowChemistry("", model);
                                }
                            }
                        }
                    }
                    catch (Exception e2)
                    {
                        //Telemetry.Write(module, "Exception", e2.Message);
                        //Telemetry.Write(module, "Exception", e2.ToString());
                        Debug.WriteLine(e2.Message);
                    }
                }
            }
            catch (Exception e1)
            {
                //Telemetry.Write(module, "Exception", e1.Message);
                //Telemetry.Write(module, "Exception", e1.ToString());
                Debug.WriteLine(e1.Message);
            }
        }
Пример #16
0
        private void LoadModel(string fileName)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
            {
                try
                {
                    string contents = string.Empty;
                    using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var textReader = new StreamReader(fileStream))
                        {
                            contents = textReader.ReadToEnd();
                        }
                    }

                    Model  model    = null;
                    string fileType = Path.GetExtension(fileName).ToLower();
                    switch (fileType)
                    {
                    case ".cml":
                        var cmlConverter = new CMLConverter();
                        model = cmlConverter.Import(contents);
                        break;

                    case ".sdf":
                    case ".mol":
                        var sdFileConverter = new SdFileConverter();
                        model = sdFileConverter.Import(contents);
                        break;

                    case ".json":
                        var jsonConverter = new JSONConverter();
                        model = jsonConverter.Import(contents);
                        break;
                    }

                    if (model != null)
                    {
                        lastModel = model;

                        // Load model into TreeView
                        foreach (var modelMolecule in model.Molecules.Values)
                        {
                            LoadTreeNode(modelMolecule);
                        }

                        model.AtomsChanged     += Model_AtomsChanged;
                        model.BondsChanged     += Model_BondsChanged;
                        model.MoleculesChanged += Model_MoleculesChanged;
                        model.PropertyChanged  += Model_PropertyChanged;

                        int atoms = model.TotalAtomsCount;
                        int bonds = model.TotalBondsCount;
                        textBox1.AppendText($"Total Atoms Count is {atoms}, Total Bonds Count is {bonds}\n");
                        var list = new List <string>();
                        list.AddRange(model.GeneralErrors);
                        list.AddRange(model.AllErrors);
                        list.AddRange(model.AllWarnings);
                        textBox1.AppendText(string.Join(Environment.NewLine, list) + "\n");
                    }
                }
                catch (Exception exception)
                {
                    _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                    _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                    MessageBox.Show(exception.StackTrace, exception.Message);
                }
            }

            // Local function to allow recursive calling
            void LoadTreeNode(Molecule modelMolecule, TreeNode root = null)
            {
                TreeNode parentNode;

                if (root == null)
                {
                    //FileInfo fi = new FileInfo(fileName);
                    //parentNode = treeView1.Nodes.Add(modelMolecule.Path, fi.Name + ": " + modelMolecule.ToString());
                    parentNode = treeView1.Nodes.Add(modelMolecule.Path, modelMolecule.ToString());
                    textBox1.AppendText($"Molecule {modelMolecule.Path} added.\n");
                }
                else
                {
                    parentNode = root.Nodes.Add(modelMolecule.Path, modelMolecule.ToString());
                    textBox1.AppendText($"Molecule {modelMolecule.Path} added.\n");
                }
                parentNode.Tag = modelMolecule;

                if (modelMolecule.Atoms.Any())
                {
                    var atomsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Atoms", $"Atoms: count {modelMolecule.Atoms.Count}");

                    foreach (Atom atom in modelMolecule.Atoms.Values)
                    {
                        var res = atomsNode.Nodes.Add(atom.Path, atom.ToString());
                        res.Tag = atom;
                        textBox1.AppendText($"Atom {atom.Path} added.\n");
                    }
                }

                if (modelMolecule.Bonds.Any())
                {
                    var bondsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Bonds", $"Bonds: count {modelMolecule.Bonds.Count}");

                    foreach (Bond bond in modelMolecule.Bonds)
                    {
                        var res = bondsNode.Nodes.Add(bond.Path, bond.ToString());
                        res.Tag = bond;
                        textBox1.AppendText($"Bond {bond.Path} added.\n");
                    }
                }

                if (modelMolecule.Formulas.Any())
                {
                    var formulasNode = parentNode.Nodes.Add(modelMolecule.Path + "/Formulas", $"Formulas: count {modelMolecule.Formulas.Count}");
                    foreach (var formula in modelMolecule.Formulas)
                    {
                        formulasNode.Nodes.Add(formula.Id, $"Formula {formula.Id} {formula.Convention} {formula.Inline}");
                    }
                }

                if (modelMolecule.Names.Any())
                {
                    var namesNode = parentNode.Nodes.Add(modelMolecule.Path + "/Names", $"Names: count {modelMolecule.Names.Count}");
                    foreach (var name in modelMolecule.Names)
                    {
                        namesNode.Nodes.Add(name.Id, $"Name {name.Id} {name.DictRef} {name.Name}");
                    }
                }

                if (modelMolecule.Rings.Any())
                {
                    var ringsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Rings", $"Rings: count {modelMolecule.Rings.Count}");

                    int ringCounter = 1;
                    foreach (Ring r in modelMolecule.Rings)
                    {
                        var ringnode = ringsNode.Nodes.Add(r.GetHashCode().ToString(), $"Ring {ringCounter++} - Priority {r.Priority} with {r.Atoms.Count} Atoms");
                        ringnode.Tag = r;
                        foreach (Atom a in r.Atoms)
                        {
                            ringnode.Nodes.Add(r.GetHashCode() + a.Id, $"{a.Id} - {a.Path}");
                        }
                    }
                }

                foreach (var childMol in modelMolecule.Molecules.Values)
                {
                    LoadTreeNode(childMol, parentNode);
                }
            }
        }
Пример #17
0
        private string FetchStructure()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            string result = lastSelected;

            ImportButton.Enabled = false;

            ListView.SelectedListViewItemCollection selected = Results.SelectedItems;
            if (selected.Count > 0)
            {
                ListViewItem item      = selected[0];
                string       pubchemId = item.Text;
                PubChemId = pubchemId;

                if (!pubchemId.Equals(lastSelected))
                {
                    Cursor = Cursors.WaitCursor;

                    // https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/241/record/SDF

                    var securityProtocol = ServicePointManager.SecurityProtocol;
                    ServicePointManager.SecurityProtocol = securityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                    try
                    {
                        var request = (HttpWebRequest)WebRequest.Create(
                            string.Format(CultureInfo.InvariantCulture, "{0}rest/pug/compound/cid/{1}/record/SDF",
                                          UserOptions.PubChemRestApiUri, pubchemId));

                        request.Timeout   = 30000;
                        request.UserAgent = "Chem4Word";

                        HttpWebResponse response;

                        response = (HttpWebResponse)request.GetResponse();
                        if (HttpStatusCode.OK.Equals(response.StatusCode))
                        {
                            // we will read data via the response stream
                            using (var resStream = response.GetResponseStream())
                            {
                                lastMolfile = new StreamReader(resStream).ReadToEnd();
                                SdFileConverter sdFileConverter = new SdFileConverter();
                                Model.Model     model           = sdFileConverter.Import(lastMolfile);
                                if (model.MeanBondLength < Core.Helpers.Constants.MinimumBondLength - Core.Helpers.Constants.BondLengthTolerance ||
                                    model.MeanBondLength > Core.Helpers.Constants.MaximumBondLength + Core.Helpers.Constants.BondLengthTolerance)
                                {
                                    model.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                                }
                                this.display1.Chemistry = model;
                                if (model.AllWarnings.Count > 0 || model.AllErrors.Count > 0)
                                {
                                    Telemetry.Write(module, "Exception(Data)", lastMolfile);
                                    List <string> lines = new List <string>();
                                    if (model.AllErrors.Count > 0)
                                    {
                                        Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllErrors));
                                        lines.Add("Errors(s)");
                                        lines.AddRange(model.AllErrors);
                                    }
                                    if (model.AllWarnings.Count > 0)
                                    {
                                        Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllWarnings));
                                        lines.Add("Warnings(s)");
                                        lines.AddRange(model.AllWarnings);
                                    }
                                    ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                                }
                                else
                                {
                                    CMLConverter cmlConverter = new CMLConverter();
                                    Cml = cmlConverter.Export(model);
                                    ImportButton.Enabled = true;
                                }
                            }
                            result = pubchemId;
                        }
                        else
                        {
                            result      = string.Empty;
                            lastMolfile = string.Empty;

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine($"Bad request. Status code: {response.StatusCode}");
                            UserInteractions.AlertUser(sb.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Equals("The operation has timed out"))
                        {
                            ErrorsAndWarnings.Text = "Please try again later - the service has timed out";
                        }
                        else
                        {
                            ErrorsAndWarnings.Text = ex.Message;
                            Telemetry.Write(module, "Exception", ex.Message);
                            Telemetry.Write(module, "Exception", ex.StackTrace);
                        }
                    }
                    finally
                    {
                        ServicePointManager.SecurityProtocol = securityProtocol;
                        Cursor = Cursors.Default;
                    }
                }
            }

            return(result);
        }
Пример #18
0
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("All molecule files (*.mol, *.cml)|*.mol;*.cml");
            sb.Append("|CML molecule files (*.cml)|*.cml");
            sb.Append("|MDL molecule files (*.mol)|*.mol");

            openFileDialog1.Filter = sb.ToString();

            DialogResult dr = openFileDialog1.ShowDialog();

            if (dr == DialogResult.OK)
            {
                string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower();
                string filename = Path.GetFileName(openFileDialog1.FileName);
                string mol      = File.ReadAllText(openFileDialog1.FileName);
                Model  model    = null;

                switch (fileType)
                {
                case ".cml":
                    CMLConverter cmlConverter = new CMLConverter();
                    model = cmlConverter.Import(mol);
                    break;

                case ".mol":
                    SdFileConverter molfileConverter = new SdFileConverter();
                    model = molfileConverter.Import(mol);
                    break;
                }

                string fCml  = "";
                string fCalc = "";
                if (model != null)
                {
                    this.Text = filename;
                    foreach (var molecule in model.Molecules)
                    {
                        if (!string.IsNullOrEmpty(molecule.ConciseFormula))
                        {
                            fCml += $"{molecule.ConciseFormula} . ";
                        }
                        fCalc += $"{molecule.CalculatedFormula()} . ";
                    }

                    if (fCalc.EndsWith(" . "))
                    {
                        fCalc = fCalc.Substring(0, fCalc.Length - 3);
                    }
                    if (fCml.EndsWith(" . "))
                    {
                        fCml = fCml.Substring(0, fCml.Length - 3);
                    }
                    lblCalculated.Text = $"{fCalc}";
                    lblFromCml.Text    = $"{fCml}";
                    lblOverall.Text    = $"{model.ConciseFormula}";

                    display1.Chemistry = mol;
                }
            }
        }
Пример #19
0
        private void LoadStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Model model = null;

                StringBuilder sb = new StringBuilder();
                sb.Append("All molecule files (*.mol, *.sdf, *.cml)|*.mol;*.sdf;*.cml");
                sb.Append("|CML molecule files (*.cml)|*.cml");
                sb.Append("|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf");

                openFileDialog1.Title            = "Open Structure";
                openFileDialog1.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
                openFileDialog1.Filter           = sb.ToString();
                openFileDialog1.FileName         = "";
                openFileDialog1.ShowHelp         = false;

                DialogResult dr = openFileDialog1.ShowDialog();

                if (dr == DialogResult.OK)
                {
                    string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower();
                    string filename = Path.GetFileName(openFileDialog1.FileName);
                    string mol      = File.ReadAllText(openFileDialog1.FileName);

                    CMLConverter    cmlConvertor    = new CMLConverter();
                    SdFileConverter sdFileConverter = new SdFileConverter();

                    switch (fileType)
                    {
                    case ".mol":
                    case ".sdf":
                        model = sdFileConverter.Import(mol);
                        break;

                    case ".cml":
                    case ".xml":
                        model = cmlConvertor.Import(mol);
                        break;
                    }

                    if (model != null)
                    {
                        model.EnsureBondLength(20, false);
                        if (string.IsNullOrEmpty(model.CustomXmlPartGuid))
                        {
                            model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                        }

                        if (!string.IsNullOrEmpty(_lastCml))
                        {
                            var clone = cmlConvertor.Import(_lastCml);
                            Debug.WriteLine(
                                $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                            _undoStack.Push(clone);
                        }

                        _lastCml = cmlConvertor.Export(model);

                        _telemetry.Write(module, "Information", $"File: {filename}");
                        ShowChemistry(filename, model);
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }
Пример #20
0
        public static int CalculateProperties(List <Molecule> newMolecules)
        {
            string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()";

            var molConverter      = new SdFileConverter();
            int changedProperties = 0;
            int newProperties     = 0;

            int webServiceCalls = newMolecules.Count + 1;

            Progress pb = new Progress();

            pb.TopLeft = Globals.Chem4WordV3.WordTopLeft;
            pb.Value   = 0;
            pb.Maximum = webServiceCalls;

            foreach (var molecule in newMolecules)
            {
                Model temp = new Model();
                var   mol  = molecule.Copy();
                temp.AddMolecule(mol);

                // GitHub: Issue #9 https://github.com/Chem4Word/Version3/issues/9
                int maxAtomicNumber = temp.MaxAtomicNumber;
                int minAtomicNumber = temp.MinAtomicNumber;

                var invalidBonds = new List <Bond>();
                if (mol.Bonds.Any())
                {
                    invalidBonds = mol.Bonds.Where(b => b.OrderValue != null && (CtabProcessor.MdlBondType(b.Order) < 1 || CtabProcessor.MdlBondType(b.Order) > 4)).ToList();
                }

                var calculatedNames    = new List <TextualProperty>();
                var calculatedFormulae = new List <TextualProperty>();

                if (mol.HasFunctionalGroups || invalidBonds.Any() || minAtomicNumber < 1 || maxAtomicNumber > 118)
                {
                    // IUPAC InChi (1.05) generator does not support Mdl Bond Types < 1 or > 4 or Elements < 1 or > 118 or 'our' functional groups

                    #region Set Default properties

                    Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Not sending structure to Web Service; HasFunctionalGroups: {mol.HasFunctionalGroups} Invalid Bonds: {invalidBonds?.Count} Min Atomic Number: {minAtomicNumber} Max Atomic Number: {maxAtomicNumber}");
                    calculatedNames.Add(new TextualProperty {
                        FullType = CMLConstants.ValueChem4WordInchiName, Value = "Unable to calculate"
                    });
                    //calculatedNames.Add(new TextualProperty { FullType = CMLConstants.ValueChem4WordAuxInfoName, Value = "Unable to calculate" });
                    calculatedNames.Add(new TextualProperty {
                        FullType = CMLConstants.ValueChem4WordInchiKeyName, Value = "Unable to calculate"
                    });

                    calculatedFormulae.Add(new TextualProperty {
                        FullType = CMLConstants.ValueChem4WordResolverFormulaName, Value = "Not requested"
                    });
                    calculatedNames.Add(new TextualProperty {
                        FullType = CMLConstants.ValueChem4WordResolverIupacName, Value = "Not requested"
                    });
                    calculatedFormulae.Add(new TextualProperty {
                        FullType = CMLConstants.ValueChem4WordResolverSmilesName, Value = "Not requested"
                    });

                    #endregion Set Default properties
                }
                else
                {
                    pb.Show();
                    pb.Increment(1);
                    pb.Message = $"Calculating InChiKey and Resolving Names using Chem4Word Web Service for molecule {molecule.Id}";

                    #region Obtain Calculated Properties

                    try
                    {
                        string afterMolFile = molConverter.Export(temp);

                        ChemicalServices cs = new ChemicalServices(Globals.Chem4WordV3.Telemetry);
                        var csr             = cs.GetChemicalServicesResult(afterMolFile);

                        if (csr?.Properties != null && csr.Properties.Any())
                        {
                            var first = csr.Properties[0];
                            if (first != null)
                            {
                                var value = string.IsNullOrEmpty(first.Inchi) ? "Not found" : first.Inchi;
                                calculatedNames.Add(new TextualProperty {
                                    FullType = CMLConstants.ValueChem4WordInchiName, Value = value
                                });

                                //value = string.IsNullOrEmpty(first.AuxInfo) ? "Not found" : first.AuxInfo;
                                //calculatedNames.Add(new TextualProperty { FullType = CMLConstants.ValueChem4WordAuxInfoName, Value = value });

                                value = string.IsNullOrEmpty(first.InchiKey) ? "Not found" : first.InchiKey;
                                calculatedNames.Add(new TextualProperty {
                                    FullType = CMLConstants.ValueChem4WordInchiKeyName, Value = value
                                });

                                value = string.IsNullOrEmpty(first.Formula) ? "Not found" : first.Formula;
                                calculatedFormulae.Add(new TextualProperty {
                                    FullType = CMLConstants.ValueChem4WordResolverFormulaName, Value = value
                                });

                                value = string.IsNullOrEmpty(first.Name) ? "Not found" : first.Name;
                                calculatedNames.Add(new TextualProperty {
                                    FullType = CMLConstants.ValueChem4WordResolverIupacName, Value = value
                                });

                                value = string.IsNullOrEmpty(first.Smiles) ? "Not found" : first.Smiles;
                                calculatedFormulae.Add(new TextualProperty {
                                    FullType = CMLConstants.ValueChem4WordResolverSmilesName, Value = value
                                });
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Globals.Chem4WordV3.Telemetry.Write(module, "Exception", $"{e}");
                    }

                    #endregion Obtain Calculated Properties
                }

                #region Merge in properties

                foreach (var formula in calculatedFormulae)
                {
                    var target = molecule.Formulas.FirstOrDefault(f => f.FullType.Equals(formula.FullType));
                    if (target == null)
                    {
                        molecule.Formulas.Add(formula);
                        newProperties++;
                    }
                    else
                    {
                        if (!target.Value.Equals(formula.Value))
                        {
                            target.Value = formula.Value;
                            changedProperties++;
                        }
                    }
                }

                foreach (var name in calculatedNames)
                {
                    var target = molecule.Names.FirstOrDefault(f => f.FullType.Equals(name.FullType));
                    if (target == null)
                    {
                        molecule.Names.Add(name);
                        newProperties++;
                    }
                    else
                    {
                        if (!target.Value.Equals(name.Value))
                        {
                            target.Value = name.Value;
                            changedProperties++;
                        }
                    }
                }

                #endregion Merge in properties
            }

            pb.Value = 0;
            pb.Hide();
            pb.Close();

            return(changedProperties + newProperties);
        }