Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Grammars/SymbolicExpressionGrammar.cs @ 11968

Last change on this file since 11968 was 11494, checked in by mkommend, 10 years ago

#2268: Moved all grammar classes into a new folder. Added new EmptySymbolicExpressionTreeGrammar which is immutable and forwards all calls to the default grammar object.

File size: 13.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2014 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 HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
29
30namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
31  [StorableClass]
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(bool deserializing)
124      : base(deserializing) {
125      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
126    }
127    protected SymbolicExpressionGrammar(SymbolicExpressionGrammar original, Cloner cloner)
128      : base(original, cloner) {
129      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
130
131      foreach (ISymbol symbol in symbols.Values)
132        RegisterSymbolEvents(symbol);
133
134      programRootSymbol = cloner.Clone(original.programRootSymbol);
135      startSymbol = cloner.Clone(original.StartSymbol);
136      defunSymbol = cloner.Clone(original.defunSymbol);
137
138      maximumFunctionArguments = original.maximumFunctionArguments;
139      minimumFunctionArguments = original.minimumFunctionArguments;
140      maximumFunctionDefinitions = original.maximumFunctionDefinitions;
141      minimumFunctionDefinitions = original.minimumFunctionDefinitions;
142    }
143
144    protected SymbolicExpressionGrammar(string name, string description)
145      : base(name, description) {
146      emptyGrammar = new EmptySymbolicExpressionTreeGrammar(this);
147
148      programRootSymbol = new ProgramRootSymbol();
149      AddSymbol(programRootSymbol);
150      SetSubtreeCount(programRootSymbol, 1, 1);
151
152      startSymbol = new StartSymbol();
153      AddSymbol(startSymbol);
154      SetSubtreeCount(startSymbol, 1, 1);
155
156      defunSymbol = new Defun();
157      AddSymbol(defunSymbol);
158      SetSubtreeCount(defunSymbol, 1, 1);
159
160      AddAllowedChildSymbol(programRootSymbol, startSymbol, 0);
161      UpdateAdfConstraints();
162    }
163
164    private void UpdateAdfConstraints() {
165      SetSubtreeCount(programRootSymbol, minimumFunctionDefinitions + 1, maximumFunctionDefinitions + 1);
166
167      // ADF branches maxFunctionDefinitions
168      for (int argumentIndex = 1; argumentIndex < maximumFunctionDefinitions + 1; argumentIndex++) {
169        RemoveAllowedChildSymbol(programRootSymbol, defunSymbol, argumentIndex);
170        AddAllowedChildSymbol(programRootSymbol, defunSymbol, argumentIndex);
171      }
172    }
173
174    public ISymbolicExpressionTreeGrammar CreateExpressionTreeGrammar() {
175      if (MaximumFunctionDefinitions == 0) return emptyGrammar;
176      else return new SymbolicExpressionTreeGrammar(this);
177    }
178
179    protected override sealed void AddSymbol(ISymbol symbol) {
180      base.AddSymbol(symbol);
181      RegisterSymbolEvents(symbol);
182      OnChanged();
183    }
184    protected override sealed void RemoveSymbol(ISymbol symbol) {
185      DeregisterSymbolEvents(symbol);
186      base.RemoveSymbol(symbol);
187      OnChanged();
188    }
189
190    public event EventHandler ReadOnlyChanged;
191    protected virtual void OnReadOnlyChanged() {
192      var handler = ReadOnlyChanged;
193      if (handler != null)
194        handler(this, EventArgs.Empty);
195    }
196
197    #region IStatefulItem methods
198    void IStatefulItem.InitializeState() {
199      ReadOnly = false;
200    }
201    void IStatefulItem.ClearState() {
202      ReadOnly = false;
203    }
204    #endregion
205
206    #region ISymbolicExpressionGrammar methods
207    void ISymbolicExpressionGrammar.AddSymbol(ISymbol symbol) {
208      if (ReadOnly) throw new InvalidOperationException();
209      AddSymbol(symbol);
210    }
211    void ISymbolicExpressionGrammar.RemoveSymbol(ISymbol symbol) {
212      if (ReadOnly) throw new InvalidOperationException();
213      RemoveSymbol(symbol);
214    }
215
216    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
217      if (ReadOnly) throw new InvalidOperationException();
218      base.AddAllowedChildSymbol(parent, child);
219    }
220    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
221      if (ReadOnly) throw new InvalidOperationException();
222      base.AddAllowedChildSymbol(parent, child, argumentIndex);
223    }
224    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
225      if (ReadOnly) throw new InvalidOperationException();
226      base.RemoveAllowedChildSymbol(parent, child);
227    }
228    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
229      if (ReadOnly) throw new InvalidOperationException();
230      base.RemoveAllowedChildSymbol(parent, child, argumentIndex);
231    }
232
233    void ISymbolicExpressionGrammar.SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
234      if (ReadOnly) throw new InvalidOperationException();
235      base.SetSubtreeCount(symbol, minimumSubtreeCount, maximumSubtreeCount);
236    }
237
238    private bool suppressEvents = false;
239    void ISymbolicExpressionGrammar.StartGrammarManipulation() {
240      suppressEvents = true;
241    }
242    void ISymbolicExpressionGrammar.FinishedGrammarManipulation() {
243      suppressEvents = false;
244      OnChanged();
245    }
246
247    protected override void OnChanged() {
248      if (suppressEvents) return;
249      base.OnChanged();
250    }
251    #endregion
252
253    #region symbol events
254    private void RegisterSymbolEvents(ISymbol symbol) {
255      foreach (var s in symbol.Flatten()) {
256        s.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
257        s.NameChanged += new EventHandler(Symbol_NameChanged);
258
259        var groupSymbol = s as GroupSymbol;
260        if (groupSymbol != null) RegisterGroupSymbolEvents(groupSymbol);
261        else s.Changed += new EventHandler(Symbol_Changed);
262      }
263    }
264    private void DeregisterSymbolEvents(ISymbol symbol) {
265      foreach (var s in symbol.Flatten()) {
266        s.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
267        s.NameChanged -= new EventHandler(Symbol_NameChanged);
268
269        var groupSymbol = s as GroupSymbol;
270        if (groupSymbol != null) DeregisterGroupSymbolEvents(groupSymbol);
271        else s.Changed -= new EventHandler(Symbol_Changed);
272      }
273    }
274
275    private void RegisterGroupSymbolEvents(GroupSymbol groupSymbol) {
276      groupSymbol.Changed += new EventHandler(GroupSymbol_Changed);
277      groupSymbol.SymbolsCollection.ItemsAdded += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
278      groupSymbol.SymbolsCollection.ItemsRemoved += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
279      groupSymbol.SymbolsCollection.CollectionReset += new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
280    }
281    private void DeregisterGroupSymbolEvents(GroupSymbol groupSymbol) {
282      groupSymbol.Changed -= new EventHandler(GroupSymbol_Changed);
283      groupSymbol.SymbolsCollection.ItemsAdded -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
284      groupSymbol.SymbolsCollection.ItemsRemoved -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
285      groupSymbol.SymbolsCollection.CollectionReset -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
286    }
287
288    private void Symbol_Changed(object sender, EventArgs e) {
289      ClearCaches();
290      OnChanged();
291    }
292
293    private void GroupSymbol_Changed(object sender, EventArgs e) {
294      GroupSymbol groupSymbol = (GroupSymbol)sender;
295      foreach (ISymbol symbol in groupSymbol.Flatten())
296        symbol.Enabled = groupSymbol.Enabled;
297
298      ClearCaches();
299      OnChanged();
300    }
301
302    private void Symbol_NameChanging(object sender, CancelEventArgs<string> e) {
303      if (symbols.ContainsKey(e.Value)) e.Cancel = true;
304    }
305    private void Symbol_NameChanged(object sender, EventArgs e) {
306      ISymbol symbol = (ISymbol)sender;
307      string oldName = symbols.Where(x => x.Value == symbol).First().Key;
308      string newName = symbol.Name;
309
310      symbols.Remove(oldName);
311      symbols.Add(newName, symbol);
312
313      var subtreeCount = symbolSubtreeCount[oldName];
314      symbolSubtreeCount.Remove(oldName);
315      symbolSubtreeCount.Add(newName, subtreeCount);
316
317      List<string> allowedChilds;
318      if (allowedChildSymbols.TryGetValue(oldName, out allowedChilds)) {
319        allowedChildSymbols.Remove(oldName);
320        allowedChildSymbols.Add(newName, allowedChilds);
321      }
322
323      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++) {
324        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(oldName, i), out allowedChilds)) {
325          allowedChildSymbolsPerIndex.Remove(Tuple.Create(oldName, i));
326          allowedChildSymbolsPerIndex.Add(Tuple.Create(newName, i), allowedChilds);
327        }
328      }
329
330      foreach (var parent in Symbols) {
331        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
332          if (allowedChilds.Remove(oldName))
333            allowedChilds.Add(newName);
334
335        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
336          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
337            if (allowedChilds.Remove(oldName)) allowedChilds.Add(newName);
338        }
339      }
340
341      ClearCaches();
342      OnChanged();
343    }
344
345    private void GroupSymbol_ItemsAdded(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
346      foreach (ISymbol symbol in e.Items)
347        if (!ContainsSymbol(symbol))
348          AddSymbol(symbol);
349      OnChanged();
350    }
351    private void GroupSymbol_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
352      foreach (ISymbol symbol in e.Items)
353        if (ContainsSymbol(symbol))
354          RemoveSymbol(symbol);
355      OnChanged();
356    }
357    private void GroupSymbol_CollectionReset(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
358      foreach (ISymbol symbol in e.Items)
359        if (!ContainsSymbol(symbol))
360          AddSymbol(symbol);
361      foreach (ISymbol symbol in e.OldItems)
362        if (ContainsSymbol(symbol))
363          RemoveSymbol(symbol);
364      OnChanged();
365    }
366    #endregion
367  }
368}
Note: See TracBrowser for help on using the repository browser.