Пример #1
0
        private void UserControl_Loaded([CanBeNull] object sender, [CanBeNull] RoutedEventArgs e)
        {
            MyDeviceSelector.Simulator  = Presenter.ApplicationPresenter.Simulator;
            MyDeviceSelector.OpenItem   = Presenter.ApplicationPresenter.OpenItem;
            MyStandbySelector.Simulator = Presenter.ApplicationPresenter.Simulator;
            MyStandbySelector.OpenItem  = Presenter.ApplicationPresenter.OpenItem;
            _plot         = new PlotModel();
            _dateTimeAxis = new LinearAxis {
                Position = AxisPosition.Bottom
            };
            _plot.Axes.Add(_dateTimeAxis);
            _categoryAxis = new CategoryAxis {
                MinorStep     = 1,
                Position      = AxisPosition.Left,
                IsZoomEnabled = false,
                IsPanEnabled  = false
            };
            _dateTimeAxis.IsZoomEnabled = false;
            _dateTimeAxis.IsPanEnabled  = false;
            _plot.Axes.Add(_categoryAxis);

            var pv = new PlotView {
                Model = _plot
            };

            DeviceGrid.Children.Add(pv);
            Grid.SetRow(pv, 2);

            RefreshGraph();
        }
        private static void MakeCategoryXAxis([NotNull] PlotModel plotModel, [NotNull][ItemNotNull] List <string> categorylabels)
        {
            var xAxis = new CategoryAxis {
                Title    = "",
                Position = AxisPosition.Bottom
            };

            xAxis.Labels.AddRange(categorylabels);
            xAxis.MajorGridlineStyle = LineStyle.None;
            xAxis.AxislineColor      = OxyColors.Black;
            xAxis.AxislineStyle      = LineStyle.Solid;
            xAxis.MinimumPadding     = 0;
            xAxis.GapWidth           = 0.0;
            xAxis.Angle = -90;
            if (categorylabels.Count > 100 || categorylabels.Count == 0)
            {
                xAxis.MajorStep = 60;
            }
            else
            {
                xAxis.MajorStep = 1;
            }

            plotModel.Axes.Add(xAxis);
        }
Пример #3
0
        private void MakeModels(long PK)
        {
            DataAccess db = new DataAccess();

            measurement = db.GetMeasurements(PK);

            var    fcvHistogram = Histogram.CreateEmpty(10, 80, 40);
            double count        = 0;

            foreach (var x in measurement)
            {
                if (x.FCV != 0)
                {
                    fcvHistogram.Increment((int)x.FCV);
                    count++;// add individual data points
                }
            }

            OxyPlot.Axes.CategoryAxis xaxis = new OxyPlot.Axes.CategoryAxis();
            xaxis.Title              = "FCV(m/s)";
            xaxis.TitleFontWeight    = 700;
            xaxis.Position           = AxisPosition.Bottom;
            xaxis.MajorGridlineStyle = LineStyle.Solid;
            xaxis.MinorGridlineStyle = LineStyle.Solid;


            OxyPlot.Axes.LinearAxis yaxis = new OxyPlot.Axes.LinearAxis();
            yaxis.Title              = "%";
            yaxis.TitleFontWeight    = 700;
            yaxis.Minimum            = 0;
            yaxis.Maximum            = 100;
            yaxis.Position           = AxisPosition.Left;
            yaxis.MajorGridlineStyle = LineStyle.Solid;
            yaxis.MinorGridlineStyle = LineStyle.Solid;

            OxyPlot.Series.ColumnSeries s1 = new OxyPlot.Series.ColumnSeries();
            s1.IsStacked   = true;
            s1.StrokeColor = OxyColors.Black;
            s1.FillColor   = OxyColors.Black;
            s1.Background  = OxyColors.Beige;
            count          = 100.0 / count;
            foreach (var x in fcvHistogram.BinsAndValues)
            {
                s1.Items.Add(new ColumnItem(x.Value * count));
                xaxis.Labels.Add(x.Key.ToString().Substring(0, 3));
            }

            var Model = new PlotModel();

            Model.Title      = "Conduction Velocities";
            Model.Background = OxyColors.GhostWhite;


            Model.Axes.Add(xaxis);
            Model.Axes.Add(yaxis);
            Model.Series.Add(s1);
            model.Add(Model);
        }
Пример #4
0
        private static void MakeBarPlot([JetBrains.Annotations.NotNull] string outputPath, [ItemNotNull][JetBrains.Annotations.NotNull] List <Column> columns, int position, int day,
                                        int minutesToSum)
        {
            var plotModel2 = new PlotModel();
            var p          = OxyPalettes.HueDistinct(columns.Count);

            plotModel2.LegendPosition    = LegendPosition.BottomCenter;
            plotModel2.LegendPlacement   = LegendPlacement.Outside;
            plotModel2.LegendOrientation = LegendOrientation.Horizontal;
            plotModel2.Title             = "Day " + day;
            // axes
            var categoryAxis = new CategoryAxis
            {
                AbsoluteMinimum = 0,
                MinimumPadding  = 0,
                GapWidth        = 0,
                MajorStep       = 60,
                Title           = "Energy"
            };

            plotModel2.Axes.Add(categoryAxis);

            var linearAxis2 = new LinearAxis
            {
                AbsoluteMinimum = 0,
                MaximumPadding  = 0.06,
                MinimumPadding  = 0,
                Title           = "Minutes"
            };

            plotModel2.Axes.Add(linearAxis2);

            for (var i = 1; i < columns.Count; i++)
            {
                var columnSeries2 = new ColumnSeries
                {
                    IsStacked       = true,
                    StrokeThickness = 0,
                    Title           = columns[i].HHNumber
                };
                for (var j = position; j < position + 1440; j += minutesToSum)
                {
                    columnSeries2.Items.Add(new ColumnItem(columns[i].MakeSum(j, minutesToSum)));
                }
                columnSeries2.FillColor = p.Colors[i];
                plotModel2.Series.Add(columnSeries2);
            }
            var path2 = Path.Combine(outputPath, "Plot." + day + "." + minutesToSum + "min.bar.png");

            PngExporter.Export(plotModel2, path2, 3200, 1600, OxyColor.FromRgb(255, 255, 255), 100);
        }
