Free cookie consent management tool by TermsFeed Policy Generator

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, 9 years ago

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

File size: 17.4 KB
RevLine 
[12119]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;
[12534]23using System.Collections.Generic;
[12120]24using System.Linq;
[12119]25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Data;
[12120]28using HeuristicLab.Operators;
[12119]29using HeuristicLab.Optimization;
[12120]30using HeuristicLab.Optimization.Operators;
[12119]31using HeuristicLab.Parameters;
32using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[12120]33using HeuristicLab.PluginInfrastructure;
34using HeuristicLab.Random;
35using HeuristicLab.Selection;
[12119]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
[12153]43    private IValueParameter<IntValue> LayerSizeParameter {
44      get { return (IValueParameter<IntValue>)Parameters["LayerSize"]; }
[12120]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    }
[12192]64    private IValueParameter<IntValue> BatchSizeParameter {
65      get { return (IValueParameter<IntValue>)Parameters["BatchSize"]; }
66    }
[12119]67    #endregion
68
69    #region Properties
[12153]70    public IntValue LayerSize {
71      get { return LayerSizeParameter.Value; }
72      set { LayerSizeParameter.Value = value; }
[12120]73    }
[12534]74    public int MaximumIterations {
75      get { return iterationsTerminator.Threshold.Value; }
76      set { iterationsTerminator.Threshold.Value = value; }
[12120]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    }
[12119]103    #endregion
104
[12138]105    private AlpsSsGeneticAlgorithmMainLoop MainLoop {
106      get { return OperatorGraph.Iterate().OfType<AlpsSsGeneticAlgorithmMainLoop>().First(); }
107    }
108
[12534]109    [Storable]
110    private ComparisonTerminator<IntValue> iterationsTerminator;
111
[12119]112    [StorableConstructor]
113    private AlpsSsGeneticAlgorithm(bool deserializing)
114      : base(deserializing) { }
115    private AlpsSsGeneticAlgorithm(AlpsSsGeneticAlgorithm original, Cloner cloner)
116      : base(original, cloner) {
[12534]117      iterationsTerminator = cloner.Clone(original.iterationsTerminator);
[12119]118      Initialize();
119    }
120    public override IDeepCloneable Clone(Cloner cloner) {
121      return new AlpsSsGeneticAlgorithm(this, cloner);
122    }
123
124    public AlpsSsGeneticAlgorithm()
125      : base() {
[12153]126      Parameters.Add(new ValueParameter<IntValue>("LayerSize", "The size of the population of solutions each layer.", new IntValue(100)));
[12120]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 });
[12192]133      Parameters.Add(new ValueParameter<IntValue>("BatchSize", "Number of inner iterations before updates and analyzers are fired.", new IntValue(100)) { Hidden = true });
[12119]134
[12120]135      var randomCreator = new RandomCreator();
[12220]136      var workingScopeCreator = new NamedSubScopesCreator() { Name = "Create Working- and Layers-Scope" };
[12157]137      var layersProcessor = new NamedSubScopeProcessor() { Name = "Process Layers-Scope" };
[12220]138      var layerCreator = new SubScopesCreator() { Name = "Create Layers" };
139      var layerProcessor = new UniformSubScopesProcessor();
[12153]140      var layerVariableCreator = new VariableCreator() { Name = "Initialize Layer" };
[12159]141      var layerNumberCreator = new ScopeIndexAssigner() { Name = "Create Layer Number" };
[12153]142      var layerSolutionsCreator = new SolutionsCreator();
[12120]143      var initializeAgeProcessor = new UniformSubScopesProcessor();
144      var initializeAge = new VariableCreator() { Name = "Initialize Age" };
[12270]145      var initializeLocalEvaluatedSolutions = new ExpressionCalculator() { Name = "Initialize local EvaluatedSolutions" };
146      var initializeEvaluatedSolutions = new Assigner() { Name = "Initialize EvaluatedSolutions" };
[12153]147      var initializePopulationSize = new Assigner() { Name = "Initialize PopulationSize" };
[12120]148      var resultsCollector = new ResultsCollector();
149      var mainLoop = new AlpsSsGeneticAlgorithmMainLoop();
[12119]150
[12120]151      OperatorGraph.InitialOperator = randomCreator;
152
153      randomCreator.SeedParameter.Value = null;
154      randomCreator.SetSeedRandomlyParameter.Value = null;
[12153]155      randomCreator.Successor = workingScopeCreator;
[12120]156
[12270]157      workingScopeCreator.NamesParameter.Value = new StringArray(new[] { "WorkingScope", "LayersScope", });
[12153]158      workingScopeCreator.Successor = layersProcessor;
[12120]159
[12220]160      layersProcessor.TargetScopeParameter.ActualName = "LayersScope";
[12157]161      layersProcessor.Operator = layerCreator;
[12270]162      layersProcessor.Successor = initializeLocalEvaluatedSolutions;
[12120]163
[12153]164      layerCreator.NumberOfSubScopesParameter.ActualName = "NumberOfLayers";
165      layerCreator.NumberOfSubScopesParameter.Value = null;
166      layerCreator.Successor = layerProcessor;
[12120]167
[12153]168      layerProcessor.Operator = layerVariableCreator;
[12120]169
[12153]170      layerVariableCreator.CollectedValues.Add(new ValueParameter<ResultCollection>("LayerResults"));
[12159]171      layerVariableCreator.CollectedValues.Add(new ValueParameter<IntValue>("Layer"));
172      layerVariableCreator.Successor = layerNumberCreator;
[12153]173
[12159]174      layerNumberCreator.ValueParameter.ActualName = "Layer";
175      layerNumberCreator.Successor = layerSolutionsCreator;
176
[12153]177      layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = LayerSizeParameter.Name;
178      layerSolutionsCreator.Successor = initializeAgeProcessor;
179
[12120]180      initializeAgeProcessor.Operator = initializeAge;
181
[12138]182      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("EvalsCreated", new IntValue(1)));
[12153]183      initializeAge.CollectedValues.Add(new ValueParameter<IntValue>("LastMove", new IntValue(1)));
[12120]184
[12270]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;
[12120]190
[12270]191      initializeEvaluatedSolutions.LeftSideParameter.ActualName = "EvaluatedSolutions";
192      initializeEvaluatedSolutions.RightSideParameter.ActualName = "LocalEvaluatedSolutions";
193      initializeEvaluatedSolutions.Successor = initializePopulationSize;
[12192]194
[12153]195      initializePopulationSize.LeftSideParameter.ActualName = "PopulationSize";
196      initializePopulationSize.RightSideParameter.ActualName = "EvaluatedSolutions";
197      initializePopulationSize.Successor = resultsCollector;
[12136]198
[12270]199      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("EvaluatedSolutions"));
[12220]200      resultsCollector.CollectedValues.Add(new ScopeTreeLookupParameter<ResultCollection>("LayerResults", "Result set for each layer", "LayerResults", 2));
[12120]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) {
[12220]207        tournamentSelector.GroupSizeParameter.Value = new IntValue(4);
[12120]208        SelectorParameter.Value = tournamentSelector;
209      }
210
[12549]211      iterationsTerminator = new ComparisonTerminator<IntValue>("Iterations", ComparisonType.Less, new IntValue(1000)) { Name = "Iterations" };
212
[12120]213      ParameterizeSelectors();
[12549]214      UpdateTerminators();
215
[12119]216      Initialize();
217    }
218
219    #region Events
[12120]220    protected override void OnProblemChanged() {
221      base.OnProblemChanged();
222      ParameterizeSolutionsCreator();
223      ParameterizeMainLoop();
224      ParameterizeSelectors();
225      ParameterizeIterationBasedOperators();
226      UpdateCrossovers();
227      UpdateMutators();
[12549]228      UpdateTerminators();
[12120]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();
[12549]245      UpdateTerminators();
[12120]246    }
247    protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
248      base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
249      ParameterizeMainLoop();
250      ParameterizeSelectors();
251    }
[12119]252    #endregion
253
254    #region Parameterization
255    private void Initialize() {
256    }
[12120]257    private void ParameterizeSolutionsCreator() {
258    }
259    private void ParameterizeMainLoop() {
[12138]260      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
261      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[12120]262    }
263    private void ParameterizeSelectors() {
264      foreach (var selector in SelectorParameter.ValidValues) {
265        selector.CopySelected = new BoolValue(true);
[12138]266        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2);
[12120]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>()) {
[12136]282          @operator.IterationsParameter.ActualName = "Iteration";
[12120]283          @operator.IterationsParameter.Hidden = true;
[12534]284          @operator.MaximumIterationsParameter.ActualName = iterationsTerminator.ThresholdParameter.Name;
[12120]285          @operator.MaximumIterationsParameter.Hidden = true;
286        }
287      }
288    }
289
[12271]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
[12138]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    }
[12120]306    protected override void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
307      var stochasticOperator = @operator as IStochasticOperator;
308      if (stochasticOperator != null) {
[12138]309        stochasticOperator.RandomParameter.ActualName = "Random";
[12120]310        stochasticOperator.RandomParameter.Hidden = true;
311      }
312    }
[12119]313    #endregion
314
315    #region Updates
[12549]316
317    private void UpdateTerminators() {
[12534]318      var newTerminators = new Dictionary<ITerminator, bool> {
319        {iterationsTerminator, !Terminators.Operators.Contains(iterationsTerminator) || Terminators.Operators.ItemChecked(iterationsTerminator)},
[12549]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)}
[12534]323      };
[12549]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      }
[12534]328
[12549]329      Terminators.Operators.Clear();
[12534]330
331      foreach (var newTerminator in newTerminators)
[12549]332        Terminators.Operators.Add(newTerminator.Key, newTerminator.Value);
[12534]333    }
[12120]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    }
[12119]365    #endregion
366  }
367}
Note: See TracBrowser for help on using the repository browser.