예제 #1
0
        private static ScatterSeries CreateRandomScatterSeries(Random r, int n, string title, MarkerType markerType)
        {
            var s1 = new ScatterSeries {
                Title = title, MarkerType = markerType, MarkerStroke = OxyColors.Black, MarkerStrokeThickness = 1.0
            };

            for (int i = 0; i < n; i++)
            {
                double x = r.NextDouble() * 10;
                double y = r.NextDouble() * 10;
                var    p = new ScatterPoint(x, y);
                s1.Points.Add(p);
            }

            return(s1);
        }
예제 #2
0
        private static List <ScatterPoint> CreateRandomScatterPoints(int n)
        {
            var r = new Random(12345);

            var points = new List <ScatterPoint>();

            for (int i = 0; i < n; i++)
            {
                double x = r.NextDouble() * 10;
                double y = r.NextDouble() * 10;
                var    p = new ScatterPoint(x, y);
                points.Add(p);
            }

            return(points);
        }
예제 #3
0
        public static ScatterSeries ScatterSeries(double[] x, double[] y, System.Drawing.Color markerColor, MarkerType mType)
        {
            var scatterSeries = new ScatterSeries();

            // var scatter = new List<DataPoint>();

            for (int i = 0; i < x.Length; i++)
            {
                var b = new ScatterPoint(x[i], y[i], 4.0, 1);

                scatterSeries.Points.Add(b);
            }
            scatterSeries.MarkerFill = OxyColor.FromRgb(markerColor.R, markerColor.G, markerColor.B);
            scatterSeries.MarkerType = mType;
            return(scatterSeries);
        }