Пример #5
0
        public TabCrossplots(EclipseProject ecl)
        {
            InitializeComponent();

            typeof(Control).InvokeMember("DoubleBuffered",
                                         System.Reflection.BindingFlags.SetProperty | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic,
                                         null, gridData, new object[] { true });

            model = new ChartModel(ecl);

            plotHisto = new PlotModel
            {
                DefaultFont = "Segoe UI",

                TitleFontSize   = 10,
                DefaultFontSize = 10,
            };

            var categoryAxes = new OxyPlot.Axes.CategoryAxis {
                Position          = AxisPosition.Left,
                TitleFont         = "Segoe UI Semilight",
                AxisTitleDistance = 8
            };

            categoryAxes.Title = "Relative Deviation";
            categoryAxes.Labels.Add("<10%");
            categoryAxes.Labels.Add("10-20%");
            categoryAxes.Labels.Add(">20%");

            plotHisto.Axes.Add(categoryAxes);

            plotHisto.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position  = OxyPlot.Axes.AxisPosition.Bottom,
                TitleFont = "Segoe UI Semilight",
                Title     = "Well Count"
            });

            plotView1.Model = plotHisto;

            plotHistoTotal = new PlotModel
            {
                DefaultFont     = "Segoe UI",
                TitleFontSize   = 10,
                DefaultFontSize = 10,
            };

            var categoryAxes2 = new OxyPlot.Axes.CategoryAxis {
                Position          = AxisPosition.Left,
                TitleFont         = "Segoe UI Semilight",
                AxisTitleDistance = 8
            };

            categoryAxes2.Title = "Relative Deviation";
            categoryAxes2.Labels.Add("<10%");
            categoryAxes2.Labels.Add("10-20%");
            categoryAxes2.Labels.Add(">20%");

            plotHistoTotal.Axes.Add(categoryAxes2);

            plotHistoTotal.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position  = OxyPlot.Axes.AxisPosition.Bottom,
                TitleFont = "Segoe UI Semilight",
                Title     = "Sum Hist Value"
            });

            plotView2.Model = plotHistoTotal;


            plotModel = new PlotModel
            {
                Title           = "(No keyword)",
                DefaultFont     = "Segoe UI",
                TitleFontSize   = 10,
                DefaultFontSize = 10
            };

            plotModel.Axes.Add(new LinearAxis
            {
                Position               = AxisPosition.Bottom,
                TitleFont              = "Segoe UI Semilight",
                Title                  = "Simulated",
                MajorGridlineStyle     = LineStyle.Dash,
                MajorGridlineThickness = 1,
            });


            plotModel.Axes.Add(new LinearAxis
            {
                Position               = AxisPosition.Left,
                TitleFont              = "Segoe UI Semilight",
                Title                  = "Historical",
                MajorGridlineStyle     = LineStyle.Dash,
                MajorGridlineThickness = 1,
            });

            plotView.Model = plotModel;

            boxKeywords.SelectedIndex     = 0;
            boxCriteriaType.SelectedIndex = 0;
            //
        }
        private PlotModel createBaseModel(DoubleRange? range, string title, double[] x, double[] y, bool discrete)
        {
            var plotModel = new PlotModel();
            plotModel.Series.Clear();
            plotModel.Axes.Clear();

            double ymin = y.FirstOrDefault(a => !Double.IsNaN(a) && !Double.IsInfinity(a));
            double ymax = ymin;

            for (int i = 0; i < y.Length; i++)
            {
                if (Double.IsNaN(y[i]) || Double.IsInfinity(y[i]))
                    continue;

                if (y[i] > ymax)
                    ymax = y[i];
                if (y[i] < ymin)
                    ymin = y[i];
            }

            double maxGrace = ymax * 0.1;
            double minGrace = ymin * 0.1;


            if (!discrete)
            {
                var xAxis = new OxyPlot.Axes.LinearAxis()
                {
                    Position = AxisPosition.Bottom,
                    Minimum = range.Value.Min,
                    Maximum = range.Value.Max,
                    Key = "xAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    IntervalLength = 80
                };

                var yAxis = new LinearAxis()
                {
                    Position = AxisPosition.Left,
                    Minimum = ymin - minGrace,
                    Maximum = ymax + maxGrace,
                    Key = "yAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    Title = title
                };

                plotModel.Axes.Add(xAxis);
                plotModel.Axes.Add(yAxis);

                var lineSeries = new LineSeries
                {
                    YAxisKey = yAxis.Key,
                    XAxisKey = xAxis.Key,
                    StrokeThickness = 2,
                    MarkerSize = 3,
                    MarkerStroke = OxyColor.FromRgb(0, 0, 0),
                    MarkerType = MarkerType.None,
                    Smooth = true,
                };

                for (int i = 0; i < x.Length; i++)
                {
                    if (Double.IsNaN(y[i]) || Double.IsInfinity(y[i]))
                        continue;

                    lineSeries.Points.Add(new DataPoint(x[i], y[i]));
                }

                plotModel.Series.Add(lineSeries);
            }
            else
            {
                var xAxis = new OxyPlot.Axes.CategoryAxis()
                {
                    Position = AxisPosition.Bottom,
                    Key = "xAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                };

                var yAxis = new LinearAxis()
                {
                    Position = AxisPosition.Left,
                    Minimum = ymin - minGrace,
                    Maximum = ymax + maxGrace,
                    Key = "yAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    Title = title
                };

                plotModel.Axes.Add(xAxis);
                plotModel.Axes.Add(yAxis);

                var boxSeries = new ColumnSeries
                {
                    YAxisKey = yAxis.Key,
                    XAxisKey = xAxis.Key,
                    StrokeThickness = 2,
                    ColumnWidth = 1,
                };

                for (int i = 0; i < x.Length; i++)
                {
                    xAxis.Labels.Add(x[i].ToString("G2"));
                    var item = new ColumnItem(y[i]);
                    boxSeries.Items.Add(item);
                }

                plotModel.Series.Add(boxSeries);
            }

            var formattable = instance as IFormattable;
            if (formattable != null)
            {
                plotModel.Title = formattable.ToString("G3", CultureInfo.CurrentUICulture);
            }
            else
            {
                plotModel.Title = instance.ToString();
            }

            plotModel.TitlePadding = 2;
            plotModel.TitleFontSize = 15;
            plotModel.TitleFontWeight = 1;
            plotModel.TitlePadding = 2;


            return plotModel;
        }
Пример #7
0
        public PlotModel Create(DoubleRange?range, string title, double[] x, double[] y, bool discrete)
        {
            var plotModel = new PlotModel();

            plotModel.Series.Clear();
            plotModel.Axes.Clear();

            double ymin = y.FirstOrDefault(a => !Double.IsNaN(a) && !Double.IsInfinity(a));
            double ymax = ymin;

            for (int i = 0; i < y.Length; i++)
            {
                if (Double.IsNaN(y[i]) || Double.IsInfinity(y[i]))
                {
                    continue;
                }

                if (y[i] > ymax)
                {
                    ymax = y[i];
                }
                if (y[i] < ymin)
                {
                    ymin = y[i];
                }
            }

            double maxGrace = ymax * 0.1;
            double minGrace = ymin * 0.1;

            if (!discrete)
            {
                var xAxis = new OxyPlot.Axes.LinearAxis()
                {
                    Position           = AxisPosition.Bottom,
                    Minimum            = range.Value.Min,
                    Maximum            = range.Value.Max,
                    Key                = "xAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    IntervalLength     = 80
                };

                var yAxis = new LinearAxis()
                {
                    Position           = AxisPosition.Left,
                    Minimum            = ymin - minGrace,
                    Maximum            = ymax + maxGrace,
                    Key                = "yAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    Title              = title
                };

                plotModel.Axes.Add(xAxis);
                plotModel.Axes.Add(yAxis);

                var lineSeries = new LineSeries
                {
                    YAxisKey        = yAxis.Key,
                    XAxisKey        = xAxis.Key,
                    StrokeThickness = 2,
                    MarkerSize      = 3,
                    MarkerStroke    = OxyColor.FromRgb(0, 0, 0),
                    MarkerType      = MarkerType.None,
                    Smooth          = true,
                };

                for (int i = 0; i < x.Length; i++)
                {
                    if (Double.IsNaN(y[i]) || Double.IsInfinity(y[i]))
                    {
                        continue;
                    }

                    lineSeries.Points.Add(new DataPoint(x[i], y[i]));
                }

                plotModel.Series.Add(lineSeries);
            }
            else
            {
                var xAxis = new OxyPlot.Axes.CategoryAxis()
                {
                    Position           = AxisPosition.Bottom,
                    Key                = "xAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                };

                var yAxis = new LinearAxis()
                {
                    Position           = AxisPosition.Left,
                    Minimum            = ymin - minGrace,
                    Maximum            = ymax + maxGrace,
                    Key                = "yAxis",
                    MajorGridlineStyle = LineStyle.Solid,
                    MinorGridlineStyle = LineStyle.Dot,
                    Title              = title
                };

                plotModel.Axes.Add(xAxis);
                plotModel.Axes.Add(yAxis);

                var boxSeries = new ColumnSeries
                {
                    YAxisKey        = yAxis.Key,
                    XAxisKey        = xAxis.Key,
                    StrokeThickness = 2,
                    ColumnWidth     = 1,
                };

                for (int i = 0; i < x.Length; i++)
                {
                    xAxis.Labels.Add(x[i].ToString("G2"));
                    var item = new ColumnItem(y[i]);
                    boxSeries.Items.Add(item);
                }

                plotModel.Series.Add(boxSeries);
            }

            //var formattable = instance as IFormattable;
            //if (formattable != null)
            //{
            //    plotModel.Title = formattable.ToString("G3", CultureInfo.CurrentUICulture);
            //}
            //else
            //{
            //    plotModel.Title = instance.ToString();
            //}

            plotModel.TitlePadding    = 2;
            plotModel.TitleFontSize   = 15;
            plotModel.TitleFontWeight = 1;
            plotModel.TitlePadding    = 2;

            return(plotModel);
        }
        public void Run([JetBrains.Annotations.NotNull] CalculationProfiler cp, [JetBrains.Annotations.NotNull] string outputDirectory, [JetBrains.Annotations.NotNull] string source)
        {
            //var cp =  CalculationProfiler.Read(@"C:\work\CalculationBenchmarks.ActionCarpetPlotTest\");

            InitializeDuration2(cp.MainPart);
            MergeAndCompress(cp.MainPart);
            InitPartsList(cp.MainPart);
            const int fontsize = 6;// = GetFontsize(cp.MainPart);
            //const string xaxislabel = "Time Consumption in CPUSeconds";

            OxyPalette p;

            if (_parts.Count > 1)
            {
                p = OxyPalettes.HueDistinct(_parts.Count);
            }
            else
            {
                p = OxyPalettes.Hue64;
            }
            var plotModel1 = new PlotModel
            {
                LegendBorderThickness = 0,
                LegendOrientation     = LegendOrientation.Vertical,
                LegendPlacement       = LegendPlacement.Inside,
                LegendPosition        = LegendPosition.TopLeft,
                PlotAreaBorderColor   = OxyColors.White,
                LegendFontSize        = fontsize,
                LegendSymbolMargin    = 25,
                DefaultFontSize       = fontsize
            };

            var ca = new CategoryAxis
            {
                Position       = AxisPosition.Left,
                GapWidth       = 0,
                MaximumPadding = 0.03,
                MajorTickSize  = 0
            };

            plotModel1.Axes.Add(ca);

            /* var la = new LinearAxis
             * {
             *   Minimum = 0,
             *   MinimumPadding = 0,
             *   Title = ChartLocalizer.Get().GetTranslation(xaxislabel),
             *   Position = AxisPosition.Bottom,
             *   MinorTickSize = 0
             * };*/
            /*  plotModel1.Axes.Add(la);
             * var caSub = new CategoryAxis();
             * caSub.StartPosition = 0.5;
             * caSub.EndPosition = 1;
             * caSub.Position = AxisPosition.Left;
             * caSub.Key = "Sub";
             * caSub.GapWidth = 0.3;
             * caSub.MajorTickSize = 0;
             * caSub.MinorTickSize = 0;
             * plotModel1.Axes.Add(caSub);*/
            //const double runningSum = 0;
            //var row = 0;

            // var allBarSeries = new Dictionary<string, IntervalBarSeries>();
            //var ba = new BarSeries();
            //ba.YAxisKey = "Sub";
            //ba.LabelFormatString = "{0:N1} %";

            /*  foreach (var s in taggingSet.Categories)
             * {
             *    caSub.Labels.Add(ChartLocalizer.Get().GetTranslation(s));
             *    var ibs = new IntervalBarSeries();
             *    // ibs.Title =
             *    var coloridx = taggingSet.GetCategoryIndexOfCategory(s);
             *    ibs.FillColor = p.Colors[coloridx];
             *    ibs.StrokeThickness = 0;
             *    ibs.FontSize = fontsize;
             *    allBarSeries.Add(s, ibs);
             *    double categorysum = 0;
             *    foreach (var tuple in consumption)
             *    {
             *        if (taggingSet.AffordanceToCategories[tuple.Item1] == s)
             *        {
             *            categorysum += tuple.Item2;
             *        }
             *    }
             *    var percent = categorysum / sum * 100;
             *    var bai = new BarItem(percent);
             *    bai.Color = p.Colors[coloridx];
             *    ba.Items.Add(bai);
             * }*/
            //   plotModel1.Series.Add(ba);

            var itemsByLevel = new Dictionary <int, IntervalBarSeries>();

            _textOffsets.Clear();
            AddBars(cp.MainPart, 0, 0, fontsize, itemsByLevel, p, plotModel1);
            //        foreach (IntervalBarSeries series in itemsByLevel.Values) {
            //          plotModel1.Series.Add(series);
            //    }
            string dstFileName = Path.Combine(outputDirectory,
                                              DirectoryNames.CalculateTargetdirectory(TargetDirectory.Charts), "CalculationDurationFlameChart." + source + ".Png");

            PngExporter.Export(plotModel1, dstFileName, 3200, 2000, OxyColor.FromArgb(255, 255, 255, 255),
                               144);
            //Save(plotModel1, plotName, srcEntry.FullFileName + newFileNameSuffix, basisPath); // ".interval"
        }
Пример #9
0
        ///<summary>
        /// Create and run a Fleet MSO that attempts to find the optimum fleet composition to raid this defense
        ///</summary>
        public double EvaluateDefense()
        {
            BalanceDefense();
            Console.WriteLine("\tSolving for optimum fleet to raid defense composition ["
                              + String.Join(",", defense.DefenseCounts)
                              + "]");

            Random rand = new Random();

            FleetSwarm[] fleetSwarms = new FleetSwarm[Program.NumSwarms];
            for (int i = 0; i < Program.NumSwarms; ++i)
            {
                fleetSwarms[i] = new FleetSwarm(defense);
            }
            Fleet  gBestFleet   = new Fleet();
            double gBestProfits = double.MinValue;

            for (int i = 0; i < Program.NumSwarms; ++i)
            {
                if (fleetSwarms[i].lBestProfits > gBestProfits)
                {
                    gBestProfits = fleetSwarms[i].lBestProfits;
                    gBestFleet.CopyFleet(fleetSwarms[i].lBestFleet);
                    PrintCurrentNewBestFleetComposition(gBestFleet.ShipCounts, gBestProfits, -1);
                }
            }


            var gBestList = new List <(int, double)>
            {
                (-1, gBestProfits)
            };


            int epoch = 0;
            int epochsSinceImprovement = 0;

            while (epoch < (Program.MaxEpochsInner) && epochsSinceImprovement < 500)
            {
                ++epoch;
                ++epochsSinceImprovement;

                //if (epoch < Program.MaxEpochs && epoch % 5 == 0)
                //{
                //    Console.WriteLine("Defense[" + String.Join(",", defense) + "], "
                //                        + " Epoch " + epoch
                //                        + ", Global Best Minimal Attack Cost = " + bestGlobalMinAttackCost.ToString("F4"));
                //}

                for (int i = 0; i < Program.NumSwarms; ++i) // each swarm
                {
                    // Shuffle(sequence, rand); // move particles in random sequence
                    for (int j = 0; j < Program.NumParticles; ++j) // each particle
                    {
                        //Check if Particle dies
                        double p1 = rand.NextDouble();
                        if (fleetSwarms[i].fleetParticles[j].consecutiveNonImproves * p1 > 20)
                        {
                            fleetSwarms[i].fleetParticles[j] = new FleetParticle(defense);              // new random position

                            if (fleetSwarms[i].fleetParticles[j].profits > fleetSwarms[i].lBestProfits) // new swarm best by luck?
                            {
                                fleetSwarms[i].lBestProfits = fleetSwarms[i].fleetParticles[j].pBestProfits;
                                fleetSwarms[i].lBestFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].fleet);

                                if (fleetSwarms[i].fleetParticles[j].profits > gBestProfits) // if a new swarm best, maybe also a new global best?
                                {
                                    //need to repeat Defense evaluation to avoid outliers skewing results
                                    double moreAccurateProfits = fleetSwarms[i].fleetParticles[j].EvaluateFleet(20);
                                    if (moreAccurateProfits > gBestProfits)
                                    {
                                        epochsSinceImprovement = 0;

                                        gBestProfits = moreAccurateProfits;
                                        gBestFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].fleet);
                                        PrintCurrentNewBestFleetComposition(gBestFleet.ShipCounts, gBestProfits, epoch);
                                        gBestList.Add((epoch, gBestProfits));
                                    }
                                }
                            }
                        }
                        // an alternative is to maintain a particle age and die with high prob after a certain age reached
                        // another option is to maintain particle health/weakness (related to either ratio of times improved / loop count
                        // or number consecutive improves or consecutive non-improves) and die with high prob when health is low

                        double p2 = rand.NextDouble();
                        if (p2 < Program.ProbImmigrate)
                        {
                            int           otherSwarm    = rand.Next(0, Program.NumSwarms);
                            int           otherParticle = rand.Next(0, Program.NumParticles);
                            FleetParticle tmp           = fleetSwarms[i].fleetParticles[j];
                            fleetSwarms[i].fleetParticles[j] = fleetSwarms[otherSwarm].fleetParticles[otherParticle];
                            fleetSwarms[otherSwarm].fleetParticles[otherParticle] = tmp;

                            if (fleetSwarms[i].fleetParticles[j].pBestProfits > fleetSwarms[otherSwarm].lBestProfits) // new (other) swarm best?
                            {
                                fleetSwarms[otherSwarm].lBestProfits = fleetSwarms[i].fleetParticles[j].pBestProfits;
                                fleetSwarms[otherSwarm].lBestFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].bestLocalFleet);
                            }
                            if (fleetSwarms[otherSwarm].fleetParticles[otherParticle].pBestProfits > fleetSwarms[i].lBestProfits) // new (curr) swarm best?
                            {
                                fleetSwarms[i].lBestProfits = fleetSwarms[otherSwarm].fleetParticles[otherParticle].pBestProfits;
                                fleetSwarms[i].lBestFleet.CopyFleet(fleetSwarms[otherSwarm].fleetParticles[otherParticle].fleet);
                            }
                            // not possible for a new global best
                        }

                        for (int k = 0; k < Program.FleetDims; ++k) // update velocity. each x position component
                        {
                            double r1 = rand.NextDouble();
                            double r2 = rand.NextDouble();
                            double r3 = rand.NextDouble();

                            fleetSwarms[i].fleetParticles[j].velocity[k] = (
                                (Program.Inertia * fleetSwarms[i].fleetParticles[j].velocity[k])
                                + (Program.GravityLocal * r1 * (fleetSwarms[i].fleetParticles[j].bestLocalFleet.ShipCounts[k]
                                                                - fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k])
                                   )
                                + (Program.GravitySwarm * r2 * (fleetSwarms[i].lBestFleet.ShipCounts[k]
                                                                - fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k])
                                   )
                                + (Program.GravityGlobal * r3 * (gBestFleet.ShipCounts[k]
                                                                 - fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k])
                                   )
                                );

                            //if (fleetSwarms[i].fleetParticles[j].velocity[k] < minX) // constrain velocities
                            //    fleetSwarms[i].fleetParticles[j].velocity[k] = minX;
                            //else if (fleetSwarms[i].fleetParticles[j].velocity[k] > maxX)
                            //    fleetSwarms[i].fleetParticles[j].velocity[k] = maxX;
                        }

                        for (int k = 0; k < Program.FleetDims; ++k) // update position
                        {
                            fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k] += (int)fleetSwarms[i].fleetParticles[j].velocity[k];
                            // constrain all xi
                            if (fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k] < 0)
                            {
                                fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k] = 0;
                            }
                            else if (fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k]
                                     > (int)((10 * Program.DefenseValue) / (ulong)Program.FleetUnitsTotalCosts[k]))
                            {
                                //fleetSwarms[i].fleetParticles[j].fleetComposition[k] = (maxX - minX) * rand.NextDouble() + minX;
                                fleetSwarms[i].fleetParticles[j].fleet.ShipCounts[k] = (int)(rand.NextDouble()
                                                                                             * (10 * Program.DefenseValue) / Program.FleetUnitsTotalCosts[k]);
                            }
                        }

                        // update error
                        fleetSwarms[i].fleetParticles[j].EvaluateFleet();

                        // check if new best error for this fleet
                        if (fleetSwarms[i].fleetParticles[j].profits > fleetSwarms[i].fleetParticles[j].pBestProfits)
                        {
                            fleetSwarms[i].fleetParticles[j].consecutiveNonImproves = 0;
                            fleetSwarms[i].fleetParticles[j].pBestProfits           = fleetSwarms[i].fleetParticles[j].profits;
                            fleetSwarms[i].fleetParticles[j].bestLocalFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].fleet);

                            if (fleetSwarms[i].fleetParticles[j].profits > fleetSwarms[i].lBestProfits) // new swarm best?
                            {
                                fleetSwarms[i].lBestProfits = fleetSwarms[i].fleetParticles[j].profits;
                                fleetSwarms[i].fleetParticles[j].bestLocalFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].fleet);

                                if (fleetSwarms[i].fleetParticles[j].profits > gBestProfits) // new global best?
                                {
                                    //Simulate again with more trials to avoid outliers messing with results
                                    double moreAccurateProfits = fleetSwarms[i].fleetParticles[j].EvaluateFleet(20);
                                    if (moreAccurateProfits > gBestProfits)
                                    {
                                        epochsSinceImprovement = 0;

                                        fleetSwarms[i].fleetParticles[j].pBestProfits = moreAccurateProfits;
                                        fleetSwarms[i].lBestProfits = moreAccurateProfits;
                                        gBestProfits = moreAccurateProfits;
                                        gBestFleet.CopyFleet(fleetSwarms[i].fleetParticles[j].fleet);
                                        PrintCurrentNewBestFleetComposition(gBestFleet.ShipCounts, gBestProfits, epoch);
                                        gBestList.Add((epoch, gBestProfits));
                                    }
                                }
                            }
                        }
                    } // each particle
                }     // each swarm
            }         // while
            string fleetStr = String.Join(", ", gBestFleet.ShipCounts);

            Console.WriteLine("\tBest fleet found: " + fleetStr);
            Console.WriteLine("\t\tProfits per hour: " + gBestProfits);
            var pm = new PlotModel {
                Title = "Defense: " + String.Join(", ", defense.DefenseCounts),
                PlotAreaBorderThickness = new OxyThickness(0),
                Subtitle = "\nBest Fleet: " + String.Join(", ", gBestFleet.ShipCounts),
            };
            var categoryAxis = new OxyPlot.Axes.CategoryAxis {
                AxislineStyle = LineStyle.Solid, TickStyle = TickStyle.None
            };
            var value = new List <DataPoint>();

            for (int i = 0; i < gBestList.Count; i++)
            {
                value.Add(new DataPoint(gBestList[i].Item1, gBestList[i].Item2));
            }


            pm.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position      = AxisPosition.Left,
                Minimum       = 0,
                Maximum       = 1.05 * Math.Abs(gBestList[gBestList.Count - 1].Item2),
                MajorStep     = 4_000_000,
                MinorStep     = 1_000_000,
                AxislineStyle = LineStyle.Solid,
                TickStyle     = TickStyle.Crossing,
                StringFormat  = "0,0"
            });
        private Axis ConvertAxis(ChartAxisViewModel axis)
        {
            Axis newAxis = null;

            switch (axis.AxisType)
            {
                case (ChartAxisType.CategoryX):
                {
                    newAxis = new CategoryAxis
                    {
                        LabelField = axis.ValueMemberPath,
                        ItemsSource = axis.DataSource.Data
                    };
                    break;
                }
                case (ChartAxisType.NumericX):
                case (ChartAxisType.NumericY):
                {
                    newAxis = new LinearAxis
                    {
                    };
                    break;
                }
                case(ChartAxisType.CategoryDateTimeX):
                {
                    var dtaxis = new DateTimeAxis
                    {
                        IntervalType = DateTimeIntervalType.Auto,
                    };

                    var scale = axis.GetScaleForProperty(axis.ValueMemberPath);
                    if (null != scale)
                    {
                        scale.PropertyChanged += (s, a) =>
                        {
                            if( a.PropertyName != "Minimum" && a.PropertyName != "Maximum")
                            {
                                return;
                            }

                            var min = new DateTime((long)scale.Minimum);
                            var max = new DateTime((long)scale.Maximum);

                            var laxis = _plotModel.Axes.FirstOrDefault(x =>  x.Title == scale.Name) as DateTimeAxis;
                            if( null == laxis )
                            {
                                return;
                            }

                            var delta = max - min;

                            var lmax = 0.0d;
                            var lmin = 0.0d;

                            if (TimeSpan.FromSeconds(1) > delta)
                            {
                                laxis.IntervalType = DateTimeIntervalType.Seconds;
                            }
                            else if (TimeSpan.FromMinutes(1) > delta)
                            {
                                laxis.IntervalType = DateTimeIntervalType.Minutes;
                            }
                            else if (TimeSpan.FromHours(1) > delta)
                            {
                                laxis.IntervalType = DateTimeIntervalType.Hours;
                            }
                            else if (TimeSpan.FromDays(1) > delta)
                            {
                                laxis.IntervalType = DateTimeIntervalType.Days;
                            }
                            else if (TimeSpan.FromDays(30) > delta)
                            {
                                laxis.IntervalType = DateTimeIntervalType.Months;
                            }
                            else
                            {
                                laxis.IntervalType = DateTimeIntervalType.Auto;
                            }

                            //TODO: remove
                            laxis.IntervalType = DateTimeIntervalType.Seconds;

                            //laxis.Minimum = scale.Minimum;
                            //laxis.Maximum = scale.Maximum;

                            OnPlotModelChanged();
                        };
                    }
                    newAxis = dtaxis;
                    break;
                }
            }

            if (null == newAxis)
            {
                return null;
            }

            switch (axis.AxisLocation)
            {
                case(AxisLocation.InsideBottom):
                case(AxisLocation.OutsideBottom):
                {
                    newAxis.Position = AxisPosition.Bottom;
                    break;
                }
                case (AxisLocation.InsideTop):
                case (AxisLocation.OutsideTop):
                {
                    newAxis.Position = AxisPosition.Top;
                    break;
                }
                case (AxisLocation.InsideLeft):
                case (AxisLocation.OutsideLeft):
                {
                    newAxis.Position = AxisPosition.Left;
                    break;
                }
                case (AxisLocation.InsideRight):
                case (AxisLocation.OutsideRight):
                {
                    newAxis.Position = AxisPosition.Right;
                    break;
                }
                default:
                {
                    newAxis.Position = AxisPosition.None;
                    break;
                }
            }

            newAxis.Title = axis.Name;

            var series = axis.AxisScaleDescriptors.FirstOrDefault();
            if (null != series)
            {
                newAxis.Title = series.Scale.Name;
            }

            newAxis.Key = newAxis.Title;

            return newAxis;
        }
