source: branches/3136_Structural_GP/HeuristicLab.Problems.DataAnalysis.Symbolic.Regression/3.4/SingleObjective/StructuredSymbolicRegressionSingleObjectiveProblem.cs @ 18152

Last change on this file since 18152 was 18152, checked in by dpiringe, 6 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: 13.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HEAL.Attic;
5using HeuristicLab.Common;
6using HeuristicLab.Core;
7using HeuristicLab.Data;
8using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
9using HeuristicLab.Optimization;
10using HeuristicLab.Parameters;
11using HeuristicLab.PluginInfrastructure;
12using HeuristicLab.Problems.Instances;
13using HeuristicLab.Problems.Instances.DataAnalysis;
14
15namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
16  [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
17  [Item(Name = "Structured Symbolic Regression Single Objective Problem (single-objective)", Description = "A problem with a structural definition and unfixed subfunctions.")]
18  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 150)]
19  public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData> {
20
21    #region Constants
22    private const string TreeEvaluatorParameterName = "TreeEvaluator";
23    private const string ProblemDataParameterName = "ProblemData";
24    private const string StructureTemplateParameterName = "Structure Template";
25    private const string InterpreterParameterName = "Interpreter";
26    private const string EstimationLimitsParameterName = "EstimationLimits";
27    private const string BestTrainingSolutionParameterName = "Best Training Solution";
28
29    private const string SymbolicExpressionTreeName = "SymbolicExpressionTree";
30    private const string VariableName = "Variable";
31
32    private const string StructureTemplateDescriptionText =
33      "Enter your expression as string in infix format into the empty input field.\n" +
34      "By checking the \"Apply Linear Scaling\" checkbox you can add the relevant scaling terms to your expression.\n" +
35      "After entering the expression click parse to build the tree.\n" +
36      "To edit the defined sub-functions, click on the corresponding-colored node in the tree view.\n" +
37      "Check the info box besides the input field for more information.";
38    #endregion
39
40    #region Parameters
41    public IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator> TreeEvaluatorParameter => (IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>)Parameters[TreeEvaluatorParameterName];
42    public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
43    public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
44    public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
45    public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
46    public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
47    #endregion
48
49    #region Properties
50
51    public IRegressionProblemData ProblemData {
52      get => ProblemDataParameter.Value;
53      set {
54        ProblemDataParameter.Value = value;
55        ProblemDataChanged?.Invoke(this, EventArgs.Empty);
56      }
57    }
58
59    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
60
61    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
62
63    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
64    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
65
66    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
67
68    public override bool Maximization => false;
69    #endregion
70
71    #region EventHandlers
72    public event EventHandler ProblemDataChanged;
73    #endregion
74
75    #region Constructors & Cloning
76    public StructuredSymbolicRegressionSingleObjectiveProblem() {
77      var provider = new PhysicsInstanceProvider();
78      var descriptor = new SheetBendingProcess();
79      var problemData = provider.LoadData(descriptor);
80      var shapeConstraintProblemData = new ShapeConstrainedRegressionProblemData(problemData);
81
82      var structureTemplate = new StructureTemplate();
83
84      var evaluators = new ItemSet<SymbolicRegressionSingleObjectiveEvaluator>(
85        ApplicationManager.Manager.GetInstances<SymbolicRegressionSingleObjectiveEvaluator>()
86        .Where(x => x.Maximization == Maximization));
87
88      Parameters.Add(new ConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>(
89        TreeEvaluatorParameterName,
90        evaluators,
91        evaluators.First()));
92
93      Parameters.Add(new ValueParameter<IRegressionProblemData>(
94        ProblemDataParameterName,
95        shapeConstraintProblemData));
96
97      Parameters.Add(new FixedValueParameter<StructureTemplate>(
98        StructureTemplateParameterName,
99        StructureTemplateDescriptionText,
100        structureTemplate));
101
102      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
103        InterpreterParameterName,
104        new SymbolicDataAnalysisExpressionTreeInterpreter()) { Hidden = true });
105
106      Parameters.Add(new FixedValueParameter<DoubleLimit>(
107        EstimationLimitsParameterName,
108        new DoubleLimit(double.NegativeInfinity, double.PositiveInfinity)) { Hidden = true });
109
110      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, "") { Hidden = true });
111
112      this.EvaluatorParameter.Hidden = true;
113
114      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
115      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
116      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
117
118      RegisterEventHandlers();
119      StructureTemplate.Template =
120        "(" +
121          "(210000 / (210000 + h)) * ((sigma_y * t * t) / (wR * Rt * t)) + " +
122          "PlasticHardening(_) - Elasticity(_)" +
123        ")" +
124        " * C(_)";
125    }
126
127    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
128      Cloner cloner) : base(original, cloner) {
129      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
130      RegisterEventHandlers();
131    }
132
133    [StorableConstructor]
134    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
135
136
137    [StorableHook(HookType.AfterDeserialization)]
138    private void AfterDeserialization() {
139      RegisterEventHandlers();
140    }
141
142    #endregion
143
144    #region Cloning
145    public override IDeepCloneable Clone(Cloner cloner) =>
146      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
147    #endregion
148
149    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
150      StructureTemplate.Reset();
151      // InfoBox for Reset?
152    }
153
154    private void RegisterEventHandlers() {
155      if (StructureTemplate != null) {
156        StructureTemplate.Changed += OnTemplateChanged;
157      }
158
159      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
160    }
161
162    private void OnTemplateChanged(object sender, EventArgs args) {
163      SetupStructureTemplate();
164    }
165
166    private void SetupStructureTemplate() {
167      foreach (var e in Encoding.Encodings.ToArray())
168        Encoding.Remove(e);
169
170      foreach (var f in StructureTemplate.SubFunctions) {
171        SetupVariables(f);
172        // to prevent the same encoding twice
173        if (!Encoding.Encodings.Any(x => x.Name == f.Name))
174          Encoding.Add(CreateEncoding(f));
175      }
176
177      ParameterizeEncoding();
178    }
179
180    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
181      base.Analyze(individuals, qualities, results, random);
182
183      var best = GetBestIndividual(individuals, qualities).Item1;
184
185      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
186        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
187      }
188
189      var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
190
191      var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
192      var solution = model.CreateRegressionSolution(ProblemData);
193
194      results[BestTrainingSolutionParameter.ActualName].Value = solution;
195    }
196
197
198    public override double Evaluate(Individual individual, IRandom random) {
199      var tree = BuildTree(individual);
200
201      if (StructureTemplate.ApplyLinearScaling)
202        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
203
204      individual[SymbolicExpressionTreeName] = tree;
205
206      // dpiringe: needed when Maximization = true
207      if (TreeEvaluatorParameter.Value is SymbolicRegressionParameterOptimizationEvaluator constantOptEvaluator) {
208        constantOptEvaluator.RandomParameter.Value = random;
209        constantOptEvaluator.RelativeNumberOfEvaluatedSamplesParameter.Value =
210          (PercentValue)constantOptEvaluator.ParameterOptimizationRowsPercentage.Clone();
211      }
212
213      return TreeEvaluatorParameter.Value.Evaluate(
214        tree, ProblemData,
215        ProblemData.TrainingIndices,
216        Interpreter,
217        StructureTemplate.ApplyLinearScaling,
218        EstimationLimits.Lower,
219        EstimationLimits.Upper);
220    }
221
222    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
223      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
224      var scalingNode = offsetNode.Subtrees.Where(x => !(x is NumberTreeNode)).First();
225
226      var offsetNumberNode = (NumberTreeNode)offsetNode.Subtrees.Where(x => x is NumberTreeNode).First();
227      var scalingNumberNode = (NumberTreeNode)scalingNode.Subtrees.Where(x => x is NumberTreeNode).First();
228
229      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
230      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
231
232      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
233      if (error == OnlineCalculatorError.None) {
234        offsetNumberNode.Value = a;
235        scalingNumberNode.Value = b;
236      }
237    }
238
239    private ISymbolicExpressionTree BuildTree(Individual individual) {
240      if (StructureTemplate.Tree == null)
241        throw new ArgumentException("No structure template defined!");
242
243      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
244
245      // build main tree
246      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
247        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
248
249        // add new tree
250        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
251                                          .GetSubtree(0); // Offset
252        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
253        subFunctionTreeNode.AddSubtree(subTree);
254
255      }
256      return templateTree;
257    }
258
259    private SymbolicExpressionTreeEncoding CreateEncoding(SubFunction subFunction) {
260      var encoding = new SymbolicExpressionTreeEncoding(
261            subFunction.Name,
262            subFunction.Grammar,
263            subFunction.MaximumSymbolicExpressionTreeLength,
264            subFunction.MaximumSymbolicExpressionTreeDepth);
265      return encoding;
266    }
267
268    private void ParameterizeEncoding() {
269      var manipulator = (IParameterizedItem)Encoding.Operators.OfType<MultiEncodingManipulator>().FirstOrDefault();
270      if (manipulator != null) {
271        foreach (var param in manipulator.Parameters.OfType<ConstrainedValueParameter<IManipulator>>()) {
272          var m = param.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().FirstOrDefault();
273          param.Value = m == null ? param.ValidValues.First() : m;
274        }
275      }
276    }
277    private void SetupVariables(SubFunction subFunction) {
278      var varSym = (Variable)subFunction.Grammar.GetSymbol(VariableName);
279      if (varSym == null) {
280        varSym = new Variable();
281        subFunction.Grammar.AddSymbol(varSym);
282      }
283
284      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
285      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
286
287      // set all variables
288      varSym.AllVariableNames = allVariables;
289
290      // set all allowed variables
291      if (subFunction.Arguments.Contains("_")) {
292        varSym.VariableNames = allInputs;
293      } else {
294        var vars = new List<string>();
295        var exceptions = new List<Exception>();
296        foreach (var arg in subFunction.Arguments) {
297          if (allInputs.Contains(arg))
298            vars.Add(arg);
299          else
300            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
301        }
302        if (exceptions.Any())
303          throw new AggregateException(exceptions);
304        varSym.VariableNames = vars;
305      }
306
307      varSym.Enabled = true;
308    }
309
310    public void Load(IRegressionProblemData data) {
311      ProblemData = data;
312    }
313  }
314}
Note: See TracBrowser for help on using the repository browser.