Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.DataAnalysis.Views/3.4/Classification/DiscriminantFunctionClassificationSolutionThresholdView.cs @ 8468

Last change on this file since 8468 was 8430, checked in by mkommend, 12 years ago

#1081: Intermediate commit of trunk updates - interpreter changes must be redone.

File size: 11.1 KB
RevLine 
[4417]1#region License Information
2/* HeuristicLab
[7268]3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[4417]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.Common;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31
[5829]32namespace HeuristicLab.Problems.DataAnalysis.Views {
[5975]33  [View("Classification Threshold")]
[6729]34  [Content(typeof(IDiscriminantFunctionClassificationSolution), false)]
[6642]35  public sealed partial class DiscriminantFunctionClassificationSolutionThresholdView : DataAnalysisSolutionEvaluationView {
[4417]36    private const double TrainingAxisValue = 0.0;
37    private const double TestAxisValue = 10.0;
38    private const double TrainingTestBorder = (TestAxisValue - TrainingAxisValue) / 2;
39    private const string TrainingLabelText = "Training Samples";
40    private const string TestLabelText = "Test Samples";
41
[5664]42    public new IDiscriminantFunctionClassificationSolution Content {
43      get { return (IDiscriminantFunctionClassificationSolution)base.Content; }
[4417]44      set { base.Content = value; }
45    }
46
47    private Dictionary<double, Series> classValueSeriesMapping;
48    private Random random;
49    private bool updateInProgress;
50
[5829]51    public DiscriminantFunctionClassificationSolutionThresholdView()
[4417]52      : base() {
53      InitializeComponent();
54
55      classValueSeriesMapping = new Dictionary<double, Series>();
56      random = new Random();
57      updateInProgress = false;
58
[4651]59      this.chart.CustomizeAllChartAreas();
[4417]60      this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
61      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
62      this.chart.ChartAreas[0].AxisX.Minimum = TrainingAxisValue - TrainingTestBorder;
63      this.chart.ChartAreas[0].AxisX.Maximum = TestAxisValue + TrainingTestBorder;
64      AddCustomLabelToAxis(this.chart.ChartAreas[0].AxisX);
65
66      this.chart.ChartAreas[0].AxisY.Title = "Estimated Values";
67      this.chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
68      this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
69    }
70
71    private void AddCustomLabelToAxis(Axis axis) {
72      CustomLabel trainingLabel = new CustomLabel();
73      trainingLabel.Text = TrainingLabelText;
74      trainingLabel.FromPosition = TrainingAxisValue - TrainingTestBorder;
75      trainingLabel.ToPosition = TrainingAxisValue + TrainingTestBorder;
76      axis.CustomLabels.Add(trainingLabel);
77
78      CustomLabel testLabel = new CustomLabel();
79      testLabel.Text = TestLabelText;
80      testLabel.FromPosition = TestAxisValue - TrainingTestBorder;
81      testLabel.ToPosition = TestAxisValue + TrainingTestBorder;
82      axis.CustomLabels.Add(testLabel);
83    }
84
85    protected override void RegisterContentEvents() {
86      base.RegisterContentEvents();
[5664]87      Content.ModelChanged += new EventHandler(Content_ModelChanged);
[4417]88      Content.ProblemDataChanged += new EventHandler(Content_ProblemDataChanged);
89    }
90    protected override void DeregisterContentEvents() {
91      base.DeregisterContentEvents();
[5664]92      Content.ModelChanged -= new EventHandler(Content_ModelChanged);
[4417]93      Content.ProblemDataChanged -= new EventHandler(Content_ProblemDataChanged);
94    }
95
96    private void Content_ProblemDataChanged(object sender, EventArgs e) {
97      UpdateChart();
98    }
[5664]99    private void Content_ModelChanged(object sender, EventArgs e) {
[5736]100      Content.Model.ThresholdsChanged += new EventHandler(Model_ThresholdsChanged);
[4417]101      UpdateChart();
102    }
[5736]103    private void Model_ThresholdsChanged(object sender, EventArgs e) {
[4417]104      AddThresholds();
105    }
106    protected override void OnContentChanged() {
107      base.OnContentChanged();
108      UpdateChart();
109    }
110
111    private void UpdateChart() {
112      if (InvokeRequired) Invoke((Action)UpdateChart);
113      else if (!updateInProgress) {
114        updateInProgress = true;
115        chart.Series.Clear();
116        classValueSeriesMapping.Clear();
117        if (Content != null) {
118          IEnumerator<string> classNameEnumerator = Content.ProblemData.ClassNames.GetEnumerator();
[5664]119          IEnumerator<double> classValueEnumerator = Content.ProblemData.ClassValues.OrderBy(x => x).GetEnumerator();
[4417]120          while (classNameEnumerator.MoveNext() && classValueEnumerator.MoveNext()) {
121            Series series = new Series(classNameEnumerator.Current);
122            series.ChartType = SeriesChartType.FastPoint;
123            series.Tag = classValueEnumerator.Current;
124            chart.Series.Add(series);
125            classValueSeriesMapping.Add(classValueEnumerator.Current, series);
126            FillSeriesWithDataPoints(series);
127          }
128          AddThresholds();
129        }
130        chart.ChartAreas[0].RecalculateAxesScale();
131        updateInProgress = false;
132      }
133    }
134
135    private void FillSeriesWithDataPoints(Series series) {
[4469]136      List<double> estimatedValues = Content.EstimatedValues.ToList();
[6740]137      var targetValues = Content.ProblemData.Dataset.GetDoubleValues(Content.ProblemData.TargetVariable).ToList();
138
[8430]139      foreach (int row in Content.ProblemData.TrainingIndices) {
[4469]140        double estimatedValue = estimatedValues[row];
[6740]141        double targetValue = targetValues[row];
[4469]142        if (targetValue.IsAlmost((double)series.Tag)) {
[4417]143          double jitterValue = random.NextDouble() * 2.0 - 1.0;
144          DataPoint point = new DataPoint();
145          point.XValue = TrainingAxisValue + 0.01 * jitterValue * JitterTrackBar.Value * (TrainingTestBorder * 0.9);
146          point.YValues[0] = estimatedValue;
147          point.Tag = new KeyValuePair<double, double>(TrainingAxisValue, jitterValue);
148          series.Points.Add(point);
149        }
150      }
151
[8430]152      foreach (int row in Content.ProblemData.TestIndices) {
[4469]153        double estimatedValue = estimatedValues[row];
[6740]154        double targetValue = targetValues[row];
155        if (targetValue.IsAlmost((double)series.Tag)) {
[4417]156          double jitterValue = random.NextDouble() * 2.0 - 1.0;
157          DataPoint point = new DataPoint();
158          point.XValue = TestAxisValue + 0.01 * jitterValue * JitterTrackBar.Value * (TrainingTestBorder * 0.9);
159          point.YValues[0] = estimatedValue;
160          point.Tag = new KeyValuePair<double, double>(TestAxisValue, jitterValue);
161          series.Points.Add(point);
162        }
163      }
[4469]164
[4417]165      UpdateCursorInterval();
166    }
167
168    private void AddThresholds() {
169      chart.Annotations.Clear();
170      int classIndex = 1;
[5717]171      foreach (double threshold in Content.Model.Thresholds) {
[4417]172        if (!double.IsInfinity(threshold)) {
173          HorizontalLineAnnotation annotation = new HorizontalLineAnnotation();
174          annotation.AllowMoving = true;
175          annotation.AllowResizing = false;
176          annotation.LineWidth = 2;
177          annotation.LineColor = Color.Red;
178
179          annotation.IsInfinitive = true;
180          annotation.ClipToChartArea = chart.ChartAreas[0].Name;
181          annotation.Tag = classIndex;  //save classIndex as Tag to avoid moving the threshold accross class bounderies
182
183          annotation.AxisX = chart.ChartAreas[0].AxisX;
184          annotation.AxisY = chart.ChartAreas[0].AxisY;
185          annotation.Y = threshold;
186
187          chart.Annotations.Add(annotation);
188          classIndex++;
189        }
190      }
191    }
192
193    private void JitterTrackBar_ValueChanged(object sender, EventArgs e) {
194      foreach (Series series in chart.Series) {
195        foreach (DataPoint point in series.Points) {
196          double value = ((KeyValuePair<double, double>)point.Tag).Key;
197          double jitterValue = ((KeyValuePair<double, double>)point.Tag).Value; ;
198          point.XValue = value + 0.01 * jitterValue * JitterTrackBar.Value * (TrainingTestBorder * 0.9);
199        }
200      }
201    }
202
203    private void chart_CustomizeLegend(object sender, CustomizeLegendEventArgs e) {
204      foreach (LegendItem legendItem in e.LegendItems) {
205        var series = chart.Series[legendItem.SeriesName];
206        if (series != null) {
207          bool seriesIsInvisible = series.Points.Count == 0;
208          foreach (LegendCell cell in legendItem.Cells)
209            cell.ForeColor = seriesIsInvisible ? Color.Gray : Color.Black;
210        }
211      }
212    }
213
214    private void chart_MouseMove(object sender, MouseEventArgs e) {
215      HitTestResult result = chart.HitTest(e.X, e.Y);
216      if (result.ChartElementType == ChartElementType.LegendItem)
217        this.Cursor = Cursors.Hand;
218      else
219        this.Cursor = Cursors.Default;
220    }
221
222    private void ToggleSeries(Series series) {
223      if (series.Points.Count == 0)
224        FillSeriesWithDataPoints(series);
225      else
226        series.Points.Clear();
227    }
228
229    private void chart_MouseDown(object sender, MouseEventArgs e) {
230      HitTestResult result = chart.HitTest(e.X, e.Y);
231      if (result.ChartElementType == ChartElementType.LegendItem) {
232        if (result.Series != null) ToggleSeries(result.Series);
233      }
234    }
235
236    private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
237      int classIndex = (int)e.Annotation.Tag;
[5717]238      double[] thresholds = Content.Model.Thresholds.ToArray();
[4417]239      thresholds[classIndex] = e.NewLocationY;
[5736]240      Content.Model.SetThresholdsAndClassValues(thresholds, Content.Model.ClassValues);
[4417]241    }
242
243    private void UpdateCursorInterval() {
244      Series series = chart.Series[0];
245      double[] xValues = (from point in series.Points
246                          where !point.IsEmpty
247                          select point.XValue)
248                    .DefaultIfEmpty(1.0)
249                    .ToArray();
250      double[] yValues = (from point in series.Points
251                          where !point.IsEmpty
252                          select point.YValues[0])
253                    .DefaultIfEmpty(1.0)
254                    .ToArray();
255
256      double xRange = xValues.Max() - xValues.Min();
257      double yRange = yValues.Max() - yValues.Min();
258      if (xRange.IsAlmost(0.0)) xRange = 1.0;
259      if (yRange.IsAlmost(0.0)) yRange = 1.0;
260      double xDigits = (int)Math.Log10(xRange) - 3;
261      double yDigits = (int)Math.Log10(yRange) - 3;
262      double xZoomInterval = Math.Pow(10, xDigits);
263      double yZoomInterval = Math.Pow(10, yDigits);
264      this.chart.ChartAreas[0].CursorX.Interval = xZoomInterval;
265      this.chart.ChartAreas[0].CursorY.Interval = yZoomInterval;
266    }
267  }
268}
Note: See TracBrowser for help on using the repository browser.