Пример #1
0
        /// <summary>
        /// Convert this molecule to a new type
        /// </summary>
        /// <param name="newType"></param>

        public void ConvertToNewType(
            MoleculeFormat newType)
        {
            if (PrimaryFormat == newType)
            {
                return;                                       // no change in type
            }
            else if (PrimaryFormat == MoleculeFormat.Molfile && newType == MoleculeFormat.Chime)
            {
                if (!Lex.IsNullOrEmpty(MolfileString))
                {
                    ChimeString = MolfileStringToChimeString(MolfileString);
                }
                PrimaryFormat = MoleculeFormat.Chime;
            }

            else if (PrimaryFormat == MoleculeFormat.Chime && newType == MoleculeFormat.Molfile)
            {
                if (!Lex.IsNullOrEmpty(ChimeString))
                {
                    MolfileString = ChimeStringToMolfileString(ChimeString);
                }
                PrimaryFormat = MoleculeFormat.Molfile;
            }

            else
            {
                MoleculeMx cs2 = ConvertTo(newType);
                cs2.MemberwiseCopy(this);
            }

            return;
        }
Пример #2
0
        /// <summary>
        /// Set molecule value including the associated native CDK IAtomContainer
        /// </summary>
        /// <param name="molFormat"></param>
        /// <param name="molString"></param>

        public void SetMolecule(
            MoleculeFormat molFormat,
            string molString)
        {
            if (molFormat == _molFormat && Lex.Eq(molString, _molString))
            {
                return;                 // no change
            }
            if (molFormat == MoleculeFormat.Molfile)
            {
                NativeMol = MolfileToAtomContainer(molString);
            }

            else if (molFormat == MoleculeFormat.Chime)
            {
                string molfile = MoleculeMx.ChimeStringToMolfileString(molString);
                NativeMol = MolfileToAtomContainer(molfile);
            }

            else if (molFormat == MoleculeFormat.Smiles)
            {
                NativeMol = SmilesToAtomContainer(molString);
            }

            else if (molFormat == MoleculeFormat.Unknown)
            {
                NativeMol = null;
            }

            _molFormat = molFormat;
            _molString = molString;
        }
Пример #3
0
/// <summary>
/// Get molecule
/// </summary>
/// <param name="molFormat"></param>
/// <param name="molString"></param>

        public void GetMolecule(
            out MoleculeFormat molFormat,
            out string molString)
        {
            molFormat = _molFormat;
            molString = _molString;
        }
Пример #4
0
        /// <summary>
        /// Convert from one format to another
        /// </summary>
        /// <param name="newFormat"></param>
        /// <returns></returns>

        public MoleculeMx ConvertTo(
            MoleculeFormat molFormatType)
        {
            string molString, msg;
            bool   conversionFailed = false;

            MoleculeMx mol = new MoleculeMx(molFormatType);

            try
            {
                // If no change in type, just copy value

                if (this.PrimaryFormat == molFormatType)                 // any change in type?
                {
                    molString = this.PrimaryValue;
                }

                else
                {
                    molString = GetMoleculeString(molFormatType);                  // convert from old type if possible
                }
                mol.SetPrimaryTypeAndValue(molFormatType, molString);
                return(mol);
            }

            catch (Exception ex)             // handle structures that don't convert - issue #216
            {
                //DebugLog.Message("ChemicalStructure.Convert exception for structure: \r\n" + Value + "\r\n" +
                //  DebugLog.FormatExceptionMessage(ex));
                //throw new Exception(ex.Message, ex);
                return(new MoleculeMx(PrimaryFormat, ""));                // return blank structure
            }
        }
Пример #5
0
        /// <summary>
        /// Get the molecule string of the specified type
        /// Do a conversion from an existing type if specified type not yet detined for the molecule
        /// </summary>
        /// <param name="newType"></param>
        /// <returns></returns>

        public string GetMoleculeString(
            MoleculeFormat newType)
        {
            try
            {
                switch (newType)
                {
                case MoleculeFormat.Molfile:
                    return(GetMolfileString());

                case MoleculeFormat.Chime:
                    return(GetChimeString());

                case MoleculeFormat.Smiles:
                    return(GetSmilesString());

                case MoleculeFormat.Helm:
                    return(GetHelmString());

                case MoleculeFormat.Sequence:
                    return(GetSequenceString());

                case MoleculeFormat.Fasta:
                    return(GetFastaString());

                default: throw new Exception("Can't convert type: " + this.PrimaryFormat);
                }
            }

            catch (Exception ex)             // handle structures that don't convert - issue #216
            {
                throw new Exception(ex.Message, ex);
            }
        }