예제 #4
0
        private void OnGeneratePoints()
        {
            try
            {
                const int countOfPoints = 500;

                if (FirstClassScatterSeries.Points.Count != 0)
                {
                    FirstClassScatterSeries.Points.Clear();
                }

                if (SecondClassScatterSeries.Points.Count != 0)
                {
                    SecondClassScatterSeries.Points.Clear();
                }

                var generator = new Generator();

                Parallel.Invoke(() =>
                {
                    FirstClass = generator.GenerateClassByGaussian(countOfPoints, FirstClassExpectationX, FirstClassExpectationY, CorrelationMatrix);
                    for (var i = 0; i < countOfPoints; i++)
                    {
                        var newPoint = new ScatterPoint(FirstClass.Vector[i, 0],
                                                        FirstClass.Vector[i, 1]);
                        FirstClassScatterSeries.Points.Add(newPoint);
                    }
                },
                                () =>
                {
                    SecondClass = generator.GenerateClassByGaussian(countOfPoints, SecondClassExpectationX, SecondClassExpectationY, CorrelationMatrix);
                    for (var i = 0; i < countOfPoints; i++)
                    {
                        var newPoint = new ScatterPoint(SecondClass.Vector[i, 0],
                                                        SecondClass.Vector[i, 1]);
                        SecondClassScatterSeries.Points.Add(newPoint);
                    }
                });

                PlotModel.InvalidatePlot(true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
예제 #5
0
        private void UpdatePaymentPlot(DayIncomeManager dayIncomeManager, IEnumerable <PaymentObject> payments)
        {
            var points = new List <ScatterPoint>();

            foreach (var payment in payments)
            {
                var Date           = UnixTimeHelper.UnixTimeToDateTime(payment.time);
                var dayIncomeValue = dayIncomeManager.GetRow((long)UnixTimeHelper.Convert(Date)).value;
                if (dayIncomeValue > 0)
                {
                    var sp = new ScatterPoint(DateTimeAxis.ToDouble(Date), dayIncomeValue);
                    points.Add(sp);
                }
            }

            BasePlot.LoadPayment(points.ToArray());
        }
예제 #6
0
        private void AddBooksAndPagesScatterSeries(PlotModel newPlot)
        {
            ScatterSeries pointsSeries;

            OxyPlotUtilities.CreateScatterPointSeries(out pointsSeries,
                                                      ChartAxisKeys.LongitudeKey, ChartAxisKeys.LatitudeKey, "Countries");

            foreach (var authorCountry in _mainModel.AuthorCountries)
            {
                var name    = authorCountry.Country;
                var country = _mainModel.WorldCountries.Where(w => w.Country == name).FirstOrDefault();
                if (country != null)
                {
                    var pointSize = authorCountry.TotalBooksReadFromCountry;
                    if (pointSize < 5)
                    {
                        pointSize = 5;
                    }

                    ScatterPoint point =
                        new ScatterPoint(country.Longitude, country.Latitude, pointSize,
                                         authorCountry.TotalPagesReadFromCountry)
                    {
                        Tag = name
                    };
                    pointsSeries.Points.Add(point);
                }
            }

            pointsSeries.TrackerFormatString = "{Tag}\nLat/Long ( {4:0.###} ,{2:0.###} ) \nTotalPages {6}";
            newPlot.Series.Add(pointsSeries);

            List <OxyColor> colors = new List <OxyColor>();

            foreach (var color in OxyPalettes.Jet(200).Colors)
            {
                var faintColor = OxyColor.FromArgb(128, color.R, color.G, color.B);
                colors.Add(faintColor);
            }

            OxyPalette faintPalette = new OxyPalette(colors);

            newPlot.Axes.Add(new LinearColorAxis {
                Position = AxisPosition.Right, Palette = faintPalette, Title = "Total Pages"
            });
        }
예제 #7
0
        public void deletePoint(ScreenPoint screenPoint)
        {
            DataPoint    temp_point = Axis.InverseTransform(screenPoint, this.Xaxis, this.Yaxis);
            ScatterPoint point      = new ScatterPoint(temp_point.X, temp_point.Y);

            foreach (ScatterPoint Point in PointsContainer.SelectedPoints.Points)
            {
                if (this.AreClose(point, Point))
                {
                    temp_point = new DataPoint(Point.X, Point.Y);
                    point      = Point;
                    break;
                }
            }
            PointsContainer.PlotPoints.Points.Remove(temp_point);
            PointsContainer.SelectedPoints.Points.Remove(point);
        }
예제 #8
0
        // event handler
        void plotModel_MouseDown(object sender, OxyPlot.OxyMouseDownEventArgs e)
        {
            if (DivergenceConvergencePlot.Series.Any(p => p.GetType() == typeof(OxyPlot.Wpf.LineSeries)))
            {
                //  int l = DivergenceConvergencePlot.Series.Count;
                var list = DivergenceConvergencePlot.Series.Where(p => p.GetType() != typeof(OxyPlot.Wpf.LineSeries)).ToList();

                DivergenceConvergencePlot.Series.Clear();
                list.ForEach(p => DivergenceConvergencePlot.Series.Add(p));

                DivergenceConvergencePlot.InvalidatePlot();
            }

            try
            {
                ScatterPoint res = (ScatterPoint)e.HitTestResult.Item;

                if (res != null)
                {
                    string ID = res.Tag.ToString();

                    OxyPlot.Wpf.LineSeries tempseries = new OxyPlot.Wpf.LineSeries();
                    List <DataPoint>       points     = new List <DataPoint>();

                    //find all series with the ID
                    foreach (OxyPlot.Wpf.ScatterSeries series in DivergenceConvergencePlot.Series)
                    {
                        if (series.Tag.ToString() == ID)
                        {
                            ScatterPoint point = (ScatterPoint)series.Items[0];

                            points.Add(new DataPoint(point.X, point.Y));
                            //contains single point
                        }
                    }

                    tempseries.ItemsSource = points;
                    DivergenceConvergencePlot.Series.Add(tempseries);

                    DivergenceConvergencePlot.InvalidatePlot();
                }
            }
            catch (Exception ex)
            { }
        }
예제 #9
0
        // Алгоритм поиска точек внутри многоугольника (во время выделения области)
        private static bool IsPointInPolygon(List <DataPoint> polygon, ScatterPoint point_to_check)
        {
            bool result = false;
            int  j      = polygon.Count() - 1;

            for (int i = 0; i < polygon.Count(); i++)
            {
                if (polygon[i].Y < point_to_check.Y && polygon[j].Y >= point_to_check.Y || polygon[j].Y < point_to_check.Y && polygon[i].Y >= point_to_check.Y)
                {
                    if (polygon[i].X + (point_to_check.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < point_to_check.X)
                    {
                        result = !result;
                    }
                }
                j = i;
            }
            return(result);
        }
예제 #10
0
        /// <summary>
        /// DispatcherTimerで実行するポイント追加メソッド
        /// UIスレッドで実行される
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MovingPoint(object sender, EventArgs e)
        {
            double mag = 50.0 + 40.0 * Math.Sin(ang2);
            double ang = ang1;
            var    p   = new ScatterPoint(mag, ang);

            ScatterPointsLive.Add(p);
            ang1 += dA1;
            ang2 += dA2;

            frameCount++;
            if (watch.ElapsedMilliseconds > 1000 && frameCount > 1)
            {
                PointAddRate = string.Format("PointAddRate {0:#.}", this.frameCount / (this.watch.ElapsedMilliseconds * 0.001));
                frameCount   = 0;
                watch.Restart();
            }
        }
예제 #11
0
        private void Diagram(HashSet <HashSet <Regions> > allClusters) // построение диаграммы
        {
            cartesianChart1.AxisX.Clear();
            cartesianChart1.AxisX.Add(new Axis()
            {
                Title     = "X-attribute",
                Separator = new Separator
                {
                    StrokeThickness = 1,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(new double[] { 5 }),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(64, 79, 86))
                }
            });
            cartesianChart1.AxisY.Clear();
            cartesianChart1.AxisY.Add(new Axis()
            {
                Title     = "Y-attribute",
                Separator = new Separator
                {
                    StrokeThickness = 1.5,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(new double[] { 4 }),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(64, 79, 86))
                }
            });

            SeriesCollection seriesViews = new SeriesCollection();

            for (int i = 0; i < allClusters.Count; i++)
            {
                ChartValues <ScatterPoint> points = new ChartValues <ScatterPoint>();

                for (int j = 0; j < allClusters.ElementAt(i).Count; j++)
                {
                    ScatterPoint point = new ScatterPoint(allClusters.ElementAt(i).ElementAt(j).firstAttribute,
                                                          allClusters.ElementAt(i).ElementAt(j).secondAttribute);
                    points.Add(point);
                }

                ScatterSeries series = new ScatterSeries();
                series.Values = points;
                seriesViews.Add(series);
                cartesianChart1.Series = seriesViews;
            }
        }
예제 #12
0
        private void PlotData(double[,] data)
        {
            pointData = data;
            var plotModel = new PlotModel();

            plotModel.Title = "Data";

            var scatterSeries = new ScatterSeries();

            scatterSeries.MarkerType = MarkerType.Circle;

            for (int row = 0; row < data.GetLength(0); row++)
            {
                var scatterPoint = new ScatterPoint(data[row, 0], data[row, 1]);
                scatterSeries.Points.Add(scatterPoint);
            }

            plotModel.Series.Add(scatterSeries);

            PlotModel = plotModel;
        }
예제 #13
0
        private void dataGridMassSpectra_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Dictionary <string, object> tableValues = PatternTools.pTools.AnonymousToDictionary(dataGridMassSpectra.SelectedItem);
            int scanNumber = (int)tableValues["ScanNumber"];

            ShowSpectrum(scanNumber);

            //Select the dot in the MS2 viewer
            ScatterSeries ss            = (ScatterSeries)MyPlotMS2disposition.Model.Series[0];
            ScatterPoint  point         = ss.Points.Find(a => (int)a.Tag == scanNumber);
            int           indexToSelect = ss.Points.IndexOf(point);

            bool isSelected = ss.IsItemSelected(indexToSelect);

            if (!isSelected)
            {
                MyPlotMS2disposition.Model.Series[0].SelectItem(indexToSelect);
                ss.SelectItem(indexToSelect);
                MyPlotMS2disposition.Model.InvalidatePlot(false);
            }
        }
예제 #14
0
        public ScatterPlot(double[] x_values, double[] y_values)
        {
            if (x_values.Length != y_values.Length)
            {
                throw new Exception("Arrays must be of equal length");
            }

            this.PlotModel = new PlotModel {
                Title = "ScatterSeries"
            };
            ScatterSeries scatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle
            };

            for (int index = 0; index < x_values.Length; index++)
            {
                ScatterPoint point = new ScatterPoint(x_values[index], y_values[index], 5, 5, OxyColors.Black);
                scatterSeries.Points.Add(point);
            }
            this.PlotModel.Series.Add(scatterSeries);
            //this.PlotModel.Axes.Add(new LinearColorAxis { Position = AxisPosition.Right, Palette = OxyPalettes.Jet(200) });
        }
