Esempio n. 1
0
        /// <summary>
        /// 制作饼状图
        /// </summary>
        /// <param name="lstInputRequest"></param>
        /// <param name="inputTitle"></param>
        /// <returns></returns>
        public Image MakePieChart(List <PieChartRequest> lstInputRequest, string inputTitle = null)
        {
            ZedGraphControl tempZ = new ZedGraphControl();

            tempZ.Width  = m_useWidth;
            tempZ.Height = m_useHight;

            var useGraph = tempZ.GraphPane;

            useGraph.Legend.IsVisible     = false;
            useGraph.XAxis.IsVisible      = false;
            useGraph.YAxis.IsVisible      = false;
            useGraph.Legend.Position      = LegendPos.InsideTopLeft;
            useGraph.Legend.FontSpec.Size = 15f;
            useGraph.Legend.IsHStack      = false;
            useGraph.Title.IsVisible      = false;

            if (!string.IsNullOrWhiteSpace(inputTitle))
            {
                useGraph.Title.Text      = inputTitle;
                useGraph.Title.IsVisible = true;
            }

            foreach (var oneRequest in lstInputRequest)
            {
                var tempSegment = useGraph.AddPieSlice(oneRequest.Value, oneRequest.UseColor, oneRequest.Offset, oneRequest.Name);
                tempSegment.LabelDetail.FontSpec.Size = 15f;
                tempSegment.Border.IsVisible          = false;
                tempSegment.LabelType = PieLabelType.Name_Value_Percent;
            }

            return(tempZ.GetImage());
        }
        public void WriteToFile(string fileName, SimplePeakChro t)
        {
            zgc.GraphPane.CurveList.Clear();

            PointPairList ppl        = new PointPairList();
            PointPairList identified = new PointPairList();

            t.Peaks.ForEach(m =>
            {
                ppl.Add(m.RetentionTime, m.Intensity / m.IonInjectionTime);
                if (m.Identified)
                {
                    identified.Add(m.RetentionTime, m.Intensity / m.IonInjectionTime);
                }
            });

            zgc.GraphPane.AddCurve("", ppl, Color.Blue, SymbolType.None);
            zgc.GraphPane.AddIndividualLine("", identified, Color.Red);

            zgc.GraphPane.XAxis.Title.Text = "Retention Time (min)";
            zgc.GraphPane.YAxis.Title.Text = "Abundance";
            zgc.GraphPane.Title.Text       = string.Format("{0}\n{1} : m/z={2:0.0000}, charge={3}, scan={4}", Path.GetFileName(fileName), t.Sequence, t.Mz, t.Charge, t.Peaks.Count);
            zgc.AxisChange();

            zgc.GetImage().Save(fileName, ImageFormat.Png);
        }
Esempio n. 3
0
        private void Form_Load(object sender, EventArgs e)
        {
            MasterPane myPaneMaster = zedG.MasterPane;

            myPaneMaster.Title.Text = "NetWorth";
            myPaneMaster.Title.FontSpec.FontColor = Color.Black;

            GraphPane myPane = zedG.GraphPane;

            myPaneMaster.PaneList[0] = (myPane);

            //    //画一张的小图
            //    GraphPane paneStats = new GraphPane(new Rectangle(10, 10, 10, 10), "Mes", " t ( h )", "Rate");
            //    myPaneMaster.PaneList.Add(paneStats);

            LineItem[] myCurve = new LineItem[lineChart.Count];

            //建立indexD变量,索引myCurve变量
            int indexD = 0;
            //建立Random变量用于控制颜色变化
            Random aa = new Random();

            foreach (var variety in lineChart)
            {
                myCurve[indexD] = myPane.AddCurve(variety.Key, null, lineChart[variety.Key],
                                                  Color.FromArgb(aa.Next(1, 255), aa.Next(1, 255), aa.Next(1, 255)), SymbolType.None);
                myCurve[indexD].Symbol.Size = 8.0F;
                myCurve[indexD].Symbol.Fill = new Fill(Color.White);
                myCurve[indexD].Line.Width  = 2.0F;
                ++indexD;
            }

            // Draw the X tics between the labels instead of at the labels
            //myPane.XAxis.IsTicsBetweenLabels = true;

            // Set the XAxis labels
            myPane.XAxis.Scale.TextLabels = date;
            // Set the XAxis to Text type
            myPane.XAxis.Type = AxisType.Text;

            //设置X轴和Y轴的名称
            myPane.XAxis.Title.Text = "时间"; //X轴
            myPane.YAxis.Title.Text = "净值"; //Y轴

            //设置图的title
            myPane.Title.Text = "净值曲线";

            // Fill the axis area with a gradient
            //myPane.AxisFill = new Fill(Color.White,
            //Color.FromArgb(255, 255, 166), 90F);
            // Fill the pane area with a solid color
            //myPane.PaneFill = new Fill(Color.FromArgb(250, 250, 255));

            //绩效指标图统计

            zedG.AxisChange();
            imageZed = zedG.GetImage();
        }
