Esempio n. 1
0
        public void Setup(ParsedStructureCriteria psc)
        {
            if (String.IsNullOrEmpty(psc.Options))
            {
                psc.Options = FullStructureSearchType.Tautomer;
            }

            if (psc.Exact)
            {
                MExact.Checked = true;
            }
            else if (psc.Isomer)
            {
                Isomer.Checked = true;
            }
            else if (psc.Tautomer)
            {
                Tautomer.Checked = true;
            }
            else if (psc.Parent)
            {
                ParentMol.Checked = true;
            }
            else
            {
                MExact.Checked = true;
            }
        }
Esempio n. 2
0
        public void Setup(ParsedStructureCriteria psc)
        {
            InitSimOptionsIfUndefined(psc);

            if (psc.SimilarityType == SimilaritySearchType.Normal)
            {
                MolsimNormalCtl.Checked = true;
            }
            else if (psc.SimilarityType == SimilaritySearchType.Sub)
            {
                MolsimSubsimCtl.Checked = true;
            }
            else if (psc.SimilarityType == SimilaritySearchType.Super)
            {
                MolsimSuperCtl.Checked = true;
            }
            else if (psc.SimilarityType == SimilaritySearchType.ECFP4)
            {
                ECFP4Ctl.Checked = true;
            }

            if (psc.MinimumSimilarity <= 0 || psc.MinimumSimilarity > 1)
            {
                psc.MinimumSimilarity = MoleculeMx.DefaultMinSimScore;
            }
            MinSim.Text = psc.MinimumSimilarity.ToString();

            if (psc.MaxSimHits <= 0)
            {
                psc.MaxSimHits = MoleculeMx.DefaultMaxSimHits;
            }
            MaxHits.Text = psc.MaxSimHits.ToString();

            ECFP4Ctl.Enabled = EcfpSimilaritySearchIsSupportedForColumn(psc);
        }
