Esempio n. 1
0
        private void GenerateChart(SeriesCreator creator, string filePath)
        {
            IEnumerable<Series> serieses = creator.ToSerieses();

            using (var ch = new Chart())
            {
                ch.Size = new Size(1300, 800);
                ch.AntiAliasing = AntiAliasingStyles.All;
                ch.TextAntiAliasingQuality = TextAntiAliasingQuality.High;
                ch.Palette = ChartColorPalette.BrightPastel;

                ChartArea area = new ChartArea();
                area.AxisX.MajorGrid.Enabled = false;
                area.AxisY.MajorGrid.Enabled = false;
                area.AxisY.Minimum = creator.GetMinimumY();
                ch.ChartAreas.Add(area);

                Legend legend = new Legend();
                legend.Font = new Font("Microsoft Sans Serif", 12, FontStyle.Regular);
                ch.Legends.Add(legend);

                foreach (var s in serieses)
                {
                    ch.Series.Add(s);
                }

                string savePath = filePath + ".png";
                ch.SaveImage(savePath, ChartImageFormat.Png);
            }
        }
Esempio n. 2
0
        private void button1_Click(object sender, EventArgs e)
        {
            //IList<DataPoint> series = new List<DataPoint>();



            using (var ch = new System.Windows.Forms.DataVisualization.Charting.Chart())
            {
                ch.ChartAreas.Add(new ChartArea());
                var series = new System.Windows.Forms.DataVisualization.Charting.Series("Total Income");


                series.ChartType = SeriesChartType.Spline;
                series.Points.AddXY("September", 100);
                series.Points.AddXY("Obtober", 300);
                series.Points.AddXY("November", 800);
                series.Points.AddXY("December", 200);
                series.Points.AddXY("January", 600);
                series.Points.AddXY("February", 400);


                ch.Series.Add(series);
                ch.SaveImage(@"C:\work\Output.jpg", ChartImageFormat.Jpeg);
            }
        }
        private void button1_Click(object sender, System.EventArgs e)
        {
            // Create a new save file dialog
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            // Sets the current file name filter string, which determines
            // the choices that appear in the "Save as file type" or
            // "Files of type" box in the dialog box.
            saveFileDialog1.Filter           = "Bitmap (*.bmp)|*.bmp|JPEG (*.jpg)|*.jpg|EMF (*.emf)|*.emf|PNG (*.png)|*.png|GIF (*.gif)|*.gif|TIFF (*.tif)|*.tif";
            saveFileDialog1.FilterIndex      = 2;
            saveFileDialog1.RestoreDirectory = true;

            // Set image file format
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                ChartImageFormat format = ChartImageFormat.Bmp;

                if (saveFileDialog1.FileName.EndsWith("bmp"))
                {
                    format = ChartImageFormat.Bmp;
                }
                else if (saveFileDialog1.FileName.EndsWith("jpg"))
                {
                    format = ChartImageFormat.Jpeg;
                }
                else if (saveFileDialog1.FileName.EndsWith("emf"))
                {
                    format = ChartImageFormat.Emf;
                }
                else if (saveFileDialog1.FileName.EndsWith("gif"))
                {
                    format = ChartImageFormat.Gif;
                }
                else if (saveFileDialog1.FileName.EndsWith("png"))
                {
                    format = ChartImageFormat.Png;
                }
                else if (saveFileDialog1.FileName.EndsWith("tif"))
                {
                    format = ChartImageFormat.Tiff;
                }

                // Save image
                Chart1.SaveImage(saveFileDialog1.FileName, format);
            }
        }
 private void ChartInDataPoint_Load(object sender, System.EventArgs e)
 {
     comboBoxChartType.SelectedIndex         = 0;
     comboBoxOriginalChartType.SelectedIndex = 0;
     // Redrawing chart cause recalculation of series elements positions
     Chart1.SaveImage(System.IO.Stream.Null, ChartImageFormat.Bmp);
     comboBoxChartType.SelectedIndex = 1;
 }
Esempio n. 5
0
        private void RenderChart(Chart chart, string chartName)
        {
            chart.Invalidate();

            var path = Path.Combine(_directory, chartName.Replace(":", "-"));
            path = Path.ChangeExtension(path, "png");
            chart.SaveImage(path, ChartImageFormat.Png);
        }
