Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1683: Implemented the SemanticSimilarityCrossover.

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.Parameters;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28using HeuristicLab.Common;
29using HeuristicLab.Core;
30using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
31using HeuristicLab.Data;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
34
35  [Item("SemanticSimilarityCrossover", "An operator which performs subtree swapping based on semantic similarity.")]
36  public sealed class SymbolicDataAnalysisExpressionSemanticSimilarityCrossover<T> : SymbolicDataAnalysisExpressionCrossover<T> where T : class, IDataAnalysisProblemData {
37    private const string SemanticSimilarityLowerBoundParameterName = "SemanticSimilarityLowerBound";
38    private const string SemanticSimilarityUpperBoundParameterName = "SemanticSimilarityUpperBound";
39
40    #region Parameter properties
41    public IValueParameter<DoubleValue> SemanticSimilarityLowerBoundParameter {
42      get { return (IValueParameter<DoubleValue>)Parameters[SemanticSimilarityLowerBoundParameterName]; }
43    }
44    public IValueParameter<DoubleValue> SemanticSimilarityUpperBoundParameter {
45      get { return (IValueParameter<DoubleValue>)Parameters[SemanticSimilarityUpperBoundParameterName]; }
46    }
47    #endregion
48
49    #region Properties
50    public DoubleValue SemanticSimilarityLowerBound {
51      get { return SemanticSimilarityLowerBoundParameter.Value; }
52    }
53    public DoubleValue SemanticSimilarityUpperBound {
54      get { return SemanticSimilarityUpperBoundParameter.Value; }
55    }
56    #endregion
57
58    [StorableConstructor]
59    private SymbolicDataAnalysisExpressionSemanticSimilarityCrossover(bool deserializing) : base(deserializing) { }
60    private SymbolicDataAnalysisExpressionSemanticSimilarityCrossover(SymbolicDataAnalysisExpressionSemanticSimilarityCrossover<T> original, Cloner cloner) : base(original, cloner) { }
61    public SymbolicDataAnalysisExpressionSemanticSimilarityCrossover()
62      : base() {
63      Parameters.Add(new ValueLookupParameter<DoubleValue>(SemanticSimilarityLowerBoundParameterName, "The lower bound of the semantic similarity interval."));
64      Parameters.Add(new ValueLookupParameter<DoubleValue>(SemanticSimilarityUpperBoundParameterName, "The lower bound of the semantic similarity interval."));
65
66      // Set some decent default values for the lower and upper bound parameters
67      SemanticSimilarityLowerBoundParameter.Value = new DoubleValue(0.0001);
68      SemanticSimilarityUpperBoundParameter.Value = new DoubleValue(10);
69    }
70    public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionSemanticSimilarityCrossover<T>(this, cloner); }
71
72    protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) {
73      ISymbolicDataAnalysisExpressionTreeInterpreter interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
74      IEnumerable<int> rows = GenerateRowsToEvaluate();
75      T problemData = ProblemDataParameter.ActualValue;
76      return Cross(random, parent0, parent1, interpreter, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value, SemanticSimilarityLowerBoundParameter.Value.Value, SemanticSimilarityUpperBoundParameter.Value.Value);
77    }
78    /// <summary>
79    /// Takes two parent individuals P0 and P1.
80    /// Randomly choose a node i from the first parent, then get a node j from the second parent that matches the semantic similarity criteria.
81    /// </summary>
82    public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1,
83                                                ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, T problemData, IEnumerable<int> rows, int maxDepth, int maxLength, double lower, double upper) {
84      var crossoverPoints0 = new List<CutPoint>();
85      parent0.Root.ForEachNodePostfix((n) => {
86        if (n.Subtrees.Any() && n != parent0.Root)
87          foreach (var child in n.Subtrees)
88            crossoverPoints0.Add(new CutPoint(n, child));
89      });
90      var crossoverPoint0 = crossoverPoints0[random.Next(crossoverPoints0.Count)];
91      int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child);
92      int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength();
93
94      var allowedBranches = new List<ISymbolicExpressionTreeNode>();
95      parent1.Root.ForEachNodePostfix((n) => {
96        if (n.Subtrees.Any() && n != parent1.Root)
97          foreach (var child in n.Subtrees)
98            if (crossoverPoint0.IsMatchingPointType(child) && (child.GetDepth() + level <= maxDepth) && (child.GetLength() + length <= maxLength))
99              allowedBranches.Add(child);
100      });
101
102      // check if empty branch is allowed
103      if (crossoverPoint0.IsMatchingPointType(null)) allowedBranches.Add(null);
104
105      if (allowedBranches.Count == 0)
106        return parent0;
107
108      var dataset = problemData.Dataset;
109
110      // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated
111      var rootSymbol = new ProgramRootSymbol();
112      var startSymbol = new StartSymbol();
113      var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol);
114      IEnumerable<double> estimatedValues0 = interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows);
115      crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore parent
116      ISymbolicExpressionTreeNode selectedBranch = null;
117
118      // pick the first node that fulfills the semantic similarity conditions
119      foreach (var node in allowedBranches) {
120        var parent = node.Parent;
121        var tree1 = CreateTreeFromNode(random, node, startSymbol, rootSymbol); // this will affect node.Parent
122        IEnumerable<double> estimatedValues1 = interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows);
123        node.Parent = parent; // restore parent
124
125        OnlineCalculatorError errorState;
126        double ssd = OnlineMeanAbsoluteErrorCalculator.Calculate(estimatedValues0, estimatedValues1, out errorState);
127
128        if (lower < ssd && ssd < upper) {
129          selectedBranch = node;
130          break;
131        }
132      }
133
134      if (selectedBranch == null)
135        return parent0;
136
137      // perform the actual swap
138      swap(crossoverPoint0, selectedBranch);
139
140      return parent0;
141    }
142
143    private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) {
144      // perform the actual swap
145      if (crossoverPoint.Child != null) {
146        // manipulate the tree of parent0 in place
147        // replace the branch in tree0 with the selected branch from tree1
148        crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex);
149        if (selectedBranch != null) {
150          crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch);
151        }
152      } else {
153        // child is null (additional child should be added under the parent)
154        if (selectedBranch != null) {
155          crossoverPoint.Parent.AddSubtree(selectedBranch);
156        }
157      }
158    }
159
160  }
161}
Note: See TracBrowser for help on using the repository browser.