Пример #6
0
/// <summary>
/// SetMoleculeAndRender
/// </summary>
/// <param name="format"></param>
/// <param name="value"></param>

        public void SetMoleculeAndRender(MoleculeFormat format, string value)
        {
            MolFormat = format;
            MolString = value;

            CdkMol = new CdkMol(MolFormat, MolString);

            RenderMolecule();

            return;
        }
Пример #7
0
        /// <summary>
        /// Construct from mol format and string
        /// </summary>

        public CdkMol(
            MoleculeFormat molFormat,
            string molString)
        {
            if (Lex.IsUndefined(molString))
            {
                return;                                         // create new structure
            }
            SetMolecule(molFormat, molString);

            return;
        }
Пример #8
0
/// <summary>
/// Execute structure search for structures stored in an general Oracle table text column
/// </summary>

        void ExecuteInternalOracleStructureColumnSearch()
        {
            SelectList = new List <MetaColumn>();
            QueryColumn    scQc            = null;
            MoleculeFormat structureFormat = MoleculeFormat.Unknown;

            MetaColumn keyMc = Eqp.QueryTable.MetaTable.KeyMetaColumn;
            MetaColumn strMc = null;

            foreach (QueryColumn qc2 in Eqp.QueryTable.QueryColumns)
            {
                if (qc2.Selected || qc2.SortOrder != 0)
                {
                    SelectList.Add(qc2.MetaColumn);
                }
                if (qc2.Criteria == "")
                {
                    continue;
                }
                if (qc2.MetaColumn.DataType == MetaColumnType.Structure)
                {
                    strMc = qc2.MetaColumn;
                    if (Lex.Eq(strMc.DataTransform, "FromMolFile"))
                    {
                        structureFormat = MoleculeFormat.Molfile;
                    }
                    else if (Lex.Eq(strMc.DataTransform, "FromChime"))
                    {
                        structureFormat = MoleculeFormat.Chime;
                    }
                    else if (Lex.Eq(strMc.DataTransform, "FromSmiles"))
                    {
                        structureFormat = MoleculeFormat.Smiles;
                    }
                    break;
                }
                else
                {
                }                       // allow criteria on other cols?
            }

            if (strMc == null)
            {
                throw new Exception("Structure criteria not found");
            }

            string sql =
                "select " + keyMc.Name + ", " + strMc.Name + " " +
                "from " + Eqp.QueryTable.MetaTable.TableMap;

            ExecuteInternalOracleStructureColumnSearch(sql, structureFormat);
            return;
        }
Пример #9
0
        /// <summary>
        /// Try to get molfile form of molecule doing a conversion from another format as necessary
        /// </summary>
        /// <param name="molFormat"></param>
        /// <param name="molString"></param>
        /// <returns></returns>

        public bool TryGetMoleculeString(
            MoleculeFormat molFormat,
            out string molString)
        {
            try
            {
                molString = GetMoleculeString(molFormat);
                return(true);
            }

            catch (Exception ex)
            {
                molString = null;
                return(false);
            }
        }
Пример #10
0
        /// <summary>
        /// Convert any ChemicalStructures containing a sketch value to a ChimeString for proper serialization
        /// </summary>
        /// <param name="oa"></param>

        public static void ConvertMoleculesToChimeStrings(object[] oa)
        {
            for (int ci = 0; ci < oa.Length; ci++)
            {
                if (!(oa[ci] is MoleculeMx))
                {
                    continue;
                }
                MoleculeMx cs = oa[ci] as MoleculeMx;
                if (Math.Abs(1) == 1)
                {
                    continue;                                   // noop for now
                }
                //if (cs.Type != StructureFormat.Sketch) continue; // obsolete
                MoleculeFormat type  = MoleculeFormat.Chime;
                string         value = cs.GetChimeString();

                cs.SetPrimaryTypeAndValue(type, value);
            }
        }
