Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1693: Implemented the context-aware crossover.

File size: 6.3 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 System.Text;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Common;
28using HeuristicLab.Core;
29using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
30using HeuristicLab.Data;
31
32namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
33
34  [Item("ContextAwareCrossover", "A crossover operator which deterministically choses the best insertion point for a randomly selected node.")]
35  public sealed class SymbolicDataAnalysisExpressionContextAwareCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
36    [StorableConstructor]
37    private SymbolicDataAnalysisExpressionContextAwareCrossover(bool deserializing) : base(deserializing) { }
38    private SymbolicDataAnalysisExpressionContextAwareCrossover(SymbolicDataAnalysisExpressionContextAwareCrossover<T> original, Cloner cloner)
39      : base(original, cloner) {
40    }
41    public SymbolicDataAnalysisExpressionContextAwareCrossover()
42      : base() {
43    }
44    public override IDeepCloneable Clone(Cloner cloner) {
45      return new SymbolicDataAnalysisExpressionContextAwareCrossover<T>(this, cloner);
46    }
47    protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
48      if (this.ExecutionContext == null)
49        throw new InvalidOperationException("ExecutionContext not set.");
50      IEnumerable<int> rows = GenerateRowsToEvaluate();
51      T problemData = ProblemDataParameter.ActualValue;
52      ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator = EvaluatorParameter.ActualValue;
53
54      return Cross(random, parent0, parent1, this.ExecutionContext, evaluator, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value);
55    }
56    /// <summary>
57    /// Takes two parent individuals P0 and P1.
58    /// 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.
59    /// </summary>
60    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, IExecutionContext context,
61                                                ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator, T problemData, IEnumerable<int> rows, int maxDepth, int maxLength) {
62      // randomly choose a node from the second parent
63      var possibleChildren = new List<ISymbolicExpressionTreeNode>();
64      parent1.Root.ForEachNodePostfix((n) => {
65        if (n.Subtrees.Any() && n != parent0.Root)
66          foreach (var child in n.Subtrees)
67            possibleChildren.Add(child);
68      });
69      var selectedChild = possibleChildren[random.Next(possibleChildren.Count)];
70      var crossoverPoints = new List<CutPoint>();
71      var qualities = new List<Tuple<CutPoint, double>>();
72
73      parent0.Root.ForEachNodePostfix((n) => {
74        if (n.Subtrees.Any() && n != parent0.Root)
75          foreach (var child in n.Subtrees) {
76            var crossoverPoint = new CutPoint(n, child);
77            int totalDepth = parent0.Root.GetBranchLevel(child) + selectedChild.GetDepth();
78            int totalLength = parent0.Root.GetLength() - child.GetLength() + selectedChild.GetLength();
79            if (crossoverPoint.IsMatchingPointType(selectedChild) && totalDepth <= maxDepth && totalLength <= maxLength) {
80              crossoverPoints.Add(crossoverPoint);
81            }
82          }
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.