Ejemplo n.º 1
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);
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
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);
            }
        }
Ejemplo n.º 4
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);
        }
Ejemplo n.º 5
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);
            }
        }
Ejemplo n.º 6
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);
        }