Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3136

  • recreated problem instance Asdzadeh1 as SheetBendingProcess
  • SheetBendingProcess is located in Physics and provided by Physics/PhysicsInstanceProvider
File size: 12.3 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      return TreeEvaluatorParameter.Value.Evaluate(
197        ProblemData,
198        tree,
199        Interpreter,
200        ProblemData.TrainingIndices,
201        StructureTemplate.ApplyLinearScaling,
202        EstimationLimits.Lower,
203        EstimationLimits.Upper);
204    }
205
206    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
207      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
208      var scalingNode = offsetNode.Subtrees.Where(x => !(x is ConstantTreeNode)).First();
209
210      var offsetConstantNode = (ConstantTreeNode)offsetNode.Subtrees.Where(x => x is ConstantTreeNode).First();
211      var scalingConstantNode = (ConstantTreeNode)scalingNode.Subtrees.Where(x => x is ConstantTreeNode).First();
212
213      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
214      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
215
216      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
217      if (error == OnlineCalculatorError.None) {
218        offsetConstantNode.Value = a;
219        scalingConstantNode.Value = b;
220      }
221    }
222
223    private ISymbolicExpressionTree BuildTree(Individual individual) {
224      if (StructureTemplate.Tree == null)
225        throw new ArgumentException("No structure template defined!");
226
227      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
228
229      // build main tree
230      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
231        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
232
233        // add new tree
234        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
235                                          .GetSubtree(0); // Offset
236        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
237        subFunctionTreeNode.AddSubtree(subTree);
238
239      }
240      return templateTree;
241    }
242
243    private void SetupVariables(SubFunction subFunction) {
244      var varSym = (Variable)subFunction.Grammar.GetSymbol(VariableName);
245      if (varSym == null) {
246        varSym = new Variable();
247        subFunction.Grammar.AddSymbol(varSym);
248      }
249
250      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
251      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
252
253      // set all variables
254      varSym.AllVariableNames = allVariables;
255
256      // set all allowed variables
257      if (subFunction.Arguments.Contains("_")) {
258        varSym.VariableNames = allInputs;
259      } else {
260        var vars = new List<string>();
261        var exceptions = new List<Exception>();
262        foreach (var arg in subFunction.Arguments) {
263          if (allInputs.Contains(arg))
264            vars.Add(arg);
265          else
266            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
267        }
268        if (exceptions.Any())
269          throw new AggregateException(exceptions);
270        varSym.VariableNames = vars;
271      }
272
273      varSym.Enabled = true;
274    }
275
276    public void Load(IRegressionProblemData data) {
277      ProblemData = data;
278      StructureTemplate.Template = "f(_)";
279    }
280  }
281}
Note: See TracBrowser for help on using the repository browser.