Exemplo n.º 1
0
        /// <summary>
        /// New update the list of related compounds
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="cid"></param>
        /// <param name="queryStruct"></param>

        private void UpdateRelatedCidsDisplay(
            MetaTable mt,
            string cid,
            MoleculeMx queryStruct,
            int renderId)
        {
            bool useNew = ServicesIniFile.ReadBool("UseNewRelatedCompoundsPopup", true);             // use new or old related compounds display

            if (!useNew)
            {
                UpdateRelatedCidsDisplayOld(mt, cid, queryStruct);
                return;
            }

            //if (!SS.I.AllowGroupingBySalts || // need this?
            //	Lex.Ne(MetaTable.DefaultRootTable, mt.Name))
            //{
            //	this.Height = RelatedStructuresPanel.Top;
            //	return;
            //}

            if (SS.I.FindRelatedCpdsInQuickSearch)
            {
                RSM.StartSearchAndRetrievalOfRelatedStructures(mt.Name, cid, queryStruct, RelatedStructureBrowser.StructureSearchTypes);
            }

            return;
        }
Exemplo n.º 2
0
		/// <summary>
		/// Calculate Tanimoto similarity between two compounds
		/// </summary>
		/// <param name="fp1"></param>
		/// <param name="rp2"></param>
		/// <returns></returns>

		double CalculateSimilarity(
			CompoundStructureActivityData cd1,
			CompoundStructureActivityData cd2)
		{
			int l1 = -1, l2 = -1;

			if (cd1.BitsetFingerprint == null || cd2.BitsetFingerprint == null)
				return 0;

			if (Debug)
			{
				if ((cd1.Cid == "111" && cd2.Cid == "222") ||
				 (cd2.Cid == "222" && cd1.Cid == "111"))
				{
					DebugLog.Message("Before: " + cd1.Cid + ": " + String.Join(", ", CdkMolUtil.GetBitSet(cd1.BitsetFingerprint)));
					DebugLog.Message("Before: " + cd2.Cid + ": " + String.Join(", ", CdkMolUtil.GetBitSet(cd2.BitsetFingerprint)));
				}
			}

			double sim = MoleculeMx.CalculateBitSetFingerprintSimilarity(cd1.BitsetFingerprint, cd2.BitsetFingerprint);

			if (Debug)
			{
				if ((cd1.Cid == "111" && cd2.Cid == "222") ||
				 (cd2.Cid == "222" && cd1.Cid == "111"))
				{
					DebugLog.Message(cd1.Cid + ": " + String.Join(", ", CdkMolUtil.GetBitSet(cd1.BitsetFingerprint)));
					DebugLog.Message(cd2.Cid + ": " + String.Join(", ", CdkMolUtil.GetBitSet(cd2.BitsetFingerprint)));
					DebugLog.Message(cd1.Cid + ", " + cd2.Cid + " Similarity: " + sim);
				}
			}

			return sim;
		}
Exemplo n.º 3
0
        /// <summary>
        /// SetStereoChemistryComments in structure object
        /// </summary>
        /// <param name="cs"></param>
        /// <param name="comments"></param>
        /// <param name="cid"></param>

        public static void SetStereochemistryComments(
            MoleculeMx cs,
            string comments,
            string cid)
        {
            if (Lex.IsUndefined(comments) || !ShowStereoComments)
            {
                return;
            }

            if (!ClientState.IsNativeSession)
            {
                return;                                     // don't include if not native session (i.e regular Mobius Client)
            }
            cs.SetMolComments("CorpId=" + cid);             // indicate this is an CorpId

            if (cs.PrimaryFormat == MoleculeFormat.Unknown)
            {             // be sure defined
                cs.SetPrimaryTypeAndValue(MoleculeFormat.Chime, "");
            }

            try { cs.CreateStructureCaption(comments); }
            catch (Exception ex)
            { DebugLog.Message("CreateStructureCaption exception for compound: " + cid); }             // issue #216

            return;
        }
