Free cookie consent management tool by TermsFeed Policy Generator

source: stable/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/SymbolicExpressionGrammar.cs @ 10394

Last change on this file since 10394 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 13.1 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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      ReadOnly = false;
185    }
186    void IStatefulItem.ClearState() {
187      ReadOnly = false;
188    }
189    #endregion
190
191    #region ISymbolicExpressionGrammar methods
192    void ISymbolicExpressionGrammar.AddSymbol(ISymbol symbol) {
193      if (ReadOnly) throw new InvalidOperationException();
194      AddSymbol(symbol);
195    }
196    void ISymbolicExpressionGrammar.RemoveSymbol(ISymbol symbol) {
197      if (ReadOnly) throw new InvalidOperationException();
198      RemoveSymbol(symbol);
199    }
200
201    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child) {
202      if (ReadOnly) throw new InvalidOperationException();
203      base.AddAllowedChildSymbol(parent, child);
204    }
205    void ISymbolicExpressionGrammar.AddAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
206      if (ReadOnly) throw new InvalidOperationException();
207      base.AddAllowedChildSymbol(parent, child, argumentIndex);
208    }
209    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child) {
210      if (ReadOnly) throw new InvalidOperationException();
211      base.RemoveAllowedChildSymbol(parent, child);
212    }
213    void ISymbolicExpressionGrammar.RemoveAllowedChildSymbol(ISymbol parent, ISymbol child, int argumentIndex) {
214      if (ReadOnly) throw new InvalidOperationException();
215      base.RemoveAllowedChildSymbol(parent, child, argumentIndex);
216    }
217
218    void ISymbolicExpressionGrammar.SetSubtreeCount(ISymbol symbol, int minimumSubtreeCount, int maximumSubtreeCount) {
219      if (ReadOnly) throw new InvalidOperationException();
220      base.SetSubtreeCount(symbol, minimumSubtreeCount, maximumSubtreeCount);
221    }
222
223    private bool suppressEvents = false;
224    void ISymbolicExpressionGrammar.StartGrammarManipulation() {
225      suppressEvents = true;
226    }
227    void ISymbolicExpressionGrammar.FinishedGrammarManipulation() {
228      suppressEvents = false;
229      OnChanged();
230    }
231
232    protected override void OnChanged() {
233      if (suppressEvents) return;
234      base.OnChanged();
235    }
236    #endregion
237
238    #region symbol events
239    private void RegisterSymbolEvents(ISymbol symbol) {
240      foreach (var s in symbol.Flatten()) {
241        s.NameChanging += new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
242        s.NameChanged += new EventHandler(Symbol_NameChanged);
243
244        var groupSymbol = s as GroupSymbol;
245        if (groupSymbol != null) RegisterGroupSymbolEvents(groupSymbol);
246        else s.Changed += new EventHandler(Symbol_Changed);
247      }
248    }
249    private void DeregisterSymbolEvents(ISymbol symbol) {
250      foreach (var s in symbol.Flatten()) {
251        s.NameChanging -= new EventHandler<CancelEventArgs<string>>(Symbol_NameChanging);
252        s.NameChanged -= new EventHandler(Symbol_NameChanged);
253
254        var groupSymbol = s as GroupSymbol;
255        if (groupSymbol != null) DeregisterGroupSymbolEvents(groupSymbol);
256        else s.Changed -= new EventHandler(Symbol_Changed);
257      }
258    }
259
260    private void RegisterGroupSymbolEvents(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    private void DeregisterGroupSymbolEvents(GroupSymbol groupSymbol) {
267      groupSymbol.Changed -= new EventHandler(GroupSymbol_Changed);
268      groupSymbol.SymbolsCollection.ItemsAdded -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsAdded);
269      groupSymbol.SymbolsCollection.ItemsRemoved -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_ItemsRemoved);
270      groupSymbol.SymbolsCollection.CollectionReset -= new Collections.CollectionItemsChangedEventHandler<ISymbol>(GroupSymbol_CollectionReset);
271    }
272
273    private void Symbol_Changed(object sender, EventArgs e) {
274      ClearCaches();
275      OnChanged();
276    }
277
278    private void GroupSymbol_Changed(object sender, EventArgs e) {
279      GroupSymbol groupSymbol = (GroupSymbol)sender;
280      foreach (ISymbol symbol in groupSymbol.Flatten())
281        symbol.Enabled = groupSymbol.Enabled;
282
283      ClearCaches();
284      OnChanged();
285    }
286
287    private void Symbol_NameChanging(object sender, CancelEventArgs<string> e) {
288      if (symbols.ContainsKey(e.Value)) e.Cancel = true;
289    }
290    private void Symbol_NameChanged(object sender, EventArgs e) {
291      ISymbol symbol = (ISymbol)sender;
292      string oldName = symbols.Where(x => x.Value == symbol).First().Key;
293      string newName = symbol.Name;
294
295      symbols.Remove(oldName);
296      symbols.Add(newName, symbol);
297
298      var subtreeCount = symbolSubtreeCount[oldName];
299      symbolSubtreeCount.Remove(oldName);
300      symbolSubtreeCount.Add(newName, subtreeCount);
301
302      List<string> allowedChilds;
303      if (allowedChildSymbols.TryGetValue(oldName, out allowedChilds)) {
304        allowedChildSymbols.Remove(oldName);
305        allowedChildSymbols.Add(newName, allowedChilds);
306      }
307
308      for (int i = 0; i < GetMaximumSubtreeCount(symbol); i++) {
309        if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(oldName, i), out allowedChilds)) {
310          allowedChildSymbolsPerIndex.Remove(Tuple.Create(oldName, i));
311          allowedChildSymbolsPerIndex.Add(Tuple.Create(newName, i), allowedChilds);
312        }
313      }
314
315      foreach (var parent in Symbols) {
316        if (allowedChildSymbols.TryGetValue(parent.Name, out allowedChilds))
317          if (allowedChilds.Remove(oldName))
318            allowedChilds.Add(newName);
319
320        for (int i = 0; i < GetMaximumSubtreeCount(parent); i++) {
321          if (allowedChildSymbolsPerIndex.TryGetValue(Tuple.Create(parent.Name, i), out allowedChilds))
322            if (allowedChilds.Remove(oldName)) allowedChilds.Add(newName);
323        }
324      }
325
326      ClearCaches();
327      OnChanged();
328    }
329
330    private void GroupSymbol_ItemsAdded(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
331      foreach (ISymbol symbol in e.Items)
332        if (!ContainsSymbol(symbol))
333          AddSymbol(symbol);
334      OnChanged();
335    }
336    private void GroupSymbol_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
337      foreach (ISymbol symbol in e.Items)
338        if (ContainsSymbol(symbol))
339          RemoveSymbol(symbol);
340      OnChanged();
341    }
342    private void GroupSymbol_CollectionReset(object sender, CollectionItemsChangedEventArgs<ISymbol> e) {
343      foreach (ISymbol symbol in e.Items)
344        if (!ContainsSymbol(symbol))
345          AddSymbol(symbol);
346      foreach (ISymbol symbol in e.OldItems)
347        if (ContainsSymbol(symbol))
348          RemoveSymbol(symbol);
349      OnChanged();
350    }
351    #endregion
352  }
353}
Note: See TracBrowser for help on using the repository browser.