Esempio n. 3
0
        /// <summary>
        /// EcfpSimilaritySearchIsSupportedForColumn
        /// </summary>
        /// <param name="psc"></param>
        /// <returns></returns>

        bool EcfpSimilaritySearchIsSupportedForColumn(
            ParsedStructureCriteria psc)
        {
            QueryColumn qc = psc.QueryColumn;

            if (qc == null || qc.MetaColumn == null || qc.QueryTable == null || qc.QueryTable.MetaTable == null)
            {
                return(false);                // assume not available if no info
            }
            MetaColumn mc = qc.MetaColumn;
            MetaTable  mt = mc.MetaTable;

            if (mc.DataType != MetaColumnType.Structure || !mc.IsSearchable)
            {
                return(false);
            }

            if (mc.IsMetaTableEcfpSimilaritySearchable())
            {
                return(true);
            }

            else
            {
                return(false);
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Update depiction style
        /// </summary>
        /// <param name="psc"></param>

        public void UpdateDepictions(ParsedStructureCriteria psc)
        {
            SmallWorldPredefinedParameters swp = psc.SmallWorldParameters;             // new values

            if (Qm == null || Qm.ResultsFormatter == null ||
                Qm.ResultsFormatter.StructureHighlightPssc == null ||
                Qm.ResultsFormatter.StructureHighlightPssc.SmallWorldParameters == null)
            {
                return;
            }

            ResultsFormatter fmtr = Qm.ResultsFormatter;
            SmallWorldPredefinedParameters swp2 =             // current view values
                                                  fmtr.StructureHighlightPssc.SmallWorldParameters;

            psc.Highlight = swp2.Highlight = swp.Highlight;
            psc.Align     = swp2.Align = swp.Align;

            int i = SmallWorldData.GetSvgOptionsIndex(swp2.Highlight, swp2.Align);
            SmallWorldDepictions d = fmtr.SmallWorldDepictions;

            if ((swp.Highlight || swp.Align) && d != null && i != 0 && d.SvgDict[i] == null)           // need to start retrieval for depiction type we don't alread have?
            {
                d.StartDepictionRetrieval(Qm, psc.QueryColumn, swp2.Highlight, swp2.Align);
                return;                 // leave display as is for now
            }

            else                                                           // clear current decpiction so new one shows
            {
                Qm.DataTableManager.ResetFormattedValues(psc.QueryColumn); // clear existing bitmaps
                Qm.MoleculeGrid.RefreshDataSource();
            }

            return;
        }
Esempio n. 5
0
        public static DialogResult Show(
            QueryColumn qc)
        {
            ParsedStructureCriteria pssc;
            string tok;

            if (Instance == null)
            {
                Instance = new CriteriaStructureFormatDialog();
            }
            CriteriaStructureFormatDialog cfd = Instance;

            if (!ParsedStructureCriteria.TryParse(qc, out pssc) ||
                (pssc.SearchType != StructureSearchType.Substructure && pssc.SearchType != StructureSearchType.SmallWorld &&
                 pssc.SearchType != StructureSearchType.Related))
            {
                XtraMessageBox.Show("Only structure columns with criteria can have formatting defined");
                return(DialogResult.Cancel);
            }

            // Setup

            new JupyterGuiConverter().ConvertFormOrUserControl(Instance);

            if (pssc.SearchType == StructureSearchType.SmallWorld)
            {
                cfd.HilightStructures.Checked = pssc.SmallWorldParameters.Highlight;
                cfd.AlignStructures.Checked   = pssc.SmallWorldParameters.Align;
            }

            else             // Other structure match hilighting (i.e. SS)
            {
                cfd.HilightStructures.Checked = pssc.Highlight;
                cfd.AlignStructures.Checked   = pssc.Align;
            }

            // Show form & get new values

            DialogResult dr = cfd.ShowDialog(SessionManager.ActiveForm);

            if (dr == DialogResult.Cancel)
            {
                return(dr);
            }

            if (pssc.SearchType == StructureSearchType.SmallWorld)
            {
                pssc.SmallWorldParameters.Highlight = cfd.HilightStructures.Checked;
                pssc.SmallWorldParameters.Align     = cfd.AlignStructures.Checked;
            }

            else             // Other structure match hilighting (i.e. SS)
            {
                pssc.Highlight = cfd.HilightStructures.Checked;
                pssc.Align     = cfd.AlignStructures.Checked;
            }

            pssc.ConvertToQueryColumnCriteria(qc);
            return(dr);
        }
Esempio n. 6
0
/// <summary>
/// Store option subcontrol values in ParsedStructureCriteria
/// </summary>
/// <returns></returns>

        public bool GetValues(ParsedStructureCriteria psc)
        {
            psc.Highlight = Highlight.Checked;
            psc.Align     = Align.Checked;

            return(true);
        }
Esempio n. 7
0
        /// <summary>
        /// Build the Query, QueryManager and DataTable for the matching structure display
        /// </summary>

        public void BuildStructureDisplayQuery()
        {
            MetaTable mt = MetaTableCollection.Get("QuickSearchRelatedStructures");

            if (mt == null)
            {
                DebugLog.Message("QuickSearchRelatedStructures MetaTable not found");
                RSC.MoleculeGridPageControl.Visible = false;
                return;
            }

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

            q.UserObject.Name     = qt.MetaTable.Label;
            StructureDisplayQuery = q;

            QueryColumn qc = qt.FirstStructureQueryColumn;

            if (qc != null)             // setup dummy criteria
            {
                ParsedStructureCriteria pssc = new ParsedStructureCriteria();
                pssc.SearchType = StructureSearchType.FullStructure;                 // just full structure search for now
                pssc.Molecule   = new MoleculeMx(MoleculeFormat.Smiles, "C");        // placeholder structure
                pssc.ConvertToQueryColumnCriteria(qc);

                qc.DisplayFormatString = "Highlight=true;Align=true";
            }

            string title = "Related Structures";

            qt.Label = title;

            DataTableMx dt = q.ResultsDataTable as DataTableMx;

            Qm = ToolHelper.SetupQueryManager(q, dt);

            MoleculeGridPageControl mgpc = RSC.MoleculeGridPageControl;
            MoleculeGridPanel       gp   = mgpc.MoleculeGridPanel;

            mgpc.Width  = RSC.Width - 3;            // be sure we have page control correctly sized
            mgpc.Height = RSC.Height - mgpc.Top - 3;

            ToolHelper.SetupGridPanelForDisplay(Qm, mgpc.MoleculeGridPanel, true, true);

            MoleculeGridControl grid = mgpc.MoleculeGrid;

            if (grid != null && grid.GV != null)
            {
                grid.GV.IndicatorWidth = 40;                 // narrow indicator a bit
            }
            //ToolHelper.DisplayData // build and display empty grid for query with columns scaled to fit the grid
            //		(q, dt, RSC.MoleculeGridPageControl.MoleculeGridPanel, true, true);

            return;
        }
Esempio n. 8
0
        bool UpdateAssociatedSmallWorldQueryColumns(
            ParsedStructureCriteria psc)
        {
            if (Qc == null || Qc.QueryTable == null)
            {
                return(false);
            }

            SmallWorldPredefinedParameters swp = psc.SmallWorldParameters;

            if (swp == null)
            {
                return(false);
            }

            MetaTable mt = Qc.MetaColumn.MetaTable;

            if (Lex.Eq(mt.Name, MetaTable.SmallWorldMetaTableName))             // special SmallWorld table
            {
                string dbCriteria = Lex.IsDefined(swp.Database) ? "Database in (" + swp.Database + ")" : "";
                SetSwQcCriteria("Database", dbCriteria, swp.Database);

                SetSwQcCriteria("distance", swp.Distance.Format());
                SetSwQcCriteria("terminalUp", swp.TerminalUp.Format());
                SetSwQcCriteria("terminalDown", swp.TerminalDown.Format());
                SetSwQcCriteria("ringUp", swp.RingUp.Format());
                SetSwQcCriteria("ringDown", swp.RingDown.Format());
                SetSwQcCriteria("linkerUp", swp.LinkerUp.Format());
                SetSwQcCriteria("linkerDown", swp.LinkerDown.Format());
                SetSwQcCriteria("minorMutations", swp.MutationMinor.Format());
                SetSwQcCriteria("majorMutations", swp.MutationMajor.Format());
                SetSwQcCriteria("substitutions", swp.SubstitutionRange.Format());
                SetSwQcCriteria("hybridisation", swp.HybridisationChange.Format());

                return(true);
            }

            else if (mt.DatabaseListMetaColumn != null)             // basic structure table
            {
                MetaColumn  dbSetMc = mt.DatabaseListMetaColumn;
                QueryColumn dbSetQc = Qc.QueryTable.GetQueryColumnByName(dbSetMc.Name);
                if (dbSetQc == null)
                {
                    return(false);
                }

                dbSetQc.Criteria        = dbSetMc.Name + " in (" + swp.Database + ")";
                dbSetQc.CriteriaDisplay = swp.Database;
                return(true);
            }

            else
            {
                return(false);             // no other cols
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Get option values & store in ParsedStructureCriteria
        /// </summary>
        /// <returns></returns>

        public bool GetValues(ParsedStructureCriteria psc)
        {
            SmallWorldPredefinedParameters swp;

            if (!GetValues(out swp))
            {
                return(false);
            }
            psc.SmallWorldParameters = swp;

            return(true);
        }
Esempio n. 10
0
        /// <summary>
        /// Return true if structure column can be searched by retrieving structure and matching with method call
        /// </summary>
        /// <param name="strQc"></param>
        /// <returns></returns>

        public static bool CanExecuteInternalStructureSearch(
            QueryColumn strQc)
        {
            ParsedStructureCriteria psc = null;

            MetaColumn strMc = strQc.MetaColumn;

            if (strMc.DataType != MetaColumnType.Structure)
            {
                return(false);                // only some structure searches are non-oracle now
            }
            MetaTable mt = strMc.MetaTable;

            bool parseOk = ParsedStructureCriteria.TryParse(strQc, out psc);

            if (parseOk && psc.SearchType == StructureSearchType.MolSim && psc.SimilarityType == SimilaritySearchType.ECFP4)             // ECFP4 search
            {
                return(true);
            }

            else if (parseOk && psc.SearchType == StructureSearchType.SmallWorld)             // smallworld executed via service calls
            {
                return(true);
            }

            else if (parseOk && psc.SearchType == StructureSearchType.Related)             // related structure search
            {
                return(true);
            }

            else if (mt.MetaBrokerType == MetaBrokerType.Annotation)             // annotation table
            {
                return(true);
            }

            else if (Lex.StartsWith(mt.Name, "USERDATABASE_STRUCTURE_"))             // structure database
            {
                return(true);
            }

            else if (Lex.Eq(strMc.DataTransform, "FromMolFile") ||             // other table with structure stored in usable format
                     Lex.Eq(strMc.DataTransform, "FromChime") ||
                     Lex.Eq(strMc.DataTransform, "FromSmiles"))
            {
                return(true);
            }

            else
            {
                return(false);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Allow user to edit the form
        /// </summary>
        /// <returns></returns>

        public static DialogResult Edit(ParsedStructureCriteria psc)
        {
            if (Instance == null)
            {
                Instance = new CriteriaStructureSimOptions();
            }
            Instance.Psc = psc;
            Instance.Setup();

            DialogResult dr = Instance.ShowDialog(SessionManager.ActiveForm);

            return(dr);
        }
Esempio n. 12
0
        /// <summary>
        /// Start preview structure search
        /// </summary>
        /// <param name="str"></param>

        public void StartQueryExecution(
            ParsedStructureCriteria psc)
        {
            if (SwQuery == null)
            {
                InitializeView();
            }

            if (psc == null || psc.Molecule == null || psc.Molecule.AtomCount < 6)
            {
                ClearDataAndGrid();
                return;
            }

            if (Qm != null && Qm.ResultsFormatter != null)
            {
                Qm.ResultsFormatter.SmallWorldDepictions = null;                 // reset dipictions since any previous depictions are invalid
            }
            string smiles = psc.Molecule.GetSmilesString();

            if (!Lex.Eq(smiles, LastQuerySmiles))
            {
                ClearDataAndGrid();                                               // clear grid if different structure (must still start search since other options may have changed)
            }
            LastPsc         = psc;
            LastQuerySmiles = smiles;

            SearchStartTime = LastUpdateTime = DateTime.Now;
            SearchStatusLabel.Appearance.ForeColor = Color.DarkRed;
            SearchStatusLabel.Text = "Searching...";
            //SystemUtil.Beep(); // debug

            QueryColumn qc = SwQuery.GetFirstStructureCriteriaColumn();

            psc.ConvertToQueryColumnCriteria(qc);

            Timer.Enabled = true;             // enable timer waiting for query execution to complete
            Thread t = new Thread(new ParameterizedThreadStart(ExecuteQueryThreadMethod));

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

            object parm = null;

            t.Start(parm);

            return;
        }
Esempio n. 13
0
 public bool GetValues(ParsedStructureCriteria psc)
 {
     if (MExact.Checked)
     {
         psc.Options = FullStructureSearchType.Exact;
     }
     else if (Isomer.Checked)
     {
         psc.Options = FullStructureSearchType.Isomer;
     }
     else if (Tautomer.Checked)
     {
         psc.Options = FullStructureSearchType.Tautomer;
     }
     else if (ParentMol.Checked)
     {
         psc.Options = FullStructureSearchType.Parent;
     }
     return(true);
 }
Esempio n. 14
0
        public bool GetValues(ParsedStructureCriteria psc)
        {
            double minSim = 0;

            double.TryParse(MinSim.Text, out minSim);
            if (minSim < 0 || minSim > 1.0)
            {
                MessageBoxMx.ShowError("Upper similarity must be between 0.0 and 1.0");
                return(false);
            }

            psc.MinimumSimilarity = minSim;

            int maxHits = -1;

            int.TryParse(MaxHits.Text, out maxHits);
            psc.MaxSimHits = maxHits;

            psc.SimilarityType = GetSelectedSimSearchType();

            return(true);
        }
Esempio n. 15
0
/// <summary>
/// Get the appropriate dictionary for possible criteria values based on the details of the current criteria
/// </summary>
/// <param name="qc"></param>
/// <returns></returns>

        public static string GetCriteriaSpecificDictionary(
            QueryColumn qc)
        {
            string     dictName = qc.MetaColumn.Dictionary;
            QueryTable qt       = qc.QueryTable;

            if (!qc.MetaColumn.IsDatabaseSetColumn)
            {
                return(dictName);
            }
            if (qt.FirstStructureQueryColumn == null)
            {
                return(dictName);                                                  // structure col in table?
            }
            if (Lex.Eq(dictName, "Structure_Databases"))
            {
                dictName = "Structure_Databases";
            }

            ParsedStructureCriteria pssc = qt.GetParsedStructureSearchCriteria();

            if (pssc == null)
            {
                return(dictName);
            }

            if (pssc.IsChemistrySearch)
            {
                return("Structure_Databases");
            }
            else if (pssc.SearchType == StructureSearchType.SmallWorld)
            {
                return("SmallWorldDatabases");
            }
            else
            {
                return(dictName);
            }
        }
Esempio n. 16
0
/// <summary>
/// If sim options are undefined then initialize with default values
/// </summary>
/// <param name="psc"></param>

        public static void InitSimOptionsIfUndefined(ParsedStructureCriteria psc)
        {
            if (psc.SimilarityType == SimilaritySearchType.Unknown)             // get any default if unknown
            {
                string simType, minSimTok, maxHitsTok;
                ToolHelper.GetDefaultSimMethod(out simType, out minSimTok, out maxHitsTok);

                psc.SimilarityType = SimilaritySearchType.Normal;
                try { psc.SimilarityType = (SimilaritySearchType)Enum.Parse(typeof(SimilaritySearchType), simType, true); }
                catch { }

                double.TryParse(minSimTok, out psc.MinimumSimilarity);
                int.TryParse(maxHitsTok, out psc.MaxSimHits);
            }

            if (psc.MinimumSimilarity > 10)
            {
                psc.MinimumSimilarity = psc.MinimumSimilarity / 10;                                         // convert 1-100 range to 0.0 - 1.0
            }
            if (psc.MinimumSimilarity < 0 || psc.MinimumSimilarity > 1.0)
            {
                psc.MinimumSimilarity = .75;
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Scale and translate structure and format into buffer
        /// </summary>
        /// <param name="mol">The structure</param>
        /// <param name="cellStyle">Style/conditional formatting to apply to cell</param>
        /// <param name="commandChar">Command character to use in buffer</param>
        /// <param name="x">Coordinate of left side of structure</param>
        /// <param name="width">Width of molecule box in milliinches</param>
        /// <param name="r">Row in buffer to put on. If less than 0 then return formatted data</param>
        /// <param name="heightInLines">number of lines used</param>

        public FormattedFieldInfo FormatStructure(
            MoleculeMx mol,
            CellStyleMx cellStyle,
            char commandChar,
            int x,
            int width,
            int r,
            ResultsField rfld = null,
            DataRowMx dataRow = null)
        {
            Rectangle destRect, boundingRect;
            int       height;       // formatted  height in milliinches
            bool      markBoundaries;
            int       fixedHeight;
            Bitmap    bm;
            Font      font;
            string    txt, molfile, molString = "", svg, cid = null;
            int       translateType, desiredBondLength = 100;
            int       pixWidth = 0, pixHeight = 0;

            bool debug = DataTableManager.DebugDetails;

            if (debug)
            {
                DebugLog.Message("=============================== FormattingStructure ===============================");
            }
            PerformanceTimer pt      = PT.Start("FormatStructure");
            Stopwatch        swTotal = Stopwatch.StartNew();
            Stopwatch        sw      = Stopwatch.StartNew();

            try
            {
                MoleculeFormat initialCsType  = mol.PrimaryFormat;
                string         initialCsValue = mol.PrimaryValue;

                QueryColumn qc = (rfld != null) ? rfld.QueryColumn : null;

                FormattedFieldInfo ffi = new FormattedFieldInfo();

                if (dataRow != null)                 // get any cid in row
                {
                    int ki = DataTableManager.DefaultKeyValueVoPos;
                    if (ki < dataRow.Length)
                    {
                        cid = dataRow[ki] as string;
                    }
                }

                //DebugLog.Message("FormatStructure " + cid);

                //if (!Rf.Grid) x = x; // debug

                ///////////////////////////////////
                // Highlight structure
                ///////////////////////////////////

                if (StructureHighlightPssc != null)
                {
                    ParsedStructureCriteria pssc = StructureHighlightPssc;

                    // Hilight substructure search match

                    if (pssc.SearchType == StructureSearchType.Substructure ||                     // regular SSS
                        pssc.SearchTypeUnion == StructureSearchType.Substructure)                  // handles related search for just SSS to get hilighting
                    {
                        if (HighlightStructureMatches)
                        {
                            try
                            {
                                mol = StrMatcher.HighlightMatchingSubstructure(mol);
                                if (DebugMx.False)                                 // debug
                                {
                                    //string highlightChildren = mol.MolLib.HighlightChildren;
                                    //Color highlightColor = mol.MolLib.HighlightColor;
                                    if (debug)
                                    {
                                        DebugLog.StopwatchMessage("tHilight", sw);
                                    }
                                }
                            }
                            catch (Exception ex) { ex = ex; }
                        }

                        if (AlignStructureToQuery)
                        {
                            try
                            {
                                mol = StrMatcher.AlignToMatchingSubstructure(mol);
                                if (debug)
                                {
                                    DebugLog.StopwatchMessage("tOrient", sw);
                                }
                            }
                            catch (Exception ex) { ex = ex; }
                        }
                    }

                    // Hilight SmallWorld structure match

                    else if (pssc.SearchType == StructureSearchType.SmallWorld)                     // Hilight SmallWorld structure search results
                    {
                        if (SmallWorldDepictions == null)
                        {
                            SmallWorldDepictions = new SmallWorldDepictions();
                        }

                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;

                        //DebugLog.Message("Depict " + cid + ", Hilight " + swp.Highlight + ", Align " + swp.Align); // + "\r\n" + new StackTrace(true));

                        if ((swp.Highlight || swp.Align) & Lex.IsDefined(cid))                         // call depiction for these
                        {
                            svg = SmallWorldDepictions.GetDepiction(cid, swp.Highlight, swp.Align);

                            if (Lex.IsDefined(svg))                             // have depiction?
                            {
                                {
                                    pixWidth            = MoleculeMx.MilliinchesToPixels(width);
                                    bm                  = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth);
                                    ffi.FormattedBitmap = mol.FormattedBitmap = bm;                                     // store in formatting info and chem structure
                                    return(ffi);
                                }
                            }

                            else if (svg == null)                             // start retrieval of this decpiction type & fall through to get default structure initially
                            {
                                SmallWorldDepictions.StartDepictionRetrieval(Qm, StructureHighlightQc, swp.Highlight, swp.Align);
                            }

                            else
                            {
                            }                                    // tried to get it but failed, fall through to get basic structure
                        }
                    }

                    else if (mol.AltFormDefined("Svg"))                     // svg form exist (e.g. SmallWorld or "related" structure search)?
                    {
                        svg = mol.SvgString;
                        if (Lex.IsDefined(svg))
                        {
                            pixWidth            = MoleculeMx.MilliinchesToPixels(width);
                            bm                  = SvgUtil.GetBitmapFromSvgXml(svg, pixWidth);
                            ffi.FormattedBitmap = mol.FormattedBitmap = bm;                             // store in formatting info and chem structure
                            return(ffi);
                        }
                    }
                }

                ///////////////////////////////////
                // Handle each output device
                ///////////////////////////////////

                ffi.HeightInLines = 1;                 // min of 1 line

                if (Rf.SdFile)
                {
                    FormatSdfileStructure(mol);
                    return(null);
                }

                int pageHeight = 11000;
                if (Rf.PageMargins != null)
                {
                    pageHeight = Rf.PageMargins.Top + Rf.PageHeight + Rf.PageMargins.Bottom;
                }

                if (Rf.Excel || Rf.Word)
                {
                    translateType = 2;
                }
                else
                {
                    translateType = 0;
                }

                if (!Rf.FixedHeightStructures)
                {
                    fixedHeight = 0;                                            // not fixed height
                }
                else if (Rf.Excel || Rf.Word)
                {
                    fixedHeight = 1;                                           // always fixed height
                }
                else
                {
                    fixedHeight = 2;                  // fixed height unless need to expand
                }
                if (Rf.Word && Rf.FixedHeightStructures)
                {
                    markBoundaries = true;
                }
                else
                {
                    markBoundaries = false;
                }

                destRect = new Rectangle(0, 0, width, width * 4 / 5);                 // default dest rect

                ///////////////////////////////////////////////////////////////////////////
                // Tempory fake generation of HELM & associatedimage for biopolymer testing
                ///////////////////////////////////////////////////////////////////////////

                //if (MoleculeMx.HelmEnabled == DebugMx.False) // artificially generate helm molecules
                //	MoleculeMx.SetMoleculeToTestHelmString(mol.GetCorpId().ToString(), mol);

                ///////////////////////////////////////////////////////////////////////////
                // End of tempory fake generation of HELM & associatedimage for biopolymer testing
                ///////////////////////////////////////////////////////////////////////////

                bool fitStructure = true;

                if (mol.IsChemStructureFormat)
                {
                    if (Rf.Grid)                     // special scale for grid
                    {
                        double scale = (float)width / MoleculeMx.StandardBoxWidth;
                        desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale));
                        //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0));
                        desiredBondLength = (int)(desiredBondLength * 90.0 / 100.0);                         // scale down a bit for grid
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tAdjustBondLength1", sw);
                        }
                    }

                    else                     // set desired bond length based on page scaling
                    {
                        float scale = (float)width / MoleculeMx.StandardBoxWidth;
                        desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange((int)(MoleculeMx.StandardBondLength * scale));
                        //desiredBondLength = (int)(ChemicalStructure.StandardBondLength * (Rf.PageScale / 100.0));
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tAdjustBondLength2", sw);
                        }
                    }

                    if (desiredBondLength < 1)
                    {
                        desiredBondLength = 1;
                    }
                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tBeforeFit", sw);
                    }

                    if (fitStructure)
                    {
                        mol.CdkMol.FitStructureIntoRectangle                         // scale and translate structure into supplied rectangle.
                            (ref destRect, desiredBondLength, translateType, fixedHeight, markBoundaries, pageHeight, out boundingRect);
                    }

                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tFitStructure", sw);
                    }

                    ffi.HeightInLines = (int)(destRect.Height / Rf.LineHeight + 1);                     // lines needed
                }

                else if (mol.IsBiopolymerFormat)
                {
                    if (mol.PrimaryFormat == MoleculeFormat.Helm && Rf.Excel)
                    {
                        svg = HelmControl.GetSvg(mol.HelmString);
                        float           inchWidth = width / 1000.0f;               // convert width milliinches to inches
                        Svg.SvgDocument svgDoc    = SvgUtil.AdjustSvgDocumentToFitContent(svg, inchWidth, Svg.SvgUnitType.Inch);
                        RectangleF      svgbb     = svgDoc.Bounds;
                        float           ar        = svgbb.Width / svgbb.Height; // aspect ratio of svg bounding box

                        height            = (int)(width / ar);                  // height in milliinches
                        ffi.HeightInLines = (int)(height / Rf.LineHeight) + 1;  // lines needed

                        destRect = new Rectangle(0, 0, width, height);
                    }
                }

                //////////////////////////
                /// Output to Grid
                //////////////////////////

                if (Rf.Grid)
                {
                    pixWidth  = MoleculeMx.MilliinchesToPixels(destRect.Width);
                    pixHeight = MoleculeMx.MilliinchesToPixels(destRect.Height);

                    if (cellStyle == null)
                    {
                        if (Qm == null || Qm.MoleculeGrid == null)
                        {
                            font = new Font("Tahoma", 8.25f);
                        }
                        else
                        {
                            font = new Font(Qm.MoleculeGrid.Font, FontStyle.Underline);
                        }
                        cellStyle = new CellStyleMx(font, Color.Blue, Color.Empty);
                    }

                    if (mol.IsChemStructureFormat)                     // molfile type molecule
                    {
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tBeforeGetDisplayPreferences", sw);
                        }
                        DisplayPreferences dp = mol.GetDisplayPreferences();
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tGetDisplayPreferences", sw);
                        }

                        //desiredBondLength = mol.CdkMol.AdjustBondLengthToValidRange(desiredBondLength); // be sure bond len within allowed range
                        //if (debug) DebugLog.StopwatchMessage("tAdjustBondLengthToValidRange", sw);
                        //dp.StandardBondLength = MoleculeMx.MilliinchesToDecipoints(desiredBondLength);
                        bm = mol.CdkMol.GetFixedHeightMoleculeBitmap(pixWidth, pixHeight, dp, cellStyle, mol.Caption);
                        if (debug)
                        {
                            DebugLog.StopwatchMessage("tGetBitmap", sw);
                        }
                    }

                    else if (mol.IsBiopolymerFormat)                     // Output HELM image for biopolymer
                    {
                        pixWidth = MoleculeMx.MilliinchesToPixels(width);
                        bm       = HelmConverter.HelmToBitmap(mol, pixWidth);
                    }

                    else
                    {
                        bm = new Bitmap(1, 1);
                    }

                    ffi.FormattedBitmap = mol.FormattedBitmap = bm;      // store in formatting & structure
                    ffi.FormattedText   = "Formatted";                   // indicate formatted (could save structure string but not needed and avoids possible conversion overhead)
                    return(ffi);
                }

                //////////////////////////
                /// Output to Html
                //////////////////////////

                else if (Rf.Html)
                {
                    if (r >= 0)
                    {
                        AssureTbFree(0, r + ffi.HeightInLines - 1);
                    }

                    if (mol.IsChemStructureFormat)
                    {
                        FormatChemStructureHtml(mol, destRect, width, r);
                    }

                    else if (mol.IsBiopolymerFormat)
                    {
                        FormatBiopolymerStructureHtml(mol, destRect, width, r);
                    }

                    if (debug)
                    {
                        DebugLog.StopwatchMessage("tFormatHtmlStructure", sw);
                    }

                    ffi.FormattedBitmap = mol.FormattedBitmap;
                    ffi.FormattedText   = mol.FormattedText;
                    return(ffi);
                }

                /////////////////////////////////////////////////////////////////
                /// Other format, store Smiles or Helm & any cellStyle in buffer
                /////////////////////////////////////////////////////////////////

                else
                {
                    if (mol.IsChemStructureFormat)
                    {
                        if (Rf.ExportStructureFormat == ExportStructureFormat.Smiles)
                        {
                            molString = mol.GetSmilesString();
                        }
                        else
                        {
                            molString = mol.GetChimeString();                          // use Chime if not smiles
                        }
                    }

                    else if (mol.IsBiopolymerFormat)
                    {
                        molString = mol.PrimaryValue;                         // usually Helm but could be sequence
                    }

                    txt = String.Format("{0} {1} {2} {3} {4} {5} {6}",
                                        x, width, destRect.Left, destRect.Top, destRect.Right, destRect.Bottom, molString);

                    if (cellStyle != null)                     // apply style to cell?
                    {
                        txt += " <CellStyle " + cellStyle.Serialize() + ">";
                    }

                    txt = commandChar + " " + txt + "\t";

                    if (r >= 0)
                    {
                        AssureTbFree(0, r + ffi.HeightInLines - 1);
                        Tb.Lines[r] += txt;                         // put in buffer
                    }

                    else
                    {
                        return(new FormattedFieldInfo(txt));                     // just return formatting
                    }
                }

                return(null);
            }

            catch (Exception ex)
            {
                DebugLog.Message(DebugLog.FormatExceptionMessage(ex));
                return(null);
            }

            finally
            {
                pt.Update();
                int formatCount = pt.Count;
                //ClientLog.Message(pt.ToString() + ", " + cs.GetMolHeader()[2]); // + ", " + new StackTrace(true));
                if (debug)
                {
                    DebugLog.StopwatchMessage("tTotalTime", swTotal);
                }
            }
        }