Пример #11
0
        ///<summary>
        /// Create and run a Fleet MSO that attempts to find the optimum fleet composition to raid this defense
        ///</summary>

        static Defense Solve()
        {
            Random rand = new Random(0);

            DefenseSwarm[] defenseSwarms = new DefenseSwarm[NumSwarms];
            for (int i = 0; i < NumSwarms; i++)
            {
                defenseSwarms[i] = new DefenseSwarm();
            }
            Defense gBestDefense = new Defense();
            double  gBestError   = double.MaxValue;

            for (int i = 0; i < NumSwarms; ++i)
            {
                if (defenseSwarms[i].lBestError < gBestError)
                {
                    gBestError = defenseSwarms[i].lBestError;
                    gBestDefense.CopyDefense(defenseSwarms[i].lBestDefense);
                }
            }


            var gBestList = new List <(int, double)>
            {
                (-1, gBestError)
            };


            int epoch = 0;

            while (epoch < MaxEpochsOuter)
            {
                ++epoch;

                if (epoch < MaxEpochsOuter)
                {
                    Console.WriteLine("Outer Epoch " + epoch + ", gBestError " + gBestError.ToString("F1"));
                }

                for (int i = 0; i < NumSwarms; ++i) // each swarm
                {
                    // Shuffle(sequence, rand); // move particles in random sequence
                    for (int j = 0; j < NumParticles; ++j) // each particle
                    {
                        //Death
                        double p1 = rand.NextDouble();
                        if (defenseSwarms[i].defenseParticles[j].consecutiveNonImproves * p1 > 20)
                        {
                            defenseSwarms[i].defenseParticles[j] = new DefenseParticle();                 // new random position
                            if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].lBestError) // new swarm best by luck?
                            {
                                defenseSwarms[i].lBestError = defenseSwarms[i].defenseParticles[j].error;
                                defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);
                                if (defenseSwarms[i].defenseParticles[j].error < gBestError) // if a new swarm best, maybe also a new global best?
                                {
                                    //must repeat defense evaluation to avoid outlier skewing results
                                    double result1 = defenseSwarms[i].defenseParticles[j].error;
                                    double result2 = defenseSwarms[i].defenseParticles[j].EvaluateDefense();
                                    double result3 = defenseSwarms[i].defenseParticles[j].EvaluateDefense();
                                    double maxResult = new[] { result1, result2, result3 }.Max();
                                    if (maxResult < gBestError)
                                    {
                                        gBestError = maxResult;
                                        gBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);
                                    }
                                }
                            }
                        }

                        //Immigration
                        double p2 = rand.NextDouble();
                        if (p2 < ProbImmigrate)
                        {
                            int             otherSwarm    = rand.Next(0, NumSwarms);
                            int             otherParticle = rand.Next(0, NumParticles);
                            DefenseParticle tmp           = defenseSwarms[i].defenseParticles[j];
                            defenseSwarms[i].defenseParticles[j] = defenseSwarms[otherSwarm].defenseParticles[otherParticle];
                            defenseSwarms[otherSwarm].defenseParticles[otherParticle] = tmp;

                            if (defenseSwarms[i].defenseParticles[j].pBestError < defenseSwarms[otherSwarm].lBestError) // new (other) swarm best?
                            {
                                defenseSwarms[otherSwarm].lBestError = defenseSwarms[i].defenseParticles[j].pBestError;
                                defenseSwarms[otherSwarm].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);
                            }
                            if (defenseSwarms[otherSwarm].defenseParticles[otherParticle].pBestError < defenseSwarms[i].lBestError) // new (curr) swarm best?
                            {
                                defenseSwarms[i].lBestError = defenseSwarms[otherSwarm].defenseParticles[otherParticle].pBestError;
                                defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[otherSwarm].defenseParticles[otherParticle].defense);
                            }
                            // not possible for a new global best
                        }

                        for (int k = 0; k < DefenseDims; ++k) // update velocity. each x position component
                        {
                            double r1 = rand.NextDouble();
                            double r2 = rand.NextDouble();
                            double r3 = rand.NextDouble();

                            defenseSwarms[i].defenseParticles[j].velocity[k]
                                = (
                                      (Inertia * defenseSwarms[i].defenseParticles[j].velocity[k])
                                      + (GravityLocal * r1 * (defenseSwarms[i].defenseParticles[j].pBestDefense.DefenseCounts[k]
                                                              - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k])
                                         )
                                      + (GravitySwarm * r2 * (defenseSwarms[i].lBestDefense.DefenseCounts[k]
                                                              - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k])
                                         )
                                      + (GravityGlobal * r3 * (gBestDefense.DefenseCounts[k]
                                                               - defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k])
                                         )
                                      );

                            //constrain velocities
                            //if (defenseSwarms[i].defenseParticles[j].velocity[k] < minX)
                            //    defenseSwarms[i].defenseParticles[j].velocity[k] = minX;
                            //else if (defenseSwarms[i].defenseParticles[j].velocity[k] > maxX)
                            //    defenseSwarms[i].defenseParticles[j].velocity[k] = maxX;
                        }

                        for (int k = 0; k < DefenseDims; ++k) // update position
                        {
                            defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] += (int)defenseSwarms[i].defenseParticles[j].velocity[k];
                            // constrain all xi
                            if (defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] < 0 ||
                                defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] > DefenseUnitsMaximums[k])
                            {
                                defenseSwarms[i].defenseParticles[j].defense.DefenseCounts[k] = (int)(rand.NextDouble() * DefenseUnitsMaximums[k]);
                            }
                        }

                        // update error
                        defenseSwarms[i].defenseParticles[j].EvaluateDefense();

                        // check if new best error for this particle
                        if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].defenseParticles[j].pBestError)
                        {
                            defenseSwarms[i].defenseParticles[j].pBestError = defenseSwarms[i].defenseParticles[j].error;
                            defenseSwarms[i].defenseParticles[j].pBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);

                            if (defenseSwarms[i].defenseParticles[j].error < defenseSwarms[i].lBestError) // new swarm best?
                            {
                                defenseSwarms[i].lBestError = defenseSwarms[i].defenseParticles[j].error;
                                defenseSwarms[i].lBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);

                                if (defenseSwarms[i].defenseParticles[j].error < gBestError) // new global best?
                                {
                                    //must repeat defense evaluation to avoid outlier skewing results
                                    double result1 = defenseSwarms[i].defenseParticles[j].error;
                                    double result2 = defenseSwarms[i].defenseParticles[j].EvaluateDefense();
                                    double result3 = defenseSwarms[i].defenseParticles[j].EvaluateDefense();
                                    double maxResult = new[] { result1, result2, result3 }.Max();
                                    if (maxResult < gBestError)
                                    {
                                        gBestError = maxResult;
                                        gBestDefense.CopyDefense(defenseSwarms[i].defenseParticles[j].defense);
                                        gBestList.Add((epoch, gBestError));
                                    }
                                }
                            }
                        }
                    } // each particle
                }     // each swarm
            }         // while
            string defenseStr = String.Join(", ", gBestDefense.DefenseCounts);

            Console.WriteLine("\n****Best defense found: " + defenseStr + " ****");
            var pm = new PlotModel {
                Title = "DefenseMSO", PlotAreaBorderThickness = new OxyThickness(0)
            };
            var categoryAxis = new OxyPlot.Axes.CategoryAxis {
                AxislineStyle = LineStyle.Solid, TickStyle = TickStyle.None
            };
            var value = new List <DataPoint>();

            for (int i = 0; i < gBestList.Count; i++)
            {
                value.Add(new DataPoint(gBestList[i].Item1, gBestList[i].Item2));
            }


            pm.Axes.Add
            (
                new OxyPlot.Axes.LinearAxis
            {
                Position      = AxisPosition.Left,
                Minimum       = -Math.Abs(gBestList[0].Item2),
                Maximum       = 1.05 * Math.Abs(gBestList[gBestList.Count - 1].Item2),
                MajorStep     = Math.Abs(gBestList[0].Item2 / 10),
                MinorStep     = Math.Abs(gBestList[0].Item2 / 50),
                AxislineStyle = LineStyle.Solid,
                TickStyle     = TickStyle.Crossing,
                StringFormat  = "0,0"
            }
            );

            pm.Axes.Add
            (
                new OxyPlot.Axes.LinearAxis
            {
                Position      = AxisPosition.Bottom,
                Minimum       = -1,
                Maximum       = MaxEpochsOuter,
                MajorStep     = Program.MaxEpochsInner / 5,
                MinorStep     = Program.MaxEpochsInner / 20,
                AxislineStyle = LineStyle.Solid,
                TickStyle     = TickStyle.Outside
            }
            );


            pm.Series.Add
            (
                new OxyPlot.Series.ScatterSeries
            {
                ItemsSource  = value,
                MarkerType   = MarkerType.Circle,
                MarkerSize   = 3.0,
                MarkerFill   = OxyColors.White,
                MarkerStroke = OxyColors.Black,
                DataFieldX   = "X",
                DataFieldY   = "Y"
            }
            );

            Stream stream = File.Create("C:\\Users\\admin\\source\\repos\\SpeedSimML\\SpeedSimML\\defenseplot.pdf");
            var    pdf    = new PdfExporter();

            PdfExporter.Export(pm, stream, 400.0, 400);


            return(gBestDefense);
        }
