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