Esempio n. 4
0
        public static void AddPic(string save_path, string title, string x_label, string y_label,
                                  double x_min, double x_max, double y_min, double y_max, List <double[]> args,
                                  List <string> curve_names, bool show_symbol = true)
        {
            ZedGraphControl zgc = new ZedGraphControl();

            zgc.Width  = 800;
            zgc.Height = 600;
            zgc.GraphPane.Title.Text                = title;
            zgc.GraphPane.XAxis.Title.Text          = x_label;
            zgc.GraphPane.YAxis.Title.Text          = y_label;
            zgc.GraphPane.XAxis.MajorGrid.IsVisible = true;
            zgc.GraphPane.YAxis.MajorGrid.IsVisible = true;
            zgc.GraphPane.YAxis.Scale.Max           = y_max;
            zgc.GraphPane.YAxis.Scale.Min           = y_min;
            zgc.GraphPane.XAxis.Scale.Max           = x_max;
            zgc.GraphPane.XAxis.Scale.Min           = x_min;
            List <SymbolType> list_symbol;

            list_symbol = new List <SymbolType>();
            foreach (SymbolType type in Enum.GetValues(typeof(SymbolType)))
            {
                list_symbol.Add(type);
            }

            // zgc.GraphPane.XAxis.Type = ZedGraph.AxisType.LinearAsOrdinal;

            for (int i = 0; i < curve_names.Count; i++)
            {
                //up曲线
                PointPairList list1 = new PointPairList(args[2 * i], args[2 * i + 1]);
                if (show_symbol == true)
                {
                    zgc.GraphPane.AddCurve(curve_names[i], list1, Color.Black, list_symbol[i % 12]);
                }
                else
                {
                    zgc.GraphPane.AddCurve(curve_names[i], list1, Color.Black, SymbolType.None);
                }
                //down曲线
                PointPairList list2 = new PointPairList(args[2 * i + 2], args[2 * i + 3]);
                if (show_symbol == true)
                {
                    zgc.GraphPane.AddCurve(curve_names[i], list2, Color.Black, list_symbol[i % 12]);
                }
                else
                {
                    zgc.GraphPane.AddCurve(curve_names[i], list2, Color.Black, SymbolType.None);
                }
            }
            zgc.AxisChange();
            zgc.Refresh();
            zgc.GetImage().Save(save_path);
        }
Esempio n. 5
0
        /// <summary>
        /// 制作一个柱状图
        /// </summary>
        /// <param name="inputValues"></param>
        /// <param name="xTtitle"></param>
        /// <param name="yTitle"></param>
        /// <param name="title"></param>
        /// <param name="useXTags"></param>
        /// <returns></returns>
        public Image MakeBarChart(List <BarItemsRequest> inputValues, string xTtitle, string yTitle, string title, List <string> useXTags)
        {
            ZedGraphControl tempZ = new ZedGraphControl();

            tempZ.Width  = m_useWidth;
            tempZ.Height = m_useHight;

            SetTitles(xTtitle, title, tempZ);

            List <BarItem> lstUseBarITem = new List <BarItem>();

            //创建柱状图
            foreach (var oneRequest in inputValues)
            {
                lstUseBarITem.Add(tempZ.GraphPane.AddBar(oneRequest.UseLable, null, oneRequest.UseValue, oneRequest.UseColor));
            }

            //添加数值
            if (m_ifShowYValue)
            {
                foreach (var oneBaritem in lstUseBarITem)
                {
                    for (int i = 0; i < oneBaritem.Points.Count; i++)
                    {
                        //此处y值+1防止重叠
                        TextObj barLabel = new TextObj(oneBaritem.Points[i].Y.ToString(),
                                                       oneBaritem.Points[i].X, oneBaritem.Points[i].Y + 1
                                                       , CoordType.AxisXYScale, AlignH.Center, AlignV.Bottom);

                        barLabel.FontSpec.Border.IsVisible = false;
                        tempZ.GraphPane.GraphObjList.Add(barLabel);
                    }
                }
            }

            //检查是否做标签
            if (null != useXTags && 0 != useXTags.Count)
            {
                tempZ.GraphPane.XAxis.Scale.TextLabels = useXTags.ToArray();
                tempZ.GraphPane.XAxis.Type             = AxisType.Text;
            }

            if (m_ifShowLables)
            {
                tempZ.GraphPane.Legend.IsVisible = false;
            }

            //调整轴
            tempZ.AxisChange();

            return(tempZ.GetImage());
        }
