Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1682: Implemented the ProbabilisticFunctionalCrossover.

File size: 8.0 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("ProbabilisticFunctionalCrossover", "An operator which performs subtree swapping based on behavioral similarity")]
35  public sealed class SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
36    [StorableConstructor]
37    private SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover(bool deserializing) : base(deserializing) { }
38    private SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover(SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover<T> original, Cloner cloner)
39      : base(original, cloner) { }
40    public SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover() : base() { }
41    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover<T>(this, cloner); }
42
43    protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
44      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
45      IEnumerable<int> rows = GenerateRowsToEvaluate();
46      T problemData = ProblemDataParameter.ActualValue;
47      var grammar = parent0.Root.Grammar;
48      return Cross(random, parent0, parent1, interpreter, problemData,
49                   rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value);
50    }
51
52    /// <summary>
53    /// Takes two parent individuals P0 and P1.
54    /// Randomly choose a node i from the first parent, then for each matching node j from the second parent, calculate the behavioral distance based on the range:
55    /// d(i,j) = 0.5 * ( abs(max(i) - max(j)) + abs(min(i) - min(j)) ).
56    /// Next, assign probabilities for the selection of the second cross point based on the inversed and normalized behavioral distance and
57    /// choose the second crosspoint via a random weighted selection procedure.
58    /// </summary>
59    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
60                                                ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, T problemData, IEnumerable<int> rows, int maxDepth, int maxLength) {
61      var crossoverPoints0 = new List<CutPoint>();
62      parent0.Root.ForEachNodePostfix((n) => {
63        if (n.Subtrees.Any() && n != parent0.Root)
64          foreach (var child in n.Subtrees)
65            crossoverPoints0.Add(new CutPoint(n, child));
66      });
67      var crossoverPoint0 = crossoverPoints0[random.Next(crossoverPoints0.Count)];
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          foreach (var child in n.Subtrees)
75            if (crossoverPoint0.IsMatchingPointType(child) && (child.GetDepth() + level <= maxDepth) && (child.GetLength() + length <= maxLength))
76              allowedBranches.Add(child);
77      });
78
79      // check if empty branch is allowed
80      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
81
82      if (allowedBranches.Count == 0)
83        return parent0;
84
85      var dataset = problemData.Dataset;
86
87      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
88      var rootSymbol = new ProgramRootSymbol();
89      var startSymbol = new StartSymbol();
90      var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol); // this will change crossoverPoint0.Child.Parent
91      IEnumerable<double> estimatedValues0 = interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows);
92      double min0 = estimatedValues0.Min();
93      double max0 = estimatedValues0.Max();
94      crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore correct parent
95
96      var weights = new List<double>();
97      foreach (var node in allowedBranches) {
98        var parent = node.Parent;
99        var tree1 = CreateTreeFromNode(random, node, rootSymbol, startSymbol);
100        IEnumerable<double> estimatedValues1 = interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows);
101        double min1 = estimatedValues1.Min();
102        double max1 = estimatedValues1.Max();
103        double behavioralDistance = (Math.Abs(min0 - min1) + Math.Abs(max0 - max1)) / 2; // this can be NaN of Infinity because some trees are crazy like exp(exp(exp(...))), we correct that below
104        weights.Add(behavioralDistance);
105        node.Parent = parent; // restore correct node parent
106      }
107
108      // remove branches with an infinite or NaN behavioral distance
109      for (int i = 0; i != weights.Count; ++i)
110        if (Double.IsNaN(weights[i]) || Double.IsInfinity(weights[i])) {
111          weights.RemoveAt(i);
112          allowedBranches.RemoveAt(i);
113        }
114
115      // check if there are any allowed branches left
116      if (allowedBranches.Count == 0)
117        return parent0;
118
119      ISymbolicExpressionTreeNode selectedBranch;
120      double sum = weights.Sum();
121      if (sum == 0.0)
122        selectedBranch = allowedBranches[0]; // just return the first, since we don't care (all weights are zero)
123      else {
124        // transform similarity distances into probabilities by normalizing and inverting the values
125        for (int i = 0; i != weights.Count; ++i)
126          weights[i] = (1 - weights[i] / sum);
127
128        selectedBranch = SelectRandomBranch(random, allowedBranches, weights);
129      }
130      swap(crossoverPoint0, selectedBranch);
131      return parent0;
132    }
133
134    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
135      if (crossoverPoint.Child != null) {
136        // manipulate the tree of parent0 in place
137        // replace the branch in tree0 with the selected branch from tree1
138        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
139        if (selectedBranch != null) {
140          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
141        }
142      } else {
143        // child is null (additional child should be added under the parent)
144        if (selectedBranch != null) {
145          crossoverPoint.Parent.AddSubtree(selectedBranch);
146        }
147      }
148    }
149
150    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, List<ISymbolicExpressionTreeNode> nodes, List<double> weights) {
151      double r = weights.Sum() * random.NextDouble();
152      for (int i = 0; i != nodes.Count; ++i) {
153        if (r < weights[i])
154          return nodes[i];
155        r -= weights[i];
156      }
157      return nodes.Last();
158    }
159  }
160}
Note: See TracBrowser for help on using the repository browser.