Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammarBase.cs @ 6347

Last change on this file since 6347 was 6233, checked in by mkommend, 14 years ago

#1532:

  • Enabled renaming of symbols
  • Fixed cloning of grammers
  • Added readonly attribute in grammars to lock grammars during the algorithm run
  • Removed useless clone method in cloner
  • Changed CheckedItemCollectionViews to enable scrolling during the locked state
File size: 16.6 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
96      symbols = original.symbols.ToDictionary(x => x.Key, y => (ISymbol)cloner.Clone(y.Value));
97      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
98
99      allowedChildSymbols = new Dictionary<string, List<string>>();
100      foreach (var element in original.allowedChildSymbols)
101        allowedChildSymbols.Add(element.Key, new List<string>(element.Value));
102
103      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
104      foreach (var element in original.allowedChildSymbolsPerIndex)
105        allowedChildSymbolsPerIndex.Add(element.Key, new List<string>(element.Value));
106
107      foreach (ISymbol symbol in symbols.Values)
108        RegisterSymbolEvents(symbol);
109    }
110
111    protected SymbolicExpressionGrammarBase(string name, string description)
112      : base(name, description) {
113      cachedMinExpressionLength = new Dictionary<string, int>();
114      cachedMaxExpressionLength = new Dictionary<string, int>();
115      cachedMinExpressionDepth = new Dictionary<string, int>();
116
117      symbols = new Dictionary<string, ISymbol>();
118      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
119      allowedChildSymbols = new Dictionary<string, List<string>>();
120      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
121    }
122
123    #region protected grammar manipulation methods
124    protected void AddSymbol(ISymbol symbol) {
125      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
126      RegisterSymbolEvents(symbol);
127      symbols.Add(symbol.Name, symbol);
128      symbolSubtreeCount.Add(symbol.Name, Tuple.Create(0, 0));
129      ClearCaches();
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    }
136    private void DeregisterSymbolEvents(ISymbol symbol) {
137      symbol.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
138      symbol.NameChanged -= new EventHandler(Symbol_NameChanged);
139    }
140
141    private void Symbol_NameChanging(object sender, CancelEventArgs<string> e) {
142      if (symbols.ContainsKey(e.Value)) e.Cancel = true;
143    }
144    private void Symbol_NameChanged(object sender, EventArgs e) {
145      ISymbol symbol = (ISymbol)sender;
146      string oldName = symbols.Where(x => x.Value == symbol).First().Key;
147      string newName = symbol.Name;
148
149      symbols.Remove(oldName);
150      symbols.Add(newName, symbol);
151
152      var subtreeCount = symbolSubtreeCount[oldName];
153      symbolSubtreeCount.Remove(oldName);
154      symbolSubtreeCount.Add(newName, subtreeCount);
155
156      List<string> allowedChilds;
157      if (allowedChildSymbols.TryGetValue(oldName, out allowedChilds)) {
158        allowedChildSymbols.Remove(oldName);
159        allowedChildSymbols.Add(newName, allowedChilds);
160      }
161
162      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++) {
163        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(oldName, i), out allowedChilds)) {
164          allowedChildSymbolsPerIndex.Remove(Tuple.Create(oldName, i));
165          allowedChildSymbolsPerIndex.Add(Tuple.Create(newName, i), allowedChilds);
166        }
167      }
168
169      foreach (var parent in Symbols) {
170        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
171          if (allowedChilds.Remove(oldName))
172            allowedChilds.Add(newName);
173
174        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
175          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
176            if (allowedChilds.Remove(oldName)) allowedChilds.Add(newName);
177        }
178      }
179
180      ClearCaches();
181    }
182
183    protected void RemoveSymbol(ISymbol symbol) {
184      symbols.Remove(symbol.Name);
185      allowedChildSymbols.Remove(symbol.Name);
186      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++)
187        allowedChildSymbolsPerIndex.Remove(Tuple.Create(symbol.Name, i));
188      symbolSubtreeCount.Remove(symbol.Name);
189
190      foreach (var parent in Symbols) {
191        List<string> allowedChilds;
192        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
193          allowedChilds.Remove(symbol.Name);
194
195        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
196          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
197            allowedChilds.Remove(symbol.Name);
198        }
199      }
200      DeregisterSymbolEvents(symbol);
201      ClearCaches();
202    }
203
204    public virtual ISymbol GetSymbol(string symbolName) {
205      ISymbol symbol;
206      if (symbols.TryGetValue(symbolName, out symbol)) return symbol;
207      return null;
208    }
209
210    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
211      List<string> childSymbols;
212      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
213        childSymbols = new List<string>();
214        allowedChildSymbols.Add(parent.Name, childSymbols);
215      }
216      if (childSymbols.Contains(child.Name)) throw new ArgumentException();
217      childSymbols.Add(child.Name);
218      ClearCaches();
219    }
220
221    protected void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
222      var key = Tuple.Create(parent.Name, argumentIndex);
223      List<string> childSymbols;
224      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
225        childSymbols = new List<string>();
226        allowedChildSymbolsPerIndex.Add(key, childSymbols);
227      }
228
229      if (IsAllowedChildSymbol(parent, child)) throw new ArgumentException();
230      if (childSymbols.Contains(child.Name)) throw new ArgumentException();
231      childSymbols.Add(child.Name);
232      ClearCaches();
233    }
234
235    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
236      List<string> childSymbols;
237      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
238        if (allowedChildSymbols[parent.Name].Remove(child.Name))
239          ClearCaches();
240      }
241    }
242
243    protected void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
244      var key = Tuple.Create(parent.Name, argumentIndex);
245      List<string> childSymbols;
246      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
247        if (allowedChildSymbolsPerIndex[key].Remove(child.Name))
248          ClearCaches();
249      }
250    }
251
252    protected void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
253      for (int i = GetMaximumSubtreeCount(symbol) - 1; i >= maximumSubtreeCount; i--) {
254        var key = Tuple.Create(symbol.Name, i);
255        allowedChildSymbolsPerIndex.Remove(key);
256      }
257
258      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
259      ClearCaches();
260    }
261    #endregion
262
263    #region ISymbolicExpressionGrammarBase Members
264    public virtual IEnumerable<ISymbol> Symbols {
265      get { return symbols.Values; }
266    }
267    public virtual IEnumerable<ISymbol> AllowedSymbols {
268      get { return Symbols.Where(s => !s.InitialFrequency.IsAlmost(0.0)); }
269    }
270    public virtual bool ContainsSymbol(ISymbol symbol) {
271      return symbols.ContainsKey(symbol.Name);
272    }
273
274    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
275      List<string> temp;
276      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
277        if (temp.Contains(child.Name)) return true;
278      return false;
279    }
280
281    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
282      List<string> temp;
283      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
284        if (temp.Contains(child.Name)) return true;
285
286      var key = Tuple.Create(parent.Name, argumentIndex);
287      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
288        return temp.Contains(child.Name);
289      return false;
290    }
291
292    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
293      return from s in AllowedSymbols where IsAllowedChildSymbol(parent, s) select s;
294    }
295
296    public virtual IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
297      var result = Enumerable.Empty<string>();
298
299      List<string> temp;
300      if (allowedChildSymbols.TryGetValue(parent.Name, out temp))
301        result = result.Union(temp);
302      var key = Tuple.Create(parent.Name, argumentIndex);
303      if (allowedChildSymbolsPerIndex.TryGetValue(key, out temp))
304        result = result.Union(temp);
305
306      return result.Select(x => GetSymbol(x));
307    }
308
309    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
310      return symbolSubtreeCount[symbol.Name].Item1;
311    }
312    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
313      return symbolSubtreeCount[symbol.Name].Item2;
314    }
315
316
317    private void ClearCaches() {
318      cachedMinExpressionLength.Clear();
319      cachedMaxExpressionLength.Clear();
320      cachedMinExpressionDepth.Clear();
321    }
322
323    private Dictionary<string, int> cachedMinExpressionLength;
324    public int GetMinimumExpressionLength(ISymbol symbol) {
325      int temp;
326      if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) {
327        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
328        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
329                                              let minForSlot = (long)(from s in AllowedSymbols
330                                                                      where IsAllowedChildSymbol(symbol, s, argIndex)
331                                                                      select GetMinimumExpressionLength(s)).DefaultIfEmpty(0).Min()
332                                              select minForSlot).DefaultIfEmpty(0).Sum();
333
334        cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue);
335        return cachedMinExpressionLength[symbol.Name];
336      }
337      return temp;
338    }
339
340    private Dictionary<string, int> cachedMaxExpressionLength;
341    public int GetMaximumExpressionLength(ISymbol symbol) {
342      int temp;
343      if (!cachedMaxExpressionLength.TryGetValue(symbol.Name, out temp)) {
344        cachedMaxExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
345        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
346                                  let maxForSlot = (long)(from s in AllowedSymbols
347                                                          where IsAllowedChildSymbol(symbol, s, argIndex)
348                                                          select GetMaximumExpressionLength(s)).DefaultIfEmpty(0).Max()
349                                  select maxForSlot).DefaultIfEmpty(0).Sum();
350        cachedMaxExpressionLength[symbol.Name] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
351        return cachedMaxExpressionLength[symbol.Name];
352      }
353      return temp;
354    }
355
356    private Dictionary<string, int> cachedMinExpressionDepth;
357    public int GetMinimumExpressionDepth(ISymbol symbol) {
358      int temp;
359      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
360        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
361        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
362                             let minForSlot = (long)(from s in AllowedSymbols
363                                                     where IsAllowedChildSymbol(symbol, s, argIndex)
364                                                     select GetMinimumExpressionDepth(s)).DefaultIfEmpty(0).Min()
365                             select minForSlot).DefaultIfEmpty(0).Max();
366        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
367        return cachedMinExpressionDepth[symbol.Name];
368      }
369      return temp;
370    }
371    #endregion
372  }
373}
Note: See TracBrowser for help on using the repository browser.