Free cookie consent management tool by TermsFeed Policy Generator

source: addons/HeuristicLab.Problems.BioBoost/HeuristicLab.Problems.BioBoost.Views/3.3/MenuItems/ExportSolutionMenuItem.cs @ 16101

Last change on this file since 16101 was 13074, checked in by gkronber, 9 years ago

#2499: added license header and removed unused usings

File size: 8.4 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 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 HeuristicLab.BioBoost.Representation;
23using HeuristicLab.Common;
24using HeuristicLab.Core;
25using HeuristicLab.MainForm;
26using HeuristicLab.Optimization;
27using HeuristicLab.Optimizer;
28using System;
29using System.Collections.Generic;
30using System.Globalization;
31using System.IO;
32using System.Linq;
33using System.Text;
34using System.Windows.Forms;
35using MenuItem = HeuristicLab.MainForm.WindowsForms.MenuItem;
36
37
38namespace HeuristicLab.BioBoost.Views {
39  internal sealed class ExportSolutionMenuItem : MenuItem, IOptimizerUserInterfaceItemProvider {
40    public override string Name {
41      get { return "Export CSV"; }
42    }
43
44    public override IEnumerable<string> Structure {
45      get { return new string[] { "&File" }; }
46    }
47
48    public override int Position {
49      get { return 1450; }
50    }
51
52    protected override void OnToolStripItemSet(EventArgs e) {
53      ToolStripItem.Enabled = false;
54    }
55
56    protected override void OnActiveViewChanged(object sender, EventArgs e) {
57      IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
58      if (activeView == null) {
59        ToolStripItem.Enabled = false;
60        return;
61      }
62
63      var content = activeView.Content;
64      RunCollection runCollection = content as RunCollection;
65      var optimizer = content as IOptimizer;
66      if (runCollection == null && optimizer != null) {
67        runCollection = ((IOptimizer)content).Runs;
68      }
69
70      var alg = content as IAlgorithm;
71      var solution = content as BioBoostCompoundSolution;
72
73      ToolStripItem.Enabled =
74        // at least on run with a result || or the alg is paused and results contains a bioboost solution
75        (runCollection != null && runCollection.Any(run => run.Results.Any(p => p.Value is BioBoostCompoundSolution))) ||
76        (alg != null && alg.ExecutionState == ExecutionState.Paused && alg.Results.Any(r => r.Value is BioBoostCompoundSolution)) ||
77        (solution != null)
78        ;
79    }
80
81    public override void Execute() {
82      var folderBrowserDialog = new FolderBrowserDialog();
83      folderBrowserDialog.Description = "Select the export directory.";
84      folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
85      if (folderBrowserDialog.ShowDialog() == DialogResult.OK) {
86        var folderName = folderBrowserDialog.SelectedPath;
87        IContentView activeView = (IContentView)MainFormManager.MainForm.ActiveView;
88        var mainForm = (MainForm.WindowsForms.MainForm)MainFormManager.MainForm;
89        mainForm.AddOperationProgressToContent(activeView.Content, "Export solutions.");
90
91        Action<IContentView> action = (view) => {
92          var i = 0;
93          // export the solutions of all runs
94          foreach (var run in view.Content.GetObjectGraphObjects(excludeStaticMembers: true).OfType<Run>()) {
95            var solution =
96              run.GetObjectGraphObjects(excludeStaticMembers: true).OfType<BioBoostCompoundSolution>().FirstOrDefault();
97            if (solution == null) continue;
98            ExportSolution(folderName, i++, run.Name, solution);
99          }
100          // export the solutions in the results of the paused algorithm
101          var alg = view.Content as IAlgorithm;
102          if (alg != null && alg.ExecutionState == ExecutionState.Paused) {
103            foreach (var solution in alg.Results.Select(r => r.Value).OfType<BioBoostCompoundSolution>()) {
104              ExportSolution(folderName, i++, alg.Name, solution);
105            }
106          }
107
108          // export the solution itself
109          var bioBoostSolution = view.Content as BioBoostCompoundSolution;
110          if (bioBoostSolution != null)
111            ExportSolution(folderName, i++, bioBoostSolution.Name, bioBoostSolution);
112        };
113
114        action.BeginInvoke(activeView, delegate(IAsyncResult result) {
115          try {
116            action.EndInvoke(result);
117          } catch (SystemException e) {
118            var dialog = new HeuristicLab.PluginInfrastructure.ErrorDialog(e);
119            dialog.ShowDialog();
120          }
121          mainForm.RemoveOperationProgressFromContent(activeView.Content);
122        }, null);
123      }
124    }
125
126    private void ExportSolution(string folderName, int i, string name, BioBoostCompoundSolution solution) {
127      var csv = CreateCsvSolution(solution);
128      var filename = string.Format("{0}-{1}.csv", i, name);
129      // remove invalid characters
130      foreach (var ch in Path.GetInvalidFileNameChars()) {
131        filename = filename.Replace(ch, '_');
132
133      }
134      var path = Path.Combine(folderName, filename);
135      if (path.Length >= 248) throw new PathTooLongException("The path is longer than 248 characters. Try to save your files in a different folder");
136      if (filename.Length >= 260) throw new PathTooLongException("The filename is longer than 260 characters. Please change the name of runs to something shorter.");
137      File.WriteAllText(path, csv);
138    }
139
140    private string CreateCsvSolution(BioBoostCompoundSolution content) {
141      content.EvaluateAndUpdateAllResults();
142      var sb = new StringBuilder();
143      // header
144      sb.Append("NUTS_ID").Append(",");
145      sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
146      sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}-Region\"", x.Key)))).Append(",");
147      sb.Append(string.Join(",", content.DoubleValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
148      sb.Append(string.Join(",", content.StringValues.Select(x => string.Format("\"{0}\"", x.Key))));
149      sb.Append(Environment.NewLine);
150      // rows
151      for (int i = 0; i < content.LocationNames.Length; i++) {
152        sb.Append(content.LocationNames[i]);
153        foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i].ToString("D", CultureInfo.InvariantCulture)); }
154        foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i] < 0 ? "" : content.LocationNames[kvp.Value[i]]); }
155        foreach (var kvp in content.DoubleValues) { sb.Append(",").Append(kvp.Value[i].ToString("G", CultureInfo.InvariantCulture)); }
156        foreach (var kvp in content.StringValues) { sb.Append(",").Append(kvp.Value[i]); }
157        sb.Append(Environment.NewLine);
158      }
159
160      return sb.ToString();
161    }
162
163    /*
164    private string CreateJsonSolution(BioBoostCompoundSolution content) {
165      var builder = new StringBuilder();
166      builder.Append("{ \"type\": \"FeatureCollection\", \n\"features\": [");
167      for (int i = 0; i < content.LocationNames.Length; i++) {
168        if (i > 0) builder.Append(",");
169        builder.Append("\n{ \"type\": \"Feature\", \"properties\": { \"NUTS_ID\": \"");
170        builder.Append(content.LocationNames[i]);
171        builder.Append("\"");
172        foreach (var kvp in content.IntValues) {
173          var target = content.LocationNames[i];
174          if (kvp.Value[i] >= 0) {
175            target = content.LocationNames[kvp.Value[i]];
176          }
177          builder.Append(",\n                                     \"");
178          builder.Append(kvp.Key);
179          builder.Append("\": \"");
180          builder.Append(target);
181          builder.Append("\"");
182        }
183        foreach (var kvp in content.DoubleValues) {
184          builder.Append(",\n                                     \"");
185          builder.Append(kvp.Key);
186          builder.Append("\": ");
187          builder.Append(kvp.Value[i].ToString("R", CultureInfo.InvariantCulture));
188        }
189        builder.Append("} }");
190      }
191      builder.Append("\n]\n}");
192
193      return builder.ToString();
194    }
195    */
196  }
197}
Note: See TracBrowser for help on using the repository browser.