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

Last change on this file since 18152 was 18152, checked in by dpiringe, 7 months ago

#3136

  • removed the calculation of EstimationLimits and set the interval [-inf, inf] as default
    • this parameter was never adjusted after problem construction -> caused bugs with the change of problem data
  • created two new method to setup/create the MultiEncoding and SymbolicExpressionTreeEncoding
  • configured the default template f(_) for a structure template
File size: 5.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HEAL.Attic;
5using HeuristicLab.Common;
6using HeuristicLab.Core;
7using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
8
9namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
10  [StorableType("E3C038DB-C6AA-457D-9F65-AF16C44CCE22")]
11  [Item("StructureTemplate", "Structure Template")]
12  public class StructureTemplate : Item {
13
14    #region Properties
15    [Storable]
16    private string template;
17    public string Template {
18      get => template;
19      set {
20        template = value;
21        Tree = Parser.Parse(template);
22        OnChanged();
23      }
24    }
25
26    [Storable]
27    private ISymbolicExpressionTree treeWithoutLinearScaling;
28    [Storable]
29    private ISymbolicExpressionTree treeWithLinearScaling;
30    public ISymbolicExpressionTree Tree {
31      get => ApplyLinearScaling ? treeWithLinearScaling : treeWithoutLinearScaling;
32      private set {
33        treeWithLinearScaling = AddLinearScalingTerms(value);
34        treeWithoutLinearScaling = value;
35        subFunctions = GetSubFunctions();
36      }
37    }
38
39    [Storable]
40    private IList<SubFunction> subFunctions = new List<SubFunction>();
41    public IEnumerable<SubFunction> SubFunctions => subFunctions;
42
43    [Storable]
44    private bool applyLinearScaling;
45    public bool ApplyLinearScaling {
46      get => applyLinearScaling;
47      set {
48        applyLinearScaling = value;
49        OnChanged();
50      }
51    }
52
53    protected InfixExpressionParser Parser { get; set; } = new InfixExpressionParser();
54
55    #endregion
56
57    #region Events
58    public event EventHandler Changed;
59
60    private void OnChanged() => Changed?.Invoke(this, EventArgs.Empty);
61    #endregion
62
63    #region Constructors
64    public StructureTemplate() {
65      Reset();
66    }
67
68    [StorableConstructor]
69    protected StructureTemplate(StorableConstructorFlag _) : base(_) { }
70
71    protected StructureTemplate(StructureTemplate original, Cloner cloner) : base(original, cloner) {
72      this.Tree = cloner.Clone(original.Tree);
73      this.Template = original.Template;
74      this.ApplyLinearScaling = original.ApplyLinearScaling;
75      this.subFunctions = original.subFunctions.Select(cloner.Clone).ToList();
76      RegisterEventHandlers();
77    }
78
79
80    [StorableHook(HookType.AfterDeserialization)]
81    private void AfterDeserialization() {
82      RegisterEventHandlers();
83    }
84    #endregion
85
86    #region Cloning
87    public override IDeepCloneable Clone(Cloner cloner) =>
88      new StructureTemplate(this, cloner);
89    #endregion
90
91    public void Reset() {
92      subFunctions = new List<SubFunction>();
93      treeWithoutLinearScaling = null;
94      treeWithLinearScaling = null;
95      applyLinearScaling = false;
96      Template = "f(_)";
97      OnChanged();
98    }
99
100    private IList<SubFunction> GetSubFunctions() {
101      var subFunctions = new List<SubFunction>();
102      foreach (var node in Tree.IterateNodesPrefix())
103        if (node is SubFunctionTreeNode subFunctionTreeNode) {
104          if (!subFunctionTreeNode.Arguments.Any())
105            throw new ArgumentException($"The sub-function '{subFunctionTreeNode}' requires inputs (e.g. {subFunctionTreeNode.Name}(var1, var2)).");
106
107          var existingSubFunction = subFunctions.Where(x => x.Name == subFunctionTreeNode.Name).FirstOrDefault();
108          if (existingSubFunction != null) {
109            // an existing subFunction needs the same signature
110            if(!existingSubFunction.Arguments.SequenceEqual(subFunctionTreeNode.Arguments))
111              throw new ArgumentException(
112                $"The sub-function '{existingSubFunction.Name}' has (at least two) different signatures " +
113                $"({existingSubFunction.Name}({string.Join(",", existingSubFunction.Arguments)}) <> " +
114                $"{subFunctionTreeNode.Name}({string.Join(",", subFunctionTreeNode.Arguments)})).");
115          } else {
116            var subFunction = new SubFunction() {
117              Name = subFunctionTreeNode.Name,
118              Arguments = subFunctionTreeNode.Arguments
119            };
120            subFunction.Changed += OnSubFunctionChanged;
121            subFunctions.Add(subFunction);
122          }
123        }
124      return subFunctions;
125    }
126
127    private void RegisterEventHandlers() {
128      foreach(var sf in SubFunctions) {
129        sf.Changed += OnSubFunctionChanged;
130      }
131    }
132
133    private ISymbolicExpressionTree AddLinearScalingTerms(ISymbolicExpressionTree tree) {
134      var clonedTree = (ISymbolicExpressionTree)tree.Clone();
135      var startNode = clonedTree.Root.Subtrees.First();
136      var template = startNode.Subtrees.First();
137
138      var add = new Addition();
139      var addNode = add.CreateTreeNode();
140
141      var mul = new Multiplication();
142      var mulNode = mul.CreateTreeNode();
143
144      var offset = new Number();
145      var offsetNode = (NumberTreeNode)offset.CreateTreeNode();
146      offsetNode.Value = 0.0;
147      var scale = new Number();
148      var scaleNode = (NumberTreeNode)scale.CreateTreeNode();
149      scaleNode.Value = 1.0;
150
151      addNode.AddSubtree(offsetNode);
152      addNode.AddSubtree(mulNode);
153      mulNode.AddSubtree(scaleNode);
154
155      startNode.RemoveSubtree(0);
156      startNode.AddSubtree(addNode);
157      mulNode.AddSubtree(template);
158      return clonedTree;
159    }
160
161    private void OnSubFunctionChanged(object sender, EventArgs e) => OnChanged();
162  }
163}
Note: See TracBrowser for help on using the repository browser.