Free cookie consent management tool by TermsFeed Policy Generator

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

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

#1730:

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