Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/HeuristicLab.Problems.DataAnalysis.Views/3.4/Controls/PartialDependencePlot.cs @ 18190

Last change on this file since 18190 was 18051, checked in by chaider, 3 years ago

#3134 Added RunCollectionPartialDependencePlotView and changed UpdateAllSeriesDataAsync method in PartialDependencePlot to await all updates from the given enumeration

File size: 28.2 KB
RevLine 
[13780]1#region License Information
2/* HeuristicLab
[17180]3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[13780]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;
[14826]23using System.Collections;
[13780]24using System.Collections.Generic;
[13836]25using System.Drawing;
[13817]26using System.Globalization;
[13780]27using System.Linq;
[13840]28using System.Threading;
[13837]29using System.Threading.Tasks;
[13780]30using System.Windows.Forms;
31using System.Windows.Forms.DataVisualization.Charting;
32using HeuristicLab.Common;
[13836]33using HeuristicLab.MainForm.WindowsForms;
[13780]34using HeuristicLab.Visualization.ChartControlsExtensions;
35
36namespace HeuristicLab.Problems.DataAnalysis.Views {
[14852]37  public partial class PartialDependencePlot : UserControl, IPartialDependencePlot {
[17579]38    private ModifiableDataset sharedFixedVariables; // used for synchronizing variable values between charts
[13837]39    private ModifiableDataset internalDataset; // holds the x values for each point drawn
[13780]40
[13842]41    private CancellationTokenSource cancelCurrentRecalculateSource;
[13840]42
[13842]43    private readonly List<IRegressionSolution> solutions;
44    private readonly Dictionary<IRegressionSolution, Series> seriesCache;
45    private readonly Dictionary<IRegressionSolution, Series> ciSeriesCache;
46
[13853]47    private readonly ToolStripMenuItem configToolStripMenuItem;
[14852]48    private readonly PartialDependencePlotConfigurationDialog configurationDialog;
[13853]49
[13842]50    #region Properties
[14014]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
[13831]61    public bool ShowLegend {
62      get { return chart.Legends[0].Enabled; }
63      set { chart.Legends[0].Enabled = value; }
[13780]64    }
[13831]65    public bool ShowCursor {
66      get { return chart.Annotations[0].Visible; }
[13853]67      set {
68        chart.Annotations[0].Visible = value;
[14131]69        if (!value) chart.Titles[0].Text = string.Empty;
[13853]70      }
[13831]71    }
[13780]72
[13855]73    public bool ShowConfigButton {
74      get { return configurationButton.Visible; }
75      set { configurationButton.Visible = value; }
76    }
77
[13831]78    private int xAxisTicks = 5;
79    public int XAxisTicks {
80      get { return xAxisTicks; }
[13843]81      set {
82        if (value != xAxisTicks) {
83          xAxisTicks = value;
[15211]84          SetupAxis(chart, chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
[13843]85          RecalculateInternalDataset();
86        }
87      }
[13780]88    }
[13842]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;
[15211]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;
[14006]102          }
[13842]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;
[15211]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;
[14006]119          }
[13842]120        }
121      }
122    }
123
[13831]124    private int yAxisTicks = 5;
[13842]125    public int YAxisTicks {
[13831]126      get { return yAxisTicks; }
[13843]127      set {
128        if (value != yAxisTicks) {
129          yAxisTicks = value;
[15211]130          SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13843]131          RecalculateInternalDataset();
132        }
133      }
[13831]134    }
[13842]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;
[15211]141          SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]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;
[15211]151          SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]152        }
153      }
154    }
[13780]155
[15213]156    private double trainingMin = -1;
157    private double trainingMax = 1;
[13780]158
[13831]159    private int drawingSteps = 1000;
160    public int DrawingSteps {
161      get { return drawingSteps; }
[13842]162      set {
163        if (value != drawingSteps) {
164          drawingSteps = value;
165          RecalculateInternalDataset();
166          ResizeAllSeriesData();
167        }
168      }
[13780]169    }
170
[13831]171    private string freeVariable;
172    public string FreeVariable {
173      get { return freeVariable; }
[13780]174      set {
[13831]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();
[13780]181      }
182    }
183
[13843]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
[14089]193    public bool IsZoomed {
194      get { return chart.ChartAreas[0].AxisX.ScaleView.IsZoomed; }
195    }
196
[13831]197    private VerticalLineAnnotation VerticalLineAnnotation {
198      get { return (VerticalLineAnnotation)chart.Annotations.SingleOrDefault(x => x is VerticalLineAnnotation); }
[13780]199    }
[13850]200
201    internal ElementPosition InnerPlotPosition {
202      get { return chart.ChartAreas[0].InnerPlotPosition; }
203    }
[13842]204    #endregion
[13780]205
[14158]206    public event EventHandler ChartPostPaint;
207
[14852]208    public PartialDependencePlot() {
[13780]209      InitializeComponent();
[13836]210
[13842]211      solutions = new List<IRegressionSolution>();
212      seriesCache = new Dictionary<IRegressionSolution, Series>();
213      ciSeriesCache = new Dictionary<IRegressionSolution, Series>();
214
[13836]215      // Configure axis
216      chart.CustomizeAllChartAreas();
[15845]217      chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = false;
218      chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = false;
[13836]219
[15839]220      chart.ChartAreas[0].Axes.ToList().ForEach(x => { x.ScaleView.Zoomable = false; });
221
[13853]222      configToolStripMenuItem = new ToolStripMenuItem("Configuration");
[13855]223      configToolStripMenuItem.Click += config_Click;
[13853]224      chart.ContextMenuStrip.Items.Add(new ToolStripSeparator());
225      chart.ContextMenuStrip.Items.Add(configToolStripMenuItem);
[14852]226      configurationDialog = new PartialDependencePlotConfigurationDialog(this);
[13853]227
[14852]228      Disposed += Control_Disposed;
[13780]229    }
[13853]230
[14852]231    private void Control_Disposed(object sender, EventArgs e) {
[13843]232      if (cancelCurrentRecalculateSource != null)
233        cancelCurrentRecalculateSource.Cancel();
[13840]234    }
235
[13842]236    public void Configure(IEnumerable<IRegressionSolution> solutions, ModifiableDataset sharedFixedVariables, string freeVariable, int drawingSteps, bool initializeAxisRanges = true) {
[13831]237      if (!SolutionsCompatible(solutions))
238        throw new ArgumentException("Solutions are not compatible with the problem data.");
239      this.freeVariable = freeVariable;
240      this.drawingSteps = drawingSteps;
[13780]241
[13842]242      this.solutions.Clear();
243      this.solutions.AddRange(solutions);
244
[13831]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)
[16519]247      if (this.sharedFixedVariables != null) {
[13831]248        this.sharedFixedVariables.ItemChanged -= sharedFixedVariables_ItemChanged;
[16519]249        this.sharedFixedVariables.Reset -= sharedFixedVariables_Reset;
250      }
251
[13831]252      this.sharedFixedVariables = sharedFixedVariables;
253      this.sharedFixedVariables.ItemChanged += sharedFixedVariables_ItemChanged;
[16519]254      this.sharedFixedVariables.Reset += sharedFixedVariables_Reset;
[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)
[14267]283        chart.Titles[0].Text = FreeVariable + " : " + defaultValue.ToString("G5", 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)
[15211]292        || trainingMin > trainingMax || drawingSteps == 0)
[13842]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);
[15211]306        chart.Invalidate();
[13842]307
[13843]308        yMin = limits.Lower;
309        yMax = limits.Upper;
[13842]310        // Set y-axis
[13843]311        if (resetYAxis)
[15211]312          SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
[13842]313
314        UpdateOutOfTrainingRangeStripLines();
315
[13853]316        calculationPendingTimer.Stop();
317        calculationPendingLabel.Visible = false;
[13843]318        if (updateOnFinish)
319          Update();
[16519]320      } catch (OperationCanceledException) {
321      } catch (AggregateException ae) {
[13842]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
[15211]336    private static void SetupAxis(EnhancedChart chart, Axis axis, double minValue, double maxValue, int ticks, double? fixedAxisMin, double? fixedAxisMax) {
337      //guard if only one distinct value is present
338      if (minValue.IsAlmost(maxValue)) {
339        minValue = minValue - 0.5;
340        maxValue = minValue + 0.5;
[14157]341      }
[13843]342
[15211]343      double axisMin, axisMax, axisInterval;
344      ChartUtil.CalculateAxisInterval(minValue, maxValue, ticks, out axisMin, out axisMax, out axisInterval);
345      axis.Minimum = fixedAxisMin ?? axisMin;
346      axis.Maximum = fixedAxisMax ?? axisMax;
347      axis.Interval = (axis.Maximum - axis.Minimum) / ticks;
348
[15222]349      chart.ChartAreas[0].RecalculateAxesScale();
[13842]350    }
351
352    private void RecalculateTrainingLimits(bool initializeAxisRanges) {
[17579]353      //Set min and max to the interval ranges
354      trainingMin = solutions.Select(s => s.ProblemData.VariableRanges.GetInterval(freeVariable).LowerBound).Max();
355      trainingMax = solutions.Select(s => s.ProblemData.VariableRanges.GetInterval(freeVariable).UpperBound).Min();
[13842]356
357      if (initializeAxisRanges) {
358        double xmin, xmax, xinterval;
[15211]359        //guard if only one distinct value is present
360        if (trainingMin.IsAlmost(trainingMax))
361          ChartUtil.CalculateAxisInterval(trainingMin - 0.5, trainingMax + 0.5, XAxisTicks, out xmin, out xmax, out xinterval);
362        else
363          ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
364
[13842]365        FixedXAxisMin = xmin;
366        FixedXAxisMax = xmax;
367      }
368    }
369
[13831]370    private void RecalculateInternalDataset() {
[13843]371      if (sharedFixedVariables == null)
372        return;
373
[13831]374      // we expand the range in order to get nice tick intervals on the x axis
[13829]375      double xmin, xmax, xinterval;
[15211]376      //guard if only one distinct value is present
377      if (trainingMin.IsAlmost(trainingMax))
378        ChartUtil.CalculateAxisInterval(trainingMin - 0.5, trainingMin + 0.5, XAxisTicks, out xmin, out xmax, out xinterval);
379      else
380        ChartUtil.CalculateAxisInterval(trainingMin, trainingMax, XAxisTicks, out xmin, out xmax, out xinterval);
[13842]381
382      if (FixedXAxisMin.HasValue) xmin = FixedXAxisMin.Value;
383      if (FixedXAxisMax.HasValue) xmax = FixedXAxisMax.Value;
[13831]384      double step = (xmax - xmin) / drawingSteps;
385
[13829]386      var xvalues = new List<double>();
[13831]387      for (int i = 0; i < drawingSteps; i++)
388        xvalues.Add(xmin + i * step);
389
[14826]390      if (sharedFixedVariables == null)
391        return;
392
393      var variables = sharedFixedVariables.VariableNames.ToList();
394      var values = new List<IList>();
395      foreach (var varName in variables) {
396        if (varName == FreeVariable) {
397          values.Add(xvalues);
398        } else if (sharedFixedVariables.VariableHasType<double>(varName)) {
399          values.Add(Enumerable.Repeat(sharedFixedVariables.GetDoubleValue(varName, 0), xvalues.Count).ToList());
400        } else if (sharedFixedVariables.VariableHasType<string>(varName)) {
401          values.Add(Enumerable.Repeat(sharedFixedVariables.GetStringValue(varName, 0), xvalues.Count).ToList());
402        }
403      }
404
405      internalDataset = new ModifiableDataset(variables, values);
[13808]406    }
407
[13842]408    private Tuple<Series, Series> CreateSeries(IRegressionSolution solution) {
409      var series = new Series {
410        ChartType = SeriesChartType.Line,
411        Name = solution.ProblemData.TargetVariable + " " + solutions.IndexOf(solution)
412      };
413      series.LegendText = series.Name;
[13837]414
[14099]415      var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
[13842]416      Series confidenceIntervalSeries = null;
417      if (confidenceBoundSolution != null) {
418        confidenceIntervalSeries = new Series {
419          ChartType = SeriesChartType.Range,
420          YValuesPerPoint = 2,
421          Name = "95% Conf. Interval " + series.Name,
422          IsVisibleInLegend = false
423        };
[13836]424      }
[13842]425      return Tuple.Create(series, confidenceIntervalSeries);
426    }
[13836]427
[13842]428    private void OrderAndColorSeries() {
[13836]429      chart.SuspendRepaint();
[13842]430
[13836]431      chart.Series.Clear();
432      // Add mean series for applying palette colors
[13842]433      foreach (var solution in solutions) {
434        chart.Series.Add(seriesCache[solution]);
[13780]435      }
[13842]436
[13836]437      chart.Palette = ChartColorPalette.BrightPastel;
438      chart.ApplyPaletteColors();
439      chart.Palette = ChartColorPalette.None;
440
[17579]441      // Add confidence interval series before its corresponding series for correct z index
[13842]442      foreach (var solution in solutions) {
443        Series ciSeries;
444        if (ciSeriesCache.TryGetValue(solution, out ciSeries)) {
445          var series = seriesCache[solution];
[13995]446          ciSeries.Color = Color.FromArgb(40, series.Color);
[13842]447          int idx = chart.Series.IndexOf(seriesCache[solution]);
448          chart.Series.Insert(idx, ciSeries);
449        }
[13836]450      }
[13842]451
[13836]452      chart.ResumeRepaint(true);
[13842]453    }
[13836]454
[18051]455    private Task<DoubleLimit> UpdateAllSeriesDataAsync(CancellationToken cancellationToken) {
[13843]456      var updateTasks = solutions.Select(solution => UpdateSeriesDataAsync(solution, cancellationToken));
457
[18051]458      return Task.Run(() => {
459        double min = double.MaxValue, max = double.MinValue;
460        foreach (var update in updateTasks) {
461          var limit = update.Result;
462          if (limit.Lower < min) min = limit.Lower;
463          if (limit.Upper > max) max = limit.Upper;
464        }
[13843]465
[18051]466        return new DoubleLimit(min, max);
467      }, cancellationToken);
[13843]468    }
469
470    private Task<DoubleLimit> UpdateSeriesDataAsync(IRegressionSolution solution, CancellationToken cancellationToken) {
[13842]471      return Task.Run(() => {
[13843]472        var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
473        var yvalues = solution.Model.GetEstimatedValues(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
[13836]474
[13843]475        double min = double.MaxValue, max = double.MinValue;
[13820]476
[13843]477        var series = seriesCache[solution];
478        for (int i = 0; i < xvalues.Count; i++) {
479          series.Points[i].SetValueXY(xvalues[i], yvalues[i]);
480          if (yvalues[i] < min) min = yvalues[i];
481          if (yvalues[i] > max) max = yvalues[i];
482        }
[13820]483
[14118]484        cancellationToken.ThrowIfCancellationRequested();
485
[14099]486        var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
[13843]487        if (confidenceBoundSolution != null) {
488          var confidenceIntervalSeries = ciSeriesCache[solution];
[14118]489          var variances = confidenceBoundSolution.Model.GetEstimatedVariances(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
[13843]490          for (int i = 0; i < xvalues.Count; i++) {
491            var lower = yvalues[i] - 1.96 * Math.Sqrt(variances[i]);
492            var upper = yvalues[i] + 1.96 * Math.Sqrt(variances[i]);
493            confidenceIntervalSeries.Points[i].SetValueXY(xvalues[i], lower, upper);
494            if (lower < min) min = lower;
495            if (upper > max) max = upper;
[13842]496          }
[13843]497        }
498
499        cancellationToken.ThrowIfCancellationRequested();
500        return new DoubleLimit(min, max);
[13842]501      }, cancellationToken);
502    }
[13840]503
[13842]504    private void ResizeAllSeriesData() {
[13843]505      if (internalDataset == null)
506        return;
507
[13842]508      var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
509      foreach (var solution in solutions)
510        ResizeSeriesData(solution, xvalues);
[13780]511    }
[13842]512    private void ResizeSeriesData(IRegressionSolution solution, IList<double> xvalues = null) {
513      if (xvalues == null)
514        xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
[13780]515
[13842]516      var series = seriesCache[solution];
517      series.Points.SuspendUpdates();
[13853]518      series.Points.Clear();
[13842]519      for (int i = 0; i < xvalues.Count; i++)
520        series.Points.Add(new DataPoint(xvalues[i], 0.0));
521      series.Points.ResumeUpdates();
[13780]522
[13842]523      Series confidenceIntervalSeries;
524      if (ciSeriesCache.TryGetValue(solution, out confidenceIntervalSeries)) {
525        confidenceIntervalSeries.Points.SuspendUpdates();
[13853]526        confidenceIntervalSeries.Points.Clear();
[13842]527        for (int i = 0; i < xvalues.Count; i++)
528          confidenceIntervalSeries.Points.Add(new DataPoint(xvalues[i], new[] { -1.0, 1.0 }));
529        confidenceIntervalSeries.Points.ResumeUpdates();
530      }
[13780]531    }
532
[13842]533    public async Task AddSolutionAsync(IRegressionSolution solution) {
[17920]534      if (solutions.Contains(solution))
535        return;
[13831]536      if (!SolutionsCompatible(solutions.Concat(new[] { solution })))
537        throw new ArgumentException("The solution is not compatible with the problem data.");
[13842]538
[13831]539      solutions.Add(solution);
[13842]540      RecalculateTrainingLimits(true);
541
542      var series = CreateSeries(solution);
543      seriesCache.Add(solution, series.Item1);
544      if (series.Item2 != null)
545        ciSeriesCache.Add(solution, series.Item2);
546
547      ResizeSeriesData(solution);
548      OrderAndColorSeries();
549
550      await RecalculateAsync();
[13995]551      var args = new EventArgs<IRegressionSolution>(solution);
552      OnSolutionAdded(this, args);
[13780]553    }
[13995]554
[13842]555    public async Task RemoveSolutionAsync(IRegressionSolution solution) {
556      if (!solutions.Remove(solution))
557        return;
558
559      RecalculateTrainingLimits(true);
560
561      seriesCache.Remove(solution);
562      ciSeriesCache.Remove(solution);
563
564      await RecalculateAsync();
[13995]565      var args = new EventArgs<IRegressionSolution>(solution);
566      OnSolutionRemoved(this, args);
[13831]567    }
[13780]568
[13831]569    private static bool SolutionsCompatible(IEnumerable<IRegressionSolution> solutions) {
[14826]570      var refSolution = solutions.First();
571      var refSolVars = refSolution.ProblemData.Dataset.VariableNames;
[17939]572      var refFactorVars = refSolution.ProblemData.Dataset.StringVariables;
[17920]573      var distinctVals = refFactorVars.ToDictionary(fv => fv, fv => refSolution.ProblemData.Dataset.GetStringValues(fv).Distinct().ToArray());
[17939]574
[14826]575      foreach (var solution in solutions.Skip(1)) {
[17939]576        var variables1 = new HashSet<string>(solution.ProblemData.Dataset.VariableNames);
577        if (!variables1.IsSubsetOf(refSolVars))
[14826]578          return false;
579
[17939]580        foreach (var factorVar in solution.ProblemData.Dataset.StringVariables) {
[17920]581          var refValues = distinctVals[factorVar];
[17939]582          var values = new HashSet<string>(solution.ProblemData.Dataset.GetStringValues(factorVar));
583
584          if (!values.IsSubsetOf(refValues))
585            return false;
[13831]586        }
587      }
588      return true;
[13780]589    }
590
[13842]591    private void UpdateOutOfTrainingRangeStripLines() {
[13831]592      var axisX = chart.ChartAreas[0].AxisX;
593      var lowerStripLine = axisX.StripLines[0];
594      var upperStripLine = axisX.StripLines[1];
595
596      lowerStripLine.IntervalOffset = axisX.Minimum;
[14006]597      lowerStripLine.StripWidth = Math.Abs(trainingMin - axisX.Minimum);
[13831]598
599      upperStripLine.IntervalOffset = trainingMax;
[14006]600      upperStripLine.StripWidth = Math.Abs(axisX.Maximum - trainingMax);
[13780]601    }
602
[13842]603    #region Events
[13995]604    public event EventHandler<EventArgs<IRegressionSolution>> SolutionAdded;
605    public void OnSolutionAdded(object sender, EventArgs<IRegressionSolution> args) {
606      var added = SolutionAdded;
607      if (added == null) return;
608      added(sender, args);
609    }
610
611    public event EventHandler<EventArgs<IRegressionSolution>> SolutionRemoved;
612    public void OnSolutionRemoved(object sender, EventArgs<IRegressionSolution> args) {
613      var removed = SolutionRemoved;
614      if (removed == null) return;
615      removed(sender, args);
616    }
617
[13817]618    public event EventHandler VariableValueChanged;
619    public void OnVariableValueChanged(object sender, EventArgs args) {
620      var changed = VariableValueChanged;
621      if (changed == null) return;
622      changed(sender, args);
623    }
624
[14089]625    public event EventHandler ZoomChanged;
626    public void OnZoomChanged(object sender, EventArgs args) {
627      var changed = ZoomChanged;
628      if (changed == null) return;
629      changed(sender, args);
630    }
631
[13842]632    private void sharedFixedVariables_ItemChanged(object o, EventArgs<int, int> e) {
633      if (o != sharedFixedVariables) return;
[14826]634      var variables = sharedFixedVariables.VariableNames.ToList();
[13842]635      var rowIndex = e.Value;
636      var columnIndex = e.Value2;
[13831]637
[13842]638      var variableName = variables[columnIndex];
639      if (variableName == FreeVariable) return;
[16519]640
[14826]641      if (internalDataset.VariableHasType<double>(variableName)) {
642        var v = sharedFixedVariables.GetDoubleValue(variableName, rowIndex);
643        var values = new List<double>(Enumerable.Repeat(v, internalDataset.Rows));
644        internalDataset.ReplaceVariable(variableName, values);
645      } else if (internalDataset.VariableHasType<string>(variableName)) {
646        var v = sharedFixedVariables.GetStringValue(variableName, rowIndex);
647        var values = new List<String>(Enumerable.Repeat(v, internalDataset.Rows));
648        internalDataset.ReplaceVariable(variableName, values);
649      } else {
650        // unsupported type
651        throw new NotSupportedException();
652      }
[13780]653    }
654
[16519]655    private void sharedFixedVariables_Reset(object sender, EventArgs e) {
[17775]656      RecalculateInternalDataset();
[16519]657      var newValue = sharedFixedVariables.GetDoubleValue(FreeVariable, 0);
658      VerticalLineAnnotation.X = newValue;
[17775]659      UpdateCursor();
[16519]660    }
661
[13818]662    private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
[13840]663      var step = (trainingMax - trainingMin) / drawingSteps;
[13846]664      double newLocation = step * (long)Math.Round(e.NewLocationX / step);
[13840]665      var axisX = chart.ChartAreas[0].AxisX;
[13995]666      if (newLocation >= axisX.Maximum)
667        newLocation = axisX.Maximum - step;
668      if (newLocation <= axisX.Minimum)
669        newLocation = axisX.Minimum + step;
[13831]670
[13846]671      e.NewLocationX = newLocation;
[14118]672
673      UpdateCursor();
674    }
675    private void chart_AnnotationPositionChanged(object sender, EventArgs e) {
676      UpdateCursor();
677    }
[14826]678    private void UpdateCursor() {
[14118]679      var x = VerticalLineAnnotation.X;
[13831]680
[16519]681      if (!sharedFixedVariables.GetDoubleValue(FreeVariable, 0).IsAlmost(x))
682        sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
683
[13853]684      if (ShowCursor) {
[14267]685        chart.Titles[0].Text = FreeVariable + " : " + x.ToString("G5", CultureInfo.CurrentCulture);
[13853]686        chart.Update();
687      }
[13831]688
[13853]689      OnVariableValueChanged(this, EventArgs.Empty);
[13818]690    }
691
[13780]692    private void chart_MouseMove(object sender, MouseEventArgs e) {
[13842]693      bool hitCursor = chart.HitTest(e.X, e.Y).ChartElementType == ChartElementType.Annotation;
694      chart.Cursor = hitCursor ? Cursors.VSplit : Cursors.Default;
[13780]695    }
696
[14131]697    private async void chart_DragDrop(object sender, DragEventArgs e) {
[13780]698      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
699      if (data != null) {
700        var solution = data as IRegressionSolution;
[13842]701        if (!solutions.Contains(solution))
[14131]702          await AddSolutionAsync(solution);
[13780]703      }
704    }
[13842]705    private void chart_DragEnter(object sender, DragEventArgs e) {
[13780]706      if (!e.Data.GetDataPresent(HeuristicLab.Common.Constants.DragDropDataFormat)) return;
707      e.Effect = DragDropEffects.None;
708
709      var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
710      var regressionSolution = data as IRegressionSolution;
711      if (regressionSolution != null) {
712        e.Effect = DragDropEffects.Copy;
713      }
714    }
[13853]715
716    private void calculationPendingTimer_Tick(object sender, EventArgs e) {
717      calculationPendingLabel.Visible = true;
718      Update();
719    }
720
[13855]721    private void config_Click(object sender, EventArgs e) {
[13853]722      configurationDialog.ShowDialog(this);
[15818]723      OnZoomChanged(this, EventArgs.Empty);
[13853]724    }
[14089]725
726    private void chart_SelectionRangeChanged(object sender, CursorEventArgs e) {
727      OnZoomChanged(this, EventArgs.Empty);
728    }
[14131]729
730    private void chart_Resize(object sender, EventArgs e) {
731      UpdateTitlePosition();
732    }
[14158]733
734    private void chart_PostPaint(object sender, ChartPaintEventArgs e) {
735      if (ChartPostPaint != null)
736        ChartPostPaint(this, EventArgs.Empty);
737    }
[13817]738    #endregion
[13780]739  }
740}
[14131]741
Note: See TracBrowser for help on using the repository browser.