예제 #1
0
        public MainViewModel()
        {
            StartTime   = DateTime.Now;
            CurrentTime = StartTime;
            DispatcherTimer timer = new DispatcherTimer();

            timer.Interval = TimeSpan.FromMilliseconds(1000);
            timer.Tick    += (sender, args) =>
            {
                if (Finish)
                {
                    return;
                }
                CurrentTime = DateTime.Now;
                var count = CorrectInputKeyboardSymbolModels.Count;
                if (count < 2)
                {
                    return;
                }
                for (int i = count - 1; i >= 0; i--)
                {
                    var span = CorrectInputKeyboardSymbolModels[count - 1].Time - CorrectInputKeyboardSymbolModels[i].Time;
                    if (span.TotalMilliseconds > 5000)
                    {
                        SpeedData.Add(new DataPoint(TimeSpanAxis.ToDouble(CurrentTime - StartTime), (count - 1 - i) / span.TotalMinutes));
                        while (SpeedData.Count > 60)
                        {
                            SpeedData.RemoveAt(0);
                        }
                        break;
                    }
                }
            };
            timer.Start();
        }
예제 #2
0
        private PlotModel CreateDistanceTraveledModel(Track Track)
        {
            PlotModel PlotModel = new PlotModel
            {
                Title = "Afgelegde weg"
            };

            PlotModel.Axes.Add(new TimeSpanAxis
            {
                Position        = AxisPosition.Bottom,
                Title           = "Tijd (s)",
                AbsoluteMinimum = TimeSpanAxis.ToDouble(new TimeSpan()),
                AbsoluteMaximum = TimeSpanAxis.ToDouble(Track.GetTotalTimeSpan())
            });
            PlotModel.Axes.Add(new LinearAxis
            {
                Position        = AxisPosition.Left,
                Title           = "Afgelegde weg (m)",
                AbsoluteMinimum = 0,
                AbsoluteMaximum = Track.GetTotalRunningDistance()
            });

            PlotModel.Series.Add(new LineSeries
            {
                Title       = "Afgelegde weg",
                ItemsSource = Track.GetDistanceTraveledDataPoints()
            });

            return(PlotModel);
        }
예제 #3
0
        private void CreateBarChart(PlotModel plotModel, Dictionary <DateTime, double> dataList)
        {
            // 각 포인트의 데이터를 model 에 add 합니다.
            // 여기서 PointAnnotation 는 각 포인트에 라벨을 표시하기 위함입니다.
            var Points = new List <DataPoint>();

            //int idx = 0;
            foreach (var i in dataList)
            {
                var pointAnnotation = new PointAnnotation();
                pointAnnotation.X = TimeSpanAxis.ToDouble(i.Key);
                pointAnnotation.Y = i.Value;
                // 실제 데이터 값을 포인트에 add 합니다.
                Points.Add(new DataPoint(TimeSpanAxis.ToDouble(i.Key), i.Value));

                // 해당 포인트에 대한 라벨표시값도 추가합니다.
                //pointAnnotation.TextVerticalAlignment = VerticalAlignment.Top;
                //pointAnnotation.TextHorizontalAlignment = HorizontalAlignment.Center;
                //pointAnnotation.Text = (i.Value).ToString("#.00");
                //plotModel.Annotations.Add(pointAnnotation);
            }

            // Line 차트를 그리기 위한 라인시리즈를 정의합니다.
            var s = new LineSeries();

            //s.LineStyle = LineStyle.Dot;

            // 각 포인트에 동그란 점으로 표시하게 합니다.
            s.MarkerType = MarkerType.Circle;
            // 정의한 포이트 데이터들을 라인시리즈의 소스로 적용합니다.
            s.ItemsSource = Points;
            // 차트에 적용할 model 에 추가합니다.
            plotModel.Series.Add(s);
        }
