source: stable/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/GradientChart.cs @ 14166

Last change on this file since 14166 was 14166, checked in by mkommend, 5 years ago

#2597: Merged r14095, r14096, r14098, r14099, r14118, r14119, r14131, r14157, r14158 into stable.

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