Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
09/20/11 11:12:10 (13 years ago)
Author:
mkommend
Message:

#1479: Merged grammar editor branch into trunk.

Location:
trunk/sources
Files:
1 added
23 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources

  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding

    • Property svn:ignore set to
      bin
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionSymbolFrequencyAnalyzer.cs

    r6709 r6803  
    127127          string symbolName;
    128128          if (aggregateDifferentNumberOfSubtrees) symbolName = node.Symbol.Name;
    129           else symbolName = node.Symbol.Name + "-" + node.SubtreesCount;
     129          else symbolName = node.Symbol.Name + "-" + node.SubtreeCount;
    130130          if (symbolFrequencies.ContainsKey(symbolName)) symbolFrequencies[symbolName] += 1;
    131131          else symbolFrequencies.Add(symbolName, 1);
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeCompiler.cs

    r5809 r6803  
    6262      foreach (var node in branch.IterateNodesPrefix()) {
    6363        Instruction instr = new Instruction();
    64         int subtreesCount = node.SubtreesCount;
     64        int subtreesCount = node.SubtreeCount;
    6565        if (subtreesCount > 255) throw new ArgumentException("Number of subtrees is too big (>255)");
    6666        instr.nArguments = (byte)subtreesCount;
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs

    r6233 r6803  
    179179          ReplaceWithMinimalTree(random, root, parent, argumentIndex);
    180180        } else {
    181           var allowedSymbols = (from s in parent.Grammar.Symbols
     181          var allowedSymbols = (from s in parent.Grammar.GetAllowedChildSymbols(parent.Symbol, argumentIndex)
    182182                                where s.InitialFrequency > 0.0
    183                                 where parent.Grammar.IsAllowedChildSymbol(parent.Symbol, s, argumentIndex)
    184183                                where parent.Grammar.GetMinimumExpressionDepth(s) < maxDepth - extensionDepth + 1
    185184                                where parent.Grammar.GetMaximumExpressionLength(s) > targetLength - totalListMinLength - currentLength
     
    271270                                              where s.InitialFrequency > 0.0
    272271                                              select node.Grammar.GetMaximumExpressionLength(s)).Max();
    273         if (aggregatedLongestExpressionLength < targetLength) minArity = i + 1;
     272        if (i > minArity && aggregatedLongestExpressionLength < targetLength) minArity = i + 1;
    274273        else break;
    275274      }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Crossovers/SubtreeCrossover.cs

    r5916 r6803  
    9696      int maxInsertedBranchDepth = maxTreeDepth - GetBranchLevel(parent0.Root, crossoverPoint0.Parent);
    9797
    98 
    9998      List<ISymbolicExpressionTreeNode> allowedBranches = new List<ISymbolicExpressionTreeNode>();
    10099      parent1.Root.ForEachNodePostfix((n) => {
    101100        if (n.GetLength() <= maxInsertedBranchLength &&
    102           n.GetDepth() <= maxInsertedBranchDepth &&
    103           IsMatchingPointType(crossoverPoint0, n))
     101            n.GetDepth() <= maxInsertedBranchDepth &&
     102            IsMatchingPointType(crossoverPoint0, n))
    104103          allowedBranches.Add(n);
    105104      });
     
    133132      if (newChild == null) {
    134133        // make sure that one subtree can be removed and that only the last subtree is removed
    135         return parent.Grammar.GetMinimumSubtreeCount(parent.Symbol) < parent.SubtreesCount &&
    136           cutPoint.ChildIndex == parent.SubtreesCount - 1;
     134        return parent.Grammar.GetMinimumSubtreeCount(parent.Symbol) < parent.SubtreeCount &&
     135          cutPoint.ChildIndex == parent.SubtreeCount - 1;
    137136      } else {
    138137        // check syntax constraints of direct parent - child relation
     
    146145            result &&
    147146            parent.Grammar.ContainsSymbol(n.Symbol) &&
    148             n.SubtreesCount >= parent.Grammar.GetMinimumSubtreeCount(n.Symbol) &&
    149             n.SubtreesCount <= parent.Grammar.GetMaximumSubtreeCount(n.Symbol);
     147            n.SubtreeCount >= parent.Grammar.GetMinimumSubtreeCount(n.Symbol) &&
     148            n.SubtreeCount <= parent.Grammar.GetMaximumSubtreeCount(n.Symbol);
    150149        });
    151150        return result;
     
    169168          }
    170169          // add one additional extension point if the number of sub trees for the symbol is not full
    171           if (n.SubtreesCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
     170          if (n.SubtreeCount < n.Grammar.GetMaximumSubtreeCount(n.Symbol)) {
    172171            // empty extension point
    173             internalCrossoverPoints.Add(new CutPoint(n, n.SubtreesCount));
     172            internalCrossoverPoints.Add(new CutPoint(n, n.SubtreeCount));
    174173          }
    175174        }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4.csproj

    r5809 r6803  
    167167    <Compile Include="Symbols\Argument.cs" />
    168168    <Compile Include="Symbols\ArgumentTreeNode.cs" />
     169    <Compile Include="Symbols\GroupSymbol.cs" />
    169170    <Compile Include="Symbols\StartSymbol.cs" />
    170171    <Compile Include="Symbols\InvokeFunction.cs" />
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbol.cs

    r5809 r6803  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using HeuristicLab.Core;
    2425
     
    2728    ISymbolicExpressionTreeNode CreateTreeNode();
    2829    double InitialFrequency { get; set; }
     30    bool Enabled { get; set; }
     31
     32    int MinimumArity { get; }
     33    int MaximumArity { get; }
     34
     35    IEnumerable<ISymbol> Flatten();
    2936
    3037    event EventHandler Changed;
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionGrammar.cs

    r6233 r6803  
    3535    bool ReadOnly { get; set; }
    3636    event EventHandler ReadOnlyChanged;
     37
     38    void AddSymbol(ISymbol symbol);
     39    void RemoveSymbol(ISymbol symbol);
     40
     41    void AddAllowedChildSymbol(ISymbol parent, ISymbol child);
     42    void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex);
     43    void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child);
     44    void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex);
     45
     46    void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount);
     47
     48    void StartGrammarManipulation();
     49    void FinishedGrammarManipulation();
    3750  }
    3851}
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionGrammarBase.cs

    r5809 r6803  
    2020#endregion
    2121
     22using System;
    2223using System.Collections.Generic;
    2324using HeuristicLab.Core;
     
    4142    int GetMaximumExpressionLength(ISymbol start);
    4243    int GetMinimumExpressionDepth(ISymbol start);
     44
     45    event EventHandler Changed;
    4346  }
    4447}
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Interfaces/ISymbolicExpressionTreeNode.cs

    r5809 r6803  
    3939
    4040    IEnumerable<ISymbolicExpressionTreeNode> Subtrees { get; }
    41     int SubtreesCount { get; }
     41    int SubtreeCount { get; }
    4242    ISymbolicExpressionTreeNode GetSubtree(int index);
    4343    int IndexOfSubtree(ISymbolicExpressionTreeNode tree);
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammar.cs

    r6532 r6803  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
     25using HeuristicLab.Collections;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Core;
    2628using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    27 using System.Collections.Generic;
    2829
    2930namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
     
    120121    protected SymbolicExpressionGrammar(SymbolicExpressionGrammar original, Cloner cloner)
    121122      : base(original, cloner) {
    122       foreach (ISymbol symbol in Symbols)
     123      foreach (ISymbol symbol in symbols.Values)
    123124        RegisterSymbolEvents(symbol);
    124125
     
    161162    }
    162163
    163     protected override void AddSymbol(ISymbol symbol) {
     164    protected override sealed void AddSymbol(ISymbol symbol) {
    164165      base.AddSymbol(symbol);
    165166      RegisterSymbolEvents(symbol);
    166     }
    167     protected override void RemoveSymbol(ISymbol symbol) {
     167      OnChanged();
     168    }
     169    protected override sealed void RemoveSymbol(ISymbol symbol) {
    168170      DeregisterSymbolEvents(symbol);
    169171      base.RemoveSymbol(symbol);
     172      OnChanged();
    170173    }
    171174
     
    177180    }
    178181
    179     #region IStatefulItem
     182    #region IStatefulItem methods
    180183    void IStatefulItem.InitializeState() { }
    181184    void IStatefulItem.ClearState() {
     
    184187    #endregion
    185188
     189    #region ISymbolicExpressionGrammar methods
     190    void ISymbolicExpressionGrammar.AddSymbol(ISymbol symbol) {
     191      if (ReadOnly) throw new InvalidOperationException();
     192      AddSymbol(symbol);
     193    }
     194    void ISymbolicExpressionGrammar.RemoveSymbol(ISymbol symbol) {
     195      if (ReadOnly) throw new InvalidOperationException();
     196      RemoveSymbol(symbol);
     197    }
     198
     199    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
     200      if (ReadOnly) throw new InvalidOperationException();
     201      base.AddAllowedChildSymbol(parent, child);
     202    }
     203    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     204      if (ReadOnly) throw new InvalidOperationException();
     205      base.AddAllowedChildSymbol(parent, child, argumentIndex);
     206    }
     207    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
     208      if (ReadOnly) throw new InvalidOperationException();
     209      base.RemoveAllowedChildSymbol(parent, child);
     210    }
     211    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     212      if (ReadOnly) throw new InvalidOperationException();
     213      base.RemoveAllowedChildSymbol(parent, child, argumentIndex);
     214    }
     215
     216    void ISymbolicExpressionGrammar.SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
     217      if (ReadOnly) throw new InvalidOperationException();
     218      base.SetSubtreeCount(symbol, minimumSubtreeCount, maximumSubtreeCount);
     219    }
     220
     221    private bool suppressEvents = false;
     222    void ISymbolicExpressionGrammar.StartGrammarManipulation() {
     223      suppressEvents = true;
     224    }
     225    void ISymbolicExpressionGrammar.FinishedGrammarManipulation() {
     226      suppressEvents = false;
     227      OnChanged();
     228    }
     229
     230    protected override void OnChanged() {
     231      if (suppressEvents) return;
     232      base.OnChanged();
     233    }
     234    #endregion
     235
    186236    #region symbol events
    187     protected virtual void RegisterSymbolEvents(ISymbol symbol) {
    188       symbol.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
    189       symbol.NameChanged += new EventHandler(Symbol_NameChanged);
    190     }
    191     protected virtual void DeregisterSymbolEvents(ISymbol symbol) {
    192       symbol.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
    193       symbol.NameChanged -= new EventHandler(Symbol_NameChanged);
     237    private void RegisterSymbolEvents(ISymbol symbol) {
     238      foreach (var s in symbol.Flatten()) {
     239        s.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
     240        s.NameChanged += new EventHandler(Symbol_NameChanged);
     241
     242        var groupSymbol = s as GroupSymbol;
     243        if (groupSymbol != null) RegisterGroupSymbolEvents(groupSymbol);
     244        else symbol.Changed += new EventHandler(Symbol_Changed);
     245      }
     246    }
     247    private void DeregisterSymbolEvents(ISymbol symbol) {
     248      foreach (var s in symbol.Flatten()) {
     249        s.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
     250        s.NameChanged -= new EventHandler(Symbol_NameChanged);
     251
     252        var groupSymbol = s as GroupSymbol;
     253        if (groupSymbol != null) DeregisterGroupSymbolEvents(groupSymbol);
     254        else symbol.Changed -= new EventHandler(Symbol_Changed);
     255      }
     256    }
     257
     258    private void RegisterGroupSymbolEvents(GroupSymbol groupSymbol) {
     259      groupSymbol.Changed += new EventHandler(GroupSymbol_Changed);
     260      groupSymbol.SymbolsCollection.ItemsAdded += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
     261      groupSymbol.SymbolsCollection.ItemsRemoved += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
     262      groupSymbol.SymbolsCollection.CollectionReset += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
     263    }
     264    private void DeregisterGroupSymbolEvents(GroupSymbol groupSymbol) {
     265      groupSymbol.Changed -= new EventHandler(GroupSymbol_Changed);
     266      groupSymbol.SymbolsCollection.ItemsAdded -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
     267      groupSymbol.SymbolsCollection.ItemsRemoved -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
     268      groupSymbol.SymbolsCollection.CollectionReset -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
     269    }
     270
     271    private void Symbol_Changed(object sender, EventArgs e) {
     272      ClearCaches();
     273      OnChanged();
     274    }
     275
     276    private void GroupSymbol_Changed(object sender, EventArgs e) {
     277      GroupSymbol groupSymbol = (GroupSymbol)sender;
     278      foreach (ISymbol symbol in groupSymbol.Flatten())
     279        symbol.Enabled = groupSymbol.Enabled;
     280
     281      ClearCaches();
     282      OnChanged();
    194283    }
    195284
     
    234323
    235324      ClearCaches();
     325      OnChanged();
     326    }
     327
     328    private void GroupSymbol_ItemsAdded(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
     329      foreach (ISymbol symbol in e.Items)
     330        if (!ContainsSymbol(symbol))
     331          AddSymbol(symbol);
     332      OnChanged();
     333    }
     334    private void GroupSymbol_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
     335      foreach (ISymbol symbol in e.Items)
     336        if (ContainsSymbol(symbol))
     337          RemoveSymbol(symbol);
     338      OnChanged();
     339    }
     340    private void GroupSymbol_CollectionReset(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
     341      foreach (ISymbol symbol in e.Items)
     342        if (!ContainsSymbol(symbol))
     343          AddSymbol(symbol);
     344      foreach (ISymbol symbol in e.OldItems)
     345        if (ContainsSymbol(symbol))
     346          RemoveSymbol(symbol);
     347      OnChanged();
    236348    }
    237349    #endregion
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammarBase.cs

    r6443 r6803  
    3636  [StorableClass]
    3737  public abstract class SymbolicExpressionGrammarBase : NamedItem, ISymbolicExpressionGrammarBase {
     38
    3839    #region properties for separation between implementation and persistence
    3940    [Storable(Name = "Symbols")]
     
    6263    #endregion
    6364
     65    private bool suppressEvents;
    6466    protected Dictionary<string, ISymbol> symbols;
    6567    protected Dictionary<string, Tuple<int, int>> symbolSubtreeCount;
     
    8082      cachedMaxExpressionLength = new Dictionary<string, int>();
    8183      cachedMinExpressionDepth = new Dictionary<string, int>();
     84
     85      suppressEvents = false;
    8286    }
    8387
     
    98102      foreach (var element in original.allowedChildSymbolsPerIndex)
    99103        allowedChildSymbolsPerIndex.Add(element.Key, new List<string>(element.Value));
     104
     105      suppressEvents = false;
    100106    }
    101107
     
    110116      allowedChildSymbols = new Dictionary<string, List<string>>();
    111117      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
     118
     119      suppressEvents = false;
    112120    }
    113121
     
    115123    protected virtual void AddSymbol(ISymbol symbol) {
    116124      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
    117       symbols.Add(symbol.Name, symbol);
    118       symbolSubtreeCount.Add(symbol.Name, Tuple.Create(0, 0));
     125      foreach (var s in symbol.Flatten()) {
     126        symbols.Add(s.Name, s);
     127        symbolSubtreeCount.Add(s.Name, Tuple.Create(s.MinimumArity, s.MaximumArity));
     128      }
    119129      ClearCaches();
    120130    }
    121131
    122132    protected virtual void RemoveSymbol(ISymbol symbol) {
    123       symbols.Remove(symbol.Name);
    124       allowedChildSymbols.Remove(symbol.Name);
    125       for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++)
    126         allowedChildSymbolsPerIndex.Remove(Tuple.Create(symbol.Name, i));
    127       symbolSubtreeCount.Remove(symbol.Name);
    128 
    129       foreach (var parent in Symbols) {
    130         List<string> allowedChilds;
    131         if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
    132           allowedChilds.Remove(symbol.Name);
    133 
    134         for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
    135           if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
    136             allowedChilds.Remove(symbol.Name);
     133      foreach (var s in symbol.Flatten()) {
     134        symbols.Remove(s.Name);
     135        allowedChildSymbols.Remove(s.Name);
     136        for (int i = 0; i < GetMaximumSubtreeCount(s); i++)
     137          allowedChildSymbolsPerIndex.Remove(Tuple.Create(s.Name, i));
     138        symbolSubtreeCount.Remove(s.Name);
     139
     140        foreach (var parent in Symbols) {
     141          List<string> allowedChilds;
     142          if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
     143            allowedChilds.Remove(s.Name);
     144
     145          for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
     146            if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
     147              allowedChilds.Remove(s.Name);
     148          }
    137149        }
     150        suppressEvents = true;
     151        foreach (var groupSymbol in Symbols.OfType<GroupSymbol>())
     152          groupSymbol.SymbolsCollection.Remove(symbol);
     153        suppressEvents = false;
    138154      }
    139155      ClearCaches();
     
    147163
    148164    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
     165      bool changed = false;
     166
     167      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
     168        changed |= AddAllowedChildSymbolToDictionaries(p, child);
     169
     170      if (changed) {
     171        ClearCaches();
     172        OnChanged();
     173      }
     174    }
     175
     176    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child) {
    149177      List<string> childSymbols;
    150178      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
     
    152180        allowedChildSymbols.Add(parent.Name, childSymbols);
    153181      }
    154       if (childSymbols.Contains(child.Name)) throw new ArgumentException();
     182      if (childSymbols.Contains(child.Name)) return false;
     183
     184      suppressEvents = true;
     185      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++)
     186        RemoveAllowedChildSymbol(parent, child, argumentIndex);
     187      suppressEvents = false;
     188
    155189      childSymbols.Add(child.Name);
    156       ClearCaches();
     190      return true;
    157191    }
    158192
    159193    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     194      bool changed = false;
     195
     196      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
     197        changed |= AddAllowedChildSymbolToDictionaries(p, child, argumentIndex);
     198
     199      if (changed) {
     200        ClearCaches();
     201        OnChanged();
     202      }
     203    }
     204
     205
     206    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child, int argumentIndex) {
     207      List<string> childSymbols;
     208      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
     209        childSymbols = new List<string>();
     210        allowedChildSymbols.Add(parent.Name, childSymbols);
     211      }
     212      if (childSymbols.Contains(child.Name)) return false;
     213
     214
    160215      var key = Tuple.Create(parent.Name, argumentIndex);
    161       List<string> childSymbols;
    162216      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
    163217        childSymbols = new List<string>();
     
    165219      }
    166220
    167       if (IsAllowedChildSymbol(parent, child)) throw new ArgumentException();
    168       if (childSymbols.Contains(child.Name)) throw new ArgumentException();
     221      if (childSymbols.Contains(child.Name)) return false;
     222
    169223      childSymbols.Add(child.Name);
    170       ClearCaches();
     224      return true;
    171225    }
    172226
    173227    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
     228      bool changed = false;
    174229      List<string> childSymbols;
    175230      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
    176         if (allowedChildSymbols[parent.Name].Remove(child.Name))
    177           ClearCaches();
     231        changed |= childSymbols.Remove(child.Name);
     232      }
     233
     234      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++) {
     235        var key = Tuple.Create(parent.Name, argumentIndex);
     236        if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
     237          changed |= childSymbols.Remove(child.Name);
     238      }
     239
     240      if (changed) {
     241        ClearCaches();
     242        OnChanged();
    178243      }
    179244    }
    180245
    181246    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     247      bool changed = false;
     248
     249      suppressEvents = true;
     250      List<string> childSymbols;
     251      if (allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
     252        if (childSymbols.Remove(child.Name)) {
     253          for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
     254            if (i != argumentIndex) AddAllowedChildSymbol(parent, child, i);
     255          }
     256          changed = true;
     257        }
     258      }
     259      suppressEvents = false;
     260
    182261      var key = Tuple.Create(parent.Name, argumentIndex);
    183       List<string> childSymbols;
    184       if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
    185         if (allowedChildSymbolsPerIndex[key].Remove(child.Name))
    186           ClearCaches();
     262      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
     263        changed |= childSymbols.Remove(child.Name);
     264
     265      if (changed) {
     266        ClearCaches();
     267        OnChanged();
    187268      }
    188269    }
    189270
    190271    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
    191       for (int i = GetMaximumSubtreeCount(symbol) - 1; i >= maximumSubtreeCount; i--) {
     272      var symbols = symbol.Flatten().Where(s => !(s is GroupSymbol));
     273      if (symbols.Any(s => s.MinimumArity > minimumSubtreeCount)) throw new ArgumentException("Invalid minimum subtree count " + minimumSubtreeCount + " for " + symbol);
     274      if (symbols.Any(s => s.MaximumArity < maximumSubtreeCount)) throw new ArgumentException("Invalid maximum subtree count " + maximumSubtreeCount + " for " + symbol);
     275
     276      foreach (ISymbol s in symbols)
     277        SetSubTreeCountInDictionaries(s, minimumSubtreeCount, maximumSubtreeCount);
     278
     279      ClearCaches();
     280      OnChanged();
     281    }
     282
     283    private void SetSubTreeCountInDictionaries(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
     284      for (int i = maximumSubtreeCount; i < GetMaximumSubtreeCount(symbol); i++) {
    192285        var key = Tuple.Create(symbol.Name, i);
    193286        allowedChildSymbolsPerIndex.Remove(key);
     
    195288
    196289      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
    197       ClearCaches();
    198290    }
    199291    #endregion
    200292
    201     #region ISymbolicExpressionGrammarBase Members
    202293    public virtual IEnumerable<ISymbol> Symbols {
    203294      get { return symbols.Values; }
    204295    }
    205296    public virtual IEnumerable<ISymbol> AllowedSymbols {
    206       get { return Symbols.Where(s => !s.InitialFrequency.IsAlmost(0.0)); }
     297      get { return Symbols.Where(s => s.Enabled); }
    207298    }
    208299    public virtual bool ContainsSymbol(ISymbol symbol) {
     
    211302
    212303    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
     304      if (!child.Enabled) return false;
     305
    213306      List<string> temp;
    214       if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
     307      if (allowedChildSymbols.TryGetValue(parent.Name, out temp)) {
    215308        if (temp.Contains(child.Name)) return true;
     309        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
     310      }
    216311      return false;
    217312    }
    218313
    219314    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
     315      if (!child.Enabled) return false;
     316      if (IsAllowedChildSymbol(parent, child)) return true;
     317
    220318      List<string> temp;
    221       if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
     319      var key = Tuple.Create(parent.Name, argumentIndex);
     320      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp)) {
    222321        if (temp.Contains(child.Name)) return true;
    223 
    224       var key = Tuple.Create(parent.Name, argumentIndex);
    225       if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
    226         return temp.Contains(child.Name);
     322        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
     323      }
    227324      return false;
    228325    }
    229326
    230327    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
    231       return from s in AllowedSymbols where IsAllowedChildSymbol(parent, s) select s;
     328      List<string> childs;
     329      if (!allowedChildSymbols.TryGetValue(parent.Name, out childs))
     330        return Enumerable.Empty<ISymbol>();
     331
     332      return childs.Select(x => GetSymbol(x)).Where(s => s.Enabled);
    232333    }
    233334
     
    242343        result = result.Union(temp);
    243344
    244       return result.Select(x => GetSymbol(x));
     345      return result.Select(x => GetSymbol(x)).Where(s => s.Enabled);
    245346    }
    246347
     
    251352      return symbolSubtreeCount[symbol.Name].Item2;
    252353    }
    253 
    254354
    255355    protected void ClearCaches() {
     
    265365        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
    266366        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
    267                                               let minForSlot = (long)(from s in AllowedSymbols
    268                                                                       where IsAllowedChildSymbol(symbol, s, argIndex)
     367                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
    269368                                                                      select GetMinimumExpressionLength(s)).DefaultIfEmpty(0).Min()
    270369                                              select minForSlot).DefaultIfEmpty(0).Sum();
     
    282381        cachedMaxExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
    283382        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
    284                                   let maxForSlot = (long)(from s in AllowedSymbols
    285                                                           where IsAllowedChildSymbol(symbol, s, argIndex)
     383                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
    286384                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
    287385                                  select maxForSlot).DefaultIfEmpty(0).Sum();
     
    298396        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
    299397        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
    300                              let minForSlot = (long)(from s in AllowedSymbols
    301                                                      where IsAllowedChildSymbol(symbol, s, argIndex)
     398                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
    302399                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
    303400                             select minForSlot).DefaultIfEmpty(0).Max();
     
    307404      return temp;
    308405    }
    309     #endregion
     406
     407    public event EventHandler Changed;
     408    protected virtual void OnChanged() {
     409      if (suppressEvents) return;
     410      var handler = Changed;
     411      if (handler != null) Changed(this, EventArgs.Empty);
     412    }
    310413  }
    311414}
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeGrammar.cs

    r6378 r6803  
    8181    }
    8282    public override IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
    83       return grammar.GetAllowedChildSymbols(parent).Union(base.GetAllowedChildSymbols(parent));
     83      var symbols = grammar.GetAllowedChildSymbols(parent).Union(base.GetAllowedChildSymbols(parent));
     84      return symbols.SelectMany(s => s.Flatten()).Where(s => s.Enabled && !(s is GroupSymbol));
    8485    }
    8586    public override IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
    86       return grammar.GetAllowedChildSymbols(parent, argumentIndex).Union(base.GetAllowedChildSymbols(parent, argumentIndex));
     87      var symbols = grammar.GetAllowedChildSymbols(parent, argumentIndex).Union(base.GetAllowedChildSymbols(parent, argumentIndex));
     88      return symbols.SelectMany(s => s.Flatten()).Where(s => s.Enabled && !(s is GroupSymbol));
    8789    }
    8890
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionTreeNode.cs

    r6684 r6803  
    128128    public virtual void ShakeLocalParameters(IRandom random, double shakingFactor) { }
    129129
    130     public int SubtreesCount {
     130    public int SubtreeCount {
    131131      get {
    132132        if (subtrees == null) return 0;
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/Argument.cs

    r6233 r6803  
    3232    public const string ArgumentName = "Argument";
    3333    public const string ArgumentDescription = "Symbol that represents a function argument.";
     34    private const int minimumArity = 0;
     35    private const int maximumArity = 0;
     36
     37    public override int MinimumArity {
     38      get { return minimumArity; }
     39    }
     40    public override int MaximumArity {
     41      get { return maximumArity; }
     42    }
     43
    3444    [Storable]
    3545    private int argumentIndex;
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/Defun.cs

    r5809 r6803  
    3232    public const string DefunName = "Defun";
    3333    public const string DefunDescription = "Symbol that represents a function defining node.";
     34    private const int minimumArity = 1;
     35    private const int maximumArity = 1;
     36
     37    public override int MinimumArity {
     38      get { return minimumArity; }
     39    }
     40    public override int MaximumArity {
     41      get { return maximumArity; }
     42    }
    3443
    3544    [StorableConstructor]
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/InvokeFunction.cs

    r6233 r6803  
    3232    public const string InvokeFunctionName = "InvokeFunction";
    3333    public const string InvokeFunctionDescription = "Symbol that the invocation of another function.";
     34    private const int minimumArity = 0;
     35    private const int maximumArity = byte.MaxValue;
     36
     37    public override int MinimumArity {
     38      get { return minimumArity; }
     39    }
     40    public override int MaximumArity {
     41      get { return maximumArity; }
     42    }
    3443
    3544    [Storable]
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/ProgramRootSymbol.cs

    r5809 r6803  
    2929    public const string ProgramRootSymbolName = "ProgramRootSymbol";
    3030    public const string ProgramRootSymbolDescription = "Special symbol that represents the program root node of a symbolic expression tree.";
     31    private const int minimumArity = 1;
     32    private const int maximumArity = byte.MaxValue;
     33
     34    public override int MinimumArity {
     35      get { return minimumArity; }
     36    }
     37    public override int MaximumArity {
     38      get { return maximumArity; }
     39    }
    3140
    3241    [StorableConstructor]
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/StartSymbol.cs

    r5809 r6803  
    2929    public const string StartSymbolName = "StartSymbol";
    3030    public const string StartSymbolDescription = "Special symbol that represents the starting node of the result producing branch of a symbolic expression tree.";
     31    private const int minimumArity = 1;
     32    private const int maximumArity = 1;
     33
     34    public override int MinimumArity {
     35      get { return minimumArity; }
     36    }
     37    public override int MaximumArity {
     38      get { return maximumArity; }
     39    }
    3140
    3241    [StorableConstructor]
    33     private StartSymbol(bool deserializing) : base(deserializing) { }
     42    private StartSymbol(bool deserializing)
     43      : base(deserializing) {
     44    }
    3445    private StartSymbol(StartSymbol original, Cloner cloner) : base(original, cloner) { }
    3546    public StartSymbol() : base(StartSymbol.StartSymbolName, StartSymbol.StartSymbolDescription) { }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Symbols/Symbol.cs

    r6233 r6803  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
     
    4243      }
    4344    }
     45
     46    [Storable(DefaultValue = true)]
     47    private bool enabled;
     48    public virtual bool Enabled {
     49      get { return enabled; }
     50      set {
     51        if (value != enabled) {
     52          enabled = value;
     53          OnChanged(EventArgs.Empty);
     54        }
     55      }
     56    }
     57
     58    [Storable(DefaultValue = false)]
     59    private bool @fixed;
     60    public bool Fixed {
     61      get { return @fixed; }
     62      set {
     63        if (value != @fixed) {
     64          @fixed = value;
     65          OnChanged(EventArgs.Empty);
     66        }
     67      }
     68    }
     69
    4470    public override bool CanChangeName {
    4571      get { return !(this is IReadOnlySymbol); }
     
    4874      get { return false; }
    4975    }
     76
     77    public abstract int MinimumArity { get; }
     78    public abstract int MaximumArity { get; }
    5079    #endregion
    5180
     
    5584      : base(original, cloner) {
    5685      initialFrequency = original.initialFrequency;
     86      enabled = original.enabled;
     87      @fixed = original.@fixed;
    5788    }
    5889
     
    6091      : base(name, description) {
    6192      initialFrequency = 1.0;
     93      enabled = true;
     94      @fixed = false;
     95    }
     96
     97    [StorableHook(HookType.AfterDeserialization)]
     98    private void AfterDeserialization() {
     99      // BackwardsCompatibility3.3
     100      #region Backwards compatible code, remove with 3.4
     101      if (initialFrequency.IsAlmost(0.0) && !(this is GroupSymbol)) enabled = false;
     102      #endregion
     103
    62104    }
    63105
     
    66108    }
    67109
    68     #region events
     110    public virtual IEnumerable<ISymbol> Flatten() {
     111      yield return this;
     112    }
     113
    69114    public event EventHandler Changed;
    70     protected void OnChanged(EventArgs e) {
     115    protected virtual void OnChanged(EventArgs e) {
    71116      EventHandler handlers = Changed;
    72117      if (handlers != null)
    73118        handlers(this, e);
    74119    }
    75     #endregion
    76120  }
    77121}
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Grammars.cs

    r6375 r6803  
    2727namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding_3._4.Tests {
    2828  public static class Grammars {
    29 
    3029    [StorableClass]
    3130    private class Addition : Symbol {
     31      private const int minimumArity = 1;
     32      private const int maximumArity = byte.MaxValue;
     33
     34      public override int MinimumArity {
     35        get { return minimumArity; }
     36      }
     37      public override int MaximumArity {
     38        get { return maximumArity; }
     39      }
     40
    3241      [StorableConstructor]
    3342      protected Addition(bool deserializing) : base(deserializing) { }
     
    4150    [StorableClass]
    4251    private class Subtraction : Symbol {
     52      private const int minimumArity = 1;
     53      private const int maximumArity = byte.MaxValue;
     54
     55      public override int MinimumArity {
     56        get { return minimumArity; }
     57      }
     58      public override int MaximumArity {
     59        get { return maximumArity; }
     60      }
     61
    4362      [StorableConstructor]
    4463      protected Subtraction(bool deserializing) : base(deserializing) { }
     
    5271    [StorableClass]
    5372    private class Multiplication : Symbol {
     73      private const int minimumArity = 1;
     74      private const int maximumArity = byte.MaxValue;
     75
     76      public override int MinimumArity {
     77        get { return minimumArity; }
     78      }
     79      public override int MaximumArity {
     80        get { return maximumArity; }
     81      }
     82
    5483      [StorableConstructor]
    5584      protected Multiplication(bool deserializing) : base(deserializing) { }
     
    6392    [StorableClass]
    6493    private class Division : Symbol {
     94      private const int minimumArity = 1;
     95      private const int maximumArity = byte.MaxValue;
     96
     97      public override int MinimumArity {
     98        get { return minimumArity; }
     99      }
     100      public override int MaximumArity {
     101        get { return maximumArity; }
     102      }
     103
    65104      [StorableConstructor]
    66105      protected Division(bool deserializing) : base(deserializing) { }
     
    74113    [StorableClass]
    75114    private class Terminal : Symbol {
     115      private const int minimumArity = 0;
     116      private const int maximumArity = 0;
     117
     118      public override int MinimumArity {
     119        get { return minimumArity; }
     120      }
     121      public override int MaximumArity {
     122        get { return maximumArity; }
     123      }
     124
    76125      [StorableConstructor]
    77126      protected Terminal(bool deserializing) : base(deserializing) { }
  • trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Tests/Util.cs

    r5809 r6803  
    122122
    123123        foreach (var argTreenode in defunTreeNode.IterateNodesPrefix().OfType<ArgumentTreeNode>()) {
    124           Assert.IsTrue(argTreenode.SubtreesCount == 0);
     124          Assert.IsTrue(argTreenode.SubtreeCount == 0);
    125125          Assert.IsTrue(((Argument)argTreenode.Symbol).ArgumentIndex < arity);
    126126        }
Note: See TracChangeset for help on using the changeset viewer.