source: branches/PerformanceComparison/HeuristicLab.OptimizationExpertSystem.Views/3.3/ExpertSystemOptimizerView.cs @ 12847

Last change on this file since 12847 was 12847, checked in by abeham, 4 years ago

#2457: Added view

File size: 11.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.Optimization;
33using HeuristicLab.Optimization.Views;
34using HeuristicLab.PluginInfrastructure;
35
36namespace HeuristicLab.OptimizationExpertSystem.Views {
37  [View("Expert-system Optimizer View")]
38  [Content(typeof(ExpertSystemOptimizer), IsDefaultView = true)]
39  public partial class ExpertSystemOptimizerView : IOptimizerView {
40    protected TypeSelectorDialog problemTypeSelectorDialog;
41    protected virtual bool SuppressEvents { get; set; }
42
43    public new ExpertSystemOptimizer Content {
44      get { return (ExpertSystemOptimizer)base.Content; }
45      set { base.Content = value; }
46    }
47
48    public ExpertSystemOptimizerView() {
49      InitializeComponent();
50    }
51
52    protected override void Dispose(bool disposing) {
53      if (disposing) {
54        if (problemTypeSelectorDialog != null) problemTypeSelectorDialog.Dispose();
55        if (components != null) components.Dispose();
56      }
57      base.Dispose(disposing);
58    }
59
60    protected override void DeregisterContentEvents() {
61      Content.PropertyChanged -= Content_PropertyChanged;
62      Content.SuggestedInstances.CollectionReset -= SuggestedInstancesOnChanged;
63      Content.SuggestedInstances.ItemsAdded -= SuggestedInstancesOnChanged;
64      Content.SuggestedInstances.ItemsMoved -= SuggestedInstancesOnChanged;
65      Content.SuggestedInstances.ItemsRemoved -= SuggestedInstancesOnChanged;
66      Content.SuggestedInstances.ItemsReplaced -= SuggestedInstancesOnChanged;
67      base.DeregisterContentEvents();
68    }
69    protected override void RegisterContentEvents() {
70      base.RegisterContentEvents();
71      Content.PropertyChanged += Content_PropertyChanged;
72      Content.SuggestedInstances.CollectionReset += SuggestedInstancesOnChanged;
73      Content.SuggestedInstances.ItemsAdded += SuggestedInstancesOnChanged;
74      Content.SuggestedInstances.ItemsMoved += SuggestedInstancesOnChanged;
75      Content.SuggestedInstances.ItemsRemoved += SuggestedInstancesOnChanged;
76      Content.SuggestedInstances.ItemsReplaced += SuggestedInstancesOnChanged;
77    }
78
79    protected override void OnContentChanged() {
80      base.OnContentChanged();
81      SuppressEvents = true;
82      try {
83        if (Content == null) {
84          maxEvaluationsTextBox.Text = String.Empty;
85
86          problemViewHost.Content = null;
87          algorithmViewHost.Content = null;
88          runsView.Content = null;
89          okbRunCollectionView.Content = null;
90        } else {
91          maxEvaluationsTextBox.Text = Content.MaximumEvaluations.ToString();
92          problemViewHost.Content = Content.Problem;
93          runsView.Content = Content.Runs;
94          okbRunCollectionView.Content = Content.KnowledgeBase;
95        }
96        UpdateSuggestedInstancesCombobox();
97      } finally { SuppressEvents = false; }
98    }
99
100    protected override void SetEnabledStateOfControls() {
101      base.SetEnabledStateOfControls();
102      maxEvaluationsTextBox.Enabled = Content != null && !ReadOnly && !Locked;
103      newProblemButton.Enabled = Content != null && !ReadOnly && !Locked;
104      openProblemButton.Enabled = Content != null && !ReadOnly && !Locked;
105      problemViewHost.Enabled = Content != null && !ReadOnly && !Locked;
106      suggestedInstancesComboBox.Enabled = Content != null && !ReadOnly && !Locked;
107      algorithmViewHost.Enabled = Content != null && !ReadOnly && !Locked;
108      runsView.Enabled = Content != null;
109      okbRunCollectionView.Enabled = Content != null;
110    }
111
112    protected override void OnClosed(FormClosedEventArgs e) {
113      if ((Content != null) && (Content.ExecutionState == ExecutionState.Started)) {
114        //The content must be stopped if no other view showing the content is available
115        var optimizers = MainFormManager.MainForm.Views.OfType<IContentView>().Where(v => v != this).Select(v => v.Content).OfType<IOptimizer>();
116        if (!optimizers.Contains(Content)) {
117          var nestedOptimizers = optimizers.SelectMany(opt => opt.NestedOptimizers);
118          if (!nestedOptimizers.Contains(Content)) Content.Stop();
119        }
120      }
121      base.OnClosed(e);
122    }
123
124    private void UpdateSuggestedInstancesCombobox() {
125      SuspendRepaint();
126      try {
127        var prevSelection = (IAlgorithm)suggestedInstancesComboBox.SelectedItem;
128        var prevNewIndex = -1;
129        suggestedInstancesComboBox.Items.Clear();
130        if (Content == null) return;
131
132        for (var i = 0; i < Content.SuggestedInstances.Count; i++) {
133          suggestedInstancesComboBox.Items.Add(Content.SuggestedInstances[i]);
134          if (prevSelection == null || Content.SuggestedInstances[i].Name == prevSelection.Name)
135            prevNewIndex = prevSelection == null ? 0 : i;
136        }
137        if (prevNewIndex >= 0) {
138          suggestedInstancesComboBox.SelectedIndex = prevNewIndex;
139        }
140      } finally { ResumeRepaint(true); }
141    }
142
143    #region Event Handlers
144    #region Content events
145    private void Content_PropertyChanged(object sender, PropertyChangedEventArgs e) {
146      if (InvokeRequired) {
147        Invoke((Action<object, PropertyChangedEventArgs>)Content_PropertyChanged, sender, e);
148        return;
149      }
150      SuppressEvents = true;
151      try {
152        switch (e.PropertyName) {
153          case "MaximumEvaluations": maxEvaluationsTextBox.Text = Content.MaximumEvaluations.ToString(); break;
154          case "Runs": runsView.Content = Content.Runs; break;
155          case "KnowledgeBase": okbRunCollectionView.Content = Content.KnowledgeBase; break;
156          case "Problem": problemViewHost.Content = Content.Problem; break;
157        }
158      } finally { SuppressEvents = false; }
159    }
160
161    private void SuggestedInstancesOnChanged(object sender, EventArgs e) {
162      SuppressEvents = true;
163      try {
164        UpdateSuggestedInstancesCombobox();
165      } finally { SuppressEvents = false; }
166    }
167    #endregion
168
169    #region Control events
170    private void maxEvaluationsTextBox_Validating(object sender, CancelEventArgs e) {
171      if (SuppressEvents) return;
172      if (InvokeRequired) {
173        Invoke((Action<object, CancelEventArgs>)maxEvaluationsTextBox_Validating, sender, e);
174        return;
175      }
176      int value;
177      if (!int.TryParse(maxEvaluationsTextBox.Text, out value)) {
178        e.Cancel = !maxEvaluationsTextBox.ReadOnly && maxEvaluationsTextBox.Enabled;
179        errorProvider.SetError(maxEvaluationsTextBox, "Please enter a valid integer number.");
180      } else {
181        Content.MaximumEvaluations = value;
182        e.Cancel = false;
183        errorProvider.SetError(maxEvaluationsTextBox, null);
184      }
185    }
186
187    private void newProblemButton_Click(object sender, EventArgs e) {
188      if (problemTypeSelectorDialog == null) {
189        problemTypeSelectorDialog = new TypeSelectorDialog { Caption = "Select Problem" };
190        problemTypeSelectorDialog.TypeSelector.Caption = "Available Problems";
191        problemTypeSelectorDialog.TypeSelector.Configure(typeof(IProblem)
192          , showNotInstantiableTypes: false, showGenericTypes: false);
193      }
194      if (problemTypeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
195        try {
196          Content.Problem = (IProblem)problemTypeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
197        } catch (Exception ex) {
198          ErrorHandling.ShowErrorDialog(this, ex);
199        }
200      }
201    }
202
203    private void openProblemButton_Click(object sender, EventArgs e) {
204      openFileDialog.Title = "Open Problem";
205      if (openFileDialog.ShowDialog(this) == DialogResult.OK) {
206        newProblemButton.Enabled = openProblemButton.Enabled = false;
207        problemViewHost.Enabled = false;
208
209        ContentManager.LoadAsync(openFileDialog.FileName, delegate(IStorableContent content, Exception error) {
210          try {
211            if (error != null) throw error;
212            var problem = content as IProblem;
213            if (problem == null) {
214              var algorithm = content as IAlgorithm;
215              if (algorithm == null || algorithm.Problem == null)
216                MessageBox.Show(this, "The selected file is not a problem, nor an algorithm with a problem.", "Invalid File", MessageBoxButtons.OK, MessageBoxIcon.Error);
217              else Content.Problem = algorithm.Problem;
218            } else
219              Content.Problem = problem;
220          } catch (Exception ex) {
221            ErrorHandling.ShowErrorDialog(this, ex);
222          } finally {
223            Invoke(new Action(delegate() {
224              problemViewHost.Enabled = true;
225              newProblemButton.Enabled = openProblemButton.Enabled = true;
226            }));
227          }
228        });
229      }
230    }
231
232    private void problemTabPage_DragEnterOver(object sender, DragEventArgs e) {
233      e.Effect = DragDropEffects.None;
234      var prob = e.Data.GetData(Constants.DragDropDataFormat) as IProblem;
235      if (!ReadOnly && prob != null) {
236        if ((e.KeyState & 32) == 32) e.Effect = DragDropEffects.Link;  // ALT key
237        else if ((e.KeyState & 4) == 4) e.Effect = DragDropEffects.Move;  // SHIFT key
238        else if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
239        else if (e.AllowedEffect.HasFlag(DragDropEffects.Move)) e.Effect = DragDropEffects.Move;
240        else if (e.AllowedEffect.HasFlag(DragDropEffects.Link)) e.Effect = DragDropEffects.Link;
241      }
242    }
243
244    private void problemTabPage_DragDrop(object sender, DragEventArgs e) {
245      if (e.Effect != DragDropEffects.None) {
246        var prob = e.Data.GetData(Constants.DragDropDataFormat) as IProblem;
247        if (e.Effect.HasFlag(DragDropEffects.Copy)) prob = (IProblem)prob.Clone();
248        Content.Problem = prob;
249      }
250    }
251
252    private void suggestedInstancesComboBox_SelectedIndexChanged(object sender, EventArgs e) {
253      if (SuppressEvents) return;
254      if (InvokeRequired) { Invoke((Action<object, EventArgs>)suggestedInstancesComboBox_SelectedIndexChanged, sender, e); return; }
255      if (suggestedInstancesComboBox.SelectedIndex >= 0)
256        algorithmViewHost.Content = (IAlgorithm)suggestedInstancesComboBox.SelectedItem;
257      else algorithmViewHost.Content = null;
258    }
259    #endregion
260    #endregion
261  }
262}
Note: See TracBrowser for help on using the repository browser.