Пример #11
0
/// <summary>
/// Execute structure search for structures stored in an Oracle text column
/// </summary>
/// <param name="sql">Basic sql to select key & structure</param>

        public void ExecuteInternalOracleStructureColumnSearch(
            string sql,
            MoleculeFormat structureFormat)
        {
            string cid, molString;

            object[]   vo;
            MoleculeMx cs;
            bool       match = false;

            QueryColumn molsimQc = Eqp.QueryTable.GetSelectedMolsimQueryColumn();             // get any column to return similarity score in

            DbCommandMx drd = new DbCommandMx();

            if (Eqp.SearchKeySubset == null)
            {
                drd.Prepare(sql);
                drd.ExecuteReader();
            }

            else             // limit to list
            {
                sql += " where " + Eqp.QueryTable.MetaTable.KeyMetaColumn.Name + " in (<list>)";
                drd.PrepareListReader(sql, DbType.String);

                List <string> dbKeySubset = new List <string>();
                foreach (string key in Eqp.SearchKeySubset)
                {
                    string dbKey = CompoundId.NormalizeForDatabase(key, Eqp.QueryTable.MetaTable);
                    dbKeySubset.Add(dbKey);
                }
                drd.ExecuteListReader(dbKeySubset);
            }

            drd.CheckForCancel = Eqp.CheckForCancel;             // set cancel check flag

            StructureMatcher matcher = new StructureMatcher();   // allocate structure matcher
            List <object[]>  results = new List <object[]>();

            int matchCount = 0;

            while (drd.Read())
            {
                cid = drd.GetObject(0).ToString();
                cid = CompoundId.Normalize(cid, Eqp.QueryTable.MetaTable);                 // normalize adding prefix as needed

                molString = drd.GetString(1);
                if (String.IsNullOrEmpty(molString))
                {
                    continue;
                }

                cs = new MoleculeMx(structureFormat, molString);
                if (Pssc.SearchType == StructureSearchType.Substructure)
                {
                    if (matcher.IsSSSMatch(Pssc.Molecule, cs))
                    {
                        vo    = new object[SelectList.Count];
                        vo[0] = CompoundId.Normalize(cid, Eqp.QueryTable.MetaTable);                         // normalize adding prefix
                        results.Add(vo);
                    }
                }

                else if (Pssc.SearchType == StructureSearchType.MolSim)
                {
                    double score = matcher.Molsim(Pssc.Molecule, cs, Pssc.SimilarityType);
                    if (score >= Pssc.MinimumSimilarity)
                    {
                        vo    = new object[SelectList.Count];
                        vo[0] = CompoundId.Normalize(cid, Eqp.QueryTable.MetaTable);                         // normalize adding prefix
                        if (vo.Length >= 2)
                        {
                            vo[1] = (float)score;
                        }

                        results.Add(vo);
                    }
                }

                else if (Pssc.SearchType == StructureSearchType.FullStructure)
                {
                    if (matcher.FullStructureMatch(Pssc.Molecule, cs, Pssc.Options))
                    {
                        vo    = new object[SelectList.Count];
                        vo[0] = CompoundId.Normalize(cid, Eqp.QueryTable.MetaTable);                         // normalize adding prefix
                        results.Add(vo);
                    }
                }
                matchCount++;

//				if (matchCount >100) break; // debug

                if (drd.Cancelled)
                {
                    Eqp.Qe.Cancelled = true;
                    drd.Dispose();
                    Results = null;
                    return;
                }
            }

            drd.Dispose();

            Results = results;
            return;
        }
Пример #12
0
 public void GetMolecule(out MoleculeFormat format, out string value)
 {
     format = MolFormat;
     value  = MolString;
     return;
 }