예제 #4
0
        public void ShowByCandidates(VotingResults votingResults, Func <Vote, bool> filter)
        {
            lock (_plotModel.SyncRoot)
            {
                _xAxis.SetAxisMinMax(TimeSpanAxis.ToDouble(votingResults.StartTime), TimeSpanAxis.ToDouble(votingResults.EndTime));

                _plotModel.Series.Clear();

                var candidates = votingResults.Votes.Where(x => filter(x)).Select(x => x.CandidateId).Distinct();

                int max = 0;
                foreach (var candidate in candidates)
                {
                    LineSeries series = TotalCumulativeVotedByTimeUtils.CreateSeries(votingResults, x => filter(x) && (x.CandidateId == candidate), out int total);
                    if (total > max)
                    {
                        max = total;
                    }
                    series.Title = votingResults.Candidates[candidate].Name;
                    _plotModel.Series.Add(series);
                }
                _yAxis.SetAxisMax(max);
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #5
0
        public PlotViewModel(IMainViewModel mainViewModel, IEnumerable <DataPoint> data)
        {
            PlotModel = new PlotModel();
            var series = new LineSeries {
                StrokeThickness = 1,
                MarkerStroke    = OxyColors.Blue,
                Color           = OxyColors.Red,
                ItemsSource     = data
            };

            PlotModel.Series.Add(series);
            PlotModel.Axes.Add(new DateTimeAxis {
                Position        = AxisPosition.Bottom,
                Minimum         = DateTimeAxis.ToDouble(DateTime.UtcNow),
                AbsoluteMinimum = DateTimeAxis.ToDouble(DateTime.UtcNow),
                Maximum         = DateTimeAxis.ToDouble(DateTime.UtcNow.AddMinutes(1)),
                Title           = "Time",
                TimeZone        = TimeZoneInfo.Local,
                MaximumRange    = TimeSpanAxis.ToDouble(TimeSpan.FromMinutes(5)),
                MinimumRange    = TimeSpanAxis.ToDouble(TimeSpan.FromSeconds(10))
            });
            PlotModel.Axes.Add(new LinearAxis {
                Position      = AxisPosition.Left,
                Minimum       = 0,
                Maximum       = 100,
                IsPanEnabled  = false,
                IsZoomEnabled = false
            });
        }
예제 #6
0
        private void AddPoint(double value, LineSeries serie)
        {
            serie.Points.RemoveAll(point => point.X < TimeSpanAxis.ToDouble(_stopwatch.Elapsed - _visibleTime));
            serie.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(_stopwatch.Elapsed), value));

            _timeAxis.Minimum = TimeSpanAxis.ToDouble(_stopwatch.Elapsed - _visibleTime);
            PlotModel.InvalidatePlot(true);
        }
        public void SupportMillisecondsInFormatStrings(string format, string expected)
        {
            var axis = new TimeSpanAxis {
                StringFormat = format
            };
            var formattedValue = axis.FormatValue(TimeSpanAxis.ToDouble(new System.TimeSpan(1, 1, 1, 2, 345)));

            Assert.That(formattedValue, Is.EqualTo(expected));
        }
        private void CreateBarChart(bool stacked, string title, Dictionary <DateTime, double> dataList)
        {
            // 차트에 바인딩될 데이터 Model 입니다.
            var model = new PlotModel
            {
                Title    = title,
                PlotType = PlotType.XY,
            };

            // x축은 시간이 보이도록 설정합니다.
            model.Axes.Add(new DateTimeAxis
            {
                Title        = "시간",
                Position     = AxisPosition.Bottom,
                StringFormat = "HH:mm:ss"
            });

            // Y 축은 값입니다.
            model.Axes.Add(new LinearAxis
            {
                Title    = "값",
                Position = AxisPosition.Left
            });

            // 각 포인트의 데이터를 model 에 add 합니다.
            // 여기서 PointAnnotation 는 각 포인트에 라벨을 표시하기 위함입니다.
            var Points = new List <DataPoint>();

            //int idx = 0;
            foreach (var i in dataList)
            {
                var pointAnnotation = new PointAnnotation();
                pointAnnotation.X = TimeSpanAxis.ToDouble(i.Key);
                pointAnnotation.Y = i.Value;
                pointAnnotation.TextVerticalAlignment   = VerticalAlignment.Top;
                pointAnnotation.TextHorizontalAlignment = HorizontalAlignment.Center;
                pointAnnotation.Text = (i.Value).ToString("0.00");
                // 실제 데이터 값을 포인트에 add 합니다.
                Points.Add(new DataPoint(TimeSpanAxis.ToDouble(i.Key), i.Value));
                // 해당 포인트에 대한 라벨표시값도 추가합니다.
                model.Annotations.Add(pointAnnotation);
            }

            // Line 차트를 그리기 위한 라인시리즈를 정의합니다.
            var s = new LineSeries();

            // 각 포인트에 동그란 점으로 표시하게 합니다.
            s.MarkerType = MarkerType.Circle;
            // 정의한 포이트 데이터들을 라인시리즈의 소스로 적용합니다.
            s.ItemsSource = Points;
            // 차트에 적용할 model 에 추가합니다.
            model.Series.Add(s);

            // 위에서 정의한 model 을 차트에 적용합니다.
            PlotChart.Model = model;
        }
예제 #9
0
 public double XFormat(double value)
 {
     if (_plotType == ShowDataType.PulseHeight ||
         _plotType == ShowDataType.PulseIntegral ||
         _plotType == ShowDataType.SinglesLow ||
         _plotType == ShowDataType.SinglesHigh)
     {
         return(value);
     }
     else
     {
         return(TimeSpanAxis.ToDouble(TimeSpan.FromHours(value)));
     }
 }
