コード例 #1
1
        private ChartValues<double> GetData()
        {
            var r = new Random();
            var trend = 100;
            var values = new ChartValues<double>();

            for (var i = 0; i < 160; i++)
            {
                var seed = r.NextDouble();
                if (seed > .8) trend += seed > .9 ? 50 : -50;
                values.Add(trend + r.Next(0, 10));
            }

            return values;
        }
コード例 #2
1
ファイル: MvvmBar.xaml.cs プロジェクト: g1ga/Live-Charts
        public void AddRandomSeries()
        {
            var r = new Random();

            var values = new ChartValues<SalesData>();
            var numberOfVals = SalesmenSeries.Count == 0 ? 5 : SalesmenSeries[0].Values.Count;
            for (var i = 0; i < numberOfVals; i++) values.Add(new SalesData
            {
                ItemsSold = r.Next(5, 30),
                Rentability = r.NextDouble() * .2,
                ItemsAverageSellPrice = 5000
            });

            SalesmenSeries.Add(new BarSeries
            {
                Title = _names[r.Next(0, _names.Count() - 1)],
                Values = values
            });
        }
コード例 #3
0
        private void AddSeriesOnClick(object sender, RoutedEventArgs e)
        {
            var vals = new ChartValues<ViewModel>();
            var r = new Random();

            for (int i = 0; i < Series[0].Values.Count; i++)
            {
                vals.Add(new ViewModel {YValue = r.Next(0, 11)});
            }

            Series.Add(new LineSeries {Values = vals, DataLabels = true});
        }
コード例 #4
0
        private ChartValues<DateTimePoint> GetData()
        {
            var r = new Random();
            var trend = 100;
            var values = new ChartValues<DateTimePoint>();

            for (var i = 0; i < 100; i++)
            {
                var seed = r.NextDouble();
                if (seed > .8) trend += seed > .9 ? 50 : -50;
                values.Add(new DateTimePoint(System.DateTime.Now.AddDays(i), trend + r.Next(0, 10)));
            }

            return values;
        }
コード例 #5
0
        public void AddRandomSeries()
        {
            var c = this.FirstOrDefault() == null ? 5 : this.First().Values.Count;

            var values = new ChartValues<SalesInfo>();
            for (int i = 0; i < c; i++)
            {
                values.Add(new SalesInfo
                {
                    Id = 1,
                    Income = _r.Next(5000, 15000),
                    Rentability = _r.NextDouble()*.15
                });
            }
            Add(new BarSeries {Title = "Random Series", Values = values});
        }
コード例 #6
0
        private void AddSeriesOnClick(object sender, RoutedEventArgs e)
        {
            var r = new Random();
            var c = SeriesCollection.Count > 0 ? SeriesCollection[0].Values.Count : 5;

            var vals = new ChartValues<ObservableValue>();

            for (var i = 0; i < c; i++)
            {
                vals.Add(new ObservableValue(r.Next(0, 10)));
            }

            SeriesCollection.Add(new PieSeries
            {
                Values = vals
            });
        }
コード例 #7
0
        public ScatterExample()
        {
            InitializeComponent();

            var r = new Random();
            ValuesA = new ChartValues<ObservablePoint>();
            ValuesB = new ChartValues<ObservablePoint>();
            ValuesC = new ChartValues<ObservablePoint>();

            for (var i = 0; i < 20; i++)
            {
                ValuesA.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
                ValuesB.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
                ValuesC.Add(new ObservablePoint(r.NextDouble() * 10, r.NextDouble() * 10));
            }

            DataContext = this;
        }
コード例 #8
0
        public ManualZAndPExample()
        {
            InitializeComponent();

            Values = new ChartValues<double>();

            var r = new Random();
            for (var i = 0; i < 100; i++)
            {
                Values.Add(r.Next(0, 10));
            }

            //In this case we are paginating the data only showing the first 25 records
            //clicking the buttons previous and next changes the page
            From = 0;
            To = 25;

            DataContext = this;
        }
コード例 #9
0
        private void AddSeriesOnClick(object sender, RoutedEventArgs e)
        {
            //Yes it also listens for series changes
            var r = new Random();

            var c = SeriesCollection[0].Values.Count;

            var val = new ChartValues<ObservableValue>();

            for (int i = 0; i < c; i++)
            {
                val.Add(new ObservableValue(r.Next(-20, 20)));
            }

            SeriesCollection.Add(new LineSeries
            {
                Values = val,
                StrokeThickness = 4,
                Fill = new SolidColorBrush(Windows.UI.Colors.Transparent),
                PointGeometrySize = 0
            });
        }
コード例 #10
0
        public DataPaginationExample()
        {
            InitializeComponent();

            var values = new ChartValues<double>();

            var r = new Random();
            for (var i = 0; i < 100; i++)
            {
                values.Add(r.Next(0, 10));
            }

            cartesianChart1.Series.Add(new LineSeries
            {
                Values = values
            });

            cartesianChart1.AxisX.Add(new Axis
            {
                MinValue = 0,
                MaxValue = 25
            });
        }
コード例 #11
0
ファイル: Drawer.cs プロジェクト: nikitc/MovementControl
        public void DrawFunction(int time1, int time2, Func <int, int, IMovementControlCondition, List <Matrix> > movementControl, IMovementControlCondition condititon)
        {
            var points = new Queue <Matrix>(movementControl(time1, time2, condititon));
            var mapper = Mappers.Xy <Point>()
                         .X(x => x.X)
                         .Y(x => x.Y);

            var values = new ChartValues <Point>();

            foreach (var point in points)
            {
                values.Add(new Point(point[0, 0], point[2, 0]));
            }

            _cartesianChart.Series = new SeriesCollection(mapper)
            {
                new LineSeries
                {
                    Title  = "Движение",
                    Values = values,
                    Fill   = Brushes.Transparent,
                }
            };
        }
コード例 #12
0
ファイル: ChartsService.cs プロジェクト: ZNTK/SWD
        public static SeriesCollection GetSeriesCollectionForLineChart(List <ValuesWithClass> valuesWithClass)
        {
            SeriesCollection      seriesCollection     = new SeriesCollection();
            List <List <double> > listOfClassification = KNearestNeighboursNColumsService.GetQualityClassificationForAllMetricAndNeighbors(valuesWithClass);
            List <string>         metrics = new List <string>()
            {
                "odległość Euklidesowa", "metryka Manhattan", "nieskończoność", "Mahalanobisa"
            };

            for (int i = 0; i < 3; i++)
            {
                ChartValues <double> chartValues = new ChartValues <double>();
                foreach (var item in listOfClassification[i])
                {
                    chartValues.Add(item);
                }
                seriesCollection.Add(new LineSeries()
                {
                    Title  = metrics[i],
                    Values = chartValues
                });
            }
            return(seriesCollection);
        }
コード例 #13
0
        public List <ChartValues <double> > CleanData()
        {
            ChartValues <double> humidityCv    = new ChartValues <double>();
            ChartValues <double> temperatureCv = new ChartValues <double>();

            double[] prev_read = { SqlReader.GetDouble(0), SqlReader.GetDouble(0) };
            bool     unclean;

            while (SqlReader.Read())
            {
                unclean = false;
                for (int i = 0; i < prev_read.Length - 1; i++)
                {
                    unclean = (Math.Abs(prev_read[i] - SqlReader.GetDouble(i)) / prev_read[i]) > 0.1;
                    if (unclean)
                    {
                        break;
                    }
                }
                if (unclean)
                {
                    continue;
                }

                prev_read[0] = SqlReader.GetDouble(0);
                prev_read[1] = SqlReader.GetDouble(1);

                humidityCv.Add(SqlReader.GetDouble(0));
                temperatureCv.Add(SqlReader.GetDouble(1));
            }
            List <ChartValues <double> > chartValues = new List <ChartValues <double> > {
                humidityCv, temperatureCv
            };

            return(chartValues);
        }
        public ServerMetricCpuValuesWindow(ServerMetric serverMetric)
        {
            InitializeComponent();

            this.ServerMetric = serverMetric;

            ChartValues <double> cpuValues = new ChartValues <double>();

            foreach (ServerMetricCpuValue cpuValue in ServerMetric.TimeSeries.CpuValues)
            {
                cpuValues.Add(cpuValue.Value);
            }

            SeriesCollection = new SeriesCollection
            {
                new LineSeries
                {
                    Title  = "CPU-Values",
                    Values = cpuValues
                }
            };

            DataContext = this;
        }
コード例 #15
0
        /// <summary>
        /// A timer that raises an event at user-defined interval.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private void TimerOnTick(object sender, EventArgs eventArgs)
        {
            Task <string> task = Task.Run(() => ExecuteUrl(tbUrl.Text));//Run a task to look for status of the server to prevent a frozen window.

            if (!string.IsNullOrWhiteSpace(task.Result))
            {
                if (IsValidJson(task.Result))
                {
                    ServerState deserializedResult = JsonConvert.DeserializeObject <ServerState>(task.Result);
                    CurrentStatus = GetServerStatus(deserializedResult.Status);
                }
                else
                {
                    CurrentStatus            = 0;
                    tslInformation.BackColor = Color.Red;
                    tslInformation.Text      = @"Offline: " + task.Result;
                }
            }
            else
            {
                CurrentStatus            = 0;
                tslInformation.BackColor = Color.Red;
                tslInformation.Text      = @"Offline";
            }
            ChartValues.Add(new MeasureModel
            {
                DateTime = DateTime.Now,
                Value    = CurrentStatus
            });

            //lets only use the last 30 values
            if (ChartValues.Count > 30)
            {
                ChartValues.RemoveAt(0);
            }
        }
コード例 #16
0
        public override SeriesCollection GeneerateSeries()
        {
            SeriesCollection seriesCollection = new SeriesCollection();

            foreach (var carPark in listListCarPark)
            {
                ChartValues <double> ts = new ChartValues <double>();
                idParkings = carPark;
                GenerateTable();
                carPark.OrderBy(x => x.month);

                foreach (var item in carPark)
                {
                    ts.Add(item.count);
                }
                seriesCollection.Add(new ColumnSeries
                {
                    Title  = carPark[0].name,
                    Values = ts
                });
                GenerateTable();
            }
            return(seriesCollection);
        }
コード例 #17
0
        public DataPaginationExample()
        {
            InitializeComponent();

            var values = new ChartValues <double>();

            var r = new Random();

            for (var i = 0; i < 100; i++)
            {
                values.Add(r.Next(0, 10));
            }

            cartesianChart1.Series.Add(new LineSeries
            {
                Values = values
            });

            cartesianChart1.AxisX.Add(new Axis
            {
                MinValue = 0,
                MaxValue = 25
            });
        }
コード例 #18
0
ファイル: _Graphs.cs プロジェクト: jyupiter/Quartz
        public static void UpdateGraphs(int index, double value)
        {
            //Debug.WriteLine("UpdateGraphs: " + index + " | " + value);
            switch (index)
            {
            case 0:
                GpuValues.Add(new MeasureModel
                {
                    DateTime = DateTime.Now,
                    Value    = value
                });
                if (GpuValues.Count > 10)
                {
                    GpuValues.RemoveAt(0);
                }
                break;

            case 1:
                CpuValues.Add(new MeasureModel
                {
                    DateTime = DateTime.Now,
                    Value    = value
                });
                if (CpuValues.Count > 10)
                {
                    CpuValues.RemoveAt(0);
                }
                break;

            case 2:
                MemValues.Add(new MeasureModel
                {
                    DateTime = DateTime.Now,
                    Value    = value
                });
                if (MemValues.Count > 10)
                {
                    MemValues.RemoveAt(0);
                }
                break;

            case 3:
                DiskValues.Add(new MeasureModel
                {
                    DateTime = DateTime.Now,
                    Value    = value
                });
                if (DiskValues.Count > 10)
                {
                    DiskValues.RemoveAt(0);
                }
                break;

            case 4:
                NetValues.Add(new MeasureModel
                {
                    DateTime = DateTime.Now,
                    Value    = value
                });
                if (NetValues.Count > 10)
                {
                    NetValues.RemoveAt(0);
                }
                break;

            default:
                Debug.WriteLine("Invalid Index " + index);
                break;
            }
            //SetAxisLimits(DateTime.Now);

            //lets only use the last 150 values
        }
