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

Last change on this file since 18103 was 18103, checked in by dpiringe, 8 months ago

#3136

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