Esempio n. 6
0
 private static void ExportChart(Chart ptrChart)
 {
     try{
         var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
         ptrChart.SaveImage(desktop + @"\" + DateTime.Now.ToString("yMdhms") + ".png", ChartImageFormat.Png);
     }catch (Exception ex) {
         MessageBox.Show("Fail:\n" + ex.Message);
     }
 }
Esempio n. 7
0
        private static void CreatePlotAndSave(TestItem testItem)
        {
            // Create a Chart
            var chart = new Chart();

            // Chart title
            var chartTitle = new Title(testItem.Label);
            chart.Titles.Add(chartTitle);

            // Create Chart Area
            ChartArea chartArea = new ChartArea();
            chartArea.AxisX.Title = "Milestone title";
            chartArea.AxisY.Title = "ms";
            chartArea.AxisX.IsMarginVisible = false;

            for (int i = 0; i < testItem.MilestoneLabels.Length;i++)
            {
                chartArea.AxisX.CustomLabels.Add(i + 0.5, i + 1.5, testItem.MilestoneLabels[i]);
            }

            // Legend
            Legend legend = new Legend("default");
            legend.Docking = Docking.Bottom;
            chart.Legends.Add(legend);

            // Add Chart Area to the Chart
            chart.ChartAreas.Add(chartArea);

            foreach (var line in testItem.Lines)
            {
                Series series = new Series();
                series.Legend = "default";
                series.LegendText = line.Label;
                series.ChartType = SeriesChartType.Line;
                series.MarkerStyle = MarkerStyle.Circle;
                series.BorderWidth = 2;
                series.MarkerSize = 5;
                for (int i = 0; i < line.Points.Length; i++)
                {
                    series.Points.Add(line.Points[i].GetMinTime());
                }
                chart.Series.Add(series);
            }

            // Set chart control location
            chart.Location = new System.Drawing.Point(16, 48);

            // Set Chart control size
            chart.Size = new System.Drawing.Size(400, 300);
            var fileName = GenerateFileName(testItem);
            var file = new FileStream(fileName, FileMode.Create);
            chart.SaveImage(file, ChartImageFormat.Png);
            file.Close();

            Console.WriteLine(String.Format("Report: \"{0}\" created.", fileName));
        }
Esempio n. 8
0
        private static void CreateChart(string outputFileName, DataSet dataSet, List <Series> series, string axisYtitle)
        {
            //prepare chart control...
            var chart = new System.Windows.Forms.DataVisualization.Charting.Chart
            {
                DataSource = dataSet.Tables[0],
                Width      = 1280,
                Height     = 720
            };

            foreach (var serie in series)
            {
                chart.Series.Add(serie);
            }

            //create chartareas...
            chart.ChartAreas.Add(new ChartArea
            {
                Name            = "ChartArea1",
                BackColor       = Color.White,
                BorderColor     = Color.FromArgb(26, 59, 105),
                BorderWidth     = 0,
                BorderDashStyle = ChartDashStyle.Solid,
                AxisX           = new Axis
                {
                    Title     = "Vg [Nm3/h]",
                    TitleFont = new Font("Tahoma", 12.0f),
                    Minimum   = 3,
                    Maximum   = 9
                },
                AxisY = new Axis
                {
                    Title     = axisYtitle,
                    TitleFont = new Font("Tahoma", 12.0f),
                }
            });

            chart.Legends.Add(new Legend("Legend")
            {
                Font = new Font("Tahoma", 12.0f)
            });

            //databind...
            chart.DataBind();

            //save result...
            chart.SaveImage(outputFileName, ChartImageFormat.Png);

            //open result...
            ProcessStartInfo psi = new ProcessStartInfo(outputFileName)
            {
                UseShellExecute = true
            };

            Process.Start(psi);
        }
Esempio n. 9
0
        private void btnExportAsImage_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();

            saveFileDialog.Filter   = "PNG Image|*.png|JPeg Image|*.jpg";
            saveFileDialog.Title    = "Save Chart As Image File";
            saveFileDialog.FileName = "Sample.png";

            DialogResult result = saveFileDialog.ShowDialog();

            saveFileDialog.RestoreDirectory = true;

            if (result == DialogResult.OK && saveFileDialog.FileName != "")
            {
                try
                {
                    if (saveFileDialog.CheckPathExists)
                    {
                        if (saveFileDialog.FilterIndex == 2)
                        {
                            chart1.SaveImage(saveFileDialog.FileName, ChartImageFormat.Jpeg);
                        }
                        else if (saveFileDialog.FilterIndex == 1)
                        {
                            chart1.SaveImage(saveFileDialog.FileName, ChartImageFormat.Png);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Given Path does not exist");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
Esempio n. 10
0
        public Bitmap Show_MSChart()
        {
            try
            {
                if (!Check_Chart())
                    return null;

                ChartArea chartArea = new ChartArea("chartArea");
                Grid grid = new Grid();
                grid.LineDashStyle = ChartDashStyle.Solid;
                grid.LineColor = Color.Black;

                Legend lengend = new Legend();
                lengend.Docking = Docking.Right;

                chartArea.AxisX.MajorGrid = grid;
                chartArea.AxisY.MajorGrid = grid;
                chartArea.AxisX.Interval = 1;
                chartArea.AxisX.IsLabelAutoFit = false;
                chartArea.BackColor = Color.FromArgb(0xEF, 0xEF, 0xEF);

                Series series = new Series("危险度");
                series.ChartType = SeriesChartType.Column;
                //series.IsValueShownAsLabel = true;
                series.Color = dataColor;
                series.BorderWidth = 0;

                SmartLabelStyle smartLabelStyle = new SmartLabelStyle();
                smartLabelStyle.AllowOutsidePlotArea = LabelOutsidePlotAreaStyle.Yes;
                series.SmartLabelStyle = smartLabelStyle;

                series.Points.DataBindXY(dataTable.DefaultView, dataX, dataTable.DefaultView, dataY);
                Chart chart = new Chart();
                chart.Width = width;
                chart.Height = height;
                chart.ChartAreas.Add(chartArea);
                chart.Series.Add(series);
                chart.Legends.Add(lengend);

                MemoryStream memoryStream = new MemoryStream();
                chart.SaveImage(memoryStream, ChartImageFormat.Jpeg);

                Bitmap bitmap = new Bitmap(memoryStream);
                return bitmap;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
Esempio n. 11
0
        /*
         * Creates a new evaluation diagram and replaces the existing image.
         */
        private void createNewDiagram(Evaluation evaluation, SlideShowWindow ssw, Dictionary <String, int> newAnswers)
        {
            // delete answer diagram of current slide
            ssw.View.Slide.Shapes[ssw.View.Slide.Shapes.Count].Delete();

            // create a new bar chart
            Charting.Chart barChart = createBarChart(newAnswers);

            // replace old diagram image with new one
            barChart.SaveImage(evaluation.pathToDiagramImage, Charting.ChartImageFormat.Png);

            // add diagramm image to current slide
            ssw.View.Slide.Shapes.AddPicture2(evaluation.pathToDiagramImage, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, DiagramImageX, DiagramImageY);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="chart"></param>
 public static void SaveImage(Chart chart)
 {
     try
     {
         using (var ms = new MemoryStream())
         {
             chart.SaveImage(ms, ChartImageFormat.Bmp);
             var bm = new Bitmap(ms);
             bm.Save(chart.Name + ".png");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(@"Image save error: " + ex.Message);
     }
 }
Esempio n. 13
0
        //Creating a fun little graph
        public static void CreateGraph(YearMap yearMap)
        {
            //Order the list of keys to get all of the years and find out how many years there were that someone lived in
            var orderedList = yearMap.YearVals.Keys.OrderBy(x => x).ToArray();
            var numberOfYears = orderedList.Count();

            var xvals = new int[numberOfYears];
            var yvals = new int[numberOfYears];
            for (int i = 0; i < yvals.Length; i++)
            {
                yvals[i] = yearMap.YearVals[orderedList[i]];
                xvals[i] = orderedList[i];
            }

            var chart = new Chart();
            chart.Size = new Size(1000, 1000);
            Title title = new Title("Number of people alive each year");
            title.Font = new Font("Calibri", 16, System.Drawing.FontStyle.Bold);
            chart.Titles.Add(title);

            var chartArea = new ChartArea();
            chartArea.AxisX.LabelStyle.Font = new Font("Calibri", 8);
            chartArea.AxisY.LabelStyle.Font = new Font("Calibri", 8);
            chartArea.AxisY.Minimum = 0;
            chartArea.AxisX.Minimum = 1900;
            chartArea.AxisX.Maximum = 2000;
            chartArea.AxisX.Title = "Years";
            chartArea.AxisX.TitleFont = new Font("Calibri", 14, System.Drawing.FontStyle.Bold);
            chartArea.AxisY.Title = "Number of People Alive";
            chartArea.AxisY.TitleFont = new Font("Calibri", 14, System.Drawing.FontStyle.Bold);
            chartArea.AxisY.Interval = 1;
            chartArea.AxisX.Interval = 5;

            chart.ChartAreas.Add(chartArea);

            var series = new Series();
            series.Name = "Series";
            series.ChartType = SeriesChartType.Bar;
            chart.Series.Add(series);

            chart.Series["Series"].Points.DataBindXY(xvals, yvals);

            chart.Invalidate();

            chart.SaveImage("../../Output/chart.png", ChartImageFormat.Png);
        }
Esempio n. 14
0
        public static void GenerateChart(ChartParamterers parameters, string resultPath)
        {
            var csvPath = string.Format("{0}.csv", resultPath);

            var records = ReadDataFromFile(csvPath);

            var myChart = new Chart
            {
                Size = ChartSize
            };

            var myChartArea = new ChartArea();
            myChart.ChartAreas.Add(myChartArea);

            var series = new Series("default")
                             {
                                 ChartType = parameters.ChartType
                             };

            foreach (var thing in records)
            {
                series.Points.AddXY(thing.X.Length > 25 ? thing.X.Substring(0, 25) : thing.X, thing.Y);
            }

            myChart.Series.Add(series);

            if (parameters.AllValuesInXInterval)
            {
                myChart.ChartAreas[0].AxisX.Interval = 1;
            }

            var font = new Font("Arial", 12, FontStyle.Bold);
            var title = new Title
            {
                Text = resultPath,
                Font = font
            };

            myChart.Titles.Add(title);

            var pngPath = string.Format("{0}.png", resultPath);
            myChart.SaveImage(pngPath, ChartImageFormat.Png);
        }
Esempio n. 15
0
        private void CreateChart(string filename, IEnumerable<Tuple<string, double>> values)
        {
            Chart singletonChart = new Chart()
            {
                Size = new Size(800, 600),
                Palette = ChartColorPalette.Pastel,
            };

            singletonChart.ChartAreas.Add("Series1");

            singletonChart.Series.Add("Series1");
            singletonChart.Series["Series1"].ChartType = SeriesChartType.Bar;
            singletonChart.ChartAreas[0].AxisX.Interval = 1;

            foreach (var value in values)
            {
                singletonChart.Series["Series1"].Points.AddXY(value.Item1, value.Item2);
            }

            singletonChart.SaveImage(filename, ChartImageFormat.Png);
        }
Esempio n. 16
0
        public string GeneratePlot(double[] items, string title)
        {
            string file = "";
            chart = new Chart();

            chart.ChartAreas.Add(new ChartArea());
            int i = 1;
            foreach (var item in items)
            {
                SetChart(title, i, item);
                i++;
            }

            DateTime d = DateTime.Now;
            var xxx = String.Format("{0}_{1}_{2}_{3}_{4}_{5}_{6}", d.Year, d.Month, d.Day, d.Hour, d.Minute, d.Second, d.Millisecond);
            String chartFilename = Common.Folder.Data + "\\" + xxx + ".bmp";
            chart.Update();
            chart.SaveImage(chartFilename, System.Drawing.Imaging.ImageFormat.Bmp);
            file = chartFilename;

            return file;
        }
        private static Bitmap CreateSegmentImage(uint code)
        {
            var chart = new Charting.Chart();

            chart.Series.Clear();
            chart.BackColor = Color.Transparent;
            chart.ChartAreas.Add("Chart Area");
            chart.ChartAreas[0].BackColor = Color.Transparent;
            chart.Series.Add("segments");
            chart.Series[0].ChartType   = Charting.SeriesChartType.Doughnut;
            chart.Series[0].BorderWidth = 10;
            chart.Series[0].BorderColor = Color.Black;
            for (var i = 0; i < 8; i++)
            {
                chart.Series[0].Points.Add(1, i);
                chart.Series[0].Points[i].Color = code.CheckBit(i) ? Globals.OnColor : Globals.OffColor;
            }

            using (var ms = new MemoryStream())
            {
                chart.SaveImage(ms, Charting.ChartImageFormat.Png);
                return(new Bitmap(ms));
            }
        }
Esempio n. 18
0
        public System.Drawing.Image generaGrafica(IList<DataPoint> series, string Pr1)
        {
            using (MemoryStream graph = new MemoryStream())
            using (var ch = new Chart())
            {
                ch.ChartAreas.Add(new ChartArea());

                var s = new Series();
                foreach (var pnt in series) s.Points.Add(pnt);
                s.XValueType = ChartValueType.DateTime;
                ch.Series.Add(s);
                s.ChartType = SeriesChartType.FastLine;
                s.Color = Color.Red;
                s.Name = Pr1;

                ch.Size = new Size(600, 400);
                ch.SaveImage(graph, ChartImageFormat.Jpeg);
                ch.Legends.Add("leyenda");

                MemoryStream ms = new MemoryStream(graph.GetBuffer());
                var image = System.Drawing.Image.FromStream(ms);
                return image;
            }
        }
Esempio n. 19
0
        private static void SaveChart(List<double> requestTimes, TimeSpan totalTime, double minTime, double maxTime, double avgTime)
        {
            DataSet dataSet = new DataSet();
            DataTable dt = new DataTable();
            dt.Columns.Add("Seconds", typeof(int));
            dt.Columns.Add("RequestCount", typeof(int));

            Dictionary<int, int> timeTable = new Dictionary<int, int>();

            List<DataRow> rows = new List<DataRow>();
            List<int> intTimes = requestTimes.OrderBy(t => t).Select(t => (int)Math.Round(t/1000)).ToList();

            foreach (int time in intTimes)
            {
                DataRow row = rows.FirstOrDefault(r => ((int)r[0]) == time);

                if (row == null)
                {
                    row = dt.NewRow();
                    row[0] = time;
                    row[1] = 0;
                    rows.Add(row);
                }

                row[1] = ((int)row[1]) + 1;
            }

            rows.ForEach(r => dt.Rows.Add(r));

            dataSet.Tables.Add(dt);

            Chart chart = new Chart();
            chart.DataSource = dataSet.Tables[0];
            chart.Width = 900;
            chart.Height = 500;

            Series series = new Series();
            series.Name = "Serie1";
            series.Color = Color.FromArgb(220, 0, 27);
            series.ChartType = SeriesChartType.Column;
            series.ShadowOffset = 0;
            series.IsValueShownAsLabel = true;
            series.XValueMember = "Seconds";
            series.YValueMembers = "RequestCount";
            series.Font = new Font(series.Font.FontFamily, 10);
            chart.Series.Add(series);

            ChartArea ca = new ChartArea();
            ca.Name = "ChartArea1";
            ca.BackColor = Color.White;
            ca.BorderWidth = 0;
            ca.AxisX = new Axis();
            ca.AxisY = new Axis();
            ca.AxisX.Title = "Time (seconds)";
            Font f = ca.AxisX.TitleFont;
            ca.AxisX.TitleFont = new Font(f.FontFamily, 12, f.Style);
            ca.AxisY.Title = "Request count";
            ca.AxisY.TitleFont = ca.AxisX.TitleFont;
            ca.AxisX.MajorGrid.LineColor = Color.LightGray;
            ca.AxisY.MajorGrid.LineColor = ca.AxisX.MajorGrid.LineColor;
            chart.ChartAreas.Add(ca);

            chart.Titles.Add("Requests times");
            chart.Titles[0].Font = ca.AxisX.TitleFont;
            chart.Titles.Add(GetChartDescriptionString(totalTime, minTime, maxTime, avgTime));
            chart.Titles[1].Font = new Font(chart.Titles[1].Font.FontFamily, 10);

            chart.DataBind();

            int i = 0;
            string fileName = "";

            //loop until you find a free file name (in case multiple instances are running at the same time)
            do
            {
                fileName = string.Format("chart-{0}.png", i++);
            }
            while(File.Exists(fileName));

            chart.SaveImage(fileName, ChartImageFormat.Png);
        }
Esempio n. 20
0
        /// <summary>
        /// Expecting a list of series names, which are the type and name, split with an ">", or can be a list of regex's
        /// </summary>
        /// <param name="series"></param>
        public Stream generateImage(List<string> series)
        {
            DateTime graphStartTime = DateTime.Now;

            //set up a windows form graph thing
            try
            {
                using (var ch = new Chart())
                {
                    ch.Width = 1200;
                    ch.Height = 600;
                    ch.TextAntiAliasingQuality = TextAntiAliasingQuality.High;

                    Title t = new Title(Roboto.Settings.botUserName + " Statistics", Docking.Top, new System.Drawing.Font("Roboto", 14), Color.Black);
                    ch.Titles.Add(t);

                    ChartArea cha = new ChartArea("cha");
                    cha.BackColor = Color.FromArgb(200,225,255);

                    cha.AxisX.Title = "Hours Ago";
                    //cha.AxisX.TitleFont = new System.Drawing.Font("Calibri", 11, System.Drawing.FontStyle.Bold);
                    cha.AxisX.TitleFont = new System.Drawing.Font("Roboto", 11);
                    cha.AxisX.MajorGrid.Interval = 6;
                    cha.AxisY.Title = "Value / " + granularity.TotalMinutes.ToString() + " mins"  ;
                    cha.AxisY.TitleFont = new System.Drawing.Font("Roboto", 11);
                    //cha.AxisY.TitleFont = new System.Drawing.Font("Calibri", 11, System.Drawing.FontStyle.Bold);

                    Legend l = new Legend("Legend");
                    l.DockedToChartArea = "cha";
                    l.IsDockedInsideChartArea = true;
                    l.Docking = Docking.Right;

                    ch.ChartAreas.Add(cha);
                    ch.Legends.Add(l);

                   //if nothing passed in, assume all stats
                    if (series.Count == 0) { series.Add(".*"); }

                    //gather all matching statTypes
                    List<statType> matches = new List<statType>();

                    foreach (string s in series)
                    {
                        //populate list of statTypes that match our query. Dont worry about order / dupes - will be ordered later
                        //try exact matches
                        string[] titles = s.Trim().Split(">"[0]);
                        if (titles.Length == 2)
                        {
                            //get the series info
                            statType seriesStats = getStatType(titles[1], titles[0]);
                            if (seriesStats != null) { matches.Add(seriesStats); }
                        }

                        //try regex matches
                        List<statType> matchingTypes = getStatTypes(s);
                        foreach (statType mt in matchingTypes)
                        {
                            matches.Add(mt);
                        }

                    }
                    if (matches.Count == 0)
                    {
                        Roboto.log.log("No chart type matches", logging.loglevel.warn);
                        return null;
                    }
                    else
                    {
                        matches = matches.Distinct().OrderBy(x => x.moduleType + ">" + x.name).ToList();
                        foreach (statType seriesStats in matches)
                        {
                            ch.Series.Add(seriesStats.getSeries(graphStartTime));
                        }
                        //ch.SaveImage(@"C:\temp\chart.jpg", ChartImageFormat.Jpeg);
                        MemoryStream ms = new MemoryStream();
                        ch.SaveImage(ms, ChartImageFormat.Jpeg);
                        return (ms);
                    }
                }
            }
            catch (Exception e)
            {
                Roboto.log.log("Error generating chart. " + e.ToString() , logging.loglevel.critical);
            }
            return null;
        }
Esempio n. 21
0
        /*
         * The next slide at this point is an evaluation slide, which is created in this method.
         */
        public void evaluateAnswers(int slideId, string sessionId, Presentation presentation)
        {
            // check if current slide has answers to evaluate
            List <String> questionIds = new List <String>();

            if (MyRibbon.pptNavigator.getCustomSlideById(slideId) != null)
            {
                foreach (var question in getCustomSlideById(slideId).EvaluationList)
                {
                    if (question.EvaluateSlideId != null && !question.IsEvaluated && question.EvaluateSlideId == slideId)
                    {
                        questionIds.Add(question.ID);
                        question.IsEvaluated = true;
                    }
                }
            }

            if (questionIds.Count == 0)
            {
                // no questions to evaluate
                return;
            }

            // make REST request to get evaluated Data
            var evaluationList = MyRibbon.myRestHelper.EvaluateAnswers(questionIds, sessionId);

            // make a chart out of the data
            if (evaluationList != null)
            {
                // iterate evaluations that should be displayed after current slide
                foreach (var evaluation in evaluationList)
                {
                    Charting.Chart barChart = createBarChart(evaluation.Answers);

                    // write out a file
                    // create a directory to store all diagramm pictures for that presentation
                    String evaluationPicsDir = presentation.Path + "/presentaion_evaluation_" + sessionId + "_" + DateTime.Now.ToString("M/d/yyyy");
                    if (!Directory.Exists(evaluationPicsDir))
                    {
                        Directory.CreateDirectory(evaluationPicsDir);
                    }
                    String pathToDiagramImage = evaluationPicsDir + "/diagramm_of_question_" + Utils.generateRandomString() + ".png";
                    barChart.SaveImage(pathToDiagramImage, Charting.ChartImageFormat.Png);


                    // create slides with that data
                    // Add slide to presentation
                    var          slideIndexToShowEvaluation = presentation.Slides.FindBySlideID(slideId).SlideIndex + 1;
                    CustomLayout customLayout =
                        presentation.SlideMaster.CustomLayouts[PpSlideLayout.ppLayoutText];
                    var evaluationSlide = presentation.Slides.AddSlide(slideIndexToShowEvaluation, customLayout);

                    // add title to that slide
                    var objText = evaluationSlide.Shapes[1].TextFrame.TextRange;
                    objText.Text      = evaluation.Question;
                    objText.Font.Name = "Arial";
                    objText.Font.Size = 24;

                    // this first image is always centered into the center of the slide, no matter what coordinates you pass
                    // workaround: add an empty image first
                    // TODO: create a folder an put image there.
                    var filePathEmptyImage = "C:\\Users\\User\\Documents\\Visual Studio 2017\\Projects\\PowerPointAddIn1\\PowerPointAddIn1\\Resources\\empty_image.png";
                    evaluationSlide.Shapes.AddPicture2(filePathEmptyImage, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, 0, 0);

                    // if question contains an image -> download it and add it to the evaluation slide
                    if (evaluation.ImageURL != null && evaluation.ImageURL.Length > 0)
                    {
                        String pathToQuestionImage = MyRibbon.myRestHelper.downloadQuestionImage(evaluationPicsDir + "/pic_of_question_" + Utils.generateRandomString(), evaluation.ImageURL);
                        evaluationSlide.Shapes.AddPicture(pathToQuestionImage, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, 30, 200, 200, 200);
                    }

                    // add diagramm image
                    evaluationSlide.Shapes.AddPicture2(pathToDiagramImage, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoTrue, DiagramImageX, DiagramImageY);

                    // add EvaluationSlide to the list.
                    evaluation.pathToDiagramImage = pathToDiagramImage;
                    int hash = EvaluationSlides.GetHashCode();
                    EvaluationSlides.Add(evaluationSlide, evaluation);
                }
            }
        }
Esempio n. 22
0
        void RenderWindow_RightButtonPressEvt(vtkObject sender, vtkObjectEventArgs e)
        {
            this.contextMenuStripActorPicker = new ContextMenuStrip();
            int[] Pos;
            Pos = this.iren.GetLastEventPosition();

            ToolStripMenuItem ToolStripMenuItem_World = new ToolStripMenuItem("World");
            ToolStripMenuItem ScaleItem = new ToolStripMenuItem("Scale");
            ToolStripMenuItem_World.DropDownItems.Add(ScaleItem);
            ScaleItem.Click += new System.EventHandler(this.ScaleClicking);

            ToolStripMenuItem ColorItem = new ToolStripMenuItem("Background Color");
            ToolStripMenuItem_World.DropDownItems.Add(ColorItem);
            ColorItem.Click += new System.EventHandler(this.ColorClicking);

            ToolStripMenuItem ExportViewItem = new ToolStripMenuItem("Export View");
            ToolStripMenuItem_World.DropDownItems.Add(ExportViewItem);
            ExportViewItem.Click += new System.EventHandler(this.ExportViewClicking);

            if (this.ListNameObjectType.Count >= 1)
            {
                ToolStripMenuItem SelectionItem = new ToolStripMenuItem("Selection Type");
                ToolStripMenuItem_World.DropDownItems.Add(SelectionItem);
                SelectableObjectName = new List<bool>();

                for (int idxName = 0; idxName < this.ListNameObjectType.Count; idxName++)
                {
                    ToolStripMenuItem TypeName = new ToolStripMenuItem(ListNameObjectType[idxName]);
                    TypeName.CheckOnClick = true;
                    TypeName.Checked = true;
                    TypeName.Click += new System.EventHandler(this.TypeNameClicking);

                    if (TypeName.Checked) SelectableObjectName.Add(true);
                    else SelectableObjectName.Add(false);
                }
            }

            string MetaObjectName = "";
            vtkPicker Picker = vtkPicker.New();
            int numActors = Picker.Pick(Pos[0], Pos[1], 0, this.ren1);
            if (numActors == 1)
            {
                vtkActor PickedActor = Picker.GetActor();

                bool selectable = false;
                for (int i = 0; i < ListObject.Count; i++)
                    if (ListObject[i].GetActor() == PickedActor)
                    {
                        cInteractive3DObject Obj = (cInteractive3DObject)ListObject[i];
                        if (Obj.GetMetaObjectContainer() != null) MetaObjectName = Obj.GetMetaObjectContainer().Information.GetName() + " -> ";

                        for (int idx = 0; idx < this.SelectableObjectName.Count; idx++)
                        {
                            // the selected actor has been identified, let's get its type
                            cInteractive3DObject TmpBioObj = (cInteractive3DObject)ListObject[i];

                            int IdxType = -1;
                            for (int TmpIdx = 0; TmpIdx < this.ListNameObjectType.Count; TmpIdx++)
                                if (TmpBioObj.GetType() == this.ListNameObjectType[TmpIdx]) IdxType = TmpIdx;

                            // Is the type selectable (i.e. checked by the user in the contextual menu ?
                            if (this.SelectableObjectName[IdxType])
                            {
                                selectable = true;
                                break;
                            }
                        }
                    }

                if (selectable == true)
                {
                    ToolStripMenuItem TypeItem = null;
                    ToolStripMenuItem ToolStripMenuItem_ObjectDisplay = new ToolStripMenuItem("Object display");
                    // ToolStripMenuItem CentroidItem = new ToolStripMenuItem("Centroid");
                    ToolStripMenuItem ToolStripMenuItem_MetaDescriptorDisplay = null;

                    ToolStripMenuItem_DescriptorDisplay = new ToolStripMenuItem("Object profil");
                    {
                        for (int i = 0; i < ListObject.Count; i++)
                            if (ListObject[i].GetActor() == PickedActor)
                            {
                                Type T = ListObject[i].GetType();
                                List<double> ListDesc = null;
                                List<string> ListProfilName = null;

                                if (T.Name == "cBiological3DVolume")
                                {
                                    cBiological3DVolume TmpVol = (cBiological3DVolume)ListObject[i];
                                    ListProfilName = TmpVol.Information.GetDescriptorNames();
                                    ListDesc = TmpVol.Information.GetInformation();
                                    TypeItem = new ToolStripMenuItem(MetaObjectName + TmpVol.GetType());
                                }
                                else if (T.Name == "cBiologicalSpot")
                                {
                                    cBiologicalSpot TmpSpot = (cBiologicalSpot)ListObject[i];
                                    ListProfilName = TmpSpot.Information.GetDescriptorNames();
                                    ListDesc = TmpSpot.Information.GetInformation();
                                    TypeItem = new ToolStripMenuItem(MetaObjectName + TmpSpot.GetType());
                                }
                                else if (T.Name == "c3DWell")
                                {
                                    c3DWell TmpWell = (c3DWell)ListObject[i];
                                    ListProfilName = TmpWell.Information.GetDescriptorNames();
                                    ListDesc = TmpWell.Information.GetInformation();
                                    TypeItem = new ToolStripMenuItem(MetaObjectName + TmpWell.GetType());

                                    Chart ThumbnailChart = TmpWell.AssociatedWell.GetChart();
                                    if (ThumbnailChart != null)
                                    {
                                        MemoryStream ms = new MemoryStream();
                                        TmpWell.AssociatedWell.GetChart().SaveImage(ms, ChartImageFormat.Bmp);
                                        TypeItem.Image = new Bitmap(ms);
                                        TypeItem.ImageScaling = ToolStripItemImageScaling.None;
                                        TypeItem.Size = new System.Drawing.Size(48, 48);

                                        // New3DWell.ThumbnailnewImage = new Bitmap(ms);
                                    }

                                    CurrentlySelectedWell = TmpWell.AssociatedWell;

                                    TypeItem.Click += new System.EventHandler(this.WellInfoClick);

                                }
                                else if (T.Name == "c3DIsoContours")
                                {
                                    c3DIsoContours TmpContours = (c3DIsoContours)ListObject[i];

                                   // ListProfilName = TmpWell.Information.GetDescriptorNames();
                                  //  ListDesc = TmpWell.Information.GetInformation();
                                    TypeItem = new ToolStripMenuItem();
                                    Chart TmpChart = new Chart();
                                    Series SeriesPos = new Series();
                                    //SeriesPos.ShadowOffset = 1;

                                    ChartArea CurrentChartArea = new ChartArea();

                                    List<double> DoubleList = new List<double>();
                                    int Idx = 0;
                                    double[] Colour =TmpContours.GetActor().GetProperty().GetColor();

                                    foreach (cPoint3D CurrentPt in TmpContours.ListPtContour)
                                    {
                                        SeriesPos.Points.AddY(CurrentPt.Z);
                                        SeriesPos.Points[Idx].MarkerSize = 2;
                                        SeriesPos.Points[Idx].MarkerStyle = MarkerStyle.Circle;

                                        SeriesPos.Points[Idx++].Color = Color.FromArgb((int)Colour[0], (int)Colour[1], (int)Colour[2]);
                                        //DoubleList.Add(CurrentPt.Z);
                                    }

                                    //CDisplayGraph DispGraph = new CDisplayGraph(DoubleList.ToArray());
                                    SeriesPos.ChartType = SeriesChartType.Point;
                                    TmpChart.ChartAreas.Add(CurrentChartArea);

                                    CurrentChartArea.Axes[1].LabelStyle.Enabled = false;
                                    CurrentChartArea.Axes[1].MajorGrid.Enabled = false;
                                    CurrentChartArea.Axes[0].Enabled = AxisEnabled.False;
                                    CurrentChartArea.Axes[1].Enabled = AxisEnabled.False;
                                    CurrentChartArea.Axes[0].MajorGrid.Enabled = false;
                                    TmpChart.Width = 120;
                                    TmpChart.Height = 60;

                                    TmpChart.TextAntiAliasingQuality = TextAntiAliasingQuality.High;

                                    TmpChart.Series.Add(SeriesPos);

                                    //Chart ThumbnailChart = TmpChart.NewWindow.chartForSimpleForm;
                                   // if (ThumbnailChart != null)
                                    {
                                        MemoryStream ms = new MemoryStream();
                                        TmpChart.SaveImage(ms, ChartImageFormat.Bmp);
                                        TypeItem.Image = new Bitmap(ms);
                                        TypeItem.ImageScaling = ToolStripItemImageScaling.None;
                                        TypeItem.Size = new System.Drawing.Size(48, 48);

                                        // New3DWell.ThumbnailnewImage = new Bitmap(ms);
                                    }

                                  //  CurrentlySelectedWell = TmpWell.AssociatedWell;

                                  //  TypeItem.Click += new System.EventHandler(this.WellInfoClick);

                                }

                                if (((cInteractive3DObject)ListObject[i]).ThumbnailnewImage != null)
                                {

                                    //    TypeItem.Image = ((cBiological3DObject)ListObject[i]).ThumbnailnewImage;
                                    //    TypeItem.ImageScaling = ToolStripItemImageScaling.None;
                                    //    TypeItem.Size = new System.Drawing.Size(48, 48);
                                    //    TypeItem.Click += new System.EventHandler(this.WellInfoClick);

                                }

                                if (ListProfilName != null)
                                    for (int idxName = 0; idxName < ListProfilName.Count; idxName++)
                                    {
                                        ToolStripMenuItem descName = new ToolStripMenuItem(ListProfilName[idxName] + " : " + ListDesc[idxName]);
                                        ToolStripMenuItem_DescriptorDisplay.DropDownItems.Add(descName);
                                    }
                                else
                                {
                                    ToolStripMenuItem descName = new ToolStripMenuItem("Null");
                                    ToolStripMenuItem_DescriptorDisplay.DropDownItems.Add(descName);
                                }

                            }
                    }

                    ToolStripSeparator SepratorStrip = new ToolStripSeparator();
                    if (ToolStripMenuItem_MetaDescriptorDisplay != null)
                        contextMenuStripActorPicker.Items.AddRange(new ToolStripItem[] { TypeItem, SepratorStrip, ToolStripMenuItem_World, ToolStripMenuItem_ObjectDisplay, ToolStripMenuItem_DescriptorDisplay, ToolStripMenuItem_MetaDescriptorDisplay });
                    else
                        contextMenuStripActorPicker.Items.AddRange(new ToolStripItem[] { TypeItem, SepratorStrip, ToolStripMenuItem_World, ToolStripMenuItem_ObjectDisplay, ToolStripMenuItem_DescriptorDisplay });
                }
                else
                    contextMenuStripActorPicker.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem_World });
            }
            else
                contextMenuStripActorPicker.Items.AddRange(new ToolStripItem[] { ToolStripMenuItem_World });

            int[] PosWindow = this.renWin.GetSize();
            contextMenuStripActorPicker.Show(Control.MousePosition);
            return;
        }
Esempio n. 23
0
        private static void CreateBenchmarkChart(string name, string filename, IEnumerable<BenchmarkResult> results)
        {
            if (!results.Any())
            {
                return;
            }

            Chart chart = new Chart()
            {
                Size = new Size(800, 600),
                Palette = ChartColorPalette.Pastel,
                BorderlineColor = Color.Black,
                BorderlineWidth = 1,
                BorderColor = Color.Black,
                BorderDashStyle = ChartDashStyle.Solid,
            };

            chart.Titles.Add(name);
            chart.ChartAreas.Add("Default");

            chart.Series.Add("Single thread");
            chart.Series["Single thread"].ChartType = SeriesChartType.Bar;

            chart.Series.Add("Multiple threads");
            chart.Series["Multiple threads"].ChartType = SeriesChartType.Bar;

            chart.ChartAreas[0].AxisX.IsMarginVisible = false;
            chart.ChartAreas[0].AxisX.Interval = 1;
            chart.ChartAreas[0].AxisY.IsLogarithmic = true;

            chart.Legends.Add(new Legend("Default")
            {
                Docking = Docking.Bottom,
                Alignment = StringAlignment.Center,
                BorderWidth = 1,
                BorderColor = Color.Black
            });

            foreach (var result in results)
            {
                // sometimes during development loop is made very short to run fast check
                // logarithmic unplotted 0 is produced and replaced with 1
                var singleThreadedValue = result.SingleThreadedResult.Time.GetValueOrDefault(1);
                chart.Series["Single thread"].Points.AddXY(result.ContainerInfo.Name, singleThreadedValue == 0 ? 1 : singleThreadedValue);
                var multiThreadedValue = result.MultiThreadedResult.Time.GetValueOrDefault(1);
                chart.Series["Multiple threads"].Points.AddXY(result.ContainerInfo.Name, multiThreadedValue == 0 ? 1 : multiThreadedValue);
            }

            chart.SaveImage(filename, ChartImageFormat.Png);
        }
        /// <summary>
        /// Creates a bar graph based on columnValueCounter input and saves the graph as an image file under the given filename.
        /// </summary>
        private string GenerateBarGraph(List <ColumnValueCounter> columnValueCounters, string filename, DocumentManipulation.TextReplacementOptions options)
        {
            Chart         chart     = new Chart();
            List <Series> allSeries = new List <Series>();

            if (columnValueCounters.Count == 0)
            {
                throw new Exception("No data imported. Invalid CSV data format");
            }
            //Get chart series X values from data
            string[] xValues = InitializeChartSeriesXValues(allSeries, columnValueCounters, chart);

            for (int i = 0; i < columnValueCounters.Count; i++)
            {
                List <UniqueRowValue> uniqueRowValues = columnValueCounters[i].uniqueRowValues;
                float[] yValues = new float[uniqueRowValues.Count];

                //for every unique row value in the column
                for (int j = 0; j < uniqueRowValues.Count; j++)
                {
                    int k;
                    int totalNumUniqueRowValues = 0;
                    //Add y values based on which mode the graph is in
                    if (options.isCount)
                    {
                        //If there is more than one relevant column then the xValues are the column names, otherwise the xValues are the uniqueRowValue names.
                        if (columnValueCounters.Count > 1)
                        {
                            allSeries[j % allSeries.Count].Points.AddXY(xValues[i], uniqueRowValues[j].count);
                            allSeries[j % allSeries.Count].Name = uniqueRowValues[j].name;
                        }
                        else
                        {
                            allSeries[j % allSeries.Count].Points.AddXY(xValues[j], uniqueRowValues[j].count);
                        }
                    }
                    else if (options.isPercentage)
                    {
                        //get the total number of values in the column
                        for (k = 0; k < uniqueRowValues.Count; k++)
                        {
                            totalNumUniqueRowValues += uniqueRowValues[k].count;
                        }
                        allSeries[j % allSeries.Count].Points.AddXY(xValues[i], Math.Round((((float)uniqueRowValues[j].count) / ((float)totalNumUniqueRowValues)) * 100, 1));
                    }
                }
            }
            if (columnValueCounters.Count <= 1)
            {
                //Add another column that represents the number of "Unknown" responses (rows that were blank in that column).
                allSeries[0].Points.AddXY("Unknown", columnValueCounters[0].unknownCount);
                //Reorder the data values so they show up in the appropriate as specified by the user.
                ApplyItemOrder(allSeries[0]);
                //Apply all of the customized settings for the series and add it to the chart.
                FinalizeBarChartSeries(chart, allSeries[0], columnValueCounters, _colorPallette[0], options);
            }
            else
            {
                //Place the series in the correct order as specified by the user in an 'order' command.
                ApplyItemOrder(allSeries);

                //for each series, create spacing between the bars in the chart, apply a color from the color pallette, and apply custom series settings for the bar chart.
                for (int j = 0; j < allSeries.Count; j++)
                {
                    if (j > 0)
                    {
                        //To create space between different series on the chart, insert a filler series that acts as a spacer.
                        CreateFillerChartSeries(chart, allSeries[j].Name, xValues.ToList());
                    }
                    if (j >= _colorPallette.Length)
                    {
                        MessageBox.Show(new Form {
                            TopMost = true
                        }, "Warning: Not enough colors specified in color pallette to accomodate data input.");
                    }
                    Color seriesColor = _colorPallette[j % _colorPallette.Length];
                    //Apply all of the customized settings for the series and then add the series to the chart.
                    FinalizeBarChartSeries(chart, allSeries[j], columnValueCounters, seriesColor, options);
                }
                //Add more space between each set of bar graph columns
                CreateFillerChartSeries(chart, "end", xValues.ToList());
                CreateFillerChartSeries(chart, "end1", xValues.ToList());
            }
            //Apply all of the customized settings for the chart itself.
            ApplyCustomChartOptions(chart, options, columnValueCounters);

            try {
                chart.SaveImage(filename, ChartImageFormat.Png);
            }
            catch (Exception) {
                throw new Exception("Failed to save graph image");
            }
            return(filename);
        }
Esempio n. 25
0
 private Stream ChartToImage(Chart chart)
 {
     MemoryStream stream = new MemoryStream();
     chart.SaveImage(stream, ChartImageFormat.Bmp);
     stream.Position = 0;
     return BitmapToJpg(stream);
 }
Esempio n. 26
0
        public void CreateChart(List<string> name, List<float> current, List<float> future)
        {
            Form formChart = new Form();
            formChart.AutoSize = true;
            formChart.AutoScroll = true;

            formChart.Show();
            Chart newChart = new Chart();

            formChart.Text = "Capability Assessment Summary Score";
            newChart.Parent = formChart;

            int maxQuestion = 0;

            if (current.Count < future.Count)
            {
                maxQuestion = future.Count;
            }
            else
            {
                maxQuestion = current.Count;
            }

            newChart.Size = new Size(800, 800);
            newChart.Visible = true;
            newChart.Text = "Capability Assessment Summary Score";
            newChart.Name = newChart.Text;
            newChart.ChartAreas.Add("chart1");
            newChart.Palette = ChartColorPalette.BrightPastel;

            newChart.ChartAreas["chart1"].Visible = true;
            newChart.ChartAreas["chart1"].AxisX.MajorGrid.Enabled = false;
            newChart.ChartAreas["chart1"].AxisY.MajorGrid.Enabled = false;

            newChart.Legends.Add("legend");
            newChart.Legends["legend"].Enabled = true;
            //newChart.Legends["legend"].LegendStyle = LegendStyle.Table;

            newChart.Titles.Add("title");
            newChart.Titles[0].Name = "title";
            newChart.Titles["title"].Visible = true;
            newChart.Titles["title"].Text = "Capability Assessment Summary Score";
            newChart.Titles["title"].Font = new Font("Arial", 14, FontStyle.Bold);

            newChart.Series.Add("As_Is");
            newChart.Series["As_Is"].ChartArea = "chart1";
            newChart.Series["As_Is"].ChartType = SeriesChartType.Bar;
            newChart.Series["As_Is"].IsValueShownAsLabel = true;
            newChart.Series["As_Is"].IsVisibleInLegend = true;
            newChart.Series["As_Is"].YValueType = ChartValueType.Double;
            newChart.Series.Add("To_Be");
            newChart.Series["To_Be"].ChartArea = "chart1";
            newChart.Series["To_Be"].ChartType = SeriesChartType.Bar;
            newChart.Series["To_Be"].IsValueShownAsLabel = true;
            newChart.Series["To_Be"].IsVisibleInLegend = true;
            newChart.Series["To_Be"].YValueType = ChartValueType.Double;

            int currentCount = current.Count;
            int futureCount = future.Count;
            float currentTotal = 0;
            float futureTotal = 0;
            double temp;

            for (int i = 0; i < currentCount; i++)
            {
                temp = Convert.ToDouble(current[i]);
                decimal tmp = Convert.ToDecimal(temp);
                tmp = Math.Round(tmp, 2);
                temp = (double)tmp;

                newChart.Series["As_Is"].Points.AddXY(name[i], temp);
                currentTotal += current[i];
            }

            for (int i = 0; i < futureCount; i++)
            {
                temp = Convert.ToDouble(future[i]);
                decimal tmp = Convert.ToDecimal(temp);
                tmp = Math.Round(tmp, 2);
                temp = (double)tmp;

                newChart.Series["To_Be"].Points.AddXY(name[i], temp);
                futureTotal += future[i];
            }

            temp = Convert.ToDouble(currentTotal);
            decimal converter = Convert.ToDecimal(temp);
            converter = Math.Round(converter, 2);
            temp = (double)converter;

            newChart.Series["As_Is"].Points.AddXY("Total", temp);

            temp = Convert.ToDouble(futureTotal);
            converter = Convert.ToDecimal(temp);
            converter = Math.Round(converter, 2);
            temp = (double)converter;

            newChart.Series["To_Be"].Points.AddXY("Total", temp);

            newChart.SaveImage(ClientDataControl.Client.FilePath + "/" + newChart.Name + ".jpg", ChartImageFormat.Jpeg);
            newChart.SaveImage(Directory.GetCurrentDirectory() + @"/Charts/" + newChart.Name + ".jpg", ChartImageFormat.Jpeg);
        }
Esempio n. 27
0
 private void SaveImage(System.Windows.Forms.DataVisualization.Charting.Chart chart)
 {
     chart.SaveImage(@"E:\courseWork\CourseProject\CourseWork\CourseWork\pictures\graphic.png", System.Drawing.Imaging.ImageFormat.Png);
 }
Esempio n. 28
0
        public void Start()
        {
            var start = this.FirstDataCol;
            var end = this.LastDataCol;
            var halfWay = (int)Math.Ceiling( end / 2f );
            this.Progress = 0;
            var delta = ( end - start + 1 );
            var individualIncrease = 1f / ( ( ( delta * delta ) + delta ) / 2 );
            if ( this.AlphaSpace )
            {
                string[] headers = null;
                int bestIndex;
                var data = this.LoadData( ref headers, out bestIndex ).ToArray();
                try
                {
                    Parallel.For( 0, delta,
                    delegate(int i)
                    //for(int i = start; i <= end; i++)
                    {
                        System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;
                        for ( int j = i; j < delta; j++ )
                        {
                            using ( Chart chart = new Chart() )
                            {
                                chart.Width = this.Width;
                                chart.Height = this.Height;
                                ChartArea ca;
                                chart.ChartAreas.Add( ca = new ChartArea() );
                                Series ourSeries = new Series();

                                ourSeries.ChartType = SeriesChartType.Point;
                                this.ProcessData( data, bestIndex, ca, ourSeries, i, j );
                                chart.Series.Add( ourSeries );
                                if ( headers != null )
                                {
                                    ca.AxisX.Title = headers[i];
                                    ca.AxisY.Title = headers[j];
                                    chart.SaveImage( String.Format( "{0}-{1}.png", headers[i], headers[j] ), ChartImageFormat.Png );
                                }
                                else
                                {
                                    chart.SaveImage( String.Format( "{0}-{1}.png", i + start, j + start ), ChartImageFormat.Png );
                                }
                            }
                            this.Progress += individualIncrease;
                        }
                    } );
                }
                catch ( AggregateException aggex )
                {
                    if ( aggex != null )
                    {
                        if ( aggex.InnerException != null )
                        {
                            throw new XTMFRuntimeException( aggex.InnerException.Message );
                        }
                        throw new XTMFRuntimeException( "Error trying to save the graph image file!" );
                    }
                }
            }
            else
            {
                try
                {
                    Parallel.For( start, end + 1,
                    delegate(int i)
                    {
                        System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.BelowNormal;
                        for ( int j = i; j <= end; j++ )
                        {
                            using ( Chart chart = new Chart() )
                            {
                                chart.Width = this.Width;
                                chart.Height = this.Height;
                                ChartArea ca;
                                chart.ChartAreas.Add( ca = new ChartArea() );
                                Series ourSeries = new Series();
                                ourSeries.ChartType = SeriesChartType.Point;
                                this.AddData( ca, ourSeries, i, j );
                                chart.Series.Add( ourSeries );
                                chart.SaveImage( String.Format( "{0}-{1}.png", i, j ), ChartImageFormat.Png );
                            }
                            this.Progress += individualIncrease;
                        }
                    } );
                }
                catch ( AggregateException aggex )
                {
                    if ( aggex != null )
                    {
                        if ( aggex.InnerException != null )
                        {
                            throw new XTMFRuntimeException( aggex.InnerException.Message );
                        }
                        throw new XTMFRuntimeException( "Error trying to save the graph image file!" );
                    }
                }
            }
            this.Progress = 1;
        }
        public static Chart chartCreation(ArrayList xaxislist, ArrayList yaxislist)
        {
            try
            {
                var chart = new System.Windows.Forms.DataVisualization.Charting.Chart();
                chart.Size = new Size(700, 400);

                var chartArea = new ChartArea();
                chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
                chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
                chartArea.AxisY.Title           = "Values in (" + UnitValue + ")";
                chartArea.AxisY.TitleFont       = new Font("Trebuchet MS", 20F, System.Drawing.FontStyle.Bold);
                chartArea.BorderWidth           = 600;
                chartArea.AlignmentOrientation  = AreaAlignmentOrientations.Vertical;
                chartArea.AlignmentStyle        = AreaAlignmentStyles.Position;
                chartArea.Area3DStyle.Enable3D  = true;
                chartArea.AxisX.LabelStyle.Font = new Font("Trebuchet MS", 15F, System.Drawing.FontStyle.Bold);
                chartArea.AxisY.LabelStyle.Font = new Font("Trebuchet MS", 15F, System.Drawing.FontStyle.Bold);

                chart.ChartAreas.Add(chartArea);
                //List<Series> Serieslist = new List<Series>();
                Series series = new Series();
                // Series series2 = new Series();
                //Serieslist.Add(series);
                //Serieslist.Add(series2);

                series.Name = "Series1";
                //series.LegendText = "2017";
                //series.Legend = series.LegendText;
                series.LegendText = "2018";

                series.Legend     = series.LegendText;
                series.ChartType  = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), Chartdata.type);
                series.XValueType = ChartValueType.String;
                chart.Series.Add(series);
                chart.Series["Series1"].Points.DataBindXY(xaxislist, yaxislist);


                //series2.Name = "Series2";
                //series2.LegendText = "2017";
                //series.IsVisibleInLegend=true;

                ////series2.LegendText = "2018";
                ////series2.Legend = series.LegendText;
                //series2.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), Chartdata1.type);
                //series2.XValueType = ChartValueType.String;
                //chart.Series.Add(series2);
                //chart.Series["Series2"].Points.DataBindXY(Chartdata1.xvals,Chartdata1.yvals);
                chart.Legends.Add(series.Legend);

                chart.Invalidate();
                chart.SaveImage(@"../../../Image/GraphImageCard.png", ChartImageFormat.Png);
                SortedList.Clear();
                list.Clear();
                UnitValue = string.Empty;
                return(chart);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Esempio n. 30
0
 // グラフの画像を生成します
 private static Image getGraphImage(Object param)
 {
     using (Chart chart = new Chart())
     {
         chart.Width = 800;
         chart.Height = 500;
         chart.Legends.Add(new Legend());
         chart.Legends[0].Title = "スマホ販売台数シェア";
         chart.ChartAreas.Add(new ChartArea());
         {
             Series s = chart.Series.Add("Android");
             s.ChartType = SeriesChartType.Line;
             s.Points.Add(getDataPoint("2010 1Q", 9.6));
             s.Points.Add(getDataPoint("2010 2Q", 17.2));
             s.Points.Add(getDataPoint("2010 3Q", 25.3));
             s.Points.Add(getDataPoint("2010 4Q", 30.5));
             s.Points.Add(getDataPoint("2011 1Q", 36.4));
             s.Points.Add(getDataPoint("2011 2Q", 43.4));
             s.Points.Add(getDataPoint("2011 3Q", 52.5));
             s.Points.Add(getDataPoint("2011 4Q", 50.9));
             s.Points.Add(getDataPoint("2012 1Q", 56.1));
             s.Points.Add(getDataPoint("2012 2Q", 64.1));
             s.Points.Add(getDataPoint("2012 3Q", 72.4));
             s.Points.Add(getDataPoint("2012 4Q", 69.7));
         }
         {
             Series s = chart.Series.Add("iOS");
             s.ChartType = SeriesChartType.Line;
             s.Points.Add(getDataPoint("2010 1Q", 15.3));
             s.Points.Add(getDataPoint("2010 2Q", 14.1));
             s.Points.Add(getDataPoint("2010 3Q", 16.6));
             s.Points.Add(getDataPoint("2010 4Q", 15.8));
             s.Points.Add(getDataPoint("2011 1Q", 16.9));
             s.Points.Add(getDataPoint("2011 2Q", 18.2));
             s.Points.Add(getDataPoint("2011 3Q", 15.0));
             s.Points.Add(getDataPoint("2011 4Q", 23.8));
             s.Points.Add(getDataPoint("2012 1Q", 22.9));
             s.Points.Add(getDataPoint("2012 2Q", 18.8));
             s.Points.Add(getDataPoint("2012 3Q", 13.9));
             s.Points.Add(getDataPoint("2012 4Q", 20.9));
         }
         {
             Series s = chart.Series.Add("Symbian");
             s.ChartType = SeriesChartType.Line;
             s.Points.Add(getDataPoint("2010 1Q", 44.2));
             s.Points.Add(getDataPoint("2010 2Q", 40.9));
             s.Points.Add(getDataPoint("2010 3Q", 36.3));
             s.Points.Add(getDataPoint("2010 4Q", 32.3));
             s.Points.Add(getDataPoint("2011 1Q", 27.7));
             s.Points.Add(getDataPoint("2011 2Q", 22.1));
             s.Points.Add(getDataPoint("2011 3Q", 16.9));
             s.Points.Add(getDataPoint("2011 4Q", 11.7));
             s.Points.Add(getDataPoint("2012 1Q", 8.6));
             s.Points.Add(getDataPoint("2012 2Q", 5.9));
             s.Points.Add(getDataPoint("2012 3Q", 2.6));
             s.Points.Add(getDataPoint("2012 4Q", 1.2));
         }
         {
             Series s = chart.Series.Add("Rim");
             s.ChartType = SeriesChartType.Line;
             s.Points.Add(getDataPoint("2010 1Q", 19.7));
             s.Points.Add(getDataPoint("2010 2Q", 18.7));
             s.Points.Add(getDataPoint("2010 3Q", 15.4));
             s.Points.Add(getDataPoint("2010 4Q", 14.6));
             s.Points.Add(getDataPoint("2011 1Q", 13.0));
             s.Points.Add(getDataPoint("2011 2Q", 11.7));
             s.Points.Add(getDataPoint("2011 3Q", 11.0));
             s.Points.Add(getDataPoint("2011 4Q", 8.8));
             s.Points.Add(getDataPoint("2012 1Q", 6.9));
             s.Points.Add(getDataPoint("2012 2Q", 5.2));
             s.Points.Add(getDataPoint("2012 3Q", 5.3));
             s.Points.Add(getDataPoint("2012 4Q", 3.5));
         }
         MemoryStream ms = new MemoryStream();
         chart.SaveImage(ms, ChartImageFormat.Png);
         return new Bitmap(ms);
     }
 }
Esempio n. 31
0
        private static void CreateOverviewChart(IEnumerable<IBenchmark> benchmarks, IEnumerable<BenchmarkResult> benchmarkResults, string type, long minTime, long maxTime)
        {
            benchmarkResults = benchmarkResults.Where(b => b.BenchmarkInfo.FullName.Contains(type)).ToArray();
            benchmarks = benchmarks.Where(b => b.GetType().FullName.Contains(type)).ToArray();

            Chart chart = new Chart()
            {
                Size = new Size(800, 600),
                Palette = ChartColorPalette.Pastel,
                BorderlineColor = Color.Black,
                BorderlineWidth = 1,
                BorderColor = Color.Black,
                BorderDashStyle = ChartDashStyle.Solid,
            };

            if (minTime == 0)
            {
                chart.Titles.Add("Overview '" + type + "' (Maximum total time: " + maxTime + "ms)");
                type += "_Fast";
            }
            else
            {
                chart.Titles.Add("Overview '" + type + "' (Minimum total time: " + minTime + "ms)");
                type += "_Slow";
            }

            chart.ChartAreas.Add("Default");
            chart.ChartAreas[0].AxisX.IsMarginVisible = false;
            chart.ChartAreas[0].AxisX.Interval = 1;
            chart.Legends.Add(new Legend("Default")
            {
                Docking = Docking.Bottom,
                Alignment = StringAlignment.Center,
                BorderWidth = 1,
                BorderColor = Color.Black
            });

            foreach (var benchmark in benchmarks)
            {
                chart.Series.Add(benchmark.Name);
                chart.Series[benchmark.Name].ChartType = SeriesChartType.StackedBar;
            }

            var containers = benchmarkResults
                .Where(r => r.ContainerInfo.Name != "No")
                .Select(r => r.ContainerInfo)
                .Distinct()
                .Select(c => new
                {
                    Container = c,
                    TotalTime = benchmarkResults.Where(b => b.ContainerInfo.Name == c.Name).Sum(b => b.SingleThreadedResult.Time)
                })
                .Where(r => r.TotalTime.HasValue && r.TotalTime.Value <= maxTime && r.TotalTime.Value >= minTime)
                .OrderByDescending(r => r.TotalTime.Value)
                .Select(r => r.Container)
                .Concat(benchmarkResults.Where(r => r.ContainerInfo.Name == "No").Select(r => r.ContainerInfo).Distinct());

            foreach (var container in containers)
            {
                foreach (var benchmark in benchmarks)
                {
                    var time = benchmarkResults.First(r => r.BenchmarkInfo.Name == benchmark.Name && r.ContainerInfo.Name == container.Name).SingleThreadedResult.Time;

                    chart.Series[benchmark.Name].Points.AddXY(container.Name, time.GetValueOrDefault());
                }
            }

            chart.SaveImage("output\\Overview_" + type + ".png", ChartImageFormat.Png);
        }
Esempio n. 32
0
        void updateChart(Chart chart, int series, Double[] points, bool saveImage, String path)
        {
            if (chart.InvokeRequired)
            {
                chart.Invoke(new updateChartSaveImageDelegate(updateChart), new object[] { chart, series, points, saveImage, path });
            }
            else
            {
                updateChart(chart, series, points);

                if (saveImage)
                {
                    String file = String.Format(filePath + "\\{0}\\{1}.png", path, counter_power++);
                    (new System.IO.FileInfo(file)).Directory.Create();
                    chart.SaveImage(file, ChartImageFormat.Png);
                }

                //for (int j = 0; j < chart.Series.Count; j++)
                //    chart.Series[j].Points.Clear();
            }
        }
Esempio n. 33
0
 private void GenerateChart(string fileName, float[] values, string xAxisName, string yAxisName)
 {
     using (Chart chart = new Chart())
     {
         chart.Width = Width;
         chart.Height = Height;
         using (ChartArea area = new ChartArea("Start Times"))
         {
             using (Series series = new Series())
             {
                 using (series.Points)
                 {
                     series.ChartType = SeriesChartType.Column;
                     for(int i = 0; i < values.Length; i++)
                     {
                         series.Points.Add(new DataPoint(i, values[i]) { AxisLabel = (Time.FromMinutes((60 * 4) + i * MinutesPerBucket)).ToString() });
                     }
                     series.BorderWidth = 1;
                     series.BorderColor = System.Drawing.Color.Black;
                     area.AxisX.Title = xAxisName;// "Start Time";
                     area.AxisY.Title = yAxisName;// "#Episodes";
                     area.AxisX.Interval = 2;
                     chart.Series.Add(series);
                     chart.ChartAreas.Add(area);
                     area.Visible = true;
                     chart.SaveImage(fileName, ChartImageFormat.Png);
                 }
             }
         }
     }
 }
Esempio n. 34
0
 void resetChart(Chart chart, int from, int to, bool saveImage, String path)
 {
     if (chart.InvokeRequired)
     {
         chart.Invoke(new resetChartSaveImageDelegate(resetChart), new object[] { chart, from, to, saveImage, path });
     }
     else
     {
         if (saveImage)
         {
             String file = String.Format(filePath + "\\{0}\\{1}.png", path, counter_day++);
             (new System.IO.FileInfo(file)).Directory.Create();
             chart.SaveImage(file, ChartImageFormat.Png);
         }
         resetChart(chart, from, to);
     }
 }
Esempio n. 35
0
        public static void SaveSummary(IEnumerable<Benchmarks.Benchmark> results, string path, bool cold, bool warm)
        {
            var chart = new Chart
            {
                Size = new Size(800, 400)
            };

            chart.Legends.Add(new Legend { 
                Alignment = StringAlignment.Center,
                Docking = Docking.Bottom,
                Enabled = true,
                IsDockedInsideChartArea = false,
                TableStyle = LegendTableStyle.Wide 
            });

            chart.ChartAreas.Add(new ChartArea
            {
                Position =
                {
                    X = 1,
                    Y = 1,
                    Width = 100,
                    Height = 93
                },
                AxisY =
                {
                    Enabled = AxisEnabled.False,
                    MajorGrid = { Enabled = false }
                },
                AxisX =
                {
                    LabelStyle = { Interval = 1 },
                    LineWidth = 0,
                    LineColor = Color.White,
                    MajorTickMark = { Enabled = false },
                    MajorGrid = { Enabled = false }
                }
            });

            Action<Func<Benchmarks.Benchmark, long>, string, Color> createSeries = (timing, label, color) =>
            {
                var series = new Series
                {
                    XValueMember = "Name",
                    ChartType = SeriesChartType.StackedBar,
                    Color = color,
                    LegendText = label,
                    IsVisibleInLegend = true
                };

                series["PixelPointWidth"] = "10";

                results.OrderBy(x => x.Name).ForEach(x => series.Points.AddXY(
                    "{0} {1}".ToFormat(x.Name, x.Format), timing(x)));

                chart.Series.Add(series);
            };

            if (warm)
            {
                createSeries(y => y.WarmDeserialize + y.WarmParse, "Warm Deserialization", Color.Red);
                createSeries(y => y.WarmSerialize + y.WarmEncode, "Warm Serialization", Color.DarkSalmon);
            }

            if (cold)
            {
                createSeries(y => y.ColdDeserialize + y.ColdParse, "Cold Deserialization", Color.Blue);
                createSeries(y => y.ColdSerialize + y.ColdEncode, "Cold Serialization", Color.LightBlue);
            }

            chart.SaveImage(path, ChartImageFormat.Png);
        }
Esempio n. 36
0
 public void SaveChart(Chart chart, string filename, string extension)
 {
     switch(extension)
     {
         case ".bmp":
             chart.SaveImage(filename, ChartImageFormat.Bmp);
             break;
         case ".emf":
             chart.SaveImage(filename, ChartImageFormat.Emf);
             break;
         case ".emf-dual":
             chart.SaveImage(filename, ChartImageFormat.EmfDual);
             break;
         case ".emf+":
             chart.SaveImage(filename, ChartImageFormat.EmfPlus);
             break;
         case ".gif":
             chart.SaveImage(filename, ChartImageFormat.Gif);
             break;
         case ".jpeg":
             chart.SaveImage(filename, ChartImageFormat.Jpeg);
             break;
         case ".png":
             chart.SaveImage(filename, ChartImageFormat.Png);
             break;
         case ".tiff":
             chart.SaveImage(filename, ChartImageFormat.Tiff);
             break;
     }
 }
Esempio n. 37
0
        private void GenerateChart(string fileName, ConcurrentDictionary<float, List<float>> values)
        {
            using ( Chart chart = new Chart() )
            {
                chart.Width = this.CharWidth;
                chart.Height = this.CharHeight;

                using ( ChartArea area = new ChartArea( "Passenger Distance vs New Driver Distance" ) )
                {
                    using ( Series firstSeries = new Series() )
                    {
                        AddData( values, chart, firstSeries );
                        firstSeries.ChartType = SeriesChartType.Point;
                        area.AxisX.Title = "Driver Distance Traveled (km)";// "Start Time";
                        area.AxisY.Title = "Passenger Distance Traveled (km)";// "#Episodes";
                        area.AxisX.Interval = 2;
                        area.Visible = true;
                        chart.ChartAreas.Add( area );
                        firstSeries.Name = "New Driver Distance";
                        firstSeries.Color = System.Drawing.Color.RoyalBlue;
                        firstSeries.BorderColor = System.Drawing.Color.Black;
                        firstSeries.BorderWidth = 1;
                        using ( Legend legend = new Legend() )
                        {
                            chart.Legends.Add( legend );
                            chart.SaveImage( fileName, ChartImageFormat.Png );
                        }
                    }
                }
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Dumps the Column/Rows determination (based on aspect ratio) Plot.
        /// </summary>
        /// <param name="filename">name of the image file to write to.</param>
        /// <param name="plotThresholds">if set to <c>true</c> plot threshold info.</param>
        private void DumpColRowsPlot(string filename, bool plotThresholds)
        {
            bool detailsPage;
            int nThumbs, nCols, nRows;
            double crossoverThreshold;

            filename = System.IO.Path.GetFileNameWithoutExtension (filename) + ".png";
            if (System.IO.File.Exists (filename))
                {
                Console.Write ("'{0}' already exists. Overwrite (Y/N) [N]?", filename);
                string answer = Console.ReadLine ();
                answer = answer.Trim ().ToLower ();
                if (answer != "y" && answer != "yes")
                    {
                    Console.Write ("Aborting operation.");
                    return;
                    }
                }

            if (_tnSettings.Interval.TotalSeconds > 0)
                {
                detailsPage = true;
                nThumbs = _tnSettings.DetailThumbs;
                nCols = _tnSettings.DetailColumns;
                nRows = _tnSettings.DetailRows;
                crossoverThreshold = _tnSettings.DetailThreshold;
                }
            else
                {
                detailsPage = false;
                nThumbs = _tnSettings.OverviewThumbs;
                nCols = _tnSettings.OverviewColumns;
                nRows = _tnSettings.OverviewRows;
                crossoverThreshold = _tnSettings.OverviewThreshold;
                }

            THelper.Information ("");
            THelper.Information ("Dumping Column/Rows Determination Plot");
            THelper.Information ("Page:             {0}  {1}x{2} ({3:F2}:1)",
                                 detailsPage ? "Detail" : "Overview",
                                 _tnSettings.Width, _tnSettings.Height,
                                 _tnSettings.AspectRatio);
            THelper.Information ("Layout Mode:      {0}", _tnSettings.LayoutMode);
            if (_tnSettings.LayoutMode == ThumbnailSettings.LayoutModes.Auto)
                THelper.Information ("Threshold:        {0:F2}", crossoverThreshold);
            if (_tnSettings.LayoutMode == ThumbnailSettings.LayoutModes.Actual)
                {
                THelper.Information ("Actual:           {1}x{2}", nCols, nRows);
                }
            else
                {
                THelper.Information ("RC Optimization:  {0}", _tnSettings.RCOptimization);
                THelper.Information ("Max RC Opt Steps: {0}", _tnSettings.MaxOptimizationSteps);
                THelper.Information ("Desired:          {0} thumbs", nThumbs);
                THelper.Information ("Minimum:          {0} columns, {1} rows",
                                     _tnSettings.MinColumns, _tnSettings.MinRows);
                }
            THelper.Information ("");

            System.Drawing.Font titleFont =
                new System.Drawing.Font ("Ariel", 24, System.Drawing.FontStyle.Bold);
            System.Drawing.Font subTitleFont =
                new System.Drawing.Font ("Ariel", 13, System.Drawing.FontStyle.Bold);
            System.Drawing.Font axisLabelFont =
                new System.Drawing.Font ("Ariel", 20, System.Drawing.FontStyle.Bold);
            System.Drawing.Font axisFont =
                new System.Drawing.Font ("Ariel", 12, System.Drawing.FontStyle.Bold);
            System.Drawing.Font annotationFont =
                new System.Drawing.Font ("Ariel", 10, System.Drawing.FontStyle.Regular);
            System.Drawing.Font annotationItFont =
                new System.Drawing.Font ("Ariel", 10, System.Drawing.FontStyle.Italic);

            Charting.Chart chart = new Charting.Chart ();
            Charting.ChartArea chartArea = chart.ChartAreas.Add ("Wasted");
            Charting.Legend legend = new Charting.Legend ("Wasted");
            legend.DockedToChartArea = "Wasted";
            legend.Font = axisFont;
            legend.Docking = Charting.Docking.Bottom;
            legend.Alignment = System.Drawing.StringAlignment.Far;
            legend.LegendStyle = Charting.LegendStyle.Column;
            chart.Legends.Add (legend);

            Charting.LabelStyle labelStyle1 = new Charting.LabelStyle();
            labelStyle1.Font = axisFont;
            Charting.LabelStyle labelStyle2 = new Charting.LabelStyle ();
            labelStyle2.Font = axisFont;
            Charting.LabelStyle labelStyle3 = new Charting.LabelStyle ();
            labelStyle3.Font = axisFont;

            chart.BackColor = System.Drawing.Color.Wheat;

            chartArea.BorderWidth = 3;
            chartArea.BorderDashStyle = Charting.ChartDashStyle.Solid;
            //chartArea.BorderColor = System.Drawing.Color.Violet;

            legend.BackColor = System.Drawing.Color.Wheat;

            string titleStr = "Optimum Number of Columns & Rows";
            if (plotThresholds)
                titleStr += "\nUsing % Wasted Thumbnail Width & Height";
            Charting.Title title = chart.Titles.Add (titleStr);
            title.Font = titleFont;
            //subTitle.DockingOffset = -2;

            Charting.TextAnnotation desired = new Charting.TextAnnotation ();
            desired.Font = subTitleFont;
            switch (_tnSettings.LayoutMode)
                {
                case ThumbnailSettings.LayoutModes.Auto:
                    chartArea.BackColor = System.Drawing.Color.Beige;
                    desired.Text = String.Format (
                        "{0} Cols or Rows; Min {1} Cols, {2} Rows; {3} Max Opt Steps",
                        nThumbs, _tnSettings.MinColumns, _tnSettings.MinRows,
                        _tnSettings.MaxOptimizationSteps);
                    break;

                case ThumbnailSettings.LayoutModes.Actual:
                    chartArea.BackColor = System.Drawing.Color.Ivory;
                    desired.Text = String.Format ("{0} Columns and {1} Rows",
                                                  nCols, nRows);
                    break;

                case ThumbnailSettings.LayoutModes.RowPriority:
                    chartArea.BackColor = System.Drawing.Color.Beige;
                    desired.Text = String.Format (
                        "{0} Rows; Min {1} Columns; {2} Max Opt Steps",
                        nThumbs, _tnSettings.MinColumns, _tnSettings.MaxOptimizationSteps);
                    break;

                case ThumbnailSettings.LayoutModes.ColumnPriority:
                    chartArea.BackColor = System.Drawing.Color.AliceBlue;
                    desired.Text = String.Format (
                        "{0} Columns; Min {1} Rows; {2} Max Opt Steps",
                        nThumbs, _tnSettings.MinRows, _tnSettings.MaxOptimizationSteps);
                    break;
                }
            desired.Text += detailsPage ? "\nDetail Page" : "\nOverview Page";
            desired.Text += String.Format ("  {0}x{1} ({2:F2}:1)",
                                           _tnSettings.Width, _tnSettings.Height,
                                           _tnSettings.AspectRatio);

            desired.Alignment = System.Drawing.ContentAlignment.BottomLeft;

            desired.X = 1;
            desired.Y = 95;
            chart.Annotations.Add (desired);

            Charting.TextAnnotation layout = new Charting.TextAnnotation ();
            layout.Font = subTitleFont;
            layout.Text = String.Format("{0} Layout Mode", _tnSettings.LayoutMode);
            if (_tnSettings.LayoutMode != ThumbnailSettings.LayoutModes.Actual)
                layout.Text += String.Format ("\nRow/Column Optimization {0}",
                                              _tnSettings.RCOptimization ? "enabled" : "disabled");
            layout.Alignment = System.Drawing.ContentAlignment.BottomRight;
            layout.X = 77;
            layout.Y = 95;
            chart.Annotations.Add (layout);

            chart.Width = 1280;
            chart.Height = 1024;
            int lineWidth = 5;
            int dotsWidth = 2;

            chartArea.AxisX.Title = "Video Aspect Ratio";
            chartArea.AxisX.TitleFont = axisLabelFont;
            chartArea.AxisX.MajorGrid.Enabled = false;
            chartArea.AxisX.MajorTickMark.Interval = 0.10;
            chartArea.AxisX.Minimum = 1.0;
            chartArea.AxisX.Maximum = 3.0;
            chartArea.AxisX.Interval = 0.5;
            chartArea.AxisX.LineWidth = 3;
            chartArea.AxisX.MajorTickMark.LineWidth = 3;
            chartArea.AxisX.LabelStyle = labelStyle1;
            chartArea.AxisX.LabelStyle.Format = "F2";
            chartArea.AxisX.IsMarginVisible = true;

            if (_tnSettings.LayoutMode == ThumbnailSettings.LayoutModes.Auto &&
                crossoverThreshold > 1.0)
                {
                Charting.StripLine stripLine = new Charting.StripLine ();
                stripLine.IntervalOffset = 0.0;
                stripLine.StripWidth = crossoverThreshold - 1.0;
                stripLine.Interval = 10000;
                stripLine.BackColor = System.Drawing.Color.AliceBlue;
                chartArea.AxisX.StripLines.Add (stripLine);
                }

            chartArea.AxisY.Title = "# of Columns or Rows";
            chartArea.AxisY.TitleFont = axisLabelFont;
            chartArea.AxisY.MajorGrid.Enabled = false;
            chartArea.AxisY.MajorTickMark.Interval = 1.0;
            chartArea.AxisY.LineWidth = 3;
            chartArea.AxisY.MajorTickMark.LineWidth = 3;
            chartArea.AxisY.LabelStyle = labelStyle2;
            //chartArea.AxisY.LabelStyle.IsEndLabelVisible = false;
            chartArea.AxisY.IsMarginVisible = true;

            if (!plotThresholds)
                {
                chartArea.AxisY2.Enabled = Charting.AxisEnabled.True;
                //chartArea.AxisY2.Title = "# of Columns or Rows";
                chartArea.AxisY2.TitleFont = axisLabelFont;
                chartArea.AxisY2.MajorGrid.Enabled = false;
                chartArea.AxisY2.MajorTickMark.Interval = 1.0;
                chartArea.AxisY2.LineWidth = 3;
                chartArea.AxisY2.MajorTickMark.LineWidth = 3;
                chartArea.AxisY2.LabelStyle = labelStyle3;
                //chartArea.AxisY2.LabelStyle.IsEndLabelVisible = false;
                chartArea.AxisY2.IsMarginVisible = true;
                }

            Charting.Series seriesNCols = chart.Series.Add ("# of Columns");
            seriesNCols.ChartType = Charting.SeriesChartType.StepLine;
            seriesNCols.ChartArea = "Wasted";
            seriesNCols.Legend = "Wasted";
            seriesNCols.IsVisibleInLegend = true;
            seriesNCols.BorderWidth = lineWidth;

            Charting.Series seriesNRows = chart.Series.Add ("# of Rows");
            seriesNRows.ChartType = Charting.SeriesChartType.StepLine;
            seriesNRows.ChartArea = "Wasted";
            seriesNRows.Legend = "Wasted";
            seriesNRows.IsVisibleInLegend = true;
            seriesNRows.BorderWidth = lineWidth;

            Charting.Series seriesWW = null;
            Charting.Series seriesWH = null;

            if (plotThresholds)
                {
                chartArea.AxisY2.Title = "% Wasted Thumbnail Width or Height";
                chartArea.AxisY2.TitleFont = axisLabelFont;
                chartArea.AxisY2.MajorGrid.Enabled = false;
                chartArea.AxisY2.LineWidth = 3;
                chartArea.AxisY2.MajorTickMark.LineWidth = 3;
                chartArea.AxisY2.LabelStyle = labelStyle3;
                //chartArea.AxisY2.LabelStyle.IsEndLabelVisible = false;
                chartArea.AxisY2.Maximum = 100.0;

                seriesWW = chart.Series.Add ("%Wasted Width");
                seriesWW.ChartType = Charting.SeriesChartType.Line;
                seriesWW.ChartArea = "Wasted";
                seriesWW.Legend = "Wasted";
                seriesWW.IsVisibleInLegend = true;
                seriesWW.BorderWidth = dotsWidth;
                seriesWW.BorderDashStyle = Charting.ChartDashStyle.Dot;
                seriesWW.YAxisType = Charting.AxisType.Secondary;

                seriesWH = chart.Series.Add ("%Wasted Height");
                seriesWH.ChartType = Charting.SeriesChartType.Line;
                seriesWH.ChartArea = "Wasted";
                seriesWH.Legend = "Wasted";
                seriesWH.IsVisibleInLegend = true;
                seriesWH.BorderWidth = dotsWidth;
                seriesWH.BorderDashStyle = Charting.ChartDashStyle.Dot;
                seriesWH.YAxisType = Charting.AxisType.Secondary;
                }

            ThumbnailCreator creator = new ThumbnailCreator (_tnSettings, null);
            ThumbnailPageLayout container = new ThumbnailPageLayout (_tnSettings);
            ThumbnailPageLayout newContainer;

            double wastedWidth, wastedHeight;
            int extraWidth, extraHeight;
            double extraWidthPercent, extraHeightPercent;

            for (double aspectRatio=1.0; aspectRatio <= 3.0; aspectRatio += 0.01)
                {
                _tnSettings.ThumbAspectRatio = aspectRatio;

                ThumbnailGrid tg = creator.CreateThumbnailGrid(_tnSettings.LayoutMode,
                                                               nThumbs,
                                                               nCols, nRows,
                                                               crossoverThreshold);

                newContainer = tg.Layout;
                container.CalcWasted (_tnSettings, tg, out wastedWidth, out wastedHeight);

                extraWidth = (int) (wastedWidth * tg.ThumbWidth);
                extraHeight = (int) (wastedHeight * tg.ThumbHeight);
                extraWidthPercent = 100.0 * extraWidth / newContainer.Width;
                extraHeightPercent = 100.0 * extraHeight / newContainer.Height;

                THelper.Information (String.Format (
                    "{9,4}x{10,4} ({13,4:F2})  {0,4:F2} {1,2}x{2,2} {3,3:D}x{4,3:D} " +
                    "{5,6:F2}x{6,6:F2} {7,3:D}x{8,3:D}  {11:F1}x{12:F1}",
                    aspectRatio,
                    tg.NColumns, tg.NRows, tg.ThumbWidth, tg.ThumbHeight,
                    wastedWidth, wastedHeight,
                    extraWidth, extraHeight,
                    newContainer.Width, newContainer.Height,
                    extraWidthPercent, extraHeightPercent,
                    newContainer.AspectRatio
                    ));

                int index;

                if (plotThresholds)
                    {
                    index = seriesWW.Points.AddXY (aspectRatio, wastedWidth * 100.0);
                    if (wastedWidth == 0.0)
                        seriesWW.Points[index].IsEmpty = true;

                    index = seriesWH.Points.AddXY (aspectRatio, wastedHeight * 100.0);
                    if (wastedHeight == 0.0)
                        seriesWH.Points[index].IsEmpty = true;
                    }

                seriesNCols.Points.AddXY (aspectRatio, tg.NColumns);
                seriesNRows.Points.AddXY (aspectRatio, tg.NRows);
                }
            chartArea.RecalculateAxesScale ();

            AddARAnnotation (chart, "Fullscreen 4:3\n(1.33)", 1.33, annotationFont, plotThresholds);
            AddARAnnotation (chart, "HD 16:9\n(1.78)", 1.78, annotationFont, plotThresholds);
            AddARAnnotation (chart, "Widescreen\n(1.85)", 1.85, annotationFont, plotThresholds);
            AddARAnnotation (chart, "CinemaScope\n(2.35)", 2.35, annotationFont, plotThresholds);
            AddARAnnotation (chart, "Ultra-Panavision\n(2.76)", 2.76, annotationFont, plotThresholds);

            AddARAnnotation (chart,
                    String.Format ("Layout Threshold\n({0:F2})",
                                crossoverThreshold),
                    crossoverThreshold,
                    _tnSettings.LayoutMode == ThumbnailSettings.LayoutModes.Auto ?
                        annotationFont : annotationItFont,
                    plotThresholds,
                    true);

            if (_tnSettings.RCOptimization && plotThresholds)
                {
                switch (_tnSettings.LayoutMode)
                    {
                    case ThumbnailSettings.LayoutModes.Auto:

                        if (_tnSettings.WidthThreshold == _tnSettings.HeightThreshold)
                            AddThresholdAnnotation (chart,
                                                   String.Format ("Width & Height Threshold\n" +
                                                                 "({0:F2})", _tnSettings.WidthThreshold),
                                                   _tnSettings.WidthThreshold,
                                                   annotationFont);
                        else
                            {
                            AddThresholdAnnotation (chart,
                                                   String.Format ("Width Threshold\n" +
                                                                 "({0:F2})", _tnSettings.WidthThreshold),
                                                   _tnSettings.WidthThreshold,
                                                   annotationFont);
                            AddThresholdAnnotation (chart,
                                                   String.Format ("Height Threshold\n" +
                                                                 "({0:F2})", _tnSettings.HeightThreshold),
                                                   _tnSettings.HeightThreshold,
                                                   annotationFont);
                            }
                        break;

                    case ThumbnailSettings.LayoutModes.RowPriority:
                        AddThresholdAnnotation (chart,
                                               String.Format ("Width Threshold\n" +
                                                             "({0:F2})", _tnSettings.WidthThreshold),
                                               _tnSettings.WidthThreshold,
                                               annotationFont);
                        break;

                    case ThumbnailSettings.LayoutModes.ColumnPriority:
                        AddThresholdAnnotation (chart,
                                               String.Format ("Height Threshold\n" +
                                                             "({0:F2})", _tnSettings.HeightThreshold),
                                               _tnSettings.HeightThreshold,
                                               annotationFont);
                        break;
                    }
                }

            chart.SaveImage (filename, Charting.ChartImageFormat.Png);
            THelper.Information ("'{0}' created.", filename);

            labelStyle1.Dispose ();
            labelStyle2.Dispose ();
            labelStyle3.Dispose ();

            titleFont.Dispose ();
            subTitleFont.Dispose ();
            axisFont.Dispose ();
            annotationFont.Dispose ();
            annotationItFont.Dispose ();
            chart.Dispose ();
        }
Esempio n. 39
0
 public void SaveGraph(string fileName)
 {
     _chart.Invalidate();
     _chart.SaveImage($"{fileName.Replace(':', '-')}.png", ChartImageFormat.Png);
 }
Esempio n. 40
0
        public static void TeamWinChart(string input, Update u)
        {
            //first we need to get the start date / timespan, otherwise default.
            var start = new DateTime(2016, 5, 15);

            if (!String.IsNullOrWhiteSpace(input))
            {
                var args = input.Split(' ');
                int amount = 0;
                if (int.TryParse(args[0], out amount) && args.Length >= 2)
                {
                    //get the interval
                    switch (args[1])
                    {
                        case "weeks":
                        case "week":
                            start = DateTime.Now.AddDays(-(amount * 7));
                            break;
                        case "day":
                        case "days":
                            start = DateTime.Now.AddDays(-amount);
                            break;
                        case "hour":
                        case "hours":
                            start = DateTime.Now.AddHours(-amount);
                            break;
                        default:
                            Bot.Api.SendTextMessage(u.Message.Chat.Id, "Acceptable intervals are: hour(s), day(s), week(s)");
                            break;
                    }
                }

            }

            var query = $@"SELECT x.Players,
             Round((COUNT (x.GameId) * 100.0 / sum (count(x.GameId)) OVER (PARTITION BY Players)), 2) AS Wins
             , X.Winner AS Team
             FROM
             (SELECT DISTINCT [gameid]
             FROM [werewolf].[Dbo].gameplayer gp inner join game g on gp.GameId = g.Id WHERE role = 'Cultist' AND TimeStarted > '{ start.ToString("yyyy-MM-dd HH:mm:ss")}') AS ac
             iNNER JOIN
             (SELECT count (gp.PlayerId) AS Players, gp.GameId, CASE WHEN gm.Winner = 'Wolves' THEN 'Wolf' ELSE gm.Winner END AS Winner
             FROM Game AS gm
             INNER JOIN GamePlayer AS gp ON gp.GameId = gm.Id
             WHERE gm.Winner is not null
             GROUP BY gp.GameId, gm.Winner
             HAVING COUNT (gp.PlayerId)> = 5)
             AS x on ac.gameId = x.gameId
             GROUP BY x.Winner, x.Players
             ORDER BY x.Players, Wins DESC";

            var result = new List<TeamWinResult>();
            using (var db = new WWContext())
            {
                result = db.Database.SqlQuery<TeamWinResult>(query).ToListAsync().Result;
            }

            //we have our results, now chart it...
            //build a datatable
            var dataSet = new DataSet();
            var dt = new DataTable();
            dt.Columns.Add("Players", typeof(int));
            dt.Columns.Add("Wins", typeof(int));
            dt.Columns.Add("Team", typeof(string));
            foreach (var r in result)
            {
                var row = dt.NewRow();
                row[0] = r.Players;
                row[1] = (int)r.Wins;
                row[2] = r.Team;
                dt.Rows.Add(row);
            }

            dataSet.Tables.Add(dt);

            //now build the chart
            Chart chart = new Chart();
            //chart.DataSource = dataSet.Tables[0];
            chart.Width = 1000;
            chart.Height = 400;
            var legend = new Legend();
            //create serie...
            foreach (var team in new[] { "Wolf", "Village", "Tanner", "Cult", "SerialKiller", "Lovers" })
            {
                Series serie1 = new Series();
                //serie1.Label = team;
                serie1.LegendText = team;
                serie1.Name = team;
                switch (team)
                {
                    case "Wolf":
                        serie1.Color = Color.SaddleBrown;
                        break;
                    case "Village":
                        serie1.Color = Color.Green;
                        break;
                    case "Tanner":
                        serie1.Color = Color.Red;
                        break;
                    case "Cult":
                        serie1.Color = Color.Blue;
                        break;
                    case "SerialKiller":
                        serie1.Color = Color.Black;
                        break;
                    case "Lovers":
                        serie1.Color = Color.Pink;
                        break;
                }
                serie1.MarkerBorderWidth = 2;
                serie1.BorderColor = Color.FromArgb(164, 164, 164);
                serie1.ChartType = SeriesChartType.StackedBar100;
                serie1.BorderDashStyle = ChartDashStyle.Solid;
                serie1.BorderWidth = 1;
                //serie1.ShadowColor = Color.FromArgb(128, 128, 128);
                //serie1.ShadowOffset = 1;
                serie1.IsValueShownAsLabel = false;
                serie1.XValueMember = "Players";
                serie1.YValueMembers = "Wins";
                serie1.Font = new Font("Tahoma", 8.0f);
                serie1.BackSecondaryColor = Color.FromArgb(0, 102, 153);
                serie1.LabelForeColor = Color.FromArgb(100, 100, 100);
                //add our values
                var pl = 4;
                foreach (var r in result.Where(x => x.Team == team).OrderBy(x => x.Players))
                {
                    pl++;
                    if (r.Players != pl)
                    {
                        while (pl < r.Players)
                        {
                            serie1.Points.AddXY(pl, 0);
                            pl++;
                        }
                    }
                    serie1.Points.AddXY(r.Players, r.Wins);
                }
                //make sure we filled all the points...
                var top = (int)(serie1.Points.OrderByDescending(x => x.XValue).FirstOrDefault()?.XValue ?? 4);

                if (top < 35)
                {
                    top++;
                    while (top <= 35)
                    {
                        serie1.Points.AddXY(top, 0);
                        top++;
                    }
                }
                //legend.CustomItems.Add(serie1.Color, team);
                chart.Series.Add(serie1);
            }
            //create chartareas...
            ChartArea ca = new ChartArea();
            ca.Name = "ChartArea1";
            ca.BackColor = Color.White;
            ca.BorderColor = Color.FromArgb(26, 59, 105);
            ca.BorderWidth = 0;
            ca.BorderDashStyle = ChartDashStyle.Solid;
            ca.AxisX = new Axis();
            ca.AxisY = new Axis();
            chart.ChartAreas.Add(ca);
            chart.Legends.Add(legend);
            //databind...
            //chart.DataBind();
            //save result

            var path = Path.Combine(Bot.RootDirectory, "myChart.png");
            chart.SaveImage(path, ChartImageFormat.Png);
            SendImage(path, u.Message.Chat.Id);
        }
Esempio n. 41
0
        public void CreateChartAgenda(List<string> name, List<float> current, List<float> future)
        {
            Form formChart = new Form();
            formChart.AutoSize = true;
            formChart.AutoScroll = true;

            formChart.Show();
            Chart newChart = new Chart();

            formChart.Text = "System Agenda Capability Assessment Results";
            newChart.Parent = formChart;

            int maxQuestion = 0;

            if (current.Count < future.Count)
            {
                maxQuestion = future.Count;
            }
            else
            {
                maxQuestion = current.Count;
            }

            newChart.Size = new Size(800, 750);
            newChart.Visible = true;
            newChart.Text = "System Agenda Capability Assessment Results";
            newChart.Name = newChart.Text;
            newChart.ChartAreas.Add("chart1");
            newChart.Palette = ChartColorPalette.BrightPastel;

            newChart.ChartAreas["chart1"].Visible = true;
            newChart.ChartAreas["chart1"].AxisX.MajorGrid.Enabled = false;
            newChart.ChartAreas["chart1"].AxisY.MajorGrid.Enabled = false;
            newChart.ChartAreas["chart1"].AxisY.Title = "Average Capability Score";
            newChart.ChartAreas["chart1"].AxisY.TitleFont = new Font("Microsoft Sans Serif", 12);
            newChart.ChartAreas["chart1"].AxisX.LabelStyle.Format = "#.##";

            newChart.Legends.Add("legend");
            newChart.Legends["legend"].Enabled = true;

            newChart.Titles.Add("title");
            newChart.Titles[0].Name = "title";
            newChart.Titles["title"].Visible = true;
            newChart.Titles["title"].Text = "System Agenda Capability Assessment Results";
            newChart.Titles["title"].Font = new Font("Arial", 14, FontStyle.Bold);

            newChart.Series.Add("As_Is");
            newChart.Series["As_Is"].ChartArea = "chart1";
            newChart.Series["As_Is"].ChartType = SeriesChartType.Bar;
            newChart.Series["As_Is"].IsValueShownAsLabel = true;

            newChart.Series.Add("To_Be");
            newChart.Series["To_Be"].ChartArea = "chart1";
            newChart.Series["To_Be"].ChartType = SeriesChartType.Bar;
            newChart.Series["To_Be"].IsValueShownAsLabel = true;
            newChart.Series["To_Be"].IsVisibleInLegend = true;

            int currentCount = current.Count;
            int futureCount = future.Count;
            double cur;

            for (int i = 0; i < currentCount; i++)
            {
                cur = Convert.ToDouble(current[i]);
                decimal tmp = Convert.ToDecimal(cur);
                tmp = Math.Round(tmp, 2);
                cur = (double)tmp;

                newChart.Series["As_Is"].Points.AddXY(name[i], cur);
            }

            for (int i = 0; i < futureCount; i++)
            {
                cur = Convert.ToDouble(future[i]);
                decimal tmp = Convert.ToDecimal(cur);
                tmp = Math.Round(tmp, 2);
                cur = (double)tmp;

                newChart.Series["To_Be"].Points.AddXY(name[i], cur);
            }

            newChart.SaveImage(ClientDataControl.Client.FilePath + "/" + newChart.Name + ".jpg", ChartImageFormat.Jpeg);
            newChart.SaveImage(Directory.GetCurrentDirectory() + @"/Charts" + newChart.Name + ".jpg", ChartImageFormat.Jpeg);
        }
Esempio n. 42
0
        private void GenerateChart(string fileName, float[] values, float[] otherValues, string xAxisName, string yAxisName)
        {
            using ( Chart chart = new Chart() )
            {
                chart.Width = this.CharWidth;
                chart.Height = this.CharHeight;

                using ( ChartArea area = new ChartArea( "Start Times" ) )
                {
                    using ( Series firstSeries = new Series() )
                    using ( Series secondSeries = new Series() )
                    {
                        AddData( values, chart, firstSeries );
                        AddData( otherValues, chart, secondSeries );
                        firstSeries.ChartType = secondSeries.ChartType = SeriesChartType.Column;
                        area.AxisX.Title = xAxisName;// "Start Time";
                        area.AxisY.Title = yAxisName;// "#Episodes";
                        area.AxisX.Interval = 2;
                        area.Visible = true;
                        chart.ChartAreas.Add( area );
                        firstSeries.Name = FirstSeriesName;
                        secondSeries.Name = SecondSeriesName;
                        firstSeries.Color = System.Drawing.Color.RoyalBlue;
                        firstSeries.BorderColor = System.Drawing.Color.Black;
                        firstSeries.BorderWidth = 1;
                        secondSeries.Color = System.Drawing.Color.Red;
                        secondSeries.BorderColor = System.Drawing.Color.Black;
                        secondSeries.BorderWidth = 1;
                        using ( Legend legend = new Legend() )
                        {
                            chart.Legends.Add( legend );
                            chart.SaveImage( fileName, ChartImageFormat.Png );
                        }
                    }
                }
            }
        }
Esempio n. 43
0
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt = readCSV("C:\\Users\\Vic\\Dropbox\\Data\\3day\\10in_1.csv");
            //dt = readCSV("C:\\Users\\Vic\\Desktop\\ewj.csv");

            //Console.WriteLine( dt.Columns.Count  );
            //Console.WriteLine(dt.Rows.Count);

            Stopwatch timer = new Stopwatch();  //碼表
            int Training_count = 20000;         //訓練資料的使用長度
            int MatchCount = 70;               //KNN裡的K值的大小
            //KDTree<double> _tree = new KDTree<double>(11);
            KDTree<double> _tree2 = new KDTree<double>(11);

            List<double> trade_list = new List<double>();
            List<double> EC1 = new List<double>();

            StreamWriter file = new System.IO.StreamWriter("C:\\001.csv");  //輸出觀察用的Log檔案
            double Long_Threshold = 0.1;
            double Short_Threshold = -0.2;
            int L_vote = 0;
            int S_vote = 0;
            double nodes_avg=0;
            double totalprofit;
            double mdd;

            timer.Reset();
            timer.Start();

            List<HistoricalStock>  data = HistoricalStockDownloader.DownloadData("SPY", 1962);
            Console.WriteLine("Get SPY from Yahoo : {0}ticks ,{1}msec", timer.ElapsedTicks, timer.ElapsedMilliseconds);
            timer.Reset();
            timer.Start();

            //把上面的資料想辦法用來計算 coodrs

            PatternFinder PF = new PatternFinder(data);

            for (int i = 10; i < 1000; i++)
            {
                PF.CalcHistorical();   //<<<<<<<-------------------------- 卡關 _tree.Add 傳入參數跟型態都沒問題,但是就是沒法加入節點
                PF.CurrentBar++;

                Console.WriteLine("CurrentBar={0} ,DateT={1},E={2} ",PF.CurrentBar,PF.Date_Time[i],PF.Expectancy  );

                //Console.Write(PF.Date_Time[i].ToShortDateString()  +","  );
                //Console.WriteLine("data.Count:" + data.Count() );
            }

            Console.WriteLine("Tree Nodes Count:"+PF._tree.Count    );
            Console.WriteLine("共使用記憶體: {0}MB", Environment.WorkingSet / 1000000);

            Console.ReadLine();
            return;  // 使用返回  中斷程式,直到上面的做好

            // 舊的流程
            for (int CurrentBar = 1; CurrentBar < dt.Rows.Count; CurrentBar++)
            {

                DataRow row = dt.Rows[CurrentBar];
                Double[] coords = new double[11];

                    //Get 11 dimentions into Array
                    for (int i2 = 4; i2 < row.ItemArray.Count() ; i2++)
                    {   coords[i2-4] = Convert.ToDouble(row.ItemArray[4])  ;   }

                    if (CurrentBar <= Training_count)
                    {   //將陣列做為index值,報酬率作為value存入KD二元樹
                        //_tree.Add(coords, Convert.ToDouble(row.ItemArray[3]));
                        //_tree2.Add(coords, Convert.ToDouble(row.ItemArray[3]));

                    }
                    else   //CurrentBar大於Training_count以後,開始Testing運算,模擬交易開始
                    {
                        L_vote = 0;
                        S_vote = 0;
                        Long_Threshold = 0.3;
                        Short_Threshold = -0.3;

                        //string s = SiteHelper.Serialize(_tree2);

                        for (int i3 = 1; i3 <= 7; i3++ )
                        {
                            //nodes_avg = _tree.Nearest(coords, MatchCount*i3  ).Average(x => x.Node.Value);
                            if (nodes_avg >= Long_Threshold) { L_vote += 1; }
                            if (nodes_avg <= Short_Threshold) { S_vote += 1; }
                        }

                        //型態比對找出群組的平均值以後 如果大於 Long_Threshold 的投票數就模擬買進
                        if (L_vote>=6 )
                        {

                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) /100 * 1000000);
                            EC1.Add(trade_list.Sum());

                            string s_out = string.Format("{0},{1},{2},{3},{4}", Convert.ToDouble(row.ItemArray[1]), row.ItemArray[2], trade_list.Last(), EC1.Last(), Math.Round( nodes_avg,2) );

                            /*
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last() );
                            Console.WriteLine(" "+ EC1.Last() );
                            */
                            Console.WriteLine(s_out);

                            /*
                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(trade_list.Last()+"," );
                            file.WriteLine(EC1.Last()  );
                            */

                            file.WriteLine(s_out);

                        }

                        /*  Take Short trades
                        if (S_vote >= 6)
                        {
                            trade_list.Add(Convert.ToDouble(row.ItemArray[3]) / 100 * -1000000  );
                            EC1.Add(trade_list.Sum());
                            //trade_list.Add(Convert.ToDouble(row.ItemArray[1]) );
                            Console.Write("" + Convert.ToDouble(row.ItemArray[1]) + " ");
                            Console.Write("" + row.ItemArray[2] + " ");
                            Console.Write(" " + trade_list.Last());
                            Console.WriteLine(" " + EC1.Last());

                            file.Write(Convert.ToDouble(row.ItemArray[1]) + ",");
                            file.Write(row.ItemArray[2] + ",");
                            file.Write(" " + trade_list.Last());
                            file.WriteLine(" " + EC1.Last());

                        }
                        */

                        /*
                        //Console.Write(CurrentBar );
                        Console.Write(row.ItemArray[1]);
                        Console.Write(" Forecast is:" + _tree.Nearest(coords, MatchCount).Average(x => x.Node.Value));
                        Console.WriteLine(" True Return is:" + Convert.ToDouble(row.ItemArray[3]) + "  ");
                        */

                        //Console.WriteLine(row.ItemArray.Count());
                    }
            }

            file.Close();

            totalprofit = trade_list.Sum();
            mdd = MaxDrawdown(EC1.ToArray());

            Console.WriteLine();
            Console.WriteLine("trade_list Profit: " + totalprofit );
            Console.WriteLine("MDD: " + mdd);
            Console.WriteLine("Profit/MDD: " +  Math.Round( totalprofit/mdd ,2)  );
            Console.WriteLine("Trades: " + trade_list.Count );
            Console.WriteLine("EC1 Count: " + EC1.Count);
            Console.WriteLine( "Total Rows: "+ dt.Rows.Count );
            //Console.WriteLine( "Tree Count(Training Count): " + _tree.Count() );

            /*
            //KDTree<double> _tree2 =
            KDTreeNodeCollection<double>  kd_nodes;
            Dictionary<KDTreeNodeCollection<double>  , int>   Dict= new Dictionary<KDTreeNodeCollection<double>,int>()  ;

            foreach (var nodes in _tree2 ){

            kd_nodes=  _tree.Nearest(nodes.Position , MatchCount) ;

            //Console.WriteLine(nodes.Position +"  "  );
            //Console.WriteLine(nodes.GetType() );

                if (Dict.ContainsKey( kd_nodes )  )
                {

                }
                else
                {
                    Dict.Add(kd_nodes, 1);

                }

            }

            Console.WriteLine("Dict count:" + Dict.Count );
             */

            // EC1 畫圖輸出來觀察 create the chart
            var chart = new Chart();
            chart.Size = new Size(600, 600);

            var chartArea = new ChartArea();
            //chartArea.AxisX.LabelStyle.Format = "dd/MMM\nhh:mm";
            chartArea.AxisX.Interval = 1;
            chartArea.AxisX.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisY.MajorGrid.LineColor = Color.LightGray;
            chartArea.AxisX.LabelStyle.Font = new Font("Consolas", 8);
            chartArea.AxisY.LabelStyle.Font = new Font("Consolas", 8);
            chart.ChartAreas.Add(chartArea);

            var series = new Series();
            series.Name = "Series1";
            series.ChartType = SeriesChartType.FastLine;
            series.XValueType = ChartValueType.DateTime;
            chart.Series.Add(series);

            /*
            foreach (int i4 in EC1) {
            series.Points.AddY(i4  );
            } */

            foreach (HistoricalStock stock in data)
            {
                //Console.WriteLine(string.Format("Date={0} High={1} Low={2} Open={3} Close={4}", stock.Date.ToShortDateString() , stock.High, stock.Low, stock.Open, stock.Close)  );
                //Console.WriteLine(stock.Date.ToShortDateString()+",");

                series.Points.AddXY( stock.Date ,stock.Close );
            }

            // draw!
            chart.Invalidate();

            // write out a file
            chart.SaveImage("c:\\chart.png", ChartImageFormat.Png);

            Process.Start(@"c:\\chart.png");

            Console.ReadLine();
        }
        private string GeneratePieChart(List <ColumnValueCounter> columnValueCounters, string filename, DocumentManipulation.TextReplacementOptions options)
        {
            Chart chart = new Chart();
            //Create a new series list to pass into InitializeChartSeriesXValues. Will be converted to a single series later.
            List <Series> allSeries = new List <Series>();

            if (columnValueCounters.Count == 0)
            {
                throw new Exception("No data imported. Invalid CSV data format");
            }
            else if (columnValueCounters.Count > 1)
            {
                throw new Exception("Invalid Pie Chart Schema");
            }
            //Get the xValues that will be represented in the pie chart. These are the row values within the column that is being made into a pie chart.
            string[] xValues = InitializeChartSeriesXValues(allSeries, columnValueCounters, chart);
            //Convert back to a single series
            Series pieSeries = allSeries[0];
            int    totalNumUniqueRowValues = 0;

            for (int i = 0; i < columnValueCounters.Count; i++)
            {
                List <UniqueRowValue> uniqueRowValues = columnValueCounters[i].uniqueRowValues;
                float[] yValues = new float[uniqueRowValues.Count];

                //for every unique row value in the column
                for (int j = 0; j < uniqueRowValues.Count; j++)
                {
                    int k;
                    //Add y values based on which mode the graph is in
                    if (options.isCount)
                    {
                        //Add a point to the pie chart corresponding to the number of this specific unique row value occurences.
                        pieSeries.Points.AddXY(xValues[j], uniqueRowValues[j].count);
                    }
                    else if (options.isPercentage)
                    {
                        totalNumUniqueRowValues = 0;
                        //get the total number of values in the column to use as a divisor
                        for (k = 0; k < uniqueRowValues.Count; k++)
                        {
                            totalNumUniqueRowValues += uniqueRowValues[k].count;
                        }
                        //Add a point corresponding to the percentage of this specific unique row value relative to the total number of values. Includes unknown rows.
                        pieSeries.Points.AddXY(xValues[j], Math.Round((((float)uniqueRowValues[j].count) / ((float)totalNumUniqueRowValues + columnValueCounters[0].unknownCount)) * 100, 1));
                    }
                }
            }

            //Reorders the data to be in accordance with the user specified order of the data.
            ApplyItemOrder(pieSeries);

            //Add another column that represents the number of "Unknown" responses (rows that were blank in that column).
            if (options.isCount)
            {
                pieSeries.Points.AddXY("Unknown", columnValueCounters[0].unknownCount);
            }
            else if (options.isPercentage)
            {
                pieSeries.Points.AddXY("Unknown", Math.Round((((float)columnValueCounters[0].unknownCount) / ((float)totalNumUniqueRowValues + columnValueCounters[0].unknownCount)) * 100, 1));
            }
            //Apply all of the customized settings for the series and add it to the chart.
            FinalizePieChartSeries(chart, pieSeries, columnValueCounters, options);
            //Apply all of the customized settings for the chart itself.
            ApplyCustomChartOptions(chart, options, columnValueCounters);

            try {
                chart.SaveImage(filename, ChartImageFormat.Png);
            }
            catch (Exception) {
                throw new Exception("Failed to create graph image");
            }
            return(filename);
        }