#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.Core;
using HeuristicLab.Data;
using HeuristicLab.MainForm;
using HeuristicLab.Optimization;
using HeuristicLab.Optimizer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using HeuristicLab.BioBoost.Data;
using HeuristicLab.BioBoost.Evaluators;
using HeuristicLab.BioBoost.Operators.Mutation;
using HeuristicLab.BioBoost.ProblemDescription;
using HeuristicLab.BioBoost.Utils;
using HeuristicLab.Encodings.IntegerVectorEncoding;
using HeuristicLab.Parameters;
using MenuItem = HeuristicLab.MainForm.WindowsForms.MenuItem;
namespace HeuristicLab.BioBoost.Views {
internal sealed class CreateBioBoostExperimentMenuItem : MenuItem, IOptimizerUserInterfaceItemProvider {
public override string Name {
get { return "Create BioBoost Experiment"; }
}
public override IEnumerable Structure {
get { return new string[] { "&Edit" }; }
}
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;
var algorithm = content as IAlgorithm;
ToolStripItem.Enabled = algorithm != null && algorithm.Problem is BioBoostProblem;
}
private enum Pathway { FP, CP, HTC };
private enum Region { BI, SK, BS, SE, SW, C, S, EU };
private enum Price { Cheap, Medium, Expensive };
private enum Implementation { Narrow, Normal, Broad };
private int nValues(Type t) { return Enum.GetValues(t).Length; }
public override void Execute() {
IContentView activeView = (IContentView)MainFormManager.MainForm.ActiveView;
var mainForm = ((MainForm.WindowsForms.MainForm) MainFormManager.MainForm);
var progress = mainForm.AddOperationProgressToContent(activeView.Content, "Generating Algorithm Configurations");
int n = nValues(typeof (Pathway))*nValues(typeof (Region))*nValues(typeof (Price))* nValues(typeof (Implementation));
int count = 0;
progress.Start();
progress.ProgressValue = 1.0*count/n;
var alg = activeView.Content as IAlgorithm;
Action action = view => {
var optimizers = new List();
foreach (Region r in Enum.GetValues(typeof (Region))) {
var x = new Experiment("BioBoost final experiment " + r);
foreach (Pathway pw in Enum.GetValues(typeof (Pathway))) {
foreach (Price p in Enum.GetValues(typeof (Price))) {
foreach (Implementation i in Enum.GetValues(typeof (Implementation))) {
x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, true));
progress.ProgressValue = 1.0*(++count)/n;
//x.Optimizers.Add(CreateConfiguration(alg, pw, r, p, i, false));
//progress.Start(string.Format("{0}/{1}", count, n));
}
}
}
var br = new BatchRun("BioBoost final batch run " + r);
br.Repetitions = 3;
br.Optimizer = x;
optimizers.Add(br);
}
progress.Finish();
foreach (var opt in optimizers)
MainFormManager.MainForm.ShowContent(opt);
};
action.BeginInvoke(activeView, delegate(IAsyncResult result) {
try {
action.EndInvoke(result);
} catch (SystemException e) {
var dialog = new PluginInfrastructure.ErrorDialog(e);
dialog.ShowDialog();
}
mainForm.RemoveOperationProgressFromContent(activeView.Content);
}, null);
}
private static IAlgorithm CreateConfiguration(IAlgorithm alg, Pathway pw, Region r, Price p, Implementation i, bool limitedDistanceInit) {
alg = (IAlgorithm) alg.Clone();
var problem = alg.Problem as BioBoostProblem;
var problemData = problem.ProblemData;
switch (r) {
case Region.BI: problemData.KeepRegions(new Regex("^(UK|IE)")); break; // BI (British Islands)
case Region.SK: problemData.KeepRegions(new Regex("^(SE|FI)")); break; // SK (Scandinavia)
case Region.BS: problemData.KeepRegions(new Regex("^(EE|LV|LT)")); break; // BS (Baltic States)
case Region.SE: problemData.KeepRegions(new Regex("^(BG|RO|EL|MK)")); break; // SE (South East Europe)
case Region.SW: problemData.KeepRegions(new Regex("^(ES|PT|FR|NL|BE|LU)")); break; //SW (South West Europe)
case Region.C: problemData.KeepRegions(new Regex("^(DE|DK|PL|CZ|SK)")); break; // C (Central Europe)
case Region.S: problemData.KeepRegions(new Regex("^(AT|SI|HU|IT|HR)")); break; // S (South Central)
case Region.EU: /* don't remove anything */ break;
}
string feedstock = null;
string carrier = null;
string finalProduct = null;
switch (pw) {
case Pathway.FP: feedstock = "Straw"; carrier = "Biosyncrude"; finalProduct = "TransportFuel"; break;
case Pathway.CP: feedstock = "ForestryResidues"; carrier = "Biooil"; finalProduct = "TransportFuel"; break;
case Pathway.HTC: feedstock = "MunicipalWaste"; carrier = "Biocoal"; finalProduct = "ElectricityOut"; break;
}
SetPathway(problemData, feedstock, carrier, finalProduct);
switch (p) {
case Price.Cheap: ScaleFeedstockPrice(problemData, feedstock, 0.75); break;
case Price.Medium: ScaleFeedstockPrice(problemData, feedstock, 1); break;
case Price.Expensive: ScaleFeedstockPrice(problemData, feedstock, 1.5); break;
}
double alpha = 1;
bool plantKiller = false;
switch (i) {
case Implementation.Narrow: alpha = 1; plantKiller = true; break;
case Implementation.Normal: alpha = 1; plantKiller = false; break;
case Implementation.Broad: alpha = 0.5; plantKiller = false; break;
}
((MonolithicEvaluator) problem.Evaluator).AlphaParameter.Value = new DoubleValue(alpha);
var mutationOperators = ((MultiMutator) NavigateItem(alg, "Mutator")).Operators;
mutationOperators.SetItemCheckedState(mutationOperators.First(op => op.Name == "PlantKiller"), plantKiller);
if (limitedDistanceInit) {
Choose( (ConstrainedValueParameter) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "LimitedDistanceTransportTargetCreator");
Set((IParameterizedItem) NavigateItem(problem, "SolutionCreator", "IntegerVectorCreator"), "TournamentSize", 20);
} else {
Choose((ConstrainedValueParameter) NavigateParameter(problem, "SolutionCreator", "IntegerVectorCreator"), "UniformRandomIntegerVectorCreator");
}
// adjust generations
int n = problem.NRegions;
Set(alg, "MaximumGenerations", n*n);
alg.Name = string.Format("BioBoost 11a final {0} {1} {2} {3} {4} {5}Gen", pw, r, p, i, limitedDistanceInit ? "LimitedDistanceInit" : "", n*n);
return alg;
}
private static void ScaleFeedstockPrice(BioBoostProblemData problemData, string feedstockName, double scale) {
Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "Price", scale);
Scale((Product) NavigateItem(problemData, "DataItems", "Product: " + feedstockName), "MaxPrice", scale);
}
private static void SetPathway(BioBoostProblemData problemData, string feedstock, string carrier, string finalProduct) {
CheckOnly(problemData, "Utilizations", feedstock);
CheckOnly(problemData, "TransportTargets", feedstock, carrier);
CheckOnly(problemData, "FinalProducts", finalProduct);
var potentials = problemData.FeedstockPotentials.Select(p => p.Name).ToHashSet();
foreach (var p in potentials) {
if (p != feedstock + "Potentials") {
problemData.FeedstockPotentials.Remove(p);
}
}
foreach (var p in problemData.Products) {
if (potentials.Contains(p.Label + "Potentials") && p.Label != feedstock)
problemData.DataItems.Remove(p);
}
}
private static void Set(IParameterizedItem item, string name, double value) { ((IValueParameter)item.Parameters[name]).Value = new DoubleValue(value); }
private static void Set(IParameterizedItem item, string name, int value) { ((IValueParameter)item.Parameters[name]).Value = new IntValue(value); }
private static void Scale(IParameterizedItem item, string name, double scale) {
var value = ((IValueParameter) item.Parameters[name]).Value.Value;
((IValueParameter)item.Parameters[name]).Value = new DoubleValue(value*scale);
}
private static void CheckOnly(IParameterizedItem item, string name, params string[] values) {
var valueSet = new HashSet(values);
var parameters = ((ValueParameter>) item.Parameters[name]).Value;
foreach (var i in parameters) {
parameters.SetItemCheckedState(i, valueSet.Contains(i.Value));
}
}
private static IItem NavigateItem(IItem item, params string[] path) {
for (int i = 0; i < path.Length; i++) {
if (item is IParameterizedItem) {
item = ((IValueParameter) ((IParameterizedItem) item).Parameters[path[i]]).Value;
} else if (item is ItemCollection) {
item = ((ItemCollection) item).First(x => x.ToString() == path[i]);
}
}
return item;
}
private static IItem NavigateParameter(IItem item, params string[] path) {
for (int i = 0; i < path.Length; i++) {
item = ((IParameterizedItem) item).Parameters[path[i]];
if (i < path.Length-1)
item = ((IValueParameter) item).Value;
}
return item;
}
private static void Choose(ConstrainedValueParameter param, string valueName) where T : class, IItem {
param.Value = param.ValidValues.First(v => v.ItemName == valueName);
}
}
}