Free cookie consent management tool by TermsFeed Policy Generator

source: branches/ExportSymbolicDataAnalysisSolutions/HeuristicLab.Problems.DataAnalysis.Symbolic.Views/3.4/MenuItems/ExportSymbolicSolutionToExcelMenuItem.cs @ 9585

Last change on this file since 9585 was 9585, checked in by mkommend, 11 years ago

#1730: Added necessary plugin dependency and improved error handling.

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