Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.RegressionSolutionGradientView/HeuristicLab.Problems.DataAnalysis.Views/3.4/GradientChart.cs @ 13836

Last change on this file since 13836 was 13836, checked in by pfleck, 8 years ago

#2597 Implemented correct coloring when multiple solutions are added for comparison with respect potential overlapping confidence intervals.

File size: 15.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Drawing;
25using System.Globalization;
26using System.Linq;
27using System.Windows.Forms;
28using System.Windows.Forms.DataVisualization.Charting;
29using HeuristicLab.Common;
30using HeuristicLab.MainForm.WindowsForms;
31using HeuristicLab.Visualization.ChartControlsExtensions;
32
33namespace HeuristicLab.Problems.DataAnalysis.Views {
34  public partial class GradientChart : UserControl {
35    private ModifiableDataset sharedFixedVariables; // used for syncronising variable values between charts
36    private ModifiableDataset internalDataset; // used to cache values and speed up calculations
37
38    public bool ShowLegend {
39      get { return chart.Legends[0].Enabled; }
40      set { chart.Legends[0].Enabled = value; }
41    }
42    public bool ShowXAxisLabel {
43      get { return chart.ChartAreas[0].AxisX.Enabled == AxisEnabled.True; }
44      set { chart.ChartAreas[0].AxisX.Enabled = value ? AxisEnabled.True : AxisEnabled.False; }
45    }
46    public bool ShowYAxisLabel {
47      get { return chart.ChartAreas[0].AxisY.Enabled == AxisEnabled.True; }
48      set { chart.ChartAreas[0].AxisY.Enabled = value ? AxisEnabled.True : AxisEnabled.False; }
49    }
50    public bool ShowCursor {
51      get { return chart.Annotations[0].Visible; }
52      set { chart.Annotations[0].Visible = value; }
53    }
54
55    private int xAxisTicks = 5;
56    public int XAxisTicks {
57      get { return xAxisTicks; }
58      set { if (xAxisTicks != value) { xAxisTicks = value; UpdateChart(); } }
59    }
60    private int yAxisTicks = 5;
61    public int YXAxisTicks {
62      get { return yAxisTicks; }
63      set { if (yAxisTicks != value) { yAxisTicks = value; UpdateChart(); } }
64    }
65
66    private double trainingMin = double.MinValue;
67    public double TrainingMin {
68      get { return trainingMin; }
69      set { if (!value.IsAlmost(trainingMin)) { trainingMin = value; UpdateChart(); } }
70    }
71    private double trainingMax = double.MaxValue;
72    public double TrainingMax {
73      get { return trainingMax; }
74      set { if (!value.IsAlmost(trainingMax)) { trainingMax = value; UpdateChart(); } }
75    }
76
77    private int drawingSteps = 1000;
78    public int DrawingSteps {
79      get { return drawingSteps; }
80      set { if (value != drawingSteps) { drawingSteps = value; UpdateChart(); } }
81    }
82
83    private string freeVariable;
84    public string FreeVariable {
85      get { return freeVariable; }
86      set {
87        if (value == freeVariable) return;
88        if (solutions.Any(s => !s.ProblemData.Dataset.DoubleVariables.Contains(value))) {
89          throw new ArgumentException("Variable does not exist in the ProblemData of the Solutions.");
90        }
91        freeVariable = value;
92        RecalculateInternalDataset();
93        UpdateChart();
94      }
95    }
96
97    private bool updateChartAutomatically = false;
98    public bool UpdateChartAutomatically {
99      get { return updateChartAutomatically; }
100      set { updateChartAutomatically = value; if (updateChartAutomatically) UpdateChart(); }
101    }
102
103    private readonly List<IRegressionSolution> solutions = new List<IRegressionSolution>();
104    public IEnumerable<IRegressionSolution> Solutions {
105      get { return solutions; }
106    }
107
108    private VerticalLineAnnotation VerticalLineAnnotation {
109      get { return (VerticalLineAnnotation)chart.Annotations.SingleOrDefault(x => x is VerticalLineAnnotation); }
110    }
111
112    public GradientChart() {
113      InitializeComponent();
114
115      // Configure axis
116      chart.CustomizeAllChartAreas();
117      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
118      chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
119      chart.ChartAreas[0].CursorX.Interval = 0;
120
121      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
122      chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
123      chart.ChartAreas[0].CursorY.Interval = 0;
124    }
125
126    public void Configure(IEnumerable<IRegressionSolution> solutions, ModifiableDataset sharedFixedVariables, string freeVariable, int drawingSteps) {
127      if (!SolutionsCompatible(solutions))
128        throw new ArgumentException("Solutions are not compatible with the problem data.");
129      this.solutions.Clear();
130      this.solutions.AddRange(solutions);
131      this.freeVariable = freeVariable;
132      this.drawingSteps = drawingSteps;
133
134      // add an event such that whenever a value is changed in the shared dataset,
135      // this change is reflected in the internal dataset (where the value becomes a whole column)
136      if (this.sharedFixedVariables != null)
137        this.sharedFixedVariables.ItemChanged -= sharedFixedVariables_ItemChanged;
138      this.sharedFixedVariables = sharedFixedVariables;
139      this.sharedFixedVariables.ItemChanged += sharedFixedVariables_ItemChanged;
140
141      trainingMin = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Min()).Max();
142      trainingMax = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Max()).Min();
143
144      RecalculateInternalDataset();
145    }
146
147    private void sharedFixedVariables_ItemChanged(object o, EventArgs<int, int> e) {
148      var sender = (ModifiableDataset)o;
149      var variables = sharedFixedVariables.DoubleVariables.ToList();
150      var rowIndex = e.Value;
151      var columnIndex = e.Value2;
152
153      var variableName = variables[columnIndex];
154      if (variableName == FreeVariable) return;
155      var v = sender.GetDoubleValue(variableName, rowIndex);
156      var values = new List<double>(Enumerable.Repeat(v, DrawingSteps));
157      internalDataset.ReplaceVariable(variableName, values);
158
159      if (UpdateChartAutomatically)
160        UpdateChart();
161    }
162
163    private void RecalculateInternalDataset() {
164      // we expand the range in order to get nice tick intervals on the x axis
165      double xmin, xmax, xinterval;
166      ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
167      double step = (xmax - xmin) / drawingSteps;
168
169      var xvalues = new List<double>();
170      for (int i = 0; i < drawingSteps; i++)
171        xvalues.Add(xmin + i * step);
172
173      var variables = sharedFixedVariables.DoubleVariables.ToList();
174      internalDataset = new ModifiableDataset(variables,
175        variables.Select(x => x == FreeVariable
176          ? xvalues
177          : Enumerable.Repeat(sharedFixedVariables.GetDoubleValue(x, 0), xvalues.Count).ToList()
178        )
179      );
180    }
181
182    public void UpdateChart() {
183      // throw exceptions?
184      if (sharedFixedVariables == null || solutions == null || !solutions.Any())
185        return;
186      if (trainingMin.IsAlmost(trainingMax) || trainingMin > trainingMax || drawingSteps == 0)
187        return;
188
189      // Set cursor
190      var defaultValue = sharedFixedVariables.GetDoubleValue(freeVariable, 0);
191      VerticalLineAnnotation.X = defaultValue;
192
193      // Calculate X-axis interval
194      double axisMin, axisMax, axisInterval;
195      ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out axisMin, out axisMax, out axisInterval);
196      var axis = chart.ChartAreas[0].AxisX;
197      axis.Minimum = axisMin;
198      axis.Maximum = axisMax;
199      axis.Interval = axisInterval;
200
201      // Create series <mean, conf. interval>
202      var seriesDict = new Dictionary<Series, Series>();
203      for (int i = 0; i < solutions.Count; ++i) {
204        var solution = solutions[i];
205        Series confidenceIntervalPlotSeries;
206        var meanSeries = CreateSeries(solution, out confidenceIntervalPlotSeries);
207        meanSeries.Name = Solutions.First().ProblemData.TargetVariable + " " + i;
208        seriesDict.Add(meanSeries, confidenceIntervalPlotSeries);
209        if (confidenceIntervalPlotSeries != null)
210          confidenceIntervalPlotSeries.Name = "95% Conf. Interval " + meanSeries.Name;
211      }
212
213      chart.SuspendRepaint();
214      chart.Series.Clear();
215      // Add mean series for applying palette colors
216      foreach (var series in seriesDict.Keys) {
217        series.LegendText = series.Name;
218        chart.Series.Add(series);
219      }
220      chart.Palette = ChartColorPalette.BrightPastel;
221      chart.ApplyPaletteColors();
222      chart.Palette = ChartColorPalette.None;
223
224      foreach (var series in seriesDict) {
225        if (series.Value == null) continue;
226        int idx = chart.Series.IndexOf(series.Key);
227        series.Value.Color = Color.FromArgb(40, series.Key.Color);
228        series.Value.IsVisibleInLegend = false;
229        chart.Series.Insert(idx, series.Value);
230      }
231      chart.ResumeRepaint(true);
232
233
234      //// calculate Y-axis interval
235      //double ymin = 0, ymax = 0;
236      //foreach (var v in chart.Series[0].Points.Select(x => x.YValues[0])) {
237      //  if (ymin > v) ymin = v;
238      //  if (ymax < v) ymax = v;
239      //}
240      //ChartUtil.CalculateAxisInterval(ymin, ymax, YXAxisTicks, out axisMin, out axisMax, out axisInterval);
241      //axis = chart.ChartAreas[0].AxisY;
242      //axis.Minimum = axisMin;
243      //axis.Maximum = axisMax;
244      //axis.Interval = axisInterval;
245
246      // set axis title
247      chart.ChartAreas[0].AxisX.Title = FreeVariable + " : " + defaultValue.ToString("N3", CultureInfo.CurrentCulture);
248
249      UpdateStripLines();
250    }
251
252    private Series CreateSeries(IRegressionSolution solution, out Series confidenceIntervalPlotSeries) {
253      var series = new Series {
254        ChartType = SeriesChartType.Line
255      };
256
257      var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
258      var yvalues = solution.Model.GetEstimatedValues(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
259      series.Points.DataBindXY(xvalues, yvalues);
260
261      var confidenceBoundSolution = solution as IConfidenceBoundRegressionSolution;
262      if (confidenceBoundSolution != null) {
263        var variances = confidenceBoundSolution.Model.GetEstimatedVariances(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
264
265        var lower = yvalues.Zip(variances, (m, s2) => m - 1.96 * Math.Sqrt(s2)).ToList();
266        var upper = yvalues.Zip(variances, (m, s2) => m + 1.96 * Math.Sqrt(s2)).ToList();
267
268        confidenceIntervalPlotSeries = new Series {
269          ChartType = SeriesChartType.Range,
270          YValuesPerPoint = 2
271        };
272        confidenceIntervalPlotSeries.Points.DataBindXY(xvalues, lower, upper);
273      } else {
274        confidenceIntervalPlotSeries = null;
275      }
276
277      return series;
278    }
279
280    public void AddSolution(IRegressionSolution solution) {
281      if (!SolutionsCompatible(solutions.Concat(new[] { solution })))
282        throw new ArgumentException("The solution is not compatible with the problem data.");
283      if (solutions.Contains(solution)) return;
284      solutions.Add(solution);
285      UpdateChart();
286    }
287    public void RemoveSolution(IRegressionSolution solution) {
288      bool removed = solutions.Remove(solution);
289      if (removed)
290        UpdateChart();
291    }
292
293    private static bool SolutionsCompatible(IEnumerable<IRegressionSolution> solutions) {
294      foreach (var solution1 in solutions) {
295        var variables1 = solution1.ProblemData.Dataset.DoubleVariables;
296        foreach (var solution2 in solutions) {
297          if (solution1 == solution2)
298            continue;
299          var variables2 = solution2.ProblemData.Dataset.DoubleVariables;
300          if (!variables1.All(variables2.Contains))
301            return false;
302        }
303      }
304      return true;
305    }
306
307    private void UpdateStripLines() {
308      var axisX = chart.ChartAreas[0].AxisX;
309      var lowerStripLine = axisX.StripLines[0];
310      var upperStripLine = axisX.StripLines[1];
311
312      lowerStripLine.IntervalOffset = axisX.Minimum;
313      lowerStripLine.StripWidth = trainingMin - axisX.Minimum;
314
315      upperStripLine.IntervalOffset = trainingMax;
316      upperStripLine.StripWidth = axisX.Maximum - trainingMax;
317    }
318
319    #region events
320    public event EventHandler VariableValueChanged;
321    public void OnVariableValueChanged(object sender, EventArgs args) {
322      var changed = VariableValueChanged;
323      if (changed == null) return;
324      changed(sender, args);
325    }
326
327    private void chart_AnnotationPositionChanged(object sender, EventArgs e) {
328      var annotation = VerticalLineAnnotation;
329      var x = annotation.X;
330      sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
331
332      chart.ChartAreas[0].AxisX.Title = FreeVariable + " : " + x.ToString("N3", CultureInfo.CurrentCulture);
333      chart.Update();
334
335      OnVariableValueChanged(this, EventArgs.Empty);
336    }
337
338    private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
339      //var step = (trainingMax - trainingMin) / drawingSteps;
340      //e.NewLocationX = step * (long)Math.Round(e.NewLocationX / step);
341      //var axisX = chart.ChartAreas[0].AxisX;
342      //if (e.NewLocationX > axisX.Maximum)
343      //  e.NewLocationX = axisX.Maximum;
344      //if (e.NewLocationX < axisX.Minimum)
345      //  e.NewLocationX = axisX.Minimum;
346
347      var annotation = VerticalLineAnnotation;
348      var x = annotation.X;
349      sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
350
351      chart.ChartAreas[0].AxisX.Title = FreeVariable + " : " + x.ToString("N3", CultureInfo.CurrentCulture);
352      chart.Update();
353
354      OnVariableValueChanged(this, EventArgs.Empty);
355    }
356
357    private void chart_MouseMove(object sender, MouseEventArgs e) {
358      chart.Cursor = chart.HitTest(e.X, e.Y).ChartElementType == ChartElementType.Annotation ? Cursors.VSplit : Cursors.Default;
359    }
360
361    private void chart_FormatNumber(object sender, FormatNumberEventArgs e) {
362      if (e.ElementType == ChartElementType.AxisLabels) {
363        switch (e.Format) {
364          case "CustomAxisXFormat":
365            break;
366          case "CustomAxisYFormat":
367            var v = e.Value;
368            e.LocalizedValue = string.Format("{0,5}", v);
369            break;
370          default:
371            break;
372        }
373      }
374    }
375
376    private void GradientChart_DragDrop(object sender, DragEventArgs e) {
377      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
378      if (data != null) {
379        var solution = data as IRegressionSolution;
380        if (!Solutions.Contains(solution))
381          AddSolution(solution);
382      }
383    }
384    private void GradientChart_DragEnter(object sender, DragEventArgs e) {
385      if (!e.Data.GetDataPresent(HeuristicLab.Common.Constants.DragDropDataFormat)) return;
386      e.Effect = DragDropEffects.None;
387
388      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
389      var regressionSolution = data as IRegressionSolution;
390      if (regressionSolution != null) {
391        e.Effect = DragDropEffects.Copy;
392      }
393    }
394    #endregion
395  }
396}
Note: See TracBrowser for help on using the repository browser.