Пример #13
0
        /// <summary>
        /// Handle conversion of Mobius custom data types between the grid and the underlying DataSet
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        void ProcessCustomUnboundColumnDataEvent(object sender, CustomColumnDataEventArgs e)
        {
            MobiusDataType     mdt   = null;
            FormattedFieldInfo ffi   = null;
            bool           formatted = false;
            NumberMx       numberEx;
            StringMx       stringEx;
            ImageMx        imageMx;
            DateTimeMx     dateTimeEx;
            DataRowMx      dr = null;
            BandedGridView mbgv;
            int            nonNullDri;
            string         debugMsg;

            if (DebugMx.False)             // fillValuesImmediately debug test
            {
                e.Value = "XXX";
                return;
            }

            DateTime t0     = DateTime.Now;
            int      callId = ++UnboundCalls;        // get id for this call

            if (sender is BandedGridView)
            {
                mbgv = sender as BandedGridView;
            }

            if (Grid.DataSource == null)
            {
                return;
            }
            CellInfo ci = Grid.GetDataTableCellInfo(e.ListSourceRowIndex, e.Column);

            //if (e.ListSourceRowIndex == 2 && ci.DataRowIndex == 1) e = e; // debug
            //if (ci.Mc.DataType == MetaColumnType.CompoundId && ci.DataRowIndex > 0) ci = ci; // debug
            //DebugLog.Message("CustomUnboundColumnData " + ci.DataRowIndex + ", " + ci.DataColIndex + ", " + ci.DataValue.ToString());
            if (ci.Rfld == null)
            {
                return;
            }

            QueryManager     qm   = Grid.QueryManager;
            ResultsFormatter fmtr = qm.ResultsFormatter;
            ResultsFormat    rf   = qm.ResultsFormat;

            if (e.ListSourceRowIndex == GridControl.NewItemRowHandle || e.ListSourceRowIndex >= Qm.DataTable.Rows.Count)             // new row being created
            {
                if (NewRow == null)
                {
                    NewRow = Qm.DataTable.NewRow();
                }
                dr = NewRow;
            }

            else if (e.ListSourceRowIndex >= 0 && ci.DataRowIndex >= 0)             // row exist in DataTable (i.e. not new row)
            {
                AdjustDataRowToRender(ci);
                if (ci.DataRowIndex >= 0)
                {
                    dr = DataTable.Rows[ci.DataRowIndex];
                    if (ci.DataRowIndex == 0)
                    {
                    }
                }
            }

            else
            {
                if (DebugDetails)
                {
                    ClientLog.Message("Fail 1");
                }
                return;                 // something else, ignore
            }

            // Store edited data for unbound column in DataTable

            if (e.IsSetData)
            {
                SetGridData(e, ci);
                return;
            }

            else if (!e.IsGetData)
            {
                return;                                // just return if not GetData as expected
            }
// Get data from underlying unbound dataset & return in format for grid

            //if (ci.Mc.DataType == MetaColumnType.Structure) ci = ci; // debug
            //if (ci.Mc.DataType == MetaColumnType.String) ci = ci; // debug
            //if (ci.DataValue is StringEx && ((StringEx)ci.DataValue).Value == " ") ci = ci; // debug

            UnboundGets++;

            if (dr == null)
            {
                e.Value = null;
                if (DebugDetails)
                {
                    ClientLog.Message("Fail 2");                               // debug
                }
                return;
            }

            if (Dtm.IsRetrievingDataMessageRow(dr) && ci.Mc != null && !ci.Mc.IsGraphical)
            {
                //if (ci.Mc.IsKey) // show retrieving data message for key field
                e.Value = "Retrieving data...";

                return;
            }

            object fieldValue = dr[ci.DataColIndex];

            if (DebugDetails && fieldValue is MoleculeMx)             // debug
            {
                MoleculeMx     cs      = fieldValue as MoleculeMx;
                MoleculeFormat csType  = cs.PrimaryFormat;
                string         csValue = cs.PrimaryValue;
                int            csLen   = cs.PrimaryValue.Length;
                string         molfile = cs.GetMolfileString();
                molfile = molfile;
            }

            try
            {
                // If already formatted use existing formatting info

                ffi = null;
                if (fieldValue is MobiusDataType)
                {
                    mdt = (MobiusDataType)fieldValue;
                    if (mdt.FormattedBitmap != null)
                    {
                        ffi = new FormattedFieldInfo();
                        ffi.FormattedBitmap = mdt.FormattedBitmap;
                    }

                    else if (mdt.FormattedText != null)
                    {
                        ffi = new FormattedFieldInfo();
                        ffi.FormattedText = mdt.FormattedText;
                    }

                    if (ffi != null)                     // if formatted then copy other format attributes as well
                    {
                        ffi.BackColor = mdt.BackColor;
                        ffi.ForeColor = mdt.ForeColor;
                        ffi.Hyperlink = mdt.Hyperlink;
                    }
                }

                // If not formatted then format

                if (ffi == null)                 // need to format?
                {
// Format non-image field (including structures)

                    if (ci.Mc.DataType != MetaColumnType.Image)                     // format other than image immediately
                    {
                        //if (ci.Mc.DataType == MetaColumnType.Structure)  // debug
                        //{
                        //	DebugLog.Message(fieldValue.ToString());
                        //	UIMisc.Beep();
                        //}

                        ffi = fmtr.FormatField(ci.Rt, ci.TableIndex, ci.Rfld, ci.FieldIndex, dr, e.ListSourceRowIndex, fieldValue, ci.DataRowIndex, false);

                        FormatFieldCalls++;
                        if (ci.Mc.DataType == MetaColumnType.Structure)
                        {
                            FormatStructureFieldCalls++;
                        }

                        StoreFormattingInformationInMdt(ffi, fieldValue, dr, ci, mdt);
                        formatted = true;
                    }

// Image: start asynch call to get image in background as necessary since it is too slow to wait for it here

                    else
                    {
                        if (fieldValue is ImageMx)
                        {
                            imageMx = fieldValue as ImageMx;
                        }

                        else
                        {
                            imageMx = new ImageMx();
                            if (fieldValue != null)
                            {
                                if (fieldValue is MobiusDataType)
                                {
                                    imageMx.DbLink = (fieldValue as MobiusDataType).DbLink;
                                }
                                else
                                {
                                    imageMx.DbLink = fieldValue.ToString();                                  // store field value as dblink
                                }
                            }
                            dr.ItemArrayRef[ci.DataColIndex] = imageMx;                             // store new image object without firing event
                        }

                        mdt = imageMx;                         // copy image object to general  MobiusDataType
                        ffi = new FormattedFieldInfo();

                        if (imageMx.FormattedBitmap != null)                         // already have bitmap?
                        {
                            ffi.FormattedBitmap = imageMx.FormattedBitmap;
                        }

                        else if (imageMx.Value != null)                                                        // have the bitmap, just need to scale it
                        {
                            int fieldWidth   = ci.Rfld.FieldWidth;                                             // current field width in milliinches
                            int desiredWidth = (int)((fieldWidth / 1000.0) * GraphicsMx.LogicalPixelsX * 1.0); // width in pixels

                            imageMx.FormattedBitmap = BitmapUtil.ScaleBitmap(imageMx.Value, desiredWidth);
                            ffi.FormattedBitmap     = imageMx.FormattedBitmap;
                        }

                        else if (imageMx.IsRetrievingValue)                         // already retrieving?
                        {
                            ffi.FormattedBitmap = (Bitmap)RetrievingImageMsg.Image; // put up the processing image
                        }
                        else if (SS.I.AsyncImageRetrieval)                          // start async image retrieval
                        {
                            FormatImageFieldCalls++;
                            GetImageBitmapAsync(ci, dr, e.ListSourceRowIndex, fieldValue, imageMx, callId);
                            ffi.FormattedBitmap = (Bitmap)RetrievingImageMsg.Image;                             // put up the processing image
                        }

                        else                         // do synchronous image retrieval
                        {
                            GetImageBitmap(ci, dr, e.ListSourceRowIndex, fieldValue, imageMx, callId);
                            ffi.FormattedBitmap = imageMx.FormattedBitmap;
                            formatted           = true;
                        }
                    }
                }

                //if (ci.Mc.DataType == MetaColumnType.CompoundId && String.IsNullOrEmpty(fmtdFld.Hyperlink)) ci = ci; // debug
                //if (mdt is CompoundId) mdt = mdt; // debug

                if (e.Column.ColumnEdit is RepositoryItemPictureEdit)
                {
                    if (ffi != null && ffi.FormattedBitmap != null)
                    {
                        e.Value = ffi.FormattedBitmap;
                    }
                    else
                    {
                        e.Value = new Bitmap(1, 1);                              // avoid no-image data message
                    }
                    //ffi.FormattedBitmap.Save(@"c:\download\test.bmp"); // debug
                }

                else
                {
                    e.Value = ffi.FormattedText;                   // non-picture column
                }
                if (ci.DataRowIndex == DataTable.Rows.Count - 1 && // if at end of DataTable && more rows available, request them
                    !Dtm.RowRetrievalComplete)
                {
                    //Progress.Show("Retrieving data..."); // put up progress dialog if not already up

                    //if (WaitForMoreDataStartTime.Equals(DateTime.MinValue)) // say we've started waiting for data
                    //{
                    //  WaitForMoreDataStartTime = DateTime.Now;
                    //  ClientLog.Message("Set WaitForMoreDataStartTime: " + WaitForMoreDataStartTime.ToLongTimeString());
                    //}

                    if (Dtm.RowRetrievalState == RowRetrievalState.Paused)
                    {
                        Dtm.StartRowRetrieval();                         // .ReadNextRowsFromQueryEngine(); // restart retrieval
                    }
                }

                else if (Lex.StartsWith(Progress.GetCaption(), "Retrieving data...") || Lex.IsUndefined(Progress.GetCaption()))
                {                 // hide any "Retrieving data..." message
                    Progress.Hide();
                    //SystemUtil.Beep();
                }

                Grid.LastRowRendered = e.ListSourceRowIndex;

                if (DebugDetails)
                {
                    debugMsg =
                        "Grid.GetData: " + callId + ", e.Row = " + e.ListSourceRowIndex +
                        ", e.Col = " + e.Column.AbsoluteIndex + ", Formatted = " + (formatted ? "T" : "F") + ", Time(ms) = " + TimeOfDay.Delta(t0) +
                        ", ColLabel = " + ci.Qc.ActiveLabel;
                    debugMsg += ", FieldValue = ";
                    if (fieldValue != null)
                    {
                        debugMsg += fieldValue.ToString();
                    }
                    debugMsg += ", e.Value = ";
                    if (e.Value != null)
                    {
                        debugMsg += e.Value.ToString();
                    }
                    else
                    {
                        debugMsg += "null";
                    }
                    ClientLog.Message(debugMsg);
                }

                // TODO: This does a some unnecessary hides which cause flashing of the window frame
                // This happens when we are not at the end of the DataTable but don't know if any additional requests
                // for rendering will occur. May be better to move this to DataTableManger when we detect
                // that we have retrieved a row that is below the level of those displayed in the grid or all rows have been retrieved.
                // Also maybe in MoleculeGridControl.RetrievalMonitorTimer_Tick
            }

            catch (Exception ex)
            {
                if (e.Column.ColumnEdit is RepositoryItemPictureEdit)
                {
                    e.Value = new Bitmap(1, 1);                     // avoid no-image data message
                }
                else
                {
                    e.Value = ex.Message;
                }

                string msg = "ColumnView_CustomUnboundColumnData Exception";
                if (ci.Rfld != null)
                {
                    msg += ",  MetaColumn: " + ci.Rfld.MetaColumn.MetaTable.Name + "." + ci.Rfld.MetaColumn.Name;
                }
                msg += ",  DataColIndex: " + ci.DataColIndex + ",  DataRowIndex: " + ci.DataRowIndex;
                if (fieldValue != null)
                {
                    msg += ",  Value: " + fieldValue.ToString();
                }
                ClientLog.Message(msg);
            }


            //			t0 = TimeOfDay.Milliseconds() - t0;
            //			ClientLog.Message("CustomUnboundColumnData event time: " + t0);
        }
