Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12012 was 8574, checked in by jkarder, 12 years ago

#1853:

  • extracted experiment generation from encoding
  • added creators
  • added crossovers
  • added manipulators
  • added support for parameters of type IFixedValueParameter
  • minor code improvements
File size: 13.1 KB
RevLine 
[8517]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 System.Threading;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Data;
31using HeuristicLab.Optimization;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[8524]33using HeuristicLab.Problems.Instances;
[8517]34
35namespace HeuristicLab.Encodings.ParameterConfigurationEncoding {
[8524]36  [Item("ParameterConfigurationTree", "Represents a parameter configuration.")]
[8517]37  [StorableClass]
38  public class ParameterConfigurationTree : ParameterizedValueConfiguration, IEnumerable {
39    [Storable]
[8535]40    private long combinationsCount;
41    public long CombinationsCount {
42      get { return combinationsCount; }
43      private set {
44        if (combinationsCount != value) {
45          combinationsCount = value;
46          OnCombinationsCountChanged();
47        }
48      }
49    }
50
51    [Storable]
[8517]52    private DoubleValue quality;
53    public DoubleValue Quality {
54      get { return quality; }
55      set {
56        if (quality != value) {
57          quality = value;
58          OnQualityChanged();
59        }
60      }
61    }
62
63    [Storable]
64    private DoubleArray normalizedQualityAverages;
65    public DoubleArray NormalizedQualityAverages {
66      get { return normalizedQualityAverages; }
67      set {
68        if (normalizedQualityAverages != value) {
69          normalizedQualityAverages = value;
70        }
71      }
72    }
73
74    [Storable]
75    private DoubleArray normalizedQualityDeviations;
76    public DoubleArray NormalizedQualityDeviations {
77      get { return normalizedQualityDeviations; }
78      set {
79        if (normalizedQualityDeviations != value) {
80          normalizedQualityDeviations = value;
81        }
82      }
83    }
84
85    [Storable]
86    private DoubleArray normalizedEvaluatedSolutions;
87    public DoubleArray NormalizedEvaluatedSolutions {
88      get { return normalizedEvaluatedSolutions; }
89      set {
90        if (normalizedEvaluatedSolutions != value) {
91          normalizedEvaluatedSolutions = value;
92        }
93      }
94    }
95
96    [Storable]
97    private DoubleArray bestQualities;
98    public DoubleArray BestQualities {
99      get { return bestQualities; }
100      set {
101        if (bestQualities != value) {
102          bestQualities = value;
103        }
104      }
105    }
106
107    [Storable]
108    private DoubleArray averageQualities;
109    public DoubleArray AverageQualities {
110      get { return averageQualities; }
111      set { averageQualities = value; }
112    }
113
114    [Storable]
115    private DoubleArray worstQualities;
116    public DoubleArray WorstQualities {
117      get { return worstQualities; }
118      set { worstQualities = value; }
119    }
120
121    [Storable]
122    private DoubleArray qualityVariances;
123    public DoubleArray QualityVariances {
124      get { return qualityVariances; }
125      set { qualityVariances = value; }
126    }
127
128    [Storable]
129    private DoubleArray qualityStandardDeviations;
130    public DoubleArray QualityStandardDeviations {
131      get { return qualityStandardDeviations; }
132      set { qualityStandardDeviations = value; }
133    }
134
135    [Storable]
136    private ItemList<TimeSpanValue> averageExecutionTimes;
137    public ItemList<TimeSpanValue> AverageExecutionTimes {
138      get { return averageExecutionTimes; }
139      set { averageExecutionTimes = value; }
140    }
141
142    [Storable]
143    private DoubleArray averageEvaluatedSolutions;
144    public DoubleArray AverageEvaluatedSolutions {
145      get { return averageEvaluatedSolutions; }
146      set { averageEvaluatedSolutions = value; }
147    }
148
149    [Storable]
150    private IntValue repetitions;
151    public IntValue Repetitions {
152      get { return repetitions; }
153      set { repetitions = value; }
154    }
155
156    [Storable]
157    protected RunCollection runs;
158    public RunCollection Runs {
159      get { return runs; }
160      set { runs = value; }
161    }
162
163    [Storable]
164    protected IDictionary<string, IItem> parameters;
165    public IDictionary<string, IItem> Parameters {
166      get { return parameters; }
167      set { parameters = value; }
168    }
169
170    public ParameterizedValueConfiguration AlgorithmConfiguration {
171      get {
172        return this.ParameterConfigurations.ElementAt(0).ValueConfigurations.First() as ParameterizedValueConfiguration;
173      }
174    }
175
176    public ParameterizedValueConfiguration ProblemConfiguration {
177      get {
178        return this.ParameterConfigurations.ElementAt(1).ValueConfigurations.First() as ParameterizedValueConfiguration;
179      }
180    }
181
[8524]182    #region Constructors and Cloning
[8517]183    [StorableConstructor]
184    protected ParameterConfigurationTree(bool deserializing) : base(deserializing) { }
185    protected ParameterConfigurationTree(ParameterConfigurationTree original, Cloner cloner)
186      : base(original, cloner) {
187      this.quality = cloner.Clone(original.quality);
188      this.normalizedQualityAverages = cloner.Clone(original.normalizedQualityAverages);
189      this.normalizedQualityDeviations = cloner.Clone(original.normalizedQualityDeviations);
190      this.normalizedEvaluatedSolutions = cloner.Clone(original.normalizedEvaluatedSolutions);
191      this.bestQualities = cloner.Clone(original.BestQualities);
192      this.averageQualities = cloner.Clone(original.averageQualities);
193      this.worstQualities = cloner.Clone(original.worstQualities);
194      this.qualityStandardDeviations = cloner.Clone(original.qualityStandardDeviations);
195      this.qualityVariances = cloner.Clone(original.qualityVariances);
196      this.averageExecutionTimes = cloner.Clone(original.averageExecutionTimes);
197      this.averageEvaluatedSolutions = cloner.Clone(original.averageEvaluatedSolutions);
198      this.repetitions = cloner.Clone(original.repetitions);
199      this.runs = cloner.Clone(original.runs);
200      this.parameters = new Dictionary<string, IItem>();
201      if (original.parameters != null) {
202        foreach (var p in original.parameters) {
203          this.parameters.Add(p.Key, cloner.Clone(p.Value));
204        }
205      }
206    }
[8524]207    public ParameterConfigurationTree() : base() { }
208    public ParameterConfigurationTree(IAlgorithm algorithm, IProblem problem)
209      : base(null, algorithm.GetType(), false) {
210      this.Optimize = false;
211      this.IsOptimizable = false;
212      this.parameters = new Dictionary<string, IItem>();
213      this.Name = algorithm.ItemName;
214
[8535]215      var algProblemItem = new AlgorithmProblemItem();
216      algProblemItem.AlgorithmParameter.Value = algorithm;
217      algProblemItem.ProblemParameter.Value = problem;
[8524]218      this.discoverValidValues = false;
219
[8535]220      var algConfig = new SingleValuedParameterConfiguration("Algorithm", algProblemItem.AlgorithmParameter);
221      var problemConfig = new SingleValuedParameterConfiguration("Problem", algProblemItem.ProblemParameter);
[8524]222
[8535]223      algConfig.CombinationsCountChanged += new EventHandler(UpdateConfigurationsCount);
224      problemConfig.CombinationsCountChanged += new EventHandler(UpdateConfigurationsCount);
225
226      this.parameterConfigurations.Add(algConfig);
227      this.parameterConfigurations.Add(problemConfig);
228
[8524]229      // problems can be modified in the list of problem instances, so the parameters which are not Optimize=true,
230      // must not be modifiable in the parameter configuration tree. otherwise the parameter values would be ambiguous
231      ProblemConfiguration.ValuesReadOnly = true;
[8535]232
233      CombinationsCount = GetCombinationCount(0);
[8524]234    }
235
[8517]236    public override IDeepCloneable Clone(Cloner cloner) {
237      return new ParameterConfigurationTree(this, cloner);
238    }
[8524]239
[8517]240    [StorableHook(HookType.AfterDeserialization)]
241    private void AfterDeserialization() {
242      if (ProblemConfiguration != null) ProblemConfiguration.ValuesReadOnly = true;
[8535]243      CombinationsCount = GetCombinationCount(0);
[8517]244    }
245    #endregion
246
247    public virtual void CollectResultValues(IDictionary<string, IItem> values) {
248      values.Add("RunsAverageExecutionTimes", AverageExecutionTimes);
249      values.Add("RunsAverageEvaluatedSolutions", AverageEvaluatedSolutions);
250      values.Add("Repetitions", Repetitions);
251      values.Add("RunsBestQualities", BestQualities);
252      values.Add("RunsAverageQualities", AverageQualities);
253      values.Add("RunsWorstQualities", WorstQualities);
254      values.Add("RunsQualityVariances", QualityVariances);
255      values.Add("RunsQualityStandardDeviations", QualityStandardDeviations);
256      values.Add("QualitiesNormalized", NormalizedQualityAverages);
257      values.Add("AverageQualityNormalized", Quality);
258      values.Add("Runs", Runs);
259    }
260
261    public virtual void CollectParameterValues(IDictionary<string, IItem> values) {
262      foreach (var p in parameters) {
263        values.Add(p);
264      }
265    }
266
267    #region Events
268    public event EventHandler QualityChanged;
269    private void OnQualityChanged() {
270      var handler = QualityChanged;
271      if (handler != null) handler(this, EventArgs.Empty);
272    }
273
274    private void Quality_ValueChanged(object sender, EventArgs e) {
275      OnQualityChanged();
276    }
277
[8535]278    private void UpdateConfigurationsCount(object sender, EventArgs e) {
279      CombinationsCount = GetCombinationCount(0);
280    }
[8517]281    #endregion
282
283    public override void Parameterize(IParameterizedItem item) {
284      this.parameters.Clear();
[8524]285      var algorithm = (IAlgorithm)item;
[8517]286      var problem = algorithm.Problem;
287
288      ProblemConfiguration.Parameterize(problem);
289      AlgorithmConfiguration.Parameterize(algorithm);
290
291      algorithm.CollectParameterValues(this.Parameters);
292    }
293
294    public IEnumerator GetEnumerator() {
295      IEnumerator enumerator = new ParameterCombinationsEnumerator(this);
296      enumerator.Reset();
297      return enumerator;
298    }
299
300    /// <summary>
301    /// returns the number of possible parameter combinations
302    /// </summary>
303    /// <param name="max">algorithm stops counting when max is reached. zero for infinite counting</param>
304    /// <returns></returns>
305    public long GetCombinationCount(long max) {
306      long cnt = 0;
307      foreach (var c in this) {
308        cnt++;
309        if (max > 0 && cnt >= max) {
310          return cnt;
311        }
312      }
313      return cnt;
314    }
315
316    public IOptimizable GetRandomOptimizable(IRandom random) {
317      List<IOptimizable> allOptimizables = GetAllOptimizables();
318      return allOptimizables[random.Next(allOptimizables.Count)];
319    }
320
321    public override string ToString() {
322      return this.Name;
323    }
324
325    public IRun ToRun(bool clearParameters) {
326      return ToRun(this.ParameterInfoString, clearParameters);
327    }
328
329    public IRun ToRun(string name, bool clearParameters) {
330      IRun run = new Run();
331      run.Name = name;
332      this.CollectResultValues(run.Results);
333      this.CollectParameterValues(run.Parameters);
334      if (clearParameters) ClearParameters(run, this.GetOptimizedParameterNames());
335      return run;
336    }
337
338    public override string ParameterInfoString {
339      get {
340        string algorithmInfo = this.AlgorithmConfiguration.ParameterInfoString;
341        string problemInfo = this.ProblemConfiguration.ParameterInfoString;
342        var sb = new StringBuilder();
343        if (!string.IsNullOrEmpty(algorithmInfo)) {
344          sb.Append("Algorithm (");
345          sb.Append(algorithmInfo);
346          sb.Append(")");
347        }
348        if (!string.IsNullOrEmpty(problemInfo)) {
349          if (sb.Length > 0)
350            sb.Append(", ");
351          sb.Append("Problem( ");
352          sb.Append(problemInfo);
353          sb.Append(")");
354        }
355        return sb.ToString();
356      }
357    }
358
359    public override void CollectOptimizedParameterNames(List<string> parameterNames, string prefix) {
360      AlgorithmConfiguration.CollectOptimizedParameterNames(parameterNames, string.Empty);
361      ProblemConfiguration.CollectOptimizedParameterNames(parameterNames, string.Empty);
362    }
363
364    #region Helpers
365    /// <summary>
366    /// Removes those parameters from the run which are not declared in parametersToKeep
367    /// </summary>
368    private void ClearParameters(IRun run, IEnumerable<string> parametersToKeep) {
369      var parametersToRemove = new List<string>();
370      foreach (var parameter in run.Parameters) {
371        if (!parametersToKeep.Contains(parameter.Key))
372          parametersToRemove.Add(parameter.Key);
373      }
374      foreach (var parameter in parametersToRemove)
375        run.Parameters.Remove(parameter);
376    }
377    #endregion
378  }
379}
Note: See TracBrowser for help on using the repository browser.