Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18178 was 18178, checked in by gkronber, 2 years ago

#3136 copied code with minor modifications from ParameterOptimizationEvaluator into the NMSEConstraintsEvaluator because the code in ParameterOptimizationEvaluator uses R² internally and is incompatible to the NMSEEvaluator.

File size: 13.4 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 SymbolicRegressionSingleObjectiveEvaluator TreeEvaluator => TreeEvaluatorParameter.Value;
60
61    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
62
63    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
64
65    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
66    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
67
68    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
69
70    public override bool Maximization => false;
71    #endregion
72
73    #region EventHandlers
74    public event EventHandler ProblemDataChanged;
75    #endregion
76
77    #region Constructors & Cloning
78    public StructuredSymbolicRegressionSingleObjectiveProblem() {
79      var provider = new PhysicsInstanceProvider();
80      var descriptor = new SheetBendingProcess();
81      var problemData = provider.LoadData(descriptor);
82      var shapeConstraintProblemData = new ShapeConstrainedRegressionProblemData(problemData);
83
84      var structureTemplate = new StructureTemplate();
85
86      var evaluators = new ItemSet<SymbolicRegressionSingleObjectiveEvaluator>(
87        ApplicationManager.Manager.GetInstances<SymbolicRegressionSingleObjectiveEvaluator>()
88        .Where(x => x.Maximization == Maximization));
89
90      Parameters.Add(new ConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>(
91        TreeEvaluatorParameterName,
92        evaluators,
93        evaluators.First()));
94
95      Parameters.Add(new ValueParameter<IRegressionProblemData>(
96        ProblemDataParameterName,
97        shapeConstraintProblemData));
98
99      Parameters.Add(new FixedValueParameter<StructureTemplate>(
100        StructureTemplateParameterName,
101        StructureTemplateDescriptionText,
102        structureTemplate));
103
104      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
105        InterpreterParameterName,
106        new SymbolicDataAnalysisExpressionTreeBatchInterpreter()) { Hidden = true });
107
108      Parameters.Add(new FixedValueParameter<DoubleLimit>(
109        EstimationLimitsParameterName,
110        new DoubleLimit(double.NegativeInfinity, double.PositiveInfinity)) { Hidden = true });
111
112      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, "") { Hidden = true });
113
114      this.EvaluatorParameter.Hidden = true;
115
116      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
117      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
118      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
119
120      RegisterEventHandlers();
121      StructureTemplate.Template =
122        "(" +
123          "(210000 / (210000 + h)) * ((sigma_y * t * t) / (wR * Rt * t)) + " +
124          "PlasticHardening(_) - Elasticity(_)" +
125        ")" +
126        " * C(_)";
127    }
128
129    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
130      Cloner cloner) : base(original, cloner) {
131      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
132      RegisterEventHandlers();
133    }
134
135    [StorableConstructor]
136    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
137
138
139    [StorableHook(HookType.AfterDeserialization)]
140    private void AfterDeserialization() {
141      RegisterEventHandlers();
142    }
143
144    #endregion
145
146    #region Cloning
147    public override IDeepCloneable Clone(Cloner cloner) =>
148      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
149    #endregion
150
151    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
152      StructureTemplate.Reset();
153      // InfoBox for Reset?
154    }
155
156    private void RegisterEventHandlers() {
157      if (StructureTemplate != null) {
158        StructureTemplate.Changed += OnTemplateChanged;
159      }
160
161      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
162    }
163
164    private void OnTemplateChanged(object sender, EventArgs args) {
165      SetupStructureTemplate();
166    }
167
168    private void SetupStructureTemplate() {
169      foreach (var e in Encoding.Encodings.ToArray())
170        Encoding.Remove(e);
171
172      foreach (var f in StructureTemplate.SubFunctions) {
173        SetupVariables(f);
174        // to prevent the same encoding twice
175        if (!Encoding.Encodings.Any(x => x.Name == f.Name))
176          Encoding.Add(CreateEncoding(f));
177      }
178
179      ParameterizeEncoding();
180    }
181
182    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
183      base.Analyze(individuals, qualities, results, random);
184
185      var best = GetBestIndividual(individuals, qualities).Item1;
186
187      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
188        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
189      }
190
191      var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
192
193      var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
194      var solution = model.CreateRegressionSolution(ProblemData);
195
196      results[BestTrainingSolutionParameter.ActualName].Value = solution;
197    }
198
199
200    public override double Evaluate(Individual individual, IRandom random) {
201      var tree = BuildTree(individual);
202
203      // NMSEConstraintsEvaluator sets linear scaling terms itself
204      if (StructureTemplate.ApplyLinearScaling && !(TreeEvaluator is NMSESingleObjectiveConstraintsEvaluator)) {
205        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
206      }
207
208      individual[SymbolicExpressionTreeName] = tree;
209
210      return TreeEvaluator.Evaluate(
211        tree, ProblemData,
212        ProblemData.TrainingIndices,
213        Interpreter,
214        StructureTemplate.ApplyLinearScaling,
215        EstimationLimits.Lower,
216        EstimationLimits.Upper);
217    }
218
219    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
220      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
221      var scalingNode = offsetNode.Subtrees.Where(x => !(x is NumberTreeNode)).First();
222
223      var offsetNumberNode = (NumberTreeNode)offsetNode.Subtrees.Where(x => x is NumberTreeNode).First();
224      var scalingNumberNode = (NumberTreeNode)scalingNode.Subtrees.Where(x => x is NumberTreeNode).First();
225
226      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
227      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
228
229      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
230      if (error == OnlineCalculatorError.None) {
231        offsetNumberNode.Value = a;
232        scalingNumberNode.Value = b;
233      }
234    }
235
236    private ISymbolicExpressionTree BuildTree(Individual individual) {
237      if (StructureTemplate.Tree == null)
238        throw new ArgumentException("No structure template defined!");
239
240      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
241
242      // build main tree
243      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
244        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
245
246        // add new tree
247        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
248                                          .GetSubtree(0); // Offset
249        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
250        subFunctionTreeNode.AddSubtree(subTree);
251
252      }
253      return templateTree;
254    }
255
256    private SymbolicExpressionTreeEncoding CreateEncoding(SubFunction subFunction) {
257      var encoding = new SymbolicExpressionTreeEncoding(
258            subFunction.Name,
259            subFunction.Grammar,
260            subFunction.MaximumSymbolicExpressionTreeLength,
261            subFunction.MaximumSymbolicExpressionTreeDepth);
262      return encoding;
263    }
264
265    private void ParameterizeEncoding() {
266      var manipulator = (IParameterizedItem)Encoding.Operators.OfType<MultiEncodingManipulator>().FirstOrDefault();
267      if (manipulator != null) {
268        foreach (var param in manipulator.Parameters.OfType<ConstrainedValueParameter<IManipulator>>()) {
269          var m = param.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().FirstOrDefault();
270          param.Value = m == null ? param.ValidValues.First() : m;
271        }
272      }
273    }
274    private void SetupVariables(SubFunction subFunction) {
275      var varSym = (Variable)subFunction.Grammar.GetSymbol(VariableName);
276      if (varSym == null) {
277        varSym = new Variable();
278        subFunction.Grammar.AddSymbol(varSym);
279      }
280
281      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
282      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
283
284      // set all variables
285      varSym.AllVariableNames = allVariables;
286
287      // set all allowed variables
288      if (subFunction.Arguments.Contains("_")) {
289        varSym.VariableNames = allInputs;
290      } else {
291        var vars = new List<string>();
292        var exceptions = new List<Exception>();
293        foreach (var arg in subFunction.Arguments) {
294          if (allInputs.Contains(arg))
295            vars.Add(arg);
296          else
297            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
298        }
299        if (exceptions.Any())
300          throw new AggregateException(exceptions);
301        varSym.VariableNames = vars;
302      }
303
304      varSym.Enabled = true;
305    }
306
307    public void Load(IRegressionProblemData data) {
308      ProblemData = data;
309    }
310  }
311}
Note: See TracBrowser for help on using the repository browser.