Esempio n. 18
0
        /// <summary>
        /// Setup Form
        /// </summary>
        /// <param name="qc"></param>

        void SetupForm(
            QueryColumn qc)
        {
            bool enabled;

            SetupDepth++;

            Qc = qc;             // column we will be specifying criteria for

            // Setup dialog boxes with current settings

            Psc = ParsedStructureCriteria.Parse(Qc);

            // Enable Search option controls

            enabled           = ChemSearchIsSupportedForColumn;
            SubStruct.Enabled = Similarity.Enabled = Full.Enabled = enabled;
            if (Psc.SearchType == StructureSearchType.Unknown)             // default to SS search if not defined yet
            {
                Psc.SearchType = StructureSearchType.Substructure;
            }

            // Enable SmallWorld Search option controls

            enabled            = SmallWorldSearchIsSupportedForColumn;
            SmallWorld.Enabled = enabled;
            if (enabled)
            {
                if (Psc.SearchType == StructureSearchType.Unknown)                 // default to SmallWorld search
                {
                    Psc.SearchType = StructureSearchType.SmallWorld;
                }
            }
            else if (Psc.SearchType == StructureSearchType.SmallWorld)             // smallworld not allowed
            {
                Psc.SearchType = StructureSearchType.Unknown;
            }

            DisplayPreferences.SetStandardDisplayPreferences(QueryMolCtl.KekuleControl.Preferences);

            if (Psc.SearchType == StructureSearchType.Substructure)
            {
                SubStruct.Checked = true;
                QueryMolCtl.KekuleControl.Preferences.HydrogenDisplayMode = HydrogenDisplayMode.Off;                 // no hydrogen display for SSS
            }

            else if (Psc.SearchType == StructureSearchType.FullStructure)
            {
                Full.Checked = true;
            }

            else if (Psc.SearchType == StructureSearchType.MolSim)
            {
                Similarity.Checked = true;
            }

            else if (Psc.SearchType == StructureSearchType.SmallWorld)
            {
                SmallWorld.Checked = true;
            }

            else
            {
                None.Checked = true;
            }

            QueryMolCtl.SetupAndRenderMolecule(Psc.Molecule);

            QueryMolCtl.EditValueChanged += new System.EventHandler(QueryMolCtl_EditValueChanged);

            //SetMolDisplayFormatText();

            SetupOptions(true);
            SetupDepth--;

            return;
        }
