Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 10377 was 9521, checked in by abeham, 11 years ago

#2043: Fixed issue

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