Пример #12
0
        public FormCrossPlots(ProjectManager pm)
        {
            InitializeComponent();
            //
            typeof(Control).InvokeMember("DoubleBuffered",
                                         BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                         null, gridData, new object[] { true });
            //

            model = new FormCrossPlotsModel(pm);

            listKeywords.SelectedIndex = 0;
            //
            boxRestart.Items.Clear();
            boxRestart.BeginUpdate();
            boxRestart.Items.AddRange(model.GetDates());

            if (boxRestart.Items.Count > 0)
            {
                boxRestart.SelectedIndex = 0;
            }

            boxRestart.EndUpdate();
            //
            plotModel = new PlotModel
            {
                Title           = "(No keyword)",
                DefaultFont     = "Segoe UI",
                TitleFontSize   = 12,
                DefaultFontSize = 11
            };

            plotModel.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position          = AxisPosition.Bottom,
                Title             = "Simualted",
                AxisTitleDistance = 8
            });


            plotModel.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position          = OxyPlot.Axes.AxisPosition.Left,
                Title             = "Historical",
                AxisTitleDistance = 8
            });

            plotView1.Model = plotModel;
            //

            plotHisto = new PlotModel
            {
                DefaultFont     = "Segoe UI",
                TitleFontWeight = 2,
                TitleFontSize   = 12,
                DefaultFontSize = 11,
            };

            var categoryAxes = new OxyPlot.Axes.CategoryAxis {
                Position = AxisPosition.Left, AxisTitleDistance = 8
            };

            categoryAxes.Title = "Relative Deviation";
            categoryAxes.Labels.Add("<10%");
            categoryAxes.Labels.Add("10-20%");
            categoryAxes.Labels.Add(">20%");

            plotHisto.Axes.Add(categoryAxes);

            plotHisto.Axes.Add(new OxyPlot.Axes.LinearAxis
            {
                Position          = OxyPlot.Axes.AxisPosition.Bottom,
                AxisTitleDistance = 8,
                Title             = "Well count"
            });

            plotView2.Model = plotHisto;

            //
            UpdateVirtualGroupsList();
        }
        public void MakeIntervalBars([JetBrains.Annotations.NotNull] ResultFileEntry srcResultFileEntry, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath,
                                     [ItemNotNull][JetBrains.Annotations.NotNull] List <Tuple <string, double> > consumption,
                                     [JetBrains.Annotations.NotNull] ChartTaggingSet taggingSet,
                                     [JetBrains.Annotations.NotNull] string newFileNameSuffix,
                                     bool showTitle,
                                     [JetBrains.Annotations.NotNull] GenericChartBase gcb, CalcOption sourceOption)
        {
            var fontsize = 48;

            if (consumption.Count <= 20)
            {
                fontsize = 22;
            }
            if (consumption.Count > 20 && consumption.Count <= 30)
            {
                fontsize = 16;
            }
            if (consumption.Count > 30 && consumption.Count <= 40)
            {
                fontsize = 14;
            }
            if (consumption.Count > 40 && consumption.Count <= 50)
            {
                fontsize = 12;
            }
            if (consumption.Count > 50)
            {
                fontsize = 10;
            }
            if (!Config.MakePDFCharts)
            {
                fontsize = (int)(fontsize * 0.8);
            }
            var unit       = "min";
            var xaxislabel = "Time Consumption in Percent";

            if (srcResultFileEntry.LoadTypeInformation != null)
            {
                var lti = srcResultFileEntry.LoadTypeInformation;
                if (!lti.ShowInCharts)
                {
                    return;
                }
                unit       = lti.UnitOfSum;
                xaxislabel = lti.Name + " in Percent";
            }
            consumption.Sort((x, y) => y.Item2.CompareTo(x.Item2));
            OxyPalette p;

            if (consumption.Count > 1)
            {
                if (taggingSet.Categories.Count > 1)
                {
                    p = OxyPalettes.HueDistinct(taggingSet.Categories.Count);
                }
                else
                {
                    p = OxyPalettes.Hue64;
                }
            }
            else
            {
                p = OxyPalettes.Hue64;
            }
            var plotModel1 = new PlotModel
            {
                LegendBorderThickness = 0,
                LegendOrientation     = LegendOrientation.Vertical,
                LegendPlacement       = LegendPlacement.Inside,
                LegendPosition        = LegendPosition.TopLeft,
                PlotAreaBorderColor   = OxyColors.White,
                LegendFontSize        = fontsize,
                LegendSymbolMargin    = 25
            };

            if (showTitle)
            {
                plotModel1.Title = plotName;
            }
            if (Config.MakePDFCharts)
            {
                plotModel1.DefaultFontSize = fontsize;
            }
            var ca = new CategoryAxis
            {
                Position       = AxisPosition.Left,
                GapWidth       = 0,
                MaximumPadding = 0.03,
                MajorTickSize  = 0
            };

            plotModel1.Axes.Add(ca);
            var la = new LinearAxis
            {
                Minimum        = 0,
                MinimumPadding = 0,
                Title          = ChartLocalizer.Get().GetTranslation(xaxislabel),
                Position       = AxisPosition.Bottom,
                MinorTickSize  = 0
            };

            plotModel1.Axes.Add(la);
            var caSub = new CategoryAxis
            {
                StartPosition = 0.5,
                EndPosition   = 1,
                Position      = AxisPosition.Left,
                Key           = "Sub",
                GapWidth      = 0.3,
                MajorTickSize = 0,
                MinorTickSize = 0
            };

            plotModel1.Axes.Add(caSub);
            double runningSum   = 0;
            var    row          = 0;
            var    sum          = consumption.Select(x => x.Item2).Sum();
            var    allBarSeries = new Dictionary <string, IntervalBarSeries>();
            var    ba           = new BarSeries
            {
                YAxisKey          = "Sub",
                LabelFormatString = "{0:N1} %"
            };

            foreach (var s in taggingSet.Categories)
            {
                caSub.Labels.Add(ChartLocalizer.Get().GetTranslation(s));
                var ibs = new IntervalBarSeries();
                // ibs.Title =
                var coloridx = taggingSet.GetCategoryIndexOfCategory(s);
                ibs.FillColor       = p.Colors[coloridx];
                ibs.StrokeThickness = 0;
                ibs.FontSize        = fontsize;
                allBarSeries.Add(s, ibs);
                double categorysum = 0;
                foreach (var tuple in consumption)
                {
                    if (taggingSet.AffordanceToCategories[tuple.Item1] == s)
                    {
                        categorysum += tuple.Item2;
                    }
                }
                var percent = categorysum / sum * 100;
                var bai     = new BarItem(percent)
                {
                    Color = p.Colors[coloridx]
                };
                ba.Items.Add(bai);
            }
            plotModel1.Series.Add(ba);
            foreach (var tuple in consumption)
            {
                var percentage = tuple.Item2 / sum * 100;
                var name       = ChartLocalizer.Get().GetTranslation(tuple.Item1.Trim());
                if (name.Length > 100)
                {
                    name = name.Substring(0, 97) + "...";
                }
                var textAnnotation1 = new TextAnnotation
                {
                    StrokeThickness = 0,
                    FontSize        = fontsize,
                    Padding         = new OxyThickness(10, 0, 10, 0)
                };
                var txtValue = tuple.Item2.ToString("N1", CultureInfo.CurrentCulture);
                if (srcResultFileEntry.LoadTypeInformation == null)
                {
                    var ts = TimeSpan.FromMinutes(tuple.Item2);
                    txtValue = ts.ToString();
                }
                textAnnotation1.Text = " " + name + " (" + txtValue + " " + unit + ", " +
                                       (tuple.Item2 / sum * 100).ToString("N1", CultureInfo.CurrentCulture) + " %)   ";
                if (runningSum < 50)
                {
                    textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left;
                    textAnnotation1.TextPosition            = new DataPoint(runningSum + percentage, row - 0.6);
                }
                else
                {
                    textAnnotation1.TextPosition            = new DataPoint(runningSum, row - 0.5);
                    textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Right;
                }
                plotModel1.Annotations.Add(textAnnotation1);
                var item     = new IntervalBarItem(runningSum, runningSum + percentage);
                var category = taggingSet.AffordanceToCategories[tuple.Item1];
                allBarSeries[category].Items.Add(item);
                foreach (var pair in allBarSeries)
                {
                    if (pair.Key != category)
                    {
                        pair.Value.Items.Add(new IntervalBarItem(0, 0));
                    }
                }
                ca.Labels.Add(string.Empty);
                runningSum += percentage;
                row++;
            }
            foreach (var pair in allBarSeries)
            {
                plotModel1.Series.Add(pair.Value);
            }
            gcb.Save(plotModel1, plotName, srcResultFileEntry.FullFileName + newFileNameSuffix, basisPath, sourceOption); // ".interval"
        }