예제 #15
0
        public void OpenPosition(int candleIndex, double openPrice, bool isShort)
        {
            if (this.OpenPrice.HasValue)
            {
                throw new InvalidOperationException("can't open position if its already opened");
            }
            this.IsShort   = isShort;
            this.OpenPrice = openPrice;

            var newPoint        = new DataPoint(candleIndex - 0.25, openPrice);
            var newPointScatter = new ScatterPoint(candleIndex - 0.25, openPrice);

            mainSeries.Points.Add(newPoint);
            openPositionsCirclesSeries.Points.Add(newPointScatter);
            if (isShort)
            {
                openPositionsDownShapesSeries.Points.Add(newPointScatter);
            }
            else
            {
                openPositionsUpShapesSeries.Points.Add(newPointScatter);
            }
        }
        public static PlotModel RandomWithFit()
        {
            const int n     = 20;
            var       model = new PlotModel {
                Title = string.Format("Random data (n={0})", n)
            };
            var l = new Legend
            {
                LegendPosition = LegendPosition.LeftTop
            };

            model.Legends.Add(l);

            var s1 = new ScatterSeries {
                Title = "Measurements"
            };
            var    random = new Random(7);
            double x      = 0;
            double y      = 0;

            for (int i = 0; i < n; i++)
            {
                x += 2 + (random.NextDouble() * 10);
                y += 1 + random.NextDouble();
                var p = new ScatterPoint(x, y);
                s1.Points.Add(p);
            }

            model.Series.Add(s1);
            double a, b;

            LeastSquaresFit(s1.Points, out a, out b);
            model.Annotations.Add(new LineAnnotation {
                Slope = a, Intercept = b, Text = "Least squares fit"
            });
            return(model);
        }
예제 #17
0
        private void PlotClusters(int[][] clusters)
        {
            var plotModel = new PlotModel();

            plotModel.Title = "Clusters";

            for (int cluster = 0; cluster < clusters.GetLength(0); cluster++)
            {
                var scatterSeries = new ScatterSeries();
                scatterSeries.MarkerType = MarkerType.Circle;

                var clusterPoints = clusters[cluster];
                for (int p = 0; p < clusterPoints.Length; p++)
                {
                    var dataPointIndex = clusterPoints[p];

                    var scatterPoint = new ScatterPoint(pointData[dataPointIndex, 0], pointData[dataPointIndex, 1], 5, cluster);
                    scatterSeries.Points.Add(scatterPoint);
                }
                plotModel.Series.Add(scatterSeries);
            }

            PlotModel = plotModel;
        }
예제 #18
0
        public void deleteProject(ScatterPoint oldBubble, Tuple <double, double> t, Project project)
        {
            BubbleLabels.Remove(t);

            if (!BubbleList.ContainsKey(t))
            {
                int indexToDelete = -1;

                for (int i = 0; i < hiddenBubbles[project.projectCategory].Count; i++)
                {
                    Project hiddenProject = hiddenBubbles[project.projectCategory][i];

                    if (hiddenProject.pName.Equals(project.pName))
                    {
                        indexToDelete = i;
                    }
                }

                if (indexToDelete != -1)
                {
                    hiddenBubbles[project.projectCategory].RemoveAt(indexToDelete);
                }

                return;
            }

            if (BubbleList[t].Count == 1)
            {
                BubbleList.Remove(t);
            }
            else
            {
                string newLabel = "Project: ";

                int indexToRemove = 0;

                for (int i = 0; i < BubbleList[t].Count; i++)
                {
                    Project bubble = (Project)BubbleList[t][i];

                    if (bubble.pName == project.pName)
                    {
                        indexToRemove = i;
                    }
                    else
                    {
                        if (newLabel.Equals("Project: "))
                        {
                            for (int j = 0; j < JSONList.Count; j++)
                            {
                                if (JSONList[j].pName.Equals(bubble.pName))
                                {
                                    newLabel = newLabel + (j + 1);
                                }
                            }
                        }
                        else
                        {
                            string labelToAdd = "0";

                            for (int j = 0; j < JSONList.Count; j++)
                            {
                                if (JSONList[j].pName.Equals(bubble.pName))
                                {
                                    labelToAdd = (j + 1).ToString();
                                }
                            }

                            if (((newLabel.ToCharArray().Count(c => c == ',')) + 1) == 3 || (newLabel.ToCharArray().Count(c => c == ',')) == 6)
                            {
                                newLabel = newLabel + ", " + Environment.NewLine + "\t" + labelToAdd;
                            }
                            else
                            {
                                newLabel = newLabel + ", " + labelToAdd;
                            }
                        }
                    }
                }

                BubbleList[t].RemoveAt(indexToRemove);

                BubbleLabels.Add(t, newLabel);
            }

            foreach (var series in SeriesCollection)
            {
                if (series.Title.Equals(project.projectCategory))
                {
                    for (int i = 0; i < series.Values.Count; i++)
                    {
                        ScatterPoint seriesValue = (ScatterPoint)series.Values[i];

                        if (seriesValue.X == oldBubble.X && seriesValue.Y == oldBubble.Y && seriesValue.Weight == oldBubble.Weight)
                        {
                            series.Values.RemoveAt(i);
                        }
                    }
                }
            }
        }
        private void AddLastTenLatLongWithTimeScatterSeries(PlotModel newPlot)
        {
            ScatterSeries pointsSeries;

            OxyPlotUtilities.CreateScatterPointSeries(out pointsSeries,
                                                      ChartAxisKeys.LongitudeKey, ChartAxisKeys.LatitudeKey, "Last Ten Books With Time");


            LineSeries overallSeries;

            OxyPlotUtilities.CreateLineSeries(out overallSeries, ChartAxisKeys.LongitudeKey, ChartAxisKeys.LatitudeKey, "Overall", 0);
            var faintColorBlue = OxyColor.FromArgb(80, OxyColors.Blue.R, OxyColors.Blue.G, OxyColors.Blue.B);

            overallSeries.Color           = faintColorBlue;
            overallSeries.StrokeThickness = 2;

            LineSeries lastTenSeries;

            OxyPlotUtilities.CreateLineSeries(out lastTenSeries, ChartAxisKeys.LongitudeKey, ChartAxisKeys.LatitudeKey, "Last 10", 0);
            var faintColorRed = OxyColor.FromArgb(80, OxyColors.Red.R, OxyColors.Red.G, OxyColors.Red.B);

            lastTenSeries.Color           = faintColorRed;
            lastTenSeries.StrokeThickness = 2;

            foreach (var delta in _mainModel.BookLocationDeltas)
            {
                var pointSize = 5;

                PolygonPoint latLong =
                    new PolygonPoint()
                {
                    Latitude = delta.AverageLatitudeLastTen, Longitude = delta.AverageLongitudeLastTen
                };
                double x, y;
                latLong.GetCoordinates(out x, out y);

                lastTenSeries.Points.Add(new DataPoint(x, y));

                ScatterPoint point =
                    new ScatterPoint(x, y, pointSize, delta.DaysSinceStart)
                {
                    Tag = delta.Date.ToString("ddd d MMM yyy")
                };
                pointsSeries.Points.Add(point);

                latLong =
                    new PolygonPoint()
                {
                    Latitude = delta.AverageLatitude, Longitude = delta.AverageLongitude
                };
                latLong.GetCoordinates(out x, out y);

                overallSeries.Points.Add(new DataPoint(x, y));
            }

            // don't draw these as renders the pic unusable
            //newPlot.Series.Add(lastTenSeries);
            //newPlot.Series.Add(overallSeries);

            pointsSeries.RenderInLegend      = false;
            pointsSeries.TrackerFormatString = "{Tag}\nLat/Long ( {4:0.###} ,{2:0.###} )";
            newPlot.Series.Add(pointsSeries);

            List <OxyColor> colors = new List <OxyColor>();

            foreach (var color in OxyPalettes.Jet(200).Colors)
            {
                var faintColor = OxyColor.FromArgb(80, color.R, color.G, color.B);
                colors.Add(faintColor);
            }

            OxyPalette faintPalette = new OxyPalette(colors);

            newPlot.Axes.Add(new LinearColorAxis {
                Position = AxisPosition.Right, Palette = faintPalette, Title = "Days Since Start"
            });
        }
