Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3136

  • changed the visibility of the following parameters: EstimationLimitsParameter, EvaluatorParameter and BestTrainingSolutionParameter
  • added first steps to set an evaluator as parameter
    • added a new parameter TreeEvaluatorParameter
    • added a temporary logic to static evaluator method Calculate
    • tried to change a lot of necessary parameters to use the method Evaluate, this caused a lot of problems -> reverted all changes
File size: 14.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;
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 TreeEvaluatorParameterName = "TreeEvaluator";
24    private const string ProblemDataParameterName = "ProblemData";
25    private const string StructureTemplateParameterName = "Structure Template";
26    private const string InterpreterParameterName = "Interpreter";
27    private const string EstimationLimitsParameterName = "EstimationLimits";
28    private const string BestTrainingSolutionParameterName = "Best Training Solution";
29
30    private const string SymbolicExpressionTreeName = "SymbolicExpressionTree";
31
32    private const string StructureTemplateDescriptionText =
33      "Enter your expression as string in infix format into the empty input field.\n" +
34      "By checking the \"Apply Linear Scaling\" checkbox you can add the relevant scaling terms to your expression.\n" +
35      "After entering the expression click parse to build the tree.\n" +
36      "To edit the defined sub-functions, click on the coressponding colored node in the tree view.";
37    #endregion
38
39    #region Parameters
40    public IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator> TreeEvaluatorParameter => (IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>)Parameters[TreeEvaluatorParameterName];
41    public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
42    public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
43    public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
44    public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
45    public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
46    #endregion
47
48    #region Properties
49
50    public IRegressionProblemData ProblemData {
51      get => ProblemDataParameter.Value;
52      set {
53        ProblemDataParameter.Value = value;
54        ProblemDataChanged?.Invoke(this, EventArgs.Empty);
55      }
56    }
57
58    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
59
60    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
61
62    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
63    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
64
65    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
66
67    public override bool Maximization => false;
68    #endregion
69
70    #region EventHandlers
71    public event EventHandler ProblemDataChanged;
72    #endregion
73
74    #region Constructors & Cloning
75    public StructuredSymbolicRegressionSingleObjectiveProblem() {
76      var problemData = new ShapeConstrainedRegressionProblemData();
77      var targetInterval = problemData.VariableRanges.GetInterval(problemData.TargetVariable);
78      var estimationWidth = targetInterval.Width * 10;
79
80
81      var structureTemplate = new StructureTemplate();
82      structureTemplate.Changed += OnTemplateChanged;
83
84      var evaluators = new ItemSet<SymbolicRegressionSingleObjectiveEvaluator>(
85        ApplicationManager.Manager.GetInstances<SymbolicRegressionSingleObjectiveEvaluator>()
86        .Where(x => x.Maximization == Maximization));
87
88      Parameters.Add(new ConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>(
89        TreeEvaluatorParameterName,
90        evaluators,
91        evaluators.First()));
92
93      Parameters.Add(new ValueParameter<IRegressionProblemData>(
94        ProblemDataParameterName,
95        problemData));
96      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
97
98      Parameters.Add(new FixedValueParameter<StructureTemplate>(
99        StructureTemplateParameterName,
100        StructureTemplateDescriptionText,
101        structureTemplate));
102     
103      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
104        InterpreterParameterName,
105        new SymbolicDataAnalysisExpressionTreeInterpreter()) { Hidden = true });
106     
107      Parameters.Add(new FixedValueParameter<DoubleLimit>(
108        EstimationLimitsParameterName,
109        new DoubleLimit(targetInterval.LowerBound - estimationWidth, targetInterval.UpperBound + estimationWidth)));
110      EstimationLimitsParameter.Hidden = true;
111
112      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, ""));
113      this.BestTrainingSolutionParameter.Hidden = true;
114
115      this.EvaluatorParameter.Hidden = true;
116
117     
118
119      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
120      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
121      //TODO change to value lookup
122      //Operators.Add(new SymbolicExpressionTreeLengthAnalyzer());
123      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
124
125    }
126
127    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
128      Cloner cloner) : base(original, cloner) { }
129
130    [StorableConstructor]
131    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
132    #endregion
133
134    #region Cloning
135    public override IDeepCloneable Clone(Cloner cloner) =>
136      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
137    #endregion
138
139    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
140      StructureTemplate.Reset();
141      // InfoBox for Reset?
142    }
143
144    private void OnTemplateChanged(object sender, EventArgs args) {
145      SetupStructureTemplate();
146    }
147
148    private void SetupStructureTemplate() {
149      foreach (var e in Encoding.Encodings.ToArray())
150        Encoding.Remove(e);
151
152      foreach (var f in StructureTemplate.SubFunctions.Values) {
153        SetupVariables(f);
154        if (!Encoding.Encodings.Any(x => x.Name == f.Name)) // to prevent the same encoding twice
155          Encoding.Add(new SymbolicExpressionTreeEncoding(
156            f.Name,
157            f.Grammar,
158            f.MaximumSymbolicExpressionTreeLength,
159            f.MaximumSymbolicExpressionTreeDepth));
160      }
161    }
162
163    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
164      base.Analyze(individuals, qualities, results, random);
165
166      var orderedIndividuals = individuals.Zip(qualities, (i, q) => new { Individual = i, Quality = q }).OrderBy(z => z.Quality);
167      var best = Maximization ? orderedIndividuals.Last().Individual : orderedIndividuals.First().Individual;
168
169      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
170        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
171      }
172
173      var tree = (ISymbolicExpressionTree)best[SymbolicExpressionTreeName];
174
175      var model = new SymbolicRegressionModel(ProblemData.TargetVariable, tree, Interpreter);
176      var solution = model.CreateRegressionSolution(ProblemData);
177
178      results[BestTrainingSolutionParameter.ActualName].Value = solution;
179    }
180
181
182    public override double Evaluate(Individual individual, IRandom random) {
183      var tree = BuildTree(individual);
184
185      if (StructureTemplate.ApplyLinearScaling)
186        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
187
188      individual[SymbolicExpressionTreeName] = tree;
189
190      //TreeEvaluatorParameter.Value.EstimationLimitsParameter.ActualValue = EstimationLimits;
191      //TreeEvaluatorParameter.Value.EstimationLimitsParameter.Value = EstimationLimits;
192      //var quality = TreeEvaluatorParameter.Value.Evaluate(new ExecutionContext(null, this, new Scope("Test")), tree, ProblemData, ProblemData.TrainingIndices);
193
194      var quality = double.MaxValue;
195      var evaluatorGUID = TreeEvaluatorParameter.Value.GetType().GUID;
196
197      // TODO: use Evaluate method instead of static Calculate -> a fake ExecutionContext is needed
198      if (evaluatorGUID == typeof(NMSESingleObjectiveConstraintsEvaluator).GUID) {
199        quality = NMSESingleObjectiveConstraintsEvaluator.Calculate(
200        Interpreter, tree,
201        EstimationLimits.Lower, EstimationLimits.Upper,
202        ProblemData, ProblemData.TrainingIndices, new IntervalArithBoundsEstimator());
203      } else if (evaluatorGUID == typeof(SymbolicRegressionLogResidualEvaluator).GUID) {
204        quality = SymbolicRegressionLogResidualEvaluator.Calculate(
205        Interpreter, tree,
206        EstimationLimits.Lower, EstimationLimits.Upper,
207        ProblemData, ProblemData.TrainingIndices);
208      } else if (evaluatorGUID == typeof(SymbolicRegressionMeanRelativeErrorEvaluator).GUID) {
209        quality = SymbolicRegressionMeanRelativeErrorEvaluator.Calculate(
210        Interpreter, tree,
211        EstimationLimits.Lower, EstimationLimits.Upper,
212        ProblemData, ProblemData.TrainingIndices);
213      } else if (evaluatorGUID == typeof(SymbolicRegressionSingleObjectiveMaxAbsoluteErrorEvaluator).GUID) {
214        quality = SymbolicRegressionSingleObjectiveMaxAbsoluteErrorEvaluator.Calculate(
215        Interpreter, tree,
216        EstimationLimits.Lower, EstimationLimits.Upper,
217        ProblemData, ProblemData.TrainingIndices, false);
218      } else if (evaluatorGUID == typeof(SymbolicRegressionSingleObjectiveMeanAbsoluteErrorEvaluator).GUID) {
219        quality = SymbolicRegressionSingleObjectiveMeanAbsoluteErrorEvaluator.Calculate(
220        Interpreter, tree,
221        EstimationLimits.Lower, EstimationLimits.Upper,
222        ProblemData, ProblemData.TrainingIndices, false);
223      } else { // SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator
224        quality = SymbolicRegressionSingleObjectiveMeanSquaredErrorEvaluator.Calculate(
225        Interpreter, tree,
226        EstimationLimits.Lower, EstimationLimits.Upper,
227        ProblemData, ProblemData.TrainingIndices, false);
228      }
229   
230      return quality;
231    }
232
233    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
234      var offsetNode = tree.Root.GetSubtree(0).GetSubtree(0);
235      var scalingNode = offsetNode.Subtrees.Where(x => !(x is ConstantTreeNode)).First();
236
237      var offsetConstantNode = (ConstantTreeNode)offsetNode.Subtrees.Where(x => x is ConstantTreeNode).First();
238      var scalingConstantNode = (ConstantTreeNode)scalingNode.Subtrees.Where(x => x is ConstantTreeNode).First();
239
240      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
241      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
242
243      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
244      if (error == OnlineCalculatorError.None) {
245        offsetConstantNode.Value = a;
246        scalingConstantNode.Value = b;
247      }
248    }
249
250    private ISymbolicExpressionTree BuildTree(Individual individual) {
251      if (StructureTemplate.Tree == null)
252        throw new ArgumentException("No structure template defined!");
253
254      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
255
256      // build main tree
257      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
258        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
259
260        // add new tree
261        var subTree = subFunctionTree.Root.GetSubtree(0)  // Start
262                                          .GetSubtree(0); // Offset
263        subTree = (ISymbolicExpressionTreeNode)subTree.Clone();
264        subFunctionTreeNode.AddSubtree(subTree);
265
266      }
267      return templateTree;
268    }
269
270    private void SetupVariables(SubFunction subFunction) {
271      var varSym = (Variable)subFunction.Grammar.GetSymbol("Variable");
272      if (varSym == null) {
273        varSym = new Variable();
274        subFunction.Grammar.AddSymbol(varSym);
275      }
276
277      var allVariables = ProblemData.InputVariables.Select(x => x.Value);
278      var allInputs = allVariables.Where(x => x != ProblemData.TargetVariable);
279
280      // set all variables
281      varSym.AllVariableNames = allVariables;
282
283      // set all allowed variables
284      if (subFunction.Arguments.Contains("_")) {
285        varSym.VariableNames = allInputs;
286      } else {
287        var vars = new List<string>();
288        var exceptions = new List<Exception>();
289        foreach (var arg in subFunction.Arguments) {
290          if (allInputs.Contains(arg))
291            vars.Add(arg);
292          else
293            exceptions.Add(new ArgumentException($"The argument '{arg}' for sub-function '{subFunction.Name}' is not a valid variable."));
294        }
295        if (exceptions.Any())
296          throw new AggregateException(exceptions);
297        varSym.VariableNames = vars;
298      }
299
300      varSym.Enabled = true;
301    }
302
303    public void Load(IRegressionProblemData data) => ProblemData = data;
304  }
305}
Note: See TracBrowser for help on using the repository browser.