Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.EvolutionaryTracking/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammar.cs @ 8423

Last change on this file since 8423 was 7439, checked in by bburlacu, 13 years ago

#1772: Created branch and solution.

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