Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.Optimizer/3.3/CreateExperimentDialog.cs @ 13777

Last change on this file since 13777 was 9363, checked in by spimming, 12 years ago

#1888:

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