#region License Information
/* HeuristicLab
* Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using HeuristicLab.BioBoost.Representation;
using HeuristicLab.Common;
using HeuristicLab.Core;
using HeuristicLab.MainForm;
using HeuristicLab.Optimization;
using HeuristicLab.Optimizer;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MenuItem = HeuristicLab.MainForm.WindowsForms.MenuItem;
namespace HeuristicLab.BioBoost.Views {
internal sealed class ExportSolutionMenuItem : MenuItem, IOptimizerUserInterfaceItemProvider {
public override string Name {
get { return "Export CSV"; }
}
public override IEnumerable Structure {
get { return new string[] { "&File" }; }
}
public override int Position {
get { return 1450; }
}
protected override void OnToolStripItemSet(EventArgs e) {
ToolStripItem.Enabled = false;
}
protected override void OnActiveViewChanged(object sender, EventArgs e) {
IContentView activeView = MainFormManager.MainForm.ActiveView as IContentView;
if (activeView == null) {
ToolStripItem.Enabled = false;
return;
}
var content = activeView.Content;
RunCollection runCollection = content as RunCollection;
var optimizer = content as IOptimizer;
if (runCollection == null && optimizer != null) {
runCollection = ((IOptimizer)content).Runs;
}
var alg = content as IAlgorithm;
var solution = content as BioBoostCompoundSolution;
ToolStripItem.Enabled =
// at least on run with a result || or the alg is paused and results contains a bioboost solution
(runCollection != null && runCollection.Any(run => run.Results.Any(p => p.Value is BioBoostCompoundSolution))) ||
(alg != null && alg.ExecutionState == ExecutionState.Paused && alg.Results.Any(r => r.Value is BioBoostCompoundSolution)) ||
(solution != null)
;
}
public override void Execute() {
var folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.Description = "Select the export directory.";
folderBrowserDialog.RootFolder = Environment.SpecialFolder.Desktop;
if (folderBrowserDialog.ShowDialog() == DialogResult.OK) {
var folderName = folderBrowserDialog.SelectedPath;
IContentView activeView = (IContentView)MainFormManager.MainForm.ActiveView;
var mainForm = (MainForm.WindowsForms.MainForm)MainFormManager.MainForm;
mainForm.AddOperationProgressToContent(activeView.Content, "Export solutions.");
Action action = (view) => {
var i = 0;
// export the solutions of all runs
foreach (var run in view.Content.GetObjectGraphObjects(excludeStaticMembers: true).OfType()) {
var solution =
run.GetObjectGraphObjects(excludeStaticMembers: true).OfType().FirstOrDefault();
if (solution == null) continue;
ExportSolution(folderName, i++, run.Name, solution);
}
// export the solutions in the results of the paused algorithm
var alg = view.Content as IAlgorithm;
if (alg != null && alg.ExecutionState == ExecutionState.Paused) {
foreach (var solution in alg.Results.Select(r => r.Value).OfType()) {
ExportSolution(folderName, i++, alg.Name, solution);
}
}
// export the solution itself
var bioBoostSolution = view.Content as BioBoostCompoundSolution;
if (bioBoostSolution != null)
ExportSolution(folderName, i++, bioBoostSolution.Name, bioBoostSolution);
};
action.BeginInvoke(activeView, delegate(IAsyncResult result) {
try {
action.EndInvoke(result);
} catch (SystemException e) {
var dialog = new HeuristicLab.PluginInfrastructure.ErrorDialog(e);
dialog.ShowDialog();
}
mainForm.RemoveOperationProgressFromContent(activeView.Content);
}, null);
}
}
private void ExportSolution(string folderName, int i, string name, BioBoostCompoundSolution solution) {
var csv = CreateCsvSolution(solution);
var filename = string.Format("{0}-{1}.csv", i, name);
// remove invalid characters
foreach (var ch in Path.GetInvalidFileNameChars()) {
filename = filename.Replace(ch, '_');
}
var path = Path.Combine(folderName, filename);
if (path.Length >= 248) throw new PathTooLongException("The path is longer than 248 characters. Try to save your files in a different folder");
if (filename.Length >= 260) throw new PathTooLongException("The filename is longer than 260 characters. Please change the name of runs to something shorter.");
File.WriteAllText(path, csv);
}
private string CreateCsvSolution(BioBoostCompoundSolution content) {
content.EvaluateAndUpdateAllResults();
var sb = new StringBuilder();
// header
sb.Append("NUTS_ID").Append(",");
sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
sb.Append(string.Join(",", content.IntValues.Select(x => string.Format("\"{0}-Region\"", x.Key)))).Append(",");
sb.Append(string.Join(",", content.DoubleValues.Select(x => string.Format("\"{0}\"", x.Key)))).Append(",");
sb.Append(string.Join(",", content.StringValues.Select(x => string.Format("\"{0}\"", x.Key))));
sb.Append(Environment.NewLine);
// rows
for (int i = 0; i < content.LocationNames.Length; i++) {
sb.Append(content.LocationNames[i]);
foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i].ToString("D", CultureInfo.InvariantCulture)); }
foreach (var kvp in content.IntValues) { sb.Append(",").Append(kvp.Value[i] < 0 ? "" : content.LocationNames[kvp.Value[i]]); }
foreach (var kvp in content.DoubleValues) { sb.Append(",").Append(kvp.Value[i].ToString("G", CultureInfo.InvariantCulture)); }
foreach (var kvp in content.StringValues) { sb.Append(",").Append(kvp.Value[i]); }
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
/*
private string CreateJsonSolution(BioBoostCompoundSolution content) {
var builder = new StringBuilder();
builder.Append("{ \"type\": \"FeatureCollection\", \n\"features\": [");
for (int i = 0; i < content.LocationNames.Length; i++) {
if (i > 0) builder.Append(",");
builder.Append("\n{ \"type\": \"Feature\", \"properties\": { \"NUTS_ID\": \"");
builder.Append(content.LocationNames[i]);
builder.Append("\"");
foreach (var kvp in content.IntValues) {
var target = content.LocationNames[i];
if (kvp.Value[i] >= 0) {
target = content.LocationNames[kvp.Value[i]];
}
builder.Append(",\n \"");
builder.Append(kvp.Key);
builder.Append("\": \"");
builder.Append(target);
builder.Append("\"");
}
foreach (var kvp in content.DoubleValues) {
builder.Append(",\n \"");
builder.Append(kvp.Key);
builder.Append("\": ");
builder.Append(kvp.Value[i].ToString("R", CultureInfo.InvariantCulture));
}
builder.Append("} }");
}
builder.Append("\n]\n}");
return builder.ToString();
}
*/
}
}