Esempio n. 19
0
/// <summary>
/// Add criteria to query to do a related structure search
/// </summary>
/// <param name="q"></param>

        void ModifyQueryForRelatedStructureSearch(
            Query q,
            MoleculeControl queryMolCtl)
        {
            q.KeyCriteria = q.KeyCriteriaDisplay = "";             // always remove any existing key criteria

            QueryTable  sqt = AddStructureTableToQuery(q);         // be sure we have a structure table in the query
            QueryColumn sqc = sqt.FirstStructureQueryColumn;

            sqc.Selected = true;

            sqc.DisplayFormatString = "Highlight=true";
            if (AlignMatches.Checked)
            {
                sqc.DisplayFormatString += ";Align=true";
            }

            QueryColumn qc = sqt.GetQueryColumnByName("molSrchType");             // include search type

            if (qc != null)
            {
                qc.Selected = true;
            }

            qc = sqt.GetSimilarityScoreQueryColumn();             // and match score
            if (qc != null)
            {
                qc.Selected = true;
            }

            ParsedStructureCriteria pssc = new ParsedStructureCriteria();

            pssc.SearchType = StructureSearchType.Related;

            //string mfText = sqt.KeyQueryColumn.ActiveLabel + ": " + queryCid; // (queryCid no longer be accurate)
            //pssc.Structure = // just store a comment with the CID in the structure
            //	new ChemicalStructureMx(StructureFormat.MolFile, ChemicalStructureMx.GetTextMessageMolFile(mfText));

            MoleculeMx m = QueryMolCtl.Molecule;

            pssc.Molecule = new MoleculeMx(m.PrimaryFormat, m.PrimaryValue);

            if (AltForms.Checked)
            {
                pssc.SearchTypeUnion |= StructureSearchType.FullStructure;
            }
            if (MatchedPairs.Checked)
            {
                pssc.SearchTypeUnion |= StructureSearchType.MatchedPairs;
            }
            if (SmallWorld.Checked)
            {
                pssc.SearchTypeUnion |= StructureSearchType.SmallWorld;
            }
            if (SimilarSearch.Checked)
            {
                pssc.SearchTypeUnion |= StructureSearchType.MolSim;
            }
            if (Substructure.Checked)
            {
                pssc.SearchTypeUnion |= StructureSearchType.Substructure;
            }

            pssc.MinimumSimilarity = .75;
            pssc.MaxSimHits        = 100;
            pssc.Highlight         = true;
            pssc.Align             = AlignMatches.Checked;
            pssc.ConvertToQueryColumnCriteria(sqc);

            if (ExcludeCurrentResultsCids.Checked && CurrentBaseQueryCidHitList != null)      // add not in list criteria
            {
                string queryStrName = queryMolCtl.GetTemporaryStructureTag();                 // see if we can get the cid

                q.KeysToExclude = new HashSet <string>(CurrentBaseQueryCidHitList);
                if (q.KeysToExclude.Contains(queryStrName))                 // keep query id
                {
                    q.KeysToExclude.Remove(queryStrName);
                }
            }

            else
            {
                q.KeyCriteria = q.KeyCriteriaDisplay = "";                 // no key criteria
            }
            return;
        }
