Пример #1
0
        /// <summary>
        /// Сохранить картинку панели, указанной с помощью индекса
        /// </summary>
        /// <param name="index"></param>
        private void SavePaneImage(int index)
        {
            // ДИалог выбора имени файла создаем вручную
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.Filter = "*.png|*.png|*.jpg; *.jpeg|*.jpg;*.jpeg|*.bmp|*.bmp|Все файлы|*.*";

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                // Получием панель по ее индексу
                GraphPane pane = zedGraph.MasterPane.PaneList[index];

                // Получаем картинку, соответствующую панели
                Bitmap bmp = pane.GetImage();

                // Сохраняем картинку средствами класса Bitmap
                // Формат картинки выбирается исходя из имени выбранного файла
                if (dlg.FileName.EndsWith(".png"))
                {
                    bmp.Save(dlg.FileName, ImageFormat.Png);
                }
                else if (dlg.FileName.EndsWith(".jpg") || dlg.FileName.EndsWith(".jpeg"))
                {
                    bmp.Save(dlg.FileName, ImageFormat.Jpeg);
                }
                else if (dlg.FileName.EndsWith(".bmp"))
                {
                    bmp.Save(dlg.FileName, ImageFormat.Bmp);
                }
                else
                {
                    bmp.Save(dlg.FileName);
                }
            }
        }
Пример #2
0
        public void DrawMelFiltersBank(string fileName)
        {
            GraphPane myPane = new GraphPane(new RectangleF(0, 0, 1200, 600),
                                             "Mel Filter Bank", "X Title", "Y Title");

            Random random = new Random();

            PointPairList ppl = new PointPairList();

            double[] filterSpectrum;
            foreach (var filter in filters)
            {
                ppl.Clear();
                if (filter.IsEnabled())
                {
                    filterSpectrum = filter.GetFilterSpectrum();
                    for (int i = 0; i < 200; i++)
                    {
                        ppl.Add(i, filterSpectrum[i]);
                    }
                    Color    color   = Color.FromArgb(random.Next(0, 255), random.Next(0, 255), random.Next(0, 255));
                    LineItem myCurve = myPane.AddCurve("", ppl.Clone(), color, SymbolType.None);
                }
            }

            Bitmap bm = new Bitmap(1, 1);

            using (Graphics g = Graphics.FromImage(bm))
                myPane.AxisChange(g);

            myPane.GetImage().Save(fileName, ImageFormat.Png);
        }
Пример #3
0
        private void CreatePercentGraph(OSPCResult r)
        {
            GraphPane g = new GraphPane(GraphRect, "Distribution of % similarity", "-", "% similarity");
            SetupGraph(g);

            var lst = r.Results.SelectMany(i => new[] { 100.0 * i.SimilarityA, 100.0 * i.SimilarityB }).OrderBy(i => i).ToArray();

            var c = g.AddCurve("Similarity",
                Enumerable.Range(1, lst.Length).Select(i => (double)i).ToArray(),
                lst,
                Color.Red);
            c.Symbol.IsVisible = false;

#if SHOW_DERIVATION_2
            var derv_2 = lst.CalcDerv2();
            c = g.AddCurve("Derivation 2",
                Enumerable.Range(1, derv_2.Length).Select(i => (double)i).ToArray(),
                derv_2.ToArray(),
                Color.Green);
            c.IsY2Axis = true;
            c.Symbol.IsVisible = false;
#endif

            AddLine(g, 100.0 * r.AVG_Similarity, Color.Blue, "Avg");
            AddLine(g, 100.0 * r.POI_Similarity, Color.Green, "POI");

            g.AxisChange();
            using (var img = g.GetImage(512, 256, 72.0f))
            {
                img.Save(Path.Combine(OutPath, "PercentGraph.png"), ImageFormat.Png);
            }
        }
Пример #4
0
        private void CreateTokenMatchGraph(OSPCResult r)
        {
            GraphPane g = new GraphPane(GraphRect, "Distribution of token / match", "-", "Token / match");
            SetupGraph(g);

            var lst = r.Results.Select(i => (double)i.TokenCount / (double)i.MatchCount).OrderBy(i => i).ToArray();

            var c = g.AddCurve("Token / match",
                Enumerable.Range(1, lst.Length).Select(i => (double)i).ToArray(),
                lst,
                Color.Red);
            c.Symbol.IsVisible = false;

#if SHOW_DERIVATION_2
            var derv_2 = lst.CalcDerv2();
            c = g.AddCurve("Derivation 2",
                Enumerable.Range(1, derv_2.Length).Select(i => (double)i).ToArray(),
                derv_2.ToArray(),
                Color.Green);
            c.IsY2Axis = true;
            c.Symbol.IsVisible = false;
#endif

            AddLine(g, r.AVG_TokenPerMatch, Color.Blue, "Avg");
            AddLine(g, r.POI_TokenPerMatch, Color.Green, "POI");

            g.AxisChange();
            using (var img = g.GetImage())
            {
                img.Save(Path.Combine(OutPath, "TokenMatchGraph.png"), ImageFormat.Png);
            }
        }
        //-------------------------------------------------------------------------------------------------------
        //Получить изображение
        public System.Drawing.Bitmap GetBitmap(int width, int height, float dpi)
        {
            GraphPane graphPane = this.zedGraphControl.GraphPane;

            System.Drawing.Bitmap bitmap = graphPane.GetImage(width, height, dpi);
            return(bitmap);
        }
Пример #6
0
        public Bitmap GenerateCurveImage(Size size)
        {
            GraphPane pane   = new GraphPane(new RectangleF(0, 0, size.Width, size.Height), string.Empty, string.Empty, string.Empty);
            Bitmap    result = new Bitmap(size.Width, size.Height);

            pane.AddCurve(string.Empty, Points, ActiveCurveGridColor);
            pane.XAxis.Scale.Min  = 0;
            pane.XAxis.Scale.Max  = 100;
            pane.YAxis.Scale.Min  = 0;
            pane.YAxis.Scale.Max  = 100;
            pane.XAxis.IsVisible  = false;
            pane.YAxis.IsVisible  = false;
            pane.Legend.IsVisible = false;
            pane.Title.IsVisible  = false;

            pane.Chart.Fill = new Fill(SystemColors.Control);
            pane.Border     = new Border(SystemColors.Control, 0);

            using (Graphics g = Graphics.FromImage(result)) {
                pane.AxisChange(g);
                result = pane.GetImage(true);
            }

            return(result);
        }
Пример #7
0
        public static string SaveDataToPng(double[] data, int id)
        {
            ZedGraphControl zedGraphControl1 = new ZedGraphControl();
            GraphPane       paneA            = new GraphPane();
            PointPairList   listA            = new PointPairList();

            paneA.Title.IsVisible = false;
            paneA.XAxis.IsVisible = false;
            paneA.YAxis.IsVisible = false;
            if (id != 0)
            {
                paneA.XAxis.Scale.Max = 300000;
            }
            else
            {
                paneA.XAxis.Scale.Max = 550000;
            }

            for (int i = 0; i < data.Length; i++)
            {
                listA.Add(i, data[i]);
            }
            LineItem myCurveA = paneA.AddCurve("", listA, Color.Blue, SymbolType.None);

            using (Graphics g = zedGraphControl1.CreateGraphics())
            {
                paneA.AxisChange(g);
                paneA.ReSize(g, new RectangleF(0, 0, 1800, 300));
            }

            string url      = @"D:\\PipeWeb\\AdImages\\";
            string filename = DateTime.Now.ToString("yyyy-MM-dd") + "--" + DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "-" + DateTime.Now.Second.ToString() + "--" + id.ToString();//以日期时间命名,避免文件名重复
            string strName  = url + filename + ".png";

            if (!Directory.Exists(url))         //如果不存在就创建file文件夹                 
            {
                Directory.CreateDirectory(url); //创建该文件夹 
                paneA.GetImage().Save(strName, ImageFormat.Png);
            }
            else
            {
                paneA.GetImage().Save(strName, ImageFormat.Png);
            }
            zedGraphControl1.Dispose();

            return(strName);
        }
        public byte[] HelloWorld(Straight firstStraight, Straight secondStraight)
        {
            // Получим панель для рисования
            GraphPane pane = new GraphPane();

            // Очистим список кривых на тот случай, если до этого сигналы уже были нарисованы
            pane.CurveList.Clear();

            PointPair firstPoint  = new PointPair(firstStraight.FirstPoint.X, firstStraight.FirstPoint.Y);
            PointPair secondPoint = new PointPair(firstStraight.SecondPoint.X, firstStraight.SecondPoint.Y);

            // Создадим список точек
            PointPairList list = new PointPairList()
            {
                firstPoint, secondPoint
            };

            string firstPointString  = "[" + firstStraight.FirstPoint.X + ":" + firstStraight.FirstPoint.Y + "]";
            string secondPointString = "[" + firstStraight.SecondPoint.X + ":" + firstStraight.SecondPoint.Y + "]";

            string straightName = firstPointString + ", " + secondPointString;

            pane.AddCurve(straightName, list, Color.Blue, SymbolType.None);

            //--------------------------Second straight----------------------------------

            firstPoint  = new PointPair(secondStraight.FirstPoint.X, secondStraight.FirstPoint.Y);
            secondPoint = new PointPair(secondStraight.SecondPoint.X, secondStraight.SecondPoint.Y);

            list = new PointPairList()
            {
                firstPoint, secondPoint
            };

            // Создадим кривую с названием "Sinc",
            // которая будет рисоваться голубым цветом (Color.Blue),
            // Опорные точки выделяться не будут (SymbolType.None)
            firstPointString  = "[" + secondStraight.FirstPoint.X + ":" + secondStraight.FirstPoint.Y + "]";
            secondPointString = "[" + secondStraight.SecondPoint.X + ":" + secondStraight.SecondPoint.Y + "]";

            straightName = firstPointString + ", " + secondPointString;

            pane.AddCurve(straightName, list, Color.Blue, SymbolType.None);


            // Вызываем метод AxisChange (), чтобы обновить данные об осях.
            // В противном случае на рисунке будет показана только часть графика,
            // которая умещается в интервалы по осям, установленные по умолчанию
            pane.AxisChange();

            // Обновляем график
            Bitmap bmp = pane.GetImage();

            var imageBytes = (byte[])new ImageConverter().ConvertTo(bmp, typeof(byte[]));

            //bmp.Save("D:\\testingbmp.png");

            return(imageBytes);
        }
