Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1851:

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