1 | namespace HeuristicLab.Problems.ProgramSynthesis.Push.Simplifier {
|
---|
2 | using System;
|
---|
3 |
|
---|
4 | using Expressions;
|
---|
5 |
|
---|
6 | using HeuristicLab.Problems.ProgramSynthesis.Push.Data.Tree;
|
---|
7 |
|
---|
8 | public static class Simplifier {
|
---|
9 | private static readonly TreeNode<Expression> NoopNode =
|
---|
10 | new TreeNode<Expression>(ExpressionTable.GetStatelessExpression<CodeNoopExpression>());
|
---|
11 |
|
---|
12 | public static PushProgram Simplify(PushProgram program, Func<PushProgram, double> evaluator) {
|
---|
13 | var bestResult = evaluator(program);
|
---|
14 | var tree = program.ToTree();
|
---|
15 | var optimizedTree = RemoveUnnecessaryExpressions(tree, tree, ref bestResult, evaluator);
|
---|
16 |
|
---|
17 | return optimizedTree.ToPushProgram(e => !ReferenceEquals(e, NoopNode.Value));
|
---|
18 | }
|
---|
19 |
|
---|
20 | private static TreeNode<Expression> RemoveUnnecessaryExpressions(Tree<Expression> program, TreeNode<Expression> node, ref double bestResult, Func<PushProgram, double> evaluator) {
|
---|
21 | for (var i = 0; i < node.Children.Count; i++) {
|
---|
22 | var child = node.Children[i];
|
---|
23 | node.ReplaceNode(i, NoopNode);
|
---|
24 |
|
---|
25 | var currentProgram = program.ToPushProgram();
|
---|
26 | var currentResult = evaluator(currentProgram);
|
---|
27 |
|
---|
28 | if (currentResult <= bestResult) {
|
---|
29 | bestResult = currentResult;
|
---|
30 | } else if (child.Value.IsProgram) {
|
---|
31 | node.ReplaceNode(i, child);
|
---|
32 | var subProgram = RemoveUnnecessaryExpressions(program, child, ref bestResult, evaluator);
|
---|
33 | node.ReplaceNode(i, subProgram);
|
---|
34 | } else {
|
---|
35 | node.ReplaceNode(i, child);
|
---|
36 | }
|
---|
37 | }
|
---|
38 |
|
---|
39 | return node;
|
---|
40 | }
|
---|
41 | }
|
---|
42 | }
|
---|