Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP-MoveOperators/HeuristicLab.Optimizer/3.3/CreateExperimentDialog.cs @ 8085

Last change on this file since 8085 was 8085, checked in by gkronber, 12 years ago

#1847: merged trunk changes r7800:HEAD into gp move operators branch

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