Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/Exporters/SymbolicSolutionExcelExporter.cs @ 9973

Last change on this file since 9973 was 9973, checked in by gkronber, 11 years ago

#2102 moved "shrink data analysis solutions" and "create ensemble" to a "data analysis" sub-menu in the "Edit" menu. And added an export button to the views for data analysis solution that automatically discovers supported exporters.

File size: 19.0 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.ComponentModel;
25using System.IO;
26using System.Linq;
27using System.Windows.Forms;
28using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views;
29using HeuristicLab.MainForm;
30using HeuristicLab.MainForm.WindowsForms;
31using HeuristicLab.Optimizer;
32using OfficeOpenXml;
33using OfficeOpenXml.Drawing.Chart;
34
35namespace HeuristicLab.Problems.DataAnalysis.Symbolic.Views {
36  public class SymbolicSolutionExcelExporter : IDataAnalysisSolutionExporter {
37    private const string TRAININGSTART = "TrainingStart";
38    private const string TRAININGEND = "TrainingEnd";
39    private const string TESTSTART = "TestStart";
40    private const string TESTEND = "TestEnd";
41
42
43    public string FileTypeFilter {
44      get { return "Excel 2007 file (*.xlsx)|*.xlsx"; }
45    }
46    public bool Supports(IDataAnalysisSolution solution) {
47      return solution is ISymbolicDataAnalysisSolution &&
48        solution is IRegressionSolution;
49    }
50
51    public void Export(IDataAnalysisSolution solution, string fileName) {
52      var symbSolution = solution as ISymbolicDataAnalysisSolution;
53      if (symbSolution == null) throw new NotSupportedException("This solution cannot be exported to Excel");
54      var formatter = new SymbolicDataAnalysisExpressionExcelFormatter();
55      var formula = formatter.Format(symbSolution.Model.SymbolicExpressionTree, solution.ProblemData.Dataset);
56      ExportChart(fileName, symbSolution, formula);
57    }
58
59    private void ExportChart(string fileName, ISymbolicDataAnalysisSolution solution, string formula) {
60      FileInfo newFile = new FileInfo(fileName);
61      if (newFile.Exists) {
62        newFile.Delete();
63        newFile = new FileInfo(fileName);
64      }
65      var formulaParts = formula.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
66
67      using (ExcelPackage package = new ExcelPackage(newFile)) {
68        ExcelWorksheet modelWorksheet = package.Workbook.Worksheets.Add("Model");
69        FormatModelSheet(modelWorksheet, solution, formulaParts);
70
71        ExcelWorksheet datasetWorksheet = package.Workbook.Worksheets.Add("Dataset");
72        WriteDatasetToExcel(datasetWorksheet, solution.ProblemData);
73
74        ExcelWorksheet inputsWorksheet = package.Workbook.Worksheets.Add("Inputs");
75        WriteInputSheet(inputsWorksheet, datasetWorksheet, formulaParts.Skip(2), solution.ProblemData.Dataset);
76
77        if (solution is IRegressionSolution) {
78          ExcelWorksheet estimatedWorksheet = package.Workbook.Worksheets.Add("Estimated Values");
79          WriteEstimatedWorksheet(estimatedWorksheet, datasetWorksheet, formulaParts, solution as IRegressionSolution);
80
81          ExcelWorksheet chartsWorksheet = package.Workbook.Worksheets.Add("Charts");
82          AddCharts(chartsWorksheet);
83        }
84        package.Workbook.Properties.Title = "Excel Export";
85        package.Workbook.Properties.Author = "HEAL";
86        package.Workbook.Properties.Comments = "Excel export of a symbolic data analysis solution from HeuristicLab";
87
88        package.Save();
89      }
90    }
91
92    private void FormatModelSheet(ExcelWorksheet modelWorksheet, ISymbolicDataAnalysisSolution solution, IEnumerable<string> formulaParts) {
93      int row = 1;
94      modelWorksheet.Cells[row, 1].Value = "Model";
95      modelWorksheet.Cells[row, 2].Value = solution.Name;
96
97      foreach (var part in formulaParts) {
98        modelWorksheet.Cells[row, 4].Value = part;
99        row++;
100      }
101
102      row = 2;
103      modelWorksheet.Cells[row, 1].Value = "Model Depth";
104      modelWorksheet.Cells[row, 2].Value = solution.Model.SymbolicExpressionTree.Depth;
105      row++;
106
107      modelWorksheet.Cells[row, 1].Value = "Model Length";
108      modelWorksheet.Cells[row, 2].Value = solution.Model.SymbolicExpressionTree.Length;
109      row += 2;
110
111      modelWorksheet.Cells[row, 1].Value = "Estimation Limits Lower";
112      modelWorksheet.Cells[row, 2].Value = solution.Model.LowerEstimationLimit;
113      modelWorksheet.Names.Add("EstimationLimitLower", modelWorksheet.Cells[row, 2]);
114      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
115      row++;
116
117      modelWorksheet.Cells[row, 1].Value = "Estimation Limits Upper";
118      modelWorksheet.Cells[row, 2].Value = solution.Model.UpperEstimationLimit;
119      modelWorksheet.Names.Add("EstimationLimitUpper", modelWorksheet.Cells[row, 2]);
120      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
121      row += 2;
122
123      modelWorksheet.Cells[row, 1].Value = "Trainings Partition Start";
124      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TrainingPartition.Start;
125      modelWorksheet.Names.Add(TRAININGSTART, modelWorksheet.Cells[row, 2]);
126      row++;
127
128      modelWorksheet.Cells[row, 1].Value = "Trainings Partition End";
129      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TrainingPartition.End;
130      modelWorksheet.Names.Add(TRAININGEND, modelWorksheet.Cells[row, 2]);
131      row++;
132
133      modelWorksheet.Cells[row, 1].Value = "Test Partition Start";
134      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TestPartition.Start;
135      modelWorksheet.Names.Add(TESTSTART, modelWorksheet.Cells[row, 2]);
136      row++;
137
138      modelWorksheet.Cells[row, 1].Value = "Test Partition End";
139      modelWorksheet.Cells[row, 2].Value = solution.ProblemData.TestPartition.End;
140      modelWorksheet.Names.Add(TESTEND, modelWorksheet.Cells[row, 2]);
141      row += 2;
142
143      string excelTrainingTarget = Indirect("B", true);
144      string excelTrainingEstimated = Indirect("C", true);
145      string excelTrainingAbsoluteError = Indirect("D", true);
146      string excelTrainingRelativeError = Indirect("E", true);
147      string excelTrainingMeanError = Indirect("F", true);
148      string excelTrainingMSE = Indirect("G", true);
149
150      string excelTestTarget = Indirect("B", false);
151      string excelTestEstimated = Indirect("C", false);
152      string excelTestAbsoluteError = Indirect("D", false);
153      string excelTestRelativeError = Indirect("E", false);
154      string excelTestMeanError = Indirect("F", false);
155      string excelTestMSE = Indirect("G", false);
156
157      modelWorksheet.Cells[row, 1].Value = "Pearson's R² (training)";
158      modelWorksheet.Cells[row, 2].Formula = string.Format("POWER(PEARSON({0},{1}),2)", excelTrainingTarget, excelTrainingEstimated);
159      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
160      row++;
161
162      modelWorksheet.Cells[row, 1].Value = "Pearson's R² (test)";
163      modelWorksheet.Cells[row, 2].Formula = string.Format("POWER(PEARSON({0},{1}),2)", excelTestTarget, excelTestEstimated);
164      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
165      row++;
166
167      modelWorksheet.Cells[row, 1].Value = "Mean Squared Error (training)";
168      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingMSE);
169      modelWorksheet.Names.Add("TrainingMSE", modelWorksheet.Cells[row, 2]);
170      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
171      row++;
172
173      modelWorksheet.Cells[row, 1].Value = "Mean Squared Error (test)";
174      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestMSE);
175      modelWorksheet.Names.Add("TestMSE", modelWorksheet.Cells[row, 2]);
176      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
177      row++;
178
179      modelWorksheet.Cells[row, 1].Value = "Mean absolute error (training)";
180      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingAbsoluteError);
181      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
182      row++;
183
184      modelWorksheet.Cells[row, 1].Value = "Mean absolute error (test)";
185      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestAbsoluteError);
186      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
187      row++;
188
189      modelWorksheet.Cells[row, 1].Value = "Mean error (training)";
190      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingMeanError);
191      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
192      row++;
193
194      modelWorksheet.Cells[row, 1].Value = "Mean error (test)";
195      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestMeanError);
196      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
197      row++;
198
199      modelWorksheet.Cells[row, 1].Value = "Average relative error (training)";
200      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTrainingRelativeError);
201      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.00%";
202      row++;
203
204      modelWorksheet.Cells[row, 1].Value = "Average relative error (test)";
205      modelWorksheet.Cells[row, 2].Formula = string.Format("AVERAGE({0})", excelTestRelativeError);
206      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.00%";
207      row++;
208
209      modelWorksheet.Cells[row, 1].Value = "Normalized Mean Squared error (training)";
210      modelWorksheet.Cells[row, 2].Formula = string.Format("TrainingMSE / VAR({0})", excelTrainingTarget);
211      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
212      row++;
213
214      modelWorksheet.Cells[row, 1].Value = "Normalized Mean Squared error  (test)";
215      modelWorksheet.Cells[row, 2].Formula = string.Format("TestMSE / VAR({0})", excelTestTarget);
216      modelWorksheet.Cells[row, 2].Style.Numberformat.Format = "0.000";
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      estimatedWorksheet.Cells["B2:B" + (rows + 1)].Style.Numberformat.Format = "0.000";
303
304      estimatedWorksheet.Cells["C2:C" + (rows + 1)].Formula = "J2";
305      estimatedWorksheet.Cells["C2:C" + (rows + 1)].Style.Numberformat.Format = "0.000";
306      estimatedWorksheet.Cells["D2:D" + (rows + 1)].Formula = "ABS(B2 - C2)";
307      estimatedWorksheet.Cells["D2:D" + (rows + 1)].Style.Numberformat.Format = "0.000";
308      estimatedWorksheet.Cells["E2:E" + (rows + 1)].Formula = "ABS(D2 / B2)";
309      estimatedWorksheet.Cells["E2:E" + (rows + 1)].Style.Numberformat.Format = "0.000";
310      estimatedWorksheet.Cells["F2:F" + (rows + 1)].Formula = "C2 - B2";
311      estimatedWorksheet.Cells["F2:F" + (rows + 1)].Style.Numberformat.Format = "0.000";
312      estimatedWorksheet.Cells["G2:G" + (rows + 1)].Formula = "POWER(F2, 2)";
313      estimatedWorksheet.Cells["G2:G" + (rows + 1)].Style.Numberformat.Format = "0.000";
314
315      estimatedWorksheet.Cells["I2:I" + (rows + 1)].Style.Numberformat.Format = "0.000";
316      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))";
317      estimatedWorksheet.Cells["J2:J" + (rows + 1)].Style.Numberformat.Format = "0.000";
318    }
319
320    private string PrepareFormula(string[] formulaParts) {
321      string preparedFormula = formulaParts[0];
322      foreach (var part in formulaParts.Skip(2)) {
323        var varMap = part.Split(new string[] { " = " }, StringSplitOptions.None);
324        var columnName = "$" + varMap[1] + "1";
325        preparedFormula = preparedFormula.Replace(columnName, "Inputs!$" + varMap[1] + "{0}");   //{0} will be replaced later with the row number
326      }
327      return preparedFormula;
328    }
329
330    private void WriteInputSheet(ExcelWorksheet inputsWorksheet, ExcelWorksheet datasetWorksheet, IEnumerable<string> list, Dataset dataset) {
331      //remark the performance of EPPlus drops dramatically
332      //if the data is not written row wise (from left to right) due the internal indices used.
333      var variableNames = dataset.VariableNames.Select((v, i) => new { variable = v, index = i + 1 }).ToDictionary(v => v.variable, v => v.index);
334      var nameMapping = list.Select(x => x.Split('=')[0].Trim()).ToArray();
335
336      for (int row = 1; row <= dataset.Rows + 1; row++) {
337        for (int column = 1; column < nameMapping.Length + 1; column++) {
338          int variableIndex = variableNames[nameMapping[column - 1]];
339          inputsWorksheet.Cells[row, column].Formula = datasetWorksheet.Cells[row, variableIndex].FullAddress;
340        }
341      }
342    }
343
344    private void WriteDatasetToExcel(ExcelWorksheet datasetWorksheet, IDataAnalysisProblemData problemData) {
345      //remark the performance of EPPlus drops dramatically
346      //if the data is not written row wise (from left to right) due the internal indices used.
347      Dataset dataset = problemData.Dataset;
348      var variableNames = dataset.VariableNames.ToList();
349      var doubleVariables = new HashSet<string>(dataset.DoubleVariables);
350
351      for (int col = 1; col <= variableNames.Count; col++)
352        datasetWorksheet.Cells[1, col].Value = variableNames[col - 1];
353
354      for (int row = 0; row < dataset.Rows; row++) {
355        for (int col = 0; col < variableNames.Count; col++) {
356          if (doubleVariables.Contains(variableNames[col]))
357            datasetWorksheet.Cells[row + 2, col + 1].Value = dataset.GetDoubleValue(variableNames[col], row);
358          else
359            datasetWorksheet.Cells[row + 2, col + 1].Value = dataset.GetValue(row, col);
360        }
361      }
362    }
363  }
364}
Note: See TracBrowser for help on using the repository browser.