コード例 #19
0
        async Task DrawChart()
        {
            try
            {
                var Medias_24 = (await Api.InstaApi.GetUserMediaAsync(Api.Username, InstaSharper.Classes.PaginationParameters.MaxPagesToLoad(2))).Value;
                if (Medias_24.Count >= 20)
                {
                    #region MediaEngagementChart
                    ChartValues <double> EngagementValues = new ChartValues <double>();
                    List <string>        CountLabels      = new List <string>();
                    int i = 1;
                    foreach (var m in Medias_24)
                    {
                        EngagementValues.Add(Math.Round(((m.LikesCount * 0.4) + (double.Parse(m.CommentsCount ?? "0") * 0.6)) / (double.Parse(FollowersCount.Text)) * 100, 3));
                        CountLabels.Add(i.ToString());
                        i++;
                    }
                    if (EngagementValues.Count > 0)
                    {
                        var EngagementSeries = new SeriesCollection
                        {
                            new LineSeries {
                                Title = "ضریب تاثیر پست", Values = EngagementValues
                            }
                        };
                        MediaEngagementChart.AxisX[0].Labels = CountLabels;
                        MediaEngagementChart.AxisX[0].Margin = new Thickness(5);
                        MediaEngagementChart.AxisX[0].Separator.IsEnabled = false;
                        MediaEngagementChart.AxisX[0].Separator.Step      = 1;
                        MediaEngagementChart.AxisY[0].Position            = AxisPosition.RightTop;
                        MediaEngagementChart.Series = EngagementSeries;
                    }
                    #endregion
                    #region MediaTypeChart
                    ChartValues <double> TypeValues = new ChartValues <double>();
                    List <string>        TypeLabels = new List <string>();
                    int Video    = 0;
                    int Carousel = 0;
                    int Picture  = 0;
                    foreach (var m in Medias_24)
                    {
                        switch (m.MediaType)
                        {
                        case InstaSharper.Classes.Models.InstaMediaType.Image:
                            Picture++;
                            break;

                        case InstaSharper.Classes.Models.InstaMediaType.Video:
                            Video++;
                            break;

                        case InstaSharper.Classes.Models.InstaMediaType.Carousel:
                            Carousel++;
                            break;

                        default:
                            break;
                        }
                    }
                    var TypeSeries = new SeriesCollection
                    {
                        new PieSeries
                        {
                            Title  = "ویدئو",
                            Values = new ChartValues <int>()
                            {
                                Video
                            }
                        },
                        new PieSeries
                        {
                            Title  = "تصویر",
                            Values = new ChartValues <int>()
                            {
                                Picture
                            }
                        },
                        new PieSeries
                        {
                            Title  = "گالری",
                            Values = new ChartValues <int>()
                            {
                                Carousel
                            }
                        }
                    };
                    MediaTypeChart.Series = TypeSeries;
                    #endregion
                    #region MediaTypeFavChart
                    ChartValues <double> TypeFavValues = new ChartValues <double>();
                    List <double>        LikedVideo    = new List <double>();
                    List <double>        LikedCarousel = new List <double>();
                    List <double>        LikedPicture  = new List <double>();
                    List <double>        AllLiked      = new List <double>();
                    foreach (var m in Medias_24)
                    {
                        switch (m.MediaType)
                        {
                        case InstaSharper.Classes.Models.InstaMediaType.Image:
                            LikedPicture.Add(m.LikesCount);
                            break;

                        case InstaSharper.Classes.Models.InstaMediaType.Video:
                            LikedVideo.Add(m.LikesCount);
                            break;

                        case InstaSharper.Classes.Models.InstaMediaType.Carousel:
                            LikedCarousel.Add(m.LikesCount);
                            break;

                        default:
                            break;
                        }
                    }

                    var TypeFavSeries = new SeriesCollection
                    {
                        new RowSeries
                        {
                            Title  = "ویدئو",
                            Values = new ChartValues <double>()
                            {
                                Math.Round(LikedVideo.Average(), 2)
                            }
                        },
                        new RowSeries
                        {
                            Title  = "تصویر",
                            Values = new ChartValues <double>()
                            {
                                Math.Round(LikedPicture.Average(), 2)
                            }
                        },
                        new RowSeries
                        {
                            Title  = "گالری",
                            Values = new ChartValues <double>()
                            {
                                Math.Round(LikedCarousel.Average(), 2)
                            }
                        }
                    };
                    MediaTypeFavChart.AxisX[0].Title  = "میانگین لایک";
                    MediaTypeFavChart.AxisX[0].Margin = new Thickness(5);
                    MediaTypeFavChart.AxisY.Clear();
                    MediaTypeFavChart.Hoverable = true;
                    MediaTypeFavChart.AxisX[0].Separator.IsEnabled = true;
                    MediaTypeFavChart.Series = TypeFavSeries;
                    #endregion
                    #region MediaLikeCommentChart
                    ChartValues <double> CommentValues = new ChartValues <double>();
                    ChartValues <double> LikeValues    = new ChartValues <double>();
                    foreach (var m in Medias_24)
                    {
                        LikeValues.Add(m.LikesCount);
                        CommentValues.Add(int.Parse(m.CommentsCount ?? "0"));
                    }
                    var MediaLikeCommentSeries = new SeriesCollection
                    {
                        new LineSeries
                        {
                            Title     = "لایک",
                            Values    = LikeValues,
                            ScalesYAt = 0
                        },
                        new LineSeries
                        {
                            Title     = "کامنت",
                            Values    = CommentValues,
                            ScalesYAt = 1
                        }
                    };
                    MediaLikeCommentChart.Series = MediaLikeCommentSeries;
                    MediaLikeCommentChart.AxisY.Clear();
                    MediaLikeCommentChart.AxisY.Add(new Axis()
                    {
                        Title = "تعداد لایک", Position = AxisPosition.LeftBottom
                    });
                    MediaLikeCommentChart.AxisY.Add(new Axis()
                    {
                        Title = "تعداد نظرات", Position = AxisPosition.RightTop
                    });
                    MediaLikeCommentChart.AxisY[0].Separator.IsEnabled = false;
                    MediaLikeCommentChart.AxisY[1].Separator.IsEnabled = false;
                    MediaLikeCommentChart.AxisX[0].Labels = CountLabels;
                    MediaLikeCommentChart.AxisX[0].Separator.IsEnabled = false;
                    MediaLikeCommentChart.AxisX[0].Separator.Step      = 1;
                    #endregion
                    #region PostCountChart
                    ChartValues <double> PostCountValues = new ChartValues <double>();
                    List <string>        DateLabels      = new List <string>();
                    for (int jasemindex = 0; jasemindex < 31; jasemindex++)
                    {
                        PostCountValues.Add(0);
                        DateLabels.Add((jasemindex + 1).ToString());
                    }
                    foreach (var m in Medias_24)
                    {
                        PostCountValues[int.Parse(m.TakenAt.Day.ToString())]++;
                    }
                    var PostCountSeries = new SeriesCollection
                    {
                        new ColumnSeries
                        {
                            Title     = "تعداد",
                            Values    = PostCountValues,
                            ScalesYAt = 0
                        }
                    };
                    PostCountChart.Series          = PostCountSeries;
                    PostCountChart.AxisX[0].Labels = DateLabels;
                    PostCountChart.AxisX[0].Separator.IsEnabled = true;
                    PostCountChart.AxisX[0].Separator.Step      = 1;
                    #endregion
                }
                //Hashtag Feq
                //    List<string> _HashtagssList = new List<string>();
                //    foreach (var m in Medias_24)
                //    {
                //        var hlist = m.Caption.Text.Split('#');
                //        if (hlist.Count() > 1)
                //        {
                //            for (int hindex = 1; hindex < hlist.Count(); hindex++)
                //            {
                //                _HashtagssList.Add(hlist[hindex].Split(' ')[0]);
                //            }
                //        }
                //    }
                //    SeriesCollection _HashtagssSeriesCollection = new SeriesCollection
                //{
                //    new ScatterSeries
                //    {
                //        Values = new ChartValues<ScatterPoint>
                //        {
                //            new ScatterPoint(5, 5, 20),
                //            new ScatterPoint(3, 4, 80),
                //            new ScatterPoint(7, 2, 20),
                //            new ScatterPoint(2, 6, 60),
                //            new ScatterPoint(8, 2, 70)
                //        },
                //        MinPointShapeDiameter = 15,
                //        MaxPointShapeDiameter = 45
                //    }
                //};
            }
            catch
            {
            }
        }
コード例 #20
0
        public HistogramWindow(int columnNumber, int countOfIntervals)
        {
            InitializeComponent();

            AllRows allRows     = AllRows.GetInstance();
            bool    rowIsString = false;

            try
            {
                double tmp = Convert.ToDouble(allRows.FullFile[0].Value[columnNumber]);
            }
            catch
            {
                rowIsString = true;
            }

            if (rowIsString)
            {
                List <string>        allString = new List <string>();
                ChartValues <double> rowCount  = new ChartValues <double>();
                for (int i = 0; i < allRows.FullFile.Count(); i++)
                {
                    var text = allString.SingleOrDefault(s => s.Equals(allRows.FullFile[i].Value[columnNumber]));
                    if (text == null)
                    {
                        var counter = allRows.FullFile.Where(s => s.Value[columnNumber] == allRows.FullFile[i].Value[columnNumber]).Count();
                        allString.Add(allRows.FullFile[i].Value[columnNumber]);
                        rowCount.Add(counter);
                    }
                }

                string[] converter = allString.ToArray();

                SeriesCollection = new SeriesCollection
                {
                    new ColumnSeries
                    {
                        Values = rowCount
                    }
                };

                Labels    = converter;
                Formatter = value => value.ToString("N");
            }
            else
            {
                List <double>        allValue = new List <double>();
                ChartValues <double> rowCount = new ChartValues <double>();

                List <double> intervals    = new List <double>();
                double[]      minmax       = MathHelper.FindMinMax(AllRows.GetInstance().FullFile, columnNumber);
                double        intervalSize = (minmax[1] - minmax[0]) / countOfIntervals;
                double        leftLimit    = minmax[0];
                while (leftLimit < minmax[1])
                {
                    intervals.Add(leftLimit);
                    leftLimit += intervalSize;
                }
                double cell;
                for (int i = 0; i < AllRows.GetInstance().FullFile.Count; i++)
                {
                    for (int j = 0; j < intervals.Count; j++)
                    {
                        if (j == intervals.Count - 1)
                        {
                            cell = j + 1;
                            allValue.Add(cell);
                            break;
                        }
                        else if (Convert.ToDouble(AllRows.GetInstance().FullFile[i].Value[columnNumber]) < intervals[j + 1])
                        {
                            cell = j + 1;
                            allValue.Add(cell);
                            break;
                        }
                    }
                }

                string[] label = new string[intervals.Count()];

                for (int i = 0; i < intervals.Count(); i++)
                {
                    if (i == intervals.Count() - 1)
                    {
                        label[i] = "<" + intervals[i].ToString() + " : " + minmax[1].ToString() + ">";
                    }
                    else
                    {
                        label[i] = "<" + intervals[i].ToString() + " : " + intervals[i + 1].ToString() + ")";
                    }
                    var counter = allValue.Where(c => c == i + 1).Count();
                    rowCount.Add(counter);
                }

                SeriesCollection = new SeriesCollection
                {
                    new ColumnSeries
                    {
                        Values = rowCount
                    }
                };


                Labels    = label;
                Formatter = value => value.ToString("N");
            }


            ////adding series will update and animate the chart automatically
            //SeriesCollection.Add(new ColumnSeries
            //{
            //    Title = "2016",
            //    Values = new ChartValues<double> { 11, 56, 42 }
            //});

            ////also adding values updates and animates the chart automatically
            //SeriesCollection[1].Values.Add(48d);



            DataContext = this;
        }