Пример #14
0
        public void MakeScatterChart([ItemNotNull][JetBrains.Annotations.NotNull] List <CalculationOutcome> outcomes, [JetBrains.Annotations.NotNull] string pngfullName, [ItemNotNull][JetBrains.Annotations.NotNull] List <SeriesEntry> series)
        {
            _calculationProfiler.StartPart(Utili.GetCurrentMethodAndClass());
            var plotModel1 = new PlotModel
            {
                LegendBorderThickness = 0,
                LegendOrientation     = LegendOrientation.Horizontal,
                LegendPlacement       = LegendPlacement.Outside,
                LegendPosition        = LegendPosition.BottomCenter,
                DefaultFontSize       = FontSize,
                LegendFontSize        = FontSize,
                DefaultFont           = "Arial",
                LegendFont            = "Arial"
            };
            var ca = new CategoryAxis
            {
                Minimum  = 0.4,
                Title    = "Number of Persons",
                Position = AxisPosition.Bottom
            };

            ca.Title = Xaxislabel;
            ca.Labels.Add("0");
            ca.Labels.Add("1");
            ca.Labels.Add("2");
            ca.Labels.Add("3");
            ca.Labels.Add("4");
            ca.Labels.Add("5");
            ca.Labels.Add("6");
            ca.MaximumPadding = 0.02;
            plotModel1.Axes.Add(ca);

            var la = new LinearAxis
            {
                Minimum        = 0,
                Position       = AxisPosition.Left,
                Title          = Yaxislabel,
                MaximumPadding = 0.02
            };

            plotModel1.Axes.Add(la);

            var sc = new LineSeries
            {
                LineStyle       = LineStyle.Dash,
                MarkerFill      = OxyColors.SkyBlue,
                MarkerSize      = 5,
                MarkerType      = MarkerType.Circle,
                StrokeThickness = 3
            };

            AddNRWPoints(sc, 1);
            sc.Title = Averagelabel;
            plotModel1.Series.Add(sc);

            var energyIntensities = outcomes.Select(x => x.EnergyIntensity).Distinct().ToList();

            energyIntensities.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal));
            series.Sort((x, y) => string.Compare(x.Version, y.Version, StringComparison.Ordinal));
            OxyPalette p = OxyPalettes.Hue64;

            if (series.Count > 1)
            {
                p = OxyPalettes.HueDistinct(series.Count);
            }

            var i = 0;

            for (var index = 0; index < series.Count; index++)
            {
                var seriesEntry = series[index];
                var entrylist   = outcomes
                                  .Where(x => x.EnergyIntensity == seriesEntry.EnergyIntensity &&
                                         x.LPGVersion == seriesEntry.Version)
                                  .ToList();
                var sc1 = new ScatterSeries();
                foreach (var entry in entrylist)
                {
                    sc1.Points.Add(
                        new ScatterPoint(entry.NumberOfPersons + seriesEntry.Offset, entry.ElectricityDouble));
                }

                sc1.Title = seriesEntry.DisplayName;
                var oc = p.Colors[i++];
                sc1.MarkerStroke = OxyColor.FromAColor(128, oc);
                sc1.MarkerFill   = oc;
                if (index == 0)
                {
                    sc1.MarkerType = MarkerType.Diamond;
                }
                else
                {
                    sc1.MarkerType = MarkerType.Star;
                }
                sc1.MarkerStrokeThickness = 1;
                plotModel1.Series.Add(sc1);
            }
            PngExporter.Export(plotModel1, pngfullName, _width, _height, OxyColor.FromRgb(255, 255, 255), _dpi);
            _calculationProfiler.StopPart(Utili.GetCurrentMethodAndClass());
            //ChartPDFCreator.OxyPDFCreator.Run(plotModel1, pdfFullName);
        }
