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

Last change on this file since 12549 was 12549, checked in by pfleck, 5 years ago

#2350 Moved updating of terminators to concrete ALPS implementation instead of abstract base class.

File size: 17.4 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.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
28using HeuristicLab.Operators;
29using HeuristicLab.Optimization;
30using HeuristicLab.Optimization.Operators;
31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35using HeuristicLab.Selection;
36
37namespace HeuristicLab.Algorithms.ALPS.SteadyState {
38  [Item("ALPS Steady-State Genetic Algorithm", "A genetic algorithmn with a steady-state age-layered population structure")]
39  [Creatable("Algorithms")]
40  [StorableClass]
41  public class AlpsSsGeneticAlgorithm : Alps {
42    #region Parameter Properties
43    private IValueParameter<IntValue> LayerSizeParameter {
44      get { return (IValueParameter<IntValue>)Parameters["LayerSize"]; }
45    }
46    public IConstrainedValueParameter<ISelector> SelectorParameter {
47      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
48    }
49    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
50      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
51    }
52    private IValueParameter<PercentValue> MutationProbabilityParameter {
53      get { return (IValueParameter<PercentValue>)Parameters["MutationProbability"]; }
54    }
55    public IConstrainedValueParameter<IManipulator> MutatorParameter {
56      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
57    }
58    private IValueParameter<IntValue> ElitesParameter {
59      get { return (IValueParameter<IntValue>)Parameters["Elites"]; }
60    }
61    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
62      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
63    }
64    private IValueParameter<IntValue> BatchSizeParameter {
65      get { return (IValueParameter<IntValue>)Parameters["BatchSize"]; }
66    }
67    #endregion
68
69    #region Properties
70    public IntValue LayerSize {
71      get { return LayerSizeParameter.Value; }
72      set { LayerSizeParameter.Value = value; }
73    }
74    public int MaximumIterations {
75      get { return iterationsTerminator.Threshold.Value; }
76      set { iterationsTerminator.Threshold.Value = value; }
77    }
78
79    public ISelector Selector {
80      get { return SelectorParameter.Value; }
81      set { SelectorParameter.Value = value; }
82    }
83    public ICrossover Crossover {
84      get { return CrossoverParameter.Value; }
85      set { CrossoverParameter.Value = value; }
86    }
87    public PercentValue MutationProbability {
88      get { return MutationProbabilityParameter.Value; }
89      set { MutationProbabilityParameter.Value = value; }
90    }
91    public IManipulator Mutator {
92      get { return MutatorParameter.Value; }
93      set { MutatorParameter.Value = value; }
94    }
95    public IntValue Elites {
96      get { return ElitesParameter.Value; }
97      set { ElitesParameter.Value = value; }
98    }
99    public bool ReevaluteElites {
100      get { return ReevaluateElitesParameter.Value.Value; }
101      set { ReevaluateElitesParameter.Value.Value = value; }
102    }
103    #endregion
104
105    private AlpsSsGeneticAlgorithmMainLoop MainLoop {
106      get { return OperatorGraph.Iterate().OfType<AlpsSsGeneticAlgorithmMainLoop>().First(); }
107    }
108
109    [Storable]
110    private ComparisonTerminator<IntValue> iterationsTerminator;
111
112    [StorableConstructor]
113    private AlpsSsGeneticAlgorithm(bool deserializing)
114      : base(deserializing) { }
115    private AlpsSsGeneticAlgorithm(AlpsSsGeneticAlgorithm original, Cloner cloner)
116      : base(original, cloner) {
117      iterationsTerminator = cloner.Clone(original.iterationsTerminator);
118      Initialize();
119    }
120    public override IDeepCloneable Clone(Cloner cloner) {
121      return new AlpsSsGeneticAlgorithm(this, cloner);
122    }
123
124    public AlpsSsGeneticAlgorithm()
125      : base() {
126      Parameters.Add(new ValueParameter<IntValue>("LayerSize", "The size of the population of solutions each layer.", new IntValue(100)));
127      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
128      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
129      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
130      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
131      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
132      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 });
133      Parameters.Add(new ValueParameter<IntValue>("BatchSize", "Number of inner iterations before updates and analyzers are fired.", new IntValue(100)) { Hidden = true });
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 initializeLocalEvaluatedSolutions = new ExpressionCalculator() { Name = "Initialize local EvaluatedSolutions" };
146      var initializeEvaluatedSolutions = new Assigner() { Name = "Initialize EvaluatedSolutions" };
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", });
158      workingScopeCreator.Successor = layersProcessor;
159
160      layersProcessor.TargetScopeParameter.ActualName = "LayersScope";
161      layersProcessor.Operator = layerCreator;
162      layersProcessor.Successor = initializeLocalEvaluatedSolutions;
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      initializeLocalEvaluatedSolutions.ExpressionResultParameter.ActualName = "LocalEvaluatedSolutions";
186      initializeLocalEvaluatedSolutions.ExpressionParameter.Value = new StringValue("LayerSize NumberOfLayers * toint");
187      initializeLocalEvaluatedSolutions.CollectedValues.Add(new LookupParameter<IntValue>("LayerSize"));
188      initializeLocalEvaluatedSolutions.CollectedValues.Add(new LookupParameter<IntValue>("NumberOfLayers"));
189      initializeLocalEvaluatedSolutions.Successor = initializeEvaluatedSolutions;
190
191      initializeEvaluatedSolutions.LeftSideParameter.ActualName = "EvaluatedSolutions";
192      initializeEvaluatedSolutions.RightSideParameter.ActualName = "LocalEvaluatedSolutions";
193      initializeEvaluatedSolutions.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>("EvaluatedSolutions"));
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      iterationsTerminator = new ComparisonTerminator<IntValue>("Iterations", ComparisonType.Less, new IntValue(1000)) { Name = "Iterations" };
212
213      ParameterizeSelectors();
214      UpdateTerminators();
215
216      Initialize();
217    }
218
219    #region Events
220    protected override void OnProblemChanged() {
221      base.OnProblemChanged();
222      ParameterizeSolutionsCreator();
223      ParameterizeMainLoop();
224      ParameterizeSelectors();
225      ParameterizeIterationBasedOperators();
226      UpdateCrossovers();
227      UpdateMutators();
228      UpdateTerminators();
229    }
230    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
231      base.Problem_SolutionCreatorChanged(sender, e);
232      ParameterizeSolutionsCreator();
233    }
234    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
235      base.Problem_EvaluatorChanged(sender, e);
236      ParameterizeSolutionsCreator();
237      ParameterizeMainLoop();
238      ParameterizeSelectors();
239    }
240    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
241      base.Problem_OperatorsChanged(sender, e);
242      ParameterizeIterationBasedOperators();
243      UpdateCrossovers();
244      UpdateMutators();
245      UpdateTerminators();
246    }
247    protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
248      base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
249      ParameterizeMainLoop();
250      ParameterizeSelectors();
251    }
252    #endregion
253
254    #region Parameterization
255    private void Initialize() {
256    }
257    private void ParameterizeSolutionsCreator() {
258    }
259    private void ParameterizeMainLoop() {
260      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
261      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
262    }
263    private void ParameterizeSelectors() {
264      foreach (var selector in SelectorParameter.ValidValues) {
265        selector.CopySelected = new BoolValue(true);
266        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2);
267        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
268        ParameterizeStochasticOperatorForLayer(selector);
269      }
270      if (Problem != null) {
271        foreach (var selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
272          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
273          selector.MaximizationParameter.Hidden = true;
274          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
275          selector.QualityParameter.Hidden = true;
276        }
277      }
278    }
279    private void ParameterizeIterationBasedOperators() {
280      if (Problem != null) {
281        foreach (var @operator in Problem.Operators.OfType<IIterationBasedOperator>()) {
282          @operator.IterationsParameter.ActualName = "Iteration";
283          @operator.IterationsParameter.Hidden = true;
284          @operator.MaximumIterationsParameter.ActualName = iterationsTerminator.ThresholdParameter.Name;
285          @operator.MaximumIterationsParameter.Hidden = true;
286        }
287      }
288    }
289
290    protected override ReductionOperations GetAgeInheritanceReduction(AgeInheritance ageInheritance) {
291      switch (ageInheritance) {
292        case ALPS.AgeInheritance.Older: return ReductionOperations.Min;
293        case ALPS.AgeInheritance.Agerage: return ReductionOperations.Avg;
294        case ALPS.AgeInheritance.Younger: return ReductionOperations.Max;
295        default: throw new NotSupportedException("AgeInheritance " + ageInheritance + " is not supported.");
296      }
297    }
298
299    protected override void ParameterizeStochasticOperator(IOperator @operator) {
300      var stochasticOperator = @operator as IStochasticOperator;
301      if (stochasticOperator != null) {
302        stochasticOperator.RandomParameter.ActualName = "Random";
303        stochasticOperator.RandomParameter.Hidden = true;
304      }
305    }
306    protected override void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
307      var stochasticOperator = @operator as IStochasticOperator;
308      if (stochasticOperator != null) {
309        stochasticOperator.RandomParameter.ActualName = "Random";
310        stochasticOperator.RandomParameter.Hidden = true;
311      }
312    }
313    #endregion
314
315    #region Updates
316
317    private void UpdateTerminators() {
318      var newTerminators = new Dictionary<ITerminator, bool> {
319        {iterationsTerminator, !Terminators.Operators.Contains(iterationsTerminator) || Terminators.Operators.ItemChecked(iterationsTerminator)},
320        {evaluationsTerminator, Terminators.Operators.Contains(evaluationsTerminator) && Terminators.Operators.ItemChecked(evaluationsTerminator)},
321        {qualityTerminator, Terminators.Operators.Contains(qualityTerminator) && Terminators.Operators.ItemChecked(qualityTerminator) },
322        {executionTimeTerminator, Terminators.Operators.Contains(executionTimeTerminator) && Terminators.Operators.ItemChecked(executionTimeTerminator)}
323      };
324      if (Problem != null) {
325        foreach (var terminator in Problem.Operators.OfType<ITerminator>())
326          newTerminators.Add(terminator, !Terminators.Operators.Contains(terminator) || Terminators.Operators.ItemChecked(terminator));
327      }
328
329      Terminators.Operators.Clear();
330
331      foreach (var newTerminator in newTerminators)
332        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
333    }
334    private void UpdateCrossovers() {
335      var oldCrossover = CrossoverParameter.Value;
336      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
337      CrossoverParameter.ValidValues.Clear();
338      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
339        ParameterizeStochasticOperatorForLayer(crossover);
340        CrossoverParameter.ValidValues.Add(crossover);
341      }
342      if (oldCrossover != null) {
343        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
344        if (crossover != null)
345          CrossoverParameter.Value = crossover;
346        else
347          oldCrossover = null;
348      }
349      if (oldCrossover == null && defaultCrossover != null)
350        CrossoverParameter.Value = defaultCrossover;
351    }
352    private void UpdateMutators() {
353      var oldMutator = MutatorParameter.Value;
354      MutatorParameter.ValidValues.Clear();
355      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
356        ParameterizeStochasticOperatorForLayer(mutator);
357        MutatorParameter.ValidValues.Add(mutator);
358      }
359      if (oldMutator != null) {
360        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
361        if (mutator != null)
362          MutatorParameter.Value = mutator;
363      }
364    }
365    #endregion
366  }
367}
Note: See TracBrowser for help on using the repository browser.