コード例 #21
0
ファイル: StatsData.cs プロジェクト: OlaPietka/Hexapawn-WPF
 public static void Add()
 {
     Values.Add(Values.Last() + 10 + _rnd.Next(-5, 3));
 }
コード例 #22
0
        internal void SetData(string SourceID)
        {
            StatisticsClass stats;

            if (SourceID == "null")
            {
                stats = StatisticsDatabase.Statistics;
                SwitchDataGames.Visibility   = Visibility.Visible;
                SwitchDataSources.Visibility = Visibility.Visible;
            }
            else
            {
                stats = StatisticsDatabase.Get(Guid.Parse(SourceID));
                SwitchDataGames.Visibility   = Visibility.Hidden;
                SwitchDataSources.Visibility = Visibility.Hidden;
            }


            long   Total             = 0;
            long   TotalInstalled    = 0;
            long   TotalNotLaunching = 0;
            long   TotalFavorite     = 0;
            string TotalPlaytime     = "0h 00min";

            long NotPlayed  = 0;
            long Played     = 0;
            long Beaten     = 0;
            long Completed  = 0;
            long Playing    = 0;
            long Abandoned  = 0;
            long OnHold     = 0;
            long PlanToPlay = 0;

            SeriesCollection StatsGraphicsPlaytimeSeries = new SeriesCollection();

            string[] StatsGraphicsPlaytimeLabels = new string[0];
            ChartValues <CustomerForTime> SourcePlaytimeSeries = new ChartValues <CustomerForTime>();

            SeriesCollection SourceGraphicsGenresSeries = new SeriesCollection();

            if (stats != null)
            {
                // Information
                Total             = stats.Total;
                TotalInstalled    = stats.GameIsInstalled.Count;
                TotalNotLaunching = stats.GameIsNotLaunching.Count;
                TotalFavorite     = stats.GameFavorite.Count;
                TotalPlaytime     = (int)TimeSpan.FromSeconds(stats.Playtime).TotalHours + "h "
                                    + TimeSpan.FromSeconds(stats.Playtime).ToString(@"mm") + "min";

                // Game completation
                List <Counter> GameCompletionStatus = stats.GameCompletionStatus;

                for (int i = 0; i < GameCompletionStatus.Count; i++)
                {
                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.NotPlayed)
                    {
                        NotPlayed = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.Played)
                    {
                        Played = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.Beaten)
                    {
                        Beaten = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.Completed)
                    {
                        Completed = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.Playing)
                    {
                        Playing = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.Abandoned)
                    {
                        Abandoned = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.OnHold)
                    {
                        OnHold = GameCompletionStatus[i].Count;
                    }

                    if (GameCompletionStatus[i].Name == "" + CompletionStatus.PlanToPlay)
                    {
                        PlanToPlay = GameCompletionStatus[i].Count;
                    }
                }

                // Graphics playtime
                int             counter = 0;
                List <dataTemp> temp    = new List <dataTemp>();
                if (SourceID == "null")
                {
                    ConcurrentDictionary <Guid, StatisticsClass> StatisticsSourceDatabase = StatisticsDatabase.StatisticsSourceDatabase;
                    StatsGraphicsPlaytimeLabels = new string[StatisticsSourceDatabase.Count];
                    temp = new List <dataTemp>();

                    if (!(bool)SwitchDataGames.IsChecked)
                    {
                        foreach (var item in StatisticsSourceDatabase)
                        {
                            temp.Add(new dataTemp()
                            {
                                Name = item.Value.Name, Count = item.Value.Playtime
                            });
                        }
                        temp.Sort((a, b) => a.Count.CompareTo(b.Count));

                        foreach (var item in temp)
                        {
                            SourcePlaytimeSeries.Add(new CustomerForTime
                            {
                                Name   = item.Name,
                                Values = item.Count
                            });
                            StatsGraphicsPlaytimeLabels[counter] = item.Name;
                            counter += 1;
                        }
                    }
                    else
                    {
                        foreach (var itemAll in StatisticsSourceDatabase)
                        {
                            foreach (var item in itemAll.Value.GameSource)
                            {
                                temp.Add(new dataTemp()
                                {
                                    Name = item.Name, Count = item.Count
                                });
                            }
                        }

                        temp.Sort((a, b) => b.Count.CompareTo(a.Count));
                        if (temp.Count > 10)
                        {
                            temp = temp.GetRange(0, 10);
                        }
                        temp.Reverse();

                        StatsGraphicsPlaytimeLabels = new string[10];

                        foreach (var item in temp)
                        {
                            if (counter < 10)
                            {
                                SourcePlaytimeSeries.Add(new CustomerForTime
                                {
                                    Name   = item.Name,
                                    Values = item.Count
                                });
                                StatsGraphicsPlaytimeLabels[counter] = item.Name;
                                counter += 1;
                            }
                        }
                    }
                }
                else
                {
                    List <Counter> StatisticsSourceDatabase = StatisticsDatabase.Get(Guid.Parse(SourceID)).GameSource;

                    temp = new List <dataTemp>();
                    foreach (var item in StatisticsSourceDatabase)
                    {
                        temp.Add(new dataTemp()
                        {
                            Name = item.Name, Count = item.Count
                        });
                    }

                    temp.Sort((a, b) => b.Count.CompareTo(a.Count));
                    if (temp.Count > 10)
                    {
                        temp = temp.GetRange(0, 10);
                    }
                    temp.Reverse();

                    StatsGraphicsPlaytimeLabels = new string[10];

                    foreach (var item in temp)
                    {
                        if (counter < 10)
                        {
                            SourcePlaytimeSeries.Add(new CustomerForTime
                            {
                                Name = item.Name, Values = item.Count
                            });
                            StatsGraphicsPlaytimeLabels[counter] = item.Name;
                            counter += 1;
                        }
                    }
                }

                StatsGraphicsPlaytimeSeries.Add(new RowSeries
                {
                    Title  = "Playtime",
                    Values = SourcePlaytimeSeries
                });

                //Graphics genres
                temp = new List <dataTemp>();
                foreach (var item in stats.GameGenres)
                {
                    temp.Add(new dataTemp()
                    {
                        Name = item.Name, Count = item.Count
                    });
                }
                temp.Sort((a, b) => b.Count.CompareTo(a.Count));

                foreach (var item in temp)
                {
                    SourceGraphicsGenresSeries.Add(new PieSeries
                    {
                        Title  = item.Name,
                        Values = new ChartValues <CustomerForSingle> {
                            new CustomerForSingle {
                                Name = item.Name, Values = item.Count
                            }
                        },
                        DataLabels = true
                    });
                }
            }
            else
            {
            }


            countTotalGames.Content        = Total;
            countTotalInstalled.Content    = TotalInstalled;
            countTotalNotLaunching.Content = TotalNotLaunching;
            countTotalFavorite.Content     = TotalFavorite;
            countTotalPlaytime.Content     = TotalPlaytime;

            countNotPlayed.Value         = NotPlayed;
            countNotPlayed.Maximum       = (stats == null) ? 1 : stats.Total;
            labelCountNotPlayed.Content  = (stats == null) ? "" : (int)Math.Round((double)(100 * NotPlayed) / stats.Total) + "%";
            countPlayed.Value            = Played;
            countPlayed.Maximum          = (stats == null) ? 1 : stats.Total;
            labelCountPlayed.Content     = (stats == null) ? "" : (int)Math.Round((double)(100 * Played) / stats.Total) + "%";
            countBeaten.Value            = Beaten;
            countBeaten.Maximum          = (stats == null) ? 1 : stats.Total;
            labelCountBeaten.Content     = (stats == null) ? "" : (int)Math.Round((double)(100 * Beaten) / stats.Total) + "%";
            countCompleted.Value         = Completed;
            countCompleted.Maximum       = (stats == null) ? 1 : stats.Total;
            labelCountCompleted.Content  = (stats == null) ? "" : (int)Math.Round((double)(100 * Completed) / stats.Total) + "%";
            countPlaying.Value           = Playing;
            countPlaying.Maximum         = (stats == null) ? 1 : stats.Total;
            labelCountPlaying.Content    = (stats == null) ? "" : (int)Math.Round((double)(100 * Playing) / stats.Total) + "%";
            countAbandoned.Value         = Abandoned;
            countAbandoned.Maximum       = (stats == null) ? 1 : stats.Total;
            labelCountAbandoned.Content  = (stats == null) ? "" : (int)Math.Round((double)(100 * Abandoned) / stats.Total) + "%";
            countOnHold.Value            = OnHold;
            countOnHold.Maximum          = (stats == null) ? 1 : stats.Total;
            labelCountOnHold.Content     = (stats == null) ? "" : (int)Math.Round((double)(100 * OnHold) / stats.Total) + "%";
            countPlanToPlay.Value        = PlanToPlay;
            countPlanToPlay.Maximum      = (stats == null) ? 1 : stats.Total;
            labelCountPlanToPlay.Content = (stats == null) ? "" : (int)Math.Round((double)(100 * PlanToPlay) / stats.Total) + "%";


            //let create a mapper so LiveCharts know how to plot our CustomerViewModel class
            var customerVmMapper = Mappers.Xy <CustomerForTime>()
                                   .Y((value, index) => index)
                                   .X(value => value.Values);

            //lets save the mapper globally
            Charting.For <CustomerForTime>(customerVmMapper);


            //let create a mapper so LiveCharts know how to plot our CustomerViewModel class
            var customerVmMapperPie = Mappers.Xy <CustomerForSingle>()
                                      .X((value, index) => index)
                                      .Y(value => value.Values);

            //lets save the mapper globally
            Charting.For <CustomerForSingle>(customerVmMapperPie);


            StatsGraphicPlaytime.Series  = StatsGraphicsPlaytimeSeries;
            StatsGraphicPlaytimeY.Labels = StatsGraphicsPlaytimeLabels;

            StatsGraphicGenres.Series = SourceGraphicsGenresSeries;
        }
        public static void SetCaresianChartBeforeAndAfter(CartesianChart cartesianChart, Points[] points)
        {
            cartesianChart.AxisX.Clear();
            cartesianChart.AxisY.Clear();
            cartesianChart.Series.Clear();

            OptimizeErrorPoints = new Points[points.Length];

            var chartValuesOriginal           = new ChartValues <double>();
            var chartValuesBeforeOptimization = new ChartValues <double>();
            var labels = new List <string>();

            var i = -1;

            foreach (var point in points)
            {
                i += 1;

                chartValuesOriginal.Add(point.Y);

                var newY = point.Y + Convert.ToDouble(Random.Next(-1, 1));

                OptimizeErrorPoints[i] = new Points()
                {
                    X = point.X,
                    Y = point.Y - newY
                };

                chartValuesBeforeOptimization.Add(newY);
                //chartValuesBeforeOptimization.Add();

                labels.Add(point.X.ToString(CultureInfo.InvariantCulture));
            }

            var seriesOriginal = new LiveCharts.Wpf.LineSeries()
            {
                Title  = "Желаемая",
                Values = chartValuesOriginal
            };

            var seriesBeforeOptimization = new LiveCharts.Wpf.LineSeries()
            {
                Title  = "Действительная",
                Values = chartValuesBeforeOptimization
            };

            cartesianChart.Series = new SeriesCollection()
            {
                seriesOriginal,
                seriesBeforeOptimization
            };

            cartesianChart.AxisX.Add(new LiveCharts.Wpf.Axis
            {
                Title  = "Frequency",
                Labels = labels
            });

            cartesianChart.AxisY.Add(new LiveCharts.Wpf.Axis
            {
                Title          = "Sales",
                LabelFormatter = value => value.ToString(CultureInfo.InvariantCulture)
            });

            cartesianChart.LegendLocation = LegendLocation.Right;
        }
