source: trunk/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Grammars/SymbolicExpressionGrammar.cs @ 18064

Last change on this file since 18064 was 18064, checked in by mkommend, 8 weeks ago

#2997: Simplified tree creator interface and removed cloning of grammars,

File size: 13.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 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.Collections;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HEAL.Attic;
29
30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
31  [StorableType("925BDEE9-0D46-48DB-BA1B-DCE82C0480B3")]
32  public abstract class SymbolicExpressionGrammar : SymbolicExpressionGrammarBase, ISymbolicExpressionGrammar {
33    #region fields & properties
34    [Storable(DefaultValue = false)]
35    private bool readOnly;
36    public bool ReadOnly {
37      get { return readOnly; }
38      set {
39        if (readOnly != value) {
40          readOnly = value;
41          OnReadOnlyChanged();
42        }
43      }
44    }
45
46    [Storable]
47    private int minimumFunctionDefinitions;
48    public int MinimumFunctionDefinitions {
49      get { return minimumFunctionDefinitions; }
50      set {
51        minimumFunctionDefinitions = value;
52        UpdateAdfConstraints();
53      }
54    }
55    [Storable]
56    private int maximumFunctionDefinitions;
57    public int MaximumFunctionDefinitions {
58      get { return maximumFunctionDefinitions; }
59      set {
60        maximumFunctionDefinitions = value;
61        UpdateAdfConstraints();
62      }
63    }
64    [Storable]
65    private int minimumFunctionArguments;
66    public int MinimumFunctionArguments {
67      get { return minimumFunctionArguments; }
68      set { minimumFunctionArguments = value; }
69    }
70    [Storable]
71    private int maximumFunctionArguments;
72    public int MaximumFunctionArguments {
73      get { return maximumFunctionArguments; }
74      set { maximumFunctionArguments = value; }
75    }
76
77    private ProgramRootSymbol programRootSymbol;
78    public ProgramRootSymbol ProgramRootSymbol {
79      get { return programRootSymbol; }
80    }
81    ISymbol ISymbolicExpressionGrammar.ProgramRootSymbol {
82      get { return ProgramRootSymbol; }
83    }
84    [Storable(Name = "ProgramRootSymbol")]
85    private ISymbol StorableProgramRootSymbol {
86      get { return programRootSymbol; }
87      set { programRootSymbol = (ProgramRootSymbol)value; }
88    }
89
90    private StartSymbol startSymbol;
91    public StartSymbol StartSymbol {
92      get { return startSymbol; }
93    }
94    ISymbol ISymbolicExpressionGrammar.StartSymbol {
95      get { return StartSymbol; }
96    }
97    [Storable(Name = "StartSymbol")]
98    private ISymbol StorableStartSymbol {
99      get { return startSymbol; }
100      set { startSymbol = (StartSymbol)value; }
101    }
102
103    private Defun defunSymbol;
104    protected Defun DefunSymbol {
105      get { return defunSymbol; }
106    }
107    [Storable(Name = "DefunSymbol")]
108    private ISymbol StorableDefunSymbol {
109      get { return defunSymbol; }
110      set { defunSymbol = (Defun)value; }
111    }
112
113    private readonly ISymbolicExpressionTreeGrammar emptyGrammar;
114    #endregion
115
116    [StorableHook(HookType.AfterDeserialization)]
117    private void AfterDeserialization() {
118      foreach (ISymbol symbol in symbols.Values)
119        RegisterSymbolEvents(symbol);
120    }
121
122    [StorableConstructor]
123    protected SymbolicExpressionGrammar(StorableConstructorFlag _) : base(_) {
124      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
125    }
126    protected SymbolicExpressionGrammar(SymbolicExpressionGrammar original, Cloner cloner)
127      : base(original, cloner) {
128      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
129
130      foreach (ISymbol symbol in symbols.Values)
131        RegisterSymbolEvents(symbol);
132
133      programRootSymbol = cloner.Clone(original.programRootSymbol);
134      startSymbol = cloner.Clone(original.StartSymbol);
135      defunSymbol = cloner.Clone(original.defunSymbol);
136
137      maximumFunctionArguments = original.maximumFunctionArguments;
138      minimumFunctionArguments = original.minimumFunctionArguments;
139      maximumFunctionDefinitions = original.maximumFunctionDefinitions;
140      minimumFunctionDefinitions = original.minimumFunctionDefinitions;
141    }
142
143    protected SymbolicExpressionGrammar(string name, string description)
144      : base(name, description) {
145      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
146
147      programRootSymbol = new ProgramRootSymbol();
148      AddSymbol(programRootSymbol);
149      SetSubtreeCount(programRootSymbol, 1, 1);
150
151      startSymbol = new StartSymbol();
152      AddSymbol(startSymbol);
153      SetSubtreeCount(startSymbol, 1, 1);
154
155      defunSymbol = new Defun();
156      AddSymbol(defunSymbol);
157      SetSubtreeCount(defunSymbol, 1, 1);
158
159      AddAllowedChildSymbol(programRootSymbol, startSymbol, 0);
160      UpdateAdfConstraints();
161    }
162
163    private void UpdateAdfConstraints() {
164      SetSubtreeCount(programRootSymbol, minimumFunctionDefinitions + 1, maximumFunctionDefinitions + 1);
165
166      // ADF branches maxFunctionDefinitions
167      for (int argumentIndex = 1; argumentIndex < maximumFunctionDefinitions + 1; argumentIndex++) {
168        RemoveAllowedChildSymbol(programRootSymbol, defunSymbol, argumentIndex);
169        AddAllowedChildSymbol(programRootSymbol, defunSymbol, argumentIndex);
170      }
171    }
172
173    public ISymbolicExpressionTreeGrammar CreateExpressionTreeGrammar() {
174      if (MaximumFunctionDefinitions == 0) return emptyGrammar;
175      else return new SymbolicExpressionTreeGrammar(this);
176    }
177
178    public override sealed void AddSymbol(ISymbol symbol) {
179      if (ReadOnly) throw new InvalidOperationException();
180      base.AddSymbol(symbol);
181      RegisterSymbolEvents(symbol);
182      OnChanged();
183    }
184    public override sealed void RemoveSymbol(ISymbol symbol) {
185      if (ReadOnly) throw new InvalidOperationException();
186      DeregisterSymbolEvents(symbol);
187      base.RemoveSymbol(symbol);
188      OnChanged();
189    }
190
191    public event EventHandler ReadOnlyChanged;
192    protected virtual void OnReadOnlyChanged() {
193      ReadOnlyChanged?.Invoke(this, EventArgs.Empty);
194    }
195
196    public sealed override void AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
197      if (ReadOnly) throw new InvalidOperationException();
198      base.AddAllowedChildSymbol(parent, child);
199    }
200    public sealed override void AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
201      if (ReadOnly) throw new InvalidOperationException();
202      base.AddAllowedChildSymbol(parent, child, argumentIndex);
203    }
204    public sealed override void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
205      if (ReadOnly) throw new InvalidOperationException();
206      base.RemoveAllowedChildSymbol(parent, child);
207    }
208    public sealed override void RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
209      if (ReadOnly) throw new InvalidOperationException();
210      base.RemoveAllowedChildSymbol(parent, child, argumentIndex);
211    }
212
213    public sealed override void SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
214      if (ReadOnly) throw new InvalidOperationException();
215      base.SetSubtreeCount(symbol, minimumSubtreeCount, maximumSubtreeCount);
216    }
217
218    private bool suppressEvents = false;
219    public void StartGrammarManipulation() {
220      suppressEvents = true;
221    }
222    public void FinishedGrammarManipulation() {
223      suppressEvents = false;
224      OnChanged();
225    }
226
227    protected sealed override void OnChanged() {
228      if (suppressEvents) return;
229      base.OnChanged();
230    }
231
232    #region symbol events
233    private void RegisterSymbolEvents(ISymbol symbol) {
234      foreach (var s in symbol.Flatten()) {
235        s.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
236        s.NameChanged += new EventHandler(Symbol_NameChanged);
237
238        var groupSymbol = s as GroupSymbol;
239        if (groupSymbol != null) RegisterGroupSymbolEvents(groupSymbol);
240        else s.Changed += new EventHandler(Symbol_Changed);
241      }
242    }
243    private void DeregisterSymbolEvents(ISymbol symbol) {
244      foreach (var s in symbol.Flatten()) {
245        s.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
246        s.NameChanged -= new EventHandler(Symbol_NameChanged);
247
248        var groupSymbol = s as GroupSymbol;
249        if (groupSymbol != null) DeregisterGroupSymbolEvents(groupSymbol);
250        else s.Changed -= new EventHandler(Symbol_Changed);
251      }
252    }
253
254    private void RegisterGroupSymbolEvents(GroupSymbol groupSymbol) {
255      groupSymbol.Changed += new EventHandler(GroupSymbol_Changed);
256      groupSymbol.SymbolsCollection.ItemsAdded += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
257      groupSymbol.SymbolsCollection.ItemsRemoved += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
258      groupSymbol.SymbolsCollection.CollectionReset += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
259    }
260    private void DeregisterGroupSymbolEvents(GroupSymbol groupSymbol) {
261      groupSymbol.Changed -= new EventHandler(GroupSymbol_Changed);
262      groupSymbol.SymbolsCollection.ItemsAdded -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
263      groupSymbol.SymbolsCollection.ItemsRemoved -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
264      groupSymbol.SymbolsCollection.CollectionReset -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
265    }
266
267    private void Symbol_Changed(object sender, EventArgs e) {
268      ClearCaches();
269      OnChanged();
270    }
271
272    private void GroupSymbol_Changed(object sender, EventArgs e) {
273      GroupSymbol groupSymbol = (GroupSymbol)sender;
274      foreach (ISymbol symbol in groupSymbol.Flatten())
275        symbol.Enabled = groupSymbol.Enabled;
276
277      ClearCaches();
278      OnChanged();
279    }
280
281    private void Symbol_NameChanging(object sender, CancelEventArgs<string> e) {
282      if (symbols.ContainsKey(e.Value)) e.Cancel = true;
283    }
284    private void Symbol_NameChanged(object sender, EventArgs e) {
285      ISymbol symbol = (ISymbol)sender;
286      string oldName = symbols.First(x => x.Value == symbol).Key;
287      string newName = symbol.Name;
288
289      symbols.Remove(oldName);
290      symbols.Add(newName, symbol);
291
292      var subtreeCount = symbolSubtreeCount[oldName];
293      symbolSubtreeCount.Remove(oldName);
294      symbolSubtreeCount.Add(newName, subtreeCount);
295
296      List<string> allowedChilds;
297      if (allowedChildSymbols.TryGetValue(oldName, out allowedChilds)) {
298        allowedChildSymbols.Remove(oldName);
299        allowedChildSymbols.Add(newName, allowedChilds);
300      }
301
302      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++) {
303        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(oldName, i), out allowedChilds)) {
304          allowedChildSymbolsPerIndex.Remove(Tuple.Create(oldName, i));
305          allowedChildSymbolsPerIndex.Add(Tuple.Create(newName, i), allowedChilds);
306        }
307      }
308
309      foreach (var parent in Symbols) {
310        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
311          if (allowedChilds.Remove(oldName))
312            allowedChilds.Add(newName);
313
314        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
315          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
316            if (allowedChilds.Remove(oldName)) allowedChilds.Add(newName);
317        }
318      }
319
320      ClearCaches();
321      OnChanged();
322    }
323
324    private void GroupSymbol_ItemsAdded(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
325      foreach (ISymbol symbol in e.Items)
326        if (!ContainsSymbol(symbol))
327          AddSymbol(symbol);
328      OnChanged();
329    }
330    private void GroupSymbol_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
331      foreach (ISymbol symbol in e.Items)
332        if (ContainsSymbol(symbol))
333          RemoveSymbol(symbol);
334      OnChanged();
335    }
336    private void GroupSymbol_CollectionReset(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
337      foreach (ISymbol symbol in e.Items)
338        if (!ContainsSymbol(symbol))
339          AddSymbol(symbol);
340      foreach (ISymbol symbol in e.OldItems)
341        if (ContainsSymbol(symbol))
342          RemoveSymbol(symbol);
343      OnChanged();
344    }
345    #endregion
346  }
347}
Note: See TracBrowser for help on using the repository browser.