Esempio n. 6
0
        public MatchImageBuilder(string mgfFile, string targetDir)
        {
            var mgfReader = new Mascot.MascotGenericFormatReader <MatchedPeak>();
            var spectra   = mgfReader.ReadFromFile(mgfFile);

            spectra.ForEach(m => m.Experimental = m.Experimental.Substring(0, m.Experimental.Length - 4));
            mgfMap = spectra.ToDictionary(m => string.Format("{0}_{1}", m.Experimental, m.ScanTimes[0].Scan));

            var mods = new Dictionary <char, double>();

            mods['&'] = 7.017166;
            mods['#'] = 3.010071;
            mods['@'] = 6.013809;
            mods['*'] = 15.994919;
            mods['C'] = 57.021464 + aas['C'].MonoMass; // 160.16523;
            mods['K'] = 8.014206 + aas['K'].MonoMass;
            mods['R'] = 10.008270 + aas['R'].MonoMass;

            aas.SetModification(mods);

            yBuilder = new CIDPeptideYSeriesBuilder <MatchedPeak>()
            {
                CurAminoacids = aas
            };
            bBuilder = new CIDPeptideBSeriesBuilder <MatchedPeak>()
            {
                CurAminoacids = aas
            };
            y2Builder = new CIDPeptideY2SeriesBuilder <MatchedPeak>()
            {
                CurAminoacids = aas
            };
            b2Builder = new CIDPeptideB2SeriesBuilder <MatchedPeak>()
            {
                CurAminoacids = aas
            };

            zgcPeaks        = new ZedGraphControl();
            zgcPeaks.Width  = 1600;
            zgcPeaks.Height = 1200;
            zgcPeaks.MasterPane.Border.IsVisible = false;

            zgcPeaks.InitMasterPanel(Graphics.FromImage(zgcPeaks.GetImage()), 2, "");
            zgcPeaks.IsSynchronizeXAxes = true;

            if (!Directory.Exists(targetDir))
            {
                Directory.CreateDirectory(targetDir);
            }
            this.targetDir = targetDir;
        }
Esempio n. 7
0
        public override IEnumerable <string> Process(string saveFileName)
        {
            using (ZedGraphControl zgcScan = new ZedGraphControl())
            {
                zgcScan.MasterPane.PaneList.Clear();
                zgcScan.MasterPane.Margin.All      = 1;
                zgcScan.MasterPane.InnerPaneGap    = 1;
                zgcScan.MasterPane.Title.Text      = "Red - Sample; Blue - Reference";
                zgcScan.MasterPane.Title.IsVisible = true;

                var count = (int)Math.Sqrt(sampleDatas.Count + refDatas.Count) + 1;
                zgcScan.Width  = 160 * count;
                zgcScan.Height = 120 * count;

                foreach (var data in sampleDatas)
                {
                    AddGraphPane(zgcScan, data, sampleColor);
                }

                foreach (var data in refDatas)
                {
                    AddGraphPane(zgcScan, data, refColor);
                }

                var maxIntensity = (from d in sampleDatas.Union(refDatas)
                                    from p in d[peakName]
                                    select p.Intensity).Max();

                zgcScan.MasterPane.PaneList.ForEach(m => m.YAxis.Scale.Max = maxIntensity);

                using (Bitmap bm = new Bitmap(1, 1))
                {
                    using (Graphics g = Graphics.FromImage(bm))
                    {
                        zgcScan.MasterPane.SetLayout(g, PaneLayout.SquareRowPreferred);

                        zgcScan.AxisChange();
                    }

                    using (var bmp = zgcScan.GetImage())
                    {
                        bmp.Save(saveFileName, ImageFormat.Png);
                    }
                }
            }

            GC.Collect();
            GC.WaitForFullGCComplete();

            return(new string[] { saveFileName });
        }
