Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Data/Tree/TreeExtensions.cs @ 14834

Last change on this file since 14834 was 14834, checked in by pkimmesw, 7 years ago

#2665 LexicaseSelector, Performance improvements, UI Fixes, Debugger only shows used stacks, fixed Debugger stepping, Added vector expressions, ERCOptions,

File size: 2.2 KB
Line 
1using System;
2using System.Collections.Generic;
3
4namespace HeuristicLab.Problems.ProgramSynthesis.Push.Data.Tree {
5  using System.Linq;
6
7  using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions;
8
9  public static class TreeExtensions {
10    public static Tree<T> ToTree<T>(
11      this IEnumerable<T> items,
12      Predicate<T> isChild,
13      Func<T, IReadOnlyList<T>> childrenResolver) {
14      var tree = new Tree<T>();
15
16      foreach (var item in items) {
17        if (isChild(item)) {
18          var subNode = childrenResolver(item).ToTree(isChild, childrenResolver);
19          subNode.Value = item;
20          tree.AddNode(subNode);
21        } else {
22          tree.Add(item);
23        }
24      }
25
26      return tree;
27    }
28
29    public static IEnumerable<TreeNode<T>> DepthLast<T>(this TreeNode<T> node) {
30      foreach (var child in node.Children) {
31        if (child.Children.Count > 0) {
32          foreach (var subChild in child.DepthLast()) {
33            yield return subChild;
34          }
35        } else yield return child;
36      }
37    }
38
39    public static IEnumerable<T> DepthLast<T>(this TreeNode<T> node, Func<IEnumerable<T>, T> resolveParent) {
40      foreach (var child in node.Children) {
41        if (child.Children.Count > 0) {
42          var subExpressions = child.DepthLast(resolveParent);
43          yield return resolveParent(subExpressions);
44        } else yield return child.Value;
45      }
46    }
47
48    public static PushProgram ToPushProgram(this TreeNode<Expression> tree, Func<Expression, bool> condition = null) {
49      var expressions = tree.DepthLast(e => ResolveProgram(e, condition));
50
51      return ResolveProgram(expressions, condition);
52    }
53
54    public static Tree<Expression> ToTree(this PushProgram program) {
55      var tree = program.Expressions.ToTree(e => e.IsProgram, e => ((PushProgram)e).Expressions);
56      tree.Value = program;
57
58      return tree;
59    }
60
61    private static PushProgram ResolveProgram(IEnumerable<Expression> expressions, Func<Expression, bool> condition = null) {
62
63      if (condition != null) {
64        expressions = expressions.Where(condition);
65      }
66
67      return new PushProgram(expressions.ToArray());
68    }
69  }
70
71}
Note: See TracBrowser for help on using the repository browser.