Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Crossovers/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Crossovers/SymbolicDataAnalysisExpressionDeterministicBestCrossover.cs @ 7489

Last change on this file since 7489 was 7481, checked in by mkommend, 12 years ago

#1682: Corrected gp-crossover code.

  • Changed ISymbolicExpressionTreeCrossover
  • Corrected SubtreeCrossover
  • Updated MultiSymbolicDataAnalysisCrossover
File size: 6.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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      Name = "DeterministicBestCrossover";
42    }
43    public override IDeepCloneable Clone(Cloner cloner) {
44      return new SymbolicDataAnalysisExpressionDeterministicBestCrossover<T>(this, cloner);
45    }
46    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
47      if (this.ExecutionContext == null)
48        throw new InvalidOperationException("ExecutionContext not set.");
49      List<int> rows = GenerateRowsToEvaluate().ToList();
50      T problemData = ProblemDataParameter.ActualValue;
51      ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator = EvaluatorParameter.ActualValue;
52
53      return Cross(random, parent0, parent1, this.ExecutionContext, evaluator, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value);
54    }
55
56    /// <summary>
57    /// Takes two parent individuals P0 and P1.
58    /// 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.
59    /// </summary>
60    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, IExecutionContext context,
61                                                ISymbolicDataAnalysisSingleObjectiveEvaluator<T> evaluator, T problemData, List<int> rows, int maxDepth, int maxLength) {
62      var crossoverPoints0 = new List<CutPoint>();
63      parent0.Root.ForEachNodePostfix((n) => {
64        if (n.Subtrees.Any() && n != parent0.Root)
65          crossoverPoints0.AddRange(from s in n.Subtrees select new CutPoint(n, s));
66      });
67      CutPoint crossoverPoint0 = crossoverPoints0.SelectRandom(random);
68      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
69      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
70
71      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
72      parent1.Root.ForEachNodePostfix((n) => {
73        if (n.Subtrees.Any() && n != parent1.Root)
74          allowedBranches.AddRange(from s in n.Subtrees
75                                   where crossoverPoint0.IsMatchingPointType(s) && s.GetDepth() + level <= maxDepth && s.GetLength() + length <= maxLength
76                                   select s);
77      });
78
79      if (allowedBranches.Count == 0)
80        return parent0;
81
82      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
83      ISymbolicExpressionTreeNode selectedBranch = null;
84
85      var nodeQualities = new List<Tuple<ISymbolicExpressionTreeNode, double>>();
86
87      var originalChild = crossoverPoint0.Child;
88
89      foreach (var node in allowedBranches) {
90        var parent = node.Parent;
91        swap(crossoverPoint0, node); // the swap will set the nodes parent to crossoverPoint0.Parent
92        double quality = evaluator.Evaluate(context, parent0, problemData, rows);
93        swap(crossoverPoint0, originalChild); // swap the child back (so that the next swap will not affect the currently swapped node from parent1)
94        nodeQualities.Add(new Tuple<ISymbolicExpressionTreeNode, double>(node, quality));
95        node.Parent = parent; // restore correct parent
96      }
97
98      nodeQualities.Sort((a, b) => a.Item2.CompareTo(b.Item2)); // assuming this sorts the list in ascending order
99      selectedBranch = evaluator.Maximization ? nodeQualities.Last().Item1 : nodeQualities.First().Item1;
100
101
102      if (selectedBranch == null)
103        throw new Exception("Selected branch is null");
104
105      if (selectedBranch.Parent == null)
106        throw new Exception("Parent is null");
107
108
109      // swap the node that would create the best offspring
110      swap(crossoverPoint0, selectedBranch);
111
112      return parent0;
113    }
114
115    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
116      if (crossoverPoint.Child != null) {
117        // manipulate the tree of parent0 in place
118        // replace the branch in tree0 with the selected branch from tree1
119        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
120        if (selectedBranch != null) {
121          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
122        }
123      } else {
124        // child is null (additional child should be added under the parent)
125        if (selectedBranch != null) {
126          crossoverPoint.Parent.AddSubtree(selectedBranch);
127        }
128      }
129    }
130  }
131}
Note: See TracBrowser for help on using the repository browser.