Changeset 14513 for branches/PushGP/HeuristicLab.Algorithms.PushGP/HeuristicLab.Algorithms.PushGP/Simplifier/RandomSimplifier.cs
- Timestamp:
- 12/20/16 22:57:11 (7 years ago)
- File:
-
- 1 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/PushGP/HeuristicLab.Algorithms.PushGP/HeuristicLab.Algorithms.PushGP/Simplifier/RandomSimplifier.cs
r14398 r14513 1 using HeuristicLab.Algorithms.PushGP.Expressions; 2 using HeuristicLab.Core; 3 using HeuristicLab.Random; 1 namespace 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; 4 7 5 namespace HeuristicLab.Algorithms.PushGP.Simplifier 6 { 7 public class RandomSimplifier : ISimplifier 8 { 9 private IRandom rand = new FastRandom(); 10 public int Trys { get; set; } 8 public class RandomSimplifier : ISimplifier { 9 private static readonly ThreadLocal<IRandom> random = RandomFactory.GetRandom(); 11 10 12 public Expression Simplify(Expression program) 13 { 14 if (program.GetType() != typeof(ExecExpandExpression)) 15 return program; 11 public int Trys { get; set; } 16 12 17 var clone = program.Clone() as ExecExpandExpression;13 public ExecExpandExpression Simplify(ExecExpandExpression program, Predicate<ExecExpandExpression> isBetter) { 18 14 19 for (var i = 0; i < Trys; i++)20 {21 var index = rand.Next(0, clone.TotalCount - 1);15 if (program.TotalCount == 1) { 16 return isBetter(ExecExpandExpression.Empty) ? ExecExpandExpression.Empty : program; 17 } 22 18 23 } 19 var copy = program.Copy(); 20 var maxTrys = Math.Min(Trys, program.TotalCount - 2); 21 var sucessfullRemoves = 0; 24 22 25 return clone; 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; 26 45 } 46 } 47 48 return copy; 27 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 } 28 62 }
Note: See TracChangeset
for help on using the changeset viewer.