source: branches/2521_ProblemRefactoring/HeuristicLab.Problems.GeneticProgramming/3.3/BasicSymbolicRegression/Problem.cs @ 17270

Last change on this file since 17270 was 17270, checked in by abeham, 3 years ago

#2521: worked on removing virtual from Maximization for single-objective problems

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Linq;
25using HEAL.Attic;
26using HeuristicLab.Common;
27using HeuristicLab.Core;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
29using HeuristicLab.Parameters;
30using HeuristicLab.Problems.DataAnalysis;
31using HeuristicLab.Problems.Instances;
32
33
34namespace HeuristicLab.Problems.GeneticProgramming.BasicSymbolicRegression {
35  [Item("Koza-style Symbolic Regression", "An implementation of symbolic regression without bells-and-whistles. Use \"Symbolic Regression Problem (single-objective)\" if you want to use all features.")]
36  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 900)]
37  [StorableType("72011B73-28C6-4D5E-BEDF-27425BC87B9C")]
38  public sealed class Problem : SymbolicExpressionTreeProblem, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData>, IProblemInstanceExporter<IRegressionProblemData> {
39
40    #region parameter names
41    private const string ProblemDataParameterName = "ProblemData";
42    #endregion
43
44    #region Parameter Properties
45    IParameter IDataAnalysisProblem.ProblemDataParameter { get { return ProblemDataParameter; } }
46
47    public IValueParameter<IRegressionProblemData> ProblemDataParameter {
48      get { return (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; }
49    }
50    #endregion
51
52    #region Properties
53    public IRegressionProblemData ProblemData {
54      get { return ProblemDataParameter.Value; }
55      set { ProblemDataParameter.Value = value; }
56    }
57    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData { get { return ProblemData; } }
58    #endregion
59
60    public event EventHandler ProblemDataChanged;
61
62    #region item cloning and persistence
63    // persistence
64    [StorableConstructor]
65    private Problem(StorableConstructorFlag _) : base(_) { }
66    [StorableHook(HookType.AfterDeserialization)]
67    private void AfterDeserialization() {
68      RegisterEventHandlers();
69    }
70
71    // cloning
72    private Problem(Problem original, Cloner cloner)
73      : base(original, cloner) {
74      RegisterEventHandlers();
75    }
76    public override IDeepCloneable Clone(Cloner cloner) { return new Problem(this, cloner); }
77    #endregion
78
79    public Problem() : base(new SymbolicExpressionTreeEncoding()) {
80      Maximization = true;
81      Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, "The data for the regression problem", new RegressionProblemData()));
82
83      Encoding.TreeLength = 100;
84      Encoding.TreeDepth = 17;
85
86      UpdateGrammar();
87      RegisterEventHandlers();
88    }
89
90
91    public override double Evaluate(ISymbolicExpressionTree tree, IRandom random) {
92      // Doesn't use classes from HeuristicLab.Problems.DataAnalysis.Symbolic to make sure that the implementation can be fully understood easily.
93      // HeuristicLab.Problems.DataAnalysis.Symbolic would already provide all the necessary functionality (esp. interpreter) but at a much higher complexity.
94      // Another argument is that we don't need a reference to HeuristicLab.Problems.DataAnalysis.Symbolic
95
96      var problemData = ProblemData;
97      var rows = ProblemData.TrainingIndices.ToArray();
98      var target = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
99      var predicted = Interpret(tree, problemData.Dataset, rows);
100
101      OnlineCalculatorError errorState;
102      var r = OnlinePearsonsRCalculator.Calculate(target, predicted, out errorState);
103      if (errorState != OnlineCalculatorError.None) r = 0;
104      return r * r;
105    }
106
107    private IEnumerable<double> Interpret(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
108      // skip programRoot and startSymbol
109      return InterpretRec(tree.Root.GetSubtree(0).GetSubtree(0), dataset, rows);
110    }
111
112    private IEnumerable<double> InterpretRec(ISymbolicExpressionTreeNode node, IDataset dataset, IEnumerable<int> rows) {
113      Func<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode, Func<double, double, double>, IEnumerable<double>> binaryEval =
114        (left, right, f) => InterpretRec(left, dataset, rows).Zip(InterpretRec(right, dataset, rows), f);
115
116      switch (node.Symbol.Name) {
117        case "+": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x + y);
118        case "*": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x * y);
119        case "-": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x - y);
120        case "%": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => y.IsAlmost(0.0) ? 0.0 : x / y); // protected division
121        default: {
122            double erc;
123            if (double.TryParse(node.Symbol.Name, out erc)) {
124              return rows.Select(_ => erc);
125            } else {
126              // assume that this is a variable name
127              return dataset.GetDoubleValues(node.Symbol.Name, rows);
128            }
129          }
130      }
131    }
132
133
134    #region events
135    private void RegisterEventHandlers() {
136      ProblemDataParameter.ValueChanged += new EventHandler(ProblemDataParameter_ValueChanged);
137      if (ProblemDataParameter.Value != null) ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
138    }
139
140    private void ProblemDataParameter_ValueChanged(object sender, EventArgs e) {
141      ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
142      OnProblemDataChanged();
143      OnReset();
144    }
145
146    private void ProblemData_Changed(object sender, EventArgs e) {
147      OnReset();
148    }
149
150    private void OnProblemDataChanged() {
151      UpdateGrammar();
152
153      var handler = ProblemDataChanged;
154      if (handler != null) handler(this, EventArgs.Empty);
155    }
156
157    private void UpdateGrammar() {
158      // whenever ProblemData is changed we create a new grammar with the necessary symbols
159      var g = new SimpleSymbolicExpressionGrammar();
160      g.AddSymbols(new[] { "+", "*", "%", "-" }, 2, 2); // % is protected division 1/0 := 0
161
162      foreach (var variableName in ProblemData.AllowedInputVariables)
163        g.AddTerminalSymbol(variableName);
164
165      // generate ephemeral random consts in the range [-10..+10[ (2*number of variables)
166      var rand = new System.Random();
167      for (int i = 0; i < ProblemData.AllowedInputVariables.Count() * 2; i++) {
168        string newErcSy;
169        do {
170          newErcSy = string.Format("{0:F2}", rand.NextDouble() * 20 - 10);
171        } while (g.Symbols.Any(sy => sy.Name == newErcSy)); // it might happen that we generate the same constant twice
172        g.AddTerminalSymbol(newErcSy);
173      }
174
175      Encoding.GrammarParameter.ReadOnly = false;
176      Encoding.Grammar = g;
177      Encoding.GrammarParameter.ReadOnly = true;
178    }
179    #endregion
180
181    #region Import & Export
182    public void Load(IRegressionProblemData data) {
183      Name = data.Name;
184      Description = data.Description;
185      ProblemData = data;
186    }
187
188    public IRegressionProblemData Export() {
189      return ProblemData;
190    }
191    #endregion
192  }
193}
Note: See TracBrowser for help on using the repository browser.