예제 #20
0
 /// <summary>
 /// UIスレッド以外からポイントを追加する時に使用(Dispatcher.BeginInvokeを使用)
 /// </summary>
 /// <param name="sp"></param>
 public void SetScatterPoint(ScatterPoint sp)
 {
     System.Windows.Application.Current.Dispatcher.BeginInvoke(
         new Action(() => ScatterPointsLive.Add(sp)));
 }
        protected override void ExecuteReactionsToModelPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            //Check if we need to update the plot
            if (e.PropertyName.Equals("FeedList"))
            {
                if (_session.FeedList_TimeSincePreviousFeed != null &&
                    _session.FeedList_TimeSinceSessionStart != null)
                {
                    //Get the datapoints that need to be plotted
                    var x_datapoints = _session.FeedList_TimeSinceSessionStart.ToList();
                    var y_datapoints = _session.FeedList_TimeSincePreviousFeed.ToList();

                    List <ScatterPoint> datapoints = new List <ScatterPoint>();
                    for (int i = 0; i < x_datapoints.Count && i < y_datapoints.Count; i++)
                    {
                        ScatterPoint j = new ScatterPoint(x_datapoints[i], y_datapoints[i]);
                        datapoints.Add(j);
                    }

                    //Grab the scatter series from the plot
                    var series = _session_plot_model.Series.Select(x => x as ScatterSeries).FirstOrDefault();
                    if (series != null)
                    {
                        //Update the plot
                        series.Points.Clear();
                        series.Points.AddRange(datapoints);
                        _session_plot_model.InvalidatePlot(true);
                    }
                }
            }
            else if (e.PropertyName.Equals("SoundList"))
            {
                int ymax = 10;
                if (_session.FeedList_TimeSincePreviousFeed != null && _session.FeedList_TimeSincePreviousFeed.Count > 0)
                {
                    ymax = _session.FeedList_TimeSincePreviousFeed.ToList().Max();
                }

                List <int> sound_list = _session.GetSoundList();

                _session_plot_model.Annotations.Clear();

                if (sound_list != null)
                {
                    var y_axis = _session_plot_model.Axes.Where(j => j.Position == AxisPosition.Left).FirstOrDefault();
                    if (y_axis != null)
                    {
                        for (int i = 0; i < sound_list.Count; i++)
                        {
                            //Create the annotation
                            LineAnnotation new_annotation = new LineAnnotation()
                            {
                                Type            = LineAnnotationType.Vertical,
                                LineStyle       = LineStyle.Dash,
                                StrokeThickness = 2,
                                Color           = OxyColor.FromRgb(255, 0, 0),
                                MinimumY        = 0,
                                MaximumY        = ymax,
                                X = sound_list[i]
                            };

                            //Add this annotation
                            _session_plot_model.Annotations.Add(new_annotation);

                            //Invalidate the plot
                            _session_plot_model.InvalidatePlot(true);
                        }
                    }
                }
            }

            //Call the base function to handle anything else
            base.ExecuteReactionsToModelPropertyChanged(sender, e);
        }
예제 #22
0
        private void ConstructPlot2()
        {
            if (DataSource != null)
            {
                var BHPChartValues   = new ChartValues <ScatterPoint>();
                var dPdGChartValues  = new ChartValues <ScatterPoint>();
                var GdPdGChartValues = new ChartValues <ScatterPoint>();

                var SelectedData = DataSource.Where((x) => x.Time >= EndPumping && x.Time <= EndDecline);

                foreach (var log in SelectedData)
                {
                    var InitialTime = SelectedData.ElementAt(0).Time;
                    var DeltaT      = (log.Time - InitialTime) / InitialTime;
                    var gDtD        = (1 + DeltaT) * (Math.Asin(Math.Pow((1 + DeltaT), -0.5)) + Math.Pow(DeltaT, 0.5));
                    var xValue      = 4 / Math.PI * (gDtD - Math.PI / 2);

                    var BHPPoint = new ScatterPoint();
                    BHPPoint.X      = xValue;
                    BHPPoint.Y      = log.SurfacePressure + Phydrostatic;
                    BHPPoint.Weight = 1;

                    BHPChartValues.Add(BHPPoint);
                }

                for (int i = 0; i < BHPChartValues.Count - 2; i++)
                {
                    var tempDPDG = (BHPChartValues.ElementAt(i).Y - BHPChartValues.ElementAt(i + 2).Y) /
                                   (BHPChartValues.ElementAt(i + 2).X - BHPChartValues.ElementAt(i).X);

                    var dPdGPoint = new ScatterPoint();
                    dPdGPoint.X      = BHPChartValues.ElementAt(i).X;
                    dPdGPoint.Y      = tempDPDG;
                    dPdGPoint.Weight = 1;

                    dPdGChartValues.Add(dPdGPoint);
                }

                for (int i = 0; i < dPdGChartValues.Count; i++)
                {
                    var tempGDPDG = dPdGChartValues.ElementAt(i).Y *dPdGChartValues.ElementAt(i).X;

                    var GdPdGPoint = new ScatterPoint();
                    GdPdGPoint.X      = dPdGChartValues.ElementAt(i).X;
                    GdPdGPoint.Y      = tempGDPDG;
                    GdPdGPoint.Weight = 1;

                    GdPdGChartValues.Add(GdPdGPoint);
                }

                PlotTwoSeries = new SeriesCollection
                {
                    new ScatterSeries
                    {
                        Values = BHPChartValues,
                        MinPointShapeDiameter = 5,
                        MaxPointShapeDiameter = 5,
                        Title     = "BHP",
                        ScalesYAt = 0,
                        Fill      = Brushes.Red
                    },
                    new ScatterSeries
                    {
                        Values = dPdGChartValues,
                        MinPointShapeDiameter = 5,
                        MaxPointShapeDiameter = 5,
                        Title     = "dP/dG",
                        ScalesYAt = 1,
                        Fill      = Brushes.Blue
                    },
                    new ScatterSeries
                    {
                        Values = GdPdGChartValues,
                        MinPointShapeDiameter = 5,
                        MaxPointShapeDiameter = 5,
                        Title     = "GdP/dG",
                        ScalesYAt = 1,
                        Fill      = Brushes.Green
                    }
                };
            }
        }
