Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3136

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