Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis/3.3/DataAnalysisSolution.cs @ 3921

Last change on this file since 3921 was 3921, checked in by mkommend, 14 years ago

fixed major bug in cloning of DataAnalysisSolutions (ticket #938)

File size: 8.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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 HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.Data;
26using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
28using System.Collections.Generic;
29using System.Linq;
30using HeuristicLab.Problems.DataAnalysis.Evaluators;
31
32namespace HeuristicLab.Problems.DataAnalysis {
33  /// <summary>
34  /// Represents a solution for a data analysis problem which can be visualized in the GUI.
35  /// </summary>
36  [Item("DataAnalysisSolution", "Represents a solution for a data analysis problem which can be visualized in the GUI.")]
37  [StorableClass]
38  public abstract class DataAnalysisSolution : NamedItem, IStringConvertibleMatrix {
39    protected DataAnalysisSolution()
40      : base() { }
41    protected DataAnalysisSolution(DataAnalysisProblemData problemData) : this(problemData, double.NegativeInfinity, double.PositiveInfinity) { }
42    protected DataAnalysisSolution(DataAnalysisProblemData problemData, double lowerEstimationLimit, double upperEstimationLimit)
43      : this() {
44      this.problemData = problemData;
45      this.lowerEstimationLimit = lowerEstimationLimit;
46      this.upperEstimationLimit = upperEstimationLimit;
47      Initialize();
48    }
49
50    [StorableConstructor]
51    private DataAnalysisSolution(bool deserializing) : base(deserializing) { }
52    [StorableHook(HookType.AfterDeserialization)]
53    private void Initialize() {
54      if (problemData != null)
55        RegisterProblemDataEvents();
56    }
57
58    [Storable]
59    private DataAnalysisProblemData problemData;
60    public DataAnalysisProblemData ProblemData {
61      get { return problemData; }
62      set {
63        if (problemData != value) {
64          if (value == null) throw new ArgumentNullException();
65          if (model != null && problemData != null && !problemData.InputVariables.Select(c => c.Value).SequenceEqual(
66            value.InputVariables.Select(c => c.Value)))
67            throw new ArgumentException("Could not set new problem data with different structure");
68
69          if (problemData != null) DeregisterProblemDataEvents();
70          problemData = value;
71          RegisterProblemDataEvents();
72          OnProblemDataChanged();
73          RecalculateEstimatedValues();
74        }
75      }
76    }
77
78    [Storable]
79    private IDataAnalysisModel model;
80    public IDataAnalysisModel Model {
81      get { return model; }
82      set {
83        if (model != value) {
84          if (value == null) throw new ArgumentNullException();
85          model = value;
86          OnModelChanged();
87          RecalculateEstimatedValues();
88        }
89      }
90    }
91
92    [Storable]
93    private double lowerEstimationLimit;
94    public double LowerEstimationLimit {
95      get { return lowerEstimationLimit; }
96      set {
97        if (lowerEstimationLimit != value) {
98          lowerEstimationLimit = value;
99          RecalculateEstimatedValues();
100        }
101      }
102    }
103
104    [Storable]
105    private double upperEstimationLimit;
106    public double UpperEstimationLimit {
107      get { return upperEstimationLimit; }
108      set {
109        if (upperEstimationLimit != value) {
110          upperEstimationLimit = value;
111          RecalculateEstimatedValues();
112        }
113      }
114    }
115
116    public abstract IEnumerable<double> EstimatedValues { get; }
117    public abstract IEnumerable<double> EstimatedTrainingValues { get; }
118    public abstract IEnumerable<double> EstimatedTestValues { get; }
119    protected abstract void RecalculateEstimatedValues();
120
121    #region Events
122    protected virtual void RegisterProblemDataEvents() {
123      ProblemData.ProblemDataChanged += new EventHandler(ProblemData_Changed);
124    }
125    protected virtual void DeregisterProblemDataEvents() {
126      ProblemData.ProblemDataChanged += new EventHandler(ProblemData_Changed);
127    }
128    private void ProblemData_Changed(object sender, EventArgs e) {
129      OnProblemDataChanged();
130    }
131
132    public event EventHandler ProblemDataChanged;
133    protected virtual void OnProblemDataChanged() {
134      var listeners = ProblemDataChanged;
135      if (listeners != null)
136        listeners(this, EventArgs.Empty);
137    }
138
139    public event EventHandler ModelChanged;
140    protected virtual void OnModelChanged() {
141      EventHandler handler = ModelChanged;
142      if (handler != null)
143        handler(this, EventArgs.Empty);
144    }
145
146    public event EventHandler EstimatedValuesChanged;
147    protected virtual void OnEstimatedValuesChanged() {
148      var listeners = EstimatedValuesChanged;
149      if (listeners != null)
150        listeners(this, EventArgs.Empty);
151    }
152    #endregion
153
154    public override IDeepCloneable Clone(Cloner cloner) {
155      DataAnalysisSolution clone = (DataAnalysisSolution)base.Clone(cloner);
156      // don't clone the problem data!
157      clone.problemData = problemData;
158      clone.model = (IDataAnalysisModel)cloner.Clone(model);
159      clone.lowerEstimationLimit = lowerEstimationLimit;
160      clone.upperEstimationLimit = upperEstimationLimit;
161      clone.Initialize();
162
163      return clone;
164    }
165
166    #region IStringConvertibleMatrix implementation
167    private List<string> rowNames = new List<string>() { "MeanSquaredError", "CoefficientOfDetermination", "MeanAbsolutePercentageError" };
168    private List<string> columnNames = new List<string>() { "Training", "Test" };
169    private double[,] resultValues = new double[3, 2];
170    int IStringConvertibleMatrix.Rows { get { return rowNames.Count; } set { } }
171    int IStringConvertibleMatrix.Columns { get { return columnNames.Count; } set { } }
172    IEnumerable<string> IStringConvertibleMatrix.ColumnNames { get { return columnNames; } set { } }
173    IEnumerable<string> IStringConvertibleMatrix.RowNames { get { return rowNames; } set { } }
174    bool IStringConvertibleMatrix.SortableView { get { return false; } set { } }
175    bool IStringConvertibleMatrix.ReadOnly { get { return true; } }
176
177    string IStringConvertibleMatrix.GetValue(int rowIndex, int columnIndex) {
178      return resultValues[rowIndex, columnIndex].ToString();
179    }
180    bool IStringConvertibleMatrix.Validate(string value, out string errorMessage) {
181      errorMessage = "This matrix is readonly.";
182      return false;
183    }
184    bool IStringConvertibleMatrix.SetValue(string value, int rowIndex, int columnIndex) { return false; }
185
186    protected void RecalculateResultValues() {
187      IEnumerable<double> originalTrainingValues = problemData.Dataset.GetVariableValues(problemData.TargetVariable.Value, problemData.TrainingSamplesStart.Value, problemData.TrainingSamplesEnd.Value);
188      IEnumerable<double> originalTestValues = problemData.Dataset.GetVariableValues(problemData.TargetVariable.Value, problemData.TestSamplesStart.Value, problemData.TestSamplesEnd.Value);
189      resultValues[0, 0] = SimpleMSEEvaluator.Calculate(originalTrainingValues, EstimatedTrainingValues);
190      resultValues[0, 1] = SimpleMSEEvaluator.Calculate(originalTestValues, EstimatedTestValues);
191      resultValues[1, 0] = SimpleRSquaredEvaluator.Calculate(originalTrainingValues, EstimatedTrainingValues);
192      resultValues[1, 1] = SimpleRSquaredEvaluator.Calculate(originalTestValues, EstimatedTestValues);
193      resultValues[2, 0] = SimpleMeanAbsolutePercentageErrorEvaluator.Calculate(originalTrainingValues, EstimatedTrainingValues);
194      resultValues[2, 1] = SimpleMeanAbsolutePercentageErrorEvaluator.Calculate(originalTestValues, EstimatedTestValues);
195
196      this.OnReset();
197    }
198
199    public event EventHandler ColumnNamesChanged;
200    public event EventHandler RowNamesChanged;
201    public event EventHandler SortableViewChanged;
202    public event EventHandler<EventArgs<int, int>> ItemChanged;
203    public event EventHandler Reset;
204    protected virtual void OnReset() {
205      EventHandler handler = Reset;
206      if (handler != null)
207        handler(this, EventArgs.Empty);
208    }
209    #endregion
210  }
211}
Note: See TracBrowser for help on using the repository browser.