Free cookie consent management tool by TermsFeed Policy Generator

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

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

Fixed a bug in the network transformation operator and changed test-cases to detect the problem. #833

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