Пример #9
0
        public static void SaveEquityCurve(
            SymbolInformation symbol,
            EvaluationResult result,
            string folderName)
        {
            var pane = new GraphPane();

            pane.Title.Text           = $"Equity Curve";
            pane.Title.FontSpec.Size  = 8;
            pane.Chart.Fill.IsScaled  = false;
            pane.Chart.Fill.Brush     = new SolidBrush(Color.DimGray);
            pane.Fill.Brush           = new SolidBrush(Color.DimGray);
            pane.Legend.Fill.Brush    = new SolidBrush(Color.DimGray);
            pane.Legend.FontSpec.Size = 6;

            var curve = pane.AddCurve("% Gain", new double[] { }, new double[] { }, LineColors[0], SymbolType.None);

            curve.Line.Width       = 2;
            curve.Line.IsVisible   = true;
            curve.Line.IsAntiAlias = true;

            foreach (var(day, equity) in result.EquityCurve)
            {
                curve.AddPoint(new XDate(day), equity);
            }

            pane.XAxis.Type = AxisType.Date;
            pane.XAxis.Scale.FontSpec.Size = 6;
            pane.XAxis.MinorGrid.IsVisible = true;
            pane.XAxis.MajorGrid.IsVisible = true;

            pane.YAxis.Scale.FontSpec.Size = 6;
            pane.YAxis.MinorGrid.IsVisible = true;
            pane.YAxis.MajorGrid.IsVisible = true;

            // force an axischange to plot all data and recalculate all axis
            // this is normally done by the control, but this is not possible in mvc3
            var bm = new Bitmap(1, 1);

            using (var g = Graphics.FromImage(bm))
            {
                pane.ReSize(g, new RectangleF(0, 0, 1280 * 5, 960 * 5));
                pane.AxisChange(g);
            }

            // create a stream to store a PNG-format image
            var actualFolder = Path.Combine(folderName, symbol.ISIN);

            Directory.CreateDirectory(actualFolder);
            var image = pane.GetImage(true);

            image.Save(
                Path.Combine(
                    actualFolder,
                    $"EquityCurve.png"),
                ImageFormat.Png);
        }
Пример #10
0
        public Bitmap GetImage()
        {
            MemoryStream graphstream = new MemoryStream();

            m_cMyPane.GetImage().Save(graphstream, ImageFormat.Bmp);
            Bitmap graphmap = new Bitmap(graphstream);

            return(graphmap);
        }
Пример #11
0
 /// <summary>
 /// Basic constructor that saves a reference to the parent
 /// <see cref="GraphPane"/> object.
 /// </summary>
 /// <param name="pane">The parent <see cref="GraphPane"/> object.</param>
 /// <param name="initialize">A <see cref="bool"/> flag to indicate whether or
 /// not the drawing variables should be initialized.  Initialization is not
 /// required if this is part of a Example internal draw operation (i.e., its in
 /// the middle of a call to <see cref="GraphPane.Draw"/>).  Otherwise, you should
 /// initialize to make sure the drawing variables are configured.  true to do
 /// an initialization, false otherwise.</param>
 public ValueHandler(GraphPane pane, bool initialize)
 {
     _pane = pane;
     if (initialize)
     {
         // just create a dummy image, which results in a full draw operation
         using (Image image = pane.GetImage())
         {
         }
     }
 }
Пример #12
0
        public Bitmap GetImage(int width, int height, float dpi, bool isAntiAlias, bool init = true)
        {
            if (init)
            {
                ConfigPane();
                DrawPane();
            }
            myPane.AxisChange();

            return(myPane.GetImage(width, height, dpi, isAntiAlias));
        }
Пример #13
0
        private void сохранитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Bitmap         bmp = pane.GetImage();
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.DefaultExt = "png";
            sfd.Filter     = "Image files (*.bmp)|*.bmp|All files (*.*)|*.*";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                bmp.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Пример #14
0
        }   //  end SetSize

        private void CreateScatterGraph(ZedGraphControl zgc)
        {
            //  get a references to the GraphPane
            GraphPane currPane = zgc.GraphPane;

            currPane.CurveList.Clear();
            //  Set the titles
            currPane.Title.Text       = currTitle;
            currPane.XAxis.Title.Text = currXtitle;
            currPane.YAxis.Title.Text = currYtitle;

            //  add data for the graph
            PointPairList DBHlist = new PointPairList();

            DBHlist.Clear();
            foreach (TreeDO td in treeList)
            {
                DBHlist.Add(td.DBH, td.TotalHeight);
            }   //  end foreach loop

            //  add the curve
            LineItem scatterCurve = currPane.AddCurve("DBH", DBHlist, Color.Black, SymbolType.Diamond);

            //hide the line to make a scatter graph
            scatterCurve.Line.IsVisible = false;
            //  hide the symbol outline
            scatterCurve.Symbol.Border.IsVisible = false;
            //  fill symbol interior with color
            scatterCurve.Symbol.Fill = new Fill(Color.MediumBlue);
            //  fill the background of the chart rect and pane
            currPane.Chart.Fill       = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f);
            currPane.Fill             = new Fill(Color.White, Color.SlateGray, 45.0f);
            currPane.Legend.IsVisible = false;

            //  refigure axes sunce the data have changed
            zgc.AxisChange();

            //  save graph
            Size   newSize    = new Size(337, 320);
            Bitmap currBMP    = new Bitmap(currPane.GetImage(), newSize);
            string outputFile = System.IO.Path.GetDirectoryName(fileName);

            outputFile += "\\Graphs\\";
            outputFile += currSaleName;
            System.IO.Directory.CreateDirectory(outputFile);
            outputFile += "\\";
            outputFile += "GR01";
            outputFile += "_";
            outputFile += currSP;
            outputFile += ".jpg";
            currBMP.Save(@outputFile, System.Drawing.Imaging.ImageFormat.Jpeg);
        }   //  end CreateScatterGraph