コード例 #24
0
ファイル: TrendChartPage.xaml.cs プロジェクト: berkeka/market
        private void ShowButtonClicked(object sender, RoutedEventArgs e)
        {
            // Clear the chart if it has values already
            if (Chart.Series != null)
            {
                Chart.Series.Clear();
            }

            // Exception control
            // If date fields are empty
            if (StartDatePicker.SelectedDate == null || EndDatePicker.SelectedDate == null)
            {
                MessageBox.Show("Lütfen tarihleri seçiniz"); return;
            }
            // If selected dates aren't possible
            if (StartDatePicker.SelectedDate >= EndDatePicker.SelectedDate)
            {
                MessageBox.Show("Başlangıç tarihi bitiş tarihinden önce olmalı"); return;
            }

            DateTime Start = (DateTime)StartDatePicker.SelectedDate;
            DateTime End   = (DateTime)EndDatePicker.SelectedDate;

            string dateFormat;

            if (End.Year != Start.Year)
            {
                dateFormat = "dd/MM/yyyy";
            }
            else
            {
                dateFormat = "dd/MM";
            }

            Chart.Series = new SeriesCollection {
            };

            // Calculate total days between selected dates
            int TotalDays = (int)(End - Start).TotalDays + 1;

            // Get selected Products
            var selectedItems = ProductList.SelectedItems;

            if (selectedItems.Count == 0)
            {
                MessageBox.Show("Lütfen ürün seçiniz"); return;
            }

            ChartValues <string> DateLabels = new ChartValues <string>();

            // Loop through selected items and draw a line for every item
            foreach (Product product in selectedItems)
            {
                // Create arrays for x and y values of the graph
                DateTime[]           dates = new DateTime[TotalDays];
                ChartValues <double> AmountOfProductsSold = new ChartValues <double>();

                var context = new MarketDBContext();

                // Loop for total days
                for (int i = 0; i < TotalDays; i++)
                {
                    DateTime indexDate    = Start.AddDays(i);
                    DateTime queryEndDate = indexDate.AddDays(1);

                    dates[i] = indexDate;

                    // List of sales that are between start and end date
                    List <Sale> saleList = context.Sales.Where(s => s.Date >= indexDate && s.Date < queryEndDate).ToList();

                    if (saleList.Count() > 0)
                    {
                        double amountSum = 0;
                        // Loop through each sale we found
                        foreach (Sale saleItem in saleList)
                        {
                            // Get each product that is related to the sale we are currently looping
                            // Then check if we have the selected product in those related products
                            List <ProductSale> psList = context.ProductSales.Where(s => s.SaleID == saleItem.ID)
                                                        .Where(ps => ps.ProductID == product.ID).ToList();

                            if (psList.Count > 0)
                            {
                                amountSum += psList.First().Amount;
                            }
                        }
                        // Insert the sum to the corresponding chartValue
                        AmountOfProductsSold.Insert(i, amountSum);
                    }
                    else
                    {
                        AmountOfProductsSold.Insert(i, 0);
                    }
                }

                foreach (DateTime date in dates)
                {
                    DateLabels.Add(date.ToString(dateFormat));
                }

                // Input data to the chart
                Chart.Series.Add(new LineSeries
                {
                    LineSmoothness = 0,
                    Title          = product.Name,
                    Values         = AmountOfProductsSold
                });
            }

            // Set date strings to labels on the X axis
            Chart.AxisX.First().Labels = DateLabels;
        }
コード例 #25
0
        private void PlotPoints()
        {
            var dates = new List <string>();

            foreach (var data in dataset)
            {
                var newDate = data[3].Replace('-', '/');
                if (DateTime.Parse(newDate) >= startDate && DateTime.Parse(newDate) <= endDate)
                {
                    var index  = data[5].IndexOf('.');
                    var newNum = int.Parse(data[5].Substring(0, index));
                    numCases.Add(DateTime.Parse(newDate), newNum);
                    dates.Add(newDate);
                }
            }

            ChartValues <ObservableValue> cases = new ChartValues <ObservableValue>();

            foreach (var numCasesValue in numCases.Values)
            {
                cases.Add(new ObservableValue(numCasesValue));
            }
            //cartesianChart1.Series.Add(new LineSeries
            //{
            //    Title = "Cases",
            //    Values = cases,
            //});
            //cartesianChart1.AxisX.Add(new Axis
            //{
            //    Title = "Date",
            //    Labels = dates
            //});

            /////
            //var dates = new List<string>();
            foreach (var data in dataset)
            {
                var newDate = data[3].Replace('-', '/');
                if (DateTime.Parse(newDate) >= startDate && DateTime.Parse(newDate) <= endDate)
                {
                    var index  = data[4].IndexOf('.');
                    var newNum = int.Parse(data[4].Substring(0, index));
                    numTotalCases.Add(DateTime.Parse(newDate), newNum);
                    dates.Add(newDate);
                }
            }

            ChartValues <ObservableValue> totalCases = new ChartValues <ObservableValue>();

            foreach (var numTotalCasesValue in numTotalCases.Values)
            {
                totalCases.Add(new ObservableValue(numTotalCasesValue));
            }
            //cartesianChart1.Series.Add(new LineSeries
            //{
            //    Title = "Total Cases",
            //    Values = totalCases,
            //});
            //cartesianChart1.AxisX.Add(new Axis
            //{
            //    Title = "Date",
            //    Labels = dates
            //});
            //
            // totalDeaths
            foreach (var data in dataset)
            {
                var newDate = data[3].Replace('-', '/');
                if (DateTime.Parse(newDate) >= startDate && DateTime.Parse(newDate) <= endDate)
                {
                    var index  = data[7].IndexOf('.');
                    var newNum = int.Parse(data[7].Substring(0, index));
                    numTotalDeaths.Add(DateTime.Parse(newDate), newNum);
                    dates.Add(newDate);
                }
            }

            ChartValues <ObservableValue> totalDeaths = new ChartValues <ObservableValue>();

            foreach (var numTotalDeathsValue in numTotalDeaths.Values)
            {
                totalDeaths.Add(new ObservableValue(numTotalDeathsValue));
            }
            //cartesianChart1.Series.Add(new LineSeries
            //{
            //    Title = "Total Deaths",
            //    Values = totalDeaths,
            //});
            //cartesianChart1.AxisX.Add(new Axis
            //{
            //    Title = "Date",
            //    Labels = dates
            //});

            pieChart1.Series = new SeriesCollection
            {
                new PieSeries
                {
                    Title  = "Total Cases",
                    Values = totalCases
                },
                new PieSeries
                {
                    Title  = "New Cases",
                    Values = cases
                },
                new PieSeries
                {
                    Title  = "Total Deaths",
                    Values = totalDeaths
                }
            };

            pieChart1.LegendLocation = LegendLocation.Bottom;
        }
コード例 #26
0
        //跑演算法
        private void Analysis()
        {
            SleepAlgorithm algo = new SleepAlgorithm();
            SleepIndex     SI;


            for (int i = 0; i < Global.Dialy_List.Count; i++)
            {
                if (Global.Dialy_List[i].haveSleep)
                {
                    Console.WriteLine("Sleep report");
                    Console.WriteLine(Global.Dialy_List[i].startRange);
                    Console.WriteLine(Global.Dialy_List[i].endRange);
                    double[]      z      = Global.Dialy_List[i].GetSleepZ();
                    List <double> sleepZ = new List <double>();
                    for (int j = Global.Dialy_List[i].startRange; j < Global.Dialy_List[i].endRange; j++)
                    {
                        sleepZ.Add(z[j]);
                    }
                    int[] stage = algo.Run(sleepZ.ToArray());
                    SI = algo.SleepQuality(stage);
                    Global.Dialy_List[i].SE   = SI.SE;
                    Global.Dialy_List[i].SOT  = SI.SOT;
                    Global.Dialy_List[i].WASO = SI.WASO;
                    Global.Dialy_List[i].TST  = SI.TST;
                    date.Add(Global.Dialy_List[i].GetDatetime());

                    SE.Add(SI.SE);
                    if (SI.SOT < 5)
                    {
                        SOT.Add(5);
                    }
                    else
                    {
                        SOT.Add(SI.SOT);
                    }
                    WASO.Add(SI.WASO);
                    TST.Add(SI.TST);

                    sleepDateList.Add(Global.Dialy_List[i].GetDatetime());
                    sleepDate.Add(Global.Dialy_List[i].startTime);
                    sleepRaw.Add(sleepZ);
                    sleepStage.Add(stage.ToList());
                }
            }
            SELabels      = date.ToArray();
            SOTLabels     = date.ToArray();
            WASOLabels    = date.ToArray();
            TSTLabels     = date.ToArray();
            SEFormatter   = value => value.ToString("N");
            SOTFormatter  = value => value.ToString("N");
            WASOFormatter = value => value.ToString("N");
            TSTFormatter  = value => value.ToString("N");

            SESeriesCollection[0].Values   = SE;
            SOTSeriesCollection[0].Values  = SOT;
            WASOSeriesCollection[0].Values = WASO;
            TSTSeriesCollection[0].Values  = TST;

            if (sleepDate.Count > 0)
            {
                //重新加入日期列表
                StageCombo.Items.Clear();
                foreach (string date in sleepDateList)
                {
                    StageCombo.Items.Add(date);
                }
                if (StageCombo.Items.Count > 0)
                {
                    StageCombo.SelectedIndex = 0;
                }
                stage.DataContext = new StageModel(sleepDate[0], sleepStage[0].ToArray());
                //初始化Y軸
                stageLabelAxes.Labels.Clear();
                stageLabelAxes.Labels.Add("Sleep");
                stageLabelAxes.Labels.Add("Wake");
            }
        }
コード例 #27
0
        private void btn_ThongKeThang_Click(object sender, EventArgs e)
        {
            //hiển thị năm
            lbl_Nam.Visible = true;
            cmb_Nam.Visible = true;

            //Clear
            ClearChart();

            //lấy ra năm và số lượng bệnh nhân điều trị.

            Axis axis = new Axis()
            {
                Title = "BIỂU ĐỒ BIẾN ĐỘNG THÁNG",

                FontSize  = 15,
                IsMerged  = true,
                Separator = new Separator
                {
                    StrokeThickness = 1,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(2),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(64, 79, 86))
                }
            };



            List <string> temp = new List <string>();

            for (int i = 1; i <= 12; i++)
            {
                temp.Add("Tháng " + i.ToString());
            }

            axis.Labels = temp;
            cartesianChart_ThongKe.AxisX.Add(axis);



            if (cmb_GioiTinh.Text == "Nam/Nữ")
            {
                LineSeries lineSeries = new LineSeries()
                {
                    Title = "Số bệnh nhân",
                    //Values = new ChartValues<double> { 14, 16, 13, 12, 16 },
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(93, 12, 123)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };

                ChartValues <double> ts = new ChartValues <double>();

                var grouped = (from p in Cons.dataContext.Treatments
                               where p.dayOfTreatment.Year == year
                               group p by new { month = p.dayOfTreatment.Month } into d
                               select new { d.Key.month, count = d.Count() }).OrderByDescending(g => g.month);

                for (int i = 1; i <= 12; i++)
                {
                    int x = 0;
                    foreach (var item in grouped.ToList())
                    {
                        if (item.month == i)
                        {
                            x = item.count;
                            break;
                        }
                    }
                    ts.Add(x);
                }

                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }

            if (cmb_GioiTinh.Text == "Nam")
            {
                LineSeries lineSeries = new LineSeries()
                {
                    Title           = "Số bệnh nhân",
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(93, 12, 123)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };

                ChartValues <double> ts = new ChartValues <double>();

                var grouped = (from p in Cons.dataContext.Treatments
                               join pp in Cons.dataContext.Patients on p.PatientId equals pp.PatientId
                               where p.dayOfTreatment.Year == year && pp.gender == true
                               group p by new { month = p.dayOfTreatment.Month } into d
                               select new { d.Key.month, count = d.Count() }).OrderByDescending(g => g.month);

                for (int i = 1; i <= 12; i++)
                {
                    int x = 0;
                    foreach (var item in grouped.ToList())
                    {
                        if (item.month == i)
                        {
                            x = item.count;
                            break;
                        }
                    }
                    ts.Add(x);
                }

                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }

            if (cmb_GioiTinh.Text == "Nữ")
            {
                LineSeries lineSeries = new LineSeries()
                {
                    Title           = "Số bệnh nhân",
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(93, 12, 123)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };

                ChartValues <double> ts = new ChartValues <double>();

                var grouped = (from p in Cons.dataContext.Treatments
                               join pp in Cons.dataContext.Patients on p.PatientId equals pp.PatientId
                               where p.dayOfTreatment.Year == year && pp.gender == false
                               group p by new { month = p.dayOfTreatment.Month } into d
                               select new { d.Key.month, count = d.Count() }).OrderByDescending(g => g.month);

                for (int i = 1; i <= 12; i++)
                {
                    int x = 0;
                    foreach (var item in grouped.ToList())
                    {
                        if (item.month == i)
                        {
                            x = item.count;
                            break;
                        }
                    }
                    ts.Add(x);
                }

                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }
            //dataGridView1.DataSource = grouped;
        }
