#region License Information
/* HeuristicLab
* Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Optimization.Operators;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
using HeuristicLab.PluginInfrastructure;
using HeuristicLab.Random;
using HeuristicLab.Selection;
namespace HeuristicLab.Algorithms.ALPS {
[Item("ALPS Genetic Algorithm", "A genetic algorithm with an age-layered population structure.")]
[Creatable("Algorithms")]
[StorableClass]
public sealed class AlpsGeneticAlgorithm : Alps {
#region Parameter Properties
private IValueParameter PopulationSizeParameter {
get { return (IValueParameter)Parameters["PopulationSize"]; }
}
public IConstrainedValueParameter SelectorParameter {
get { return (IConstrainedValueParameter)Parameters["Selector"]; }
}
public IConstrainedValueParameter CrossoverParameter {
get { return (IConstrainedValueParameter)Parameters["Crossover"]; }
}
private IValueParameter MutationProbabilityParameter {
get { return (IValueParameter)Parameters["MutationProbability"]; }
}
public IConstrainedValueParameter MutatorParameter {
get { return (IConstrainedValueParameter)Parameters["Mutator"]; }
}
private IValueParameter ElitesParameter {
get { return (IValueParameter)Parameters["Elites"]; }
}
private IFixedValueParameter ReevaluateElitesParameter {
get { return (IFixedValueParameter)Parameters["ReevaluateElites"]; }
}
private IValueParameter PlusSelectionParameter {
get { return (IValueParameter)Parameters["PlusSelection"]; }
}
#endregion
#region Properties
public IntArray PopulationSize {
get { return PopulationSizeParameter.Value; }
set { PopulationSizeParameter.Value = value; }
}
public int MaximumGenerations {
get { return generationsTerminator.Threshold.Value; }
set { generationsTerminator.Threshold.Value = value; }
}
public ISelector Selector {
get { return SelectorParameter.Value; }
set { SelectorParameter.Value = value; }
}
public ICrossover Crossover {
get { return CrossoverParameter.Value; }
set { CrossoverParameter.Value = value; }
}
public PercentValue MutationProbability {
get { return MutationProbabilityParameter.Value; }
set { MutationProbabilityParameter.Value = value; }
}
public IManipulator Mutator {
get { return MutatorParameter.Value; }
set { MutatorParameter.Value = value; }
}
public IntValue Elites {
get { return ElitesParameter.Value; }
set { ElitesParameter.Value = value; }
}
public bool ReevaluteElites {
get { return ReevaluateElitesParameter.Value.Value; }
set { ReevaluateElitesParameter.Value.Value = value; }
}
public bool PlusSelection {
get { return PlusSelectionParameter.Value.Value; }
set { PlusSelectionParameter.Value.Value = value; }
}
private AlpsGeneticAlgorithmMainLoop MainLoop {
get { return OperatorGraph.Iterate().OfType().First(); }
}
#endregion
[Storable]
private ComparisonTerminator generationsTerminator;
[StorableConstructor]
private AlpsGeneticAlgorithm(bool deserializing)
: base(deserializing) { }
private AlpsGeneticAlgorithm(AlpsGeneticAlgorithm original, Cloner cloner)
: base(original, cloner) {
generationsTerminator = cloner.Clone(original.generationsTerminator);
Initialize();
}
public override IDeepCloneable Clone(Cloner cloner) {
return new AlpsGeneticAlgorithm(this, cloner);
}
public AlpsGeneticAlgorithm()
: base() {
Parameters.Add(new ValueParameter("PopulationSize", "The size of the population of solutions each layer.", new IntArray(new[] { 100 })));
Parameters.Add(new ConstrainedValueParameter("Selector", "The operator used to select solutions for reproduction."));
Parameters.Add(new ConstrainedValueParameter("Crossover", "The operator used to cross solutions."));
Parameters.Add(new ValueParameter("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
Parameters.Add(new OptionalConstrainedValueParameter("Mutator", "The operator used to mutate solutions."));
Parameters.Add(new ValueParameter("Elites", "The numer of elite solutions which are kept in each generation.", new IntValue(1)));
Parameters.Add(new FixedValueParameter("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)", new BoolValue(false)) { Hidden = true });
Parameters.Add(new ValueParameter("PlusSelection", "Include the parents in the selection of the invividuals for the next generation.", new BoolValue(false)) { Hidden = true });
var globalRandomCreator = new RandomCreator();
var layer0Creator = new SubScopesCreator() { Name = "Create Layer Zero" };
var layer0Processor = new LayerUniformSubScopesProcessor();
var localRandomCreator = new LocalRandomCreator();
var layerVariableCreator = new VariableCreator();
var layerSolutionsCreator = new SolutionsCreator();
var initializeAgeProcessor = new UniformSubScopesProcessor();
var initializeAge = new VariableCreator() { Name = "Initialize Age" };
var initializeLayerPopulationSize = new SubScopesCounter() { Name = "Init LayerPopulationCounter" };
var initializeLocalEvaluatedSolutions = new Assigner() { Name = "Initialize LayerEvaluatedSolutions" };
var initializeGlobalEvaluatedSolutions = new DataReducer() { Name = "Initialize EvaluatedSolutions" };
var resultsCollector = new ResultsCollector();
var mainLoop = new AlpsGeneticAlgorithmMainLoop();
OperatorGraph.InitialOperator = globalRandomCreator;
globalRandomCreator.RandomParameter.ActualName = "GlobalRandom";
globalRandomCreator.SeedParameter.Value = null;
globalRandomCreator.SetSeedRandomlyParameter.Value = null;
globalRandomCreator.Successor = layer0Creator;
layer0Creator.NumberOfSubScopesParameter.Value = new IntValue(1);
layer0Creator.Successor = layer0Processor;
layer0Processor.Operator = localRandomCreator;
layer0Processor.Successor = initializeGlobalEvaluatedSolutions;
localRandomCreator.Successor = layerVariableCreator;
layerVariableCreator.CollectedValues.Add(new ValueParameter("Layer", new IntValue(0)));
layerVariableCreator.Successor = layerSolutionsCreator;
layerSolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
layerSolutionsCreator.Successor = initializeAgeProcessor;
initializeAgeProcessor.Operator = initializeAge;
initializeAgeProcessor.Successor = initializeLayerPopulationSize;
initializeLayerPopulationSize.ValueParameter.ActualName = "LayerPopulationSize";
initializeLayerPopulationSize.Successor = initializeLocalEvaluatedSolutions;
initializeAge.CollectedValues.Add(new ValueParameter("Age", new IntValue(0)));
initializeAge.Successor = null;
initializeLocalEvaluatedSolutions.LeftSideParameter.ActualName = "LayerEvaluatedSolutions";
initializeLocalEvaluatedSolutions.RightSideParameter.ActualName = "LayerPopulationSize";
initializeLocalEvaluatedSolutions.Successor = null;
initializeGlobalEvaluatedSolutions.ReductionOperation.Value.Value = ReductionOperations.Sum;
initializeGlobalEvaluatedSolutions.TargetOperation.Value.Value = ReductionOperations.Assign;
initializeGlobalEvaluatedSolutions.ParameterToReduce.ActualName = "LayerEvaluatedSolutions";
initializeGlobalEvaluatedSolutions.TargetParameter.ActualName = "EvaluatedSolutions";
initializeGlobalEvaluatedSolutions.Successor = resultsCollector;
resultsCollector.CollectedValues.Add(new LookupParameter("Evaluated Solutions", null, "EvaluatedSolutions"));
resultsCollector.Successor = mainLoop;
foreach (var selector in ApplicationManager.Manager.GetInstances().Where(s => !(s is IMultiObjectiveSelector)).OrderBy(s => Name))
SelectorParameter.ValidValues.Add(selector);
var tournamentSelector = SelectorParameter.ValidValues.OfType().FirstOrDefault();
if (tournamentSelector != null) {
tournamentSelector.GroupSizeParameter.Value = new IntValue(4);
SelectorParameter.Value = tournamentSelector;
}
ParameterizeSelectors();
Initialize();
}
#region Events
protected override void OnProblemChanged() {
base.OnProblemChanged();
ParameterizeSolutionsCreator();
ParameterizeMainLoop();
ParameterizeSelectors();
ParameterizeIterationBasedOperators();
UpdateCrossovers();
UpdateMutators();
}
protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
base.Problem_SolutionCreatorChanged(sender, e);
ParameterizeSolutionsCreator();
}
protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
base.Problem_EvaluatorChanged(sender, e);
ParameterizeSolutionsCreator();
ParameterizeMainLoop();
ParameterizeSelectors();
}
protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
base.Problem_OperatorsChanged(sender, e);
ParameterizeIterationBasedOperators();
UpdateCrossovers();
UpdateMutators();
}
protected override void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
base.Evaluator_QualityParameter_ActualNameChanged(sender, e);
ParameterizeMainLoop();
ParameterizeSelectors();
}
#endregion
#region Parameterization
private void Initialize() {
}
private void ParameterizeSolutionsCreator() {
MainLoop.LayerUpdator.SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
MainLoop.LayerUpdator.SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
}
private void ParameterizeMainLoop() {
MainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
MainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
MainLoop.MainOperator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
MainLoop.MainOperator.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
MainLoop.MainOperator.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
MainLoop.LayerUpdator.SolutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
}
private void ParameterizeSelectors() {
foreach (var selector in SelectorParameter.ValidValues) {
selector.CopySelected = new BoolValue(true);
// Explicit setting of NumberOfSelectedSubScopesParameter is not required anymore because the NumberOfSelectedSubScopesCalculator calculates it itself
//selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(2 * (PopulationSize - Elites.Value));
selector.NumberOfSelectedSubScopesParameter.Hidden = true;
ParameterizeStochasticOperatorForLayer(selector);
}
if (Problem != null) {
foreach (var selector in SelectorParameter.ValidValues.OfType()) {
selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
selector.MaximizationParameter.Hidden = true;
selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
selector.QualityParameter.Hidden = true;
}
}
}
private void ParameterizeIterationBasedOperators() {
if (Problem != null) {
foreach (var @operator in Problem.Operators.OfType()) {
@operator.IterationsParameter.ActualName = "Generations";
@operator.IterationsParameter.Hidden = true;
@operator.MaximumIterationsParameter.ActualName = generationsTerminator.ThresholdParameter.Name;
@operator.MaximumIterationsParameter.Hidden = true;
}
}
}
protected override ReductionOperations GetAgeInheritanceReduction(AgeInheritance ageInheritance) {
switch (ageInheritance) {
case ALPS.AgeInheritance.Older: return ReductionOperations.Max;
case ALPS.AgeInheritance.Agerage: return ReductionOperations.Avg;
case ALPS.AgeInheritance.Younger: return ReductionOperations.Min;
default: throw new NotSupportedException("AgeInheritance " + ageInheritance + " is not supported.");
}
}
#endregion
#region Updates
protected override void UpdateTerminators() {
var newTerminators = new Dictionary {
{generationsTerminator, !Terminators.Operators.Contains(generationsTerminator) || Terminators.Operators.ItemChecked(generationsTerminator)},
};
base.UpdateTerminators();
foreach (var newTerminator in newTerminators)
Terminators.Operators.Insert(0, newTerminator.Key, newTerminator.Value);
}
protected override void CreateTerminators() {
generationsTerminator = new ComparisonTerminator("Generations", ComparisonType.Less, new IntValue(1000)) { Name = "Generations" };
base.CreateTerminators();
}
private void UpdateCrossovers() {
var oldCrossover = CrossoverParameter.Value;
var defaultCrossover = Problem.Operators.OfType().FirstOrDefault();
CrossoverParameter.ValidValues.Clear();
foreach (var crossover in Problem.Operators.OfType().OrderBy(c => c.Name)) {
ParameterizeStochasticOperatorForLayer(crossover);
CrossoverParameter.ValidValues.Add(crossover);
}
if (oldCrossover != null) {
var crossover = CrossoverParameter.ValidValues.FirstOrDefault(c => c.GetType() == oldCrossover.GetType());
if (crossover != null)
CrossoverParameter.Value = crossover;
else
oldCrossover = null;
}
if (oldCrossover == null && defaultCrossover != null)
CrossoverParameter.Value = defaultCrossover;
}
private void UpdateMutators() {
var oldMutator = MutatorParameter.Value;
MutatorParameter.ValidValues.Clear();
foreach (var mutator in Problem.Operators.OfType().OrderBy(m => m.Name)) {
ParameterizeStochasticOperatorForLayer(mutator);
MutatorParameter.ValidValues.Add(mutator);
}
if (oldMutator != null) {
var mutator = MutatorParameter.ValidValues.FirstOrDefault(m => m.GetType() == oldMutator.GetType());
if (mutator != null)
MutatorParameter.Value = mutator;
}
}
#endregion
}
}