Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithm.cs @ 12858

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

#2269

  • Added missing Hook.
  • Sealed some classes.
File size: 17.0 KB
RevLine 
[11567]1#region License Information
2/* HeuristicLab
[12018]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[11567]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;
[12531]23using System.Collections.Generic;
[11578]24using System.Linq;
[11567]25using HeuristicLab.Common;
26using HeuristicLab.Core;
[11568]27using HeuristicLab.Data;
28using HeuristicLab.Operators;
[11567]29using HeuristicLab.Optimization;
[11578]30using HeuristicLab.Optimization.Operators;
[11568]31using HeuristicLab.Parameters;
[11567]32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[11578]33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35using HeuristicLab.Selection;
[11567]36
37namespace HeuristicLab.Algorithms.ALPS {
38  [Item("ALPS Genetic Algorithm", "A genetic algorithm with an age-layered population structure.")]
39  [Creatable("Algorithms")]
40  [StorableClass]
[12119]41  public sealed class AlpsGeneticAlgorithm : Alps {
[11567]42    #region Parameter Properties
[12035]43    private IValueParameter<IntArray> PopulationSizeParameter {
44      get { return (IValueParameter<IntArray>)Parameters["PopulationSize"]; }
[11568]45    }
46    public IConstrainedValueParameter<ISelector> SelectorParameter {
47      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
48    }
49    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
50      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
51    }
52    private IValueParameter<PercentValue> MutationProbabilityParameter {
53      get { return (IValueParameter<PercentValue>)Parameters["MutationProbability"]; }
54    }
55    public IConstrainedValueParameter<IManipulator> MutatorParameter {
56      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
57    }
58    private IValueParameter<IntValue> ElitesParameter {
59      get { return (IValueParameter<IntValue>)Parameters["Elites"]; }
60    }
61    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
62      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
63    }
[12186]64    private IValueParameter<BoolValue> PlusSelectionParameter {
65      get { return (IValueParameter<BoolValue>)Parameters["PlusSelection"]; }
66    }
[11567]67    #endregion
68
69    #region Properties
[12035]70    public IntArray PopulationSize {
[11568]71      get { return PopulationSizeParameter.Value; }
72      set { PopulationSizeParameter.Value = value; }
73    }
[12533]74    public int MaximumGenerations {
75      get { return generationsTerminator.Threshold.Value; }
76      set { generationsTerminator.Threshold.Value = value; }
77    }
[11568]78    public ISelector Selector {
79      get { return SelectorParameter.Value; }
80      set { SelectorParameter.Value = value; }
81    }
82    public ICrossover Crossover {
83      get { return CrossoverParameter.Value; }
84      set { CrossoverParameter.Value = value; }
85    }
86    public PercentValue MutationProbability {
87      get { return MutationProbabilityParameter.Value; }
88      set { MutationProbabilityParameter.Value = value; }
89    }
90    public IManipulator Mutator {
91      get { return MutatorParameter.Value; }
92      set { MutatorParameter.Value = value; }
93    }
94    public IntValue Elites {
95      get { return ElitesParameter.Value; }
96      set { ElitesParameter.Value = value; }
97    }
98    public bool ReevaluteElites {
99      get { return ReevaluateElitesParameter.Value.Value; }
100      set { ReevaluateElitesParameter.Value.Value = value; }
101    }
[12186]102    public bool PlusSelection {
103      get { return PlusSelectionParameter.Value.Value; }
104      set { PlusSelectionParameter.Value.Value = value; }
105    }
[11578]106
[11580]107    private AlpsGeneticAlgorithmMainLoop MainLoop {
108      get { return OperatorGraph.Iterate().OfType<AlpsGeneticAlgorithmMainLoop>().First(); }
109    }
[11676]110    #endregion
111
[12531]112    [Storable]
113    private ComparisonTerminator<IntValue> generationsTerminator;
114
[11567]115    [StorableConstructor]
116    private AlpsGeneticAlgorithm(bool deserializing)
117      : base(deserializing) { }
[12570]118    [StorableHook(HookType.AfterDeserialization)]
119    private void AfterDeserialization() {
120      Initialize();
121    }
[11567]122    private AlpsGeneticAlgorithm(AlpsGeneticAlgorithm original, Cloner cloner)
123      : base(original, cloner) {
[12531]124      generationsTerminator = cloner.Clone(original.generationsTerminator);
[11578]125      Initialize();
[11567]126    }
127    public override IDeepCloneable Clone(Cloner cloner) {
128      return new AlpsGeneticAlgorithm(this, cloner);
129    }
130    public AlpsGeneticAlgorithm()
131      : base() {
[12048]132      Parameters.Add(new ValueParameter<IntArray>("PopulationSize", "The size of the population of solutions each layer.", new IntArray(new[] { 100 })));
[11568]133      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
134      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
135      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
136      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
137      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
138      Parameters.Add(new FixedValueParameter<BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)", new BoolValue(false)) { Hidden = true });
[12186]139      Parameters.Add(new ValueParameter<BoolValue>("PlusSelection", "Include the parents in the selection of the invividuals for the next generation.", new BoolValue(false)) { Hidden = true });
[11578]140
141      var globalRandomCreator = new RandomCreator();
142      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
[12035]143      var layer0Processor = new LayerUniformSubScopesProcessor();
[11578]144      var localRandomCreator = new LocalRandomCreator();
[11585]145      var layerVariableCreator = new VariableCreator();
[11578]146      var layerSolutionsCreator = new SolutionsCreator();
147      var initializeAgeProcessor = new UniformSubScopesProcessor();
148      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
[11676]149      var initializeLayerPopulationSize = new SubScopesCounter() { Name = "Init LayerPopulationCounter" };
150      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
[11578]151      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
152      var resultsCollector = new ResultsCollector();
[11580]153      var mainLoop = new AlpsGeneticAlgorithmMainLoop();
154
[11578]155      OperatorGraph.InitialOperator = globalRandomCreator;
156
157      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
158      globalRandomCreator.SeedParameter.Value = null;
159      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
160      globalRandomCreator.Successor = layer0Creator;
161
162      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
163      layer0Creator.Successor = layer0Processor;
164
[12035]165      layer0Processor.Operator = localRandomCreator;
[11578]166      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
167
[11585]168      localRandomCreator.Successor = layerVariableCreator;
[11578]169
[11585]170      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer", new IntValue(0)));
171      layerVariableCreator.Successor = layerSolutionsCreator;
172
[11578]173      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
174      layerSolutionsCreator.Successor = initializeAgeProcessor;
175
176      initializeAgeProcessor.Operator = initializeAge;
[11676]177      initializeAgeProcessor.Successor = initializeLayerPopulationSize;
[11578]178
[11676]179      initializeLayerPopulationSize.ValueParameter.ActualName = "LayerPopulationSize";
180      initializeLayerPopulationSize.Successor = initializeLocalEvaluatedSolutions;
181
[11578]182      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("Age", new IntValue(0)));
183      initializeAge.Successor = null;
184
[11676]185      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
186      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "LayerPopulationSize";
[11578]187      initializeLocalEvaluatedSolutions.Successor = null;
188
189      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
190      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
[11590]191      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
[11578]192      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
193      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
194
[11609]195      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
[11578]196      resultsCollector.Successor = mainLoop;
197
198      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
199        SelectorParameter.ValidValues.Add(selector);
[12119]200      var tournamentSelector = SelectorParameter.ValidValues.OfType<TournamentSelector>().FirstOrDefault();
201      if (tournamentSelector != null) {
[12260]202        tournamentSelector.GroupSizeParameter.Value = new IntValue(4);
[12119]203        SelectorParameter.Value = tournamentSelector;
204      }
[11578]205
[12548]206      generationsTerminator = new ComparisonTerminator<IntValue>("Generations", ComparisonType.Less, new IntValue(1000)) { Name = "Generations" };
207
[11578]208      ParameterizeSelectors();
[12548]209
210      UpdateTerminators();
211
[11578]212      Initialize();
[11567]213    }
[11578]214
215    #region Events
216    protected override void OnProblemChanged() {
[12119]217      base.OnProblemChanged();
[11578]218      ParameterizeSolutionsCreator();
219      ParameterizeMainLoop();
220      ParameterizeSelectors();
[12120]221      ParameterizeIterationBasedOperators();
[11578]222      UpdateCrossovers();
223      UpdateMutators();
[12548]224      UpdateTerminators();
[11578]225    }
226    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
[12119]227      base.Problem_SolutionCreatorChanged(sender, e);
[11578]228      ParameterizeSolutionsCreator();
229    }
230    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
[12119]231      base.Problem_EvaluatorChanged(sender, e);
[11578]232      ParameterizeSolutionsCreator();
233      ParameterizeMainLoop();
234      ParameterizeSelectors();
235    }
236    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
[12119]237      base.Problem_OperatorsChanged(sender, e);
[12120]238      ParameterizeIterationBasedOperators();
[11578]239      UpdateCrossovers();
240      UpdateMutators();
[12548]241      UpdateTerminators();
[11578]242    }
[12119]243    protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
244      base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
[11578]245      ParameterizeMainLoop();
246      ParameterizeSelectors();
247    }
248    #endregion
249
250    #region Parameterization
251    private void Initialize() {
252    }
253    private void ParameterizeSolutionsCreator() {
[11590]254      MainLoop.LayerUpdator.SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
255      MainLoop.LayerUpdator.SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
[11578]256    }
257    private void ParameterizeMainLoop() {
[12045]258      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
259      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[11583]260      MainLoop.MainOperator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
261      MainLoop.MainOperator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
262      MainLoop.MainOperator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[11609]263      MainLoop.LayerUpdator.SolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
[11578]264    }
265    private void ParameterizeSelectors() {
266      foreach (var selector in SelectorParameter.ValidValues) {
267        selector.CopySelected = new BoolValue(true);
[12035]268        // Explicit setting of NumberOfSelectedSubScopesParameter is not required anymore because the NumberOfSelectedSubScopesCalculator calculates it itself
269        //selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSize - Elites.Value));
[11578]270        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
271        ParameterizeStochasticOperatorForLayer(selector);
272      }
273      if (Problem != null) {
274        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
275          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
276          selector.MaximizationParameter.Hidden = true;
277          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
278          selector.QualityParameter.Hidden = true;
279        }
280      }
281    }
[12120]282    private void ParameterizeIterationBasedOperators() {
283      if (Problem != null) {
284        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
285          @operator.IterationsParameter.ActualName = "Generations";
286          @operator.IterationsParameter.Hidden = true;
[12531]287          @operator.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
[12120]288          @operator.MaximumIterationsParameter.Hidden = true;
289        }
290      }
291    }
[12271]292
293    protected override ReductionOperations GetAgeInheritanceReduction(AgeInheritance ageInheritance) {
294      switch (ageInheritance) {
295        case ALPS.AgeInheritance.Older: return ReductionOperations.Max;
296        case ALPS.AgeInheritance.Agerage: return ReductionOperations.Avg;
297        case ALPS.AgeInheritance.Younger: return ReductionOperations.Min;
298        default: throw new NotSupportedException("AgeInheritance " + ageInheritance + " is not supported.");
299      }
300    }
[11578]301    #endregion
302
303    #region Updates
[12548]304    private void UpdateTerminators() {
[12531]305      var newTerminators = new Dictionary<ITerminator, bool> {
306        {generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
[12548]307        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
308        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
309        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
[12531]310      };
[12548]311      if (Problem != null) {
312        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
313          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
314      }
[12531]315
[12548]316      Terminators.Operators.Clear();
[12531]317
318      foreach (var newTerminator in newTerminators)
[12548]319        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
[12531]320    }
[11578]321    private void UpdateCrossovers() {
322      var oldCrossover = CrossoverParameter.Value;
323      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
324      CrossoverParameter.ValidValues.Clear();
325      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
326        ParameterizeStochasticOperatorForLayer(crossover);
327        CrossoverParameter.ValidValues.Add(crossover);
328      }
329      if (oldCrossover != null) {
330        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
[11678]331        if (crossover != null)
332          CrossoverParameter.Value = crossover;
333        else
334          oldCrossover = null;
[11578]335      }
336      if (oldCrossover == null && defaultCrossover != null)
337        CrossoverParameter.Value = defaultCrossover;
338    }
339    private void UpdateMutators() {
340      var oldMutator = MutatorParameter.Value;
341      MutatorParameter.ValidValues.Clear();
342      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
343        ParameterizeStochasticOperatorForLayer(mutator);
344        MutatorParameter.ValidValues.Add(mutator);
345      }
346      if (oldMutator != null) {
347        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
[11678]348        if (mutator != null)
349          MutatorParameter.Value = mutator;
[11578]350      }
351    }
352    #endregion
[11567]353  }
354}
Note: See TracBrowser for help on using the repository browser.