Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2350 Renamed EvaluatedSolutions and ResultEvaluatedSolutions to LocalEvaluatedSolutions and EvaluatedSolutions for consistency with other algorithms.

File size: 15.7 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;
[12120]23using System.Linq;
[12119]24using HeuristicLab.Common;
25using HeuristicLab.Core;
26using HeuristicLab.Data;
[12120]27using HeuristicLab.Operators;
[12119]28using HeuristicLab.Optimization;
[12120]29using HeuristicLab.Optimization.Operators;
[12119]30using HeuristicLab.Parameters;
31using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[12120]32using HeuristicLab.PluginInfrastructure;
33using HeuristicLab.Random;
34using HeuristicLab.Selection;
[12119]35
36namespace HeuristicLab.Algorithms.ALPS.SteadyState {
37  [Item("ALPS Steady-State Genetic Algorithm", "A genetic algorithmn with a steady-state age-layered population structure")]
38  [Creatable("Algorithms")]
39  [StorableClass]
40  public class AlpsSsGeneticAlgorithm : Alps {
41    #region Parameter Properties
[12153]42    private IValueParameter<IntValue> LayerSizeParameter {
43      get { return (IValueParameter<IntValue>)Parameters["LayerSize"]; }
[12120]44    }
[12136]45    private IValueParameter<IntValue> MaximumIterationsParameter {
46      get { return (IValueParameter<IntValue>)Parameters["MaximumIterations"]; }
[12120]47    }
48    public IConstrainedValueParameter<ISelector> SelectorParameter {
49      get { return (IConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
50    }
51    public IConstrainedValueParameter<ICrossover> CrossoverParameter {
52      get { return (IConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
53    }
54    private IValueParameter<PercentValue> MutationProbabilityParameter {
55      get { return (IValueParameter<PercentValue>)Parameters["MutationProbability"]; }
56    }
57    public IConstrainedValueParameter<IManipulator> MutatorParameter {
58      get { return (IConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
59    }
60    private IValueParameter<IntValue> ElitesParameter {
61      get { return (IValueParameter<IntValue>)Parameters["Elites"]; }
62    }
63    private IFixedValueParameter<BoolValue> ReevaluateElitesParameter {
64      get { return (IFixedValueParameter<BoolValue>)Parameters["ReevaluateElites"]; }
65    }
[12192]66    private IValueParameter<IntValue> BatchSizeParameter {
67      get { return (IValueParameter<IntValue>)Parameters["BatchSize"]; }
68    }
[12119]69    #endregion
70
71    #region Properties
[12153]72    public IntValue LayerSize {
73      get { return LayerSizeParameter.Value; }
74      set { LayerSizeParameter.Value = value; }
[12120]75    }
[12136]76    public IntValue MaximumIterations {
77      get { return MaximumIterationsParameter.Value; }
78      set { MaximumIterationsParameter.Value = value; }
[12120]79    }
80
81    public ISelector Selector {
82      get { return SelectorParameter.Value; }
83      set { SelectorParameter.Value = value; }
84    }
85    public ICrossover Crossover {
86      get { return CrossoverParameter.Value; }
87      set { CrossoverParameter.Value = value; }
88    }
89    public PercentValue MutationProbability {
90      get { return MutationProbabilityParameter.Value; }
91      set { MutationProbabilityParameter.Value = value; }
92    }
93    public IManipulator Mutator {
94      get { return MutatorParameter.Value; }
95      set { MutatorParameter.Value = value; }
96    }
97    public IntValue Elites {
98      get { return ElitesParameter.Value; }
99      set { ElitesParameter.Value = value; }
100    }
101    public bool ReevaluteElites {
102      get { return ReevaluateElitesParameter.Value.Value; }
103      set { ReevaluateElitesParameter.Value.Value = value; }
104    }
[12119]105    #endregion
106
[12138]107    private AlpsSsGeneticAlgorithmMainLoop MainLoop {
108      get { return OperatorGraph.Iterate().OfType<AlpsSsGeneticAlgorithmMainLoop>().First(); }
109    }
110
[12119]111    [StorableConstructor]
112    private AlpsSsGeneticAlgorithm(bool deserializing)
113      : base(deserializing) { }
114    private AlpsSsGeneticAlgorithm(AlpsSsGeneticAlgorithm original, Cloner cloner)
115      : base(original, cloner) {
116      Initialize();
117    }
118    public override IDeepCloneable Clone(Cloner cloner) {
119      return new AlpsSsGeneticAlgorithm(this, cloner);
120    }
121
122    public AlpsSsGeneticAlgorithm()
123      : base() {
[12153]124      Parameters.Add(new ValueParameter<IntValue>("LayerSize", "The size of the population of solutions each layer.", new IntValue(100)));
[12136]125      Parameters.Add(new ValueParameter<IntValue>("MaximumIterations", "The maximum number of iterations that should be processed.", new IntValue(1000)));
[12120]126      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
127      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
128      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
129      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
130      Parameters.Add(new ValueParameter<IntValue>("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
131      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]132      Parameters.Add(new ValueParameter<IntValue>("BatchSize", "Number of inner iterations before updates and analyzers are fired.", new IntValue(100)) { Hidden = true });
[12120]133      AgeInheritance = new ReductionOperation(ReductionOperations.Min);
[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
211      ParameterizeSelectors();
[12119]212      Initialize();
213    }
214
215    #region Events
[12120]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    }
[12119]246    #endregion
247
248    #region Parameterization
249    private void Initialize() {
250    }
[12120]251    private void ParameterizeSolutionsCreator() {
252    }
253    private void ParameterizeMainLoop() {
[12138]254      MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
255      MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
[12120]256    }
257    private void ParameterizeSelectors() {
258      foreach (var selector in SelectorParameter.ValidValues) {
259        selector.CopySelected = new BoolValue(true);
[12138]260        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2);
[12120]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>()) {
[12136]276          @operator.IterationsParameter.ActualName = "Iteration";
[12120]277          @operator.IterationsParameter.Hidden = true;
[12136]278          @operator.MaximumIterationsParameter.ActualName = MaximumIterationsParameter.Name;
[12120]279          @operator.MaximumIterationsParameter.Hidden = true;
280        }
281      }
282    }
283
[12138]284    protected override void ParameterizeStochasticOperator(IOperator @operator) {
285      var stochasticOperator = @operator as IStochasticOperator;
286      if (stochasticOperator != null) {
287        stochasticOperator.RandomParameter.ActualName = "Random";
288        stochasticOperator.RandomParameter.Hidden = true;
289      }
290    }
[12120]291    protected override void ParameterizeStochasticOperatorForLayer(IOperator @operator) {
292      var stochasticOperator = @operator as IStochasticOperator;
293      if (stochasticOperator != null) {
[12138]294        stochasticOperator.RandomParameter.ActualName = "Random";
[12120]295        stochasticOperator.RandomParameter.Hidden = true;
296      }
297    }
[12119]298    #endregion
299
300    #region Updates
[12120]301    private void UpdateCrossovers() {
302      var oldCrossover = CrossoverParameter.Value;
303      var defaultCrossover = Problem.Operators.OfType<ICrossover>().FirstOrDefault();
304      CrossoverParameter.ValidValues.Clear();
305      foreach (var crossover in Problem.Operators.OfType<ICrossover>().OrderBy(c => c.Name)) {
306        ParameterizeStochasticOperatorForLayer(crossover);
307        CrossoverParameter.ValidValues.Add(crossover);
308      }
309      if (oldCrossover != null) {
310        var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
311        if (crossover != null)
312          CrossoverParameter.Value = crossover;
313        else
314          oldCrossover = null;
315      }
316      if (oldCrossover == null && defaultCrossover != null)
317        CrossoverParameter.Value = defaultCrossover;
318    }
319    private void UpdateMutators() {
320      var oldMutator = MutatorParameter.Value;
321      MutatorParameter.ValidValues.Clear();
322      foreach (var mutator in Problem.Operators.OfType<IManipulator>().OrderBy(m => m.Name)) {
323        ParameterizeStochasticOperatorForLayer(mutator);
324        MutatorParameter.ValidValues.Add(mutator);
325      }
326      if (oldMutator != null) {
327        var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
328        if (mutator != null)
329          MutatorParameter.Value = mutator;
330      }
331    }
[12119]332    #endregion
333  }
334}
Note: See TracBrowser for help on using the repository browser.