Пример #14
0
        /// <summary>
        /// Scale and translate structure and format into buffer
        /// </summary>
        /// <param name="mol">The structure</param>
        /// <param name="cellStyle">Style/conditional formatting to apply to cell</param>
        /// <param name="commandChar">Command character to use in buffer</param>
        /// <param name="x">Coordinate of left side of structure</param>
        /// <param name="width">Width of molecule box in milliinches</param>
        /// <param name="r">Row in buffer to put on. If less than 0 then return formatted data</param>
        /// <param name="heightInLines">number of lines used</param>

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

            bool debug = DataTableManager.DebugDetails;

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

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

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

                FormattedFieldInfo ffi = new FormattedFieldInfo();

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

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

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

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

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

                    // Hilight substructure search match

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

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

                    // Hilight SmallWorld structure match

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

                        SmallWorldPredefinedParameters swp = pssc.SmallWorldParameters;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                bool fitStructure = true;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                return(null);
            }

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

            finally
            {
                pt.Update();
                int formatCount = pt.Count;
                //ClientLog.Message(pt.ToString() + ", " + cs.GetMolHeader()[2]); // + ", " + new StackTrace(true));
                if (debug)
                {
                    DebugLog.StopwatchMessage("tTotalTime", swTotal);
                }
            }
        }