Пример #15
0
        private void button1_Click(object sender, EventArgs e)
        {
            Image img = gyroPane.GetImage();

            SaveFileDialog sfd = new SaveFileDialog();

            sfd.FileName         = "NinjaScanLite_ACC";
            sfd.InitialDirectory = System.IO.Directory.GetCurrentDirectory();
            sfd.Filter           = "PNG file(*.png)|*.png";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                img.Save(sfd.FileName, System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Пример #16
0
        public void WriteChart(string folder, string strategyName, string chartName, TradeStats stats, TransactionPairs daily)
        {
            if (daily.Count == 0)
            {
                return;
            }
            GraphPane myPane = new GraphPane(new RectangleF(0, 0, 640, 480),
                                             chartName, "Date", "Price");

            PointPairList ppl = new PointPairList();
            double        y   = stats.BeginningBalance;

            ppl.Add(daily[0].EntryTime.ToOADate(), y);
            for (int i = 0; i < daily.Count; i++)
            {
                y += daily.CalcProfitLoss(i);
                ppl.Add(daily[i].ExitTime.ToOADate(), y);
            }

            if (trace)
            {
                log.Trace("Chart start = " + ppl[0].Y + ", end = " + ppl[ppl.Count - 1].Y);
            }

            LineItem myCurve = myPane.AddCurve("Profit/Loss Equity Curve", ppl, Color.Blue, SymbolType.None);

            myCurve.Line.Fill = new Fill(Color.Blue);

            // pretty it up a little
            myPane.Chart.Fill                = new Fill(Color.White, Color.LightGoldenrodYellow, 45.0f);
            myPane.Fill                      = new Fill(Color.White);
            myPane.Border.IsVisible          = false;
            myPane.Title.FontSpec.Size       = 20.0f;
            myPane.XAxis.Type                = AxisType.DateAsOrdinal;
            myPane.XAxis.Title.FontSpec.Size = 14.0f;
            myPane.XAxis.Scale.FontSpec.Size = 14.0f;
            myPane.XAxis.Title.IsOmitMag     = true;

            myPane.YAxis.Title.FontSpec.Size = 14.0f;
            myPane.YAxis.Scale.FontSpec.Size = 14.0f;
//		    myPane.YAxis.Title.IsOmitMag = true;
            myPane.Legend.IsVisible = false;

            myPane.AxisChange();

            string pathName = folder + strategyName + @"\Images\" + chartName + ".gif";

            Directory.CreateDirectory(Path.GetDirectoryName(pathName));
            myPane.GetImage().Save(pathName, ImageFormat.Gif);
        }
Пример #17
0
        public void GetGraph()
        {
            GraphPane myPane = new GraphPane();

            myPane.CurveList.Clear();
            PointPairList list = new PointPairList();

            for (int i = 0; i < ax.Length; i++)
            {
                list.Add(ax[i], ay[i]);
            }
            myPane.AddCurve("Sinc", list, Color.Blue, SymbolType.None);
            Bitmap   bm = new Bitmap(10, 10);
            Graphics g  = Graphics.FromImage(bm);

            myPane.AxisChange(g);
            Image im = myPane.GetImage();

            im.Save($"{FileName}.png", ImageFormat.Png); // save graphic in png format
        }
Пример #18
0
        public static void DrawGpaph(PointPairList us, PointPairList sift, string name)
        {
            GraphPane myPane = new GraphPane();

            myPane.XAxis.Title.Text = "l / (r + l)";
            myPane.YAxis.Title.Text = "r / corresp";

            myPane.XAxis.Scale.Min = 0;
            myPane.XAxis.Scale.Max = 1;
            myPane.YAxis.Scale.Min = 0;
            myPane.YAxis.Scale.Max = 1;


            LineItem myCurve1 = myPane.AddCurve("us", us, Color.Red);
            LineItem myCurve2 = myPane.AddCurve("Sift", sift, Color.Blue);

            myPane.AxisChange();
            Bitmap bmp = myPane.GetImage();

            bmp.Save(name);
        }
Пример #19
0
        static int CreateTablePieChart(string fn)
        {
            GraphPane myPane = new GraphPane(new RectangleF(0, 0, 640, 480), "Flavour", "X", "Y");

            // Add some pie slices
            PieItem segment01 = myPane.AddPieSlice(15, Color.Navy, Color.White, 45f, 0.10, "Salt");
            PieItem segment02 = myPane.AddPieSlice(20, Color.DarkRed, Color.White, 45f, 0.00, "Pepper");
            PieItem segment03 = myPane.AddPieSlice(26, Color.LimeGreen, Color.White, 45f, 0.00, "Nutmeg ");

            segment03.LabelDetail.FontSpec.FontColor = Color.Red;

            // Calculate the Axis Scale Ranges
            myPane.AxisChange();

            Bitmap bm = new Bitmap(1, 1);

            using (Graphics g = Graphics.FromImage(bm))
                myPane.AxisChange(g);
            myPane.GetImage().Save(fn, ImageFormat.Png);

            return(3);
        }
Пример #20
0
        private void GenerateGraph()
        {
            // Setup the graph pane
            var pane = new GraphPane(new RectangleF(0, 0, 1024, 480), "HashPeak", "GPU engine clock (MHz)", "Hashrate (khash/s)");

            pane.Y2Axis.Title.Text = "Hardware errors";

            // Add the hashrate curve
            pane.AddCurve("Hashrate", _hashRatePoints, Color.Green, SymbolType.None);
            ((LineItem)pane.CurveList[0]).Line.Width       = 2.0F;
            ((LineItem)pane.CurveList[0]).Line.IsAntiAlias = true;

            // Add the HW errors curve
            pane.AddCurve("Hardware errors", _hwErrorPoints, Color.Red, SymbolType.None);
            ((LineItem)pane.CurveList[1]).Line.Width       = 2.0F;
            ((LineItem)pane.CurveList[1]).Line.IsAntiAlias = true;
            pane.CurveList[1].IsY2Axis = true;
            pane.Y2Axis.IsVisible      = true;

            // Setup scales
            pane.XAxis.Scale.Min  = _minGpuClock;
            pane.XAxis.Scale.Max  = _maxGpuClock;
            pane.Y2Axis.Scale.Min = 0;

            // Save as PNG
            var bitmap = new Bitmap(1, 1);

            using (var g = Graphics.FromImage(bitmap))
                pane.AxisChange(g);

            try
            {
                pane.GetImage(true).Save(string.Format(GraphFilenameFormat, _host, _gpuId, _saveMemClock, _minGpuClock, _maxGpuClock, DateTime.Now.ToString("yyyyMMdd")), ImageFormat.Png);
            }
            catch (Exception)
            {
                CH.Exit("An error occurred while saving graph to file {0}. Is the file in use?", string.Format(GraphFilenameFormat, _host, _gpuId, _saveMemClock, _minGpuClock, _maxGpuClock, DateTime.Now.ToString("yyyyMMdd")));
            }
        }
Пример #21
0
        /// <summary>
        /// Graphs an array of doubles varying between -1 and 1
        /// </summary>
        /// <param name="data">data</param>
        /// <param name="fileName">filename to save png to</param>
        /// <param name="onlyCanvas">true if no borders should be printed</param>
        public static void DrawGraph(double[] data, string fileName, bool onlyCanvas = false)
        {
            var myPane = new GraphPane(new RectangleF(0, 0, 1200, 600), "", "", "");

            if (onlyCanvas)
            {
                myPane.Chart.Border.IsVisible = false;
                myPane.Chart.Fill.IsVisible   = false;
                myPane.Fill.Color             = Color.Black;
                myPane.Margin.All             = 0;
                myPane.Title.IsVisible        = false;
                myPane.XAxis.IsVisible        = false;
                myPane.YAxis.IsVisible        = false;
            }
            myPane.XAxis.Scale.Max = data.Length - 1;
            myPane.XAxis.Scale.Min = 0;
            //myPane.YAxis.Scale.Max = 1;
            //myPane.YAxis.Scale.Min = -1;

            // add pretty stuff
            myPane.Fill       = new Fill(Color.WhiteSmoke, Color.Lavender, 0F);
            myPane.Chart.Fill = new Fill(Color.FromArgb(255, 255, 245),
                                         Color.FromArgb(255, 255, 190), 90F);

            var timeData = Enumerable.Range(0, data.Length)
                           .Select(i => (double)i)
                           .ToArray();

            myPane.AddCurve(null, timeData, data, Color.Blue, SymbolType.None);

            var bmp = new Bitmap(1, 1);

            using (Graphics g = Graphics.FromImage(bmp))
                myPane.AxisChange(g);

            myPane.GetImage().Save(fileName, ImageFormat.Png);
        }
Пример #22
0
        private void TrendCDMs()
        {
            ZedGraphAssistant.colorArray = new Color[] { Color.Red };
            PointPairList pplMD       = ZedGraphAssistant.CdmPlottableList("Miss Distance", cdmCollection);
            GraphPane     missDisPlot = ZedGraphAssistant.CreateGraph("Conjunction Trending", null, g,
                                                                      new PointPairList[] { pplMD }, new string[] { "Miss Distance" }, new TextObj[] { }, true);

            missDisPlot.YAxis.Title.Text = "Miss Distance (m)";
            missDisPlot.XAxis.Title.Text = "Creation Date (UTC)";

            zgMissDistance.GraphPane = missDisPlot;
            zgMissDistance.AxisChange();
            zgMissDistance.Invalidate();

            ZedGraphAssistant.colorArray = new Color[] { Color.Blue };
            PointPairList pplTca  = ZedGraphAssistant.CdmPlottableList("TCA", cdmCollection);
            GraphPane     tcaPlot = ZedGraphAssistant.CreateGraph("Conjunction Trending", null, g, new PointPairList[] { pplTca }, new string[] { "TCA" }, new TextObj[] { }, true);

            tcaPlot.YAxis.Type            = AxisType.Date;
            tcaPlot.YAxis.Scale.Format    = "MMM d\nHH:mm:ss.sss";
            tcaPlot.YAxis.Scale.MajorUnit = DateUnit.Minute;
            tcaPlot.YAxis.Scale.MinorUnit = DateUnit.Second;
            tcaPlot.YAxis.Scale.MinorStep = 10;
            tcaPlot.YAxis.Title.Text      = "Time of Close Approach (UTC)";
            tcaPlot.XAxis.Title.Text      = "Creation Date (UTC)";
            zgTCA.GraphPane = tcaPlot;
            zgTCA.AxisChange();
            zgTCA.Invalidate();

            ZedGraphAssistant.colorArray = new Color[] { Color.Green };
            PointPairList pplProb  = ZedGraphAssistant.CdmPlottableList("Probability", cdmCollection);
            GraphPane     probPlot = ZedGraphAssistant.CreateGraph("Conjunction Trending", null, g, new PointPairList[] { pplProb }, new string[] { "Probability" }, new TextObj[] { }, true);

            probPlot.YAxis.Title.Text = "Probability";
            probPlot.XAxis.Title.Text = "Creation Date (UTC)";
            zgProbability.GraphPane   = probPlot;
            zgProbability.AxisChange();
            zgProbability.Invalidate();

            ZedGraphAssistant.colorArray = new Color[] { Color.Orange };
            PointPairList pplSD  = ZedGraphAssistant.CdmPlottableList("Sigma Dilution", cdmCollection);
            GraphPane     sdPlot = ZedGraphAssistant.CreateGraph("Conjunction Trending", null, g, new PointPairList[] { pplSD }, new string[] { "Sigma Dilution" }, new TextObj[] { }, true);

            sdPlot.YAxis.Title.Text = "Sigma Dilution (m)";
            sdPlot.XAxis.Title.Text = "Creation Date (UTC)";
            zgSigma.GraphPane       = sdPlot;
            zgSigma.AxisChange();
            zgSigma.Invalidate();

            ZedGraphAssistant.colorArray = new Color[] { Color.Red, Color.Blue };
            GraphPane combinedPlot = ZedGraphAssistant.CreateGraph("Conjunction Trending", null, g, new PointPairList[] { pplMD }, new string[] { "Miss Distance" }, new TextObj[] { }, true);
            LineItem  y2LineTCA    = combinedPlot.AddCurve("TCA", pplTca, Color.Blue, ZedGraphAssistant.NextSymbol);

            y2LineTCA.IsY2Axis                      = true;
            y2LineTCA.Line.Width                    = 2.0f;
            y2LineTCA.Line.Style                    = System.Drawing.Drawing2D.DashStyle.Dash;
            combinedPlot.XAxis.Title.Text           = "Creation Date (UTC)";
            combinedPlot.Y2Axis.Type                = AxisType.Date;
            combinedPlot.Y2Axis.Scale.Format        = "MMM d\nHH:mm:ss.sss";
            combinedPlot.Y2Axis.Scale.MajorUnit     = DateUnit.Day;
            combinedPlot.Y2Axis.Scale.MinorUnit     = DateUnit.Minute;
            combinedPlot.Y2Axis.Scale.MinorStep     = 5;
            combinedPlot.Y2Axis.Scale.MinAuto       = true;
            combinedPlot.Y2Axis.Scale.MaxAuto       = true;
            combinedPlot.Y2Axis.Scale.FontSpec.Size = combinedPlot.YAxis.Scale.FontSpec.Size;
            combinedPlot.Y2Axis.Title.FontSpec      = combinedPlot.YAxis.Title.FontSpec;
            combinedPlot.Y2Axis.Title.Text          = "Time of Close Approach (UTC)";
            combinedPlot.Y2Axis.IsVisible           = true;
            zgCombined.GraphPane                    = combinedPlot;
            zgCombined.AxisChange();
            zgCombined.Invalidate();

            SetSize();
            string safeName  = Regex.Replace(cdmCollection[0].Primary.SatName + "and" + cdmCollection[0].Secondary.SatName, "[///(/)" + new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + " ]", "");
            string outputDir = Path.Combine(CdmReader.CdmOutputDirectory, safeName);

            if (!Directory.Exists(outputDir))
            {
                Directory.CreateDirectory(outputDir);
            }
            if (probPlot != null)
            {
                probPlot.GetImage(1280, 1024, 180).Save(Path.Combine(outputDir, "Probability.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (tcaPlot != null)
            {
                tcaPlot.GetImage(1280, 1024, 180).Save(Path.Combine(outputDir, "TCA.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (missDisPlot != null)
            {
                missDisPlot.GetImage(1280, 1024, 180).Save(Path.Combine(outputDir, "MissDistance.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (combinedPlot != null)
            {
                combinedPlot.GetImage(1280, 1024, 180).Save(Path.Combine(outputDir, "TCAandMissDistance.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (sdPlot != null)
            {
                sdPlot.GetImage(1280, 1024, 180).Save(Path.Combine(outputDir, "SigmaDilution.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Пример #23
0
        public static void genChart(ZedGraphControl ct, string productCode, string type, string title, params PointPairList[] lists)
        {
            GraphPane pane = ct.GraphPane;

            ct.IsAntiAlias                  = true;
            pane.Border.IsVisible           = false;
            pane.Title.Text                 = title;
            pane.Title.FontSpec.Family      = "宋体";
            pane.Title.FontSpec.Size        = 26;
            pane.Title.FontSpec.IsAntiAlias = true;
            pane.YAxis.Title.IsVisible      = false;
            pane.Legend.IsVisible           = true;
            pane.Legend.FontSpec.Family     = "宋体";
            pane.Legend.FontSpec.Size       = 20;


            //倾斜度
            pane.XAxis.Scale.FontSpec.Angle = 30;

            pane.XAxis.Type = AxisType.DateAsOrdinal;
            if (type.Length == 0 || (type.IndexOf('i') >= 0 && type.IndexOf('m') < 0))
            {
                pane.XAxis.Scale.Format = "yy-MM-dd";
            }
            else
            {
                pane.XAxis.Scale.Format = "yy-MM-dd";
            }

            pane.XAxis.Scale.IsReverse            = true;
            pane.XAxis.Scale.FontSpec.Family      = "宋体";
            pane.XAxis.Scale.FontSpec.IsBold      = true;
            pane.XAxis.Scale.FontSpec.IsAntiAlias = true;   //抗锯齿
            //pane.XAxis.Scale.FontSpec.IsDropShadow = true;    //看起来粗一点
            pane.XAxis.Scale.FontSpec.Size = 20;
            //在对面不显示出刻度
            pane.XAxis.MajorTic.IsOpposite = false;
            pane.XAxis.Title.IsVisible     = false;

            pane.YAxis.Scale.FontSpec.Family = "宋体";
            pane.YAxis.Scale.FontSpec.Size   = 20;
            pane.YAxis.MajorGrid.IsVisible   = true;
            pane.YAxis.MajorGrid.PenWidth    = 1;
            pane.YAxis.MajorGrid.DashOff     = 2; //虚线中孔间距
            pane.YAxis.MajorGrid.DashOn      = 2; //虚线单位长度
            pane.YAxis.MajorGrid.Color       = Color.FromArgb(201, 201, 201);
            pane.YAxis.MajorTic.IsOpposite   = false;

            //去掉小刻度
            pane.XAxis.MinorTic.IsAllTics = false;
            pane.XAxis.Scale.MajorStep    = 1;
            pane.YAxis.MinorTic.IsAllTics = false;
            try
            {
                pane.YAxis.Scale.MajorStep = Math.Floor(lists[0].Max(list => list.Y) / 20);
            }
            catch
            {
                pane.XAxis.Scale.MajorStep = 1;
            }



            int    i         = 0;
            Color  color     = Color.Red;
            string legend    = "价格指数";
            Regex  dateRegex = new Regex(@".*日价格趋势.*");
            Match  m         = dateRegex.Match(title);

            if (m.Success)
            {
                legend = "均价";
            }
            foreach (PointPairList list in lists)
            {
                if (lists.Length > 1)
                {
                    switch (i)
                    {
                    case 0: color = Color.Orange;
                        legend    = "最低价";
                        break;

                    case 1: color = Color.Red;
                        legend    = "均价";
                        break;

                    case 2: color = Color.Green;
                        legend    = "最高价";
                        break;
                    }
                }
                LineItem curve = pane.AddCurve(legend, list, color, SymbolType.Diamond);
                curve.Line.Width       = 1.5F;
                curve.Symbol.Fill      = new Fill(Color.White);
                curve.Symbol.Size      = 5;
                curve.Line.IsAntiAlias = true;

                if (i != 1 && lists.Length > 1)
                {
                    curve.Line.Style = System.Drawing.Drawing2D.DashStyle.Dot;
                }
                i++;
            }

            // Leave some extra space on top for the labels to fit within the chart rect
            //pane.YAxis.Scale.MaxGrace = 0.2;

            //pane.XAxis.Scale.BaseTic = 50;

            //pane.Chart.Fill = new Fill(Color.White, Color.SteelBlue, 45.0F);
            pane.Chart.Border.IsVisible = false;

            //pane.Chart.Border.Color = Color.Red;

            //重新计算坐标刻度
            ct.AxisChange();
            Bitmap bmp = pane.GetImage(270, 200, 1000);

            if (productCode.Equals("00"))
            {
                productCode = "";
            }

            bmp.Save(("chart/" + type + "s" + productCode + ".png").ToUpper());

            pane.GetImage(330, 200, 1000).Save(("chart/" + type + "m" + productCode + ".png").ToUpper());
            pane.GetImage(675, 200, 1000).Save(("chart/" + type + "l" + productCode + ".png").ToUpper());
        }
Пример #24
0
        private void ExecuteSingleCDMComparison()
        {
            if (conjunction == null)
            {
                return;
            }
            string safeName = Regex.Replace(conjunction.Primary.SatName + "and" + conjunction.Secondary.SatName + "_" + conjunction.ID, "[///(/)" + new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars()) + " ]", "");

            conjunction.GenerateStkCdmObjects();
            string conjunctionIdFileName = safeName;//Regex.Replace(conjunction.ID,"[///(/)" + new string(Path.GetInvalidFileNameChars())+ new string(Path.GetInvalidPathChars()) + " ]", "");

            dirPath = Path.Combine(CdmReader.CdmOutputDirectory, conjunctionIdFileName);
            DirectoryInfo dir = Directory.CreateDirectory(dirPath);

            ZedGraphAssistant.colorArray = null;
            GraphPane conjunctionGraph = conjunction.GraphConjunction(g);
            GraphPane primaryGraph     = conjunction.Primary.GraphSatelliteStateComparison(g);
            GraphPane secondaryGraph   = conjunction.Secondary.GraphSatelliteStateComparison(g);

            if (conjunctionGraph != null)
            {
                //conjunctionGraph.ReSize(g, zConjunction.GraphPane.Rect);
                zConjunction.GraphPane = conjunctionGraph;
                zConjunction.AxisChange();
                zConjunction.Invalidate();
            }

            if (primaryGraph != null)
            {
                //primaryGraph.ReSize(g, zPrimary.GraphPane.Rect);
                zPrimary.GraphPane = primaryGraph;
                zPrimary.AxisChange();
                zPrimary.Invalidate();
            }

            if (secondaryGraph != null)
            {
                //secondaryGraph.ReSize(g, zSecondary.GraphPane.Rect);
                zSecondary.GraphPane = secondaryGraph;
                zSecondary.AxisChange();
                zSecondary.Invalidate();
            }

            SetSize();

            if (conjunctionGraph != null)
            {
                conjunctionGraph.GetImage(1280, 1024, 180).Save(Path.Combine(dirPath, "Conjunction.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (primaryGraph != null)
            {
                primaryGraph.GetImage(1280, 1024, 180).Save(Path.Combine(dirPath, "Primary.png"), System.Drawing.Imaging.ImageFormat.Png);
            }
            if (secondaryGraph != null)
            {
                secondaryGraph.GetImage(1280, 1024, 180).Save(Path.Combine(dirPath, "Secondary.png"), System.Drawing.Imaging.ImageFormat.Png);
            }


            string summary = "Conjunction for " + conjunction.Primary.SSC + "/" + conjunction.Primary.SatName + "[+] and "
                             + conjunction.Secondary.SSC + "/" + conjunction.Secondary.SatName + "[-]";

            summary += Environment.NewLine;
            summary += Environment.NewLine + "CDM Summary";
            summary += Environment.NewLine + "Created       : " + conjunction.CreationDate;
            summary += Environment.NewLine + "TCA           : " + conjunction.TCA;
            summary += Environment.NewLine + "TCA Range (m) : " + conjunction.MissDistance;

            summary += Environment.NewLine;
            summary += Environment.NewLine + "STK Validation of CDM";
            summary += Environment.NewLine + "STK Range at CDM TCA (m) : " + conjunction.StkRangeAtCdmTca;
            summary += Environment.NewLine + "STK TCA                  : " + conjunction.StkTimeOfMinRange;
            summary += Environment.NewLine + "STK Min Range (m)        : " + conjunction.MissDistance;

            string[] conjunctionToSecondariesSummary = conjunction.SummaryOfConjunctionsFromSecondaryStates();

            if (conjunctionToSecondariesSummary.Length > 0)
            {
                summary += Environment.NewLine + Environment.NewLine + "Conjunction Comparisons :";
                foreach (string item in conjunctionToSecondariesSummary)
                {
                    summary += Environment.NewLine + item;
                }
            }
            txtCdmResults.Text = summary;
            File.WriteAllText(Path.Combine(dirPath, "CdmSummary.txt"), summary);
        }
Пример #25
0
        void PictureLoad()
        {
            try
            {
                if (comboBox1.Text == "View all readings in a selected date")
                {
                    double Systolic = 0.0, Diastolic = 0.0;
                    string CTime = "";

                    myPane.Title.Text            = "All Readings\n   (" + calendar1.SelectedDate.ToShortDateString() + ")";
                    myPane.XAxis.Title.Text      = "Time(Hours)";
                    myPane.YAxis.Title.Text      = "Pressure Readings";
                    myPane.XAxis.Type            = ZedGraph.AxisType.Date;
                    myPane.XAxis.Scale.Format    = @"h tt";
                    myPane.XAxis.Scale.MajorUnit = DateUnit.Hour;
                    myPane.XAxis.Scale.MajorStep = 1.0;
                    myPane.XAxis.Scale.MinorUnit = DateUnit.Minute;
                    myPane.XAxis.Scale.MinorStep = 4.0;
                    myPane.YAxis.Scale.Min       = 0;
                    myPane.YAxis.Scale.Max       = 250.0;
                    myPane.XAxis.Scale.Min       = new XDate(calendar1.SelectedDate.Year, calendar1.SelectedDate.Month, calendar1.SelectedDate.Day, 0, 0, 0);
                    myPane.XAxis.Scale.Max       = new XDate(calendar1.SelectedDate.Year, calendar1.SelectedDate.Month, calendar1.SelectedDate.Day, 23, 0, 0);
                    zedGraphControl1.AxisChange();
                    zedGraphControl1.Invalidate();

                    string          source = "SELECT * from Record where [PatientID] = '" + MainForm.patientID + "' and [CDate] = #" + calendar1.SelectedDate + "#";
                    OleDbConnection cn     = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Patient\'s Record.accdb");
                    cn.Open();
                    OleDbCommand    cmd    = new OleDbCommand(source, cn);
                    OleDbDataReader reader = cmd.ExecuteReader();

                    PointPairList list1 = new PointPairList();
                    PointPairList list2 = new PointPairList();

                    while (reader.Read())
                    {
                        Systolic  = Convert.ToDouble(reader.GetValue(1).ToString());
                        Diastolic = Convert.ToDouble(reader.GetValue(2).ToString());
                        CTime     = reader.GetValue(4).ToString();
                        list1.Add(new XDate(DateTime.Parse(calendar1.SelectedDate.ToShortDateString() + " " + CTime)), Systolic);
                        list2.Add(new XDate(DateTime.Parse(calendar1.SelectedDate.ToShortDateString() + " " + CTime)), Diastolic);
                    }

                    LineItem myCurve;

                    myCurve = myPane.AddCurve("Systolic", list1, Color.Red, SymbolType.Circle);
                    myCurve = myPane.AddCurve("Diastolic", list2, Color.Blue, SymbolType.Circle);
                    myPane.GetImage(462, 220, 10000, true);
                    myPane.GetImage().Save("C:\\graph.png");
                    myPane.CurveList.Clear();

                    reader.Close();
                    cn.Close();
                }

                else if (comboBox1.Text == "Average Per Hour")
                {
                    myPane.Title.Text                        = "Average Per Hour";
                    myPane.XAxis.Title.Text                  = "Time(Hour)";
                    myPane.YAxis.Title.Text                  = "Pressure Readings";
                    myPane.XAxis.Type                        = ZedGraph.AxisType.Date;
                    myPane.XAxis.Scale.Format                = @"h tt";
                    myPane.XAxis.Scale.MajorUnit             = DateUnit.Hour;
                    myPane.XAxis.Scale.MajorStep             = 1.0;
                    myPane.XAxis.Scale.IsSkipCrossLabel      = false;
                    myPane.XAxis.Scale.IsPreventLabelOverlap = true;
                    myPane.XAxis.Scale.Min                   = new XDate(calendar1.SelectedDate.Year, calendar1.SelectedDate.Month, calendar1.SelectedDate.Day, 0, 0, 0);
                    myPane.XAxis.Scale.Max                   = new XDate(calendar1.SelectedDate.Year, calendar1.SelectedDate.Month, calendar1.SelectedDate.Day, 23, 0, 0);
                    myPane.YAxis.Scale.Min                   = 0;
                    myPane.YAxis.Scale.Max                   = 250.0;
                    zedGraphControl1.AxisChange();
                    zedGraphControl1.Invalidate();

                    PointPairList list1 = new PointPairList();
                    PointPairList list2 = new PointPairList();


                    string          source = source = "SELECT Sys, Dias, Hour From HourTable Where PatientID ='" + MainForm.patientID + "' and CDate = #" + calendar1.SelectedDate + "#";
                    OleDbConnection cn     = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + "C:\\Patient\'s Record.accdb");
                    cn.Open();
                    OleDbCommand    cmd    = new OleDbCommand(source, cn);
                    OleDbDataReader reader = cmd.ExecuteReader();


                    while (reader.Read())
                    {
                        list1.Add(new XDate(DateTime.Parse(calendar1.SelectedDate.ToShortDateString() + " " + reader.GetValue(2).ToString()).ToOADate()), Convert.ToDouble(reader.GetValue(0).ToString()));
                        list2.Add(new XDate(DateTime.Parse(calendar1.SelectedDate.ToShortDateString() + " " + reader.GetValue(2).ToString()).ToOADate()), Convert.ToDouble(reader.GetValue(1).ToString()));
                    }
                    LineItem myCurve;

                    myCurve = myPane.AddCurve("Systolic", list1, Color.Red, SymbolType.Circle);
                    myCurve = myPane.AddCurve("Diastolic", list2, Color.Blue, SymbolType.Circle);
                    myPane.GetImage(462, 220, 10000, true);
                    myPane.GetImage().Save("C:\\graph.png");
                    myPane.CurveList.Clear();


                    reader.Close();
                    cn.Close();
                }
                else if (comboBox1.Text == "Average Per Month")
                {
                    string          source = "SELECT Sys, Dias, Month, Year, Stat From MonthTable Where PatientID ='" + MainForm.patientID + "' and Year = " + calendar1.SelectedDate.Year;
                    OleDbConnection cn     = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\\Patient\'s Record.accdb");
                    cn.Open();
                    OleDbCommand    cmd    = new OleDbCommand(source, cn);
                    OleDbDataReader reader = cmd.ExecuteReader();

                    myPane.Title.Text            = "Average Per Month\n    (" + calendar1.SelectedDate.Year.ToString() + ")";
                    myPane.XAxis.Title.Text      = "Time(Month)";
                    myPane.YAxis.Title.Text      = "Pressure Readings";
                    myPane.XAxis.Type            = ZedGraph.AxisType.Date;
                    myPane.XAxis.Scale.Format    = @"MM";
                    myPane.XAxis.Scale.MajorUnit = DateUnit.Month;
                    myPane.XAxis.Scale.MajorStep = 1.0;
                    myPane.YAxis.Scale.Min       = 0;
                    myPane.YAxis.Scale.Max       = 250.0;
                    myPane.XAxis.Scale.Min       = new XDate(calendar1.SelectedDate.Year, 1, 1);
                    myPane.XAxis.Scale.Max       = new XDate(calendar1.SelectedDate.Year, 12, 1);
                    zedGraphControl1.AxisChange();
                    zedGraphControl1.Invalidate();


                    PointPairList list1 = new PointPairList();
                    PointPairList list2 = new PointPairList();

                    while (reader.Read())
                    {
                        list1.Add(new XDate(reader.GetInt16(3), DateTime.Parse("1." + reader.GetString(2) + "2011").Month, 1), reader.GetDouble(0));//DateTime.ParseExact(reader.GetString(2), "MM", CultureInfo.CurrentCulture).Month
                        list2.Add(new XDate(reader.GetInt16(3), DateTime.Parse("1." + reader.GetString(2) + "2011").Month, 1), reader.GetDouble(1));
                    }

                    LineItem myCurve;

                    myCurve = myPane.AddCurve("Systolic", list1, Color.Red, SymbolType.Circle);
                    myCurve = myPane.AddCurve("Diastolic", list2, Color.Blue, SymbolType.Circle);
                    myPane.GetImage(462, 220, 10000, true);
                    myPane.GetImage().Save("C:\\graph.png");
                    myPane.CurveList.Clear();
                }
                else if (comboBox1.Text == "Average Per Year")
                {
                    myPane.Title.Text            = "Average Per Year\n   (" + calendar1.year1 + "-" + calendar1.year12 + ")";
                    myPane.XAxis.Title.Text      = "Time(Year)";
                    myPane.YAxis.Title.Text      = "Pressure Readings";
                    myPane.XAxis.Type            = ZedGraph.AxisType.Date;
                    myPane.XAxis.Scale.Format    = @"yyyy";
                    myPane.XAxis.Scale.MajorUnit = DateUnit.Year;
                    myPane.XAxis.Scale.MajorStep = 1.0;
                    myPane.XAxis.Scale.MinorUnit = DateUnit.Year;
                    myPane.XAxis.Scale.MajorStep = 1.0;
                    myPane.YAxis.Scale.Min       = 0;
                    myPane.YAxis.Scale.Max       = 250.0;
                    myPane.XAxis.Scale.Min       = new XDate(calendar1.year1, 1, 1);
                    myPane.XAxis.Scale.Max       = new XDate(calendar1.year12, 12, 1);
                    zedGraphControl1.AxisChange();
                    zedGraphControl1.Invalidate();

                    string          source = "SELECT Sys, Dias, Year, Stat From YearTable Where PatientID ='" + MainForm.patientID + "' and Year BETWEEN " + calendar1.year1 + " and " + calendar1.year12;
                    OleDbConnection cn     = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " + "C:\\Patient\'s Record.accdb");
                    cn.Open();
                    OleDbCommand    cmd    = new OleDbCommand(source, cn);
                    OleDbDataReader reader = cmd.ExecuteReader();


                    PointPairList list1 = new PointPairList();
                    PointPairList list2 = new PointPairList();

                    while (reader.Read())
                    {
                        list1.Add(new XDate(reader.GetInt16(2), 1, 1), reader.GetDouble(0));
                        list2.Add(new XDate(reader.GetInt16(2), 1, 1), reader.GetDouble(1));
                    }

                    LineItem myCurve;

                    myCurve = myPane.AddCurve("Systolic", list1, Color.Red, SymbolType.Circle);
                    myCurve = myPane.AddCurve("Diastolic", list2, Color.Blue, SymbolType.Circle);
                    myPane.GetImage(462, 220, 10000, true);
                    myPane.GetImage().Save("C:\\graph.png");
                    myPane.CurveList.Clear();
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Invalid operation has been detected!");
                Application.Exit();
            }
        }
Пример #26
0
        public static Bitmap compare_graph_bar(DateTime firstday, DateTime lastday, user[] users)
        {
            //g settings
            GraphPane testg = new GraphPane();

            testg.Title.Text = "Taux chancéïque journalier";
            testg.LineType   = LineType.Normal;

            //x axis
            testg.XAxis.Title.Text               = "Date journaïtique";
            testg.XAxis.Type                     = AxisType.Date;
            testg.XAxis.Scale.Format             = "dd-MMM-yy";
            testg.XAxis.Scale.MajorUnit          = DateUnit.Day;
            testg.XAxis.Scale.MajorStep          = 1;
            testg.XAxis.Scale.Min                = new XDate(firstday.AddDays(-1));
            testg.XAxis.Scale.Max                = new XDate(lastday.AddDays(1));
            testg.XAxis.MajorTic.IsBetweenLabels = true;
            testg.XAxis.MinorTic.Size            = 0;
            testg.XAxis.MajorTic.IsInside        = false;
            testg.XAxis.MajorTic.IsOutside       = true;
            testg.BarSettings.Type               = BarType.Cluster;

            //y axis
            testg.YAxis.Title.Text = "Pourcentage chancéïque (%)";
            testg.YAxis.Scale.Min  = 0;
            testg.YAxis.Scale.Max  = 100;

            //random color
            var xdays = new List <double>();

            foreach (var user in users)
            {
                double        moyenne = 0;
                List <double> yluck   = new List <double>();
                for (DateTime d = firstday; d <= lastday; d = d.AddDays(1))
                {
                    xdays.Add(new XDate(d));
                    yluck.Add(user.luck_at(d));
                    moyenne += user.luck_at(d);
                }
                var curve = testg.AddBar("Chance pour " + user.name, xdays.ToArray(), yluck.ToArray(), System.Drawing.Color.FromArgb(user.graph_color));
                moyenne /= yluck.Count;
                double[] listmoy = Enumerable.Repeat(moyenne, yluck.Count + 2).ToArray();

                xdays.Insert(0, new XDate(firstday.AddDays(-1)));
                xdays.Add(new XDate(lastday.AddDays(1)));
                var moy = testg.AddCurve("moyenne chancéïque", xdays.ToArray(), listmoy, System.Drawing.Color.FromArgb(user.graph_color));
                moy.Line.Width  = 1;
                moy.Symbol.Size = 0;
            }

            //enregister bitmap
            var bm = new Bitmap(1, 1);
            var g  = Graphics.FromImage(bm);

            testg.AxisChange(g);
            var bm2 = testg.GetImage(1920, 1080, 1000, true);

            bm2.Save("out.png");
            return(bm2);
        }
Пример #27
0
        public void UpdateGraph()
        {
            try
            {
                try
                {
                    DateTime startTime = DateTime.Now;

                    // Take a copy of the metrics file.
                    if (File.Exists(m_metricsFileCopyName))
                    {
                        File.Delete(m_metricsFileCopyName);
                    }

                    logger.Debug("Copying " + m_metricsFileName + " to " + m_metricsFileCopyName);
                    File.Copy(m_metricsFileName, m_metricsFileCopyName);

                    StreamReader metricsReader = new StreamReader(m_metricsFileCopyName);
                    m_totalSIPPacketsList.Clear();
                    m_sipRequestsInList.Clear();
                    m_sipResponsesInList.Clear();
                    m_sipRequestsOutList.Clear();
                    m_sipResponsesOutList.Clear();
                    m_pendingTransactionsList.Clear();
                    m_discardsList.Clear();
                    m_unrecognisedList.Clear();
                    m_tooLargeList.Clear();
                    m_badSIPList.Clear();
                    m_stunList.Clear();
                    m_totalParseTimeList.Clear();
                    m_avgParseTimeList.Clear();
                    m_sipMethodsLists = new Dictionary <SIPMethodsEnum, RollingPointPairList>();
                    m_topTalkersLists.Clear();
                    m_topTalkersCount.Clear();

                    string metricsLine = metricsReader.ReadLine();
                    int    sampleCount = 0;
                    while (metricsLine != null)
                    {
                        #region Process metrics line.

                        if (metricsLine.Trim().Length != 0 && Regex.Match(metricsLine, ",").Success)
                        {
                            string[] fields       = metricsLine.Split(',');
                            XDate    sampleDate   = new XDate(DateTime.Parse(fields[1]));
                            int      samplePeriod = Convert.ToInt32(fields[2]);         // Sample period in seconds.
                            if (samplePeriod == 0)
                            {
                                throw new ApplicationException("The sample period for a measurement was 0 in SIPTransportMetricsGraphAgent.");
                            }

                            if (metricsLine.StartsWith(m_trafficMetrics))
                            {
                                try
                                {
                                    m_totalSIPPacketsList.Add(sampleDate, Convert.ToDouble(fields[3]) / samplePeriod);
                                    m_sipRequestsInList.Add(sampleDate, Convert.ToDouble(fields[4]) / samplePeriod);
                                    m_sipResponsesInList.Add(sampleDate, Convert.ToDouble(fields[5]) / samplePeriod);
                                    m_sipRequestsOutList.Add(sampleDate, Convert.ToDouble(fields[6]) / samplePeriod);
                                    m_sipResponsesOutList.Add(sampleDate, Convert.ToDouble(fields[7]) / samplePeriod);
                                    m_pendingTransactionsList.Add(sampleDate, Convert.ToDouble(fields[8]));
                                    m_unrecognisedList.Add(sampleDate, Convert.ToDouble(fields[9]) / samplePeriod);
                                    m_badSIPList.Add(sampleDate, Convert.ToDouble(fields[10]) / samplePeriod);
                                    m_stunList.Add(sampleDate, Convert.ToDouble(fields[11]) / samplePeriod);
                                    m_discardsList.Add(sampleDate, Convert.ToDouble(fields[12]) / samplePeriod);
                                    m_tooLargeList.Add(sampleDate, Convert.ToDouble(fields[13]) / samplePeriod);
                                    m_totalParseTimeList.Add(sampleDate, Convert.ToDouble(fields[14]) / samplePeriod);
                                    m_avgParseTimeList.Add(sampleDate, Convert.ToDouble(fields[15]));
                                    sampleCount++;
                                }
                                catch (Exception sampleExcp)
                                {
                                    logger.Warn("Could not process metrics sample: " + metricsLine + ". " + sampleExcp.Message);
                                }
                            }
                            else if (metricsLine.StartsWith(m_methodMetrics))
                            {
                                for (int index = 3; index < fields.Length; index++)
                                {
                                    string[]       methodSplit   = fields[index].Split('=');
                                    SIPMethodsEnum method        = SIPMethods.GetMethod(methodSplit[0]);
                                    int            methodPackets = Convert.ToInt32(methodSplit[1]) / samplePeriod;

                                    if (!m_sipMethodsLists.ContainsKey(method))
                                    {
                                        m_sipMethodsLists.Add(method, new RollingPointPairList(GRAPH_SAMPLES));
                                    }

                                    m_sipMethodsLists[method].Add(sampleDate, methodPackets);
                                }
                            }
                            else if (metricsLine.StartsWith(m_topTalkerMetrics))
                            {
                                for (int index = 3; index < fields.Length; index++)
                                {
                                    string[] talkersSplit     = fields[index].Split('=');
                                    string   topTalkerSocket  = talkersSplit[0];
                                    int      topTalkerPackets = Convert.ToInt32(talkersSplit[1]) / samplePeriod;

                                    if (!m_topTalkersLists.ContainsKey(topTalkerSocket))
                                    {
                                        m_topTalkersLists.Add(topTalkerSocket, new RollingPointPairList(GRAPH_SAMPLES));
                                        m_topTalkersCount.Add(topTalkerSocket, 0);
                                    }

                                    //logger.Debug("Adding point for " + topTalkerSocket + " and " + topTalkerPackets + ".");
                                    m_topTalkersLists[topTalkerSocket].Add(sampleDate, topTalkerPackets);
                                    m_topTalkersCount[topTalkerSocket] = m_topTalkersCount[topTalkerSocket] + topTalkerPackets;
                                }
                            }
                        }

                        #endregion

                        metricsLine = metricsReader.ReadLine();
                    }
                    metricsReader.Close();

                    #region Create the traffic graphs.

                    GraphPane totalSIPPacketsGraphPane        = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Total SIP Packets per Second", "Time", "Packets/s");
                    GraphPane pendingSIPTransactionsGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Pending SIP Transactions", "Time", "Total");
                    GraphPane breakdownGraphPane         = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Request and Responses per Second", "Time", "Packets/s");
                    GraphPane anomaliesGraphPane         = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Anomalous Packets per Second", "Time", "Packets/s");
                    GraphPane totalParseTimesGraphPane   = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Packet Parse Time per Second", "Time", "Total Parse Tme (ms)/s");
                    GraphPane averageParseTimesGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "Average SIP Packet Parse Time", "Time", "Average Parse Tme (ms)");

                    totalSIPPacketsGraphPane.Legend.IsVisible   = false;
                    totalSIPPacketsGraphPane.XAxis.Type         = AxisType.Date;
                    totalSIPPacketsGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    pendingSIPTransactionsGraphPane.Legend.IsVisible   = false;
                    pendingSIPTransactionsGraphPane.XAxis.Type         = AxisType.Date;
                    pendingSIPTransactionsGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    breakdownGraphPane.Legend.Location.AlignH = AlignH.Right;
                    breakdownGraphPane.XAxis.Type             = AxisType.Date;
                    breakdownGraphPane.XAxis.Scale.Format     = "HH:mm:ss";

                    anomaliesGraphPane.XAxis.Type         = AxisType.Date;
                    anomaliesGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    totalParseTimesGraphPane.XAxis.Type         = AxisType.Date;
                    totalParseTimesGraphPane.Legend.IsVisible   = false;
                    totalParseTimesGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    averageParseTimesGraphPane.XAxis.Type         = AxisType.Date;
                    averageParseTimesGraphPane.Legend.IsVisible   = false;
                    averageParseTimesGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    LineItem totalSIPPacketsCurve     = totalSIPPacketsGraphPane.AddCurve("Total SIP Packets", m_totalSIPPacketsList, Color.Black, SymbolType.None);
                    LineItem pendingTransactionsCurve = pendingSIPTransactionsGraphPane.AddCurve("Pending SIP Transactions", m_pendingTransactionsList, Color.Black, SymbolType.None);
                    LineItem sipRequestsInCurve       = breakdownGraphPane.AddCurve("Requests In", m_sipRequestsInList, Color.Blue, SymbolType.None);
                    LineItem sipResponsesInCurve      = breakdownGraphPane.AddCurve("Responses In", m_sipResponsesInList, Color.DarkGreen, SymbolType.None);
                    LineItem sipRequestsOutCurve      = breakdownGraphPane.AddCurve("Requests Out", m_sipRequestsOutList, Color.BlueViolet, SymbolType.None);
                    LineItem sipResponsesOutCurve     = breakdownGraphPane.AddCurve("Responses Out", m_sipResponsesOutList, Color.DarkKhaki, SymbolType.None);
                    LineItem discardsCurve            = anomaliesGraphPane.AddCurve("Discards", m_discardsList, Color.Red, SymbolType.None);
                    LineItem badSIPCurve           = anomaliesGraphPane.AddCurve("Bad SIP", m_badSIPList, Color.Purple, SymbolType.None);
                    LineItem unrecognisedCurve     = anomaliesGraphPane.AddCurve("Unrecognised", m_unrecognisedList, Color.Green, SymbolType.None);
                    LineItem tooLargeCurve         = anomaliesGraphPane.AddCurve("Too Large", m_tooLargeList, Color.Coral, SymbolType.None);
                    LineItem stunCurve             = anomaliesGraphPane.AddCurve("STUN", m_stunList, Color.Blue, SymbolType.None);
                    LineItem totalParseTimeCurve   = totalParseTimesGraphPane.AddCurve("Total Parse Time", m_totalParseTimeList, Color.Black, SymbolType.None);
                    LineItem averageParseTimeCurve = averageParseTimesGraphPane.AddCurve("Average Parse Time", m_avgParseTimeList, Color.Black, SymbolType.None);

                    totalSIPPacketsGraphPane.AxisChange(m_g);
                    pendingSIPTransactionsGraphPane.AxisChange(m_g);
                    breakdownGraphPane.AxisChange(m_g);
                    anomaliesGraphPane.AxisChange(m_g);
                    totalParseTimesGraphPane.AxisChange(m_g);
                    averageParseTimesGraphPane.AxisChange(m_g);

                    Bitmap totalsGraphBitmap = totalSIPPacketsGraphPane.GetImage();
                    totalsGraphBitmap.Save(m_localGraphsDir + "siptotals.png", ImageFormat.Png);

                    Bitmap pendingTransactionsGraphBitmap = pendingSIPTransactionsGraphPane.GetImage();
                    pendingTransactionsGraphBitmap.Save(m_localGraphsDir + "siptransactions.png", ImageFormat.Png);

                    Bitmap breakdownGraphBitmap = breakdownGraphPane.GetImage();
                    breakdownGraphBitmap.Save(m_localGraphsDir + "sipmessagetypes.png", ImageFormat.Png);

                    Bitmap anomaliesGraphBitmap = anomaliesGraphPane.GetImage();
                    anomaliesGraphBitmap.Save(m_localGraphsDir + "anomalies.png", ImageFormat.Png);

                    Bitmap totalParseTimeGraphBitmap = totalParseTimesGraphPane.GetImage();
                    totalParseTimeGraphBitmap.Save(m_localGraphsDir + "siptotalparse.png", ImageFormat.Png);

                    Bitmap averageParseTimeGraphBitmap = averageParseTimesGraphPane.GetImage();
                    averageParseTimeGraphBitmap.Save(m_localGraphsDir + "sipaverageparse.png", ImageFormat.Png);

                    #endregion

                    #region Create SIP methods graph.

                    GraphPane methodsGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Packets for Method per Second", "Time", "SIP Packets/s");
                    methodsGraphPane.XAxis.Type         = AxisType.Date;
                    methodsGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                    foreach (KeyValuePair <SIPMethodsEnum, RollingPointPairList> entry in m_sipMethodsLists)
                    {
                        Color    methodColor = (m_methodColours.ContainsKey(entry.Key)) ? m_methodColours[entry.Key] : Color.Black;
                        LineItem methodCurve = methodsGraphPane.AddCurve(entry.Key.ToString(), entry.Value, methodColor, SymbolType.None);
                    }

                    methodsGraphPane.AxisChange(m_g);
                    Bitmap methodsGraphBitmap = methodsGraphPane.GetImage();
                    methodsGraphBitmap.Save(m_localGraphsDir + "sipmethods.png", ImageFormat.Png);

                    #endregion

                    #region Create top talkers graph.

                    // Get the top 10 talkers.
                    if (m_topTalkersCount.Count > 0)
                    {
                        string[] topTalkerSockets = new string[m_topTalkersCount.Count];
                        int[]    topTalkerValues  = new int[m_topTalkersCount.Count];
                        m_topTalkersCount.Keys.CopyTo(topTalkerSockets, 0);
                        m_topTalkersCount.Values.CopyTo(topTalkerValues, 0);

                        Array.Sort <int, string>(topTalkerValues, topTalkerSockets);

                        GraphPane toptalkersGraphPane = new GraphPane(new Rectangle(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT), "SIP Top Talkers", "Time", "SIP Packets/s");
                        toptalkersGraphPane.XAxis.Type         = AxisType.Date;
                        toptalkersGraphPane.XAxis.Scale.Format = "HH:mm:ss";

                        //foreach (KeyValuePair<string, RollingPointPairList> entry in m_topTalkersLists)
                        for (int index = topTalkerSockets.Length - 1; (index >= topTalkerSockets.Length - NUMBER_TOPTALKERS_TOPPLOT && index >= 0); index--)
                        {
                            string socket = topTalkerSockets[index];
                            RollingPointPairList topTalkerPoints = m_topTalkersLists[socket];
                            Color topTalkerColor = m_topTalkerColours[topTalkerSockets.Length - 1 - index];
                            //logger.Debug("Adding curve for " + socket + " (count=" + topTalkerValues[index] + ").");
                            LineItem topTalkersCurve = toptalkersGraphPane.AddCurve(socket, topTalkerPoints, topTalkerColor, SymbolType.None);
                            //break;
                        }

                        toptalkersGraphPane.AxisChange(m_g);
                        Bitmap topTalkersGraphBitmap = toptalkersGraphPane.GetImage();
                        topTalkersGraphBitmap.Save(m_localGraphsDir + "siptoptalkers.png", ImageFormat.Png);
                    }

                    #endregion

                    logger.Debug("Metrics graph for " + m_metricsFileCopyName + " completed in " + DateTime.Now.Subtract(startTime).TotalMilliseconds.ToString("0.##") + "ms, " + sampleCount + " samples.");

                    #region Uplodad file to server.

                    /*if (m_serverFilename != null && m_serverFilename.Trim().Length > 0)
                     * {
                     *  Uri target = new Uri(m_serverFilename);
                     *  FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
                     *  request.Method = WebRequestMethods.Ftp.UploadFile;
                     *  request.Credentials = new NetworkCredential("anonymous", "*****@*****.**");
                     *
                     *  FileStream localStream = File.OpenRead(m_totalsGraphFilename);
                     *  Stream ftpStream = request.GetRequestStream();
                     *  byte[] buffer = new byte[localStream.Length];
                     *  localStream.Read(buffer, 0, buffer.Length);
                     *  localStream.Close();
                     *  ftpStream.Write(buffer, 0, buffer.Length);
                     *  ftpStream.Close();
                     *
                     *  FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                     *  response.Close();
                     *  //logger.Debug("Result of ftp upload to " + m_serverFilename + " is " + response.StatusDescription + ".");
                     * }*/

                    #endregion
                }
                catch (Exception graphExcp)
                {
                    logger.Error("Exception Saving Graph. " + graphExcp.Message);
                }
            }
            catch (Exception excp)
            {
                logger.Debug("Exception UpdateGraph. " + excp.Message);
            }
        }
Пример #28
0
        private static Image SaveGraph(BlockBase block, IEnumerable <Signal> signals, string title)
        {
            var minX       = double.MaxValue;
            var maxX       = double.MinValue;
            var minY       = double.MaxValue;
            var maxY       = double.MinValue;
            var pane       = new GraphPane(new RectangleF(0, 0, 324, 243), title, "", "");
            var colors     = new[] { Color.Red, Color.Blue, Color.DarkGreen, Color.SaddleBrown, Color.Magenta };
            var colorIndex = 0;
            var i          = 0;

            foreach (var signal in signals)
            {
                var samples = signal.GetSamplesPair().ToList();

                var yAxys = new PointPairList();
                yAxys.AddRange(samples.Select(it => new PointPair(it[1], it[0])));

                if (title == "Abs" ||
                    block.Name == "IFFT" && title == "In" ||
                    block.GetType().Name == "RelationalOperatorBlock" && title == "Out")
                {
                    pane.AddBar(title, yAxys, Color.Blue);
                }
                else
                {
                    pane.AddCurve(title, yAxys, colors[colorIndex], SymbolType.None);
                }

                colorIndex++;
                if (colorIndex >= colors.Length)
                {
                    colorIndex = 0;
                }

                if (signal.CustomPlot != null && signal.CustomPlot.Length > 0 && signal.CustomPlot.Length == 2)
                {
                    var minValue = signal.Samples.Min() * 1.1;
                    var maxValue = signal.Samples.Max() * 1.1;

                    var area = new PointPairList
                    {
                        { signal.CustomPlot[0], minValue },
                        { signal.CustomPlot[0], maxValue },
                        { signal.CustomPlot[0], maxValue },
                        { signal.CustomPlot[1], maxValue },
                        { signal.CustomPlot[1], maxValue },
                        { signal.CustomPlot[1], minValue },
                        { signal.CustomPlot[1], minValue },
                        { signal.CustomPlot[0], minValue }
                    };
                    pane.AddCurve(DesignerResources.PreviousSize, area, Color.Orange, SymbolType.None);
                }
                var localMinY = signal.Samples.Min();
                var localMaxY = signal.Samples.Max();
                var localMinX = samples.Min(it => it[1]);
                var localMaxX = samples.Max(it => it[1]);
                if (localMinY < minY)
                {
                    minY = localMinY;
                }
                if (localMaxY > maxY)
                {
                    maxY = localMaxY;
                }
                if (localMinX < minX)
                {
                    minX = localMinX;
                }
                if (localMaxX > maxX)
                {
                    maxX = localMaxX;
                }
                i++;
            }

            pane.Legend.IsVisible      = false;
            pane.XAxis.Title.IsVisible = false;
            pane.XAxis.Scale.Min       = minX;
            pane.XAxis.Scale.Max       = maxX;
            pane.YAxis.Title.IsVisible = false;
            pane.YAxis.Scale.Min       = minY;
            pane.YAxis.Scale.Max       = maxY;
            pane.AxisChange();
            return(pane.GetImage());
        }
Пример #29
0
        }   //  end CreateScatterGraph

        private void CreateBarGraph(ZedGraphControl zgc)
        {
            //  get reference to the GraphPane
            GraphPane currPane = zgc.GraphPane;

            currPane.CurveList.Clear();
            //  set titles
            currPane.Title.Text = currTitle;
            currPane.Title.FontSpec.IsItalic = true;
            currPane.Title.FontSpec.Size     = 24;
            currPane.Title.FontSpec.Family   = "Times New Roman";
            currPane.XAxis.Title.Text        = currXtitle;
            currPane.YAxis.Title.Text        = currYtitle;

            //  Add data for the graph
            PointPairList graphList = new PointPairList();

            graphList.Clear();
            double maxDBH;
            double minDBH      = 0;
            string legendTitle = "";

            switch (graphNum)
            {
            case 5:
                //  had to store the values in net cubic instead of expansion factor
                foreach (LogStockDO lsd in logStockList)
                {
                    graphList.Add(lsd.DIBClass, lsd.NetCubicFoot, lsd.DIBClass / 5);
                }
                legendTitle = "NUMBER OF LOGS";
                currPane.XAxis.Scale.Min = 0;
                maxDBH = Convert.ToInt16(logStockList.Max(l => l.DIBClass));
                currPane.XAxis.Scale.Max       = maxDBH;
                currPane.XAxis.Scale.MajorStep = 2;
                break;

            case 6:
            case 7:
            case 8:
                foreach (TreeDO td in treeList)
                {
                    graphList.Add(td.DBH, td.ExpansionFactor);
                }
                legendTitle = "NUMBER OF TREES";
                maxDBH      = Convert.ToInt16(treeList.Max(t => t.DBH));
                currPane.XAxis.Scale.Max = maxDBH + 1;
                //  find first dbh class with value
                foreach (TreeDO t in treeList)
                {
                    if (t.ExpansionFactor > 0)
                    {
                        minDBH = t.DBH;
                        break;
                    }   //  endif
                }       //  end foreach loop
                currPane.XAxis.Scale.Min       = minDBH - 1;
                currPane.XAxis.Scale.MajorStep = 2;
                break;

            case 9:
                foreach (CreateTextFile.ReportSubtotal gd in graphData)
                {
                    graphList.Add(gd.Value4, gd.Value3);
                }
                legendTitle = "NUMBER OF TREES";
                double MaxKPI = Convert.ToInt16(graphData.Max(g => g.Value4));
                currPane.XAxis.Scale.Max = MaxKPI + 1;
                break;

            case 11:
                foreach (TreeDO td in treeList)
                {
                    graphList.Add(td.DBH, td.TreeCount);
                }
                legendTitle = "BASAL AREA PER ACRE";
                maxDBH      = Convert.ToInt16(treeList.Max(t => t.DBH));
                currPane.XAxis.Scale.Max = maxDBH + 1;
                //  find first dbh class with value
                foreach (TreeDO t in treeList)
                {
                    if (t.TreeCount > 0)
                    {
                        minDBH = t.DBH;
                        break;
                    }   //  endif
                }       //  end foreach loop
                currPane.X2Axis.Scale.Min       = minDBH - 1;
                currPane.X2Axis.Scale.MajorStep = 2;
                break;
            }   //  end switch

            //  add the curve
            BarItem barCurve = currPane.AddBar(legendTitle, graphList, Color.Blue);

            barCurve.Bar.Fill      = new Fill(Color.ForestGreen);
            barCurve.Bar.Fill.Type = FillType.Solid;

            currPane.Chart.Fill = new Fill(Color.White, Color.FromArgb(153, 204, 255), 45);
            currPane.Fill       = new Fill(Color.White, Color.FromArgb(255, 255, 225), 45);
            //  tell ZedGraph to calculate the axis ranges
            zgc.AxisChange();

            //  save graphs
            Size   newSize    = new Size(337, 320);
            Bitmap currBMP    = new Bitmap(currPane.GetImage(), newSize);
            string outputFile = System.IO.Path.GetDirectoryName(fileName);

            outputFile += "\\Graphs\\";
            outputFile += currSaleName;
            System.IO.Directory.CreateDirectory(outputFile);
            outputFile += "\\";
            //  add graph report to file name
            switch (graphNum)
            {
            case 5:
                outputFile += "GR05";
                outputFile += "_";
                outputFile += currSP;
                break;

            case 6:
                outputFile += "GR06";
                break;

            case 7:
                outputFile += "GR07";
                outputFile += "_";
                outputFile += currSP;
                break;

            case 8:
                outputFile += "GR08";
                outputFile += "_";
                outputFile += currSP;
                break;

            case 9:
                outputFile += "GR09";
                outputFile += "_";
                outputFile += currSP;
                break;

            case 11:
                outputFile += "GR11";
                outputFile += "_";
                outputFile += currSP;
                break;
            }   //  end switch
            outputFile += ".jpg";
            currBMP.Save(@outputFile, System.Drawing.Imaging.ImageFormat.Jpeg);
            return;
        }   //  end CreateBarGraph
Пример #30
0
        }   //  end CreateBarGraph

        private void CreatePieGraph(ZedGraphControl zgc)
        {
            //get reference to the GraphPane
            GraphPane currPane = zgc.GraphPane;

            currPane.CurveList.Clear();
            //  Set titles
            currPane.Title.Text = currTitle;
            currPane.Title.FontSpec.IsItalic = true;
            currPane.Title.FontSpec.Size     = 28;
            currPane.Title.FontSpec.Family   = "Times New Roman";

            //  fill the pane background with a color gradient
            currPane.Fill = new Fill(Color.White, Color.ForestGreen, 45.0f);
            //  No fill for the chart background
            currPane.Chart.Fill.Type = FillType.None;

            //  Set the legend to an arbitrary location
            currPane.Legend.Position = LegendPos.InsideBotRight;
            currPane.Legend.Location = new Location(0.95f, 0.12f, CoordType.PaneFraction,
                                                    AlignH.Right, AlignV.Top);
            currPane.Legend.FontSpec.Size = 8f;
            currPane.Legend.IsHStack      = false;

            //  Add pie slices
            int listTotal = 0;

            if (graphNum != 10)
            {
                listTotal = lcdList.Count;
            }
            else
            {
                listTotal = graphData.Count;
            }
            double[] valuesForSlices = new double[listTotal];
            string[] labelsForSlices = new string[listTotal];
            int      listCnt         = 0;
            double   valuesTotal     = 0;
            string   totalLabel      = "";
            //  request was made to put percentages on each group
            //  to capture the small areas that don't show up well in the chart
            double        totalValue      = 0;
            double        percentOfTotal  = 0;
            StringBuilder combinedLabel   = new StringBuilder();
            string        convertedNumber = "";

            switch (graphNum)
            {
            case 2:
                totalValue = lcdList.Sum(l => l.SumExpanFactor);
                //  dump needed values into arrays
                foreach (LCDDO l in lcdList)
                {
                    valuesForSlices[listCnt] = l.SumExpanFactor;
                    combinedLabel.Append(l.Species);
                    //  calculate percentage
                    percentOfTotal = l.SumExpanFactor / totalValue * 100;
                    combinedLabel.Append(" ");
                    convertedNumber = Utilities.FormatField(percentOfTotal, "{0,4:F1}").ToString();
                    combinedLabel.Append(convertedNumber);
                    combinedLabel.Append("%");
                    labelsForSlices[listCnt] = combinedLabel.ToString();
                    listCnt++;
                    combinedLabel.Remove(0, combinedLabel.Length);
                }       //  end foreach loop
                valuesTotal = lcdList.Sum(l => l.SumExpanFactor);
                totalLabel  = "TOTAL NUMBER OF TREES\n";
                totalLabel += Utilities.FormatField(valuesTotal, "{0,10:F0}").ToString();
                break;

            case 3:
                totalValue = lcdList.Sum(l => l.SumNCUFT);
                //  dump needed values into arrays
                foreach (LCDDO l in lcdList)
                {
                    valuesForSlices[listCnt] = l.SumNCUFT;
                    combinedLabel.Append(l.Species);
                    //  calculate percentage
                    percentOfTotal = l.SumNCUFT / totalValue * 100;
                    combinedLabel.Append(" ");
                    convertedNumber = Utilities.FormatField(percentOfTotal, "{0,4:F1}").ToString();
                    combinedLabel.Append(convertedNumber);
                    combinedLabel.Append("%");
                    labelsForSlices[listCnt] = combinedLabel.ToString();
                    listCnt++;
                    combinedLabel.Remove(0, combinedLabel.Length);
                }       //  end foreach loop
                valuesTotal = lcdList.Sum(l => l.SumNCUFT);
                totalLabel  = "TOTAL NET CUFT VOLUME\n";
                totalLabel += Utilities.FormatField(valuesTotal, "{0,10:F0}").ToString();
                break;

            case 4:
                totalValue = lcdList.Sum(l => l.SumNCUFT);
                //  dump needed values into arrays
                foreach (LCDDO l in lcdList)
                {
                    valuesForSlices[listCnt] = l.SumNCUFT;
                    //  NOTE -- for this report, primary product was dumped into species
                    //  for convenience in coding
                    combinedLabel.Append(l.Species);
                    //  calculate percentage
                    percentOfTotal = l.SumNCUFT / totalValue * 100;
                    combinedLabel.Append(" ");
                    convertedNumber = Utilities.FormatField(percentOfTotal, "{0,4:F1}").ToString();
                    combinedLabel.Append(convertedNumber);
                    combinedLabel.Append("%");
                    labelsForSlices[listCnt] = combinedLabel.ToString();
                    listCnt++;
                    combinedLabel.Remove(0, combinedLabel.Length);
                }       //  end foreach loop
                valuesTotal = lcdList.Sum(l => l.SumNCUFT);
                totalLabel  = "TOTAL NET CUFT VOLUME\n";
                totalLabel += Utilities.FormatField(valuesTotal, "{0,10:F0}").ToString();
                break;

            case 10:
                //  dump needed values into arrays
                foreach (CreateTextFile.ReportSubtotal gd in graphData)
                {
                    valuesForSlices[listCnt] = gd.Value3;
                    combinedLabel.Append(gd.Value1);
                    //  calculate percentage
                    combinedLabel.Append(" ");
                    convertedNumber = Utilities.FormatField(gd.Value3, "{0,4:F1}").ToString();
                    combinedLabel.Append(convertedNumber);
                    labelsForSlices[listCnt] = combinedLabel.ToString();

                    listCnt++;
                    combinedLabel.Remove(0, combinedLabel.Length);
                }       //  end foreach loop
                valuesTotal = totalValue;
                totalLabel  = "TOTAL BAF PER ACRE ";
                totalLabel += Utilities.FormatField(valuesTotal, "{0,10:F0}").ToString();
                break;
            }   //  end switch

            PieItem[] pieSlices = currPane.AddPieSlices(valuesForSlices, labelsForSlices);
            foreach (PieItem p in pieSlices)
            {
                p.LabelDetail.FontSpec.Size = 18f;
            }

            //  Make a text label to highlight the total value
            TextObj text = new TextObj(totalLabel, 0.10F, 0.18F, CoordType.ChartFraction);

            text.Location.AlignH           = AlignH.Center;
            text.Location.AlignV           = AlignV.Bottom;
            text.FontSpec.Size             = 10f;
            text.FontSpec.Border.IsVisible = false;
            text.FontSpec.Fill             = new Fill(Color.White, Color.FromArgb(0, 255, 64), 45F);
            text.FontSpec.StringAlignment  = StringAlignment.Center;
            currPane.GraphObjList.Add(text);

            //  Create a drop shadow for the total value text item
            TextObj text2 = new TextObj(text);

            text2.FontSpec.Fill = new Fill(Color.Black);
            text2.Location.X   += 0.008f;
            text2.Location.Y   += 0.01f;
            currPane.GraphObjList.Add(text2);

            //  Calculate the axis scale ranges
            zgc.AxisChange();


            //  save graphs
            Size   newSize    = new Size(337, 320);
            Bitmap currBMP    = new Bitmap(currPane.GetImage(), newSize);
            string outputFile = System.IO.Path.GetDirectoryName(fileName);

            outputFile += "\\Graphs\\";
            outputFile += currSaleName;
            System.IO.Directory.CreateDirectory(outputFile);
            outputFile += "\\";
            //  add graph report to file name
            switch (graphNum)
            {
            case 2:
                outputFile += "GR02";
                break;

            case 3:
                outputFile += "GR03";
                break;

            case 4:
                outputFile += "GR04";
                break;

            case 10:
                outputFile += "GR10";
                break;
            }   //  end switch
            outputFile += "_";
            outputFile += currSP;
            outputFile += ".jpg";
            currBMP.Save(@outputFile, System.Drawing.Imaging.ImageFormat.Jpeg);

            return;
        }   //  end CreatePieGraph