Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ParameterConfigurationEncoding/HeuristicLab.Encodings.ParameterConfigurationEncoding/3.3/ParameterConfigurationTree.cs

Last change on this file was 15171, checked in by jkarder, 7 years ago

#1853: worked on ParameterConfigurationEncoding

  • updated to .NET 4.5
  • replaced CreateExperimentDialogV2 with CreateExperimentView
  • improved experiment generation
  • fixed plugin dependencies and cleaned project references
File size: 13.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Linq;
26using System.Text;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Optimization;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
32
33namespace HeuristicLab.Encodings.ParameterConfigurationEncoding {
34  [Item("ParameterConfigurationTree", "Represents a parameter configuration.")]
35  [StorableClass]
36  public class ParameterConfigurationTree : ParameterizedValueConfiguration, IEnumerable {
37    [Storable]
38    private long combinationsCount;
39    public long CombinationsCount {
40      get { return combinationsCount; }
41      private set {
42        if (combinationsCount != value) {
43          combinationsCount = value;
44          OnCombinationsCountChanged();
45        }
46      }
47    }
48
49    [Storable]
50    private DoubleValue quality;
51    public DoubleValue Quality {
52      get { return quality; }
53      set {
54        if (quality != value) {
55          quality = value;
56          OnQualityChanged();
57        }
58      }
59    }
60
61    [Storable]
62    private DoubleArray normalizedQualityAverages;
63    public DoubleArray NormalizedQualityAverages {
64      get { return normalizedQualityAverages; }
65      set {
66        if (normalizedQualityAverages != value) {
67          normalizedQualityAverages = value;
68        }
69      }
70    }
71
72    [Storable]
73    private DoubleArray normalizedQualityDeviations;
74    public DoubleArray NormalizedQualityDeviations {
75      get { return normalizedQualityDeviations; }
76      set {
77        if (normalizedQualityDeviations != value) {
78          normalizedQualityDeviations = value;
79        }
80      }
81    }
82
83    [Storable]
84    private DoubleArray normalizedEvaluatedSolutions;
85    public DoubleArray NormalizedEvaluatedSolutions {
86      get { return normalizedEvaluatedSolutions; }
87      set {
88        if (normalizedEvaluatedSolutions != value) {
89          normalizedEvaluatedSolutions = value;
90        }
91      }
92    }
93
94    [Storable]
95    private DoubleArray bestQualities;
96    public DoubleArray BestQualities {
97      get { return bestQualities; }
98      set {
99        if (bestQualities != value) {
100          bestQualities = value;
101        }
102      }
103    }
104
105    [Storable]
106    private DoubleArray averageQualities;
107    public DoubleArray AverageQualities {
108      get { return averageQualities; }
109      set { averageQualities = value; }
110    }
111
112    [Storable]
113    private DoubleArray worstQualities;
114    public DoubleArray WorstQualities {
115      get { return worstQualities; }
116      set { worstQualities = value; }
117    }
118
119    [Storable]
120    private DoubleArray qualityVariances;
121    public DoubleArray QualityVariances {
122      get { return qualityVariances; }
123      set { qualityVariances = value; }
124    }
125
126    [Storable]
127    private DoubleArray qualityStandardDeviations;
128    public DoubleArray QualityStandardDeviations {
129      get { return qualityStandardDeviations; }
130      set { qualityStandardDeviations = value; }
131    }
132
133    [Storable]
134    private ItemList<TimeSpanValue> averageExecutionTimes;
135    public ItemList<TimeSpanValue> AverageExecutionTimes {
136      get { return averageExecutionTimes; }
137      set { averageExecutionTimes = value; }
138    }
139
140    [Storable]
141    private DoubleArray averageEvaluatedSolutions;
142    public DoubleArray AverageEvaluatedSolutions {
143      get { return averageEvaluatedSolutions; }
144      set { averageEvaluatedSolutions = value; }
145    }
146
147    [Storable]
148    private IntValue repetitions;
149    public IntValue Repetitions {
150      get { return repetitions; }
151      set { repetitions = value; }
152    }
153
154    [Storable]
155    protected RunCollection runs;
156    public RunCollection Runs {
157      get { return runs; }
158      set { runs = value; }
159    }
160
161    [Storable]
162    protected IDictionary<string, IItem> parameters;
163    public IDictionary<string, IItem> Parameters {
164      get { return parameters; }
165      set { parameters = value; }
166    }
167
168    public ParameterizedValueConfiguration AlgorithmConfiguration {
169      get {
170        return this.ParameterConfigurations.ElementAt(0).ValueConfigurations.First() as ParameterizedValueConfiguration;
171      }
172    }
173
174    public ParameterizedValueConfiguration ProblemConfiguration {
175      get {
176        return this.ParameterConfigurations.ElementAt(1).ValueConfigurations.First() as ParameterizedValueConfiguration;
177      }
178    }
179
180    #region Constructors and Cloning
181    [StorableConstructor]
182    protected ParameterConfigurationTree(bool deserializing) : base(deserializing) { }
183    protected ParameterConfigurationTree(ParameterConfigurationTree original, Cloner cloner)
184      : base(original, cloner) {
185      this.quality = cloner.Clone(original.quality);
186      this.normalizedQualityAverages = cloner.Clone(original.normalizedQualityAverages);
187      this.normalizedQualityDeviations = cloner.Clone(original.normalizedQualityDeviations);
188      this.normalizedEvaluatedSolutions = cloner.Clone(original.normalizedEvaluatedSolutions);
189      this.bestQualities = cloner.Clone(original.BestQualities);
190      this.averageQualities = cloner.Clone(original.averageQualities);
191      this.worstQualities = cloner.Clone(original.worstQualities);
192      this.qualityStandardDeviations = cloner.Clone(original.qualityStandardDeviations);
193      this.qualityVariances = cloner.Clone(original.qualityVariances);
194      this.averageExecutionTimes = cloner.Clone(original.averageExecutionTimes);
195      this.averageEvaluatedSolutions = cloner.Clone(original.averageEvaluatedSolutions);
196      this.repetitions = cloner.Clone(original.repetitions);
197      this.runs = cloner.Clone(original.runs);
198      this.parameters = new Dictionary<string, IItem>();
199      if (original.parameters != null) {
200        foreach (var p in original.parameters) {
201          this.parameters.Add(p.Key, cloner.Clone(p.Value));
202        }
203      }
204    }
205    public ParameterConfigurationTree() : base() { }
206    public ParameterConfigurationTree(IAlgorithm algorithm, IProblem problem)
207      : base(null, algorithm.GetType(), false) {
208      this.Optimize = false;
209      this.IsOptimizable = false;
210      this.parameters = new Dictionary<string, IItem>();
211      this.Name = algorithm.ItemName;
212
213      var algProblemItem = new AlgorithmProblemItem();
214      algProblemItem.AlgorithmParameter.Value = algorithm;
215      algProblemItem.ProblemParameter.Value = problem;
216      this.discoverValidValues = false;
217
218      var algConfig = new SingleValuedParameterConfiguration("Algorithm", algProblemItem.AlgorithmParameter);
219      var problemConfig = new SingleValuedParameterConfiguration("Problem", algProblemItem.ProblemParameter);
220
221      algConfig.CombinationsCountChanged += new EventHandler(UpdateConfigurationsCount);
222      problemConfig.CombinationsCountChanged += new EventHandler(UpdateConfigurationsCount);
223
224      this.parameterConfigurations.Add(algConfig);
225      this.parameterConfigurations.Add(problemConfig);
226
227      // problems can be modified in the list of problem instances, so the parameters which are not Optimize=true,
228      // must not be modifiable in the parameter configuration tree. otherwise the parameter values would be ambiguous
229      ProblemConfiguration.ValuesReadOnly = true;
230
231      CombinationsCount = GetCombinationCount(0);
232    }
233
234    public override IDeepCloneable Clone(Cloner cloner) {
235      return new ParameterConfigurationTree(this, cloner);
236    }
237
238    [StorableHook(HookType.AfterDeserialization)]
239    private void AfterDeserialization() {
240      if (ProblemConfiguration != null) ProblemConfiguration.ValuesReadOnly = true;
241      CombinationsCount = GetCombinationCount(0);
242    }
243    #endregion
244
245    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
246      values.Add("RunsAverageExecutionTimes", AverageExecutionTimes);
247      values.Add("RunsAverageEvaluatedSolutions", AverageEvaluatedSolutions);
248      values.Add("Repetitions", Repetitions);
249      values.Add("RunsBestQualities", BestQualities);
250      values.Add("RunsAverageQualities", AverageQualities);
251      values.Add("RunsWorstQualities", WorstQualities);
252      values.Add("RunsQualityVariances", QualityVariances);
253      values.Add("RunsQualityStandardDeviations", QualityStandardDeviations);
254      values.Add("QualitiesNormalized", NormalizedQualityAverages);
255      values.Add("AverageQualityNormalized", Quality);
256      values.Add("Runs", Runs);
257    }
258
259    public virtual void CollectParameterValues(IDictionary<string, IItem> values) {
260      foreach (var p in parameters) {
261        values.Add(p);
262      }
263    }
264
265    #region Events
266    public event EventHandler QualityChanged;
267    private void OnQualityChanged() {
268      var handler = QualityChanged;
269      if (handler != null) handler(this, EventArgs.Empty);
270    }
271
272    private void Quality_ValueChanged(object sender, EventArgs e) {
273      OnQualityChanged();
274    }
275
276    private void UpdateConfigurationsCount(object sender, EventArgs e) {
277      CombinationsCount = GetCombinationCount(0);
278    }
279    #endregion
280
281    public override void Parameterize(IParameterizedItem item) {
282      this.parameters.Clear();
283      var algorithm = (IAlgorithm)item;
284      var problem = algorithm.Problem;
285
286      ProblemConfiguration.Parameterize(problem);
287      AlgorithmConfiguration.Parameterize(algorithm);
288
289      algorithm.CollectParameterValues(this.Parameters);
290    }
291
292    public IEnumerator GetEnumerator() {
293      IEnumerator enumerator = new ParameterCombinationsEnumerator(this);
294      enumerator.Reset();
295      return enumerator;
296    }
297
298    /// <summary>
299    /// returns the number of possible parameter combinations
300    /// </summary>
301    /// <param name="max">algorithm stops counting when max is reached. zero for infinite counting</param>
302    /// <returns></returns>
303    public long GetCombinationCount(long max) {
304      long cnt = 0;
305      foreach (var c in this) {
306        cnt++;
307        if (max > 0 && cnt >= max) {
308          return cnt;
309        }
310      }
311      return cnt;
312    }
313
314    public IOptimizable GetRandomOptimizable(IRandom random) {
315      List<IOptimizable> allOptimizables = GetAllOptimizables();
316      return allOptimizables[random.Next(allOptimizables.Count)];
317    }
318
319    public override string ToString() {
320      return this.Name;
321    }
322
323    public IRun ToRun(bool clearParameters) {
324      return ToRun(this.ParameterInfoString, clearParameters);
325    }
326
327    public IRun ToRun(string name, bool clearParameters) {
328      IRun run = new Run();
329      run.Name = name;
330      this.CollectResultValues(run.Results);
331      this.CollectParameterValues(run.Parameters);
332      if (clearParameters) ClearParameters(run, this.GetOptimizedParameterNames());
333      return run;
334    }
335
336    public override string ParameterInfoString {
337      get {
338        string algorithmInfo = this.AlgorithmConfiguration.ParameterInfoString;
339        string problemInfo = this.ProblemConfiguration.ParameterInfoString;
340
341        var sb = new StringBuilder(AlgorithmConfiguration.NumberedName);
342        if (!string.IsNullOrEmpty(algorithmInfo)) sb.AppendFormat(" ({0})", algorithmInfo);
343        if (!string.IsNullOrEmpty(problemInfo)) sb.AppendFormat(", {0} ({1})", ProblemConfiguration.NumberedName, problemInfo);
344
345        return sb.ToString();
346      }
347    }
348
349    public override void CollectOptimizedParameterNames(List<string> parameterNames, string prefix) {
350      AlgorithmConfiguration.CollectOptimizedParameterNames(parameterNames, string.Empty);
351      ProblemConfiguration.CollectOptimizedParameterNames(parameterNames, string.Empty);
352    }
353
354    #region Helpers
355    /// <summary>
356    /// Removes those parameters from the run which are not declared in parametersToKeep
357    /// </summary>
358    private void ClearParameters(IRun run, IEnumerable<string> parametersToKeep) {
359      var parametersToRemove = new List<string>();
360      foreach (var parameter in run.Parameters) {
361        if (!parametersToKeep.Contains(parameter.Key))
362          parametersToRemove.Add(parameter.Key);
363      }
364      foreach (var parameter in parametersToRemove)
365        run.Parameters.Remove(parameter);
366    }
367    #endregion
368  }
369}
Note: See TracBrowser for help on using the repository browser.