コード例 #1
0
        private void InsertScriptButton_Click(object sender, EventArgs e)
        {
            string fileName = @"<MiscConfigDir>\MobiusSpotfireApi.IronPythonScript.txt";
            string script   = new ServerFile().ReadAll(fileName);

            string args = "";

            Api.ConfigureAnalysisForMobiusUse(args);

            Clipboard.SetText(script);             // put script on clipboard

            string msg =
                @"The necessary Document Properties have been created. 

You must manually create a script named MobiusSpotfireApi, insert the
text currently on the clipboard into the script and save it.

Then, associate this script with the MobiusSpotfireApiCall so that the script
is called whenever the the property is changed.

Finally, save the analysis to the Spotfire Libary. You can then add this Spotfire 
analysis to any Mobius query from the Query Results page using the 
Add View > Select Spotfire analysis from library command.";

            MessageBoxMx.Show(msg);

            return;
        }
コード例 #2
0
		/// <summary>
		/// Rename a Spotfire Column
		/// </summary>
		/// <param name="ri"></param>

		void RenameColumn(int ri)
		{
			DataRow dRow = FieldDataTable.Rows[ri];
			string currentName = dRow["SpotfireColNameField"] as string;

			string newName = InputBoxMx.Show("Name:", "Rename Column", currentName);
			if (Lex.IsUndefined(newName) || newName == currentName) return;

			for (int ri2 = 0; ri2 < FieldDataTable.Rows.Count; ri2++)
			{
				if (ri2 == ri) continue;
				string name = FieldDataTable.Rows[ri2]["SpotfireColNameField"] as string;
				if (Lex.Eq(name, newName))
				{
					MessageBoxMx.ShowError("Name already in use: " + newName);
					return;
				}
			}

			dRow["SpotfireColNameField"] = newName;

			CurrentMap.ColumnMapCollection[ri].SpotfireColumnName = newName;

			Api.RenameColumn(CurrentMap.SpotfireDataTable?.Name, currentName, newName);

			return;
		}
コード例 #3
0
        /// <summary>
        /// Log fatal error & display to user
        /// </summary>
        /// <param name="ex"></param>

        static void LogUnexpectedError(Exception ex)
        {
            string msg = DebugLog.FormatExceptionMessage(ex);

            ClientLog.LogFatalErrorMessage(msg); // special log
            ClientLog.Message(msg);              // regular log
            MessageBoxMx.ShowError(msg);         // show to user
        }