Пример #15
0
        private void SetupWeeklyGraphWithSpecificYear(string graphType, Dictionary <int, decimal> data, string costOrCount)
        {
            switch (graphType)
            {
            case "Line":

                MyGraph = new PlotModel()
                {
                    Title = YAxisComboBox.Text + " " + XAxisComboBox.Text + " in " + SelectedYearComboBox.Text
                };

                myLineSeries = new LineSeries()
                {
                    CanTrackerInterpolatePoints = false,
                    MarkerFill = OxyColors.SteelBlue,
                    MarkerType = MarkerType.Circle
                };

                foreach (KeyValuePair <int, decimal> datum in data)
                {
                    myLineSeries.Points.Add(new DataPoint((double)datum.Key, (double)datum.Value));
                }

                // Define X-Axis
                Xaxis                    = new OxyPlot.Axes.LinearAxis();
                Xaxis.Maximum            = 52;
                Xaxis.Minimum            = 0;
                Xaxis.Position           = OxyPlot.Axes.AxisPosition.Bottom;
                Xaxis.Title              = "Time (Weeks)";
                Xaxis.MajorGridlineStyle = LineStyle.Solid;
                Xaxis.MinorGridlineStyle = LineStyle.Solid;

                //Define Y-Axis
                Yaxis = new OxyPlot.Axes.LinearAxis();

                switch (costOrCount)
                {
                case "cost":

                    Yaxis.MajorStep          = 100;
                    Yaxis.MinimumPadding     = 0.05;
                    Yaxis.Minimum            = 0;
                    Yaxis.MinorStep          = 50;
                    Yaxis.Title              = "Cost (£)";
                    Yaxis.MajorGridlineStyle = LineStyle.Solid;
                    Yaxis.MinorGridlineStyle = LineStyle.Solid;

                    break;

                case "count":

                    Yaxis.MajorStep          = 1;
                    Yaxis.MinimumPadding     = 0.05;
                    Yaxis.Minimum            = 0;
                    Yaxis.MinorStep          = 1;
                    Yaxis.Title              = "Number of Cases";
                    Yaxis.MajorGridlineStyle = LineStyle.Solid;
                    Yaxis.MinorGridlineStyle = LineStyle.Solid;

                    break;

                default:
                    MessageBox.Show("Invalid flag. Expected 'case' or 'cost' - received: " + costOrCount);
                    break;
                }

                MyGraph.Axes.Add(Xaxis);
                MyGraph.Axes.Add(Yaxis);
                MyGraph.Series.Add(myLineSeries);

                GraphView.Model = MyGraph;

                break;

            case "Bar":

                MyGraph = new PlotModel()
                {
                    Title = YAxisComboBox.Text + " " + XAxisComboBox.Text + " in " + SelectedYearComboBox.Text
                };

                List <ColumnItem> barData = new List <ColumnItem>();
                foreach (KeyValuePair <int, decimal> datum in data)
                {
                    barData.Add(new ColumnItem((double)datum.Value));
                }

                myColumnSeries = new ColumnSeries()
                {
                    ItemsSource = barData,
                    //LabelFormatString = "{0:F2}",
                    LabelPlacement = LabelPlacement.Inside
                };

                // Define X-Axis
                List <int> xAxisCategories = new List <int>();
                foreach (KeyValuePair <int, decimal> datum in data)
                {
                    xAxisCategories.Add(datum.Key);
                }

                Xaxis = new OxyPlot.Axes.CategoryAxis()
                {
                    Key                = "Time",
                    ItemsSource        = xAxisCategories,
                    Position           = AxisPosition.Bottom,
                    Title              = "Time (Weeks)",
                    MinorGridlineStyle = LineStyle.Solid
                };


                //Define Y-Axis
                Yaxis = new LinearAxis();
                switch (costOrCount)
                {
                case "cost":

                    Yaxis.Position           = AxisPosition.Left;
                    Yaxis.MajorStep          = 200;
                    Yaxis.MinimumPadding     = 0.05;
                    Yaxis.Minimum            = 0;
                    Yaxis.MinorStep          = 50;
                    Yaxis.Title              = "Cost (£)";
                    Yaxis.MajorGridlineStyle = LineStyle.Solid;
                    Yaxis.MinorGridlineStyle = LineStyle.Solid;

                    break;

                case "count":

                    Yaxis.Position           = AxisPosition.Left;
                    Yaxis.MajorStep          = 5;
                    Yaxis.Minimum            = 0;
                    Yaxis.MinimumPadding     = 0.05;
                    Yaxis.MinorStep          = 1;
                    Yaxis.Title              = "Number of Cases";
                    Yaxis.MajorGridlineStyle = LineStyle.Solid;
                    Yaxis.MinorGridlineStyle = LineStyle.Solid;
                    break;

                default:
                    MessageBox.Show("Invalid flag. Expected 'case' or 'cost' - received: " + costOrCount);
                    break;
                }



                MyGraph.Axes.Add(Yaxis);
                MyGraph.Axes.Add(Xaxis);
                MyGraph.Series.Add(myColumnSeries);

                GraphView.Model = MyGraph;

                break;

            default:
                MessageBox.Show("Invalid Chart Type Specified in ReportsPage.SetupGraphWithSpecificYear().");
                break;
            }
        }
        private Axis ConvertAxis(ChartAxisViewModel axis)
        {
            Axis newAxis = null;

            switch (axis.AxisType)
            {
            case (ChartAxisType.CategoryX):
            {
                newAxis = new CategoryAxis
                {
                    LabelField  = axis.ValueMemberPath,
                    ItemsSource = axis.DataSource.Data
                };
                break;
            }

            case (ChartAxisType.NumericX):
            case (ChartAxisType.NumericY):
            {
                newAxis = new LinearAxis
                {
                };
                break;
            }

            case (ChartAxisType.CategoryDateTimeX):
            {
                var dtaxis = new DateTimeAxis
                {
                    IntervalType = DateTimeIntervalType.Auto,
                };

                var scale = axis.GetScaleForProperty(axis.ValueMemberPath);
                if (null != scale)
                {
                    scale.PropertyChanged += (s, a) =>
                    {
                        if (a.PropertyName != "Minimum" && a.PropertyName != "Maximum")
                        {
                            return;
                        }

                        var min = new DateTime((long)scale.Minimum);
                        var max = new DateTime((long)scale.Maximum);

                        var laxis = _plotModel.Axes.FirstOrDefault(x => x.Title == scale.Name) as DateTimeAxis;
                        if (null == laxis)
                        {
                            return;
                        }

                        var delta = max - min;

                        var lmax = 0.0d;
                        var lmin = 0.0d;

                        if (TimeSpan.FromSeconds(1) > delta)
                        {
                            laxis.IntervalType = DateTimeIntervalType.Seconds;
                        }
                        else if (TimeSpan.FromMinutes(1) > delta)
                        {
                            laxis.IntervalType = DateTimeIntervalType.Minutes;
                        }
                        else if (TimeSpan.FromHours(1) > delta)
                        {
                            laxis.IntervalType = DateTimeIntervalType.Hours;
                        }
                        else if (TimeSpan.FromDays(1) > delta)
                        {
                            laxis.IntervalType = DateTimeIntervalType.Days;
                        }
                        else if (TimeSpan.FromDays(30) > delta)
                        {
                            laxis.IntervalType = DateTimeIntervalType.Months;
                        }
                        else
                        {
                            laxis.IntervalType = DateTimeIntervalType.Auto;
                        }

                        //TODO: remove
                        laxis.IntervalType = DateTimeIntervalType.Seconds;

                        //laxis.Minimum = scale.Minimum;
                        //laxis.Maximum = scale.Maximum;

                        OnPlotModelChanged();
                    };
                }
                newAxis = dtaxis;
                break;
            }
            }

            if (null == newAxis)
            {
                return(null);
            }

            switch (axis.AxisLocation)
            {
            case (AxisLocation.InsideBottom):
            case (AxisLocation.OutsideBottom):
            {
                newAxis.Position = AxisPosition.Bottom;
                break;
            }

            case (AxisLocation.InsideTop):
            case (AxisLocation.OutsideTop):
            {
                newAxis.Position = AxisPosition.Top;
                break;
            }

            case (AxisLocation.InsideLeft):
            case (AxisLocation.OutsideLeft):
            {
                newAxis.Position = AxisPosition.Left;
                break;
            }

            case (AxisLocation.InsideRight):
            case (AxisLocation.OutsideRight):
            {
                newAxis.Position = AxisPosition.Right;
                break;
            }

            default:
            {
                newAxis.Position = AxisPosition.None;
                break;
            }
            }

            newAxis.Title = axis.Name;

            var series = axis.AxisScaleDescriptors.FirstOrDefault();

            if (null != series)
            {
                newAxis.Title = series.Scale.Name;
            }

            newAxis.Key = newAxis.Title;

            return(newAxis);
        }