Esempio n. 8
0
        public void PrintTube()
        {
            StreamWriter file = File.AppendText(filename);

            file.WriteLine("\t Значение\t -2.5%\t\t +2.5%\t");
            for (int i = 0; i <= N + M; i++)
            {
                file.Write("P{0}\t {1:0.00000}\t ", i, Probability[i]);
                for (int j = 0; j < FivePerCentTube.GetLength(1); j++)
                {
                    file.Write("{0:0.00000}\t ", FivePerCentTube[i, j]);
                }
                file.WriteLine();
            }
            file.WriteLine();
            file.WriteLine();
            file.Close();

            PrintLines(Time, ProbabilityTime, zedGraphControl1);
            Image bmp = zedGraphControl1.GetImage();

            bmp.Save("Pk(t).bmp");
        }
        public override IEnumerable <string> Process(string saveFileName)
        {
            ZedGraphControl zgcScan = new ZedGraphControl();

            zgcScan.MasterPane.PaneList.Clear();
            zgcScan.MasterPane.Margin.All   = 1;
            zgcScan.MasterPane.InnerPaneGap = 1;

            var count = (int)Math.Sqrt(datas.Count) + 1;

            zgcScan.Width  = 300 * count;
            zgcScan.Height = 200 * count;

            foreach (var data in datas)
            {
                GraphPane myPane = new GraphPane();

                var items  = data[peakName];
                var points = new PointPairList();
                items.ConvertAll(m => new PointPair(m.Scan, m.Intensity)).ForEach(m => points.Add(m));

                myPane.AddCurve(data.FileName, points, color, SymbolType.None);

                zgcScan.MasterPane.PaneList.Add(myPane);
            }

            zgcScan.MasterPane.PaneList.ForEach(m => m.YAxis.Scale.Max = maxIntensity);

            Bitmap bm = new Bitmap(1, 1);

            using (Graphics g = Graphics.FromImage(bm))
            {
                zgcScan.MasterPane.SetLayout(g, PaneLayout.SquareRowPreferred);

                zgcScan.AxisChange();
            }

            zgcScan.GetImage().Save(saveFileName, ImageFormat.Png);

            return(new string[] { saveFileName });
        }
Esempio n. 10
0
        public static void recordToPng(ZedGraphControl zedG, string path = "")
        {
            var fullPath = path;

            zedG.GetImage().Save(fullPath);
        }
Esempio n. 11
0
        /// <summary>
        /// 【原版】窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form_Load(object sender, EventArgs e)
        {
            MasterPane myPaneMaster = zedG.MasterPane;

            myPaneMaster.Title.Text = "NetWorth";
            myPaneMaster.Title.FontSpec.FontColor = Color.Black;

            GraphPane myPane = zedG.GraphPane;

            myPaneMaster.PaneList[0] = (myPane);

            //    //画一张的小图
            //GraphPane paneStats = new GraphPane(new Rectangle(10, 10, 10, 10), "Mes", " t ( h )", "Rate");
            //myPaneMaster.PaneList.Add(paneStats);

            //GraphPane paneStats = new GraphPane(new Rectangle(10, 10, 50, 50), "Mes", " t ( h )", "Rate");
            //myPaneMaster.PaneList[1]=(paneStats);

            LineItem[] myCurve = new LineItem[lineChart.Count];

            //建立indexD变量,索引myCurve变量
            int indexD = 0;

            #region 设置曲线颜色:随机模式【请勿删除!】
            //建立Random变量用于控制颜色变化
            //Random aa = new Random();
            //foreach (var variety in lineChart)
            //{
            //    myCurve[indexD] = myPane.AddCurve(variety.Key, null, lineChart[variety.Key],
            //        Color.FromArgb(aa.Next(1, 255), aa.Next(1, 255), aa.Next(1, 255)), SymbolType.None);
            //    myCurve[indexD].Symbol.Size = 8.0F;
            //    myCurve[indexD].Symbol.Fill = new Fill(Color.White);
            //    myCurve[indexD].Line.Width = 2.0F;
            //    ++indexD;
            //}
            #endregion

            #region 设置曲线颜色:自定义模式+随机模式
            //建立Random变量用于控制颜色变化
            Random aa = new Random();
            foreach (var variety in lineChart)
            {
                //如果当前索引值indexD小于用户自定义颜色模板的个数,则使用用户定义的颜色
                if (indexD <= colorList.Count - 1)
                {
                    myCurve[indexD] = myPane.AddCurve(variety.Key, null, lineChart[variety.Key],
                                                      Color.FromArgb(colorList[indexD].Red, colorList[indexD].Green, colorList[indexD].Blue), SymbolType.None);
                }
                //如果当前索引值indexD大于用户自定义颜色模板的个数,则随机生成颜色
                else
                {
                    myCurve[indexD] = myPane.AddCurve(variety.Key, null, lineChart[variety.Key],
                                                      Color.FromArgb(aa.Next(1, 255), aa.Next(1, 255), aa.Next(1, 255)), SymbolType.None);
                }

                myCurve[indexD].Symbol.Size = 8.0F;
                myCurve[indexD].Symbol.Fill = new Fill(Color.White);
                myCurve[indexD].Line.Width  = 2.0F;
                ++indexD;
            }
            #endregion

            // Draw the X tics between the labels instead of at the labels
            //myPane.XAxis.IsTicsBetweenLabels = true;

            // Set the XAxis labels
            myPane.XAxis.Scale.TextLabels = date;
            // Set the XAxis to Text type
            myPane.XAxis.Type = AxisType.Text;

            //设置X轴和Y轴的名称
            myPane.XAxis.Title.Text = XAxisTitleString; //X轴
            myPane.YAxis.Title.Text = YAxisTitleString; //Y轴

            //设置图的title
            myPane.Title.Text = formTitleString;



            // Fill the axis area with a gradient
            //myPane.AxisFill = new Fill(Color.White,
            //Color.FromArgb(255, 255, 166), 90F);
            // Fill the pane area with a solid color
            //myPane.PaneFill = new Fill(Color.FromArgb(250, 250, 255));

            //绩效指标图统计

            zedG.AxisChange();
            imageZed = zedG.GetImage();
        }
