Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2269 Added AgeInheritance as own type and value for consistent configuration.

File size: 14.6 KB
RevLine 
[11580]1#region License Information
2/* HeuristicLab
[12018]3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[11580]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
[11583]22using System.Linq;
23using HeuristicLab.Algorithms.GeneticAlgorithm;
[11580]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;
[11583]32using HeuristicLab.Selection;
[11580]33
34namespace HeuristicLab.Algorithms.ALPS {
35
36  [Item("AlpsGeneticAlgorithmMainLoop", "An ALPS genetic algorithm main loop operator.")]
[11585]37  [StorableClass]
[11583]38  public sealed class AlpsGeneticAlgorithmMainLoop : AlgorithmOperator {
[11580]39    #region Parameter Properties
[12045]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    }
[11580]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
[11583]57    public GeneticAlgorithmMainLoop MainOperator {
58      get { return OperatorGraph.Iterate().OfType<GeneticAlgorithmMainLoop>().First(); }
59    }
[11586]60    public EldersEmigrator EldersEmigrator {
61      get { return OperatorGraph.Iterate().OfType<EldersEmigrator>().First(); }
62    }
[11590]63    public LayerUpdator LayerUpdator {
64      get { return OperatorGraph.Iterate().OfType<LayerUpdator>().First(); }
65    }
[11583]66
[11580]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() {
[12045]77      Parameters.Add(new ValueLookupParameter<BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
78      Parameters.Add(new ScopeTreeLookupParameter<DoubleValue>("Quality", "The value which represents the quality of a solution."));
[11580]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();
[11590]85      var layerVariableCreator = new VariableCreator() { Name = "Initialize Layer" };
[11580]86      var initLayerAnalyzerPlaceholder = new Placeholder() { Name = "LayerAnalyzer (Placeholder)" };
[11609]87      var initAnalyzerPlaceholder = new Placeholder() { Name = "Analyzer (Placeholder)" };
88      var resultsCollector = new ResultsCollector();
[12045]89      var matingPoolPreProcessor = new UniformSubScopesProcessor() { Name = "MatingPoolPreProcessor" };
90      var matingPoolPreSorter = new SubScopesSorter() { Name = "MatingPoolPreSorter" };
[11583]91      var matingPoolCreator = new MatingPoolCreator() { Name = "Create Mating Pools" };
[12035]92      var matingPoolProcessor = new LayerUniformSubScopesProcessor();
[11590]93      var initializeLayer = new Assigner() { Name = "Reset LayerEvaluatedSolutions" };
[11586]94      var mainOperator = CreatePreparedGeneticAlgorithmMainLoop();
[11583]95      var generationsIcrementor = new IntCounter() { Name = "Increment Generations" };
96      var evaluatedSolutionsReducer = new DataReducer() { Name = "Increment EvaluatedSolutions" };
[11585]97      var eldersEmigrator = new EldersEmigrator() { Name = "Emigrate Elders" };
[11586]98      var layerUpdator = new LayerUpdator(mainOperator) { Name = "Update Layers" };
[12197]99      var layerAnalyzerProcessor = new LayerUniformSubScopesProcessor();
100      var layerAnalyzerPlaceholder = new Placeholder() { Name = "LayerAnalyzer (Placeholder)" };
[11580]101      var analyzerPlaceholder = new Placeholder() { Name = "Analyzer (Placeholder)" };
102      var generationsComparator = new Comparator() { Name = "Generations >= MaximumGenerations" };
103      var terminateBranch = new ConditionalBranch() { Name = "Terminate?" };
104
105      OperatorGraph.InitialOperator = variableCreator;
106
107      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Generations", new IntValue(0)));
108      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("GenerationsSinceLastRefresh", new IntValue(0)));
[11586]109      variableCreator.CollectedValues.Add(new ValueParameter<IntValue>("OpenLayers", new IntValue(1)));
[11609]110      variableCreator.Successor = initLayerAnalyzerProcessor;
[11580]111
[11590]112      initLayerAnalyzerProcessor.Operators.Add(layerVariableCreator);
[11609]113      initLayerAnalyzerProcessor.Successor = initAnalyzerPlaceholder;
[11580]114
[11590]115      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("LayerEvaluatedSolutions"));
[12071]116      layerVariableCreator.CollectedValues.Add(new ValueParameter<ResultCollection>("LayerResults"));
[11590]117      layerVariableCreator.Successor = initLayerAnalyzerPlaceholder;
118
[11580]119      initLayerAnalyzerPlaceholder.OperatorParameter.ActualName = LayerAnalyzerParameter.Name;
120      initLayerAnalyzerPlaceholder.Successor = null;
121
[11609]122      initAnalyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
123      initAnalyzerPlaceholder.Successor = resultsCollector;
124
125      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Generations"));
[12071]126      resultsCollector.CollectedValues.Add(new ScopeTreeLookupParameter<ResultCollection>("LayerResults", "Result set for each layer", "LayerResults"));
[11609]127      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("OpenLayers"));
128      resultsCollector.CopyValue = new BoolValue(false);
[12045]129      resultsCollector.Successor = matingPoolPreProcessor;
[11609]130
[12045]131      matingPoolPreProcessor.Operator = matingPoolPreSorter;
132      matingPoolPreProcessor.Successor = matingPoolCreator;
133
134      matingPoolPreSorter.ValueParameter.ActualName = QualityParameter.Name;
135      matingPoolPreSorter.DescendingParameter.ActualName = MaximizationParameter.Name;
136
[11580]137      matingPoolCreator.Successor = matingPoolProcessor;
138
139      matingPoolProcessor.Parallel.Value = true;
[11590]140      matingPoolProcessor.Operator = initializeLayer;
[11583]141      matingPoolProcessor.Successor = generationsIcrementor;
[11580]142
[11590]143      initializeLayer.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
144      initializeLayer.RightSideParameter.Value = new IntValue(0);
145      initializeLayer.Successor = mainOperator;
146
[11583]147      generationsIcrementor.ValueParameter.ActualName = "Generations";
148      generationsIcrementor.Increment = new IntValue(1);
149      generationsIcrementor.Successor = evaluatedSolutionsReducer;
150
[11676]151      evaluatedSolutionsReducer.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
[11583]152      evaluatedSolutionsReducer.TargetParameter.ActualName = "EvaluatedSolutions";
153      evaluatedSolutionsReducer.ReductionOperation.Value = new ReductionOperation(ReductionOperations.Sum);
154      evaluatedSolutionsReducer.TargetOperation.Value = new ReductionOperation(ReductionOperations.Sum);
155      evaluatedSolutionsReducer.Successor = eldersEmigrator;
156
[12197]157      eldersEmigrator.Successor = layerUpdator;
[11580]158
[12197]159      layerUpdator.Successor = layerAnalyzerProcessor;
[11580]160
[12197]161      layerAnalyzerProcessor.Operator = layerAnalyzerPlaceholder;
162      layerAnalyzerProcessor.Successor = analyzerPlaceholder;
[11580]163
[12197]164      layerAnalyzerPlaceholder.OperatorParameter.ActualName = LayerAnalyzerParameter.Name;
[11580]165
166      analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
167      analyzerPlaceholder.Successor = generationsComparator;
168
169      generationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
170      generationsComparator.LeftSideParameter.ActualName = "Generations";
171      generationsComparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;
172      generationsComparator.ResultParameter.ActualName = "TerminateGenerations";
173      generationsComparator.Successor = terminateBranch;
174
[11583]175      terminateBranch.ConditionParameter.ActualName = "TerminateGenerations";
[12045]176      terminateBranch.FalseBranch = matingPoolPreProcessor;
[11583]177    }
[11580]178
[11586]179    private GeneticAlgorithmMainLoop CreatePreparedGeneticAlgorithmMainLoop() {
[11583]180      var mainLoop = new GeneticAlgorithmMainLoop();
[12186]181
[11583]182      var selector = mainLoop.OperatorGraph.Iterate().OfType<Placeholder>().First(o => o.OperatorParameter.ActualName == "Selector");
183      var crossover = mainLoop.OperatorGraph.Iterate().OfType<Placeholder>().First(o => o.OperatorParameter.ActualName == "Crossover");
[11590]184      var subScopesCounter = mainLoop.OperatorGraph.Iterate().OfType<SubScopesCounter>().First();
[11583]185      var elitesMerger = mainLoop.OperatorGraph.Iterate().OfType<MergingReducer>().First();
186
[12186]187      // Operator starts with calculating number of selected scopes base on plus/comma-selection replacement scheme
188      var numberOfSubScopesBranch = new ConditionalBranch() { Name = "PlusSelection?" };
189      var numberOfSelectedSubScopesPlusCalculator = new ExpressionCalculator() { Name = "NumberOfSelectedSubScopes = PopulationSize * 2" };
190      var numberOfSelectedSubScopesCalculator = new ExpressionCalculator() { Name = "NumberOfSelectedSubScopes = (PopulationSize - Elites) * 2" };
191      var replacementBranch = new ConditionalBranch() { Name = "PlusSelection?" };
192
193      mainLoop.OperatorGraph.InitialOperator = numberOfSubScopesBranch;
194
195      numberOfSubScopesBranch.ConditionParameter.ActualName = "PlusSelection";
196      numberOfSubScopesBranch.TrueBranch = numberOfSelectedSubScopesPlusCalculator;
197      numberOfSubScopesBranch.FalseBranch = numberOfSelectedSubScopesCalculator;
198      numberOfSubScopesBranch.Successor = selector;
199
200      numberOfSelectedSubScopesPlusCalculator.CollectedValues.Add(new LookupParameter<IntValue>("PopulationSize"));
201      numberOfSelectedSubScopesPlusCalculator.ExpressionResultParameter.ActualName = "NumberOfSelectedSubScopes";
202      numberOfSelectedSubScopesPlusCalculator.ExpressionParameter.Value = new StringValue("PopulationSize 2 * toint");
203
[12094]204      numberOfSelectedSubScopesCalculator.CollectedValues.Add(new LookupParameter<IntValue>("PopulationSize"));
205      numberOfSelectedSubScopesCalculator.CollectedValues.Add(new LookupParameter<IntValue>("Elites"));
206      numberOfSelectedSubScopesCalculator.ExpressionResultParameter.ActualName = "NumberOfSelectedSubScopes";
207      numberOfSelectedSubScopesCalculator.ExpressionParameter.Value = new StringValue("PopulationSize Elites - 2 * toint");
[11583]208
[12186]209      // Use Elitism or Plus-Selection as replacement strategy
210      var selectedProcessor = (SubScopesProcessor)selector.Successor;
211      var elitismReplacement = selectedProcessor.Successor;
212      selectedProcessor.Successor = replacementBranch;
213      replacementBranch.ConditionParameter.ActualName = "PlusSelection";
214      replacementBranch.FalseBranch = elitismReplacement;
215
216      // Plus selection replacement
217      var replacementMergingReducer = new MergingReducer();
218      var replacementBestSelector = new BestSelector();
219      var replacementRightReducer = new RightReducer();
220      replacementBranch.TrueBranch = replacementMergingReducer;
221
222      replacementMergingReducer.Successor = replacementBestSelector;
223
224      replacementBestSelector.NumberOfSelectedSubScopesParameter.ActualName = "PopulationSize";
225      replacementBestSelector.CopySelected = new BoolValue(false);
226      replacementBestSelector.Successor = replacementRightReducer;
227
228      replacementRightReducer.Successor = null;
229
230      // Increment ages of all individuals after replacement
231      var incrementAgeProcessor = new UniformSubScopesProcessor();
232      var ageIncrementor = new IntCounter() { Name = "Increment Age" };
233      replacementBranch.Successor = incrementAgeProcessor;
234      incrementAgeProcessor.Operator = ageIncrementor;
235      incrementAgeProcessor.Successor = null;
236      ageIncrementor.ValueParameter.ActualName = "Age";
237      ageIncrementor.Increment = new IntValue(1);
238      //ageIncrementor.Successor = null;
239
[11583]240      // Insert AgeCalculator between crossover and its successor
241      var crossoverSuccessor = crossover.Successor;
242      var ageCalculator = new DataReducer() { Name = "Calculate Age" };
[12186]243      crossover.Successor = ageCalculator;
244
[11583]245      ageCalculator.ParameterToReduce.ActualName = "Age";
246      ageCalculator.TargetParameter.ActualName = "Age";
[11678]247      ageCalculator.ReductionOperation.Value = null;
[12271]248      ageCalculator.ReductionOperation.ActualName = "AgeInheritanceReduction";
[11583]249      ageCalculator.TargetOperation.Value = new ReductionOperation(ReductionOperations.Assign);
250      ageCalculator.Successor = crossoverSuccessor;
251
[11590]252      // When counting the evaluated solutions, write in LayerEvaluatedSolutions
253      subScopesCounter.ValueParameter.ActualName = "LayerEvaluatedSolutions";
254      subScopesCounter.AccumulateParameter.Value = new BoolValue(false);
255
[12186]256      // Instead of generational loop after merging of elites, stop
257      elitesMerger.Successor = null;
[11583]258
259      // Parameterize
260      foreach (var stochasticOperator in mainLoop.OperatorGraph.Iterate().OfType<IStochasticOperator>())
261        stochasticOperator.RandomParameter.ActualName = "LocalRandom";
262      foreach (var stochasticBranch in mainLoop.OperatorGraph.Iterate().OfType<StochasticBranch>())
263        stochasticBranch.RandomParameter.ActualName = "LocalRandom";
264
265      return mainLoop;
[11580]266    }
267  }
268}
Note: See TracBrowser for help on using the repository browser.