Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
12/20/12 16:24:54 (12 years ago)
Author:
bburlacu
Message:

#1772: Merged HeuristicLab.Encodings.SymbolicExpressionTreeEncoding from trunk. Added Fragment class implementing IFragment interface.

Location:
branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding
Files:
3 added
1 deleted
33 edited
1 copied

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding

  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs

    r7439 r9083  
    8888
    8989    [StorableConstructor]
    90     private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base() { }
     90    private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base(deserializing) { }
    9191    private SymbolicExpressionTreeLengthAnalyzer(SymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
    9292      : base(original, cloner) {
     
    153153        // if the table was not created yet, we create it here
    154154        if (treeLengthsTable == null) {
    155           treeLengthsTable = new DataTable("Histogram");
     155          treeLengthsTable = new DataTable("Tree Length Histogram");
    156156          SymbolicExpressionTreeLengthsParameter.ActualValue = treeLengthsTable;
    157157        }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs

    r7439 r9083  
    139139      // the grammar in the newly defined function is a clone of the grammar of the originating branch
    140140      defunNode.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBody.Grammar.Clone());
     141
     142      var allowedChildSymbols = selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol);
     143      foreach (var allowedChildSymbol in allowedChildSymbols)
     144        defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
     145      var maxSubtrees = selectedBody.Grammar.GetMaximumSubtreeCount(selectedBody.Symbol);
     146      for (int i = 0; i < maxSubtrees; i++) {
     147        foreach (var allowedChildSymbol in selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol, i))
     148          defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
     149      }
     150
    141151      // remove all argument symbols from grammar except that one contained in cutpoints
    142152      var oldArgumentSymbols = selectedBody.Grammar.Symbols.OfType<Argument>().ToList();
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs

    r7439 r9083  
    7373      symbolicExpressionTree.Root.AddSubtree(duplicatedDefunBranch);
    7474      duplicatedDefunBranch.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBranch.Grammar.Clone());
     75
     76      var allowedChildSymbols = selectedBranch.Grammar.GetAllowedChildSymbols(selectedBranch.Symbol);
     77      foreach (var allowedChildSymbol in allowedChildSymbols)
     78        duplicatedDefunBranch.Grammar.AddAllowedChildSymbol(duplicatedDefunBranch.Symbol, allowedChildSymbol);
     79      var maxSubtrees = selectedBranch.Grammar.GetMaximumSubtreeCount(selectedBranch.Symbol);
     80      for (int i = 0; i < maxSubtrees; i++) {
     81        foreach (var allowedChildSymbol in selectedBranch.Grammar.GetAllowedChildSymbols(selectedBranch.Symbol, i))
     82          duplicatedDefunBranch.Grammar.AddAllowedChildSymbol(duplicatedDefunBranch.Symbol, allowedChildSymbol);
     83      }
     84
    7585      // add an invoke symbol for each branch that is allowed to invoke the original function
    7686      foreach (var subtree in symbolicExpressionTree.Root.Subtrees.OfType<SymbolicExpressionTreeTopLevelNode>()) {
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeCompiler.cs

    r7439 r9083  
    2525
    2626namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    27   public class SymbolicExpressionTreeCompiler {
    28     private Dictionary<string, ushort> entryPoint = new Dictionary<string, ushort>();
    29     private List<Func<Instruction, Instruction>> postInstructionCompiledHooks = new List<Func<Instruction, Instruction>>();
     27  public static class SymbolicExpressionTreeCompiler {
    3028
    31     public Instruction[] Compile(ISymbolicExpressionTree tree, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper) {
     29    public static Instruction[] Compile(ISymbolicExpressionTree tree, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper) {
     30      return Compile(tree, opCodeMapper, Enumerable.Empty<Func<Instruction, Instruction>>());
     31    }
     32    public static Instruction[] Compile(ISymbolicExpressionTree tree, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper, IEnumerable<Func<Instruction, Instruction>> postInstructionCompiledHooks) {
     33      Dictionary<string, ushort> entryPoint = new Dictionary<string, ushort>();
    3234      List<Instruction> code = new List<Instruction>();
    33       entryPoint.Clear();
    3435      // compile main body branches
    3536      foreach (var branch in tree.Root.GetSubtree(0).Subtrees) {
    36         code.AddRange(Compile(branch, opCodeMapper));
     37        code.AddRange(Compile(branch, opCodeMapper, postInstructionCompiledHooks));
    3738      }
    3839      // compile function branches
     
    4344        if (code.Count > ushort.MaxValue) throw new ArgumentException("Code for the tree is too long (> ushort.MaxValue).");
    4445        entryPoint[branch.FunctionName] = (ushort)code.Count;
    45         code.AddRange(Compile(branch.GetSubtree(0), opCodeMapper));
     46        code.AddRange(Compile(branch.GetSubtree(0), opCodeMapper, postInstructionCompiledHooks));
    4647      }
    4748      // address of all functions is fixed now
     
    5253          var invokeNode = (InvokeFunctionTreeNode)instr.dynamicNode;
    5354          instr.iArg0 = entryPoint[invokeNode.Symbol.FunctionName];
    54           code[i] = instr;
    5555        }
    5656      }
     
    5959    }
    6060
    61     private IEnumerable<Instruction> Compile(ISymbolicExpressionTreeNode branch, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper) {
     61    private static IEnumerable<Instruction> Compile(ISymbolicExpressionTreeNode branch, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper, IEnumerable<Func<Instruction, Instruction>> postInstructionCompiledHooks) {
    6262      foreach (var node in branch.IterateNodesPrefix()) {
    6363        Instruction instr = new Instruction();
     
    7777      }
    7878    }
    79 
    80     /// <summary>
    81     /// Adds a function that will be called every time an instruction is compiled.
    82     /// The compiled will insert the instruction returned by the hook into the code.
    83     /// </summary>
    84     /// <param name="hook">The hook that should be called for each compiled instruction.</param>
    85     public void AddInstructionPostProcessingHook(Func<Instruction, Instruction> hook) {
    86       postInstructionCompiledHooks.Add(hook);
    87     }
    8879  }
    8980}
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs

    r7997 r9083  
    3333  [StorableClass]
    3434  [Item("FullTreeCreator", "An operator that creates new symbolic expression trees using the 'Full' method")]
    35   public class FullTreeCreator : TracingSymbolicExpressionTreeCreator,
     35  public class FullTreeCreator : SymbolicExpressionTreeCreator,
    3636                                 ISymbolicExpressionTreeSizeConstraintOperator,
    3737                                 ISymbolicExpressionTreeGrammarBasedOperator {
     
    147147        throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
    148148
     149
    149150      int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
    150151      // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
     
    160161          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
    161162          .ToList();
    162         var weights = possibleSymbols.Select(s => s.InitialFrequency);
     163        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
    163164        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
    164165        var tree = selectedSymbol.CreateTreeNode();
     
    192193        if (!possibleSymbols.Any())
    193194          throw new InvalidOperationException("No symbols are available for the tree.");
    194         var weights = possibleSymbols.Select(s => s.InitialFrequency);
     195        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
    195196        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
    196197        var tree = selectedSymbol.CreateTreeNode();
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs

    r7997 r9083  
    160160          .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
    161161          .ToList();
    162         var weights = possibleSymbols.Select(s => s.InitialFrequency);
     162        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
    163163        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
    164164        var tree = selectedSymbol.CreateTreeNode();
     
    179179        throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
    180180
    181       var allowedSymbols = root.Grammar.AllowedSymbols
    182         .Where(s => s.InitialFrequency > 0.0)
    183         .ToList();
     181      var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
    184182
    185183      for (var i = 0; i < arity; i++) {
     
    188186            root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth)
    189187          .ToList();
     188
    190189        if (!possibleSymbols.Any())
    191190          throw new InvalidOperationException("No symbols are available for the tree.");
    192         var weights = possibleSymbols.Select(s => s.InitialFrequency);
     191        var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
    193192        var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
    194193        var tree = selectedSymbol.CreateTreeNode();
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs

    r7997 r9083  
    176176        extensionPoints.Add(x);
    177177      }
    178       long minExtensionPointsLength = extensionPoints.Select(x => x.MinimumExtensionLength).Sum();
    179       long maxExtensionPointsLength = extensionPoints.Select(x => x.MaximumExtensionLength).Sum();
     178      //necessary to use long data type as the extension point length could be int.MaxValue
     179      long minExtensionPointsLength = extensionPoints.Select(x => (long)x.MinimumExtensionLength).Sum();
     180      long maxExtensionPointsLength = extensionPoints.Select(x => (long)x.MaximumExtensionLength).Sum();
    180181
    181182      // while there are pending extension points and we have not reached the limit of adding new extension points
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SymbolicExpressionTreeCrossover.cs

    r7792 r9083  
    3232  [Item("SymbolicExpressionTreeCrossover", "A base class for operators that perform a crossover of symbolic expression trees.")]
    3333  [StorableClass]
    34   public abstract class SymbolicExpressionTreeCrossover : SymbolicExpressionTreeOperator, ISymbolicExpressionTreeCrossover {
     34  public abstract class SymbolicExpressionTreeCrossover : TracingSymbolicExpressionTreeOperator, ISymbolicExpressionTreeCrossover {
    3535    private const string ParentsParameterName = "Parents";
    3636    private const string ChildParameterName = "Child";
     
    5959      Parameters.Add(new ScopeTreeLookupParameter<ISymbolicExpressionTree>(ParentsParameterName, "The parent symbolic expression trees which should be crossed."));
    6060      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(ChildParameterName, "The child symbolic expression tree resulting from the crossover."));
     61      ParentsParameter.ActualName = "SymbolicExpressionTree";
     62      ChildParameter.ActualName = "SymbolicExpressionTree";
    6163    }
    6264
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/TracingSymbolicExpressionTreeCrossover.cs

    r8557 r9083  
    2424using HeuristicLab.Common;
    2525using HeuristicLab.Core;
    26 using HeuristicLab.EvolutionaryTracking;
    2726using HeuristicLab.Parameters;
    2827using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    3736    private const string ParentsParameterName = "Parents";
    3837    private const string ChildParameterName = "Child";
    39 
    4038
    4139    #region Parameter Properties
     
    9088      while (i != min && ReferenceEquals(nodes0[i], nodes1[i])) ++i;
    9189
    92       // add heredity information into the global variables
    93       GlobalTraceMap[Child] = new ItemList<IItem>(Parents.Select(x => GlobalCloneMap[x])); ; // map child to its corresponding parents from the previous generation
    94       GlobalFragmentMap[Child] = new GenericWrapper<ISymbolicExpressionTreeNode>(i == min ? null : nodes1[i]); // map child to the index of its fragment
     90      // map child to its corresponding parents from the previous generation
     91      GlobalTraceMap[Child] = new ItemList<IItem>(from p in Parents select GlobalCloneMap[p]);
     92      var fragment0 = new Fragment(i == min ? null : nodes0[i]); // fragment replaced in Parent0
     93      var fragment1 = new Fragment(i == min ? null : nodes1[i]); // fragment received from Parent1
     94      GlobalFragmentMap[Child] = fragment1; // map child to the index of its fragment
     95      // transaction.FragmentIn = the fragment received from the other parent
     96      // transaction.FragmentOut = the fragment that got replaced
     97      GlobalGeneticExchangeMap.Add(new GeneticExchange { FragmentIn = fragment1, FragmentOut = fragment0 });
    9598      return base.Apply();
    9699    }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/CutPoint.cs

    r8213 r9083  
    6464      }
    6565    }
    66 
    67     //public static CutPoint GetCutPoint(ISymbolicExpressionTree parent, ISymbolicExpressionTree child) {
    68     //  return GetCutPoint(parent.Root, child.Root);
    69     //}
    70 
    71     //public static CutPoint GetCutPoint(ISymbolicExpressionTree parent, ISymbolicExpressionTreeNode child) {
    72     //  return GetCutPoint(parent.Root, child);
    73     //}
    74 
    75     //public static CutPoint GetCutPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTree child) {
    76     //  return GetCutPoint(parent, child.Root);
    77     //}
    78 
    79     // child is the result of a genetic operation on parent
    80     // this method returns the index on which the two individuals start to differ
    81     //public static CutPoint GetCutPoint(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
    82     //  var e1 = parent.IterateNodesPostfix().GetEnumerator();
    83     //  var e2 = child.IterateNodesPostfix().GetEnumerator();
    84     //  int pos = -1;
    85     //  var comparer = new SymbolicExpressionTreeNodeSimilarityComparer((int)SymbolicExpressionTreeMatching.SimilarityLevel.Exact);
    86     //  while (e1.MoveNext() && e2.MoveNext())
    87     //    if (comparer.Equals(e1.Current, e2.Current))
    88     //      ++pos;
    89     //  return pos == -1 ? null : new CutPoint(parent, pos);
    90     //}
    9166  }
    9267}
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/EnumerableExtensions.cs

    r7439 r9083  
    2020#endregion
    2121
     22using System;
    2223using System.Collections.Generic;
    2324using System.Linq;
    2425using HeuristicLab.Core;
    25 using System;
    2626
    2727namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/GenericWrapper.cs

    r8557 r9083  
    66  [Item("Generic wrapper", "Wrapper class for non-item HeuristicLab objects")]
    77  [StorableClass]
    8   public class GenericWrapper<T> : NamedItem where T : class, IDeepCloneable {
     8  public class GenericWrapper<T> : Item where T : class, IDeepCloneable {
    99    [Storable]
    1010    public T Content { get; private set; }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj

    r8557 r9083  
    167167    <Compile Include="Compiler\SymbolicExpressionTreeCompiler.cs" />
    168168    <None Include="Plugin.cs.frame" />
     169    <Compile Include="GeneticExchange.cs" />
     170    <Compile Include="Fragment.cs" />
     171    <Compile Include="Interfaces\IFragment.cs" />
    169172    <Compile Include="Interfaces\Operators\ITracingSymbolicExpressionTreeOperator.cs" />
    170173    <Compile Include="TracingSymbolicExpressionTreeOperator.cs" />
     
    264267  -->
    265268  <PropertyGroup>
    266     <PreBuildEvent>set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
     269    <PreBuildEvent Condition=" '$(OS)' == 'Windows_NT' ">set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
    267270set ProjectDir=$(ProjectDir)
    268271set SolutionDir=$(SolutionDir)
     
    271274call PreBuildEvent.cmd
    272275</PreBuildEvent>
     276    <PreBuildEvent Condition=" '$(OS)' != 'Windows_NT' ">
     277export ProjectDir=$(ProjectDir)
     278export SolutionDir=$(SolutionDir)
     279
     280$SolutionDir/PreBuildEvent.sh
     281</PreBuildEvent>
    273282  </PropertyGroup>
    274283</Project>
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj.user

    r8213 r9083  
    88    <StartAction>Program</StartAction>
    99    <StartProgram>C:\Users\bburlacu\Projects\HeuristicLab\Trunk\sources\bin\HeuristicLab 3.3.exe</StartProgram>
     10    <StartArguments>/start:Optimizer /hideStarter</StartArguments>
    1011  </PropertyGroup>
    1112  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTree.cs

    r7792 r9083  
    2929    int Depth { get; }
    3030
     31    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth();
    3132    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPrefix();
    3233    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPostfix();
    33     IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth();
    3434  }
    3535}
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeNode.cs

    r7792 r9083  
    3434    int GetBranchLevel(ISymbolicExpressionTreeNode child);
    3535
     36    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth();
    3637    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPostfix();
    3738    IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPrefix();
    38     IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth();
     39    void ForEachNodePrefix(Action<ISymbolicExpressionTreeNode> a);
    3940    void ForEachNodePostfix(Action<ISymbolicExpressionTreeNode> a);
    40     void ForEachNodePrefix(Action<ISymbolicExpressionTreeNode> a);
    4141
    4242    IEnumerable<ISymbolicExpressionTreeNode> Subtrees { get; }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ChangeNodeTypeManipulation.cs

    r7514 r9083  
    2424using HeuristicLab.Core;
    2525using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     26using System.Collections.Generic;
    2627
    2728namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    2930  [Item("ChangeNodeTypeManipulation", "Selects a random tree node and changes the symbol.")]
    3031  public sealed class ChangeNodeTypeManipulation : TracingSymbolicExpressionTreeManipulator {
     32    private const int MAX_TRIES = 100;
     33
    3134    [StorableConstructor]
    3235    private ChangeNodeTypeManipulation(bool deserializing) : base(deserializing) { }
     
    4346
    4447    public static void ChangeNodeType(IRandom random, ISymbolicExpressionTree symbolicExpressionTree) {
    45       // select any node as parent (except the root node)
    46       var manipulationPoints = (from parent in symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1)
    47                                 let subtreeCount = parent.Subtrees.Count()
    48                                 from subtreeIndex in Enumerable.Range(0, subtreeCount)
    49                                 let subtree = parent.GetSubtree(subtreeIndex)
    50                                 let existingSubtreeCount = subtree.Subtrees.Count()
    51                                 // find possible symbols for the node (also considering the existing branches below it)
    52                                 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex)
    53                                                       // do not replace the existing symbol with itself
    54                                                       where symbol.Name != subtree.Symbol.Name
    55                                                       where symbol.InitialFrequency > 0
    56                                                       where existingSubtreeCount <= parent.Grammar.GetMaximumSubtreeCount(symbol)
    57                                                       where existingSubtreeCount >= parent.Grammar.GetMinimumSubtreeCount(symbol)
    58                                                       // keep only symbols that are still possible considering the existing sub-trees
    59                                                       where (from existingSubtreeIndex in Enumerable.Range(0, existingSubtreeCount)
    60                                                              let existingSubtree = subtree.GetSubtree(existingSubtreeIndex)
    61                                                              select parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex))
    62                                                              .All(x => x == true)
    63                                                       select symbol)
    64                                                       .ToList()
    65                                 where allowedSymbols.Count() > 0
    66                                 select new { Parent = parent, Child = subtree, Index = subtreeIndex, AllowedSymbols = allowedSymbols })
    67                                .ToList();
    68       if (manipulationPoints.Count == 0) { return; }
    69       var selectedManipulationPoint = manipulationPoints.SelectRandom(random);
     48      List<ISymbol> allowedSymbols = new List<ISymbol>();
     49      ISymbolicExpressionTreeNode parent;
     50      int childIndex;
     51      ISymbolicExpressionTreeNode child;
     52      // repeat until a fitting parent and child are found (MAX_TRIES times)
     53      int tries = 0;
     54      do {
     55        parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random);
     56        childIndex = random.Next(parent.SubtreeCount);
    7057
    71       var weights = selectedManipulationPoint.AllowedSymbols.Select(s => s.InitialFrequency).ToList();
    72       var newSymbol = selectedManipulationPoint.AllowedSymbols.SelectRandom(weights, random);
     58        child = parent.GetSubtree(childIndex);
     59        int existingSubtreeCount = child.SubtreeCount;
     60        allowedSymbols.Clear();
     61        foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) {
     62          // check basic properties that the new symbol must have
     63          if (symbol.Name != child.Symbol.Name &&
     64            symbol.InitialFrequency > 0 &&
     65            existingSubtreeCount <= parent.Grammar.GetMinimumSubtreeCount(symbol) &&
     66            existingSubtreeCount >= parent.Grammar.GetMaximumSubtreeCount(symbol)) {
     67            // check that all existing subtrees are also allowed for the new symbol
     68            bool allExistingSubtreesAllowed = true;
     69            for (int existingSubtreeIndex = 0; existingSubtreeIndex < existingSubtreeCount && allExistingSubtreesAllowed; existingSubtreeIndex++) {
     70              var existingSubtree = child.GetSubtree(existingSubtreeIndex);
     71              allExistingSubtreesAllowed &= parent.Grammar.IsAllowedChildSymbol(symbol, existingSubtree.Symbol, existingSubtreeIndex);
     72            }
     73            if (allExistingSubtreesAllowed) {
     74              allowedSymbols.Add(symbol);
     75            }
     76          }
     77        }
     78        tries++;
     79      } while (tries < MAX_TRIES && allowedSymbols.Count == 0);
    7380
    74       // replace the old node with the new node
    75       var newNode = newSymbol.CreateTreeNode();
    76       if (newNode.HasLocalParameters)
    77         newNode.ResetLocalParameters(random);
    78       foreach (var subtree in selectedManipulationPoint.Child.Subtrees)
    79         newNode.AddSubtree(subtree);
    80       selectedManipulationPoint.Parent.RemoveSubtree(selectedManipulationPoint.Index);
    81       selectedManipulationPoint.Parent.InsertSubtree(selectedManipulationPoint.Index, newNode);
     81      if (tries < MAX_TRIES) {
     82        var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList();
     83        var newSymbol = allowedSymbols.SelectRandom(weights, random);
     84
     85        // replace the old node with the new node
     86        var newNode = newSymbol.CreateTreeNode();
     87        if (newNode.HasLocalParameters)
     88          newNode.ResetLocalParameters(random);
     89        foreach (var subtree in child.Subtrees)
     90          newNode.AddSubtree(subtree);
     91        parent.RemoveSubtree(childIndex);
     92        parent.InsertSubtree(childIndex, newNode);
     93      }
    8294    }
    8395  }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/MultiSymbolicExpressionTreeManipulator.cs

    r7439 r9083  
    3737  [StorableClass]
    3838  public sealed class MultiSymbolicExpressionTreeManipulator : StochasticMultiBranch<ISymbolicExpressionTreeManipulator>,
     39    ITracingSymbolicExpressionTreeOperator,
    3940    ISymbolicExpressionTreeManipulator,
    4041    IStochasticOperator,
     
    4344    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
    4445    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
     46    private const string SymbolicExpressionTreeNodeComparerParameterName = "SymbolicExpressionTreeNodeComparer";
     47    private const string SymbolicExpressionTreeNodeComparerParameterDescription = "The comparison operator used to check if two symbolic expression tree nodes are equal or similar.";
    4548
    4649    public override bool CanChangeName {
     
    4952    protected override bool CreateChildOperation {
    5053      get { return true; }
     54    }
     55    public ValueParameter<ISymbolicExpressionTreeNodeComparer> SymbolicExpressionTreeNodeComparerParameter {
     56      get { return (ValueParameter<ISymbolicExpressionTreeNodeComparer>)Parameters[SymbolicExpressionTreeNodeComparerParameterName]; }
     57    }
     58    public ISymbolicExpressionTreeNodeComparer SymbolicExpressionTreeNodeComparer {
     59      get { return (ISymbolicExpressionTreeNodeComparer)SymbolicExpressionTreeNodeComparerParameter.ActualValue; }
    5160    }
    5261
     
    7180      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
    7281      Parameters.Add(new ValueLookupParameter<IntValue>(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
     82      Parameters.Add(new ValueParameter<ISymbolicExpressionTreeNodeComparer>(SymbolicExpressionTreeNodeComparerParameterName, SymbolicExpressionTreeNodeComparerParameterDescription));
    7383
    7484      List<ISymbolicExpressionTreeManipulator> list = new List<ISymbolicExpressionTreeManipulator>();
     
    110120        manipulator.MaximumSymbolicExpressionTreeLengthParameter.ActualName = MaximumSymbolicExpressionTreeLengthParameter.Name;
    111121      }
     122      var comparers = ApplicationManager.Manager.GetInstances<ISymbolicExpressionTreeNodeComparer>().ToList();
     123      if (comparers.Count > 0)
     124        foreach (var manipulator in Operators.OfType<ITracingSymbolicExpressionTreeOperator>()) {
     125          manipulator.SymbolicExpressionTreeNodeComparerParameter.ActualValue = comparers.First();
     126        }
    112127    }
    113128  }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/OnePointShaker.cs

    r7514 r9083  
    5757
    5858    protected override void Manipulate(IRandom random, ISymbolicExpressionTree tree) {
     59      OnePointShaker.Shake(random, tree, ShakingFactor);
     60    }
     61
     62    public static void Shake(IRandom random, ISymbolicExpressionTree tree, double shakingFactor) {
    5963      List<ISymbolicExpressionTreeNode> parametricNodes = new List<ISymbolicExpressionTreeNode>();
    6064      tree.Root.ForEachNodePostfix(n => {
     
    6367      if (parametricNodes.Count > 0) {
    6468        var selectedPoint = parametricNodes.SelectRandom(random);
    65         selectedPoint.ShakeLocalParameters(random, ShakingFactor);
     69        selectedPoint.ShakeLocalParameters(random, shakingFactor);
    6670      }
    6771    }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/ReplaceBranchManipulation.cs

    r7514 r9083  
    2626using HeuristicLab.Parameters;
    2727using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     28using System.Collections.Generic;
    2829
    2930namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    3132  [Item("ReplaceBranchManipulation", "Selects a branch of the tree randomly and replaces it with a newly initialized branch (using PTC2).")]
    3233  public sealed class ReplaceBranchManipulation : TracingSymbolicExpressionTreeManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
     34    private const int MAX_TRIES = 100;
    3335    private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
    3436    private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
     
    6870
    6971    public static void ReplaceRandomBranch(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, int maxTreeLength, int maxTreeDepth) {
    70       // select any node as parent (except the root node)
    71       var manipulationPoints = (from parent in symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1)
    72                                 from subtree in parent.Subtrees
    73                                 let subtreeIndex = parent.IndexOfSubtree(subtree)
    74                                 let maxLength = maxTreeLength - symbolicExpressionTree.Length + subtree.GetLength()
    75                                 let maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + subtree.GetDepth()
    76                                 // find possible symbols for the node (also considering the existing branches below it)
    77                                 let allowedSymbols = (from symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, subtreeIndex)
    78                                                       // do not replace symbol with the same symbol
    79                                                       where symbol.Name != subtree.Symbol.Name
    80                                                       where symbol.InitialFrequency > 0
    81                                                       where parent.Grammar.GetMinimumExpressionDepth(symbol) + 1 <= maxDepth
    82                                                       where parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength
    83                                                       select symbol)
    84                                                       .ToList()
    85                                 where allowedSymbols.Count > 0
    86                                 select new {
    87                                   Parent = parent,
    88                                   Child = subtree,
    89                                   Index = subtreeIndex,
    90                                   AllowedSymbols = allowedSymbols,
    91                                   MaxLength = maxLength,
    92                                   MaxDepth = maxDepth
    93                                 })
    94                                .ToList();
     72      var allowedSymbols = new List<ISymbol>();
     73      ISymbolicExpressionTreeNode parent;
     74      int childIndex;
     75      int maxLength;
     76      int maxDepth;
     77      // repeat until a fitting parent and child are found (MAX_TRIES times)
     78      int tries = 0;
     79      do {
     80        parent = symbolicExpressionTree.Root.IterateNodesPrefix().Skip(1).Where(n => n.SubtreeCount > 0).SelectRandom(random);
     81        childIndex = random.Next(parent.SubtreeCount);
     82        var child = parent.GetSubtree(childIndex);
     83        maxLength = maxTreeLength - symbolicExpressionTree.Length + child.GetLength();
     84        maxDepth = maxTreeDepth - symbolicExpressionTree.Depth + child.GetDepth();
    9585
    96       if (manipulationPoints.Count == 0) return;
    97       var selectedManipulationPoint = manipulationPoints.SelectRandom(random);
     86        allowedSymbols.Clear();
     87        foreach (var symbol in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, childIndex)) {
     88          // check basic properties that the new symbol must have
     89          if (symbol.Name != child.Symbol.Name &&
     90            symbol.InitialFrequency > 0 &&
     91            parent.Grammar.GetMinimumExpressionDepth(symbol) + 1 <= maxDepth &&
     92            parent.Grammar.GetMinimumExpressionLength(symbol) <= maxLength) {
     93            allowedSymbols.Add(symbol);
     94          }
     95        }
     96        tries++;
     97      } while (tries < MAX_TRIES && allowedSymbols.Count == 0);
    9898
    99       var weights = selectedManipulationPoint.AllowedSymbols.Select(s => s.InitialFrequency).ToList();
    100       var seedSymbol = selectedManipulationPoint.AllowedSymbols.SelectRandom(weights, random);
    101       // replace the old node with the new node
    102       var seedNode = seedSymbol.CreateTreeNode();
    103       if (seedNode.HasLocalParameters)
    104         seedNode.ResetLocalParameters(random);
     99      if (tries < MAX_TRIES) {
     100        var weights = allowedSymbols.Select(s => s.InitialFrequency).ToList();
     101        var seedSymbol = allowedSymbols.SelectRandom(weights, random);
     102        // replace the old node with the new node
     103        var seedNode = seedSymbol.CreateTreeNode();
     104        if (seedNode.HasLocalParameters)
     105          seedNode.ResetLocalParameters(random);
    105106
    106       selectedManipulationPoint.Parent.RemoveSubtree(selectedManipulationPoint.Index);
    107       selectedManipulationPoint.Parent.InsertSubtree(selectedManipulationPoint.Index, seedNode);
    108       ProbabilisticTreeCreator.PTC2(random, seedNode, selectedManipulationPoint.MaxLength, selectedManipulationPoint.MaxDepth);
     107        parent.RemoveSubtree(childIndex);
     108        parent.InsertSubtree(childIndex, seedNode);
     109        ProbabilisticTreeCreator.PTC2(random, seedNode, maxLength, maxDepth);
     110      }
    109111    }
    110112  }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Manipulators/TracingSymbolicExpressionTreeManipulator.cs

    r8557 r9083  
    2525using HeuristicLab.Common;
    2626using HeuristicLab.Core;
    27 using HeuristicLab.EvolutionaryTracking;
    2827using HeuristicLab.Parameters;
    2928using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    3736  public abstract class TracingSymbolicExpressionTreeManipulator : TracingSymbolicExpressionTreeOperator, ISymbolicExpressionTreeManipulator {
    3837    private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
     38    [Storable]
     39    private readonly Dictionary<Type, byte> manipulationTypes = new Dictionary<Type, byte>();
    3940
    4041    #region Parameter Properties
     
    5253    [StorableConstructor]
    5354    protected TracingSymbolicExpressionTreeManipulator(bool deserializing) : base(deserializing) { }
    54     protected TracingSymbolicExpressionTreeManipulator(TracingSymbolicExpressionTreeManipulator original, Cloner cloner) : base(original, cloner) { }
     55    protected TracingSymbolicExpressionTreeManipulator(TracingSymbolicExpressionTreeManipulator original, Cloner cloner)
     56      : base(original, cloner) {
     57      this.manipulationTypes = new Dictionary<Type, byte>(original.manipulationTypes);
     58    }
    5559    public TracingSymbolicExpressionTreeManipulator()
    5660      : base() {
    5761      Parameters.Add(new LookupParameter<ISymbolicExpressionTree>(SymbolicExpressionTreeParameterName, "The symbolic expression tree on which the operator should be applied."));
     62
     63      manipulationTypes.Add(typeof(FullTreeShaker), ManipulationType.FullTreeShaker);
     64      manipulationTypes.Add(typeof(OnePointShaker), ManipulationType.OnePointShaker);
     65      manipulationTypes.Add(typeof(ChangeNodeTypeManipulation), ManipulationType.ChangeNodeTypeManipulation);
     66      manipulationTypes.Add(typeof(ReplaceBranchManipulation), ManipulationType.ReplaceBranchManipulation);
    5867    }
    5968
     
    7281       * - After tree is mutated, we set GlobalTraceMap[tree] = clone and GlobalFragmentMap[tree] = modified node from tree
    7382       */
    74       ISymbolicExpressionTreeNode fragment;
     83      Fragment fragment = null;
    7584      if (GlobalTraceMap.ContainsKey(tree)) {
    76         var clone = (IItem)tree.Clone(); // create clone of tree
     85        var clone = (IItem)tree.Clone();
     86        GlobalCloneMap[clone] = GlobalCloneMap[tree];
     87        GlobalCloneMap[tree] = clone;
    7788        GlobalTraceMap[clone] = GlobalTraceMap[tree]; // clone gets parents of tree
    7889        GlobalTraceMap[tree] = new ItemList<IItem> { clone }; // tree gets clone as parent
    79         fragment = ((GenericWrapper<ISymbolicExpressionTreeNode>)GlobalFragmentMap[tree]).Content;
    80         int index = tree.IterateNodesBreadth().ToList().IndexOf(fragment); // returns -1 if fragment is not present in tree
    81         GlobalFragmentMap[clone] = new GenericWrapper<ISymbolicExpressionTreeNode>(index == -1 ? null : ((ISymbolicExpressionTree)clone).IterateNodesBreadth().ElementAt(index));
     90        fragment = (Fragment)GlobalFragmentMap[tree];
     91        int index = tree.IterateNodesBreadth().ToList().IndexOf(fragment.Root); // returns -1 if fragment is not present in tree (can happen if fragment is null)
     92        GlobalFragmentMap[clone] = new Fragment(index == -1 ? null : ((ISymbolicExpressionTree)clone).IterateNodesBreadth().ElementAt(index));
    8293      } else {
    8394        GlobalTraceMap[tree] = new ItemList<IItem> { GlobalCloneMap[tree] };
    8495      }
    8596
    86       var original = GlobalCloneMap[tree];
    87       var nodes0 = ((ISymbolicExpressionTree)original).IterateNodesBreadth().ToList();
     97      var concreteType = this.GetType();
    8898
    89       // perform mutation
     99      if (!manipulationTypes.ContainsKey(concreteType))
     100        throw new Exception(this.Name + ": Unknown manipulation type (key not found in the dictionary).");
     101
     102      var nodes0 = tree.IterateNodesBreadth().ToList(); // list of nodes before manipulation
    90103      Manipulate(RandomParameter.ActualValue, tree);
     104      var nodes1 = tree.IterateNodesBreadth().ToList(); // list of nodes after manipulation
     105      int min = Math.Min(nodes0.Count, nodes1.Count);
    91106
    92       var nodes1 = tree.IterateNodesBreadth().ToList();
     107      switch (manipulationTypes[concreteType]) {
     108        case ManipulationType.FullTreeShaker: {
     109            // the FullTreeShaker changes the local parameters of all the nodes in the tree
     110            // therefore, the whole tree is considered to be the fragment
     111            fragment = new Fragment(tree.Root.GetSubtree(0).GetSubtree(0));
     112            break;
     113          }
     114        case ManipulationType.OnePointShaker: {
     115            var original = (ISymbolicExpressionTree)GlobalCloneMap[tree];
     116            var nodesOriginal = original.IterateNodesBreadth().ToList();
     117            int i = 0;
     118            var comparer = SymbolicExpressionTreeNodeComparer;
     119            while (i != min && comparer.Equals(nodesOriginal[i], nodes1[i])) ++i;
     120            fragment = new Fragment(i == min ? null : nodes1[i], 1);
     121            break;
     122          }
     123        case ManipulationType.ChangeNodeTypeManipulation: {
     124            int i = 0;
     125            while (i != min && ReferenceEquals(nodes0[i], nodes1[i])) ++i;
     126            fragment = new Fragment(i == min ? null : nodes1[i], 1);
     127            break;
     128          }
     129        case ManipulationType.ReplaceBranchManipulation: {
     130            int i = 0;
     131            while (i != min && ReferenceEquals(nodes0[i], nodes1[i])) ++i;
     132            fragment = new Fragment(i == min ? null : nodes1[i]);
     133            break;
     134          }
     135        default:
     136          throw new Exception(Name + ": Unknown manipulaton type.");
     137      }
    93138
    94       int min = Math.Min(nodes0.Count, nodes1.Count);
    95       // some tree manipulators only change local parameters while the actual node stays the same
    96       // consequently, we need a stronger comparison than ReferenceEquals
    97       var comp = SymbolicExpressionTreeNodeComparer;
    98       if (comp == null)
    99         throw new Exception(Name + ": Could not get SymbolicExpressionTreeNodeComparerParameter!");
    100       var mismatches = new List<int>();
    101       for (int i = 0; i != min; ++i) {
    102         if (!comp.Equals(nodes0[i], nodes1[i])) {
    103           mismatches.Add(i);
    104         }
    105       }
    106       if (mismatches.Count == 0) // should never happen
    107         fragment = null;
    108       else
    109         fragment = mismatches.Count > 1 ? nodes1[mismatches[0]].Parent : nodes1[mismatches[0]];
    110       GlobalFragmentMap[tree] = new GenericWrapper<ISymbolicExpressionTreeNode>(fragment);
     139      GlobalFragmentMap[tree] = fragment;
    111140      return base.Apply();
    112141    }
    113142
    114143    protected abstract void Manipulate(IRandom random, ISymbolicExpressionTree symbolicExpressionTree);
     144
     145    private struct ManipulationType {
     146      public const byte FullTreeShaker = 1;
     147      public const byte OnePointShaker = 2;
     148      public const byte ChangeNodeTypeManipulation = 3;
     149      public const byte ReplaceBranchManipulation = 4;
     150    }
    115151  }
    116152}
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Plugin.cs

    r8213 r9083  
    2323
    2424namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    25   [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding", "Provides operators and related classes for the symbolic expression tree encoding.", "3.4.2.7997")]
     25  [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding","Provides operators and related classes for the symbolic expression tree encoding.", "3.4.3.8557")]
    2626  [PluginFile("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.dll", PluginFileType.Assembly)]
    2727  [PluginDependency("HeuristicLab.Analysis", "3.3")]
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Plugin.cs.frame

    r8213 r9083  
    2323
    2424namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
    25   [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding", "Provides operators and related classes for the symbolic expression tree encoding.", "3.4.2.7997")]
     25  [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding","Provides operators and related classes for the symbolic expression tree encoding.", "3.4.3.$WCREV$")]
    2626  [PluginFile("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.dll", PluginFileType.Assembly)]
    2727  [PluginDependency("HeuristicLab.Analysis", "3.3")]
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Properties/AssemblyInfo.cs.frame

    r7439 r9083  
    4545
    4646[assembly: AssemblyVersion("3.4.0.0")]
    47 [assembly: AssemblyFileVersion("3.4.2.$WCREV$")]
     47[assembly: AssemblyFileVersion("3.4.3.$WCREV$")]
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammar.cs

    r7439 r9083  
    181181
    182182    #region IStatefulItem methods
    183     void IStatefulItem.InitializeState() { }
     183    void IStatefulItem.InitializeState() {
     184      ReadOnly = false;
     185    }
    184186    void IStatefulItem.ClearState() {
    185187      ReadOnly = false;
     
    242244        var groupSymbol = s as GroupSymbol;
    243245        if (groupSymbol != null) RegisterGroupSymbolEvents(groupSymbol);
    244         else symbol.Changed += new EventHandler(Symbol_Changed);
     246        else s.Changed += new EventHandler(Symbol_Changed);
    245247      }
    246248    }
     
    252254        var groupSymbol = s as GroupSymbol;
    253255        if (groupSymbol != null) DeregisterGroupSymbolEvents(groupSymbol);
    254         else symbol.Changed -= new EventHandler(Symbol_Changed);
     256        else s.Changed -= new EventHandler(Symbol_Changed);
    255257      }
    256258    }
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammarBase.cs

    r7439 r9083  
    308308    }
    309309    public virtual IEnumerable<ISymbol> AllowedSymbols {
    310       get { return Symbols.Where(s => s.Enabled); }
     310      get { foreach (var s in Symbols) if (s.Enabled) yield return s; }
    311311    }
    312312    public virtual bool ContainsSymbol(ISymbol symbol) {
     
    316316    private readonly Dictionary<Tuple<string, string>, bool> cachedIsAllowedChildSymbol;
    317317    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
     318      if (allowedChildSymbols.Count == 0) return false;
    318319      if (!child.Enabled) return false;
    319320
    320321      bool result;
    321       if (cachedIsAllowedChildSymbol.TryGetValue(Tuple.Create(parent.Name, child.Name), out result)) return result;
     322      var key = Tuple.Create(parent.Name, child.Name);
     323      if (cachedIsAllowedChildSymbol.TryGetValue(key, out result)) return result;
     324
    322325      List<string> temp;
    323326      if (allowedChildSymbols.TryGetValue(parent.Name, out temp)) {
    324327        //if (temp.Contains(child.Name)) return true;
    325         if (temp.SelectMany(s => GetSymbol(s).Flatten()).Where(s => s.Name == child.Name).Any()) {
    326           cachedIsAllowedChildSymbol.Add(Tuple.Create(parent.Name, child.Name), true);
     328        if (temp.SelectMany(s => GetSymbol(s).Flatten()).Any(s => s.Name == child.Name)) {
     329          cachedIsAllowedChildSymbol.Add(key, true);
    327330          return true;
    328331        }
    329332      }
    330       cachedIsAllowedChildSymbol.Add(Tuple.Create(parent.Name, child.Name), false);
     333      cachedIsAllowedChildSymbol.Add(key, false);
    331334      return false;
    332335    }
     
    336339      if (!child.Enabled) return false;
    337340      if (IsAllowedChildSymbol(parent, child)) return true;
     341      if (allowedChildSymbolsPerIndex.Count == 0) return false;
    338342
    339343      bool result;
    340       if (cachedIsAllowedChildSymbolIndex.TryGetValue(Tuple.Create(parent.Name, child.Name, argumentIndex), out result)) return result;
     344      var key = Tuple.Create(parent.Name, child.Name, argumentIndex);
     345      if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
     346
    341347      List<string> temp;
    342       var key = Tuple.Create(parent.Name, argumentIndex);
    343       if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp)) {
    344         //if (temp.Contains(child.Name)) return true;
    345         if (temp.SelectMany(s => GetSymbol(s).Flatten()).Where(s => s.Name == child.Name).Any()) {
    346           cachedIsAllowedChildSymbolIndex.Add(Tuple.Create(parent.Name, child.Name, argumentIndex), true);
     348      if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, argumentIndex), out temp)) {
     349        if (temp.SelectMany(s => GetSymbol(s).Flatten()).Any(s => s.Name == child.Name)) {
     350          cachedIsAllowedChildSymbolIndex.Add(key, true);
    347351          return true;
    348352        }
    349353      }
    350       cachedIsAllowedChildSymbolIndex.Add(Tuple.Create(parent.Name, child.Name, argumentIndex), false);
     354      cachedIsAllowedChildSymbolIndex.Add(key, false);
    351355      return false;
    352356    }
    353357
    354358    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
    355       return from child in AllowedSymbols
    356              where IsAllowedChildSymbol(parent, child)
    357              select child;
     359      foreach (ISymbol child in AllowedSymbols) {
     360        if (IsAllowedChildSymbol(parent, child)) yield return child;
     361      }
    358362    }
    359363
    360364    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
    361       return from child in AllowedSymbols
    362              where IsAllowedChildSymbol(parent, child, argumentIndex)
    363              select child;
     365      foreach (ISymbol child in AllowedSymbols) {
     366        if (IsAllowedChildSymbol(parent, child, argumentIndex)) yield return child;
     367      }
    364368    }
    365369
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTree.cs

    r7792 r9083  
    2323using System.Collections.Generic;
    2424using System.Drawing;
     25using System.Linq;
    2526using HeuristicLab.Common;
    2627using HeuristicLab.Core;
     
    7576    }
    7677
     78    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth() {
     79      if (root == null)
     80        return Enumerable.Empty<SymbolicExpressionTreeNode>();
     81      return root.IterateNodesBreadth();
     82    }
     83
    7784    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPrefix() {
    7885      if (root == null)
    79         return new SymbolicExpressionTreeNode[0];
     86        return Enumerable.Empty<SymbolicExpressionTreeNode>();
    8087      return root.IterateNodesPrefix();
    8188    }
    8289    public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesPostfix() {
    8390      if (root == null)
    84         return new SymbolicExpressionTreeNode[0];
     91        return Enumerable.Empty<SymbolicExpressionTreeNode>();
    8592      return root.IterateNodesPostfix();
    86     }
    87     public IEnumerable<ISymbolicExpressionTreeNode> IterateNodesBreadth() {
    88       if (root == null)
    89         return new SymbolicExpressionTreeNode[0];
    90       return root.IterateNodesBreadth();
    9193    }
    9294
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeGrammar.cs

    r7439 r9083  
    2222using System;
    2323using System.Collections.Generic;
    24 using System.Linq;
    2524using HeuristicLab.Common;
    2625using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
     
    5150
    5251    public override IEnumerable<ISymbol> Symbols {
    53       get { return grammar.Symbols.Union(base.Symbols); }
     52      get {
     53        foreach (var s in grammar.Symbols) yield return s;
     54        foreach (var s in base.symbols.Values) yield return s;
     55      }
    5456    }
    5557    public override IEnumerable<ISymbol> AllowedSymbols {
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeNode.cs

    r7799 r9083  
    5353    protected SymbolicExpressionTreeNode(bool deserializing) { }
    5454    protected SymbolicExpressionTreeNode(SymbolicExpressionTreeNode original, Cloner cloner)
    55       : base() {
     55      : base(original, cloner) {
    5656      symbol = original.symbol; // symbols are reused
     57      length = original.length;
     58      depth = original.depth;
    5759      if (original.subtrees != null) {
    5860        subtrees = new List<ISymbolicExpressionTreeNode>(original.subtrees.Count);
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeTerminalNode.cs

    r7439 r9083  
    3030  public abstract class SymbolicExpressionTreeTerminalNode : SymbolicExpressionTreeNode {
    3131    public override IEnumerable<ISymbolicExpressionTreeNode> Subtrees {
    32       get {
    33         return Enumerable.Empty<ISymbolicExpressionTreeNode>();
    34       }
     32      get { return Enumerable.Empty<ISymbolicExpressionTreeNode>(); }
    3533    }
    3634
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeTopLevelNode.cs

    r7439 r9083  
    4444    public SymbolicExpressionTreeTopLevelNode(ISymbol symbol) : base(symbol) { }
    4545
    46 
    4746    public override IDeepCloneable Clone(Cloner cloner) {
    4847      return new SymbolicExpressionTreeTopLevelNode(this, cloner);
  • branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/TracingSymbolicExpressionTreeOperator.cs

    r8557 r9083  
    2424using HeuristicLab.Parameters;
    2525using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    26 
    2726using CloneMapType = HeuristicLab.Core.ItemDictionary<HeuristicLab.Core.IItem, HeuristicLab.Core.IItem>;
     27using GeneticExchangeMapType = HeuristicLab.Core.ItemList<HeuristicLab.Core.IItem>;
    2828using TraceMapType = HeuristicLab.Core.ItemDictionary<HeuristicLab.Core.IItem, HeuristicLab.Core.IItemList<HeuristicLab.Core.IItem>>;
    2929
     
    3838    private const string GlobalCloneMapParameterName = "GlobalCloneMap";
    3939    private const string GlobalFragmentMapParameterName = "GlobalFragmentMap";
     40    private const string GlobalGeneticExchangeMapParameterName = "GlobalGeneticExchangeMap";
    4041
    4142    private const string SymbolicExpressionTreeNodeComparerParameterName = "SymbolicExpressionTreeNodeComparer";
     
    5253      get { return (LookupParameter<CloneMapType>)Parameters[GlobalFragmentMapParameterName]; }
    5354    }
     55    public LookupParameter<GeneticExchangeMapType> GlobalGeneticExchangeMapParameter {
     56      get { return (LookupParameter<GeneticExchangeMapType>)Parameters[GlobalGeneticExchangeMapParameterName]; }
     57    }
    5458    public ValueParameter<ISymbolicExpressionTreeNodeComparer> SymbolicExpressionTreeNodeComparerParameter {
    5559      get { return (ValueParameter<ISymbolicExpressionTreeNodeComparer>)Parameters[SymbolicExpressionTreeNodeComparerParameterName]; }
    5660    }
    5761    #endregion
     62
     63    [StorableHook(HookType.AfterDeserialization)]
     64    private void AfterDeserialization() {
     65      if (Parameters.ContainsKey("GlobalTransactionMap"))
     66        Parameters.Remove("GlobalTransactionMap");
     67      if (!Parameters.ContainsKey(GlobalGeneticExchangeMapParameterName))
     68        Parameters.Add(new LookupParameter<GeneticExchangeMapType>(GlobalGeneticExchangeMapParameterName, "A global list of genetic exchange transactions."));
     69    }
    5870
    5971    #region Properties
     
    6678    public CloneMapType GlobalFragmentMap {
    6779      get { return GlobalFragmentMapParameter.ActualValue; }
     80    }
     81    public GeneticExchangeMapType GlobalGeneticExchangeMap {
     82      get { return GlobalGeneticExchangeMapParameter.ActualValue; }
    6883    }
    6984    public ISymbolicExpressionTreeNodeComparer SymbolicExpressionTreeNodeComparer {
     
    8095      Parameters.Add(new LookupParameter<CloneMapType>(GlobalFragmentMapParameterName, "A global map keeping track of tree fragments received via crossover."));
    8196      Parameters.Add(new LookupParameter<TraceMapType>(GlobalTraceMapParameterName, "A global cache containing tracing info."));
     97      Parameters.Add(new LookupParameter<GeneticExchangeMapType>(GlobalGeneticExchangeMapParameterName, "A global list of genetic exchange transactions."));
    8298      Parameters.Add(new ValueParameter<ISymbolicExpressionTreeNodeComparer>(SymbolicExpressionTreeNodeComparerParameterName, SymbolicExpressionTreeNodeComparerParameterDescription));
    8399    }
     
    89105      if (GlobalTraceMap == null) gScope.Variables.Add(new Variable(GlobalTraceMapParameterName, new TraceMapType()));
    90106      if (GlobalFragmentMap == null) gScope.Variables.Add(new Variable(GlobalFragmentMapParameterName, new CloneMapType()));
     107      if (GlobalGeneticExchangeMap == null) gScope.Variables.Add(new Variable(GlobalGeneticExchangeMapParameterName, new GeneticExchangeMapType()));
    91108    }
    92109  }
Note: See TracChangeset for help on using the changeset viewer.