Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Algorithms.ALPS.SteadyState/3.3/AlpsSsGeneticAlgorithm.cs @ 12159

Last change on this file since 12159 was 12159, checked in by pfleck, 10 years ago

#2350

  • Changed the SteadyStateMatingPoolCreator to put the mating pool in the working scope.
  • Added the ScopeIndexAssigner for setting the correct layer number.
  • Adapted the AlpsSsGeneticAlgorithmMainLoop.
File size: 14.9 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.SteadyState {
37  [Item("ALPS Steady-State Genetic Algorithm", "A genetic algorithmn with a steady-state age-layered population structure")]
38  [Creatable("Algorithms")]
39  [StorableClass]
40  public class AlpsSsGeneticAlgorithm : Alps {
41    #region Parameter Properties
42    private IValueParameter<IntValue> LayerSizeParameter {
43      get { return (IValueParameter<IntValue>)Parameters["LayerSize"]; }
44    }
45    private IValueParameter<IntValue> MaximumIterationsParameter {
46      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
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 IntValue LayerSize {
70      get { return LayerSizeParameter.Value; }
71      set { LayerSizeParameter.Value = value; }
72    }
73    public IntValue MaximumIterations {
74      get { return MaximumIterationsParameter.Value; }
75      set { MaximumIterationsParameter.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    #endregion
103
104    private AlpsSsGeneticAlgorithmMainLoop MainLoop {
105      get { return OperatorGraph.Iterate().OfType<AlpsSsGeneticAlgorithmMainLoop>().First(); }
106    }
107
108    [StorableConstructor]
109    private AlpsSsGeneticAlgorithm(bool deserializing)
110      : base(deserializing) { }
111    private AlpsSsGeneticAlgorithm(AlpsSsGeneticAlgorithm original, Cloner cloner)
112      : base(original, cloner) {
113      Initialize();
114    }
115    public override IDeepCloneable Clone(Cloner cloner) {
116      return new AlpsSsGeneticAlgorithm(this, cloner);
117    }
118
119    public AlpsSsGeneticAlgorithm()
120      : base() {
121      Parameters.Add(new ValueParameter<IntValue>("LayerSize", "The size of the population of solutions each layer.", new IntValue(100)));
122      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of iterations that should be processed.", new IntValue(1000)));
123      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
124      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
125      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
126      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
127      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
128      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 });
129      AgeInheritance = new ReductionOperation(ReductionOperations.Min);
130
131      var randomCreator = new RandomCreator();
132      var workingScopeCreator = new NamedSubScopesCreator() { Name = "Create WorkingScope and Layers-Scope" };
133      var layersProcessor = new NamedSubScopeProcessor() { Name = "Process Layers-Scope" };
134      var layerCreator = new SubScopesCreator() { Name = "Create Layer" };
135      var layerProcessor = new /*Layer*/UniformSubScopesProcessor();
136      var layerVariableCreator = new VariableCreator() { Name = "Initialize Layer" };
137      var layerNumberCreator = new ScopeIndexAssigner() { Name = "Create Layer Number" };
138      var layerSolutionsCreator = new SolutionsCreator();
139      var initializeAgeProcessor = new UniformSubScopesProcessor();
140      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
141      var initializeEvaluatedSolutions = new ExpressionCalculator() { Name = "Initialize EvaluatedSolutions" };
142      var initializePopulationSize = new Assigner() { Name = "Initialize PopulationSize" };
143      var resultsCollector = new ResultsCollector();
144      var mainLoop = new AlpsSsGeneticAlgorithmMainLoop();
145
146      OperatorGraph.InitialOperator = randomCreator;
147
148      randomCreator.SeedParameter.Value = null;
149      randomCreator.SetSeedRandomlyParameter.Value = null;
150      randomCreator.Successor = workingScopeCreator;
151
152      workingScopeCreator.NamesParameter.Value = new StringArray(new[] { "WorkingScope", "Layers" });
153      workingScopeCreator.Successor = layersProcessor;
154
155      layersProcessor.TargetScopeParameter.ActualName = "Layers";
156      layersProcessor.Operator = layerCreator;
157      layersProcessor.Successor = initializeEvaluatedSolutions;
158
159      layerCreator.NumberOfSubScopesParameter.ActualName = "NumberOfLayers";
160      layerCreator.NumberOfSubScopesParameter.Value = null;
161      layerCreator.Successor = layerProcessor;
162
163      layerProcessor.Operator = layerVariableCreator;
164
165      layerVariableCreator.CollectedValues.Add(new ValueParameter<ResultCollection>("LayerResults"));
166      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer"));
167      layerVariableCreator.Successor = layerNumberCreator;
168
169      layerNumberCreator.ValueParameter.ActualName = "Layer";
170      layerNumberCreator.Successor = layerSolutionsCreator;
171
172      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = LayerSizeParameter.Name;
173      layerSolutionsCreator.Successor = initializeAgeProcessor;
174
175      initializeAgeProcessor.Operator = initializeAge;
176
177      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("EvalsCreated", new IntValue(1)));
178      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("LastMove", new IntValue(1)));
179
180      initializeEvaluatedSolutions.ExpressionResultParameter.ActualName = "EvaluatedSolutions";
181      initializeEvaluatedSolutions.ExpressionParameter.Value = new StringValue("LayerSize NumberOfLayers * toint");
182      initializeEvaluatedSolutions.CollectedValues.Add(new LookupParameter<IntValue>("LayerSize"));
183      initializeEvaluatedSolutions.CollectedValues.Add(new LookupParameter<IntValue>("NumberOfLayers"));
184      initializeEvaluatedSolutions.Successor = initializePopulationSize;
185
186      initializePopulationSize.LeftSideParameter.ActualName = "PopulationSize";
187      initializePopulationSize.RightSideParameter.ActualName = "EvaluatedSolutions";
188      initializePopulationSize.Successor = resultsCollector;
189
190      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
191      resultsCollector.Successor = mainLoop;
192
193      foreach (var selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
194        SelectorParameter.ValidValues.Add(selector);
195      var tournamentSelector = SelectorParameter.ValidValues.OfType<TournamentSelector>().FirstOrDefault();
196      if (tournamentSelector != null) {
197        tournamentSelector.GroupSizeParameter.Value = new IntValue(5);
198        SelectorParameter.Value = tournamentSelector;
199      }
200
201      ParameterizeSelectors();
202      Initialize();
203    }
204
205    #region Events
206    protected override void OnProblemChanged() {
207      base.OnProblemChanged();
208      ParameterizeSolutionsCreator();
209      ParameterizeMainLoop();
210      ParameterizeSelectors();
211      ParameterizeIterationBasedOperators();
212      UpdateCrossovers();
213      UpdateMutators();
214    }
215    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
216      base.Problem_SolutionCreatorChanged(sender, e);
217      ParameterizeSolutionsCreator();
218    }
219    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
220      base.Problem_EvaluatorChanged(sender, e);
221      ParameterizeSolutionsCreator();
222      ParameterizeMainLoop();
223      ParameterizeSelectors();
224    }
225    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
226      base.Problem_OperatorsChanged(sender, e);
227      ParameterizeIterationBasedOperators();
228      UpdateCrossovers();
229      UpdateMutators();
230    }
231    protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
232      base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
233      ParameterizeMainLoop();
234      ParameterizeSelectors();
235    }
236    #endregion
237
238    #region Parameterization
239    private void Initialize() {
240    }
241    private void ParameterizeSolutionsCreator() {
242    }
243    private void ParameterizeMainLoop() {
244      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
245      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
246    }
247    private void ParameterizeSelectors() {
248      foreach (var selector in SelectorParameter.ValidValues) {
249        selector.CopySelected = new BoolValue(true);
250        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2);
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 = "Iteration";
267          @operator.IterationsParameter.Hidden = true;
268          @operator.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
269          @operator.MaximumIterationsParameter.Hidden = true;
270        }
271      }
272    }
273
274    protected override void ParameterizeStochasticOperator(IOperator @operator) {
275      var stochasticOperator = @operator as IStochasticOperator;
276      if (stochasticOperator != null) {
277        stochasticOperator.RandomParameter.ActualName = "Random";
278        stochasticOperator.RandomParameter.Hidden = true;
279      }
280    }
281    protected override void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
282      var stochasticOperator = @operator as IStochasticOperator;
283      if (stochasticOperator != null) {
284        stochasticOperator.RandomParameter.ActualName = "Random";
285        stochasticOperator.RandomParameter.Hidden = true;
286      }
287    }
288    #endregion
289
290    #region Updates
291    private void UpdateCrossovers() {
292      var oldCrossover = CrossoverParameter.Value;
293      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
294      CrossoverParameter.ValidValues.Clear();
295      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
296        ParameterizeStochasticOperatorForLayer(crossover);
297        CrossoverParameter.ValidValues.Add(crossover);
298      }
299      if (oldCrossover != null) {
300        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
301        if (crossover != null)
302          CrossoverParameter.Value = crossover;
303        else
304          oldCrossover = null;
305      }
306      if (oldCrossover == null && defaultCrossover != null)
307        CrossoverParameter.Value = defaultCrossover;
308    }
309    private void UpdateMutators() {
310      var oldMutator = MutatorParameter.Value;
311      MutatorParameter.ValidValues.Clear();
312      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
313        ParameterizeStochasticOperatorForLayer(mutator);
314        MutatorParameter.ValidValues.Add(mutator);
315      }
316      if (oldMutator != null) {
317        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
318        if (mutator != null)
319          MutatorParameter.Value = mutator;
320      }
321    }
322    #endregion
323  }
324}
Note: See TracBrowser for help on using the repository browser.