Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Algorithms.ALPS/3.3/Alps.cs @ 12570

Last change on this file since 12570 was 12570, checked in by pfleck, 9 years ago

#2269

  • Added missing Hook.
  • Sealed some classes.
File size: 19.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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.Generic;
24using System.Linq;
25using HeuristicLab.Analysis;
26using HeuristicLab.Collections;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Data;
30using HeuristicLab.Operators;
31using HeuristicLab.Optimization;
32using HeuristicLab.Optimization.Operators;
33using HeuristicLab.Parameters;
34using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
35using HeuristicLab.Random;
36
37namespace HeuristicLab.Algorithms.ALPS {
38  [Item("ALPS", "Base class for all ALPS-based algorithms.")]
39  [StorableClass]
40  public abstract class Alps : HeuristicOptimizationEngineAlgorithm, IStorableContent {
41    public string Filename { get; set; }
42
43    #region Problem Properties
44    public override Type ProblemType {
45      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
46    }
47    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
48      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
49      set { base.Problem = value; }
50    }
51    #endregion
52
53    #region Parameter Properties
54    private IValueParameter<IntValue> SeedParameter {
55      get { return (IValueParameter<IntValue>)Parameters["Seed"]; }
56    }
57    private IValueParameter<BoolValue> SetSeedRandomlyParameter {
58      get { return (IValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
59    }
60    private IFixedValueParameter<MultiAnalyzer> AnalyzerParameter {
61      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
62    }
63    private IFixedValueParameter<MultiAnalyzer> LayerAnalyzerParameter {
64      get { return (IFixedValueParameter<MultiAnalyzer>)Parameters["LayerAnalyzer"]; }
65    }
66    private IValueParameter<IntValue> NumberOfLayersParameter {
67      get { return (IValueParameter<IntValue>)Parameters["NumberOfLayers"]; }
68    }
69    private IValueParameter<EnumValue<AgingScheme>> AgingSchemeParameter {
70      get { return (IValueParameter<EnumValue<AgingScheme>>)Parameters["AgingScheme"]; }
71    }
72    private IValueParameter<IntValue> AgeGapParameter {
73      get { return (IValueParameter<IntValue>)Parameters["AgeGap"]; }
74    }
75    private IValueParameter<IntArray> AgeLimitsParameter {
76      get { return (IValueParameter<IntArray>)Parameters["AgeLimits"]; }
77    }
78    private IValueParameter<EnumValue<AgeInheritance>> AgeInheritanceParameter {
79      get { return (IValueParameter<EnumValue<AgeInheritance>>)Parameters["AgeInheritance"]; }
80    }
81    private IValueParameter<ReductionOperation> AgeInheritanceReductionParameter {
82      get { return (IValueParameter<ReductionOperation>)Parameters["AgeInheritanceReduction"]; }
83    }
84    private IValueParameter<IntValue> MatingPoolRangeParameter {
85      get { return (IValueParameter<IntValue>)Parameters["MatingPoolRange"]; }
86    }
87    private IValueParameter<PercentValue> MatingPoolSelectionPercentageParameter {
88      get { return (IValueLookupParameter<PercentValue>)Parameters["MatingPoolSelectionPercentage"]; }
89    }
90    private IValueParameter<MultiTerminator> TerminatorParameter {
91      get { return (IValueParameter<MultiTerminator>)Parameters["Terminator"]; }
92    }
93    #endregion
94
95    #region Properties
96    public IntValue Seed {
97      get { return SeedParameter.Value; }
98      set { SeedParameter.Value = value; }
99    }
100    public BoolValue SetSeedRandomly {
101      get { return SetSeedRandomlyParameter.Value; }
102      set { SetSeedRandomlyParameter.Value = value; }
103    }
104    public MultiAnalyzer Analyzer {
105      get { return AnalyzerParameter.Value; }
106    }
107    public MultiAnalyzer LayerAnalyzer {
108      get { return LayerAnalyzerParameter.Value; }
109    }
110    public IntValue NumberOfLayers {
111      get { return NumberOfLayersParameter.Value; }
112      set { NumberOfLayersParameter.Value = value; }
113    }
114    public EnumValue<AgingScheme> AgingScheme {
115      get { return AgingSchemeParameter.Value; }
116      set { AgingSchemeParameter.Value = value; }
117    }
118    public IntValue AgeGap {
119      get { return AgeGapParameter.Value; }
120      set { AgeGapParameter.Value = value; }
121    }
122    public IntArray AgeLimits {
123      get { return AgeLimitsParameter.Value; }
124      set { AgeLimitsParameter.Value = value; }
125    }
126    public EnumValue<AgeInheritance> AgeInheritance {
127      get { return AgeInheritanceParameter.Value; }
128      set { AgeInheritanceParameter.Value = value; }
129    }
130    private ReductionOperation AgeInheritanceReduction {
131      get { return AgeInheritanceReductionParameter.Value; }
132      set { AgeInheritanceReductionParameter.Value = value; }
133    }
134    public IntValue MatingPoolRange {
135      get { return MatingPoolRangeParameter.Value; }
136      set { MatingPoolRangeParameter.Value = value; }
137    }
138    public PercentValue MatingPoolSelectionPercentage {
139      get { return MatingPoolSelectionPercentageParameter.Value; }
140      set { MatingPoolSelectionPercentageParameter.Value = value; }
141    }
142    public MultiTerminator Terminators {
143      get { return TerminatorParameter.Value; }
144    }
145    #endregion
146
147    #region Helper Properties
148    protected RandomCreator GlobalRandomCreator {
149      get { return (RandomCreator)OperatorGraph.InitialOperator; }
150    }
151    protected SolutionsCreator SolutionsCreator {
152      get { return OperatorGraph.Iterate().OfType<SolutionsCreator>().First(); }
153    }
154    #endregion
155
156    #region Preconfigured Analyzers
157    [Storable]
158    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
159    [Storable]
160    private BestAverageWorstQualityAnalyzer layerQualityAnalyzer;
161    #endregion
162    #region Preconfigured Terminators
163    [Storable]
164    protected ComparisonTerminator<IntValue> evaluationsTerminator;
165    [Storable]
166    protected SingleObjectiveQualityTerminator qualityTerminator;
167    [Storable]
168    protected ExecutionTimeTerminator executionTimeTerminator;
169    #endregion
170
171    [StorableConstructor]
172    protected Alps(bool deserializing)
173      : base(deserializing) { }
174    [StorableHook(HookType.AfterDeserialization)]
175    private void AfterDeserialization() {
176      Initialize();
177    }
178    protected Alps(Alps original, Cloner cloner)
179      : base(original, cloner) {
180      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
181      layerQualityAnalyzer = cloner.Clone(original.layerQualityAnalyzer);
182      evaluationsTerminator = cloner.Clone(original.evaluationsTerminator);
183      qualityTerminator = cloner.Clone(original.qualityTerminator);
184      executionTimeTerminator = cloner.Clone(original.executionTimeTerminator);
185      Initialize();
186    }
187
188    protected Alps()
189      : base() {
190      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
191      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
192      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze the islands.", new MultiAnalyzer()));
193      Parameters.Add(new FixedValueParameter<MultiAnalyzer>("LayerAnalyzer", "The operator used to analyze each layer.", new MultiAnalyzer()));
194      Parameters.Add(new ValueParameter<IntValue>("NumberOfLayers", "The number of layers.", new IntValue(10)));
195      Parameters.Add(new ValueParameter<EnumValue<AgingScheme>>("AgingScheme", "The aging scheme for setting the age-limits for the layers.", new EnumValue<AgingScheme>(ALPS.AgingScheme.Polynomial)));
196      Parameters.Add(new ValueParameter<IntValue>("AgeGap", "The frequency of reseeding the lowest layer and scaling factor for the age-limits for the layers", new IntValue(20)));
197      Parameters.Add(new ValueParameter<IntArray>("AgeLimits", new IntArray(new int[0])) { Hidden = true });
198      Parameters.Add(new ValueParameter<EnumValue<AgeInheritance>>("AgeInheritance", "The operator for determining the age of an offspring based the parents' age.", new EnumValue<AgeInheritance>(ALPS.AgeInheritance.Older)));
199      Parameters.Add(new ValueParameter<ReductionOperation>("AgeInheritanceReduction") { Hidden = true });
200      Parameters.Add(new ValueParameter<IntValue>("MatingPoolRange", "The range of layers used for creating a mating pool. (1 = current + previous layer)", new IntValue(1)) { Hidden = true });
201      Parameters.Add(new ValueParameter<PercentValue>("MatingPoolSelectionPercentage", "Percentage of the previous layers used for creating a mating pool.", new PercentValue(1.0, restrictToUnitInterval: true)) { Hidden = true });
202      Parameters.Add(new ValueParameter<MultiTerminator>("Terminator", "The termination criteria which sould be checked.", new MultiTerminator()));
203
204      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
205      layerQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
206
207      evaluationsTerminator = new ComparisonTerminator<IntValue>("EvaluatedSolutions", ComparisonType.Less, new IntValue(int.MaxValue)) { Name = "Evaluations" };
208      qualityTerminator = new SingleObjectiveQualityTerminator() { Name = "Quality" };
209      executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
210
211      ParameterizeAgeLimits();
212      ParameterizeAgeInheritanceReduction();
213
214      ParameterizeAnalyzers();
215      UpdateAnalyzers();
216
217      ParameterizeTerminators();
218
219      Initialize();
220    }
221
222
223    #region Events
224    public override void Prepare() {
225      if (Problem != null)
226        base.Prepare();
227    }
228
229    protected override void OnProblemChanged() {
230      base.OnProblemChanged();
231      ParameterizeStochasticOperator(Problem.SolutionCreator);
232      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
233      foreach (var @operator in Problem.Operators.OfType<IOperator>())
234        ParameterizeStochasticOperator(@operator);
235      ParameterizeSolutionsCreator();
236      ParameterizeAnalyzers();
237      ParameterizeTerminators();
238      UpdateAnalyzers();
239      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
240    }
241    protected override void RegisterProblemEvents() {
242      base.RegisterProblemEvents();
243      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
244      if (maximizationParameter != null) maximizationParameter.ValueChanged += new EventHandler(MaximizationParameter_ValueChanged);
245    }
246    protected override void DeregisterProblemEvents() {
247      var maximizationParameter = (IValueParameter<BoolValue>)Problem.MaximizationParameter;
248      if (maximizationParameter != null) maximizationParameter.ValueChanged -= new EventHandler(MaximizationParameter_ValueChanged);
249      base.DeregisterProblemEvents();
250    }
251
252    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
253      base.Problem_SolutionCreatorChanged(sender, e);
254      ParameterizeStochasticOperator(Problem.SolutionCreator);
255      ParameterizeSolutionsCreator();
256    }
257    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
258      base.Problem_EvaluatorChanged(sender, e);
259      ParameterizeStochasticOperatorForLayer(Problem.Evaluator);
260      ParameterizeSolutionsCreator();
261      ParameterizeAnalyzers();
262      Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
263    }
264
265    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
266      foreach (var @operator in Problem.Operators.OfType<IOperator>())
267        ParameterizeStochasticOperator(@operator);
268      UpdateAnalyzers();
269      base.Problem_OperatorsChanged(sender, e);
270    }
271    protected virtual void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
272      ParameterizeAnalyzers();
273    }
274    private void MaximizationParameter_ValueChanged(object sender, EventArgs e) {
275      ParameterizeTerminators();
276    }
277    private void QualityAnalyzer_CurrentBestQualityParameter_NameChanged(object sender, EventArgs e) {
278      ParameterizeTerminators();
279    }
280
281    private void AgeGapParameter_ValueChanged(object sender, EventArgs e) {
282      AgeGap.ValueChanged += AgeGap_ValueChanged;
283      ParameterizeAgeLimits();
284    }
285    private void AgeGap_ValueChanged(object sender, EventArgs e) {
286      ParameterizeAgeLimits();
287    }
288    private void AgingSchemeParameter_ValueChanged(object sender, EventArgs e) {
289      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
290      ParameterizeAgeLimits();
291    }
292    private void AgingScheme_ValueChanged(object sender, EventArgs e) {
293      ParameterizeAgeLimits();
294    }
295    private void NumberOfLayersParameter_ValueChanged(object sender, EventArgs e) {
296      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
297      ParameterizeAgeLimits();
298    }
299    private void NumberOfLayers_ValueChanged(object sender, EventArgs e) {
300      ParameterizeAgeLimits();
301    }
302    private void AgeInheritanceParameter_ValueChanged(object sender, EventArgs e) {
303      AgeInheritance.ValueChanged += AgeInheritance_ValueChanged;
304      ParameterizeAgeInheritanceReduction();
305    }
306    private void AgeInheritance_ValueChanged(object sender, EventArgs e) {
307      ParameterizeAgeInheritanceReduction();
308    }
309    private void AnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
310      foreach (var analyzer in e.Items) {
311        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
312          parameter.Depth = 2;
313        }
314      }
315    }
316    private void LayerAnalyzerOperators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<IAnalyzer>> e) {
317      foreach (var analyzer in e.Items) {
318        IParameter resultParameter;
319        if (analyzer.Value.Parameters.TryGetValue("Results", out resultParameter)) {
320          var lookupParameter = resultParameter as ILookupParameter;
321          if (lookupParameter != null)
322            lookupParameter.ActualName = "LayerResults";
323        }
324        foreach (var parameter in analyzer.Value.Parameters.OfType<IScopeTreeLookupParameter>()) {
325          parameter.Depth = 1;
326        }
327      }
328    }
329    #endregion
330
331    #region Parameterization
332    private void Initialize() {
333      if (Problem != null)
334        Problem.Evaluator.QualityParameter.ActualNameChanged += Evaluator_QualityParameter_ActualNameChanged;
335      AgeGapParameter.ValueChanged += AgeGapParameter_ValueChanged;
336      AgeGap.ValueChanged += AgeGap_ValueChanged;
337      AgingSchemeParameter.ValueChanged += AgingSchemeParameter_ValueChanged;
338      AgingScheme.ValueChanged += AgingScheme_ValueChanged;
339      NumberOfLayersParameter.ValueChanged += NumberOfLayersParameter_ValueChanged;
340      NumberOfLayers.ValueChanged += NumberOfLayers_ValueChanged;
341      AgeInheritanceParameter.ValueChanged += AgeInheritanceParameter_ValueChanged;
342      AgeInheritance.ValueChanged += AgeInheritance_ValueChanged;
343      Analyzer.Operators.ItemsAdded += AnalyzerOperators_ItemsAdded;
344      LayerAnalyzer.Operators.ItemsAdded += LayerAnalyzerOperators_ItemsAdded;
345      qualityAnalyzer.CurrentBestQualityParameter.NameChanged += new EventHandler(QualityAnalyzer_CurrentBestQualityParameter_NameChanged);
346    }
347    private void ParameterizeSolutionsCreator() {
348      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
349      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
350    }
351    private void ParameterizeAnalyzers() {
352      qualityAnalyzer.ResultsParameter.ActualName = "Results";
353      qualityAnalyzer.ResultsParameter.Hidden = true;
354      qualityAnalyzer.QualityParameter.Depth = 2;
355      layerQualityAnalyzer.ResultsParameter.ActualName = "Results";
356      layerQualityAnalyzer.ResultsParameter.Hidden = true;
357      layerQualityAnalyzer.QualityParameter.Depth = 1;
358      if (Problem != null) {
359        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
360        qualityAnalyzer.MaximizationParameter.Hidden = true;
361        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
362        qualityAnalyzer.QualityParameter.Hidden = true;
363        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
364        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
365        layerQualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
366        layerQualityAnalyzer.MaximizationParameter.Hidden = true;
367        layerQualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
368        layerQualityAnalyzer.QualityParameter.Hidden = true;
369        layerQualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
370        layerQualityAnalyzer.BestKnownQualityParameter.Hidden = true;
371      }
372    }
373    private void ParameterizeTerminators() {
374      qualityTerminator.Parameterize(qualityAnalyzer.CurrentBestQualityParameter, Problem);
375    }
376    private void ParameterizeAgeInheritanceReduction() {
377      AgeInheritanceReduction.Value = GetAgeInheritanceReduction(AgeInheritance.Value);
378    }
379    protected abstract ReductionOperations GetAgeInheritanceReduction(AgeInheritance ageInheritance);
380    private void ParameterizeAgeLimits() {
381      var scheme = AgingScheme.Value;
382      int ageGap = AgeGap.Value;
383      int numberOfLayers = NumberOfLayers.Value;
384      AgeLimits = scheme.CalculateAgeLimits(ageGap, numberOfLayers);
385    }
386    protected virtual void ParameterizeStochasticOperator(IOperator @operator) {
387      var stochasticOperator = @operator as IStochasticOperator;
388      if (stochasticOperator != null) {
389        stochasticOperator.RandomParameter.ActualName = "GlobalRandom";
390        stochasticOperator.RandomParameter.Hidden = true;
391      }
392    }
393    protected virtual void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
394      var stochasticOperator = @operator as IStochasticOperator;
395      if (stochasticOperator != null) {
396        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
397        stochasticOperator.RandomParameter.Hidden = true;
398      }
399    }
400    #endregion
401
402    #region Updates
403    private void UpdateAnalyzers() {
404      Analyzer.Operators.Clear();
405      LayerAnalyzer.Operators.Clear();
406
407      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
408      LayerAnalyzer.Operators.Add(layerQualityAnalyzer, layerQualityAnalyzer.EnabledByDefault);
409
410      if (Problem != null) {
411        foreach (var analyzer in Problem.Operators.OfType<IAnalyzer>()) {
412          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
413        }
414      }
415    }
416    #endregion
417  }
418}
Note: See TracBrowser for help on using the repository browser.