예제 #10
0
        public void ShowLinearIntepolatedBlockGraphItems(bool setMinTime, BlockGraphItem <TimeSpan>[] array)
        {
            lock (_plotModel.SyncRoot)
            {
                ConfigureAxes(setMinTime, array);

                var series = PrepareSeries();
                for (int i = 0; i < array.Length; i++)
                {
                    series.Points.Add(new DataPoint(array[i].BlockNumber, TimeSpanAxis.ToDouble(array[i].Data)));
                }
            }
            _plotModel.InvalidatePlot(true);
        }
 public TransactionPerBlockTimelineModelDrawer()
 {
     _plotModel = new PlotModel();
     _xAxis     = new TimeSpanAxis()
     {
         Position           = AxisPosition.Bottom,
         Key                = XAxisKey,
         MinorGridlineStyle = LineStyle.Dash,
         MajorGridlineStyle = LineStyle.Solid,
         MinorStep          = TimeSpanAxis.ToDouble(TimeSpan.FromHours(1)),
         Title              = "Time"
     };
     _plotModel.Axes.Add(_xAxis);
 }
예제 #12
0
        public static IEnumerable <LineSeries> SeriesCtor(IEnumerable <TimeTracker> trackers)
        {
            foreach (TimeTracker tracker in trackers)
            {
                LineSeries series = SeriesFromTracker(tracker);
                foreach (KeyValuePair <TimeSpan, int> pair in tracker)
                {
                    series.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(pair.Key), pair.Value));
                }

                yield return(series);
            }
            yield break;
        }
예제 #13
0
        public static PlotModel Default()
        {
            var model = new PlotModel {
                Title = "TimeSpanAxis"
            };

            model.Axes.Add(new TimeSpanAxis {
                Position = AxisPosition.Bottom, Maximum = TimeSpanAxis.ToDouble(TimeSpan.FromMinutes(15))
            });
            model.Axes.Add(new LinearAxis {
                Position = AxisPosition.Left
            });
            return(model);
        }
