Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Optimizer/3.3/CreateExperimentDialog.cs @ 7974

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

#1851:

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