Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3136: removed a special case from the Evaluate method because it can never be true (maximization is fixed to false).

File size: 13.2 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 SymbolicDataAnalysisExpressionTreeBatchInterpreter()) { 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
205      individual[SymbolicExpressionTreeName] = tree;
206
207      return TreeEvaluatorParameter.Value.Evaluate(
208        tree, ProblemData,
209        ProblemData.TrainingIndices,
210        Interpreter,
211        StructureTemplate.ApplyLinearScaling,
212        EstimationLimits.Lower,
213        EstimationLimits.Upper);
214    }
215
216    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
217      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
218      var scalingNode = offsetNode.Subtrees.Where(x => !(x is NumberTreeNode)).First();
219
220      var offsetNumberNode = (NumberTreeNode)offsetNode.Subtrees.Where(x => x is NumberTreeNode).First();
221      var scalingNumberNode = (NumberTreeNode)scalingNode.Subtrees.Where(x => x is NumberTreeNode).First();
222
223      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
224      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
225
226      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
227      if (error == OnlineCalculatorError.None) {
228        offsetNumberNode.Value = a;
229        scalingNumberNode.Value = b;
230      }
231    }
232
233    private ISymbolicExpressionTree BuildTree(Individual individual) {
234      if (StructureTemplate.Tree == null)
235        throw new ArgumentException("No structure template defined!");
236
237      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
238
239      // build main tree
240      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
241        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
242
243        // add new tree
244        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
245                                          .GetSubtree(0); // Offset
246        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
247        subFunctionTreeNode.AddSubtree(subTree);
248
249      }
250      return templateTree;
251    }
252
253    private SymbolicExpressionTreeEncoding CreateEncoding(SubFunction subFunction) {
254      var encoding = new SymbolicExpressionTreeEncoding(
255            subFunction.Name,
256            subFunction.Grammar,
257            subFunction.MaximumSymbolicExpressionTreeLength,
258            subFunction.MaximumSymbolicExpressionTreeDepth);
259      return encoding;
260    }
261
262    private void ParameterizeEncoding() {
263      var manipulator = (IParameterizedItem)Encoding.Operators.OfType<MultiEncodingManipulator>().FirstOrDefault();
264      if (manipulator != null) {
265        foreach (var param in manipulator.Parameters.OfType<ConstrainedValueParameter<IManipulator>>()) {
266          var m = param.ValidValues.OfType<MultiSymbolicExpressionTreeManipulator>().FirstOrDefault();
267          param.Value = m == null ? param.ValidValues.First() : m;
268        }
269      }
270    }
271    private void SetupVariables(SubFunction subFunction) {
272      var varSym = (Variable)subFunction.Grammar.GetSymbol(VariableName);
273      if (varSym == null) {
274        varSym = new Variable();
275        subFunction.Grammar.AddSymbol(varSym);
276      }
277
278      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
279      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
280
281      // set all variables
282      varSym.AllVariableNames = allVariables;
283
284      // set all allowed variables
285      if (subFunction.Arguments.Contains("_")) {
286        varSym.VariableNames = allInputs;
287      } else {
288        var vars = new List<string>();
289        var exceptions = new List<Exception>();
290        foreach (var arg in subFunction.Arguments) {
291          if (allInputs.Contains(arg))
292            vars.Add(arg);
293          else
294            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
295        }
296        if (exceptions.Any())
297          throw new AggregateException(exceptions);
298        varSym.VariableNames = vars;
299      }
300
301      varSym.Enabled = true;
302    }
303
304    public void Load(IRegressionProblemData data) {
305      ProblemData = data;
306    }
307  }
308}
Note: See TracBrowser for help on using the repository browser.