Пример #17
0
        private void DrawGraph(Artist artist)
        {
            StatModel.Series.Clear();
            StatModel.Axes.Clear();

            var categoryAxis = new OxyPlot.Axes.CategoryAxis
            {
                Position = AxisPosition.Bottom
            };
            var s1 = new OxyPlot.Series.ColumnSeries
            {
                Title       = $"Творчество художника ({artist.full_name})",
                StrokeColor = OxyColors.Black, StrokeThickness = 1
            };

            var paintings = context.Paintings.Where(x => x.artist_id == artist.id &&
                                                    x.year_of_creation != null)
                            .OrderBy(x => x.year_of_creation)
                            .ToArray();

            if (paintings.Any())
            {
                var min = artist.date_of_birth.Value.Year;
                var max = artist.date_of_death?.Year != null ?
                          artist.date_of_death.Value.Year :
                          artist.date_of_birth.Value.AddYears(120).Year;
                int currIndex = 0;
                for (int i = min; ; i += 5)
                {
                    var nextBound = i + 5;
                    if (nextBound > max)
                    {
                        nextBound = max;
                    }
                    int count = 0;
                    while (currIndex < paintings.Length &&
                           paintings[currIndex].year_of_creation <= nextBound)
                    {
                        count++;
                        currIndex++;
                    }
                    s1.Items.Add(new ColumnItem(count));
                    categoryAxis.Labels.Add(i + Environment.NewLine + nextBound);
                    if (nextBound == max)
                    {
                        break;
                    }
                }

                var valueAxis = new OxyPlot.Axes.LinearAxis
                {
                    Position        = AxisPosition.Left,
                    MinimumPadding  = 0,
                    MaximumPadding  = 0.06,
                    AbsoluteMinimum = 0
                };

                StatModel.Series.Add(s1);
                StatModel.Axes.Add(categoryAxis);
                StatModel.Axes.Add(valueAxis);
                StatModel.InvalidatePlot(true);
            }
        }