Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2925_AutoDiffForDynamicalModels/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Grammars/SymbolicExpressionGrammarBase.cs @ 16953

Last change on this file since 16953 was 16953, checked in by gkronber, 5 years ago

#2925: made a fix in StorableProperties of SymExprGrammarBase which is necessary because of the new HEAL.Attic-based persistence.

File size: 20.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2019 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 HEAL.Attic;
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  [StorableType("E76C087C-4E10-488A-86D0-295A4265DA53")]
37  public abstract class SymbolicExpressionGrammarBase : NamedItem, ISymbolicExpressionGrammarBase {
38
39    #region properties for separation between implementation and persistence
40    private List<Action> afterDeserializationActions = new List<Action>();
41    [Storable(Name = "Symbols")]
42    private IEnumerable<ISymbol> StorableSymbols {
43      get { return symbols.Values.ToArray(); }
44      set { afterDeserializationActions.Add(() => { foreach (var s in value) symbols.Add(s.Name, s); }); }
45    }
46
47    [Storable(Name = "SymbolSubtreeCount")]
48    private IEnumerable<KeyValuePair<ISymbol, Tuple<int, int>>> StorableSymbolSubtreeCount {
49      get { return symbolSubtreeCount.Select(x => new KeyValuePair<ISymbol, Tuple<int, int>>(GetSymbol(x.Key), x.Value)).ToArray(); }
50      set { afterDeserializationActions.Add(() => { foreach (var pair in value) symbolSubtreeCount.Add(pair.Key.Name, pair.Value); }); }
51    }
52
53    [Storable(Name = "AllowedChildSymbols")]
54    private IEnumerable<KeyValuePair<ISymbol, IEnumerable<ISymbol>>> StorableAllowedChildSymbols {
55      get { return allowedChildSymbols.Select(x => new KeyValuePair<ISymbol, IEnumerable<ISymbol>>(GetSymbol(x.Key), x.Value.Select(GetSymbol).ToArray())).ToArray(); }
56      set { afterDeserializationActions.Add(() => { foreach (var pair in value) allowedChildSymbols.Add(pair.Key.Name, pair.Value.Select(y => y.Name).ToList()); }); }
57    }
58
59    [Storable(Name = "AllowedChildSymbolsPerIndex")]
60    private IEnumerable<KeyValuePair<Tuple<ISymbol, int>, IEnumerable<ISymbol>>> StorableAllowedChildSymbolsPerIndex {
61      get { return allowedChildSymbolsPerIndex.Select(x => new KeyValuePair<Tuple<ISymbol, int>, IEnumerable<ISymbol>>(Tuple.Create(GetSymbol(x.Key.Item1), x.Key.Item2), x.Value.Select(GetSymbol).ToArray())).ToArray(); }
62      set {
63        afterDeserializationActions.Add(() => {
64          foreach (var pair in value)
65            allowedChildSymbolsPerIndex.Add(Tuple.Create(pair.Key.Item1.Name, pair.Key.Item2), pair.Value.Select(y => y.Name).ToList());
66        });
67      }
68    }
69    #endregion
70
71    private bool suppressEvents;
72    protected readonly Dictionary<string, ISymbol> symbols;
73    protected readonly Dictionary<string, Tuple<int, int>> symbolSubtreeCount;
74    protected readonly Dictionary<string, List<string>> allowedChildSymbols;
75    protected readonly Dictionary<Tuple<string, int>, List<string>> allowedChildSymbolsPerIndex;
76
77    public override bool CanChangeName {
78      get { return false; }
79    }
80    public override bool CanChangeDescription {
81      get { return false; }
82    }
83
84    [StorableConstructor]
85    protected SymbolicExpressionGrammarBase(StorableConstructorFlag _) : base(_) {
86
87      symbols = new Dictionary<string, ISymbol>();
88      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
89      allowedChildSymbols = new Dictionary<string, List<string>>();
90      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
91
92      suppressEvents = false;
93    }
94
95    protected SymbolicExpressionGrammarBase(SymbolicExpressionGrammarBase original, Cloner cloner)
96      : base(original, cloner) {
97
98      symbols = original.symbols.ToDictionary(x => x.Key, y => cloner.Clone(y.Value));
99      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
100
101      allowedChildSymbols = new Dictionary<string, List<string>>();
102      foreach (var element in original.allowedChildSymbols)
103        allowedChildSymbols.Add(element.Key, new List<string>(element.Value));
104
105      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
106      foreach (var element in original.allowedChildSymbolsPerIndex)
107        allowedChildSymbolsPerIndex.Add(element.Key, new List<string>(element.Value));
108
109      suppressEvents = false;
110    }
111
112    protected SymbolicExpressionGrammarBase(string name, string description)
113      : base(name, description) {
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    [StorableHook(HookType.AfterDeserialization)]
123    private void AfterDeserialization() {
124      foreach(var a in afterDeserializationActions) {
125        a();
126      }
127    }
128
129
130    #region protected grammar manipulation methods
131    public virtual void AddSymbol(ISymbol symbol) {
132      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
133      foreach (var s in symbol.Flatten()) {
134        symbols.Add(s.Name, s);
135        int maxSubTreeCount = Math.Min(s.MinimumArity + 1, s.MaximumArity);
136        symbolSubtreeCount.Add(s.Name, Tuple.Create(s.MinimumArity, maxSubTreeCount));
137      }
138      ClearCaches();
139    }
140
141    public virtual void RemoveSymbol(ISymbol symbol) {
142      foreach (var s in symbol.Flatten()) {
143        symbols.Remove(s.Name);
144        allowedChildSymbols.Remove(s.Name);
145        for (int i = 0; i < GetMaximumSubtreeCount(s); i++)
146          allowedChildSymbolsPerIndex.Remove(Tuple.Create(s.Name, i));
147        symbolSubtreeCount.Remove(s.Name);
148
149        foreach (var parent in Symbols) {
150          List<string> allowedChilds;
151          if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
152            allowedChilds.Remove(s.Name);
153
154          for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
155            if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
156              allowedChilds.Remove(s.Name);
157          }
158        }
159        suppressEvents = true;
160        foreach (var groupSymbol in Symbols.OfType<GroupSymbol>())
161          groupSymbol.SymbolsCollection.Remove(symbol);
162        suppressEvents = false;
163      }
164      ClearCaches();
165    }
166
167    public virtual ISymbol GetSymbol(string symbolName) {
168      ISymbol symbol;
169      if (symbols.TryGetValue(symbolName, out symbol)) return symbol;
170      return null;
171    }
172
173    public virtual void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
174      bool changed = false;
175
176      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
177        changed |= AddAllowedChildSymbolToDictionaries(p, child);
178
179      if (changed) {
180        ClearCaches();
181        OnChanged();
182      }
183    }
184
185    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child) {
186      List<string> childSymbols;
187      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
188        childSymbols = new List<string>();
189        allowedChildSymbols.Add(parent.Name, childSymbols);
190      }
191      if (childSymbols.Contains(child.Name)) return false;
192
193      suppressEvents = true;
194      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++)
195        RemoveAllowedChildSymbol(parent, child, argumentIndex);
196      suppressEvents = false;
197
198      childSymbols.Add(child.Name);
199      return true;
200    }
201
202    public virtual void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
203      bool changed = false;
204
205      foreach (ISymbol p in parent.Flatten().Where(p => !(p is GroupSymbol)))
206        changed |= AddAllowedChildSymbolToDictionaries(p, child, argumentIndex);
207
208      if (changed) {
209        ClearCaches();
210        OnChanged();
211      }
212    }
213
214
215    private bool AddAllowedChildSymbolToDictionaries(ISymbol parent, ISymbol child, int argumentIndex) {
216      List<string> childSymbols;
217      if (!allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
218        childSymbols = new List<string>();
219        allowedChildSymbols.Add(parent.Name, childSymbols);
220      }
221      if (childSymbols.Contains(child.Name)) return false;
222
223
224      var key = Tuple.Create(parent.Name, argumentIndex);
225      if (!allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols)) {
226        childSymbols = new List<string>();
227        allowedChildSymbolsPerIndex.Add(key, childSymbols);
228      }
229
230      if (childSymbols.Contains(child.Name)) return false;
231
232      childSymbols.Add(child.Name);
233      return true;
234    }
235
236    public virtual void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
237      bool changed = false;
238      List<string> childSymbols;
239      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
240        changed |= childSymbols.Remove(child.Name);
241      }
242
243      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++) {
244        var key = Tuple.Create(parent.Name, argumentIndex);
245        if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
246          changed |= childSymbols.Remove(child.Name);
247      }
248
249      if (changed) {
250        ClearCaches();
251        OnChanged();
252      }
253    }
254
255    public virtual void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
256      bool changed = false;
257
258      suppressEvents = true;
259      List<string> childSymbols;
260      if (allowedChildSymbols.TryGetValue(parent.Name, out childSymbols)) {
261        if (childSymbols.Remove(child.Name)) {
262          for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
263            if (i != argumentIndex) AddAllowedChildSymbol(parent, child, i);
264          }
265          changed = true;
266        }
267      }
268      suppressEvents = false;
269
270      var key = Tuple.Create(parent.Name, argumentIndex);
271      if (allowedChildSymbolsPerIndex.TryGetValue(key, out childSymbols))
272        changed |= childSymbols.Remove(child.Name);
273
274      if (changed) {
275        ClearCaches();
276        OnChanged();
277      }
278    }
279
280    public virtual void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
281      var symbols = symbol.Flatten().Where(s => !(s is GroupSymbol));
282      if (symbols.Any(s => s.MinimumArity > minimumSubtreeCount)) throw new ArgumentException("Invalid minimum subtree count " + minimumSubtreeCount + " for " + symbol);
283      if (symbols.Any(s => s.MaximumArity < maximumSubtreeCount)) throw new ArgumentException("Invalid maximum subtree count " + maximumSubtreeCount + " for " + symbol);
284
285      foreach (ISymbol s in symbols)
286        SetSubTreeCountInDictionaries(s, minimumSubtreeCount, maximumSubtreeCount);
287
288      ClearCaches();
289      OnChanged();
290    }
291
292    private void SetSubTreeCountInDictionaries(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
293      for (int i = maximumSubtreeCount; i < GetMaximumSubtreeCount(symbol); i++) {
294        var key = Tuple.Create(symbol.Name, i);
295        allowedChildSymbolsPerIndex.Remove(key);
296      }
297
298      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
299    }
300    #endregion
301
302    public virtual IEnumerable<ISymbol> Symbols {
303      get { return symbols.Values; }
304    }
305    public virtual IEnumerable<ISymbol> AllowedSymbols {
306      get { return Symbols.Where(s => s.Enabled); }
307    }
308    public virtual bool ContainsSymbol(ISymbol symbol) {
309      return symbols.ContainsKey(symbol.Name);
310    }
311
312    private readonly Dictionary<Tuple<string, string>, bool> cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();
313    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
314      if (allowedChildSymbols.Count == 0) return false;
315      if (!child.Enabled) return false;
316
317      bool result;
318      var key = Tuple.Create(parent.Name, child.Name);
319      if (cachedIsAllowedChildSymbol.TryGetValue(key, out result)) return result;
320
321      // value has to be calculated and cached make sure this is done in only one thread
322      lock (cachedIsAllowedChildSymbol) {
323        // in case the value has been calculated on another thread in the meanwhile
324        if (cachedIsAllowedChildSymbol.TryGetValue(key, out result)) return result;
325
326        List<string> temp;
327        if (allowedChildSymbols.TryGetValue(parent.Name, out temp)) {
328          for (int i = 0; i < temp.Count; i++) {
329            var symbol = GetSymbol(temp[i]);
330            foreach (var s in symbol.Flatten())
331              if (s.Name == child.Name) {
332                cachedIsAllowedChildSymbol.Add(key, true);
333                return true;
334              }
335          }
336        }
337        cachedIsAllowedChildSymbol.Add(key, false);
338        return false;
339      }
340    }
341
342    private readonly Dictionary<Tuple<string, string, int>, bool> cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();
343    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
344      if (!child.Enabled) return false;
345      if (IsAllowedChildSymbol(parent, child)) return true;
346      if (allowedChildSymbolsPerIndex.Count == 0) return false;
347
348      bool result;
349      var key = Tuple.Create(parent.Name, child.Name, argumentIndex);
350      if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
351
352      // value has to be calculated and cached make sure this is done in only one thread
353      lock (cachedIsAllowedChildSymbolIndex) {
354        // in case the value has been calculated on another thread in the meanwhile
355        if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
356
357        List<string> temp;
358        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, argumentIndex), out temp)) {
359          for (int i = 0; i < temp.Count; i++) {
360            var symbol = GetSymbol(temp[i]);
361            foreach (var s in symbol.Flatten())
362              if (s.Name == child.Name) {
363                cachedIsAllowedChildSymbolIndex.Add(key, true);
364                return true;
365              }
366          }
367        }
368        cachedIsAllowedChildSymbolIndex.Add(key, false);
369        return false;
370      }
371    }
372
373    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
374      foreach (ISymbol child in AllowedSymbols) {
375        if (IsAllowedChildSymbol(parent, child)) yield return child;
376      }
377    }
378
379    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
380      foreach (ISymbol child in AllowedSymbols) {
381        if (IsAllowedChildSymbol(parent, child, argumentIndex)) yield return child;
382      }
383    }
384
385    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
386      return symbolSubtreeCount[symbol.Name].Item1;
387    }
388    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
389      return symbolSubtreeCount[symbol.Name].Item2;
390    }
391
392    protected void ClearCaches() {
393      cachedMinExpressionLength.Clear();
394      cachedMaxExpressionLength.Clear();
395      cachedMinExpressionDepth.Clear();
396      cachedMaxExpressionDepth.Clear();
397
398      cachedIsAllowedChildSymbol.Clear();
399      cachedIsAllowedChildSymbolIndex.Clear();
400    }
401
402    private readonly Dictionary<string, int> cachedMinExpressionLength = new Dictionary<string, int>();
403    public int GetMinimumExpressionLength(ISymbol symbol) {
404      int res;
405      if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res))
406        return res;
407
408      // value has to be calculated and cached make sure this is done in only one thread
409      lock (cachedMinExpressionLength) {
410        // in case the value has been calculated on another thread in the meanwhile
411        if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res)) return res;
412
413        GrammarUtils.CalculateMinimumExpressionLengths(this, cachedMinExpressionLength);
414        return cachedMinExpressionLength[symbol.Name];
415      }
416    }
417
418
419    private readonly Dictionary<Tuple<string, int>, int> cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();
420    public int GetMaximumExpressionLength(ISymbol symbol, int maxDepth) {
421      int temp;
422      var key = Tuple.Create(symbol.Name, maxDepth);
423      if (cachedMaxExpressionLength.TryGetValue(key, out temp)) return temp;
424      // value has to be calculated and cached make sure this is done in only one thread
425      lock (cachedMaxExpressionLength) {
426        // in case the value has been calculated on another thread in the meanwhile
427        if (cachedMaxExpressionLength.TryGetValue(key, out temp)) return temp;
428
429        cachedMaxExpressionLength[key] = int.MaxValue; // prevent infinite recursion
430        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
431                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
432                                                          where s.InitialFrequency > 0.0
433                                                          where GetMinimumExpressionDepth(s) < maxDepth
434                                                          select GetMaximumExpressionLength(s, maxDepth - 1)).DefaultIfEmpty(0).Max()
435                                  select maxForSlot).DefaultIfEmpty(0).Sum();
436        cachedMaxExpressionLength[key] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
437        return cachedMaxExpressionLength[key];
438      }
439    }
440
441    private readonly Dictionary<string, int> cachedMinExpressionDepth = new Dictionary<string, int>();
442    public int GetMinimumExpressionDepth(ISymbol symbol) {
443      int res;
444      if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res))
445        return res;
446
447      // value has to be calculated and cached make sure this is done in only one thread
448      lock (cachedMinExpressionDepth) {
449        // in case the value has been calculated on another thread in the meanwhile
450        if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res)) return res;
451
452        GrammarUtils.CalculateMinimumExpressionDepth(this, cachedMinExpressionDepth);
453        return cachedMinExpressionDepth[symbol.Name];
454      }
455    }
456
457    private readonly Dictionary<string, int> cachedMaxExpressionDepth = new Dictionary<string, int>();
458    public int GetMaximumExpressionDepth(ISymbol symbol) {
459      int temp;
460      if (cachedMaxExpressionDepth.TryGetValue(symbol.Name, out temp)) return temp;
461      // value has to be calculated and cached make sure this is done in only one thread
462      lock (cachedMaxExpressionDepth) {
463        // in case the value has been calculated on another thread in the meanwhile
464        if (cachedMaxExpressionDepth.TryGetValue(symbol.Name, out temp)) return temp;
465
466        cachedMaxExpressionDepth[symbol.Name] = int.MaxValue;
467        long maxDepth = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
468                             let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
469                                                     where s.InitialFrequency > 0.0
470                                                     select GetMaximumExpressionDepth(s)).DefaultIfEmpty(0).Max()
471                             select maxForSlot).DefaultIfEmpty(0).Max();
472        cachedMaxExpressionDepth[symbol.Name] = (int)Math.Min(maxDepth, int.MaxValue);
473        return cachedMaxExpressionDepth[symbol.Name];
474      }
475    }
476
477    public event EventHandler Changed;
478    protected virtual void OnChanged() {
479      if (suppressEvents) return;
480      var handler = Changed;
481      if (handler != null) handler(this, EventArgs.Empty);
482    }
483  }
484}
Note: See TracBrowser for help on using the repository browser.