Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12186 was 12186, checked in by pfleck, 8 years ago

#2269 Added the possibility for a plus-selection replacement scheme.

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