コード例 #4
0
        private bool GetPersonalMoeExecutableLocation(string mxp)
        {
            string moeArgs, newCl = "";

            while (true)             // loop til we get a valid executable name or cancelled
            {
                if (mxp != null)
                {
                    string msg =
                        "Unable to find MOE executable:\r\n\r\n" +
                        "  " + mxp + "\r\n\r\n" +
                        "Would you like to define a new location for the MOE executable?";
                    DialogResult dr = MessageBoxMx.Show(msg, "Can't Find MOE", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
                    if (dr != System.Windows.Forms.DialogResult.Yes)
                    {
                        return(false);
                    }
                }

                string cl = Preferences.Get("MoeCommandLine");                 // get any personal preference first

                string txt =
                    "Enter your preferred \"non-standard\" personal location for MOE executable file.\r\n" +
                    "For example, the Target field from the MOE Desktop shortcut.\r\n" +
                    "To use the system default executable set the value to blank.";

                newCl = InputBoxMx.Show(txt, "Set location of MOE executable file", cl);
                if (newCl == null)
                {
                    return(false);                               // cancelled
                }
                else if (newCl.Trim() == "")
                {
                    break;                                          // use system default
                }
                else
                {
                    ParseMoeCommandLine(newCl, out mxp, out moeArgs);
                    if (File.Exists(mxp))
                    {
                        break;
                    }
                }
            }

            Preferences.Set("MoeCommandLine", newCl);
            return(true);
        }
コード例 #5
0
        private void OKButton_Click(object sender, EventArgs e)
        {
            if (ExportToFile.Checked)
            {
                if (ExportSingle.Checked)
                {
                    string fileName = FileName.Text;
                    if (Directory.Exists(fileName))
                    {
                        MessageBoxMx.Show("\"" + fileName + "\" appears to be a folder name rather than a file name", "Mobius",
                                          MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        FileName.Focus();
                        return;
                    }
                    string fullFileName = UIMisc.CheckFileName(2, FileName, _lastValidatedFileName, ClientDirs.DefaultMobiusUserDocumentsFolder, ".pdb");
                    if (fullFileName == "")
                    {
                        return;
                    }
                    FileName.Text = fullFileName;
                }

                else
                {
                    string folder = FileName.Text;
                    if (String.IsNullOrEmpty(folder))
                    {
                        folder = ClientDirs.DefaultMobiusUserDocumentsFolder;
                    }
                    folder = Path.GetDirectoryName(folder);
                    if (!Directory.Exists(folder))
                    {
                        MessageBoxMx.Show("Folder does not exist: " + folder, "Mobius",
                                          MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        FileName.Focus();
                        return;
                    }
                }
            }

            DialogResult = DialogResult.OK;

            //UIMisc.BringActiveFormToFront(); // after showdialog be sure active form is on top
        }
コード例 #6
0
        public void Execute(string command)
        {
            try
            {
                command = command.Replace("%20", " ");                 // convert any special URL characters (todo: more complete translation)
                DebugLog.Message("MobiusClientIntegrationPoint Command: " + Lex.AddDoubleQuotes(command));
                CommandExec.PostCommand(command);
            }

            catch (Exception ex)
            {
                string msg =
                    "Error executing external command: " + command + "\n\n" +
                    DebugLog.FormatExceptionMessage(ex);

                ServicesLog.Message(msg);
                MessageBoxMx.ShowError(msg);
            }
        }
コード例 #7
0
        private void Search_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dr = ProcessInput();
                if (dr == DialogResult.OK)
                {
                    DialogResult = dr;
                }
                return;
            }

            catch (Exception ex)
            {
                string msg = "Unexpected error: " + ex.Message + "\r\n" + DebugLog.FormatExceptionMessage(ex);
                ServicesLog.Message(msg);
                MessageBoxMx.ShowError(msg);
            }
        }
コード例 #8
0
        private void OkButton_Click(object sender, EventArgs e)
        {
            if (SelectedQuery == null)
            {
                QuerySelectorControl.Focus();
                MessageBoxMx.ShowError("A query must be selected");
                return;
            }

            if (SelectedView == null)
            {
                ViewSelectorComboBox.Focus();
                MessageBoxMx.ShowError("A view must be selected for the query");
                return;
            }

            DialogResult = DialogResult.OK;
            return;
        }
コード例 #9
0
        /// <summary>
        /// If the user selected a field from a non-summarized table, give them the option to replace it with the field from the
        /// summarized table (if available).  Performance is better. This will also avoid extra rows as well as a cartesian product.
        /// </summary>

        private void CheckForSummarizedVersionOfMetaColumn()
        {
            return;

#if false // disabled for now
            if (SelectedColumn == null || SelectedColumn.QueryColumn == null)
            {
                return;
            }

            QueryColumn qc = SelectedColumn.QueryColumn;
            MetaColumn  mc = qc.MetaColumn;
            MetaTable   mt = mc.MetaTable;
            QueryTable  qt = new QueryTable(mt);

            bool unsummarrizedVersionSelected = (!mt.UseSummarizedData && mt.SummarizedExists);
            if (!unsummarrizedVersionSelected)
            {
                return;
            }

            QueryTable  summarizedQt = qt.AdjustSummarizationLevel(useSummarized: true);
            QueryColumn summarizedQc = summarizedQt.GetQueryColumnByName(qc.ActiveLabel);
            if (summarizedQc == null)
            {
                return;
            }

            string msg =
                "You have selected the un-summarized version of " + qc.ActiveLabel + ".\n" +
                "Using the summarized version will result in better performance and avoid unwanted extra rows.\n" +
                "It is recommended that the summarized version be used for calculated fields.\n\n" +
                "Would you like to use the summarized version instead?\n";

            DialogResult dialogResult = MessageBoxMx.Show(msg, "Summarized Data Available!", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dialogResult == DialogResult.Yes)
            {
                SelectedColumn = null                 //summarizedQc.MetaColumn;

                                 return;
            }
#endif
        }
コード例 #10
0
/// <summary>
/// OK clicked - Update the query in the query builder and run if a new query
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>

        private void OK_Click(object sender, EventArgs e)
        {
            string title = "";

            KeyQc = KeyCriteriaCtl.QueryColumn;


            if (Lex.IsUndefined(KeyQc?.Criteria))
            {
                MessageBoxMx.Show("You must supply one or more compound ids.", UmlautMobius.String);
                KeyCriteriaCtl.Cids.Focus();
                return;
            }

            //TargetSummaryOptions tso = Tso; // copy to force update of Query fields
            //if (!KeyCriteriaCtl.GetFormValues(tso)) return;
            //Tso = tso;
            //TargetSummaryOptionsControl.SavePreferences(Tso);

            BuildQuery("");

            if (!QueryRendered)
            {
                QueryCount++;
                Query.UserObject.Name = "Summarized Target Results Analysis " + QueryCount;
                QbUtil.AddQueryAndRender(Query, false);                 // add query if necessary
                QueryRendered = true;
            }

            else
            {
                //QbUtil.NewQuery(Query.UserObject.Name); // show in query builder
                //QbUtil.SetCurrentQueryInstance(Query);
                QueryTable qt = GetUnpivotedSummaryTable(Query);
                QbUtil.RenderQuery(qt);
            }

            DialogResult = DialogResult.OK;
            return;
        }
コード例 #11
0
        /// <summary>
        /// Tools menu item click
        /// Create a standalone SasMap analysis based on the current query and then run it
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>

        public string Run(
            string args)
        {
            QueryTable  qt;
            MetaTable   mt;
            QueryColumn qc;

            int qid = SS.I.ServicesIniFile.ReadInt("SasMapToolModelQuery", 888070);

            if (qid < 0)
            {
                throw new Exception("SasMapToolModelQuery not defined");
            }

            Query q = QbUtil.ReadQuery(qid);

            if (q == null)
            {
                throw new Exception("Failed to read SasMapToolModelQuery: " + qid);
            }

            q.UserObject = new UserObject(UserObjectType.Query);             // treat this as a new query

            QueryTable sasQt = q.GetQueryTableByNameWithException(SasMapParms.MetaTableName);

            SasQc = sasQt.GetQueryColumnByNameWithException(SasMapParms.ParametersMetaColumnName);

            BaseQuery = GetBaseQuery();
            if (BaseQuery == null || BaseQuery.Tables.Count == 0)
            {
                MessageBoxMx.ShowError("The current query must contain one or more data tables before a SasMap can be defined on the query");
                return("");
            }

            Parms = LastParms;

            qc = BaseQuery?.GetFirstKeyColumn();
            qc = qc.Clone();
            qc.CopyCriteriaFromQueryKeyCriteria(BaseQuery);
            Parms.KeyCriteriaQc = qc;

            Parms.EndpointMc = BaseQuery?.GetFirstResultColumnByPriority(true)?.MetaColumn; // pick the highest priority result column as the default endpoint

            QbUtil.SetMode(QueryMode.Build);                                                // be sure in build mode

            DialogResult dr = Edit();

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

            StoreParmsInQueryColumnCriteria(Parms, SasQc);

            // Add as a new query and run it

            AnalysisCount++;

            q.Name = "Structure-Activity Similarity Analysis " + AnalysisCount;
            q.SingleStepExecution = true;

            // Add the query to the QueryBuilder and run it

            DelayedCallback.Schedule(             // add and run the query after exiting this dialog
                delegate(object state)
            {
                QbUtil.AddQuery(q);
                QbUtil.SetCurrentQueryInstance(q);                         // set to new query
                QbUtil.RenderQuery();
                QueryExec.RunQuery(q, SS.I.DefaultQueryDest);
            });

            Progress.Hide();

            return("");
        }
コード例 #12
0
        /// <summary>
        /// OK button clicked, process input
        /// </summary>
        /// <returns></returns>

        bool ProcessInput()
        {
            MetaTable   mt;
            Query       q;
            QueryColumn qc;
            string      actDifLabel = "", actSasCoefLabel = "";
            string      tok;

            if (Lex.IsDefined(KeyCriteriaCtl.QueryColumn.Criteria))
            {
                Parms.KeyCriteriaQc = KeyCriteriaCtl.QueryColumn;
            }

            else
            {
                MessageBoxMx.ShowError("Compound Id criteria must be defined.");
                return(false);
            }

            if (EndPointCtl.MetaColumn == null)
            {
                MessageBoxMx.ShowError("An endpoint assay result must be selected.");
                return(false);
            }

            Parms.EndpointMc = EndPointCtl.MetaColumn;
            string endPointLabel = EndPointCtl.MetaColumn.Label;

            qc = SasQt.GetQueryColumnByName("ACTIVITY1");
            if (qc != null)
            {
                qc.Label = endPointLabel + " 1";
            }

            qc = SasQt.GetQueryColumnByName("ACTIVITY2");
            if (qc != null)
            {
                qc.Label = endPointLabel + " 2";
            }

            actSasCoefLabel = "Act. Diff. / (1-Sim.)";

            // Get the type of calculation

            ActDiffCalcType calcType = ActDiffCalcType.Undefined;

            if (SimpleDifference.Checked)
            {
                calcType    = ActDiffCalcType.SimpleDifference;
                actDifLabel = "Activity Difference";
            }

            else if (NegativeLog.Checked)
            {
                actDifLabel = "Negative Log Difference";
                calcType    = ActDiffCalcType.NegativeLog;
            }

            else if (MolarNegativeLog.Checked)
            {
                calcType = ActDiffCalcType.MolarNegativeLog;

                if (Lex.Contains(endPointLabel, "IC50"))
                {
                    actDifLabel = "pIC50 Difference (Molar)";
                }

                else if (Lex.Contains(endPointLabel, "EC50"))
                {
                    actDifLabel = "pEC50 Difference (Molar)";
                }

                else
                {
                    actDifLabel = "Negative Log Difference (Molar)";
                }
            }

            else if (Ratio.Checked)
            {
                calcType        = ActDiffCalcType.Ratio;
                actDifLabel     = "Activity Ratio";
                actSasCoefLabel = "Act. Ratio / (1-Sim.)";
            }

            qc = SasQt.GetQueryColumnByName("ACTIVITY_DIFF");
            if (qc != null)
            {
                qc.Label = actDifLabel;
            }

            qc = SasQt.GetQueryColumnByName("ACT_SIM_COEF");
            if (qc != null)
            {
                qc.Label = actSasCoefLabel;
            }

            Parms.UseAbsoluteValue = CalcAbsoluteValue.Checked;

            Parms.ActDiffCalcType = calcType;

            // Get molsim parameters

            QueryColumn simQc = SasQt.GetQueryColumnByName("SIMILARITY");

            if (ECFP4Similarity.Checked)
            {
                Parms.SimilarityType = SimilaritySearchType.ECFP4;
                if (simQc != null)
                {
                    simQc.Label = "Structural Similarity (ECFP4)";
                }
            }

            else if (StandardSimilarity.Checked)
            {
                Parms.SimilarityType = SimilaritySearchType.Normal;
                if (simQc != null)
                {
                    simQc.Label = "Structural Similarity";
                }
            }

            tok = MinSimCtl.Text;
            Parms.MinimumSimilarity = -1;
            try { Parms.MinimumSimilarity = Double.Parse(tok); }
            catch (Exception ex) { }
            if (Parms.MinimumSimilarity <= 0 || Parms.MinimumSimilarity > 1)
            {
                MessageBoxMx.ShowError(
                    "Minimum acceptable structural similarity\n" +
                    "must be between 0 and 1.0");
                MinSimCtl.Focus();
                return(false);
            }

            // Get pair count

            tok = PairCountCtl.Text;
            Parms.MaxPairCount = -1;
            try { Parms.MaxPairCount = Int32.Parse(tok); }
            catch (Exception ex) { }
            if (Parms.MaxPairCount <= 0.0)
            {
                MessageBoxMx.ShowError(
                    "Pair count must be a positive integer value.");
                PairCountCtl.Focus();
                return(false);
            }

            return(true);
        }
コード例 #13
0
        /// <summary>
        /// ExportToPyMolMethod
        /// </summary>
        /// <param name="url"></param>
        /// <param name="qm"></param>
        void ExportToPyMolMethod(
            string url,
            string densityMapUrl,
            string target,
            QueryManager qm)
        {
            StreamWriter sw;

            string rec, msg, scriptSourceFile, pluginSourceFile, script;

            bool includeProtein = true;             // always include protein

            //bool includeElectronDensity = IncludeElectronDensityPyMol.Checked;
            if (!IncludeElectronDensityPyMol.Checked)
            {
                _qcDensity = null;
            }

            pluginSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.py";                       // the PyMOL plugin
            CopyToReadLockedFile(pluginSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.py"); // move CorpView2.py to CorpView.py
            if (!File.Exists(pluginSourceFile))
            {
                throw new Exception("Plugin file not found: " + pluginSourceFile);
            }



            scriptSourceFile = CommonConfigInfo.MiscConfigDir + @"\CorpView.pml";             // the script that starts pymol & hands it the .csv file
            CopyToReadLockedFile(scriptSourceFile, CommonConfigInfo.MiscConfigDir + @"\CorpView2.pml");
            if (!File.Exists(scriptSourceFile))
            {
                throw new Exception("Script file not found: " + scriptSourceFile);
            }

            string csvFile = ClientDirs.TempDir + @"\PyMolBatchLoad.csv";             // the .csv file to write

            WriteCsvFile(csvFile, ExportSingle.Checked, _qcProtein, _qcDensity, _qcTarget, qm, url, densityMapUrl, target);

            //qm.Query.Tables[0].MetaTable.Name

            try             // Read the CorpView2.pml that gets edited.
            {
                StreamReader sr = new StreamReader(scriptSourceFile);
                script = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception ex)
            { throw new Exception("Error reading " + scriptSourceFile + ": " + ex.Message); }

            // Get the path to the plugin file

            string pluginFile = null;
            Lex    lex        = new Lex("=");

            lex.OpenString(script);
            while (true)
            {
                string tok = lex.Get();
                if (tok == "")
                {
                    break;
                }
                if (Lex.Ne(tok, "pluginLocation"))
                {
                    continue;
                }

                pluginFile = lex.Get();
                if (pluginFile == "=")
                {
                    pluginFile = lex.Get();
                }
                pluginFile = Lex.RemoveSingleQuotes(pluginFile);
            }

            if (pluginFile == null)
            {
                throw new Exception("Can't find definition of plugin location");
            }

            // Get the proper plugin directory

            string pluginFolder = Path.GetDirectoryName(pluginFile);

            if (!Directory.Exists(pluginFolder))
            {
                string pluginFile2 = pluginFile;
                pluginFile2 = Lex.Replace(pluginFile2, "Progra~1", "Progra~2");                 // Win7 x86 folder using 8.3 names
                pluginFile2 = Lex.Replace(pluginFile2, "Program Files", "Program Files (x86)"); // Win7 x86 folder with regular names
                string pluginFolder2 = Path.GetDirectoryName(pluginFile2);
                if (!Directory.Exists(pluginFolder2))
                {
                    DebugLog.Message("Can't find PyMOL plugin folder: " + pluginFolder);
                    MessageBox.Show("Can't find PyMol plugin folder " + pluginFolder + ".\rContact Pymol Support team.");
                    Progress.Hide();
                    return;
                }
                script     = Lex.Replace(script, pluginFile, pluginFile2);             // substitute proper plugin file name in script
                pluginFile = pluginFile2;
            }

            bool update         = false;
            bool pyMolInstalled = File.Exists(pluginFile);

            ClientLog.Message("Checking for PyMol installation...");

            if (pyMolInstalled)
            {
                DateTime dt1 = File.GetLastWriteTime(pluginSourceFile);
                DateTime dt2 = File.GetLastWriteTime(pluginFile);
                if (DateTime.Compare(dt1, dt2) > 0)
                {
                    ClientLog.Message("  PyMol file is older than the Mobius version.");
                    update = true;
                }
            }
            else
            {
                ClientLog.Message("  Could not find PyMol file: " + pluginFile);
                update = true;
            }

            // Be sure the plugin is up to date

            if (update)
            {
                try
                {
                    File.Copy(pluginSourceFile, pluginFile, true);                      // copy CorpView.py to Pymol startup dir
                }
                catch (Exception ex)
                {
                    ClientLog.Message("   Error copying CorpView.py to: " + pluginFile + ", " + ex.Message);
                    if (!pyMolInstalled)
                    {
                        MessageBox.Show("Unable to find Corp Plugin (CorpView.py) for Pymol.\rWindows 7 will not allow Mobius access to copy the plugin to your machine.\rContact Pymol Support team.");
                        Progress.Hide();
                        return;
                    }
                }
            }

            DebugLog.Message("Error copying CorpView.py to: " + pluginFile);

            // Plug the csv file name into the script

            string csvFileNameParm = "<csv-file-name>";

            if (!Lex.Contains(script, csvFileNameParm))
            {
                throw new Exception("<csv-file-name> not found in script");
            }
            string csvFileNameForScript = csvFile.Replace(@"\", "/");             // translate backslashes so they aren't interpreted as escapes

            script = Lex.Replace(script, csvFileNameParm, csvFileNameForScript);

            string scriptFile = ClientDirs.TempDir + @"\CorpView.pml";

            sw = new StreamWriter(scriptFile);
            sw.Write(script);
            sw.Close();

            Progress.Show("Passing data to PyMOL...");
            try
            {
                //DebugLog.Message("startFile: " + startFile);
                //DebugLog.Message("startArgs: " + startArgs);
                Process p = Process.Start(scriptFile);
            }
            catch (Exception ex)
            {
                MessageBoxMx.ShowError("Failed to start PyMOL");
                Progress.Hide();
                return;
            }

            System.Threading.Thread.Sleep(3000);             // leave message up a bit while PyMOL is starting/being activated
            Progress.Hide();
        }
コード例 #14
0
/// <summary>
/// Build query table for decomposition & add to query
/// </summary>
/// <returns></returns>

        DialogResult ProcessInput()
        {
            Query       q;
            MetaTable   mt;
            MetaColumn  mc;
            QueryTable  qt;
            QueryColumn qc;

            q = QbUtil.Query;
            if (q == null || q.Tables.Count == 0)
            {
                MessageBoxMx.ShowError("No current query.");
                return(DialogResult.None);
            }

            qt = q.GetQueryTableByName("Rgroup_Decomposition");
            bool newTable = false;

            if (qt == null)
            {
                mt       = MetaTableCollection.GetWithException("Rgroup_Decomposition");
                qt       = new QueryTable(mt);
                newTable = true;
            }

            qc = qt.GetQueryColumnByNameWithException("Core");

            MoleculeMx core = new MoleculeMx(MoleculeFormat.Molfile, QueryMolCtl.MolfileString);

            if (core.AtomCount == 0)
            {
                MessageBoxMx.ShowError("A Core structure with R-groups must be defined.");
                return(DialogResult.None);
            }

            qc.MolString       = core.GetMolfileString();       // put core structure into table criteria
            qc.CriteriaDisplay = "Substructure search (SSS)";
            qc.Criteria        = "CORE SSS SQUERY";

            if (!Structure.Checked && !Smiles.Checked && !Formula.Checked &&
                !Weight.Checked && !Index.Checked)
            {
                MessageBoxMx.ShowError("At least one substituent display format must be selected.");
                return(DialogResult.None);
            }

            qc = qt.GetQueryColumnByName("R1_Structure");
            if (ShowCoreStructure.Checked)
            {
                qc.Label            = "R-group, Core\tChime=" + core.GetChimeString();      // reference core in query col header label
                qc.MetaColumn.Width = 25;
            }

            SetSelected(qt, "R1_Structure", Structure.Checked);
            SetSelected(qt, "R1_Smiles", Smiles.Checked);
            SetSelected(qt, "R1_Formula", Formula.Checked);
            SetSelected(qt, "R1_Weight", Weight.Checked);
            SetSelected(qt, "R1_SubstNo", Index.Checked);

            string terminateOption = TerminateOption.Text;

            qc = qt.GetQueryColumnByName("Terminate_Option");
            if (qc != null && Lex.IsDefined(terminateOption))
            {
                qc.Criteria        = qt.MetaTable.Name + " = " + Lex.AddSingleQuotes(terminateOption);
                qc.CriteriaDisplay = "= " + Lex.AddSingleQuotes(terminateOption);
            }

            else
            {
                qc.Criteria = qc.CriteriaDisplay = "";              // not defined
            }
            if (newTable)
            {
                q.AddQueryTable(qt);          // add to query if new
            }
            QbUtil.RenderQuery();             // show it
            UsageDao.LogEvent("RgroupDecomposition");
            return(DialogResult.OK);
        }
コード例 #15
0
        /// <summary>
        /// Handle a click on a link to a 3D structure & open in Vida
        /// If clicked from an XtraGrid give the user a range of options for the data
        /// to be exported. If clicked from a HTML page give limited options.
        /// </summary>
        /// <param name="mtName"></param>
        /// <param name="mcName"></param>
        /// <param name="url"></param>

        public void ClickFunction(
            string mtName,
            string mcName,
            string url)
        {
            ResultsFormatter fmtr = null;
            ResultsField     rfld = null;
            //DataRowMx dr;
            StringMx     sx;
            StreamWriter sw;
            int          markedCount   = 0;
            string       densityMapUrl = null;
            string       target        = null;

            _currentMetaTable     = mtName;
            _currentPdbColumnName = mcName;

            IncludeElectronDensityPyMol.Checked = false;

            MetaTable mt = MetaTableCollection.Get(mtName);

            if (mt == null)
            {
                return;
            }

            MetaColumn mc = mt.GetMetaColumnByName(mcName);

            if (mc == null)
            {
                return;
            }

            _xRay2Request = Lex.Contains(mtName, "XRay2");    // newer XRay2 database table?
            _urlFileName  = Path.GetFileName(url);            // extract file name from url

            QueryManager qm = ClickFunctions.CurrentClickQueryManager;

            if (qm != null)
            {
                Query         q  = qm.Query;
                ResultsFormat rf = qm.ResultsFormat;
                fmtr = qm.ResultsFormatter;

                rfld = rf.GetResultsField(mc);
                if (rfld == null)
                {
                    return;
                }

                QueryTable qt = q.GetQueryTableByNameWithException(mtName);
                _qcProtein = qt.GetQueryColumnByNameWithException(mcName);

                if (_xRay2Request)                 // newer XRay2 database
                {
                    string mapUrl = "";
                    if (mcName == "ALIGNED_SPLIT_COMPLEX_URL")
                    {
                        mapUrl = "ALIGNED_SPLIT_MAP_URL";
                    }
                    else if (mcName == "ALIGNED_FULL_COMPLEX_URL")
                    {
                        mapUrl = "ALIGNED_FULL_MAP_URL";
                    }
                    else if (mcName == "ORIGINAL_PDB_URL")
                    {
                        mapUrl = "ORIGINAL_MAP_URL";
                    }                                                                 //{ mapUrl = "ORIGINAL_MAP_URL"; }

                    _qcDensity = qt.GetQueryColumnByName(mapUrl);                     //("ALIGNED_SPLIT_MAP_URL");
                    if (_qcDensity != null && !_qcDensity.Selected)
                    {
                        _qcDensity = null;
                    }

                    _qcTarget = qt.GetQueryColumnByName("primary_gene_name_alias");
                    if (_qcTarget != null && !_qcTarget.Selected)
                    {
                        _qcTarget = null;
                    }
                }

                if (_qcDensity != null)
                {
                    // if there is a density map url located in the density column, enable the PyMol CheckEdit
                    DataRowMx dr = qm.DataTable.Rows[qm.MoleculeGrid.LastMouseDownCellInfo.DataRowIndex];
                    densityMapUrl = Lex.ToString(dr[_qcDensity.VoPosition]);
                }
                else
                {
                    // user did not select the map column, try to retrieve the XRay1 or Xray2 density map url fromt he metatable
                    densityMapUrl = _xRay2Request ? GetXray2DensityMapUrl(url, qt.MetaTable.Name, mcName) : GetXray1DensityMapUrl(url, qt.MetaTable.Name);
                }

                // default checkbox to false so user does not load electron density maps everytime, since these take
                // extra time to load.
                IncludeElectronDensityPyMol.Checked = false;

                IncludeElectronDensityPyMol.Enabled = !string.IsNullOrEmpty(densityMapUrl);

                if (_qcProtein == null && _qcDensity == null)
                {
                    throw new Exception("Neither the PDB nor the MAP column is selected in the query");
                }

                markedCount = fmtr.MarkedRowCount;
                int unmarkedCount = fmtr.UnmarkedRowCount;

                if (markedCount == 0 || unmarkedCount == 0)                 // if no specific selection assume user wants single structure
                {
                    ExportSingle.Checked = true;
                    FileName.Text        = _urlFileName;
                }
                else
                {
                    ExportMarked.Checked = true;                  // assume wants marked structures
                }
                ExportMarked.Enabled = true;
            }

            else              // simple setup for click from HTML display
            {
                ExportSingle.Checked = true;
                ExportMarked.Enabled = false;
                FileName.Text        = _urlFileName;

                densityMapUrl = GetXray2DensityMapUrl(url, _currentMetaTable, mcName);
                target        = GetTarget(url, _currentMetaTable, mcName);


                ////IncludeProtein.Enabled = IncludeElectronDensityEnabled = false;

                ////if (Lex.Eq(mcName, "bsl_xray_cmplx_url"))
                ////  IncludeProtein.Checked = true;

                ////else if (Lex.Eq(mcName, "bsl_xray_edensity_url"))
                ////  IncludeElectronDensityChecked = true;
            }

            if (mcName == "ALIGNED_SPLIT_MAP_URL" || mcName == "ALIGNED_FULL_MAP_URL" || mcName == "ORIGINAL_MAP_URL")              // not viewable fileds
            {
                DisablePymol();
                DisableMoe();
                ExportToFile.Enabled = ExportToFile.Checked = true;
            }

            else if (mcName == "ALIGNED_FULL_COMPLEX_URL" || mcName == "ORIGINAL_PDB_URL" || mcName == "ALIGNED_SPLIT_COMPLEX_URL")             // viewable by PyMol
            {
                EnableMoe();
                EnablePymol();
                ExportToFile.Enabled = true;
                ExportToFile.Checked = false;
            }
            else             //everything else should be viewable by MOE
            {
                EnableMoe();
                DisablePymol();
                ExportToFile.Enabled = true;
                ExportToFile.Checked = false;
            }

            DialogResult dlgRslt = ShowDialog(SessionManager.ActiveForm);

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

            bool exportSingle = ExportSingle.Checked;
            bool exportMarked = !exportSingle;

            if (!IncludeElectronDensityPyMol.Checked)
            {
                densityMapUrl = null;
            }

            if (exportMarked)             // see if reasonable count if exporting marked rows
            {
                string msg;
                if (markedCount == 0)
                {
                    msg = "No rows have been marked for export";
                    MessageBoxMx.Show(msg, "Mobius", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }

                if (markedCount > 10)
                {
                    msg =
                        markedCount + " structures have been selected out export.\n" +
                        "Are you sure these are the structures you want to export?";
                    dlgRslt = MessageBoxMx.Show(msg, "Mobius", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    if (dlgRslt != DialogResult.Yes)
                    {
                        return;
                    }
                }
            }

            // Export to PyMol (Schrodinger) - Collab with Paul Sprengeler and Ken Schwinn
            // Relavant Files:
            // 1. Plugin: CorpView.py (in Mobius config dir)
            // 2. Script: CorpView.pml - Runs the plugin and then passes in the .csv file (in Mobius config dir)
            //		 Expected content (note: <csv-file-name> gets replaced):
            //			import pymol
            //			pluginLocation = 'C:\Progra~1\PyMOL\PyMOL\modules\pmg_tk\startup\CorpView.py'
            //			cmd.do('run ' + pluginLocation)
            //			cmd.do('lv_create_environment')
            //			cmd.do('lv_import_mobius <csv-file-name>')
            //			cmd.do('lv_destroy_environment')
            // 3. Csv file: PyMolBatchLoad.csv - Csv file in format expected by plugin (in Mobius temp dir)

            if (ExportToPyMol.Checked)
            {
                ExportToPyMolMethod(url, densityMapUrl, target, qm);
            }

            else if (ExportToMOE.Checked)             // Export to MOE
            {
                ExportToMOEMethod(url, qm, fmtr, rfld);
            }

            else
            {
                ExportToFilesMethod(url, qm, fmtr, rfld);
            }
        }
コード例 #16
0
        static void Main(string[] args)
        {
            Splash splash     = null;
            bool   unattended = false;
            bool   startedByMobiusClientStart = false;
            string username = "", msg;

            string argString = "";

            for (int ai = 0; ai < args.Length; ai++)
            {
                string arg = args[ai];

                Lex.AppendToList(ref argString, " ", arg);                 // append arg separating by a space

                if (Lex.Eq(arg, "username") && ai + 2 < args.Length)
                {
                    username = args[ai + 2].ToUpper();
                }

                if (Lex.Eq(arg, "StartedByMobiusClientStart"))
                {
                    startedByMobiusClientStart = true;
                }

                if (Lex.Eq(arg, "unattended"))
                {
                    unattended = true;
                }
            }

            string machineName = Environment.MachineName;

            LogDetailedMessages =             // flag to do special detailed logging
                                  Lex.Contains(machineName, "<server>");

            // If not started by MobiusClientStart then do our own check to see if we are the current version

            if (!startedByMobiusClientStart)
            {
                UpdateClientVersionIfNecessary();
            }

            ClientLog.Initialize(username);             // initialize client logging
            ClientLog.Message("Mobius.Client started, ParmString: " + argString);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);             // must be done before first window is opened

            /*
             * DevExpress.XtraEditors.WindowsFormsSettings.SetDPIAware(); // don't do unless Mobius refactored as a DPI aware app (e.g. DX LayoutControl)
             * Note that setting Override high DPI scaling behavior = System (Enhanced) for the Mobius app can be used
             * to provide better Win 10 rendering for high DPI displays and/or non-100% display scaling
             *
             * To prevent the DevExpress de, es, ja, ru folders from being created delete the language files
             * under: C:\Program Files(x86)\DevExpress 19.1\Components\Bin\Framework (replace the version with the current version)
             */

            // Set up handling of unexpected exits

            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(ThreadException); // Occurs when an untrapped thread exception is thrown
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);                     // Always route exceptions to the System.Windows.Forms.Application.ThreadException handler

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            Application.ThreadExit      += new EventHandler(ThreadExit);
            Application.ApplicationExit += new EventHandler(ApplicationExit);

            ApplicationRecovery.OnApplicationCrash += new ApplicationRecovery.ApplicationCrashHandler(ApplicationRecovery_OnApplicationCrash);             // try to catch crashes not caught via c# exceptions
            ApplicationRecovery.RegisterForRestart();

            /////////////////////
            // Development tests
            /////////////////////

            //SpotfireApiClient.UseAnalystClient = true; // debug

            bool RunDevTest = false;

            if (RunDevTest)             // && ClientState.IsDeveloper) // do a quick dev test & then exit
            {
                if (DebugMx.True)
                {
                    Mobius.KekuleJs.KekuleTestForm f = new Mobius.KekuleJs.KekuleTestForm();
                    Application.Run(f);
                    return;
                }

                if (DebugMx.False)
                {
                    MoleculeViewer v = new MoleculeViewer();
                    Application.Run(v);
                    return;
                }

                if (DebugMx.False)
                {
                    //NCDK_Example.DepictionGenerator_Example.Run();

                    //string version = java.lang.Package.getPackage("java.lang").getImplementationVersion();

                    //StreamReader sr = new StreamReader(@"c:\downloads\aspirin.mol");
                    //string molfile = sr.ReadToEnd();
                    //sr.Close();

                    //IAtomContainer ac = CdkMol.MolfileToAtomContainer(molfile);

                    //if (DebugMx.False) // Helm editor
                    //{
                    //	Helm.CefMx.InitializeCef();
                    //	HelmEditorDialog editor = new HelmEditorDialog();
                    //	string helm = "PEPTIDE1{A.L.C}$$$$";
                    //	string newHelm = editor.Edit(helm);
                    //	return;
                    //
                }


                if (DebugMx.False)
                {
                    RelatedCompoundsDialog rcd = new RelatedCompoundsDialog();
                    rcd.QueryMolCtl.SetPrimaryTypeAndValue(MoleculeFormat.Smiles, "CC(=O)OC1=CC=CC=C1C(=O)O");                     // aspirin
                    Application.Run(rcd);
                    return;
                }

                if (DebugMx.False)                 // Spotfire API test form
                {
                    Application.Run(new Mobius.SpotfireClient.TestMobiusSpotfireApiForm());
                    //Application.Run(new Mobius.SpotfireClient.ScatterPlotPropertiesDialog());
                    return;
                }

                //string shares = DirectoryMx.GetSharedFolderAccessRule(); // get shares


                //if (DebugMx.False) // test old Spotfire Webplayer interface
                //{
                //	Application.Run(new Mobius.SpotfireClient.TestWebplayerInterfaceForm());
                //	return;
                //}

                //Mobius.ComOps.SVGParser.Test();

                //string windowsLoginName = WindowsIdentity.GetCurrent().Name;
                //if (Lex.Eq(windowsLoginName, "<UserDomainAndName>")) // debugging settings
                //{
                //  CommandLineService.ExecuteCommand("Set DebugQE true");
                //  CommandLineService.ExecuteCommand("Set DebugDbCmd true");
                //}

                //if (DebugMx.True) while (true) { new BitmapTest().ShowDialog(); }

                //RunDevTestMethod();
                //return;
            }

            ///////////////////////////
            // End of Development tests
            ///////////////////////////

            // Check for required software versions

            if (!SessionManager.CheckForCorrectSoftwareVersions())
            {
                Environment.Exit(-1);
            }

            // Put up splash screen

            Splash.Unattended = unattended;
            LogDetailedMessage("Putting up splash");

            try
            {
                //if (Math.Abs(1) == 1) throw new Exception("Fatal Error Test"); // debug
                //if (!Lex.Contains(argString, "Attempt 3")) throw new Exception("Fatal Error Test"); // debug

                IniFile iniFile = null;

                // Put up splash screen

                if (splash == null)
                {
                    splash = Splash.ShowForm();
                }

                iniFile = MobiusClientUtil.OpenAppropriateClientIniFile();
                if (iniFile == null)
                {
                    throw new Exception("MobiusClient.ini not found");
                }

                msg = "Startup iniFile: " + iniFile.IniFileName;
                ClientLog.Message(msg);

                // Initialize services and get a session, session is created asynch while rest of client code loads in

                try
                {
                    int  t0     = TimeOfDay.Milliseconds();
                    bool asynch = true;                     // initialize session asynch

                    ServiceFacade.ServiceFacade.CreateSession(iniFile, argString, asynch);
                    t0 = TimeOfDay.Milliseconds() - t0;
                    LogDetailedMessage("ServiceFacade.Initialize time (asynch): " + t0);
                }
                catch (Exception ex)
                {
                    msg = "ServiceFacade.Initialize failed:" + "\r\n\r\n" +
                          DebugLog.FormatExceptionMessage(ex);
                    DebugLog.Message(msg);
                    ClientLog.Message(msg);
                    MessageBoxMx.ShowError(msg);
                    return;
                }

                LogDetailedMessage("Creating SessionManager");
                SessionManager = new SessionManager();

                SessionManager.Splash = splash;

                // Setup and display the Shell

                LogDetailedMessage("Setting up Shell");

                Shell shell = new Shell();                 // create the shell form
                SessionManager.ShellForm = shell;

                SessionManager.MainMenuControl    = shell.MainMenuControl;
                SessionManager.HelpButton         = shell.HelpButtonItem;
                SessionManager.RibbonCtl          = shell.Ribbon;
                SessionManager.QuickSearchControl = shell.CommandLine;

                StatusBarManager sbm = SessionManager.StatusBarManager;
                SessionManager.StatusBarManager.StatusBarCtl = shell.StatusBar;

                LogDetailedMessage("Setting up Status Controls");
                sbm.SetupStatusControls(
                    shell.RetrievalProgressBar,
                    shell.RetrievalProgressButton,
                    shell.RowCountCtl,
                    shell.DatabaseSubsetButtonItem,
                    shell.ClearFiltersCtl,
                    shell.FiltersEnabledCtl,
                    shell.FilterStringCtl);

                LogDetailedMessage("Setting up Zoom Controls");
                sbm.SetupViewZoomControls(
                    shell.ZoomButtonItem,
                    shell.ZoomPctBarItem,
                    shell.ZoomSlider);

                SessionManager.QueriesControl = shell.QueriesControl;
                //SystemUtil.Beep();
                if (!SessionManager.Initialize(argString))
                {
                    return;                                                        // Initialize the session, just return if init fails
                }
                //SystemUtil.Beep();

                LogDetailedMessage("Calling Application.Run");
                Application.Run(shell); // show the shell & start message loop
                return;                 // app normally never gets here
            }

            catch (Exception ex)                                    // unexpected fatal error
            {
                if (unattended && !argString.Contains("Attempt 3")) // try restart up to three times if unattended
                {
                    int attempt = 1;
                    if (!Lex.Contains(argString, "Attempt"))
                    {
                        argString += " Attempt 2";                                                          // get current attempt number and set new attempt
                    }
                    else if (Lex.TryReplace(ref argString, "Attempt 2", "Attempt 3"))
                    {
                        attempt = 2;
                    }
                    else
                    {
                        attempt = 3;
                    }

                    ClientLog.Message("Startup error, Attempt: " + attempt + ", " + DebugLog.FormatExceptionMessage(ex));

                    Process p = Process.Start(Application.ExecutablePath, argString);
                    return;
                }

                LogUnexpectedError(ex);                 // log message and exit
                return;
            }
        }
コード例 #17
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);
        }
コード例 #18
0
        /// <summary>
        /// Startup Vida with supplied arguments
        /// </summary>
        /// <param name="args"></param>

        public void StartVida(
            string args)
        {
            RegistryKey key = null;
            string      rootKeyName = null, version = null, installPath = null, msg;

            string[] sa = args.Split('\t');

            string[] vidaPaths = sa[0].Split(';'); // array of paths to try
            string   startArgs = sa[1];            // args to pass to Vida

            for (int pi = 0; pi < vidaPaths.Length; pi++)
            {
                string path = vidaPaths[pi].Trim();
                if (path == "")
                {
                    continue;
                }

                else if (!String.IsNullOrEmpty(Path.GetDirectoryName(path)))                 // directory name
                {
                    if (Directory.Exists(path))
                    {
                        installPath = path;
                        //DebugLog.Message("StartVida installPath: " + installPath);
                        break;
                    }
                }

                else                 // registry key
                {
                    string keyName = path;
                    key = Registry.CurrentUser.OpenSubKey(keyName);
                    if (key != null)
                    {
                        rootKeyName = keyName;
                        version     = (string)key.GetValue("version");
                        if (!String.IsNullOrEmpty(version))
                        {
                            key = Registry.CurrentUser.OpenSubKey(rootKeyName + @"\" + version);
                            if (key != null)
                            {
                                installPath = (string)key.GetValue("InstallPath");
                                //DebugLog.Message("StartVida key: " + rootKeyName + @"\" + version + ", installPath: " + installPath);
                                break;
                            }
                        }
                        break;
                    }
                }
            }

            if (String.IsNullOrEmpty(installPath))
            {
                msg = "Mobius is unable to locate a VIDA installation on this machine.";
                MessageBoxMx.Show(msg, "Mobius", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            string startFile = installPath + @"\vida.bat";

            try
            {
                //DebugLog.Message("startFile: " + startFile);
                //DebugLog.Message("startArgs: " + startArgs);
                Process p = Process.Start(startFile, startArgs);
            }
            catch (Exception ex)
            {
                MessageBoxMx.Show("Failed to start VIDA: " + startFile + " " + startArgs + "\n" + ex.Message, "Mobius");
                return;
            }

            return;
        }
コード例 #19
0
        /// <summary>
        /// OK button clicked, process input
        /// </summary>
        /// <returns></returns>

        DialogResult ProcessInput()
        {
            int           rgCount;                              // number of Rgroups
            List <Rgroup> rgList;                               // list of existing Rgroups

            bool[]        rgExists;                             // entry = true if rgroup exists in core
            Rgroup        rg;
            bool          oneD, twoD;                           // matrix dimensionality
            List <string> keys = null;
            Dictionary <string, List <QualifiedNumber> > mElem; // matrix element dictionary

            List <RgroupSubstituent>[] rSubs;                   // substituents seen for each Rgroup
            Query        q, q0, q2;
            QueryTable   qt, qt2;
            QueryColumn  qc, qc2;
            MetaTable    mt, mt2;
            MetaColumn   mc, mc2;
            DataTableMx  dt;
            DataRowMx    dr;
            DialogResult dlgRslt;
            string       tok;
            int          ri, rii, si, qti, qci, bi, bi2;

            // Get core structure & list of R-groups

            MoleculeMx core = new MoleculeMx(MoleculeFormat.Molfile, SQuery.MolfileString);

            if (core.AtomCount == 0)
            {
                MessageBoxMx.ShowError("A Core structure with R-groups must be defined");
                return(DialogResult.None);
            }

            if (!Structure.Checked && !Smiles.Checked && !Formula.Checked &&
                !Weight.Checked && !Index.Checked)
            {
                MessageBoxMx.ShowError("At least one substituent display format must be selected.");
                return(DialogResult.None);
            }

            mt = MetaTableCollection.GetWithException("Rgroup_Decomposition");
            qt = new QueryTable(mt);
            qc = qt.GetQueryColumnByNameWithException("Core");

            qc.MolString       = core.GetMolfileString();       // put core structure into table criteria
            qc.CriteriaDisplay = "Substructure search (SSS)";
            qc.Criteria        = "CORE SSS SQUERY";

            qc = qt.GetQueryColumnByNameWithException("R1_Structure");
            if (ShowCoreStructure.Checked)
            {
                qc.Label            = "R-group, Core\tChime=" + core.GetChimeString();      // reference core in query col header label
                qc.MetaColumn.Width = 25;
            }

            RgroupDecomposition.SetSelected(qt, "R1_Structure", Structure.Checked);             // select for retrieval if checked
            RgroupDecomposition.SetSelected(qt, "R1_Smiles", Smiles.Checked);
            RgroupDecomposition.SetSelected(qt, "R1_Formula", Formula.Checked);
            RgroupDecomposition.SetSelected(qt, "R1_Weight", Weight.Checked);
            RgroupDecomposition.SetSelected(qt, "R1_SubstNo", Index.Checked);

            string terminateOption = "First mapping";             // terminate on first complete match

            qc                 = qt.GetQueryColumnByNameWithException("Terminate_Option");
            qc.Criteria        = qt.MetaTable.Name + " = " + Lex.AddSingleQuotes(terminateOption);
            qc.CriteriaDisplay = "= " + Lex.AddSingleQuotes(terminateOption);

            QueryTable rgdQt = qt;             // keep a ref to it

            if (QbUtil.Query == null || QbUtil.Query.Tables.Count == 0)
            {
                MessageBoxMx.ShowError("No current query.");
                return(DialogResult.None);
            }

            q0 = QbUtil.Query;          // original query this analysis is based on
            q  = q0.Clone();            // make copy of source query we can modify
            q.SingleStepExecution = false;

            qti = 0;
            while (qti < q.Tables.Count)             // deselect query columns that we don't want
            {
                qt = q.Tables[qti];
                if (Lex.Eq(qt.MetaTable.Name, "Rgroup_Decomposition"))
                {                 // remove any rgroup decomp table
                    qti++;
                    continue;
                }

                mt = qt.MetaTable;
                if (mt.MultiPivot ||                                 // check for tables not allowed in underlying query
                    mt.MetaBrokerType == MetaBrokerType.CalcField || // (called ShouldPresearchAndTransform previously)
                    mt.MetaBrokerType == MetaBrokerType.MultiTable ||
                    mt.MetaBrokerType == MetaBrokerType.RgroupDecomp)
                {
                    MessageBoxMx.ShowError("Multipivot/Rgroup table \"" + qt.ActiveLabel +
                                           "\" can't be included in an underlying Rgroup Matrix query");
                    return(DialogResult.None);
                }

                for (qci = 0; qci < qt.QueryColumns.Count; qci++)
                {
                    qc = qt.QueryColumns[qci];
                    if (qc.MetaColumn == null)
                    {
                        continue;
                    }

                    switch (qc.MetaColumn.DataType)
                    {
                    case MetaColumnType.CompoundId:                             // keep only these
                    case MetaColumnType.Integer:
                    case MetaColumnType.Number:
                    case MetaColumnType.QualifiedNo:
                    case MetaColumnType.String:
                        break;

                    default:
                        qc.Selected = false;
                        break;
                    }
                }

                qti++;
            }

            q.AddQueryTable(rgdQt);             // Add Rgroup decom table to end of cloned source query

            Progress.Show("Retrieving data...");
            try
            {
                dlgRslt = ToolHelper.ExecuteQuery(ref q, out keys);
                if (dlgRslt != DialogResult.OK)
                {
                    return(dlgRslt);
                }
            }

            catch (Exception ex)
            {
                MessageBoxMx.ShowError("Error executing query:\r\n" + ex.Message);
                return(DialogResult.None);
            }

            if (keys == null || keys.Count == 0)
            {
                Progress.Hide();
                MessageBoxMx.ShowError("No results were returned by the query.");
                return(DialogResult.None);
            }

// Scan modified query to get list of rgroup indexes that are present

            rgExists = new bool[32];
            rgList   = new List <Rgroup>();

            QueryTable rgQt = q.GetQueryTableByName("Rgroup_Decomposition");

            foreach (QueryColumn qc0 in rgQt.QueryColumns)
            {
                mc = qc0.MetaColumn;
                if (!(mc.Name.StartsWith("R") && mc.Name.EndsWith("_STRUCTURE") && qc0.Selected))
                {
                    continue;                     // skip if not a selected Rgroup structure
                }
                int len = mc.Name.Length - ("R" + "_STRUCTURE").Length;
                tok = mc.Name.Substring(1, len);
                if (!int.TryParse(tok, out ri))
                {
                    continue;
                }
                rgExists[ri - 1] = true;
                rg        = new Rgroup();
                rg.RIndex = ri;
                rg.VoPos  = qc0.VoPosition;
                rgList.Add(rg);
            }

            for (bi = 1; bi < rgList.Count; bi++)
            {             // sort by increasing R index
                rg = rgList[bi];
                for (bi2 = bi - 1; bi2 >= 0; bi2--)
                {
                    if (rg.RIndex >= rgList[bi2].RIndex)
                    {
                        break;
                    }
                    rgList[bi2 + 1] = rgList[bi2];
                }

                rgList[bi2 + 1] = rg;
            }

            rgCount = rgList.Count;

            twoD = TwoD.Checked;
            if (rgCount == 1)
            {
                twoD = false;                           // if only 1 rgroup can't do as 2d
            }
            oneD = !twoD;

// Read data into mElem and rgroup substituents into rSubs.
// Matrix mElem is keyed on [R1Smiles, R2Smiles,... RnSmiles, FieldName] for 1d and
// [R1Smiles, R2Smiles,... FieldName, RnSmiles] for 2d

            QueryManager     qm  = q.QueryManager as QueryManager;
            DataTableManager dtm = qm.DataTableManager;

            dt = qm.DataTable;

            mElem = new Dictionary <string, List <QualifiedNumber> >(); // matrix element dictionary
            rSubs = new List <RgroupSubstituent> [32];                  // list of substituents seen for each Rgroup
            for (rii = 0; rii < rgCount; rii++)                         // alloc substituent list for rgroup
            {
                rSubs[rii] = new List <RgroupSubstituent>();
            }

            int rowCount = 0;

            while (true)
            {             // scan data accumulating rgroup substituents and data values
                dr = dtm.FetchNextDataRow();
                if (dr == null)
                {
                    break;
                }
                rowCount++;

                string cid = dr[dtm.KeyValueVoPos] as string;
                string lastMapCid = "", rgroupKey = "", rgroupKeyLast = "";
                int    mapCount = 0;
                for (rii = 0; rii < rgCount; rii++)                 // for
                {
                    MoleculeMx rSub = dr[rgList[rii].VoPos] as MoleculeMx;
                    if (rSub == null || rSub.AtomCount == 0)
                    {
                        continue;
                    }

                    ri = rgList[rii].RIndex;                     // actual R index in query
                    int subIdx = RgroupSubstituent.Get(rSub, rSubs[rii]);
                    //					if (ri == 1 && subIdx != 0) subIdx = subIdx; // debug
                    if (subIdx < 0)
                    {
                        continue;
                    }
                    string rKey = "R" + ri.ToString() + "_" + (subIdx + 1).ToString();

                    if (oneD || rii < rgCount - 1)
                    {
                        if (rgroupKey != "")
                        {
                            rgroupKey += "\t";
                        }
                        rgroupKey += rKey;
                    }

                    else
                    {
                        rgroupKeyLast = rKey;
                    }
                    lastMapCid = cid;
                    mapCount++;
                }

                if (lastMapCid == cid)                 // add the data if compound has a mapping
                {
                    AccumulateMatrixElements(mElem, q, dr, rgroupKey, rgroupKeyLast, cid);
                }

                if (Progress.IsTimeToUpdate)
                {
                    Progress.Show("Retrieving data: " + StringMx.FormatIntegerWithCommas(rowCount) + " rows...");
                }
            }
            if (rowCount == 0)
            {
                Progress.Hide();
                MessageBoxMx.ShowError("No data rows retrieved");
                return(DialogResult.None);
            }

            if (twoD && (rSubs[rgCount - 1] == null || rSubs[rgCount - 1].Count == 0))
            {             // if 2D be sure we have at least one substituent for the last Rgroup
                Progress.Hide();
                MessageBoxMx.ShowError("No substituents found for R" + rgCount.ToString());
                return(DialogResult.None);
            }

            // Create a MetaTable & DataTable for matrix results

            Progress.Show("Analyzing data...");

            mt = new MetaTable();             // create output table
            MatrixCount++;
            mt.Name           = "RGROUPMATRIX_" + MatrixCount;
            mt.Label          = "R-group Matrix " + MatrixCount;
            mt.MetaBrokerType = MetaBrokerType.RgroupDecomp;

            mc =                       // use sequence for key
                 mt.AddMetaColumn("RgroupMatrixId", "No.", MetaColumnType.Integer, ColumnSelectionEnum.Selected, 3);
            mc.ClickFunction = "None"; // avoid hyperlink on this key
            mc.IsKey         = true;

            int maxLeftR = rgCount;

            if (twoD)
            {
                maxLeftR = rgCount - 1;
            }
            for (ri = 0; ri < maxLeftR; ri++)
            {
                string rStr = "R" + (ri + 1).ToString();
                if (Structure.Checked)
                {
                    mc = mt.AddMetaColumn(rStr + "Str", rStr, MetaColumnType.Structure, ColumnSelectionEnum.Selected, 12);
                    if (ri == 0 && ShowCoreStructure.Checked)                     // include core structure above R1 if requested
                    {
                        string chimeString = MoleculeMx.MolfileStringToSmilesString(SQuery.MolfileString);
                        mc.Label = "R1, Core\tChime=" + chimeString;
                        mc.Width = 25;
                    }
                }
                if (Smiles.Checked)
                {
                    mc = mt.AddMetaColumn(rStr + "Smi", rStr + " Smiles", MetaColumnType.String, ColumnSelectionEnum.Selected, 12);
                }
                if (Formula.Checked)
                {
                    mc = mt.AddMetaColumn(rStr + "Mf", rStr + " Formula", MetaColumnType.String, ColumnSelectionEnum.Selected, 8);
                }
                if (Weight.Checked)
                {
                    mc = mt.AddMetaColumn(rStr + "MW", rStr + " Mol. Wt.", MetaColumnType.Number, ColumnSelectionEnum.Selected, 6, ColumnFormatEnum.Decimal, 2);
                }

                if (Index.Checked)
                {
                    mc        = mt.AddMetaColumn(rStr + "Index", rStr + " Subst. Idx.", MetaColumnType.Number, ColumnSelectionEnum.Selected, 4);
                    mc.Format = ColumnFormatEnum.Decimal;
                }
            }

            mc =             // add column to contain result type
                 mt.AddMetaColumn("ResultType", "Result Type", MetaColumnType.String, ColumnSelectionEnum.Selected, 12);

            if (oneD)             // add just 1 column to contain results
            {
                mc = mt.AddMetaColumn("Results", "Results", MetaColumnType.QualifiedNo, ColumnSelectionEnum.Selected, 12);
                mc.MetaBrokerType = MetaBrokerType.RgroupDecomp;                 // broker to do special col handling for cond formtting
                if (QbUtil.Query.UserObject.Id > 0)
                {
                    mc.DetailsAvailable = true;
                }
            }

            else             // add col for each substituent for last rgroup
            {
                string rStr = "R" + rgCount.ToString();
                for (si = 0; si < rSubs[rgCount - 1].Count; si++)
                {
                    string            cName  = rStr + "_" + (si + 1).ToString();
                    string            cLabel = cName.Replace("_", ".");
                    RgroupSubstituent rgs    = rSubs[ri][si];  // get substituent info
                    if (Structure.Checked)                     // include structure
                    {
                        cLabel += "\tChime=" + rgs.Struct.GetChimeString();
                    }

                    else if (Smiles.Checked)
                    {
                        cLabel += " = " + rgs.Struct.GetSmilesString();
                    }

                    else if (Formula.Checked)
                    {
                        cLabel += " = " + rgs.Struct.MolFormula;
                    }

                    else if (Weight.Checked)
                    {
                        cLabel += " = " + rgs.Struct.MolWeight;
                    }

                    else if (Index.Checked)
                    {
                        cLabel += " = " + (si + 1).ToString();
                    }

                    mc = mt.AddMetaColumn(cName, cLabel, MetaColumnType.QualifiedNo, ColumnSelectionEnum.Selected, 12);
                    mc.MetaBrokerType = MetaBrokerType.RgroupDecomp;
                    if (QbUtil.Query.UserObject.Id > 0)
                    {
                        mc.DetailsAvailable = true;
                    }
                }
            }

            MetaTableCollection.UpdateGlobally(mt); // add as a known metatable

            if (mElem.Count == 0)                   // be sure we have a matrix
            {
                Progress.Hide();
                MessageBoxMx.ShowError("No matrix can be created because insufficient data was found.");
                return(DialogResult.None);
            }

            // Build the DataTable

            Progress.Show("Building data table...");

            q2  = new Query();            // build single-table query to hold matrix
            qt2 = new QueryTable(q2, mt);
            dt  = DataTableManager.BuildDataTable(q2);

            Dictionary <string, List <QualifiedNumber> > .KeyCollection kc = mElem.Keys;
            string[] rgKeys = new string[mElem.Count];
            kc.CopyTo(rgKeys, 0);
            Array.Sort(rgKeys);

            string[] rgKey = null, lastRgKey = null;
            int      rki   = 0;

            for (rki = 0; rki < rgKeys.Length; rki++)
            {
                rgKey = rgKeys[rki].Split('\t');

                int riTop = rgCount + 1;                 // all r substituents & field name on left
                if (twoD)
                {
                    riTop = rgCount;
                }

                for (ri = 0; ri < riTop; ri++)                 // see if any changes in left side substituents or field name
                {
                    if (lastRgKey == null || rgKey[ri] != lastRgKey[ri])
                    {
                        break;
                    }
                }
                if (ri < riTop || oneD)                 // if 2d then new row only if some change before last R
                {
                    dr = dt.NewRow();
                    dt.Rows.Add(dr);
                    dr[dtm.KeyValueVoPos + 1] = new NumberMx(dt.Rows.Count);                     // integer row key
                }

                if (!HideRepeatingSubstituents.Checked)
                {
                    ri = 0;                                                     // start at first if not hiding
                }
                lastRgKey = rgKey;

                for (ri = ri; ri < riTop; ri++)                 // build row with these
                {
                    string rgSub = rgKey[ri];                   // get substituent id or table.column name
                    if (rgSub == "")
                    {
                        continue;
                    }

                    if (ri < riTop - 1)
                    {                     // output substituent and/or smiles
                        string rStr = "R" + (ri + 1).ToString();
                        si = rgSub.IndexOf("_");
                        si = Int32.Parse(rgSub.Substring(si + 1)) - 1;                 // get substituent index
                        RgroupSubstituent rgs = rSubs[ri][si];                         // get substituent info

                        if (Structure.Checked)
                        {
                            qc2 = qt2.GetQueryColumnByName(rStr + "Str");
                            dr[QcToDcName(qc2)] = rgs.Struct;
                        }

                        if (Smiles.Checked)
                        {
                            qc2 = qt2.GetQueryColumnByName(rStr + "Smi");
                            dr[QcToDcName(qc2)] = new StringMx(rgs.Struct.GetSmilesString());
                        }

                        if (Formula.Checked)
                        {
                            qc2 = qt2.GetQueryColumnByName(rStr + "Mf");
                            dr[QcToDcName(qc2)] = new StringMx(rgs.Struct.MolFormula);
                        }

                        if (Weight.Checked)
                        {
                            qc2 = qt2.GetQueryColumnByName(rStr + "Mw");
                            dr[QcToDcName(qc2)] = new NumberMx(rgs.Struct.MolWeight);
                        }

                        if (Index.Checked)
                        {
                            qc2 = qt2.GetQueryColumnByName(rStr + "Index");
                            dr[QcToDcName(qc2)] = new NumberMx(si + 1);
                        }
                    }

                    else                                // output field name
                    {
                        string[] sa = rgSub.Split('.'); // get field name
                        qt = q.GetQueryTableByName(sa[0]);
                        qc = qt.GetQueryColumnByName(sa[1]);
                        string fieldName = qc.ActiveLabel;
                        if (q0.Tables.Count >= 3)                         // qualify by table if 3 or more tables in original query
                        {
                            fieldName = qt.ActiveLabel + " - " + fieldName;
                        }

                        qc2 = qt2.GetQueryColumnByName("ResultType");
                        dr[QcToDcName(qc2)] = new StringMx(fieldName);
                    }
                }

                // Output value

                string cName;
                if (oneD)
                {
                    cName = "Results";
                }
                else
                {
                    cName = rgKey[rgCount];                  // get key for this substituent (e.g. R2_1)
                }
                if (Lex.IsUndefined(cName))
                {
                    continue;                                         // may be no substituent match
                }
                qc2 = qt2.GetQueryColumnByName(cName);
                QualifiedNumber qn = SummarizeData(mElem[rgKeys[rki]]);                 // get summarized value
                dr[QcToDcName(qc2)] = qn;
            }

            ToolHelper.DisplayData(q2, dt, true);

            UsageDao.LogEvent("RgroupMatrix");
            Progress.Hide();
            return(DialogResult.OK);
        }