Esempio n. 20
0
        /// <summary>
        /// Setup a SmallWorld search that most closely matches a full structure, SSS or Similarity search
        /// </summary>
        /// <param name="qt"></param>
        /// <param name="structQc"></param>
        /// <param name="psc"></param>
        /// <returns></returns>

        ParsedStructureCriteria AdjustSearchForSmallWorldAsNeeded(
            ParsedStructureCriteria psc)
        {
            /*
             * public static SmallWorldPredefinedParameters
             *      SmallWorld = ToSwp("preset=SmallWorld; dist=0-4; tup=0-4; tdn=0-4; rup=0-4; rdn=0-4; lup=0-4; ldn=0-4; maj=0-4; min=0-4; sub=0-4; hyb=0-4"),
             *      Substructure = ToSwp("preset=Substructure; dist=0-4; tup=0-10; tdn=0-0; rup=0-10; rdn=0-0; lup=0-10; ldn=0-0; maj=0-0; min=0-0; sub=0-4; hyb=0-4"),
             *      SuperStructure = ToSwp("preset=SuperStructure; dist=0-4; tup=0-0; tdn=10-0; rup=0-0; rdn=0-10; lup=0-0; ldn=0-10; maj=0-0; min=0-0; sub=0-4; hyb=0-4"),
             *      BemisMurckoFramework = ToSwp("preset=Bemis-Murcko Framework; dist=0-4; tup=0-10; tdn=0-10; rup=0-0; rdn=0-0; lup=0-0; ldn=0-0; maj=0-10; min=0-10; sub=0-4; hyb=0-4"),
             *      NqMCS = ToSwp("preset=Nq MCS; dist=0-4; tup=0-10; tdn=0-10; rup=0-10; rdn=0-10; lup=0-10; ldn=0-0; maj=0-0; min=0-0; sub=0-4; hyb=0-4"),
             *      ElementGraph = ToSwp("preset=Element Graph; dist=0-4; tup=0-0; tdn=0-0; rup=0-0; rdn=0-0; lup=0-0; ldn=0-0; maj=0-0; min=0-0; sub=0-4; hyb=0-4"),
             *      CustomSettings = ToSwp("preset=Custom; dist=0-4; tup=0-4; tdn=0-4; rup=0-4; rdn=0-4; lup=0-4; ldn=0-4; maj=0-4; min=0-4; sub=0-4; hyb=0-4"); // defaults to same values as "SmallWorld"
             */

            SmallWorldPredefinedParameters swp;

            MetaTable mt = psc?.QueryColumn?.MetaTable;

            if (mt == null)
            {
                throw new Exception("Metatable not defined in PSC");
            }

            if (mt.IsCartridgeSearchable)
            {
                return(psc);
            }

            if (!mt.IsSmallWorldSearchable)
            {
                throw new Exception("Data table is not searchable by cartridge or SmallWorld");
            }

            if (psc.SearchType == StructureSearchType.SmallWorld)
            {
                return(psc);                                                              // already SmallWorld search?
            }
            ParsedStructureCriteria psc2 = psc.Clone();

            psc2.SearchType = StructureSearchType.SmallWorld;

            if (psc.SearchType == StructureSearchType.FullStructure)
            {
                swp = CriteriaStructureOptionsSW.ElementGraph.Clone();
            }

            else if (psc.SearchType == StructureSearchType.Substructure)
            {
                swp = CriteriaStructureOptionsSW.Substructure.Clone();
            }

            else if (psc.SearchType == StructureSearchType.MolSim)
            {
                swp = CriteriaStructureOptionsSW.SmallWorld.Clone();
            }

            else
            {
                throw new Exception("Unsupported structure search type for " + mt.Label + ": " + psc.SearchType);
            }

            swp.Database = mt.Name;

            psc2.SmallWorldParameters = swp;
            return(psc2);
        }