예제 #23
0
 public ListBoxScatterPointItem(ScatterPoint point)
 {
     Point = point;
 }
예제 #24
0
        private PlotModel DrawSection()
        {
            PlotModel sectionPlotModel = new PlotModel();

            SetUpGraph(sectionPlotModel);

            // RYSOWANIE KOLEJNYCH PARTÓW
            foreach (var part in Section.Parts)
            {
                AreaSeries seria_part = new AreaSeries();
                seria_part.Color           = Kolory_Parts[Section.Parts.IndexOf(part)];
                seria_part.StrokeThickness = generalThickness;

                // KONTUR PARTU
                foreach (var side in part.Contour.Sides)
                {
                    DataPoint point1 = new DataPoint(side.StartPoint.X, side.StartPoint.Y);
                    seria_part.Points.Add(point1);
                    DataPoint point2 = new DataPoint(side.EndPoint.X, side.EndPoint.Y);
                    seria_part.Points.Add(point2);
                }
                seria_part.Title = part.Name;
                sectionPlotModel.Series.Add(seria_part);

                // VOIDY W PARCIE
                foreach (var _void in part.Voids)
                {
                    AreaSeries seria_void = new AreaSeries();
                    seria_void.Color           = Kolory_Parts[Section.Parts.IndexOf(part)];
                    seria_void.Fill            = OxyColors.White;
                    seria_void.StrokeThickness = generalThickness;

                    foreach (var side in _void.Sides)
                    {
                        DataPoint point1 = new DataPoint(side.StartPoint.X, side.StartPoint.Y);
                        seria_void.Points.Add(point1);
                        DataPoint point2 = new DataPoint(side.EndPoint.X, side.EndPoint.Y);
                        seria_void.Points.Add(point2);
                    }
                    sectionPlotModel.Series.Add(seria_void);
                }
            }

            // RYSOWANIE KOLEJNYCH GRUP ZBROJENIA
            foreach (var reoGroup in Section.Reinforcement)
            {
                ScatterSeries seria_reo = new ScatterSeries();
                seria_reo.MarkerFill = Kolory_Reinforcement[Section.Reinforcement.IndexOf(reoGroup)];
                seria_reo.MarkerType = MarkerType.Circle;

                foreach (var bar in reoGroup.Bars)
                {
                    ScatterPoint point = new ScatterPoint(bar.Coordinates.X, bar.Coordinates.Y);
                    point.Size = bar.Diameter * 100;
                    seria_reo.Points.Add(point);
                }
                seria_reo.Title = reoGroup.Name;
                sectionPlotModel.Series.Add(seria_reo);
            }

            //RYSOWANIE ŚRODKA CIĘŻKOŚCI CAŁEGO ZBROJENIA
            ScatterSeries seria_centroid0 = new ScatterSeries();

            seria_centroid0.MarkerStroke          = OxyColors.Black;
            seria_centroid0.MarkerType            = MarkerType.Plus;
            seria_centroid0.MarkerStrokeThickness = 3.5;

            ScatterPoint pointC0 = new ScatterPoint(Section.Centroid.X, Section.Centroid.Y);

            pointC0.Size = 10;
            seria_centroid0.Points.Add(pointC0);

            seria_centroid0.Title = "Section centroid";
            sectionPlotModel.Series.Add(seria_centroid0);

            //RYSOWANIE GŁÓWNYCH OSI BEZWŁADNOŚCI PRZEKROJU


            //RYSOWANIE ŚRODKÓW CIĘŻKOŚCI PARTÓW
            foreach (var part in Section.Parts)
            {
                ScatterSeries seria_centroids = new ScatterSeries();
                seria_centroids.MarkerStroke          = Kolory_Centroids[Section.Parts.IndexOf(part)];
                seria_centroids.MarkerType            = MarkerType.Plus;
                seria_centroids.MarkerStrokeThickness = 2.5;

                ScatterPoint pointC = new ScatterPoint(part.Centroid.X, part.Centroid.Y);
                pointC.Size = 7.5;
                seria_centroids.Points.Add(pointC);

                seria_centroids.Title = part.Name + " - centroid";
                sectionPlotModel.Series.Add(seria_centroids);
            }

            //PRZYPISANIE MODELU
            return(sectionPlotModel);
        }
예제 #25
0
        private void InitializePlot()
        {
            //TODO: Plot the history data.
            Plot.Model = new PlotModel();
            Plot.Dock  = DockStyle.Fill;
            PlotBox.Controls.Add(Plot);


            Plot.Model.PlotType   = PlotType.XY;
            Plot.Model.Background = OxyColor.FromRgb(255, 255, 255);
            Plot.Model.TextColor  = OxyColor.FromRgb(0, 0, 0);

            axis1.Position = AxisPosition.Bottom;
            axis1.Minimum  = -1.0;
            axis1.Maximum  = 10.0;
            axis1.Title    = "运行时间";
            axis1.Unit     = "秒";
            Plot.Model.Axes.Add(axis1);

            var axis2 = new LinearAxis();

            axis2.Position = AxisPosition.Left;
            axis2.Minimum  = -15.0;
            axis2.Maximum  = 15.0;
            axis2.Title    = "转速";
            axis2.Unit     = "档";
            Plot.Model.Axes.Add(axis2);

            // add Series and Axis to plot model
            ScatterSeries arcScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0xFF, 0x66, 0x77)
            };
            ScatterSeries solderScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0xBB, 0x11, 0x66)
            };
            ScatterSeries accScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0x88, 0x33, 0x44)
            };
            ScatterSeries deaccScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0x55, 0x88, 0xAA)
            };
            ScatterSeries rotateScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0x33, 0xAA, 0xDD)
            };
            ScatterSeries reverseRotateScatterSeries = new ScatterSeries {
                MarkerType = MarkerType.Circle, MarkerFill = OxyColor.FromRgb(0x55, 0x99, 0x11)
            };

            Plot.Model.Series.Add(arcScatterSeries);
            Plot.Model.Series.Add(solderScatterSeries);
            Plot.Model.Series.Add(accScatterSeries);
            Plot.Model.Series.Add(deaccScatterSeries);
            Plot.Model.Series.Add(rotateScatterSeries);
            Plot.Model.Series.Add(reverseRotateScatterSeries);

            var signals     = History.Signals;
            var signalCount = signals.Count;

            Plot.Model.InvalidatePlot(true);                                                                 // Invalidate it.

            var totalTime = (int)((signals.Last().Timestamp - signals.First().Timestamp).TotalMilliseconds); // Ignore time less tham 1ms.

            axis1.Maximum = Math.Floor(totalTime / 1000.0 + 5);

            for (int i = 0; i < signalCount; i++)
            {
                var signal       = signals[i];
                var currentSpeed = 0;

                var delta = (int)((signals[i].Timestamp - signals.First().Timestamp).TotalMilliseconds);

                ScatterSeries currentSerials = null;
                switch (signal.Type)
                {
                case SignalType.ArcStart:
                    currentSerials = arcScatterSeries;
                    break;

                case SignalType.ArcEnd:
                    currentSerials = arcScatterSeries;
                    break;

                case SignalType.SolderStart:
                    currentSerials = solderScatterSeries;
                    break;

                case SignalType.SolderEnd:
                    currentSerials = solderScatterSeries;
                    break;

                case SignalType.Acceleration:
                    currentSerials = accScatterSeries;
                    currentSpeed   = signal.Step;
                    break;

                case SignalType.Deceleration:
                    currentSerials = deaccScatterSeries;
                    currentSpeed   = signal.Step;   // TODO: Fixme, should be minus while reverse rotate.
                    break;

                case SignalType.RevolveStart:
                    currentSerials = reverseRotateScatterSeries;
                    break;

                case SignalType.RevolveEnd:
                    currentSerials = reverseRotateScatterSeries;
                    break;

                case SignalType.Unknown:
                    currentSerials = rotateScatterSeries;     // TODO: Fix it.
                    break;

                default:
                    currentSerials = rotateScatterSeries;     // TODO: Fix it.
                    break;
                }
                var point = new ScatterPoint(delta / 1000.0, currentSpeed, 3);
                currentSerials.Points.Add(point);
            }
        }
