Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Persistence Test/HeuristicLab.ES/3.2/ESEditor.cs @ 3589

Last change on this file since 3589 was 2474, checked in by swagner, 15 years ago

Implemented generic EventArgs (#796)

File size: 21.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.ComponentModel;
25using System.Drawing;
26using System.Data;
27using System.Text;
28using System.Windows.Forms;
29using HeuristicLab.PluginInfrastructure;
30using HeuristicLab.Common;
31using HeuristicLab.Core;
32
33namespace HeuristicLab.ES {
34  /// <summary>
35  /// Class for visual representation of an <see cref="ES"/>.
36  /// </summary>
37  public partial class ESEditor : EditorBase {
38    private ChooseOperatorDialog chooseOperatorDialog;
39    private OperatorLibrary operatorLibrary;
40    private List<IOperator> problemInitializers;
41    private int selectedProblemInitializer;
42    private List<IOperator> solutionGenerators;
43    private int selectedSolutionGenerator;
44    private List<IOperator> mutators;
45    private int selectedMutator;
46    private List<IOperator> evaluators;
47    private int selectedEvaluator;
48    private List<IOperator> recombinators;
49    private int selectedRecombinator;
50
51    /// <summary>
52    /// Gets or sets the evolution strategy to display.
53    /// </summary>
54    /// <remarks>Uses property <see cref="ViewBase.Item"/> of base class <see cref="EditorBase"/>.
55    /// No own data storage present.</remarks>
56    public ES ES {
57      get { return (ES)Item; }
58      set { base.Item = value; }
59    }
60
61    /// <summary>
62    /// Initializes a new instance of <see cref="ESEditor"/>.
63    /// </summary>
64    public ESEditor() {
65      InitializeComponent();
66      problemInitializers = new List<IOperator>();
67      selectedProblemInitializer = -1;
68      solutionGenerators = new List<IOperator>();
69      selectedSolutionGenerator = -1;
70      mutators = new List<IOperator>();
71      selectedMutator = -1;
72      evaluators = new List<IOperator>();
73      selectedEvaluator = -1;
74      recombinators = new List<IOperator>();
75      selectedRecombinator = -1;
76    }
77    /// <summary>
78    /// Initializes a new instance of <see cref="ESEditor"/> with the given <paramref name="es"/>.
79    /// </summary>
80    /// <param name="es">The evolution strategy to display.</param>
81    public ESEditor(ES es)
82      : this() {
83      ES = es;
84    }
85
86    private int AddOperator(ComboBox comboBox, IOperator iOperator, List<IOperator> list) {
87      for (int i = 0; i < comboBox.Items.Count - 1; i++) {
88        if ((comboBox.Items[i] as string).CompareTo(iOperator.Name) > 0) {
89          comboBox.Items.Insert(i, iOperator.Name);
90          list.Insert(i, iOperator);
91          return i;
92        }
93      }
94      int index = comboBox.Items.Count - 1;
95      comboBox.Items.Insert(index, iOperator.Name);
96      list.Add(iOperator);
97      return index;
98    }
99    private int SetOperator(ComboBox comboBox, IOperator iOperator, List<IOperator> list) {
100      int index;
101      if ((index = list.FindIndex(op => op.Name.Equals(iOperator.Name))) >= 0) {
102        comboBox.Items.RemoveAt(index);
103        list.RemoveAt(index);
104        return AddOperator(comboBox, iOperator, list);
105      } else return -1;
106    }
107
108    /// <summary>
109    /// Removes all event handlers from the underlying <see cref="ES"/>.
110    /// </summary>
111    /// <remarks>Calls <see cref="ViewBase.RemoveItemEvents"/> of base class <see cref="EditorBase"/>.</remarks>
112    protected override void RemoveItemEvents() {
113      ES.Engine.ExceptionOccurred -= new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
114      ES.Engine.Finished -= new EventHandler(Engine_Finished);
115      ES.Changed -= new EventHandler(ES_Changed);
116      scopeView.Scope = null;
117      base.RemoveItemEvents();
118    }
119    /// <summary>
120    /// Adds event handlers to the underlying <see cref="ES"/>.
121    /// </summary>
122    /// <remarks>Calls <see cref="ViewBase.AddItemEvents"/> of base class <see cref="EditorBase"/>.</remarks>
123    protected override void AddItemEvents() {
124      base.AddItemEvents();
125      ES.Engine.ExceptionOccurred += new EventHandler<EventArgs<Exception>>(Engine_ExceptionOccurred);
126      ES.Engine.Finished += new EventHandler(Engine_Finished);
127      ES.Changed += new EventHandler(ES_Changed);
128      SetDataBinding();
129      scopeView.Scope = ES.Engine.GlobalScope;
130    }
131
132    void ES_Changed(object sender, EventArgs e) {
133      // neither Refresh() nor Update() work
134      randomSeedTextBox.Text = ES.Seed.ToString();
135      muTextBox.Text = ES.Mu.ToString();
136      rhoTextBox.Text = ES.Rho.ToString();
137      lambdaTextBox.Text = ES.Lambda.ToString();
138      learningRateTextBox.Text = ES.LearningRate.ToString();
139      generalLearningRateTextBox.Text = ES.GeneralLearningRate.ToString();
140    }
141
142    /// <summary>
143    /// Updates all controls with the latest data of the model.
144    /// </summary>
145    /// <remarks>Calls <see cref="ViewBase.UpdateControls"/> of base class <see cref="EditorBase"/>.</remarks>
146    protected override void UpdateControls() {
147      base.UpdateControls();
148      if (ES == null) {
149        tabControl.Enabled = false;
150      } else {
151        tabControl.Enabled = true;
152        int index;
153        if (!((index = problemInitializers.FindIndex(op => op.Name.Equals(ES.ProblemInjector.Name))) >= 0)) {
154          index = AddOperator(problemInitializationComboBox, ES.ProblemInjector, problemInitializers);
155          if (index <= selectedProblemInitializer) selectedProblemInitializer++;
156        }
157        problemInitializationComboBox.SelectedIndex = index;
158        if (!((index = solutionGenerators.FindIndex(op => op.Name.Equals(ES.SolutionGenerator.Name))) >= 0)) {
159          index = AddOperator(solutionGenerationComboBox, ES.SolutionGenerator, solutionGenerators);
160          if (index <= selectedSolutionGenerator) selectedSolutionGenerator++;
161        }
162        solutionGenerationComboBox.SelectedIndex = index;
163        if (!((index = evaluators.FindIndex(op => op.Name.Equals(ES.Evaluator.Name))) >= 0)) {
164          index = AddOperator(evaluationComboBox, ES.Evaluator, evaluators);
165          if (index <= selectedEvaluator) selectedEvaluator++;
166        }
167        evaluationComboBox.SelectedIndex = index;
168        if (!((index = mutators.FindIndex(op => op.Name.Equals(ES.Mutator.Name))) >= 0)) {
169          index = AddOperator(mutationComboBox, ES.Mutator, mutators);
170          if (index <= selectedMutator) selectedMutator++;
171        }
172        mutationComboBox.SelectedIndex = index;
173        if (!((index = recombinators.FindIndex(op => op.Name.Equals(ES.Recombinator.Name))) >= 0)) {
174          index = AddOperator(recombinationComboBox, ES.Recombinator, recombinators);
175          if (index <= selectedRecombinator) selectedRecombinator++;
176        }
177        recombinationComboBox.SelectedIndex = index;
178        plusRadioButton.Checked = ES.PlusNotation;
179        commaRadioButton.Checked = !ES.PlusNotation;
180      }
181    }
182
183    private void SetDataBinding() {
184      setRandomSeedRandomlyCheckBox.DataBindings.Add("Checked", ES, "SetSeedRandomly");
185      randomSeedTextBox.DataBindings.Add("Text", ES, "Seed");
186      muTextBox.DataBindings.Add("Text", ES, "Mu");
187      rhoTextBox.DataBindings.Add("Text", ES, "Rho");
188      lambdaTextBox.DataBindings.Add("Text", ES, "Lambda");
189      maximumGenerationsTextBox.DataBindings.Add("Text", ES, "MaximumGenerations");
190      shakingFactorsLowerBoundTextBox.DataBindings.Add("Text", ES, "ShakingFactorsMin");
191      shakingFactorsUpperBoundTextBox.DataBindings.Add("Text", ES, "ShakingFactorsMax");
192      problemDimensionTextBox.DataBindings.Add("Text", ES, "ProblemDimension");
193      generalLearningRateTextBox.DataBindings.Add("Text", ES, "GeneralLearningRate");
194      learningRateTextBox.DataBindings.Add("Text", ES, "LearningRate");
195    }
196
197    #region Button Events
198    private void viewProblemInitializationButton_Click(object sender, EventArgs e) {
199      IView view = ES.ProblemInjector.CreateView();
200      if (view != null)
201        PluginManager.ControlManager.ShowControl(view);
202    }
203    private void viewSolutionGenerationButton_Click(object sender, EventArgs e) {
204      IView view = ES.SolutionGenerator.CreateView();
205      if (view != null)
206        PluginManager.ControlManager.ShowControl(view);
207    }
208    private void viewMutationButton_Click(object sender, EventArgs e) {
209      IView view = ES.Mutator.CreateView();
210      if (view != null)
211        PluginManager.ControlManager.ShowControl(view);
212    }
213    private void viewEvaluationButton_Click(object sender, EventArgs e) {
214      IView view = ES.Evaluator.CreateView();
215      if (view != null)
216        PluginManager.ControlManager.ShowControl(view);
217    }
218    private void viewRecombinationButton_Click(object sender, EventArgs e) {
219      IView view = ES.Recombinator.CreateView();
220      if (view != null)
221        PluginManager.ControlManager.ShowControl(view);
222    }
223    private void setProblemInitializationButton_Click(object sender, EventArgs e) {
224     
225    }
226    private void executeButton_Click(object sender, EventArgs e) {
227      executeButton.Enabled = false;
228      abortButton.Enabled = true;
229      ES.Engine.Execute();
230    }
231    private void abortButton_Click(object sender, EventArgs e) {
232      ES.Engine.Abort();
233    }
234    private void resetButton_Click(object sender, EventArgs e) {
235      ES.Engine.Reset();
236    }
237    private void cloneEngineButton_Click(object sender, EventArgs e) {
238      IEngine clone = (IEngine)ES.Engine.Clone();
239      IEditor editor = ((IEditable)clone).CreateEditor();
240      PluginManager.ControlManager.ShowControl(editor);
241    }
242    #endregion
243
244    #region Engine Events
245    private delegate void OnExceptionEventDelegate(object sender, EventArgs<Exception> e);
246    private void Engine_ExceptionOccurred(object sender, EventArgs<Exception> e) {
247      if (InvokeRequired)
248        Invoke(new OnExceptionEventDelegate(Engine_ExceptionOccurred), sender, e);
249      else
250        Auxiliary.ShowErrorMessageBox(e.Value);
251    }
252    private void Engine_Finished(object sender, EventArgs e) {
253      scopeView.Refresh();
254      if (executeButton.InvokeRequired) {
255        executeButton.Invoke(new MethodInvoker(EnableExecute));
256      } else {
257        executeButton.Enabled = true;
258        abortButton.Enabled = false;
259      }
260    }
261    private void EnableExecute() {
262      executeButton.Enabled = true;
263      abortButton.Enabled = false;
264    }
265    #endregion
266
267    #region RadioButton Events
268    private void plusRadioButton_CheckedChanged(object sender, EventArgs e) {
269      if (plusRadioButton.Checked) ES.PlusNotation = true;
270    }
271
272    private void commaRadioButton_CheckedChanged(object sender, EventArgs e) {
273      if (commaRadioButton.Checked) ES.PlusNotation = false;
274    }
275    #endregion
276
277    private void problemDimensionTextBox_Validated(object sender, EventArgs e) {
278      UpdateLearningRates();
279      Refresh();
280    }
281
282    private void UpdateLearningRates() {
283      if (ES != null) {
284        int dimension = int.Parse(problemDimensionTextBox.Text);
285        ES.GeneralLearningRate = 1 / Math.Sqrt(2 * dimension);
286        ES.LearningRate = 1 / Math.Sqrt(2 * Math.Sqrt(dimension));
287      }
288    }
289
290    private void openOperatorLibraryButton_Click(object sender, EventArgs e) {
291      if (openOperatorLibraryFileDialog.ShowDialog() == DialogResult.OK) {
292
293        operatorLibrary = (PersistenceManager.Load(openOperatorLibraryFileDialog.FileName) as OperatorLibrary);
294        if (operatorLibrary == null) {
295          MessageBox.Show("The selected file is not an operator library");
296          return;
297        }
298        foreach (IOperatorGroup topLevelGroup in operatorLibrary.Group.SubGroups) {
299          if (topLevelGroup.Name.Equals("Problem")) {
300            foreach (IOperatorGroup group in topLevelGroup.SubGroups) {
301              if (group.Name.Equals("Initialization")) {
302                foreach (IOperator op in group.Operators) {
303                  int index = SetOperator(problemInitializationComboBox, (IOperator)op.Clone(), problemInitializers);
304                  if (index < 0) {
305                    index = AddOperator(problemInitializationComboBox, (IOperator)op.Clone(), problemInitializers);
306                    if (index <= selectedProblemInitializer) selectedProblemInitializer++;
307                  }
308                }
309              } else if (group.Name.Equals("Solution generation")) {
310                foreach (IOperator op in group.Operators) {
311                  int index = SetOperator(solutionGenerationComboBox, (IOperator)op.Clone(), solutionGenerators);
312                  if (index < 0) {
313                    index = AddOperator(solutionGenerationComboBox, (IOperator)op.Clone(), solutionGenerators);
314                    if (index <= selectedSolutionGenerator) selectedSolutionGenerator++;
315                  }
316                }
317              } else if (group.Name.Equals("Evaluation")) {
318                foreach (IOperator op in group.Operators) {
319                  int index = SetOperator(evaluationComboBox, (IOperator)op.Clone(), evaluators);
320                  if (index < 0) {
321                    index = AddOperator(evaluationComboBox, (IOperator)op.Clone(), evaluators);
322                    if (index <= selectedEvaluator) selectedEvaluator++;
323                  }
324                }
325              }
326            }
327          } else if (topLevelGroup.Name.Equals("ES")) {
328            foreach (IOperatorGroup group in topLevelGroup.SubGroups) {
329              if (group.Name.Equals("Mutation")) {
330                foreach (IOperator op in group.Operators) {
331                  int index = SetOperator(mutationComboBox, (IOperator)op.Clone(), mutators);
332                  if (index < 0) {
333                    index = AddOperator(mutationComboBox, (IOperator)op.Clone(), mutators);
334                    if (index <= selectedMutator) selectedMutator++;
335                  }
336                }
337              } else if (group.Name.Equals("Recombination")) {
338                foreach (IOperator op in group.Operators) {
339                  int index = SetOperator(recombinationComboBox, (IOperator)op.Clone(), recombinators);
340                  if (index < 0) {
341                    index = AddOperator(recombinationComboBox, (IOperator)op.Clone(), recombinators);
342                    if (index <= selectedRecombinator) selectedRecombinator++;
343                  }
344                }
345              }
346            }
347          }
348        }
349        problemInitializationComboBox.SelectedIndexChanged -= new EventHandler(problemInitializationComboBox_SelectedIndexChanged);
350        problemInitializationComboBox.SelectedIndex = selectedProblemInitializer;
351        problemInitializationComboBox.SelectedIndexChanged += new EventHandler(problemInitializationComboBox_SelectedIndexChanged);
352        solutionGenerationComboBox.SelectedIndexChanged -= new EventHandler(solutionGenerationComboBox_SelectedIndexChanged);
353        solutionGenerationComboBox.SelectedIndex = selectedSolutionGenerator;
354        solutionGenerationComboBox.SelectedIndexChanged += new EventHandler(solutionGenerationComboBox_SelectedIndexChanged);
355        evaluationComboBox.SelectedIndexChanged -= new EventHandler(evaluationComboBox_SelectedIndexChanged);
356        evaluationComboBox.SelectedIndex = selectedEvaluator;
357        evaluationComboBox.SelectedIndexChanged += new EventHandler(evaluationComboBox_SelectedIndexChanged);
358        mutationComboBox.SelectedIndexChanged -= new EventHandler(mutationComboBox_SelectedIndexChanged);
359        mutationComboBox.SelectedIndex = selectedMutator;
360        mutationComboBox.SelectedIndexChanged += new EventHandler(mutationComboBox_SelectedIndexChanged);
361        recombinationComboBox.SelectedIndexChanged -= new EventHandler(recombinationComboBox_SelectedIndexChanged);
362        recombinationComboBox.SelectedIndex = selectedRecombinator;
363        recombinationComboBox.SelectedIndexChanged += new EventHandler(recombinationComboBox_SelectedIndexChanged);
364      }
365    }
366
367    private void problemInitializationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
368      int index = problemInitializationComboBox.SelectedIndex;
369      if (index != selectedProblemInitializer) {
370        if (index == problemInitializationComboBox.Items.Count - 1) {
371          if (chooseOperatorDialog == null) chooseOperatorDialog = new ChooseOperatorDialog();
372          if (chooseOperatorDialog.ShowDialog(this) == DialogResult.OK) {
373            selectedProblemInitializer = -1;
374            index = SetOperator(problemInitializationComboBox, chooseOperatorDialog.Operator, problemInitializers);
375            if (index < 0) index = AddOperator(problemInitializationComboBox, chooseOperatorDialog.Operator, problemInitializers);
376          } else {
377            problemInitializationComboBox.SelectedIndex = selectedProblemInitializer;
378            return;
379          }
380        }
381        if (index >= 0) {
382          ES.ProblemInjector = problemInitializers[index];
383          selectedProblemInitializer = index;
384          problemInitializationComboBox.SelectedIndex = index;
385        }
386      }
387    }
388
389    private void solutionGenerationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
390      int index = solutionGenerationComboBox.SelectedIndex;
391      if (index != selectedSolutionGenerator) {
392        if (index == solutionGenerationComboBox.Items.Count - 1) {
393          if (chooseOperatorDialog == null) chooseOperatorDialog = new ChooseOperatorDialog();
394          if (chooseOperatorDialog.ShowDialog(this) == DialogResult.OK) {
395            selectedSolutionGenerator = -1;
396            index = SetOperator(solutionGenerationComboBox, chooseOperatorDialog.Operator, solutionGenerators);
397            if (index < 0) AddOperator(solutionGenerationComboBox, chooseOperatorDialog.Operator, solutionGenerators);
398          } else {
399            solutionGenerationComboBox.SelectedIndex = selectedSolutionGenerator;
400            return;
401          }
402        }
403        if (index >= 0) {
404          ES.SolutionGenerator = solutionGenerators[index];
405          selectedSolutionGenerator = index;
406          solutionGenerationComboBox.SelectedIndex = selectedSolutionGenerator;
407        }
408      }
409    }
410
411    private void evaluationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
412      int index = evaluationComboBox.SelectedIndex;
413      if (index != selectedEvaluator) {
414        if (index == evaluationComboBox.Items.Count - 1) {
415          if (chooseOperatorDialog == null) chooseOperatorDialog = new ChooseOperatorDialog();
416          if (chooseOperatorDialog.ShowDialog(this) == DialogResult.OK) {
417            selectedEvaluator = -1;
418            index = SetOperator(evaluationComboBox, chooseOperatorDialog.Operator, evaluators);
419            if (index < 0) index = AddOperator(evaluationComboBox, chooseOperatorDialog.Operator, evaluators);
420          } else {
421            evaluationComboBox.SelectedIndex = selectedEvaluator;
422            return;
423          }
424        }
425        if (index >= 0) {
426          ES.Evaluator = evaluators[index];
427          selectedEvaluator = index;
428          evaluationComboBox.SelectedIndex = index;
429        }
430      }
431    }
432
433    private void mutationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
434      int index = mutationComboBox.SelectedIndex;
435      if (index != selectedMutator) {
436        if (index == mutationComboBox.Items.Count - 1) {
437          if (chooseOperatorDialog == null) chooseOperatorDialog = new ChooseOperatorDialog();
438          if (chooseOperatorDialog.ShowDialog(this) == DialogResult.OK) {
439            selectedMutator = -1;
440            index = SetOperator(mutationComboBox, chooseOperatorDialog.Operator, mutators);
441            if (index < 0) index = AddOperator(mutationComboBox, chooseOperatorDialog.Operator, mutators);
442          } else {
443            mutationComboBox.SelectedIndex = selectedMutator;
444            return;
445          }
446        }
447        if (index >= 0) {
448          ES.Mutator = mutators[index];
449          selectedMutator = index;
450          mutationComboBox.SelectedIndex = index;
451        }
452      }
453    }
454
455    private void recombinationComboBox_SelectedIndexChanged(object sender, EventArgs e) {
456      int index = recombinationComboBox.SelectedIndex;
457      if (index != selectedRecombinator) {
458        if (index == recombinationComboBox.Items.Count - 1) {
459          if (chooseOperatorDialog == null) chooseOperatorDialog = new ChooseOperatorDialog();
460          if (chooseOperatorDialog.ShowDialog(this) == DialogResult.OK) {
461            selectedRecombinator = -1;
462            index = SetOperator(recombinationComboBox, chooseOperatorDialog.Operator, recombinators);
463            if (index < 0) index = AddOperator(recombinationComboBox, chooseOperatorDialog.Operator, recombinators);
464          } else {
465            recombinationComboBox.SelectedIndex = selectedRecombinator;
466            return;
467          }
468        }
469        if (index >= 0) {
470          ES.Recombinator = recombinators[index];
471          selectedRecombinator = index;
472          recombinationComboBox.SelectedIndex = index;
473        }
474      }
475    }
476  }
477}
Note: See TracBrowser for help on using the repository browser.