Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 12422 was 12422, checked in by mkommend, 9 years ago

#2320: Merged the encoding class and all accompanying changes in the trunk.

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