Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2350

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