Exemplo n.º 4
0
/// <summary>
/// Display the structure and other basic data for the supplied cid
/// </summary>
/// <param name="cidArg"></param>

        void DisplayCidData(string cidArg)
        {
            MoleculeMx str = null;
            string     mwTxt = "", mfTxt = "", haTxt = "", tok;

            string intCid = CompoundId.Normalize(cidArg, RootTable);
            string extCid = CompoundId.Format(intCid, RootTable);

            CidCtl.Text = extCid;

            if (RootTable == null || RootTable.KeyMetaColumn.DataType == MetaColumnType.CompoundId)
            {
                str = MoleculeUtil.SelectMoleculeForCid(intCid, RootTable);
            }

            if (Lex.IsDefined(str?.PrimaryValue))             // have a structure with at least one atom
            {
                if (str.PrimaryDisplayFormat == MoleculeRendererType.Chemistry)
                {
                    int ha = str.HeavyAtomCount;
                    if (ha > 0)
                    {
                        haTxt = ha.ToString();
                    }

                    double mw = str.MolWeight;
                    if (mw >= 0)
                    {
                        mwTxt = String.Format("{0:f3}", mw);
                    }
                    HeavyAtoms.Text = "";
                    Weight.Text     = mwTxt;

                    string mf = str.MolFormula;
                    HeavyAtoms.Text = "";
                    Formula.Text    = mf;
                }

                else
                {
                }                        // biopolymer, don't calc structure props (too slow for now)

                HeavyAtoms.Text = haTxt;
                Weight.Text     = mwTxt;
                Formula.Text    = mfTxt;

                MolCtl.Molecule = str;

                return;
            }

            else             // no structure
            {
                HeavyAtoms.Text = "";
                Weight.Text     = "";
                Formula.Text    = "";
                MolCtl.ClearMolecule();
                return;
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Format structure for output to SDFile
        /// </summary>
        /// <param name="molid"></param>

        void FormatSdfileStructure(
            MoleculeMx cs)
        {
            string molFile, cid;

            if (SS.I.RemoveLeadingZerosFromCids)             // normal formatting
            {
                cid = CompoundId.Format(CurrentKey);
            }
            else
            {
                cid = CurrentKey;              // just use internal formatting
            }
            cs      = cs.Convert(Rf.StructureFlags | MoleculeTransformationFlags.RemoveStructureCaption, cid);
            molFile = cs.GetMolfileString();

            if (molFile.IndexOf("\r") < 0)             // add carriage returns to molfile if it doesn't contain them
            {
                molFile = molFile.Replace("\n", "\r\n");
            }

            SdfLine = molFile;

            return;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Update the list of related compounds
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="cid"></param>
        /// <param name="str"></param>

        private void UpdateRelatedCidsDisplayOld(
            MetaTable mt,
            string cid,
            MoleculeMx str)
        {
            if (SS.I.AllowGroupingBySalts)             // build list of salts & send
            {
                List <string> salts = MoleculeUtil.GetAllSaltForms(Cid);
                if (salts == null || salts.Count == 0)                 // nothing related
                {
                    OtherCidsList.Visible = false;                     // hide list
                }
                else
                {
                    OtherCidsList.Properties.Items.Clear();
                    foreach (string s in salts)
                    {
                        string extCid = CompoundId.Format(s);
                        OtherCidsList.Properties.Items.Add(extCid);
                    }
                    string listHeader = salts.Count.ToString() + " Other Match";
                    if (salts.Count > 1)
                    {
                        listHeader += "es";                              // use proper grammar
                    }
                    OtherCidsList.Text    = listHeader;                  // select first item
                    OtherCidsList.Visible = true;
                }
            }

            else
            {
                OtherCidsList.Visible = false;              // hide list
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Get the list of related compounds
        /// </summary>
        /// <param name="mt"></param>
        /// <param name="cid"></param>
        /// <param name="str"></param>

        public void StartSearchAndRetrievalOfRelatedStructures(
            string mtName,
            string cid,
            MoleculeMx str,
            StructureSearchType searchTypes)
        {
            RSC.RenderSearchResultsDelegate = RenderSearchResults;             // set render callback

            DisplayEmptySearchResults();

            if (Lex.IsUndefined(str.PrimaryValue) || (!str.IsChemStructureFormat && str.IsBiopolymerFormat))             // reasonable structure?
            {
                return;
            }

            Cid         = cid;
            CidMtName   = mtName;
            QueryStruct = str;
            SearchTypes = searchTypes;

            Timer.Enabled = true;

            Thread t = new Thread(new ParameterizedThreadStart(SearchAndRetrieveRelatedStructuresThreadMethod));

            t.IsBackground = true;
            t.SetApartmentState(ApartmentState.STA);

            object[] parms = null;
            t.Start(parms);

            return;
        }
Exemplo n.º 8
0
        public void Setup(ColumnInfo colInfo)
        {
            bool check;

            InSetup = true;
            ColInfo = colInfo;                                                                    // save ref to colInfo

            ParsedSingleCriteria psc = MqlUtil.ParseSingleCriteria(ColInfo.Qc.SecondaryCriteria); // parse criteria

            if (psc == null)
            {
                StructureRenditor.MolfileString = "";
            }
            else
            {
                MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, psc.Value);
                MoleculeMx.SetRendererStructure(StructureRenditor, cs);
            }

            Timer.Enabled    = true;
            StructureChanged = false;

            InSetup = false;
            return;
        }
Exemplo n.º 9
0
        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (ServiceFacade.ServiceFacade.InServiceCall)
            {
                return;                                                         // avoid multiplexing service calls that could cause problems
            }
            if (InTimer_Tick)
            {
                return;
            }
            InTimer_Tick = true;

            string currentCid = CidCtl.Text;

            if (currentCid == PreviousCid)
            {
                InTimer_Tick = false;
                return;
            }

            PreviousCid = currentCid;

            string     cid = CompoundId.Normalize(currentCid, MetaTable);
            MetaTable  mt  = CompoundId.GetRootMetaTableFromCid(cid, MetaTable);
            MoleculeMx mol = MoleculeUtil.SelectMoleculeForCid(cid, mt);

            QuickStructure.SetupAndRenderMolecule(mol);

            InTimer_Tick = false;
            return;
        }
Exemplo n.º 10
0
            /// <summary>
            /// Get substituent for a decomposition rgroup & map position & store in list
            /// </summary>
            /// <param name="rSub">Substituent structure</param>
            /// <param name="rSubs">List of substituents so far</param>
            /// <returns>Index of the substituent in rSubs</returns>

            public static int Get(
                MoleculeMx rSub,
                List <RgroupSubstituent> rSubs)
            {
                double mw = rSub.MolWeight;
                int    si;

                for (si = 0; si < rSubs.Count; si++)
                {                 // see if we've seen this substituent
                    if (mw != rSubs[si].Mw)
                    {
                        continue;                                         // quick compare on mol weight first
                    }
                    if (matcher == null)
                    {
                        matcher = new StructureMatcher();
                    }
                    if (matcher.Equal(rSub, rSubs[si].Struct))
                    {
                        break;
                    }
                }

                if (si >= rSubs.Count)
                {                 // add new item
                    RgroupSubstituent rgs = new RgroupSubstituent();
                    rgs.Mw     = mw;
                    rgs.Struct = rSub;
                    rSubs.Add(rgs);
                }

                return(si);
            }
Exemplo n.º 11
0
        private void Timer_Tick(object sender, EventArgs e)
        {
            if (!StructureChanged)
            {
                return;
            }

            QueryColumn qc = ColInfo.Qc;

            if (String.IsNullOrEmpty(StructureRenditor.MolfileString))
            {
                qc.SecondaryCriteria = qc.SecondaryCriteriaDisplay = "";
            }

            else
            {
                // Chime: CYAAFQwAncwQGj8h7GZ^yjgsajoFd0PQ1OYrnIdaPTl0lGnQYLHH2prJeJi$BhUHcMsE1TyQisJflsW2r293v92iC1^wVm$8wwLM7^krIFa8A1X6Jvu8VIYgCgJ8$y1RuqgCc5ifKbMAflB
                string chimeString = MoleculeMx.MolfileStringToChimeString(StructureRenditor.MolfileString);
                qc.SecondaryCriteria        = "SSS ( " + qc.MetaColumn.Name + ", " + Lex.AddSingleQuotes(chimeString) + ") = 1";
                qc.SecondaryCriteriaDisplay = qc.ActiveLabel + " contains substructure";
            }

            qc.SecondaryFilterType = FilterType.StructureSearch;

            QueryManager.QueryResultsControl.UpdateFiltering(ColInfo);
            FilterBasicCriteriaControl.SyncBaseQuerySecondaryCriteria(qc);             // sync any base query

            StructureChanged = false;
            return;
        }
Exemplo n.º 12
0
        public List <StructSearchMatch> ExecuteSearch(
            MoleculeMx queryMolMx)
        {
            CdkMol         m2       = (CdkMol)queryMolMx.CdkMol;
            IAtomContainer queryMol = m2.NativeMol;

            return(ExecuteSearch(queryMol));
        }
Exemplo n.º 13
0
        /// <summary>
        /// Select a MoleculeMx object for a compound id
        /// </summary>
        /// <param name="cid"></param>
        /// <param name="mt"></param>
        /// <returns></returns>

        public static MoleculeMx SelectMoleculeForCid(
            string cid,
            MetaTable mt = null)
        {
            MoleculeMx mol = null;
            Stopwatch  sw  = Stopwatch.StartNew();

            mol = MoleculeCache.Get(cid);             // see if molecule in cache
            if (mol != null)
            {
                return(mol);
            }

            if (ServiceFacade.UseRemoteServices)
            {
                string mtName = mt?.Name;

                Mobius.Services.Native.INativeSession       nativeClient = ServiceFacade.CreateNativeSessionProxy();
                Services.Native.NativeMethodTransportObject resultObject =
                    ServiceFacade.InvokeNativeMethod(nativeClient,
                                                     (int)Services.Native.ServiceCodes.MobiusCompoundUtilService,
                                                     (int)Services.Native.ServiceOpCodes.MobiusCompoundUtilService.SelectMoleculeFromCid,
                                                     new Services.Native.NativeMethodTransportObject(new object[] { cid, mtName }));            // , setStereoChemistryComments
                ((System.ServiceModel.IClientChannel)nativeClient).Close();

                if (resultObject == null)
                {
                    return(null);
                }
                byte[] ba = resultObject.Value as byte[];
                if (ba != null && ba.Length > 0)
                {
                    MobiusDataType mdt = MobiusDataType.DeserializeBinarySingle(ba);
                    mol = mdt as MoleculeMx;
                }
            }

            else
            {
                mol = QEL.MoleculeUtil.SelectMoleculeForCid(cid, mt);
            }

            if (MoleculeMx.IsDefined(mol))
            {
                bool isUcdb = (mt != null && mt.Root.IsUserDatabaseStructureTable);                 // user compound database
                if (!isUcdb)
                {
                    MoleculeCache.AddMolecule(cid, mol);                          // add to cache
                }
            }

            long ms = sw.ElapsedMilliseconds;

            return(mol);
        }
Exemplo n.º 14
0
        // public static string CTabToCharExpression = // expression to convert a ctab into a Oracle char type. Returns 'Large Structure' if too big & handle at retrieve time
        //  "case when length(chime(ctab)) <= 4000 then to_char(chime(ctab)) else 'Large Structure' end";
        // public static string LargeStructureString = "Large Structure"; // string that indicates that chime for structure is > 4000 chars
        // Examples: 3203030, 3020939, 3020943, 3046095, 2240877, 2312187, 2836746

        /// <summary>
        /// Convert an objectinto a ChemicalStructure object
        /// </summary>
        /// <param name="fieldValue"></param>
        /// <returns></returns>

        public static MoleculeMx ConvertObjectToChemicalStructure(
            object fieldValue)
        {
            MoleculeMx     cs;
            MoleculeFormat structureFormat;
            string         txt;

            if (fieldValue == null)
            {
                cs = null;
            }

            else if (fieldValue is MoleculeMx)
            {
                cs = (MoleculeMx)fieldValue;
            }

            else if (fieldValue is string || fieldValue is CompoundId || fieldValue is QualifiedNumber)
            {
                if (fieldValue is string)
                {
                    txt = (string)fieldValue;
                }

                else if (fieldValue is CompoundId)
                {
                    txt = ((CompoundId)fieldValue).Value;
                }

                else
                {
                    txt = ((QualifiedNumber)fieldValue).TextValue;
                }

                structureFormat = MoleculeMx.GetMoleculeFormatType(txt);
                if (structureFormat != MoleculeFormat.Unknown)                 // just convert is known format
                {
                    cs = MoleculeMx.MolStringToMoleculeMx(txt);
                }

                else                 // see if unqualified compound id
                {
                    cs = MoleculeUtil.SelectMoleculeForCid(txt);
                }
            }

            else
            {
                throw new Exception("Object is not a recognized structure format");
            }

            return(cs);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Insert molecule into Excel table cell
        /// </summary>
        /// <param name="cs"></param>
        /// <param name="row"></param>
        /// <param name="col"></param>

        public static void SetCellMolecule(
            int row,
            int col,
            MoleculeMx cs)
        {
            if (IsInsightForExcelAvailable)
            {
                SetInsightForExcelMolecule(row, col, cs);
            }

            return;
        }
Exemplo n.º 16
0
        public void SetupControl(
            MoleculeMx molecule)
        {
            InSetup = true;

            MoleculeControl.SetupAndRenderMolecule(molecule);

            MolDisplayFormatEdit.Text =
                molecule.PrimaryDisplayFormat == MoleculeRendererType.Helm ? "Biopolymer" : "Structure";

            InSetup = false;
            return;
        }
Exemplo n.º 17
0
        /// <summary>
        /// Fix HCl etc groups for proper left side H display
        /// </summary>
        /// <param name="skid"></param>
        /// <returns></returns>

        public static int FixSingleAtomHydrogens(
            MoleculeMx cs)
        {
            int    atmcnt, ai, oldmode, fixcnt, atype, i1, i2, i3;
            string fontname;
            int    size, emphasis;
            double x = 0, y = 0, z = 0;
            int    aid, na, nb, sgrp;
            long   t1, t2;
            string lp;

            return(0);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Do generic display of a structure
        /// </summary>
        /// <param name="title"></param>
        /// <param name="cidLabel"></param>
        /// <param name="structLabel"></param>
        /// <param name="structure"></param>

        public static void DisplayStructure(
            string title,
            string cidLabel,
            string structLabel,
            MoleculeMx structure,
            MoleculeGridPanel gridPanel,
            bool embedDataInQuery)
        {
            List <MoleculeMx> structures = new List <MoleculeMx>();

            structures.Add(structure);

            DisplayStructures(title, cidLabel, structLabel, structures, gridPanel, embedDataInQuery);
            return;
        }
Exemplo n.º 19
0
        //    # Get list of bits where at least one must be in result fp. Use least popular bits if possible.
        //    if db.mfp_counts:
        //        reqbits = [count['_id'] for count in db.mfp_counts.find({'_id': {'$in': qfp
        //	}
        //}).sort('count', 1).limit(ncommon)]
        //    else:
        //        reqbits = qfp[:ncommon]
        //		results = []
        //    for fp in db.molecules.find({'mfp.bits': {'$in': reqbits}, 'mfp.count': {'$gte': qmin, '$lte': qmax}}):
        //        intersection = len(set(qfp) & set(fp['mfp']['bits']))
        //        pn = fp['mfp']['count']
        //				tanimoto = float(intersection) / (pn + qn - intersection)
        //        if tanimoto >= threshold:
        //            results.append((tanimoto, fp['chembl_id'], fp['smiles']))
        //    return results


        /// <summary>
        /// Test to calculate similarity between pairs of structures (Alt syntax: Call SimSearchMx.Test [cid1] [cid2]
        ///  Tautomers:
        ///  Isotopes:
        ///  Neg Counterion, (Cl-) with 2 quatternary N+ with H attached in main frag:
        ///  Neg Counterion, (I-) with quatternary N+ (no attached H) in main frag:
        ///  Pos Counterion (Li+) with O- in main frag:
        ///  Benzene, cyclohexane:
        ///  StereoIsomers:
        ///  StereoIsomers:
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public static string Test(string args)
        {
            string[] sa   = args.Split(' ');
            string   cid1 = CompoundId.Normalize(sa[0]);
            string   cid2 = CompoundId.Normalize(sa[1]);

            int smiLen = 40;

            MoleculeMx           s1   = MoleculeMx.SelectMoleculeForCid(cid1);
            IAtomContainer       mol  = CdkMol.MolfileToAtomContainer(s1.GetMolfileString());
            UniChemData          ucd1 = UniChemUtil.BuildUniChemData(mol);
            List <FingerprintMx> fps1 = UniChemDataToFingerprintMxList(ucd1);

            MoleculeMx           s2   = MoleculeMx.SelectMoleculeForCid(cid2);
            IAtomContainer       mol2 = CdkMol.MolfileToAtomContainer(s2.GetMolfileString());
            UniChemData          ucd2 = UniChemUtil.BuildUniChemData(mol2);
            List <FingerprintMx> fps2 = UniChemDataToFingerprintMxList(ucd2);

            string fps2Smiles = (sa[0] + " / " + sa[1]).PadRight(smiLen);
            string scores     = "";

            for (int i1 = 0; i1 < fps1.Count; i1++)
            {
                FingerprintMx fp1 = fps1[i1];
                for (int i2 = 0; i2 < fps2.Count; i2++)
                {
                    FingerprintMx fp2 = fps2[i2];

                    if (i1 == 0)                     // build smiles headers of cid2 frags if first cid1 frag
                    {
                        fps2Smiles += "\t" + fp2.CanonSmiles.PadRight(smiLen);
                    }

                    if (i2 == 0)
                    {
                        scores += "\r\n" + fp1.CanonSmiles.PadRight(smiLen);                         // include smiles at start of each line
                    }
                    float simScore = CalculateFingerprintPairSimilarityScore(fp1, fp2);
                    scores += "\t" + string.Format("{0:0.00}", simScore).PadRight(smiLen);
                }
            }

            scores = fps2Smiles + scores;

            FileUtil.WriteAndOpenTextDocument("SimilarityScores", scores);

            return("");
        }
Exemplo n.º 20
0
        /// <summary>
        /// DisplayStructureInPopupGrid
        /// </summary>
        /// <param name="title"></param>
        /// <param name="cidLabel"></param>
        /// <param name="structLabel"></param>
        /// <param name="structure"></param>

        public static void DisplayStructureInPopupGrid(
            string title,
            string cidLabel,
            string structLabel,
            MoleculeMx structure)
        {
            List <MoleculeMx> structures = new List <MoleculeMx>();

            structures.Add(structure);

            PopupGrid pg = new PopupGrid();
            bool      embedDataInQuery = false;

            DisplayStructures(title, cidLabel, structLabel, structures, pg.MoleculeGridPanel, embedDataInQuery);
            return;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Modal edit of molecule
        /// </summary>

        public static MoleculeMx Edit(
            MoleculeMx mol,
            MoleculeRendererType editorType = MoleculeRendererType.Unknown,
            string title = "")
        {
            MoleculeMx mol2 = null;

            try
            {
                if (editorType == MoleculeRendererType.Unknown)                 // need to assign editor type?
                {
                    if (mol.IsChemStructureFormat)
                    {
                        editorType = MoleculeRendererType.Chemistry;
                    }

                    else if (mol.IsBiopolymerFormat)
                    {
                        editorType = MoleculeRendererType.Helm;
                    }

                    else
                    {
                        editorType = MoleculeRendererType.Chemistry;                      // final default
                    }
                }

                bool useChemEditor = (editorType != MoleculeRendererType.Helm);

                if (useChemEditor)
                {
                    mol2 = mol.ConvertTo(MoleculeFormat.Molfile);
                    return(EditCdkMolMolecule(mol2, title));
                }

                else                 // use Helm editor
                {
                    return(EditHelmMolecule(mol, title));
                }
            }

            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Error editing molecule");
                return(null);
            }
        }
Exemplo n.º 22
0
/// <summary>
/// Copy the structure associated with the specified compound id to the clipboard
/// </summary>
/// <param name="cn"></param>
/// <param name="mt"></param>
/// <returns></returns>

        public static bool CopyCompoundIdStructureToClipBoard(
            string cn,
            MetaTable mt)
        {
            MoleculeMx mol = MoleculeUtil.SelectMoleculeForCid(cn, mt);

            if (mol != null)
            {
                MoleculeControl.CopyMoleculeToClipboard(mol);
                return(true);
            }
            else
            {
                MessageBoxMx.Show("Unable to retrieve structure");
                return(false);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// AddToFavoritesList
        /// </summary>
        /// <param name="molEditorCtl"></param>
        /// <param name="searchType"></param>

        public static void AddToFavoritesList(
            MoleculeControl molEditorCtl,
            StructureSearchType searchType)
        {
            MoleculeListItem sli = null;
            DialogResult     dr;

            MoleculeMx mol = molEditorCtl.Molecule;

            if (MoleculeMx.IsUndefined(mol))
            {
                return;
            }

            mol = mol.Clone();             // make a copy for the list

            sli = FindStructure(mol, GetFavoriteStructuresList());
            if (sli != null)
            {
                dr = MessageBoxMx.Show("The current molecule already exists in Favorites list under the name: " + sli.Name + "\r\n" +
                                       "Do you still want the add the current query molecule to the Favorites list?", "Molecule already in Favorites", MessageBoxButtons.YesNoCancel);

                if (dr != DialogResult.Yes)
                {
                    return;
                }
            }

            string name = molEditorCtl.GetTemporaryStructureTag();

            name = InputBoxMx.Show("Enter the name that you want to assign to the molecule", "Enter Name", name);
            if (Lex.IsUndefined(name))
            {
                return;
            }

            sli              = new MoleculeListItem();
            sli.Name         = name;
            sli.Molecule     = mol;
            sli.UpdateDate   = DateTime.Now;
            sli.MoleculeType = StructureSearchTypeUtil.StructureSearchTypeToExternalName(searchType);
            FavoritesList.ItemList.Insert(0, sli);

            SaveStructureList(FavoritesList, FavoritesPreferencesParmName);
            return;
        }
Exemplo n.º 24
0
        private void ViewMoleculeInNewWindowMenuItem_Click(object sender, EventArgs e)
        {
            int gri = MoleculeGrid.LastMouseDownRowIdx;

            if (gri < 0 || gri >= StructureList.Count)
            {
                return;
            }
            MoleculeListItem sli = StructureList[gri];

            if (!MoleculeMx.IsDefined(sli.Molecule))
            {
                return;
            }
            MoleculeViewer.ShowMolecule(sli.Molecule);

            return;
        }
Exemplo n.º 25
0
        void ListItemSelectedCallback(MoleculeListItem sli)
        {
            if (MolEditorCtl == null)
            {
                return;
            }

            if (sli == null)
            {
                DialogResult = DialogResult.Cancel;
                return;
            }

            MoleculeMx mol = sli.Molecule;

            MolEditorCtl.SetPrimaryTypeAndValue(mol.PrimaryFormat, mol.PrimaryValue);
            MolEditorCtl.TagString = sli.Name + "\t" + sli.Molecule.PrimaryValue;             // store name to use if molecule is unchanged
            DialogResult           = DialogResult.OK;
        }
Exemplo n.º 26
0
/// <summary>
/// EditHelmMolecule
/// </summary>
/// <param name="title"></param>
/// <param name="mol"></param>
/// <returns></returns>

        public static MoleculeMx EditHelmMolecule(
            MoleculeMx mol,
            string title = "")
        {
            MoleculeMx mol2 = mol.ConvertTo(MoleculeFormat.Helm);

            string helm = mol2.HelmString;

            HelmEditorDialog editor  = new HelmEditorDialog();
            string           newHelm = editor.Edit(helm);

            if (newHelm == null)
            {
                return(null);
            }

            mol2.SetPrimaryTypeAndValue(MoleculeFormat.Helm, newHelm);
            return(mol2);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Edit Molecule
        /// </summary>
        /// <param name="title"></param>
        /// <param name="mol"></param>
        /// <returns></returns>

        public static MoleculeMx EditCdkMolMolecule(
            MoleculeMx mol,
            string title = "")
        {
            MoleculeMx     mol2 = null;
            MoleculeFormat molFormat;
            string         molString;

            try
            {
                Instance.MoleculeCtl.Molecule = mol;
                INativeMolControl molCtl = (INativeMolControl)Instance.MoleculeCtl.KekuleControl;
                molCtl.EditorReturnedHandler = new MolEditorReturnedHandler(Instance.MolLibEditorReturned);

                Instance.Text = title;
                //molCtl.RenditorName = title; // shows as tooltip on editor Done button
                Instance.MoleculeCtl.InSetup = true;
                MoleculeMx.SetRendererStructure(molCtl, mol);
                Instance.MoleculeCtl.InSetup = false;
                Instance.MoleculeChanged     = false;

                DialogResult dr =                 // Show the form. The shown event invokes Draw & the dialog is ended when drawing is done
                                  Instance.ShowDialog(SessionManager.ActiveForm);

                if (dr != DialogResult.OK)
                {
                    return(null);
                }

                molCtl.GetMolecule(out molFormat, out molString);
                mol2 = new MoleculeMx(molFormat, molString);
                return(mol2);
            }

            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "Error editing structure");
                Instance.MoleculeCtl.InSetup = false;
                return(null);
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Do Generic display of a list of structures
        /// </summary>
        /// <param name="title"></param>
        /// <param name="cidLabel"></param>
        /// <param name="structLabel"></param>
        /// <param name="structures"></param>

        public static void DisplayStructures(
            string title,
            string cidLabel,
            string structLabel,
            List <MoleculeMx> structures,
            MoleculeGridPanel gridPanel,
            bool embedDataInQuery)
        {
            QueryManager qm = null;

            MetaTable mt = MetaTableCollection.GetWithException("Generic_Structure_Table");

            mt.MetaBrokerType = MetaBrokerType.NoSql;

            Query      q  = ToolHelper.InitEmbeddedDataToolQuery(mt);
            QueryTable qt = q.Tables[0];

            qt.Label = title;
            qt.GetQueryColumnByName("CompoundId").Label = cidLabel;
            qt.GetQueryColumnByName("Structure").Label  = structLabel;

            DataTableMx dt = q.ResultsDataTable as DataTableMx;

            for (int mi = 0; mi < structures.Count; mi++)
            {
                MoleculeMx cs  = structures[mi];
                DataRowMx  dr  = dt.NewRow();
                string     cid = cs.Id;
                if (Lex.IsUndefined(cid))
                {
                    cid = (mi + 1).ToString();
                }
                dr[qt.Alias + ".CompoundId"] = new CompoundId(cid);
                dr[qt.Alias + ".Structure"]  = cs;
                dt.Rows.Add(dr);
            }

            DisplayData(q, dt, gridPanel, embedDataInQuery);

            return;
        }
Exemplo n.º 29
0
        private void DelayedEditMolecule(object arg)
        {
            try
            {
                int    ci  = (int)arg;
                string txt = Criteria.Text.Substring(ci + 16);                 // pick up structure name
                int    i1  = txt.IndexOf("]");
                if (i1 < 0)
                {
                    return;
                }
                string sid = txt.Substring(0, i1).Trim().ToUpper();

                string chime = "";
                if (LabeledCriteria.Structures.ContainsKey(sid))
                {
                    chime = LabeledCriteria.Structures[sid];
                }
                MoleculeMx mol = new MoleculeMx(MoleculeFormat.Chime, chime);

                MoleculeMx mol2 = MoleculeEditor.Edit(mol, MoleculeRendererType.Unknown, "Edit Structure");
                if (mol2 == null)
                {
                    return;
                }

                if (mol2.IsChemStructureFormat)                 // store chime for chem structure
                {
                    mol2.ConvertTo(MoleculeFormat.Chime);
                }

                LabeledCriteria.Structures[sid] = mol2.GetPrimaryTypeAndValueString();
                return;
            }

            catch (Exception ex)
            {
                return;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Retrieve an existing molecule and store in MoleculeControl
        /// </summary>
        /// <param name="molCtl"></param>
        /// <param name="mc"></param>

        public static void RetrieveDatabaseStructure(
            MoleculeControl molCtl,
            MetaColumn mc)
        {
            MetaTable mt = null;
            string    cid = "", txt;

            txt = "compound id";
            if (mc != null)
            {
                mt   = mc.MetaTable;
                txt += " (" + mt.KeyMetaColumn.Label + ", etc.)";
            }

            txt = "Enter the " + txt + " that you want to use as a model.";

            while (true)
            {
                cid = InputCompoundId.Show(txt, "Retrieve Molecule from Database", cid, mt);
                if (String.IsNullOrEmpty(cid))
                {
                    return;
                }

                string molString = InputCompoundId.Molecule.PrimaryValue;
                if (String.IsNullOrEmpty(molString))
                {
                    MessageBoxMx.ShowError("Compound number is not in the database, try again.");
                    continue;
                }

                MoleculeMx cs = InputCompoundId.Molecule;

                cs.RemoveStructureCaption();                                      // remove any caption
                molCtl.SetPrimaryTypeAndValue(cs.PrimaryFormat, cs.PrimaryValue); // set mol
                molCtl.SetTemporaryMoleculeTag(cid);                              // associate the cid in case saved as history/favorite
                break;
            }
        }