Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2521_ProblemRefactoring/HeuristicLab.Algorithms.DataAnalysis.Views/3.4/CrossValidationView.cs @ 18086

Last change on this file since 18086 was 18086, checked in by mkommend, 2 years ago

#2521: Merged trunk changes into branch.

File size: 17.5 KB
Line 
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
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using System.Windows.Forms;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Core.Views;
29using HeuristicLab.MainForm;
30using HeuristicLab.Optimization;
31using HeuristicLab.PluginInfrastructure;
32using HeuristicLab.Problems.DataAnalysis;
33
34namespace HeuristicLab.Algorithms.DataAnalysis.Views {
35  [View("CrossValidation View")]
36  [Content(typeof(CrossValidation), true)]
37  public sealed partial class CrossValidationView : NamedItemView {
38    private TypeSelectorDialog algorithmTypeSelectorDialog;
39    private TypeSelectorDialog problemTypeSelectorDialog;
40
41    public CrossValidationView() {
42      InitializeComponent();
43    }
44
45    public new CrossValidation Content {
46      get { return (CrossValidation)base.Content; }
47      set { base.Content = value; }
48    }
49
50    protected override void OnContentChanged() {
51      base.OnContentChanged();
52      if (Content == null) {
53        workersNumericUpDown.Value = 1;
54        foldsNumericUpDown.Value = 2;
55        samplesStartStringConvertibleValueView.Content = null;
56        samplesEndStringConvertibleValueView.Content = null;
57        algorithmNamedItemView.Content = null;
58        algorithmProblemViewHost.Content = null;
59        algorithmParameterCollectionView.Content = null;
60        resultCollectionView.Content = null;
61        runCollectionView.Content = null;
62        storeAlgorithmInEachRunCheckBox.Checked = true;
63        shuffleSamplesCheckBox.Checked = false;
64      } else {
65        Locked = ReadOnly = Content.ExecutionState == ExecutionState.Started;
66        workersNumericUpDown.Value = Content.NumberOfWorkers.Value;
67        foldsNumericUpDown.Value = Content.Folds.Value;
68        samplesStartStringConvertibleValueView.Content = Content.SamplesStart;
69        samplesEndStringConvertibleValueView.Content = Content.SamplesEnd;
70        UpdateAlgorithmView();
71        UpdateProblemView();
72        runCollectionView.Content = Content.Runs;
73        algorithmParameterCollectionView.Content = ((IParameterizedNamedItem)Content).Parameters;
74        resultCollectionView.Content = Content.Results;
75        executionTimeTextBox.Text = Content.ExecutionTime.ToString();
76        storeAlgorithmInEachRunCheckBox.Checked = Content.StoreAlgorithmInEachRun;
77        shuffleSamplesCheckBox.Checked = Content.ShuffleSamples.Value;
78      }
79    }
80
81    protected override void RegisterContentEvents() {
82      base.RegisterContentEvents();
83      Content.AlgorithmChanged += new EventHandler(Content_AlgorithmChanged);
84      Content.ProblemChanged += new EventHandler(Content_ProblemChanged);
85      Content.Folds.ValueChanged += new EventHandler(Content_Folds_ValueChanged);
86      Content.NumberOfWorkers.ValueChanged += new EventHandler(Content_NumberOfWorker_ValueChanged);
87
88      Content.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
89      Content.ExecutionStateChanged += new EventHandler(Content_ExecutionStateChanged);
90      Content.ExecutionTimeChanged += new EventHandler(Content_ExecutionTimeChanged);
91      Content.StoreAlgorithmInEachRunChanged += new EventHandler(Content_StoreAlgorithmInEachRunChanged);
92    }
93
94    protected override void DeregisterContentEvents() {
95      Content.AlgorithmChanged -= new EventHandler(Content_AlgorithmChanged);
96      Content.ProblemChanged -= new EventHandler(Content_ProblemChanged);
97      Content.Folds.ValueChanged -= new EventHandler(Content_Folds_ValueChanged);
98      Content.NumberOfWorkers.ValueChanged -= new EventHandler(Content_NumberOfWorker_ValueChanged);
99
100      Content.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred);
101      Content.ExecutionStateChanged -= new EventHandler(Content_ExecutionStateChanged);
102      Content.ExecutionTimeChanged -= new EventHandler(Content_ExecutionTimeChanged);
103      Content.StoreAlgorithmInEachRunChanged -= new EventHandler(Content_StoreAlgorithmInEachRunChanged);
104      base.DeregisterContentEvents();
105    }
106
107    protected override void OnClosed(FormClosedEventArgs e) {
108      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) {
109        //The content must be stopped if no other view showing the content is available
110        var optimizers = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v != this).Select(v => v.Content).OfType<IOptimizer>();
111        if (!optimizers.Contains(Content)) {
112          var nestedOptimizers = optimizers.SelectMany(opt => opt.NestedOptimizers);
113          if (!nestedOptimizers.Contains(Content)) Content.Stop();
114        }
115      }
116      base.OnClosed(e);
117    }
118
119    protected override void SetEnabledStateOfControls() {
120      if (InvokeRequired) Invoke((Action)SetEnabledStateOfControls);
121      else {
122        base.SetEnabledStateOfControls();
123        this.Enabled = Content != null;
124
125        if (Content != null) {
126          storeAlgorithmInEachRunCheckBox.Enabled = !ReadOnly;
127          openAlgorithmButton.Enabled = !ReadOnly;
128          newAlgorithmButton.Enabled = !ReadOnly;
129
130          algorithmNamedItemView.Enabled = Content.Algorithm != null && (Content.ExecutionState == ExecutionState.Prepared || Content.ExecutionState == ExecutionState.Stopped);
131          algorithmTabControl.Enabled = Content.Algorithm != null && (Content.ExecutionState == ExecutionState.Prepared || Content.ExecutionState == ExecutionState.Stopped);
132          foldsNumericUpDown.Enabled = Content.ExecutionState == ExecutionState.Prepared;
133          samplesStartStringConvertibleValueView.Enabled = Content.ExecutionState == ExecutionState.Prepared;
134          samplesEndStringConvertibleValueView.Enabled = Content.ExecutionState == ExecutionState.Prepared;
135          workersNumericUpDown.Enabled = (Content.ExecutionState == ExecutionState.Prepared) || (Content.ExecutionState == ExecutionState.Paused);
136
137          startButton.Enabled = (Content.ExecutionState == ExecutionState.Prepared) || (Content.ExecutionState == ExecutionState.Paused);
138          pauseButton.Enabled = Content.ExecutionState == ExecutionState.Started;
139          stopButton.Enabled = (Content.ExecutionState == ExecutionState.Started) || (Content.ExecutionState == ExecutionState.Paused);
140          resetButton.Enabled = Content.ExecutionState != ExecutionState.Started;
141          // prevent changing the shuffle if the algorithm is not finished
142          shuffleSamplesCheckBox.Enabled = Content.ExecutionState == ExecutionState.Prepared;
143        }
144      }
145    }
146
147    #region Content Events
148    private void Content_AlgorithmChanged(object sender, EventArgs e) {
149      UpdateAlgorithmView();
150      UpdateProblemView();
151      SetEnabledStateOfControls();
152    }
153    private void UpdateAlgorithmView() {
154      algorithmNamedItemView.Content = Content.Algorithm;
155      UpdateProblemView();
156    }
157
158    private void Content_ProblemChanged(object sender, EventArgs e) {
159      UpdateProblemView();
160      SetEnabledStateOfControls();
161    }
162    private void UpdateProblemView() {
163      algorithmProblemViewHost.Content = Content.Problem;
164    }
165
166    private void Content_Folds_ValueChanged(object sender, EventArgs e) {
167      foldsNumericUpDown.Value = Content.Folds.Value;
168    }
169    private void Content_NumberOfWorker_ValueChanged(object sender, EventArgs e) {
170      workersNumericUpDown.Value = Content.NumberOfWorkers.Value;
171    }
172
173    private void Content_ExecutionStateChanged(object sender, EventArgs e) {
174      if (InvokeRequired)
175        Invoke(new EventHandler(Content_ExecutionStateChanged), sender, e);
176      else {
177        Locked = ReadOnly = Content.ExecutionState == ExecutionState.Started;
178        SetEnabledStateOfControls();
179      }
180    }
181
182    private void Content_ExecutionTimeChanged(object sender, EventArgs e) {
183      if (InvokeRequired)
184        Invoke(new EventHandler(Content_ExecutionTimeChanged), sender, e);
185      else
186        executionTimeTextBox.Text = Content == null ? "-" : Content.ExecutionTime.ToString();
187    }
188    private void Content_ExceptionOccurred(object sender, EventArgs<Exception> e) {
189      if (InvokeRequired)
190        Invoke(new EventHandler<EventArgs<Exception>>(Content_ExceptionOccurred), sender, e);
191      else
192        ErrorHandling.ShowErrorDialog(this, e.Value);
193    }
194    private void Content_StoreAlgorithmInEachRunChanged(object sender, EventArgs e) {
195      if (InvokeRequired)
196        Invoke(new EventHandler(Content_StoreAlgorithmInEachRunChanged), sender, e);
197      else
198        storeAlgorithmInEachRunCheckBox.Checked = Content.StoreAlgorithmInEachRun;
199    }
200    #endregion
201
202    #region GUI events
203    private void shuffleSamplesCheckBox_CheckedChanged(object sender, EventArgs e) {
204      if (Content != null)
205        Content.ShuffleSamples.Value = shuffleSamplesCheckBox.Checked;
206    }
207    private void foldsNumericUpDown_Validated(object sender, EventArgs e) {
208      if (foldsNumericUpDown.Text == string.Empty)
209        foldsNumericUpDown.Text = foldsNumericUpDown.Value.ToString();
210    }
211    private void foldsNumericUpDown_ValueChanged(object sender, EventArgs e) {
212      if (Content != null)
213        Content.Folds.Value = (int)foldsNumericUpDown.Value;
214    }
215
216    private void workersNumericUpDown_Validated(object sender, EventArgs e) {
217      if (workersNumericUpDown.Text == string.Empty)
218        workersNumericUpDown.Text = workersNumericUpDown.Value.ToString();
219    }
220    private void workersNumericUpDown_ValueChanged(object sender, EventArgs e) {
221      if (Content != null)
222        Content.NumberOfWorkers.Value = (int)workersNumericUpDown.Value;
223    }
224
225    private async void startButton_Click(object sender, EventArgs e) {
226      try {
227        await Content.StartAsync();
228      } catch (Exception ex) {
229        ErrorHandling.ShowErrorDialog(this, ex);
230      }
231    }
232    private void pauseButton_Click(object sender, EventArgs e) {
233      Content.Pause();
234    }
235    private void stopButton_Click(object sender, EventArgs e) {
236      Content.Stop();
237    }
238    private void resetButton_Click(object sender, EventArgs e) {
239      Content.Prepare(false);
240    }
241
242    private void newAlgorithmButton_Click(object sender, EventArgs e) {
243      if (algorithmTypeSelectorDialog == null) {
244        algorithmTypeSelectorDialog = new TypeSelectorDialog();
245        algorithmTypeSelectorDialog.Caption = "Select Algorithm";
246        algorithmTypeSelectorDialog.TypeSelector.Caption = "Available Algorithms";
247        algorithmTypeSelectorDialog.TypeSelector.Configure(typeof(IAlgorithm), false, true);
248      }
249      if (algorithmTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
250        try {
251          Content.Algorithm = (IAlgorithm)algorithmTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
252        } catch (Exception ex) {
253          ErrorHandling.ShowErrorDialog(this, ex);
254        }
255      }
256    }
257
258    private void openAlgorithmButton_Click(object sender, EventArgs e) {
259      openFileDialog.Title = "Open Algorithm";
260      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
261        algorithmTabControl.Enabled = false;
262
263        ContentManager.LoadAsync(openFileDialog.FileName, delegate (IStorableContent content, Exception error) {
264          try {
265            if (error != null) throw error;
266            IAlgorithm algorithm = content as IAlgorithm;
267            if (algorithm == null || !(algorithm.Problem is IDataAnalysisProblem))
268              MessageBox.Show(this, "The selected file does not contain an algorithm or the problem of the algorithm is not a DataAnalysisProblem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
269            else
270              Content.Algorithm = algorithm;
271          } catch (Exception ex) {
272            ErrorHandling.ShowErrorDialog(this, ex);
273          } finally {
274            Invoke(new Action(delegate () {
275              algorithmTabControl.Enabled = true;
276            }));
277          }
278        });
279      }
280    }
281
282    private void newProblemButton_Click(object sender, EventArgs e) {
283      if (problemTypeSelectorDialog == null) {
284        problemTypeSelectorDialog = new TypeSelectorDialog();
285        problemTypeSelectorDialog.Caption = "Select Problem";
286        problemTypeSelectorDialog.TypeSelector.Caption = "Available Problems";
287      }
288      problemTypeSelectorDialog.TypeSelector.Configure(new List<Type>() { Content.ProblemType, Content.Algorithm.ProblemType }, false, true, true);
289      if (problemTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
290        Content.Problem = (IDataAnalysisProblem)problemTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
291      }
292    }
293
294    private void openProblemButton_Click(object sender, EventArgs e) {
295      openFileDialog.Title = "Open Problem";
296      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
297        newProblemButton.Enabled = openProblemButton.Enabled = false;
298        algorithmProblemViewHost.Enabled = false;
299
300        ContentManager.LoadAsync(openFileDialog.FileName, delegate (IStorableContent content, Exception error) {
301          try {
302            if (error != null) throw error;
303            IDataAnalysisProblem problem = content as IDataAnalysisProblem;
304            if (problem == null && (Content.Algorithm.ProblemType.IsAssignableFrom(content.GetType())))
305              Invoke(new Action(() =>
306                MessageBox.Show(this, "The selected file does not contain a DataAnalysisProblem problem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error)));
307            else
308              Content.Problem = problem;
309          } catch (Exception ex) {
310            Invoke(new Action(() => ErrorHandling.ShowErrorDialog(this, ex)));
311          } finally {
312            Invoke(new Action(delegate () {
313              algorithmProblemViewHost.Enabled = true;
314              newProblemButton.Enabled = openProblemButton.Enabled = true;
315            }));
316          }
317        });
318      }
319    }
320
321    private void algorithmTabPage_DragEnterOver(object sender, DragEventArgs e) {
322      e.Effect = DragDropEffects.None;
323      IAlgorithm algorithm = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IAlgorithm;
324      if (!ReadOnly && algorithm != null &&
325        (algorithm.ProblemType != null || Content.ProblemType.IsAssignableFrom(algorithm.Problem.GetType()))) {
326        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
327        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
328        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
329        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
330        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
331      }
332    }
333    private void algorithmTabPage_DragDrop(object sender, DragEventArgs e) {
334      if (e.Effect != DragDropEffects.None) {
335        IAlgorithm algorithm = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IAlgorithm;
336        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) algorithm = (IAlgorithm)algorithm.Clone();
337        Content.Algorithm = algorithm;
338      }
339    }
340
341    private void algorithmProblemTabPage_DragEnterOver(object sender, DragEventArgs e) {
342      e.Effect = DragDropEffects.None;
343      if (ReadOnly) return;
344      IProblem problem = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IProblem;
345      if (problem != null && Content.ProblemType.IsAssignableFrom(problem.GetType()) &&
346        Content.Algorithm.ProblemType.IsAssignableFrom(problem.GetType())) {
347        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
348        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
349        else if ((e.AllowedEffect & DragDropEffects.Copy) == DragDropEffects.Copy) e.Effect = DragDropEffects.Copy;
350        else if ((e.AllowedEffect & DragDropEffects.Move) == DragDropEffects.Move) e.Effect = DragDropEffects.Move;
351        else if ((e.AllowedEffect & DragDropEffects.Link) == DragDropEffects.Link) e.Effect = DragDropEffects.Link;
352      }
353    }
354    private void algorithmProblemTabPage_DragDrop(object sender, DragEventArgs e) {
355      if (e.Effect != DragDropEffects.None) {
356        IDataAnalysisProblem problem = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as IDataAnalysisProblem;
357        if ((e.Effect & DragDropEffects.Copy) == DragDropEffects.Copy) problem = (IDataAnalysisProblem)problem.Clone();
358        Content.Problem = problem;
359      }
360    }
361
362    private void storeAlgorithmInEachRunCheckBox_CheckedChanged(object sender, EventArgs e) {
363      if (Content != null) Content.StoreAlgorithmInEachRun = storeAlgorithmInEachRunCheckBox.Checked;
364    }
365    #endregion
366  }
367}
Note: See TracBrowser for help on using the repository browser.