예제 #26
0
        //Creates a new project on the graph
        public void AddNewProject(Project newProject)
        {
            foreach (var series in SeriesCollection)
            {
                if (series.Title.Equals(newProject.projectCategory))
                {
                    var XCoord = calculateXCoord(newProject.resource, newProject.data, newProject.vendors, newProject.sponsorship, newProject.implementation);

                    //var YCoord = calculateYCoord(newProject.value, newProject.transformativeG, newProject.hrpriority, newProject.risk);

                    var YCoord = calculateYCoord(newProject.value, newProject.strategicA, newProject.risk);

                    var newBubble = new ScatterPoint(XCoord, YCoord, newProject.value);

                    var newTuple = new Tuple <double, double>(XCoord, YCoord);

                    if (BubbleLabels.ContainsKey(newTuple))
                    {
                        string newLabel = "0";

                        for (int i = 0; i < JSONList.Count; i++)
                        {
                            if (JSONList[i].pName.Equals(newProject.pName))
                            {
                                newLabel = (i + 1).ToString();
                            }
                        }

                        string oldLabel = BubbleLabels[newTuple];

                        if ((BubbleList[newTuple].Count + 1) == 4 || (BubbleList[newTuple].Count + 1) == 7)
                        {
                            BubbleLabels[newTuple] = oldLabel + ", " + Environment.NewLine + "\t" + newLabel;
                        }
                        else
                        {
                            BubbleLabels[newTuple] = oldLabel + ", " + newLabel;
                        }

                        BubbleList[newTuple].Add(newProject);
                    }
                    else
                    {
                        string newLabel = "Project: ";

                        for (int i = 0; i < JSONList.Count; i++)
                        {
                            if (JSONList[i].pName.Equals(newProject.pName))
                            {
                                newLabel = newLabel + (i + 1);
                            }
                        }

                        BubbleLabels.Add(newTuple, newLabel);

                        ArrayList listOfProjects = new ArrayList();

                        listOfProjects.Add(newProject);

                        BubbleList.Add(newTuple, listOfProjects);
                    }

                    series.Values.Add(newBubble);
                }
            }
        }
 /// <summary>
 /// Determines whether the specified point is valid.
 /// </summary>
 /// <param name="pt">
 /// The pointt.
 /// </param>
 /// <param name="xaxis">
 /// The x axis.
 /// </param>
 /// <param name="yaxis">
 /// The y axis.
 /// </param>
 /// <returns>
 /// <c>true</c> if the point is valid; otherwise, <c>false</c> .
 /// </returns>
 public virtual bool IsValidPoint(ScatterPoint pt, Axis xaxis, Axis yaxis)
 {
     return !double.IsNaN(pt.X) && !double.IsInfinity(pt.X) && !double.IsNaN(pt.Y) && !double.IsInfinity(pt.Y)
            && (xaxis != null && xaxis.IsValidValue(pt.X)) && (yaxis != null && yaxis.IsValidValue(pt.Y));
 }
