Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CellularGeneticAlgorithm/HeuristicLab.Algorithms.CellularGeneticAlgorithm/3.4/CellularGeneticAlgorithm.cs @ 9070

Last change on this file since 9070 was 7540, checked in by svonolfe, 13 years ago

Added first working version of cellular GA (#1781)

File size: 17.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Core;
6using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
7using HeuristicLab.Optimization;
8using HeuristicLab.Common;
9using HeuristicLab.Parameters;
10using HeuristicLab.Data;
11using HeuristicLab.Analysis;
12using HeuristicLab.Optimization.Operators;
13using HeuristicLab.Operators;
14using HeuristicLab.PluginInfrastructure;
15using HeuristicLab.Random;
16
17namespace HeuristicLab.Algorithms.CellularGeneticAlgorithm {
18  /// <summary>
19  /// A genetic algorithm.
20  /// </summary>
21  [Item("Cellular Genetic Algorithm", "A cellular genetic algorithm.")]
22  [Creatable("Algorithms")]
23  [StorableClass]
24  public sealed class CellularGeneticAlgorithm : HeuristicOptimizationEngineAlgorithm, IStorableContent {
25    public string Filename { get; set; }
26
27    #region Problem Properties
28    public override Type ProblemType {
29      get { return typeof(ISingleObjectiveHeuristicOptimizationProblem); }
30    }
31    public new ISingleObjectiveHeuristicOptimizationProblem Problem {
32      get { return (ISingleObjectiveHeuristicOptimizationProblem)base.Problem; }
33      set { base.Problem = value; }
34    }
35    #endregion
36
37    #region Parameter Properties
38    private ValueParameter<IntValue> SeedParameter {
39      get { return (ValueParameter<IntValue>)Parameters["Seed"]; }
40    }
41    private ValueParameter<BoolValue> SetSeedRandomlyParameter {
42      get { return (ValueParameter<BoolValue>)Parameters["SetSeedRandomly"]; }
43    }
44    private ValueParameter<IntValue> PopulationSizeParameter {
45      get { return (ValueParameter<IntValue>)Parameters["PopulationSize"]; }
46    }
47    public ConstrainedValueParameter<ISelector> SelectorParameter {
48      get { return (ConstrainedValueParameter<ISelector>)Parameters["Selector"]; }
49    }
50    public ConstrainedValueParameter<ICrossover> CrossoverParameter {
51      get { return (ConstrainedValueParameter<ICrossover>)Parameters["Crossover"]; }
52    }
53    private ValueParameter<PercentValue> MutationProbabilityParameter {
54      get { return (ValueParameter<PercentValue>)Parameters["MutationProbability"]; }
55    }
56    public OptionalConstrainedValueParameter<IManipulator> MutatorParameter {
57      get { return (OptionalConstrainedValueParameter<IManipulator>)Parameters["Mutator"]; }
58    }
59    private ValueParameter<MultiAnalyzer> AnalyzerParameter {
60      get { return (ValueParameter<MultiAnalyzer>)Parameters["Analyzer"]; }
61    }
62    private ValueParameter<NeighborhoodSelector> NeighborhoodSelectorParameter {
63      get { return (ValueParameter<NeighborhoodSelector>)Parameters["NeighborhoodSelector"]; }
64    }
65    private ValueParameter<IntValue> MaximumGenerationsParameter {
66      get { return (ValueParameter<IntValue>)Parameters["MaximumGenerations"]; }
67    }
68    #endregion
69
70    #region Properties
71    public IntValue Seed {
72      get { return SeedParameter.Value; }
73      set { SeedParameter.Value = value; }
74    }
75    public BoolValue SetSeedRandomly {
76      get { return SetSeedRandomlyParameter.Value; }
77      set { SetSeedRandomlyParameter.Value = value; }
78    }
79    public IntValue PopulationSize {
80      get { return PopulationSizeParameter.Value; }
81      set { PopulationSizeParameter.Value = value; }
82    }
83    public ISelector Selector {
84      get { return SelectorParameter.Value; }
85      set { SelectorParameter.Value = value; }
86    }
87    public ICrossover Crossover {
88      get { return CrossoverParameter.Value; }
89      set { CrossoverParameter.Value = value; }
90    }
91    public PercentValue MutationProbability {
92      get { return MutationProbabilityParameter.Value; }
93      set { MutationProbabilityParameter.Value = value; }
94    }
95    public IManipulator Mutator {
96      get { return MutatorParameter.Value; }
97      set { MutatorParameter.Value = value; }
98    }
99    public MultiAnalyzer Analyzer {
100      get { return AnalyzerParameter.Value; }
101      set { AnalyzerParameter.Value = value; }
102    }
103    public NeighborhoodSelector NeighborhoodSelector {
104      get { return NeighborhoodSelectorParameter.Value; }
105      set { NeighborhoodSelectorParameter.Value = value; }
106    }
107    public IntValue MaximumGenerations {
108      get { return MaximumGenerationsParameter.Value; }
109      set { MaximumGenerationsParameter.Value = value; }
110    }
111    private RandomCreator RandomCreator {
112      get { return (RandomCreator)OperatorGraph.InitialOperator; }
113    }
114    private SolutionsCreator SolutionsCreator {
115      get { return (SolutionsCreator)RandomCreator.Successor; }
116    }
117    private CellularGeneticAlgorithmMainLoop GeneticAlgorithmMainLoop {
118      get { return FindMainLoop(SolutionsCreator.Successor); }
119    }
120    [Storable]
121    private BestAverageWorstQualityAnalyzer qualityAnalyzer;
122    #endregion
123
124    public CellularGeneticAlgorithm()
125      : base() {
126      Parameters.Add(new ValueParameter<IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
127      Parameters.Add(new ValueParameter<BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
128      Parameters.Add(new ValueParameter<IntValue>("PopulationSize", "The size of the population of solutions.", new IntValue(100)));
129      Parameters.Add(new ConstrainedValueParameter<ISelector>("Selector", "The operator used to select solutions for reproduction."));
130      Parameters.Add(new ConstrainedValueParameter<ICrossover>("Crossover", "The operator used to cross solutions."));
131      Parameters.Add(new ValueParameter<PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution.", new PercentValue(0.05)));
132      Parameters.Add(new OptionalConstrainedValueParameter<IManipulator>("Mutator", "The operator used to mutate solutions."));
133      Parameters.Add(new ValueParameter<MultiAnalyzer>("Analyzer", "The operator used to analyze each generation.", new MultiAnalyzer()));
134      Parameters.Add(new ValueParameter<NeighborhoodSelector>("NeighborhoodSelector", "The neighborhood selector.", new VonNeumannNeighborhoodSelector()));
135      Parameters.Add(new ValueParameter<IntValue>("MaximumGenerations", "The maximum number of generations which should be processed.", new IntValue(1000)));
136
137      RandomCreator randomCreator = new RandomCreator();
138      SolutionsCreator solutionsCreator = new SolutionsCreator();
139      SubScopesCounter subScopesCounter = new SubScopesCounter();
140      ResultsCollector resultsCollector = new ResultsCollector();
141      CellularGeneticAlgorithmMainLoop mainLoop = new CellularGeneticAlgorithmMainLoop();
142      OperatorGraph.InitialOperator = randomCreator;
143
144      randomCreator.RandomParameter.ActualName = "Random";
145      randomCreator.SeedParameter.ActualName = SeedParameter.Name;
146      randomCreator.SeedParameter.Value = null;
147      randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
148      randomCreator.SetSeedRandomlyParameter.Value = null;
149      randomCreator.Successor = solutionsCreator;
150
151      solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
152      solutionsCreator.Successor = resultsCollector;/*subScopesCounter;
153
154      subScopesCounter.Name = "Initialize EvaluatedSolutions";
155      subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
156      subScopesCounter.Successor = resultsCollector;*/
157
158      resultsCollector.CollectedValues.Add(new LookupParameter<IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
159      resultsCollector.ResultsParameter.ActualName = "Results";
160      resultsCollector.Successor = mainLoop;
161
162      mainLoop.SelectorParameter.ActualName = SelectorParameter.Name;
163      mainLoop.CrossoverParameter.ActualName = CrossoverParameter.Name;
164      mainLoop.MaximumGenerationsParameter.ActualName = MaximumGenerationsParameter.Name;
165      mainLoop.MutatorParameter.ActualName = MutatorParameter.Name;
166      mainLoop.MutationProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
167      mainLoop.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
168      mainLoop.AnalyzerParameter.ActualName = AnalyzerParameter.Name;
169      mainLoop.EvaluatedSolutionsParameter.ActualName = "EvaluatedSolutions";
170      mainLoop.PopulationSizeParameter.ActualName = PopulationSizeParameter.Name;
171      mainLoop.ResultsParameter.ActualName = "Results";
172
173      foreach (ISelector selector in ApplicationManager.Manager.GetInstances<ISelector>().Where(x => !(x is IMultiObjectiveSelector)).OrderBy(x => x.Name))
174        SelectorParameter.ValidValues.Add(selector);
175      ISelector proportionalSelector = SelectorParameter.ValidValues.FirstOrDefault(x => x.GetType().Name.Equals("ProportionalSelector"));
176      if (proportionalSelector != null) SelectorParameter.Value = proportionalSelector;
177      ParameterizeSelectors();
178
179      qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
180      ParameterizeAnalyzers();
181      UpdateAnalyzers();
182
183      Initialize();
184    }
185    [StorableConstructor]
186    private CellularGeneticAlgorithm(bool deserializing) : base(deserializing) { }
187    [StorableHook(HookType.AfterDeserialization)]
188    private void AfterDeserialization() {
189      Initialize();
190    }
191
192    private CellularGeneticAlgorithm(CellularGeneticAlgorithm original, Cloner cloner)
193      : base(original, cloner) {
194      qualityAnalyzer = cloner.Clone(original.qualityAnalyzer);
195      Initialize();
196    }
197    public override IDeepCloneable Clone(Cloner cloner) {
198      return new CellularGeneticAlgorithm(this, cloner);
199    }
200
201    public override void Prepare() {
202      if (Problem != null) base.Prepare();
203    }
204
205    #region Events
206    protected override void OnProblemChanged() {
207      ParameterizeStochasticOperator(Problem.SolutionCreator);
208      ParameterizeStochasticOperator(Problem.Evaluator);
209      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
210      ParameterizeSolutionsCreator();
211      ParameterizeGeneticAlgorithmMainLoop();
212      ParameterizeSelectors();
213      ParameterizeAnalyzers();
214      ParameterizeIterationBasedOperators();
215      UpdateCrossovers();
216      UpdateMutators();
217      UpdateAnalyzers();
218      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
219      base.OnProblemChanged();
220    }
221
222    protected override void Problem_SolutionCreatorChanged(object sender, EventArgs e) {
223      ParameterizeStochasticOperator(Problem.SolutionCreator);
224      ParameterizeSolutionsCreator();
225      base.Problem_SolutionCreatorChanged(sender, e);
226    }
227    protected override void Problem_EvaluatorChanged(object sender, EventArgs e) {
228      ParameterizeStochasticOperator(Problem.Evaluator);
229      ParameterizeSolutionsCreator();
230      ParameterizeGeneticAlgorithmMainLoop();
231      ParameterizeSelectors();
232      ParameterizeAnalyzers();
233      Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
234      base.Problem_EvaluatorChanged(sender, e);
235    }
236    protected override void Problem_OperatorsChanged(object sender, EventArgs e) {
237      foreach (IOperator op in Problem.Operators) ParameterizeStochasticOperator(op);
238      ParameterizeIterationBasedOperators();
239      UpdateCrossovers();
240      UpdateMutators();
241      UpdateAnalyzers();
242      base.Problem_OperatorsChanged(sender, e);
243    }
244    private void Elites_ValueChanged(object sender, EventArgs e) {
245      ParameterizeSelectors();
246    }
247
248    private void PopulationSizeParameter_ValueChanged(object sender, EventArgs e) {
249      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
250      ParameterizeSelectors();
251    }
252    private void PopulationSize_ValueChanged(object sender, EventArgs e) {
253      ParameterizeSelectors();
254    }
255    private void Evaluator_QualityParameter_ActualNameChanged(object sender, EventArgs e) {
256      ParameterizeGeneticAlgorithmMainLoop();
257      ParameterizeSelectors();
258      ParameterizeAnalyzers();
259    }
260    #endregion
261
262    #region Helpers
263    private void Initialize() {
264      PopulationSizeParameter.ValueChanged += new EventHandler(PopulationSizeParameter_ValueChanged);
265      PopulationSize.ValueChanged += new EventHandler(PopulationSize_ValueChanged);
266      if (Problem != null) {
267        Problem.Evaluator.QualityParameter.ActualNameChanged += new EventHandler(Evaluator_QualityParameter_ActualNameChanged);
268      }
269    }
270
271    private void ParameterizeSolutionsCreator() {
272      SolutionsCreator.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
273      SolutionsCreator.SolutionCreatorParameter.ActualName = Problem.SolutionCreatorParameter.Name;
274    }
275    private void ParameterizeGeneticAlgorithmMainLoop() {
276      GeneticAlgorithmMainLoop.EvaluatorParameter.ActualName = Problem.EvaluatorParameter.Name;
277      GeneticAlgorithmMainLoop.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
278      GeneticAlgorithmMainLoop.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
279    }
280    private void ParameterizeStochasticOperator(IOperator op) {
281      IStochasticOperator stochasticOp = op as IStochasticOperator;
282      if (stochasticOp != null) {
283        stochasticOp.RandomParameter.ActualName = RandomCreator.RandomParameter.ActualName;
284        stochasticOp.RandomParameter.Hidden = true;
285      }
286    }
287    private void ParameterizeSelectors() {
288      foreach (ISelector selector in SelectorParameter.ValidValues) {
289        selector.CopySelected = new BoolValue(true);
290        selector.NumberOfSelectedSubScopesParameter.Value = new IntValue(1);
291        selector.NumberOfSelectedSubScopesParameter.Hidden = true;
292        ParameterizeStochasticOperator(selector);
293      }
294      if (Problem != null) {
295        foreach (ISingleObjectiveSelector selector in SelectorParameter.ValidValues.OfType<ISingleObjectiveSelector>()) {
296          selector.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
297          selector.MaximizationParameter.Hidden = true;
298          selector.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
299          selector.QualityParameter.Hidden = true;
300        }
301      }
302    }
303    private void ParameterizeAnalyzers() {
304      qualityAnalyzer.ResultsParameter.ActualName = "Results";
305      qualityAnalyzer.ResultsParameter.Hidden = true;
306      if (Problem != null) {
307        qualityAnalyzer.MaximizationParameter.ActualName = Problem.MaximizationParameter.Name;
308        qualityAnalyzer.MaximizationParameter.Hidden = true;
309        qualityAnalyzer.QualityParameter.ActualName = Problem.Evaluator.QualityParameter.ActualName;
310        qualityAnalyzer.QualityParameter.Depth = 1;
311        qualityAnalyzer.QualityParameter.Hidden = true;
312        qualityAnalyzer.BestKnownQualityParameter.ActualName = Problem.BestKnownQualityParameter.Name;
313        qualityAnalyzer.BestKnownQualityParameter.Hidden = true;
314      }
315    }
316    private void ParameterizeIterationBasedOperators() {
317      if (Problem != null) {
318        foreach (IIterationBasedOperator op in Problem.Operators.OfType<IIterationBasedOperator>()) {
319          op.IterationsParameter.ActualName = "Generations";
320          op.IterationsParameter.Hidden = true;
321          op.MaximumIterationsParameter.ActualName = "MaximumGenerations";
322          op.MaximumIterationsParameter.Hidden = true;
323        }
324      }
325    }
326    private void UpdateCrossovers() {
327      ICrossover oldCrossover = CrossoverParameter.Value;
328      CrossoverParameter.ValidValues.Clear();
329      foreach (ICrossover crossover in Problem.Operators.OfType<ICrossover>().OrderBy(x => x.Name))
330        CrossoverParameter.ValidValues.Add(crossover);
331      if (oldCrossover != null) {
332        ICrossover crossover = CrossoverParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldCrossover.GetType());
333        if (crossover != null) CrossoverParameter.Value = crossover;
334      }
335    }
336    private void UpdateMutators() {
337      IManipulator oldMutator = MutatorParameter.Value;
338      MutatorParameter.ValidValues.Clear();
339      foreach (IManipulator mutator in Problem.Operators.OfType<IManipulator>().OrderBy(x => x.Name))
340        MutatorParameter.ValidValues.Add(mutator);
341      if (oldMutator != null) {
342        IManipulator mutator = MutatorParameter.ValidValues.FirstOrDefault(x => x.GetType() == oldMutator.GetType());
343        if (mutator != null) MutatorParameter.Value = mutator;
344      }
345    }
346    private void UpdateAnalyzers() {
347      Analyzer.Operators.Clear();
348      if (Problem != null) {
349        foreach (IAnalyzer analyzer in Problem.Operators.OfType<IAnalyzer>()) {
350          foreach (IScopeTreeLookupParameter param in analyzer.Parameters.OfType<IScopeTreeLookupParameter>())
351            param.Depth = 1;
352          Analyzer.Operators.Add(analyzer, analyzer.EnabledByDefault);
353        }
354      }
355      Analyzer.Operators.Add(qualityAnalyzer, qualityAnalyzer.EnabledByDefault);
356    }
357    private CellularGeneticAlgorithmMainLoop FindMainLoop(IOperator start) {
358      IOperator mainLoop = start;
359      while (mainLoop != null && !(mainLoop is CellularGeneticAlgorithmMainLoop))
360        mainLoop = ((SingleSuccessorOperator)mainLoop).Successor;
361      if (mainLoop == null) return null;
362      else return (CellularGeneticAlgorithmMainLoop)mainLoop;
363    }
364    #endregion
365  }
366}
Note: See TracBrowser for help on using the repository browser.