Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RuntimeOptimizer/HeuristicLab.Optimizer/3.3/CreateExperimentDialog.cs @ 8975

Last change on this file since 8975 was 8975, checked in by abeham, 12 years ago

#1985:

  • Moved arithmetic progression dialog to MainForm (created a folder dialogs)
  • Added a button to generate such a progression for snapshot times
  • Changed TimeLimitRun to react on ExecutionTimeChanged instead of maintaining its own timers
  • Changed to allow manual snapshoting only during Paused state
  • Perform a pause + snapshot when terminating the algorithm instead of stop + snapshot (allows the algorithm in the final snapshot to continue running if the option was selected)
File size: 37.8 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.Collections.Generic;
24using System.ComponentModel;
25using System.Globalization;
26using System.Linq;
27using System.Text;
28using System.Threading;
29using System.Windows.Forms;
30using HeuristicLab.Core;
31using HeuristicLab.Data;
32using HeuristicLab.MainForm.WindowsForms;
33using HeuristicLab.Optimization;
34using HeuristicLab.Parameters;
35using HeuristicLab.Problems.Instances;
36
37namespace HeuristicLab.Optimizer {
38  public partial class CreateExperimentDialog : Form {
39    private enum DialogMode { Normal = 1, DiscoveringInstances = 2, CreatingExperiment = 3, PreparingExperiment = 4 };
40
41    private IOptimizer optimizer;
42    public IOptimizer Optimizer {
43      get { return optimizer; }
44      set {
45        optimizer = value;
46        Experiment = null;
47        okButton.Enabled = optimizer != null;
48        SetTabControlVisibility();
49        FillInstanceTreeViewAsync();
50        FillParametersListView();
51      }
52    }
53
54    public Experiment Experiment { get; private set; }
55
56    private bool createBatchRun;
57    private int repetitions;
58    private Dictionary<IProblemInstanceProvider, HashSet<IDataDescriptor>> instances;
59    private Dictionary<IValueParameter, IntArray> intParameters;
60    private Dictionary<IValueParameter, DoubleArray> doubleParameters;
61    private HashSet<IValueParameter> boolParameters;
62    private Dictionary<IValueParameter, HashSet<IItem>> multipleChoiceParameters;
63    private IItem optionalNullChoice = new BoolValue(); // any item will do
64
65    private StringBuilder failedInstances;
66    private EventWaitHandle backgroundWorkerWaitHandle = new ManualResetEvent(false);
67    private bool suppressTreeViewEventHandling, suppressCheckAllNoneEventHandling;
68
69    public CreateExperimentDialog() : this(null) { }
70    public CreateExperimentDialog(IOptimizer optimizer) {
71      InitializeComponent();
72      instanceDiscoveryProgressLabel.BackColor = instancesTabPage.BackColor;
73      createBatchRun = createBatchRunCheckBox.Checked;
74      repetitions = (int)repetitionsNumericUpDown.Value;
75      // do not set the Optimizer property here, because we want to delay instance discovery to the time when the form loads
76      this.optimizer = optimizer;
77      Experiment = null;
78      okButton.Enabled = optimizer != null;
79
80      instances = new Dictionary<IProblemInstanceProvider, HashSet<IDataDescriptor>>();
81      intParameters = new Dictionary<IValueParameter, IntArray>();
82      doubleParameters = new Dictionary<IValueParameter, DoubleArray>();
83      boolParameters = new HashSet<IValueParameter>();
84      multipleChoiceParameters = new Dictionary<IValueParameter, HashSet<IItem>>();
85    }
86
87    #region Event handlers
88    private void CreateExperimentDialog_Load(object sender, EventArgs e) {
89      SetTabControlVisibility();
90      FillInstanceTreeViewAsync();
91      FillParametersListView();
92    }
93
94    private void CreateExperimentDialog_FormClosing(object sender, FormClosingEventArgs e) {
95      if (experimentCreationBackgroundWorker.IsBusy) {
96        if (DialogResult != System.Windows.Forms.DialogResult.OK) {
97          if (experimentCreationBackgroundWorker.IsBusy) experimentCreationBackgroundWorker.CancelAsync();
98          if (instanceDiscoveryBackgroundWorker.IsBusy) instanceDiscoveryBackgroundWorker.CancelAsync();
99        }
100        e.Cancel = true;
101      }
102    }
103
104    private void okButton_Click(object sender, EventArgs e) {
105      SetMode(DialogMode.CreatingExperiment);
106      experimentCreationBackgroundWorker.RunWorkerAsync();
107      backgroundWorkerWaitHandle.WaitOne(); // make sure the background worker has started before exiting
108    }
109
110    #region Parameters variation
111    private void parametersListView_ItemChecked(object sender, ItemCheckedEventArgs e) {
112      var parameter = (IValueParameter)e.Item.Tag;
113      var isConstrainedValueParameter = typeof(OptionalConstrainedValueParameter<>).Equals(parameter.GetType().GetGenericTypeDefinition())
114        || typeof(ConstrainedValueParameter<>).Equals(parameter.GetType().GetGenericTypeDefinition());
115
116      if (!isConstrainedValueParameter && parameter.Value == null) {
117        if (e.Item.Checked) e.Item.Checked = false;
118        return;
119      }
120
121      if (isConstrainedValueParameter) {
122        if (e.Item.Checked) multipleChoiceParameters.Add(parameter, new HashSet<IItem>());
123        else multipleChoiceParameters.Remove(parameter);
124      }
125
126      var intValue = parameter.Value as ValueTypeValue<int>;
127      if (intValue != null) {
128        if (e.Item.Checked) {
129          IntArray initialValues;
130          if (intValue.Value == int.MinValue)
131            initialValues = new IntArray(new int[] { -100, -50, 5 });
132          else if (intValue.Value == int.MaxValue)
133            initialValues = new IntArray(new int[] { 5, 50, 100 });
134          else if (intValue.Value == 0)
135            initialValues = new IntArray(new int[] { 0, 1, 2 });
136          else if (Math.Abs(intValue.Value) < 10)
137            initialValues = new IntArray(new int[] { intValue.Value - 1, intValue.Value, intValue.Value + 1 });
138          else initialValues = new IntArray(new int[] { intValue.Value / 2, intValue.Value, intValue.Value * 2 });
139          intParameters.Add(parameter, initialValues);
140          intParameters[parameter].Reset += new EventHandler(ValuesArray_Reset);
141        } else intParameters.Remove(parameter);
142      }
143
144      var doubleValue = parameter.Value as ValueTypeValue<double>;
145      if (doubleValue != null) {
146        if (e.Item.Checked) {
147          DoubleArray initialValues;
148          if (doubleValue.Value == double.MinValue)
149            initialValues = new DoubleArray(new double[] { -1, -0.5, 0 });
150          else if (doubleValue.Value == double.MaxValue)
151            initialValues = new DoubleArray(new double[] { 0, 0.5, 1 });
152          else if (doubleValue.Value == 0.0)
153            initialValues = new DoubleArray(new double[] { 0, 0.1, 0.2 });
154          else if (Math.Abs(doubleValue.Value) <= 1.0) {
155            if (doubleValue.Value > 0.9 || (doubleValue.Value < 0.0 && doubleValue.Value > -0.1))
156              initialValues = new DoubleArray(new double[] { doubleValue.Value - 0.2, doubleValue.Value - 0.1, doubleValue.Value });
157            else if (doubleValue.Value < -0.9 || (doubleValue.Value > 0 && doubleValue.Value < 0.1))
158              initialValues = new DoubleArray(new double[] { doubleValue.Value, doubleValue.Value + 0.1, doubleValue.Value + 0.2 });
159            else initialValues = new DoubleArray(new double[] { doubleValue.Value - 0.1, doubleValue.Value, doubleValue.Value + 0.1 });
160          } else initialValues = new DoubleArray(new double[] { doubleValue.Value / 2.0, doubleValue.Value, doubleValue.Value * 2.0 });
161          doubleParameters.Add(parameter, initialValues);
162          doubleParameters[parameter].Reset += new EventHandler(ValuesArray_Reset);
163        } else doubleParameters.Remove(parameter);
164      }
165
166      var boolValue = parameter.Value as ValueTypeValue<bool>;
167      if (boolValue != null) {
168        if (e.Item.Checked) boolParameters.Add(parameter);
169        else boolParameters.Remove(parameter);
170      }
171
172      UpdateVariationsLabel();
173      if (e.Item.Selected) UpdateDetailsView(parameter);
174      else e.Item.Selected = true;
175    }
176
177    private void parametersListView_SelectedIndexChanged(object sender, EventArgs e) {
178      if (parametersListView.SelectedItems.Count == 0) {
179        ClearDetailsView();
180      } else {
181        var parameter = parametersListView.SelectedItems[0].Tag as IValueParameter;
182        UpdateDetailsView(parameter);
183      }
184    }
185
186    private void UpdateDetailsView(IValueParameter parameter) {
187      ClearDetailsView();
188
189      var isOptionalConstrainedValueParameter = typeof(OptionalConstrainedValueParameter<>).IsAssignableFrom(parameter.GetType().GetGenericTypeDefinition());
190      var isConstrainedValueParameter =
191        isOptionalConstrainedValueParameter
192        || typeof(ConstrainedValueParameter<>).Equals(parameter.GetType().GetGenericTypeDefinition());
193
194      if (isConstrainedValueParameter) {
195        detailsTypeLabel.Text = "Choices:";
196        choicesListView.Tag = parameter;
197
198        if (isOptionalConstrainedValueParameter) {
199          choicesListView.Items.Add(new ListViewItem("-") {
200            Tag = optionalNullChoice,
201            Checked = multipleChoiceParameters.ContainsKey(parameter)
202            && multipleChoiceParameters[parameter].Contains(optionalNullChoice)
203          });
204        }
205        dynamic constrainedValuedParameter = parameter;
206        dynamic validValues = constrainedValuedParameter.ValidValues;
207        foreach (var choice in validValues) {
208          choicesListView.Items.Add(new ListViewItem(choice.ToString()) {
209            Tag = choice,
210            Checked = multipleChoiceParameters.ContainsKey(parameter)
211            && multipleChoiceParameters[parameter].Contains(choice)
212          });
213        }
214        choicesListView.Enabled = multipleChoiceParameters.ContainsKey(parameter);
215        detailsTypeLabel.Visible = true;
216        choicesListView.Visible = true;
217        return;
218      }
219
220      if (parameter.Value is ValueTypeValue<bool>) {
221        detailsTypeLabel.Text = "Boolean parameter: True / False";
222        detailsTypeLabel.Visible = true;
223      }
224
225      var intValue = parameter.Value as ValueTypeValue<int>;
226      if (intValue != null) {
227        if (intParameters.ContainsKey(parameter))
228          stringConvertibleArrayView.Content = intParameters[parameter];
229        stringConvertibleArrayView.Visible = true;
230        stringConvertibleArrayView.ReadOnly = !intParameters.ContainsKey(parameter);
231        generateButton.Tag = parameter;
232        generateButton.Enabled = intParameters.ContainsKey(parameter);
233        generateButton.Visible = true;
234        return;
235      }
236
237      var doubleValue = parameter.Value as ValueTypeValue<double>;
238      if (doubleValue != null) {
239        if (doubleParameters.ContainsKey(parameter))
240          stringConvertibleArrayView.Content = doubleParameters[parameter];
241        stringConvertibleArrayView.Visible = true;
242        stringConvertibleArrayView.ReadOnly = !doubleParameters.ContainsKey(parameter);
243        generateButton.Tag = parameter;
244        generateButton.Enabled = doubleParameters.ContainsKey(parameter);
245        generateButton.Visible = true;
246        return;
247      }
248    }
249
250    #region Detail controls
251    private void choiceListView_ItemChecked(object sender, ItemCheckedEventArgs e) {
252      var parameter = (IValueParameter)choicesListView.Tag;
253      if (multipleChoiceParameters.ContainsKey(parameter)) {
254        if (e.Item.Checked) {
255          multipleChoiceParameters[parameter].Add((IItem)e.Item.Tag);
256        } else multipleChoiceParameters[parameter].Remove((IItem)e.Item.Tag);
257
258        UpdateVariationsLabel();
259      }
260    }
261
262    private void generateButton_Click(object sender, EventArgs e) {
263      var parameter = (IValueParameter)generateButton.Tag;
264      bool integerOnly = intParameters.ContainsKey(parameter);
265      double min = 0, max = 1, step = 1;
266      #region Try to calculate some meaningful values
267      if (integerOnly) {
268        int len = intParameters[parameter].Length;
269        if (len > 0) {
270          min = intParameters[parameter].Min();
271          max = intParameters[parameter].Max();
272          step = len >= 2 ? Math.Abs((intParameters[parameter][len - 1] - intParameters[parameter][len - 2])) : 1;
273        }
274      } else {
275        int len = doubleParameters[parameter].Length;
276        if (len > 0) {
277          min = doubleParameters[parameter].Min();
278          max = doubleParameters[parameter].Max();
279          step = len >= 2 ? Math.Abs((doubleParameters[parameter][len - 1] - doubleParameters[parameter][len - 2])) : 1;
280        }
281      }
282      #endregion
283      using (var dialog = new DefineArithmeticProgressionDialog(integerOnly, min, max, step)) {
284        if (dialog.ShowDialog(this) == DialogResult.OK) {
285          var values = dialog.Values;
286          if (integerOnly) {
287            intParameters[parameter].Reset -= new EventHandler(ValuesArray_Reset);
288            intParameters[parameter] = new IntArray(values.Select(x => (int)x).ToArray());
289            intParameters[parameter].Reset += new EventHandler(ValuesArray_Reset);
290            stringConvertibleArrayView.Content = intParameters[parameter];
291          } else {
292            doubleParameters[parameter].Reset -= new EventHandler(ValuesArray_Reset);
293            doubleParameters[parameter] = new DoubleArray(values.ToArray());
294            doubleParameters[parameter].Reset += new EventHandler(ValuesArray_Reset);
295            stringConvertibleArrayView.Content = doubleParameters[parameter];
296          }
297          UpdateVariationsLabel();
298        }
299      }
300    }
301
302    private void ValuesArray_Reset(object sender, EventArgs e) {
303      UpdateVariationsLabel();
304    }
305    #endregion
306    #endregion
307
308    #region Instances
309    private void instancesTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
310      if (!suppressTreeViewEventHandling) {
311        if (e.Node.Nodes.Count > 0) { // provider node was (un)checked
312          SyncProviderNode(e.Node);
313        } else { // descriptor node was (un)checked
314          SyncInstanceNode(e.Node);
315        }
316
317        suppressCheckAllNoneEventHandling = true;
318        try {
319          var treeViewNodes = instancesTreeView.Nodes.OfType<TreeNode>().SelectMany(x => x.Nodes.OfType<TreeNode>());
320          selectAllCheckBox.Checked = treeViewNodes.Count() == instances.SelectMany(x => x.Value).Count();
321          selectNoneCheckBox.Checked = !treeViewNodes.Any(x => x.Checked);
322        } finally { suppressCheckAllNoneEventHandling = false; }
323        UpdateVariationsLabel();
324      }
325    }
326
327    private void SyncProviderNode(TreeNode node) {
328      suppressTreeViewEventHandling = true;
329      try {
330        foreach (TreeNode n in node.Nodes) {
331          if (n.Checked != node.Checked) {
332            n.Checked = node.Checked;
333            SyncInstanceNode(n, false);
334          }
335        }
336      } finally { suppressTreeViewEventHandling = false; }
337    }
338
339    private void SyncInstanceNode(TreeNode node, bool providerCheck = true) {
340      var provider = (IProblemInstanceProvider)node.Parent.Tag;
341      var descriptor = (IDataDescriptor)node.Tag;
342      if (node.Checked) {
343        if (!instances.ContainsKey(provider))
344          instances.Add(provider, new HashSet<IDataDescriptor>());
345        instances[provider].Add(descriptor);
346      } else {
347        if (instances.ContainsKey(provider)) {
348          instances[provider].Remove(descriptor);
349          if (instances[provider].Count == 0)
350            instances.Remove(provider);
351        }
352      }
353      if (providerCheck) {
354        bool allChecked = node.Parent.Nodes.OfType<TreeNode>().All(x => x.Checked);
355        suppressTreeViewEventHandling = true;
356        try {
357          node.Parent.Checked = allChecked;
358        } finally { suppressTreeViewEventHandling = false; }
359      }
360    }
361
362    private void selectAllCheckBox_CheckedChanged(object sender, EventArgs e) {
363      if (!suppressCheckAllNoneEventHandling) {
364        if (selectAllCheckBox.Checked) {
365          suppressCheckAllNoneEventHandling = true;
366          try { selectNoneCheckBox.Checked = false; } finally { suppressCheckAllNoneEventHandling = false; }
367          try {
368            suppressTreeViewEventHandling = true;
369            foreach (TreeNode node in instancesTreeView.Nodes) {
370              if (!node.Checked) {
371                node.Checked = true;
372                SyncProviderNode(node);
373              }
374            }
375          } finally { suppressTreeViewEventHandling = false; }
376        }
377        UpdateVariationsLabel();
378      }
379    }
380
381    private void selectNoneCheckBox_CheckedChanged(object sender, EventArgs e) {
382      if (!suppressCheckAllNoneEventHandling) {
383        if (selectNoneCheckBox.Checked) {
384          suppressCheckAllNoneEventHandling = true;
385          try { selectAllCheckBox.Checked = false; } finally { suppressCheckAllNoneEventHandling = false; }
386          try {
387            suppressTreeViewEventHandling = true;
388            foreach (TreeNode node in instancesTreeView.Nodes) {
389              if (node.Checked) {
390                node.Checked = false;
391                SyncProviderNode(node);
392              }
393            }
394          } finally { suppressTreeViewEventHandling = false; }
395        }
396        UpdateVariationsLabel();
397      }
398    }
399    #endregion
400
401    private void createBatchRunCheckBox_CheckedChanged(object sender, EventArgs e) {
402      repetitionsNumericUpDown.Enabled = createBatchRunCheckBox.Checked;
403      createBatchRun = createBatchRunCheckBox.Checked;
404    }
405
406    private void repetitionsNumericUpDown_Validated(object sender, EventArgs e) {
407      if (repetitionsNumericUpDown.Text == string.Empty)
408        repetitionsNumericUpDown.Text = repetitionsNumericUpDown.Value.ToString();
409      repetitions = (int)repetitionsNumericUpDown.Value;
410    }
411
412    private void experimentsLabel_TextChanged(object sender, EventArgs e) {
413      long number;
414      if (long.TryParse(variationsLabel.Text, NumberStyles.AllowThousands, CultureInfo.CurrentCulture.NumberFormat, out number)) {
415        if (number > 1000) warningProvider.SetError(variationsLabel, "Consider reducing the number of variations!");
416        else warningProvider.SetError(variationsLabel, null);
417      }
418    }
419    #endregion
420
421    #region Helpers
422    private void SetTabControlVisibility() {
423      bool isAlgorithm = optimizer != null && optimizer is IAlgorithm;
424      bool instancesAvailable = isAlgorithm
425        && ((IAlgorithm)optimizer).Problem != null
426        && ProblemInstanceManager.GetProviders(((IAlgorithm)optimizer).Problem).Any();
427      if (instancesAvailable && tabControl.TabCount == 1)
428        tabControl.TabPages.Add(instancesTabPage);
429      else if (!instancesAvailable && tabControl.TabCount == 2)
430        tabControl.TabPages.Remove(instancesTabPage);
431      tabControl.Visible = isAlgorithm;
432      if (isAlgorithm) {
433        variationsLabel.Visible = true;
434        experimentsToCreateDescriptionLabel.Visible = true;
435        Height = 450;
436      } else {
437        variationsLabel.Visible = false;
438        experimentsToCreateDescriptionLabel.Visible = false;
439        Height = 130;
440      }
441    }
442
443    private void FillParametersListView() {
444      parametersListView.Items.Clear();
445      intParameters.Clear();
446      doubleParameters.Clear();
447      boolParameters.Clear();
448      multipleChoiceParameters.Clear();
449
450      if (Optimizer is IAlgorithm) {
451        var parameters = ((IAlgorithm)optimizer).Parameters;
452        foreach (var param in parameters) {
453          var valueParam = param as IValueParameter;
454          if (valueParam != null && (valueParam.Value is ValueTypeValue<bool>
455              || valueParam.Value is ValueTypeValue<int>
456              || valueParam.Value is ValueTypeValue<double>)
457            || typeof(OptionalConstrainedValueParameter<>).IsAssignableFrom(param.GetType().GetGenericTypeDefinition())
458            || typeof(ConstrainedValueParameter<>).IsAssignableFrom(param.GetType().GetGenericTypeDefinition()))
459            parametersListView.Items.Add(new ListViewItem(param.Name) { Tag = param });
460        }
461      }
462    }
463
464    private void FillInstanceTreeViewAsync() {
465      instances.Clear();
466      instancesTreeView.Nodes.Clear();
467
468      if (Optimizer is IAlgorithm && ((IAlgorithm)Optimizer).Problem != null) {
469        SetMode(DialogMode.DiscoveringInstances);
470        instanceDiscoveryBackgroundWorker.RunWorkerAsync();
471      }
472    }
473
474    private void AddOptimizer(IOptimizer optimizer, Experiment experiment) {
475      if (createBatchRun) {
476        var batchRun = new BatchRun(repetitions.ToString() + "x " + optimizer.Name) {
477          Repetitions = repetitions,
478          Optimizer = optimizer
479        };
480        experiment.Optimizers.Add(batchRun);
481      } else {
482        experiment.Optimizers.Add(optimizer);
483      }
484    }
485
486    private int GetNumberOfVariations() {
487      int instancesCount = 1;
488      if (instances.Values.Any())
489        instancesCount = Math.Max(instances.Values.SelectMany(x => x).Count(), 1);
490
491      int intParameterVariations = 1;
492      foreach (var intParam in intParameters.Values) {
493        intParameterVariations *= Math.Max(intParam.Length, 1);
494      }
495      int doubleParameterVariations = 1;
496      foreach (var doubleParam in doubleParameters.Values) {
497        doubleParameterVariations *= Math.Max(doubleParam.Length, 1);
498      }
499      int boolParameterVariations = 1;
500      foreach (var boolParam in boolParameters) {
501        boolParameterVariations *= 2;
502      }
503      int choiceParameterVariations = 1;
504      foreach (var choiceParam in multipleChoiceParameters.Values) {
505        choiceParameterVariations *= Math.Max(choiceParam.Count, 1);
506      }
507
508      return (instancesCount * intParameterVariations * doubleParameterVariations * boolParameterVariations * choiceParameterVariations);
509    }
510
511    private void SetMode(DialogMode mode) {
512      if (InvokeRequired) Invoke((Action<DialogMode>)SetMode, mode);
513      else {
514        createBatchRunCheckBox.Enabled = mode == DialogMode.Normal;
515        repetitionsNumericUpDown.Enabled = mode == DialogMode.Normal;
516        parametersSplitContainer.Enabled = mode == DialogMode.Normal || mode == DialogMode.DiscoveringInstances;
517        selectAllCheckBox.Enabled = mode == DialogMode.Normal;
518        selectNoneCheckBox.Enabled = mode == DialogMode.Normal;
519        instancesTreeView.Enabled = mode == DialogMode.Normal;
520        instancesTreeView.Visible = mode == DialogMode.Normal || mode == DialogMode.CreatingExperiment || mode == DialogMode.PreparingExperiment;
521        okButton.Enabled = mode == DialogMode.Normal;
522        okButton.Visible = mode != DialogMode.CreatingExperiment && mode != DialogMode.PreparingExperiment;
523        cancelButton.Enabled = mode != DialogMode.PreparingExperiment;
524        instanceDiscoveryProgressLabel.Visible = mode == DialogMode.DiscoveringInstances;
525        instanceDiscoveryProgressBar.Visible = mode == DialogMode.DiscoveringInstances;
526        experimentCreationProgressBar.Visible = mode == DialogMode.CreatingExperiment || mode == DialogMode.PreparingExperiment;
527      }
528    }
529
530    private void ClearDetailsView() {
531      stringConvertibleArrayView.Visible = false;
532      stringConvertibleArrayView.Content = null;
533      stringConvertibleArrayView.ReadOnly = true;
534      generateButton.Visible = false;
535      detailsTypeLabel.Visible = false;
536      choicesListView.Items.Clear();
537      choicesListView.Enabled = false;
538      choicesListView.Visible = false;
539    }
540
541    private void UpdateVariationsLabel() {
542      variationsLabel.Text = GetNumberOfVariations().ToString("#,#", CultureInfo.CurrentCulture);
543    }
544
545    #region Retrieve parameter combinations
546    private IEnumerable<Dictionary<IValueParameter, int>> GetIntParameterConfigurations() {
547      var configuration = new Dictionary<IValueParameter, int>();
548      var enumerators = new Dictionary<IValueParameter, IEnumerator<int>>();
549      bool finished;
550      do {
551        foreach (var p in intParameters) {
552          if (!enumerators.ContainsKey(p.Key)) {
553            enumerators[p.Key] = p.Value.GetEnumerator();
554            enumerators[p.Key].MoveNext();
555          }
556          configuration[p.Key] = enumerators[p.Key].Current;
557        }
558        yield return configuration;
559
560        finished = true;
561        foreach (var p in intParameters) {
562          if (!enumerators[p.Key].MoveNext()) {
563            enumerators[p.Key] = p.Value.GetEnumerator();
564            enumerators[p.Key].MoveNext();
565          } else {
566            finished = false;
567            break;
568          }
569        }
570      } while (!finished);
571    }
572
573    private IEnumerable<Dictionary<IValueParameter, double>> GetDoubleParameterConfigurations() {
574      var configuration = new Dictionary<IValueParameter, double>();
575      var enumerators = new Dictionary<IValueParameter, IEnumerator<double>>();
576      bool finished;
577      do {
578        foreach (var p in doubleParameters) {
579          if (!enumerators.ContainsKey(p.Key)) {
580            enumerators[p.Key] = p.Value.GetEnumerator();
581            enumerators[p.Key].MoveNext();
582          }
583          configuration[p.Key] = enumerators[p.Key].Current;
584        }
585        yield return configuration;
586
587        finished = true;
588        foreach (var p in doubleParameters) {
589          if (!enumerators[p.Key].MoveNext()) {
590            enumerators[p.Key] = p.Value.GetEnumerator();
591            enumerators[p.Key].MoveNext();
592          } else {
593            finished = false;
594            break;
595          }
596        }
597      } while (!finished);
598    }
599
600    private IEnumerable<Dictionary<IValueParameter, bool>> GetBoolParameterConfigurations() {
601      var configuration = new Dictionary<IValueParameter, bool>();
602      bool finished;
603      do {
604        finished = true;
605        foreach (var p in boolParameters) {
606          if (!configuration.ContainsKey(p)) configuration.Add(p, false);
607          else {
608            if (configuration[p]) {
609              configuration[p] = false;
610            } else {
611              configuration[p] = true;
612              finished = false;
613              break;
614            }
615          }
616        }
617        yield return configuration;
618      } while (!finished);
619    }
620
621    private IEnumerable<Dictionary<IValueParameter, IItem>> GetMultipleChoiceConfigurations() {
622      var configuration = new Dictionary<IValueParameter, IItem>();
623      var enumerators = new Dictionary<IValueParameter, IEnumerator<IItem>>();
624      bool finished;
625      do {
626        foreach (var p in multipleChoiceParameters.Keys.ToArray()) {
627          if (!enumerators.ContainsKey(p)) {
628            enumerators.Add(p, multipleChoiceParameters[p].GetEnumerator());
629            if (!enumerators[p].MoveNext()) {
630              multipleChoiceParameters.Remove(p);
631              continue;
632            }
633          }
634          configuration[p] = enumerators[p].Current;
635        }
636
637        finished = true;
638        foreach (var p in multipleChoiceParameters.Keys) {
639          if (!enumerators[p].MoveNext()) {
640            enumerators[p] = multipleChoiceParameters[p].GetEnumerator();
641            enumerators[p].MoveNext();
642          } else {
643            finished = false;
644            break;
645          }
646        }
647        yield return configuration;
648      } while (!finished);
649    }
650    #endregion
651    #endregion
652
653    #region Background workers
654    #region Instance discovery
655    private void instanceDiscoveryBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
656      instanceDiscoveryBackgroundWorker.ReportProgress(0, "Finding instance providers...");
657      var instanceProviders = ProblemInstanceManager.GetProviders(((IAlgorithm)Optimizer).Problem).ToArray();
658      var nodes = new List<TreeNode>(instanceProviders.Length);
659      for (int i = 0; i < instanceProviders.Length; i++) {
660        var provider = instanceProviders[i];
661        var providerNode = new TreeNode(provider.Name) { Tag = provider };
662        var descriptors = ProblemInstanceManager.GetDataDescriptors(provider);
663        foreach (var desc in descriptors) {
664          #region Check cancellation request
665          if (instanceDiscoveryBackgroundWorker.CancellationPending) {
666            e.Cancel = true;
667            e.Result = nodes.ToArray();
668            return;
669          }
670          #endregion
671          var node = new TreeNode(desc.Name) { Tag = desc };
672          providerNode.Nodes.Add(node);
673          if (providerNode.Nodes.Count == 1)
674            nodes.Add(providerNode);
675        }
676        double progress = nodes.Count > 0 ? i / (double)nodes.Count : 0.0;
677        instanceDiscoveryBackgroundWorker.ReportProgress((int)(100 * progress), provider.Name);
678      }
679      e.Result = nodes.ToArray();
680      instanceDiscoveryBackgroundWorker.ReportProgress(100, string.Empty);
681    }
682
683    private void instanceDiscoveryBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
684      if (instanceDiscoveryProgressBar.Value != e.ProgressPercentage)
685        instanceDiscoveryProgressBar.Value = e.ProgressPercentage;
686      instanceDiscoveryProgressLabel.Text = (string)e.UserState;
687    }
688
689    private void instanceDiscoveryBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
690      try {
691        if (((TreeNode[])e.Result).Length > 0) {
692          instancesTreeView.Nodes.AddRange((TreeNode[])e.Result);
693          foreach (TreeNode node in instancesTreeView.Nodes)
694            node.Collapse();
695        }
696        selectNoneCheckBox.Checked = true;
697      } catch { }
698      try {
699        SetMode(DialogMode.Normal);
700        if (e.Error != null) MessageBox.Show(e.Error.Message, "Error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
701      } catch { }
702    }
703    #endregion
704
705    #region Experiment creation
706    private void experimentCreationBackgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
707      backgroundWorkerWaitHandle.Set(); // notify the ok button that we're busy now
708      failedInstances = new StringBuilder();
709      var localExperiment = new Experiment();
710
711      int counter = 0, totalVariations = GetNumberOfVariations();
712      int totalInstances = instances.Values.SelectMany(x => x).Count();
713      if (totalInstances == 0) {
714        try {
715          AddParameterVariations(Optimizer, localExperiment, ref counter, totalVariations);
716        } catch (OperationCanceledException) {
717          e.Cancel = true;
718          return;
719        }
720        experimentCreationBackgroundWorker.ReportProgress(100, string.Empty);
721      } else {
722        foreach (var provider in instances.Keys) {
723          foreach (var descriptor in instances[provider]) {
724            var algorithm = (IAlgorithm)Optimizer.Clone();
725            bool failed = false;
726            try {
727              ProblemInstanceManager.LoadData(provider, descriptor, (IProblemInstanceConsumer)algorithm.Problem);
728            } catch (Exception ex) {
729              failedInstances.AppendLine(descriptor.Name + ": " + ex.Message);
730              failed = true;
731            }
732            if (!failed) {
733              try {
734                if (totalInstances > 1 && totalVariations / totalInstances > 1) {
735                  var experiment = new Experiment(descriptor.Name);
736                  AddParameterVariations(algorithm, experiment, ref counter, totalVariations);
737                  localExperiment.Optimizers.Add(experiment);
738                } else {
739                  AddParameterVariations(algorithm, localExperiment, ref counter, totalVariations);
740                }
741              } catch (OperationCanceledException) {
742                e.Cancel = true;
743                return;
744              }
745            } else experimentCreationBackgroundWorker.ReportProgress((int)Math.Round((100.0 * counter) / totalVariations), "Loading failed (" + descriptor.Name + ")");
746          }
747        }
748      }
749      // this step can take some time
750      SetMode(DialogMode.PreparingExperiment);
751      experimentCreationBackgroundWorker.ReportProgress(-1);
752      localExperiment.Prepare(true);
753      experimentCreationBackgroundWorker.ReportProgress(100);
754      Experiment = localExperiment;
755    }
756
757    private void AddParameterVariations(IOptimizer optimizer, Experiment localExperiment, ref int counter, int totalVariations) {
758      var variations = CalculateParameterVariations(optimizer);
759      foreach (var v in variations) {
760        if (experimentCreationBackgroundWorker.CancellationPending)
761          throw new OperationCanceledException();
762        AddOptimizer(v, localExperiment);
763        counter++;
764        experimentCreationBackgroundWorker.ReportProgress((int)Math.Round((100.0 * counter) / totalVariations), string.Empty);
765      }
766    }
767
768    private IEnumerable<IOptimizer> CalculateParameterVariations(IOptimizer optimizer) {
769      if (!boolParameters.Any() && !intParameters.Any() && !doubleParameters.Any() && !multipleChoiceParameters.Any()) {
770        var o = (IOptimizer)optimizer.Clone();
771        o.Runs.Clear();
772        yield return o;
773        yield break;
774      }
775      bool finished;
776      var mcEnumerator = GetMultipleChoiceConfigurations().GetEnumerator();
777      var boolEnumerator = GetBoolParameterConfigurations().GetEnumerator();
778      var intEnumerator = GetIntParameterConfigurations().GetEnumerator();
779      var doubleEnumerator = GetDoubleParameterConfigurations().GetEnumerator();
780      mcEnumerator.MoveNext(); boolEnumerator.MoveNext(); intEnumerator.MoveNext(); doubleEnumerator.MoveNext();
781      do {
782        var variant = (IAlgorithm)optimizer.Clone();
783        variant.Runs.Clear();
784        variant.Name += " {";
785        finished = true;
786        if (doubleParameters.Any()) {
787          foreach (var d in doubleEnumerator.Current) {
788            var value = (ValueTypeValue<double>)((IValueParameter)variant.Parameters[d.Key.Name]).Value;
789            value.Value = d.Value;
790            variant.Name += d.Key.Name + "=" + d.Value.ToString() + ", ";
791          }
792          if (finished) {
793            if (doubleEnumerator.MoveNext()) {
794              finished = false;
795            } else {
796              doubleEnumerator = GetDoubleParameterConfigurations().GetEnumerator();
797              doubleEnumerator.MoveNext();
798            }
799          }
800        }
801        if (intParameters.Any()) {
802          foreach (var i in intEnumerator.Current) {
803            var value = (ValueTypeValue<int>)((IValueParameter)variant.Parameters[i.Key.Name]).Value;
804            value.Value = i.Value;
805            variant.Name += i.Key.Name + "=" + i.Value.ToString() + ", ";
806          }
807          if (finished) {
808            if (intEnumerator.MoveNext()) {
809              finished = false;
810            } else {
811              intEnumerator = GetIntParameterConfigurations().GetEnumerator();
812              intEnumerator.MoveNext();
813            }
814          }
815        }
816        if (boolParameters.Any()) {
817          foreach (var b in boolEnumerator.Current) {
818            var value = (ValueTypeValue<bool>)((IValueParameter)variant.Parameters[b.Key.Name]).Value;
819            value.Value = b.Value;
820            variant.Name += b.Key.Name + "=" + b.Value.ToString() + ", ";
821          }
822          if (finished) {
823            if (boolEnumerator.MoveNext()) {
824              finished = false;
825            } else {
826              boolEnumerator = GetBoolParameterConfigurations().GetEnumerator();
827              boolEnumerator.MoveNext();
828            }
829          }
830        }
831        if (multipleChoiceParameters.Any()) {
832          foreach (var m in mcEnumerator.Current) {
833            dynamic variantParam = variant.Parameters[m.Key.Name];
834            if (m.Value == optionalNullChoice) {
835              variantParam.Value = null;
836              variant.Name += m.Key.Name + "=null, ";
837              continue;
838            }
839            var variantEnumerator = ((IEnumerable<object>)variantParam.ValidValues).GetEnumerator();
840            var originalEnumerator = ((IEnumerable<object>)((dynamic)m.Key).ValidValues).GetEnumerator();
841            while (variantEnumerator.MoveNext() && originalEnumerator.MoveNext()) {
842              if (m.Value == (IItem)originalEnumerator.Current) {
843                variantParam.Value = (dynamic)variantEnumerator.Current;
844                if (m.Value is INamedItem)
845                  variant.Name += m.Key.Name + "=" + ((INamedItem)m.Value).Name + ", ";
846                else variant.Name += m.Key.Name + "=" + m.Value.ToString() + ", ";
847                break;
848              }
849            }
850          }
851          if (finished) {
852            if (mcEnumerator.MoveNext()) {
853              finished = false;
854            } else {
855              mcEnumerator = GetMultipleChoiceConfigurations().GetEnumerator();
856              mcEnumerator.MoveNext();
857            }
858          }
859        }
860        variant.Name = variant.Name.Substring(0, variant.Name.Length - 2) + "}";
861        yield return variant;
862      } while (!finished);
863    }
864
865    private void experimentCreationBackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
866      if (e.ProgressPercentage >= 0 && e.ProgressPercentage <= 100) {
867        experimentCreationProgressBar.Style = ProgressBarStyle.Continuous;
868        experimentCreationProgressBar.Value = e.ProgressPercentage;
869      } else {
870        experimentCreationProgressBar.Style = ProgressBarStyle.Marquee;
871      }
872    }
873
874    private void experimentCreationBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
875      try {
876        SetMode(DialogMode.Normal);
877        if (e.Error != null) MessageBox.Show(e.Error.Message, "Error occurred", MessageBoxButtons.OK, MessageBoxIcon.Error);
878        if (failedInstances.Length > 0) MessageBox.Show("Some instances could not be loaded: " + Environment.NewLine + failedInstances.ToString(), "Some instances failed to load", MessageBoxButtons.OK, MessageBoxIcon.Error);
879        if (!e.Cancelled && e.Error == null) {
880          DialogResult = System.Windows.Forms.DialogResult.OK;
881          Close();
882        }
883      } catch { }
884    }
885    #endregion
886    #endregion
887  }
888}
Note: See TracBrowser for help on using the repository browser.