Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2350

  • Implemented AlpsSsGeneticAlgorithm.
  • Created empty AlpsSsGeneticAlgorithmMainLoop.
File size: 14.7 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    #endregion
67
68    #region Properties
69    public IntArray PopulationSize {
70      get { return PopulationSizeParameter.Value; }
71      set { PopulationSizeParameter.Value = value; }
72    }
73    public IntValue MaximumGenerations {
74      get { return MaximumGenerationsParameter.Value; }
75      set { MaximumGenerationsParameter.Value = value; }
76    }
77
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    }
102
103    private AlpsGeneticAlgorithmMainLoop MainLoop {
104      get { return OperatorGraph.Iterate().OfType<AlpsGeneticAlgorithmMainLoop>().First(); }
105    }
106    #endregion
107
108    [StorableConstructor]
109    private AlpsGeneticAlgorithm(bool deserializing)
110      : base(deserializing) { }
111    private AlpsGeneticAlgorithm(AlpsGeneticAlgorithm original, Cloner cloner)
112      : base(original, cloner) {
113      Initialize();
114    }
115    public override IDeepCloneable Clone(Cloner cloner) {
116      return new AlpsGeneticAlgorithm(this, cloner);
117    }
118    public AlpsGeneticAlgorithm()
119      : base() {
120      Parameters.Add(new ValueParameter<IntArray>("PopulationSize", "The size of the population of solutions each layer.", new IntArray(new[] { 100 })));
121      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations that should be processed.", new IntValue(1000)));
122      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
123      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
124      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
125      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
126      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
127      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 });
128
129      var globalRandomCreator = new RandomCreator();
130      var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
131      var layer0Processor = new LayerUniformSubScopesProcessor();
132      var localRandomCreator = new LocalRandomCreator();
133      var layerVariableCreator = new VariableCreator();
134      var layerSolutionsCreator = new SolutionsCreator();
135      var initializeAgeProcessor = new UniformSubScopesProcessor();
136      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
137      var initializeLayerPopulationSize = new SubScopesCounter() { Name = "Init LayerPopulationCounter" };
138      var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
139      var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
140      var resultsCollector = new ResultsCollector();
141      var mainLoop = new AlpsGeneticAlgorithmMainLoop();
142
143      OperatorGraph.InitialOperator = globalRandomCreator;
144
145      globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
146      globalRandomCreator.SeedParameter.Value = null;
147      globalRandomCreator.SetSeedRandomlyParameter.Value = null;
148      globalRandomCreator.Successor = layer0Creator;
149
150      layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
151      layer0Creator.Successor = layer0Processor;
152
153      layer0Processor.Operator = localRandomCreator;
154      layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
155
156      localRandomCreator.Successor = layerVariableCreator;
157
158      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer", new IntValue(0)));
159      layerVariableCreator.Successor = layerSolutionsCreator;
160
161      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
162      layerSolutionsCreator.Successor = initializeAgeProcessor;
163
164      initializeAgeProcessor.Operator = initializeAge;
165      initializeAgeProcessor.Successor = initializeLayerPopulationSize;
166
167      initializeLayerPopulationSize.ValueParameter.ActualName = "LayerPopulationSize";
168      initializeLayerPopulationSize.Successor = initializeLocalEvaluatedSolutions;
169
170      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("Age", new IntValue(0)));
171      initializeAge.Successor = null;
172
173      initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
174      initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "LayerPopulationSize";
175      initializeLocalEvaluatedSolutions.Successor = null;
176
177      initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
178      initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
179      initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
180      initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
181      initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
182
183      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
184      resultsCollector.Successor = mainLoop;
185
186      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
187        SelectorParameter.ValidValues.Add(selector);
188      var tournamentSelector = SelectorParameter.ValidValues.OfType<TournamentSelector>().FirstOrDefault();
189      if (tournamentSelector != null) {
190        tournamentSelector.GroupSizeParameter.Value = new IntValue(5);
191        SelectorParameter.Value = tournamentSelector;
192      }
193
194      ParameterizeSelectors();
195      Initialize();
196    }
197
198    #region Events
199    protected override void OnProblemChanged() {
200      base.OnProblemChanged();
201      ParameterizeSolutionsCreator();
202      ParameterizeMainLoop();
203      ParameterizeSelectors();
204      ParameterizeIterationBasedOperators();
205      UpdateCrossovers();
206      UpdateMutators();
207    }
208    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
209      base.Problem_SolutionCreatorChanged(sender, e);
210      ParameterizeSolutionsCreator();
211    }
212    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
213      base.Problem_EvaluatorChanged(sender, e);
214      ParameterizeSolutionsCreator();
215      ParameterizeMainLoop();
216      ParameterizeSelectors();
217    }
218    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
219      base.Problem_OperatorsChanged(sender, e);
220      ParameterizeIterationBasedOperators();
221      UpdateCrossovers();
222      UpdateMutators();
223    }
224    protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
225      base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
226      ParameterizeMainLoop();
227      ParameterizeSelectors();
228    }
229    #endregion
230
231    #region Parameterization
232    private void Initialize() {
233    }
234    private void ParameterizeSolutionsCreator() {
235      MainLoop.LayerUpdator.SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
236      MainLoop.LayerUpdator.SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
237    }
238    private void ParameterizeMainLoop() {
239      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
240      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
241      MainLoop.MainOperator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
242      MainLoop.MainOperator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
243      MainLoop.MainOperator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
244      MainLoop.LayerUpdator.SolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
245    }
246    private void ParameterizeSelectors() {
247      foreach (var selector in SelectorParameter.ValidValues) {
248        selector.CopySelected = new BoolValue(true);
249        // Explicit setting of NumberOfSelectedSubScopesParameter is not required anymore because the NumberOfSelectedSubScopesCalculator calculates it itself
250        //selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSize - Elites.Value));
251        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
252        ParameterizeStochasticOperatorForLayer(selector);
253      }
254      if (Problem != null) {
255        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
256          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
257          selector.MaximizationParameter.Hidden = true;
258          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
259          selector.QualityParameter.Hidden = true;
260        }
261      }
262    }
263    private void ParameterizeIterationBasedOperators() {
264      if (Problem != null) {
265        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
266          @operator.IterationsParameter.ActualName = "Generations";
267          @operator.IterationsParameter.Hidden = true;
268          @operator.MaximumIterationsParameter.ActualName = MaximumGenerationsParameter.Name;
269          @operator.MaximumIterationsParameter.Hidden = true;
270        }
271      }
272    }
273    #endregion
274
275    #region Updates
276    private void UpdateCrossovers() {
277      var oldCrossover = CrossoverParameter.Value;
278      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
279      CrossoverParameter.ValidValues.Clear();
280      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
281        ParameterizeStochasticOperatorForLayer(crossover);
282        CrossoverParameter.ValidValues.Add(crossover);
283      }
284      if (oldCrossover != null) {
285        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
286        if (crossover != null)
287          CrossoverParameter.Value = crossover;
288        else
289          oldCrossover = null;
290      }
291      if (oldCrossover == null && defaultCrossover != null)
292        CrossoverParameter.Value = defaultCrossover;
293    }
294    private void UpdateMutators() {
295      var oldMutator = MutatorParameter.Value;
296      MutatorParameter.ValidValues.Clear();
297      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
298        ParameterizeStochasticOperatorForLayer(mutator);
299        MutatorParameter.ValidValues.Add(mutator);
300      }
301      if (oldMutator != null) {
302        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
303        if (mutator != null)
304          MutatorParameter.Value = mutator;
305      }
306    }
307    #endregion
308  }
309}
Note: See TracBrowser for help on using the repository browser.