Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GeneticProgramming.BloodGlucosePrediction/Problem.cs @ 14061

Last change on this file since 14061 was 13865, checked in by gkronber, 8 years ago

#2608 first import of project

File size: 6.5 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.Optimization;
29using HeuristicLab.Parameters;
30using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
31using HeuristicLab.Problems.DataAnalysis;
32using HeuristicLab.Problems.Instances;
33
34
35namespace HeuristicLab.Problems.GeneticProgramming.GlucosePrediction {
36  [Item("Blood Glucose Forecast", "See MedGEC Workshop at GECCO 2016")]
37  [Creatable(CreatableAttribute.Categories.GeneticProgrammingProblems, Priority = 999)]
38  [StorableClass]
39  public sealed class Problem : SymbolicExpressionTreeProblem, IRegressionProblem, IProblemInstanceConsumer<IRegressionProblemData>, IProblemInstanceExporter<IRegressionProblemData> {
40
41    #region parameter names
42    private const string ProblemDataParameterName = "ProblemData";
43    #endregion
44
45    #region Parameter Properties
46    IParameter IDataAnalysisProblem.ProblemDataParameter { get { return ProblemDataParameter; } }
47
48    public IValueParameter<IRegressionProblemData> ProblemDataParameter {
49      get { return (IValueParameter<IRegressionProblemData>)Parameters[ProblemDataParameterName]; }
50    }
51    #endregion
52
53    #region Properties
54    public IRegressionProblemData ProblemData {
55      get { return ProblemDataParameter.Value; }
56      set { ProblemDataParameter.Value = value; }
57    }
58    IDataAnalysisProblemData IDataAnalysisProblem.ProblemData { get { return ProblemData; } }
59    #endregion
60
61    public event EventHandler ProblemDataChanged;
62
63    public override bool Maximization {
64      get { return false; }
65    }
66
67    #region item cloning and persistence
68    // persistence
69    [StorableConstructor]
70    private Problem(bool deserializing) : base(deserializing) { }
71    [StorableHook(HookType.AfterDeserialization)]
72    private void AfterDeserialization() {
73      RegisterEventHandlers();
74    }
75
76    // cloning
77    private Problem(Problem original, Cloner cloner)
78      : base(original, cloner) {
79      RegisterEventHandlers();
80    }
81    public override IDeepCloneable Clone(Cloner cloner) { return new Problem(this, cloner); }
82    #endregion
83
84    public Problem()
85      : base() {
86      Parameters.Add(new ValueParameter<IRegressionProblemData>(ProblemDataParameterName, "The data for the glucose prediction problem", new RegressionProblemData()));
87
88      var g = new SimpleSymbolicExpressionGrammar(); // empty grammar is replaced in UpdateGrammar()
89      base.Encoding = new SymbolicExpressionTreeEncoding(g, 100, 17);
90
91      UpdateGrammar();
92      RegisterEventHandlers();
93    }
94
95
96    public override double Evaluate(ISymbolicExpressionTree tree, IRandom random) {
97      var problemData = ProblemData;
98      var rows = problemData.TrainingIndices.ToArray();
99      var target = problemData.Dataset.GetDoubleValues(problemData.TargetVariable, rows);
100      var predicted = Interpreter.Apply(tree.Root.GetSubtree(0).GetSubtree(0), problemData.Dataset, rows); 
101
102      // only take predictions for which the target is not NaN
103      var selectedTuples = target.Zip(predicted, Tuple.Create).Where(t => !double.IsNaN(t.Item1)).ToArray();
104      target = selectedTuples.Select(t => t.Item1);
105      predicted = selectedTuples.Select(t => t.Item2);
106
107      OnlineCalculatorError errorState;
108      var mse = OnlineMeanSquaredErrorCalculator.Calculate(target, predicted, out errorState);
109      if (errorState != OnlineCalculatorError.None) mse = 1E6;
110      return mse;
111    }
112
113    public override void Analyze(ISymbolicExpressionTree[] trees, double[] qualities, ResultCollection results, IRandom random) {
114      base.Analyze(trees, qualities, results, random);
115
116      if (!results.ContainsKey("Solution")) {
117        results.Add(new Result("Solution", typeof(IRegressionSolution)));
118      }
119
120      var bestTree = trees.First();
121      var bestQuality = qualities.First();
122      for (int i = 1; i < trees.Length; i++) {
123        if (qualities[i] < bestQuality) {
124          bestQuality = qualities[i];
125          bestTree = trees[i];
126        }
127      }
128
129      var clonedProblemData = (IRegressionProblemData)ProblemData.Clone();
130      var model = new Model(clonedProblemData, (ISymbolicExpressionTree)bestTree.Clone());
131      results["Solution"].Value = model.CreateRegressionSolution(clonedProblemData);
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 Grammar();
160      Encoding.Grammar = g;
161    }
162    #endregion
163
164    #region Import & Export
165    public void Load(IRegressionProblemData data) {
166      Name = data.Name;
167      Description = data.Description;
168      ProblemData = data;
169    }
170
171    public IRegressionProblemData Export() {
172      return ProblemData;
173    }
174    #endregion
175  }
176}
Note: See TracBrowser for help on using the repository browser.