Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
08/21/17 11:33:53 (7 years ago)
Author:
pkimmesw
Message:

#2665 Testet Problems, Testet error functions, Small fixes, Created HL files

Location:
branches/PushGP/HeuristicLab.PushGP
Files:
1 added
1 deleted
52 edited

Legend:

Unmodified
Added
Removed
  • branches/PushGP/HeuristicLab.PushGP

    • Property svn:ignore
      •  

        old new  
        11*.user
         2packages
         3TestResults
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Analyzer/IndividualZeroErrorAnalyzer.cs

    r15289 r15334  
    2323    private const string RESULT_PARAMETER_NAME = "Zero Error Individuals Per Case";
    2424    private const string RESULT_PARAMETER_DESCRIPTION = "Relative frequency of instructions aggregated over the whole population.";
    25     private const string Y_AXIS_TITLE = "Count of zero error individuals";
     25    private const string Y_AXIS_TITLE = "Relative count of zero error individuals";
    2626    private const string X_AXIS_TITLE = "Case Nr";
    2727    private const string ROW_NAME = "Cases";
     
    134134            YAxisMaximumFixedValue = 1,
    135135            YAxisMinimumAuto = false,
    136             SecondYAxisMaximumAuto = false,
     136            YAxisMaximumAuto = false,
    137137            XAxisMinimumFixedValue = 1,
    138138            XAxisMaximumFixedValue = caseCount,
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Attributes/PushExpressionAttriubte.cs

    r15273 r15334  
    2020    /// Determines the amount of items fetched form the EXEC stack required for this expression. Used for mapping individuals.
    2121    /// </summary>
    22     public readonly uint ExecIn;
     22    public readonly uint RequiredBlockCount;
    2323
    2424    /// <summary>
     
    3232      string description,
    3333      StackTypes additionalStackDependencies = default(StackTypes),
    34       uint execIn = 0,
     34      uint requiredBlockCount = 0,
    3535      bool isHidden = false,
    3636      int inExpressionNr = -1) {
     
    4040      Name = name;
    4141      Description = description;
    42       ExecIn = execIn;
     42      RequiredBlockCount = requiredBlockCount;
    4343      IsHidden = isHidden;
    4444      InExpressionNr = inExpressionNr > 0 ? inExpressionNr : default(int?);
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Configuration/IReadonlyPushConfiguration.cs

    r15289 r15334  
    99    int MaxStringLength { get; }
    1010    int MaxVectorLength { get; }
    11     int MaxPointsInProgram { get; }
     11    int MaxProgramLength { get; }
    1212    int MaxPointsInRandomExpression { get; }
    1313    bool TopLevelPushCode { get; }
    1414    bool TopLevelPopCode { get; }
    15     int MaxParenthesesClose { get; }
    16     double ParenthesesCloseBiasLevel { get; }
     15    int MaxClose { get; }
     16    double CloseBiasLevel { get; }
    1717    IReadOnlyErcOptions ErcOptions { get; }
    1818    string FloatStringFormat { get; }
     19    bool TopLevelPushInputArguments { get; }
    1920
    2021    bool IsStackEnabled(StackTypes stackType);
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Configuration/PushConfiguration.cs

    r15289 r15334  
    11namespace HeuristicLab.Problems.ProgramSynthesis.Push.Configuration {
    22  using System.Collections.Generic;
    3   using Base.Erc;
    4   using Common;
    5   using Persistence.Default.CompositeSerializers.Storable;
     3
     4  using HeuristicLab.Common;
     5  using HeuristicLab.Core;
     6  using HeuristicLab.Data;
     7  using HeuristicLab.Parameters;
     8  using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     9  using HeuristicLab.Problems.ProgramSynthesis.Base.Erc;
    610
    711  [StorableClass]
    812  public class PushConfiguration : PushConfigurationBase, IReadOnlyPushConfiguration {
     13    private const string INSTRUCTIONS_PARAMETER_NAME = "Instructions";
     14    private const string INSTRUCTIONS_PARAMETER_DESCRIPTION = "Enables/Disables Instructions";
     15    private const string EVAL_PUSH_LIMIT_PARAMETER_NAME = "EvalPushLimit";
     16    private const string EVAL_PUSH_LIMIT_PARAMETER_DESCRIPTION = "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).";
     17    private const string MIN_PROGRAM_LENGTH = "MinProgramLength";
     18    private const string MIN_PROGRAM_LENGTH_PARAMETER_DESCRIPTION = "This is the minium 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.";
     19    private const string MAX_PROGRAM_LENGTH = "MaxProgramLength";
     20    private const string MAX_PROGRAM_LENGTH_PARAMETER_DESCRIPTION = "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.";
     21    private const string TOP_LEVEL_PUSH_CODE_PARAMETER_NAME = "TopLevelPushCode";
     22    private const string TOP_LEVEL_PUSH_CODE_PARAMETER_DESCRIPTION = "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.";
     23    private const string TOP_LEVEL_POP_CODE_PARAMETER_NAME = "TopLevelPopCode";
     24    private const string TOP_LEVEL_POP_CODE_PARAMETER_DESCRIPTION = "When TRUE, the CODE stack will be popped at the end of top level calls to the interpreter. The default is FALSE.";
     25    private const string MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_NAME = "MaxPointsInRandomInstruction";
     26    private const string MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_DESCRIPTION = "MaxPointsInRandomInstruction";
     27    private const string ERC_OPTIONS_PARAMETER_NAME = "ERC options";
     28    private const string MAX_STRING_LENGTH_PARAMETER_NAME = "Max. string length of string literals";
     29    private const string MAX_DEPTH_PARAMETER_NAME = "Max. depth of a Push program";
     30    private const string MAX_CLOSE_PARAMETER_NAME = "Max. close";
     31    private const string MAX_PARENTHESES_CLOSE_PARAMETER_DESCRIPTION = "Specifies how many sub programs are max. closed if open during the recursive translation of an individual to a push program. Value is exclusive.";
     32    private const string CLOSE_BIAS_LEVEL_PARAMETER_NAME = "Close bias level";
     33    private const string PARENTHESES_CLOSE_BIAS_LEVEL_PARAMETER_DESCRIPTION = "Specifies how strong a random value between 0 .. 'Max. parentheses close' is biased towards 0. In other words, this parameter controls the length of sub programs.";
     34    private const string MAX_VECTOR_LENGTH_PARAMETER_NAME = "Max. vector length";
     35    private const string TOP_LEVEL_PUSH_INPUT_ARGUMENTS = "TopLevelPushInputArguments";
     36
    937    public PushConfiguration() {
    10       Name = "Push Configuration";
    11 
    12       ErcOptions = new ErcOptions();
    13       EvalPushLimit = 1024;
    14       MinPointsInProgram = 25;
    15       MaxPointsInProgram = 200;
    16       TopLevelPushCode = true;
    17       TopLevelPopCode = false;
    18       MaxPointsInRandomExpression = 64;
    19       MaxStringLength = 1000;
    20       MaxVectorLength = 500;
    21       MaxDepth = 100;
     38      Parameters = new ParameterCollection();
     39      InitParameters();
     40
    2241      FloatStringFormat = "R";
    23       MaxParenthesesClose = 4;
    24       ParenthesesCloseBiasLevel = 1;
    25     }
    26 
     42    }
     43
     44    public PushConfiguration(PushConfiguration origin, Cloner cloner) : base(origin, cloner) {
     45      Parameters = cloner.Clone(origin.Parameters);
     46    }
     47
     48    public override IDeepCloneable Clone(Cloner cloner) {
     49      return new PushConfiguration(this, cloner);
     50    }
    2751
    2852    [StorableConstructor]
    29     public PushConfiguration(bool deserializing)
    30       : base(deserializing) {
    31     }
    32 
    33     public PushConfiguration(PushConfiguration origin, Cloner cloner) : base(origin, cloner) {
    34 
    35       ErcOptions = cloner.Clone(origin.ErcOptions);
    36       EvalPushLimit = origin.EvalPushLimit;
    37       MinPointsInProgram = origin.MinPointsInProgram;
    38       MaxPointsInProgram = origin.MaxPointsInProgram;
    39       MaxPointsInRandomExpression = origin.MaxPointsInRandomExpression;
    40       TopLevelPushCode = origin.TopLevelPushCode;
    41       TopLevelPopCode = origin.TopLevelPopCode;
    42       MaxStringLength = origin.MaxStringLength;
    43       MaxVectorLength = origin.MaxVectorLength;
    44       MaxDepth = origin.MaxDepth;
    45       FloatStringFormat = origin.FloatStringFormat;
    46       MaxParenthesesClose = origin.MaxParenthesesClose;
    47       ParenthesesCloseBiasLevel = origin.ParenthesesCloseBiasLevel;
    48     }
     53    protected PushConfiguration(bool deserialize) { }
     54
     55    [StorableHook(HookType.AfterDeserialization)]
     56    // ReSharper disable once UnusedMember.Local
     57    private void AfterDeserialization() {
     58      InitParameters();
     59    }
     60
     61    [Storable]
     62    public ParameterCollection Parameters { get; private set; }
    4963
    5064    [Storable]
    5165    public string FloatStringFormat { get; set; }
    5266
    53 
    54     IReadOnlyList<string> IReadOnlyExpressionsConfiguration.EnabledExpressions { get { return enabledExpressions; } }
    55 
    56     [Storable]
    57     public int MaxParenthesesClose { get; set; }
    58     [Storable]
    59     public double ParenthesesCloseBiasLevel { get; set; }
    60 
    61 
    62     [Storable]
    63     public ErcOptions ErcOptions { get; set; }
    64 
    65     IReadOnlyErcOptions IReadOnlyPushConfiguration.ErcOptions { get { return ErcOptions; } }
     67    private void InitParameters() {
     68      if (!Parameters.ContainsKey(INSTRUCTIONS_PARAMETER_NAME))
     69        Parameters.Add(new ValueParameter<IExpressionsConfiguration>(
     70          INSTRUCTIONS_PARAMETER_NAME,
     71          INSTRUCTIONS_PARAMETER_DESCRIPTION,
     72          this));
     73
     74      if (!Parameters.ContainsKey(ERC_OPTIONS_PARAMETER_NAME))
     75        Parameters.Add(new ValueParameter<ErcOptions>(ERC_OPTIONS_PARAMETER_NAME));
     76
     77      if (!Parameters.ContainsKey(MAX_VECTOR_LENGTH_PARAMETER_NAME))
     78        Parameters.Add(new FixedValueParameter<IntValue>(
     79          MAX_VECTOR_LENGTH_PARAMETER_NAME,
     80          new IntValue(500)) { Hidden = true });
     81
     82      if (!Parameters.ContainsKey(EVAL_PUSH_LIMIT_PARAMETER_NAME))
     83        Parameters.Add(new FixedValueParameter<IntValue>(
     84          EVAL_PUSH_LIMIT_PARAMETER_NAME,
     85          EVAL_PUSH_LIMIT_PARAMETER_DESCRIPTION,
     86          new IntValue(1000)));
     87
     88      if (!Parameters.ContainsKey(MAX_PROGRAM_LENGTH))
     89        Parameters.Add(new FixedValueParameter<IntValue>(
     90          MAX_PROGRAM_LENGTH,
     91          MAX_PROGRAM_LENGTH_PARAMETER_DESCRIPTION,
     92          new IntValue(200)));
     93
     94      if (!Parameters.ContainsKey(MIN_PROGRAM_LENGTH))
     95        Parameters.Add(new FixedValueParameter<IntValue>(
     96          MIN_PROGRAM_LENGTH,
     97          MIN_PROGRAM_LENGTH_PARAMETER_DESCRIPTION,
     98          new IntValue(0)) { Hidden = true });
     99
     100      if (!Parameters.ContainsKey(MAX_CLOSE_PARAMETER_NAME))
     101        Parameters.Add(new FixedValueParameter<IntValue>(
     102          MAX_CLOSE_PARAMETER_NAME,
     103          MAX_PARENTHESES_CLOSE_PARAMETER_DESCRIPTION,
     104          new IntValue(4)) { Hidden = false });
     105
     106      if (!Parameters.ContainsKey(CLOSE_BIAS_LEVEL_PARAMETER_NAME))
     107        Parameters.Add(new FixedValueParameter<DoubleValue>(
     108          CLOSE_BIAS_LEVEL_PARAMETER_NAME,
     109          PARENTHESES_CLOSE_BIAS_LEVEL_PARAMETER_DESCRIPTION,
     110          new DoubleValue(3)) { Hidden = false });
     111
     112      if (!Parameters.ContainsKey(TOP_LEVEL_PUSH_CODE_PARAMETER_NAME))
     113        Parameters.Add(new FixedValueParameter<BoolValue>(
     114          TOP_LEVEL_PUSH_CODE_PARAMETER_NAME,
     115          TOP_LEVEL_PUSH_CODE_PARAMETER_DESCRIPTION,
     116          new BoolValue(true)) { Hidden = true });
     117
     118      if (!Parameters.ContainsKey(TOP_LEVEL_POP_CODE_PARAMETER_NAME))
     119        Parameters.Add(new FixedValueParameter<BoolValue>(
     120          TOP_LEVEL_POP_CODE_PARAMETER_NAME,
     121          TOP_LEVEL_POP_CODE_PARAMETER_DESCRIPTION,
     122          new BoolValue(false)) { Hidden = true });
     123
     124      if (!Parameters.ContainsKey(MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_NAME))
     125        Parameters.Add(new FixedValueParameter<IntValue>(
     126          MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_NAME,
     127          MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_DESCRIPTION,
     128          new IntValue(50)) { Hidden = true });
     129
     130      if (!Parameters.ContainsKey(MAX_STRING_LENGTH_PARAMETER_NAME))
     131        Parameters.Add(new FixedValueParameter<IntValue>(
     132          MAX_STRING_LENGTH_PARAMETER_NAME,
     133          new IntValue(1000)) { Hidden = true });
     134
     135      if (!Parameters.ContainsKey(MAX_DEPTH_PARAMETER_NAME))
     136        Parameters.Add(new FixedValueParameter<IntValue>(
     137          MAX_DEPTH_PARAMETER_NAME,
     138          new IntValue(1000)) { Hidden = true });
     139
     140      if (!Parameters.ContainsKey(TOP_LEVEL_PUSH_INPUT_ARGUMENTS))
     141        Parameters.Add(new FixedValueParameter<BoolValue>(
     142          TOP_LEVEL_PUSH_INPUT_ARGUMENTS,
     143          new BoolValue(true)) { Hidden = false });
     144    }
     145
     146    public IValueParameter<IExpressionsConfiguration> InstructionsParameter
     147    {
     148      get { return (IValueParameter<IExpressionsConfiguration>)Parameters[INSTRUCTIONS_PARAMETER_NAME]; }
     149    }
     150
     151    public IExpressionsConfiguration Instructions
     152    {
     153      get { return InstructionsParameter.Value; }
     154      set { InstructionsParameter.Value = value; }
     155    }
     156
     157    public IValueParameter<ErcOptions> ErcOptionsParameter
     158    {
     159      get { return (IValueParameter<ErcOptions>)Parameters[ERC_OPTIONS_PARAMETER_NAME]; }
     160    }
     161
     162    public ErcOptions ErcOptions
     163    {
     164      get { return ErcOptionsParameter.Value; }
     165      set
     166      {
     167        ErcOptionsParameter.Value = value;
     168      }
     169    }
     170
     171    IReadOnlyList<string> IReadOnlyExpressionsConfiguration.EnabledExpressions
     172    {
     173      get
     174      {
     175        return enabledExpressions;
     176      }
     177    }
     178
     179    IReadOnlyErcOptions IReadOnlyPushConfiguration.ErcOptions
     180    {
     181      get
     182      {
     183        return ErcOptions;
     184      }
     185    }
    66186
    67187    /// <summary>
     
    74194    ///     is up to the calling program.
    75195    /// </summary>
    76     [Storable]
    77     public int EvalPushLimit { get; set; }
     196    public IValueParameter<IntValue> EvalPushLimitParameter
     197    {
     198      get { return (IValueParameter<IntValue>)Parameters[EVAL_PUSH_LIMIT_PARAMETER_NAME]; }
     199    }
     200
     201    public int EvalPushLimit
     202    {
     203      get { return EvalPushLimitParameter.Value.Value; }
     204      set { EvalPushLimitParameter.Value.Value = value; }
     205    }
     206
     207
     208    /// <summary>
     209    /// Determines the likelihood of smaller or bigger values.
     210    /// x greater than 1 means that result is biased towards min.
     211    /// x smaller than 1 means that result is biased towards max.
     212    /// </summary>
     213    public IValueParameter<DoubleValue> CloseBiasLevelParameter
     214    {
     215      get { return (IValueParameter<DoubleValue>)Parameters[CLOSE_BIAS_LEVEL_PARAMETER_NAME]; }
     216    }
     217
     218    public double CloseBiasLevel
     219    {
     220      get { return CloseBiasLevelParameter.Value.Value; }
     221      set { CloseBiasLevelParameter.Value.Value = value; }
     222    }
     223
     224    /// <summary>
     225    /// Determines the maximum of blocks which will be closed.
     226    /// </summary>
     227    public IValueParameter<IntValue> MaxCloseParameter
     228    {
     229      get { return (IValueParameter<IntValue>)Parameters[MAX_CLOSE_PARAMETER_NAME]; }
     230    }
     231
     232    public int MaxClose
     233    {
     234      get { return MaxCloseParameter.Value.Value; }
     235      set
     236      {
     237        MaxCloseParameter.Value.Value = value;
     238      }
     239    }
    78240
    79241    /// <summary>
    80242    /// This is the maximum of depth a push program can have. Expressions, which lead to exceed this limit are interpreted as NOOP.
    81243    /// </summary>
    82     [Storable]
    83     public int MaxDepth { get; set; }
    84 
    85     /// <summary>
    86     ///     This is the minimum size of an item on the CODE stack, expressed as a number of points.
    87     ///     A point is an instruction, a literal, or a pair of parentheses. Any instruction that would cause this limit to be
    88     ///     exceeded should instead act as a NOOP, leaving all stacks in the states that they were in before the execution of the
    89     ///     instruction.
    90     /// </summary>
    91     [Storable]
    92     public int MinPointsInProgram { get; set; }
     244    public IValueParameter<IntValue> MaxDepthParameter
     245    {
     246      get { return (IValueParameter<IntValue>)Parameters[MAX_DEPTH_PARAMETER_NAME]; }
     247    }
     248
     249    public int MaxDepth
     250    {
     251      get { return MaxDepthParameter.Value.Value; }
     252      set
     253      {
     254        MaxDepthParameter.Value.Value = value;
     255      }
     256    }
     257
     258    public IValueParameter<IntValue> MinProgramLengthParameter
     259    {
     260      get { return (IValueParameter<IntValue>)Parameters[MIN_PROGRAM_LENGTH]; }
     261    }
     262
     263    public int MinProgramLength
     264    {
     265      get { return MinProgramLengthParameter.Value.Value; }
     266      set
     267      {
     268        MinProgramLengthParameter.Value.Value = value;
     269      }
     270    }
    93271
    94272    /// <summary>
     
    98276    ///     instruction.
    99277    /// </summary>
    100     [Storable]
    101     public int MaxPointsInProgram { get; set; }
     278    public IValueParameter<IntValue> MaxProgramLengthParameter
     279    {
     280      get { return (IValueParameter<IntValue>)Parameters[MAX_PROGRAM_LENGTH]; }
     281    }
     282
     283    public int MaxProgramLength
     284    {
     285      get { return MaxProgramLengthParameter.Value.Value; }
     286      set
     287      {
     288        MaxProgramLengthParameter.Value.Value = value;
     289      }
     290    }
     291
     292    public IValueParameter<IntValue> MaxVectorLengthParameter
     293    {
     294      get { return (IValueParameter<IntValue>)Parameters[MAX_VECTOR_LENGTH_PARAMETER_NAME]; }
     295    }
     296
     297    public int MaxVectorLength
     298    {
     299      get { return MaxVectorLengthParameter.Value.Value; }
     300      set { MaxVectorLengthParameter.Value.Value = value; }
     301    }
    102302
    103303    /// <summary>
    104304    ///     The maximum number of points in an expression produced by the CODE.RAND instruction.
    105305    /// </summary>
    106     [Storable]
    107     public int MaxPointsInRandomExpression { get; set; }
     306    public IValueParameter<IntValue> MaxPointsInRandomExpressionParameter
     307    {
     308      get { return (IValueParameter<IntValue>)Parameters[MAX_POINTS_IN_RANDOM_INSTRUCTION_PARAMETER_NAME]; }
     309    }
     310
     311    public int MaxPointsInRandomExpression
     312    {
     313      get { return MaxPointsInRandomExpressionParameter.Value.Value; }
     314      set
     315      {
     316        MaxPointsInRandomExpressionParameter.Value.Value = value;
     317      }
     318    }
    108319
    109320    /// <summary>
     
    111322    ///     will be pushed onto the CODE stack prior to execution.
    112323    /// </summary>
    113     [Storable]
    114     public bool TopLevelPushCode { get; set; }
     324    public IValueParameter<BoolValue> TopLevelPushCodeParameter
     325    {
     326      get { return (IValueParameter<BoolValue>)Parameters[TOP_LEVEL_PUSH_CODE_PARAMETER_NAME]; }
     327    }
     328
     329    public bool TopLevelPushCode
     330    {
     331      get { return TopLevelPushCodeParameter.Value.Value; }
     332      set
     333      {
     334        TopLevelPushCodeParameter.Value.Value = value;
     335      }
     336    }
    115337
    116338    /// <summary>
    117339    ///     When TRUE, the CODE stack will be popped at the end of top level calls to the interpreter. The default is FALSE.
    118340    /// </summary>
    119     [Storable]
    120     public bool TopLevelPopCode { get; set; }
    121 
    122     [Storable]
    123     public int MaxStringLength { get; set; }
    124 
    125     [Storable]
    126     public int MaxVectorLength { get; set; }
    127 
    128     public override IDeepCloneable Clone(Cloner cloner) {
    129       return new PushConfiguration(this, cloner);
     341    public IValueParameter<BoolValue> TopLevelPopCodeParameter
     342    {
     343      get { return (IValueParameter<BoolValue>)Parameters[TOP_LEVEL_POP_CODE_PARAMETER_NAME]; }
     344    }
     345
     346    public bool TopLevelPopCode
     347    {
     348      get { return TopLevelPopCodeParameter.Value.Value; }
     349      set
     350      {
     351        TopLevelPopCodeParameter.Value.Value = value;
     352      }
     353    }
     354
     355    public IValueParameter<IntValue> MaxStringLengthParameter
     356    {
     357      get { return (IValueParameter<IntValue>)Parameters[MAX_STRING_LENGTH_PARAMETER_NAME]; }
     358    }
     359
     360    public int MaxStringLength
     361    {
     362      get { return MaxStringLengthParameter.Value.Value; }
     363      set { MaxStringLengthParameter.Value.Value = value; }
     364    }
     365
     366    public IValueParameter<BoolValue> TopLevelPushInputArgumentsParameter
     367    {
     368      get { return (IValueParameter<BoolValue>)Parameters[TOP_LEVEL_PUSH_INPUT_ARGUMENTS]; }
     369    }
     370
     371    public bool TopLevelPushInputArguments
     372    {
     373      get { return TopLevelPushInputArgumentsParameter.Value.Value; }
     374      set { TopLevelPushInputArgumentsParameter.Value.Value = value; }
    130375    }
    131376  }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Crossover/AlternationCrossover.cs

    r15289 r15334  
    3131      ChildParameter.ActualName = "PlushVector";
    3232
     33      Parameters.Add(new LookupParameter<IntValue>("MaxProgramLength", "The max length of children"));
     34
    3335      Parameters.Add(new FixedValueParameter<PercentValue>("AlternationRate", "Specifies the probability of switching to another parent.", new PercentValue(0.5)));
    3436      Parameters.Add(new FixedValueParameter<DoubleValue>("AlignmentDeviation", "When alternating between parents, the index at which to continue copying may be offset backward or forward some amount based on a random sample from a normal distribution with mean 0 and standard deviation set by the alignment deviation parameter", new DoubleValue(1.0)));
    35       Parameters.Add(new FixedValueParameter<IntValue>("MaxLength", "The max length of a children", new IntValue(100)));
     37
    3638    }
    3739
     
    4749    }
    4850
    49     public IValueParameter<IntValue> MaxLengthParameter
     51    public ILookupParameter<IntValue> MaxProgramLengthParameter
    5052    {
    51       get { return (IValueParameter<IntValue>)Parameters["MaxLength"]; }
     53      get { return (ILookupParameter<IntValue>)Parameters["MaxProgramLength"]; }
    5254    }
    5355
    54     public int MaxLength
     56    public int MaxProgramLength
    5557    {
    56       get { return MaxLengthParameter.Value.Value; }
    57       set { MaxLengthParameter.Value.Value = value; }
     58      get { return MaxProgramLengthParameter.ActualValue.Value; }
     59      set { MaxProgramLengthParameter.ActualValue.Value = value; }
    5860    }
    5961
     
    98100        ParentsParameter.ActualValue,
    99101        AlternationRate,
    100         MaxLength,
     102        MaxProgramLength,
    101103        AlignmentDeviation);
    102104      return base.InstrumentedApply();
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Data/Pool/IPooledObject.cs

    r15189 r15334  
    11namespace HeuristicLab.Problems.ProgramSynthesis.Push.Data.Pool {
    22  public interface IPooledObject {
    3     void Init();
    43    void Reset();
    54  }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Data/Pool/ManagedPoolProvider.cs

    r15189 r15334  
    77  using System.Reflection;
    88  using System.Runtime.Serialization.Formatters.Binary;
     9
     10  using Microsoft.IO;
    911
    1012  public interface IManagedPool<T> : IDisposable where T : class, IPooledObject {
     
    1719    private readonly ObjectPool<IManagedPool<T>> managedPools;
    1820    private readonly BinaryFormatter binaryFormatter = new BinaryFormatter();
     21    private readonly RecyclableMemoryStreamManager recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();
    1922    private byte[] dummyPartition;
    20     private static volatile object dummyCreationLockObject = new object();
     23    private volatile object dummyCreationLockObject = new object();
    2124
    2225    private static readonly FieldInfo InternalListArrayProperty = typeof(List<T[]>).GetField(
     
    5659
    5760    private T[] CloneDummyPartition() {
     61      // init dummy partition
    5862      if (dummyPartition == null) {
    5963        lock (dummyCreationLockObject) {
     
    6569            }
    6670
    67             using (var memoryStream = new MemoryStream()) {
    68               binaryFormatter.Serialize(memoryStream, temp);
    69               dummyPartition = memoryStream.ToArray();
     71            using (var ms = recyclableMemoryStreamManager.GetStream("dummyPartition")) {
     72              binaryFormatter.Serialize(ms, temp);
     73              dummyPartition = ms.ToArray();
    7074            }
    7175          }
     
    7377      }
    7478
    75       using (var memoryStream = new MemoryStream(dummyPartition)) {
    76         memoryStream.Seek(0, SeekOrigin.Begin);
    77 
    78         var result = (T[])binaryFormatter.Deserialize(memoryStream);
    79 
    80         for (var i = 0; i < result.Length; i++)
    81           result[i].Init();
    82 
     79      using (var ms = recyclableMemoryStreamManager.GetStream("dummyPartition", dummyPartition, 0, dummyPartition.Length)) {
     80        ms.Seek(0, SeekOrigin.Begin);
     81        var result = (T[])binaryFormatter.Deserialize(ms);
    8382        return result;
    8483      }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Data/Pool/PooledList.cs

    r15189 r15334  
    66  [Serializable]
    77  public class PooledList<T> : List<T>, IPooledObject {
    8     public Guid Id { get; private set; }
    9 
    10     void IPooledObject.Init() {
    11       Id = Guid.NewGuid();
    12     }
    138
    149    void IPooledObject.Reset() {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Data/Pool/PooledObject.cs

    r15189 r15334  
    2020    }
    2121
    22     void IPooledObject.Init() { }
    23 
    2422    public void Reset() {
    2523      resetor(item);
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Encoding/PlushEncoding.cs

    r15289 r15334  
    2727      minLengthParameter = new FixedValueParameter<IntValue>(Name + ".MinLength", new IntValue(25));
    2828      maxLengthParameter = new FixedValueParameter<IntValue>(Name + ".MaxLength", new IntValue(100));
    29       minCloseParameter = new FixedValueParameter<IntValue>(Name + ".MinClose", new IntValue(0));
    3029      maxCloseParameter = new FixedValueParameter<IntValue>(Name + ".MaxClose", new IntValue(3));
    3130      closeBiasLevelParameter = new FixedValueParameter<DoubleValue>(Name + ".CloseBiasLevel", new DoubleValue(3d));
    3231      instructionsParameter = new ValueParameter<IExpressionsConfiguration>(Name + ".Instructions");
    3332      ercOptionsParameter = new ValueParameter<ErcOptions>(Name + ".ErcOptions");
    34       inInstructionProbabilityParameter = new FixedValueParameter<PercentValue>(Name + ".InInstructionProbability");
     33      inInstructionProbabilityParameter = new FixedValueParameter<PercentValue>(Name + ".InInstructionProbability", new PercentValue(0.1));
    3534
    3635      Parameters.Add(minLengthParameter);
    3736      Parameters.Add(maxLengthParameter);
    38       Parameters.Add(minCloseParameter);
    3937      Parameters.Add(maxCloseParameter);
    4038      Parameters.Add(closeBiasLevelParameter);
     
    7876      ConfigureOperators(Operators);
    7977    }
    80     private void OnMinCloseParameterChanged() {
    81       RegisterMinCloseParameterEvents();
    82       ConfigureOperators(Operators);
    83     }
    8478    private void OnMaxCloseParameterChanged() {
    8579      RegisterMaxCloseParameterEvents();
     
    106100      RegisterMinLengthParameterEvents();
    107101      RegisterMaxLengthParameterEvents();
    108       RegisterMinCloseParameterEvents();
    109102      RegisterMaxCloseParameterEvents();
    110103      RegisterCloseBiasLevelParameterEvents();
     
    124117    }
    125118
    126     private void RegisterMinCloseParameterEvents() {
    127       MinCloseParameter.ValueChanged += (o, s) => ConfigureOperators(Operators);
    128       MinCloseParameter.Value.ValueChanged += (o, s) => ConfigureOperators(Operators);
    129     }
    130 
    131119    private void RegisterMaxCloseParameterEvents() {
    132120      MaxCloseParameter.ValueChanged += (o, s) => ConfigureOperators(Operators);
     
    156144    #region Encoding Parameters
    157145    [Storable]
    158     private IFixedValueParameter<IntValue> minLengthParameter;
    159     public IFixedValueParameter<IntValue> MinLengthParameter
     146    private IValueParameter<IntValue> minLengthParameter;
     147    public IValueParameter<IntValue> MinLengthParameter
    160148    {
    161149      get { return minLengthParameter; }
     
    174162
    175163    [Storable]
    176     private IFixedValueParameter<IntValue> maxLengthParameter;
    177     public IFixedValueParameter<IntValue> MaxLengthParameter
     164    private IValueParameter<IntValue> maxLengthParameter;
     165    public IValueParameter<IntValue> MaxLengthParameter
    178166    {
    179167      get { return maxLengthParameter; }
     
    192180
    193181    [Storable]
    194     private IFixedValueParameter<IntValue> minCloseParameter;
    195     public IFixedValueParameter<IntValue> MinCloseParameter
    196     {
    197       get { return minCloseParameter; }
    198       set
    199       {
    200         if (value == null) throw new ArgumentNullException("Min close parameter must not be null.");
    201         if (value.Value == null) throw new ArgumentNullException("Min close parameter value must not be null.");
    202         if (minCloseParameter == value) return;
    203 
    204         if (minCloseParameter != null) Parameters.Remove(minCloseParameter);
    205         minCloseParameter = value;
    206         Parameters.Add(minCloseParameter);
    207         OnMinCloseParameterChanged();
    208       }
    209     }
    210 
    211     [Storable]
    212     private IFixedValueParameter<IntValue> maxCloseParameter;
    213     public IFixedValueParameter<IntValue> MaxCloseParameter
     182    private IValueParameter<IntValue> maxCloseParameter;
     183    public IValueParameter<IntValue> MaxCloseParameter
    214184    {
    215185      get { return maxCloseParameter; }
     
    228198
    229199    [Storable]
    230     private IFixedValueParameter<DoubleValue> closeBiasLevelParameter;
    231     public IFixedValueParameter<DoubleValue> CloseBiasLevelParameter
     200    private IValueParameter<DoubleValue> closeBiasLevelParameter;
     201    public IValueParameter<DoubleValue> CloseBiasLevelParameter
    232202    {
    233203      get { return closeBiasLevelParameter; }
     
    246216
    247217    [Storable]
    248     private IFixedValueParameter<PercentValue> inInstructionProbabilityParameter;
    249     public IFixedValueParameter<PercentValue> InInstructionProbabilityParameter
     218    private IValueParameter<PercentValue> inInstructionProbabilityParameter;
     219    public IValueParameter<PercentValue> InInstructionProbabilityParameter
    250220    {
    251221      get { return inInstructionProbabilityParameter; }
     
    321291    }
    322292
    323     public int MinClose
    324     {
    325       get { return MinCloseParameter.Value.Value; }
    326       set { MinCloseParameter.Value.Value = value; }
    327     }
    328 
    329293    public int MaxClose
    330294    {
     
    341305
    342306    #region Operator Discovery
    343     private static readonly IEnumerable<Type> encodingSpecificOperatorTypes;
     307    private static readonly IEnumerable<Type> EncodingSpecificOperatorTypes;
    344308    static PlushEncoding() {
    345       encodingSpecificOperatorTypes = new List<Type>() {
     309      EncodingSpecificOperatorTypes = new List<Type>() {
    346310        typeof (IPlushOperator),
    347311        typeof (IPlushCreator),
     
    353317    private void DiscoverOperators() {
    354318      var assembly = typeof(IPlushOperator).Assembly;
    355       var discoveredTypes = ApplicationManager.Manager.GetTypes(encodingSpecificOperatorTypes, assembly, true, false, false);
     319      var discoveredTypes = ApplicationManager.Manager.GetTypes(EncodingSpecificOperatorTypes, assembly, true, false, false);
    356320      var operators = discoveredTypes.Select(t => (IOperator)Activator.CreateInstance(t));
    357321      var newOperators = operators.Except(Operators, new TypeEqualityComparer<IOperator>()).ToList();
     
    374338        creator.MinLengthParameter.ActualName = MinLengthParameter.Name;
    375339        creator.MaxLengthParameter.ActualName = MaxLengthParameter.Name;
    376         creator.MinCloseParameter.ActualName = MinCloseParameter.Name;
    377         creator.MaxCloseParameter.ActualName = MinCloseParameter.Name;
     340        creator.MaxCloseParameter.ActualName = MaxCloseParameter.Name;
    378341        creator.CloseBiasLevelParameter.ActualName = CloseBiasLevelParameter.Name;
    379342        creator.ErcOptionsParameter.ActualName = ErcOptionsParameter.Name;
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Encoding/PlushEntry.cs

    r15275 r15334  
    99    public PlushEntry() { }
    1010
     11    public PlushEntry(Expression instruction = null, int close = 0, bool silent = false) {
     12      Instruction = instruction;
     13      Close = close;
     14      Silent = silent;
     15    }
     16
     17    [StorableConstructor]
    1118    public PlushEntry(bool deserializing) : base(deserializing) { }
    1219
     
    1421      Instruction = cloner.Clone(origin.Instruction);
    1522      Close = origin.Close;
     23      Silent = origin.Silent;
    1624    }
    1725
     
    2028    [Storable]
    2129    public int Close { get; set; }
     30    [Storable]
     31    public bool Silent { get; set; }
    2232
    2333    public override IDeepCloneable Clone(Cloner cloner) {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Encoding/PlushVector.cs

    r15289 r15334  
    11namespace HeuristicLab.Problems.ProgramSynthesis.Push.Encoding {
    22  using System.Collections.Generic;
    3 
    43  using HeuristicLab.Common;
    54  using HeuristicLab.Core;
     
    98
    109  [StorableClass]
    11   public class PlushVector : Item {
     10  public sealed class PlushVector : Item {
    1211
    1312    [Storable]
     
    2221
    2322    [StorableConstructor]
    24     public PlushVector(bool deserializing) : base(deserializing) {
     23    private PlushVector(bool deserializing) : base(deserializing) {
    2524    }
    2625
    2726    public PlushVector(PlushVector origin, Cloner cloner) : base(origin, cloner) {
    28       entries = new List<PlushEntry>(origin.entries);
     27      entries = new List<PlushEntry>(origin.entries.Count);
     28      for (var i = 0; i < origin.entries.Count; i++) {
     29        entries.Add(cloner.Clone(origin.entries[i]));
     30      }
     31
    2932      pushProgram = origin.pushProgram;
    3033    }
     
    6265      var instructions = new List<Expression>();
    6366
    64       for (var i = currentIndex; i < entries.Count; i++) {
    65         var entry = entries[i];
     67      for (; currentIndex < entries.Count; currentIndex++) {
     68        var entry = entries[currentIndex];
     69
     70        if (entry.Silent)
     71          continue;
     72
     73        close += entry.Close;
     74        instructions.Add(entry.Instruction);
     75
     76        PushExpressionAttribute attribute;
    6677        var instructionType = entry.Instruction.GetType();
    6778
    68         close += entry.Close;
    69 
    70         PushExpressionAttribute attribute;
    7179        if (ExpressionTable.TypeToAttributeTable.TryGetValue(instructionType, out attribute)) {
    72           for (var blockIdx = 0u; blockIdx < attribute.ExecIn && currentIndex < entries.Count; blockIdx++) {
    73             if (close != 0) {
     80          for (var blockIdx = 0u; blockIdx < attribute.RequiredBlockCount; blockIdx++) {
     81            if (close == 0 && currentIndex < entries.Count) {
     82              currentIndex++;
     83              var subProgram = FromPlush(ref currentIndex, ref close, depth + 1);
     84              instructions.Add(subProgram);
     85            } else {
    7486              close--;
    7587              instructions.Add(PushProgram.Empty);
    76             } else {
    77               currentIndex++;
    78               var subProgram = FromPlush(ref currentIndex, ref close, depth + 1);
    79               var subExpression = subProgram.Count == 1 ? subProgram.Expressions[0] : subProgram;
    80 
    81               instructions.Add(subExpression);
    8288            }
    8389          }
    8490        }
    85 
    86         instructions.Add(entry.Instruction);
    8791
    8892        if (close > 0 && depth > 0) {
     
    96100      }
    97101
     102      instructions.Reverse();
    98103      return new PushProgram(instructions);
    99104    }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Evaluator/PushBenchmarkSuiteEvaluator.cs

    r15289 r15334  
    33  using System.Collections.Generic;
    44  using System.Globalization;
     5  using System.Linq;
    56
    67  using HeuristicLab.BenchmarkSuite;
     
    910  using HeuristicLab.Parameters;
    1011  using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     12  using HeuristicLab.Problems.ProgramSynthesis.Base.Extensions;
    1113  using HeuristicLab.Problems.ProgramSynthesis.Push.Configuration;
    1214  using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions;
     
    1820  public class PushBenchmarkSuiteEvaluator : ParameterizedNamedItem, IPushEvaluator {
    1921
    20     private const string DataBoundsParameterName = "DataBounds";
    21     private const string DataParameterName = "Data";
    22     private const string DataParameterDescription = "Program Synthesis";
     22    private const string DATA_BOUNDS_PARAMETER_NAME = "DataBounds";
     23    private const string DATA_PARAMETER_NAME = "Data";
     24    private const string DATA_PARAMETER_DESCRIPTION = "Program Synthesis";
    2325
    2426    public PushBenchmarkSuiteEvaluator() {
    25       Parameters.Add(new FixedValueParameter<DataBounds>(DataBoundsParameterName));
     27      Parameters.Add(new FixedValueParameter<DataBounds>(DATA_BOUNDS_PARAMETER_NAME));
    2628
    2729      Parameters.Add(new ValueParameter<ProblemData>(
    28         DataParameterName,
    29         DataParameterDescription));
     30        DATA_PARAMETER_NAME,
     31        DATA_PARAMETER_DESCRIPTION));
    3032    }
    3133
     
    4749    public IValueParameter<ProblemData> DataParameter
    4850    {
    49       get { return (IValueParameter<ProblemData>)Parameters[DataParameterName]; }
     51      get { return (IValueParameter<ProblemData>)Parameters[DATA_PARAMETER_NAME]; }
    5052    }
    5153
     
    5860    public IValueParameter<DataBounds> DataBoundsParameter
    5961    {
    60       get { return (IValueParameter<DataBounds>)Parameters[DataBoundsParameterName]; }
     62      get { return (IValueParameter<DataBounds>)Parameters[DATA_BOUNDS_PARAMETER_NAME]; }
    6163    }
    6264
     
    131133
    132134      switch (Data.ProblemType) {
     135        // special
    133136        case ProblemType.NumberIO: return NumberIo(interpreter, example);
    134         case ProblemType.Median: return Median(interpreter, example);
     137        case ProblemType.StringDifferences: return StringDifferences(interpreter, example);
     138        case ProblemType.EvenSquares: return EvenSquares(interpreter, example);
     139        case ProblemType.WallisPi: return WallisPi(interpreter, example);
     140        case ProblemType.VectorSummed: return VectorsSummed(interpreter, example);
     141        case ProblemType.XWordLines: return XWordLines(interpreter, example);
     142        case ProblemType.NegativeToZero: return NegativeToZero(interpreter, example);
     143        case ProblemType.WordStats: return WordStats(interpreter, example);
     144        case ProblemType.Checksum: return Checksum(interpreter, example);
     145        case ProblemType.Grades: return Grade(interpreter, example);
     146        case ProblemType.Syllables: return Syllables(interpreter, example);
     147
     148        // printed string right/wrong
     149        case ProblemType.Smallest:
     150        case ProblemType.Median: return PrintedStringRight(interpreter, example);
     151
     152        // boolean error
     153        case ProblemType.MirrorImage:
     154        case ProblemType.SuperAnagrams:
     155        case ProblemType.CompareStringLengths: return GetDiff(example.OutputBoolean, interpreter.BooleanStack, Data.WorstResult, BooleanDiffer);
     156
     157        // float error
     158        case ProblemType.VectorAverage: return GetDiff(example.OutputFloat, interpreter.FloatStack, Data.WorstResult, (a, b) => FloatDiffer(a, b, example.OutputFloatPrecision));
     159
     160        // integer error
     161        case ProblemType.LastIndexOfZero:
     162        case ProblemType.CountOdds:
     163        case ProblemType.SumOfSquares:
     164        case ProblemType.ScrabbleScore:
     165        case ProblemType.CollatzNumbers: return GetDiff(example.OutputInteger, interpreter.IntegerStack, Data.WorstResult, IntegerDiffer);
     166
     167        // levenshtein distance + integer error
     168        case ProblemType.ReplaceSpaceWithNewline:
     169          return GetPrintDiffer(example.OutputPrint, interpreter.PrintStack, Data.WorstResult)
     170               + GetDiff(example.OutputInteger, interpreter.IntegerStack, Data.WorstResult, IntegerDiffer);
     171
     172        // printed levenshtein distance
     173        case ProblemType.ForLoopIndex:
     174        case ProblemType.DoubleLetters:
     175        case ProblemType.StringLengthsBackwards:
     176        case ProblemType.PigLatin:
     177        case ProblemType.Digits:
     178        case ProblemType.SmallOrLarge: return GetPrintDiffer(example.OutputPrint, interpreter.PrintStack, Data.WorstResult);
    135179      }
    136180
     
    163207    }
    164208
    165     private double Median(IPushInterpreter interpreter, Example example) {
    166       return interpreter.PrintStack.IsEmpty || !interpreter.PrintStack.ToString().Equals(example.OutputPrint) ? 1 : 0;
     209    private double PrintedStringRight(IPushInterpreter interpreter, Example example) {
     210      return interpreter.PrintStack.IsEmpty ||
     211             !interpreter.PrintStack.ToString().Equals(example.OutputPrint)
     212             ? 1
     213             : 0;
    167214    }
    168215
    169216    private double NumberIo(IPushInterpreter interpreter, Example example) {
    170       if (interpreter.PrintStack.IsEmpty)
     217      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
    171218        return Data.WorstResult;
    172219
     
    176223      if (double.TryParse(printResult, NumberStyles.Number | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out value)) {
    177224        var diff = Math.Abs(example.OutputFloat[0] - value);
    178         var result = Math.Min(diff, Data.WorstResult);
    179 
    180         return result;
     225        diff = Math.Min(diff, Data.WorstResult);
     226
     227        return diff;
    181228      }
    182229
     
    187234        Data.WorstResult);
    188235
    189       return levenshteinDistance + penaltyError;
     236      var result = levenshteinDistance + penaltyError;
     237      return Math.Min(result, Data.WorstResult);
     238    }
     239
     240    private double StringDifferences(IPushInterpreter interpreter, Example example) {
     241      if (string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     242        return 0.0;
     243      }
     244
     245      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     246        return Data.WorstResult;
     247      }
     248
     249      var printResult = interpreter.PrintStack.ToString();
     250      var distance = example.OutputPrint.LevenshteinDistance(printResult);
     251      var lineCountWithCorrectFormat = interpreter.PrintStack.AsStrings().Count(line => {
     252        var parts = line.Split(' ');
     253
     254        if (parts.Length != 3)
     255          return false;
     256
     257        var part0 = parts[0].Trim();
     258        if (part0.Length == 0 || !part0.IsNumeric())
     259          return false;
     260
     261        var part1 = parts[1].Trim();
     262        if (part1.Length != 1)
     263          return false;
     264
     265        var part2 = parts[2].Trim();
     266        if (part2.Length != 1)
     267          return false;
     268
     269        return true;
     270      });
     271
     272      var lineCountWithInvalidFormat = example.OutputPrintLineCount - lineCountWithCorrectFormat;
     273      lineCountWithInvalidFormat = Math.Min(lineCountWithInvalidFormat, example.OutputPrintLineCount);
     274
     275      var result = distance + lineCountWithInvalidFormat;
     276      return Math.Min(result, Data.WorstResult);
     277    }
     278
     279    private double EvenSquares(IPushInterpreter interpreter, Example example) {
     280      if (string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     281        return 0.0;
     282      }
     283
     284      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     285        return Data.WorstResult;
     286      }
     287
     288      var distance = example.OutputPrint.LevenshteinDistance(interpreter.PrintStack.ToString());
     289      var printLines = interpreter.PrintStack.AsStrings().ToArray();
     290      var lineCountWithCorrectFormat = printLines.Count(line => line.IsNumeric());
     291      var lineCountWithInvalidFormat = example.OutputPrintLineCount - lineCountWithCorrectFormat;
     292
     293      lineCountWithInvalidFormat = Math.Abs(Math.Min(lineCountWithInvalidFormat, example.OutputPrintLineCount));
     294
     295      var compareLength = Math.Min(printLines.Length, example.OutputPrintLineCount);
     296      long integerError = 0;
     297
     298      for (var i = 0; i < compareLength; i++) {
     299        long value;
     300        if (long.TryParse(printLines[i], out value)) {
     301          integerError += Math.Abs(value - example.OutputIntegerVector[0][i]);
     302        } else {
     303          integerError += example.OutputPrintLineCount > 0
     304            ? (long)(Data.WorstResult / example.OutputPrintLineCount)
     305            : 0;
     306        }
     307      }
     308
     309      var result = distance + lineCountWithInvalidFormat + integerError;
     310      return Math.Min(result, Data.WorstResult);
     311    }
     312
     313    private double WallisPi(IPushInterpreter interpreter, Example example) {
     314      if (interpreter.FloatStack.IsEmpty)
     315        return Data.WorstResult;
     316
     317      var floatDiff = GetDiff(example.OutputFloat, interpreter.FloatStack, Data.WorstResult, (a, b) => FloatDiffer(a, b, example.OutputFloatPrecision));
     318      var expectedStr = example.OutputFloat[0].ToString(Data.FloatStringFormat, CultureInfo.CurrentCulture);
     319      var resultStr = interpreter.FloatStack.TopOrDefault.ToString(Data.FloatStringFormat, CultureInfo.CurrentCulture);
     320      var distance = expectedStr.LevenshteinDistance(resultStr);
     321
     322      var result = floatDiff + distance;
     323      return Math.Min(result, Data.WorstResult);
     324    }
     325
     326    private double VectorsSummed(IPushInterpreter interpreter, Example example) {
     327      if (interpreter.IntegerVectorStack.IsEmpty && example.OutputIntegerVector.Length > 0)
     328        return Data.WorstResult;
     329
     330      var resultVector = interpreter.IntegerVectorStack[0];
     331      var expectedVector = example.OutputIntegerVector[0];
     332      var comparableLength = Math.Min(resultVector.Count, expectedVector.Length);
     333
     334      // add penalty if length does not match
     335      var result = expectedVector.Length > 0
     336        ? (expectedVector.Length - comparableLength) * (Data.WorstResult / expectedVector.Length)
     337        : 0;
     338
     339      for (var i = 0; i < comparableLength; i++) {
     340        result += Math.Abs(resultVector[i] - expectedVector[i]);
     341      }
     342
     343      return Math.Min(result, Data.WorstResult);
     344    }
     345
     346    private double XWordLines(IPushInterpreter interpreter, Example example) {
     347      if (string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     348        return 0.0;
     349      }
     350
     351      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
     352        return Data.WorstResult;
     353
     354      var estimatedWordsPerLineCount = example.InputInteger[0];
     355      var estimatedWordCount = example.OutputInteger[0];
     356      var estimatedLastWordCount = estimatedWordCount - estimatedWordsPerLineCount * Math.Max(0, example.OutputPrintLineCount - 1);
     357      var printResult = interpreter.PrintStack.ToString();
     358      var distance = example.OutputPrint.LevenshteinDistance(printResult);
     359      var lineCount = interpreter.PrintStack.Count;
     360      var lineCountError = Math.Abs(example.OutputPrintLineCount - lineCount);
     361      var totalWordsPerLineError = 0L;
     362
     363      for (var i = 0; i < interpreter.PrintStack.Lines.Count - 1; i++) {
     364        totalWordsPerLineError += Math.Abs(interpreter.PrintStack.Lines[i].Split(' ').Length - estimatedWordsPerLineCount);
     365      }
     366
     367      // last line
     368      var lastLine = interpreter.PrintStack.Lines[interpreter.PrintStack.Lines.Count - 1];
     369      totalWordsPerLineError += Math.Abs(lastLine.Split(' ').Length - estimatedLastWordCount);
     370
     371      var result = distance + lineCountError + totalWordsPerLineError;
     372      return Math.Min(result, Data.WorstResult);
     373    }
     374
     375    private double NegativeToZero(IPushInterpreter interpreter, Example example) {
     376      if (interpreter.IntegerVectorStack.IsEmpty && example.OutputIntegerVector.Length > 0)
     377        return Data.WorstResult;
     378
     379      var resultVector = interpreter.IntegerVectorStack.Top;
     380      var expectedVector = example.OutputIntegerVector[0];
     381      var comparableLength = Math.Min(resultVector.Count, expectedVector.Length);
     382
     383      // add penalty if length does not match
     384      var result = expectedVector.Length > 0
     385        ? (expectedVector.Length - comparableLength) * (Data.WorstResult / expectedVector.Length)
     386        : 0;
     387
     388      for (var i = 0; i < comparableLength; i++) {
     389        var expectedStr = expectedVector[i].ToString();
     390        var resultStr = resultVector[i].ToString();
     391        result += expectedStr.LevenshteinDistance(resultStr);
     392      }
     393
     394      return Math.Min(result, Data.WorstResult);
     395    }
     396
     397    private double WordStats(IPushInterpreter interpreter, Example example) {
     398      if (string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty) {
     399        return 0.0;
     400      }
     401
     402      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
     403        return Data.WorstResult;
     404
     405      var printStr = interpreter.PrintStack.ToString();
     406      var distance = example.OutputPrint.LevenshteinDistance(printStr);
     407
     408      var statsError = 0.0;
     409      long numberOfSentences;
     410      var expectedNumberOfSentences = example.OutputInteger[0];
     411      statsError += BenchmarkSuite.Problems.WordStats.GetNumberOfSentences(printStr, out numberOfSentences)
     412        ? Math.Abs(expectedNumberOfSentences - numberOfSentences)
     413        : Data.WorstResult / 3.0;
     414
     415      double averageSentenceLength;
     416      var expectedAverageSentenceLength = example.OutputFloat[0];
     417      statsError += BenchmarkSuite.Problems.WordStats.GetAverageSentenceLength(printStr, out averageSentenceLength)
     418        ? Math.Abs(expectedAverageSentenceLength - averageSentenceLength)
     419        : Data.WorstResult / 3.0;
     420
     421      var result = distance + statsError;
     422      return Math.Min(result, Data.WorstResult);
     423    }
     424
     425    private double Checksum(IPushInterpreter interpreter, Example example) {
     426      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
     427        return Data.WorstResult;
     428
     429      var printStr = interpreter.PrintStack.ToString();
     430      var distance = example.OutputPrint.LevenshteinDistance(printStr);
     431
     432      var expectedLastCharIndex = example.OutputPrint.Length - 1;
     433      var result = distance;
     434
     435      if (expectedLastCharIndex >= 0) {
     436        var expectedLastChar = example.OutputPrint[expectedLastCharIndex];
     437        var resultLastCharIndex = printStr.Length - 1;
     438
     439        if (resultLastCharIndex >= 0) {
     440          var resultLastChar = printStr[resultLastCharIndex];
     441          result += Math.Abs(expectedLastChar - resultLastChar);
     442        }
     443      }
     444
     445      return Math.Min(result, Data.WorstResult);
     446    }
     447
     448    private double Syllables(IPushInterpreter interpreter, Example example) {
     449      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
     450        return Data.WorstResult;
     451
     452      var printStr = interpreter.PrintStack.ToString();
     453      var distance = example.OutputPrint.LevenshteinDistance(printStr);
     454
     455      long numberOfSyllables;
     456      var expectedNumberOfSyllables = example.OutputInteger[0];
     457      var numberOfSyllablesError = BenchmarkSuite.Problems.Syllables.GetNumberOfSyllables(printStr, out numberOfSyllables)
     458        ? Math.Abs(expectedNumberOfSyllables - numberOfSyllables)
     459        : Data.WorstResult / 2.0;
     460
     461      var result = distance + numberOfSyllablesError;
     462      return Math.Min(result, Data.WorstResult);
     463    }
     464
     465    private double Grade(IPushInterpreter interpreter, Example example) {
     466      if (!string.IsNullOrEmpty(example.OutputPrint) && interpreter.PrintStack.IsEmpty)
     467        return Data.WorstResult;
     468
     469      var printStr = interpreter.PrintStack.ToString();
     470      var distance = example.OutputPrint.LevenshteinDistance(printStr);
     471
     472      char grade;
     473      var expectedGrade = example.OutputChar[0];
     474      var gradeError = BenchmarkSuite.Problems.Grades.GetGrade(printStr, out grade)
     475        ? Math.Abs(expectedGrade - grade)
     476        : Data.WorstResult / 2;
     477
     478      var result = distance + gradeError;
     479      return Math.Min(result, Data.WorstResult);
    190480    }
    191481
     
    215505
    216506    private static double StringDiffer(string a, string b) {
    217       return LevenshteinDistance(a, b);
     507      return a.LevenshteinDistance(b);
    218508    }
    219509
     
    240530
    241531    private static double GetPrintDiffer(string estimated, string printResult, double worstResult) {
    242       var distance = LevenshteinDistance(estimated, printResult);
     532      var distance = estimated.LevenshteinDistance(printResult);
    243533
    244534      return Math.Min(distance, worstResult);
     
    247537    private static double GetPrintDiffer(string estimated, IPrintStack printStack, double worstResult) {
    248538      var printResult = printStack.ToString();
    249       var distance = LevenshteinDistance(estimated, printResult);
     539      var distance = estimated.LevenshteinDistance(printResult);
    250540
    251541      return Math.Min(distance, worstResult);
     
    293583      return diff;
    294584    }
    295 
    296     /// <summary>
    297     /// https://www.dotnetperls.com/levenshtein
    298     /// </summary>
    299     private static int LevenshteinDistance(string source, string target) {
    300       if (source == null && target == null) return 0;
    301       if (source == null) return target.Length;
    302       if (target == null) return source.Length;
    303 
    304       int n = source.Length;
    305       int m = target.Length;
    306       int[,] d = new int[n + 1, m + 1];
    307 
    308       // Step 1
    309       if (n == 0) {
    310         return m;
    311       }
    312 
    313       if (m == 0) {
    314         return n;
    315       }
    316 
    317       // Step 2
    318       for (int i = 0; i <= n; d[i, 0] = i++) {
    319       }
    320 
    321       for (int j = 0; j <= m; d[0, j] = j++) {
    322       }
    323 
    324       // Step 3
    325       for (int i = 1; i <= n; i++) {
    326         //Step 4
    327         for (int j = 1; j <= m; j++) {
    328           // Step 5
    329           int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
    330 
    331           // Step 6
    332           d[i, j] = Math.Min(
    333               Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
    334               d[i - 1, j - 1] + cost);
    335         }
    336       }
    337       // Step 7
    338       return d[n, m];
    339     }
    340585  }
    341586}
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/CodeExpressions.cs

    r15032 r15334  
    9494    "CODE.QUOTE",
    9595    "Specifies that the next expression submitted for execution will instead be pushed literally onto the CODE stack.",
    96     StackTypes.Exec)]
     96    StackTypes.Exec,
     97    requiredBlockCount: 1)]
    9798  [StorableClass]
    9899  public class CodeQuoteExpression : StatelessExpression {
     
    175176
    176177          if (secondProgram.Depth > interpreter.Configuration.MaxDepth ||
    177               firstProgram.Count + secondProgram.Count > interpreter.Configuration.MaxPointsInProgram)
     178              firstProgram.Count + secondProgram.Count > interpreter.Configuration.MaxProgramLength)
    178179            return;
    179         } else if (firstProgram.Count + 1 > interpreter.Configuration.MaxPointsInProgram) return;
     180        } else if (firstProgram.Count + 1 > interpreter.Configuration.MaxProgramLength) return;
    180181      } else if (second.IsProgram) {
    181182        secondProgram = (PushProgram)second;
    182183
    183184        if (secondProgram.Depth > interpreter.Configuration.MaxDepth
    184             || secondProgram.Count + 1 > interpreter.Configuration.MaxPointsInProgram) return;
    185       } else if (interpreter.Configuration.MaxPointsInProgram <= 2) {
     185            || secondProgram.Count + 1 > interpreter.Configuration.MaxProgramLength) return;
     186      } else if (interpreter.Configuration.MaxProgramLength <= 2) {
    186187        return;
    187188      }
     
    318319      return interpreter.CodeStack.Count < 2 ||
    319320            (interpreter.CodeStack.Top.IsProgram &&
    320             ((PushProgram)interpreter.CodeStack.Top).Expressions.Count + 1 > interpreter.Configuration.MaxPointsInProgram);
     321            ((PushProgram)interpreter.CodeStack.Top).Expressions.Count + 1 > interpreter.Configuration.MaxProgramLength);
    321322    }
    322323
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/DefineExpressions.cs

    r15032 r15334  
    6868    "Defines the name on top of the NAME stack as an instruction that will push the top item of the EXEC stack onto the EXEC stack.",
    6969    StackTypes.Name,
    70     execIn: 1)]
     70    requiredBlockCount: 1)]
    7171  [StorableClass]
    7272  public class ExecDefineExpression : DefineExpression<Expression> {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/DoCountExpressions.cs

    r15032 r15334  
    5757    "An iteration instruction that performs a loop (the body of which is taken from the EXEC stack) the number of times indicated by the INTEGER argument, pushing an index (which runs from zero to one less than the number of iterations) onto the INTEGER stack prior to each execution of the loop body.",
    5858    StackTypes.Integer,
    59     execIn: 1)]
     59    requiredBlockCount: 1)]
    6060  public class ExecDoCountExpression : StatelessExpression {
    6161    public ExecDoCountExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/DoRangeExpressions.cs

    r15032 r15334  
    8383    description: "An iteration instruction that executes the top item on the EXEC stack a number of times that depends on the top two integers, while also pushing the loop counter onto the INTEGER stack for possible access during the execution of the body of the loop.",
    8484    additionalStackDependencies: StackTypes.Integer,
    85     execIn: 1)]
     85    requiredBlockCount: 1)]
    8686  public class ExecDoRangeExpression : StatelessExpression {
    8787    public ExecDoRangeExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/DoTimesExpressions.cs

    r15032 r15334  
    6868  [Serializable]
    6969  [StorableClass]
    70   [PushExpression(StackTypes.Exec, "EXEC.DO*TIMES", "Like EXEC.DO*COUNT but does not push the loop counter", StackTypes.Integer, execIn: 1)]
     70  [PushExpression(StackTypes.Exec, "EXEC.DO*TIMES", "Like EXEC.DO*COUNT but does not push the loop counter", StackTypes.Integer, requiredBlockCount: 1)]
    7171  public class ExecDoTimesExpression : StatelessExpression {
    7272    public ExecDoTimesExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/DuplicateExpressions.cs

    r15032 r15334  
    8888
    8989  [StorableClass]
    90   [PushExpression(StackTypes.Exec, "EXEC.DUP", "Duplicates the top item on the EXEC stack." , execIn: 1)]
     90  [PushExpression(StackTypes.Exec, "EXEC.DUP", "Duplicates the top item on the EXEC stack." , requiredBlockCount: 1)]
    9191  public class ExecDuplicateExpression : DuplicateExpression<Expression> {
    9292    public ExecDuplicateExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/EmptyExpression.cs

    r15032 r15334  
    7272  }
    7373
     74  [StorableClass]
    7475  [PushExpression(
    7576    StackTypes.Float,
     
    8586  }
    8687
     88  [StorableClass]
    8789  [PushExpression(
    8890    StackTypes.Boolean,
    8991    "BOOLEAN.EMPTY",
    90     "Pushes TRUE onto the BOOLEAN stack if the BOOLEAN stack is empty, otherwise FALSE.",
    91     StackTypes.Boolean)]
     92    "Pushes TRUE onto the BOOLEAN stack if the BOOLEAN stack is empty, otherwise FALSE.")]
    9293  public class BooleanEmptyExpression : EmptyExpression<bool> {
    9394    public BooleanEmptyExpression() { }
     
    99100  }
    100101
     102  [StorableClass]
    101103  [PushExpression(
    102104    StackTypes.Char,
     
    113115  }
    114116
     117  [StorableClass]
    115118  [PushExpression(
    116119    StackTypes.String,
     
    127130  }
    128131
     132  [StorableClass]
    129133  [PushExpression(
    130134    StackTypes.IntegerVector,
     
    141145  }
    142146
     147  [StorableClass]
    143148  [PushExpression(
    144149    StackTypes.FloatVector,
     
    155160  }
    156161
     162  [StorableClass]
    157163  [PushExpression(
    158164    StackTypes.BooleanVector,
     
    169175  }
    170176
     177  [StorableClass]
    171178  [PushExpression(
    172179    StackTypes.StringVector,
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/EqualsExpressions.cs

    r15032 r15334  
    8383    StackTypes.Boolean,
    8484    "BOOLEAN.=",
    85     "Pushes TRUE onto the BOOLEAN stack if the top two BOOLEAN items are equal, or FALSE otherwise.",
    86     StackTypes.Boolean)]
     85    "Pushes TRUE onto the BOOLEAN stack if the top two BOOLEAN items are equal, or FALSE otherwise.")]
    8786  public class BooleanEqualsExpression : EqualsExpression<bool> {
    8887    public BooleanEqualsExpression() { }
     
    125124    "Pushes TRUE onto the BOOLEAN stack if the top two EXEC items are equal, or FALSE otherwise.",
    126125    StackTypes.Boolean,
    127     execIn: 0)]
     126    requiredBlockCount: 0)]
    128127  public class ExecEqualsExpression : EqualsExpression<Expression> {
    129128    public ExecEqualsExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/ExecExpressions.cs

    r15032 r15334  
    2020    "If the top item of the BOOLEAN stack is TRUE then this removes the second item on the EXEC stack, leaving the first item to be executed. If it is false then it removes the first item, leaving the second to be executed.",
    2121    StackTypes.Boolean,
    22     execIn: 2)]
     22    requiredBlockCount: 2)]
    2323  public class ExecIfExpression : StatelessExpression {
    2424    public ExecIfExpression() { }
     
    4545    "EXEC.Y",
    4646    "Inserts beneath the top item of the EXEC stack a new item of the form \"( EXEC.Y <TopItem> )\"",
    47     execIn: 1)]
     47    requiredBlockCount: 1)]
    4848  [StorableClass]
    4949  public class ExecYExpression : StatelessExpression {
     
    5454    public override bool IsNoop(IInternalPushInterpreter interpreter) {
    5555      return interpreter.ExecStack.Count == 0 ||
    56              interpreter.Configuration.MaxPointsInProgram < 2 ||
     56             interpreter.Configuration.MaxProgramLength < 2 ||
    5757             (interpreter.ExecStack.Top.IsProgram && ((PushProgram)interpreter.ExecStack.Top).Depth == interpreter.Configuration.MaxDepth);
    5858    }
     
    8080    "EXEC.K",
    8181    "Removes the second item on the EXEC stack.",
    82     execIn: 2)]
     82    requiredBlockCount: 2)]
    8383  [StorableClass]
    8484  public class ExecKExpression : StatelessExpression {
     
    106106    "EXEC.S",
    107107    "Pops 3 items from the EXEC stack called A, B, and C. Then pushes a list containing B and C back onto the EXEC stack, followed by another instance of C, followed by another instance of A.",
    108     execIn: 3)]
     108    requiredBlockCount: 3)]
    109109  [StorableClass]
    110110  public class ExecSExpression : StatelessExpression {
     
    167167    "EXEC.WHILE",
    168168    "Executes top EXEC item recursively as long top BOOLEAN is TRUE.",
    169     StackTypes.Boolean, execIn: 1)]
     169    StackTypes.Boolean, requiredBlockCount: 1)]
    170170  [StorableClass]
    171171  public class ExecWhileExpression : StatelessExpression {
     
    196196    "EXEC.DO*WHILE",
    197197    "Executes top EXEC item recursively until max. amount of eval. expressions is reached or top EXEC item removes the the recursive call.",
    198     execIn: 1)]
     198    requiredBlockCount: 1)]
    199199  [StorableClass]
    200200  public class ExecDoWhileExpression : StatelessExpression {
     
    220220    "Top EXEC item is only executed, if top BOOLEAN is TRUE.",
    221221    StackTypes.Boolean,
    222     execIn: 1)]
     222    requiredBlockCount: 1)]
    223223  [StorableClass]
    224224  public class ExecWhenExpression : StatelessExpression {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/Expression.cs

    r15189 r15334  
    11namespace HeuristicLab.Problems.ProgramSynthesis.Push.Expressions {
    22  using System;
    3   using System.Collections.Generic;
    43
    54  using HeuristicLab.Common;
     
    2019    public bool IsProgram { get { return GetType() == typeof(PushProgram); } }
    2120
    22     public static readonly IReadOnlyCollection<Expression> EmptyContainer = new Expression[0];
    23 
    24     public abstract string StringRepresentation
    25     {
    26       get;
    27     }
     21    public abstract string StringRepresentation { get; }
    2822
    2923    public abstract bool IsNoop(IInternalPushInterpreter interpreter);
     
    4337
    4438    public object Clone() {
    45       return Clone(new Cloner());
     39      return this;
    4640    }
    4741
     
    5044    }
    5145
    52     void IPooledObject.Init() { }
    53 
    5446    void IPooledObject.Reset() { }
    5547  }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/ExpressionTable.cs

    r15273 r15334  
    66  using Attributes;
    77  using Data.Pool;
     8
     9  using HeuristicLab.Problems.ProgramSynthesis.Base.Extensions;
     10
    811  using Stack;
    912
     
    124127    }
    125128
    126     private static bool IsSubclassOf(Type type, Type baseType) {
    127       if (type == null || baseType == null || type == baseType)
    128         return false;
    129 
    130       if (baseType.IsGenericType == false) {
    131         if (type.IsGenericType == false)
    132           return type.IsSubclassOf(baseType);
    133       } else {
    134         baseType = baseType.GetGenericTypeDefinition();
    135       }
    136 
    137       type = type.BaseType;
    138       var objectType = typeof(object);
    139       while (type != objectType && type != null) {
    140         var curentType = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
    141         if (curentType == baseType)
    142           return true;
    143 
    144         type = type.BaseType;
    145       }
    146 
    147       return false;
    148     }
     129
    149130
    150131    private static IEnumerable<Type> GetExpressionTypes(Type baseType) {
     
    152133             from assemblyType in domainAssembly.GetTypes()
    153134             where !assemblyType.IsAbstract &&
    154                    IsSubclassOf(assemblyType, baseType) &&
     135                   assemblyType.IsSubclass(baseType) &&
    155136                   assemblyType.GetConstructor(Type.EmptyTypes) != null
    156137             select assemblyType;
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/FloatExpressions.cs

    r15032 r15334  
    341341  /// </summary>
    342342  [PushExpression(StackTypes.Float, "FLOAT.COS", "Pushes the cosine of the top item.")]
     343  [StorableClass]
    343344  public class FloatCosineExpression : StatelessExpression {
    344345    public FloatCosineExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/PopExpressions.cs

    r15032 r15334  
    8484
    8585  [StorableClass]
    86   [PushExpression(StackTypes.Exec, "EXEC.POP", "Pops the top EXEC item.", execIn: 1)]
     86  [PushExpression(StackTypes.Exec, "EXEC.POP", "Pops the top EXEC item.", requiredBlockCount: 1)]
    8787  public class ExecPopExpression : PopExpression<Expression> {
    8888    public ExecPopExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/PrintExpressions.cs

    r15289 r15334  
    2626
    2727  [StorableClass]
     28  [PushExpression(StackTypes.Print, "PRINT.ENSURE_NEWLINE", "Pushes an empty string onto the PRINT STACK if current line isn't empty already.")]
     29  public class PrintEnsureNewLineExpression : StatelessExpression {
     30    public PrintEnsureNewLineExpression() { }
     31    [StorableConstructor]
     32    protected PrintEnsureNewLineExpression(bool deserializing) : base(deserializing) { }
     33
     34    public override bool IsNoop(IInternalPushInterpreter interpreter) {
     35      return interpreter.PrintStack.IsCurrentLineEmpty;
     36    }
     37
     38    public override void Eval(IInternalPushInterpreter interpreter) {
     39      interpreter.PrintStack.NewLine();
     40    }
     41  }
     42
     43  [StorableClass]
    2844  public abstract class PrintExpression<T> : StatelessExpression {
    2945    protected PrintExpression() { }
     
    104120    "Pushes the top BOOLEAN onto the EXEC stack.",
    105121    StackTypes.Exec,
    106     execIn: 1)]
     122    requiredBlockCount: 1)]
    107123  public class ExecPrintExpression : PrintExpression<Expression> {
    108124    public ExecPrintExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/PushProgram.cs

    r15189 r15334  
    55namespace HeuristicLab.Problems.ProgramSynthesis.Push.Expressions {
    66  using System.Diagnostics;
     7  using System.Diagnostics.CodeAnalysis;
     8
    79  using Constants;
    810  using Data.Pool;
     
    3840
    3941    [StorableConstructor]
    40     public PushProgram(bool deserializing) : this(EmptyExpressions) { }
     42    private PushProgram(bool deserializing) : this(EmptyExpressions) { }
    4143
    4244    public PushProgram(IReadOnlyList<Expression> expressions) {
     
    6769    }
    6870
    69     void IPooledObject.Init() { }
    70 
    7171    void IPooledObject.Reset() {
    7272      expressions = null;
     
    159159    [NonSerialized]
    160160    private int? hashCode;
     161    [SuppressMessage("ReSharper", "NonReadonlyMemberInGetHashCode")]
    161162    public override int GetHashCode() {
    162163      if (hashCode == null) hashCode = expressions.HashCode();
     
    256257      get
    257258      {
    258         if (branches == null) {
    259           branches = 1;
    260 
    261           for (var i = 0; i < Count; i++) {
    262             var expression = expressions[i];
    263 
    264             if (!expression.IsProgram)
    265               continue;
    266 
    267             var program = (PushProgram)expression;
    268             branches += program.Branches;
    269           }
    270         }
    271 
     259        if (branches == null) CountBranches();
    272260        return branches.Value;
     261      }
     262    }
     263
     264    private void CountBranches() {
     265      branches = 1;
     266
     267      for (var i = 0; i < Count; i++) {
     268        var expression = expressions[i];
     269
     270        if (!expression.IsProgram)
     271          continue;
     272
     273        var program = (PushProgram)expression;
     274        branches += program.Branches;
    273275      }
    274276    }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/RotateExpressions.cs

    r15032 r15334  
    100100    "EXEC.ROT",
    101101    "Rotates the top 3 items of the EXEC stack clockwise.",
    102     execIn: 3)]
     102    requiredBlockCount: 3)]
    103103  [StorableClass]
    104104  public class ExecRotateExpression : RotateExpression<Expression> {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/ShoveExpressions.cs

    r15032 r15334  
    107107    "Moves the top EXEC item to a specific stack index, whereby the index is taken from the INTEGER stack.",
    108108    StackTypes.Integer,
    109     execIn: 1)]
     109    requiredBlockCount: 1)]
    110110  [StorableClass]
    111111  public class ExecShoveExpression : ShoveExpression<Expression> {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/StatefulExpression.cs

    r15189 r15334  
    6969    }
    7070
    71     void IPooledObject.Init() { }
    72 
    7371    public void Reset() {
    7472      State = default(T);
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/StringExpressions.cs

    r15189 r15334  
    122122    public override bool IsNoop(IInternalPushInterpreter interpreter) {
    123123      return interpreter.StringStack.Count < 2 ||
    124              interpreter.StringStack.Top.Length + interpreter.StringStack[1].Length >= interpreter.Configuration.MaxStringLength;
     124             interpreter.StringStack.Top.Length + interpreter.StringStack[1].Length > interpreter.Configuration.MaxStringLength;
    125125    }
    126126
     
    148148      return interpreter.StringStack.IsEmpty ||
    149149             interpreter.CharStack.IsEmpty ||
    150              interpreter.StringStack.Top.Length + 1 >= interpreter.Configuration.MaxStringLength;
     150             interpreter.StringStack.Top.Length + 1 > interpreter.Configuration.MaxStringLength;
    151151    }
    152152
     
    618618
    619619    public override void Eval(IInternalPushInterpreter interpreter) {
     620      var result = GetResultString(interpreter);
     621
     622      // Should be checked in isNoop but would require to calculate result twice which is an expensive operation
     623      if (result.Length > interpreter.Configuration.MaxStringLength)
     624        return;
     625
     626      interpreter.StringStack.Remove(2);
     627      interpreter.StringStack.Top = result;
     628    }
     629
     630    private static string GetResultString(IInternalPushInterpreter interpreter) {
    620631      var third = interpreter.StringStack[2];
    621632      var second = interpreter.StringStack[1];
    622633      var first = interpreter.StringStack[0];
    623       interpreter.StringStack.Remove(2);
    624 
    625       interpreter.StringStack.Top = third.Length == 0 || second.Length == 0
     634
     635      var result = third.Length == 0 || second.Length == 0
    626636        ? third
    627637        : third.Replace(second, first);
     638
     639      return result;
    628640    }
    629641  }
     
    647659
    648660    public override void Eval(IInternalPushInterpreter interpreter) {
     661      var result = GetResultString(interpreter);
     662
     663      // Should be checked in isNoop but would require to calculate result twice which is an expensive operation
     664      if (result.Length > interpreter.Configuration.MaxStringLength)
     665        return;
     666
     667      interpreter.StringStack.Remove(2);
     668      interpreter.StringStack.Top = result;
     669    }
     670
     671    private static string GetResultString(IInternalPushInterpreter interpreter) {
    649672      var third = interpreter.StringStack[2];
    650673      var second = interpreter.StringStack[1];
    651674      var first = interpreter.StringStack[0];
    652       interpreter.StringStack.Remove(2);
    653 
    654       interpreter.StringStack.Top = third.Length == 0 || second.Length == 0
     675
     676      var result = third.Length == 0 || second.Length == 0
    655677        ? third
    656678        : ReplaceFirst(third, second, first);
     679      return result;
    657680    }
    658681
     
    802825    "STRING.ITERATE",
    803826    "Iterates over the top STRING using the CODE on the EXEC stack.",
    804     StackTypes.Exec | StackTypes.Char, execIn: 1)]
     827    StackTypes.Exec | StackTypes.Char, requiredBlockCount: 1)]
    805828  public class StringIterateExpression : StatelessExpression {
    806829    public StringIterateExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/SwapExpressions.cs

    r15032 r15334  
    104104    "EXEC.SWAP",
    105105    "Swaps the top two items on the stack.",
    106     execIn: 2)]
     106    requiredBlockCount: 2)]
    107107  public class ExecSwapExpression : SwapExpression<Expression> {
    108108    public ExecSwapExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/VectorIterateExpressions.cs

    r15189 r15334  
    6767    "Iterates in reverse order (due to performance reasons) over the top INTEGER[] using the top item of the EXEC stack.",
    6868    StackTypes.Integer | StackTypes.Exec,
    69     execIn: 1)]
     69    requiredBlockCount: 1)]
    7070  public class IntegerVectorIterateExpression : VectorIterateExpression<long> {
    7171    public IntegerVectorIterateExpression() { }
     
    8787    "FLOAT[].ITERATE",
    8888    "Iterates in reverse order (due to performance reasons) over the top FLOAT[] using the top item of the EXEC stack.",
    89     StackTypes.Float | StackTypes.Exec, execIn: 1)]
     89    StackTypes.Float | StackTypes.Exec, requiredBlockCount: 1)]
    9090  public class FloatVectorIterateExpression : VectorIterateExpression<double> {
    9191    public FloatVectorIterateExpression() { }
     
    107107    "BOOLEAN[].ITERATE",
    108108    "Iterates in reverse order (due to performance reasons) over the top BOOLEAN[] using the top item of the EXEC stack.",
    109     StackTypes.Boolean | StackTypes.Exec, execIn: 1)]
     109    StackTypes.Boolean | StackTypes.Exec, requiredBlockCount: 1)]
    110110  public class BooleanVectorIterateExpression : VectorIterateExpression<bool> {
    111111    public BooleanVectorIterateExpression() { }
     
    127127    "STRING[].ITERATE",
    128128    "Iterates in reverse order (due to performance reasons) over the top STRING[] using the top item of the EXEC stack.",
    129     StackTypes.String | StackTypes.Exec, execIn: 1)]
     129    StackTypes.String | StackTypes.Exec, requiredBlockCount: 1)]
    130130  public class StringVectorIterateExpression : VectorIterateExpression<string> {
    131131    public StringVectorIterateExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/YankDuplicateExpressions.cs

    r15032 r15334  
    116116    "EXEC.YANKDUP",
    117117    "Pushes a copy of an indexed item \"deep\" in the stack onto the top of the stack, without removing the deep item.",
    118     StackTypes.Integer, execIn: 0)]
     118    StackTypes.Integer, requiredBlockCount: 0)]
    119119  public class ExecYankDuplicateExpression : YankDuplicateExpression<Expression> {
    120120    public ExecYankDuplicateExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Expressions/YankExpressions.cs

    r15032 r15334  
    115115    "Removes an indexed item from \"deep\" in the stack and pushes it on top of the stack.",
    116116    StackTypes.Integer,
    117     execIn: 0)]
     117    requiredBlockCount: 0)]
    118118  public class ExecYankExpression : YankExpression<Expression> {
    119119    public ExecYankExpression() { }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Extensions/ControlExntensions.cs

    r14834 r15334  
    1717
    1818      if (propertyInfo == null ||
     19          // ReSharper disable once AssignNullToNotNullAttribute
    1920          !control.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
    2021          control.GetType().GetProperty(
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Individual/InduvidualMapper.cs

    r15273 r15334  
    4747        var expressionType = expression.GetType();
    4848
    49         if (config.ParenthesesCloseBiasLevel > 0) {
    50           close += random.NextBiased(0, config.MaxParenthesesClose, config.ParenthesesCloseBiasLevel);
     49        if (config.CloseBiasLevel > 0) {
     50          close += random.NextBiased(0, config.MaxClose, config.CloseBiasLevel);
    5151
    5252          // check if expression requires additional blocks
     
    5454            var attr = ExpressionTable.TypeToAttributeTable[expressionType];
    5555
    56             for (var blockIdx = 0u; blockIdx < attr.ExecIn && currentIndex < vector.Length; blockIdx++) {
     56            for (var blockIdx = 0u; blockIdx < attr.RequiredBlockCount && currentIndex < vector.Length; blockIdx++) {
    5757              if (close != 0) {
    5858                close--;
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Interpreter/Extensions.cs

    r15289 r15334  
    7777
    7878    public static void PrintStacks(this IPushInterpreter interpreter) {
     79      var maxStackNameLength = interpreter.Stacks.Max(x => x.Key.ToString().Length);
     80      var totalLength = maxStackNameLength + 6;
     81
    7982      foreach (var pair in interpreter.Stacks) {
    8083        var stackName = pair.Key.ToString();
    8184        var stack = interpreter.Stacks[pair.Key];
    8285
    83         if (stack.IsEmpty || !stack.IsEnabled) continue;
     86        if (stack.IsEmpty || !stack.IsEnabled)
     87          continue;
    8488
    85         var stackString = string.Join(" ", interpreter.StringifyStack(pair.Key).Reverse());
    86         Console.WriteLine("--------- {0} ---------\n{1}\n", stackName, stackString);
     89        var stackString = string.Join(" ", interpreter.StringifyStack(pair.Key));
     90
     91        //var padLength = (totalLength - stackName.Length) / 2;
     92        //var padLengthLeft = stackName.Length + padLength;
     93        //var padLengthRight = padLengthLeft + padLength;
     94        //Console.WriteLine("{0}\n{1}\n", stackName.PadLeft(padLengthLeft, '-').PadRight(padLengthRight, '-'), stackString);
     95
     96        Console.WriteLine("{0}: {1}", stackName, stackString);
    8797      }
    8898
     
    96106
    97107    public static void InitExample(this IPushInterpreter interpreter, Example example) {
    98       interpreter.BooleanStack.Push(example.InputBoolean);
    99       interpreter.IntegerStack.Push(example.InputInteger);
    100       interpreter.FloatStack.Push(example.InputFloat);
    101       interpreter.CharStack.Push(example.InputChar);
    102       interpreter.StringStack.Push(example.InputString);
    103       interpreter.StringVectorStack.Push(example.InputStringVector);
    104       interpreter.IntegerVectorStack.Push(example.InputIntegerVector);
    105       interpreter.FloatVectorStack.Push(example.InputFloatVector);
     108      if (interpreter.Configuration.TopLevelPushInputArguments) {
     109        interpreter.BooleanStack.Push(example.InputBoolean);
     110        interpreter.IntegerStack.Push(example.InputInteger);
     111        interpreter.FloatStack.Push(example.InputFloat);
     112        interpreter.CharStack.Push(example.InputChar);
     113        interpreter.StringStack.Push(example.InputString);
     114        interpreter.StringVectorStack.Push(example.InputStringVector);
     115        interpreter.IntegerVectorStack.Push(example.InputIntegerVector);
     116        interpreter.FloatVectorStack.Push(example.InputFloatVector);
     117      }
    106118
     119      // init in expressions
    107120      interpreter.SetInput(
    108121        integers: example.InputInteger,
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Interpreter/PushInterpreter.cs

    r15273 r15334  
    3131
    3232      // setting the capacity of the Stacks to max points ensures that there will be enough memory at runtime
    33       ExecStack = new PushStack<Expression>(Configuration.MaxPointsInProgram);
     33      ExecStack = new PushStack<Expression>(Configuration.MaxProgramLength);
    3434      CodeStack = new PushStack<Expression>();
    3535      NameStack = new PushStack<string>();
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Interpreter/PushInterpreterPool.cs

    r15273 r15334  
    2222      ExpressionListPoolProvider = new ManagedPoolProvider<PooledList<Expression>>(poolPartitionSize, () => new PooledList<Expression>(), maxPartitionCount);
    2323
    24       pool = new ObjectPool<PooledPushInterpreter>(() => {
    25         var poolContainer = new InterpreterPoolContainer(PushProgramPoolProvider, ExpressionListPoolProvider);
    26         return new PooledPushInterpreter(this, PushConfiguration, poolContainer);
    27       }, size);
     24      pool = new ObjectPool<PooledPushInterpreter>(CreateInterpreter, size);
     25    }
     26
     27    private PooledPushInterpreter CreateInterpreter() {
     28      var poolContainer = new InterpreterPoolContainer(PushProgramPoolProvider, ExpressionListPoolProvider);
     29      return new PooledPushInterpreter(this, PushConfiguration, poolContainer);
    2830    }
    2931
     
    3133
    3234    public PooledPushInterpreter Create(IRandom random = null) {
    33       var interpreter = pool.Allocate();
    34       interpreter.Reset(random);
     35      //var interpreter = pool.Allocate();
     36      //interpreter.Reset(random);
     37
     38      var poolContainer = new InterpreterPoolContainer(PushProgramPoolProvider, ExpressionListPoolProvider);
     39      var interpreter = new PooledPushInterpreter(this, PushConfiguration, poolContainer, random);
    3540
    3641      return interpreter;
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Manipulator/UniformMutation.cs

    r15289 r15334  
    1 namespace HeuristicLab.Problems.ProgramSynthesis.Push.Manipulator {
     1// ReSharper disable CompareOfFloatsByEqualityOperator
     2namespace HeuristicLab.Problems.ProgramSynthesis.Push.Manipulator {
    23
    34  using HeuristicLab.Common;
     
    910  using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    1011  using HeuristicLab.Problems.ProgramSynthesis.Base.Erc;
     12  using HeuristicLab.Problems.ProgramSynthesis.Base.Extensions;
    1113  using HeuristicLab.Problems.ProgramSynthesis.Push.Configuration;
    1214  using HeuristicLab.Problems.ProgramSynthesis.Push.Encoding;
     15  using HeuristicLab.Problems.ProgramSynthesis.Push.Expressions;
    1316  using HeuristicLab.Problems.ProgramSynthesis.Push.Generators.CodeGenerator;
    1417
     
    2730      Parameters.Add(new ValueLookupParameter<PercentValue>("InInstructionProbability", "The probability of IN Instructions"));
    2831
    29       Parameters.Add(new FixedValueParameter<PercentValue>("InstructionMutationProbability", "The probability an instruction gets mutated", new PercentValue(0.02)));
    30       Parameters.Add(new FixedValueParameter<PercentValue>("CloseMutationProbability", "The probability close gets mutated", new PercentValue(0.02)));
    31       Parameters.Add(new FixedValueParameter<PercentValue>("CloseIncrementRate", "When mutating individual, the increment rate specifies if close should be increased or decreased by 1.", new PercentValue(0.5)));
     32      Parameters.Add(new FixedValueParameter<PercentValue>("InstructionMutationProbability", "The probability instructions get mutated", new PercentValue(0.8)));
     33      Parameters.Add(new FixedValueParameter<PercentValue>("InstructionMutationRate", "The probability an instruction gets mutated", new PercentValue(0.01)));
     34      Parameters.Add(new FixedValueParameter<PercentValue>("InstructionConstantTweakRate", "When mutating an instruction, this parameter specifies if mutation is related to the current type (e.g. INTEGER, FLOAT) or not. ", new PercentValue(0)));
     35      Parameters.Add(new FixedValueParameter<PercentValue>("CloseMutationProbability", "The probability close gets mutated", new PercentValue(0.2)));
     36      Parameters.Add(new FixedValueParameter<PercentValue>("CloseIncrementRate", "When mutating individual, the increment rate specifies if close should be increased or decreased by 1.", new PercentValue(0.1)));
    3237    }
    3338
     
    4752      get { return InstructionMutationProbabilityParameter.Value.Value; }
    4853      set { InstructionMutationProbabilityParameter.Value.Value = value; }
     54    }
     55
     56    public IValueParameter<PercentValue> InstructionMutationRateParameter
     57    {
     58      get { return (IValueParameter<PercentValue>)Parameters["InstructionMutationRate"]; }
     59    }
     60
     61    public double InstructionMutationRate
     62    {
     63      get { return InstructionMutationRateParameter.Value.Value; }
     64      set { InstructionMutationRateParameter.Value.Value = value; }
     65    }
     66
     67    public IValueParameter<PercentValue> InstructionConstantTweakRateParameter
     68    {
     69      get { return (IValueParameter<PercentValue>)Parameters["InstructionConstantTweakRate"]; }
     70    }
     71
     72    public double InstructionConstantTweakRate
     73    {
     74      get { return InstructionConstantTweakRateParameter.Value.Value; }
     75      set { InstructionConstantTweakRateParameter.Value.Value = value; }
    4976    }
    5077
     
    104131        RandomParameter.ActualValue,
    105132        PlushVectorParameter.ActualValue,
    106         CloseIncrementRate,
    107133        ErcOptionsParameter.ActualValue,
    108134        InstructionsParameter.ActualValue,
    109135        InInstructionProbabilityParameter.ActualValue.Value,
    110136        CloseMutationProbability,
    111         InstructionMutationProbability);
     137        CloseIncrementRate,
     138        InstructionMutationProbability,
     139        InstructionMutationRate,
     140        InstructionConstantTweakRate);
    112141      return base.InstrumentedApply();
    113142    }
     
    116145      IRandom random,
    117146      PlushVector plushVector,
    118       double closeIncrementRate,
    119147      IReadOnlyErcOptions ercOptions,
    120148      IReadOnlyExpressionsConfiguration instructions,
    121149      double inInstructionProbability,
    122150      double closeMutationProbability,
    123       double instructionMutationProbability
     151      double closeIncrementRate,
     152      double instructionMutationProbability,
     153      double instructionMutationRate,
     154      double constantTweakRate
    124155      ) {
    125156
    126       for (var i = 0; i < plushVector.Entries.Count; i++) {
    127         var entry = plushVector[i];
    128         var x = random.NextDouble();
    129 
    130         if (x < instructionMutationProbability) {
    131           var instruction = CodeGeneratorUtils.GetRandomExpression(
    132             random,
    133             ercOptions,
    134             instructions,
    135             inInstructionProbability);
    136           entry.Instruction = instruction;
     157      var x = random.NextDouble();
     158
     159      // instruction manipulation
     160      if (x < instructionMutationProbability) {
     161        if (instructionMutationRate == 0) return;
     162        for (var i = 0; i < plushVector.Entries.Count; i++) {
     163          MutateInstruction(random, ercOptions, instructions, inInstructionProbability, instructionMutationRate, constantTweakRate, plushVector[i]);
    137164        }
    138165
    139         x = random.NextDouble();
    140 
    141         if (x < closeMutationProbability) {
    142           x = random.NextDouble();
    143           entry.Close += x < closeIncrementRate ? 1 : -1;
    144 
    145           if (entry.Close < 0)
    146             entry.Close = 0;
     166        plushVector.UpdatePushProgram();
     167        return;
     168      }
     169
     170      // close manipulation
     171      if (x < instructionMutationProbability + closeMutationProbability) {
     172        if (closeIncrementRate == 0) return;
     173        for (var i = 0; i < plushVector.Entries.Count; i++) {
     174          MutateClose(random, closeIncrementRate, plushVector[i]);
    147175        }
     176
     177        plushVector.UpdatePushProgram();
     178        return;
    148179      }
    149 
    150       // specifies that the program cached within entry must be updated before reuse
    151       plushVector.UpdatePushProgram();
     180    }
     181
     182    private static void MutateClose(IRandom random, double closeIncrementRate, PlushEntry entry) {
     183      entry.Close += random.NextDouble() < closeIncrementRate ? 1 : -1;
     184
     185      if (entry.Close < 0)
     186        entry.Close = 0;
     187    }
     188
     189    private static void MutateInstruction(
     190      IRandom random,
     191      IReadOnlyErcOptions ercOptions,
     192      IReadOnlyExpressionsConfiguration instructions,
     193      double inInstructionProbability,
     194      double instructionMutationRate,
     195      double constantTweakRate,
     196      PlushEntry entry) {
     197
     198      if (random.NextDouble() >= instructionMutationRate)
     199        return;
     200
     201      var entryType = entry.Instruction.GetType();
     202
     203      if (constantTweakRate > 0 && random.NextDouble() < constantTweakRate &&
     204          entryType.IsSubclass(typeof(PushExpression<>))) {
     205        var attribute = ExpressionTable.TypeToAttributeTable[entryType];
     206        entry.Instruction = CodeGeneratorUtils.CreateRandomErcExpression(attribute.StackType, random, ercOptions);
     207        return;
     208      }
     209
     210      entry.Instruction = CodeGeneratorUtils.GetRandomExpression(
     211        random,
     212        ercOptions,
     213        instructions,
     214        inInstructionProbability);
    152215    }
    153216  }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/IntegerVectorPushBenchmarkSuiteProblem.cs

    r15289 r15334  
    5151      Description = data.Description;
    5252      BestKnownQuality = data.BestResult;
    53       Config.MaxPointsInProgram = data.MaxSize;
     53      Config.MaxProgramLength = data.MaxSize;
    5454      Config.EvalPushLimit = data.EvalLimit;
    5555      Config.ErcOptions = data.ErcOptions;
     
    6262      Encoding.Bounds[0, 1] = Config.EnabledExpressions.Count;
    6363
    64       Encoding.Length = data.MaxSize;
     64      Encoding.Length = data.MaxSize / 2;
     65
    6566    }
    6667
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/BenchmarkSuite/PlushPushBenchmarkSuiteProblem.cs

    r15289 r15334  
    4848      Description = data.Description;
    4949      BestKnownQuality = data.BestResult;
    50       Config.MaxPointsInProgram = data.MaxSize;
     50      Config.MaxProgramLength = data.MaxSize;
    5151      Config.EvalPushLimit = data.EvalLimit;
    5252      Config.ErcOptions = data.ErcOptions;
     
    5656      Config.InitInExpressions(data.TotalInputArgumentCount);
    5757
    58       Encoding.MaxLength = data.MaxSize;
     58      Encoding.MinLength = 0;
     59      Encoding.MaxLength = data.MaxSize / 2;
    5960    }
    6061
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/IntegerVectorPushProblem.cs

    r15289 r15334  
    5959      Encoding.Bounds[0, 0] = 0;
    6060      Encoding.Bounds[0, 1] = Config.EnabledExpressions.Count;
    61       Encoding.Length = Config.MaxPointsInProgram;
     61      Encoding.Length = Config.MaxProgramLength;
    6262    }
    6363
     
    7272
    7373      solutionCreator.ErcOptions = Config.ErcOptions;
     74      solutionCreator.MinLength = Config.MinProgramLength;
    7475
    7576      if (!Operators.OfType<PushExpressionFrequencyAnalyzer>().Any()) {
    7677        Operators.Add(new PushExpressionFrequencyAnalyzer());
     78      }
     79
     80      if (!Operators.OfType<IndividualZeroErrorAnalyzer>().Any()) {
     81        Operators.Add(new IndividualZeroErrorAnalyzer());
    7782      }
    7883
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/PlushPushProblem.cs

    r15289 r15334  
    33
    44  using HeuristicLab.Common;
    5   using HeuristicLab.Core;
    6   using HeuristicLab.Data;
    75  using HeuristicLab.Optimization;
    86  using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    3129      Encoding.ErcOptionsParameter = Config.ErcOptionsParameter;
    3230      Encoding.InstructionsParameter = Config.InstructionsParameter;
    33       Encoding.MaxLength = Config.MaxPointsInProgram;
     31      Encoding.MinLengthParameter = Config.MinProgramLengthParameter;
     32      Encoding.MaxLengthParameter = Config.MaxProgramLengthParameter;
     33      Encoding.MaxCloseParameter = Config.MaxCloseParameter;
     34      Encoding.CloseBiasLevelParameter = Config.CloseBiasLevelParameter;
    3435    }
    3536
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Problem/PushProblemBase.cs

    r15289 r15334  
    2020  public abstract class PushProblemBase<T> : SingleObjectiveBasicProblem<T> where T : class, IEncoding {
    2121    [Storable]
    22     protected readonly PushConfigurationParameterCollection Config;
     22    public readonly PushConfiguration Config;
    2323
    2424    protected PushInterpreterPool Pool;
     
    3737
    3838    protected PushProblemBase(IPushEvaluator evaluator) {
    39       Config = new PushConfigurationParameterCollection();
     39      Config = new PushConfiguration();
    4040      PushEvaluator = evaluator;
    4141
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/SolutionCreator/IPlushCreator.cs

    r15289 r15334  
    1010    IValueLookupParameter<IntValue> MinLengthParameter { get; }
    1111    IValueLookupParameter<IntValue> MaxLengthParameter { get; }
    12     IValueLookupParameter<IntValue> MinCloseParameter { get; }
    1312    IValueLookupParameter<IntValue> MaxCloseParameter { get; }
    1413    IValueLookupParameter<DoubleValue> CloseBiasLevelParameter { get; }
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/SolutionCreator/PlushCreator.cs

    r15289 r15334  
    2424      Parameters.Add(new ValueLookupParameter<IntValue>("MinLength", "The min length of the vector."));
    2525      Parameters.Add(new ValueLookupParameter<IntValue>("MaxLength", "The max length of the vector."));
    26       Parameters.Add(new ValueLookupParameter<IntValue>("MinClose", "The min close variable for a plush genome entry."));
    2726      Parameters.Add(new ValueLookupParameter<IntValue>("MaxClose", "The max close variable for a plush genome entry."));
    2827      Parameters.Add(new ValueLookupParameter<DoubleValue>("CloseBiasLevel", "Determines how strongly the random close variable is biased towards 0."));
     
    6968      get { return (IValueLookupParameter<PercentValue>)Parameters["InInstructionProbability"]; }
    7069    }
    71     public IValueLookupParameter<IntValue> MinCloseParameter
    72     {
    73       get { return (IValueLookupParameter<IntValue>)Parameters["MinClose"]; }
    74     }
    7570    public IValueLookupParameter<IntValue> MaxCloseParameter
    7671    {
     
    9792      var instructions = InstructionsParameter.ActualValue;
    9893      var inInstructionProbability = InInstructionProbabilityParameter.ActualValue.Value;
    99       var minClose = MinCloseParameter.ActualValue.Value;
    10094      var maxClose = MaxCloseParameter.ActualValue.Value;
    10195      var biasLevel = CloseBiasLevelParameter.ActualValue.Value;
     
    10397      if (minLength > maxLength)
    10498        throw new InvalidOperationException("MinLength > MaxLength");
    105 
    106       if (minClose > maxClose)
    107         throw new InvalidOperationException("MinClose > MaxClose");
    10899
    109100      var length = random.Next(minLength, maxLength);
     
    117108          inInstructionProbability);
    118109
    119         var close = random.NextBiased(minClose, maxClose, biasLevel);
     110        var close = maxClose == 0 ? 1 : random.NextBiased(0, maxClose, biasLevel);
    120111
    121112        result.Add(new PlushEntry {
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Stack/IPrintStack.cs

    r15289 r15334  
    11namespace HeuristicLab.Problems.ProgramSynthesis.Push.Stack {
     2  using System.Collections.Generic;
     3
    24  public interface IPrintStack : IPushStack {
     5    bool IsCurrentLineEmpty { get; }
     6    IReadOnlyList<string> Lines { get; }
     7
    38    void NewLine();
    49    void Push<T>(T item);
  • branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis/Push/Stack/PrintStack.cs

    r15289 r15334  
    1414  public class PrintStack : IPrintStack {
    1515    private int lineCount = 0;
     16    private int length = 0;
     17    private IReadOnlyList<string> lines;
    1618    private readonly StringBuilder stringBuilder = new StringBuilder();
    1719
     20    public PrintStack() {
     21      IsCurrentLineEmpty = true;
     22    }
     23
     24    public bool IsCurrentLineEmpty { get; private set; }
     25
    1826    IEnumerator IEnumerable.GetEnumerator() {
    19       var lines = AsStrings();
    20       return lines.GetEnumerator();
     27      return Lines.GetEnumerator();
    2128    }
    2229
     
    2532    }
    2633
     34    public IReadOnlyList<string> Lines
     35    {
     36      get
     37      {
     38        if (stringBuilder.Length == length) return lines;
     39        length = stringBuilder.Length;
     40        lines = stringBuilder.ToString().Split(PushEnvironment.NewLine);
     41
     42        return lines;
     43      }
     44    }
     45
    2746    void IPushStack.Clear() {
     47      lineCount = 0;
     48      length = 0;
     49      lines = null;
     50      IsCurrentLineEmpty = true;
    2851      stringBuilder.Clear();
    2952    }
     
    3154    public void NewLine() {
    3255      stringBuilder.Append(PushEnvironment.NewLine);
     56      IsCurrentLineEmpty = true;
    3357      lineCount++;
    3458    }
     
    3660    public void Push<T>(T item) {
    3761      if (IsEmpty) lineCount = 1;
    38       stringBuilder.Append(item);
     62      var str = item.ToString();
     63      stringBuilder.Append(str);
     64      IsCurrentLineEmpty = IsCurrentLineEmpty && string.IsNullOrEmpty(str);
    3965    }
    4066
     
    4268      if (IsEmpty) lineCount = 1;
    4369      stringBuilder.Concat(item);
     70      IsCurrentLineEmpty = false;
    4471    }
    4572
     
    4774      if (IsEmpty) lineCount = 1;
    4875      stringBuilder.Concat(item);
     76      IsCurrentLineEmpty = false;
    4977    }
    5078
     
    5280      if (IsEmpty) lineCount = 1;
    5381      stringBuilder.Concat(item);
     82      IsCurrentLineEmpty = false;
    5483    }
    5584
     
    5786      if (IsEmpty) lineCount = 1;
    5887      stringBuilder.Concat(item);
     88      IsCurrentLineEmpty = false;
    5989    }
    6090
     
    6292      if (IsEmpty) lineCount = 1;
    6393      stringBuilder.Append(item);
     94      IsCurrentLineEmpty = false;
    6495    }
    6596
     
    6798      if (IsEmpty) lineCount = 1;
    6899      stringBuilder.Append(item);
     100      IsCurrentLineEmpty = false;
    69101    }
    70 
    71102
    72103    public void Push(string item) {
    73104      if (IsEmpty) lineCount = 1;
    74105      stringBuilder.Append(item);
     106      IsCurrentLineEmpty = IsCurrentLineEmpty && string.IsNullOrEmpty(item);
    75107    }
    76108
     
    78110      for (var i = startIndex; i < items.Count; i++)
    79111        stringBuilder.Append(items[i]);
     112
     113      IsCurrentLineEmpty = false;
    80114    }
    81115
     
    87121      foreach (var item in items)
    88122        stringBuilder.Append(item);
     123
     124      IsCurrentLineEmpty = false;
    89125    }
    90126
    91127    public IEnumerable<string> AsStrings() {
    92       var lines = stringBuilder.ToString().Split(PushEnvironment.NewLine);
    93       return lines;
     128      return Lines;
    94129    }
    95130
    96131    public IEnumerable<object> AsObjects() {
    97       return AsStrings();
     132      return Lines;
    98133    }
    99134
Note: See TracChangeset for help on using the changeset viewer.