예제 #14
0
        public void ShowBlockStartTime(VotingResults votingResults)
        {
            lock (_plotModel.SyncRoot)
            {
                var xAxis = _plotModel.Axes.Where(x => x.Key == XAxisKey).Single();
                xAxis.SetMinMaxBlocksToXAxis(votingResults);

                var series = PrepareSeries();

                BlockTimeVisualHelper.LoadBlockTimesToSeries(votingResults, null, series);
                var yAxis = _plotModel.Axes.Where(x => x.Key == "y_axis").Single();
                yAxis.SetAxisMax(TimeSpanAxis.ToDouble(votingResults.Votes.Select(x => x.Time).Max()));
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #15
0
        public void Show(VotingResults votingResults, Func <Vote, bool> filter)
        {
            lock (_plotModel.SyncRoot)
            {
                _xAxis.SetAxisMinMax(TimeSpanAxis.ToDouble(votingResults.StartTime), TimeSpanAxis.ToDouble(votingResults.EndTime));

                _plotModel.Series.Clear();

                LineSeries series = TotalCumulativeVotedByTimeUtils.CreateSeries(votingResults, filter, out var max);
                series.Title = "Всего проголосовало";
                _yAxis.SetAxisMax(max);
                _plotModel.Series.Add(series);
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #16
0
        private PlotModel CreateSpeedModel(Track Track)
        {
            PlotModel PlotModel = new PlotModel
            {
                Title = "Snelheid"
            };

            PlotModel.Axes.Add(new TimeSpanAxis
            {
                Position        = AxisPosition.Bottom,
                Title           = "Tijd (s)",
                AbsoluteMinimum = TimeSpanAxis.ToDouble(new TimeSpan()),
                AbsoluteMaximum = TimeSpanAxis.ToDouble(Track.GetTotalTimeSpan())
            });
            PlotModel.Axes.Add(new LinearAxis
            {
                Position        = AxisPosition.Left,
                Title           = "Snelheid (m/s)",
                AbsoluteMinimum = 0,
                AbsoluteMaximum = Track.GetMaxSpeed()
            });

            PlotModel.Series.Add(new LineSeries
            {
                Title       = "Snelheid",
                ItemsSource = Track.GetSpeedDataPoints(),
            });

            int i = 1;

            foreach (List <DataPoint> ldp in Track.GetSegmentAvarageSpeedDataPoints())
            {
                PlotModel.Series.Add(new LineSeries
                {
                    Title       = $"Gemiddelde snelheid in segment {i}",
                    ItemsSource = ldp
                });
                i++;
            }

            PlotModel.Series.Add(new LineSeries
            {
                Title       = "Gemiddelde snelheid",
                ItemsSource = Track.GetAvergageSpeedDataPoints()
            });

            return(PlotModel);
        }
예제 #17
0
        public void AddCustomData(string title, IEnumerable <TimeGraphItem <int> > data)
        {
            lock (_plotModel.SyncRoot)
            {
                LineSeries series = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    Title = title
                };

                foreach (var item in data)
                {
                    series.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(item.Time), item.Data));
                }

                _plotModel.Series.Add(series);
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #18
0
        public static void DrawAnomalyZones(this IPlotModelDrawer @this, IEnumerable <AnomalyZoneDefinition> anomalyZones)
        {
            OxyColor[] anomalyZoneColors = new OxyColor[]
            {
                // каждый охотник желает знать где сидит фазан
                OxyColor.FromAColor(100, OxyColors.Red),
                OxyColor.FromAColor(100, OxyColors.Orange),
                OxyColor.FromAColor(100, OxyColors.Yellow),
                OxyColor.FromAColor(100, OxyColors.Violet)
            };
            int counter = 0;

            lock (@this.PlotModel.SyncRoot)
            {
                foreach (var anomalyZone in anomalyZones)
                {
                    var color = anomalyZoneColors[counter % anomalyZoneColors.Length];

                    var timeAxisKey = @this.GetTimeAxisKey();
                    if (timeAxisKey != null)
                    {
                        double start    = TimeSpanAxis.ToDouble(anomalyZone.StartTime);
                        double end      = TimeSpanAxis.ToDouble(anomalyZone.EndTime);
                        var    timeAxis = @this.PlotModel.GetAxis(timeAxisKey);

                        var annotation = CreateAnomalyZoneForAxis(timeAxis, start, end, anomalyZone.Name);
                        annotation.Fill = color;
                        @this.PlotModel.Annotations.Add(annotation);
                    }
                    var blockNumberAxisKey = @this.GetBlockNumberAxisKey();
                    if (blockNumberAxisKey != null)
                    {
                        var blockNumberAxis = @this.PlotModel.GetAxis(blockNumberAxisKey);
                        var annotation      = CreateAnomalyZoneForAxis(blockNumberAxis, anomalyZone.StartBlock, anomalyZone.EndBlock, anomalyZone.Name);
                        annotation.Fill = color;
                        @this.PlotModel.Annotations.Add(annotation);
                    }
                    counter++;
                }
            }
            @this.PlotModel.InvalidatePlot(false);
        }
예제 #19
0
        public void Show(RemoteVotingStatistics statistics)
        {
            lock (_plotModel.SyncRoot)
            {
                _plotModel.Series.Clear();

                var series1 = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    Title = "Перешло на страницу голосования"
                };
                var series2 = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    Title = "Правильно ввели регистрационную СМС"
                };
                var series3 = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    Title = "Выдано бюллететеней"
                };
                var series4 = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    Title = "Проголосовало"
                };
                _plotModel.Series.Add(series1);
                _plotModel.Series.Add(series2);
                _plotModel.Series.Add(series3);
                _plotModel.Series.Add(series4);
                foreach (var item in statistics.Statistics)
                {
                    series1.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(item.Time), item.ComeToRegistrationPage));
                    series2.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(item.Time), item.ValidatedBySms));
                    series3.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(item.Time), item.Registered));
                    series4.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(item.Time), item.Voted));
                }
                _xAxis.SetAxisMinMax(statistics.StartTime, statistics.EndTime);
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #20
0
        public BlockTimePlotModelHelper()
        {
            _plotModel = new PlotModel();
            var xAxis = new LinearAxis()
            {
                Position = AxisPosition.Bottom,
                Key      = XAxisKey
            };

            _plotModel.Axes.Add(xAxis);

            var yAxis = new TimeSpanAxis()
            {
                Position        = AxisPosition.Left,
                Key             = "y_axis",
                AbsoluteMinimum = TimeSpanAxis.ToDouble(TimeSpan.Zero),
                Minimum         = TimeSpanAxis.ToDouble(TimeSpan.Zero)
            };

            _plotModel.Axes.Add(yAxis);
        }
예제 #21
0
        public StatisticsPlotModelHelper()
        {
            _plotModel = new PlotModel();
            _xAxis     = new TimeSpanAxis()
            {
                Position        = AxisPosition.Bottom,
                Key             = "x_axis",
                AbsoluteMinimum = TimeSpanAxis.ToDouble(TimeSpan.Zero),
                Minimum         = TimeSpanAxis.ToDouble(TimeSpan.Zero)
            };
            _plotModel.Axes.Add(_xAxis);

            var yAxis = new LinearAxis()
            {
                Position        = AxisPosition.Left,
                Key             = "y_axis",
                AbsoluteMinimum = 0,
                Minimum         = 0
            };

            _plotModel.Axes.Add(yAxis);
        }
        public static LineSeries CreateSeries(VotingResults votingResults, Func <Vote, bool> filter, out int total)
        {
            LineSeries series = new LineSeries()
            {
                CanTrackerInterpolatePoints = false
            };

            var points = votingResults.Votes
                         .Where(x => filter(x))
                         .GroupBy(x => x.Time, (key, votes) => new TimeGraphItem <int>(key, votes.Count()))
                         .OrderBy(x => x.Time)
                         .ToArray();

            int totalVotedByTime = 0;

            for (int i = 0; i < points.Length; i++)
            {
                totalVotedByTime += points[i].Data;
                series.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(points[i].Time), totalVotedByTime));
            }
            total = totalVotedByTime;
            return(series);
        }
