Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1682: Implemented the MultiSymbolicDataAnalysisExpressionTreeCrossover

File size: 8.2 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 the behavioral similarity between subtrees.")]
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    public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
53      return Cross(random, parent0, parent1);
54    }
55
56    /// <summary>
57    /// Takes two parent individuals P0 and P1.
58    /// 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:
59    /// d(i,j) = 0.5 * ( abs(max(i) - max(j)) + abs(min(i) - min(j)) ).
60    /// Next, assign probabilities for the selection of the second cross point based on the inversed and normalized behavioral distance and
61    /// choose the second crosspoint via a random weighted selection procedure.
62    /// </summary>
63    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
64                                                ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, T problemData, IEnumerable<int> rows, int maxDepth, int maxLength) {
65      var crossoverPoints0 = new List<CutPoint>();
66      parent0.Root.ForEachNodePostfix((n) => {
67        if (n.Subtrees.Any() && n != parent0.Root)
68          foreach (var child in n.Subtrees)
69            crossoverPoints0.Add(new CutPoint(n, child));
70      });
71      var crossoverPoint0 = crossoverPoints0[random.Next(crossoverPoints0.Count)];
72      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
73      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
74
75      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
76      parent1.Root.ForEachNodePostfix((n) => {
77        if (n.Subtrees.Any() && n != parent1.Root)
78          foreach (var child in n.Subtrees)
79            if (crossoverPoint0.IsMatchingPointType(child) && (child.GetDepth() + level <= maxDepth) && (child.GetLength() + length <= maxLength))
80              allowedBranches.Add(child);
81      });
82
83      // check if empty branch is allowed
84      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
85
86      if (allowedBranches.Count == 0)
87        return parent0;
88
89      var dataset = problemData.Dataset;
90
91      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
92      var rootSymbol = new ProgramRootSymbol();
93      var startSymbol = new StartSymbol();
94      var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol); // this will change crossoverPoint0.Child.Parent
95      IEnumerable<double> estimatedValues0 = interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows);
96      double min0 = estimatedValues0.Min();
97      double max0 = estimatedValues0.Max();
98      crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore correct parent
99
100      var weights = new List<double>();
101      foreach (var node in allowedBranches) {
102        var parent = node.Parent;
103        var tree1 = CreateTreeFromNode(random, node, rootSymbol, startSymbol);
104        IEnumerable<double> estimatedValues1 = interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows);
105        double min1 = estimatedValues1.Min();
106        double max1 = estimatedValues1.Max();
107        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
108        weights.Add(behavioralDistance);
109        node.Parent = parent; // restore correct node parent
110      }
111
112      // remove branches with an infinite or NaN behavioral distance
113      for (int i = 0; i != weights.Count; ++i)
114        if (Double.IsNaN(weights[i]) || Double.IsInfinity(weights[i])) {
115          weights.RemoveAt(i);
116          allowedBranches.RemoveAt(i);
117        }
118
119      // check if there are any allowed branches left
120      if (allowedBranches.Count == 0)
121        return parent0;
122
123      ISymbolicExpressionTreeNode selectedBranch;
124      double sum = weights.Sum();
125      if (sum == 0.0)
126        selectedBranch = allowedBranches[0]; // just return the first, since we don't care (all weights are zero)
127      else {
128        // transform similarity distances into probabilities by normalizing and inverting the values
129        for (int i = 0; i != weights.Count; ++i)
130          weights[i] = (1 - weights[i] / sum);
131
132        selectedBranch = SelectRandomBranch(random, allowedBranches, weights);
133      }
134      swap(crossoverPoint0, selectedBranch);
135      return parent0;
136    }
137
138    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
139      if (crossoverPoint.Child != null) {
140        // manipulate the tree of parent0 in place
141        // replace the branch in tree0 with the selected branch from tree1
142        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
143        if (selectedBranch != null) {
144          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
145        }
146      } else {
147        // child is null (additional child should be added under the parent)
148        if (selectedBranch != null) {
149          crossoverPoint.Parent.AddSubtree(selectedBranch);
150        }
151      }
152    }
153
154    private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, List<ISymbolicExpressionTreeNode> nodes, List<double> weights) {
155      double r = weights.Sum() * random.NextDouble();
156      for (int i = 0; i != nodes.Count; ++i) {
157        if (r < weights[i])
158          return nodes[i];
159        r -= weights[i];
160      }
161      return nodes.Last();
162    }
163  }
164}
Note: See TracBrowser for help on using the repository browser.