コード例 #28
0
        private void GenerateChart(int v)
        {
            _values = new ChartValues <GanttPoint>();
            var labels = new List <string>();

            _values.Clear();
            OrderSchedule.DataContext = null;
            if (v < 0)
            {
                DataContext = this;
                return;
            }


            var zam = my_ListZamowin.ElementAt(v);

            var      now = DateTime.Now;
            DateTime hms = new DateTime(now.Year, now.Month, now.Day, 8, 0, 0);

            List <Double> timeList = new List <Double>();
            Double        tempTime = 0;;

            foreach (var ity in sequenceList.ElementAt(0))
            {
                timeList.Add(tempTime);
                tempTime += zam._Param[my_ColumnName.ElementAt(ity)];
            }

            foreach (var tempList in sequenceList)
            {
                int    firstIndex = FindFirstIndex(my_ColumnName, sequenceList, tempList);
                Double starTime   = timeList.ElementAt(firstIndex);
                Double endTime    = starTime;
                foreach (var ity in tempList)
                {
                    endTime += zam._Param[my_ColumnName.ElementAt(ity)];
                    _values.Add(new GanttPoint(hms.AddMinutes(starTime).Ticks, hms.AddMinutes(endTime).Ticks));
                    starTime += zam._Param[my_ColumnName.ElementAt(ity)];
                    labels.Add("Task: " + my_ColumnName.ElementAt(ity));
                }
            }


            Series = new SeriesCollection
            {
                new RowSeries
                {
                    Values     = _values,
                    DataLabels = true
                }
            };
            Formatter = value => new DateTime((long)value).ToString("H:mm");


            //for (var i = 0; i < _values.Count; i++)
            //    labels.Add("Task " + i);
            Labels = labels.ToArray();

            ResetZoomOnClick(null, null);

            OrderSchedule.DataContext = this;
        }
コード例 #29
0
 private static ChartValues<double> BuildRandomValues()
 {
     var serie = new ChartValues<double>();
     for (int i = 0; i < 10; i++) serie.Add(_random.Next(-10,10));
     return serie;
 }
コード例 #30
0
        public async Task Initialize(int channelIndex)
        {
            BciData[] sampleData = DataManager.Current.LastSample;

            var channelData = new double[sampleData.Length];

            for (int i = 0; i < sampleData.Length; ++i)
            {
                channelData[i] = sampleData[i].ChannelData[channelIndex] * DataManager.ScaleFactor;
            }

            double[] xValues = new double[channelData.Length];
            for (int i = 0; i < channelData.Length; ++i)
            {
                xValues[i] = i;
            }

            Status = "Decomposing...";
            IImfDecomposition decomp = await Emd.EnsembleDecomposeAsync(xValues, channelData,
                                                                        1000, DataManager.Current.EnsembleCount);

            Status = "Analysing...";
            IHilbertSpectrum hs = await Hsa.GetHilbertSpectrumAsync(decomp, 1.0);

            Status = null;

            _xStep = hs.MaxFrequency / XLength;

            var marginalData = new ChartValues <double>();

            for (double w = 0; w <= hs.MaxFrequency; w += _xStep)
            {
                marginalData.Add(hs.ComputeMarginalAt(w));
            }

            double marginalMin = marginalData[0], marginalMax = marginalData[0], marginalMean = 0.0;

            foreach (double val in marginalData)
            {
                marginalMean += val;
                if (val < marginalMin)
                {
                    marginalMin = val;
                }
                else if (val > marginalMax)
                {
                    marginalMax = val;
                }
            }
            marginalMean /= marginalData.Count;

            Info = $"Channel = {channelIndex+1}\nMin value = {marginalMin}\nMax value = {marginalMax}\nAverage value = {marginalMean}";

            var mapper = new CartesianMapper <double>()
                         .X((value, index) => hs.MinFrequency + index * _xStep)
                         .Y((value, index) => value);

            _marginalSpectrum = new SeriesCollection(mapper)
            {
                new LineSeries {
                    Title           = "Marginal Hilbert Spectrum",
                    Values          = marginalData,
                    PointGeometry   = DefaultGeometries.None,
                    StrokeThickness = 0.5,
                    Stroke          = new SolidColorBrush(Colors.Red)
                }
            };
            OnPropertyChanged(nameof(MarginalSpectrum));
        }
コード例 #31
0
ファイル: Quadrature.cs プロジェクト: SitamMatt/Integration
        public double expcalkaabsolut(double a, double b, int v)
        {
            //double result = 0, x = 0, fx = 0;
            //double h = (b - a) / v;
            //for (int i = 0; i <= v; i++)
            //{
            //    x = a + i * h;
            //    fx = expabsolut(x);
            //    if (i == 0 || i == v)
            //    {
            //        result += fx;
            //    }
            //    else if (i % 2 != 0)
            //    {
            //        result += 4 * fx;
            //    }
            //    else
            //    {
            //        result += 2 * fx;
            //    }
            //}
            //result *= (h / 3);
            //return result;
            var vals = new ChartValues <ObservablePoint>();
            //ofstream plik;
            //string filename("nodes" + std::to_string(v));
            //plik.open(filename);
            double result = 0, x = 0, fx = 0;
            double h = (b - a) / v;

            for (int i = 0; i <= v; i++)
            {
                x  = a + i * h;
                fx = expabsolut(x);
                vals.Add(new ObservablePoint(x, fx));
                //plik << x << " " << fx << endl;
                if (i == 0 || i == v)
                {
                    result += fx;
                }
                else if (i % 2 != 0)
                {
                    result += 4 * fx;
                }
                else
                {
                    result += 2 * fx;
                }
            }
            result *= (h / 3);
            values.Add(vals);
            //plik.close();
            return(result);

            /*double simp = 0, blad = 0, s = 0, x = 0;
             * double h = (b - a) / v;
             * for (int i = 1; i <= v; i++)
             * {
             *  x = a + i * h;
             *  blad += expabsolut(x - (h / 2));
             *  if (i < v)
             *  {
             *      s += (expabsolut(x));
             *  }
             * }
             * return (h / 6)*(expabsolut(a) + expabsolut(b) + 2 * s + 4 * blad);*/
        }
コード例 #32
0
ファイル: Chart.xaml.cs プロジェクト: yurijvolkov/Statirys
 private ChartValues<DateModel> GetData(List<DateTime> date, List<int> data)
 {
     ChartValues<DateModel> values = new ChartValues<DateModel>();
     for (int i = 0; i < date.Count; i++)
     {
         DateModel dm = new DateModel();
         dm.DateTime = date[i].Date;
         dm.Value = data[i];
         values.Add(dm);
     }
     return values;
 }
コード例 #33
0
        public DetailTripViewModel(int tripID)
        {
            TogglePieChart = true;
            ToggleCommand  = new RelayCommand <Label>((p) => { return(p != null); }, (p) =>
            {
                if (TogglePieChart)
                {
                    ChartData      = ChartMemberPaid;
                    togglePieChart = false;
                    p.Content      = "Biểu đồ tiền đã chi";
                }
                else
                {
                    ChartData      = ChartTripCosts;
                    togglePieChart = true;
                    p.Content      = "Biểu đồ tổng chi phí";
                }
            });
            CurrentTrip = DataAccess.GetTripByID(tripID);

            // Các địa điểm của chuyến đi
            Locations = DataAccess.GetTripLocations(tripID);

            // Hình ảnh của chuyển đi
            ImageCarousel = DataAccess.GetTripImages(tripID);
            ImageCount    = ImageCarousel.Count.ToString();

            // Thành viên của chuyến đi
            Members     = DataAccess.GetTripMembers(tripID);
            MemberCount = Members.Count;

            // Chi phí của chuyến đi
            TripCosts = DataAccess.GetTripCosts(tripID);
            // Tạo biểu đồ bánh
            ChartTripCosts  = new SeriesCollection();
            ChartMemberPaid = new SeriesCollection();
            // Đưa dữ liệu vào biểu đồ bánh chi phí chuyến đi
            foreach (TripCost element in TripCosts)
            {
                TotalExpenses += element.Amount;

                ChartValues <double> cost = new ChartValues <double>();
                if (element.Amount > 0)
                {
                    cost.Add(element.Amount);
                    PieSeries series = new PieSeries
                    {
                        Values = cost,
                        Title  = element.Name
                    };
                    ChartTripCosts.Add(series);
                }
            }
            // Đưa dữ liệu vào biểu đồ bánh tiền đã trả
            foreach (Member element in Members)
            {
                ChartValues <double> amount = new ChartValues <double>();
                if (element.AmountPaid > 0)
                {
                    amount.Add(element.AmountPaid);
                    PieSeries series = new PieSeries
                    {
                        Values = amount,
                        Title  = element.Name
                    };
                    ChartMemberPaid.Add(series);
                }
            }
            // Tính toán số tiền mỗi thành viên trả
            AmountSplit = 1.0 * TotalExpenses / MemberCount;
            MoneySplit  = new List <Member>();
            foreach (Member member in Members)
            {
                Member newElement = new Member(member)
                {
                    AmountPaid = AmountSplit - member.AmountPaid
                };
                MoneySplit.Add(newElement);
            }
            ChartData = ChartTripCosts;
        }