Esempio n. 12
0
        /// <summary>
        /// Envoi un courriel en format HTML
        /// </summary>
        /// <param name="tagFormater">L'objet de conversion des tags initialiser avec un compte</param>
        /// <param name="smtp">La configuration du serveur SMTP</param>
        /// <param name="recipients">La liste des récipients</param>
        /// <param name="subject">Le sujet du courriel</param>
        /// <param name="templateFile">Le modèle à utiliser pour le courriel</param>
        /// <param name="img">L'image du graphique</param>
        public void SendMailHTML(MailTagFormater tagFormater,
                                 SmtpSettings smtp,
                                 string recipients,
                                 string subject,
                                 string templateFile,
                                 VideotronAccount account)
        {
            // Les templates personnalisé sont plus fort que ceux de base (notion d'override)
            // Si le template n'existe pas, on prend le premier de la liste
            if (MailTemplates.FirstOrDefault(p => p.Name == templateFile) == null)
            {
                templateFile = MailTemplates.FirstOrDefault().Name;
            }

            subject = tagFormater.Convert(subject);

            StringBuilder template = new StringBuilder(tagFormater.Convert(MailTemplates.FirstOrDefault(p => p.Name == templateFile).GetContent()));

            SmtpClient client = new SmtpClient(smtp.Host, smtp.Port);

            client.Credentials = new NetworkCredential(smtp.Username, smtp.Password);

            MailMessage message = new MailMessage();

            message.From = new MailAddress(smtp.SenderMail, smtp.Sender, System.Text.Encoding.UTF8);

            foreach (string address in recipients.Split(';'))
            {
                message.To.Add(new MailAddress(address));
            }

            message.Subject = subject;

            switch (MailTemplates.FirstOrDefault(p => p.Name == templateFile).Encoding)
            {
            case MailTemplate.MailTemplateEncodingType.ASCII:
                message.SubjectEncoding = System.Text.Encoding.ASCII;
                message.BodyEncoding    = System.Text.Encoding.ASCII;
                break;

            case MailTemplate.MailTemplateEncodingType.ISO8859:
                message.SubjectEncoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                message.BodyEncoding    = System.Text.Encoding.GetEncoding("ISO-8859-1");
                break;

            default:
                message.SubjectEncoding = System.Text.Encoding.UTF8;
                message.BodyEncoding    = System.Text.Encoding.UTF8;
                break;
            }

            // Modèle HTML
            if (MailTemplates.FirstOrDefault(p => p.Name == templateFile).IsHTML)
            {
                message.IsBodyHtml = true;
                AlternateView htmlView;

                // Embebbed image
                List <string> embeddedImageFile = new List <string>();
                Match         embeddedImage;
                string        addedImage;
                do
                {
                    embeddedImage = Regex.Match(template.ToString(), "src=\"(?<src>[^cid]+)\"", RegexOptions.IgnoreCase);

                    if (embeddedImage.Success)
                    {
                        addedImage = System.IO.Path.Combine(MailTemplates.FirstOrDefault(p => p.Name == templateFile).Folder,
                                                            embeddedImage.Groups["src"].Value);
                        if (!File.Exists(addedImage))
                        {
                            throw new FileNotFoundException(addedImage);
                        }

                        embeddedImageFile.Add(addedImage);
                        template.Replace(String.Format("{0}", embeddedImage.Groups["src"].Value), String.Format("cid:img{0}", embeddedImageFile.Count));
                    }
                }while (embeddedImage.Success);

                // Insertion du graphique
                // Il faudrait le mettre dans MailTagFormater, mais c'est compliqué, pas le temps
                List <Tuple <int, int> > graphSize = new List <Tuple <int, int> >();
                Match match      = Regex.Match(template.ToString(), @"\[GRAPH(\((?<param>[^\)]*)?\))?\]", RegexOptions.IgnoreCase);
                int   graphCount = 0;
                int   delta      = 0;
                while (match.Success)
                {
                    int width  = 430;
                    int height = 230;

                    Match paramMatch = Regex.Match(match.Groups["param"].Value,
                                                   @"(?<method>[a-z]{3,})=(?<param>[^,]+)",
                                                   RegexOptions.IgnoreCase);
                    while (paramMatch.Success)
                    {
                        if (paramMatch.Groups["method"].Value.ToUpper() == "WIDTH")
                        {
                            width = Convert.ToInt32(paramMatch.Groups["param"].Value);
                        }
                        else if (paramMatch.Groups["method"].Value.ToUpper() == "HEIGHT")
                        {
                            height = Convert.ToInt32(paramMatch.Groups["param"].Value);
                        }
                        paramMatch = paramMatch.NextMatch();
                    }

                    graphSize.Add(new Tuple <int, int>(width, height));

                    template.Remove(match.Index + delta, match.Length);
                    string newValue = String.Format("<img src=\"cid:graph_{0}\" width=\"{1}\" height=\"{2}\" />",
                                                    graphCount,
                                                    width,
                                                    height);
                    template.Insert(match.Index + delta, newValue);

                    if (match.Length > newValue.Length)
                    {
                        delta -= match.Length - newValue.Length;
                    }
                    else if (match.Length < newValue.Length)
                    {
                        delta += newValue.Length - match.Length;
                    }

                    graphCount++;
                    match = match.NextMatch();
                }

                htmlView = AlternateView.CreateAlternateViewFromString(template.ToString(), System.Text.Encoding.UTF8, "text/html");
                for (int i = 0; i < graphSize.Count; i++)
                {
                    System.Drawing.Image img;
                    MemoryStream         memoryGraph  = new MemoryStream();
                    GraphFactory         graphFactory = new GraphFactory();
                    ZedGraphControl      graph        = graphFactory.Generate(account.Username,
                                                                              new Period(account.PeriodStart, account.PeriodEnd),
                                                                              graphSize[i].Item1, graphSize[i].Item2);

                    img = graph.GetImage();
                    img.Save(memoryGraph, System.Drawing.Imaging.ImageFormat.Jpeg);
                    memoryGraph.Position = 0;

                    htmlView.LinkedResources.Add(new LinkedResource(memoryGraph,
                                                                    MediaTypeNames.Image.Jpeg)
                    {
                        ContentId        = String.Format("graph_{0}", i),
                        TransferEncoding = TransferEncoding.Base64
                    });
                }

                for (int i = 0; i < embeddedImageFile.Count; i++)
                {
                    if (Regex.Match(embeddedImageFile[i], "(jpg|jpeg)$", RegexOptions.IgnoreCase).Success)
                    {
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Jpeg)
                        {
                            ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64
                        });
                    }
                    else if (Regex.Match(embeddedImageFile[i], "gif$", RegexOptions.IgnoreCase).Success)
                    {
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Gif)
                        {
                            ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64
                        });
                    }
                    else if (Regex.Match(embeddedImageFile[i], "tiff$", RegexOptions.IgnoreCase).Success)
                    {
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i], MediaTypeNames.Image.Tiff)
                        {
                            ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64
                        });
                    }
                    else
                    {
                        htmlView.LinkedResources.Add(new LinkedResource(embeddedImageFile[i])
                        {
                            ContentId = String.Format("img{0}", i + 1), TransferEncoding = TransferEncoding.Base64
                        });
                    }
                }

                message.AlternateViews.Add(htmlView);
            }

            // Plain/Text
            else
            {
                message.Body = template.ToString();
            }
            client.Send(message);
            message.Dispose();
        }
