Free cookie consent management tool by TermsFeed Policy Generator

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, 2 years 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
RevLine 
[18061]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;
[18062]13using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
[18075]14using HeuristicLab.PluginInfrastructure;
[18084]15using HeuristicLab.Problems.Instances.DataAnalysis;
[18061]16
[18063]17namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Regression {
[18061]18  [StorableType("7464E84B-65CC-440A-91F0-9FA920D730F9")]
[18063]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)]
[18075]21  public class StructuredSymbolicRegressionSingleObjectiveProblem : SingleObjectiveBasicProblem<MultiEncoding>, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData> {
[18061]22
23    #region Constants
[18081]24    private const string TreeEvaluatorParameterName = "TreeEvaluator";
[18061]25    private const string ProblemDataParameterName = "ProblemData";
[18063]26    private const string StructureTemplateParameterName = "Structure Template";
[18075]27    private const string InterpreterParameterName = "Interpreter";
[18076]28    private const string EstimationLimitsParameterName = "EstimationLimits";
29    private const string BestTrainingSolutionParameterName = "Best Training Solution";
[18072]30
[18076]31    private const string SymbolicExpressionTreeName = "SymbolicExpressionTree";
[18095]32    private const string VariableName = "Variable";
[18076]33
34    private const string StructureTemplateDescriptionText =
[18072]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.";
[18061]39    #endregion
40
[18072]41    #region Parameters
[18081]42    public IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator> TreeEvaluatorParameter => (IConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>)Parameters[TreeEvaluatorParameterName];
[18061]43    public IValueParameter<IRegressionProblemData> ProblemDataParameter => (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName];
[18063]44    public IFixedValueParameter<StructureTemplate> StructureTemplateParameter => (IFixedValueParameter<StructureTemplate>)Parameters[StructureTemplateParameterName];
[18075]45    public IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter> InterpreterParameter => (IValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>)Parameters[InterpreterParameterName];
[18076]46    public IFixedValueParameter<DoubleLimit> EstimationLimitsParameter => (IFixedValueParameter<DoubleLimit>)Parameters[EstimationLimitsParameterName];
47    public IResultParameter<ISymbolicRegressionSolution> BestTrainingSolutionParameter => (IResultParameter<ISymbolicRegressionSolution>)Parameters[BestTrainingSolutionParameterName];
[18061]48    #endregion
49
50    #region Properties
[18081]51
[18076]52    public IRegressionProblemData ProblemData {
53      get => ProblemDataParameter.Value;
[18061]54      set {
55        ProblemDataParameter.Value = value;
56        ProblemDataChanged?.Invoke(this, EventArgs.Empty);
57      }
58    }
59
[18075]60    public StructureTemplate StructureTemplate => StructureTemplateParameter.Value;
[18061]61
[18075]62    public ISymbolicDataAnalysisExpressionTreeInterpreter Interpreter => InterpreterParameter.Value;
[18063]63
[18061]64    IParameter IDataAnalysisProblem.ProblemDataParameter => ProblemDataParameter;
65    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData => ProblemData;
66
[18076]67    public DoubleLimit EstimationLimits => EstimationLimitsParameter.Value;
68
[18081]69    public override bool Maximization => false;
[18061]70    #endregion
71
72    #region EventHandlers
73    public event EventHandler ProblemDataChanged;
74    #endregion
75
76    #region Constructors & Cloning
77    public StructuredSymbolicRegressionSingleObjectiveProblem() {
[18101]78      var provider = new PhysicsInstanceProvider();
79      var descriptor = new SheetBendingProcess();
[18084]80      var problemData = provider.LoadData(descriptor);
81      var shapeConstraintProblemData = new ShapeConstrainedRegressionProblemData(problemData);
82
83
84      var targetInterval = shapeConstraintProblemData.VariableRanges.GetInterval(shapeConstraintProblemData.TargetVariable);
[18076]85      var estimationWidth = targetInterval.Width * 10;
[18062]86
[18076]87
[18065]88      var structureTemplate = new StructureTemplate();
[18066]89      structureTemplate.Changed += OnTemplateChanged;
[18065]90
[18081]91      var evaluators = new ItemSet<SymbolicRegressionSingleObjectiveEvaluator>(
92        ApplicationManager.Manager.GetInstances<SymbolicRegressionSingleObjectiveEvaluator>()
93        .Where(x => x.Maximization == Maximization));
94
95      Parameters.Add(new ConstrainedValueParameter<SymbolicRegressionSingleObjectiveEvaluator>(
[18095]96        TreeEvaluatorParameterName,
[18081]97        evaluators,
98        evaluators.First()));
99
[18075]100      Parameters.Add(new ValueParameter<IRegressionProblemData>(
[18076]101        ProblemDataParameterName,
[18084]102        shapeConstraintProblemData));
[18081]103      ProblemDataParameter.ValueChanged += ProblemDataParameterValueChanged;
104
[18075]105      Parameters.Add(new FixedValueParameter<StructureTemplate>(
[18076]106        StructureTemplateParameterName,
107        StructureTemplateDescriptionText,
[18075]108        structureTemplate));
[18099]109
[18075]110      Parameters.Add(new ValueParameter<ISymbolicDataAnalysisExpressionTreeInterpreter>(
[18076]111        InterpreterParameterName,
112        new SymbolicDataAnalysisExpressionTreeInterpreter()) { Hidden = true });
[18099]113
[18076]114      Parameters.Add(new FixedValueParameter<DoubleLimit>(
115        EstimationLimitsParameterName,
[18095]116        new DoubleLimit(targetInterval.LowerBound - estimationWidth, targetInterval.UpperBound + estimationWidth)) { Hidden = true });
[18081]117
[18095]118      Parameters.Add(new ResultParameter<ISymbolicRegressionSolution>(BestTrainingSolutionParameterName, "") { Hidden = true });
[18075]119
[18081]120      this.EvaluatorParameter.Hidden = true;
[18099]121
[18076]122      Operators.Add(new SymbolicDataAnalysisVariableFrequencyAnalyzer());
123      Operators.Add(new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer());
124      Operators.Add(new SymbolicExpressionSymbolFrequencyAnalyzer());
125
[18099]126      StructureTemplate.Template =
[18084]127        "(" +
128          "(210000 / (210000 + h)) * ((sigma_y * t * t) / (wR * Rt * t)) + " +
129          "PlasticHardening(_) - Elasticity(_)" +
130        ")" +
131        " * C(_)";
[18061]132    }
133
[18076]134    public StructuredSymbolicRegressionSingleObjectiveProblem(StructuredSymbolicRegressionSingleObjectiveProblem original,
135      Cloner cloner) : base(original, cloner) { }
[18061]136
137    [StorableConstructor]
[18063]138    protected StructuredSymbolicRegressionSingleObjectiveProblem(StorableConstructorFlag _) : base(_) { }
[18065]139    #endregion
[18061]140
[18065]141    #region Cloning
[18061]142    public override IDeepCloneable Clone(Cloner cloner) =>
143      new StructuredSymbolicRegressionSingleObjectiveProblem(this, cloner);
144    #endregion
145
[18075]146    private void ProblemDataParameterValueChanged(object sender, EventArgs e) {
147      StructureTemplate.Reset();
148      // InfoBox for Reset?
149    }
150
[18066]151    private void OnTemplateChanged(object sender, EventArgs args) {
[18068]152      SetupStructureTemplate();
153    }
154
155    private void SetupStructureTemplate() {
[18066]156      foreach (var e in Encoding.Encodings.ToArray())
157        Encoding.Remove(e);
158
[18068]159      foreach (var f in StructureTemplate.SubFunctions.Values) {
160        SetupVariables(f);
[18075]161        if (!Encoding.Encodings.Any(x => x.Name == f.Name)) // to prevent the same encoding twice
162          Encoding.Add(new SymbolicExpressionTreeEncoding(
[18076]163            f.Name,
164            f.Grammar,
165            f.MaximumSymbolicExpressionTreeLength,
[18075]166            f.MaximumSymbolicExpressionTreeDepth));
[18066]167      }
168    }
169
170    public override void Analyze(Individual[] individuals, double[] qualities, ResultCollection results, IRandom random) {
171      base.Analyze(individuals, qualities, results, random);
172
[18095]173      var best = GetBestIndividual(individuals, qualities).Item1;
[18076]174
175      if (!results.ContainsKey(BestTrainingSolutionParameter.ActualName)) {
176        results.Add(new Result(BestTrainingSolutionParameter.ActualName, typeof(SymbolicRegressionSolution)));
[18066]177      }
178
[18076]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;
[18066]185    }
186
[18076]187
[18065]188    public override double Evaluate(Individual individual, IRandom random) {
[18066]189      var tree = BuildTree(individual);
[18071]190
[18072]191      if (StructureTemplate.ApplyLinearScaling)
[18076]192        AdjustLinearScalingParams(ProblemData, tree, Interpreter);
193
194      individual[SymbolicExpressionTreeName] = tree;
195
[18103]196      if(TreeEvaluatorParameter.Value is SymbolicRegressionConstantOptimizationEvaluator)
197        TreeEvaluatorParameter.Value.RandomParameter.Value = random;
198
[18095]199      return TreeEvaluatorParameter.Value.Evaluate(
[18103]200        tree, ProblemData,
201        ProblemData.TrainingIndices,
[18095]202        Interpreter,
203        StructureTemplate.ApplyLinearScaling,
[18099]204        EstimationLimits.Lower,
[18095]205        EstimationLimits.Upper);
[18066]206    }
207
[18076]208    private static void AdjustLinearScalingParams(IRegressionProblemData problemData, ISymbolicExpressionTree tree, ISymbolicDataAnalysisExpressionTreeInterpreter interpreter) {
[18071]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
[18076]215      var estimatedValues = interpreter.GetSymbolicExpressionTreeValues(tree, problemData.Dataset, problemData.TrainingIndices);
216      var targetValues = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, problemData.TrainingIndices);
[18071]217
218      OnlineLinearScalingParameterCalculator.Calculate(estimatedValues, targetValues, out double a, out double b, out OnlineCalculatorError error);
[18076]219      if (error == OnlineCalculatorError.None) {
[18071]220        offsetConstantNode.Value = a;
221        scalingConstantNode.Value = b;
222      }
223    }
224
[18066]225    private ISymbolicExpressionTree BuildTree(Individual individual) {
[18075]226      if (StructureTemplate.Tree == null)
227        throw new ArgumentException("No structure template defined!");
228
[18065]229      var templateTree = (ISymbolicExpressionTree)StructureTemplate.Tree.Clone();
[18066]230
[18065]231      // build main tree
[18076]232      foreach (var subFunctionTreeNode in templateTree.IterateNodesPrefix().OfType<SubFunctionTreeNode>()) {
233        var subFunctionTree = individual.SymbolicExpressionTree(subFunctionTreeNode.Name);
[18062]234
[18076]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
[18065]241      }
[18066]242      return templateTree;
[18061]243    }
244
[18068]245    private void SetupVariables(SubFunction subFunction) {
[18095]246      var varSym = (Variable)subFunction.Grammar.GetSymbol(VariableName);
[18068]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
[18099]278    public void Load(IRegressionProblemData data) {
279      ProblemData = data;
280      StructureTemplate.Template = "f(_)";
281    }
[18061]282  }
283}
Note: See TracBrowser for help on using the repository browser.