コード例 #34
0
        private void btn_ThongKeTheoNam_Click(object sender, EventArgs e)
        {
            lbl_Nam.Visible = false;
            cmb_Nam.Visible = false;
            //Clear
            ClearChart();

            //lấy ra năm và số lượng bệnh nhân điều trị.
            var genderList = Cons.dataContext.Treatments.GroupBy(x => x.dayOfTreatment.Year).Select(n => new
            {
                Nam     = n.Key,
                SoLuong = n.Count()
            }).OrderBy(n => n.Nam);

            // Add năm.
            Axis axis = new Axis()
            {
                Title = "BIỂU ĐỒ BIẾN ĐỘNG NĂM",

                FontSize  = 15,
                IsMerged  = true,
                Separator = new Separator
                {
                    StrokeThickness = 1,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(2),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(64, 79, 86))
                }
            };

            List <string> temp = new List <string>();

            foreach (var item in genderList.ToList())
            {
                temp.Add(item.Nam.ToString());
            }

            axis.Labels = temp;
            cartesianChart_ThongKe.AxisX.Add(axis);



            #region Theo năm - số lượng bệnh nhân

            if (cmb_GioiTinh.Text == "Nam/Nữ")
            {
                // vẽ biểu đồ.
                LineSeries lineSeries = new LineSeries()
                {
                    Title = "Số bệnh nhân",
                    //Values = new ChartValues<double> { 14, 16, 13, 12, 16 },
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(93, 12, 123)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };

                ChartValues <double> ts = new ChartValues <double>();

                foreach (var item in genderList.ToList())
                {
                    ts.Add(item.SoLuong);
                }
                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }

            if (cmb_GioiTinh.Text == "Nam")
            {
                ChartValues <double> ts = new ChartValues <double>();
                //lấy ra năm và số lượng bệnh nhân là nam điều trị.

                var list = from t in Cons.dataContext.Treatments
                           join p in Cons.dataContext.Patients on t.PatientId equals p.PatientId
                           where p.gender == true
                           select new
                {
                    Nam        = t.dayOfTreatment.Year,
                    MaBenhNhan = p.PatientId,
                    GioiTinh   = p.gender
                };

                // Proessing.
                int    countMale = 0;
                string oldCode   = "";
                foreach (var i in genderList.ToList())
                {
                    countMale = 0;
                    oldCode   = "";
                    foreach (var item in list.ToList())
                    {
                        if (item.GioiTinh == true && oldCode != item.MaBenhNhan && item.Nam == i.Nam)
                        {
                            countMale++;
                            oldCode = item.MaBenhNhan;
                        }
                    }
                    ts.Add(countMale);
                }


                //dataGridView1.Visible = true;
                //dataGridView1.DataSource = list;
                // vẽ biểu đồ.
                LineSeries lineSeries = new LineSeries()
                {
                    Title           = "Số bệnh nhân nam",
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(1, 135, 134)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };



                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }

            if (cmb_GioiTinh.Text == "Nữ")
            {
                ChartValues <double> ts = new ChartValues <double>();
                //lấy ra năm và số lượng bệnh nhân là nam điều trị.

                var list = from t in Cons.dataContext.Treatments
                           join p in Cons.dataContext.Patients on t.PatientId equals p.PatientId
                           where p.gender == false
                           select new
                {
                    Nam        = t.dayOfTreatment.Year,
                    MaBenhNhan = p.PatientId,
                    GioiTinh   = p.gender
                };

                // Proessing.
                int    countFemale = 0;
                string oldCode     = "";
                foreach (var i in genderList.ToList())
                {
                    countFemale = 0;
                    oldCode     = "";
                    foreach (var item in list.ToList())
                    {
                        if (item.GioiTinh == false && oldCode != item.MaBenhNhan && item.Nam == i.Nam)
                        {
                            countFemale++;
                            oldCode = item.MaBenhNhan;
                        }
                    }
                    ts.Add(countFemale);
                }
                //dataGridView1.Visible = true;
                //dataGridView1.DataSource = list;
                // vẽ biểu đồ.
                LineSeries lineSeries = new LineSeries()
                {
                    Title = "Số bệnh nhân nữ",
                    //Values = new ChartValues<double> { 14, 16, 13, 12, 16 },
                    StrokeThickness = 4,
                    StrokeDashArray = new System.Windows.Media.DoubleCollection(20),
                    Stroke          = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(205, 16, 118)),
                    LineSmoothness  = 0,
                    PointGeometry   = null
                };


                lineSeries.Values = ts;
                cartesianChart_ThongKe.Series.Add(lineSeries);
            }

            //dataGridView1.Visible = false;
            #endregion
        }
コード例 #35
0
        private void ComputeChartsDatapoints()
        {
            var globalGroups = BlockchainTransactions
                               .OrderBy(x => x.Timestamp.Date)
                               .GroupBy(x => x.Timestamp.Date);

            ChartValues <int>    dailyTransactions     = new ChartValues <int>();
            ChartValues <double> dailyCurrencyTraded   = new ChartValues <double>();
            ChartValues <double> dailyReceivedCurrency = new ChartValues <double>();
            ChartValues <double> dailySentCurrency     = new ChartValues <double>();

            Labels = new List <string>();

            foreach (var group in globalGroups)
            {
                dailyTransactions.Add(group.Count());

                double sum = 0;

                for (int i = 0; i < group.Count(); i++)
                {
                    Transaction t = group.ElementAt(i);

                    sum += t.Amount;
                }

                dailyCurrencyTraded.Add(Math.Round(sum, 4));

                Labels.Add(group.Key.ToString("yyyy.MM.dd"));
            }

            var dateGroups = UserTransactions
                             .OrderBy(x => Convert.ToDateTime(x.Timestamp).Date)
                             .GroupBy(x => Convert.ToDateTime(x.Timestamp).Date);

            foreach (var group in dateGroups)
            {
                double sumReceived = 0;
                double sumSent     = 0;

                for (int i = 0; i < group.Count(); i++)
                {
                    CustomTransaction ct = group.ElementAt(i);

                    if (ct.Recipient.Equals("You"))
                    {
                        sumReceived += ct.Amount;
                    }
                    else
                    {
                        sumSent += ct.Amount;
                    }
                }

                dailyReceivedCurrency.Add(Math.Round(sumReceived, 4));
                dailySentCurrency.Add(Math.Round(sumSent, 4));
            }

            DailyTransactions = new SeriesCollection()
            {
                new ColumnSeries()
                {
                    Title  = "Daily Global Transactions",
                    Values = dailyTransactions
                }
            };

            DailyCurrencyTraded = new SeriesCollection()
            {
                new ColumnSeries()
                {
                    Title  = "Daily Global BRC Traded",
                    Values = dailyCurrencyTraded
                }
            };

            DailyBalances = new SeriesCollection()
            {
                new StackedColumnSeries()
                {
                    Title  = "Received Currency",
                    Values = dailyReceivedCurrency
                },

                new StackedColumnSeries()
                {
                    Title  = "Sent Currency",
                    Values = dailySentCurrency
                }
            };
        }
コード例 #36
0
        public static Dictionary <string, LineSeries> GeneratePlots(Dictionary <string, List <Statement> > allStatements, DateTime startDate)
        {
            Dictionary <string, LineSeries> ret = new Dictionary <string, LineSeries>();
            double             netStart         = 0;
            double             balance          = 0;
            List <Transaction> netEntries       = new List <Transaction>();
            var mapper = Mappers.Xy <KeyValuePair <double, double> >().X(v => v.Key).Y(v => v.Value);

            foreach (string account in allStatements.Keys)
            {
                balance = -1000000;

                List <Transaction> allEntries = new List <Transaction>();
                foreach (Statement statement in allStatements[account])
                {
                    if (balance == -1000000)
                    {
                        balance   = statement.StartingBalance;
                        netStart += statement.StartingBalance;
                    }

                    foreach (Transaction entry in statement.Transactions)
                    {
                        allEntries.Add(entry);
                        netEntries.Add(entry);
                    }
                }

                allEntries = allEntries.OrderBy(e => e.Date).ToList();


                ChartValues <KeyValuePair <double, double> > entries = new ChartValues <KeyValuePair <double, double> >();
                foreach (Transaction entry in allEntries)
                {
                    double amount = entry.CheckingAmount == 0 ? (entry.SavingsAmount == 0 ? entry.CreditAmount : entry.SavingsAmount) : entry.CheckingAmount;
                    balance += amount;
                    entries.Add(new KeyValuePair <double, double>((entry.Date - startDate).TotalDays, balance));
                }

                ret[account] = new LineSeries(mapper)
                {
                    Title  = account,//.Replace(' ', '_').Replace('-','_');
                    Values = entries
                };
            }

            netEntries = netEntries.OrderBy(e => e.Date).ToList();
            ChartValues <KeyValuePair <double, double> > netPlot = new ChartValues <KeyValuePair <double, double> >();

            balance = netStart;
            foreach (Transaction entry in netEntries)
            {
                double amount = entry.CheckingAmount == 0 ? (entry.SavingsAmount == 0 ? entry.CreditAmount : entry.SavingsAmount) : entry.CheckingAmount;
                balance += amount;
                netPlot.Add(new KeyValuePair <double, double>((entry.Date - startDate).TotalDays, balance));
            }

            ret["Net"] = new LineSeries(mapper)
            {
                Title  = "Net",
                Values = netPlot
            };

            return(ret);
        }
コード例 #37
0
        private void GetChartDictinary()
        {
            this.ChartDictinary = new ObservableDictionary <string, SeriesCollection>();

            using (var db = new CAKESTOREEntities())
            {
                //Get orders list
                var ordersList = db.ORDERS.ToList();
                //Get date list from order list
                var dateList = ordersList.Select(o => o.DATE_CREATE.Value).ToList();
                //Get max date
                var maxDate = dateList.Max();
                //Get min date
                var minDate = dateList.Min();
                //Get year range (e.g 2019, 2020)
                var yearRange = GetYearRange(minDate, maxDate);

                if (yearRange.Count != 0)
                {
                    //For each year
                    yearRange.ForEach(y =>
                    {
                        // Get order list of that year
                        var ordersOfYearY = ordersList.Where(o => o.DATE_CREATE.Value.Year == y).ToList();

                        if (ordersOfYearY.Count != 0)
                        {
                            //A dictionary with key-value pair = <month, revenue of that month>
                            var orderDictionary = new Dictionary <int, double>();
                            //Initialize month of a year range
                            var months = Enumerable.Range(1, 12);

                            //For each month of a year
                            foreach (var month in months)
                            {
                                //Get order profit list of that month
                                var orderProfitOfThisMonthList = ordersOfYearY.Where(o => o.DATE_CREATE.Value.Month == month).Select(o => (double)o.TOTAL_PRICE).ToList();
                                //Calculate sum profit of that month
                                var profitOfThisMonth = orderProfitOfThisMonthList.Sum();
                                //Add to dictinary
                                orderDictionary.Add(month, profitOfThisMonth);
                            }

                            //A chart values for chart (expeted 12 double value corresponding to 12 month of year)
                            var chartValues = new ChartValues <double>();

                            //For each value in dictionary
                            foreach (var item in orderDictionary.Values)
                            {
                                //Add value to chart values
                                chartValues.Add(item);
                            }

                            //Initialize a seriessCollection corresponding to chart of that year
                            var seriesCollection = new SeriesCollection
                            {
                                //Initialize a column series corresponding to revenue of each month of a year
                                new ColumnSeries
                                {
                                    //Year
                                    Title = y.ToString(),
                                    //Chart values for each month of that year
                                    Values = chartValues
                                }
                            };

                            //Add to chart dictionary
                            this.ChartDictinary.Add(y.ToString(), seriesCollection);
                        }
                    });
                }
            };
            this.SelectedIndex = ChartDictinary.Count - 1;
        }