Esempio n. 21
0
        /// <summary>
        /// Search button clicked, process input
        /// </summary>
        /// <returns></returns>

        DialogResult ProcessInput()
        {
            CidList      cidList             = null;
            StreamReader structureFileReader = null;
            string       qid;       // query identifier, compoundId, file name or sdFile key value
            QueryManager qm;
            DataTableMx  dt;
            DataColumn   dc;
            DataRowMx    dr;
            //object[] dr; // if using Qe
            DialogResult   dlgRslt = DialogResult.OK;
            Query          q = null;
            QueryTable     qt = null;
            QueryColumn    simScoreQc, structQc;          // query column containing latest query settings
            MetaTable      mt = null;
            MetaColumn     keyMc = null, structMc = null, dbSetMc = null, simScoreMc = null, mc;
            MetaColumnType storageType;
            string         txt, tok;

            if (DatabasesToSearch.Text == "")
            {
                MessageBoxMx.ShowError("Databases to search must be defined.");
                DatabasesToSearch.Focus();
                return(DialogResult.Cancel);
            }

            // Get list of databases

            string[]         dba    = DatabasesToSearch.Text.Split(',');
            List <MetaTable> tables = new List <MetaTable>();

            foreach (string dbLabel0 in dba)
            {
                string dbLabel = dbLabel0.Trim();

                RootTable dbInfo = RootTable.GetFromTableLabel(dbLabel);
                if (dbInfo == null)
                {
                    MessageBoxMx.ShowError("Can't find database " + DatabasesToSearch.Text);
                    DatabasesToSearch.Focus();
                    return(DialogResult.Cancel);
                }

                mt = MetaTableCollection.Get(dbInfo.MetaTableName);
                if (mt == null)
                {
                    MessageBoxMx.ShowError("Unable to locate parent structure table for database: " + DatabasesToSearch.Text);
                    DatabasesToSearch.Focus();
                    return(DialogResult.Cancel);
                }

                if (dbSetMc == null)
                {
                    dbSetMc = mt.DatabaseListMetaColumn;
                }

                tables.Add(mt);
            }

            if (dbSetMc == null)
            {
                throw new Exception("\"Databases\" metacolumn not found for any of the databases to search");
            }

            // Validate other form values

            RetrieveStructures = RetrieveMatchingStructures.Checked;

            bool fromList        = FromList.Checked;
            int  listCidsRead    = 0;
            int  inputQueryCount = -1;

            if (fromList)             // using list, validate list name
            {
                if (SavedListUo == null)
                {
                    MessageBoxMx.ShowError("Compound list must be defined.");
                    ListName.Focus();
                    return(DialogResult.Cancel);
                }

                cidList = CidListCommand.Read(SavedListUo);
                if (cidList == null)
                {
                    MessageBoxMx.ShowError("Error reading list.");
                    ListName.Focus();
                    return(DialogResult.Cancel);
                }

                inputQueryCount = cidList.Count;
            }

            else             // Using SdFile, validate SdFile name
            {
                StructureFile = FileName.Text;
                if (StructureFile == "")
                {
                    MessageBoxMx.ShowError("File must be defined.");
                    FileName.Focus();
                    return(DialogResult.Cancel);
                }

                try { structureFileReader = new StreamReader(StructureFile); structureFileReader.Close(); }
                catch (Exception ex)
                {
                    MessageBoxMx.ShowError("Can't read file: " + Lex.Dq(StructureFile));
                    FileName.Focus();
                    return(DialogResult.Cancel);
                }

                keyField = KeyField.Text;             // get key, blank to use name in 1st line

                inputQueryCount = -1;                 // don't know how many queries unless we read the file (todo?)
            }

            tok = ResultsName.Text.Trim();             // name to store results under
            if (tok == "")
            {
                MessageBoxMx.ShowError("A name for the results must be provided.");
                ResultsName.Focus();
                return(DialogResult.Cancel);
            }

            if (SubStruct.Checked)
            {
                Psc.SearchType = StructureSearchType.Substructure;
            }
            else if (Full.Checked)
            {
                Psc.SearchType = StructureSearchType.FullStructure;
            }
            else if (Similarity.Checked)
            {
                Psc.SearchType = StructureSearchType.MolSim;
            }
            else
            {
                throw new Exception("Unrecognized search type");
            }

            // Write initial log entries

            SearchCount++;
            string logFileName = ClientDirs.DefaultMobiusUserDocumentsFolder + @"\Multistructure Search " + SearchCount + ".txt";

            if (!UIMisc.CanWriteFileToDefaultDir(logFileName))
            {
                return(DialogResult.Cancel);
            }
            LogStream = new StreamWriter(logFileName);

            if (ResultsUo == null)
            {
                ResultsUo = new UserObject(UserObjectType.Annotation);
            }
            ResultsUo.Name = tok;
            UserObjectTree.GetValidUserObjectTypeFolder(ResultsUo);

            DateTime startTime = DateTime.Now;

            WriteToLog("Multiple " + Psc.SearchType + " Search");
            WriteToLog("Databases: " + DatabasesToSearch.Text);
            WriteToLog("Date: " + startTime);
            if (fromList)
            {
                WriteToLog("Input List: " + SavedListUo.Name);
            }
            else
            {
                WriteToLog("Input Structure File: " + StructureFile);
            }
            WriteToLog("Output List: " + ResultsUo.Name);

            WriteToLog("Log File: " + logFileName);
            WriteToLog("");
            WriteToLog("Query, Match, Score");

            int              queryCount           = 0;
            int              matchAtLeastOneCount = 0;
            MoleculeMx       queryStructure       = null; // current structure being searched
            CidList          matchList            = new CidList();
            List <MatchData> matchData            = new List <MatchData>();

            if (FromFile.Checked)             // open SdFile as required
            {
                structureFileReader = new StreamReader(StructureFile);
            }

            // Search of structures one at a time

            while (true)
            {
                if (fromList)                 // get next structure from list
                {
                    if (listCidsRead >= cidList.Count)
                    {
                        break;
                    }
                    qid = cidList[listCidsRead].Cid;
                    listCidsRead++;
                    if (qid.Trim() == "")
                    {
                        continue;
                    }
                    if (qid.ToLower().IndexOf(".mol") > 0 || qid.ToLower().IndexOf(".skc") > 0)
                    {                     // file reference
                        if (!File.Exists(qid))
                        {
                            continue;
                        }
                        if (qid.ToLower().IndexOf(".mol") > 0)
                        {
                            queryStructure = MoleculeMx.ReadMolfile(qid);
                        }
                        else
                        {
                            queryStructure = MoleculeMx.ReadSketchFile(qid);
                        }
                    }

                    else
                    {
                        queryStructure = MoleculeUtil.SelectMoleculeForCid(qid);
                    }
                    if (queryStructure == null || queryStructure.AtomCount == 0)
                    {
                        continue;                                                                              // oops
                    }
                }

                else                 // get next structure from input file
                {
                    qid = null;

                    if (StructureFile.ToLower().EndsWith(".sdf"))
                    {
                        List <SdFileField> fList = SdFileDao.Read(structureFileReader);
                        if (fList == null)                         // end of sdFile
                        {
                            structureFileReader.Close();
                            break;
                        }
                        if (fList.Count == 0)
                        {
                            continue;
                        }

                        queryStructure = new MoleculeMx(MoleculeFormat.Molfile, fList[0].Data);
                        if (queryStructure == null || queryStructure.AtomCount == 0)
                        {
                            continue;
                        }

                        if (keyField != "")                         // key field specified?
                        {
                            qid = SdFileDao.GetDataField(fList, keyField);
                        }
                        else                         // get name from 1st line of molfile
                        {
                            string molFile = fList[0].Data;
                            int    i1      = molFile.IndexOf("\n");
                            if (i1 == 0)
                            {
                                qid = "";
                            }
                            else
                            {
                                qid = molFile.Substring(0, i1).Trim();
                            }
                        }
                        if (string.IsNullOrEmpty(qid))
                        {
                            qid = SdFileDao.GetDataField(fList, "compound_id");
                        }
                    }

                    else                     // assume smiles file
                    {
                        string smiles = structureFileReader.ReadLine();
                        if (smiles == null)                         // end of sdFile
                        {
                            structureFileReader.Close();
                            break;
                        }
                        smiles = smiles.Trim();
                        if (smiles.Length == 0)
                        {
                            continue;
                        }

                        int i1 = smiles.IndexOf(",");                         // get any preceeding queryId
                        if (i1 < 0)
                        {
                            i1 = smiles.IndexOf("\t");
                        }
                        if (i1 >= 0)
                        {
                            qid    = smiles.Substring(0, i1).Trim();
                            smiles = smiles.Substring(i1 + 1).Trim();
                        }

                        queryStructure = new MoleculeMx(MoleculeFormat.Smiles, smiles);
                        if (queryStructure == null || queryStructure.AtomCount == 0)
                        {
                            continue;
                        }
                    }

                    if (qid == null || qid.Trim() == "")
                    {
                        qid = (queryCount + 1).ToString();                                                      // be sure we have a query id
                    }
                }

                queryCount++;                 // count the query
                if (queryStructure == null || queryStructure.AtomCount == 0)
                {
                    WriteToLog("Error converting specific structure " + queryCount.ToString() + ", " + qid);
                    continue;
                }

                queryStructure.RemoveStructureCaption();                 // remove any Mobius-added caption
                Psc.Molecule = queryStructure;

                string msg =
                    "Searching Structure: " + queryCount.ToString();
                if (inputQueryCount > 0)
                {
                    msg += " of " + inputQueryCount.ToString();
                }
                msg += "\n" +
                       "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\n" +
                       "Total Matches: " + matchList.Count.ToString();

                Progress.Show(msg);

                // Do the search over the list of databases

                for (int ti = 0; ti < tables.Count; ti++)
                {
                    mt = tables[ti];

                    q = new Query();                     // build basic query
                    //q.SingleStepExecution = true; // do in single step (doesn't currently return sim score)
                    q.ShowStereoComments = false;

                    qt = new QueryTable(mt);

                    q.AddQueryTable(qt);
                    qt.SelectKeyOnly();                     // start selecting desired cols

                    keyMc = mt.KeyMetaColumn;

                    structMc          = mt.FirstStructureMetaColumn;
                    structQc          = qt.GetQueryColumnByName(structMc.Name);
                    structQc.Selected = RetrieveStructures;

                    dbSetMc = mt.DatabaseListMetaColumn;
                    if (dbSetMc == null)
                    {
                        throw new Exception("\"Databases\" metacolumn not found for table: " + mt.Label);
                    }
                    QueryColumn dbSetQc = qt.GetQueryColumnByName(dbSetMc.Name);
                    dbSetQc.Selected = true;                     // select the database name
                    RootTable root = RootTable.GetFromTableName(mt.Name);
                    txt = " in (" + root.Label + ")";
                    dbSetQc.Criteria        = dbSetMc.Name + txt;
                    dbSetQc.CriteriaDisplay = txt;

                    simScoreMc = mt.SimilarityScoreMetaColumn;
                    simScoreQc = null;
                    if (simScoreMc != null)                     // get sim score if it exists
                    {
                        simScoreQc          = qt.GetQueryColumnByName(simScoreMc.Name);
                        simScoreQc.Selected = true;                         // return sim score
                    }

                    Psc.QueryColumn = structQc;
                    ParsedStructureCriteria psc2 = AdjustSearchForSmallWorldAsNeeded(Psc);
                    psc2.ConvertToQueryColumnCriteria(structQc);                     // format the QC for the structure search

                    DateTime t0 = DateTime.Now;

                    //QueryEngine qe = new QueryEngine();
                    //qe.NextRowsMin = 1000; // minimum number of rows to prefetch
                    //qe.NextRowsMax = -1; // maximum number of rows to prefetch
                    //qe.NextRowsMaxTime = 10000; // max time in milliseconds for next fetch
                    //qe.ExecuteQuery(q);

                    qm = new QueryManager();
                    try { dlgRslt = qm.ExecuteQuery(ref q); }
                    catch (Exception ex)
                    {
                        WriteToLog("Error searching structure: " + ex.Message + ", " + queryCount.ToString() + ", " + qid);
                        continue;
                    }

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

                    double executeTime = TimeOfDay.Delta(ref t0);

                    int offset = qm.DataTableManager.KeyValueVoPos + 1;
                    //int offset = 0; // for QE
                    int keyPos = offset++;
                    int strPos = RetrieveStructures ? offset++ : -1;
                    int dbPos  = offset++;
                    int simPos = offset++;

                    int fetchCnt = 0;
                    while (true)
                    {
                        dr = qm.NextRow();
                        //dr = qe.NextRow(); // for Qe
                        if (dr == null)
                        {
                            break;
                        }

                        fetchCnt++;

                        if (fetchCnt == 1)
                        {
                            matchAtLeastOneCount++;                             // number of queries that have at least one match
                        }
                        MatchData md = new MatchData();
                        md.Qno = queryCount;
                        md.Qid = qid;
                        if (RetrieveStructures)
                        {
                            md.Qstr = "Chime=" + queryStructure.GetChimeString();
                        }

                        CompoundId cid = CompoundId.ConvertTo(dr[keyPos]);
                        md.Mid = cid.Value;

                        if (RetrieveStructures)
                        {
                            MoleculeMx ms = MoleculeMx.ConvertTo(dr[strPos]);
                            if (!NullValue.IsNull(ms))
                            {
                                md.Mstr = "Chime=" + ms.GetChimeString();
                            }
                        }

                        StringMx db = StringMx.ConvertTo(dr[dbPos]);
                        if (!NullValue.IsNull(db))
                        {
                            md.Db = db.Value;
                        }

                        if (Psc.SearchType == StructureSearchType.MolSim)
                        {
                            NumberMx nex = NumberMx.ConvertTo(dr[simPos]);
                            if (!NullValue.IsNull(nex))
                            {
                                md.Score = nex.Value;
                            }
                        }

                        if (matchList.Contains(cid.Value))                         // already have compound id as match for other query?
                        {
                            if (Psc.SearchType != StructureSearchType.MolSim)
                            {
                                continue;                                                             // if similarity search see if more similar
                            }
                            CidListElement le = matchList.Get(cid.Value);                             // reference current score
                            if (le.Tag > md.Score)
                            {
                                continue;                                         // only replace if more similar
                            }
                            matchList.Remove(le.Cid);                             // remove from list
                            for (int mi = 0; mi < matchData.Count; mi++)          // remove from data
                            {
                                if (matchData[mi].Mid == md.Mid)
                                {
                                    matchData.RemoveAt(mi);
                                    break;
                                }
                            }
                        }

                        matchList.Add(md.Mid);
                        matchList.Get(md.Mid).Tag = md.Score;      // keep score in list
                        matchData.Add(md);                         // add to results

                        txt = md.Qid + ", " + md.Mid + ", " + md.Score.ToString();
                        WriteToLog(txt);
                    }                     // Fetch result loop

                    double fetchTime = TimeOfDay.Delta(ref t0);
                }                 // DB loop

                if (Progress.CancelRequested)
                {
                    Progress.Hide();
                    MessageBoxMx.ShowError("Search cancelled.");
                    try { LogStream.Close(); } catch { }
                    return(DialogResult.Cancel);
                }
            }                                           // key loop

            CidListCommand.WriteCurrentList(matchList); // write the list of numbers

            UsageDao.LogEvent("MultipleStructSearch");

            txt =
                "=== Multiple structure search complete ===\r\n\r\n" +

                "Structures Searched: " + queryCount.ToString() + "\r\n";

            txt +=
                "Structures with one or more matches: " + matchAtLeastOneCount.ToString() + "\r\n" +
                "Total Matches: " + matchList.Count.ToString() + "\r\n";

            TimeSpan ts = DateTime.Now.Subtract(startTime);

            ts   = new TimeSpan(ts.Hours, ts.Minutes, ts.Seconds);
            txt += "Total Time: " + ts + "\r\n\r\n";

            WriteToLog("\r\n" + txt);
            try { LogStream.Close(); } catch { }

            if (matchList.Count == 0)
            {
                Progress.Hide();
                MessageBoxMx.ShowError("No matches have been found.");
                return(DialogResult.Cancel);
            }

            tok = "Matching compound ids";
            if (Psc.SearchType == StructureSearchType.MolSim)
            {
                tok = "Similar compound ids";
            }
            txt += tok + " have been written to the current list: " + ResultsUo.Name + "\n" +
                   "Log file written to: " + logFileName + "\n\n" +
                   "Do you want to view the match results?";

            DialogResult dRslt = MessageBoxMx.Show(txt, "Multiple Structure Search", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

            if (dRslt == DialogResult.Cancel)
            {
                return(DialogResult.Cancel);
            }

            else if (dRslt == DialogResult.No)             // show log
            {
                SystemUtil.StartProcess(logFileName);
                return(DialogResult.Cancel);
            }

            // Display results

            Progress.Show("Formatting results...");

            mt                = new MetaTable();
            mt.Name           = "MULTSTRUCTSEARCH_" + SearchCount;
            mt.Label          = "Multiple Structure Search " + SearchCount;
            mt.TableMap       = "Mobius.Tools.MultStructSearch";       // plugin id
            mt.MetaBrokerType = MetaBrokerType.NoSql;

            ColumnSelectionEnum structureColumnSelection = RetrieveStructures ? ColumnSelectionEnum.Selected : ColumnSelectionEnum.Unselected;

            keyMc       = keyMc.Clone();
            keyMc.Name  = "MatchingCid";
            keyMc.Label = "Matching Compound Id";
            mt.AddMetaColumn(keyMc);

            structMc                  = structMc.Clone();
            structMc.Name             = "MatchingStructure";
            structMc.Label            = "Matching Structure";
            structMc.InitialSelection = structureColumnSelection;
            mt.AddMetaColumn(structMc);

            dbSetMc      = dbSetMc.Clone();
            dbSetMc.Name = "Database";
            mt.AddMetaColumn(dbSetMc);
            //if (DatabasesToSearch.Text.Contains(","))
            dbSetMc.InitialSelection = ColumnSelectionEnum.Selected;

            mc = mt.AddMetaColumn("Molsimilarity", "Similarity Search Score", MetaColumnType.Number, ColumnSelectionEnum.Unselected, 10);
            if (Psc.SearchType == StructureSearchType.MolSim)
            {
                mc.InitialSelection = ColumnSelectionEnum.Selected;
            }

            mc = mt.AddMetaColumn("QueryNo", "Query Number", MetaColumnType.Integer);
            //mc = mt.AddMetaColumn("QueryMatchNo", "Query Match Number", MetaColumnType.Integer);

            mc = mt.AddMetaColumn("QueryId", "Query Id", MetaColumnType.String);
            mc = mt.AddMetaColumn("QueryStructure", "Query Structure", MetaColumnType.Structure);
            mc.InitialSelection = structureColumnSelection;

            q  = ToolHelper.InitEmbeddedDataToolQuery(mt);
            dt = q.ResultsDataTable as DataTableMx;

            for (int mi = 0; mi < matchData.Count; mi++)
            {
                MatchData md = matchData[mi];
                dr = dt.NewRow();
                dr[qt.Alias + ".MatchingCid"] = new CompoundId(md.Mid);
                if (RetrieveStructures)
                {
                    dr[qt.Alias + ".MatchingStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Mstr);
                }
                dr[qt.Alias + ".Database"] = new StringMx(md.Db);
                if (Psc.SearchType == StructureSearchType.MolSim)
                {
                    dr[qt.Alias + ".Molsimilarity"] = new NumberMx(md.Score);
                }
                dr[qt.Alias + ".QueryNo"] = new NumberMx(md.Qno);
                dr[qt.Alias + ".QueryId"] = new StringMx(md.Qid);
                if (RetrieveStructures)
                {
                    dr[qt.Alias + ".QueryStructure"] = new MoleculeMx(MoleculeFormat.Chime, md.Qstr);
                }

                dt.Rows.Add(dr);
            }

            ToolHelper.DisplayData(q, dt, true);

            Progress.Hide();
            return(DialogResult.OK);
        }
Esempio n. 22
0
        /// <summary>
        /// Initialize for any structure hilighting
        /// </summary>

        void InitializeStructureHilighting()
        {
            QueryColumn qc = null;

            if (StructureHighlightingInitialized)
            {
                return;
            }

            // Structure match hilighting / orienting

            try
            {
                do
                {
                    qc = Query.GetFirstStructureCriteriaColumn();
                    if (qc == null)
                    {
                        break;
                    }
                    if (Lex.IsUndefined(qc.Criteria))
                    {
                        break;
                    }

                    ParsedSingleCriteria psc = MqlUtil.ParseQueryColumnCriteria(qc);
                    if (psc == null || Lex.IsUndefined(psc.Value))
                    {
                        break;
                    }

                    ParsedStructureCriteria pssc = ParsedStructureCriteria.ConvertFromPscToPssc(psc);

                    StructureDisplayFormat sdf = StructureDisplayFormat.Deserialize(qc.DisplayFormatString);                     // get any hilighting info from format

                    if (pssc.SearchType == StructureSearchType.Substructure)
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for highlighting
                        }
                    }

                    else if (pssc.SearchType == StructureSearchType.SmallWorld && pssc.SmallWorldParameters != null)
                    {
                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;
                        HighlightStructureMatches = swp.Highlight;
                        AlignStructureToQuery     = swp.Align;
                        //SmallWorldDepictions = null; // depiction cache
                    }

                    else if (pssc.SearchType == StructureSearchType.Related)                     //
                    {
                        string chime = MoleculeMx.MolfileStringToChimeString(qc.MolString);
                        if (!String.IsNullOrEmpty(chime))
                        {
                            AlignStructureToQuery     = Lex.Contains(psc.Value2, "Orient") || Lex.Contains(psc.Value2, "Align=True");
                            HighlightStructureMatches = !(Lex.Contains(psc.Value2, "NoHighlight") || Lex.Contains(psc.Value2, "Highlight=false"));
                            MoleculeMx cs = new MoleculeMx(MoleculeFormat.Chime, chime);
                            StrMatcher = new StructureMatcher();
                            StrMatcher.SetSSSQueryMolecule(cs);                             // set query used for SSS highlighting
                        }
                    }

                    else if (sdf.Highlight || sdf.Align)                     // other cases
                    {
                        HighlightStructureMatches = sdf.Highlight;
                        AlignStructureToQuery     = sdf.Align;
                    }

                    else
                    {
                        break;                      // no hilighting / orienting
                    }
                    StructureHighlightQc   = qc;
                    StructureHighlightPssc = pssc;
                } while (false);
            }

            catch (Exception ex)             // log & ignore any errors
            {
                string msg = DebugLog.FormatExceptionMessage(ex);
                if (qc != null)
                {
                    msg += "\r\n" +
                           "Criteria: " + qc.Criteria + "\r\n" +
                           "Molstring: " + qc.MolString;
                }

                DebugLog.Message(msg);
                return;
            }

            // Atom number display (not currently used)

            SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.None;             // see if need to display atom numbers
            for (int ti = 1; ti < Rf.Tables.Count; ti++)
            {
                ResultsTable rt = Rf.Tables[ti];
                MetaTable    mt = rt.MetaTable;
                if (mt.Name.IndexOf("todo: table that needs atom number display") >= 0)
                {
                    SS.I.DisplayAtomNumbers = (int)AtomNumberDisplayMode.All;
                    break;
                }
            }

            StructureHighlightingInitialized = true;
            return;
        }