예제 #28
0
        private void BackTest(decimal startAmountUSDT, decimal minEMA, decimal maxEMA, int minPeriod, int maxPeriod)
        {
            var scatterPlotsBuy  = new ChartValues <ScatterPoint>();
            var scatterPlotsSell = new ChartValues <ScatterPoint>();

            Status status = Status.USDT;

            var firstBTCPrice    = candles[maxPeriod].Open;
            var lastBTCPrice     = candles.Last().Open;
            var startAmountInBTC = startAmountUSDT / firstBTCPrice;
            int nTrades          = 0;

            IList <decimal> minEMAS = new List <decimal>();
            IList <decimal> maxEMAS = new List <decimal>();

            Console.WriteLine("Min EMA: " + minEMA + " Max EMA: " + maxEMA);
            Console.WriteLine("Start amount USDT: " + Math.Round(startAmountUSDT, 2) + " BTC: " + Math.Round(startAmountInBTC) + " BTC PRICE: " + Math.Round(firstBTCPrice, 2));
            Console.WriteLine("Start backtesting");
            Console.WriteLine("...");

            decimal currentUSDT = startAmountUSDT;
            decimal currentBTC  = 0;

            for (int i = maxPeriod; i < candles.Count; i++)
            {
                var candle = candles[i];

                var avgMinEma = candles.Skip(i + 1 - minPeriod).Take(minPeriod).Select(x => x.Open).Sum() / minPeriod;
                var avgMaxEma = candles.Skip(i + 1 - maxPeriod).Take(maxPeriod).Select(x => x.Open).Sum() / maxPeriod;

                minEMAS.Add(avgMinEma);
                maxEMAS.Add(avgMaxEma);

                var ema = avgMinEma / avgMaxEma;

                if (ema > maxEMA && status == Status.USDT)
                {
                    status      = Status.BTC;
                    currentBTC  = currentUSDT / candle.Open;
                    currentUSDT = 0;
                    nTrades++;

                    var scatterPlots = new ScatterPoint(i, (double)candle.Open);
                    scatterPlotsBuy.Add(scatterPlots);
                }
                else if (ema < minEMA && status == Status.BTC)
                {
                    status      = Status.USDT;
                    currentUSDT = currentBTC * candle.Open;
                    currentBTC  = 0;
                    nTrades++;

                    var scatterPlots = new ScatterPoint(i, (double)candle.Open);
                    scatterPlotsSell.Add(scatterPlots);
                }
            }
            Console.WriteLine("End");
            Console.WriteLine("Total trades: " + nTrades);
            if (status == Status.USDT)
            {
                var endAmountInBTC = currentUSDT / lastBTCPrice;
                Console.WriteLine("End amount USDT: " + Math.Round(currentUSDT, 2) + " - BTC: " + Math.Round(endAmountInBTC, 2) + " - BTC PRICE: " + Math.Round(lastBTCPrice, 2));
                var profitIncrement = Math.Round(((currentUSDT - startAmountUSDT) / startAmountUSDT * 100), 2);
                var btcIncrement    = Math.Round(((lastBTCPrice - firstBTCPrice) / firstBTCPrice * 100), 2);
                Console.WriteLine("Profit Increment: " + profitIncrement + "% - BTC Increment: " + btcIncrement + "%");
                Console.WriteLine("Real profit: " + (profitIncrement - btcIncrement) + "%");

                txbNTrades.Text           = nTrades.ToString();
                txbStartUSDTAmount.Text   = startAmountUSDT.ToString();
                txbEndUSDTAmount.Text     = Math.Round(currentUSDT, 2).ToString();
                txbIncrementUSDT.Text     = Math.Round(currentUSDT - startAmountUSDT, 2).ToString();
                txbIncrementUSDTPerc.Text = Math.Round(((currentUSDT - startAmountUSDT) / startAmountUSDT * 100), 2).ToString();

                txbStartBTCPrice.Text    = Math.Round(firstBTCPrice, 2).ToString();
                txbEndBTCPrice.Text      = Math.Round(lastBTCPrice, 2).ToString();
                txbIncrementBTC.Text     = Math.Round(lastBTCPrice - firstBTCPrice, 2).ToString();
                txbIncrementBTCPerc.Text = Math.Round(((lastBTCPrice - firstBTCPrice) / firstBTCPrice * 100), 2).ToString();

                var estimatedValue = (startAmountUSDT / firstBTCPrice) * lastBTCPrice;
                var profit         = currentUSDT - estimatedValue;
                txbProfitUSDT.Text     = Math.Round(profit, 2).ToString();
                txbProfitUSDTPerc.Text = Math.Round(((currentUSDT - estimatedValue) / estimatedValue * 100), 2).ToString();
            }
            else
            {
                var endAmountInUSDT = currentBTC * lastBTCPrice;
                Console.WriteLine("End amount USDT: " + Math.Round(endAmountInUSDT, 2) + " - BTC: " + Math.Round(currentBTC, 2) + " - BTC PRICE: " + Math.Round(lastBTCPrice, 2));
                var profitIncrement = Math.Round(((endAmountInUSDT - startAmountUSDT) / startAmountUSDT * 100), 2);
                var btcIncrement    = Math.Round(((lastBTCPrice - firstBTCPrice) / firstBTCPrice * 100), 2);
                Console.WriteLine("Profit Increment: " + profitIncrement + "% - BTC Increment: " + btcIncrement + "%");
                Console.WriteLine("Real profit: " + (profitIncrement - btcIncrement) + "%");


                txbNTrades.Text           = nTrades.ToString();
                txbStartUSDTAmount.Text   = startAmountUSDT.ToString();
                txbEndUSDTAmount.Text     = Math.Round(endAmountInUSDT, 2).ToString();
                txbIncrementUSDT.Text     = Math.Round(endAmountInUSDT - startAmountUSDT, 2).ToString();
                txbIncrementUSDTPerc.Text = Math.Round(((endAmountInUSDT - startAmountUSDT) / startAmountUSDT * 100), 2).ToString();

                txbStartBTCPrice.Text    = Math.Round(firstBTCPrice, 2).ToString();
                txbEndBTCPrice.Text      = Math.Round(lastBTCPrice, 2).ToString();
                txbIncrementBTC.Text     = Math.Round(lastBTCPrice - firstBTCPrice, 2).ToString();
                txbIncrementBTCPerc.Text = Math.Round(((lastBTCPrice - firstBTCPrice) / firstBTCPrice * 100), 2).ToString();

                var estimatedValue = (startAmountUSDT / firstBTCPrice) * lastBTCPrice;
                var profit         = endAmountInUSDT - estimatedValue;
                txbProfitUSDT.Text     = Math.Round(profit, 2).ToString();
                txbProfitUSDTPerc.Text = Math.Round(((endAmountInUSDT - estimatedValue) / estimatedValue * 100), 2).ToString();
            }

            txbIncrementUSDT.Foreground     = GetColorByValue(txbIncrementUSDT.Text);
            txbIncrementUSDTPerc.Foreground = GetColorByValue(txbIncrementUSDTPerc.Text);
            txbIncrementBTC.Foreground      = GetColorByValue(txbIncrementBTC.Text);
            txbIncrementBTCPerc.Foreground  = GetColorByValue(txbIncrementBTCPerc.Text);
            txbProfitUSDT.Foreground        = GetColorByValue(txbProfitUSDT.Text);
            txbProfitUSDTPerc.Foreground    = GetColorByValue(txbProfitUSDTPerc.Text);

            if (SeriesCollection != null)
            {
                DrawBackTestChart(minEMAS, maxEMAS, scatterPlotsBuy, scatterPlotsSell, minPeriod, maxPeriod);
            }
        }
        /// <summary>
        /// Sets up the plot model to be displayed.
        /// </summary>
        /// <returns>The plot model.</returns>
        protected override PlotModel SetupPlot()
        {
            // Create the plot model
            var newPlot = new PlotModel {
                Title = "Last 10 Books Time vs Pages Plot"
            };

            OxyPlotUtilities.SetupPlotLegend(newPlot, "Last 10 Books Time vs Pages Plot");
            SetupPagesPerDayWithTimeVsTimeAxes(newPlot);

            // create series and add them to the plot
            ScatterSeries pointsSeries;

            OxyPlotUtilities.CreateScatterPointSeries(
                out pointsSeries,
                ChartAxisKeys.DaysTakenKey,
                ChartAxisKeys.TotalPagesReadKey,
                "Time Taken Vs Pages");

            List <BooksDelta> deltasSet = new List <BooksDelta>();

            double minRate = 1e16;
            double maxRate = 0.0;

            foreach (var delta in BooksReadProvider.BookDeltas)
            {
                deltasSet.Add(delta);
                if (deltasSet.Count < 10)
                {
                    continue;
                }

                BooksDelta end = deltasSet.Last();

                double daysTaken = end.LastTenTally.DaysInTally;
                double pagesRead = end.LastTenTally.TotalPages;
                if (daysTaken < 1.0)
                {
                    daysTaken = 1.0;
                }
                double       rate  = pagesRead / daysTaken;
                ScatterPoint point =
                    new ScatterPoint(daysTaken, pagesRead, 5, rate)
                {
                    Tag = end.Date.ToString("ddd d MMM yyy")
                };
                pointsSeries.Points.Add(point);

                if (minRate > rate)
                {
                    minRate = rate;
                }
                if (maxRate < rate)
                {
                    maxRate = rate;
                }

                deltasSet.RemoveAt(0);
            }
            pointsSeries.TrackerFormatString = "{Tag}\n{1}: {2:0.###}\n{3}: {4:0.###}";
            newPlot.Series.Add(pointsSeries);
            newPlot.Axes.Add(new LinearColorAxis {
                Position = AxisPosition.Right, Palette = OxyPalettes.Jet(200), Title = "Page Rate"
            });

            // finally update the model with the new plot
            return(newPlot);
        }
        public static PlotModel RandomWithFit()
        {
            const int n = 20;
            var model = new PlotModel(string.Format("Random data (n={0})", n)) { LegendPosition = LegendPosition.LeftTop };

            var s1 = new ScatterSeries { Title = "Measurements" };
            var random = new Random();
            double x = 0;
            double y = 0;
            for (int i = 0; i < n; i++)
            {
                x += 2 + random.NextDouble() * 10;
                y += 1 + random.NextDouble();
                var p = new ScatterPoint(x, y);
                s1.Points.Add(p);
            }
            model.Series.Add(s1);
            double a, b;
            LeastSquaresFit(s1.Points, out a, out b);
            model.Annotations.Add(new LineAnnotation { Slope = a, Intercept = b, Text = "Least squares fit" });
            return model;
        }
 private static ScatterSeries CreateRandomScatterSeries(int n, string title, MarkerType markerType)
 {
     var s1 = new ScatterSeries { Title = title, MarkerType = markerType, MarkerStroke = OxyColors.Black, MarkerStrokeThickness = 1.0 };
     for (int i = 0; i < n; i++)
     {
         double x = Randomizer.NextDouble() * 10;
         double y = Randomizer.NextDouble() * 10;
         var p = new ScatterPoint(x, y);
         s1.Points.Add(p);
     }
     return s1;
 }
