Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.GP.StructureIdentification.Networks/3.2/NetworkToFunctionTransformer.cs @ 2633

Last change on this file since 2633 was 2633, checked in by gkronber, 14 years ago

Fixed test-cases for constant expressions and expressions of one argument and fixed a bug in the network transformation operator. #833

File size: 17.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2008 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.Core;
27using HeuristicLab.Data;
28using HeuristicLab.GP.Interfaces;
29using HeuristicLab.Modeling;
30using HeuristicLab.DataAnalysis;
31using System.Diagnostics;
32
33namespace HeuristicLab.GP.StructureIdentification.Networks {
34  public class NetworkToFunctionTransformer : OperatorBase {
35    public NetworkToFunctionTransformer()
36      : base() {
37      AddVariableInfo(new VariableInfo("Network", "The network (open expression)", typeof(IGeneticProgrammingModel), VariableKind.In));
38      AddVariableInfo(new VariableInfo("TargetVariables", "Name of the target variables", typeof(ItemList<StringData>), VariableKind.In));
39      AddVariableInfo(new VariableInfo("FunctionTree", "The function tree with all targetvaribales", typeof(IGeneticProgrammingModel), VariableKind.New));
40    }
41
42    public override string Description {
43      get { return "Extracts the network (function tree with unbound parameters) and creates a closed form function tree for each target variable."; }
44    }
45
46    public override IOperation Apply(IScope scope) {
47      IGeneticProgrammingModel model = GetVariableValue<IGeneticProgrammingModel>("Network", scope, true);
48      ItemList<StringData> targetVariables = GetVariableValue<ItemList<StringData>>("TargetVariables", scope, true);
49      // clear old sub-scopes
50      while (scope.SubScopes.Count > 0) scope.RemoveSubScope(scope.SubScopes[0]);
51
52      var targetVariableEnumerator = targetVariables.Select(x => x.Data).GetEnumerator();
53      // create a new sub-scope for each target variable with the transformed expression
54      foreach (IFunctionTree transformedTree in Transform(model.FunctionTree, targetVariables.Select(x => x.Data))) {
55        targetVariableEnumerator.MoveNext();
56        Scope exprScope = new Scope();
57        scope.AddSubScope(exprScope);
58        exprScope.AddVariable(new HeuristicLab.Core.Variable(scope.TranslateName("FunctionTree"), new GeneticProgrammingModel(transformedTree)));
59        exprScope.AddVariable(new HeuristicLab.Core.Variable(scope.TranslateName("TargetVariable"), new StringData(targetVariableEnumerator.Current)));
60        Debug.Assert(!(transformedTree is VariableFunctionTree) || ((VariableFunctionTree)transformedTree).VariableName != targetVariableEnumerator.Current);
61      }
62
63      return null;
64    }
65
66    private static IEnumerable<IFunctionTree> Transform(IFunctionTree networkDescription, IEnumerable<string> targetVariables) {
67      // bind open parameters of network to target variables
68      //IFunctionTree openExpression = RemoveOpenParameters(networkDescription);
69      IFunctionTree paritallyEvaluatedOpenExpression = ApplyMetaFunctions((IFunctionTree)networkDescription.Clone());
70      IFunctionTree boundExpression = BindVariables(paritallyEvaluatedOpenExpression, targetVariables.GetEnumerator());
71
72      // create a new sub-scope for each target variable with the transformed expression
73      foreach (var targetVariable in targetVariables) {
74        yield return TransformExpression(boundExpression, targetVariable, targetVariables.Except(new string[] { targetVariable }));
75      }
76    }
77
78    /// <summary>
79    /// applies all tree-transforming meta functions (= cycle and flip)
80    /// precondition: root is a F2 function (possibly cycle) and the tree contains 0 or n flip functions, each branch has an openparameter symbol in the bottom left
81    /// postconditon: root is any F2 function (but cycle) and the tree doesn't contains any flips, each branch has an openparameter symbol in the bottom left
82    /// </summary>
83    /// <param name="tree"></param>
84    /// <returns></returns>
85    private static IFunctionTree ApplyMetaFunctions(IFunctionTree tree) {
86      return ApplyFlips(ApplyCycles(tree));
87    }
88
89    private static IFunctionTree ApplyFlips(IFunctionTree tree) {
90      if (tree.SubTrees.Count == 0) {
91        return tree;
92      } else if (tree.Function is Flip) {
93        var partiallyAppliedBranch = ApplyFlips(tree.SubTrees[0]);
94        if (partiallyAppliedBranch.Function is OpenParameter) return partiallyAppliedBranch;
95        else return InvertChain(partiallyAppliedBranch);
96      } else {
97        List<IFunctionTree> subTrees = new List<IFunctionTree>(tree.SubTrees);
98        while (tree.SubTrees.Count > 0) tree.RemoveSubTree(0);
99        foreach (var subTree in subTrees) {
100          tree.AddSubTree(ApplyFlips(subTree));
101        }
102        return tree;
103      }
104    }
105
106    /// <summary>
107    ///  inverts and reverses chain of functions.
108    ///  precondition: tree is any F1 non-terminal that ends with an openParameter
109    ///  postcondition: tree is inverted and reversed chain of F1 non-terminals and ends with an openparameter.
110    /// </summary>
111    /// <param name="tree"></param>
112    /// <returns></returns>
113    private static IFunctionTree InvertChain(IFunctionTree tree) {
114      List<IFunctionTree> currentChain = new List<IFunctionTree>(IterateChain(tree));
115      // get a list of function trees from bottom to top
116      List<IFunctionTree> reversedChain = new List<IFunctionTree>(currentChain.Reverse<IFunctionTree>().Skip(1));
117      IFunctionTree openParam = currentChain.Last();
118
119      // build new tree by inverting every function in the reversed chain and keeping f0 branches untouched.
120      IFunctionTree parent = reversedChain[0];
121      IFunctionTree invParent = GetInvertedFunction(parent.Function).GetTreeNode();
122      for (int j = 1; j < parent.SubTrees.Count; j++) {
123        invParent.AddSubTree(parent.SubTrees[j]);
124      }
125      IFunctionTree root = invParent;
126      for (int i = 1; i < reversedChain.Count(); i++) {
127        IFunctionTree child = reversedChain[i];
128        IFunctionTree invChild = GetInvertedFunction(child.Function).GetTreeNode();
129        invParent.InsertSubTree(0, invChild);
130
131        parent = child;
132        invParent = invChild;
133        for (int j = 1; j < parent.SubTrees.Count; j++) {
134          invParent.AddSubTree(parent.SubTrees[j]);
135        }
136      }
137      // append open param at the end
138      invParent.InsertSubTree(0, openParam);
139      return root;
140    }
141
142    private static IEnumerable<IFunctionTree> IterateChain(IFunctionTree tree) {
143      while (tree.SubTrees.Count > 0) {
144        yield return tree;
145        tree = tree.SubTrees[0];
146      }
147      yield return tree;
148    }
149
150
151    private static Dictionary<Type, IFunction> invertedFunction = new Dictionary<Type, IFunction>() {
152      { typeof(AdditionF1), new SubtractionF1() },
153      { typeof(SubtractionF1), new AdditionF1() },
154      { typeof(MultiplicationF1), new DivisionF1() },
155      { typeof(DivisionF1), new MultiplicationF1() },
156      { typeof(OpenLog), new OpenExp() },
157      { typeof(OpenExp), new OpenLog() },
158      //{ typeof(OpenSqr), new OpenSqrt() },
159      //{ typeof(OpenSqrt), new OpenSqr() },
160      { typeof(Flip), new Flip()},
161      { typeof(Addition), new Subtraction()},
162      { typeof(Subtraction), new Addition()},
163      { typeof(Multiplication), new Division()},
164      { typeof(Division), new Multiplication()},
165      { typeof(Exponential), new Logarithm()},
166      { typeof(Logarithm), new Exponential()}
167    };
168    private static IFunction GetInvertedFunction(IFunction function) {
169      return invertedFunction[function.GetType()];
170    }
171
172    private static IFunctionTree ApplyCycles(IFunctionTree tree) {
173      int nRotations = 0;
174      while (tree.Function is Cycle) {
175        nRotations++;
176        tree = tree.SubTrees[0];
177      }
178      if (nRotations > 0 && nRotations % tree.SubTrees.Count > 0) {
179        IFunctionTree[] subTrees = tree.SubTrees.ToArray();
180        while (tree.SubTrees.Count > 0) tree.RemoveSubTree(0);
181
182        nRotations = nRotations % subTrees.Length;
183        Array.Reverse(subTrees, 0, nRotations);
184        Array.Reverse(subTrees, nRotations, subTrees.Length - nRotations);
185        Array.Reverse(subTrees, 0, subTrees.Length);
186
187        for (int i = 0; i < subTrees.Length; i++) {
188          tree.AddSubTree(subTrees[i]);
189        }
190      }
191      return tree;
192    }
193
194
195
196    private static IFunctionTree AppendLeft(IFunctionTree tree, IFunctionTree node) {
197      IFunctionTree originalTree = tree;
198      while (!IsBottomLeft(tree)) tree = tree.SubTrees[0];
199      tree.InsertSubTree(0, node);
200      return originalTree;
201    }
202
203    private static bool IsBottomLeft(IFunctionTree tree) {
204      if (tree.SubTrees.Count == 0) return true;
205      else if (tree.SubTrees[0].Function is Variable) return true;
206      else if (tree.SubTrees[0].Function is Constant) return true;
207      else return false;
208    }
209
210    /// <summary>
211    /// recieves a function tree transforms it into a function-tree for the given target variable
212    /// </summary>
213    /// <param name="tree"></param>
214    /// <param name="targetVariable"></param>
215    /// <returns></returns>
216    private static IFunctionTree TransformExpression(IFunctionTree tree, string targetVariable, IEnumerable<string> parameters) {
217      if (tree.Function is Constant) return tree;
218      if (tree.Function is Variable || tree.Function is Differential) {
219        VariableFunctionTree varTree = (VariableFunctionTree)tree;
220        varTree.Weight = 1.0;
221        if (varTree.VariableName == targetVariable) varTree.VariableName = parameters.First();
222        return varTree;
223      }
224      if (tree.Function is Addition || tree.Function is Subtraction ||
225          tree.Function is Multiplication || tree.Function is Division ||
226          tree.Function is Exponential || tree.Function is Logarithm) {
227        var occuringVariables = from x in FunctionTreeIterator.IteratePrefix(tree)
228                                where x is VariableFunctionTree
229                                let name = ((VariableFunctionTree)x).VariableName
230                                select name;
231        var openParameters = (new string[] { targetVariable }).Concat(parameters);
232        var missingVariables = openParameters.Except(occuringVariables);
233        if (missingVariables.Count() > 0) {
234          VariableFunctionTree varTree = (VariableFunctionTree)(new Variable()).GetTreeNode();
235          varTree.VariableName = missingVariables.First();
236          varTree.SampleOffset = 0;
237          varTree.Weight = 1.0;
238          tree = (IFunctionTree)tree.Clone();
239          tree.InsertSubTree(0, varTree);
240        }
241      }
242      int targetIndex = -1;
243      IFunctionTree combinator = null;
244      List<IFunctionTree> subTrees = new List<IFunctionTree>(tree.SubTrees);
245      if (HasTargetVariable(subTrees[0], targetVariable)) {
246        targetIndex = 0;
247        combinator = FunctionFromCombinator(tree).GetTreeNode();
248      } else {
249        for (int i = 1; i < subTrees.Count; i++) {
250          if (HasTargetVariable(subTrees[i], targetVariable)) {
251            targetIndex = i;
252            combinator = GetInvertedFunction(FunctionFromCombinator(tree)).GetTreeNode();
253            break;
254          }
255        }
256      }
257      if (targetIndex == -1) {
258        // target variable was not found
259        return tree;
260      } else {
261        // target variable was found
262        for (int i = 0; i < subTrees.Count; i++) {
263          if (i != targetIndex)
264            combinator.AddSubTree(subTrees[i]);
265        }
266        if (subTrees[targetIndex].Function is Variable) return combinator;
267        else {
268          IFunctionTree bottomLeft;
269          IFunctionTree targetChain = InvertF0Chain(subTrees[targetIndex], out bottomLeft);
270          bottomLeft.InsertSubTree(0, combinator);
271          return targetChain;
272        }
273      }
274    }
275
276    // inverts a chain of F0 functions
277    // precondition: left bottom is a variable (the selected target variable)
278    // postcondition: the chain is inverted. the target variable is removed
279    private static IFunctionTree InvertF0Chain(IFunctionTree tree, out IFunctionTree bottomLeft) {
280      List<IFunctionTree> currentChain = IterateChain(tree).ToList();
281
282      List<IFunctionTree> reversedChain = currentChain.Reverse<IFunctionTree>().Skip(1).ToList();
283
284      // build new tree by inverting every function in the reversed chain and keeping f0 branches untouched.
285      IFunctionTree parent = reversedChain[0];
286      IFunctionTree invParent = GetInvertedFunction(parent.Function).GetTreeNode();
287      for (int j = 1; j < parent.SubTrees.Count; j++) {
288        invParent.AddSubTree(parent.SubTrees[j]);
289      }
290      IFunctionTree root = invParent;
291      for (int i = 1; i < reversedChain.Count(); i++) {
292        IFunctionTree child = reversedChain[i];
293        IFunctionTree invChild = GetInvertedFunction(child.Function).GetTreeNode();
294        invParent.InsertSubTree(0, invChild);
295        parent = child;
296        invParent = invChild;
297        for (int j = 1; j < parent.SubTrees.Count; j++) {
298          invParent.AddSubTree(parent.SubTrees[j]);
299        }
300      }
301      bottomLeft = invParent;
302      return root;
303    }
304
305
306
307    //private static IFunctionTree InvertCombinator(IFunctionTree tree) {
308    //  if (tree.Function is OpenAddition) {
309    //    return (new OpenSubtraction()).GetTreeNode();
310    //  } else if (tree.Function is OpenSubtraction) {
311    //    return (new OpenAddition()).GetTreeNode();
312    //  } else if (tree.Function is OpenMultiplication) {
313    //    return (new OpenDivision()).GetTreeNode();
314    //  } else if (tree.Function is OpenDivision) {
315    //    return (new OpenMultiplication()).GetTreeNode();
316    //  } else throw new InvalidOperationException();
317    //}
318
319    private static Dictionary<Type, IFunction> combinatorFunction = new Dictionary<Type, IFunction>() {
320      { typeof(OpenAddition), new Addition()},
321      { typeof(OpenSubtraction), new Subtraction()},
322      { typeof(OpenDivision), new Division()},
323      { typeof(OpenMultiplication), new Multiplication()},
324      { typeof(Addition), new Addition()},
325      { typeof(Subtraction), new Subtraction()},
326      { typeof(Division), new Division()},
327      { typeof(Multiplication), new Multiplication()},
328      { typeof(Logarithm), new Logarithm()},
329      { typeof(Exponential), new Exponential()},
330    };
331    private static IFunction FunctionFromCombinator(IFunctionTree tree) {
332      return combinatorFunction[tree.Function.GetType()];
333    }
334
335    private static bool HasTargetVariable(IFunctionTree tree, string targetVariable) {
336      if (tree.SubTrees.Count == 0) {
337        var varTree = tree as VariableFunctionTree;
338        if (varTree != null) return varTree.VariableName == targetVariable;
339        else return false;
340      } else return (from x in tree.SubTrees
341                     where HasTargetVariable(x, targetVariable)
342                     select true).Any();
343    }
344
345    private static Dictionary<Type, IFunction> closedForm = new Dictionary<Type, IFunction>() {
346      {typeof(OpenAddition), new OpenAddition()},
347      {typeof(OpenSubtraction), new OpenSubtraction()},
348      {typeof(OpenMultiplication), new OpenMultiplication()},
349      {typeof(OpenDivision), new OpenDivision()},
350      {typeof(AdditionF1), new Addition()},
351      {typeof(SubtractionF1), new Subtraction()},
352      {typeof(MultiplicationF1), new Multiplication()},
353      {typeof(DivisionF1), new Division()},
354      {typeof(OpenExp), new Exponential()},
355      {typeof(OpenLog), new Logarithm()},
356      //{typeof(OpenSqr), new Power()},
357      //{typeof(OpenSqrt), new Sqrt()},
358      {typeof(OpenParameter), new Variable()},
359    };
360
361    /// <summary>
362    /// transforms a tree that contains F2 and F1 functions into a tree composed of F2 and F0 functions.
363    /// precondition: the tree doesn't contains cycle or flip symbols. the tree has openparameters in the bottom left
364    /// postcondition: all F1 and functions are replaced by matching F0 functions
365    /// </summary>
366    /// <param name="tree"></param>
367    /// <param name="targetVariables"></param>
368    /// <returns></returns>
369    private static IFunctionTree BindVariables(IFunctionTree tree, IEnumerator<string> targetVariables) {
370      if (!closedForm.ContainsKey(tree.Function.GetType())) return tree;
371      IFunction matchingFunction = closedForm[tree.Function.GetType()];
372      IFunctionTree matchingTree = matchingFunction.GetTreeNode();
373      if (matchingFunction is Variable) {
374        targetVariables.MoveNext();
375        var varTreeNode = (VariableFunctionTree)matchingTree;
376        varTreeNode.VariableName = targetVariables.Current;
377        varTreeNode.SampleOffset = ((OpenParameterFunctionTree)tree).SampleOffset;
378        varTreeNode.Weight = 1.0;
379        return varTreeNode;
380        //} else if (matchingFunction is Power) {
381        //  matchingTree.AddSubTree(BindVariables(tree.SubTrees[0], targetVariables));
382        //  var const2 = (ConstantFunctionTree)(new Constant()).GetTreeNode();
383        //  const2.Value = 2.0;
384        //  matchingTree.AddSubTree(const2);
385      } else {
386        foreach (IFunctionTree subTree in tree.SubTrees) {
387          matchingTree.AddSubTree(BindVariables(subTree, targetVariables));
388        }
389      }
390
391      return matchingTree;
392    }
393  }
394}
Note: See TracBrowser for help on using the repository browser.