private static void SaveCustomerSegmentationPlotChart(IEnumerable <ClusteringPrediction> predictions, string plotLocation) { Common.ConsoleHelper.ConsoleWriteHeader("Plot Customer Segmentation"); var plot = new PlotModel { Title = "Customer Segmentation", IsLegendVisible = true }; var clusters = predictions.Select(p => p.SelectedClusterId).Distinct().OrderBy(x => x); foreach (var cluster in clusters) { var scatter = new ScatterSeries { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"Cluster: {cluster}", RenderInLegend = true }; var series = predictions .Where(p => p.SelectedClusterId == cluster) .Select(p => new ScatterPoint(p.Location[0], p.Location[1])).ToArray(); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new System.IO.FileStream(plotLocation, System.IO.FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Plot location: {plotLocation}"); }
static void VisualizeClustering(IEnumerable <IrisClustering> predictedData, string savePath) { var plot = new PlotModel { Title = "Iris Cluster", IsLegendVisible = true }; var clusters = predictedData.Select(x => x.Predicted_cluster).Distinct().OrderBy(x => x); foreach (var cluster in clusters) { var scatter = new ScatterSeries() { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"Cluster : {cluster}" }; var series = predictedData.Where(x => x.Predicted_cluster == cluster).Select(p => new ScatterPoint(p.Location[0], p.Location[1])); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new FileStream(savePath, FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Clustering svg generated at {savePath}."); }
static void VisualizeMulticlassClassification(string algorithmName, IEnumerable <Wine> testData, IEnumerable <WineClassification> predictedData, string savePath) { try { var plot = new PlotModel { Title = "Iris Type Prediction", IsLegendVisible = true }; var types = predictedData.Select(x => x.Predicted_result).Distinct().OrderBy(x => x); foreach (var type in types) { var scatter = new ScatterSeries() { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"type : {type}" }; var series = predictedData.Where(x => x.Predicted_result == type).Select(p => new ScatterPoint(p.Location[0], p.Location[1])); scatter.Points.AddRange(series); plot.Series.Add(scatter); } plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; var exporter = new SvgExporter { Width = 600, Height = 400 }; using (var fs = new FileStream(savePath, FileMode.Create)) { exporter.Export(plot, fs); } Console.WriteLine($"Classification svg generated at {savePath}."); } catch { Console.WriteLine($"Unable to generate visualization for {algorithmName}"); } }
private static void MakeLinePlot([JetBrains.Annotations.NotNull] string outputPath, [ItemNotNull][JetBrains.Annotations.NotNull] List <Column> columns, int position, int day) { var p = OxyPalettes.HueDistinct(columns.Count); var plotModel1 = new PlotModel { LegendPosition = LegendPosition.BottomCenter, LegendPlacement = LegendPlacement.Outside, LegendOrientation = LegendOrientation.Horizontal, Title = "Day " + day }; var linearAxis1 = new LinearAxis { Position = AxisPosition.Bottom }; plotModel1.Axes.Add(linearAxis1); for (var i = 1; i < columns.Count; i++) { var lineSeries1 = new LineSeries { Title = columns[i].HHNumber, Color = p.Colors[i] }; for (var j = position; j < position + 1440; j++) { lineSeries1.Points.Add(new DataPoint(j, columns[i].Values[j])); } plotModel1.Series.Add(lineSeries1); } var path = Path.Combine(outputPath, "Plot." + day + ".line.png"); PngExporter.Export(plotModel1, path, 3200, 1600, OxyColor.FromRgb(255, 255, 255), 100); }
private PlotModel MakeChart([JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] string yaxisLabel, TimeSpan timestep, [ItemNotNull][JetBrains.Annotations.NotNull] List <string> headers, [ItemNotNull][JetBrains.Annotations.NotNull] List <double[]> values, [JetBrains.Annotations.NotNull] List <DateTime> dates, int maxTimestep) { var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; if (Parameters.ShowTitle) { plotModel1.Title = plotName; } var dateTimeAxis = new DateTimeAxis { Position = AxisPosition.Bottom, StringFormat = "dd.MM. HH:mm" }; plotModel1.Axes.Add(dateTimeAxis); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = yaxisLabel }; plotModel1.Axes.Add(linearAxis2); // data var p = OxyPalettes.HueDistinct(headers.Count); var currentTime = new TimeSpan(0); for (var i = 2; i < headers.Count; i++) { // main columns var columnSeries2 = new LineSeries { Title = headers[i] }; for (var j = 0; j < values.Count && j < maxTimestep; j++) { currentTime = currentTime.Add(timestep); var dt = dates[j]; var dp = new DataPoint(DateTimeAxis.ToDouble(dt), values[j][i]); columnSeries2.Points.Add(dp); } columnSeries2.Color = p.Colors[i]; plotModel1.Series.Add(columnSeries2); } return(plotModel1); }
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); }
/// <summary> /// Create the palette list. /// </summary> private void CreatePaletteList() { PaletteList = new BindingList <OxyPalette>(); PaletteList.Add(OxyPalettes.BlackWhiteRed(64)); PaletteList.Add(OxyPalettes.BlueWhiteRed(64)); PaletteList.Add(OxyPalettes.BlueWhiteRed31); PaletteList.Add(OxyPalettes.Cool(64)); PaletteList.Add(OxyPalettes.Gray(64)); PaletteList.Add(OxyPalettes.Hot(64)); PaletteList.Add(OxyPalettes.Hue64); PaletteList.Add(OxyPalettes.HueDistinct(64)); PaletteList.Add(OxyPalettes.Jet(64)); PaletteList.Add(OxyPalettes.Rainbow(64)); }
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" }
private static void MakeBarCharts([ItemNotNull][JetBrains.Annotations.NotNull] List <AffTagEntry> entries, [JetBrains.Annotations.NotNull] string dstDirectory) { var personNames = entries.Select(x => x.PersonName.Trim()).Distinct().ToList(); // make absolute values var plotModel1 = MakePlotmodel(personNames, "Simulationszeit in Prozent"); var tagNames = entries.Select(x => x.AffTagName).Distinct().ToList(); OxyPalette p; if (tagNames.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(tagNames.Count); } var personSums = new Dictionary <string, double>(); foreach (var personName in personNames) { var sum = entries.Where(x => x.PersonName == personName).Select(x => x.Value).Sum(); personSums.Add(personName, sum); } for (var i = 0; i < tagNames.Count; i++) { var tag = tagNames[i]; var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", XAxisKey = "N", StrokeThickness = 1, Title = ChartLocalizer.Get().GetTranslation(tag), LabelPlacement = LabelPlacement.Middle, StrokeColor = OxyColors.White, FillColor = p.Colors[i] }; foreach (var personName in personNames) { var te = entries.FirstOrDefault(x => x.AffTagName == tag && x.PersonName == personName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / personSums[te.PersonName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel1.Series.Add(columnSeries2); } const string fileName = "MergedAffordanceTaggingSet.WoBleibtDieZeit.Absolute.pdf"; OxyPDFCreator.Run(plotModel1, fileName); foreach (var tagName in tagNames) { var plotModel2 = MakePlotmodel(personNames, "Anteil an der Gesamtzeit in Prozent"); var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, StrokeColor = OxyColors.White, XAxisKey = "N", Title = ChartLocalizer.Get().GetTranslation(tagName), LabelPlacement = LabelPlacement.Middle, FillColor = OxyColors.LightBlue }; var averageValue = entries.Where(x => x.AffTagName == tagName) .Select(x => x.Value / personSums[x.PersonName] * 100) .Average(); var ls = new LineSeries { Color = OxyColors.Red, Title = "Durchschnitt" }; for (var i = 0; i < personNames.Count; i++) { var personName = personNames[i]; ls.Points.Add(new DataPoint(i, averageValue)); var te = entries.FirstOrDefault(x => x.AffTagName == tagName && x.PersonName == personName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / personSums[personName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel2.Series.Add(columnSeries2); plotModel2.Series.Add(ls); var cleanTag = AutomationUtili.CleanFileName(tagName); var relfileName = Path.Combine(dstDirectory, "MergedAffordanceTaggingSet.WoBleibtDieZeit." + cleanTag + ".pdf"); OxyPDFCreator.Run(plotModel2, relfileName); } }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry rfe) { Profiler.StartPart(Utili.GetCurrentMethodAndClass()); string plotName = "Execution Count for " + rfe.HouseholdNumberString; var consumption = new Dictionary <string, List <Tuple <string, double> > >(); var lastname = string.Empty; if (rfe.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(rfe.FullFileName)) { while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed."); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); if (s == "-----") { var name = sr.ReadLine(); if (name == null) { throw new LPGException("Readline failed."); } consumption.Add(name, new List <Tuple <string, double> >()); lastname = name; sr.ReadLine(); // header } else { var d = Convert.ToDouble(cols[1], CultureInfo.CurrentCulture); consumption[lastname].Add(new Tuple <string, double>(cols[0], d)); } } } foreach (var pair in consumption) { var mylist = pair.Value; mylist.Sort(Comparison); } foreach (var pair in consumption) { var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; var personName = pair.Key; if (Parameters.ShowTitle) { plotModel1.Title = plotName + " " + personName; } plotModel1.IsLegendVisible = false; // axes var cate = new CategoryAxis { AbsoluteMinimum = 0, MinimumPadding = 0, GapWidth = 0, MinorStep = 1, Title = " ", Angle = 90, AxisTitleDistance = 150, ClipTitle = false }; plotModel1.Axes.Add(cate); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = "Times of execution" }; plotModel1.Axes.Add(linearAxis2); // data OxyPalette p; if (pair.Value.Count > 1) { p = OxyPalettes.HueDistinct(pair.Value.Count); } else { p = OxyPalettes.Hue64; } var columnSeries2 = new ColumnSeries { StrokeThickness = 0, Title = "Actions" }; for (var i = 0; i < pair.Value.Count; i++) { var label = pair.Value[i].Item1; if (label.Length > 40) { label = label.Substring(0, 40); } cate.Labels.Add(label); var ci = new ColumnItem(pair.Value[i].Item2) { Color = p.Colors[i] }; columnSeries2.Items.Add(ci); } plotModel1.Series.Add(columnSeries2); var fi = new FileInfo(rfe.FullFileName); var pn = fi.Name.Substring(0, fi.Name.Length - 3); var cleanedName = AutomationUtili.CleanFileName(pair.Key); if (fi.DirectoryName == null) { throw new LPGException("Directory Name was null"); } var correctfilename = Path.Combine(fi.DirectoryName, pn + cleanedName + ".png"); Save(plotModel1, plotName, correctfilename, Parameters.BaseDirectory, CalcOption.ActivationsPerHour); } Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry srcEntry) { string plotName = "Activity Frequencies per Minute " + srcEntry.HouseholdNumberString; Profiler.StartPart(Utili.GetCurrentMethodAndClass()); var consumption = new Dictionary <string, List <Tuple <string, List <double> > > >(); var lastname = string.Empty; if (srcEntry.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(srcEntry.FullFileName)) { while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed"); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); if (cols.Length == 1) { consumption.Add(cols[0], new List <Tuple <string, List <double> > >()); lastname = cols[0]; sr.ReadLine(); } else { var values = new List <double>(); for (var i = 1; i < cols.Length; i++) { var d = Convert.ToDouble(cols[i], CultureInfo.CurrentCulture); values.Add(d); } consumption[lastname].Add(new Tuple <string, List <double> >(cols[0], values)); } } } foreach (var pair in consumption) { var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; var personName = pair.Key; if (Parameters.ShowTitle) { plotModel1.Title = plotName + " " + personName; } // axes var categoryAxis = new CategoryAxis { AbsoluteMinimum = 0, MinimumPadding = 0, GapWidth = 0, MajorStep = 60, Title = "Minutes" }; plotModel1.Axes.Add(categoryAxis); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = "Days" }; plotModel1.Axes.Add(linearAxis2); // data OxyPalette p; if (pair.Value.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(pair.Value.Count); } for (var i = 0; i < pair.Value.Count; i++) { var columnSeries2 = new ColumnSeries { IsStacked = true, StrokeThickness = 0, Title = pair.Value[i].Item1 }; var values = pair.Value[i].Item2; for (var j = 0; j < values.Count; j++) { columnSeries2.Items.Add(new ColumnItem(values[j])); } columnSeries2.FillColor = p.Colors[i]; plotModel1.Series.Add(columnSeries2); } Save(plotModel1, plotName, srcEntry.FullFileName + "." + personName, Parameters.BaseDirectory, CalcOption.ActivationFrequencies); } Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
private void MakeBarCharts([JetBrains.Annotations.NotNull] ResultFileEntry rfe, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath, [JetBrains.Annotations.NotNull] Dictionary <string, List <TagEntry> > consumption) { Profiler.StartPart(Utili.GetCurrentMethodAndClass()); foreach (var pair in consumption) { var hasReferenceValue = pair.Value.Any(x => x.ReferenceValues.Count > 0); if (!hasReferenceValue) { continue; } var plotModel1 = new PlotModel(); pair.Value.Sort((x, y) => x.Value.CompareTo(y.Value)); plotModel1.LegendBorderThickness = 0; plotModel1.LegendOrientation = LegendOrientation.Horizontal; plotModel1.LegendPlacement = LegendPlacement.Outside; plotModel1.LegendPosition = LegendPosition.BottomCenter; var labelFontSize = 12; if (Config.MakePDFCharts) { plotModel1.DefaultFontSize = Parameters.PDFFontSize; plotModel1.LegendFontSize = Parameters.PDFFontSize; labelFontSize = 16; } plotModel1.LegendSymbolMargin = 20; if (Parameters.ShowTitle) { plotModel1.Title = plotName; } var categoryAxis1 = new CategoryAxis { MinorStep = 1, Minimum = -0.5 }; categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation("Simulated")); var firstEntry = pair.Value[0]; var referenceCount = firstEntry.ReferenceHeaders.Count; for (var i = 0; i < referenceCount; i++) { categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation(firstEntry.ReferenceHeaders[i])); } categoryAxis1.GapWidth = 1; categoryAxis1.MaximumPadding = 0.02; categoryAxis1.Position = AxisPosition.Left; plotModel1.Axes.Add(categoryAxis1); var sum1 = pair.Value.Select(x => x.Value).Sum(); var sums = new List <double>(); foreach (var entry in pair.Value) { for (var i = 0; i < entry.ReferenceValues.Count; i++) { if (sums.Count < i + 1) { sums.Add(0); } sums[i] += entry.ReferenceValues[i]; } } var sum2 = sums.Max(); var totalSum = Math.Max(sum1, sum2); string s2 = rfe.LoadTypeInformation?.Name ?? ""; var linearAxis1 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.02, MinimumPadding = 0, MajorStep = totalSum / 5, MinorTickSize = 0, Position = AxisPosition.Bottom, Title = ChartLocalizer.Get().GetTranslation(s2) + " in " + rfe.LoadTypeInformation?.UnitOfSum + string.Empty }; plotModel1.Axes.Add(linearAxis1); OxyPalette p; if (pair.Value.Count > 1) { p = OxyPalettes.HueDistinct(pair.Value.Count); } else { p = OxyPalettes.Hue64; } var colSums = new Dictionary <int, double> { { 0, 0 }, { 1, 0 } }; var count = 0; foreach (var tagentry in pair.Value) { var columnSeries2 = new BarSeries { FillColor = p.Colors[count] }; count++; columnSeries2.IsStacked = true; columnSeries2.StackGroup = "1"; columnSeries2.StrokeThickness = 1; columnSeries2.StrokeColor = OxyColor.FromArgb(255, 255, 255, 255); columnSeries2.StrokeThickness = 0.1; columnSeries2.Title = ChartLocalizer.Get().GetTranslation(tagentry.TagName); columnSeries2.LabelPlacement = LabelPlacement.Middle; var coli = new BarItem(tagentry.Value); columnSeries2.Items.Add(coli); foreach (var referenceValue in tagentry.ReferenceValues) { var coli2 = new BarItem(referenceValue); columnSeries2.Items.Add(coli2); } var col = 0; if (tagentry.Value / sum1 > 0.2) { var d = tagentry.Value; var valuetext = d.ToString("N0", CultureInfo.CurrentCulture) + " " + rfe.LoadTypeInformation?.UnitOfSum + " (" + (d / sum1 * 100).ToString("N1", CultureInfo.CurrentCulture) + " %)"; SetRectangelAnnotation(col, colSums, plotModel1, valuetext, d, 0.25, 0.35, labelFontSize); var shortendName = ChartLocalizer.Get().GetTranslation(tagentry.TagName).Trim(); if (shortendName.Length > 20) { shortendName = shortendName.Substring(0, 17) + "..."; } SetRectangelAnnotation(col, colSums, plotModel1, shortendName, d, 0.35, 0.45, labelFontSize); } col++; double refValue = 0; if (tagentry.ReferenceValues.Count > 0) { refValue = tagentry.ReferenceValues[0]; } if (refValue / sum2 > 0.15) { var valueText = refValue.ToString("N0", CultureInfo.CurrentCulture) + " " + rfe.LoadTypeInformation?.UnitOfSum + " (" + (refValue / sum2 * 100).ToString("N1", CultureInfo.CurrentCulture) + " %)"; SetRectangelAnnotation(col, colSums, plotModel1, valueText, refValue, 0.25, 0.35, labelFontSize); var labelText = ChartLocalizer.Get().GetTranslation(tagentry.TagName); SetRectangelAnnotation(col, colSums, plotModel1, labelText, refValue, 0.35, 0.45, labelFontSize); } colSums[0] += tagentry.Value; if (tagentry.ReferenceValues.Count > 0) { colSums[1] += tagentry.ReferenceValues[0]; } plotModel1.Series.Add(columnSeries2); } var fi = new FileInfo(rfe.FullFileName); var modifiedName = fi.Name.Substring(0, fi.Name.Length - 3) + AutomationUtili.CleanFileName(pair.Key) + ".bars"; if (fi.DirectoryName == null) { throw new LPGException("File was not assigned to a directory"); } var cleanedfullname = Path.Combine(fi.DirectoryName, modifiedName); Save(plotModel1, plotName, cleanedfullname, basisPath, CalcOption.HouseholdContents); } Profiler.StopPart(Utili.GetCurrentMethodAndClass()); }
private static void MakeGeneralBarChart([ItemNotNull][JetBrains.Annotations.NotNull] List <AffordanceEntry> entries, [JetBrains.Annotations.NotNull] string dstDir) { var householdNames = entries.Select(x => x.HouseholdName.Trim()).Distinct().ToList(); // make absolute values var plotModel1 = MakePlotmodel(householdNames, ChartLocalizer.Get().GetTranslation("Electricity") + " in kWh"); var affNames = entries.Select(x => x.AffordanceName).Distinct().ToList(); affNames.Sort((x, y) => string.Compare(x, y, StringComparison.Ordinal)); OxyPalette p; if (affNames.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(affNames.Count); } for (var i = 0; i < affNames.Count; i++) { var tag = affNames[i]; var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, StrokeColor = OxyColors.White, Title = ChartLocalizer.Get().GetTranslation(tag), LabelPlacement = LabelPlacement.Middle, FillColor = p.Colors[i] }; foreach (var householdName in householdNames) { var te = entries.FirstOrDefault(x => x.AffordanceName == tag && x.HouseholdName == householdName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel1.Series.Add(columnSeries2); } var fileName = Path.Combine(dstDir, "MergedAffordanceEnergyUse.pdf"); OxyPDFCreator.Run(plotModel1, fileName); var hhSums = new Dictionary <string, double>(); var households = entries.Select(x => x.HouseholdName).Distinct().ToList(); foreach (var household in households) { var sum = entries.Where(x => x.HouseholdName == household).Select(x => x.Value).Sum(); hhSums.Add(household, sum); } foreach (var affordanceName in affNames) { var plotModel2 = MakePlotmodel(householdNames, "Anteil am Gesamtverbrauch in Prozent"); plotModel2.LegendFontSize = Fontsize; var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, Title = ChartLocalizer.Get().GetTranslation(affordanceName), LabelPlacement = LabelPlacement.Middle, FillColor = OxyColors.LightBlue }; var averageValue = entries.Where(x => x.AffordanceName == affordanceName) .Select(x => x.Value / hhSums[x.HouseholdName] * 100) .Average(); var ls = new LineSeries { Color = OxyColors.Red, Title = "Durchschnitt" }; for (var i = 0; i < householdNames.Count; i++) { var householdName = householdNames[i]; ls.Points.Add(new DataPoint(i, averageValue)); var te = entries.FirstOrDefault( x => x.AffordanceName == affordanceName && x.HouseholdName == householdName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / hhSums[householdName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel2.Series.Add(columnSeries2); plotModel2.Series.Add(ls); var cleanTag = AutomationUtili.CleanFileName(affordanceName); var relfileName = Path.Combine(dstDir, "MergedAffordanceTaggingEnergyUse." + cleanTag + ".pdf"); OxyPDFCreator.Run(plotModel2, relfileName); } }
private void DrawChart([JetBrains.Annotations.NotNull] HouseholdKeyEntry hhkey, [JetBrains.Annotations.NotNull] Dictionary <string, List <double> > energyUsesPerPersonByAfforcance, [ItemNotNull][JetBrains.Annotations.NotNull] List <string> persons, [JetBrains.Annotations.NotNull] CalcLoadTypeDto lti) { string plotName = "Affordance Energy Use Per Person " + hhkey.HHKey.Key + " " + lti.Name; var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter, LegendMargin = 10, LegendItemAlignment = HorizontalAlignment.Left }; var labelfontsize = 14; if (Config.MakePDFCharts) { plotModel1.DefaultFontSize = Parameters.PDFFontSize; plotModel1.LegendFontSize = 16; labelfontsize = 18; } if (Parameters.ShowTitle) { plotModel1.Title = plotName; } // axes var categoryAxis1 = new CategoryAxis { MinorStep = 1, GapWidth = 1, Position = AxisPosition.Left }; OxyPalette p; if (energyUsesPerPersonByAfforcance.Count > 1) { p = OxyPalettes.HueDistinct(energyUsesPerPersonByAfforcance.Count); } else { p = OxyPalettes.Hue64; } foreach (var personName in persons) { categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation(personName)); } plotModel1.Axes.Add(categoryAxis1); string s2 = lti.Name + " in " + lti.UnitOfSum; var linearAxis1 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.03, MinimumPadding = 0, MinorTickSize = 0, Position = AxisPosition.Bottom, Title = ChartLocalizer.Get().GetTranslation(s2) }; plotModel1.Axes.Add(linearAxis1); // generate plot var count = 0; Dictionary <int, double> colSums2 = new Dictionary <int, double>(); Dictionary <int, double> colSums = new Dictionary <int, double>(); for (int i = 0; i < persons.Count; i++) { colSums.Add(i, 0); colSums2.Add(i, 0); } foreach (var pair in energyUsesPerPersonByAfforcance) { // main columns var columnSeries2 = new BarSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 0.1, StrokeColor = OxyColors.White, Title = pair.Key, //affordance name LabelPlacement = LabelPlacement.Middle, FillColor = p.Colors[count++] }; var col = 0; foreach (var d in pair.Value) { //energy use values var coli = new BarItem(d); colSums2[col] += d; columnSeries2.Items.Add(coli); col++; } plotModel1.Series.Add(columnSeries2); } foreach (var pair in energyUsesPerPersonByAfforcance) { var col = 0; foreach (var d in pair.Value) { if (d / colSums2[col] > 0.2) { { var textAnnotation1 = new RectangleAnnotation(); var shortendName = pair.Key; if (shortendName.Length > 30) { shortendName = shortendName.Substring(0, 30) + "..."; } textAnnotation1.Text = shortendName; textAnnotation1.MinimumX = colSums[col]; textAnnotation1.MaximumX = colSums[col] + d; textAnnotation1.MinimumY = col + 0.35; textAnnotation1.MaximumY = col + 0.45; textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left; textAnnotation1.TextVerticalAlignment = VerticalAlignment.Middle; textAnnotation1.FontSize = labelfontsize; textAnnotation1.StrokeThickness = 0; textAnnotation1.Fill = OxyColors.White; plotModel1.Annotations.Add(textAnnotation1); } { var textAnnotation2 = new RectangleAnnotation { Text = d.ToString("N1", CultureInfo.CurrentCulture) + " " + lti.UnitOfSum, TextHorizontalAlignment = HorizontalAlignment.Left, TextVerticalAlignment = VerticalAlignment.Middle, MinimumX = colSums[col], MaximumX = colSums[col] + d, MinimumY = col + 0.25, MaximumY = col + 0.35, Fill = OxyColors.White, FontSize = labelfontsize, StrokeThickness = 0 }; plotModel1.Annotations.Add(textAnnotation2); } } colSums[col] += d; col++; } } Save(plotModel1, plotName, "AffordanceEnergyUsePerPerson." + hhkey.HHKey + "." + lti.FileName + ".png", Parameters.BaseDirectory, CalcOption.AffordanceEnergyUse); }
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" }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry rfe) { Profiler.StartPart(Utili.GetCurrentMethodAndClass()); string plotName = "Time of Use " + rfe.HouseholdNumberString + " " + rfe.LoadTypeInformation?.Name; bool isEnergy = rfe.ResultFileID == ResultFileID.TimeOfUseEnergy; var devices = new List <Device>(); if (rfe.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(rfe.FullFileName)) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed"); } var header1 = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); foreach (var header in header1) { devices.Add(new Device(header)); } while (!sr.EndOfStream && s.Length > 0) { s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed"); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); for (var index = 2; index < cols.Length; index++) { var col = cols[index]; if (col.Length > 0) { if (col.Length > 0) { var success = double.TryParse(col, out double d); if (!success) { throw new LPGException("Double Trouble! " + rfe.FileName); } devices[index].Values.Add(d); } } } } } devices.RemoveAt(0); devices.RemoveAt(0); devices.Sort((x, y) => y.Sum.CompareTo(x.Sum)); double max = 0; for (var i = 0; i < devices[0].Values.Count; i++) { double sum = 0; foreach (var device in devices) { if (device.Values.Count > i) { sum += device.Values[i]; } } if (sum > max) { max = sum; } } var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; if (Parameters.ShowTitle) { plotModel1.Title = plotName; } // axes var cate = new CategoryAxis { AbsoluteMinimum = 0, MinimumPadding = 0, GapWidth = 0, MajorStep = 60, Title = "Minutes" }; plotModel1.Axes.Add(cate); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0 }; if (isEnergy) { linearAxis2.Title = rfe.LoadTypeInformation?.Name + " in " + rfe.LoadTypeInformation?.UnitOfPower; } else { linearAxis2.Title = "Minutes/(Household-Year)"; } linearAxis2.Minimum = 0; linearAxis2.Maximum = max * 1.05; plotModel1.Axes.Add(linearAxis2); // data var p = OxyPalettes.HueDistinct(devices.Count); for (var i = 0; i < devices.Count; i++) { // main columns var columnSeries2 = new ColumnSeries { IsStacked = true, StrokeThickness = 0, Title = devices[i].Name }; var myvalues = devices[i].Values; for (var j = 0; j < myvalues.Count; j++) { columnSeries2.Items.Add(new ColumnItem(myvalues[j])); } columnSeries2.FillColor = p.Colors[i]; plotModel1.Series.Add(columnSeries2); } Save(plotModel1, plotName, rfe.FullFileName, Parameters.BaseDirectory, CalcOption.TimeOfUsePlot); Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
private void InitializeChart() { // Create the plot model var mainModel = new PlotModel { DefaultColors = OxyPalettes.HueDistinct(NumSeries).Colors, IsLegendVisible = true, Title = "Draw on me!" }; // Add a basic xAxis mainModel.Axes.Add(new LinearAxis { IsPanEnabled = true, IsZoomEnabled = true, Key = "xAxis", Position = AxisPosition.Bottom, MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot, Title = "X" }); // And a basic yAxis mainModel.Axes.Add(new LinearAxis { IsPanEnabled = true, IsZoomEnabled = true, Key = "yAxis", Position = AxisPosition.Left, MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dot, Title = "Y" }); // And generate some interesting data on the chart to play with for (int s = 0; s < NumSeries; s++) { switch (s % 3) { case 0: mainModel.Series.Add(new FunctionSeries(x => Math.Sin(x + s), MinimumX, MaximumX, NumPoints) { YAxisKey = "yAxis" }); break; case 1: mainModel.Series.Add(new FunctionSeries(x => Math.Sin((x + s) / 4) * Math.Acos(Math.Sin(x + s)), MinimumX, MaximumX, NumPoints) { YAxisKey = "yAxis" }); break; case 2: mainModel.Series.Add(new FunctionSeries( x => Math.Sin(2 * Math.Cos(2 * Math.Sin(2 * Math.Cos(x + s)))), MinimumX, MaximumX, NumPoints) { YAxisKey = "yAxis" }); break; } } // Add the model to both the PlotView and the Drawing Toolbar uiPlotView.Model = mainModel; uiDrawingToolbar.ChartModel = mainModel; // Add saving and printing events to the drawing toolbar uiDrawingToolbar.uiSaveButton.Click += uiSaveButton_OnClick; uiDrawingToolbar.uiPrintButton.Click += uiPrintButton_OnClick; // And for fun, make it so you can copy the chart with Ctrl+C uiPlotView.ActualController.BindKeyDown(OxyKey.C, OxyModifierKeys.Control, new DelegatePlotCommand <OxyKeyEventArgs>( CopyChart_OnKeyDown)); }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry rfe) { string plotName = "Affordance Tagging Set " + rfe.HouseholdNumberString; Profiler.StartPart(Utili.GetCurrentMethodAndClass()); var consumption = new Dictionary <string, List <double> >(); var colNames = new Dictionary <int, string>(); var colSums = new Dictionary <int, double>(); double totalSum = 0; if (rfe.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(rfe.FullFileName)) { // read data var header = sr.ReadLine(); if (header == null) { throw new LPGException("Readline failed."); } var colheaders = header.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); for (var index = 1; index < colheaders.Length; index++) { if (colheaders[index].Length > 0) { colNames.Add(index, colheaders[index]); colSums.Add(index - 1, 0); } } while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed."); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); var list = new List <double>(); consumption.Add(cols[0], list); for (var index = 1; index < cols.Length - 1; index++) { var d = Convert.ToDouble(cols[index], CultureInfo.CurrentCulture); list.Add(d); totalSum += d; } } } var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter, LegendSymbolMargin = 20 }; var labelFontSize = 11; var pngOffset = 0.1; // in the pdfs the vertical text gets moved a little. this is the offset in the png to counter that. if (Config.MakePDFCharts) { plotModel1.DefaultFontSize = Parameters.PDFFontSize; plotModel1.LegendFontSize = Parameters.PDFFontSize; labelFontSize = 16; pngOffset = 0; } if (Parameters.ShowTitle) { plotModel1.Title = plotName; } // axes var categoryAxis1 = new CategoryAxis { MinorStep = 1, MaximumPadding = 0.02, GapWidth = 1, FontSize = 18 }; foreach (var s in colNames.Values) { categoryAxis1.Labels.Add(ChartLocalizer.Get().GetTranslation(s)); } plotModel1.Axes.Add(categoryAxis1); var linearAxis1 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.03, MinimumPadding = 0, MinorTickSize = 0 }; linearAxis1.MajorStep *= 2; linearAxis1.Title = ChartLocalizer.Get().GetTranslation("Time in Percent"); plotModel1.Axes.Add(linearAxis1); OxyPalette p; if (consumption.Count > 1) { p = OxyPalettes.HueDistinct(consumption.Count); } else { p = OxyPalettes.Hue64; } // generate plot var colheight = totalSum / consumption.Values.First().Count; var count = 0; foreach (var keyValuePair in consumption) { // main columns var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 0.5, StrokeColor = OxyColors.White, Title = ChartLocalizer.Get().GetTranslation(keyValuePair.Key), LabelPlacement = LabelPlacement.Middle }; var col = 0; foreach (var minutes in keyValuePair.Value) { var d = minutes / colheight * 100; var ci = new ColumnItem(d); columnSeries2.Items.Add(ci); if (d > 15) { { var textAnnotation1 = new RectangleAnnotation { Text = minutes.ToString("N0", CultureInfo.CurrentCulture) + " min (" + d.ToString("N1", CultureInfo.CurrentCulture) + " %)", TextHorizontalAlignment = HorizontalAlignment.Left, TextVerticalAlignment = VerticalAlignment.Top, StrokeThickness = 0, MinimumY = colSums[col], MaximumY = colSums[col] + d, MinimumX = col + 0.28 + pngOffset, MaximumX = col + 0.40 + pngOffset, Fill = OxyColors.Transparent, TextRotation = 270, FontSize = labelFontSize }; plotModel1.Annotations.Add(textAnnotation1); } { var textAnnotation1 = new RectangleAnnotation(); var shortendName = ChartLocalizer.Get().GetTranslation(keyValuePair.Key); if (shortendName.Length > 20) { shortendName = shortendName.Substring(0, 17) + "..."; } textAnnotation1.Text = shortendName.Trim(); textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left; textAnnotation1.TextVerticalAlignment = VerticalAlignment.Top; textAnnotation1.StrokeThickness = 0; textAnnotation1.MinimumY = colSums[col]; textAnnotation1.MaximumY = colSums[col] + d; textAnnotation1.MinimumX = col + 0.20 + pngOffset; textAnnotation1.MaximumX = col + 0.30 + pngOffset; textAnnotation1.Fill = OxyColors.Transparent; textAnnotation1.TextRotation = 270; textAnnotation1.FontSize = labelFontSize; plotModel1.Annotations.Add(textAnnotation1); } } colSums[col] += d; col++; } columnSeries2.FillColor = p.Colors[count]; count++; plotModel1.Series.Add(columnSeries2); } Save(plotModel1, plotName, rfe.FullFileName, Parameters.BaseDirectory, CalcOption.HouseholdContents); Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry srcResultFileEntry) { string plotName = "Activity Percentages " + srcResultFileEntry.HouseholdKey + " " + srcResultFileEntry.LoadTypeInformation?.Name; Profiler.StartPart(Utili.GetCurrentMethodAndClass()); var consumption = new Dictionary <string, List <Tuple <string, double> > >(); var lastname = string.Empty; if (srcResultFileEntry.FullFileName == null) { throw new LPGException("Srcfile was null"); } using (var sr = new StreamReader(srcResultFileEntry.FullFileName)) { while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed"); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); if (cols.Length == 1) { consumption.Add(cols[0], new List <Tuple <string, double> >()); lastname = cols[0]; sr.ReadLine(); } else { var val = Convert.ToDouble(cols[1], CultureInfo.CurrentCulture); consumption[lastname].Add(new Tuple <string, double>(cols[0], val)); } } } foreach (var pair in consumption) { var personname = pair.Key; var plotModel1 = new PlotModel { LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; if (Parameters.ShowTitle) { plotModel1.Title = plotName + " " + personname; } var pieSeries1 = new PieSeries { InsideLabelColor = OxyColors.White, InsideLabelPosition = 0.8, StrokeThickness = 2, AreInsideLabelsAngled = true }; OxyPalette p; if (pair.Value.Count > 2) { p = OxyPalettes.HueDistinct(pair.Value.Count); } else { p = OxyPalettes.Hue64; } pieSeries1.InsideLabelColor = OxyColor.FromRgb(0, 0, 0); var i = 0; foreach (var tuple in pair.Value) { var name = tuple.Item1.Trim(); if (name.Length > 30) { name = name.Substring(0, 20) + "..."; } var slice = new PieSlice(name, tuple.Item2) { Fill = p.Colors[i++] }; pieSeries1.Slices.Add(slice); } plotModel1.Series.Add(pieSeries1); Save(plotModel1, plotName, srcResultFileEntry.FullFileName + "." + personname, Parameters.BaseDirectory, CalcOption.ActivationFrequencies); } Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
protected override FileProcessingResult MakeOnePlot(ResultFileEntry srcResultFileEntry) { string plotName = "Device Profiles External Time Resolution " + srcResultFileEntry.HouseholdNumberString + " " + srcResultFileEntry.LoadTypeInformation?.Name; Profiler.StartPart(Utili.GetCurrentMethodAndClass()); var headers = new List <string>(); var values = new List <double[]>(); if (srcResultFileEntry.FullFileName == null) { throw new LPGException("fullfilename was null"); } using (var sr = new StreamReader(srcResultFileEntry.FullFileName)) { var topLine = sr.ReadLine(); if (topLine == null) { throw new LPGException("Readline failed"); } var header1 = topLine.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); headers.AddRange(header1); while (!sr.EndOfStream && values.Count < 5000) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed"); } var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); var result = new double[headers.Count]; for (var index = 0; index < cols.Length; index++) { var col = cols[index]; var success = double.TryParse(col, out double d); if (success) { result[index] = d; } } values.Add(result); } } var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter }; if (Parameters.ShowTitle) { plotModel1.Title = plotName; } // axes var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = "2" }; plotModel1.Axes.Add(linearAxis2); // data OxyPalette p; if (headers.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(headers.Count); } for (var i = 2; i < headers.Count; i++) { // main columns var columnSeries2 = new AreaSeries { StrokeThickness = 0, Title = headers[i] }; for (var j = 0; j < values.Count; j++) { double sum = 0; for (var k = i - 1; k > 0; k--) { sum += values[j][k]; } var bottom = new DataPoint(j, sum); columnSeries2.Points.Add(bottom); var top = new DataPoint(j, sum + values[j][i]); columnSeries2.Points2.Add(top); } columnSeries2.Color = p.Colors[i]; plotModel1.Series.Add(columnSeries2); } Save(plotModel1, plotName, srcResultFileEntry.FullFileName, Parameters.BaseDirectory, CalcOption.DeviceProfileExternalIndividualHouseholds); Profiler.StopPart(Utili.GetCurrentMethodAndClass()); return(FileProcessingResult.ShouldCreateFiles); }
public void MakePlotMonthly([JetBrains.Annotations.NotNull] ResultFileEntry rfe, [JetBrains.Annotations.NotNull] string plotName, [JetBrains.Annotations.NotNull] DirectoryInfo basisPath) { Profiler.StartPart(Utili.GetCurrentMethodAndClass()); var consumption = new List <Tuple <string, List <double> > >(); var months = 0; double totalSum = 0; if (rfe.FullFileName == null) { throw new LPGException("filename was null"); } using (var sr = new StreamReader(rfe.FullFileName)) { sr.ReadLine(); // header while (!sr.EndOfStream) { var s = sr.ReadLine(); if (s == null) { throw new LPGException("Readline failed."); } if (!s.StartsWith("Sums;", StringComparison.Ordinal)) { var cols = s.Split(Parameters.CSVCharacterArr, StringSplitOptions.None); var l = new List <double>(); for (var i = 1; i < cols.Length; i++) { if (cols[i].Length > 0) { var d = Convert.ToDouble(cols[i], CultureInfo.CurrentCulture); totalSum += d; l.Add(d); } } consumption.Add(new Tuple <string, List <double> >(cols[0], l)); if (l.Count > months) { months = l.Count; } } } } if (consumption.Count == 0) { return; } var plotModel1 = new PlotModel { // general LegendBorderThickness = 0, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Outside, LegendPosition = LegendPosition.BottomCenter, Title = plotName }; // axes var categoryAxis1 = new CategoryAxis { MinorStep = 1 }; var colSums = new Dictionary <int, double>(); for (var i = 0; i < months; i++) { categoryAxis1.Labels.Add("Month " + (i + 1)); colSums.Add(i, 0); } plotModel1.Axes.Add(categoryAxis1); var linearAxis1 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0 }; plotModel1.Axes.Add(linearAxis1); // generate plot var p = OxyPalettes.Hue64; if (consumption.Count > 1) { p = OxyPalettes.HueDistinct(consumption.Count); } var series = 0; foreach (var pair in consumption) { // main columns var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, Title = pair.Item1, LabelPlacement = LabelPlacement.Middle, FillColor = p.Colors[series++] }; var col = 0; foreach (var d in pair.Item2) { var ci = new ColumnItem(d); columnSeries2.Items.Add(ci); colSums[col] += d; if (d / totalSum > 0.025) { var textAnnotation1 = new TextAnnotation(); var shortendName = pair.Item1; if (shortendName.Length > 15) { shortendName = shortendName.Substring(0, 15) + "..."; } textAnnotation1.Text = shortendName + Environment.NewLine + d; textAnnotation1.TextPosition = new DataPoint(col + 0.3, colSums[col] - d / 2); textAnnotation1.TextHorizontalAlignment = HorizontalAlignment.Left; textAnnotation1.TextVerticalAlignment = VerticalAlignment.Middle; plotModel1.Annotations.Add(textAnnotation1); } col++; } plotModel1.Series.Add(columnSeries2); } Save(plotModel1, plotName, rfe.FullFileName, basisPath, CalcOption.TotalsPerDevice); Profiler.StopPart(Utili.GetCurrentMethodAndClass()); }
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); }
private static void MakeBarCharts([JetBrains.Annotations.NotNull] string setName, [ItemNotNull][JetBrains.Annotations.NotNull] List <TagEntry> entries, [JetBrains.Annotations.NotNull] string dstDirectory) { var householdNames = entries.Select(x => x.HouseholdName.Trim()).Distinct().ToList(); // make absolute values var plotModel1 = MakePlotmodel(householdNames, ChartLocalizer.Get().GetTranslation("Electricity") + " in kWh"); var tagNames = entries.Select(x => x.TagName).Distinct().ToList(); OxyPalette p; if (tagNames.Count < 2) { p = OxyPalettes.Hue64; } else { p = OxyPalettes.HueDistinct(tagNames.Count); } for (var i = 0; i < tagNames.Count; i++) { var tag = tagNames[i]; var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, StrokeColor = OxyColors.White, Title = ChartLocalizer.Get().GetTranslation(tag), LabelPlacement = LabelPlacement.Middle, FillColor = p.Colors[i] }; foreach (var householdName in householdNames) { var te = entries.FirstOrDefault(x => x.TagName == tag && x.HouseholdName == householdName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel1.Series.Add(columnSeries2); } var fileName = "MergedDeviceTagging." + setName + ".pdf"; OxyPDFCreator.Run(plotModel1, fileName); var hhSums = new Dictionary <string, double>(); foreach (var householdName in householdNames) { var sum = entries.Where(x => x.HouseholdName == householdName).Select(x => x.Value).Sum(); hhSums.Add(householdName, sum); } foreach (var tagName in tagNames) { var plotModel2 = MakePlotmodel(householdNames, "Anteil am Gesamtverbrauch in Prozent"); var columnSeries2 = new ColumnSeries { IsStacked = true, StackGroup = "1", StrokeThickness = 1, StrokeColor = OxyColors.White, Title = ChartLocalizer.Get().GetTranslation(tagName), LabelPlacement = LabelPlacement.Middle, FillColor = OxyColors.LightBlue }; foreach (var householdName in householdNames) { var te = entries.FirstOrDefault(x => x.TagName == tagName && x.HouseholdName == householdName); if (te != null) { columnSeries2.Items.Add(new ColumnItem(te.Value / hhSums[householdName] * 100)); } else { columnSeries2.Items.Add(new ColumnItem(0)); } } plotModel2.Series.Add(columnSeries2); var cleanTag = AutomationUtili.CleanFileName(tagName); var relfileName = Path.Combine(dstDirectory, "MergedDeviceTagging." + setName + "." + cleanTag + ".pdf"); OxyPDFCreator.Run(plotModel2, relfileName); } }
private static void MakeBarPlot([JetBrains.Annotations.NotNull] string outputPath, [ItemNotNull][JetBrains.Annotations.NotNull] List <Column> columns, int position, int day) { var plotModel2 = new PlotModel(); // filter significant columns var allColumns = new List <Tuple <string, double> >(); for (var i = 1; i < columns.Count; i++) { allColumns.Add(new Tuple <string, double>(columns[i].Name, columns[i].MakeSum(position, 1440))); } allColumns.Sort((x, y) => y.Item2.CompareTo(x.Item2)); var topCols = allColumns.Select(x => x.Item1).Take(20).ToList(); var p = OxyPalettes.HueDistinct(topCols.Count); var oxc = OxyColor.FromArgb(255, 50, 50, 50); plotModel2.LegendPosition = LegendPosition.BottomCenter; plotModel2.LegendPlacement = LegendPlacement.Outside; plotModel2.LegendOrientation = LegendOrientation.Horizontal; plotModel2.Title = "Day " + day; // axes var cate = new CategoryAxis { AbsoluteMinimum = 0, MinimumPadding = 0, GapWidth = 0, MajorStep = 60, Title = "Activities" }; plotModel2.Axes.Add(cate); var linearAxis2 = new LinearAxis { AbsoluteMinimum = 0, MaximumPadding = 0.06, MinimumPadding = 0, Title = "Minutes" }; plotModel2.Axes.Add(linearAxis2); const int minutesToSum = 15; for (var i = 1; i < columns.Count; i++) { if (columns[i].MakeSum(position, 1440) > 0) { var columnSeries2 = new ColumnSeries { IsStacked = true, StrokeThickness = 0, Title = columns[i].Name }; for (var j = position; j < position + 1440; j += minutesToSum) { columnSeries2.Items.Add(new ColumnItem(columns[i].MakeSum(j, minutesToSum) / minutesToSum)); } if (topCols.Contains(columns[i].Name)) { var coloridx = topCols.IndexOf(columns[i].Name); columnSeries2.FillColor = p.Colors[coloridx]; } else { columnSeries2.FillColor = oxc; } plotModel2.Series.Add(columnSeries2); } } var path2 = Path.Combine(outputPath, "ActivityPlot." + day + ".bar.png"); PngExporter.Export(plotModel2, path2, 3200, 1600, OxyColor.FromRgb(255, 255, 255), 100); }
private void InitializeChart() { var model = new PlotModel { DefaultColors = OxyPalettes.HueDistinct(4).Colors, LegendBackground = OxyColor.FromAColor(140, OxyColors.WhiteSmoke), LegendBorder = OxyColors.Black, LegendOrientation = LegendOrientation.Horizontal, LegendPlacement = LegendPlacement.Inside, LegendPosition = LegendPosition.BottomLeft, Title = "Real Time (Matriz de Rotação para Euler Angles)" }; xAxis = new LinearAxis { Key = "xAxis", Position = AxisPosition.Bottom, MajorGridlineStyle = LineStyle.Solid, MinorGridlineStyle = LineStyle.Dash, Title = "Time", }; model.Axes.Add(xAxis); yAxis = new LinearAxis { Key = "yAxis1", Position = AxisPosition.Left, PositionTier = 0, Minimum = -250, Maximum = 250, Title = "Graus º" }; model.Axes.Add(yAxis); _series1 = new LineSeries { LineStyle = LineStyle.Solid, StrokeThickness = 1, Tag = "pitch", Title = "pitch", YAxisKey = "yAxis1" }; model.Series.Add(_series1); _series2 = new LineSeries { LineStyle = LineStyle.Solid, StrokeThickness = 1, Tag = "roll", Title = "roll", YAxisKey = "yAxis1" }; model.Series.Add(_series2); _series3 = new LineSeries { LineStyle = LineStyle.Solid, StrokeThickness = 1, Tag = "yaw", Title = "yaw", YAxisKey = "yAxis1" }; model.Series.Add(_series3); uiMainPlot.Model = model; }
public static PlotModel HueDistinctReverse200() { return(HeatMapSeriesExamples.CreatePeaks(OxyPalettes.HueDistinct(200).Reverse(), false)); }
static void Main(string[] args) { //############################################################### //INICIALIZACIÓN DEL PROCESO //############################################################### //Inicialización de mlContext; utilización del seed para replicidad MLContext mlContext = new MLContext(seed: 1); //Definición de las clases de los datos de entrada: // -Clase Observaciones: CountryObservation //Carga de datos IDataView originalFullData = mlContext.Data .LoadFromTextFile <CountryObservation>( _DataPath, separatorChar: ',', hasHeader: true); //############################################################### //CONSTRUYE EL CONJUNTO DE DATOS (DATASET) //############################################################### IDataView trainingDataView = originalFullData; //Guardamos dataset trainingDataView using (var fileStream = File.Create(_salida_trainDataPath)) { mlContext.Data.SaveAsText(trainingDataView, fileStream, separatorChar: ';', headerRow: true, schema: true); } //############################################################### //SELECCIÓN DE VARIABLES //############################################################### //Suprimimos del esquema IDataView lo que no seleccionemos como features string[] featureColumnNames = trainingDataView.Schema.AsQueryable() .Select(column => column.Name) .Where(name => name != "country")//no aporta información .ToArray(); //############################################################### //TRANFORMACIÓN DE LOS DATOS DEL MODELO --> pipeline //############################################################### //Concatena IEstimator <ITransformer> pipeline = mlContext.Transforms.Concatenate("Features", featureColumnNames) //Normalizado de las Features .Append(mlContext.Transforms.NormalizeMinMax(inputColumnName: "Features", outputColumnName: "FeaturesNormalized")); //Guardamos dataset transformedData IDataView transformedData = pipeline.Fit(trainingDataView).Transform(trainingDataView); using (var fileStream = File.Create(_salida_transformationData)) { mlContext.Data.SaveAsText(transformedData, fileStream, separatorChar: ';', headerRow: true, schema: true); } //############################################################### //SELECCIÓN DEL ALGORITMO DE ENTRENAMIENTO --> trainingPipeline //############################################################### //*************************************************************** //1. K-Means //*************************************************************** //Selección del Número de Clusters int k = 4; //Opciones K-Means var options = new KMeansTrainer.Options { FeatureColumnName = "FeaturesNormalized", NumberOfClusters = k, MaximumNumberOfIterations = 5800, OptimizationTolerance = 1e-6f }; //K-Means var trainer_km = mlContext.Clustering.Trainers.KMeans(options); //Se añade el Algoritmo al pipeline de transformación de datos IEstimator <ITransformer> trainingPipeline_km = pipeline.Append(trainer_km); //############################################################### //ENTRENAMIENTO DEL MODELO //############################################################### Console.WriteLine($"\n**************************************************************"); Console.WriteLine($"* Entrenamiento del Modelo calculado con el Algoritmo K-Means "); Console.WriteLine($"*-------------------------------------------------------------"); var watch_km = System.Diagnostics.Stopwatch.StartNew(); var model_km = trainingPipeline_km.Fit(trainingDataView); watch_km.Stop(); var elapseds_km = watch_km.ElapsedMilliseconds * 0.001; Console.WriteLine($"El entrenamiento K-Means ha tardado: {elapseds_km:#.##} s\n"); //############################################################### //EVALUACIÓN DEL MODELO //############################################################### //Transformación del IDataView trainingDataView var predictions_km = model_km.Transform(trainingDataView); //Calculo de las métricas de cada Modelo var metrics_km = mlContext.Clustering.Evaluate(predictions_km, scoreColumnName: "Score", featureColumnName: "FeaturesNormalized"); //Mostramos las métricas K-Means Console.WriteLine($"\n**************************************************************"); Console.WriteLine($"* Métricas para el Modelo calculado con el Algoritmo K-Means "); Console.WriteLine($"*-------------------------------------------------------------"); Console.WriteLine($"* K-Means Average Distance: {metrics_km.AverageDistance:#.##}"); Console.WriteLine($"* K-Means Davies Bouldin Index: {metrics_km.DaviesBouldinIndex:#.##}"); Console.WriteLine($"* K-Means Normalized Mutual Information: {metrics_km.NormalizedMutualInformation:#.##}"); //############################################################### //SELECCIÓN MODELO //############################################################### //Guardamos el Modelo para su posterior consumo mlContext.Model.Save(model_km, trainingDataView.Schema, _salida_modelPath); //############################################################### //VISUALIZACIÓN DEL MODELO //############################################################### //Definición de las clases de las predicciones: // -Clase Predicciones: CountryPrediction //Inicialización de PlotModel var plot = new PlotModel { Title = "Clúster Paises", IsLegendVisible = true }; //Transformamos el dataset con el Modelo var predictionsData = model_km.Transform(trainingDataView); //Creamos Array a partir del IDataView y la clase de predicción var predictions = mlContext.Data .CreateEnumerable <CountryPrediction>(predictionsData, false) .ToArray(); //Extraemos la lista de los nombres clusteres creados var clusters = predictions .Select(p => p.PredictedLabel).Distinct().OrderBy(x => x); //Construimos el conjunto de puntos para su visualización foreach (var cluster in clusters) { var scatter = new ScatterSeries { MarkerType = MarkerType.Circle, MarkerStrokeThickness = 2, Title = $"Cluster: {cluster}", RenderInLegend = true }; //Array ScatterPoint (2 dimensiones) var series = predictions .Where(p => p.PredictedLabel == cluster) //Seleccionamos 2 de las 5 coordenadas de nuestras Features .Select(p => new ScatterPoint(p.Location[2], p.Location[0])).ToArray(); scatter.Points.AddRange(series); plot.Series.Add(scatter); } //Le damos un color a cada cluster plot.DefaultColors = OxyPalettes.HueDistinct(plot.Series.Count).Colors; //Guardamos la gráfica en un archivo .svg var exporter = new SvgExporter { Width = 1000, Height = 800 }; using (var fs = new System.IO.FileStream(_salida_plotDataPath, System.IO.FileMode.Create)) { exporter.Export(plot, fs); } //Guardamos un archivo .csv con el cluster resultante para cada pais using (var w = new System.IO.StreamWriter(_salida_ResultDataPath)) { w.WriteLine($"Country;Cluster"); w.Flush(); predictions.ToList().ForEach(prediction => { w.WriteLine($"{prediction.country};{prediction.PredictedLabel}"); w.Flush(); }); } }