Esempio n. 23
0
        /// <summary>
        /// Prep non-Oracle query
        /// </summary>
        /// <param name="eqp"></param>
        /// <returns></returns>

        public override string PrepareQuery(
            ExecuteQueryParms eqp)
        {
            int cti;

            Eqp = eqp;
            QueryEngine qe = eqp.Qe;
            Query       q  = qe.Query;
            QueryTable  qt = eqp.QueryTable;
            QueryColumn qc;
            MetaTable   mt = qt.MetaTable;
            MetaColumn  mc = null;

            StructCriteriaQc = KeyCriteriaQc = null;

            QueryColumn strQc = qt.FirstStructureQueryColumn;

            if (strQc != null && Lex.IsDefined(strQc.Criteria))
            {
                StructCriteriaQc = strQc;
            }
            else
            {
                throw new Exception("Structure criteria not defined");
            }

            Pssc = ParsedStructureCriteria.Parse(StructCriteriaQc);

            QueryColumn keyQc = qt.KeyQueryColumn;

            if (keyQc != null && Lex.IsDefined(q.KeyCriteria))             //keyQc.Criteria))
            {
                KeyCriteriaQc = keyQc;
            }

            if (StructCriteriaQc == null &&
                KeyCriteriaQc == null &&
                eqp.SearchKeySubset == null)
            {
                throw new Exception("NonSqlBroker - No criteria specified");
            }

            SelectList = new List <MetaColumn>();            // list of selected metacolumns
            foreach (QueryColumn qc2 in qt.QueryColumns)
            {
                if (qc2.MetaColumn == null)
                {
                    continue;                                         // in case metacolumn not defined
                }
                if (qc2.IsKey)
                {
                    qc2.Selected = true;
                }
                if (qc2.Selected || qc2.SortOrder != 0)
                {
                    SelectList.Add(qc2.MetaColumn);
                }
            }

            // Setup for ECFP4 similarity search

            if (Pssc.SearchType == StructureSearchType.MolSim && Pssc.SimilarityType == SimilaritySearchType.ECFP4)
            {
                Ecfp4Dao = null;                 // reset Dao to initiate new search
                return("");
            }

            else if (Pssc.SearchType == StructureSearchType.SmallWorld) // SmallWorld search
            {
                SwDao = null;                                           // reset Dao to initiate new search
                return("");
            }

            else if (Pssc.SearchType == StructureSearchType.Related) // Related structure search
            {
                RSS = null;                                          // reset to initiate new search
                return("");
            }

            else if (!MqlUtil.IsCartridgeMetaTable(mt)) // must be non chemical cartridge table (e.g. User structure DB or structure in Annotation table
            {
                return("");                             // everything looks ok, query criteria stored here, no sql returned
            }
            else
            {
                throw new Exception("Unsupported NonSqlBroker search for table: " + eqp.QueryTable.MetaTable.Label);
            }
        }
Esempio n. 24
0
/// <summary>
/// Setup option subcontrols for ParsedStructureCriteria
/// </summary>
/// <param name="psc"></param>

        public void Setup(ParsedStructureCriteria psc)
        {
            Highlight.Checked = psc.Highlight;
            Align.Checked     = psc.Align;
        }