Esempio n. 13
0
        public override Image Draw(
            GraphDefinition graphDefinition,
            IEnumerable <PersistedCityStatisticsWithFinancialData> statistics,
            Font font,
            Size size)
        {
            using (var chartMemoryStream = new MemoryStream())
            {
                var zg = new ZedGraphControl
                {
                    Size = size,
                    Font = font
                };

                var chart = zg.GraphPane;

                foreach (var axis in new[] { chart.XAxis, chart.YAxis as Axis })
                {
                    axis.Scale.IsUseTenPower = false;
                    axis.Scale.Format        = "F0";
                }

                chart.XAxis.Title.Text = "Time";
                chart.XAxis.Type       = AxisType.LinearAsOrdinal;
                chart.YAxis.Type       = AxisType.Linear;
                chart.YAxis.Title.Text = graphDefinition.Title;

                foreach (var z in graphDefinition.GraphSeriesSet)
                {
                    var pointPairList = new PointPairList();

                    foreach (var statistic in statistics)
                    {
                        pointPairList.Add(statistic.PersistedCityStatistics.TimeCode, z.GetValue(statistic));
                    }

                    chart.AddCurve(z.Label, pointPairList, z.Color, SymbolType.None);
                }

                chart.Title.Text = graphDefinition.Title;

                if (graphDefinition.IsCurrency)
                {
                    chart.YAxis.ScaleFormatEvent += (pane, axis, val, index) =>
                    {
                        return(val.ToString("C"));
                    };
                }

                graphDefinition.DataMeter.WithResultIfHasMatch(dataMeter =>
                {
                    chart.YAxis.ScaleFormatEvent += (pane, axis, val, index) =>
                    {
                        var meter = dataMeter.Thresholds.SingleOrDefault(
                            x => x.MinMeasureUnitThreshold <= val && x.MaxMeasureUnitThreshold > val);

                        if (meter != null)
                        {
                            return(meter.Category.ToString());
                        }
                        return(string.Empty);
                    };
                });

                zg.AxisChange();

                return(zg.GetImage());
            }
        }
