Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/GradientChart.cs @ 14157

Last change on this file since 14157 was 14157, checked in by bburlacu, 8 years ago

#2597: Avoid calling CalculateAxesInterval when the interval is invalid.

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