Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 6934 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
Line 
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 {
38
39    #region properties for separation between implementation and persistence
40    [Storable(Name = "Symbols")]
41    private IEnumerable<ISymbol> StorableSymbols {
42      get { return symbols.Values.ToArray(); }
43      set { symbols = value.ToDictionary(sym => sym.Name); }
44    }
45
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    }
51
52    [Storable(Name = "AllowedChildSymbols")]
53    private IEnumerable<KeyValuePair<ISymbol, IEnumerable<ISymbol>>> StorableAllowedChildSymbols {
54      get { return allowedChildSymbols.Select(x => new KeyValuePair<ISymbol, IEnumerable<ISymbol>>(GetSymbol(x.Key), x.Value.Select(y => GetSymbol(y)).ToArray())).ToArray(); }
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 {
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(); }
61      set { allowedChildSymbolsPerIndex = value.ToDictionary(x => Tuple.Create(x.Key.Item1.Name, x.Key.Item2), x => x.Value.Select(y => y.Name).ToList()); }
62    }
63    #endregion
64
65    private bool suppressEvents;
66    protected Dictionary<string, ISymbol> symbols;
67    protected Dictionary<string, Tuple<int, int>> symbolSubtreeCount;
68    protected Dictionary<string, List<string>> allowedChildSymbols;
69    protected Dictionary<Tuple<string, int>, List<string>> allowedChildSymbolsPerIndex;
70
71    public override bool CanChangeName {
72      get { return false; }
73    }
74    public override bool CanChangeDescription {
75      get { return false; }
76    }
77
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>();
84
85      suppressEvents = false;
86    }
87
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
94      symbols = original.symbols.ToDictionary(x => x.Key, y => (ISymbol)cloner.Clone(y.Value));
95      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
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));
104
105      suppressEvents = false;
106    }
107
108    protected SymbolicExpressionGrammarBase(string name, string description)
109      : base(name, description) {
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>();
115      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
116      allowedChildSymbols = new Dictionary<string, List<string>>();
117      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
118
119      suppressEvents = false;
120    }
121
122    #region protected grammar manipulation methods
123    protected virtual void AddSymbol(ISymbol symbol) {
124      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
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      }
129      ClearCaches();
130    }
131
132    protected virtual void RemoveSymbol(ISymbol symbol) {
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          }
149        }
150        suppressEvents = true;
151        foreach (var groupSymbol in Symbols.OfType<GroupSymbol>())
152          groupSymbol.SymbolsCollection.Remove(symbol);
153        suppressEvents = false;
154      }
155      ClearCaches();
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) {
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) {
177      List<string> childSymbols;
178      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
179        childSymbols = new List<string>();
180        allowedChildSymbols.Add(parent.Name, childSymbols);
181      }
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
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
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
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      }
220
221      if (childSymbols.Contains(child.Name)) return false;
222
223      childSymbols.Add(child.Name);
224      return true;
225    }
226
227    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
228      bool changed = false;
229      List<string> childSymbols;
230      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
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();
243      }
244    }
245
246    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
261      var key = Tuple.Create(parent.Name, argumentIndex);
262      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
263        changed |= childSymbols.Remove(child.Name);
264
265      if (changed) {
266        ClearCaches();
267        OnChanged();
268      }
269    }
270
271    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
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++) {
285        var key = Tuple.Create(symbol.Name, i);
286        allowedChildSymbolsPerIndex.Remove(key);
287      }
288
289      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
290    }
291    #endregion
292
293    public virtual IEnumerable<ISymbol> Symbols {
294      get { return symbols.Values; }
295    }
296    public virtual IEnumerable<ISymbol> AllowedSymbols {
297      get { return Symbols.Where(s => s.Enabled); }
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) {
304      if (!child.Enabled) return false;
305
306      List<string> temp;
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      }
311      return false;
312    }
313
314    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
315      if (!child.Enabled) return false;
316      if (IsAllowedChildSymbol(parent, child)) return true;
317
318      List<string> temp;
319      var key = Tuple.Create(parent.Name, argumentIndex);
320      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp)) {
321        if (temp.Contains(child.Name)) return true;
322        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
323      }
324      return false;
325    }
326
327    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
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);
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
345      return result.Select(x => GetSymbol(x)).Where(s => s.Enabled);
346    }
347
348    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
349      return symbolSubtreeCount[symbol.Name].Item1;
350    }
351    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
352      return symbolSubtreeCount[symbol.Name].Item2;
353    }
354
355    protected void ClearCaches() {
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))
367                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
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))
383                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
384                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
385                                  select maxForSlot).DefaultIfEmpty(0).Sum();
386        cachedMaxExpressionLength[symbol.Name] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
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
397        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
398                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
399                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
400                             select minForSlot).DefaultIfEmpty(0).Max();
401        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
402        return cachedMinExpressionDepth[symbol.Name];
403      }
404      return temp;
405    }
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    }
413  }
414}
Note: See TracBrowser for help on using the repository browser.