예제 #23
0
        public void ShowLastConstValueInterpolatedBlockGraphItems(bool setMinTime, BlockGraphItem <TimeSpan>[] array)
        {
            lock (_plotModel.SyncRoot)
            {
                ConfigureAxes(setMinTime, array);

                var series             = PrepareSeries();
                int lastBlock          = array[0].BlockNumber;
                var lastBlockTimeValue = TimeSpanAxis.ToDouble(array[0].Data);
                series.Points.Add(new DataPoint(lastBlock, lastBlockTimeValue));


                for (int i = 1; i < array.Length; i++)
                {
                    var prevAverageBlock = array[i].BlockNumber - 1;
                    if (lastBlock < prevAverageBlock)
                    {
                        lastBlockTimeValue = TimeSpanAxis.ToDouble(array[i].Data);
                        // расширяем значение на предыдущие блоки
                        series.Points.Add(new DataPoint(lastBlock + 1, lastBlockTimeValue));

                        // добавляем значение
                        lastBlock = array[i].BlockNumber;
                        series.Points.Add(new DataPoint(lastBlock, lastBlockTimeValue));
                    }
                    else
                    {
                        // просто добавляем это значение
                        lastBlock          = array[i].BlockNumber;
                        lastBlockTimeValue = TimeSpanAxis.ToDouble(array[i].Data);
                        series.Points.Add(new DataPoint(lastBlock, lastBlockTimeValue));
                    }
                }
            }
            _plotModel.InvalidatePlot(true);
        }
예제 #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="yIsTimeAxis">Является ли y осью времени (а не интервала)</param>
        public BlockTimePlotModelDrawer(bool yIsTimeAxis = false)
        {
            _yIsTimeAxis = yIsTimeAxis;
            _plotModel   = new PlotModel();
            var xAxis = new LinearAxis()
            {
                Position = AxisPosition.Bottom,
                Key      = XAxisKey,
                Title    = "Block Number"
            };

            _plotModel.Axes.Add(xAxis);

            var yAxis = new TimeSpanAxis()
            {
                Position        = AxisPosition.Left,
                Key             = YAxisKey,
                AbsoluteMinimum = TimeSpanAxis.ToDouble(TimeSpan.Zero),
                Minimum         = TimeSpanAxis.ToDouble(TimeSpan.Zero),
                Title           = "Time"
            };

            _plotModel.Axes.Add(yAxis);
        }
