Free cookie consent management tool by TermsFeed Policy Generator

source: branches/GP.Grammar.Editor/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammarBase.cs @ 6955

Last change on this file since 6955 was 6626, checked in by mkommend, 13 years ago

#1479: Corrected bug concerning the deletion of symbols in the grammar editor.

File size: 17.5 KB
RevLine 
[5686]1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
28
29namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
30  /// <summary>
31  /// The default symbolic expression grammar stores symbols and syntactic constraints for symbols.
32  /// Symbols are treated as equvivalent if they have the same name.
33  /// Syntactic constraints limit the number of allowed sub trees for a node with a symbol and which symbols are allowed
34  /// in the sub-trees of a symbol (can be specified for each sub-tree index separately).
35  /// </summary>
36  [StorableClass]
37  public abstract class SymbolicExpressionGrammarBase : NamedItem, ISymbolicExpressionGrammarBase {
[6296]38
[5686]39    #region properties for separation between implementation and persistence
[5695]40    [Storable(Name = "Symbols")]
41    private IEnumerable<ISymbol> StorableSymbols {
42      get { return symbols.Values.ToArray(); }
43      set { symbols = value.ToDictionary(sym => sym.Name); }
44    }
[5686]45
[5695]46    [Storable(Name = "SymbolSubtreeCount")]
47    private IEnumerable<KeyValuePair<ISymbol, Tuple<int, int>>> StorableSymbolSubtreeCount {
48      get { return symbolSubtreeCount.Select(x => new KeyValuePair<ISymbol, Tuple<int, int>>(GetSymbol(x.Key), x.Value)).ToArray(); }
49      set { symbolSubtreeCount = value.ToDictionary(x => x.Key.Name, x => x.Value); }
50    }
[5686]51
[5695]52    [Storable(Name = "AllowedChildSymbols")]
53    private IEnumerable<KeyValuePair<ISymbol, IEnumerable<ISymbol>>> StorableAllowedChildSymbols {
[5712]54      get { return allowedChildSymbols.Select(x => new KeyValuePair<ISymbol, IEnumerable<ISymbol>>(GetSymbol(x.Key), x.Value.Select(y => GetSymbol(y)).ToArray())).ToArray(); }
[5695]55      set { allowedChildSymbols = value.ToDictionary(x => x.Key.Name, x => x.Value.Select(y => y.Name).ToList()); }
56    }
57
58    [Storable(Name = "AllowedChildSymbolsPerIndex")]
59    private IEnumerable<KeyValuePair<Tuple<ISymbol, int>, IEnumerable<ISymbol>>> StorableAllowedChildSymbolsPerIndex {
[5712]60      get { return allowedChildSymbolsPerIndex.Select(x => new KeyValuePair<Tuple<ISymbol, int>, IEnumerable<ISymbol>>(Tuple.Create<ISymbol, int>(GetSymbol(x.Key.Item1), x.Key.Item2), x.Value.Select(y => GetSymbol(y)).ToArray())).ToArray(); }
[5695]61      set { allowedChildSymbolsPerIndex = value.ToDictionary(x => Tuple.Create(x.Key.Item1.Name, x.Key.Item2), x => x.Value.Select(y => y.Name).ToList()); }
62    }
[5686]63    #endregion
64
[6415]65    private bool suppressEvents;
[5686]66    protected Dictionary<string, ISymbol> symbols;
[5695]67    protected Dictionary<string, Tuple<int, int>> symbolSubtreeCount;
[5686]68    protected Dictionary<string, List<string>> allowedChildSymbols;
69    protected Dictionary<Tuple<string, int>, List<string>> allowedChildSymbolsPerIndex;
70
[5688]71    public override bool CanChangeName {
72      get { return false; }
73    }
74    public override bool CanChangeDescription {
75      get { return false; }
76    }
77
[5686]78    [StorableConstructor]
79    protected SymbolicExpressionGrammarBase(bool deserializing)
80      : base(deserializing) {
81      cachedMinExpressionLength = new Dictionary<string, int>();
82      cachedMaxExpressionLength = new Dictionary<string, int>();
83      cachedMinExpressionDepth = new Dictionary<string, int>();
[6296]84
85      suppressEvents = false;
[5686]86    }
[6233]87
[5686]88    protected SymbolicExpressionGrammarBase(SymbolicExpressionGrammarBase original, Cloner cloner)
89      : base(original, cloner) {
90      cachedMinExpressionLength = new Dictionary<string, int>();
91      cachedMaxExpressionLength = new Dictionary<string, int>();
92      cachedMinExpressionDepth = new Dictionary<string, int>();
93
[6233]94      symbols = original.symbols.ToDictionary(x => x.Key, y => (ISymbol)cloner.Clone(y.Value));
[5695]95      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
[5686]96
97      allowedChildSymbols = new Dictionary<string, List<string>>();
98      foreach (var element in original.allowedChildSymbols)
99        allowedChildSymbols.Add(element.Key, new List<string>(element.Value));
100
101      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
102      foreach (var element in original.allowedChildSymbolsPerIndex)
103        allowedChildSymbolsPerIndex.Add(element.Key, new List<string>(element.Value));
[6233]104
[6296]105      suppressEvents = false;
[5686]106    }
107
[5688]108    protected SymbolicExpressionGrammarBase(string name, string description)
109      : base(name, description) {
[5686]110      cachedMinExpressionLength = new Dictionary<string, int>();
111      cachedMaxExpressionLength = new Dictionary<string, int>();
112      cachedMinExpressionDepth = new Dictionary<string, int>();
113
114      symbols = new Dictionary<string, ISymbol>();
[5695]115      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
[5686]116      allowedChildSymbols = new Dictionary<string, List<string>>();
117      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
[6296]118
119      suppressEvents = false;
[5686]120    }
121
122    #region protected grammar manipulation methods
[6618]123    protected virtual void AddSymbol(ISymbol symbol) {
124      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
[6622]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      }
[6299]129      ClearCaches();
130    }
[6296]131
[6618]132    protected virtual void RemoveSymbol(ISymbol symbol) {
[6622]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);
[5686]139
[6622]140        foreach (var parent in Symbols) {
141          List<string> allowedChilds;
142          if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
143            allowedChilds.Remove(s.Name);
[5686]144
[6622]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          }
[5686]149        }
[6626]150        suppressEvents = true;
151        foreach (var groupSymbol in Symbols.OfType<GroupSymbol>())
152          groupSymbol.SymbolsCollection.Remove(symbol);
153        suppressEvents = false;
[5686]154      }
[6622]155      ClearCaches();
[5686]156    }
157
158    public virtual ISymbol GetSymbol(string symbolName) {
159      ISymbol symbol;
160      if (symbols.TryGetValue(symbolName, out symbol)) return symbol;
161      return null;
162    }
163
164    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
[6299]165      bool changed = false;
[6296]166
[6409]167      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
168        changed |= AddAllowedChildSymbolToDictionaries(p, child);
[6299]169
170      if (changed) {
171        ClearCaches();
172        OnChanged();
173      }
174    }
175
176    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child) {
[5686]177      List<string> childSymbols;
178      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
179        childSymbols = new List<string>();
180        allowedChildSymbols.Add(parent.Name, childSymbols);
181      }
[6299]182      if (childSymbols.Contains(child.Name)) return false;
[6296]183
[6299]184      suppressEvents = true;
185      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++)
186        RemoveAllowedChildSymbol(parent, child, argumentIndex);
187      suppressEvents = false;
188
189      childSymbols.Add(child.Name);
190      return true;
191    }
192
193    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
194      bool changed = false;
195
[6409]196      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
197        changed |= AddAllowedChildSymbolToDictionaries(p, child, argumentIndex);
[6299]198
199      if (changed) {
[6296]200        ClearCaches();
201        OnChanged();
202      }
[5686]203    }
204
[6299]205
206    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child, int argumentIndex) {
[6296]207      List<string> childSymbols;
[6409]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;
[6296]213
[6409]214
[5686]215      var key = Tuple.Create(parent.Name, argumentIndex);
216      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
217        childSymbols = new List<string>();
218        allowedChildSymbolsPerIndex.Add(key, childSymbols);
219      }
[6409]220
[6299]221      if (childSymbols.Contains(child.Name)) return false;
[5686]222
[6299]223      childSymbols.Add(child.Name);
224      return true;
[5686]225    }
226
227    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
[6296]228      bool changed = false;
[5792]229      List<string> childSymbols;
230      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
[6299]231        changed |= childSymbols.Remove(child.Name);
[6296]232      }
233
234      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++) {
235        var key = Tuple.Create(parent.Name, argumentIndex);
[6299]236        if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
237          changed |= childSymbols.Remove(child.Name);
[5792]238      }
[6296]239
240      if (changed) {
241        ClearCaches();
242        OnChanged();
243      }
[5686]244    }
245
246    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
[6296]247      bool changed = false;
248
[6299]249      suppressEvents = true;
[5792]250      List<string> childSymbols;
[6296]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;
[6284]257        }
[5792]258      }
[6299]259      suppressEvents = false;
[6296]260
261      var key = Tuple.Create(parent.Name, argumentIndex);
[6299]262      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
263        changed |= childSymbols.Remove(child.Name);
[6296]264
265      if (changed) {
266        ClearCaches();
267        OnChanged();
268      }
[5686]269    }
270
271    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
[6409]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);
[6620]274      if (symbols.Any(s => s.MaximumArity < maximumSubtreeCount)) throw new ArgumentException("Invalid maximum subtree count " + maximumSubtreeCount + " for " + symbol);
[6299]275
[6409]276      foreach (ISymbol s in symbols)
277        SetSubTreeCountInDictionaries(s, minimumSubtreeCount, maximumSubtreeCount);
278
[6299]279      ClearCaches();
280      OnChanged();
281    }
282
283    private void SetSubTreeCountInDictionaries(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
[6403]284      for (int i = maximumSubtreeCount; i < GetMaximumSubtreeCount(symbol); i++) {
[5686]285        var key = Tuple.Create(symbol.Name, i);
286        allowedChildSymbolsPerIndex.Remove(key);
287      }
288
[5695]289      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
[5686]290    }
291    #endregion
292
293    public virtual IEnumerable<ISymbol> Symbols {
294      get { return symbols.Values; }
295    }
296    public virtual IEnumerable<ISymbol> AllowedSymbols {
[6296]297      get { return Symbols.Where(s => s.Enabled); }
[5686]298    }
299    public virtual bool ContainsSymbol(ISymbol symbol) {
300      return symbols.ContainsKey(symbol.Name);
301    }
302
303    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
[6296]304      if (!child.Enabled) return false;
305
[5686]306      List<string> temp;
[6409]307      if (allowedChildSymbols.TryGetValue(parent.Name, out temp)) {
308        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      }
[5686]311      return false;
312    }
313
314    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
[6296]315      if (!child.Enabled) return false;
[6409]316      if (IsAllowedChildSymbol(parent, child)) return true;
[6296]317
[5686]318      List<string> temp;
[6409]319      var key = Tuple.Create(parent.Name, argumentIndex);
320      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp)) {
[5686]321        if (temp.Contains(child.Name)) return true;
[6409]322        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
323      }
[5686]324      return false;
325    }
326
327    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
[6296]328      List<string> childs;
[6409]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);
[5686]333    }
334
335    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
336      var result = Enumerable.Empty<string>();
337
338      List<string> temp;
339      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
340        result = result.Union(temp);
341      var key = Tuple.Create(parent.Name, argumentIndex);
342      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
343        result = result.Union(temp);
344
[6296]345      return result.Select(x => GetSymbol(x)).Where(s => s.Enabled);
[5686]346    }
347
348    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
[5695]349      return symbolSubtreeCount[symbol.Name].Item1;
[5686]350    }
351    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
[5695]352      return symbolSubtreeCount[symbol.Name].Item2;
[5686]353    }
354
[6618]355    protected void ClearCaches() {
[5686]356      cachedMinExpressionLength.Clear();
357      cachedMaxExpressionLength.Clear();
358      cachedMinExpressionDepth.Clear();
359    }
360
361    private Dictionary<string, int> cachedMinExpressionLength;
362    public int GetMinimumExpressionLength(ISymbol symbol) {
363      int temp;
364      if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) {
365        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
366        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
[6296]367                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
[5686]368                                                                      select GetMinimumExpressionLength(s)).DefaultIfEmpty(0).Min()
369                                              select minForSlot).DefaultIfEmpty(0).Sum();
370
371        cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue);
372        return cachedMinExpressionLength[symbol.Name];
373      }
374      return temp;
375    }
376
377    private Dictionary<string, int> cachedMaxExpressionLength;
378    public int GetMaximumExpressionLength(ISymbol symbol) {
379      int temp;
380      if (!cachedMaxExpressionLength.TryGetValue(symbol.Name, out temp)) {
381        cachedMaxExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
382        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
[6296]383                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
[5686]384                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
385                                  select maxForSlot).DefaultIfEmpty(0).Sum();
[6009]386        cachedMaxExpressionLength[symbol.Name] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
[5686]387        return cachedMaxExpressionLength[symbol.Name];
388      }
389      return temp;
390    }
391
392    private Dictionary<string, int> cachedMinExpressionDepth;
393    public int GetMinimumExpressionDepth(ISymbol symbol) {
394      int temp;
395      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
396        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
[6009]397        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
[6296]398                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
[6009]399                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
400                             select minForSlot).DefaultIfEmpty(0).Max();
401        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
[5686]402        return cachedMinExpressionDepth[symbol.Name];
403      }
404      return temp;
405    }
[6284]406
407    public event EventHandler Changed;
408    protected virtual void OnChanged() {
[6296]409      if (suppressEvents) return;
[6284]410      var handler = Changed;
411      if (handler != null) Changed(this, EventArgs.Empty);
412    }
[5686]413  }
414}
Note: See TracBrowser for help on using the repository browser.