Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ALPS/HeuristicLab.Algorithms.ALPS/3.3/AlpsGeneticAlgorithmMainLoop.cs @ 13035

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

#2269 Fixed removing unnecessary operators.

File size: 13.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.Linq;
23using HeuristicLab.Algorithms.GeneticAlgorithm;
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.Selection;
33
34namespace HeuristicLab.Algorithms.ALPS {
35
36  [Item("AlpsGeneticAlgorithmMainLoop", "An ALPS genetic algorithm main loop operator.")]
37  [StorableClass]
38  public sealed class AlpsGeneticAlgorithmMainLoop : AlgorithmOperator {
39    #region Parameter Properties
40    public ValueLookupParameter<BoolValue> MaximizationParameter {
41      get { return (ValueLookupParameter<BoolValue>)Parameters["Maximization"]; }
42    }
43    public ScopeTreeLookupParameter<DoubleValue> QualityParameter {
44      get { return (ScopeTreeLookupParameter<DoubleValue>)Parameters["Quality"]; }
45    }
46    public ILookupParameter<IntValue> MaximumGenerationsParameter {
47      get { return (ILookupParameter<IntValue>)Parameters["MaximumGenerations"]; }
48    }
49    public ILookupParameter<IOperator> AnalyzerParameter {
50      get { return (ILookupParameter<IOperator>)Parameters["Analyzer"]; }
51    }
52    public ILookupParameter<IOperator> LayerAnalyzerParameter {
53      get { return (ILookupParameter<IOperator>)Parameters["LayerAnalyzer"]; }
54    }
55    #endregion
56
57    public GeneticAlgorithmMainLoop MainOperator {
58      get { return OperatorGraph.Iterate().OfType<GeneticAlgorithmMainLoop>().First(); }
59    }
60    public EldersEmigrator EldersEmigrator {
61      get { return OperatorGraph.Iterate().OfType<EldersEmigrator>().First(); }
62    }
63    public LayerUpdator LayerUpdator {
64      get { return OperatorGraph.Iterate().OfType<LayerUpdator>().First(); }
65    }
66
67    [StorableConstructor]
68    private AlpsGeneticAlgorithmMainLoop(bool deserializing)
69      : base(deserializing) { }
70    private AlpsGeneticAlgorithmMainLoop(AlpsGeneticAlgorithmMainLoop original, Cloner cloner)
71      : base(original, cloner) { }
72    public override IDeepCloneable Clone(Cloner cloner) {
73      return new AlpsGeneticAlgorithmMainLoop(this, cloner);
74    }
75    public AlpsGeneticAlgorithmMainLoop()
76      : base() {
77      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false.") { Hidden = true });
78      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The value which represents the quality of a solution."));
79      Parameters.Add(new LookupParameter<IntValue>("MaximumGenerations", "The maximum number of generations that the algorithm should process."));
80      Parameters.Add(new LookupParameter<IOperator>("Analyzer", "The operator used to the analyze all individuals."));
81      Parameters.Add(new LookupParameter<IOperator>("LayerAnalyzer", "The operator used to analyze each layer."));
82
83      var variableCreator = new VariableCreator() { Name = "Initialize" };
84      var initLayerAnalyzerProcessor = new SubScopesProcessor();
85      var layerVariableCreator = new VariableCreator() { Name = "Initialize Layer" };
86      var initLayerAnalyzerPlaceholder = new Placeholder() { Name = "LayerAnalyzer (Placeholder)" };
87      var initAnalyzerPlaceholder = new Placeholder() { Name = "Analyzer (Placeholder)" };
88      var resultsCollector = new ResultsCollector();
89      var matingPoolCreator = new MatingPoolCreator() { Name = "Create Mating Pools" };
90      var matingPoolProcessor = new UniformSubScopesProcessor();
91      var initializeLayer = new Assigner() { Name = "Reset LayerEvaluatedSolutions" };
92      var mainOperator = CreatePreparedGeneticAlgorithmMainLoop();
93      var generationsIcrementor = new IntCounter() { Name = "Increment Generations" };
94      var evaluatedSolutionsReducer = new DataReducer() { Name = "Increment EvaluatedSolutions" };
95      var eldersEmigrator = new EldersEmigrator() { Name = "Emigrate Elders" };
96      var layerUpdator = new LayerUpdator(mainOperator) { Name = "Update Layers" };
97      var layerAnalyzerProcessor = new UniformSubScopesProcessor();
98      var layerAnalyzerPlaceholder = new Placeholder() { Name = "LayerAnalyzer (Placeholder)" };
99      var analyzerPlaceholder = new Placeholder() { Name = "Analyzer (Placeholder)" };
100      var termination = new TerminationOperator();
101
102      OperatorGraph.InitialOperator = variableCreator;
103
104      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Generations", new IntValue(0)));
105      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("GenerationsSinceLastRefresh", new IntValue(0)));
106      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("OpenLayers", new IntValue(1)));
107      variableCreator.Successor = initLayerAnalyzerProcessor;
108
109      initLayerAnalyzerProcessor.Operators.Add(layerVariableCreator);
110      initLayerAnalyzerProcessor.Successor = initAnalyzerPlaceholder;
111
112      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("LayerEvaluatedSolutions"));
113      layerVariableCreator.CollectedValues.Add(new ValueParameter<ResultCollection>("LayerResults"));
114      layerVariableCreator.Successor = initLayerAnalyzerPlaceholder;
115
116      initLayerAnalyzerPlaceholder.OperatorParameter.ActualName = LayerAnalyzerParameter.Name;
117      initLayerAnalyzerPlaceholder.Successor = null;
118
119      initAnalyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
120      initAnalyzerPlaceholder.Successor = resultsCollector;
121
122      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Generations"));
123      resultsCollector.CollectedValues.Add(new ScopeTreeLookupParameter<ResultCollection>("LayerResults", "Result set for each layer", "LayerResults"));
124      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("OpenLayers"));
125      resultsCollector.CopyValue = new BoolValue(false);
126      resultsCollector.Successor = matingPoolCreator;
127
128      matingPoolCreator.Successor = matingPoolProcessor;
129
130      matingPoolProcessor.Parallel.Value = true;
131      matingPoolProcessor.Operator = initializeLayer;
132      matingPoolProcessor.Successor = generationsIcrementor;
133
134      initializeLayer.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
135      initializeLayer.RightSideParameter.Value = new IntValue(0);
136      initializeLayer.Successor = mainOperator;
137
138      generationsIcrementor.ValueParameter.ActualName = "Generations";
139      generationsIcrementor.Increment = new IntValue(1);
140      generationsIcrementor.Successor = evaluatedSolutionsReducer;
141
142      evaluatedSolutionsReducer.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
143      evaluatedSolutionsReducer.TargetParameter.ActualName = "EvaluatedSolutions";
144      evaluatedSolutionsReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Sum);
145      evaluatedSolutionsReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Sum);
146      evaluatedSolutionsReducer.Successor = eldersEmigrator;
147
148      eldersEmigrator.Successor = layerUpdator;
149
150      layerUpdator.Successor = layerAnalyzerProcessor;
151
152      layerAnalyzerProcessor.Operator = layerAnalyzerPlaceholder;
153      layerAnalyzerProcessor.Successor = analyzerPlaceholder;
154
155      layerAnalyzerPlaceholder.OperatorParameter.ActualName = LayerAnalyzerParameter.Name;
156
157      analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
158      analyzerPlaceholder.Successor = termination;
159
160      termination.ContinueBranch = matingPoolCreator;
161    }
162
163    private GeneticAlgorithmMainLoop CreatePreparedGeneticAlgorithmMainLoop() {
164      var mainLoop = new GeneticAlgorithmMainLoop();
165
166      var oldInitialOp = mainLoop.OperatorGraph.InitialOperator;
167      var selector = mainLoop.OperatorGraph.Iterate().OfType<Placeholder>().First(o => o.OperatorParameter.ActualName == "Selector");
168      var crossover = mainLoop.OperatorGraph.Iterate().OfType<Placeholder>().First(o => o.OperatorParameter.ActualName == "Crossover");
169      var subScopesCounter = mainLoop.OperatorGraph.Iterate().OfType<SubScopesCounter>().First();
170      var elitesMerger = mainLoop.OperatorGraph.Iterate().OfType<MergingReducer>().First();
171
172      // Operator starts with calculating number of selected scopes base on plus/comma-selection replacement scheme
173      var numberOfSubScopesBranch = new ConditionalBranch() { Name = "PlusSelection?" };
174      var numberOfSelectedSubScopesPlusCalculator = new ExpressionCalculator() { Name = "NumberOfSelectedSubScopes = PopulationSize * 2" };
175      var numberOfSelectedSubScopesCalculator = new ExpressionCalculator() { Name = "NumberOfSelectedSubScopes = (PopulationSize - Elites) * 2" };
176      var replacementBranch = new ConditionalBranch() { Name = "PlusSelection?" };
177
178      // Set new initial operator
179      mainLoop.OperatorGraph.InitialOperator = numberOfSubScopesBranch;
180
181      numberOfSubScopesBranch.ConditionParameter.ActualName = "PlusSelection";
182      numberOfSubScopesBranch.TrueBranch = numberOfSelectedSubScopesPlusCalculator;
183      numberOfSubScopesBranch.FalseBranch = numberOfSelectedSubScopesCalculator;
184      numberOfSubScopesBranch.Successor = selector;
185
186      numberOfSelectedSubScopesPlusCalculator.CollectedValues.Add(new LookupParameter<IntValue>("PopulationSize"));
187      numberOfSelectedSubScopesPlusCalculator.ExpressionResultParameter.ActualName = "NumberOfSelectedSubScopes";
188      numberOfSelectedSubScopesPlusCalculator.ExpressionParameter.Value = new StringValue("PopulationSize 2 * toint");
189
190      numberOfSelectedSubScopesCalculator.CollectedValues.Add(new LookupParameter<IntValue>("PopulationSize"));
191      numberOfSelectedSubScopesCalculator.CollectedValues.Add(new LookupParameter<IntValue>("Elites"));
192      numberOfSelectedSubScopesCalculator.ExpressionResultParameter.ActualName = "NumberOfSelectedSubScopes";
193      numberOfSelectedSubScopesCalculator.ExpressionParameter.Value = new StringValue("PopulationSize Elites - 2 * toint");
194
195      // Use Elitism or Plus-Selection as replacement strategy
196      var selectedProcessor = (SubScopesProcessor)selector.Successor;
197      var elitismReplacement = selectedProcessor.Successor;
198      selectedProcessor.Successor = replacementBranch;
199      replacementBranch.ConditionParameter.ActualName = "PlusSelection";
200      replacementBranch.FalseBranch = elitismReplacement;
201
202      // Plus selection replacement
203      var replacementMergingReducer = new MergingReducer();
204      var replacementBestSelector = new BestSelector();
205      var replacementRightReducer = new RightReducer();
206      replacementBranch.TrueBranch = replacementMergingReducer;
207
208      replacementMergingReducer.Successor = replacementBestSelector;
209
210      replacementBestSelector.NumberOfSelectedSubScopesParameter.ActualName = "PopulationSize";
211      replacementBestSelector.CopySelected = new BoolValue(false);
212      replacementBestSelector.Successor = replacementRightReducer;
213
214      replacementRightReducer.Successor = null;
215
216      // Increment ages of all individuals after replacement
217      var incrementAgeProcessor = new UniformSubScopesProcessor();
218      var ageIncrementor = new IntCounter() { Name = "Increment Age" };
219      replacementBranch.Successor = incrementAgeProcessor;
220      incrementAgeProcessor.Operator = ageIncrementor;
221      incrementAgeProcessor.Successor = null;
222      ageIncrementor.ValueParameter.ActualName = "Age";
223      ageIncrementor.Increment = new IntValue(1);
224      //ageIncrementor.Successor = null;
225
226      // Insert AgeCalculator between crossover and its successor
227      var crossoverSuccessor = crossover.Successor;
228      var ageCalculator = new WeightingReducer() { Name = "Calculate Age" };
229      crossover.Successor = ageCalculator;
230
231      ageCalculator.ParameterToReduce.ActualName = "Age";
232      ageCalculator.TargetParameter.ActualName = "Age";
233      ageCalculator.WeightParameter.ActualName = "AgeInheritance";
234      ageCalculator.Successor = crossoverSuccessor;
235
236      // When counting the evaluated solutions, write in LayerEvaluatedSolutions
237      subScopesCounter.ValueParameter.ActualName = "LayerEvaluatedSolutions";
238      subScopesCounter.AccumulateParameter.Value = new BoolValue(false);
239
240      // Instead of generational loop after merging of elites, stop
241      elitesMerger.Successor = null;
242
243      // Parameterize
244      foreach (var stochasticOperator in mainLoop.OperatorGraph.Iterate().OfType<IStochasticOperator>())
245        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
246      foreach (var stochasticBranch in mainLoop.OperatorGraph.Iterate().OfType<StochasticBranch>())
247        stochasticBranch.RandomParameter.ActualName = "LocalRandom";
248
249      // Remove unused operators
250      var usedOperators = mainLoop.OperatorGraph.Iterate();
251      var unusedOperators = mainLoop.OperatorGraph.Operators.Except(usedOperators);
252      foreach (var op in unusedOperators.ToList())
253        mainLoop.OperatorGraph.Operators.Remove(op);
254
255      return mainLoop;
256    }
257  }
258}
Note: See TracBrowser for help on using the repository browser.