Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/PartialDependencePlot.cs @ 15428

Last change on this file since 15428 was 14852, checked in by gkronber, 8 years ago

#2670 renamed TargetResponseCurve and GradientChart -> PartialDependencePlot

File size: 27.2 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;
24using System.Collections.Generic;
25using System.Drawing;
26using System.Globalization;
27using System.Linq;
28using System.Threading;
29using System.Threading.Tasks;
30using System.Windows.Forms;
31using System.Windows.Forms.DataVisualization.Charting;
32using HeuristicLab.Common;
33using HeuristicLab.MainForm.WindowsForms;
34using HeuristicLab.Visualization.ChartControlsExtensions;
35
36namespace HeuristicLab.Problems.DataAnalysis.Views {
37  public partial class PartialDependencePlot : UserControl, IPartialDependencePlot {
38    private ModifiableDataset sharedFixedVariables; // used for syncronising variable values between charts
39    private ModifiableDataset internalDataset; // holds the x values for each point drawn
40
41    private CancellationTokenSource cancelCurrentRecalculateSource;
42
43    private readonly List<IRegressionSolution> solutions;
44    private readonly Dictionary<IRegressionSolution, Series> seriesCache;
45    private readonly Dictionary<IRegressionSolution, Series> ciSeriesCache;
46
47    private readonly ToolStripMenuItem configToolStripMenuItem;
48    private readonly PartialDependencePlotConfigurationDialog configurationDialog;
49
50    #region Properties
51    public string XAxisTitle {
52      get { return chart.ChartAreas[0].AxisX.Title; }
53      set { chart.ChartAreas[0].AxisX.Title = value; }
54    }
55
56    public string YAxisTitle {
57      get { return chart.ChartAreas[0].AxisY.Title; }
58      set { chart.ChartAreas[0].AxisY.Title = value; }
59    }
60
61    public bool ShowLegend {
62      get { return chart.Legends[0].Enabled; }
63      set { chart.Legends[0].Enabled = value; }
64    }
65    public bool ShowCursor {
66      get { return chart.Annotations[0].Visible; }
67      set {
68        chart.Annotations[0].Visible = value;
69        if (!value) chart.Titles[0].Text = string.Empty;
70      }
71    }
72
73    public bool ShowConfigButton {
74      get { return configurationButton.Visible; }
75      set { configurationButton.Visible = value; }
76    }
77
78    private int xAxisTicks = 5;
79    public int XAxisTicks {
80      get { return xAxisTicks; }
81      set {
82        if (value != xAxisTicks) {
83          xAxisTicks = value;
84          SetupAxis(chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
85          RecalculateInternalDataset();
86        }
87      }
88    }
89    private double? fixedXAxisMin;
90    public double? FixedXAxisMin {
91      get { return fixedXAxisMin; }
92      set {
93        if ((value.HasValue && fixedXAxisMin.HasValue && !value.Value.IsAlmost(fixedXAxisMin.Value)) || (value.HasValue != fixedXAxisMin.HasValue)) {
94          fixedXAxisMin = value;
95          if (trainingMin < trainingMax) {
96            SetupAxis(chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
97            RecalculateInternalDataset();
98            // set the vertical line position
99            if (VerticalLineAnnotation.X <= fixedXAxisMin) {
100              var axisX = chart.ChartAreas[0].AxisX;
101              var step = (axisX.Maximum - axisX.Minimum) / drawingSteps;
102              VerticalLineAnnotation.X = axisX.Minimum + step;
103            }
104          }
105        }
106      }
107    }
108    private double? fixedXAxisMax;
109    public double? FixedXAxisMax {
110      get { return fixedXAxisMax; }
111      set {
112        if ((value.HasValue && fixedXAxisMax.HasValue && !value.Value.IsAlmost(fixedXAxisMax.Value)) || (value.HasValue != fixedXAxisMax.HasValue)) {
113          fixedXAxisMax = value;
114          if (trainingMin < trainingMax) {
115            SetupAxis(chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
116            RecalculateInternalDataset();
117            // set the vertical line position
118            if (VerticalLineAnnotation.X >= fixedXAxisMax) {
119              var axisX = chart.ChartAreas[0].AxisX;
120              var step = (axisX.Maximum - axisX.Minimum) / drawingSteps;
121              VerticalLineAnnotation.X = axisX.Maximum - step;
122            }
123          }
124        }
125      }
126    }
127
128    private int yAxisTicks = 5;
129    public int YAxisTicks {
130      get { return yAxisTicks; }
131      set {
132        if (value != yAxisTicks) {
133          yAxisTicks = value;
134          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
135          RecalculateInternalDataset();
136        }
137      }
138    }
139    private double? fixedYAxisMin;
140    public double? FixedYAxisMin {
141      get { return fixedYAxisMin; }
142      set {
143        if ((value.HasValue && fixedYAxisMin.HasValue && !value.Value.IsAlmost(fixedYAxisMin.Value)) || (value.HasValue != fixedYAxisMin.HasValue)) {
144          fixedYAxisMin = value;
145          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
146        }
147      }
148    }
149    private double? fixedYAxisMax;
150    public double? FixedYAxisMax {
151      get { return fixedYAxisMax; }
152      set {
153        if ((value.HasValue && fixedYAxisMax.HasValue && !value.Value.IsAlmost(fixedYAxisMax.Value)) || (value.HasValue != fixedYAxisMax.HasValue)) {
154          fixedYAxisMax = value;
155          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
156        }
157      }
158    }
159
160    private double trainingMin = 1;
161    private double trainingMax = -1;
162
163    private int drawingSteps = 1000;
164    public int DrawingSteps {
165      get { return drawingSteps; }
166      set {
167        if (value != drawingSteps) {
168          drawingSteps = value;
169          RecalculateInternalDataset();
170          ResizeAllSeriesData();
171        }
172      }
173    }
174
175    private string freeVariable;
176    public string FreeVariable {
177      get { return freeVariable; }
178      set {
179        if (value == freeVariable) return;
180        if (solutions.Any(s => !s.ProblemData.Dataset.DoubleVariables.Contains(value))) {
181          throw new ArgumentException("Variable does not exist in the ProblemData of the Solutions.");
182        }
183        freeVariable = value;
184        RecalculateInternalDataset();
185      }
186    }
187
188    private double yMin;
189    public double YMin {
190      get { return yMin; }
191    }
192    private double yMax;
193    public double YMax {
194      get { return yMax; }
195    }
196
197    public bool IsZoomed {
198      get { return chart.ChartAreas[0].AxisX.ScaleView.IsZoomed; }
199    }
200
201    private VerticalLineAnnotation VerticalLineAnnotation {
202      get { return (VerticalLineAnnotation)chart.Annotations.SingleOrDefault(x => x is VerticalLineAnnotation); }
203    }
204
205    internal ElementPosition InnerPlotPosition {
206      get { return chart.ChartAreas[0].InnerPlotPosition; }
207    }
208    #endregion
209
210    public event EventHandler ChartPostPaint;
211
212    public PartialDependencePlot() {
213      InitializeComponent();
214
215      solutions = new List<IRegressionSolution>();
216      seriesCache = new Dictionary<IRegressionSolution, Series>();
217      ciSeriesCache = new Dictionary<IRegressionSolution, Series>();
218
219      // Configure axis
220      chart.CustomizeAllChartAreas();
221      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
222      chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
223      chart.ChartAreas[0].CursorX.Interval = 0;
224
225      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = true;
226      chart.ChartAreas[0].AxisY.ScaleView.Zoomable = true;
227      chart.ChartAreas[0].CursorY.Interval = 0;
228
229      configToolStripMenuItem = new ToolStripMenuItem("Configuration");
230      configToolStripMenuItem.Click += config_Click;
231      chart.ContextMenuStrip.Items.Add(new ToolStripSeparator());
232      chart.ContextMenuStrip.Items.Add(configToolStripMenuItem);
233      configurationDialog = new PartialDependencePlotConfigurationDialog(this);
234
235      Disposed += Control_Disposed;
236    }
237
238    private void Control_Disposed(object sender, EventArgs e) {
239      if (cancelCurrentRecalculateSource != null)
240        cancelCurrentRecalculateSource.Cancel();
241    }
242
243    public void Configure(IEnumerable<IRegressionSolution> solutions, ModifiableDataset sharedFixedVariables, string freeVariable, int drawingSteps, bool initializeAxisRanges = true) {
244      if (!SolutionsCompatible(solutions))
245        throw new ArgumentException("Solutions are not compatible with the problem data.");
246      this.freeVariable = freeVariable;
247      this.drawingSteps = drawingSteps;
248
249      this.solutions.Clear();
250      this.solutions.AddRange(solutions);
251
252      // add an event such that whenever a value is changed in the shared dataset,
253      // this change is reflected in the internal dataset (where the value becomes a whole column)
254      if (this.sharedFixedVariables != null)
255        this.sharedFixedVariables.ItemChanged -= sharedFixedVariables_ItemChanged;
256      this.sharedFixedVariables = sharedFixedVariables;
257      this.sharedFixedVariables.ItemChanged += sharedFixedVariables_ItemChanged;
258
259      RecalculateTrainingLimits(initializeAxisRanges);
260      RecalculateInternalDataset();
261
262      chart.Series.Clear();
263      seriesCache.Clear();
264      ciSeriesCache.Clear();
265      foreach (var solution in this.solutions) {
266        var series = CreateSeries(solution);
267        seriesCache.Add(solution, series.Item1);
268        if (series.Item2 != null)
269          ciSeriesCache.Add(solution, series.Item2);
270      }
271
272      // Set cursor and x-axis
273      // Make sure to allow a small offset to be able to distinguish the vertical line annotation from the axis
274      var defaultValue = sharedFixedVariables.GetDoubleValue(freeVariable, 0);
275      var step = (trainingMax - trainingMin) / drawingSteps;
276      var minimum = chart.ChartAreas[0].AxisX.Minimum;
277      var maximum = chart.ChartAreas[0].AxisX.Maximum;
278      if (defaultValue <= minimum)
279        VerticalLineAnnotation.X = minimum + step;
280      else if (defaultValue >= maximum)
281        VerticalLineAnnotation.X = maximum - step;
282      else
283        VerticalLineAnnotation.X = defaultValue;
284
285      if (ShowCursor)
286        chart.Titles[0].Text = FreeVariable + " : " + defaultValue.ToString("G5", CultureInfo.CurrentCulture);
287
288      ResizeAllSeriesData();
289      OrderAndColorSeries();
290    }
291
292    public async Task RecalculateAsync(bool updateOnFinish = true, bool resetYAxis = true) {
293      if (IsDisposed
294        || sharedFixedVariables == null || !solutions.Any() || string.IsNullOrEmpty(freeVariable)
295        || trainingMin.IsAlmost(trainingMax) || trainingMin > trainingMax || drawingSteps == 0)
296        return;
297
298      calculationPendingTimer.Start();
299
300      // cancel previous recalculate call
301      if (cancelCurrentRecalculateSource != null)
302        cancelCurrentRecalculateSource.Cancel();
303      cancelCurrentRecalculateSource = new CancellationTokenSource();
304      var cancellationToken = cancelCurrentRecalculateSource.Token;
305
306      // Update series
307      try {
308        var limits = await UpdateAllSeriesDataAsync(cancellationToken);
309
310        yMin = limits.Lower;
311        yMax = limits.Upper;
312        // Set y-axis
313        if (resetYAxis)
314          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
315
316        UpdateOutOfTrainingRangeStripLines();
317
318        calculationPendingTimer.Stop();
319        calculationPendingLabel.Visible = false;
320        if (updateOnFinish)
321          Update();
322      } catch (OperationCanceledException) { } catch (AggregateException ae) {
323        if (!ae.InnerExceptions.Any(e => e is OperationCanceledException))
324          throw;
325      }
326    }
327
328    public void UpdateTitlePosition() {
329      var title = chart.Titles[0];
330      var plotArea = InnerPlotPosition;
331
332      title.Visible = plotArea.Width != 0;
333
334      title.Position.X = plotArea.X + (plotArea.Width / 2);
335    }
336
337    private void SetupAxis(Axis axis, double minValue, double maxValue, int ticks, double? fixedAxisMin, double? fixedAxisMax) {
338      if (minValue < maxValue) {
339        double axisMin, axisMax, axisInterval;
340        ChartUtil.CalculateAxisInterval(minValue, maxValue, ticks, out axisMin, out axisMax, out axisInterval);
341        axis.Minimum = fixedAxisMin ?? axisMin;
342        axis.Maximum = fixedAxisMax ?? axisMax;
343        axis.Interval = (axis.Maximum - axis.Minimum) / ticks;
344      }
345
346      try {
347        chart.ChartAreas[0].RecalculateAxesScale();
348      } catch (InvalidOperationException) {
349        // Can occur if eg. axis min == axis max
350      }
351    }
352
353    private void RecalculateTrainingLimits(bool initializeAxisRanges) {
354      trainingMin = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Min()).Max();
355      trainingMax = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Max()).Min();
356
357      if (initializeAxisRanges) {
358        double xmin, xmax, xinterval;
359        ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
360        FixedXAxisMin = xmin;
361        FixedXAxisMax = xmax;
362      }
363    }
364
365    private void RecalculateInternalDataset() {
366      if (sharedFixedVariables == null)
367        return;
368
369      // we expand the range in order to get nice tick intervals on the x axis
370      double xmin, xmax, xinterval;
371      ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
372
373      if (FixedXAxisMin.HasValue) xmin = FixedXAxisMin.Value;
374      if (FixedXAxisMax.HasValue) xmax = FixedXAxisMax.Value;
375      double step = (xmax - xmin) / drawingSteps;
376
377      var xvalues = new List<double>();
378      for (int i = 0; i < drawingSteps; i++)
379        xvalues.Add(xmin + i * step);
380
381      if (sharedFixedVariables == null)
382        return;
383
384      var variables = sharedFixedVariables.VariableNames.ToList();
385      var values = new List<IList>();
386      foreach (var varName in variables) {
387        if (varName == FreeVariable) {
388          values.Add(xvalues);
389        } else if (sharedFixedVariables.VariableHasType<double>(varName)) {
390          values.Add(Enumerable.Repeat(sharedFixedVariables.GetDoubleValue(varName, 0), xvalues.Count).ToList());
391        } else if (sharedFixedVariables.VariableHasType<string>(varName)) {
392          values.Add(Enumerable.Repeat(sharedFixedVariables.GetStringValue(varName, 0), xvalues.Count).ToList());
393        }
394      }
395
396      internalDataset = new ModifiableDataset(variables, values);
397    }
398
399    private Tuple<Series, Series> CreateSeries(IRegressionSolution solution) {
400      var series = new Series {
401        ChartType = SeriesChartType.Line,
402        Name = solution.ProblemData.TargetVariable + " " + solutions.IndexOf(solution)
403      };
404      series.LegendText = series.Name;
405
406      var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
407      Series confidenceIntervalSeries = null;
408      if (confidenceBoundSolution != null) {
409        confidenceIntervalSeries = new Series {
410          ChartType = SeriesChartType.Range,
411          YValuesPerPoint = 2,
412          Name = "95% Conf. Interval " + series.Name,
413          IsVisibleInLegend = false
414        };
415      }
416      return Tuple.Create(series, confidenceIntervalSeries);
417    }
418
419    private void OrderAndColorSeries() {
420      chart.SuspendRepaint();
421
422      chart.Series.Clear();
423      // Add mean series for applying palette colors
424      foreach (var solution in solutions) {
425        chart.Series.Add(seriesCache[solution]);
426      }
427
428      chart.Palette = ChartColorPalette.BrightPastel;
429      chart.ApplyPaletteColors();
430      chart.Palette = ChartColorPalette.None;
431
432      // Add confidence interval series before its coresponding series for correct z index
433      foreach (var solution in solutions) {
434        Series ciSeries;
435        if (ciSeriesCache.TryGetValue(solution, out ciSeries)) {
436          var series = seriesCache[solution];
437          ciSeries.Color = Color.FromArgb(40, series.Color);
438          int idx = chart.Series.IndexOf(seriesCache[solution]);
439          chart.Series.Insert(idx, ciSeries);
440        }
441      }
442
443      chart.ResumeRepaint(true);
444    }
445
446    private async Task<DoubleLimit> UpdateAllSeriesDataAsync(CancellationToken cancellationToken) {
447      var updateTasks = solutions.Select(solution => UpdateSeriesDataAsync(solution, cancellationToken));
448
449      double min = double.MaxValue, max = double.MinValue;
450      foreach (var update in updateTasks) {
451        var limit = await update;
452        if (limit.Lower < min) min = limit.Lower;
453        if (limit.Upper > max) max = limit.Upper;
454      }
455
456      return new DoubleLimit(min, max);
457    }
458
459    private Task<DoubleLimit> UpdateSeriesDataAsync(IRegressionSolution solution, CancellationToken cancellationToken) {
460      return Task.Run(() => {
461        var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
462        var yvalues = solution.Model.GetEstimatedValues(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
463
464        double min = double.MaxValue, max = double.MinValue;
465
466        var series = seriesCache[solution];
467        for (int i = 0; i < xvalues.Count; i++) {
468          series.Points[i].SetValueXY(xvalues[i], yvalues[i]);
469          if (yvalues[i] < min) min = yvalues[i];
470          if (yvalues[i] > max) max = yvalues[i];
471        }
472        chart.Invalidate();
473
474        cancellationToken.ThrowIfCancellationRequested();
475
476        var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
477        if (confidenceBoundSolution != null) {
478          var confidenceIntervalSeries = ciSeriesCache[solution];
479          var variances = confidenceBoundSolution.Model.GetEstimatedVariances(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
480          for (int i = 0; i < xvalues.Count; i++) {
481            var lower = yvalues[i] - 1.96 * Math.Sqrt(variances[i]);
482            var upper = yvalues[i] + 1.96 * Math.Sqrt(variances[i]);
483            confidenceIntervalSeries.Points[i].SetValueXY(xvalues[i], lower, upper);
484            if (lower < min) min = lower;
485            if (upper > max) max = upper;
486          }
487          chart.Invalidate();
488        }
489
490        cancellationToken.ThrowIfCancellationRequested();
491        return new DoubleLimit(min, max);
492      }, cancellationToken);
493    }
494
495    private void ResizeAllSeriesData() {
496      if (internalDataset == null)
497        return;
498
499      var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
500      foreach (var solution in solutions)
501        ResizeSeriesData(solution, xvalues);
502    }
503    private void ResizeSeriesData(IRegressionSolution solution, IList<double> xvalues = null) {
504      if (xvalues == null)
505        xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
506
507      var series = seriesCache[solution];
508      series.Points.SuspendUpdates();
509      series.Points.Clear();
510      for (int i = 0; i < xvalues.Count; i++)
511        series.Points.Add(new DataPoint(xvalues[i], 0.0));
512      series.Points.ResumeUpdates();
513
514      Series confidenceIntervalSeries;
515      if (ciSeriesCache.TryGetValue(solution, out confidenceIntervalSeries)) {
516        confidenceIntervalSeries.Points.SuspendUpdates();
517        confidenceIntervalSeries.Points.Clear();
518        for (int i = 0; i < xvalues.Count; i++)
519          confidenceIntervalSeries.Points.Add(new DataPoint(xvalues[i], new[] { -1.0, 1.0 }));
520        confidenceIntervalSeries.Points.ResumeUpdates();
521      }
522    }
523
524    public async Task AddSolutionAsync(IRegressionSolution solution) {
525      if (!SolutionsCompatible(solutions.Concat(new[] { solution })))
526        throw new ArgumentException("The solution is not compatible with the problem data.");
527      if (solutions.Contains(solution))
528        return;
529
530      solutions.Add(solution);
531      RecalculateTrainingLimits(true);
532
533      var series = CreateSeries(solution);
534      seriesCache.Add(solution, series.Item1);
535      if (series.Item2 != null)
536        ciSeriesCache.Add(solution, series.Item2);
537
538      ResizeSeriesData(solution);
539      OrderAndColorSeries();
540
541      await RecalculateAsync();
542      var args = new EventArgs<IRegressionSolution>(solution);
543      OnSolutionAdded(this, args);
544    }
545
546    public async Task RemoveSolutionAsync(IRegressionSolution solution) {
547      if (!solutions.Remove(solution))
548        return;
549
550      RecalculateTrainingLimits(true);
551
552      seriesCache.Remove(solution);
553      ciSeriesCache.Remove(solution);
554
555      await RecalculateAsync();
556      var args = new EventArgs<IRegressionSolution>(solution);
557      OnSolutionRemoved(this, args);
558    }
559
560    private static bool SolutionsCompatible(IEnumerable<IRegressionSolution> solutions) {
561      var refSolution = solutions.First();
562      var refSolVars = refSolution.ProblemData.Dataset.VariableNames;
563      foreach (var solution in solutions.Skip(1)) {
564        var variables1 = solution.ProblemData.Dataset.VariableNames;
565        if (!variables1.All(refSolVars.Contains))
566          return false;
567
568        foreach (var factorVar in variables1.Where(solution.ProblemData.Dataset.VariableHasType<string>)) {
569          var distinctVals = refSolution.ProblemData.Dataset.GetStringValues(factorVar).Distinct();
570          if (solution.ProblemData.Dataset.GetStringValues(factorVar).Any(val => !distinctVals.Contains(val))) return false;
571        }
572      }
573      return true;
574    }
575
576    private void UpdateOutOfTrainingRangeStripLines() {
577      var axisX = chart.ChartAreas[0].AxisX;
578      var lowerStripLine = axisX.StripLines[0];
579      var upperStripLine = axisX.StripLines[1];
580
581      lowerStripLine.IntervalOffset = axisX.Minimum;
582      lowerStripLine.StripWidth = Math.Abs(trainingMin - axisX.Minimum);
583
584      upperStripLine.IntervalOffset = trainingMax;
585      upperStripLine.StripWidth = Math.Abs(axisX.Maximum - trainingMax);
586    }
587
588    #region Events
589    public event EventHandler<EventArgs<IRegressionSolution>> SolutionAdded;
590    public void OnSolutionAdded(object sender, EventArgs<IRegressionSolution> args) {
591      var added = SolutionAdded;
592      if (added == null) return;
593      added(sender, args);
594    }
595
596    public event EventHandler<EventArgs<IRegressionSolution>> SolutionRemoved;
597    public void OnSolutionRemoved(object sender, EventArgs<IRegressionSolution> args) {
598      var removed = SolutionRemoved;
599      if (removed == null) return;
600      removed(sender, args);
601    }
602
603    public event EventHandler VariableValueChanged;
604    public void OnVariableValueChanged(object sender, EventArgs args) {
605      var changed = VariableValueChanged;
606      if (changed == null) return;
607      changed(sender, args);
608    }
609
610    public event EventHandler ZoomChanged;
611    public void OnZoomChanged(object sender, EventArgs args) {
612      var changed = ZoomChanged;
613      if (changed == null) return;
614      changed(sender, args);
615    }
616
617    private void sharedFixedVariables_ItemChanged(object o, EventArgs<int, int> e) {
618      if (o != sharedFixedVariables) return;
619      var variables = sharedFixedVariables.VariableNames.ToList();
620      var rowIndex = e.Value;
621      var columnIndex = e.Value2;
622
623      var variableName = variables[columnIndex];
624      if (variableName == FreeVariable) return;
625      if (internalDataset.VariableHasType<double>(variableName)) {
626        var v = sharedFixedVariables.GetDoubleValue(variableName, rowIndex);
627        var values = new List<double>(Enumerable.Repeat(v, internalDataset.Rows));
628        internalDataset.ReplaceVariable(variableName, values);
629      } else if (internalDataset.VariableHasType<string>(variableName)) {
630        var v = sharedFixedVariables.GetStringValue(variableName, rowIndex);
631        var values = new List<String>(Enumerable.Repeat(v, internalDataset.Rows));
632        internalDataset.ReplaceVariable(variableName, values);
633      } else {
634        // unsupported type
635        throw new NotSupportedException();
636      }
637    }
638
639    private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
640      var step = (trainingMax - trainingMin) / drawingSteps;
641      double newLocation = step * (long)Math.Round(e.NewLocationX / step);
642      var axisX = chart.ChartAreas[0].AxisX;
643      if (newLocation >= axisX.Maximum)
644        newLocation = axisX.Maximum - step;
645      if (newLocation <= axisX.Minimum)
646        newLocation = axisX.Minimum + step;
647
648      e.NewLocationX = newLocation;
649
650      UpdateCursor();
651    }
652    private void chart_AnnotationPositionChanged(object sender, EventArgs e) {
653      UpdateCursor();
654    }
655    private void UpdateCursor() {
656      var x = VerticalLineAnnotation.X;
657      sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
658
659      if (ShowCursor) {
660        chart.Titles[0].Text = FreeVariable + " : " + x.ToString("G5", CultureInfo.CurrentCulture);
661        chart.Update();
662      }
663
664      OnVariableValueChanged(this, EventArgs.Empty);
665    }
666
667    private void chart_MouseMove(object sender, MouseEventArgs e) {
668      bool hitCursor = chart.HitTest(e.X, e.Y).ChartElementType == ChartElementType.Annotation;
669      chart.Cursor = hitCursor ? Cursors.VSplit : Cursors.Default;
670    }
671
672    private async void chart_DragDrop(object sender, DragEventArgs e) {
673      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
674      if (data != null) {
675        var solution = data as IRegressionSolution;
676        if (!solutions.Contains(solution))
677          await AddSolutionAsync(solution);
678      }
679    }
680    private void chart_DragEnter(object sender, DragEventArgs e) {
681      if (!e.Data.GetDataPresent(HeuristicLab.Common.Constants.DragDropDataFormat)) return;
682      e.Effect = DragDropEffects.None;
683
684      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
685      var regressionSolution = data as IRegressionSolution;
686      if (regressionSolution != null) {
687        e.Effect = DragDropEffects.Copy;
688      }
689    }
690
691    private void calculationPendingTimer_Tick(object sender, EventArgs e) {
692      calculationPendingLabel.Visible = true;
693      Update();
694    }
695
696    private void config_Click(object sender, EventArgs e) {
697      configurationDialog.ShowDialog(this);
698    }
699
700    private void chart_SelectionRangeChanged(object sender, CursorEventArgs e) {
701      OnZoomChanged(this, EventArgs.Empty);
702    }
703
704    private void chart_Resize(object sender, EventArgs e) {
705      UpdateTitlePosition();
706    }
707
708    private void chart_PostPaint(object sender, ChartPaintEventArgs e) {
709      if (ChartPostPaint != null)
710        ChartPostPaint(this, EventArgs.Empty);
711    }
712    #endregion
713  }
714}
715
Note: See TracBrowser for help on using the repository browser.