コード例 #38
0
        private void SetStaticChart(IList <double> frametimes)
        {
            if (frametimes == null || !frametimes.Any())
            {
                return;
            }

            double GeMetricValue(IList <double> sequence, EMetric metric) =>
            _frametimeStatisticProvider.GetFpsMetricValue(sequence, metric);

            var max                       = GeMetricValue(frametimes, EMetric.Max);
            var p99_quantile              = GeMetricValue(frametimes, EMetric.P99);
            var p95_quantile              = GeMetricValue(frametimes, EMetric.P95);
            var average                   = GeMetricValue(frametimes, EMetric.Average);
            var p0dot1_quantile           = GeMetricValue(frametimes, EMetric.P0dot1);
            var p0dot2_quantile           = GeMetricValue(frametimes, EMetric.P0dot2);
            var p1_quantile               = GeMetricValue(frametimes, EMetric.P1);
            var p5_quantile               = GeMetricValue(frametimes, EMetric.P5);
            var p1_averageLow             = GeMetricValue(frametimes, EMetric.OnePercentLow);
            var p0dot1_averageLow         = GeMetricValue(frametimes, EMetric.ZerodotOnePercentLow);
            var min                       = GeMetricValue(frametimes, EMetric.Min);
            var adaptiveStandardDeviation = GeMetricValue(frametimes, EMetric.AdaptiveStd);

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                IChartValues values = new ChartValues <double>();

                if (_appConfiguration.UseSingleRecordAdaptiveSTDStatisticParameter && !double.IsNaN(adaptiveStandardDeviation))
                {
                    values.Add(adaptiveStandardDeviation);
                }
                if (_appConfiguration.UseSingleRecordMinStatisticParameter)
                {
                    values.Add(min);
                }
                if (_appConfiguration.UseSingleRecordP0Dot1LowAverageStatisticParameter && !double.IsNaN(p0dot1_averageLow))
                {
                    values.Add(p0dot1_averageLow);
                }
                if (_appConfiguration.UseSingleRecordP0Dot1QuantileStatisticParameter)
                {
                    values.Add(p0dot1_quantile);
                }
                if (_appConfiguration.UseSingleRecordP0Dot2QuantileStatisticParameter)
                {
                    values.Add(p0dot2_quantile);
                }
                if (_appConfiguration.UseSingleRecordP1LowAverageStatisticParameter && !double.IsNaN(p1_averageLow))
                {
                    values.Add(p1_averageLow);
                }
                if (_appConfiguration.UseSingleRecordP1QuantileStatisticParameter)
                {
                    values.Add(p1_quantile);
                }
                if (_appConfiguration.UseSingleRecordP5QuantileStatisticParameter)
                {
                    values.Add(p5_quantile);
                }
                if (_appConfiguration.UseSingleRecordAverageStatisticParameter)
                {
                    values.Add(average);
                }
                if (_appConfiguration.UseSingleRecordP95QuantileStatisticParameter)
                {
                    values.Add(p95_quantile);
                }
                if (_appConfiguration.UseSingleRecord99QuantileStatisticParameter)
                {
                    values.Add(p99_quantile);
                }
                if (_appConfiguration.UseSingleRecordMaxStatisticParameter)
                {
                    values.Add(max);
                }

                StatisticCollection = new SeriesCollection
                {
                    new RowSeries
                    {
                        Title        = RecordInfo.GameName,
                        Fill         = new SolidColorBrush(Color.FromRgb(241, 125, 32)),
                        Values       = values,
                        DataLabels   = true,
                        FontSize     = 11,
                        MaxRowHeigth = 30
                    }
                };

                double maxOffset = (values as IList <double>).Max() * 0.15;
                BarMaxValue      = (int)((values as IList <double>).Max() + maxOffset);

                var parameterLabelList = new List <string>();

                //{ "Adaptive STD", "Min", "0.1% Low", "0.1%", "0.2%", "1% Low", "1%", "5%", "Average", "95%", "99%", "Max" }
                if (_appConfiguration.UseSingleRecordAdaptiveSTDStatisticParameter && !double.IsNaN(adaptiveStandardDeviation))
                {
                    parameterLabelList.Add("Adaptive STD");
                }
                if (_appConfiguration.UseSingleRecordMinStatisticParameter)
                {
                    parameterLabelList.Add("Min");
                }
                if (_appConfiguration.UseSingleRecordP0Dot1LowAverageStatisticParameter && !double.IsNaN(p0dot1_averageLow))
                {
                    parameterLabelList.Add("0.1% Low");
                }
                if (_appConfiguration.UseSingleRecordP0Dot1QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P0.1");
                }
                if (_appConfiguration.UseSingleRecordP0Dot2QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P0.2");
                }
                if (_appConfiguration.UseSingleRecordP1LowAverageStatisticParameter && !double.IsNaN(p1_averageLow))
                {
                    parameterLabelList.Add("1% Low");
                }
                if (_appConfiguration.UseSingleRecordP1QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P1");
                }
                if (_appConfiguration.UseSingleRecordP5QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P5");
                }
                if (_appConfiguration.UseSingleRecordAverageStatisticParameter)
                {
                    parameterLabelList.Add("Average");
                }
                if (_appConfiguration.UseSingleRecordP95QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P95");
                }
                if (_appConfiguration.UseSingleRecord99QuantileStatisticParameter)
                {
                    parameterLabelList.Add("P99");
                }
                if (_appConfiguration.UseSingleRecordMaxStatisticParameter)
                {
                    parameterLabelList.Add("Max");
                }

                ParameterLabels = parameterLabelList.ToArray();
            }));
        }
