Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 16447 was 16447, checked in by jkarder, 5 years ago

#2845: adapted BioBoost addon

File size: 8.3 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        Progress.Show(activeView.Content, "Export solutions.", ProgressMode.Indeterminate);
89
90        Action<IContentView> action = (view) => {
91          var i = 0;
92          // export the solutions of all runs
93          foreach (var run in view.Content.GetObjectGraphObjects(excludeStaticMembers: true).OfType<Run>()) {
94            var solution =
95              run.GetObjectGraphObjects(excludeStaticMembers: true).OfType<BioBoostCompoundSolution>().FirstOrDefault();
96            if (solution == null) continue;
97            ExportSolution(folderName, i++, run.Name, solution);
98          }
99          // export the solutions in the results of the paused algorithm
100          var alg = view.Content as IAlgorithm;
101          if (alg != null && alg.ExecutionState == ExecutionState.Paused) {
102            foreach (var solution in alg.Results.Select(r => r.Value).OfType<BioBoostCompoundSolution>()) {
103              ExportSolution(folderName, i++, alg.Name, solution);
104            }
105          }
106
107          // export the solution itself
108          var bioBoostSolution = view.Content as BioBoostCompoundSolution;
109          if (bioBoostSolution != null)
110            ExportSolution(folderName, i++, bioBoostSolution.Name, bioBoostSolution);
111        };
112
113        action.BeginInvoke(activeView, delegate(IAsyncResult result) {
114          try {
115            action.EndInvoke(result);
116          } catch (SystemException e) {
117            var dialog = new HeuristicLab.PluginInfrastructure.ErrorDialog(e);
118            dialog.ShowDialog();
119          }
120          Progress.Hide(activeView.Content);
121        }, null);
122      }
123    }
124
125    private void ExportSolution(string folderName, int i, string name, BioBoostCompoundSolution solution) {
126      var csv = CreateCsvSolution(solution);
127      var filename = string.Format("{0}-{1}.csv", i, name);
128      // remove invalid characters
129      foreach (var ch in Path.GetInvalidFileNameChars()) {
130        filename = filename.Replace(ch, '_');
131
132      }
133      var path = Path.Combine(folderName, filename);
134      if (path.Length >= 248) throw new PathTooLongException("The path is longer than 248 characters. Try to save your files in a different folder");
135      if (filename.Length >= 260) throw new PathTooLongException("The filename is longer than 260 characters. Please change the name of runs to something shorter.");
136      File.WriteAllText(path, csv);
137    }
138
139    private string CreateCsvSolution(BioBoostCompoundSolution content) {
140      content.EvaluateAndUpdateAllResults();
141      var sb = new StringBuilder();
142      // header
143      sb.Append("NUTS_ID").Append(",");
144      sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
145      sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}-Region\"", x.Key)))).Append(",");
146      sb.Append(string.Join(",", content.DoubleValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
147      sb.Append(string.Join(",", content.StringValues.Select(x => string.Format("\"{0}\"", x.Key))));
148      sb.Append(Environment.NewLine);
149      // rows
150      for (int i = 0; i < content.LocationNames.Length; i++) {
151        sb.Append(content.LocationNames[i]);
152        foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i].ToString("D", CultureInfo.InvariantCulture)); }
153        foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i] < 0 ? "" : content.LocationNames[kvp.Value[i]]); }
154        foreach (var kvp in content.DoubleValues) { sb.Append(",").Append(kvp.Value[i].ToString("G", CultureInfo.InvariantCulture)); }
155        foreach (var kvp in content.StringValues) { sb.Append(",").Append(kvp.Value[i]); }
156        sb.Append(Environment.NewLine);
157      }
158
159      return sb.ToString();
160    }
161
162    /*
163    private string CreateJsonSolution(BioBoostCompoundSolution content) {
164      var builder = new StringBuilder();
165      builder.Append("{ \"type\": \"FeatureCollection\", \n\"features\": [");
166      for (int i = 0; i < content.LocationNames.Length; i++) {
167        if (i > 0) builder.Append(",");
168        builder.Append("\n{ \"type\": \"Feature\", \"properties\": { \"NUTS_ID\": \"");
169        builder.Append(content.LocationNames[i]);
170        builder.Append("\"");
171        foreach (var kvp in content.IntValues) {
172          var target = content.LocationNames[i];
173          if (kvp.Value[i] >= 0) {
174            target = content.LocationNames[kvp.Value[i]];
175          }
176          builder.Append(",\n                                     \"");
177          builder.Append(kvp.Key);
178          builder.Append("\": \"");
179          builder.Append(target);
180          builder.Append("\"");
181        }
182        foreach (var kvp in content.DoubleValues) {
183          builder.Append(",\n                                     \"");
184          builder.Append(kvp.Key);
185          builder.Append("\": ");
186          builder.Append(kvp.Value[i].ToString("R", CultureInfo.InvariantCulture));
187        }
188        builder.Append("} }");
189      }
190      builder.Append("\n]\n}");
191
192      return builder.ToString();
193    }
194    */
195  }
196}
Note: See TracBrowser for help on using the repository browser.