Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Simplifier/RandomSimplifier.cs @ 14745

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

#2665 Merged ExecExpandExpression and PushProgram due to performance reasons, Tested managed object pooling

File size: 1.9 KB
Line 
1namespace HeuristicLab.Problems.ProgramSynthesis.Push.Simplifier {
2  using System;
3  using HeuristicLab.Core;
4  using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions;
5
6  public class RandomSimplifier : ISimplifier {
7    public int Trys { get; set; }
8
9    public PushProgram Simplify(PushProgram program, IRandom random, Predicate<PushProgram> isBetter) {
10
11      if (program.TotalCount == 1) {
12        return isBetter(PushProgram.Empty) ? PushProgram.Empty : program;
13      }
14
15      var copy = program.Copy();
16      var maxTries = Math.Min(Trys, program.TotalCount - 2);
17      var successfulRemoves = 0;
18
19      for (var i = 0; i < maxTries; i++) {
20        var rndIndex = random.Next(1, program.TotalCount - 1 - successfulRemoves);
21        var node = copy.GetFromTree(
22          rndIndex,
23          (super, parent, child, childIndex, parentIndex) => new {
24            Super = super,
25            Parent = parent,
26            ChildIndex = childIndex,
27            ParentIndex = parentIndex
28          });
29
30        var oldParentExpressions = node.Parent.State;
31        var newParentExpressions = RemoveAt(oldParentExpressions, node.ChildIndex);
32        var newParent = new PushProgram(newParentExpressions);
33
34        var superExpressions = node.Super == null ? copy.State : node.Super.State;
35        superExpressions[node.ParentIndex] = newParent;
36
37        if (isBetter(copy)) {
38          successfulRemoves++;
39        } else {
40          superExpressions[node.ParentIndex] = node.Parent;
41        }
42      }
43
44      return copy;
45    }
46
47    private static T[] RemoveAt<T>(T[] source, int index) {
48      var dest = new T[source.Length - 1];
49      if (index > 0)
50        Array.Copy(source, 0, dest, 0, index);
51
52      if (index < source.Length - 1)
53        Array.Copy(source, index + 1, dest, index, source.Length - index - 1);
54
55      return dest;
56    }
57  }
58}
Note: See TracBrowser for help on using the repository browser.