Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.Problems.GeneticProgramming/3.3/BasicSymbolicRegression/Problem.cs @ 14626

Last change on this file since 14626 was 13269, checked in by mkommend, 9 years ago

#2472: Moved cloning and persistence code near the default ctor for all new GP problems.

File size: 7.9 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.Common;
26using HeuristicLab.Core;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using HeuristicLab.Parameters;
29using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
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  [StorableClass]
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    public override bool Maximization {
63      get { return true; }
64    }
65
66    #region item cloning and persistence
67    // persistence
68    [StorableConstructor]
69    private Problem(bool deserializing) : base(deserializing) { }
70    [StorableHook(HookType.AfterDeserialization)]
71    private void AfterDeserialization() {
72      RegisterEventHandlers();
73    }
74
75    // cloning
76    private Problem(Problem original, Cloner cloner)
77      : base(original, cloner) {
78      RegisterEventHandlers();
79    }
80    public override IDeepCloneable Clone(Cloner cloner) { return new Problem(this, cloner); }
81    #endregion
82
83    public Problem()
84      : base() {
85      Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, "The data for the regression problem", new RegressionProblemData()));
86
87      var g = new SimpleSymbolicExpressionGrammar(); // empty grammar is replaced in UpdateGrammar()
88      base.Encoding = new SymbolicExpressionTreeEncoding(g, 100, 17);
89
90      UpdateGrammar();
91      RegisterEventHandlers();
92    }
93
94
95    public override double Evaluate(ISymbolicExpressionTree tree, IRandom random) {
96      // Doesn't use classes from HeuristicLab.Problems.DataAnalysis.Symbolic to make sure that the implementation can be fully understood easily.
97      // HeuristicLab.Problems.DataAnalysis.Symbolic would already provide all the necessary functionality (esp. interpreter) but at a much higher complexity.
98      // Another argument is that we don't need a reference to HeuristicLab.Problems.DataAnalysis.Symbolic
99
100      var problemData = ProblemData;
101      var rows = ProblemData.TrainingIndices.ToArray();
102      var target = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
103      var predicted = Interpret(tree, problemData.Dataset, rows);
104
105      OnlineCalculatorError errorState;
106      var r = OnlinePearsonsRCalculator.Calculate(target, predicted, out errorState);
107      if (errorState != OnlineCalculatorError.None) r = 0;
108      return r * r;
109    }
110
111    private IEnumerable<double> Interpret(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
112      // skip programRoot and startSymbol
113      return InterpretRec(tree.Root.GetSubtree(0).GetSubtree(0), dataset, rows);
114    }
115
116    private IEnumerable<double> InterpretRec(ISymbolicExpressionTreeNode node, IDataset dataset, IEnumerable<int> rows) {
117      Func<ISymbolicExpressionTreeNode, ISymbolicExpressionTreeNode, Func<double, double, double>, IEnumerable<double>> binaryEval =
118        (left, right, f) => InterpretRec(left, dataset, rows).Zip(InterpretRec(right, dataset, rows), f);
119
120      switch (node.Symbol.Name) {
121        case "+": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x + y);
122        case "*": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x * y);
123        case "-": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => x - y);
124        case "%": return binaryEval(node.GetSubtree(0), node.GetSubtree(1), (x, y) => y.IsAlmost(0.0) ? 0.0 : x / y); // protected division
125        default: {
126            double erc;
127            if (double.TryParse(node.Symbol.Name, out erc)) {
128              return rows.Select(_ => erc);
129            } else {
130              // assume that this is a variable name
131              return dataset.GetDoubleValues(node.Symbol.Name, rows);
132            }
133          }
134      }
135    }
136
137
138    #region events
139    private void RegisterEventHandlers() {
140      ProblemDataParameter.ValueChanged += new EventHandler(ProblemDataParameter_ValueChanged);
141      if (ProblemDataParameter.Value != null) ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
142    }
143
144    private void ProblemDataParameter_ValueChanged(object sender, EventArgs e) {
145      ProblemDataParameter.Value.Changed += new EventHandler(ProblemData_Changed);
146      OnProblemDataChanged();
147      OnReset();
148    }
149
150    private void ProblemData_Changed(object sender, EventArgs e) {
151      OnReset();
152    }
153
154    private void OnProblemDataChanged() {
155      UpdateGrammar();
156
157      var handler = ProblemDataChanged;
158      if (handler != null) handler(this, EventArgs.Empty);
159    }
160
161    private void UpdateGrammar() {
162      // whenever ProblemData is changed we create a new grammar with the necessary symbols
163      var g = new SimpleSymbolicExpressionGrammar();
164      g.AddSymbols(new[] { "+", "*", "%", "-" }, 2, 2); // % is protected division 1/0 := 0
165
166      foreach (var variableName in ProblemData.AllowedInputVariables)
167        g.AddTerminalSymbol(variableName);
168
169      // generate ephemeral random consts in the range [-10..+10[ (2*number of variables)
170      var rand = new System.Random();
171      for (int i = 0; i < ProblemData.AllowedInputVariables.Count() * 2; i++) {
172        string newErcSy;
173        do {
174          newErcSy = string.Format("{0:F2}", rand.NextDouble() * 20 - 10);
175        } while (g.Symbols.Any(sy => sy.Name == newErcSy)); // it might happen that we generate the same constant twice
176        g.AddTerminalSymbol(newErcSy);
177      }
178
179      Encoding.Grammar = g;
180    }
181    #endregion
182
183    #region Import & Export
184    public void Load(IRegressionProblemData data) {
185      Name = data.Name;
186      Description = data.Description;
187      ProblemData = data;
188    }
189
190    public IRegressionProblemData Export() {
191      return ProblemData;
192    }
193    #endregion
194  }
195}
Note: See TracBrowser for help on using the repository browser.