Changeset 15017 for branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem
- Timestamp:
- 06/01/17 09:28:34 (8 years ago)
- Location:
- branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem
- Files:
-
- 9 edited
Legend:
- Unmodified
- Added
- Removed
-
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/BenchmarkSuitePushSolutionView.cs
r14952 r15017 10 10 using HeuristicLab.BenchmarkSuite.Views; 11 11 using HeuristicLab.Common; 12 using HeuristicLab.Problems.ProgramSynthesis.Push.Constants; 12 13 13 14 using Interpreter; … … 237 238 238 239 case ExampleArgumentType.Print: 239 var requiredLines = example.OutputPrint.Split(new[] { Environment.NewLine }, StringSplitOptions.None).Length; 240 var count = Math.Min(requiredLines, interpreter.PrintStack.Count); 241 return string.Join(valueSeparator, string.Join(Environment.NewLine, interpreter.PrintStack.Peek(count))); 240 return string.Join(valueSeparator, string.Join(PushEnvironment.NewLine, interpreter.PrintStack.Take(example.OutputPrintLineCount))); 242 241 243 242 case ExampleArgumentType.String: … … 257 256 } 258 257 259 private static string GetVectorEntryAsString<T>(int offset, IPushStack< List<T>> vectorStack) {258 private static string GetVectorEntryAsString<T>(int offset, IPushStack<IReadOnlyList<T>> vectorStack) { 260 259 return vectorStack.Count > offset 261 260 ? "[" + string.Join(",", vectorStack[offset]) + "]" 262 261 : string.Empty; 263 }264 265 private int GetCount<T>(IPushStack<T> stack, T[] data) {266 return Math.Max(0, Math.Min(data.Length, stack.Count));267 }268 269 private int GetVectorCount<T>(IPushStack<List<T>> stack, T[][] data) {270 return Math.Max(0, Math.Min(data.Length, stack.Count));271 262 } 272 263 -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/PushBenchmarkSuiteEvaluator.cs
r14952 r15017 12 12 using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; 13 13 using HeuristicLab.Problems.ProgramSynthesis.Push.Configuration; 14 using HeuristicLab.Problems.ProgramSynthesis.Push.Constants; 14 15 15 16 using Interpreter; … … 78 79 } 79 80 80 public EvaluationResult Evaluate(IPushInterpreter interpreter, PushProgram program, IRandom random,int start, int end) {81 public EvaluationResult Evaluate(IPushInterpreter interpreter, PushProgram program, int start, int end) { 81 82 var length = end - start; 82 83 if (length <= 0) return null; … … 87 88 var result = Evaluate(interpreter, program, i); 88 89 evaluationResult.ExampleQualities[i - start] = result; 89 evaluationResult. TotalQuality += result;90 evaluationResult.AvgQuality += result; 90 91 interpreter.Reset(); 91 92 } 92 93 93 evaluationResult. TotalQuality /= length;94 evaluationResult.AvgQuality /= length; 94 95 95 96 return evaluationResult; 96 97 } 97 98 98 public EvaluationResult EvaluateTest(IPushInterpreter interpreter, PushProgram program , IRandom random) {99 return Evaluate(interpreter, program, random,DataBounds.TestRange.Start, DataBounds.TestRange.End);99 public EvaluationResult EvaluateTest(IPushInterpreter interpreter, PushProgram program) { 100 return Evaluate(interpreter, program, DataBounds.TestRange.Start, DataBounds.TestRange.End); 100 101 } 101 102 102 103 public EvaluationResult EvaluateTest(IReadOnlyPushConfiguration config, PushProgram program, IRandom random) { 103 104 var interpreter = new PushInterpreter(config, random); 104 return EvaluateTest(interpreter, program , random);105 return EvaluateTest(interpreter, program); 105 106 } 106 107 107 108 public EvaluationResult EvaluateTest(PushInterpreterPool pool, PushProgram program, IRandom random) { 108 109 using (var interpreter = pool.Create(random)) { 109 return EvaluateTest(interpreter, program , random);110 } 111 } 112 113 public EvaluationResult EvaluateTraining(IPushInterpreter interpreter, PushProgram program , IRandom random) {114 return Evaluate(interpreter, program, random,DataBounds.TrainingRange.Start, DataBounds.TrainingRange.End);110 return EvaluateTest(interpreter, program); 111 } 112 } 113 114 public EvaluationResult EvaluateTraining(IPushInterpreter interpreter, PushProgram program) { 115 return Evaluate(interpreter, program, DataBounds.TrainingRange.Start, DataBounds.TrainingRange.End); 115 116 } 116 117 117 118 public EvaluationResult EvaluateTraining(IReadOnlyPushConfiguration config, PushProgram program, IRandom random) { 118 119 var interpreter = new PushInterpreter(config, random); 119 return EvaluateTraining(interpreter, program , random);120 return EvaluateTraining(interpreter, program); 120 121 } 121 122 122 123 public EvaluationResult EvaluateTraining(PushInterpreterPool pool, PushProgram program, IRandom random) { 123 124 using (var interpreter = pool.Create(random)) { 124 return EvaluateTraining(interpreter, program , random);125 return EvaluateTraining(interpreter, program); 125 126 } 126 127 } … … 134 135 interpreter.CharStack.Push(example.InputChar); 135 136 interpreter.StringStack.Push(example.InputString); 136 interpreter.StringVectorStack.Push(example.InputStringVector .Select(v => new List<string>(v)));137 interpreter.IntegerVectorStack.Push(example.InputIntegerVector .Select(v => new List<long>(v)));138 interpreter.FloatVectorStack.Push(example.InputFloatVector .Select(v => new List<double>(v)));137 interpreter.StringVectorStack.Push(example.InputStringVector); 138 interpreter.IntegerVectorStack.Push(example.InputIntegerVector); 139 interpreter.FloatVectorStack.Push(example.InputFloatVector); 139 140 140 141 interpreter.Run(program); 141 142 143 switch (Data.ProblemType) { 144 //case ProblemType.NumberIO: 145 // if (interpreter.PrintStack.IsEmpty) 146 // return Data.WorstResult; 147 148 // double value; 149 // var levenshteinDistance = GetPrintDiffer(example.OutputPrint, interpreter.PrintStack, example.OutputPrintLineCount, Data.WorstResult); 150 // return levenshteinDistance + (double.TryParse(interpreter.PrintStack.Top, out value) 151 // ? FloatDiffer(value, example.OutputFloat[0], example.OutputFloatPrecision) 152 // : Data.WorstResult / 2); 153 154 case ProblemType.Median: return interpreter.PrintStack.IsEmpty ? 1 : interpreter.PrintStack.Top.Equals(example.OutputPrint) ? 0 : 1; 155 } 156 142 157 var result = GetDiff(example.OutputInteger, interpreter.IntegerStack, Data.WorstResult, IntegerDiffer) 143 + GetDiff(example.OutputFloat, interpreter.FloatStack, Data.WorstResult, FloatDiffer)158 + GetDiff(example.OutputFloat, interpreter.FloatStack, Data.WorstResult, (a, b) => FloatDiffer(a, b, example.OutputFloatPrecision)) 144 159 + GetDiff(example.OutputBoolean, interpreter.BooleanStack, Data.WorstResult, BooleanDiffer) 145 160 + GetDiff(example.OutputString, interpreter.StringStack, Data.WorstResult, StringDiffer) 146 161 + GetDiff(example.OutputChar, interpreter.CharStack, Data.WorstResult, CharDiffer) 147 + GetPrintDiffer(example.OutputPrint, interpreter.PrintStack )162 + GetPrintDiffer(example.OutputPrint, interpreter.PrintStack, example.OutputPrintLineCount, Data.WorstResult) 148 163 + GetVectorDiff(example.OutputIntegerVector, interpreter.IntegerVectorStack, Data.WorstResult, (a, b) => VectorDiffer(a, b, IntegerDiffer)) 149 + GetVectorDiff(example.OutputFloatVector, interpreter.FloatVectorStack, Data.WorstResult, (a, b) => VectorDiffer(a, b, FloatDiffer))164 + GetVectorDiff(example.OutputFloatVector, interpreter.FloatVectorStack, Data.WorstResult, (a, b) => VectorDiffer(a, b, (x, y) => FloatDiffer(x, y, example.OutputFloatVectorPrecision))) 150 165 + GetVectorDiff(example.OutputStringVector, interpreter.StringVectorStack, Data.WorstResult, (a, b) => VectorDiffer(a, b, StringDiffer)); 151 166 … … 153 168 } 154 169 155 private static double FloatDiffer(double a, double b) { 156 var result = a - b; 157 158 if (result.IsAlmost(double.MinValue) || double.IsPositiveInfinity(result) || double.IsNaN(result)) 170 private static double FloatDiffer(double a, double b, int digits) { 171 var result = Math.Round(a, digits) - Math.Round(b, digits); 172 173 // ReSharper disable once CompareOfFloatsByEqualityOperator 174 if (result == double.MinValue || double.IsPositiveInfinity(result) || double.IsNaN(result)) 159 175 return double.MaxValue; 160 176 161 if (result.IsAlmost(double.MaxValue) || double.IsNegativeInfinity(result)) 177 // ReSharper disable once CompareOfFloatsByEqualityOperator 178 if (result == double.MaxValue || double.IsNegativeInfinity(result)) 162 179 return double.MinValue; 163 180 … … 200 217 } 201 218 202 private static readonly string[] separator = { "\n" }; 203 private static double GetPrintDiffer(string estimated, IPushStack<string> printStack) { 204 var estimatedCount = estimated.Split(separator, StringSplitOptions.None).Length; 205 var printResult = string.Join(separator[0], printStack.Take(estimatedCount)); 206 207 return LevenshteinDistance(estimated, printResult); 208 } 209 210 private static double GetVectorDiff<T>(IReadOnlyList<IReadOnlyList<T>> estimated, IPushStack<List<T>> resultStack, double worstResult, Func<IReadOnlyList<T>, IReadOnlyList<T>, double> differ) 219 private static double GetPrintDiffer(string estimated, IPushStack<string> printStack, int estimatedCount, double worstResult) { 220 var printResult = string.Join(PushEnvironment.NewLine, printStack.Take(estimatedCount)); 221 var distance = LevenshteinDistance(estimated, printResult); 222 223 return Math.Min(distance, worstResult); 224 } 225 226 private static double GetVectorDiff<T>(IReadOnlyList<IReadOnlyList<T>> estimated, IPushStack<IReadOnlyList<T>> resultStack, double worstResult, Func<IReadOnlyList<T>, IReadOnlyList<T>, double> differ) 211 227 where T : IComparable { 212 228 if (estimated.Count == 0) return 0d; -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/PushBenchmarkSuiteProblem.cs
r14952 r15017 5 5 6 6 using HeuristicLab.BenchmarkSuite; 7 using HeuristicLab. Encodings.IntegerVectorEncoding;7 using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions; 8 8 9 9 using Instances; … … 38 38 PushEvaluator.LoadData(data); 39 39 40 BestKnownQuality = data.BestResult;41 MaxPointsInProgram = data.MaxSize;42 MinPointsInProgram = data.MaxSize;43 EvalPushLimit = data.EvalLimit;44 ErcOptions = data.ErcOptions;45 40 Name = "Push Problem: " + data.Name; 46 41 Description = data.Description; 42 BestKnownQuality = data.BestResult; 43 config.MaxPointsInProgram = data.MaxSize; 44 config.EvalPushLimit = data.EvalLimit; 45 config.ErcOptions = data.ErcOptions; 46 config.FloatStringFormat = data.FloatStringFormat; 47 47 48 48 config.SetEnabledStacks((StackTypes)data.EnabledDataTypes); … … 50 50 Encoding.Bounds[0, 0] = 0; 51 51 Encoding.Bounds[0, 1] = config.EnabledExpressions.Count; 52 Encoding.Length = config.MaxPointsInProgram; 52 53 InitProgramLength = data.MaxSize / 2; 53 54 } 54 55 55 56 protected override PushSolution CreatePushSolution( 56 IntegerVector vector,57 PushProgram program, 57 58 double bestQuality, 58 59 IRandom random, 59 60 IReadOnlyPushConfiguration config, 60 61 IPushEvaluator evaluator) { 61 return new PushBenchmarkSuiteSolution( vector, bestQuality, random, (IReadOnlyPushConfiguration)config.Clone(), (PushBenchmarkSuiteEvaluator)PushEvaluator.Clone());62 return new PushBenchmarkSuiteSolution(program, bestQuality, random, (IReadOnlyPushConfiguration)config.Clone(), (PushBenchmarkSuiteEvaluator)PushEvaluator.Clone()); 62 63 } 63 64 } -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/PushBenchmarkSuiteSolution.cs
r14897 r15017 3 3 using Configuration; 4 4 using Core; 5 using Encodings.IntegerVectorEncoding; 5 6 using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions; 7 6 8 using Persistence.Default.CompositeSerializers.Storable; 7 9 … … 9 11 public class PushBenchmarkSuiteSolution : PushSolution { 10 12 public PushBenchmarkSuiteSolution( 11 IntegerVector integerVector,13 PushProgram program, 12 14 double quality, 13 15 IRandom random, 14 16 IReadOnlyPushConfiguration config, 15 17 PushBenchmarkSuiteEvaluator evaluator, 16 bool simplify = false) : base( integerVector, quality, random, config, evaluator, simplify) {18 bool simplify = false) : base(program, quality, random, config, evaluator, simplify) { 17 19 } 18 20 … … 23 25 24 26 public override PushSolution Simplify() { 25 return new PushBenchmarkSuiteSolution( IntegerVector, Quality, Random, Config, (PushBenchmarkSuiteEvaluator)Evaluator, true);27 return new PushBenchmarkSuiteSolution(Program, Quality, Random, Config, (PushBenchmarkSuiteEvaluator)Evaluator, true); 26 28 } 27 29 -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/EvaluationResult.cs
r14897 r15017 6 6 7 7 8 public double TotalQuality { get; set; }8 public double AvgQuality { get; set; } 9 9 public double[] ExampleQualities { get; set; } 10 10 } -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/IPushEvaluator.cs
r14897 r15017 8 8 public interface IPushEvaluator : IDeepCloneable { 9 9 EvaluationResult EvaluateTest(IReadOnlyPushConfiguration config, PushProgram program, IRandom random); 10 EvaluationResult EvaluateTest(IPushInterpreter interpreter, PushProgram program , IRandom random);10 EvaluationResult EvaluateTest(IPushInterpreter interpreter, PushProgram program); 11 11 EvaluationResult EvaluateTest(PushInterpreterPool pool, PushProgram program, IRandom random); 12 12 EvaluationResult EvaluateTraining(IReadOnlyPushConfiguration config, PushProgram program, IRandom random); 13 EvaluationResult EvaluateTraining(IPushInterpreter interpreter, PushProgram program , IRandom random);13 EvaluationResult EvaluateTraining(IPushInterpreter interpreter, PushProgram program); 14 14 EvaluationResult EvaluateTraining(PushInterpreterPool pool, PushProgram program, IRandom random); 15 15 } -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/IndividualMapper.cs
r14897 r15017 1 1 namespace HeuristicLab.Problems.ProgramSynthesis.Push.Problem { 2 using System.Collections.Generic; 2 3 3 4 using HeuristicLab.Core; … … 7 8 using HeuristicLab.Problems.ProgramSynthesis.Push.Data.Pool; 8 9 using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions; 10 using HeuristicLab.Problems.ProgramSynthesis.Push.Extensions; 9 11 using HeuristicLab.Problems.ProgramSynthesis.Push.Generators.CodeGenerator; 10 12 using HeuristicLab.Random; … … 17 19 public static PushProgram ToPushProgram(this Individual individual, IReadOnlyPushConfiguration config) { 18 20 return individual.IntegerVector().ToPushProgram(config); 21 } 22 23 public static PushProgram ToPushProgram(this Individual individual, IReadOnlyPushConfiguration config, IRandom random) { 24 return individual.IntegerVector().ToPushProgram(config, random); 19 25 } 20 26 … … 35 41 } 36 42 37 p rivatestatic int GetSeed(this IntegerVector vector) {38 var seed = 0;43 public static int GetSeed(this IntegerVector vector) { 44 var seed = 17; 39 45 for (var i = 0; i < vector.Length; i++) 40 seed += (i + 1) *vector[i];46 seed = seed * 23 + vector[i]; 41 47 return seed; 42 48 } 43 49 44 private static PushProgram ToPushProgram(this IntegerVector vector, IReadOnlyPushConfiguration config, IRandom random) { 45 var enabledExpressions = config.EnabledExpressions; 46 var ercOptions = config.ErcOptions; 47 //var programLength = random.Next(config.MinPointsInProgram, config.MaxPointsInProgram + 1); 48 var expressions = new Expression[vector.Length]; 50 public static PushProgram ToPushProgram(this IntegerVector vector, IReadOnlyPushConfiguration config, IRandom random) { 51 var currentIndex = 0; 52 var close = 0; 49 53 50 for (var i = 0; i < vector.Length; i++) 51 expressions[i] = CodeGeneratorUtils.CreateExpressionOrErc(vector[i], random, enabledExpressions, ercOptions); 54 return FromPlush(vector, ref currentIndex, ref close, 0, config, random); 55 } 56 57 private static PushProgram FromPlush(IntegerVector vector, ref int currentIndex, ref int close, int depth, IReadOnlyPushConfiguration config, IRandom random) { 58 if (currentIndex >= vector.Length) 59 return PushProgram.Empty; 60 61 var expressions = new List<Expression>(); 62 63 for (; currentIndex < vector.Length; currentIndex++) { 64 var expression = CodeGeneratorUtils.CreateExpressionOrErc( 65 vector[currentIndex] % config.EnabledExpressions.Count, 66 random, 67 config.EnabledExpressions, 68 config.ErcOptions); 69 70 var expressionType = expression.GetType(); 71 close += random.NextBiased(0, config.MaxParenthesesClose, config.ParenthesesCloseBiasLevel); 72 73 74 // check if expression requires additional blocks 75 if (ExpressionTable.TypeToAttributeTable.ContainsKey(expressionType)) { 76 var attr = ExpressionTable.TypeToAttributeTable[expressionType]; 77 78 for (var blockIdx = 0u; blockIdx < attr.ExecIn && currentIndex < vector.Length; blockIdx++) { 79 if (close != 0) { 80 close--; 81 expressions.Add(PushProgram.Empty); 82 } else { 83 currentIndex++; 84 var subProgram = FromPlush(vector, ref currentIndex, ref close, depth + 1, config, random); 85 var subExpression = subProgram.Count == 1 ? subProgram.Expressions[0] : subProgram; 86 expressions.Add(subExpression); 87 } 88 } 89 } 90 91 expressions.Add(expression); 92 93 if (close > 0 && depth > 0) { 94 close--; 95 break; 96 } 97 98 if (depth == 0) { 99 close = 0; 100 } 101 } 52 102 53 103 return new PushProgram(expressions); -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/PushProblem.cs
r14952 r15017 10 10 using HeuristicLab.Data; 11 11 using HeuristicLab.Encodings.IntegerVectorEncoding; 12 using HeuristicLab.Problems.ProgramSynthesis. Base.Erc;12 using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions; 13 13 using HeuristicLab.Problems.ProgramSynthesis.Push.Problem.BenchmarkSuite; 14 14 … … 22 22 public abstract class PushProblem : SingleObjectiveBasicProblem<IntegerVectorEncoding> { 23 23 [Storable] 24 protected readonly PushConfiguration config;24 protected readonly PushConfigurationParameterCollection config; 25 25 protected PushInterpreterPool pool; 26 protected readonly ObjectPool<IRandom> randomPool = new ObjectPool<IRandom>(() => new MersenneTwister() );26 protected readonly ObjectPool<IRandom> randomPool = new ObjectPool<IRandom>(() => new MersenneTwister(), Environment.ProcessorCount * 4); 27 27 28 28 [Storable] 29 29 protected readonly IPushEvaluator PushEvaluator; 30 30 31 public const string CaseQualitiesScopeParameterName = "CaseQualities";32 31 private const string BestTrainingSolutionResultName = "Best Solution"; 33 32 private const string TestQualityResultName = "Test Quality"; 34 33 35 34 protected PushProblem(PushBenchmarkSuiteEvaluator evaluator) { 36 config = new PushConfiguration ();35 config = new PushConfigurationParameterCollection(); 37 36 PushEvaluator = evaluator; 38 37 … … 40 39 InitEvents(); 41 40 InitParameters(); 41 InitEncoding(); 42 42 } 43 43 … … 61 61 InitData(); 62 62 InitEvents(); 63 InitParameters(); 63 64 } 64 65 … … 76 77 } 77 78 79 public ILookupParameter<IntValue> SeedParamater 80 { 81 get { return (ILookupParameter<IntValue>)Parameters["Seed"]; } 82 } 83 78 84 #region Parameters 79 80 private const string InstructionsParameterName = "Instructions"; 81 private const string InstructionsParameterDescription = "Enables/Disables Instructions"; 82 private const string EvalPushLimitParameterName = "EvalPushLimit"; 83 private const string EvalPushLimitParameterDescription = "This is the maximum allowed number of \"executions\" in a single top-level call to the interpreter. The execution of a single Push instruction counts as one execution, as does the processing of a single literal, as does the descent into one layer of parentheses (that is, the processing of the \"(\" counts as one execution)."; 84 private const string MinPointsInProgramParameterName = "MinProgramLength"; 85 private const string MinProgramLengthParameterDescription = "This is the minimum size of an item on the CODE/EXEC stack, expressed as a number of points. A point is an instruction, a literal, or a pair of parentheses."; 86 private const string MaxPointsInProgramParameterName = "MaxProgramLength"; 87 private const string MaxProgramLengthParameterDescription = "This is the maximum size of an item on the CODE/EXEC stack, expressed as a number of points. A point is an instruction, a literal, or a pair of parentheses."; 88 private const string TopLevelPushCodeParameterName = "TopLevelPushCode"; 89 private const string TopLevelPushCodeParameterDescription = "When TRUE (which is the default), code passed to the top level of the interpreter will be pushed onto the CODE stack prior to execution."; 90 private const string TopLevelPopCodeParameterName = "TopLevelPopCode"; 91 private const string TopLevelPopCodeParameterDescription = "When TRUE, the CODE stack will be popped at the end of top level calls to the interpreter. The default is FALSE."; 92 private const string MaxPointsInRandomInstructionParameterName = "MaxPointsInRandomInstruction"; 93 private const string MaxPointsInRandomInstructionParameterDescription = "MaxPointsInRandomInstruction"; 94 private const string ErcOptionsParameterName = "ERC options"; 95 private const string MaxStringLengthParameterName = "Max. string length"; 96 private const string MaxDepthParameterName = "Max. program recursion"; 85 private const string InitProgramLengthParameterName = "InitProgramLength"; 86 private const string InitProgramLengthParameterDescription = "This is the initial size of a push program."; 87 88 public const string CasesScopeParameterName = "CaseQualities"; 89 public const string CaseQualitiesScopeParameterName = "CaseQualities"; 97 90 98 91 private void InitParameters() { 99 Parameters.Add(new ValueParameter<IEnabledExpressionsConfiguration>( 100 InstructionsParameterName, 101 InstructionsParameterDescription, 102 config)); 103 104 Parameters.Add(new ValueParameter<ErcOptions>(ErcOptionsParameterName, config.ErcOptions)); 105 106 Parameters.Add(new FixedValueParameter<IntValue>( 107 EvalPushLimitParameterName, 108 EvalPushLimitParameterDescription, 109 new IntValue(config.EvalPushLimit))); 110 111 Parameters.Add(new FixedValueParameter<IntValue>( 112 MinPointsInProgramParameterName, 113 MinProgramLengthParameterDescription, 114 new IntValue(config.MinPointsInProgram)) { Hidden = true }); 115 116 Parameters.Add(new FixedValueParameter<IntValue>( 117 MaxPointsInProgramParameterName, 118 MaxProgramLengthParameterDescription, 119 new IntValue(config.MaxPointsInProgram))); 120 Encoding.LengthParameter = MaxPointsInProgramParameter as IFixedValueParameter<IntValue>; 121 122 Parameters.Add(new FixedValueParameter<BoolValue>( 123 TopLevelPushCodeParameterName, 124 TopLevelPushCodeParameterDescription, 125 new BoolValue(config.TopLevelPushCode)) { Hidden = true }); 126 127 Parameters.Add(new FixedValueParameter<BoolValue>( 128 TopLevelPopCodeParameterName, 129 TopLevelPopCodeParameterDescription, 130 new BoolValue(config.TopLevelPopCode)) { Hidden = true }); 131 132 Parameters.Add(new FixedValueParameter<IntValue>( 133 MaxPointsInRandomInstructionParameterName, 134 MaxPointsInRandomInstructionParameterDescription, 135 new IntValue(config.MaxPointsInRandomExpression)) { Hidden = true }); 136 137 Parameters.Add(new FixedValueParameter<IntValue>( 138 MaxStringLengthParameterName, 139 new IntValue(config.MaxStringLength)) { Hidden = true }); 140 141 Parameters.Add(new FixedValueParameter<IntValue>( 142 MaxDepthParameterName, 143 new IntValue(config.MaxDepth)) { Hidden = true }); 144 145 Parameters.Add(new LookupParameter<BoolArray>("Cases", "The training cases that have been successfully executed.")); 146 Parameters.Add(new LookupParameter<DoubleArray>(CaseQualitiesScopeParameterName, "The quality of every single training case for each individual")); 147 92 foreach (var paramater in config.Parameters) { 93 if (!Parameters.ContainsKey(paramater.Name)) { 94 Parameters.Add(paramater); 95 } 96 } 97 98 if (!Parameters.ContainsKey(InitProgramLengthParameterName)) { 99 Parameters.Add(new FixedValueParameter<IntValue>( 100 InitProgramLengthParameterName, 101 InitProgramLengthParameterDescription, 102 new IntValue(50))); 103 } 104 105 Encoding.LengthParameter = InitProgramLengthParameter as IFixedValueParameter<IntValue>; 106 107 if (!Parameters.ContainsKey(CasesScopeParameterName)) 108 Parameters.Add(new LookupParameter<BoolArray>(CasesScopeParameterName, "The training cases that have been successfully executed.")); 109 110 if (!Parameters.ContainsKey(CaseQualitiesScopeParameterName)) 111 Parameters.Add(new LookupParameter<DoubleArray>(CaseQualitiesScopeParameterName, "The quality of every single training case for each individual")); 112 } 113 114 protected override void OnReset() { 115 base.OnReset(); 116 117 // clear pools and free reserved memory 118 pool.Clear(); 119 } 120 121 private void InitEncoding() { 148 122 Encoding.Bounds[0, 0] = 0; 149 123 Encoding.Bounds[0, 1] = config.EnabledExpressions.Count; … … 151 125 } 152 126 153 public IValueParameter<IEnabledExpressionsConfiguration> InstructionsParameter 127 /// <summary> 128 /// This is the inital size of an push program generated by a solution creator 129 /// </summary> 130 public IValueParameter<IntValue> InitProgramLengthParameter 154 131 { 155 get { return (IValueParameter<I EnabledExpressionsConfiguration>)Parameters[InstructionsParameterName]; }156 } 157 158 public IEnabledExpressionsConfiguration Instructions132 get { return (IValueParameter<IntValue>)Parameters[InitProgramLengthParameterName]; } 133 } 134 135 public int InitProgramLength 159 136 { 160 get { return InstructionsParameter.Value; } 161 set { InstructionsParameter.Value = value; } 162 } 163 164 public IValueParameter<ErcOptions> ErcOptionsParameter 165 { 166 get { return (IValueParameter<ErcOptions>)Parameters[ErcOptionsParameterName]; } 167 } 168 169 public ErcOptions ErcOptions 170 { 171 get { return config.ErcOptions; } 137 get { return InitProgramLengthParameter.Value.Value; } 172 138 set 173 139 { 174 ErcOptionsParameter.Value = value; 175 config.ErcOptions = value; 176 } 177 } 178 179 /// <summary> 180 /// This is the maximum allowed number of "executions" in a single top-level call to the interpreter. 181 /// The execution of a single Push instruction counts as one execution, as does the processing of a single literal, 182 /// as does the descent into one layer of parentheses (that is, the processing of the "(" counts as one execution). 183 /// When this limit is exceeded the interpreter aborts immediately, leaving its stacks in the states they were in prior 184 /// to the abort (so they may still be examined by a calling program). Whether or not this counts as an "abnormal" 185 /// termination 186 /// is up to the calling program. 187 /// </summary> 188 public IValueParameter<IntValue> EvalPushLimitParameter 189 { 190 get { return (IValueParameter<IntValue>)Parameters[EvalPushLimitParameterName]; } 191 } 192 193 public int EvalPushLimit 194 { 195 get { return config.EvalPushLimit; } 196 set 197 { 198 EvalPushLimitParameter.Value.Value = value; 199 config.EvalPushLimit = value; 200 } 201 } 202 203 /// <summary> 204 /// This is the maximum of depth a push program can have. Expressions, which lead to exceed this limit are interpreted as NOOP. 205 /// </summary> 206 public IValueParameter<IntValue> MaxDepthParameter 207 { 208 get { return (IValueParameter<IntValue>)Parameters[MaxDepthParameterName]; } 209 } 210 211 public int MaxDepth 212 { 213 get { return config.MaxDepth; } 214 set 215 { 216 MaxDepthParameter.Value.Value = value; 217 config.MaxDepth = value; 218 } 219 } 220 221 /// <summary> 222 /// This is the maximum size of an item on the CODE stack, expressed as a number of points. 223 /// A point is an instruction, a literal, or a pair of parentheses. Any instruction that would cause this limit to be 224 /// exceeded 225 /// should instead act as a NOOP, leaving all stacks in the states that they were in before the execution of the 226 /// instruction. 227 /// </summary> 228 public IValueParameter<IntValue> MaxPointsInProgramParameter 229 { 230 get { return (IValueParameter<IntValue>)Parameters[MaxPointsInProgramParameterName]; } 231 } 232 233 public int MaxPointsInProgram 234 { 235 get { return config.MaxPointsInProgram; } 236 set 237 { 238 MaxPointsInProgramParameter.Value.Value = value; 239 config.MaxPointsInProgram = value; 240 } 241 } 242 243 /// <summary> 244 /// This is the minimum size of an item on the CODE stack, expressed as a number of points. 245 /// A point is an instruction, a literal, or a pair of parentheses. Any instruction that would cause this limit to be 246 /// exceeded 247 /// should instead act as a NOOP, leaving all stacks in the states that they were in before the execution of the 248 /// instruction. 249 /// </summary> 250 public IValueParameter<IntValue> MinPointsInProgramParameter 251 { 252 get { return (IValueParameter<IntValue>)Parameters[MinPointsInProgramParameterName]; } 253 } 254 255 public int MinPointsInProgram 256 { 257 get { return config.MaxPointsInProgram; } 258 set 259 { 260 MinPointsInProgramParameter.Value.Value = value; 261 config.MinPointsInProgram = value; 262 } 263 } 264 265 /// <summary> 266 /// The maximum number of points in an expression produced by the CODE.RAND instruction. 267 /// </summary> 268 public IValueParameter<IntValue> MaxPointsInRandomExpressionParameter 269 { 270 get { return (IValueParameter<IntValue>)Parameters[MaxPointsInRandomInstructionParameterName]; } 271 } 272 273 public int MaxPointsInRandomExpression 274 { 275 get { return config.MaxPointsInRandomExpression; } 276 set 277 { 278 MaxPointsInRandomExpressionParameter.Value.Value = value; 279 config.MaxPointsInRandomExpression = value; 280 } 281 } 282 283 /// <summary> 284 /// When TRUE (which is the default), code passed to the top level of the interpreter 285 /// will be pushed onto the CODE stack prior to execution. 286 /// </summary> 287 public IValueParameter<BoolValue> TopLevelPushCodeParameter 288 { 289 get { return (IValueParameter<BoolValue>)Parameters[TopLevelPushCodeParameterName]; } 290 } 291 292 public bool TopLevelPushCode 293 { 294 get { return config.TopLevelPushCode; } 295 set 296 { 297 TopLevelPushCodeParameter.Value.Value = value; 298 config.TopLevelPushCode = value; 299 } 300 } 301 302 /// <summary> 303 /// When TRUE, the CODE stack will be popped at the end of top level calls to the interpreter. The default is FALSE. 304 /// </summary> 305 public IValueParameter<BoolValue> TopLevelPopCodeParameter 306 { 307 get { return (IValueParameter<BoolValue>)Parameters[TopLevelPopCodeParameterName]; } 308 } 309 310 public bool TopLevelPopCode 311 { 312 get { return config.TopLevelPopCode; } 313 set 314 { 315 TopLevelPopCodeParameter.Value.Value = value; 316 config.TopLevelPopCode = value; 317 } 318 } 319 320 public IValueParameter<IntValue> MaxStringLengthParameter 321 { 322 get { return (IValueParameter<IntValue>)Parameters[MaxStringLengthParameterName]; } 323 } 324 325 public int MaxStringLength 326 { 327 get { return config.MaxStringLength; } 328 set 329 { 330 MaxStringLengthParameter.Value.Value = value; 331 config.MaxStringLength = value; 140 InitProgramLengthParameter.Value.Value = value; 332 141 } 333 142 } … … 339 148 var bestQuality = Maximization ? qualities.Max() : qualities.Min(); 340 149 var bestIdx = Array.IndexOf(qualities, bestQuality); 341 var bestIndividual = individuals[bestIdx].IntegerVector(); 342 343 var isIndividualBetter = AnalyzeBestTrainingSolution(bestIndividual, bestQuality, results, random); 150 var vector = individuals[bestIdx].IntegerVector(); 151 var seed = vector.GetSeed(); 152 var rand = randomPool.Allocate(); 153 rand.Reset(seed); 154 155 var program = vector.ToPushProgram(config, rand); 156 var isIndividualBetter = AnalyzeBestTrainingSolution(program, bestQuality, results, rand); 344 157 345 158 if (isIndividualBetter) { 346 AnalyzeBestTestSolution(bestIndividual, results, random); 347 } 348 } 349 350 private void AnalyzeBestTestSolution(IntegerVector bestIndividual, ResultCollection results, IRandom random) { 351 var program = bestIndividual.ToPushProgram(config, randomPool); 352 var testResult = PushEvaluator.EvaluateTest(pool, program, random); 159 rand.Reset(seed); 160 AnalyzeBestTestSolution(program, results, rand); 161 } 162 163 randomPool.Free(rand); 164 } 165 166 private void AnalyzeBestTestSolution(PushProgram program, ResultCollection results, IRandom random) { 167 var testResult = PushEvaluator.EvaluateTraining(pool, program, random); 353 168 354 169 if (!results.ContainsKey(TestQualityResultName)) { 355 results.Add(new Result(TestQualityResultName, new DoubleValue(testResult. TotalQuality)));170 results.Add(new Result(TestQualityResultName, new DoubleValue(testResult.AvgQuality))); 356 171 } else { 357 ((DoubleValue)results[TestQualityResultName].Value).Value = testResult.TotalQuality; 358 } 359 } 360 361 private bool AnalyzeBestTrainingSolution(IntegerVector bestIndividual, double bestQuality, ResultCollection results, IRandom random) { 362 var solution = CreatePushSolution( 363 bestIndividual, 364 bestQuality, 365 random, 366 config, 367 PushEvaluator); 368 172 ((DoubleValue)results[TestQualityResultName].Value).Value = testResult.AvgQuality; 173 } 174 } 175 176 private bool AnalyzeBestTrainingSolution(PushProgram program, double bestQuality, ResultCollection results, IRandom random) { 369 177 if (!results.ContainsKey(BestTrainingSolutionResultName)) { 178 var solution = CreatePushSolution( 179 program, 180 bestQuality, 181 random, 182 config, 183 PushEvaluator); 184 370 185 results.Add(new Result(BestTrainingSolutionResultName, solution)); 371 186 return true; … … 374 189 var currentBestQuality = ((PushSolution)results[BestTrainingSolutionResultName].Value).Quality; 375 190 376 if (Maximization && currentBestQuality < bestQuality || 377 !Maximization && currentBestQuality > bestQuality) { 378 results[BestTrainingSolutionResultName].Value = solution; 191 if ((!Maximization && currentBestQuality > bestQuality) || 192 (Maximization && currentBestQuality < bestQuality)) { 193 results[BestTrainingSolutionResultName].Value = CreatePushSolution( 194 program, 195 bestQuality, 196 random, 197 config, 198 PushEvaluator); 379 199 return true; 380 200 } … … 383 203 } 384 204 205 private EvaluationResult EvaluateIntegerVector(IntegerVector vector) { 206 var rand = randomPool.Allocate(); 207 var seed = vector.GetSeed(); 208 rand.Reset(seed); 209 210 var program = vector.ToPushProgram(config, rand); 211 var result = PushEvaluator.EvaluateTraining(pool, program, rand); 212 randomPool.Free(rand); 213 214 return result; 215 } 216 385 217 protected abstract PushSolution CreatePushSolution( 386 IntegerVector vector,218 PushProgram program, 387 219 double bestQuality, 388 220 IRandom random, … … 391 223 392 224 public override double Evaluate(Individual individual, IRandom random) { 393 var program = individual.ToPushProgram(config, randomPool);394 var result = PushEvaluator.EvaluateTraining(pool, program, random);225 var vector = individual.IntegerVector(); 226 var result = EvaluateIntegerVector(vector); 395 227 396 228 individual[CaseQualitiesScopeParameterName] = new DoubleArray(result.ExampleQualities); 397 229 398 return result. TotalQuality;230 return result.AvgQuality; 399 231 } 400 232 } -
branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/PushSolution.cs
r14952 r15017 3 3 using Configuration; 4 4 using Core; 5 using Encodings.IntegerVectorEncoding;6 5 using Expressions; 7 6 using Persistence.Default.CompositeSerializers.Storable; … … 12 11 public readonly double Quality; 13 12 [Storable] 14 public readonly IntegerVector IntegerVector;15 [Storable]16 13 public readonly IRandom Random; 17 14 [Storable] … … 21 18 [Storable] 22 19 protected readonly bool simplify; 23 20 [Storable] 24 21 public PushProgram Program; 25 22 26 23 27 public PushSolution( IntegerVector integerVector, double quality, IRandom random, IReadOnlyPushConfiguration config, IPushEvaluator evaluator, bool simplify = false)24 public PushSolution(PushProgram program, double quality, IRandom random, IReadOnlyPushConfiguration config, IPushEvaluator evaluator, bool simplify = false) 28 25 : base("Solution", "A push solution.") { 29 IntegerVector = integerVector;30 26 Quality = quality; 31 27 Random = random; … … 34 30 this.simplify = simplify; 35 31 36 InitProgram(); 37 } 32 Program = simplify 33 ? Simplifier.Simplifier.Simplify(program, Config, p => Evaluator.EvaluateTraining(Config, p, Random).AvgQuality) 34 : program; 38 35 39 private void InitProgram() {40 Program = IntegerVector.ToPushProgram(Config);41 42 if (simplify)43 Program = Simplifier.Simplifier.Simplify(Program, Config, p => Evaluator.EvaluateTraining(Config, p, Random).TotalQuality);44 36 } 45 37 46 38 public PushSolution(PushSolution origin, Cloner cloner) : base(origin, cloner) { 47 IntegerVector = cloner.Clone(origin.IntegerVector);39 Program = cloner.Clone(origin.Program); 48 40 Quality = origin.Quality; 49 41 Random = cloner.Clone(origin.Random); … … 55 47 56 48 public virtual PushSolution Simplify() { 57 return new PushSolution( IntegerVector, Quality, Random, Config, Evaluator, true);49 return new PushSolution(Program, Quality, Random, Config, Evaluator, true); 58 50 } 59 51 60 52 [StorableConstructor] 61 53 protected PushSolution(bool deserializing) : base(deserializing) { } 62 63 [StorableHook(HookType.AfterDeserialization)]64 // ReSharper disable once UnusedMember.Local65 private void AfterDeserialization() {66 InitProgram();67 }68 54 69 55 public override IDeepCloneable Clone(Cloner cloner) {
Note: See TracChangeset
for help on using the changeset viewer.