1 | #region License Information
|
---|
2 | /* HeuristicLab
|
---|
3 | * Copyright (C) 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 |
|
---|
22 | using System;
|
---|
23 | using System.Collections;
|
---|
24 | using System.Collections.Generic;
|
---|
25 | using System.Drawing;
|
---|
26 | using System.Globalization;
|
---|
27 | using System.Linq;
|
---|
28 | using System.Threading;
|
---|
29 | using System.Threading.Tasks;
|
---|
30 | using System.Windows.Forms;
|
---|
31 | using System.Windows.Forms.DataVisualization.Charting;
|
---|
32 | using HeuristicLab.Common;
|
---|
33 | using HeuristicLab.MainForm.WindowsForms;
|
---|
34 | using HeuristicLab.Visualization.ChartControlsExtensions;
|
---|
35 |
|
---|
36 | namespace HeuristicLab.Problems.DataAnalysis.Views {
|
---|
37 | public partial class PartialDependencePlot : UserControl, IPartialDependencePlot {
|
---|
38 | private ModifiableDataset sharedFixedVariables; // used for synchronizing variable values between charts
|
---|
39 | private ModifiableDataset internalDataset; // holds the x values for each point drawn
|
---|
40 |
|
---|
41 | private CancellationTokenSource cancelCurrentRecalculateSource;
|
---|
42 |
|
---|
43 | private readonly List<IRegressionSolution> solutions;
|
---|
44 | private readonly Dictionary<IRegressionSolution, Series> seriesCache;
|
---|
45 | private readonly Dictionary<IRegressionSolution, Series> ciSeriesCache;
|
---|
46 |
|
---|
47 | private readonly ToolStripMenuItem configToolStripMenuItem;
|
---|
48 | private readonly PartialDependencePlotConfigurationDialog configurationDialog;
|
---|
49 |
|
---|
50 | #region Properties
|
---|
51 | public string XAxisTitle {
|
---|
52 | get { return chart.ChartAreas[0].AxisX.Title; }
|
---|
53 | set { chart.ChartAreas[0].AxisX.Title = value; }
|
---|
54 | }
|
---|
55 |
|
---|
56 | public string YAxisTitle {
|
---|
57 | get { return chart.ChartAreas[0].AxisY.Title; }
|
---|
58 | set { chart.ChartAreas[0].AxisY.Title = value; }
|
---|
59 | }
|
---|
60 |
|
---|
61 | public bool ShowLegend {
|
---|
62 | get { return chart.Legends[0].Enabled; }
|
---|
63 | set { chart.Legends[0].Enabled = value; }
|
---|
64 | }
|
---|
65 | public bool ShowCursor {
|
---|
66 | get { return chart.Annotations[0].Visible; }
|
---|
67 | set {
|
---|
68 | chart.Annotations[0].Visible = value;
|
---|
69 | if (!value) chart.Titles[0].Text = string.Empty;
|
---|
70 | }
|
---|
71 | }
|
---|
72 |
|
---|
73 | public bool ShowConfigButton {
|
---|
74 | get { return configurationButton.Visible; }
|
---|
75 | set { configurationButton.Visible = value; }
|
---|
76 | }
|
---|
77 |
|
---|
78 | private int xAxisTicks = 5;
|
---|
79 | public int XAxisTicks {
|
---|
80 | get { return xAxisTicks; }
|
---|
81 | set {
|
---|
82 | if (value != xAxisTicks) {
|
---|
83 | xAxisTicks = value;
|
---|
84 | SetupAxis(chart, chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
|
---|
85 | RecalculateInternalDataset();
|
---|
86 | }
|
---|
87 | }
|
---|
88 | }
|
---|
89 | private double? fixedXAxisMin;
|
---|
90 | public double? FixedXAxisMin {
|
---|
91 | get { return fixedXAxisMin; }
|
---|
92 | set {
|
---|
93 | if ((value.HasValue && fixedXAxisMin.HasValue && !value.Value.IsAlmost(fixedXAxisMin.Value)) || (value.HasValue != fixedXAxisMin.HasValue)) {
|
---|
94 | fixedXAxisMin = value;
|
---|
95 | SetupAxis(chart, chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
|
---|
96 | RecalculateInternalDataset();
|
---|
97 | // set the vertical line position
|
---|
98 | if (VerticalLineAnnotation.X <= fixedXAxisMin) {
|
---|
99 | var axisX = chart.ChartAreas[0].AxisX;
|
---|
100 | var step = (axisX.Maximum - axisX.Minimum) / drawingSteps;
|
---|
101 | VerticalLineAnnotation.X = axisX.Minimum + step;
|
---|
102 | }
|
---|
103 | }
|
---|
104 | }
|
---|
105 | }
|
---|
106 | private double? fixedXAxisMax;
|
---|
107 | public double? FixedXAxisMax {
|
---|
108 | get { return fixedXAxisMax; }
|
---|
109 | set {
|
---|
110 | if ((value.HasValue && fixedXAxisMax.HasValue && !value.Value.IsAlmost(fixedXAxisMax.Value)) || (value.HasValue != fixedXAxisMax.HasValue)) {
|
---|
111 | fixedXAxisMax = value;
|
---|
112 | SetupAxis(chart, chart.ChartAreas[0].AxisX, trainingMin, trainingMax, XAxisTicks, FixedXAxisMin, FixedXAxisMax);
|
---|
113 | RecalculateInternalDataset();
|
---|
114 | // set the vertical line position
|
---|
115 | if (VerticalLineAnnotation.X >= fixedXAxisMax) {
|
---|
116 | var axisX = chart.ChartAreas[0].AxisX;
|
---|
117 | var step = (axisX.Maximum - axisX.Minimum) / drawingSteps;
|
---|
118 | VerticalLineAnnotation.X = axisX.Maximum - step;
|
---|
119 | }
|
---|
120 | }
|
---|
121 | }
|
---|
122 | }
|
---|
123 |
|
---|
124 | private int yAxisTicks = 5;
|
---|
125 | public int YAxisTicks {
|
---|
126 | get { return yAxisTicks; }
|
---|
127 | set {
|
---|
128 | if (value != yAxisTicks) {
|
---|
129 | yAxisTicks = value;
|
---|
130 | SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
|
---|
131 | RecalculateInternalDataset();
|
---|
132 | }
|
---|
133 | }
|
---|
134 | }
|
---|
135 | private double? fixedYAxisMin;
|
---|
136 | public double? FixedYAxisMin {
|
---|
137 | get { return fixedYAxisMin; }
|
---|
138 | set {
|
---|
139 | if ((value.HasValue && fixedYAxisMin.HasValue && !value.Value.IsAlmost(fixedYAxisMin.Value)) || (value.HasValue != fixedYAxisMin.HasValue)) {
|
---|
140 | fixedYAxisMin = value;
|
---|
141 | SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
|
---|
142 | }
|
---|
143 | }
|
---|
144 | }
|
---|
145 | private double? fixedYAxisMax;
|
---|
146 | public double? FixedYAxisMax {
|
---|
147 | get { return fixedYAxisMax; }
|
---|
148 | set {
|
---|
149 | if ((value.HasValue && fixedYAxisMax.HasValue && !value.Value.IsAlmost(fixedYAxisMax.Value)) || (value.HasValue != fixedYAxisMax.HasValue)) {
|
---|
150 | fixedYAxisMax = value;
|
---|
151 | SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
|
---|
152 | }
|
---|
153 | }
|
---|
154 | }
|
---|
155 |
|
---|
156 | private double trainingMin = -1;
|
---|
157 | private double trainingMax = 1;
|
---|
158 |
|
---|
159 | private int drawingSteps = 1000;
|
---|
160 | public int DrawingSteps {
|
---|
161 | get { return drawingSteps; }
|
---|
162 | set {
|
---|
163 | if (value != drawingSteps) {
|
---|
164 | drawingSteps = value;
|
---|
165 | RecalculateInternalDataset();
|
---|
166 | ResizeAllSeriesData();
|
---|
167 | }
|
---|
168 | }
|
---|
169 | }
|
---|
170 |
|
---|
171 | private string freeVariable;
|
---|
172 | public string FreeVariable {
|
---|
173 | get { return freeVariable; }
|
---|
174 | set {
|
---|
175 | if (value == freeVariable) return;
|
---|
176 | if (solutions.Any(s => !s.ProblemData.Dataset.DoubleVariables.Contains(value))) {
|
---|
177 | throw new ArgumentException("Variable does not exist in the ProblemData of the Solutions.");
|
---|
178 | }
|
---|
179 | freeVariable = value;
|
---|
180 | RecalculateInternalDataset();
|
---|
181 | }
|
---|
182 | }
|
---|
183 |
|
---|
184 | private double yMin;
|
---|
185 | public double YMin {
|
---|
186 | get { return yMin; }
|
---|
187 | }
|
---|
188 | private double yMax;
|
---|
189 | public double YMax {
|
---|
190 | get { return yMax; }
|
---|
191 | }
|
---|
192 |
|
---|
193 | public bool IsZoomed {
|
---|
194 | get { return chart.ChartAreas[0].AxisX.ScaleView.IsZoomed; }
|
---|
195 | }
|
---|
196 |
|
---|
197 | private VerticalLineAnnotation VerticalLineAnnotation {
|
---|
198 | get { return (VerticalLineAnnotation)chart.Annotations.SingleOrDefault(x => x is VerticalLineAnnotation); }
|
---|
199 | }
|
---|
200 |
|
---|
201 | internal ElementPosition InnerPlotPosition {
|
---|
202 | get { return chart.ChartAreas[0].InnerPlotPosition; }
|
---|
203 | }
|
---|
204 | #endregion
|
---|
205 |
|
---|
206 | public event EventHandler ChartPostPaint;
|
---|
207 |
|
---|
208 | public PartialDependencePlot() {
|
---|
209 | InitializeComponent();
|
---|
210 |
|
---|
211 | solutions = new List<IRegressionSolution>();
|
---|
212 | seriesCache = new Dictionary<IRegressionSolution, Series>();
|
---|
213 | ciSeriesCache = new Dictionary<IRegressionSolution, Series>();
|
---|
214 |
|
---|
215 | // Configure axis
|
---|
216 | chart.CustomizeAllChartAreas();
|
---|
217 | chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = false;
|
---|
218 | chart.ChartAreas[0].CursorY.IsUserSelectionEnabled = false;
|
---|
219 |
|
---|
220 | chart.ChartAreas[0].Axes.ToList().ForEach(x => { x.ScaleView.Zoomable = false; });
|
---|
221 |
|
---|
222 | configToolStripMenuItem = new ToolStripMenuItem("Configuration");
|
---|
223 | configToolStripMenuItem.Click += config_Click;
|
---|
224 | chart.ContextMenuStrip.Items.Add(new ToolStripSeparator());
|
---|
225 | chart.ContextMenuStrip.Items.Add(configToolStripMenuItem);
|
---|
226 | configurationDialog = new PartialDependencePlotConfigurationDialog(this);
|
---|
227 |
|
---|
228 | Disposed += Control_Disposed;
|
---|
229 | }
|
---|
230 |
|
---|
231 | private void Control_Disposed(object sender, EventArgs e) {
|
---|
232 | if (cancelCurrentRecalculateSource != null)
|
---|
233 | cancelCurrentRecalculateSource.Cancel();
|
---|
234 | }
|
---|
235 |
|
---|
236 | public void Configure(IEnumerable<IRegressionSolution> solutions, ModifiableDataset sharedFixedVariables, string freeVariable, int drawingSteps, bool initializeAxisRanges = true) {
|
---|
237 | if (!SolutionsCompatible(solutions))
|
---|
238 | throw new ArgumentException("Solutions are not compatible with the problem data.");
|
---|
239 | this.freeVariable = freeVariable;
|
---|
240 | this.drawingSteps = drawingSteps;
|
---|
241 |
|
---|
242 | this.solutions.Clear();
|
---|
243 | this.solutions.AddRange(solutions);
|
---|
244 |
|
---|
245 | // add an event such that whenever a value is changed in the shared dataset,
|
---|
246 | // this change is reflected in the internal dataset (where the value becomes a whole column)
|
---|
247 | if (this.sharedFixedVariables != null) {
|
---|
248 | this.sharedFixedVariables.ItemChanged -= sharedFixedVariables_ItemChanged;
|
---|
249 | this.sharedFixedVariables.Reset -= sharedFixedVariables_Reset;
|
---|
250 | }
|
---|
251 |
|
---|
252 | this.sharedFixedVariables = sharedFixedVariables;
|
---|
253 | this.sharedFixedVariables.ItemChanged += sharedFixedVariables_ItemChanged;
|
---|
254 | this.sharedFixedVariables.Reset += sharedFixedVariables_Reset;
|
---|
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("G5", 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 > 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 | chart.Invalidate();
|
---|
307 |
|
---|
308 | yMin = limits.Lower;
|
---|
309 | yMax = limits.Upper;
|
---|
310 | // Set y-axis
|
---|
311 | if (resetYAxis)
|
---|
312 | SetupAxis(chart, chart.ChartAreas[0].AxisY, yMin, yMax, YAxisTicks, FixedYAxisMin, FixedYAxisMax);
|
---|
313 |
|
---|
314 | UpdateOutOfTrainingRangeStripLines();
|
---|
315 |
|
---|
316 | calculationPendingTimer.Stop();
|
---|
317 | calculationPendingLabel.Visible = false;
|
---|
318 | if (updateOnFinish)
|
---|
319 | Update();
|
---|
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 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;
|
---|
341 | }
|
---|
342 |
|
---|
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 |
|
---|
349 | chart.ChartAreas[0].RecalculateAxesScale();
|
---|
350 | }
|
---|
351 |
|
---|
352 | private void RecalculateTrainingLimits(bool initializeAxisRanges) {
|
---|
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();
|
---|
356 |
|
---|
357 | if (initializeAxisRanges) {
|
---|
358 | double xmin, xmax, xinterval;
|
---|
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 |
|
---|
365 | FixedXAxisMin = xmin;
|
---|
366 | FixedXAxisMax = xmax;
|
---|
367 | }
|
---|
368 | }
|
---|
369 |
|
---|
370 | private void RecalculateInternalDataset() {
|
---|
371 | if (sharedFixedVariables == null)
|
---|
372 | return;
|
---|
373 |
|
---|
374 | // we expand the range in order to get nice tick intervals on the x axis
|
---|
375 | double xmin, xmax, xinterval;
|
---|
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);
|
---|
381 |
|
---|
382 | if (FixedXAxisMin.HasValue) xmin = FixedXAxisMin.Value;
|
---|
383 | if (FixedXAxisMax.HasValue) xmax = FixedXAxisMax.Value;
|
---|
384 | double step = (xmax - xmin) / drawingSteps;
|
---|
385 |
|
---|
386 | var xvalues = new List<double>();
|
---|
387 | for (int i = 0; i < drawingSteps; i++)
|
---|
388 | xvalues.Add(xmin + i * step);
|
---|
389 |
|
---|
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);
|
---|
406 | }
|
---|
407 |
|
---|
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;
|
---|
414 |
|
---|
415 | var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
|
---|
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 | };
|
---|
424 | }
|
---|
425 | return Tuple.Create(series, confidenceIntervalSeries);
|
---|
426 | }
|
---|
427 |
|
---|
428 | private void OrderAndColorSeries() {
|
---|
429 | chart.SuspendRepaint();
|
---|
430 |
|
---|
431 | chart.Series.Clear();
|
---|
432 | // Add mean series for applying palette colors
|
---|
433 | foreach (var solution in solutions) {
|
---|
434 | chart.Series.Add(seriesCache[solution]);
|
---|
435 | }
|
---|
436 |
|
---|
437 | chart.Palette = ChartColorPalette.BrightPastel;
|
---|
438 | chart.ApplyPaletteColors();
|
---|
439 | chart.Palette = ChartColorPalette.None;
|
---|
440 |
|
---|
441 | // Add confidence interval series before its corresponding series for correct z index
|
---|
442 | foreach (var solution in solutions) {
|
---|
443 | Series ciSeries;
|
---|
444 | if (ciSeriesCache.TryGetValue(solution, out ciSeries)) {
|
---|
445 | var series = seriesCache[solution];
|
---|
446 | ciSeries.Color = Color.FromArgb(40, series.Color);
|
---|
447 | int idx = chart.Series.IndexOf(seriesCache[solution]);
|
---|
448 | chart.Series.Insert(idx, ciSeries);
|
---|
449 | }
|
---|
450 | }
|
---|
451 |
|
---|
452 | chart.ResumeRepaint(true);
|
---|
453 | }
|
---|
454 |
|
---|
455 | private async Task<DoubleLimit> UpdateAllSeriesDataAsync(CancellationToken cancellationToken) {
|
---|
456 | var updateTasks = solutions.Select(solution => UpdateSeriesDataAsync(solution, cancellationToken));
|
---|
457 |
|
---|
458 | double min = double.MaxValue, max = double.MinValue;
|
---|
459 | foreach (var update in updateTasks) {
|
---|
460 | var limit = await update;
|
---|
461 | if (limit.Lower < min) min = limit.Lower;
|
---|
462 | if (limit.Upper > max) max = limit.Upper;
|
---|
463 | }
|
---|
464 |
|
---|
465 | return new DoubleLimit(min, max);
|
---|
466 | }
|
---|
467 |
|
---|
468 | private Task<DoubleLimit> UpdateSeriesDataAsync(IRegressionSolution solution, CancellationToken cancellationToken) {
|
---|
469 | return Task.Run(() => {
|
---|
470 | var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
|
---|
471 | var yvalues = solution.Model.GetEstimatedValues(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
|
---|
472 |
|
---|
473 | double min = double.MaxValue, max = double.MinValue;
|
---|
474 |
|
---|
475 | var series = seriesCache[solution];
|
---|
476 | for (int i = 0; i < xvalues.Count; i++) {
|
---|
477 | series.Points[i].SetValueXY(xvalues[i], yvalues[i]);
|
---|
478 | if (yvalues[i] < min) min = yvalues[i];
|
---|
479 | if (yvalues[i] > max) max = yvalues[i];
|
---|
480 | }
|
---|
481 |
|
---|
482 | cancellationToken.ThrowIfCancellationRequested();
|
---|
483 |
|
---|
484 | var confidenceBoundSolution = solution as IConfidenceRegressionSolution;
|
---|
485 | if (confidenceBoundSolution != null) {
|
---|
486 | var confidenceIntervalSeries = ciSeriesCache[solution];
|
---|
487 | var variances = confidenceBoundSolution.Model.GetEstimatedVariances(internalDataset, Enumerable.Range(0, internalDataset.Rows)).ToList();
|
---|
488 | for (int i = 0; i < xvalues.Count; i++) {
|
---|
489 | var lower = yvalues[i] - 1.96 * Math.Sqrt(variances[i]);
|
---|
490 | var upper = yvalues[i] + 1.96 * Math.Sqrt(variances[i]);
|
---|
491 | confidenceIntervalSeries.Points[i].SetValueXY(xvalues[i], lower, upper);
|
---|
492 | if (lower < min) min = lower;
|
---|
493 | if (upper > max) max = upper;
|
---|
494 | }
|
---|
495 | }
|
---|
496 |
|
---|
497 | cancellationToken.ThrowIfCancellationRequested();
|
---|
498 | return new DoubleLimit(min, max);
|
---|
499 | }, cancellationToken);
|
---|
500 | }
|
---|
501 |
|
---|
502 | private void ResizeAllSeriesData() {
|
---|
503 | if (internalDataset == null)
|
---|
504 | return;
|
---|
505 |
|
---|
506 | var xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
|
---|
507 | foreach (var solution in solutions)
|
---|
508 | ResizeSeriesData(solution, xvalues);
|
---|
509 | }
|
---|
510 | private void ResizeSeriesData(IRegressionSolution solution, IList<double> xvalues = null) {
|
---|
511 | if (xvalues == null)
|
---|
512 | xvalues = internalDataset.GetDoubleValues(FreeVariable).ToList();
|
---|
513 |
|
---|
514 | var series = seriesCache[solution];
|
---|
515 | series.Points.SuspendUpdates();
|
---|
516 | series.Points.Clear();
|
---|
517 | for (int i = 0; i < xvalues.Count; i++)
|
---|
518 | series.Points.Add(new DataPoint(xvalues[i], 0.0));
|
---|
519 | series.Points.ResumeUpdates();
|
---|
520 |
|
---|
521 | Series confidenceIntervalSeries;
|
---|
522 | if (ciSeriesCache.TryGetValue(solution, out confidenceIntervalSeries)) {
|
---|
523 | confidenceIntervalSeries.Points.SuspendUpdates();
|
---|
524 | confidenceIntervalSeries.Points.Clear();
|
---|
525 | for (int i = 0; i < xvalues.Count; i++)
|
---|
526 | confidenceIntervalSeries.Points.Add(new DataPoint(xvalues[i], new[] { -1.0, 1.0 }));
|
---|
527 | confidenceIntervalSeries.Points.ResumeUpdates();
|
---|
528 | }
|
---|
529 | }
|
---|
530 |
|
---|
531 | public async Task AddSolutionAsync(IRegressionSolution solution) {
|
---|
532 | if (solutions.Contains(solution))
|
---|
533 | return;
|
---|
534 | if (!SolutionsCompatible(solutions.Concat(new[] { solution })))
|
---|
535 | throw new ArgumentException("The solution is not compatible with the problem data.");
|
---|
536 |
|
---|
537 | solutions.Add(solution);
|
---|
538 | RecalculateTrainingLimits(true);
|
---|
539 |
|
---|
540 | var series = CreateSeries(solution);
|
---|
541 | seriesCache.Add(solution, series.Item1);
|
---|
542 | if (series.Item2 != null)
|
---|
543 | ciSeriesCache.Add(solution, series.Item2);
|
---|
544 |
|
---|
545 | ResizeSeriesData(solution);
|
---|
546 | OrderAndColorSeries();
|
---|
547 |
|
---|
548 | await RecalculateAsync();
|
---|
549 | var args = new EventArgs<IRegressionSolution>(solution);
|
---|
550 | OnSolutionAdded(this, args);
|
---|
551 | }
|
---|
552 |
|
---|
553 | public async Task RemoveSolutionAsync(IRegressionSolution solution) {
|
---|
554 | if (!solutions.Remove(solution))
|
---|
555 | return;
|
---|
556 |
|
---|
557 | RecalculateTrainingLimits(true);
|
---|
558 |
|
---|
559 | seriesCache.Remove(solution);
|
---|
560 | ciSeriesCache.Remove(solution);
|
---|
561 |
|
---|
562 | await RecalculateAsync();
|
---|
563 | var args = new EventArgs<IRegressionSolution>(solution);
|
---|
564 | OnSolutionRemoved(this, args);
|
---|
565 | }
|
---|
566 |
|
---|
567 | private static bool SolutionsCompatible(IEnumerable<IRegressionSolution> solutions) {
|
---|
568 | var refSolution = solutions.First();
|
---|
569 | var refSolVars = refSolution.ProblemData.Dataset.VariableNames;
|
---|
570 | var refFactorVars = refSolution.ProblemData.Dataset.StringVariables;
|
---|
571 | var distinctVals = refFactorVars.ToDictionary(fv => fv, fv => refSolution.ProblemData.Dataset.GetStringValues(fv).Distinct().ToArray());
|
---|
572 |
|
---|
573 | foreach (var solution in solutions.Skip(1)) {
|
---|
574 | var variables1 = new HashSet<string>(solution.ProblemData.Dataset.VariableNames);
|
---|
575 | if (!variables1.IsSubsetOf(refSolVars))
|
---|
576 | return false;
|
---|
577 |
|
---|
578 | foreach (var factorVar in solution.ProblemData.Dataset.StringVariables) {
|
---|
579 | var refValues = distinctVals[factorVar];
|
---|
580 | var values = new HashSet<string>(solution.ProblemData.Dataset.GetStringValues(factorVar));
|
---|
581 |
|
---|
582 | if (!values.IsSubsetOf(refValues))
|
---|
583 | return false;
|
---|
584 | }
|
---|
585 | }
|
---|
586 | return true;
|
---|
587 | }
|
---|
588 |
|
---|
589 | private void UpdateOutOfTrainingRangeStripLines() {
|
---|
590 | var axisX = chart.ChartAreas[0].AxisX;
|
---|
591 | var lowerStripLine = axisX.StripLines[0];
|
---|
592 | var upperStripLine = axisX.StripLines[1];
|
---|
593 |
|
---|
594 | lowerStripLine.IntervalOffset = axisX.Minimum;
|
---|
595 | lowerStripLine.StripWidth = Math.Abs(trainingMin - axisX.Minimum);
|
---|
596 |
|
---|
597 | upperStripLine.IntervalOffset = trainingMax;
|
---|
598 | upperStripLine.StripWidth = Math.Abs(axisX.Maximum - trainingMax);
|
---|
599 | }
|
---|
600 |
|
---|
601 | #region Events
|
---|
602 | public event EventHandler<EventArgs<IRegressionSolution>> SolutionAdded;
|
---|
603 | public void OnSolutionAdded(object sender, EventArgs<IRegressionSolution> args) {
|
---|
604 | var added = SolutionAdded;
|
---|
605 | if (added == null) return;
|
---|
606 | added(sender, args);
|
---|
607 | }
|
---|
608 |
|
---|
609 | public event EventHandler<EventArgs<IRegressionSolution>> SolutionRemoved;
|
---|
610 | public void OnSolutionRemoved(object sender, EventArgs<IRegressionSolution> args) {
|
---|
611 | var removed = SolutionRemoved;
|
---|
612 | if (removed == null) return;
|
---|
613 | removed(sender, args);
|
---|
614 | }
|
---|
615 |
|
---|
616 | public event EventHandler VariableValueChanged;
|
---|
617 | public void OnVariableValueChanged(object sender, EventArgs args) {
|
---|
618 | var changed = VariableValueChanged;
|
---|
619 | if (changed == null) return;
|
---|
620 | changed(sender, args);
|
---|
621 | }
|
---|
622 |
|
---|
623 | public event EventHandler ZoomChanged;
|
---|
624 | public void OnZoomChanged(object sender, EventArgs args) {
|
---|
625 | var changed = ZoomChanged;
|
---|
626 | if (changed == null) return;
|
---|
627 | changed(sender, args);
|
---|
628 | }
|
---|
629 |
|
---|
630 | private void sharedFixedVariables_ItemChanged(object o, EventArgs<int, int> e) {
|
---|
631 | if (o != sharedFixedVariables) return;
|
---|
632 | var variables = sharedFixedVariables.VariableNames.ToList();
|
---|
633 | var rowIndex = e.Value;
|
---|
634 | var columnIndex = e.Value2;
|
---|
635 |
|
---|
636 | var variableName = variables[columnIndex];
|
---|
637 | if (variableName == FreeVariable) return;
|
---|
638 |
|
---|
639 | if (internalDataset.VariableHasType<double>(variableName)) {
|
---|
640 | var v = sharedFixedVariables.GetDoubleValue(variableName, rowIndex);
|
---|
641 | var values = new List<double>(Enumerable.Repeat(v, internalDataset.Rows));
|
---|
642 | internalDataset.ReplaceVariable(variableName, values);
|
---|
643 | } else if (internalDataset.VariableHasType<string>(variableName)) {
|
---|
644 | var v = sharedFixedVariables.GetStringValue(variableName, rowIndex);
|
---|
645 | var values = new List<String>(Enumerable.Repeat(v, internalDataset.Rows));
|
---|
646 | internalDataset.ReplaceVariable(variableName, values);
|
---|
647 | } else {
|
---|
648 | // unsupported type
|
---|
649 | throw new NotSupportedException();
|
---|
650 | }
|
---|
651 | }
|
---|
652 |
|
---|
653 | private void sharedFixedVariables_Reset(object sender, EventArgs e) {
|
---|
654 | RecalculateInternalDataset();
|
---|
655 | var newValue = sharedFixedVariables.GetDoubleValue(FreeVariable, 0);
|
---|
656 | VerticalLineAnnotation.X = newValue;
|
---|
657 | UpdateCursor();
|
---|
658 | }
|
---|
659 |
|
---|
660 | private void chart_AnnotationPositionChanging(object sender, AnnotationPositionChangingEventArgs e) {
|
---|
661 | var step = (trainingMax - trainingMin) / drawingSteps;
|
---|
662 | double newLocation = step * (long)Math.Round(e.NewLocationX / step);
|
---|
663 | var axisX = chart.ChartAreas[0].AxisX;
|
---|
664 | if (newLocation >= axisX.Maximum)
|
---|
665 | newLocation = axisX.Maximum - step;
|
---|
666 | if (newLocation <= axisX.Minimum)
|
---|
667 | newLocation = axisX.Minimum + step;
|
---|
668 |
|
---|
669 | e.NewLocationX = newLocation;
|
---|
670 |
|
---|
671 | UpdateCursor();
|
---|
672 | }
|
---|
673 | private void chart_AnnotationPositionChanged(object sender, EventArgs e) {
|
---|
674 | UpdateCursor();
|
---|
675 | }
|
---|
676 | private void UpdateCursor() {
|
---|
677 | var x = VerticalLineAnnotation.X;
|
---|
678 |
|
---|
679 | if (!sharedFixedVariables.GetDoubleValue(FreeVariable, 0).IsAlmost(x))
|
---|
680 | sharedFixedVariables.SetVariableValue(x, FreeVariable, 0);
|
---|
681 |
|
---|
682 | if (ShowCursor) {
|
---|
683 | chart.Titles[0].Text = FreeVariable + " : " + x.ToString("G5", CultureInfo.CurrentCulture);
|
---|
684 | chart.Update();
|
---|
685 | }
|
---|
686 |
|
---|
687 | OnVariableValueChanged(this, EventArgs.Empty);
|
---|
688 | }
|
---|
689 |
|
---|
690 | private void chart_MouseMove(object sender, MouseEventArgs e) {
|
---|
691 | bool hitCursor = chart.HitTest(e.X, e.Y).ChartElementType == ChartElementType.Annotation;
|
---|
692 | chart.Cursor = hitCursor ? Cursors.VSplit : Cursors.Default;
|
---|
693 | }
|
---|
694 |
|
---|
695 | private async void chart_DragDrop(object sender, DragEventArgs e) {
|
---|
696 | var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
|
---|
697 | if (data != null) {
|
---|
698 | var solution = data as IRegressionSolution;
|
---|
699 | if (!solutions.Contains(solution))
|
---|
700 | await AddSolutionAsync(solution);
|
---|
701 | }
|
---|
702 | }
|
---|
703 | private void chart_DragEnter(object sender, DragEventArgs e) {
|
---|
704 | if (!e.Data.GetDataPresent(HeuristicLab.Common.Constants.DragDropDataFormat)) return;
|
---|
705 | e.Effect = DragDropEffects.None;
|
---|
706 |
|
---|
707 | var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
|
---|
708 | var regressionSolution = data as IRegressionSolution;
|
---|
709 | if (regressionSolution != null) {
|
---|
710 | e.Effect = DragDropEffects.Copy;
|
---|
711 | }
|
---|
712 | }
|
---|
713 |
|
---|
714 | private void calculationPendingTimer_Tick(object sender, EventArgs e) {
|
---|
715 | calculationPendingLabel.Visible = true;
|
---|
716 | Update();
|
---|
717 | }
|
---|
718 |
|
---|
719 | private void config_Click(object sender, EventArgs e) {
|
---|
720 | configurationDialog.ShowDialog(this);
|
---|
721 | OnZoomChanged(this, EventArgs.Empty);
|
---|
722 | }
|
---|
723 |
|
---|
724 | private void chart_SelectionRangeChanged(object sender, CursorEventArgs e) {
|
---|
725 | OnZoomChanged(this, EventArgs.Empty);
|
---|
726 | }
|
---|
727 |
|
---|
728 | private void chart_Resize(object sender, EventArgs e) {
|
---|
729 | UpdateTitlePosition();
|
---|
730 | }
|
---|
731 |
|
---|
732 | private void chart_PostPaint(object sender, ChartPaintEventArgs e) {
|
---|
733 | if (ChartPostPaint != null)
|
---|
734 | ChartPostPaint(this, EventArgs.Empty);
|
---|
735 | }
|
---|
736 | #endregion
|
---|
737 | }
|
---|
738 | }
|
---|
739 |
|
---|