source: branches/3136_Structural_GP/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/StructureTemplate/StructureTemplate.cs @ 18190

Last change on this file since 18190 was 18190, checked in by mkommend, 4 months ago

#3136:
Added parameters for paramter optimization / linear scaling in StructeredSymRegProblem.
Added license headers to StructureTemplate and StructeredSymRegProblem.
Fixed type in NMSEConstraint evaluator.

File size: 7.7 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 HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29
30namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
31  [StorableType("E3C038DB-C6AA-457D-9F65-AF16C44CCE22")]
32  [Item("StructureTemplate", "Structure Template")]
33  public class StructureTemplate : Item {
34
35    #region Properties
36    [Storable]
37    private string template;
38    public string Template {
39      get => template;
40      set {
41        if (value == template) return;
42
43        template = value;
44        var parsedTree = Parser.Parse(template);
45        if (applyLinearScaling)
46          parsedTree = AddLinearScalingTerms(parsedTree);
47        Tree = parsedTree;
48        OnChanged();
49      }
50    }
51
52    private ISymbolicExpressionTree _oldTree;
53    [Storable(OldName = "treeWithoutLinearScaling")]
54    private ISymbolicExpressionTree _OldTreeW {
55      set => _oldTree = value;
56    }
57
58    [Storable]
59    private ISymbolicExpressionTree tree;
60    public ISymbolicExpressionTree Tree {
61      get => tree;
62      private set {
63        tree = value;
64
65        var newFunctions = GetSubFunctions();
66        var oldFunctions = subFunctions?.Intersect(newFunctions)
67                           ?? Enumerable.Empty<SubFunction>();
68        // adds new functions and keeps the old ones (if they match)
69        subFunctions = newFunctions.Except(oldFunctions).Concat(oldFunctions).ToList();
70      }
71    }
72
73    [Storable]
74    private IList<SubFunction> subFunctions = new List<SubFunction>();
75    public IEnumerable<SubFunction> SubFunctions => subFunctions;
76
77    [Storable]
78    private bool applyLinearScaling;
79    public bool ApplyLinearScaling {
80      get => applyLinearScaling;
81      set {
82        if (value == applyLinearScaling) return;
83
84        applyLinearScaling = value;
85        if (applyLinearScaling) Tree = AddLinearScalingTerms(Tree);
86        else Tree = RemoveLinearScalingTerms(Tree);
87
88        OnChanged();
89      }
90    }
91
92    protected InfixExpressionParser Parser { get; set; } = new InfixExpressionParser();
93
94    #endregion
95
96    #region Events
97    public event EventHandler Changed;
98
99    private void OnChanged() => Changed?.Invoke(this, EventArgs.Empty);
100    #endregion
101
102    #region Constructors
103    public StructureTemplate() {
104      Reset();
105    }
106
107    [StorableConstructor]
108    protected StructureTemplate(StorableConstructorFlag _) : base(_) { }
109
110    protected StructureTemplate(StructureTemplate original, Cloner cloner) : base(original, cloner) {
111      this.tree = cloner.Clone(original.tree);
112      this.template = original.Template;
113      this.applyLinearScaling = original.ApplyLinearScaling;
114      this.subFunctions = original.subFunctions.Select(cloner.Clone).ToList();
115      RegisterEventHandlers();
116    }
117
118
119    [StorableHook(HookType.AfterDeserialization)]
120    private void AfterDeserialization() {
121      if (Tree == null && _oldTree != null) {
122        if (ApplyLinearScaling) _oldTree = AddLinearScalingTerms(_oldTree);
123        Tree = _oldTree;
124        _oldTree = null;
125      }
126
127      RegisterEventHandlers();
128    }
129    #endregion
130
131    #region Cloning
132    public override IDeepCloneable Clone(Cloner cloner) =>
133      new StructureTemplate(this, cloner);
134    #endregion
135
136    public void Reset() {
137      subFunctions = new List<SubFunction>();
138      tree = null;
139      Template = "f(_)";
140    }
141
142    private IList<SubFunction> GetSubFunctions() {
143      var subFunctions = new List<SubFunction>();
144      foreach (var node in Tree.IterateNodesPrefix())
145        if (node is SubFunctionTreeNode subFunctionTreeNode) {
146          if (!subFunctionTreeNode.Arguments.Any())
147            throw new ArgumentException($"The sub-function '{subFunctionTreeNode}' requires inputs (e.g. {subFunctionTreeNode.Name}(var1, var2)).");
148
149          var existingSubFunction = subFunctions.Where(x => x.Name == subFunctionTreeNode.Name).FirstOrDefault();
150          if (existingSubFunction != null) {
151            // an existing subFunction must have the same signature
152            if (!existingSubFunction.Arguments.SequenceEqual(subFunctionTreeNode.Arguments))
153              throw new ArgumentException(
154                $"The sub-function '{existingSubFunction.Name}' has (at least two) different signatures " +
155                $"({existingSubFunction.Name}({string.Join(",", existingSubFunction.Arguments)}) <> " +
156                $"{subFunctionTreeNode.Name}({string.Join(",", subFunctionTreeNode.Arguments)})).");
157          } else {
158            var subFunction = new SubFunction() {
159              Name = subFunctionTreeNode.Name,
160              Arguments = subFunctionTreeNode.Arguments
161            };
162            subFunction.Changed += OnSubFunctionChanged;
163            subFunctions.Add(subFunction);
164          }
165        }
166      return subFunctions;
167    }
168
169    private void RegisterEventHandlers() {
170      foreach (var sf in SubFunctions) {
171        sf.Changed += OnSubFunctionChanged;
172      }
173    }
174
175    private static ISymbolicExpressionTree AddLinearScalingTerms(ISymbolicExpressionTree tree) {
176      var clonedTree = (ISymbolicExpressionTree)tree.Clone();
177      var startNode = clonedTree.Root.Subtrees.First();
178      var template = startNode.Subtrees.First();
179
180      var addNode = new Addition().CreateTreeNode();
181      var mulNode = new Multiplication().CreateTreeNode();
182      var offsetNode = new NumberTreeNode(0.0);
183      var scaleNode = new NumberTreeNode(1.0);
184
185      addNode.AddSubtree(offsetNode);
186      addNode.AddSubtree(mulNode);
187      mulNode.AddSubtree(scaleNode);
188
189      startNode.RemoveSubtree(0);
190      startNode.AddSubtree(addNode);
191      mulNode.AddSubtree(template);
192      return clonedTree;
193    }
194
195    private static ISymbolicExpressionTree RemoveLinearScalingTerms(ISymbolicExpressionTree tree) {
196      var clonedTree = (ISymbolicExpressionTree)tree.Clone();
197      var startNode = clonedTree.Root.Subtrees.First();
198
199      //check for scaling terms
200      var addNode = startNode.GetSubtree(0);
201      var offsetNode = addNode.GetSubtree(0);
202      var mulNode = addNode.GetSubtree(1);
203      var scaleNode = mulNode.GetSubtree(0);
204      var templateNode = mulNode.GetSubtree(1);
205
206      var error = false;
207      if (addNode.Symbol is not Addition) error = true;
208      if (mulNode.Symbol is not Multiplication) error = true;
209      if (offsetNode is not NumberTreeNode offset || offset.Value != 0.0) error = true;
210      if (scaleNode is not NumberTreeNode scale || scale.Value != 1.0) error = true;
211      if (error) throw new ArgumentException("Scaling terms cannot be found.");
212
213      startNode.RemoveSubtree(0);
214      startNode.AddSubtree(templateNode);
215
216      return clonedTree;
217    }
218
219    private void OnSubFunctionChanged(object sender, EventArgs e) => OnChanged();
220  }
221}
Note: See TracBrowser for help on using the repository browser.