Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 14145 was 14131, checked in by pfleck, 8 years ago

#2597:

  • Moved variable name + cursor value to the top.
  • Fixed some warnings (missing async await).
File size: 25.7 KB
RevLine 
[13780]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;
[13836]24using System.Drawing;
[13817]25using System.Globalization;
[13780]26using System.Linq;
[13840]27using System.Threading;
[13837]28using System.Threading.Tasks;
[13780]29using System.Windows.Forms;
30using System.Windows.Forms.DataVisualization.Charting;
31using HeuristicLab.Common;
[13836]32using HeuristicLab.MainForm.WindowsForms;
[13780]33using HeuristicLab.Visualization.ChartControlsExtensions;
34
35namespace HeuristicLab.Problems.DataAnalysis.Views {
[13831]36  public partial class GradientChart : UserControl {
37    private ModifiableDataset sharedFixedVariables; // used for syncronising variable values between charts
[13837]38    private ModifiableDataset internalDataset; // holds the x values for each point drawn
[13780]39
[13842]40    private CancellationTokenSource cancelCurrentRecalculateSource;
[13840]41
[13842]42    private readonly List<IRegressionSolution> solutions;
43    private readonly Dictionary<IRegressionSolution, Series> seriesCache;
44    private readonly Dictionary<IRegressionSolution, Series> ciSeriesCache;
45
[13853]46    private readonly ToolStripMenuItem configToolStripMenuItem;
47    private readonly GradientChartConfigurationDialog configurationDialog;
48
[13842]49    #region Properties
[14014]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
[13831]60    public bool ShowLegend {
61      get { return chart.Legends[0].Enabled; }
62      set { chart.Legends[0].Enabled = value; }
[13780]63    }
[13831]64    public bool ShowCursor {
65      get { return chart.Annotations[0].Visible; }
[13853]66      set {
67        chart.Annotations[0].Visible = value;
[14131]68        if (!value) chart.Titles[0].Text = string.Empty;
[13853]69      }
[13831]70    }
[13780]71
[13855]72    public bool ShowConfigButton {
73      get { return configurationButton.Visible; }
74      set { configurationButton.Visible = value; }
75    }
76
[13831]77    private int xAxisTicks = 5;
78    public int XAxisTicks {
79      get { return xAxisTicks; }
[13843]80      set {
81        if (value != xAxisTicks) {
82          xAxisTicks = value;
83          SetupAxis(chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
84          RecalculateInternalDataset();
85        }
86      }
[13780]87    }
[13842]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;
[14006]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          }
[13842]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;
[14006]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          }
[13842]123        }
124      }
125    }
126
[13831]127    private int yAxisTicks = 5;
[13842]128    public int YAxisTicks {
[13831]129      get { return yAxisTicks; }
[13843]130      set {
131        if (value != yAxisTicks) {
132          yAxisTicks = value;
133          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
134          RecalculateInternalDataset();
135        }
136      }
[13831]137    }
[13842]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;
[14021]144          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]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;
[14021]154          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]155        }
156      }
157    }
[13780]158
[13843]159    private double trainingMin = 1;
160    private double trainingMax = -1;
[13780]161
[13831]162    private int drawingSteps = 1000;
163    public int DrawingSteps {
164      get { return drawingSteps; }
[13842]165      set {
166        if (value != drawingSteps) {
167          drawingSteps = value;
168          RecalculateInternalDataset();
169          ResizeAllSeriesData();
170        }
171      }
[13780]172    }
173
[13831]174    private string freeVariable;
175    public string FreeVariable {
176      get { return freeVariable; }
[13780]177      set {
[13831]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();
[13780]184      }
185    }
186
[13843]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
[14089]196    public bool IsZoomed {
197      get { return chart.ChartAreas[0].AxisX.ScaleView.IsZoomed; }
198    }
199
[13831]200    private VerticalLineAnnotation VerticalLineAnnotation {
201      get { return (VerticalLineAnnotation)chart.Annotations.SingleOrDefault(x => x is VerticalLineAnnotation); }
[13780]202    }
[13850]203
204    internal ElementPosition InnerPlotPosition {
205      get { return chart.ChartAreas[0].InnerPlotPosition; }
206    }
[13842]207    #endregion
[13780]208
209    public GradientChart() {
210      InitializeComponent();
[13836]211
[13842]212      solutions = new List<IRegressionSolution>();
213      seriesCache = new Dictionary<IRegressionSolution, Series>();
214      ciSeriesCache = new Dictionary<IRegressionSolution, Series>();
215
[13836]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;
[13840]225
[13853]226      configToolStripMenuItem = new ToolStripMenuItem("Configuration");
[13855]227      configToolStripMenuItem.Click += config_Click;
[13853]228      chart.ContextMenuStrip.Items.Add(new ToolStripSeparator());
229      chart.ContextMenuStrip.Items.Add(configToolStripMenuItem);
230      configurationDialog = new GradientChartConfigurationDialog(this);
231
[13842]232      Disposed += GradientChart_Disposed;
[13780]233    }
[13853]234
[13840]235    private void GradientChart_Disposed(object sender, EventArgs e) {
[13843]236      if (cancelCurrentRecalculateSource != null)
237        cancelCurrentRecalculateSource.Cancel();
[13840]238    }
239
[13842]240    public void Configure(IEnumerable<IRegressionSolution> solutions, ModifiableDataset sharedFixedVariables, string freeVariable, int drawingSteps, bool initializeAxisRanges = true) {
[13831]241      if (!SolutionsCompatible(solutions))
242        throw new ArgumentException("Solutions are not compatible with the problem data.");
243      this.freeVariable = freeVariable;
244      this.drawingSteps = drawingSteps;
[13780]245
[13842]246      this.solutions.Clear();
247      this.solutions.AddRange(solutions);
248
[13831]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;
[13780]255
[13842]256      RecalculateTrainingLimits(initializeAxisRanges);
[13831]257      RecalculateInternalDataset();
[13842]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
[14118]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)
[14131]283        chart.Titles[0].Text = FreeVariable + " : " + defaultValue.ToString("N3", CultureInfo.CurrentCulture);
[14118]284
[13842]285      ResizeAllSeriesData();
286      OrderAndColorSeries();
[13780]287    }
288
[13843]289    public async Task RecalculateAsync(bool updateOnFinish = true, bool resetYAxis = true) {
[13842]290      if (IsDisposed
291        || sharedFixedVariables == null || !solutions.Any() || string.IsNullOrEmpty(freeVariable)
292        || trainingMin.IsAlmost(trainingMax) || trainingMin > trainingMax || drawingSteps == 0)
293        return;
[13829]294
[13853]295      calculationPendingTimer.Start();
296
[13842]297      // cancel previous recalculate call
298      if (cancelCurrentRecalculateSource != null)
299        cancelCurrentRecalculateSource.Cancel();
300      cancelCurrentRecalculateSource = new CancellationTokenSource();
[14118]301      var cancellationToken = cancelCurrentRecalculateSource.Token;
[13842]302
303      // Update series
304      try {
[13843]305        var limits = await UpdateAllSeriesDataAsync(cancellationToken);
[13842]306
[13843]307        yMin = limits.Lower;
308        yMax = limits.Upper;
[13842]309        // Set y-axis
[13843]310        if (resetYAxis)
311          SetupAxis(chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]312
313        UpdateOutOfTrainingRangeStripLines();
314
[13853]315        calculationPendingTimer.Stop();
316        calculationPendingLabel.Visible = false;
[13843]317        if (updateOnFinish)
318          Update();
[13842]319      }
320      catch (OperationCanceledException) { }
321      catch (AggregateException ae) {
322        if (!ae.InnerExceptions.Any(e => e is OperationCanceledException))
323          throw;
324      }
[13831]325    }
326
[14131]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
[13843]336    private void SetupAxis(Axis axis, double minValue, double maxValue, int ticks, double? fixedAxisMin, double? fixedAxisMax) {
[13842]337      double axisMin, axisMax, axisInterval;
338      ChartUtil.CalculateAxisInterval(minValue, maxValue, ticks, out axisMin, out axisMax, out axisInterval);
339      axis.Minimum = fixedAxisMin ?? axisMin;
340      axis.Maximum = fixedAxisMax ?? axisMax;
[13843]341      axis.Interval = (axis.Maximum - axis.Minimum) / ticks;
342
[13845]343      try {
344        chart.ChartAreas[0].RecalculateAxesScale();
345      }
346      catch (InvalidOperationException) {
347        // Can occur if eg. axis min == axis max
348      }
[13842]349    }
350
351    private void RecalculateTrainingLimits(bool initializeAxisRanges) {
352      trainingMin = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Min()).Max();
353      trainingMax = solutions.Select(s => s.ProblemData.Dataset.GetDoubleValues(freeVariable, s.ProblemData.TrainingIndices).Max()).Min();
354
355      if (initializeAxisRanges) {
356        double xmin, xmax, xinterval;
357        ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
358        FixedXAxisMin = xmin;
359        FixedXAxisMax = xmax;
360      }
361    }
362
[13831]363    private void RecalculateInternalDataset() {
[13843]364      if (sharedFixedVariables == null)
365        return;
366
[13831]367      // we expand the range in order to get nice tick intervals on the x axis
[13829]368      double xmin, xmax, xinterval;
[13831]369      ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
[13842]370
371      if (FixedXAxisMin.HasValue) xmin = FixedXAxisMin.Value;
372      if (FixedXAxisMax.HasValue) xmax = FixedXAxisMax.Value;
[13831]373      double step = (xmax - xmin) / drawingSteps;
374
[13829]375      var xvalues = new List<double>();
[13831]376      for (int i = 0; i < drawingSteps; i++)
377        xvalues.Add(xmin + i * step);
378
379      var variables = sharedFixedVariables.DoubleVariables.ToList();
380      internalDataset = new ModifiableDataset(variables,
381        variables.Select(x => x == FreeVariable
382          ? xvalues
383          : Enumerable.Repeat(sharedFixedVariables.GetDoubleValue(x, 0), xvalues.Count).ToList()
384        )
385      );
[13808]386    }
387
[13842]388    private Tuple<Series, Series> CreateSeries(IRegressionSolution solution) {
389      var series = new Series {
390        ChartType = SeriesChartType.Line,
391        Name = solution.ProblemData.TargetVariable + " " + solutions.IndexOf(solution)
392      };
393      series.LegendText = series.Name;
[13837]394
[14099]395      var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
[13842]396      Series confidenceIntervalSeries = null;
397      if (confidenceBoundSolution != null) {
398        confidenceIntervalSeries = new Series {
399          ChartType = SeriesChartType.Range,
400          YValuesPerPoint = 2,
401          Name = "95% Conf. Interval " + series.Name,
402          IsVisibleInLegend = false
403        };
[13836]404      }
[13842]405      return Tuple.Create(series, confidenceIntervalSeries);
406    }
[13836]407
[13842]408    private void OrderAndColorSeries() {
[13836]409      chart.SuspendRepaint();
[13842]410
[13836]411      chart.Series.Clear();
412      // Add mean series for applying palette colors
[13842]413      foreach (var solution in solutions) {
414        chart.Series.Add(seriesCache[solution]);
[13780]415      }
[13842]416
[13836]417      chart.Palette = ChartColorPalette.BrightPastel;
418      chart.ApplyPaletteColors();
419      chart.Palette = ChartColorPalette.None;
420
[13842]421      // Add confidence interval series before its coresponding series for correct z index
422      foreach (var solution in solutions) {
423        Series ciSeries;
424        if (ciSeriesCache.TryGetValue(solution, out ciSeries)) {
425          var series = seriesCache[solution];
[13995]426          ciSeries.Color = Color.FromArgb(40, series.Color);
[13842]427          int idx = chart.Series.IndexOf(seriesCache[solution]);
428          chart.Series.Insert(idx, ciSeries);
429        }
[13836]430      }
[13842]431
[13836]432      chart.ResumeRepaint(true);
[13842]433    }
[13836]434
[13843]435    private async Task<DoubleLimit> UpdateAllSeriesDataAsync(CancellationToken cancellationToken) {
436      var updateTasks = solutions.Select(solution => UpdateSeriesDataAsync(solution, cancellationToken));
437
438      double min = double.MaxValue, max = double.MinValue;
439      foreach (var update in updateTasks) {
440        var limit = await update;
441        if (limit.Lower < min) min = limit.Lower;
442        if (limit.Upper > max) max = limit.Upper;
443      }
444
445      return new DoubleLimit(min, max);
446    }
447
448    private Task<DoubleLimit> UpdateSeriesDataAsync(IRegressionSolution solution, CancellationToken cancellationToken) {
[13842]449      return Task.Run(() => {
[13843]450        var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
451        var yvalues = solution.Model.GetEstimatedValues(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
[13836]452
[13843]453        double min = double.MaxValue, max = double.MinValue;
[13820]454
[13843]455        var series = seriesCache[solution];
456        for (int i = 0; i < xvalues.Count; i++) {
457          series.Points[i].SetValueXY(xvalues[i], yvalues[i]);
458          if (yvalues[i] < min) min = yvalues[i];
459          if (yvalues[i] > max) max = yvalues[i];
460        }
[14118]461        chart.Invalidate();
[13820]462
[14118]463        cancellationToken.ThrowIfCancellationRequested();
464
[14099]465        var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
[13843]466        if (confidenceBoundSolution != null) {
467          var confidenceIntervalSeries = ciSeriesCache[solution];
[14118]468          var variances = confidenceBoundSolution.Model.GetEstimatedVariances(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
[13843]469          for (int i = 0; i < xvalues.Count; i++) {
470            var lower = yvalues[i] - 1.96 * Math.Sqrt(variances[i]);
471            var upper = yvalues[i] + 1.96 * Math.Sqrt(variances[i]);
472            confidenceIntervalSeries.Points[i].SetValueXY(xvalues[i], lower, upper);
473            if (lower < min) min = lower;
474            if (upper > max) max = upper;
[13842]475          }
[14118]476          chart.Invalidate();
[13843]477        }
478
479        cancellationToken.ThrowIfCancellationRequested();
480        return new DoubleLimit(min, max);
[13842]481      }, cancellationToken);
482    }
[13840]483
[13842]484    private void ResizeAllSeriesData() {
[13843]485      if (internalDataset == null)
486        return;
487
[13842]488      var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
489      foreach (var solution in solutions)
490        ResizeSeriesData(solution, xvalues);
[13780]491    }
[13842]492    private void ResizeSeriesData(IRegressionSolution solution, IList<double> xvalues = null) {
493      if (xvalues == null)
494        xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
[13780]495
[13842]496      var series = seriesCache[solution];
497      series.Points.SuspendUpdates();
[13853]498      series.Points.Clear();
[13842]499      for (int i = 0; i < xvalues.Count; i++)
500        series.Points.Add(new DataPoint(xvalues[i], 0.0));
501      series.Points.ResumeUpdates();
[13780]502
[13842]503      Series confidenceIntervalSeries;
504      if (ciSeriesCache.TryGetValue(solution, out confidenceIntervalSeries)) {
505        confidenceIntervalSeries.Points.SuspendUpdates();
[13853]506        confidenceIntervalSeries.Points.Clear();
[13842]507        for (int i = 0; i < xvalues.Count; i++)
508          confidenceIntervalSeries.Points.Add(new DataPoint(xvalues[i], new[] { -1.0, 1.0 }));
509        confidenceIntervalSeries.Points.ResumeUpdates();
510      }
[13780]511    }
512
[13842]513    public async Task AddSolutionAsync(IRegressionSolution solution) {
[13831]514      if (!SolutionsCompatible(solutions.Concat(new[] { solution })))
515        throw new ArgumentException("The solution is not compatible with the problem data.");
[13842]516      if (solutions.Contains(solution))
517        return;
518
[13831]519      solutions.Add(solution);
[13842]520      RecalculateTrainingLimits(true);
521
522      var series = CreateSeries(solution);
523      seriesCache.Add(solution, series.Item1);
524      if (series.Item2 != null)
525        ciSeriesCache.Add(solution, series.Item2);
526
527      ResizeSeriesData(solution);
528      OrderAndColorSeries();
529
530      await RecalculateAsync();
[13995]531      var args = new EventArgs<IRegressionSolution>(solution);
532      OnSolutionAdded(this, args);
[13780]533    }
[13995]534
[13842]535    public async Task RemoveSolutionAsync(IRegressionSolution solution) {
536      if (!solutions.Remove(solution))
537        return;
538
539      RecalculateTrainingLimits(true);
540
541      seriesCache.Remove(solution);
542      ciSeriesCache.Remove(solution);
543
544      await RecalculateAsync();
[13995]545      var args = new EventArgs<IRegressionSolution>(solution);
546      OnSolutionRemoved(this, args);
[13831]547    }
[13780]548
[13831]549    private static bool SolutionsCompatible(IEnumerable<IRegressionSolution> solutions) {
550      foreach (var solution1 in solutions) {
551        var variables1 = solution1.ProblemData.Dataset.DoubleVariables;
552        foreach (var solution2 in solutions) {
553          if (solution1 == solution2)
554            continue;
555          var variables2 = solution2.ProblemData.Dataset.DoubleVariables;
556          if (!variables1.All(variables2.Contains))
557            return false;
558        }
559      }
560      return true;
[13780]561    }
562
[13842]563    private void UpdateOutOfTrainingRangeStripLines() {
[13831]564      var axisX = chart.ChartAreas[0].AxisX;
565      var lowerStripLine = axisX.StripLines[0];
566      var upperStripLine = axisX.StripLines[1];
567
568      lowerStripLine.IntervalOffset = axisX.Minimum;
[14006]569      lowerStripLine.StripWidth = Math.Abs(trainingMin - axisX.Minimum);
[13831]570
571      upperStripLine.IntervalOffset = trainingMax;
[14006]572      upperStripLine.StripWidth = Math.Abs(axisX.Maximum - trainingMax);
[13780]573    }
574
[13842]575    #region Events
[13995]576    public event EventHandler<EventArgs<IRegressionSolution>> SolutionAdded;
577    public void OnSolutionAdded(object sender, EventArgs<IRegressionSolution> args) {
578      var added = SolutionAdded;
579      if (added == null) return;
580      added(sender, args);
581    }
582
583    public event EventHandler<EventArgs<IRegressionSolution>> SolutionRemoved;
584    public void OnSolutionRemoved(object sender, EventArgs<IRegressionSolution> args) {
585      var removed = SolutionRemoved;
586      if (removed == null) return;
587      removed(sender, args);
588    }
589
[13817]590    public event EventHandler VariableValueChanged;
591    public void OnVariableValueChanged(object sender, EventArgs args) {
592      var changed = VariableValueChanged;
593      if (changed == null) return;
594      changed(sender, args);
595    }
596
[14089]597    public event EventHandler ZoomChanged;
598    public void OnZoomChanged(object sender, EventArgs args) {
599      var changed = ZoomChanged;
600      if (changed == null) return;
601      changed(sender, args);
602    }
603
[13842]604    private void sharedFixedVariables_ItemChanged(object o, EventArgs<int, int> e) {
605      if (o != sharedFixedVariables) return;
606      var variables = sharedFixedVariables.DoubleVariables.ToList();
607      var rowIndex = e.Value;
608      var columnIndex = e.Value2;
[13831]609
[13842]610      var variableName = variables[columnIndex];
611      if (variableName == FreeVariable) return;
612      var v = sharedFixedVariables.GetDoubleValue(variableName, rowIndex);
613      var values = new List<double>(Enumerable.Repeat(v, DrawingSteps));
614      internalDataset.ReplaceVariable(variableName, values);
[13780]615    }
616
[13818]617    private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
[13840]618      var step = (trainingMax - trainingMin) / drawingSteps;
[13846]619      double newLocation = step * (long)Math.Round(e.NewLocationX / step);
[13840]620      var axisX = chart.ChartAreas[0].AxisX;
[13995]621      if (newLocation >= axisX.Maximum)
622        newLocation = axisX.Maximum - step;
623      if (newLocation <= axisX.Minimum)
624        newLocation = axisX.Minimum + step;
[13831]625
[13846]626      e.NewLocationX = newLocation;
[14118]627
628      UpdateCursor();
629    }
630    private void chart_AnnotationPositionChanged(object sender, EventArgs e) {
631      UpdateCursor();
632    }
633    void UpdateCursor() {
634      var x = VerticalLineAnnotation.X;
[13831]635      sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
636
[13853]637      if (ShowCursor) {
[14131]638        chart.Titles[0].Text = FreeVariable + " : " + x.ToString("N3", CultureInfo.CurrentCulture);
[13853]639        chart.Update();
640      }
[13831]641
[13853]642      OnVariableValueChanged(this, EventArgs.Empty);
[13818]643    }
644
[13780]645    private void chart_MouseMove(object sender, MouseEventArgs e) {
[13842]646      bool hitCursor = chart.HitTest(e.X, e.Y).ChartElementType == ChartElementType.Annotation;
647      chart.Cursor = hitCursor ? Cursors.VSplit : Cursors.Default;
[13780]648    }
649
[14131]650    private async void chart_DragDrop(object sender, DragEventArgs e) {
[13780]651      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
652      if (data != null) {
653        var solution = data as IRegressionSolution;
[13842]654        if (!solutions.Contains(solution))
[14131]655          await AddSolutionAsync(solution);
[13780]656      }
657    }
[13842]658    private void chart_DragEnter(object sender, DragEventArgs e) {
[13780]659      if (!e.Data.GetDataPresent(HeuristicLab.Common.Constants.DragDropDataFormat)) return;
660      e.Effect = DragDropEffects.None;
661
662      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
663      var regressionSolution = data as IRegressionSolution;
664      if (regressionSolution != null) {
665        e.Effect = DragDropEffects.Copy;
666      }
667    }
[13853]668
669    private void calculationPendingTimer_Tick(object sender, EventArgs e) {
670      calculationPendingLabel.Visible = true;
671      Update();
672    }
673
[13855]674    private void config_Click(object sender, EventArgs e) {
[13853]675      configurationDialog.ShowDialog(this);
676    }
[14089]677
678    private void chart_SelectionRangeChanged(object sender, CursorEventArgs e) {
679      OnZoomChanged(this, EventArgs.Empty);
680    }
[14131]681
682    private void chart_Resize(object sender, EventArgs e) {
683      UpdateTitlePosition();
684    }
[13817]685    #endregion
[13780]686  }
687}
[14131]688
Note: See TracBrowser for help on using the repository browser.