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

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

#3136

  • added new parameters
  • added the builded tree into the scope, this allows operators to use the final tree
  • added new operators
File size: 11.2 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;
15
16namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
17  [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
18  [Item(Name = "Structured Symbolic Regression Single Objective Problem (single-objective)", Description = "A problem with a structural definition and unfixed subfunctions.")]
19  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 150)]
20  public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData> {
21
22    #region Constants
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
31    private const string StructureTemplateDescriptionText =
32      "Enter your expression as string in infix format into the empty input field.\n" +
33      "By checking the \"Apply Linear Scaling\" checkbox you can add the relevant scaling terms to your expression.\n" +
34      "After entering the expression click parse to build the tree.\n" +
35      "To edit the defined sub-functions, click on the coressponding colored node in the tree view.";
36    #endregion
37
38    #region Parameters
39    public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
40    public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
41    public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
42    public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
43    public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
44    #endregion
45
46    #region Properties
47    public IRegressionProblemData ProblemData {
48      get => ProblemDataParameter.Value;
49      set {
50        ProblemDataParameter.Value = value;
51        ProblemDataChanged?.Invoke(this, EventArgs.Empty);
52      }
53    }
54
55    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
56
57    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
58
59    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
60    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
61
62    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
63
64    public override bool Maximization => true;
65    #endregion
66
67    #region EventHandlers
68    public event EventHandler ProblemDataChanged;
69    #endregion
70
71    #region Constructors & Cloning
72    public StructuredSymbolicRegressionSingleObjectiveProblem() {
73      var problemData = new ShapeConstrainedRegressionProblemData();
74      var targetInterval = problemData.VariableRanges.GetInterval(problemData.TargetVariable);
75      var estimationWidth = targetInterval.Width * 10;
76
77
78      var structureTemplate = new StructureTemplate();
79      structureTemplate.Changed += OnTemplateChanged;
80
81      Parameters.Add(new ValueParameter<IRegressionProblemData>(
82        ProblemDataParameterName,
83        problemData));
84      Parameters.Add(new FixedValueParameter<StructureTemplate>(
85        StructureTemplateParameterName,
86        StructureTemplateDescriptionText,
87        structureTemplate));
88      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
89        InterpreterParameterName,
90        new SymbolicDataAnalysisExpressionTreeInterpreter()) { Hidden = true });
91      Parameters.Add(new FixedValueParameter<DoubleLimit>(
92        EstimationLimitsParameterName,
93        new DoubleLimit(targetInterval.LowerBound - estimationWidth, targetInterval.UpperBound + estimationWidth)));
94      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, ""));
95
96      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
97
98      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
99      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
100      //TODO change to value lookup
101      //Operators.Add(new SymbolicExpressionTreeLengthAnalyzer());
102      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
103
104    }
105
106    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
107      Cloner cloner) : base(original, cloner) { }
108
109    [StorableConstructor]
110    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
111    #endregion
112
113    #region Cloning
114    public override IDeepCloneable Clone(Cloner cloner) =>
115      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
116    #endregion
117
118    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
119      StructureTemplate.Reset();
120      // InfoBox for Reset?
121    }
122
123    private void OnTemplateChanged(object sender, EventArgs args) {
124      SetupStructureTemplate();
125    }
126
127    private void SetupStructureTemplate() {
128      foreach (var e in Encoding.Encodings.ToArray())
129        Encoding.Remove(e);
130
131      foreach (var f in StructureTemplate.SubFunctions.Values) {
132        SetupVariables(f);
133        if (!Encoding.Encodings.Any(x => x.Name == f.Name)) // to prevent the same encoding twice
134          Encoding.Add(new SymbolicExpressionTreeEncoding(
135            f.Name,
136            f.Grammar,
137            f.MaximumSymbolicExpressionTreeLength,
138            f.MaximumSymbolicExpressionTreeDepth));
139      }
140    }
141
142    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
143      base.Analyze(individuals, qualities, results, random);
144
145      var orderedIndividuals = individuals.Zip(qualities, (i, q) => new { Individual = i, Quality = q }).OrderBy(z => z.Quality);
146      var best = Maximization ? orderedIndividuals.Last().Individual : orderedIndividuals.First().Individual;
147
148      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
149        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
150      }
151
152      var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
153
154      var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
155      var solution = model.CreateRegressionSolution(ProblemData);
156
157      results[BestTrainingSolutionParameter.ActualName].Value = solution;
158    }
159
160
161    public override double Evaluate(Individual individual, IRandom random) {
162      var tree = BuildTree(individual);
163
164      if (StructureTemplate.ApplyLinearScaling)
165        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
166
167      individual[SymbolicExpressionTreeName] = tree;
168
169      var quality = SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator.Calculate(
170        Interpreter, tree,
171        EstimationLimits.Lower, EstimationLimits.Upper,
172        ProblemData, ProblemData.TrainingIndices, false);
173
174      return quality;
175    }
176
177    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
178      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
179      var scalingNode = offsetNode.Subtrees.Where(x => !(x is ConstantTreeNode)).First();
180
181      var offsetConstantNode = (ConstantTreeNode)offsetNode.Subtrees.Where(x => x is ConstantTreeNode).First();
182      var scalingConstantNode = (ConstantTreeNode)scalingNode.Subtrees.Where(x => x is ConstantTreeNode).First();
183
184      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
185      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
186
187      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
188      if (error == OnlineCalculatorError.None) {
189        offsetConstantNode.Value = a;
190        scalingConstantNode.Value = b;
191      }
192    }
193
194    private ISymbolicExpressionTree BuildTree(Individual individual) {
195      if (StructureTemplate.Tree == null)
196        throw new ArgumentException("No structure template defined!");
197
198      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
199
200      // build main tree
201      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
202        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
203
204        // add new tree
205        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
206                                          .GetSubtree(0); // Offset
207        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
208        subFunctionTreeNode.AddSubtree(subTree);
209
210      }
211      return templateTree;
212    }
213
214    private void SetupVariables(SubFunction subFunction) {
215      var varSym = (Variable)subFunction.Grammar.GetSymbol("Variable");
216      if (varSym == null) {
217        varSym = new Variable();
218        subFunction.Grammar.AddSymbol(varSym);
219      }
220
221      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
222      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
223
224      // set all variables
225      varSym.AllVariableNames = allVariables;
226
227      // set all allowed variables
228      if (subFunction.Arguments.Contains("_")) {
229        varSym.VariableNames = allInputs;
230      } else {
231        var vars = new List<string>();
232        var exceptions = new List<Exception>();
233        foreach (var arg in subFunction.Arguments) {
234          if (allInputs.Contains(arg))
235            vars.Add(arg);
236          else
237            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
238        }
239        if (exceptions.Any())
240          throw new AggregateException(exceptions);
241        varSym.VariableNames = vars;
242      }
243
244      varSym.Enabled = true;
245    }
246
247    public void Load(IRegressionProblemData data) => ProblemData = data;
248  }
249}
Note: See TracBrowser for help on using the repository browser.