#region License Information /* HeuristicLab * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Generic; using System.Linq; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding; namespace HeuristicLab.Problems.DataAnalysis.Symbolic { [Item("ProbabilisticFunctionalCrossover", "An operator which performs subtree swapping based on the behavioral similarity between subtrees.")] public sealed class SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover : SymbolicDataAnalysisExpressionCrossover where T : class, IDataAnalysisProblemData { [StorableConstructor] private SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover(bool deserializing) : base(deserializing) { } private SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover(SymbolicDataAnalysisExpressionCrossover original, Cloner cloner) : base(original, cloner) { } public SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover() : base() { Name = "ProbabilisticFunctionalCrossover"; } public override IDeepCloneable Clone(Cloner cloner) { return new SymbolicDataAnalysisExpressionProbabilisticFunctionalCrossover(this, cloner); } protected override ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) { ISymbolicDataAnalysisExpressionTreeInterpreter interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue; List rows = GenerateRowsToEvaluate().ToList(); T problemData = ProblemDataParameter.ActualValue; return Cross(random, parent0, parent1, interpreter, problemData, rows, MaximumSymbolicExpressionTreeDepth.Value, MaximumSymbolicExpressionTreeLength.Value); } public override ISymbolicExpressionTree Crossover(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1) { return Cross(random, parent0, parent1); } /// /// Takes two parent individuals P0 and P1. /// 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: /// d(i,j) = 0.5 * ( abs(max(i) - max(j)) + abs(min(i) - min(j)) ). /// Next, assign probabilities for the selection of the second cross point based on the inversed and normalized behavioral distance and /// choose the second crosspoint via a random weighted selection procedure. /// public static ISymbolicExpressionTree Cross(IRandom random, ISymbolicExpressionTree parent0, ISymbolicExpressionTree parent1, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter, T problemData, IList rows, int maxDepth, int maxLength) { var crossoverPoints0 = new List(); parent0.Root.ForEachNodePostfix((n) => { if (n.Subtrees.Any() && n != parent0.Root) foreach (var child in n.Subtrees) crossoverPoints0.Add(new CutPoint(n, child)); }); var crossoverPoint0 = crossoverPoints0.SelectRandom(random); int level = parent0.Root.GetBranchLevel(crossoverPoint0.Child); int length = parent0.Root.GetLength() - crossoverPoint0.Child.GetLength(); var allowedBranches = new List(); parent1.Root.ForEachNodePostfix((n) => { if (n.Subtrees.Any() && n != parent1.Root) allowedBranches.AddRange(n.Subtrees.Where(s => crossoverPoint0.IsMatchingPointType(s) && s.GetDepth() + level <= maxDepth && s.GetLength() + length <= maxLength)); }); if (allowedBranches.Count == 0) return parent0; var dataset = problemData.Dataset; // create symbols in order to improvize an ad-hoc tree so that the child can be evaluated var rootSymbol = new ProgramRootSymbol(); var startSymbol = new StartSymbol(); var tree0 = CreateTreeFromNode(random, crossoverPoint0.Child, rootSymbol, startSymbol); // this will change crossoverPoint0.Child.Parent List estimatedValues0 = interpreter.GetSymbolicExpressionTreeValues(tree0, dataset, rows).ToList(); double min0 = estimatedValues0.Min(); double max0 = estimatedValues0.Max(); crossoverPoint0.Child.Parent = crossoverPoint0.Parent; // restore correct parent var weights = new List(); foreach (var node in allowedBranches) { var parent = node.Parent; var tree1 = CreateTreeFromNode(random, node, rootSymbol, startSymbol); List estimatedValues1 = interpreter.GetSymbolicExpressionTreeValues(tree1, dataset, rows).ToList(); double min1 = estimatedValues1.Min(); double max1 = estimatedValues1.Max(); 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 weights.Add(behavioralDistance); node.Parent = parent; // restore correct node parent } // remove branches with an infinite or NaN behavioral distance int count = weights.Count, idx = 0; while (idx < count) { if (Double.IsNaN(weights[idx]) || Double.IsInfinity(weights[idx])) { weights.RemoveAt(idx); allowedBranches.RemoveAt(idx); --count; } else { ++idx; } } // check if there are any allowed branches left if (allowedBranches.Count == 0) return parent0; ISymbolicExpressionTreeNode selectedBranch; double sum = weights.Sum(); if (sum == 0.0) selectedBranch = allowedBranches[0]; // just return the first, since we don't care (all weights are zero) else { // transform similarity distances into probabilities by normalizing and inverting the values for (int i = 0; i != weights.Count; ++i) weights[i] = (1 - weights[i] / sum); //selectedBranch = allowedBranches.SelectRandom(weights, random); selectedBranch = SelectRandomBranch(random, allowedBranches, weights); } swap(crossoverPoint0, selectedBranch); return parent0; } private static void swap(CutPoint crossoverPoint, ISymbolicExpressionTreeNode selectedBranch) { if (crossoverPoint.Child != null) { // manipulate the tree of parent0 in place // replace the branch in tree0 with the selected branch from tree1 crossoverPoint.Parent.RemoveSubtree(crossoverPoint.ChildIndex); if (selectedBranch != null) { crossoverPoint.Parent.InsertSubtree(crossoverPoint.ChildIndex, selectedBranch); } } else { // child is null (additional child should be added under the parent) if (selectedBranch != null) { crossoverPoint.Parent.AddSubtree(selectedBranch); } } } private static ISymbolicExpressionTreeNode SelectRandomBranch(IRandom random, IList nodes, IList weights) { double r = weights.Sum() * random.NextDouble(); for (int i = 0; i != nodes.Count; ++i) { if (r < weights[i]) return nodes[i]; r -= weights[i]; } return nodes.Last(); } } }