Free cookie consent management tool by TermsFeed Policy Generator

source: branches/gp-crossover/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionDeterministicBestCrossover.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("DeterministicBestCrossover", "An operator which performs subtree swapping in a deterministic way, by choosing the best subtree to be swapped in a certain position.")]
33  public sealed class SymbolicDataAnalysisExpressionDeterministicBestCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
34    [StorableConstructor]
35    private SymbolicDataAnalysisExpressionDeterministicBestCrossover(bool deserializing) : base(deserializing) { }
36    private SymbolicDataAnalysisExpressionDeterministicBestCrossover(SymbolicDataAnalysisExpressionCrossover<T> original, Cloner cloner)
37      : base(original, cloner) {
38    }
39    public SymbolicDataAnalysisExpressionDeterministicBestCrossover()
40      : base() {
41    }
42    public override IDeepCloneable Clone(Cloner cloner) {
43      return new SymbolicDataAnalysisExpressionDeterministicBestCrossover<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    /// <summary>
59    /// Takes two parent individuals P0 and P1.
60    /// Randomly choose a node i from the first parent, then test all nodes j from the second parent to determine the best child that would be obtained by swapping i for j.
61    /// </summary>
62    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, IExecutionContext context,
63                                                ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator, T problemData, List<int> rows, int maxDepth, int maxLength) {
64      var crossoverPoints0 = new List<CutPoint>();
65      parent0.Root.ForEachNodePostfix((n) => {
66        if (n.Subtrees.Any() && n != parent0.Root)
67          crossoverPoints0.AddRange(from s in n.Subtrees select new CutPoint(n, s));
68      });
69      CutPoint crossoverPoint0 = crossoverPoints0.SelectRandom(random);
70      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
71      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
72
73      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
74      parent1.Root.ForEachNodePostfix((n) => {
75        if (n.Subtrees.Any() && n != parent1.Root)
76          allowedBranches.AddRange(from s in n.Subtrees
77                                   where crossoverPoint0.IsMatchingPointType(s) && s.GetDepth() + level <= maxDepth && s.GetLength() + length <= maxLength
78                                   select s);
79      });
80
81      if (allowedBranches.Count == 0)
82        return parent0;
83
84      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
85      ISymbolicExpressionTreeNode selectedBranch = null;
86
87      var nodeQualities = new List<Tuple<ISymbolicExpressionTreeNode, double>>();
88
89      var originalChild = crossoverPoint0.Child;
90
91      foreach (var node in allowedBranches) {
92        var parent = node.Parent;
93        swap(crossoverPoint0, node); // the swap will set the nodes parent to crossoverPoint0.Parent
94        double quality = evaluator.Evaluate(context, parent0, problemData, rows);
95        swap(crossoverPoint0, originalChild); // swap the child back (so that the next swap will not affect the currently swapped node from parent1)
96        nodeQualities.Add(new Tuple<ISymbolicExpressionTreeNode, double>(node, quality));
97        node.Parent = parent; // restore correct parent
98      }
99
100      nodeQualities.Sort((a, b) => a.Item2.CompareTo(b.Item2)); // assuming this sorts the list in ascending order
101      selectedBranch = evaluator.Maximization ? nodeQualities.Last().Item1 : nodeQualities.First().Item1;
102
103
104      if (selectedBranch == null)
105        throw new Exception("Selected branch is null");
106
107      if (selectedBranch.Parent == null)
108        throw new Exception("Parent is null");
109
110
111      // swap the node that would create the best offspring
112      swap(crossoverPoint0, selectedBranch);
113
114      return parent0;
115    }
116
117    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
118      if (crossoverPoint.Child != null) {
119        // manipulate the tree of parent0 in place
120        // replace the branch in tree0 with the selected branch from tree1
121        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
122        if (selectedBranch != null) {
123          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
124        }
125      } else {
126        // child is null (additional child should be added under the parent)
127        if (selectedBranch != null) {
128          crossoverPoint.Parent.AddSubtree(selectedBranch);
129        }
130      }
131    }
132  }
133}
Note: See TracBrowser for help on using the repository browser.