Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1479: Created branch for grammar editing.

File size: 17.2 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    #region properties for separation between implementation and persistence
39    [Storable(Name = "Symbols")]
40    private IEnumerable<ISymbol> StorableSymbols {
41      get { return symbols.Values.ToArray(); }
42      set { symbols = value.ToDictionary(sym => sym.Name); }
43    }
44
45    [Storable(Name = "SymbolSubtreeCount")]
46    private IEnumerable<KeyValuePair<ISymbol, Tuple<int, int>>> StorableSymbolSubtreeCount {
47      get { return symbolSubtreeCount.Select(x => new KeyValuePair<ISymbol, Tuple<int, int>>(GetSymbol(x.Key), x.Value)).ToArray(); }
48      set { symbolSubtreeCount = value.ToDictionary(x => x.Key.Name, x => x.Value); }
49    }
50
51    [Storable(Name = "AllowedChildSymbols")]
52    private IEnumerable<KeyValuePair<ISymbol, IEnumerable<ISymbol>>> StorableAllowedChildSymbols {
53      get { return allowedChildSymbols.Select(x => new KeyValuePair<ISymbol, IEnumerable<ISymbol>>(GetSymbol(x.Key), x.Value.Select(y => GetSymbol(y)).ToArray())).ToArray(); }
54      set { allowedChildSymbols = value.ToDictionary(x => x.Key.Name, x => x.Value.Select(y => y.Name).ToList()); }
55    }
56
57    [Storable(Name = "AllowedChildSymbolsPerIndex")]
58    private IEnumerable<KeyValuePair<Tuple<ISymbol, int>, IEnumerable<ISymbol>>> StorableAllowedChildSymbolsPerIndex {
59      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(); }
60      set { allowedChildSymbolsPerIndex = value.ToDictionary(x => Tuple.Create(x.Key.Item1.Name, x.Key.Item2), x => x.Value.Select(y => y.Name).ToList()); }
61    }
62    #endregion
63
64    protected Dictionary<string, ISymbol> symbols;
65    protected Dictionary<string, Tuple<int, int>> symbolSubtreeCount;
66    protected Dictionary<string, List<string>> allowedChildSymbols;
67    protected Dictionary<Tuple<string, int>, List<string>> allowedChildSymbolsPerIndex;
68
69    public override bool CanChangeName {
70      get { return false; }
71    }
72    public override bool CanChangeDescription {
73      get { return false; }
74    }
75
76    [StorableConstructor]
77    protected SymbolicExpressionGrammarBase(bool deserializing)
78      : base(deserializing) {
79      cachedMinExpressionLength = new Dictionary<string, int>();
80      cachedMaxExpressionLength = new Dictionary<string, int>();
81      cachedMinExpressionDepth = new Dictionary<string, int>();
82    }
83    [StorableHook(HookType.AfterDeserialization)]
84    private void AfterDeserialization() {
85      foreach (ISymbol symbol in symbols.Values)
86        RegisterSymbolEvents(symbol);
87    }
88
89    protected SymbolicExpressionGrammarBase(SymbolicExpressionGrammarBase original, Cloner cloner)
90      : base(original, cloner) {
91      cachedMinExpressionLength = new Dictionary<string, int>();
92      cachedMaxExpressionLength = new Dictionary<string, int>();
93      cachedMinExpressionDepth = new Dictionary<string, int>();
94
95      symbols = original.symbols.ToDictionary(x => x.Key, y => (ISymbol)cloner.Clone(y.Value));
96      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
97
98      allowedChildSymbols = new Dictionary<string, List<string>>();
99      foreach (var element in original.allowedChildSymbols)
100        allowedChildSymbols.Add(element.Key, new List<string>(element.Value));
101
102      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
103      foreach (var element in original.allowedChildSymbolsPerIndex)
104        allowedChildSymbolsPerIndex.Add(element.Key, new List<string>(element.Value));
105
106      foreach (ISymbol symbol in symbols.Values)
107        RegisterSymbolEvents(symbol);
108    }
109
110    protected SymbolicExpressionGrammarBase(string name, string description)
111      : base(name, description) {
112      cachedMinExpressionLength = new Dictionary<string, int>();
113      cachedMaxExpressionLength = new Dictionary<string, int>();
114      cachedMinExpressionDepth = new Dictionary<string, int>();
115
116      symbols = new Dictionary<string, ISymbol>();
117      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
118      allowedChildSymbols = new Dictionary<string, List<string>>();
119      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
120    }
121
122    #region protected grammar manipulation methods
123    protected void AddSymbol(ISymbol symbol) {
124      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
125      RegisterSymbolEvents(symbol);
126      symbols.Add(symbol.Name, symbol);
127      symbolSubtreeCount.Add(symbol.Name, Tuple.Create(0, 0));
128      ClearCaches();
129      OnChanged();
130    }
131
132    private void RegisterSymbolEvents(ISymbol symbol) {
133      symbol.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
134      symbol.NameChanged += new EventHandler(Symbol_NameChanged);
135      symbol.Changed += new EventHandler(Symbol_Changed);
136    }
137    private void DeregisterSymbolEvents(ISymbol symbol) {
138      symbol.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
139      symbol.NameChanged -= new EventHandler(Symbol_NameChanged);
140      symbol.Changed -= new EventHandler(Symbol_Changed);
141    }
142
143    private void Symbol_NameChanging(object sender, CancelEventArgs<string> e) {
144      if (symbols.ContainsKey(e.Value)) e.Cancel = true;
145    }
146    private void Symbol_NameChanged(object sender, EventArgs e) {
147      ISymbol symbol = (ISymbol)sender;
148      string oldName = symbols.Where(x => x.Value == symbol).First().Key;
149      string newName = symbol.Name;
150
151      symbols.Remove(oldName);
152      symbols.Add(newName, symbol);
153
154      var subtreeCount = symbolSubtreeCount[oldName];
155      symbolSubtreeCount.Remove(oldName);
156      symbolSubtreeCount.Add(newName, subtreeCount);
157
158      List<string> allowedChilds;
159      if (allowedChildSymbols.TryGetValue(oldName, out allowedChilds)) {
160        allowedChildSymbols.Remove(oldName);
161        allowedChildSymbols.Add(newName, allowedChilds);
162      }
163
164      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++) {
165        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(oldName, i), out allowedChilds)) {
166          allowedChildSymbolsPerIndex.Remove(Tuple.Create(oldName, i));
167          allowedChildSymbolsPerIndex.Add(Tuple.Create(newName, i), allowedChilds);
168        }
169      }
170
171      foreach (var parent in Symbols) {
172        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
173          if (allowedChilds.Remove(oldName))
174            allowedChilds.Add(newName);
175
176        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
177          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
178            if (allowedChilds.Remove(oldName)) allowedChilds.Add(newName);
179        }
180      }
181
182      ClearCaches();
183      OnChanged();
184    }
185
186    private void Symbol_Changed(object sende, EventArgs e) {
187      ClearCaches();
188      OnChanged();
189    }
190
191    protected void RemoveSymbol(ISymbol symbol) {
192      symbols.Remove(symbol.Name);
193      allowedChildSymbols.Remove(symbol.Name);
194      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++)
195        allowedChildSymbolsPerIndex.Remove(Tuple.Create(symbol.Name, i));
196      symbolSubtreeCount.Remove(symbol.Name);
197
198      foreach (var parent in Symbols) {
199        List<string> allowedChilds;
200        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
201          allowedChilds.Remove(symbol.Name);
202
203        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
204          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
205            allowedChilds.Remove(symbol.Name);
206        }
207      }
208      DeregisterSymbolEvents(symbol);
209      ClearCaches();
210      OnChanged();
211    }
212
213    public virtual ISymbol GetSymbol(string symbolName) {
214      ISymbol symbol;
215      if (symbols.TryGetValue(symbolName, out symbol)) return symbol;
216      return null;
217    }
218
219    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
220      List<string> childSymbols;
221      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
222        childSymbols = new List<string>();
223        allowedChildSymbols.Add(parent.Name, childSymbols);
224      }
225      if (childSymbols.Contains(child.Name)) throw new ArgumentException();
226      childSymbols.Add(child.Name);
227      ClearCaches();
228      OnChanged();
229    }
230
231    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
232      var key = Tuple.Create(parent.Name, argumentIndex);
233      List<string> childSymbols;
234      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
235        childSymbols = new List<string>();
236        allowedChildSymbolsPerIndex.Add(key, childSymbols);
237      }
238
239      if (IsAllowedChildSymbol(parent, child)) throw new ArgumentException();
240      if (childSymbols.Contains(child.Name)) throw new ArgumentException();
241      childSymbols.Add(child.Name);
242      ClearCaches();
243      OnChanged();
244    }
245
246    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
247      List<string> childSymbols;
248      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
249        if (allowedChildSymbols[parent.Name].Remove(child.Name)) {
250          ClearCaches();
251          OnChanged();
252        }
253      }
254    }
255
256    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
257      var key = Tuple.Create(parent.Name, argumentIndex);
258      List<string> childSymbols;
259      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
260        if (allowedChildSymbolsPerIndex[key].Remove(child.Name)) {
261          ClearCaches();
262          OnChanged();
263        }
264      }
265    }
266
267    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
268      for (int i = GetMaximumSubtreeCount(symbol) - 1; i >= maximumSubtreeCount; i--) {
269        var key = Tuple.Create(symbol.Name, i);
270        allowedChildSymbolsPerIndex.Remove(key);
271      }
272
273      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
274      ClearCaches();
275      OnChanged();
276    }
277    #endregion
278
279    #region ISymbolicExpressionGrammarBase Members
280    public virtual IEnumerable<ISymbol> Symbols {
281      get { return symbols.Values; }
282    }
283    public virtual IEnumerable<ISymbol> AllowedSymbols {
284      get { return Symbols.Where(s => !s.InitialFrequency.IsAlmost(0.0)); }
285    }
286    public virtual bool ContainsSymbol(ISymbol symbol) {
287      return symbols.ContainsKey(symbol.Name);
288    }
289
290    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
291      List<string> temp;
292      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
293        if (temp.Contains(child.Name)) return true;
294      return false;
295    }
296
297    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
298      List<string> temp;
299      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
300        if (temp.Contains(child.Name)) return true;
301
302      var key = Tuple.Create(parent.Name, argumentIndex);
303      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
304        return temp.Contains(child.Name);
305      return false;
306    }
307
308    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
309      return from s in AllowedSymbols where IsAllowedChildSymbol(parent, s) select s;
310    }
311
312    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
313      var result = Enumerable.Empty<string>();
314
315      List<string> temp;
316      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
317        result = result.Union(temp);
318      var key = Tuple.Create(parent.Name, argumentIndex);
319      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
320        result = result.Union(temp);
321
322      return result.Select(x => GetSymbol(x)).Where(s => !s.InitialFrequency.IsAlmost(0.0));
323    }
324
325    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
326      return symbolSubtreeCount[symbol.Name].Item1;
327    }
328    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
329      return symbolSubtreeCount[symbol.Name].Item2;
330    }
331
332    private void ClearCaches() {
333      cachedMinExpressionLength.Clear();
334      cachedMaxExpressionLength.Clear();
335      cachedMinExpressionDepth.Clear();
336    }
337
338    private Dictionary<string, int> cachedMinExpressionLength;
339    public int GetMinimumExpressionLength(ISymbol symbol) {
340      int temp;
341      if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) {
342        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
343        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
344                                              let minForSlot = (long)(from s in AllowedSymbols
345                                                                      where IsAllowedChildSymbol(symbol, s, argIndex)
346                                                                      select GetMinimumExpressionLength(s)).DefaultIfEmpty(0).Min()
347                                              select minForSlot).DefaultIfEmpty(0).Sum();
348
349        cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue);
350        return cachedMinExpressionLength[symbol.Name];
351      }
352      return temp;
353    }
354
355    private Dictionary<string, int> cachedMaxExpressionLength;
356    public int GetMaximumExpressionLength(ISymbol symbol) {
357      int temp;
358      if (!cachedMaxExpressionLength.TryGetValue(symbol.Name, out temp)) {
359        cachedMaxExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
360        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
361                                  let maxForSlot = (long)(from s in AllowedSymbols
362                                                          where IsAllowedChildSymbol(symbol, s, argIndex)
363                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
364                                  select maxForSlot).DefaultIfEmpty(0).Sum();
365        cachedMaxExpressionLength[symbol.Name] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
366        return cachedMaxExpressionLength[symbol.Name];
367      }
368      return temp;
369    }
370
371    private Dictionary<string, int> cachedMinExpressionDepth;
372    public int GetMinimumExpressionDepth(ISymbol symbol) {
373      int temp;
374      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
375        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
376        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
377                             let minForSlot = (long)(from s in AllowedSymbols
378                                                     where IsAllowedChildSymbol(symbol, s, argIndex)
379                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
380                             select minForSlot).DefaultIfEmpty(0).Max();
381        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
382        return cachedMinExpressionDepth[symbol.Name];
383      }
384      return temp;
385    }
386
387    public event EventHandler Changed;
388    protected virtual void OnChanged() {
389      var handler = Changed;
390      if (handler != null) Changed(this, EventArgs.Empty);
391    }
392    #endregion
393  }
394}
Note: See TracBrowser for help on using the repository browser.