コード例 #39
0
        public AchievementsGraphicsDataCountSources GetCountBySources()
        {
            List <string> tempSourcesLabels = new List <string>();

            if (PluginSettings.EnableRetroAchievementsView && PluginSettings.EnableRetroAchievements)
            {
                if (_isRetroachievements)
                {
                    if (PluginSettings.EnableRetroAchievements)
                    {
                        tempSourcesLabels.Add("RetroAchievements");
                    }
                }
                else
                {
                    if (PluginSettings.EnableGog)
                    {
                        tempSourcesLabels.Add("GOG");
                    }
                    if (PluginSettings.EnableSteam)
                    {
                        tempSourcesLabels.Add("Steam");
                    }
                    if (PluginSettings.EnableOrigin)
                    {
                        tempSourcesLabels.Add("Origin");
                    }
                    if (PluginSettings.EnableXbox)
                    {
                        tempSourcesLabels.Add("Xbox");
                    }
                    if (PluginSettings.EnableLocal)
                    {
                        tempSourcesLabels.Add("Playnite");
                        tempSourcesLabels.Add("Hacked");
                    }
                    if (PluginSettings.EnableRpcs3Achievements)
                    {
                        tempSourcesLabels.Add("RPCS3");
                    }
                }
            }
            else
            {
                if (PluginSettings.EnableGog)
                {
                    tempSourcesLabels.Add("GOG");
                }
                if (PluginSettings.EnableSteam)
                {
                    tempSourcesLabels.Add("Steam");
                }
                if (PluginSettings.EnableOrigin)
                {
                    tempSourcesLabels.Add("Origin");
                }
                if (PluginSettings.EnableXbox)
                {
                    tempSourcesLabels.Add("Xbox");
                }
                if (PluginSettings.EnableRetroAchievements)
                {
                    tempSourcesLabels.Add("RetroAchievements");
                }
                if (PluginSettings.EnableRpcs3Achievements)
                {
                    tempSourcesLabels.Add("RPCS3");
                }
                if (PluginSettings.EnableLocal)
                {
                    tempSourcesLabels.Add("Playnite");
                    tempSourcesLabels.Add("Hacked");
                }
            }

            tempSourcesLabels.Sort((x, y) => x.CompareTo(y));

            string[] GraphicsAchievementsLabels = new string[tempSourcesLabels.Count];
            List <AchievementsGraphicsDataSources> tempDataUnlocked = new List <AchievementsGraphicsDataSources>();
            List <AchievementsGraphicsDataSources> tempDataLocked   = new List <AchievementsGraphicsDataSources>();
            List <AchievementsGraphicsDataSources> tempDataTotal    = new List <AchievementsGraphicsDataSources>();

            for (int i = 0; i < tempSourcesLabels.Count; i++)
            {
                GraphicsAchievementsLabels[i] = TransformIcon.Get(tempSourcesLabels[i]);
                tempDataLocked.Add(new AchievementsGraphicsDataSources {
                    source = tempSourcesLabels[i], value = 0
                });
                tempDataUnlocked.Add(new AchievementsGraphicsDataSources {
                    source = tempSourcesLabels[i], value = 0
                });
                tempDataTotal.Add(new AchievementsGraphicsDataSources {
                    source = tempSourcesLabels[i], value = 0
                });
            }


            foreach (var item in Database.Items)
            {
                if (!item.Value.HaveAchivements || item.Value.IsDeleted)
                {
                    continue;
                }

                try
                {
                    string SourceName = PlayniteTools.GetSourceName(_PlayniteApi, item.Key);

                    foreach (Achievements achievements in item.Value.Items)
                    {
                        for (int i = 0; i < tempDataUnlocked.Count; i++)
                        {
                            if (tempDataUnlocked[i].source == SourceName)
                            {
                                tempDataTotal[i].value += 1;
                                if (achievements.DateUnlocked != default(DateTime))
                                {
                                    tempDataUnlocked[i].value += 1;
                                }
                                if (achievements.DateUnlocked == default(DateTime))
                                {
                                    tempDataLocked[i].value += 1;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.LogError(ex, "SuccessStory", $"Error on GetCountBySources() for {item.Key}");
                }
            }

            ChartValues <CustomerForSingle> SourceAchievementsSeriesUnlocked = new ChartValues <CustomerForSingle>();
            ChartValues <CustomerForSingle> SourceAchievementsSeriesLocked   = new ChartValues <CustomerForSingle>();
            ChartValues <CustomerForSingle> SourceAchievementsSeriesTotal    = new ChartValues <CustomerForSingle>();

            for (int i = 0; i < tempDataUnlocked.Count; i++)
            {
                SourceAchievementsSeriesUnlocked.Add(new CustomerForSingle
                {
                    Name   = TransformIcon.Get(tempDataUnlocked[i].source),
                    Values = tempDataUnlocked[i].value
                });
                SourceAchievementsSeriesLocked.Add(new CustomerForSingle
                {
                    Name   = TransformIcon.Get(tempDataLocked[i].source),
                    Values = tempDataLocked[i].value
                });
                SourceAchievementsSeriesTotal.Add(new CustomerForSingle
                {
                    Name   = TransformIcon.Get(tempDataTotal[i].source),
                    Values = tempDataTotal[i].value
                });
            }


            return(new AchievementsGraphicsDataCountSources
            {
                Labels = GraphicsAchievementsLabels,
                SeriesLocked = SourceAchievementsSeriesLocked,
                SeriesUnlocked = SourceAchievementsSeriesUnlocked,
                SeriesTotal = SourceAchievementsSeriesTotal
            });
        }
コード例 #40
0
        public void GetActivityForGamesLogGraphics(GameActivityClass gameActivity, bool withTitle, string dateSelected = "")
        {
            List <ActivityDetailsData> gameActivitiesDetails = gameActivity.GetSessionActivityDetails(dateSelected);

            string[] activityForGameLogLabels             = new string[0];
            List <ActivityDetailsData> gameLogsDefinitive = new List <ActivityDetailsData>();

            if (gameActivitiesDetails.Count > 0)
            {
                if (gameActivitiesDetails.Count > 10)
                {
                    // Variateur
                    int conteurEnd   = gameActivitiesDetails.Count + variateurLog;
                    int conteurStart = conteurEnd - 10;

                    if (conteurEnd > gameActivitiesDetails.Count)
                    {
                        int temp = conteurEnd - gameActivitiesDetails.Count;
                        conteurEnd   = gameActivitiesDetails.Count;
                        conteurStart = conteurEnd - 10;

                        variateurLog = variateurLogTemp;
                    }

                    if (conteurStart < 0)
                    {
                        conteurStart = 0;
                        conteurEnd   = 10;

                        variateurLog = variateurLogTemp;
                    }

                    variateurLogTemp = variateurLog;

                    // Create data
                    int sCount = 0;
                    activityForGameLogLabels = new string[10];
                    for (int iLog = conteurStart; iLog < conteurEnd; iLog++)
                    {
                        gameLogsDefinitive.Add(gameActivitiesDetails[iLog]);
                        activityForGameLogLabels[sCount] = Convert.ToDateTime(gameActivitiesDetails[iLog].Datelog).ToLocalTime().ToString(Playnite.Common.Constants.TimeUiFormat);
                        sCount += 1;
                    }
                }
                else
                {
                    gameLogsDefinitive = gameActivitiesDetails;

                    activityForGameLogLabels = new string[gameActivitiesDetails.Count];
                    for (int iLog = 0; iLog < gameActivitiesDetails.Count; iLog++)
                    {
                        activityForGameLogLabels[iLog] = Convert.ToDateTime(gameActivitiesDetails[iLog].Datelog).ToLocalTime().ToString(Playnite.Common.Constants.TimeUiFormat);
                    }
                }
            }
            else
            {
                return;
            }

            // Set data in graphic.
            ChartValues <int> CPUseries = new ChartValues <int>();
            ChartValues <int> GPUseries = new ChartValues <int>();
            ChartValues <int> RAMseries = new ChartValues <int>();
            ChartValues <int> FPSseries = new ChartValues <int>();

            for (int iLog = 0; iLog < gameLogsDefinitive.Count; iLog++)
            {
                CPUseries.Add(gameLogsDefinitive[iLog].CPU);
                GPUseries.Add(gameLogsDefinitive[iLog].GPU);
                RAMseries.Add(gameLogsDefinitive[iLog].RAM);
                FPSseries.Add(gameLogsDefinitive[iLog].FPS);
            }

            SeriesCollection activityForGameLogSeries = new SeriesCollection
            {
                new ColumnSeries
                {
                    Title  = "cpu usage (%)",
                    Values = CPUseries
                },
                new ColumnSeries
                {
                    Title  = "gpu usage (%)",
                    Values = GPUseries
                },
                new ColumnSeries
                {
                    Title  = "ram usage (%)",
                    Values = RAMseries
                },
                new LineSeries
                {
                    Title  = "fps",
                    Values = FPSseries
                }
            };
            Func <double, string> activityForGameLogFormatter = value => value.ToString("N");

            gameSeriesLog.DataTooltip                 = new LiveCharts.Wpf.DefaultTooltip();
            gameSeriesLog.DataTooltip.Background      = (Brush)resources.GetResource("CommonToolTipBackgroundBrush");
            gameSeriesLog.DataTooltip.Padding         = new Thickness(10);
            gameSeriesLog.DataTooltip.BorderThickness = (Thickness)resources.GetResource("CommonToolTipBorderThickness");
            gameSeriesLog.DataTooltip.BorderBrush     = (Brush)resources.GetResource("CommonToolTipBorderBrush");
            gameSeriesLog.DataTooltip.Foreground      = (Brush)resources.GetResource("CommonToolTipForeground");

            gameSeriesLog.Series       = activityForGameLogSeries;
            gameLabelsY.MinValue       = 0;
            gameLabelsX.Labels         = activityForGameLogLabels;
            gameLabelsY.LabelFormatter = activityForGameLogFormatter;

            if (withTitle)
            {
                lGameSeriesLog.Visibility = Visibility.Visible;
                lGameSeriesLog.Content    = resources.GetString("LOCGameActivityLogTitleDate") + " "
                                            + ((DateTime)gameActivitiesDetails[0].Datelog).ToString(Playnite.Common.Constants.DateUiFormat);
            }
        }
コード例 #41
0
        /// <summary>
        /// Get number achievements unlock by month for a game or not.
        /// </summary>
        /// <param name="GameID"></param>
        /// <returns></returns>
        public AchievementsGraphicsDataCount GetCountByDay(Guid?GameID = null, int limit = 11)
        {
            string[] GraphicsAchievementsLabels = new string[limit + 1];
            ChartValues <CustomerForSingle> SourceAchievementsSeries = new ChartValues <CustomerForSingle>();

            LocalDateConverter localDateConverter = new LocalDateConverter();

            // All achievements
            if (GameID == null)
            {
                for (int i = limit; i >= 0; i--)
                {
                    //GraphicsAchievementsLabels[(limit - i)] = DateTime.Now.AddDays(-i).ToString("yyyy-MM-dd");
                    GraphicsAchievementsLabels[(limit - i)] = (string)localDateConverter.Convert(DateTime.Now.AddDays(-i), null, null, null);
                    SourceAchievementsSeries.Add(new CustomerForSingle
                    {
                        //Name = DateTime.Now.AddDays(-i).ToString("yyyy-MM-dd"),
                        Name   = (string)localDateConverter.Convert(DateTime.Now.AddDays(-i), null, null, null),
                        Values = 0
                    });
                }

                try
                {
                    foreach (var item in Database.Items)
                    {
                        if (!item.Value.HaveAchivements || item.Value.IsDeleted == false)
                        {
                            continue;
                        }

                        List <Achievements> temp = item.Value.Items;
                        foreach (Achievements itemAchievements in temp)
                        {
                            if (itemAchievements.DateUnlocked != null && itemAchievements.DateUnlocked != default(DateTime))
                            {
                                //string tempDate = ((DateTime)itemAchievements.DateUnlocked).ToLocalTime().ToString("yyyy-MM-dd");
                                string tempDate = (string)localDateConverter.Convert(((DateTime)itemAchievements.DateUnlocked).ToLocalTime(), null, null, null);
                                int    index    = Array.IndexOf(GraphicsAchievementsLabels, tempDate);

                                if (index >= 0 && index < (limit + 1))
                                {
                                    SourceAchievementsSeries[index].Values += 1;
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.LogError(ex, "SuccessStory", $"Error in load GetCountByDay()");
                }
            }
            // Achievement for a game
            else
            {
                try
                {
                    List <Achievements> Achievements = GetOnlyCache((Guid)GameID).Items;

                    if (Achievements != null && Achievements.Count > 0)
                    {
                        Achievements.Sort((x, y) => ((DateTime)y.DateUnlocked).CompareTo((DateTime)x.DateUnlocked));
                        DateTime TempDateTime = DateTime.Now;

                        // Find last achievement date unlock
                        if (((DateTime)Achievements[0].DateUnlocked).ToLocalTime().ToString("yyyy-MM-dd") != "0001-01-01" && ((DateTime)Achievements[0].DateUnlocked).ToLocalTime().ToString("yyyy-MM-dd") != "1982-12-15")
                        {
                            TempDateTime = ((DateTime)Achievements[0].DateUnlocked).ToLocalTime();
                        }

                        for (int i = limit; i >= 0; i--)
                        {
                            //GraphicsAchievementsLabels[(limit - i)] = TempDateTime.AddDays(-i).ToString("yyyy-MM-dd");
                            GraphicsAchievementsLabels[(limit - i)] = (string)localDateConverter.Convert(TempDateTime.AddDays(-i), null, null, null);
                            SourceAchievementsSeries.Add(new CustomerForSingle
                            {
                                //Name = TempDateTime.AddDays(-i).ToString("yyyy-MM-dd"),
                                Name   = (string)localDateConverter.Convert((TempDateTime.AddDays(-i)), null, null, null),
                                Values = 0
                            });
                        }

                        for (int i = 0; i < Achievements.Count; i++)
                        {
                            //string tempDate = ((DateTime)Achievements[i].DateUnlocked).ToLocalTime().ToString("yyyy-MM-dd");
                            string tempDate = (string)localDateConverter.Convert(((DateTime)Achievements[i].DateUnlocked).ToLocalTime(), null, null, null);
                            int    index    = Array.IndexOf(GraphicsAchievementsLabels, tempDate);

                            if (index >= 0 && index < (limit + 1))
                            {
                                SourceAchievementsSeries[index].Values += 1;
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Common.LogError(ex, "SuccessStory", $"Error in load GetCountByDay({GameID.ToString()})");
                }
            }

            return(new AchievementsGraphicsDataCount {
                Labels = GraphicsAchievementsLabels, Series = SourceAchievementsSeries
            });
        }
コード例 #42
0
        public void reload3()
        {
            cartesianChart3.AxisX.Clear();
            cartesianChart3.AxisY.Clear();
            cartesianChart3.Series.Clear();

            List <Int64>  saldo  = new List <Int64>();
            List <Int64>  bon    = new List <Int64>();
            List <Int64>  adhoc  = new List <Int64>();
            List <Int64>  isi    = new List <Int64>();
            List <Int64>  isiCrm = new List <Int64>();
            List <String> hari   = new List <String>();

            using (SqlConnection sql = new SqlConnection(Variables.connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = sql;
                    sql.Open();
                    cmd.CommandText = "select saldo = sum(saldoAwal20 + saldoAwal50 + saldoAwal100), bon = SUM(bon20 + bon50 + bon100), adhoc = SUM(adhoc100+ adhoc50+adhoc20), isiATM = SUM(isiATM100 + isiATM50 + isiATM20) ,hari= DAY(tanggal), isiCRM = SUM(isiCRM100+ isiCRM50+ isiCRM20) from TransaksiAtms ta join Pkt p on ta.kodePkt = p.kodePkt where year(tanggal) = " + comboTahun3.SelectedValue.ToString() + areaChoose(comboArea.SelectedValue.ToString()) + " and month(tanggal) = " + comboBulan3.SelectedValue.ToString() + " group by DAY(tanggal) order by day(tanggal)";
                    SqlDataReader reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        saldo.Add((Int64)reader[0]);
                        bon.Add((Int64)reader[1]);
                        adhoc.Add((Int64)reader[2]);
                        isi.Add((Int64)reader[3]);
                        hari.Add(reader[4].ToString());
                        isiCrm.Add((Int64)reader[5]);
                    }

                    ChartValues <String> cv = new ChartValues <String>();
                    foreach (String temp in hari)
                    {
                        cv.Add(temp);
                    }
                    ChartValues <Int64> cv2 = new ChartValues <Int64>();
                    foreach (Int64 temp in isi)
                    {
                        cv2.Add(temp);
                    }
                    ChartValues <Int64> cv5 = new ChartValues <Int64>();
                    foreach (Int64 temp in saldo)
                    {
                        cv5.Add(temp);
                    }
                    ChartValues <Int64> cv6 = new ChartValues <Int64>();
                    foreach (var temp in isiCrm)
                    {
                        cv6.Add(temp);
                    }
                    cartesianChart3.Series = new SeriesCollection
                    {
                        new ColumnSeries
                        {
                            Title  = "Saldo",
                            Values = cv5,

                            //DataLabels = true,
                            LabelPoint     = p => (Math.Round((p.Y / 1000000000000), 1)).ToString() + "T",
                            Foreground     = System.Windows.Media.Brushes.Black,
                            DataLabels     = true,
                            FontSize       = 10,
                            LabelsPosition = BarLabelPosition.Top
                        },

                        new LineSeries
                        {
                            Title          = "Isi ATM",
                            Values         = cv2,
                            LabelPoint     = p => (Math.Round((p.Y / 1000000000000), 1)).ToString() + "T",
                            LineSmoothness = 0,
                            DataLabels     = true,
                            Foreground     = new SolidColorBrush(System.Windows.Media.Color.FromRgb(255, 0, 0))
                        },
                        new LineSeries
                        {
                            Title          = "Isi CRM",
                            Values         = cv6,
                            LabelPoint     = p => (Math.Round((p.Y / 1000000000), 2)).ToString() + "M",
                            LineSmoothness = 0,
                            DataLabels     = true,
                            Foreground     = new SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0)),
                            FontSize       = 8
                        },
                    };


                    cartesianChart3.AxisX.Add(new Axis
                    {
                        Title  = "Saldo ATM Nasional",
                        Labels = hari,
                        //Separator = DefaultAxes.CleanSeparator,
                        Separator = new Separator // force the separator step to 1, so it always display all labels
                        {
                            Step      = 1,
                            IsEnabled = false //disable it to make it invisible.
                        }
                    });

                    cartesianChart3.AxisY.Add(new Axis
                    {
                        Title          = "Jumlah",
                        LabelFormatter = value => (value / 1000000000000).ToString() + "T",
                        MinValue       = 0
                    });

                    //cartesianChart3.AxisY.Add(new Axis
                    //{
                    //    Title = "Jumlah",
                    //    LabelFormatter = value => value.ToString(),
                    //    MinValue = 0,
                    //    Position =AxisPosition.RightTop
                    //});

                    cartesianChart3.LegendLocation = LegendLocation.Right;

                    //example
                }
            }
        }
コード例 #43
0
        private SeriesCollection GetScoreDistribution(List<double> ratings)
        {
            ChartValues<int> chartValues = new ChartValues<int>();
            foreach (var item in ratings)
            {
                chartValues.Add(GetRatingCount(item));
            }

            var seriesCollection = new SeriesCollection();
            seriesCollection.Add(new RowSeries
            {
                Title = "Ratings",
                Values = chartValues,
                DataLabels = true,
                LabelPoint = x => x.X.ToString()
            });

            return seriesCollection;
        }