Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2350 Added Termination Criteria to Steady-State ALPS.

File size: 16.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;
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      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 = iterationsTerminator.ThresholdParameter.Name;
279          @operator.MaximumIterationsParameter.Hidden = true;
280        }
281      }
282    }
283
284    protected override ReductionOperations GetAgeInheritanceReduction(AgeInheritance ageInheritance) {
285      switch (ageInheritance) {
286        case ALPS.AgeInheritance.Older: return ReductionOperations.Min;
287        case ALPS.AgeInheritance.Agerage: return ReductionOperations.Avg;
288        case ALPS.AgeInheritance.Younger: return ReductionOperations.Max;
289        default: throw new NotSupportedException("AgeInheritance " + ageInheritance + " is not supported.");
290      }
291    }
292
293    protected override void ParameterizeStochasticOperator(IOperator @operator) {
294      var stochasticOperator = @operator as IStochasticOperator;
295      if (stochasticOperator != null) {
296        stochasticOperator.RandomParameter.ActualName = "Random";
297        stochasticOperator.RandomParameter.Hidden = true;
298      }
299    }
300    protected override void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
301      var stochasticOperator = @operator as IStochasticOperator;
302      if (stochasticOperator != null) {
303        stochasticOperator.RandomParameter.ActualName = "Random";
304        stochasticOperator.RandomParameter.Hidden = true;
305      }
306    }
307    #endregion
308
309    #region Updates
310    protected override void UpdateTerminators() {
311      var newTerminators = new Dictionary<ITerminator, bool> {
312        {iterationsTerminator, !Terminators.Operators.Contains(iterationsTerminator) || Terminators.Operators.ItemChecked(iterationsTerminator)},
313      };
314
315      base.UpdateTerminators();
316
317      foreach (var newTerminator in newTerminators)
318        Terminators.Operators.Insert(0, newTerminator.Key, newTerminator.Value);
319    }
320    protected override void CreateTerminators() {
321      iterationsTerminator = new ComparisonTerminator<IntValue>("Iterations", ComparisonType.Less, new IntValue(1000)) { Name = "Iterations" };
322      base.CreateTerminators();
323    }
324    private void UpdateCrossovers() {
325      var oldCrossover = CrossoverParameter.Value;
326      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
327      CrossoverParameter.ValidValues.Clear();
328      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
329        ParameterizeStochasticOperatorForLayer(crossover);
330        CrossoverParameter.ValidValues.Add(crossover);
331      }
332      if (oldCrossover != null) {
333        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
334        if (crossover != null)
335          CrossoverParameter.Value = crossover;
336        else
337          oldCrossover = null;
338      }
339      if (oldCrossover == null && defaultCrossover != null)
340        CrossoverParameter.Value = defaultCrossover;
341    }
342    private void UpdateMutators() {
343      var oldMutator = MutatorParameter.Value;
344      MutatorParameter.ValidValues.Clear();
345      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
346        ParameterizeStochasticOperatorForLayer(mutator);
347        MutatorParameter.ValidValues.Add(mutator);
348      }
349      if (oldMutator != null) {
350        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
351        if (mutator != null)
352          MutatorParameter.Value = mutator;
353      }
354    }
355    #endregion
356  }
357}
Note: See TracBrowser for help on using the repository browser.