#region License Information
/* HeuristicLab
* Copyright (C) 2002-2013 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.Collections.Generic;
using System.Linq;
using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
using HeuristicLab.Problems.DataAnalysis.Transformations;
namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
public class SymbolicExpressionTreeBacktransformator : IModelBacktransformator {
private readonly ITransformationMapper transformationMapper;
public SymbolicExpressionTreeBacktransformator(ITransformationMapper transformationMapper) {
this.transformationMapper = transformationMapper;
}
public void Backtransform(IDataAnalysisModel model, IEnumerable transformations) {
var symbolicModel = (ISymbolicDataAnalysisModel)model;
foreach (var transformation in transformations) {
ApplyBacktransformation(transformation, symbolicModel.SymbolicExpressionTree);
}
}
private void ApplyBacktransformation(ITransformation transformation, ISymbolicExpressionTree symbolicExpressionTree) {
var variableNodes = symbolicExpressionTree.IterateNodesBreadth()
.Where(n => IsVariableNode(n, transformation.Column));
var transformationTree = transformationMapper.GenerateModel(transformation);
foreach (var variableNode in variableNodes) {
SwapTransformationTree(transformationTree, variableNode);
}
}
private void SwapTransformationTree(ISymbolicExpressionTreeNode transformationTreeNode, ISymbolicExpressionTreeNode targetNode) {
var parent = targetNode.Parent;
int index = parent.IndexOfSubtree(targetNode);
parent.RemoveSubtree(index);
parent.InsertSubtree(index, transformationTreeNode);
}
private bool IsVariableNode(ISymbolicExpressionTreeNode node, string variableName) {
var variableNode = node as VariableTreeNode;
if (variableNode == null) return false;
return variableNode.VariableName == variableName;
}
}
}