Esempio n. 14
0
        private void DrawSpectrum(IIdentifiedSpectrum spectrum)
        {
            if (spectrum.Annotations.ContainsKey("PepMutation"))
            {
                zgcPeaks.MasterPane.PaneList[0].Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2},MUT={3},COUNT={4}",
                                                                           spectrum.TheoreticalMH,
                                                                           PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                                           spectrum.Sequence,
                                                                           spectrum.Annotations["PepMutation"],
                                                                           (from a in spectrum.Annotations
                                                                            where a.Key.EndsWith("_PepCount")
                                                                            select Convert.ToInt32(a.Value)).Sum());
            }
            else
            {
                zgcPeaks.MasterPane.PaneList[0].Title.Text = string.Format("MH={0:0.00000},PPM={1:0.0},SEQ={2}",
                                                                           spectrum.TheoreticalMH,
                                                                           PrecursorUtils.mz2ppm(spectrum.TheoreticalMH, spectrum.TheoreticalMinusExperimentalMass),
                                                                           spectrum.Sequence);
            }

            var mass = aas.MonoPeptideMass(PeptideUtils.GetMatchedSequence(spectrum.Sequence));

            if (Math.Abs(mass - spectrum.TheoreticalMass) > 0.1)
            {
                MessageBox.Show(string.Format("Error : {0} - {1}", mass, spectrum.TheoreticalMass));
                return;
            }

            var name = string.Format("{0}_{1}", spectrum.Query.FileScan.Experimental, spectrum.Query.FileScan.FirstScan);

            var peakPane = zgcPeaks.MasterPane.PaneList[0];

            peakPane.ClearData();

            var ppmPane = zgcPeaks.MasterPane.PaneList[1];

            ppmPane.ClearData();

            if (!mgfMap.ContainsKey(name))
            {
                MessageBox.Show("Cannot find peak list {0}", name);
                return;
            }

            var mgf = mgfMap[name];

            var maxIntensity = mgf.Max(m => m.Intensity);
            var maxMz        = Math.Min(2000, mgf.Max(m => m.Mz));

            var productTolerance = productIonPPM;
            var minIntensity     = maxIntensity * 0.05;

            AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, yBuilder, spectrum.Sequence, Color.Red);
            AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, bBuilder, spectrum.Sequence, Color.Blue);

            if (spectrum.Charge > 2)
            {
                AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, y2Builder, spectrum.Sequence, Color.Brown);
                AddIonSeries(peakPane, ppmPane, mgf, productTolerance, minIntensity, b2Builder, spectrum.Sequence, Color.GreenYellow);
            }

            AddUnmatchedIons(peakPane, mgf);

            foreach (var pane in zgcPeaks.MasterPane.PaneList)
            {
                pane.XAxis.Scale.Min = 0;
                pane.XAxis.Scale.Max = maxMz;
            }
            zgcPeaks.UpdateGraph();

            var targetpngfile = GetTargetFile(targetDir, spectrum);

            zgcPeaks.GetImage().Save(targetpngfile, ImageFormat.Png);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates an image of a barchart which represents the data in <paramref name="barChartData"/>.  The image is saved at <paramref name="completeFileName"/>.
        /// </summary>
        /// <param name="completeFileName">The path at which to save the generated image.</param>
        /// <param name="barChartData">The &lt;year, value&gt; plots for the barchart.</param>
        /// <returns>True on success, false on fail.</returns>
        private bool CreateBarChartImageFile(string completeFileName, SortedDictionary <int, double> barChartData)
        {
            if (Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
            {
                return(this.InvokeCreateBarChartImageFile(completeFileName, barChartData));
            }

            try
            {
                const string fontFamily = "Times New Roman";
                const float  fontSize   = 12f;


                ZedGraphControl chart = new ZedGraphControl();
                chart.Size = new Size((barChartData.Count + 2) * 45, 300);

                GraphPane pane = chart.GraphPane;
                pane.IsFontsScaled = false;

                pane.BarSettings.Type = BarType.Stack;
                pane.Chart.Fill       = new Fill(Color.Transparent);
                pane.Fill             = new Fill(Color.LightBlue, Color.AliceBlue, 90F);

                pane.Title.FontSpec.Family = fontFamily;
                pane.Title.FontSpec.Size   = fontSize;
                pane.Title.IsVisible       = false;
                pane.Title.Text            = string.Empty;

                pane.XAxis.MajorGrid.IsVisible = false;

                pane.XAxis.MajorTic.IsInside = false;

                pane.XAxis.Scale.FontSpec.Family = fontFamily;
                pane.XAxis.Scale.FontSpec.Size   = fontSize;

                pane.XAxis.Title.FontSpec.Family = fontFamily;
                pane.XAxis.Title.FontSpec.Size   = fontSize;
                pane.XAxis.Title.IsVisible       = false;
                pane.XAxis.Title.Text            = string.Empty;

                pane.X2Axis.IsVisible           = false;
                pane.X2Axis.MajorGrid.IsVisible = false;
                pane.X2Axis.MinorGrid.IsVisible = false;
                pane.X2Axis.MajorTic.IsInside   = false;
                pane.X2Axis.MajorTic.IsOutside  = false;
                pane.X2Axis.MinorTic.IsInside   = false;
                pane.X2Axis.MinorTic.IsOutside  = false;

                pane.YAxis.MajorGrid.IsVisible = true;
                pane.YAxis.MajorGrid.Color     = Color.LightSteelBlue;


                pane.YAxis.MajorTic.IsInside = false;

                pane.YAxis.MinorTic.IsInside  = false;
                pane.YAxis.MinorTic.IsOutside = false;


                pane.YAxis.Scale.FontSpec.Family = fontFamily;
                pane.YAxis.Scale.FontSpec.Size   = fontSize;

                pane.YAxis.Title.FontSpec.Family = fontFamily;
                pane.YAxis.Title.FontSpec.Size   = fontSize;
                pane.YAxis.Title.IsVisible       = false;
                pane.YAxis.Title.Text            = string.Empty;


                pane.Y2Axis.IsVisible           = false;
                pane.Y2Axis.MajorGrid.IsVisible = false;
                pane.Y2Axis.MinorGrid.IsVisible = false;
                pane.Y2Axis.MajorTic.IsInside   = false;
                pane.Y2Axis.MajorTic.IsOutside  = false;
                pane.Y2Axis.MinorTic.IsInside   = false;
                pane.Y2Axis.MinorTic.IsOutside  = false;

                int      idx    = 0;
                string[] labels = new string[barChartData.Count];

                PointPairList nPoints = new PointPairList();
                PointPairList pPoints = new PointPairList();
                foreach (KeyValuePair <int, double> yearValue in barChartData)
                {
                    int yr = yearValue.Key % 100;
                    labels[idx] = "'" + yr.ToString("00");

                    double value = yearValue.Value * 100;
                    if (yearValue.Value >= 0)
                    {
                        nPoints.Add(yearValue.Key, 0.0);
                        pPoints.Add(yearValue.Key, value);
                    }
                    else
                    {
                        nPoints.Add(yearValue.Key, value);
                        pPoints.Add(yearValue.Key, 0.0);
                    }

                    idx++;
                }

                pane.XAxis.Scale.TextLabels = labels;
                pane.XAxis.Type             = AxisType.Text;


                //negative values
                BarItem nBar = pane.AddBar(string.Empty, nPoints, Color.Empty);
                nBar.Bar.Fill = new Fill(Color.FromArgb(227, 99, 52), Color.FromArgb(255, 177, 126), Color.FromArgb(227, 99, 52));

                //positive values
                BarItem pBar = pane.AddBar(string.Empty, pPoints, Color.Empty);
                pBar.Bar.Fill = new Fill(Color.FromArgb(81, 148, 157), Color.FromArgb(107, 197, 222), Color.FromArgb(81, 148, 157));

                //1 - Update the chart with the series
                chart.AxisChange();

                //2 - Process the value labels for each point
                this.WriteValueLabels(pane, nBar, fontFamily, fontSize, true);
                this.WriteValueLabels(pane, pBar, fontFamily, fontSize, false);

                //3 - Update the chart again
                chart.AxisChange();

                using (Image img = chart.GetImage())
                {
                    EncoderParameters parms = new EncoderParameters(1);
                    EncoderParameter  parm  = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L);
                    parms.Param[0] = parm;

                    ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg);
                    img.Save(completeFileName, jgpEncoder, parms);
                }

                try
                {
                    chart.Dispose();
                    chart = null;
                }
                catch { }

                return(true);
            }
            catch { }

            return(false);
        }