source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Regression/RegressionSolutionResidualHistogram.cs @ 8104

Last change on this file since 8104 was 8104, checked in by sforsten, 10 years ago

#1708:

  • Removed ALL_SERIES constant
  • Reordered methods
  • CalculateResiduals returns now all residuals instead of a dictionary
  • reduced number of parameters for methods were possible
File size: 10.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Linq;
26using System.Windows.Forms;
27using System.Windows.Forms.DataVisualization.Charting;
28using HeuristicLab.MainForm;
29using HeuristicLab.MainForm.WindowsForms;
30
31namespace HeuristicLab.Problems.DataAnalysis.Views {
32  [View("Residual Histogram")]
33  [Content(typeof(IRegressionSolution))]
34  public partial class RegressionSolutionResidualHistogram : DataAnalysisSolutionEvaluationView {
35
36    #region variables
37    protected const string ALL_SAMPLES = "All samples";
38    protected const string TRAINING_SAMPLES = "Training samples";
39    protected const string TEST_SAMPLES = "Test samples";
40    /// <summary>
41    /// approximate amount of bins
42    /// </summary>
43    protected const double bins = 25;
44    /// <summary>
45    ///  keeps for all series a list for every bin with the position of the bin, the relative frequency of the
46    ///  residuals and the beginning and the end of the interval of the bin
47    ///  </summary>
48    protected readonly Dictionary<string, List<List<double>>> relativeFrequencies;
49    #endregion
50
51    public new IRegressionSolution Content {
52      get { return (IRegressionSolution)base.Content; }
53      set { base.Content = value; }
54    }
55
56    public RegressionSolutionResidualHistogram()
57      : base() {
58      InitializeComponent();
59      relativeFrequencies = new Dictionary<string, List<List<double>>>();
60      foreach (string series in new List<String>() { ALL_SAMPLES, TRAINING_SAMPLES, TEST_SAMPLES }) {
61        chart.Series.Add(series);
62        chart.Series[series].LegendText = series;
63        chart.Series[series].ChartType = SeriesChartType.Column;
64        chart.Series[series]["PointWidth"] = "0.9";
65        chart.Series[series].BorderWidth = 1;
66        chart.Series[series].BorderDashStyle = ChartDashStyle.Solid;
67        chart.Series[series].BorderColor = Color.Black;
68        chart.Series[series].ToolTip = series + " Y = #VALY from #CUSTOMPROPERTY(from) to #CUSTOMPROPERTY(to)";
69        relativeFrequencies[series] = new List<List<double>>();
70      }
71      //configure axis
72      chart.CustomizeAllChartAreas();
73      chart.ChartAreas[0].AxisX.Title = "Residuals";
74      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
75      chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
76      chart.ChartAreas[0].CursorX.Interval = 1;
77      chart.ChartAreas[0].CursorY.Interval = 1;
78      chart.ChartAreas[0].AxisY.Title = "Relative Frequency";
79      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
80      chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
81      chart.ChartAreas[0].AxisY.IsStartedFromZero = true;
82    }
83
84    private void RedrawChart() {
85      foreach (Series series in chart.Series) {
86        series.Points.Clear();
87        relativeFrequencies[series.Name].Clear();
88      }
89      if (Content != null) {
90        List<double> residuals = CalculateResiduals();
91        double realMax = Math.Max(Math.Abs(residuals.Min()), Math.Abs(residuals.Max()));
92        double roundedMax = HumanRoundMax(realMax);
93        double intervalWidth = (roundedMax * 2.0) / bins;
94        intervalWidth = HumanRoundMax(intervalWidth);
95        // sets roundedMax to a value, so that zero will be in the middle of the x axis
96        double help = realMax / intervalWidth;
97        help = help % 1 < 0.5 ? (int)help : (int)help + 1;
98        roundedMax = help * intervalWidth;
99
100        foreach (Series series in chart.Series) {
101          CalculateFrequencies(residuals, series.Name, roundedMax, intervalWidth);
102          if (!series.Equals(ALL_SAMPLES))
103            ShowValues(series);
104        }
105
106        ChartArea chartArea = chart.ChartAreas[0];
107        chartArea.AxisX.Minimum = -roundedMax - intervalWidth;
108        chartArea.AxisX.Maximum = roundedMax + intervalWidth;
109        // get the highest frequency of a residual of any series
110        chartArea.AxisY.Maximum = (from series in relativeFrequencies.Values
111                                   select (from residual in series
112                                           select residual.ElementAt(1)).Max()).Max();
113        if (chartArea.AxisY.Maximum < 0.1) {
114          chartArea.AxisY.Interval = 0.01;
115          chartArea.AxisY.Maximum = Math.Ceiling(chartArea.AxisY.Maximum * 100) / 100;
116        } else {
117          chartArea.AxisY.Interval = 0.1;
118          chartArea.AxisY.Maximum = Math.Ceiling(chartArea.AxisY.Maximum * 10) / 10;
119        }
120        chartArea.AxisX.Interval = intervalWidth;
121        int curBins = (int)Math.Round((roundedMax * 2) / intervalWidth);
122        //shifts the x axis label so that zero is in the middle
123        if (curBins % 2 == 0)
124          chartArea.AxisX.IntervalOffset = intervalWidth;
125        else
126          chartArea.AxisX.IntervalOffset = intervalWidth / 2;
127      }
128    }
129
130    private List<double> CalculateResiduals() {
131      List<double> residuals = new List<double>();
132
133      IRegressionProblemData problemdata = Content.ProblemData;
134      List<double> targetValues = problemdata.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToList();
135      List<double> estimatedValues = Content.EstimatedValues.ToList();
136
137      for (int i = 0; i < Content.ProblemData.Dataset.Rows; i++) {
138        double residual = estimatedValues[i] - targetValues[i];
139        residuals.Add(residual);
140      }
141      return residuals;
142    }
143
144    private void CalculateFrequencies(List<double> residualValues, string series, double max, double intervalWidth) {
145      IEnumerable<double> relevantResiduals = residualValues;
146      IRegressionProblemData problemdata = Content.ProblemData;
147      if (series.Equals(TRAINING_SAMPLES)) {
148        relevantResiduals = residualValues.Skip(problemdata.TrainingPartition.Start).Take(problemdata.TrainingPartition.Size);
149      } else if (series.Equals(TEST_SAMPLES)) {
150        relevantResiduals = residualValues.Skip(problemdata.TestPartition.Start).Take(problemdata.TestPartition.Size);
151      }
152
153      double intervalCenter = intervalWidth / 2.0;
154      double sampleCount = relevantResiduals.Count();
155      double current = -max;
156
157      for (int i = 0; i <= bins; i++) {
158        IEnumerable<double> help = relevantResiduals.Where(x => x >= (current - intervalCenter) && x < (current + intervalCenter));
159        relativeFrequencies[series].Add(new List<double>() { current, help.Count() / sampleCount, current - intervalCenter, current + intervalCenter });
160        current += intervalWidth;
161      }
162    }
163
164    private void ShowValues(Series series) {
165      List<List<double>> relativeSeriesFrequencies = relativeFrequencies[series.Name];
166      DataPointCollection seriesPoints = series.Points;
167
168      foreach (var valueList in relativeSeriesFrequencies) {
169        seriesPoints.AddXY(valueList[0], valueList[1]);
170        seriesPoints[seriesPoints.Count - 1]["from"] = valueList[2].ToString();
171        seriesPoints[seriesPoints.Count - 1]["to"] = valueList[3].ToString();
172      }
173    }
174
175    private void ToggleSeriesData(Series series) {
176      if (series.Points.Count > 0) {  //checks if series is shown
177        if (chart.Series.Any(s => s != series && s.Points.Count > 0)) {
178          series.Points.Clear();
179        }
180      } else if (Content != null) {
181        ShowValues(series);
182        chart.Legends[series.Legend].ForeColor = Color.Black;
183        chart.Refresh();
184      }
185    }
186
187    private double HumanRoundMax(double max) {
188      double base10;
189      if (max > 0) base10 = Math.Pow(10.0, Math.Floor(Math.Log10(max)));
190      else base10 = Math.Pow(10.0, Math.Ceiling(Math.Log10(-max)));
191      double rounding = (max > 0) ? base10 : -base10;
192      while (rounding < max) rounding += base10;
193      return rounding;
194    }
195
196    #region events
197    protected override void RegisterContentEvents() {
198      base.RegisterContentEvents();
199      Content.ModelChanged += new EventHandler(Content_ModelChanged);
200      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
201    }
202    protected override void DeregisterContentEvents() {
203      base.DeregisterContentEvents();
204      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
205      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
206    }
207
208    protected override void OnContentChanged() {
209      base.OnContentChanged();
210      RedrawChart();
211    }
212    private void Content_ProblemDataChanged(object sender, EventArgs e) {
213      RedrawChart();
214    }
215    private void Content_ModelChanged(object sender, EventArgs e) {
216      RedrawChart();
217    }
218    private void chart_MouseDown(object sender, MouseEventArgs e) {
219      HitTestResult result = chart.HitTest(e.X, e.Y);
220      if (result.ChartElementType == ChartElementType.LegendItem) {
221        ToggleSeriesData(result.Series);
222      }
223    }
224    private void chart_MouseMove(object sender, MouseEventArgs e) {
225      HitTestResult result = chart.HitTest(e.X, e.Y);
226      if (result.ChartElementType == ChartElementType.LegendItem)
227        Cursor = Cursors.Hand;
228      else
229        Cursor = Cursors.Default;
230    }
231    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
232      if (chart.Series.Count != 3) return;
233      e.LegendItems[0].Cells[1].ForeColor = chart.Series[ALL_SAMPLES].Points.Count == 0 ? Color.Gray : Color.Black;
234      e.LegendItems[1].Cells[1].ForeColor = chart.Series[TRAINING_SAMPLES].Points.Count == 0 ? Color.Gray : Color.Black;
235      e.LegendItems[2].Cells[1].ForeColor = chart.Series[TEST_SAMPLES].Points.Count == 0 ? Color.Gray : Color.Black;
236    }
237    #endregion
238  }
239}
Note: See TracBrowser for help on using the repository browser.