예제 #25
0
        // updates the graphs and graph averages for a selected lap
        private void updateGraphsAndData(int selectedLapIndex)
        {
            Lap      lap   = ActiveActivity.Laps[selectedLapIndex];
            DateTime start = lap.Trackpoints.First().Time;

            double max = 0;
            double min = 0;

            //update watts graph
            if (ActiveType == Sport.Biking)
            {
                List <DataPoint> wattsDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as BikeExtension).Watts)).ToList());

                Console.WriteLine(wattsDataPoints.First().X);

                max = wattsDataPoints.Max(x => x.X) + 1;
                min = wattsDataPoints.Min(x => x.X);

                if (wattsDataPoints[0].Y >= 0)
                {
                    WattsData = new GraphData(wattsDataPoints, max, min);
                }
                else
                {
                    WattsData = null;
                }
            }

            // update hr graph
            List <DataPoint> hrDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.HeartRate)).ToList());

            max = hrDataPoints.Max(x => x.X) + 1;
            min = hrDataPoints.Min(x => x.X);

            if (hrDataPoints[0].Y >= 0)
            {
                HeartRateData = new GraphData(hrDataPoints, max, min);
            }
            else
            {
                HeartRateData = null;
            }

            //update speed graph
            List <DataPoint> speedDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Extensions.Speed)).ToList());

            max = speedDataPoints.Max(x => x.X) + 1;
            min = speedDataPoints.Min(x => x.X);

            if (speedDataPoints[0].Y >= 0)
            {
                SpeedData = new GraphData(speedDataPoints, max, min);
            }
            else
            {
                SpeedData = null;
            }

            if (ActiveType == Sport.Biking)
            {
                // update cadence graph
                List <DataPoint> cadenceDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Cadence)).ToList());

                max = cadenceDataPoints.Max(x => x.X) + 1;
                min = cadenceDataPoints.Min(x => x.X);

                if (cadenceDataPoints[0].Y >= 0)
                {
                    CadenceData = new GraphData(cadenceDataPoints, max, min);
                }
                else
                {
                    CadenceData = null;
                }
            }
            else if (ActiveType == Sport.Running)
            {
                // update cadence graph
                List <DataPoint> cadenceDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), (y.Extensions as RunExtension).Cadence)).ToList());

                max = cadenceDataPoints.Max(x => x.X) + 1;
                min = cadenceDataPoints.Min(x => x.X);

                if (cadenceDataPoints[0].Y >= 0)
                {
                    CadenceData = new GraphData(cadenceDataPoints, max, min);
                }
                else
                {
                    CadenceData = null;
                }
            }

            // update elevation graph
            List <DataPoint> altitudeDataPoints = new List <DataPoint>(lap.Trackpoints.Select(y => new DataPoint(TimeSpanAxis.ToDouble(y.Time - start), y.Altitude)).ToList());

            max = altitudeDataPoints.Max(x => x.X) + 1;
            min = altitudeDataPoints.Min(x => x.X);

            if (altitudeDataPoints[0].Y != -1)
            {
                ElevationData = new GraphData(altitudeDataPoints, max, min);
            }
            else
            {
                ElevationData = null;
            }

            //Update HR stats
            if (ActiveActivity != null)
            {
                double avg   = lap.AvgHeartRate;
                double maxim = lap.MaxHeartRate;
                if (avg < 0)
                {
                    HeartRateInfo = "No HR data provided :(";
                }
                else
                {
                    HeartRateInfo = "Average: " + Math.Round(avg, 0) + " bpm\nMax: " + Math.Round(maxim, 0) + " bpm";
                }
            }
            //update cadence stats
            if (ActiveActivity != null)
            {
                if (ActiveActivity is BikeActivity)
                {
                    double avg   = lap.AvgCadence;
                    double maxim = lap.MaxCadence;
                    if (avg < 0)
                    {
                        CadenceInfo = "No cadence data provided :(";
                    }
                    else
                    {
                        CadenceInfo = "Average: " + Math.Round(avg, 0) + " spm\nMax: " + Math.Round(maxim, 0) + " spm";
                    }
                }
            }
            //Update speed stats
            if (ActiveActivity != null)
            {
                double avg   = lap.AvgSpeed;
                double maxim = lap.MaxSpeed;
                if (avg < 0)
                {
                    SpeedInfo = "No speed data provided :(";
                }
                else
                {
                    SpeedInfo = "Average: " + Math.Round(avg, 2) + " mph\nMax: " + Math.Round(maxim, 2) + " mph";
                }
            }
            // update power stats
            if (ActiveActivity != null)
            {
                if (ActiveActivity is BikeActivity)
                {
                    double avg   = lap.AvgPower;
                    double maxim = lap.MaxPower;
                    if (avg < 0)
                    {
                        WattsInfo = "No power data provided :(";
                    }
                    else
                    {
                        WattsInfo = "Average: " + Math.Round(avg, 0) + " W\nMax: " + Math.Round(maxim, 0) + " W";
                    }
                }
                else
                {
                    WattsInfo = "No power data provided :(";
                }
            }

            //update elevation stats
            if (ActiveActivity != null)
            {
                var ascList  = ActiveActivity.Laps.Select(x => x.ElevationGain);
                var descList = ActiveActivity.Laps.Select(x => x.ElevationLoss);

                double asc     = lap.ElevationGain;
                double desc    = lap.ElevationLoss;
                double largest = lap.BiggestClimb;

                if (asc < 0 && desc < 0)
                {
                    ElevationInfo = "No elevation data provided :(";
                }
                else
                {
                    ElevationInfo = "Ascent: " + Math.Round(asc, 0) + " ft\nDescent: " + Math.Round(desc, 0) + " ft\nLargest climb: " + Math.Round(largest, 0) + " ft";
                }

                if (ActiveActivity != null)
                {
                    if (ActiveActivity is BikeActivity)
                    {
                        Name = (ActiveActivity as BikeActivity).Name;
                    }
                    else if (ActiveActivity is RunActivity)
                    {
                        Name = (ActiveActivity as RunActivity).Name;
                    }
                }
            }
        }
예제 #26
0
 public static void SetAxisMinMax(this TimeSpanAxis axis, TimeSpan min, TimeSpan max)
 {
     axis.AbsoluteMinimum = axis.Minimum = TimeSpanAxis.ToDouble(min);
     axis.AbsoluteMaximum = axis.Maximum = TimeSpanAxis.ToDouble(max);
 }
