Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/MenuItems/ExportSymbolicSolutionToExcelMenuItem.cs @ 9600

Last change on this file since 9600 was 9600, checked in by sforsten, 11 years ago

#1730: added "ABS" again in the calculation of the relative error which was removed in r9585. If the target is negative, the absolute value prevents that the formula would result in a negative relative error.

File size: 17.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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.IO;
25using System.Linq;
26using System.Windows.Forms;
27using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
28using HeuristicLab.MainForm;
29using HeuristicLab.Optimizer;
30using OfficeOpenXml;
31using OfficeOpenXml.Drawing.Chart;
32
33namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
34  public class ExportSymbolicSolutionToExcelMenuItem : MainForm.WindowsForms.MenuItem, IOptimizerUserInterfaceItemProvider {
35    private const string TRAININGSTART = "TrainingStart";
36    private const string TRAININGEND = "TrainingEnd";
37    private const string TESTSTART = "TestStart";
38    private const string TESTEND = "TestEnd";
39
40    public override string Name {
41      get { return "Export Symbolic Solution To Excel"; }
42    }
43    public override IEnumerable<string> Structure {
44      get { return new string[] { "&Edit" }; }
45    }
46    public override int Position {
47      get { return 2500; }
48    }
49    public override string ToolTipText {
50      get { return "Create excel file of symbolic data analysis solutions."; }
51    }
52
53    protected override void OnToolStripItemSet(EventArgs e) {
54      ToolStripItem.Enabled = false;
55    }
56    protected override void OnActiveViewChanged(object sender, EventArgs e) {
57      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
58      ToolStripItem.Enabled = activeView != null && activeView.Content is ISymbolicDataAnalysisSolution;
59    }
60
61    public override void Execute() {
62      var activeView = (IContentView)MainFormManager.MainForm.ActiveView;
63      var solution = (ISymbolicDataAnalysisSolution)activeView.Content;
64      var formatter = new SymbolicDataAnalysisExpressionExcelFormatter();
65      var formula = formatter.Format(solution.Model.SymbolicExpressionTree);
66      var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
67
68      SaveFileDialog saveFileDialog = new SaveFileDialog();
69      saveFileDialog.Filter = "Excel Workbook|*.xlsx";
70      saveFileDialog.Title = "Save an Excel File";
71      if (saveFileDialog.ShowDialog() == DialogResult.OK) {
72        string fileName = saveFileDialog.FileName;
73        FileInfo newFile = new FileInfo(fileName);
74        if (newFile.Exists) {
75          newFile.Delete();
76          newFile = new FileInfo(fileName);
77        }
78        using (ExcelPackage package = new ExcelPackage(newFile)) {
79          ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model");
80          FormatModelSheet(modelWorksheet, solution, formulaParts);
81
82          ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset");
83          WriteDatasetToExcel(datasetWorksheet, solution.ProblemData);
84
85          ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs");
86          WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset);
87
88          if (solution is IRegressionSolution) {
89            ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values");
90            WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution);
91
92            ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts");
93            AddCharts(chartsWorksheet);
94          }
95          package.Workbook.Properties.Title = "Excel Export";
96          package.Workbook.Properties.Author = "HEAL";
97          package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab";
98
99          package.Save();
100        }
101      }
102    }
103
104    private void FormatModelSheet(ExcelWorksheet modelWorksheet, ISymbolicDataAnalysisSolution solution, IEnumerable<string> formulaParts) {
105      int row = 1;
106      modelWorksheet.Cells[row, 1].Value = "Model";
107      modelWorksheet.Cells[row, 2].Value = solution.Name;
108
109      foreach (var part in formulaParts) {
110        modelWorksheet.Cells[row, 4].Value = part;
111        row++;
112      }
113
114      row = 2;
115      modelWorksheet.Cells[row, 1].Value = "Model Depth";
116      modelWorksheet.Cells[row, 2].Value = solution.Model.SymbolicExpressionTree.Depth;
117      row++;
118
119      modelWorksheet.Cells[row, 1].Value = "Model Length";
120      modelWorksheet.Cells[row, 2].Value = solution.Model.SymbolicExpressionTree.Length;
121      row += 2;
122
123      modelWorksheet.Cells[row, 1].Value = "Estimation Limits Lower";
124      modelWorksheet.Cells[row, 2].Value = solution.Model.LowerEstimationLimit;
125      modelWorksheet.Names.Add("EstimationLimitLower", modelWorksheet.Cells[row, 2]);
126      row++;
127
128      modelWorksheet.Cells[row, 1].Value = "Estimation Limits Upper";
129      modelWorksheet.Cells[row, 2].Value = solution.Model.UpperEstimationLimit;
130      modelWorksheet.Names.Add("EstimationLimitUpper", modelWorksheet.Cells[row, 2]);
131      row += 2;
132
133      modelWorksheet.Cells[row, 1].Value = "Trainings Partition Start";
134      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TrainingPartition.Start;
135      modelWorksheet.Names.Add(TRAININGSTART, modelWorksheet.Cells[row, 2]);
136      row++;
137
138      modelWorksheet.Cells[row, 1].Value = "Trainings Partition End";
139      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TrainingPartition.End;
140      modelWorksheet.Names.Add(TRAININGEND, modelWorksheet.Cells[row, 2]);
141      row++;
142
143      modelWorksheet.Cells[row, 1].Value = "Test Partition Start";
144      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TestPartition.Start;
145      modelWorksheet.Names.Add(TESTSTART, modelWorksheet.Cells[row, 2]);
146      row++;
147
148      modelWorksheet.Cells[row, 1].Value = "Test Partition End";
149      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TestPartition.End;
150      modelWorksheet.Names.Add(TESTEND, modelWorksheet.Cells[row, 2]);
151      row += 2;
152
153      string excelTrainingTarget = Indirect("B", true);
154      string excelTrainingEstimated = Indirect("C", true);
155      string excelTrainingAbsoluteError = Indirect("D", true);
156      string excelTrainingRelativeError = Indirect("E", true);
157      string excelTrainingMeanError = Indirect("F", true);
158      string excelTrainingMSE = Indirect("G", true);
159
160      string excelTestTarget = Indirect("B", false);
161      string excelTestEstimated = Indirect("C", false);
162      string excelTestAbsoluteError = Indirect("D", false);
163      string excelTestRelativeError = Indirect("E", false);
164      string excelTestMeanError = Indirect("F", false);
165      string excelTestMSE = Indirect("G", false);
166
167      modelWorksheet.Cells[row, 1].Value = "Pearson's R² (training)";
168      modelWorksheet.Cells[row, 2].Formula = string.Format("POWER(PEARSON({0},{1}),2)", excelTrainingTarget, excelTrainingEstimated);
169      row++;
170
171      modelWorksheet.Cells[row, 1].Value = "Pearson's R² (test)";
172      modelWorksheet.Cells[row, 2].Formula = string.Format("POWER(PEARSON({0},{1}),2)", excelTestTarget, excelTestEstimated);
173      row++;
174
175      modelWorksheet.Cells[row, 1].Value = "Mean Squared Error (training)";
176      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingMSE);
177      modelWorksheet.Names.Add("TrainingMSE", modelWorksheet.Cells[row, 2]);
178      row++;
179
180      modelWorksheet.Cells[row, 1].Value = "Mean Squared Error (test)";
181      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestMSE);
182      modelWorksheet.Names.Add("TestMSE", modelWorksheet.Cells[row, 2]);
183      row++;
184
185      modelWorksheet.Cells[row, 1].Value = "Mean absolute error (training)";
186      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingAbsoluteError);
187      row++;
188
189      modelWorksheet.Cells[row, 1].Value = "Mean absolute error (test)";
190      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestAbsoluteError);
191      row++;
192
193      modelWorksheet.Cells[row, 1].Value = "Mean error (training)";
194      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingMeanError);
195      row++;
196
197      modelWorksheet.Cells[row, 1].Value = "Mean error (test)";
198      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestMeanError);
199      row++;
200
201      modelWorksheet.Cells[row, 1].Value = "Average relative error (training)";
202      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingRelativeError);
203      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.00%";
204      row++;
205
206      modelWorksheet.Cells[row, 1].Value = "Average relative error (test)";
207      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestRelativeError);
208      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.00%";
209      row++;
210
211      modelWorksheet.Cells[row, 1].Value = "Normalized Mean Squared error (training)";
212      modelWorksheet.Cells[row, 2].Formula = string.Format("TrainingMSE / VAR({0})", excelTrainingTarget);
213      row++;
214
215      modelWorksheet.Cells[row, 1].Value = "Normalized Mean Squared error  (test)";
216      modelWorksheet.Cells[row, 2].Formula = string.Format("TestMSE / VAR({0})", excelTestTarget);
217
218      modelWorksheet.Cells["A1:B" + row].AutoFitColumns();
219
220      AddModelTreePicture(modelWorksheet, solution.Model);
221    }
222
223    private string Indirect(string column, bool training) {
224      if (training) {
225        return string.Format("INDIRECT(\"'Estimated Values'!{0}\"&{1}+2&\":{0}\"&{2}+1)", column, TRAININGSTART, TRAININGEND);
226      } else {
227        return string.Format("INDIRECT(\"'Estimated Values'!{0}\"&{1}+2&\":{0}\"&{2}+1)", column, TESTSTART, TESTEND);
228      }
229    }
230
231    private void AddCharts(ExcelWorksheet chartsWorksheet) {
232      chartsWorksheet.Names.AddFormula("AllId", "OFFSET('Estimated Values'!$A$1,1,0, COUNTA('Estimated Values'!$A:$A)-1)");
233      chartsWorksheet.Names.AddFormula("AllTarget", "OFFSET('Estimated Values'!$B$1,1,0, COUNTA('Estimated Values'!$B:$B)-1)");
234      chartsWorksheet.Names.AddFormula("AllEstimated", "OFFSET('Estimated Values'!$C$1,1,0, COUNTA('Estimated Values'!$C:$C)-1)");
235      chartsWorksheet.Names.AddFormula("TrainingId", "OFFSET('Estimated Values'!$A$1,Model!TrainingStart + 1,0, Model!TrainingEnd - Model!TrainingStart)");
236      chartsWorksheet.Names.AddFormula("TrainingTarget", "OFFSET('Estimated Values'!$B$1,Model!TrainingStart + 1,0, Model!TrainingEnd - Model!TrainingStart)");
237      chartsWorksheet.Names.AddFormula("TrainingEstimated", "OFFSET('Estimated Values'!$C$1,Model!TrainingStart + 1,0, Model!TrainingEnd - Model!TrainingStart)");
238      chartsWorksheet.Names.AddFormula("TestId", "OFFSET('Estimated Values'!$A$1,Model!TestStart + 1,0, Model!TestEnd - Model!TestStart)");
239      chartsWorksheet.Names.AddFormula("TestTarget", "OFFSET('Estimated Values'!$B$1,Model!TestStart + 1,0, Model!TestEnd - Model!TestStart)");
240      chartsWorksheet.Names.AddFormula("TestEstimated", "OFFSET('Estimated Values'!$C$1,Model!TestStart + 1,0, Model!TestEnd - Model!TestStart)");
241
242      var scatterPlot = chartsWorksheet.Drawings.AddChart("scatterPlot", eChartType.XYScatter);
243      scatterPlot.SetSize(800, 400);
244      scatterPlot.SetPosition(0, 0);
245      scatterPlot.Title.Text = "Scatter Plot";
246      var seriesAll = scatterPlot.Series.Add("AllTarget", "AllEstimated");
247      seriesAll.Header = "All";
248      var seriesTraining = scatterPlot.Series.Add("TrainingTarget", "TrainingEstimated");
249      seriesTraining.Header = "Training";
250      var seriesTest = scatterPlot.Series.Add("TestTarget", "TestEstimated");
251      seriesTest.Header = "Test";
252
253      var lineChart = chartsWorksheet.Drawings.AddChart("lineChart", eChartType.XYScatterLinesNoMarkers);
254      lineChart.SetSize(800, 400);
255      lineChart.SetPosition(400, 0);
256      lineChart.Title.Text = "LineChart";
257      var lineTarget = lineChart.Series.Add("AllTarget", "AllId");
258      lineTarget.Header = "Target";
259      var lineAll = lineChart.Series.Add("AllEstimated", "AllId");
260      lineAll.Header = "All";
261      var lineTraining = lineChart.Series.Add("TrainingEstimated", "TrainingId");
262      lineTraining.Header = "Training";
263      var lineTest = lineChart.Series.Add("TestEstimated", "TestId");
264      lineTest.Header = "Test";
265    }
266
267    private void AddModelTreePicture(ExcelWorksheet modelWorksheet, ISymbolicDataAnalysisModel model) {
268      SymbolicExpressionTreeChart modelTreePicture = new SymbolicExpressionTreeChart();
269      modelTreePicture.Tree = model.SymbolicExpressionTree;
270      string tmpFilename = Path.GetTempFileName();
271      modelTreePicture.Width = 1000;
272      modelTreePicture.Height = 500;
273      modelTreePicture.SaveImageAsEmf(tmpFilename);
274
275      FileInfo fi = new FileInfo(tmpFilename);
276      var excelModelTreePic = modelWorksheet.Drawings.AddPicture("ModelTree", fi);
277      excelModelTreePic.SetSize(50);
278      excelModelTreePic.SetPosition(2, 0, 6, 0);
279    }
280
281    private void WriteEstimatedWorksheet(ExcelWorksheet estimatedWorksheet, ExcelWorksheet datasetWorksheet, string[] formulaParts, IRegressionSolution solution) {
282      string preparedFormula = PrepareFormula(formulaParts);
283      int rows = solution.ProblemData.Dataset.Rows;
284      estimatedWorksheet.Cells[1, 1].Value = "Id";
285      estimatedWorksheet.Cells[1, 2].Value = "Target Variable";
286      estimatedWorksheet.Cells[1, 3].Value = "Estimated Values";
287      estimatedWorksheet.Cells[1, 4].Value = "Absolute Error";
288      estimatedWorksheet.Cells[1, 5].Value = "Relative Error";
289      estimatedWorksheet.Cells[1, 6].Value = "Error";
290      estimatedWorksheet.Cells[1, 7].Value = "Squared Error";
291      estimatedWorksheet.Cells[1, 9].Value = "Unbounded Estimated Values";
292      estimatedWorksheet.Cells[1, 10].Value = "Bounded Estimated Values";
293
294      estimatedWorksheet.Cells[1, 1, 1, 10].AutoFitColumns();
295
296      int targetIndex = solution.ProblemData.Dataset.VariableNames.ToList().FindIndex(x => x.Equals(solution.ProblemData.TargetVariable)) + 1;
297      for (int i = 0; i < rows; i++) {
298        estimatedWorksheet.Cells[i + 2, 1].Value = i;
299        estimatedWorksheet.Cells[i + 2, 2].Formula = datasetWorksheet.Cells[i + 2, targetIndex].FullAddress;
300        estimatedWorksheet.Cells[i + 2, 9].Formula = string.Format(preparedFormula, i + 2);
301      }
302
303      estimatedWorksheet.Cells["C2:C" + (rows + 1)].Formula = "J2";
304
305      estimatedWorksheet.Cells["D2:D" + (rows + 1)].Formula = "ABS(B2 - C2)";
306      estimatedWorksheet.Cells["E2:E" + (rows + 1)].Formula = "ABS(D2 / B2)";
307      estimatedWorksheet.Cells["F2:F" + (rows + 1)].Formula = "C2 - B2";
308      estimatedWorksheet.Cells["G2:G" + (rows + 1)].Formula = "POWER(F2, 2)";
309
310      estimatedWorksheet.Cells["J2:J" + (rows + 1)].Formula = "IFERROR(IF(I2 > Model!EstimationLimitUpper, Model!EstimationLimitUpper, IF(I2 < Model!EstimationLimitLower, Model!EstimationLimitLower, I2)), AVERAGE(Model!EstimationLimitLower, Model!EstimationLimitUpper))";
311    }
312
313    private string PrepareFormula(string[] formulaParts) {
314      string preparedFormula = formulaParts[0];
315      foreach (var part in formulaParts.Skip(2)) {
316        var varMap = part.Split(new string[] { " = " }, StringSplitOptions.None);
317        var columnName = "$" + varMap[1] + "1";
318        preparedFormula = preparedFormula.Replace(columnName, "Inputs!$" + varMap[1] + "{0}");   //{0} will be replaced later with the row number
319      }
320      return preparedFormula;
321    }
322
323    private void WriteInputSheet(ExcelWorksheet inputsWorksheet, ExcelWorksheet datasetWorksheet, IEnumerable<string> list, Dataset dataset) {
324      int rows = dataset.Rows;
325      var variableNames = dataset.VariableNames.ToList();
326      int cur = 1;
327      foreach (var variableMapping in list) {
328        var varMap = variableMapping.Split(new string[] { " = " }, StringSplitOptions.None);
329        if (varMap.Count() != 2) throw new ArgumentException("variableMapping is not correct");
330        int column = variableNames.FindIndex(x => x.Equals(varMap[0])) + 1;
331        inputsWorksheet.Cells[1, cur].Value = varMap[0];
332        for (int i = 2; i <= rows + 1; i++) {
333          inputsWorksheet.Cells[i, cur].Formula = datasetWorksheet.Cells[i, column].FullAddress;
334        }
335        cur++;
336      }
337    }
338
339    private void WriteDatasetToExcel(ExcelWorksheet datasetWorksheet, IDataAnalysisProblemData problemData) {
340      Dataset dataset = problemData.Dataset;
341      var variableNames = dataset.VariableNames.ToList();
342      for (int col = 1; col <= variableNames.Count; col++) {
343        datasetWorksheet.Cells[1, col].Value = variableNames[col - 1];
344        if (dataset.DoubleVariables.Contains(variableNames[col - 1])) {
345          datasetWorksheet.Cells[2, col].LoadFromCollection(dataset.GetDoubleValues(variableNames[col - 1]));
346        } else {
347          var coll = Enumerable.Range(0, dataset.Rows).Select(x => dataset.GetValue(x, col - 1));
348          datasetWorksheet.Cells[2, col].LoadFromCollection(coll);
349        }
350      }
351    }
352  }
353}
Note: See TracBrowser for help on using the repository browser.