Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1479: Corrected changes from trunk integration.

File size: 17.1 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      symbols.Add(symbol.Name, symbol);
126      symbolSubtreeCount.Add(symbol.Name, Tuple.Create(0, 0));
127      ClearCaches();
128    }
129
130    protected virtual void RemoveSymbol(ISymbol symbol) {
131      symbols.Remove(symbol.Name);
132      allowedChildSymbols.Remove(symbol.Name);
133      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++)
134        allowedChildSymbolsPerIndex.Remove(Tuple.Create(symbol.Name, i));
135      symbolSubtreeCount.Remove(symbol.Name);
136
137      foreach (var parent in Symbols) {
138        List<string> allowedChilds;
139        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
140          allowedChilds.Remove(symbol.Name);
141
142        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
143          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
144            allowedChilds.Remove(symbol.Name);
145        }
146      }
147    }
148
149    public virtual ISymbol GetSymbol(string symbolName) {
150      ISymbol symbol;
151      if (symbols.TryGetValue(symbolName, out symbol)) return symbol;
152      return null;
153    }
154
155    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
156      bool changed = false;
157
158      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
159        changed |= AddAllowedChildSymbolToDictionaries(p, child);
160
161      if (changed) {
162        ClearCaches();
163        OnChanged();
164      }
165    }
166
167    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child) {
168      List<string> childSymbols;
169      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
170        childSymbols = new List<string>();
171        allowedChildSymbols.Add(parent.Name, childSymbols);
172      }
173      if (childSymbols.Contains(child.Name)) return false;
174
175      suppressEvents = true;
176      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++)
177        RemoveAllowedChildSymbol(parent, child, argumentIndex);
178      suppressEvents = false;
179
180      childSymbols.Add(child.Name);
181      return true;
182    }
183
184    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
185      bool changed = false;
186
187      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
188        changed |= AddAllowedChildSymbolToDictionaries(p, child, argumentIndex);
189
190      if (changed) {
191        ClearCaches();
192        OnChanged();
193      }
194    }
195
196
197    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child, int argumentIndex) {
198      List<string> childSymbols;
199      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
200        childSymbols = new List<string>();
201        allowedChildSymbols.Add(parent.Name, childSymbols);
202      }
203      if (childSymbols.Contains(child.Name)) return false;
204
205
206      var key = Tuple.Create(parent.Name, argumentIndex);
207      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
208        childSymbols = new List<string>();
209        allowedChildSymbolsPerIndex.Add(key, childSymbols);
210      }
211
212      if (childSymbols.Contains(child.Name)) return false;
213
214      childSymbols.Add(child.Name);
215      return true;
216    }
217
218    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
219      bool changed = false;
220      List<string> childSymbols;
221      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
222        changed |= childSymbols.Remove(child.Name);
223      }
224
225      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++) {
226        var key = Tuple.Create(parent.Name, argumentIndex);
227        if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
228          changed |= childSymbols.Remove(child.Name);
229      }
230
231      if (changed) {
232        ClearCaches();
233        OnChanged();
234      }
235    }
236
237    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
238      bool changed = false;
239
240      suppressEvents = true;
241      List<string> childSymbols;
242      if (allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
243        if (childSymbols.Remove(child.Name)) {
244          for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
245            if (i != argumentIndex) AddAllowedChildSymbol(parent, child, i);
246          }
247          changed = true;
248        }
249      }
250      suppressEvents = false;
251
252      var key = Tuple.Create(parent.Name, argumentIndex);
253      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
254        changed |= childSymbols.Remove(child.Name);
255
256      if (changed) {
257        ClearCaches();
258        OnChanged();
259      }
260    }
261
262    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
263      var symbols = symbol.Flatten().Where(s => !(s is GroupSymbol));
264      if (symbols.Any(s => s.MinimumArity > minimumSubtreeCount)) throw new ArgumentException("Invalid minimum subtree count " + minimumSubtreeCount + " for " + symbol);
265      if (symbols.Any(s => s.MaximumArity < maximumSubtreeCount)) throw new ArgumentException("Invalid maximum subtree count " + maximumSubtreeCount + " for " + symbol);
266
267      foreach (ISymbol s in symbols)
268        SetSubTreeCountInDictionaries(s, minimumSubtreeCount, maximumSubtreeCount);
269
270      ClearCaches();
271      OnChanged();
272    }
273
274    private void SetSubTreeCountInDictionaries(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
275      for (int i = maximumSubtreeCount; i < GetMaximumSubtreeCount(symbol); i++) {
276        var key = Tuple.Create(symbol.Name, i);
277        allowedChildSymbolsPerIndex.Remove(key);
278      }
279
280      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
281    }
282    #endregion
283
284    public virtual IEnumerable<ISymbol> Symbols {
285      get { return symbols.Values; }
286    }
287    public virtual IEnumerable<ISymbol> AllowedSymbols {
288      get { return Symbols.Where(s => s.Enabled); }
289    }
290    public virtual bool ContainsSymbol(ISymbol symbol) {
291      return symbols.ContainsKey(symbol.Name);
292    }
293
294    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
295      if (!child.Enabled) return false;
296
297      List<string> temp;
298      if (allowedChildSymbols.TryGetValue(parent.Name, out temp)) {
299        if (temp.Contains(child.Name)) return true;
300        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
301      }
302      return false;
303    }
304
305    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
306      if (!child.Enabled) return false;
307      if (IsAllowedChildSymbol(parent, child)) return true;
308
309      List<string> temp;
310      var key = Tuple.Create(parent.Name, argumentIndex);
311      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp)) {
312        if (temp.Contains(child.Name)) return true;
313        if (temp.SelectMany(s => GetSymbol(s).Flatten().Select(n => n.Name)).Contains(child.Name)) return true;
314      }
315      return false;
316    }
317
318    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
319      List<string> childs;
320      if (!allowedChildSymbols.TryGetValue(parent.Name, out childs))
321        return Enumerable.Empty<ISymbol>();
322
323      return childs.Select(x => GetSymbol(x)).Where(s => s.Enabled);
324    }
325
326    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
327      var result = Enumerable.Empty<string>();
328
329      List<string> temp;
330      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
331        result = result.Union(temp);
332      var key = Tuple.Create(parent.Name, argumentIndex);
333      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
334        result = result.Union(temp);
335
336      return result.Select(x => GetSymbol(x)).Where(s => s.Enabled);
337    }
338
339    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
340      return symbolSubtreeCount[symbol.Name].Item1;
341    }
342    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
343      return symbolSubtreeCount[symbol.Name].Item2;
344    }
345
346    protected void ClearCaches() {
347      cachedMinExpressionLength.Clear();
348      cachedMaxExpressionLength.Clear();
349      cachedMinExpressionDepth.Clear();
350    }
351
352    private Dictionary<string, int> cachedMinExpressionLength;
353    public int GetMinimumExpressionLength(ISymbol symbol) {
354      int temp;
355      if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) {
356        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
357        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
358                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
359                                                                      select GetMinimumExpressionLength(s)).DefaultIfEmpty(0).Min()
360                                              select minForSlot).DefaultIfEmpty(0).Sum();
361
362        cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue);
363        return cachedMinExpressionLength[symbol.Name];
364      }
365      return temp;
366    }
367
368    private Dictionary<string, int> cachedMaxExpressionLength;
369    public int GetMaximumExpressionLength(ISymbol symbol) {
370      int temp;
371      if (!cachedMaxExpressionLength.TryGetValue(symbol.Name, out temp)) {
372        cachedMaxExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
373        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
374                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
375                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
376                                  select maxForSlot).DefaultIfEmpty(0).Sum();
377        cachedMaxExpressionLength[symbol.Name] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
378        return cachedMaxExpressionLength[symbol.Name];
379      }
380      return temp;
381    }
382
383    private Dictionary<string, int> cachedMinExpressionDepth;
384    public int GetMinimumExpressionDepth(ISymbol symbol) {
385      int temp;
386      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
387        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
388        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
389                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
390                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
391                             select minForSlot).DefaultIfEmpty(0).Max();
392        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
393        return cachedMinExpressionDepth[symbol.Name];
394      }
395      return temp;
396    }
397
398    public event EventHandler Changed;
399    protected virtual void OnChanged() {
400      if (suppressEvents) return;
401      var handler = Changed;
402      if (handler != null) Changed(this, EventArgs.Empty);
403    }
404  }
405}
Note: See TracBrowser for help on using the repository browser.