예제 #27
0
        public AnalysisWindow(TrackList <AudioTrack> trackList)
        {
            // init data bound variables (since they're not dependency properties, they will only be read once
            // when the control with the applied binding initializes, so the variabled need to be initialized
            // before InitializeComponent() is called)
            AnalysisMode           = AnalysisMode.Correlation;
            AnalysisWindowSize     = new TimeSpan(0, 0, 1);
            AnalysisIntervalLength = new TimeSpan(0, 0, 30);
            AnalysisSampleRate     = 22050;

            InitializeComponent();

            progressMonitor = new ProgressMonitor();
            this.trackList  = trackList;

            dataTable = new DataTable();
            dataTable.Columns.Add("Time", typeof(TimeSpan));
            dataTable.Columns.Add("Min", typeof(double));
            dataTable.Columns.Add("Max", typeof(double));
            dataTable.Columns.Add("Σ+", typeof(double));
            dataTable.Columns.Add("Σ-", typeof(double));
            dataTable.Columns.Add("|Σ|", typeof(double));
            dataTable.Columns.Add("μ+", typeof(double));
            dataTable.Columns.Add("μ-", typeof(double));
            dataTable.Columns.Add("|μ|", typeof(double));
            dataTable.Columns.Add("%", typeof(double));

            var graphStyles = new Tuple <OxyColor, MarkerType>[] {
                new Tuple <OxyColor, MarkerType>(OxyColors.YellowGreen, MarkerType.Cross), // down
                new Tuple <OxyColor, MarkerType>(OxyColors.YellowGreen, MarkerType.Plus),  // up
                new Tuple <OxyColor, MarkerType>(OxyColors.Magenta, MarkerType.Plus),      // up
                new Tuple <OxyColor, MarkerType>(OxyColors.Magenta, MarkerType.Cross),     // down
                new Tuple <OxyColor, MarkerType>(OxyColors.Magenta, MarkerType.Circle),
                new Tuple <OxyColor, MarkerType>(OxyColors.Cyan, MarkerType.Plus),         // up
                new Tuple <OxyColor, MarkerType>(OxyColors.Cyan, MarkerType.Cross),        // down
                new Tuple <OxyColor, MarkerType>(OxyColors.Cyan, MarkerType.Circle),
                new Tuple <OxyColor, MarkerType>(OxyColors.Red, MarkerType.Circle)
            };

            var plotModel = new PlotModel();

            // setup plotter axes and viewport
            plotModel.Axes.Add(new TimeSpanAxis()
            {
                Position = AxisPosition.Bottom,
                Minimum  = 0,
                Maximum  = TimeSpanAxis.ToDouble(trackList.End - trackList.Start)
            });
            plotModel.Axes.Add(new LinearAxis()
            {
                Minimum            = -0.1,
                Maximum            = 1.2,
                MajorGridlineStyle = LineStyle.Automatic,
                MinorGridlineStyle = LineStyle.Automatic
            });

            // setup plotter graph lines
            for (int i = 1; i < dataTable.Columns.Count; i++)
            {
                DataColumn column = dataTable.Columns[i];
                plotModel.Series.Add(new LineSeries {
                    Color               = graphStyles[i - 1].Item1,
                    MarkerType          = graphStyles[i - 1].Item2,
                    MarkerFill          = OxyColors.Red,
                    MarkerStroke        = OxyColors.Red,
                    Title               = column.ColumnName,
                    TrackerFormatString = "{0}\nTime: {2}\nValue: {4}" // bugfix https://github.com/oxyplot/oxyplot/issues/265
                });
            }

            plotModel.IsLegendVisible = false;
            resultPlotter.Model       = plotModel;

            dataTable.RowChanged += delegate(object sender, DataRowChangeEventArgs e) {
                if (e.Action == DataRowAction.Add)
                {
                    TimeSpan time = (TimeSpan)e.Row.ItemArray[0];
                    for (int x = 0; x < plotModel.Series.Count; x++)
                    {
                        ((LineSeries)plotModel.Series[x]).Points.Add(new DataPoint(TimeSpanAxis.ToDouble(time), (double)e.Row.ItemArray[x + 1]));
                    }
                }
                plotModel.InvalidatePlot(false);
            };
            dataTable.TableCleared += delegate(object sender, DataTableClearEventArgs e) {
                for (int x = 0; x < plotModel.Series.Count; x++)
                {
                    ((LineSeries)plotModel.Series[x]).Points.Clear();
                }
                plotModel.InvalidatePlot(false);
            };
        }
        private PlotModel MakeChart([JetBrains.Annotations.NotNull] string plotName,
                                    [ItemNotNull][JetBrains.Annotations.NotNull] List <Entry> entries,
                                    bool showTitle,
                                    [CanBeNull] LoadTypeInformation lti)
        {
            var days = new HashSet <string>();

            foreach (var entry in entries)
            {
                days.Add(entry.Day);
            }

            var    seasons      = entries.Select(x => x.Season).Distinct().ToList();
            var    maxTimeValue = 0;
            double maxVal       = 0;

            foreach (var entry in entries)
            {
                if (entry.Values.Count > maxTimeValue)
                {
                    maxTimeValue = entry.Values.Count;
                }
                if (entry.Values.Max() > maxVal)
                {
                    maxVal = entry.Values.Max();
                }
            }
            seasons.Sort();
            var plotModel1 = new PlotModel
            {
                LegendPosition    = LegendPosition.BottomCenter,
                LegendPlacement   = LegendPlacement.Outside,
                LegendOrientation = LegendOrientation.Horizontal
            };
            var strokeThickness = 1;

            if (Config.MakePDFCharts)
            {
                plotModel1.DefaultFontSize = Parameters.PDFFontSize;
                plotModel1.LegendFontSize  = Parameters.PDFFontSize;
                strokeThickness            = 1;
            }
            if (showTitle)
            {
                plotModel1.Title = plotName;
            }
            var linearAxis1 = new TimeSpanAxis
            {
                Position = AxisPosition.Bottom
            };
            var min = entries.Select(x => x.Values.Min()).Min();

            if (min > 0)
            {
                min = -0.0001;
            }

            linearAxis1.Minimum        = 0;
            linearAxis1.MinimumPadding = 0;
            linearAxis1.MinorTickSize  = 0;
            linearAxis1.MaximumPadding = 0.03;
            linearAxis1.MajorStep      = 60 * 60 * 6;
            plotModel1.Axes.Add(linearAxis1);
            double start = 0;
            var    step  = 1.0 / days.Count;

            foreach (var day in days)
            {
                var ls = new LineSeries();
                ls.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(new TimeSpan(0)), 0));
                ls.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(new TimeSpan(24, 0, 0)), 0));
                ls.Color    = OxyColors.LightGray;
                ls.YAxisKey = day;
                plotModel1.Series.Add(ls);
            }
            foreach (var daytype in days)
            {
                var linearAxis2 = new LinearAxis
                {
                    StartPosition = start,
                    EndPosition   = start + step * 0.95,
                    Key           = daytype,
                    Title         = ChartLocalizer.Get().GetTranslation(daytype + " in " + lti?.UnitOfPower),
                    MinorTickSize = 0
                };
                linearAxis1.Minimum        = min;
                linearAxis2.MinimumPadding = 0.005;
                linearAxis2.MaximumPadding = 0.1;
                linearAxis2.Maximum        = maxVal;
                plotModel1.Axes.Add(linearAxis2);

                var ls = new LineSeries
                {
                    StrokeThickness = 0.5,
                    Color           = OxyColors.Black,
                    YAxisKey        = daytype
                };
                ls.Points.Add(new DataPoint(0, 0));
                ls.Points.Add(new DataPoint(maxTimeValue, 0));
                start += step;
            }
            var colorList = new List <OxyColor>
            {
                OxyColors.Green,
                OxyColors.Red,
                OxyColors.Blue
            };
            var seasonColors = new Dictionary <string, int>();
            var seasonCount  = 0;

            foreach (var season in seasons)
            {
                seasonColors.Add(season, seasonCount);
                seasonCount++;
            }
            var labeledSeasons = new List <string>();

            for (var i = 0; i < entries.Count; i++)
            {
                var ts     = new TimeSpan(0);
                var oneDay = new TimeSpan(24, 0, 0);
#pragma warning disable VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding.
                var stepsize = new TimeSpan(oneDay.Ticks / entries[i].Values.Count);
#pragma warning restore VSD0045 // The operands of a divisive expression are both integers and result in an implicit rounding.
                var lineSeries1 = new LineSeries();
                var seasonLabel = ChartLocalizer.Get().GetTranslation(entries[i].Season);
                if (!labeledSeasons.Contains(seasonLabel))
                {
                    lineSeries1.Title = seasonLabel;
                    labeledSeasons.Add(seasonLabel);
                }
                lineSeries1.YAxisKey = entries[i].Day;
                var seasonColor = seasonColors[entries[i].Season];
                lineSeries1.Color           = colorList[seasonColor];
                lineSeries1.StrokeThickness = strokeThickness;
                for (var j = 0; j < entries[i].Values.Count; j++)
                {
                    lineSeries1.Points.Add(new DataPoint(TimeSpanAxis.ToDouble(ts), entries[i].Values[j]));
                    ts = ts.Add(stepsize);
                }
                plotModel1.Series.Add(lineSeries1);
            }

            return(plotModel1);
        }
예제 #29
0
 public static void SetAxisMin(this Axis axis, TimeSpan min)
 {
     axis.AbsoluteMinimum = axis.Minimum = TimeSpanAxis.ToDouble(min);
 }
예제 #30
0
 public static void SetAxisMax(this Axis axis, TimeSpan max)
 {
     axis.AbsoluteMaximum = axis.Maximum = TimeSpanAxis.ToDouble(max);
 }