Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gp-crossover/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionContextAwareCrossover.cs @ 7193

Last change on this file since 7193 was 7193, checked in by bburlacu, 12 years ago

#1682: Overhauled the crossover operators, fixed bug in the DeterministicBestCrossover.

File size: 6.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 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.Persistence.Default.CompositeSerializers.Storable;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
31
32  [Item("ContextAwareCrossover", "An operator which deterministically choses the best insertion point for a randomly selected node.")]
33  public sealed class SymbolicDataAnalysisExpressionContextAwareCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
34    [StorableConstructor]
35    private SymbolicDataAnalysisExpressionContextAwareCrossover(bool deserializing) : base(deserializing) { }
36    private SymbolicDataAnalysisExpressionContextAwareCrossover(SymbolicDataAnalysisExpressionCrossover<T> original, Cloner cloner)
37      : base(original, cloner) {
38    }
39    public SymbolicDataAnalysisExpressionContextAwareCrossover()
40      : base() {
41    }
42    public override IDeepCloneable Clone(Cloner cloner) {
43      return new SymbolicDataAnalysisExpressionContextAwareCrossover<T>(this, cloner);
44    }
45    protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
46      if (this.ExecutionContext == null)
47        throw new InvalidOperationException("ExecutionContext not set.");
48      List<int> rows = GenerateRowsToEvaluate().ToList();
49      T problemData = ProblemDataParameter.ActualValue;
50      ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator = EvaluatorParameter.ActualValue;
51
52      return Cross(random, parent0, parent1, this.ExecutionContext, evaluator, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value);
53    }
54
55    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
56      return Cross(random, parent0, parent1);
57    }
58
59    /// <summary>
60    /// Takes two parent individuals P0 and P1.
61    /// Randomly choose a node i from the second parent, then test all possible crossover points from the first parent to determine the best location for i to be inserted.
62    /// </summary>
63    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, IExecutionContext context,
64                                                ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator, T problemData, List<int> rows, int maxDepth, int maxLength) {
65      // randomly choose a node from the second parent
66      var possibleChildren = new List<ISymbolicExpressionTreeNode>();
67      parent1.Root.ForEachNodePostfix((n) => {
68        if (n.Subtrees.Any() && n != parent0.Root)
69          possibleChildren.AddRange(n.Subtrees);
70      });
71      var selectedChild = possibleChildren.SelectRandom(random);
72      var crossoverPoints = new List<CutPoint>();
73      var qualities = new List<Tuple<CutPoint, double>>();
74
75      parent0.Root.ForEachNodePostfix((n) => {
76        if (n.Subtrees.Any() && n != parent0.Root)
77          crossoverPoints.AddRange(from s in n.Subtrees
78                                   let crossoverPoint = new CutPoint(n, s)
79                                   let totalDepth = parent0.Root.GetBranchLevel(s) + selectedChild.GetDepth()
80                                   let totalLength = parent0.Root.GetLength() - s.GetLength() + selectedChild.GetLength()
81                                   where crossoverPoint.IsMatchingPointType(selectedChild) && totalDepth <= maxDepth && totalLength <= maxLength
82                                   select crossoverPoint);
83      });
84
85      if (crossoverPoints.Any()) {
86        // this loop will perform two swap operations per each crossover point
87        foreach (var crossoverPoint in crossoverPoints) {
88          // save the old parent so we can restore it later
89          var parent = selectedChild.Parent;
90          // perform a swap and check the quality of the solution
91          swap(crossoverPoint, selectedChild);
92          double quality = evaluator.Evaluate(context, parent0, problemData, rows);
93          qualities.Add(new Tuple<CutPoint, double>(crossoverPoint, quality));
94          // restore the correct parent
95          selectedChild.Parent = parent;
96          // swap the replaced subtree back into the tree so that the structure is preserved
97          swap(crossoverPoint, crossoverPoint.Child);
98        }
99
100        qualities.Sort((a, b) => a.Item2.CompareTo(b.Item2)); // assuming this sorts the list in ascending order
101        var crossoverPoint0 = evaluator.Maximization ? qualities.Last().Item1 : qualities.First().Item1;
102        // swap the node that would create the best offspring
103        // this last swap makes a total of (2 * crossoverPoints.Count() + 1) swap operations.
104        swap(crossoverPoint0, selectedChild);
105      }
106
107      return parent0;
108    }
109
110    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
111      if (crossoverPoint.Child != null) {
112        // manipulate the tree of parent0 in place
113        // replace the branch in tree0 with the selected branch from tree1
114        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
115        if (selectedBranch != null) {
116          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
117        }
118      } else {
119        // child is null (additional child should be added under the parent)
120        if (selectedBranch != null) {
121          crossoverPoint.Parent.AddSubtree(selectedBranch);
122        }
123      }
124    }
125  }
126}
Note: See TracBrowser for help on using the repository browser.