Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12833 was 12680, checked in by abeham, 9 years ago

#2366: integrated into trunk

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