Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 18104 was 18104, checked in by dpiringe, 2 years ago

#3136

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