Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2213_irace/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/PartialDependencePlot.cs @ 17578

Last change on this file since 17578 was 15845, checked in by gkronber, 7 years ago

#2888 removed selection rectangles (not necessary anymore because zooming was disabled)

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