#region License Information
/* HeuristicLab
* Copyright (C) 2002-2012 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.Common;
using HeuristicLab.Core;
using HeuristicLab.Data;
using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
using HeuristicLab.Operators;
using HeuristicLab.Optimization;
using HeuristicLab.Parameters;
using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
[Item("ReplaceBranchMultiMoveGenerator", "")]
[StorableClass]
public class ReplaceBranchMultiMoveGenerator : SingleSuccessorOperator, IStochasticOperator, ISymbolicExpressionTreeMoveOperator, IMultiMoveGenerator,
ISymbolicDataAnalysisInterpreterOperator, ISymbolicExpressionTreeGrammarBasedOperator, ISymbolicExpressionTreeSizeConstraintOperator {
public ILookupParameter RandomParameter {
get { return (ILookupParameter)Parameters["Random"]; }
}
public IValueLookupParameter SampleSizeParameter {
get { return (IValueLookupParameter)Parameters["SampleSize"]; }
}
public ILookupParameter SymbolicDataAnalysisTreeInterpreterParameter {
get { return (ILookupParameter)Parameters["Interpreter"]; }
}
public IValueLookupParameter SymbolicExpressionTreeGrammarParameter {
get { return (IValueLookupParameter)Parameters["Grammar"]; }
}
public ILookupParameter ProblemDataParameter {
get { return (ILookupParameter)Parameters["ProblemData"]; }
}
public IntValue SampleSize {
get { return SampleSizeParameter.Value; }
set { SampleSizeParameter.Value = value; }
}
public ILookupParameter SymbolicExpressionTreeParameter {
get { return (ILookupParameter)Parameters["SymbolicExpressionTree"]; }
}
public ILookupParameter ReplaceBranchMoveParameter {
get { return (LookupParameter)Parameters["ReplaceBranchMove"]; }
}
public IValueParameter ReplacementBranchesPoolSize {
get { return (IValueParameter)Parameters["ReplacementBranchesPoolSize"]; }
}
public IValueParameter MaxReplacementBranchLength {
get { return (IValueParameter)Parameters["MaxReplacementBranchLength"]; }
}
public IValueParameter MaxReplacementBranchDepth {
get { return (IValueParameter)Parameters["MaxReplacementBranchDepth"]; }
}
protected ScopeParameter CurrentScopeParameter {
get { return (ScopeParameter)Parameters["CurrentScope"]; }
}
public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
get { return (IValueLookupParameter)Parameters["MaximumSymbolicExpressionTreeDepth"]; }
}
public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
get { return (IValueLookupParameter)Parameters["MaximumSymbolicExpressionTreeLength"]; }
}
public IValueLookupParameter NeighbourhoodSizeParameter {
get { return (IValueLookupParameter)Parameters["NeighbourhoodSize"]; }
}
public IValueLookupParameter SemanticParameter {
get { return (IValueLookupParameter)Parameters["Semantic"]; }
}
public ILookupParameter> FragmentsParameter {
get { return (ILookupParameter>)Parameters["Fragments"]; }
}
public ILookupParameter> FragmentOutputsParameter {
get { return (ILookupParameter>)Parameters["FragmentOutputs"]; }
}
[StorableConstructor]
protected ReplaceBranchMultiMoveGenerator(bool deserializing) : base(deserializing) { }
protected ReplaceBranchMultiMoveGenerator(ReplaceBranchMultiMoveGenerator original, Cloner cloner) : base(original, cloner) { }
public ReplaceBranchMultiMoveGenerator()
: base() {
Parameters.Add(new LookupParameter("Random", "The random number generator."));
Parameters.Add(new ValueLookupParameter("SampleSize", "The number of moves to generate."));
Parameters.Add(new LookupParameter("SymbolicExpressionTree", "The symbolic expression tree for which moves should be generated."));
Parameters.Add(new LookupParameter("ReplaceBranchMove", "The moves that should be generated in subscopes."));
Parameters.Add(new ScopeParameter("CurrentScope", "The current scope where the moves should be added as subscopes."));
Parameters.Add(new ValueLookupParameter("Grammar"));
Parameters.Add(new LookupParameter("Interpreter"));
Parameters.Add(new LookupParameter("ProblemData"));
Parameters.Add(new ValueParameter("ReplacementBranchesPoolSize", new IntValue(10000)));
Parameters.Add(new ValueParameter("MaxReplacementBranchLength", new IntValue(8)));
Parameters.Add(new ValueParameter("MaxReplacementBranchDepth", new IntValue(4)));
Parameters.Add(new ValueLookupParameter("MaximumSymbolicExpressionTreeDepth"));
Parameters.Add(new ValueLookupParameter("MaximumSymbolicExpressionTreeLength"));
Parameters.Add(new ValueLookupParameter("NeighbourhoodSize", new IntValue(5)));
Parameters.Add(new ValueLookupParameter("Semantic", new BoolValue()));
Parameters.Add(new LookupParameter>("Fragments"));
Parameters.Add(new LookupParameter>("FragmentOutputs"));
}
[StorableHook(HookType.AfterDeserialization)]
private void AfterDeserialization() {
if (!Parameters.ContainsKey("MaximumSymbolicExpressionTreeDepth")) {
Parameters.Add(new ValueLookupParameter("MaximumSymbolicExpressionTreeDepth"));
Parameters.Add(new ValueLookupParameter("MaximumSymbolicExpressionTreeLength"));
}
if (!Parameters.ContainsKey("NeighbourhoodSize")) {
Parameters.Add(new ValueLookupParameter("NeighbourhoodSize", new IntValue(5)));
}
}
public override IDeepCloneable Clone(Cloner cloner) {
return new ReplaceBranchMultiMoveGenerator(this, cloner);
}
public override IOperation Apply() {
var random = RandomParameter.ActualValue;
if (FragmentsParameter.ActualValue == null || FragmentOutputsParameter.ActualValue == null) {
InitializeOperator();
}
var tree = SymbolicExpressionTreeParameter.ActualValue;
string moveParameterName = ReplaceBranchMoveParameter.ActualName;
var moveScopes = new List();
int n = SampleSizeParameter.ActualValue.Value;
var moves = GenerateMoves(tree, random, n);
foreach (var m in moves) {
var moveScope = new Scope(moveScopes.Count.ToString());
moveScope.Variables.Add(new HeuristicLab.Core.Variable(moveParameterName, m));
moveScopes.Add(moveScope);
}
CurrentScopeParameter.ActualValue.SubScopes.AddRange(moveScopes);
return base.Apply();
}
public IEnumerable GenerateMoves(ISymbolicExpressionTree tree, IRandom random, int n) {
int maxDepth = MaximumSymbolicExpressionTreeDepthParameter.ActualValue.Value;
int maxLength = MaximumSymbolicExpressionTreeLengthParameter.ActualValue.Value;
var possibleInternalChildren = (from parent in tree.Root.GetSubtree(0).IterateNodesPrefix()
from i in Enumerable.Range(0, parent.SubtreeCount)
let currentChild = parent.GetSubtree(i)
where currentChild.SubtreeCount > 0
where tree.Root.GetBranchLevel(currentChild) < maxDepth + 2
where tree.Length - currentChild.GetLength() < maxLength
select new CutPoint(parent, i)).ToArray();
var possibleLeaveChildren = (from parent in tree.Root.GetSubtree(0).IterateNodesPrefix()
from i in Enumerable.Range(0, parent.SubtreeCount)
let currentChild = parent.GetSubtree(i)
where currentChild.SubtreeCount == 0
where tree.Root.GetBranchLevel(currentChild) < maxDepth + 2
where tree.Length - 1 < maxLength
select new CutPoint(parent, i)).ToArray();
if (possibleInternalChildren.Length == 0) possibleInternalChildren = possibleLeaveChildren;
if (possibleLeaveChildren.Length == 0) possibleLeaveChildren = possibleInternalChildren;
var root = (new ProgramRootSymbol()).CreateTreeNode();
var start = (new StartSymbol()).CreateTreeNode();
root.AddSubtree(start);
var t = new SymbolicExpressionTree(root);
var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
var ds = ProblemDataParameter.ActualValue.Dataset;
var rows = ProblemDataParameter.ActualValue.TrainingIndices;
bool semantic = SemanticParameter.ActualValue.Value;
int maxNeighbours = NeighbourhoodSizeParameter.ActualValue.Value;
var count = 0;
while (count < n) {
// select a random replacement point
CutPoint[] possibleChildren;
if (random.NextDouble() < 0.9)
possibleChildren = possibleInternalChildren;
else possibleChildren = possibleLeaveChildren;
var selected = possibleChildren[random.Next(possibleChildren.Length)];
// evaluate
start.AddSubtree(selected.Parent.GetSubtree(selected.ChildIndex));
var output = interpreter.GetSymbolicExpressionTreeValues(t, ds, rows).ToArray();
start.RemoveSubtree(0);
if (semantic) {
foreach (var m in FindMostSimilarFragments(tree, maxLength, maxDepth, selected, random, maxNeighbours, output)) {
yield return m;
count++;
}
} else {
foreach (var m in FindRandomFragments(tree, maxLength, maxDepth, selected, random, maxNeighbours, output)) {
yield return m;
count++;
}
}
}
}
private IEnumerable FindRandomFragments(ISymbolicExpressionTree tree, int maxLength, int maxDepth, CutPoint selected,
IRandom random, int maxNeighbours, double[] output) {
var selectedFragments = new List(maxNeighbours);
int treeLength = tree.Length;
int removedFragementLength = selected.Parent.GetSubtree(selected.ChildIndex).GetLength();
int parentBranchLevel = tree.Root.GetBranchLevel(selected.Parent);
int iterations = 0;
int maxIterations = maxNeighbours + 100;
var fragments = FragmentsParameter.ActualValue;
var fragmentOutput = FragmentOutputsParameter.ActualValue;
// select random fragments
while (selectedFragments.Count < maxNeighbours && iterations++ < maxIterations) {
int r = random.Next(fragments.Count);
var selectedFragment = fragments[r];
var selectedFragmentOutput = fragmentOutput[r];
// if the branch is allowed in the selected point
if (treeLength - removedFragementLength + selectedFragment.Length <= maxLength + 4 &&
parentBranchLevel + selectedFragment.Depth - 2 <= maxDepth + 2 &&
tree.Root.Grammar.IsAllowedChildSymbol(selected.Parent.Symbol, selectedFragment.Root.GetSubtree(0).GetSubtree(0).Symbol, selected.ChildIndex)) {
selectedFragments.Add(r);
}
}
// yield moves (we need to add linear scaling parameters for the inserted tree)
return selectedFragments
.Select(i => new ReplaceBranchMove(tree, selected.Parent, selected.ChildIndex, fragments[i].Root.GetSubtree(0).GetSubtree(0), output, fragmentOutput[i].ToArray(), i));
}
private IEnumerable FindMostSimilarFragments(ISymbolicExpressionTree tree, int maxLength, int maxDepth, CutPoint selected,
IRandom random, int maxNeighbours, double[] output) {
var fragments = FragmentsParameter.ActualValue;
var fragmentOutput = FragmentOutputsParameter.ActualValue;
var bestTrees = new SortedList>(fragments.Count);
int treeLength = tree.Length;
int removedFragementLength = selected.Parent.GetSubtree(selected.ChildIndex).GetLength();
int parentBranchLevel = tree.Root.GetBranchLevel(selected.Parent);
// iterate over the whole pool of branches for replacement
for (int i = 0; i < fragments.Count; i++) {
// if the branch is allowed in the selected point
if (treeLength - removedFragementLength + fragments[i].Length <= maxLength + 4 &&
parentBranchLevel + fragments[i].Depth - 2 <= maxDepth + 2 &&
tree.Root.Grammar.IsAllowedChildSymbol(selected.Parent.Symbol, fragments[i].Root.GetSubtree(0).GetSubtree(0).Symbol, selected.ChildIndex)) {
OnlineCalculatorError error;
// calculate the similarity
double similarity = OnlinePearsonsRSquaredCalculator.Calculate(output, fragmentOutput[i], out error);
similarity = Math.Round(similarity, 5);
if (error != OnlineCalculatorError.None) similarity = 0.0;
// if we found a new bestSimilarity then keep the replacement branch in a sorted list (keep maximally the n best for this replacement point)
if (similarity < 1 && ((bestTrees.Count < maxNeighbours) || similarity > bestTrees.ElementAt(0).Key)) {
if (!bestTrees.ContainsKey(similarity)) {
var l = new List();
bestTrees.Add(similarity, l);
}
bestTrees[similarity].Add(i);
if (bestTrees.Count > maxNeighbours) bestTrees.RemoveAt(0);
}
}
}
int c = 0;
// yield moves (we need to add linear scaling parameters for the inserted tree)
while (c < maxNeighbours) {
var l = bestTrees.ElementAt(c % bestTrees.Count).Value;
var index = l[random.Next(l.Count)];
yield return
new ReplaceBranchMove(tree, selected.Parent, selected.ChildIndex, fragments[index].Root.GetSubtree(0).GetSubtree(0),
output, fragmentOutput[index].ToArray(), index);
c++;
}
}
private void InitializeOperator() {
// init locally and set only at the end in case of exceptions
var trees = new List();
var treeOutput = new List();
var random = RandomParameter.ActualValue;
var g = SymbolicExpressionTreeGrammarParameter.ActualValue;
var constSym = g.Symbols.Single(s => s is Constant);
// temporarily disable constants
double oldConstFreq = constSym.InitialFrequency;
constSym.InitialFrequency = 0.0;
var interpreter = SymbolicDataAnalysisTreeInterpreterParameter.ActualValue;
var ds = ProblemDataParameter.ActualValue.Dataset;
var rows = ProblemDataParameter.ActualValue.TrainingIndices;
// create pool of random branches for replacement (no constants)
// and evaluate the output
// only keep fragments if the output does not contain invalid values
var n = ReplacementBranchesPoolSize.Value.Value;
while (trees.Count < n) {
var t = ProbabilisticTreeCreator.Create(random, g, MaxReplacementBranchLength.Value.Value, MaxReplacementBranchDepth.Value.Value);
var output = interpreter.GetSymbolicExpressionTreeValues(t, ds, rows);
if (!output.Any(x => double.IsInfinity(x) || double.IsNaN(x))) {
trees.Add(t);
treeOutput.Add(output.ToArray());
}
}
// enable constants again
constSym.InitialFrequency = oldConstFreq;
// set parameters
FragmentsParameter.ActualValue = new ItemList(trees);
FragmentOutputsParameter.ActualValue = new ItemList(treeOutput.Select(a => new DoubleArray(a)));
}
}
}