Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.Algorithms.PushGP/HeuristicLab.Algorithms.PushGP/Simplifier/RandomSimplifier.cs @ 14513

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

#2665 Added Problem.ProgramSynthesis Project, Fixed Expression Issues, Fixed Code Generation

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