Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PerformanceComparison/HeuristicLab.Optimization.Views/3.3/IRRestarterView.cs @ 12804

Last change on this file since 12804 was 12804, checked in by abeham, 9 years ago

#2431:

  • worked on IRRRun (early abort still troublesome)
  • Updated RLD view to allow defining targets
  • Attempting to handle maximization/minimization
File size: 13.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.ComponentModel;
24using System.Globalization;
25using System.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Analysis;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Core.Views;
31using HeuristicLab.MainForm;
32using HeuristicLab.PluginInfrastructure;
33
34namespace HeuristicLab.Optimization.Views {
35  [View("Independent Random Restarter View")]
36  [Content(typeof(IndepdentRandomRestarter), IsDefaultView = true)]
37  public partial class IndependentRandomRestarterView : IOptimizerView {
38    protected TypeSelectorDialog algorithmTypeSelectorDialog;
39    protected virtual bool SuppressEvents { get; set; }
40
41    public new IndepdentRandomRestarter Content {
42      get { return (IndepdentRandomRestarter)base.Content; }
43      set { base.Content = value; }
44    }
45
46    public IndependentRandomRestarterView() {
47      InitializeComponent();
48      terminationComboBox.Items.AddRange(Enum.GetValues(typeof(TerminationCriterium)).Cast<object>().ToArray());
49    }
50
51    protected override void Dispose(bool disposing) {
52      if (disposing) {
53        if (algorithmTypeSelectorDialog != null) algorithmTypeSelectorDialog.Dispose();
54        if (components != null) components.Dispose();
55      }
56      base.Dispose(disposing);
57    }
58
59    protected override void DeregisterContentEvents() {
60      Content.PropertyChanged -= Content_PropertyChanged;
61      base.DeregisterContentEvents();
62    }
63    protected override void RegisterContentEvents() {
64      base.RegisterContentEvents();
65      Content.PropertyChanged += Content_PropertyChanged;
66    }
67
68    protected override void OnContentChanged() {
69      base.OnContentChanged();
70      SuppressEvents = true;
71      try {
72        if (Content == null) {
73          maxExecutionTimeTextBox.Text = String.Empty;
74          maxEvaluationsTextBox.Text = String.Empty;
75          moveCostPerSolutionTextBox.Text = String.Empty;
76          targetValueTextBox.Text = String.Empty;
77          maximizationCheckBox.CheckState = CheckState.Indeterminate;
78          terminationComboBox.SelectedIndex = -1;
79
80          algorithmViewHost.Content = null;
81          currentRunView.Content = null;
82          runsView.Content = null;
83        } else {
84          maxExecutionTimeTextBox.Text = TimeSpanHelper.FormatNatural(Content.MaximumExecutionTime);
85          maxEvaluationsTextBox.Text = Content.MaximumEvaluations.ToString();
86          moveCostPerSolutionTextBox.Text = Content.MoveCostPerSolution.ToString(CultureInfo.CurrentCulture.NumberFormat);
87          targetValueTextBox.Text = Content.TargetValue.ToString(CultureInfo.CurrentCulture.NumberFormat);
88          maximizationCheckBox.Checked = Content.Maximization;
89          terminationComboBox.SelectedItem = Content.TerminationCriterium;
90
91          algorithmViewHost.Content = Content.Algorithm;
92          currentRunView.Content = Content.CurrentRun;
93          runsView.Content = Content.Runs;
94        }
95      } finally { SuppressEvents = false; }
96    }
97
98    protected override void SetEnabledStateOfControls() {
99      base.SetEnabledStateOfControls();
100      maxExecutionTimeTextBox.Enabled = Content != null && !ReadOnly && !Locked;
101      maxEvaluationsTextBox.Enabled = Content != null && !ReadOnly && !Locked;
102      moveCostPerSolutionTextBox.Enabled = Content != null && !ReadOnly && !Locked;
103      targetValueTextBox.Enabled = Content != null && !ReadOnly && !Locked;
104      maximizationCheckBox.Enabled = Content != null && !ReadOnly && !Locked;
105      terminationComboBox.Enabled = Content != null && !ReadOnly && !Locked;
106      newAlgorithmButton.Enabled = Content != null && !ReadOnly;
107      openAlgorithmButton.Enabled = Content != null && !ReadOnly;
108      algorithmViewHost.Enabled = Content != null;
109      currentRunView.Enabled = Content != null;
110      runsView.Enabled = Content != null;
111    }
112
113    protected override void OnClosed(FormClosedEventArgs e) {
114      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) {
115        //The content must be stopped if no other view showing the content is available
116        var optimizers = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v != this).Select(v => v.Content).OfType<IAlgorithm>();
117        if (!optimizers.Contains(Content.Algorithm)) {
118          var nestedOptimizers = optimizers.SelectMany(opt => opt.NestedOptimizers);
119          if (!nestedOptimizers.Contains(Content)) Content.Stop();
120        }
121      }
122      base.OnClosed(e);
123    }
124
125    #region Event Handlers
126    #region Content events
127    private void Content_PropertyChanged(object sender, PropertyChangedEventArgs e) {
128      SuppressEvents = true;
129      try {
130        switch (e.PropertyName) {
131          case "TerminationCriterium": terminationComboBox.SelectedItem = Content.TerminationCriterium; break;
132          case "MaximumExecutionTime": maxExecutionTimeTextBox.Text = TimeSpanHelper.FormatNatural(Content.MaximumExecutionTime); break;
133          case "MaximumEvaluations": maxEvaluationsTextBox.Text = Content.MaximumEvaluations.ToString(); break;
134          case "TargetValue": targetValueTextBox.Text = Content.TargetValue.ToString(CultureInfo.CurrentCulture.NumberFormat); break;
135          case "Maximization": maximizationCheckBox.Checked = Content.Maximization; break;
136          case "MoveCostPerSolution": moveCostPerSolutionTextBox.Text = Content.MoveCostPerSolution.ToString(CultureInfo.CurrentCulture.NumberFormat); break;
137          case "Algorithm": algorithmViewHost.Content = Content.Algorithm; break;
138          case "CurrentRun": currentRunView.Content = Content.CurrentRun; break;
139          case "Runs": runsView.Content = Content.Runs; break;
140        }
141      } finally { SuppressEvents = false; }
142    }
143    #endregion
144
145    #region Control events
146    private void maxExecutionTimeTextBox_Validating(object sender, CancelEventArgs e) {
147      if (SuppressEvents) return;
148      if (InvokeRequired) {
149        Invoke((Action<object, CancelEventArgs>)maxExecutionTimeTextBox_Validating, sender, e);
150        return;
151      }
152      TimeSpan ts;
153      if (!TimeSpanHelper.TryGetFromNaturalFormat(maxExecutionTimeTextBox.Text, out ts)) {
154        e.Cancel = !maxExecutionTimeTextBox.ReadOnly && maxExecutionTimeTextBox.Enabled;
155        errorProvider.SetError(maxExecutionTimeTextBox, "Please enter a valid time span, e.g. 20 seconds ; 45s ; 4min ; 1h ; 3 hours ; 2 days ; 4d");
156      } else {
157        Content.MaximumExecutionTime = ts;
158        e.Cancel = false;
159        errorProvider.SetError(maxExecutionTimeTextBox, null);
160      }
161    }
162
163    private void maxEvaluationsTextBox_Validating(object sender, CancelEventArgs e) {
164      if (SuppressEvents) return;
165      if (InvokeRequired) {
166        Invoke((Action<object, CancelEventArgs>)maxEvaluationsTextBox_Validating, sender, e);
167        return;
168      }
169      int value;
170      if (!int.TryParse(maxEvaluationsTextBox.Text, out value)) {
171        e.Cancel = !maxEvaluationsTextBox.ReadOnly && maxEvaluationsTextBox.Enabled;
172        errorProvider.SetError(maxEvaluationsTextBox, "Please enter a valid integer number.");
173      } else {
174        Content.MaximumEvaluations = value;
175        e.Cancel = false;
176        errorProvider.SetError(maxEvaluationsTextBox, null);
177      }
178    }
179
180    private void moveCostPerSolutionTextBox_Validating(object sender, CancelEventArgs e) {
181      if (SuppressEvents) return;
182      if (InvokeRequired) {
183        Invoke((Action<object, CancelEventArgs>)moveCostPerSolutionTextBox_Validating, sender, e);
184        return;
185      }
186      double value;
187      if (!double.TryParse(moveCostPerSolutionTextBox.Text, out value)) {
188        e.Cancel = !moveCostPerSolutionTextBox.ReadOnly && moveCostPerSolutionTextBox.Enabled;
189        errorProvider.SetError(moveCostPerSolutionTextBox, "Please enter a valid integer number.");
190      } else {
191        Content.MoveCostPerSolution = value;
192        e.Cancel = false;
193        errorProvider.SetError(moveCostPerSolutionTextBox, null);
194      }
195    }
196
197    private void targetValueTextBox_Validating(object sender, CancelEventArgs e) {
198      if (SuppressEvents) return;
199      if (InvokeRequired) {
200        Invoke((Action<object, CancelEventArgs>)targetValueTextBox_Validating, sender, e);
201        return;
202      }
203      double value;
204      if (!double.TryParse(targetValueTextBox.Text, out value)) {
205        e.Cancel = !targetValueTextBox.ReadOnly && targetValueTextBox.Enabled;
206        errorProvider.SetError(targetValueTextBox, "Please enter a valid integer number.");
207      } else {
208        Content.TargetValue = value;
209        e.Cancel = false;
210        errorProvider.SetError(targetValueTextBox, null);
211      }
212    }
213
214    private void maximizationCheckBox_CheckedChanged(object sender, EventArgs e) {
215      if (SuppressEvents) return;
216      if (InvokeRequired) {
217        Invoke((Action<object, EventArgs>)maximizationCheckBox_CheckedChanged, sender, e);
218        return;
219      }
220      Content.Maximization = maximizationCheckBox.Checked;
221    }
222
223    private void terminationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
224      if (SuppressEvents) return;
225      if (InvokeRequired) {
226        Invoke((Action<object, EventArgs>)terminationComboBox_SelectedIndexChanged, sender, e);
227        return;
228      }
229      Content.TerminationCriterium = (TerminationCriterium)terminationComboBox.SelectedItem;
230    }
231
232    private void newAlgorithmButton_Click(object sender, EventArgs e) {
233      if (algorithmTypeSelectorDialog == null) {
234        algorithmTypeSelectorDialog = new TypeSelectorDialog { Caption = "Select Algorithm" };
235        algorithmTypeSelectorDialog.TypeSelector.Caption = "Available Algorithms";
236        algorithmTypeSelectorDialog.TypeSelector.Configure(typeof(IAlgorithm)
237          , showNotInstantiableTypes: false, showGenericTypes: false);
238      }
239      if (algorithmTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
240        try {
241          Content.Algorithm = (IAlgorithm)algorithmTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
242        } catch (Exception ex) {
243          ErrorHandling.ShowErrorDialog(this, ex);
244        }
245      }
246    }
247
248    private void openAlgorithmButton_Click(object sender, EventArgs e) {
249      openFileDialog.Title = "Open Algorithm";
250      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
251        newAlgorithmButton.Enabled = openAlgorithmButton.Enabled = false;
252        algorithmViewHost.Enabled = false;
253
254        ContentManager.LoadAsync(openFileDialog.FileName, delegate(IStorableContent content, Exception error) {
255          try {
256            if (error != null) throw error;
257            var algorithm = content as IAlgorithm;
258            if (algorithm == null)
259              MessageBox.Show(this, "The selected file does not contain an algorithm.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
260            else
261              Content.Algorithm = algorithm;
262          } catch (Exception ex) {
263            ErrorHandling.ShowErrorDialog(this, ex);
264          } finally {
265            Invoke(new Action(delegate() {
266              algorithmViewHost.Enabled = true;
267              newAlgorithmButton.Enabled = openAlgorithmButton.Enabled = true;
268            }));
269          }
270        });
271      }
272    }
273
274    private void algorithmTabPage_DragEnterOver(object sender, DragEventArgs e) {
275      e.Effect = DragDropEffects.None;
276      var alg = e.Data.GetData(Constants.DragDropDataFormat) as IAlgorithm;
277      if (!ReadOnly && alg != null) {
278        if (!typeof(ISingleObjectiveHeuristicOptimizationProblem).IsAssignableFrom(alg.ProblemType))
279          return;
280        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
281        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
282        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
283        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
284        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
285      }
286    }
287
288    private void algorithmTabPage_DragDrop(object sender, DragEventArgs e) {
289      if (e.Effect != DragDropEffects.None) {
290        var algorithm = e.Data.GetData(Constants.DragDropDataFormat) as IAlgorithm;
291        if (e.Effect.HasFlag(DragDropEffects.Copy)) algorithm = (IAlgorithm)algorithm.Clone();
292        Content.Algorithm = algorithm;
293      }
294    }
295    #endregion
296    #endregion
297  }
298}
Note: See TracBrowser for help on using the repository browser.