Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Grammars/SymbolicExpressionGrammarBase.cs @ 14792

Last change on this file since 14792 was 14186, checked in by swagner, 8 years ago

#2526: Updated year of copyrights in license headers

File size: 23.5 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2016 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 { foreach (var s in value) symbols.Add(s.Name, s); }
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 { foreach (var pair in value) symbolSubtreeCount.Add(pair.Key.Name, pair.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(GetSymbol).ToArray())).ToArray(); }
55      set { foreach (var pair in value) allowedChildSymbols.Add(pair.Key.Name, pair.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(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      }
65    }
66    #endregion
67
68    private bool suppressEvents;
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;
73
74    public override bool CanChangeName {
75      get { return false; }
76    }
77    public override bool CanChangeDescription {
78      get { return false; }
79    }
80
81    [StorableConstructor]
82    protected SymbolicExpressionGrammarBase(bool deserializing)
83      : base(deserializing) {
84      cachedMinExpressionLength = new Dictionary<string, int>();
85      cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();
86      cachedMinExpressionDepth = new Dictionary<string, int>();
87      cachedMaxExpressionDepth = new Dictionary<string, int>();
88
89      cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();
90      cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();
91
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
97      suppressEvents = false;
98    }
99
100    protected SymbolicExpressionGrammarBase(SymbolicExpressionGrammarBase original, Cloner cloner)
101      : base(original, cloner) {
102      cachedMinExpressionLength = new Dictionary<string, int>();
103      cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();
104      cachedMinExpressionDepth = new Dictionary<string, int>();
105      cachedMaxExpressionDepth = new Dictionary<string, int>();
106
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));
111      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>(original.symbolSubtreeCount);
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));
120
121      suppressEvents = false;
122    }
123
124    protected SymbolicExpressionGrammarBase(string name, string description)
125      : base(name, description) {
126      cachedMinExpressionLength = new Dictionary<string, int>();
127      cachedMaxExpressionLength = new Dictionary<Tuple<string, int>, int>();
128      cachedMinExpressionDepth = new Dictionary<string, int>();
129      cachedMaxExpressionDepth = new Dictionary<string, int>();
130
131      cachedIsAllowedChildSymbol = new Dictionary<Tuple<string, string>, bool>();
132      cachedIsAllowedChildSymbolIndex = new Dictionary<Tuple<string, string, int>, bool>();
133
134      symbols = new Dictionary<string, ISymbol>();
135      symbolSubtreeCount = new Dictionary<string, Tuple<int, int>>();
136      allowedChildSymbols = new Dictionary<string, List<string>>();
137      allowedChildSymbolsPerIndex = new Dictionary<Tuple<string, int>, List<string>>();
138
139      suppressEvents = false;
140    }
141
142    #region protected grammar manipulation methods
143    public virtual void AddSymbol(ISymbol symbol) {
144      if (ContainsSymbol(symbol)) throw new ArgumentException("Symbol " + symbol + " is already defined.");
145      foreach (var s in symbol.Flatten()) {
146        symbols.Add(s.Name, s);
147        int maxSubTreeCount = Math.Min(s.MinimumArity + 1, s.MaximumArity);
148        symbolSubtreeCount.Add(s.Name, Tuple.Create(s.MinimumArity, maxSubTreeCount));
149      }
150      ClearCaches();
151    }
152
153    public virtual void RemoveSymbol(ISymbol symbol) {
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);
160
161        foreach (var parent in Symbols) {
162          List<string> allowedChilds;
163          if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
164            allowedChilds.Remove(s.Name);
165
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          }
170        }
171        suppressEvents = true;
172        foreach (var groupSymbol in Symbols.OfType<GroupSymbol>())
173          groupSymbol.SymbolsCollection.Remove(symbol);
174        suppressEvents = false;
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
185    public virtual void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
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) {
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      suppressEvents = true;
206      for (int argumentIndex = 0; argumentIndex < GetMaximumSubtreeCount(parent); argumentIndex++)
207        RemoveAllowedChildSymbol(parent, child, argumentIndex);
208      suppressEvents = false;
209
210      childSymbols.Add(child.Name);
211      return true;
212    }
213
214    public virtual void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
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
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
242      if (childSymbols.Contains(child.Name)) return false;
243
244      childSymbols.Add(child.Name);
245      return true;
246    }
247
248    public virtual void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
249      bool changed = false;
250      List<string> childSymbols;
251      if (allowedChildSymbols.TryGetValue(child.Name, out childSymbols)) {
252        changed |= childSymbols.Remove(child.Name);
253      }
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      }
265    }
266
267    public virtual void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
268      bool changed = false;
269
270      suppressEvents = true;
271      List<string> childSymbols;
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        }
279      }
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      }
290    }
291
292    public virtual void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
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++) {
306        var key = Tuple.Create(symbol.Name, i);
307        allowedChildSymbolsPerIndex.Remove(key);
308      }
309
310      symbolSubtreeCount[symbol.Name] = Tuple.Create(minimumSubtreeCount, maximumSubtreeCount);
311    }
312    #endregion
313
314    public virtual IEnumerable<ISymbol> Symbols {
315      get { return symbols.Values; }
316    }
317    public virtual IEnumerable<ISymbol> AllowedSymbols {
318      get { return Symbols.Where(s => s.Enabled); }
319    }
320    public virtual bool ContainsSymbol(ISymbol symbol) {
321      return symbols.ContainsKey(symbol.Name);
322    }
323
324    private readonly Dictionary<Tuple<string, string>, bool> cachedIsAllowedChildSymbol;
325    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child) {
326      if (allowedChildSymbols.Count == 0) return false;
327      if (!child.Enabled) return false;
328
329      bool result;
330      var key = Tuple.Create(parent.Name, child.Name);
331      if (cachedIsAllowedChildSymbol.TryGetValue(key, out result)) return result;
332
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          for (int i = 0; i < temp.Count; i++) {
341            var symbol = GetSymbol(temp[i]);
342            foreach (var s in symbol.Flatten())
343              if (s.Name == child.Name) {
344                cachedIsAllowedChildSymbol.Add(key, true);
345                return true;
346              }
347          }
348        }
349        cachedIsAllowedChildSymbol.Add(key, false);
350        return false;
351      }
352    }
353
354    private readonly Dictionary<Tuple<string, string, int>, bool> cachedIsAllowedChildSymbolIndex;
355    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
356      if (!child.Enabled) return false;
357      if (IsAllowedChildSymbol(parent, child)) return true;
358      if (allowedChildSymbolsPerIndex.Count == 0) return false;
359
360      bool result;
361      var key = Tuple.Create(parent.Name, child.Name, argumentIndex);
362      if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
363
364      // value has to be calculated and cached make sure this is done in only one thread
365      lock (cachedIsAllowedChildSymbolIndex) {
366        // in case the value has been calculated on another thread in the meanwhile
367        if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
368
369        List<string> temp;
370        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, argumentIndex), out temp)) {
371          for (int i = 0; i < temp.Count; i++) {
372            var symbol = GetSymbol(temp[i]);
373            foreach (var s in symbol.Flatten())
374              if (s.Name == child.Name) {
375                cachedIsAllowedChildSymbolIndex.Add(key, true);
376                return true;
377              }
378          }
379        }
380        cachedIsAllowedChildSymbolIndex.Add(key, false);
381        return false;
382      }
383    }
384
385    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
386      foreach (ISymbol child in AllowedSymbols) {
387        if (IsAllowedChildSymbol(parent, child)) yield return child;
388      }
389    }
390
391    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
392      foreach (ISymbol child in AllowedSymbols) {
393        if (IsAllowedChildSymbol(parent, child, argumentIndex)) yield return child;
394      }
395    }
396
397    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
398      return symbolSubtreeCount[symbol.Name].Item1;
399    }
400    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
401      return symbolSubtreeCount[symbol.Name].Item2;
402    }
403
404    protected void ClearCaches() {
405      cachedMinExpressionLength.Clear();
406      cachedMaxExpressionLength.Clear();
407      cachedMinExpressionDepth.Clear();
408      cachedMaxExpressionDepth.Clear();
409
410      cachedIsAllowedChildSymbol.Clear();
411      cachedIsAllowedChildSymbolIndex.Clear();
412    }
413
414    private readonly Dictionary<string, int> cachedMinExpressionLength;
415    public int GetMinimumExpressionLength(ISymbol symbol) {
416      int res;
417      if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res))
418        return res;
419
420      // value has to be calculated and cached make sure this is done in only one thread
421      lock (cachedMinExpressionLength) {
422        // in case the value has been calculated on another thread in the meanwhile
423        if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res)) return res;
424
425        res = GetMinimumExpressionLengthRec(symbol);
426        foreach (var entry in cachedMinExpressionLength.Where(e => e.Value >= int.MaxValue).ToList()) {
427          if (entry.Key != symbol.Name) cachedMinExpressionLength.Remove(entry.Key);
428        }
429        return res;
430      }
431    }
432
433    private int GetMinimumExpressionLengthRec(ISymbol symbol) {
434      int temp;
435      if (!cachedMinExpressionLength.TryGetValue(symbol.Name, out temp)) {
436        cachedMinExpressionLength[symbol.Name] = int.MaxValue; // prevent infinite recursion
437        long sumOfMinExpressionLengths = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
438                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
439                                                                      where s.InitialFrequency > 0.0
440                                                                      select GetMinimumExpressionLengthRec(s)).DefaultIfEmpty(0).Min()
441                                              select minForSlot).DefaultIfEmpty(0).Sum();
442
443        cachedMinExpressionLength[symbol.Name] = (int)Math.Min(sumOfMinExpressionLengths, int.MaxValue);
444        return cachedMinExpressionLength[symbol.Name];
445      }
446      return temp;
447    }
448
449    private readonly Dictionary<Tuple<string, int>, int> cachedMaxExpressionLength;
450    public int GetMaximumExpressionLength(ISymbol symbol, int maxDepth) {
451      int temp;
452      var key = Tuple.Create(symbol.Name, maxDepth);
453      if (cachedMaxExpressionLength.TryGetValue(key, out temp)) return temp;
454      // value has to be calculated and cached make sure this is done in only one thread
455      lock (cachedMaxExpressionLength) {
456        // in case the value has been calculated on another thread in the meanwhile
457        if (cachedMaxExpressionLength.TryGetValue(key, out temp)) return temp;
458
459        cachedMaxExpressionLength[key] = int.MaxValue; // prevent infinite recursion
460        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
461                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
462                                                          where s.InitialFrequency > 0.0
463                                                          where GetMinimumExpressionDepth(s) < maxDepth
464                                                          select GetMaximumExpressionLength(s, maxDepth - 1)).DefaultIfEmpty(0).Max()
465                                  select maxForSlot).DefaultIfEmpty(0).Sum();
466        cachedMaxExpressionLength[key] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
467        return cachedMaxExpressionLength[key];
468      }
469    }
470
471    private readonly Dictionary<string, int> cachedMinExpressionDepth;
472    public int GetMinimumExpressionDepth(ISymbol symbol) {
473      int res;
474      if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res))
475        return res;
476
477      // value has to be calculated and cached make sure this is done in only one thread
478      lock (cachedMinExpressionDepth) {
479        // in case the value has been calculated on another thread in the meanwhile
480        if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res)) return res;
481
482        res = GetMinimumExpressionDepthRec(symbol);
483        foreach (var entry in cachedMinExpressionDepth.Where(e => e.Value >= int.MaxValue).ToList()) {
484          if (entry.Key != symbol.Name) cachedMinExpressionDepth.Remove(entry.Key);
485        }
486        return res;
487      }
488    }
489    private int GetMinimumExpressionDepthRec(ISymbol symbol) {
490      int temp;
491      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
492        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
493        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
494                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
495                                                     where s.InitialFrequency > 0.0
496                                                     select GetMinimumExpressionDepthRec(s)).DefaultIfEmpty(0).Min()
497                             select minForSlot).DefaultIfEmpty(0).Max();
498        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
499        return cachedMinExpressionDepth[symbol.Name];
500      }
501      return temp;
502    }
503
504    private readonly Dictionary<string, int> cachedMaxExpressionDepth;
505    public int GetMaximumExpressionDepth(ISymbol symbol) {
506      int temp;
507      if (cachedMaxExpressionDepth.TryGetValue(symbol.Name, out temp)) return temp;
508      // value has to be calculated and cached make sure this is done in only one thread
509      lock (cachedMaxExpressionDepth) {
510        // in case the value has been calculated on another thread in the meanwhile
511        if (cachedMaxExpressionDepth.TryGetValue(symbol.Name, out temp)) return temp;
512
513        cachedMaxExpressionDepth[symbol.Name] = int.MaxValue;
514        long maxDepth = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
515                             let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
516                                                     where s.InitialFrequency > 0.0
517                                                     select GetMaximumExpressionDepth(s)).DefaultIfEmpty(0).Max()
518                             select maxForSlot).DefaultIfEmpty(0).Max();
519        cachedMaxExpressionDepth[symbol.Name] = (int)Math.Min(maxDepth, int.MaxValue);
520        return cachedMaxExpressionDepth[symbol.Name];
521      }
522    }
523
524    public event EventHandler Changed;
525    protected virtual void OnChanged() {
526      if (suppressEvents) return;
527      var handler = Changed;
528      if (handler != null) handler(this, EventArgs.Empty);
529    }
530  }
531}
Note: See TracBrowser for help on using the repository browser.