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, 7 years ago

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

File size: 23.3 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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          if (temp.SelectMany(s => GetSymbol(s).Flatten()).Any(s => s.Name == child.Name)) {
341            cachedIsAllowedChildSymbol.Add(key, true);
342            return true;
343          }
344        }
345        cachedIsAllowedChildSymbol.Add(key, false);
346        return false;
347      }
348    }
349
350    private readonly Dictionary<Tuple<string, string, int>, bool> cachedIsAllowedChildSymbolIndex;
351    public virtual bool IsAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
352      if (!child.Enabled) return false;
353      if (IsAllowedChildSymbol(parent, child)) return true;
354      if (allowedChildSymbolsPerIndex.Count == 0) return false;
355
356      bool result;
357      var key = Tuple.Create(parent.Name, child.Name, argumentIndex);
358      if (cachedIsAllowedChildSymbolIndex.TryGetValue(key, out result)) return result;
359
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          }
371        }
372        cachedIsAllowedChildSymbolIndex.Add(key, false);
373        return false;
374      }
375    }
376
377    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent) {
378      foreach (ISymbol child in AllowedSymbols) {
379        if (IsAllowedChildSymbol(parent, child)) yield return child;
380      }
381    }
382
383    public IEnumerable<ISymbol> GetAllowedChildSymbols(ISymbol parent, int argumentIndex) {
384      foreach (ISymbol child in AllowedSymbols) {
385        if (IsAllowedChildSymbol(parent, child, argumentIndex)) yield return child;
386      }
387    }
388
389    public virtual int GetMinimumSubtreeCount(ISymbol symbol) {
390      return symbolSubtreeCount[symbol.Name].Item1;
391    }
392    public virtual int GetMaximumSubtreeCount(ISymbol symbol) {
393      return symbolSubtreeCount[symbol.Name].Item2;
394    }
395
396    protected void ClearCaches() {
397      cachedMinExpressionLength.Clear();
398      cachedMaxExpressionLength.Clear();
399      cachedMinExpressionDepth.Clear();
400      cachedMaxExpressionDepth.Clear();
401
402      cachedIsAllowedChildSymbol.Clear();
403      cachedIsAllowedChildSymbolIndex.Clear();
404    }
405
406    private readonly Dictionary<string, int> cachedMinExpressionLength;
407    public int GetMinimumExpressionLength(ISymbol symbol) {
408      int res;
409      if (cachedMinExpressionLength.TryGetValue(symbol.Name, out res))
410        return res;
411
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;
422      }
423    }
424
425    private int GetMinimumExpressionLengthRec(ISymbol symbol) {
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))
430                                              let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
431                                                                      where s.InitialFrequency > 0.0
432                                                                      select GetMinimumExpressionLengthRec(s)).DefaultIfEmpty(0).Min()
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
441    private readonly Dictionary<Tuple<string, int>, int> cachedMaxExpressionLength;
442    public int GetMaximumExpressionLength(ISymbol symbol, int maxDepth) {
443      int temp;
444      var key = Tuple.Create(symbol.Name, maxDepth);
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
451        cachedMaxExpressionLength[key] = int.MaxValue; // prevent infinite recursion
452        long sumOfMaxTrees = 1 + (from argIndex in Enumerable.Range(0, GetMaximumSubtreeCount(symbol))
453                                  let maxForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
454                                                          where s.InitialFrequency > 0.0
455                                                          where GetMinimumExpressionDepth(s) < maxDepth
456                                                          select GetMaximumExpressionLength(s, maxDepth - 1)).DefaultIfEmpty(0).Max()
457                                  select maxForSlot).DefaultIfEmpty(0).Sum();
458        cachedMaxExpressionLength[key] = (int)Math.Min(sumOfMaxTrees, int.MaxValue);
459        return cachedMaxExpressionLength[key];
460      }
461    }
462
463    private readonly Dictionary<string, int> cachedMinExpressionDepth;
464    public int GetMinimumExpressionDepth(ISymbol symbol) {
465      int res;
466      if (cachedMinExpressionDepth.TryGetValue(symbol.Name, out res))
467        return res;
468
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;
479      }
480    }
481    private int GetMinimumExpressionDepthRec(ISymbol symbol) {
482      int temp;
483      if (!cachedMinExpressionDepth.TryGetValue(symbol.Name, out temp)) {
484        cachedMinExpressionDepth[symbol.Name] = int.MaxValue; // prevent infinite recursion
485        long minDepth = 1 + (from argIndex in Enumerable.Range(0, GetMinimumSubtreeCount(symbol))
486                             let minForSlot = (long)(from s in GetAllowedChildSymbols(symbol, argIndex)
487                                                     where s.InitialFrequency > 0.0
488                                                     select GetMinimumExpressionDepthRec(s)).DefaultIfEmpty(0).Min()
489                             select minForSlot).DefaultIfEmpty(0).Max();
490        cachedMinExpressionDepth[symbol.Name] = (int)Math.Min(minDepth, int.MaxValue);
491        return cachedMinExpressionDepth[symbol.Name];
492      }
493      return temp;
494    }
495
496    private readonly Dictionary<string, int> cachedMaxExpressionDepth;
497    public int GetMaximumExpressionDepth(ISymbol symbol) {
498      int temp;
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
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
516    public event EventHandler Changed;
517    protected virtual void OnChanged() {
518      if (suppressEvents) return;
519      var handler = Changed;
520      if (handler != null) handler(this, EventArgs.Empty);
521    }
522  }
523}
Note: See TracBrowser for help on using the repository browser.