Пример #15
0
        /// <summary>
        /// Construct from mol format and string
        /// </summary>
        /// <param name="molFormat"></param>
        /// <param name="molString"></param>
        /// <returns></returns>

        public ICdkMol NewCdkMol(
            MoleculeFormat molFormat,
            string molString)
        {
            return(new CdkMol(molFormat, molString));
        }
Пример #16
0
        public static void Load()
        {
            string value;
            int    i1;

            PrefDict = UserObjectDao.GetUserParameters(Security.UserName);

            SS.I.PreferredProjectId =             // get preferred project
                                      Get("PreferredProject", "DEFAULT_FOLDER");

            SS.I.TableColumnZoom     = GetInt("TableColumnZoom", 100);
            SS.I.GraphicsColumnZoom  = GetInt("GraphicsColumnZoom", 100);
            SS.I.ScrollGridByPixel   = GetBool("ScrollGridByPixel", false);           // default to row scrolling
            SS.I.AsyncImageRetrieval = GetBool("AsyncImageRetrieval", true);

            try             // get preferred number format
            {
                value = Get("DefaultNumberFormat", "SigDigits");
                EnumUtil.TryParse(value, out SS.I.DefaultNumberFormat);

                SS.I.DefaultDecimals = GetInt("DefaultDecimals", 3);
            }
            catch (Exception ex) { }

            SS.I.RepeatReport =             // repeating report across page
                                GetBool("RepeatReport", false);

            MqlUtil.DefaultToSingleStepQueryExecution =             // default to single step query execution
                                                        GetBool("DefaultToSingleStepQueryExecution", false);

            if (MqlUtil.DefaultToSingleStepQueryExecution)
            {
                QueryEngine.SetParameter("DefaultToSingleStepQueryExecution", MqlUtil.DefaultToSingleStepQueryExecution.ToString());                 // set in QE for current session
            }
            SS.I.FindRelatedCpdsInQuickSearch =
                GetBool("FindRelatedCpdsInQuickSearch", true);

            SS.I.RestoreWindowsAtStartup =             // get bool for restoring windows at startup
                                           GetBool("RestoreWindowsAtStartup", false);

            SS.I.BreakHtmlPopupsAtPageWidth =
                GetBool("BreakHtmlPopupsAtPageWidth", true);

            try             // qualified number splitting
            {
                value = Get("QualifiedNumberSplit");
                SS.I.QualifiedNumberSplit = QnfSplitControl.DeserializeQualifiedNumberSplit(value);
            }
            catch (Exception ex) { }

            SS.I.HilightCidChanges =
                GetBool("HilightCorpIdChanges", true);

            SS.I.RemoveLeadingZerosFromCids =
                GetBool("RemoveLeadingZerosFromCids", true);

            SS.I.GridMarkCheckBoxesInitially =             // (always false initially now)
                                               GetBool("GridMarkCheckBoxesInitially", false);

            value = Get("DefaultHorizontalAlignment", MetaColumn.SessionDefaultHAlignment.ToString());
            MetaColumn.SessionDefaultHAlignment = (HorizontalAlignmentEx)Enum.Parse(typeof(HorizontalAlignmentEx), value, true);

            value = Get("DefaultVerticalAlignment", MetaColumn.SessionDefaultVAlignment.ToString());
            MetaColumn.SessionDefaultVAlignment = (VerticalAlignmentEx)Enum.Parse(typeof(VerticalAlignmentEx), value, true);

            SS.I.EvenRowBackgroundColor =
                Color.FromArgb(GetInt("EvenRowBackgroundColor", Color.WhiteSmoke.ToArgb()));                 // slightly contrasting color

            SS.I.OddRowBackgroundColor =
                Color.FromArgb(GetInt("OddRowBackgroundColor", Color.White.ToArgb()));

            ClientDirs.DefaultMobiusUserDocumentsFolder = Preferences.Get("DefaultExportFolder", ClientDirs.DefaultMobiusUserDocumentsFolder);

            MoleculeFormat molFormat = MoleculeFormat.Molfile;

            value = Get("PreferredMoleculeFormat", "Molfile");
            if (Enum.TryParse(value, out molFormat))
            {
                MoleculeMx.PreferredMoleculeFormat = molFormat;
            }

            return;
        }
Пример #17
0
        /// <summary>
        /// Construct from mol format and string
        /// </summary>
        /// <param name="molFormat"></param>
        /// <param name="molString"></param>
        /// <returns></returns>

        public INativeMolMx NewCdkMol(
            MoleculeFormat molFormat,
            string molString)
        {
            return(new CdkMol(molFormat, molString));
        }