예제 #32
0
        public void TestSimpleCreation()
        {
            var random = new Random();
            var points = new List <int> {
                100, 1000, 10000, 100000
            };

            foreach (var totalPoints in points)
            {
                var start      = DateTime.Now;
                var plotModel1 = new PlotModel {
                    Subtitle = "No 'binning'", Title = "ScatterSeries (n=32768)"
                };

                var linearAxis1 = new LinearAxis {
                    Position = AxisPosition.Bottom
                };
                plotModel1.Axes.Add(linearAxis1);

                var linearAxis2 = new LinearAxis();
                plotModel1.Axes.Add(linearAxis2);

                var scatterSeries1 = new ScatterSeries
                {
                    MarkerSize            = 1,
                    MarkerStrokeThickness = 0,
                    MarkerType            = MarkerType.Diamond,
                    Title = "Series 1" + totalPoints
                };

                var pointList = new List <ScatterPoint>();
                for (var i = 0; i < totalPoints; i++)
                {
                    var xPos  = random.NextDouble();
                    var yPos  = random.NextDouble();
                    var point = new ScatterPoint(xPos, yPos);
                    pointList.Add(point);
                }
                Console.WriteLine();

                var end = DateTime.Now;
                Console.WriteLine("Creation Part of Test Took: {0:.00} seconds for {1} points",
                                  end.Subtract(start).TotalSeconds, totalPoints);

                start = DateTime.Now;
                scatterSeries1.Points.AddRange(pointList);
                plotModel1.Series.Add(scatterSeries1);
                end = DateTime.Now;
                Console.WriteLine("Scatter Plot Part of Test Took: {0:.00} seconds for {1} points",
                                  end.Subtract(start).TotalSeconds, totalPoints);

                start = DateTime.Now;
                var svg       = new SvgExporter();
                var svgString = svg.ExportToString(plotModel1);

                var xml = new XmlDocument();
                xml.LoadXml(svgString);
                var x              = SvgDocument.Open(xml); // Svg.SvgDocument();
                var bmp            = x.Draw();
                var outputFilePath = GetPath(@"testResults\ScatterPlot\testScatter" + totalPoints + ".jpg");
                bmp.Save(outputFilePath);

                end = DateTime.Now;
                Console.WriteLine("Saving Part of Test Took: {0:.00} seconds for {1} points",
                                  end.Subtract(start).TotalSeconds, totalPoints);
            }
        }
        private void difference_Click(object sender, EventArgs e)
        {
            cartesianChart1.Series.Clear();
            Dictionary <string, string> dictionary = new Dictionary <string, string>();

            dictionary.Add("Municipios", citiesComboBox.Text);

            dm.filterDataForHarvested(dictionary);

            SeriesCollection harvestedSerie = new SeriesCollection();

            StackedAreaSeries hSerie = new StackedAreaSeries();
            StackedAreaSeries pSerie = new StackedAreaSeries();



            hSerie.Title = "Harvested";
            pSerie.Title = "Planted";

            ChartValues <ScatterPoint> cvalues = new ChartValues <ScatterPoint>();
            ScatterPoint pair;


            foreach (CropMeasurement cm in dm.Harvested)
            {
                if (cm.A_o >= 2011 && cm.A_o <= 2017)
                {
                    pair = new ScatterPoint(cm.A_o, cm.getTypeCrop(cropCombobox.Text));
                    cvalues.Add(pair);
                }
            }
            hSerie.Values         = cvalues;
            hSerie.LineSmoothness = 0;

            dm.filterDataForPlanted(dictionary);

            ChartValues <ScatterPoint> cvalues2 = new ChartValues <ScatterPoint>();
            ScatterPoint pair2;

            foreach (CropMeasurement cm in dm.Planted)
            {
                if (cm.A_o >= 2011 && cm.A_o <= 2017)
                {
                    pair2 = new ScatterPoint(cm.A_o, cm.getTypeCrop(cropCombobox.Text));
                    cvalues2.Add(pair2);
                }
            }
            pSerie.Values         = cvalues2;
            pSerie.LineSmoothness = 0;


            harvestedSerie.Add(hSerie);
            harvestedSerie.Add(pSerie);


            cartesianChart1.Series = harvestedSerie;

            cartesianChart1.AxisX = new AxesCollection
            {
                new Axis {
                    Title = "Date",
                    //LabelFormatter = value => new DateTime((long)value).ToShortDateString()
                },
            };
        }